diff --git a/Util/BuildTools/BuildOSM2ODR.sh b/Util/BuildTools/BuildOSM2ODR.sh index 0d3534222..0c4d9e1af 100755 --- a/Util/BuildTools/BuildOSM2ODR.sh +++ b/Util/BuildTools/BuildOSM2ODR.sh @@ -13,8 +13,12 @@ END REMOVE_INTERMEDIATE=false BUILD_OSM2ODR=false +GIT_PULL=true +CURRENT_OSM2ODR_COMMIT=f05c86588f797922758f1a7a50585a3aa969c17a +OSM2ODR_BRANCH=carla_osm2odr +OSM2ODR_REPO=https://github.com/carla-simulator/sumo.git -OPTS=`getopt -o h --long help,rebuild,build,clean,carsim -n 'parse-options' -- "$@"` +OPTS=`getopt -o h --long help,rebuild,build,clean,carsim,no-pull -n 'parse-options' -- "$@"` eval set -- "$OPTS" @@ -27,6 +31,9 @@ while [[ $# -gt 0 ]]; do --build ) BUILD_OSM2ODR=true; shift ;; + --no-pull ) + GIT_PULL=false + shift ;; --clean ) REMOVE_INTERMEDIATE=true; shift ;; @@ -44,7 +51,7 @@ source $(dirname "$0")/Environment.sh function get_source_code_checksum { local EXCLUDE='*__pycache__*' - find "${OSM2ODR_ROOT_FOLDER}"/* \! -path "${EXCLUDE}" -print0 | sha1sum | awk '{print $1}' + find "${OSM2ODR_SOURCE_FOLDER}"/* \! -path "${EXCLUDE}" -print0 | sha1sum | awk '{print $1}' } if ! { ${REMOVE_INTERMEDIATE} || ${BUILD_OSM2ODR}; }; then @@ -69,17 +76,29 @@ fi if ${BUILD_OSM2ODR} ; then log "Building OSM2ODR." - [ ! -d ${OSM2ODR_BUILD_FOLDER} ] && mkdir ${OSM2ODR_BUILD_FOLDER} + # [ ! -d ${OSM2ODR_BUILD_FOLDER} ] && mkdir ${OSM2ODR_BUILD_FOLDER} + if ${GIT_PULL} ; then + if [ ! -d ${OSM2ODR_SOURCE_FOLDER} ] ; then + git clone -b ${OSM2ODR_BRANCH} ${OSM2ODR_REPO} ${OSM2ODR_SOURCE_FOLDER} + fi + cd ${OSM2ODR_SOURCE_FOLDER} + git fetch + git checkout ${CURRENT_OSM2ODR_COMMIT} + fi + + mkdir -p ${OSM2ODR_BUILD_FOLDER} cd ${OSM2ODR_BUILD_FOLDER} # define clang compiler export CC=/usr/bin/clang-8 export CXX=/usr/bin/clang++-8 - cmake ${OSM2ODR_ROOT_FOLDER} \ + cmake ${OSM2ODR_SOURCE_FOLDER} \ -G "Eclipse CDT4 - Ninja" \ -DCMAKE_INSTALL_PREFIX=${LIBCARLA_INSTALL_CLIENT_FOLDER} \ -DPROJ_INCLUDE_DIR=${CARLA_BUILD_FOLDER}/proj-install/include \ - -DPROJ_LIBRARY=${CARLA_BUILD_FOLDER}/proj-install/lib/libproj.a + -DPROJ_LIBRARY=${CARLA_BUILD_FOLDER}/proj-install/lib/libproj.a \ + -DXercesC_INCLUDE_DIR=${CARLA_BUILD_FOLDER}/xerces-c-3.2.3-install/include \ + -DXercesC_LIBRARY=${CARLA_BUILD_FOLDER}/xerces-c-3.2.3-install/lib/libxerces-c.a ninja osm2odr ninja install diff --git a/Util/BuildTools/Linux.mk b/Util/BuildTools/Linux.mk index fd1e282b3..07c01ffd8 100644 --- a/Util/BuildTools/Linux.mk +++ b/Util/BuildTools/Linux.mk @@ -149,4 +149,4 @@ build.utils: PythonAPI @${CARLA_BUILD_TOOLS_FOLDER}/BuildUtilsDocker.sh osm2odr: - @${CARLA_BUILD_TOOLS_FOLDER}/BuildOSM2ODR.sh --build + @${CARLA_BUILD_TOOLS_FOLDER}/BuildOSM2ODR.sh --build $(ARGS) diff --git a/Util/BuildTools/Vars.mk b/Util/BuildTools/Vars.mk index 2a5563496..ecefe1703 100644 --- a/Util/BuildTools/Vars.mk +++ b/Util/BuildTools/Vars.mk @@ -19,8 +19,8 @@ LIBCARLA_BUILD_CLIENT_FOLDER=${CARLA_BUILD_FOLDER}/libcarla-client-build LIBCARLA_INSTALL_SERVER_FOLDER=${CARLAUE4_PLUGIN_ROOT_FOLDER}/CarlaDependencies LIBCARLA_INSTALL_CLIENT_FOLDER=${CARLA_PYTHONAPI_SOURCE_FOLDER}/dependencies -OSM2ODR_ROOT_FOLDER=${CURDIR}/Util/OSM2ODR OSM2ODR_BUILD_FOLDER=${CARLA_BUILD_FOLDER}/libosm2dr-build +OSM2ODR_SOURCE_FOLDER=${CARLA_BUILD_FOLDER}/libosm2dr-source CARLAUE4_PLUGIN_DEPS_FOLDER=${CARLAUE4_PLUGIN_ROOT_FOLDER}/CarlaDependencies diff --git a/Util/OSM2ODR/.gitignore b/Util/OSM2ODR/.gitignore deleted file mode 100644 index ba077a403..000000000 --- a/Util/OSM2ODR/.gitignore +++ /dev/null @@ -1 +0,0 @@ -bin diff --git a/Util/OSM2ODR/AUTHORS b/Util/OSM2ODR/AUTHORS deleted file mode 100644 index 6299c1766..000000000 --- a/Util/OSM2ODR/AUTHORS +++ /dev/null @@ -1,78 +0,0 @@ -Christian Roessel roessel croessel -Markus Hartinger -Peter Mieth -Georg Hertkorn georg -Daniel Krajzewicz dkrajzew -Julia Ringel jringel -Danilot Teta Boyom boyom -Andreas Gaubatz agaubatz -Maik Drozdzynski der_maik81 -Miguel Liebe miguelliebe -Eric Nicolay ericnicolay -Axel Wegener awegener -Thimor Bohn t-bohn -Felix Brack fxrb -Michael Behrisch behrisch -Yun-Pang Floetteroed yunpangwang -Ronald Nippold ronald_nippold -Friedemann Wesner fwesner -Tino Morenz morenzt -Christoph Sommer sommerc -Bjoern Hendriks bjhend -Sascha Krieg SaschaKrieg saschaKrieg -Clemens Honomichl chonomichl -Matthias Heppner heppa -Lena Kalleske kalleske -Christian Schmidt cschmidt87 -Matthew Fullerton fullerton -Walter Bamberger simsiem w-bamberger -Piotr Woznica piwoz -Tobias Mayer -Laura Bieker-Walz bieker -Matthias Roeckl mroeckl -Jakob Erdmann namdre -Jerome Haerri haerri -Karol Stosiek kstosiek -Maximilian Wittmann wittmax -Marek Heinrich mahei -Melanie Weber mknocke -Mario Krumnow mkrumnow -Riccardo Belletti rickybo89 -Anna Chiara Bellini acbellini -Alessio Bonfietti bonfioale -Federico Caselli fcaselli-it -Robbin Blokpoel rblokpoel -Nikolaus Furian nikolausfurian -Gianfilippo Slager -Sandesh Uppoor suppoor -Matthias Wagner mwagner -Mathew Robertson -Bill Baxter -Lyle Johnson -Peter Wagner piwagner -Eric Melde melde -Evamarie Wiessner -Andreas Kendziorra kend-an -Robert Hilbrich rhilbrich -Thomas Lockhart -Gerald Richter ait-mob-dts -Lukas Grohmann -Tamas Kurczveil emilkur -Pablo Alvarez Lopez palcraft -Joerg Schweizer joerg-schweizer -Mirco Sturari mircosturari -Martin Dippold -Gregor Laemmel laemmel -Leonhard Luecken luecken -Martin Taraz martintaraz -Lara Codeca -Matthias Schwamborn -Olaf Angelo Banse Bueno -Mirko Barthauer -Michele Segata -Raphael Riebl -Tarek Chouaki -Tobias Jacobowitz -Jim Div -Maximiliano Bottazzi -Sebastian Ehmann diff --git a/Util/OSM2ODR/CMakeLists.txt b/Util/OSM2ODR/CMakeLists.txt deleted file mode 100644 index 540b7a8f0..000000000 --- a/Util/OSM2ODR/CMakeLists.txt +++ /dev/null @@ -1,105 +0,0 @@ -# set VERSION to empty string -cmake_policy(SET CMP0048 NEW) -# do not expand quoted variables in if statements -cmake_policy(SET CMP0054 NEW) -# Options -option(MULTITHREADED_BUILD "Use all available cores for building (applies to Visual Studio only)" true) -option(PROFILING "Enable output of profiling data (applies to gcc/clang builds only)" false) -set(BINARY_SUFFIX "" CACHE STRING "Append the suffix to every generated binary") -set(COMPILE_DEFINITIONS "" CACHE STRING "Macros or defines to add when compiling") - -# Set a default build type if none was specified -# you may use -DCMAKE_BUILD_TYPE:STRING=Debug from the command line -set(default_build_type "Release") - -if (NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) - message(STATUS "Setting build type to '${default_build_type}' as none was specified.") - set(CMAKE_BUILD_TYPE "${default_build_type}" CACHE - STRING "Choose the type of build." FORCE) - # Set the possible values of build type for cmake-gui - set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS "Debug" "Release") -endif () - -project(SUMO) -set(PACKAGE_VERSION "git") -cmake_minimum_required(VERSION 3.1) - -set(CMAKE_COLOR_MAKEFILE ON) -set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_SOURCE_DIR}/cmake_modules/") - -set(ENABLED_FEATURES "${CMAKE_SYSTEM} ${CMAKE_SYSTEM_PROCESSOR} ${CMAKE_CXX_COMPILER_ID} ${CMAKE_CXX_COMPILER_VERSION} ${CMAKE_BUILD_TYPE}") - -if (COMPILE_DEFINITIONS) - add_compile_definitions(${COMPILE_DEFINITIONS}) -endif () - -# compiler specific flags -if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang") - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -pthread -Wall -pedantic -Wextra -fPIC") -elseif (MSVC) - # enabling /WX is not possible due to warnings in external headers - # /Wall brings MSVC 2013 to complete halt - if (MULTITHREADED_BUILD) - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /MP") - endif () - if (MSVC_VERSION GREATER 1914) - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /experimental:external /external:W2") - set(CMAKE_INCLUDE_SYSTEM_FLAG_CXX "/external:I ") - endif () - # exporting symbols for shared libraries needs to enabled explicitly - set(CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS ON) -endif () - -# force Visual Studio to leave out the Release / Debug dirs -# Debug messages -message(STATUS "CMAKE_BINARY_DIR: " ${CMAKE_BINARY_DIR}) -message(STATUS "CMAKE_SOURCE_DIR: " ${CMAKE_SOURCE_DIR}) -message(STATUS "") -message(STATUS "Platform: ") -message(STATUS " Host: " ${CMAKE_HOST_SYSTEM} " " ${CMAKE_HOST_SYSTEM_PROCESSOR}) -message(STATUS " Target: " ${CMAKE_SYSTEM} " " ${CMAKE_SYSTEM_PROCESSOR}) -message(STATUS " CMake: " ${CMAKE_VERSION}) -message(STATUS " CMake generator: " ${CMAKE_GENERATOR}) -message(STATUS " CMake build tool: " ${CMAKE_BUILD_TOOL}) -message(STATUS " Compiler: " ${CMAKE_CXX_COMPILER_ID} " " ${CMAKE_CXX_COMPILER_VERSION}) -if (CMAKE_GENERATOR MATCHES Xcode) - message(STATUS " Xcode: " ${XCODE_VERSION}) -endif () -message(STATUS "") - -find_package(Proj) -if (PROJ_FOUND) - include_directories(SYSTEM ${PROJ_INCLUDE_DIR}) - set(ENABLED_FEATURES "${ENABLED_FEATURES} Proj") -endif (PROJ_FOUND) - -set(XERCES_PATH "../../Build/xerces-c-3.2.3-install") -set(XercesC_INCLUDE_DIR "${XERCES_PATH}/include") -set(XercesC_LIBRARY "${XERCES_PATH}/lib") -# Install xercesc -file(GLOB XERCES_LIBS "${XercesC_LIBRARY}/*.*") -install(FILES ${XERCES_LIBS} DESTINATION lib) -find_package(XercesC REQUIRED) -if (XercesC_FOUND) - include_directories(SYSTEM ${XercesC_INCLUDE_DIRS}) -endif (XercesC_FOUND) - -find_package(X11) -if (X11_FOUND) - link_directories(${X11_LIBRARY_DIR}) - include_directories(SYSTEM ${X11_INCLUDE_DIR}) -endif (X11_FOUND) - -find_package(ZLIB) -if (ZLIB_FOUND) - set(HAVE_ZLIB 1) - link_directories(${ZLIB_LIBRARY_DIR}) - include_directories(SYSTEM ${ZLIB_INCLUDE_DIR}) -endif () - -include_directories(${CMAKE_CURRENT_BINARY_DIR}/src) -include_directories(${CMAKE_CURRENT_SOURCE_DIR}/src) - -add_subdirectory(src) - -message(STATUS "Enabled features: ${ENABLED_FEATURES}") diff --git a/Util/OSM2ODR/CMakeSettings.json b/Util/OSM2ODR/CMakeSettings.json deleted file mode 100644 index cbaabb0d4..000000000 --- a/Util/OSM2ODR/CMakeSettings.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "configurations": [ - { - "name": "x64-Debug", - "generator": "Ninja", - "configurationType": "Debug", - "inheritEnvironments": [ "msvc_x64_x64" ], - "buildRoot": "${projectDir}\\out\\build\\${name}", - "installRoot": "${projectDir}\\out\\install\\${name}", - "cmakeCommandArgs": "", - "buildCommandArgs": "-v", - "ctestCommandArgs": "", - "variables": [] - }, - { - "name": "x64-Release", - "generator": "Ninja", - "configurationType": "Release", - "buildRoot": "${projectDir}\\out\\build\\${name}", - "installRoot": "${projectDir}\\out\\install\\${name}", - "cmakeCommandArgs": "", - "buildCommandArgs": "-v", - "ctestCommandArgs": "", - "inheritEnvironments": [ "msvc_x64_x64" ], - "variables": [] - }, - { - "name": "VisualStudio2019-x64", - "generator": "Visual Studio 16 2019 Win64", - "configurationType": "", - "inheritEnvironments": [ "msvc_x64_x64" ], - "buildRoot": "${projectDir}\\out\\${name}", - "installRoot": "${projectDir}\\out\\install\\${name}", - "cmakeCommandArgs": "", - "buildCommandArgs": "", - "ctestCommandArgs": "", - "variables": [] - } - ] -} \ No newline at end of file diff --git a/Util/OSM2ODR/LICENSE b/Util/OSM2ODR/LICENSE deleted file mode 100644 index d3087e4c5..000000000 --- a/Util/OSM2ODR/LICENSE +++ /dev/null @@ -1,277 +0,0 @@ -Eclipse Public License - v 2.0 - - THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE - PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION - OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. - -1. DEFINITIONS - -"Contribution" means: - - a) in the case of the initial Contributor, the initial content - Distributed under this Agreement, and - - b) in the case of each subsequent Contributor: - i) changes to the Program, and - ii) additions to the Program; - where such changes and/or additions to the Program originate from - and are Distributed by that particular Contributor. A Contribution - "originates" from a Contributor if it was added to the Program by - such Contributor itself or anyone acting on such Contributor's behalf. - Contributions do not include changes or additions to the Program that - are not Modified Works. - -"Contributor" means any person or entity that Distributes the Program. - -"Licensed Patents" mean patent claims licensable by a Contributor which -are necessarily infringed by the use or sale of its Contribution alone -or when combined with the Program. - -"Program" means the Contributions Distributed in accordance with this -Agreement. - -"Recipient" means anyone who receives the Program under this Agreement -or any Secondary License (as applicable), including Contributors. - -"Derivative Works" shall mean any work, whether in Source Code or other -form, that is based on (or derived from) the Program and for which the -editorial revisions, annotations, elaborations, or other modifications -represent, as a whole, an original work of authorship. - -"Modified Works" shall mean any work in Source Code or other form that -results from an addition to, deletion from, or modification of the -contents of the Program, including, for purposes of clarity any new file -in Source Code form that contains any contents of the Program. Modified -Works shall not include works that contain only declarations, -interfaces, types, classes, structures, or files of the Program solely -in each case in order to link to, bind by name, or subclass the Program -or Modified Works thereof. - -"Distribute" means the acts of a) distributing or b) making available -in any manner that enables the transfer of a copy. - -"Source Code" means the form of a Program preferred for making -modifications, including but not limited to software source code, -documentation source, and configuration files. - -"Secondary License" means either the GNU General Public License, -Version 2.0, or any later versions of that license, including any -exceptions or additional permissions as identified by the initial -Contributor. - -2. GRANT OF RIGHTS - - a) Subject to the terms of this Agreement, each Contributor hereby - grants Recipient a non-exclusive, worldwide, royalty-free copyright - license to reproduce, prepare Derivative Works of, publicly display, - publicly perform, Distribute and sublicense the Contribution of such - Contributor, if any, and such Derivative Works. - - b) Subject to the terms of this Agreement, each Contributor hereby - grants Recipient a non-exclusive, worldwide, royalty-free patent - license under Licensed Patents to make, use, sell, offer to sell, - import and otherwise transfer the Contribution of such Contributor, - if any, in Source Code or other form. This patent license shall - apply to the combination of the Contribution and the Program if, at - the time the Contribution is added by the Contributor, such addition - of the Contribution causes such combination to be covered by the - Licensed Patents. The patent license shall not apply to any other - combinations which include the Contribution. No hardware per se is - licensed hereunder. - - c) Recipient understands that although each Contributor grants the - licenses to its Contributions set forth herein, no assurances are - provided by any Contributor that the Program does not infringe the - patent or other intellectual property rights of any other entity. - Each Contributor disclaims any liability to Recipient for claims - brought by any other entity based on infringement of intellectual - property rights or otherwise. As a condition to exercising the - rights and licenses granted hereunder, each Recipient hereby - assumes sole responsibility to secure any other intellectual - property rights needed, if any. For example, if a third party - patent license is required to allow Recipient to Distribute the - Program, it is Recipient's responsibility to acquire that license - before distributing the Program. - - d) Each Contributor represents that to its knowledge it has - sufficient copyright rights in its Contribution, if any, to grant - the copyright license set forth in this Agreement. - - e) Notwithstanding the terms of any Secondary License, no - Contributor makes additional grants to any Recipient (other than - those set forth in this Agreement) as a result of such Recipient's - receipt of the Program under the terms of a Secondary License - (if permitted under the terms of Section 3). - -3. REQUIREMENTS - -3.1 If a Contributor Distributes the Program in any form, then: - - a) the Program must also be made available as Source Code, in - accordance with section 3.2, and the Contributor must accompany - the Program with a statement that the Source Code for the Program - is available under this Agreement, and informs Recipients how to - obtain it in a reasonable manner on or through a medium customarily - used for software exchange; and - - b) the Contributor may Distribute the Program under a license - different than this Agreement, provided that such license: - i) effectively disclaims on behalf of all other Contributors all - warranties and conditions, express and implied, including - warranties or conditions of title and non-infringement, and - implied warranties or conditions of merchantability and fitness - for a particular purpose; - - ii) effectively excludes on behalf of all other Contributors all - liability for damages, including direct, indirect, special, - incidental and consequential damages, such as lost profits; - - iii) does not attempt to limit or alter the recipients' rights - in the Source Code under section 3.2; and - - iv) requires any subsequent distribution of the Program by any - party to be under a license that satisfies the requirements - of this section 3. - -3.2 When the Program is Distributed as Source Code: - - a) it must be made available under this Agreement, or if the - Program (i) is combined with other material in a separate file or - files made available under a Secondary License, and (ii) the initial - Contributor attached to the Source Code the notice described in - Exhibit A of this Agreement, then the Program may be made available - under the terms of such Secondary Licenses, and - - b) a copy of this Agreement must be included with each copy of - the Program. - -3.3 Contributors may not remove or alter any copyright, patent, -trademark, attribution notices, disclaimers of warranty, or limitations -of liability ("notices") contained within the Program from any copy of -the Program which they Distribute, provided that Contributors may add -their own appropriate notices. - -4. COMMERCIAL DISTRIBUTION - -Commercial distributors of software may accept certain responsibilities -with respect to end users, business partners and the like. While this -license is intended to facilitate the commercial use of the Program, -the Contributor who includes the Program in a commercial product -offering should do so in a manner which does not create potential -liability for other Contributors. Therefore, if a Contributor includes -the Program in a commercial product offering, such Contributor -("Commercial Contributor") hereby agrees to defend and indemnify every -other Contributor ("Indemnified Contributor") against any losses, -damages and costs (collectively "Losses") arising from claims, lawsuits -and other legal actions brought by a third party against the Indemnified -Contributor to the extent caused by the acts or omissions of such -Commercial Contributor in connection with its distribution of the Program -in a commercial product offering. The obligations in this section do not -apply to any claims or Losses relating to any actual or alleged -intellectual property infringement. In order to qualify, an Indemnified -Contributor must: a) promptly notify the Commercial Contributor in -writing of such claim, and b) allow the Commercial Contributor to control, -and cooperate with the Commercial Contributor in, the defense and any -related settlement negotiations. The Indemnified Contributor may -participate in any such claim at its own expense. - -For example, a Contributor might include the Program in a commercial -product offering, Product X. That Contributor is then a Commercial -Contributor. If that Commercial Contributor then makes performance -claims, or offers warranties related to Product X, those performance -claims and warranties are such Commercial Contributor's responsibility -alone. Under this section, the Commercial Contributor would have to -defend claims against the other Contributors related to those performance -claims and warranties, and if a court requires any other Contributor to -pay any damages as a result, the Commercial Contributor must pay -those damages. - -5. NO WARRANTY - -EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, AND TO THE EXTENT -PERMITTED BY APPLICABLE LAW, THE PROGRAM IS PROVIDED ON AN "AS IS" -BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR -IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF -TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR -PURPOSE. Each Recipient is solely responsible for determining the -appropriateness of using and distributing the Program and assumes all -risks associated with its exercise of rights under this Agreement, -including but not limited to the risks and costs of program errors, -compliance with applicable laws, damage to or loss of data, programs -or equipment, and unavailability or interruption of operations. - -6. DISCLAIMER OF LIABILITY - -EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, AND TO THE EXTENT -PERMITTED BY APPLICABLE LAW, NEITHER RECIPIENT NOR ANY CONTRIBUTORS -SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, -EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION LOST -PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE -EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE -POSSIBILITY OF SUCH DAMAGES. - -7. GENERAL - -If any provision of this Agreement is invalid or unenforceable under -applicable law, it shall not affect the validity or enforceability of -the remainder of the terms of this Agreement, and without further -action by the parties hereto, such provision shall be reformed to the -minimum extent necessary to make such provision valid and enforceable. - -If Recipient institutes patent litigation against any entity -(including a cross-claim or counterclaim in a lawsuit) alleging that the -Program itself (excluding combinations of the Program with other software -or hardware) infringes such Recipient's patent(s), then such Recipient's -rights granted under Section 2(b) shall terminate as of the date such -litigation is filed. - -All Recipient's rights under this Agreement shall terminate if it -fails to comply with any of the material terms or conditions of this -Agreement and does not cure such failure in a reasonable period of -time after becoming aware of such noncompliance. If all Recipient's -rights under this Agreement terminate, Recipient agrees to cease use -and distribution of the Program as soon as reasonably practicable. -However, Recipient's obligations under this Agreement and any licenses -granted by Recipient relating to the Program shall continue and survive. - -Everyone is permitted to copy and distribute copies of this Agreement, -but in order to avoid inconsistency the Agreement is copyrighted and -may only be modified in the following manner. The Agreement Steward -reserves the right to publish new versions (including revisions) of -this Agreement from time to time. No one other than the Agreement -Steward has the right to modify this Agreement. The Eclipse Foundation -is the initial Agreement Steward. The Eclipse Foundation may assign the -responsibility to serve as the Agreement Steward to a suitable separate -entity. Each new version of the Agreement will be given a distinguishing -version number. The Program (including Contributions) may always be -Distributed subject to the version of the Agreement under which it was -received. In addition, after a new version of the Agreement is published, -Contributor may elect to Distribute the Program (including its -Contributions) under the new version. - -Except as expressly stated in Sections 2(a) and 2(b) above, Recipient -receives no rights or licenses to the intellectual property of any -Contributor under this Agreement, whether expressly, by implication, -estoppel or otherwise. All rights in the Program not expressly granted -under this Agreement are reserved. Nothing in this Agreement is intended -to be enforceable by any entity that is not a Contributor or Recipient. -No third-party beneficiary rights are created under this Agreement. - -Exhibit A - Form of Secondary Licenses Notice - -"This Source Code may also be made available under the following -Secondary Licenses when the conditions for such availability set forth -in the Eclipse Public License, v. 2.0 are satisfied: {name license(s), -version(s), and exceptions or additional permissions here}." - - Simply including a copy of this Agreement, including this Exhibit A - is not sufficient to license the Source Code under Secondary Licenses. - - If it is not possible or desirable to put the notice in a particular - file, then You may include the notice in a location (such as a LICENSE - file in a relevant directory) where a recipient would be likely to - look for such a notice. - - You may add additional accurate notices of copyright ownership. diff --git a/Util/OSM2ODR/cmake-variants.yaml b/Util/OSM2ODR/cmake-variants.yaml deleted file mode 100644 index e19ec29f5..000000000 --- a/Util/OSM2ODR/cmake-variants.yaml +++ /dev/null @@ -1,30 +0,0 @@ -buildType: - default: debug - description: My option - choices: - debug: - short: Debug - long: Build with debug info - buildType: Debug - release: - short: Release - long: Optimize binaries - buildType: Release - -useFMI: - default: 'no' - description: My option - choices: - 'yes': - short: FMI - long: Enable the use of FMI - settings: - FMI: 'yes' - 'no': - short: 'No FMI' - long: Do not build the FMI library - settings: - FMI: 'no' - - - diff --git a/Util/OSM2ODR/cmake_modules/FindProj.cmake b/Util/OSM2ODR/cmake_modules/FindProj.cmake deleted file mode 100644 index 92cf92c26..000000000 --- a/Util/OSM2ODR/cmake_modules/FindProj.cmake +++ /dev/null @@ -1,97 +0,0 @@ -# Source: https://github.com/qgis/QGIS/blob/3b3f6748f1e5e8f77fa87477add360ec0203fb26/cmake/FindProj.cmake -# Changes: included BSD license text - -# Find Proj -# ~~~~~~~~~ -# Copyright (c) 2007, Martin Dobias -# Redistribution and use is allowed according to the terms of the BSD license. -# -#Redistribution and use in source and binary forms, with or without -#modification, are permitted provided that the following conditions -#are met: -# -#1. Redistributions of source code must retain the copyright -# notice, this list of conditions and the following disclaimer. -#2. Redistributions in binary form must reproduce the copyright -# notice, this list of conditions and the following disclaimer in the -# documentation and/or other materials provided with the distribution. -#3. The name of the author may not be used to endorse or promote products -# derived from this software without specific prior written permission. -# -#THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR -#IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES -#OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. -#IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, -#INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT -#NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -#DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -#THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -#(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -#THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -# CMake module to search for Proj library -# -# If it's found it sets PROJ_FOUND to TRUE -# and following variables are set: -# PROJ_INCLUDE_DIR -# PROJ_API_FILE -# PROJ_LIBRARY - -# FIND_PATH and FIND_LIBRARY normally search standard locations -# before the specified paths. To search non-standard paths first, -# FIND_* is invoked first with specified paths and NO_DEFAULT_PATH -# and then again with no specified paths to search the default -# locations. When an earlier FIND_* succeeds, subsequent FIND_*s -# searching for the same item do nothing. - -# try to use framework on mac -# want clean framework path, not unix compatibility path -IF (APPLE) - IF (CMAKE_FIND_FRAMEWORK MATCHES "FIRST" - OR CMAKE_FRAMEWORK_PATH MATCHES "ONLY" - OR NOT CMAKE_FIND_FRAMEWORK) - SET (CMAKE_FIND_FRAMEWORK_save ${CMAKE_FIND_FRAMEWORK} CACHE STRING "" FORCE) - SET (CMAKE_FIND_FRAMEWORK "ONLY" CACHE STRING "" FORCE) - #FIND_PATH(PROJ_INCLUDE_DIR PROJ/proj_api.h) - FIND_LIBRARY(PROJ_LIBRARY PROJ) - IF (PROJ_LIBRARY) - # FIND_PATH doesn't add "Headers" for a framework - SET (PROJ_INCLUDE_DIR ${PROJ_LIBRARY}/Headers CACHE PATH "Path to a file.") - ENDIF (PROJ_LIBRARY) - SET (CMAKE_FIND_FRAMEWORK ${CMAKE_FIND_FRAMEWORK_save} CACHE STRING "" FORCE) - ENDIF () -ENDIF (APPLE) - -FIND_PATH(PROJ_INCLUDE_DIR NAMES proj.h proj_api.h PATHS - "$ENV{INCLUDE}" - "$ENV{LIB_DIR}/include" - "$ENV{GDAL_DIR}/include" - ) - -FIND_LIBRARY(PROJ_LIBRARY NAMES proj_i proj proj_6_1 PATHS - "$ENV{LIB}" - "$ENV{LIB_DIR}/lib" - "$ENV{GDAL_DIR}/lib" - ) - -IF (PROJ_INCLUDE_DIR AND PROJ_LIBRARY) - SET(PROJ_FOUND TRUE) - IF (EXISTS "${PROJ_INCLUDE_DIR}/proj.h") - SET(PROJ_API_FILE "proj.h") - ELSE () - SET(PROJ_API_FILE "proj_api.h") - ENDIF () - IF (NOT PROJ_FIND_QUIETLY) - MESSAGE(STATUS "Found Proj: ${PROJ_LIBRARY}") - ENDIF (NOT PROJ_FIND_QUIETLY) -ELSE () - SET(PROJ_FOUND FALSE) - SET(PROJ_LIBRARY "") - IF (PROJ_FIND_REQUIRED) - MESSAGE(FATAL_ERROR "Could not find Proj") - ELSE () - IF (NOT PROJ_FIND_QUIETLY) - MESSAGE(STATUS "Could NOT find Proj") - ENDIF (NOT PROJ_FIND_QUIETLY) - ENDIF (PROJ_FIND_REQUIRED) -ENDIF () diff --git a/Util/OSM2ODR/src/CMakeLists.txt b/Util/OSM2ODR/src/CMakeLists.txt deleted file mode 100644 index 167f48f9a..000000000 --- a/Util/OSM2ODR/src/CMakeLists.txt +++ /dev/null @@ -1,66 +0,0 @@ -set(osm2odr_sources "OSM2ODR.cpp") - -configure_file(config.h.cmake config.h) - -if (EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/../.git") - set(VERSION_DEP "${CMAKE_CURRENT_SOURCE_DIR}/../.git") -endif() - -file(GLOB netbuild_sources "netbuild/*.cpp" "netbuild/*.h") -set(osm2odr_sources "${osm2odr_sources};${netbuild_sources}") - -file(GLOB netimport_sources "netimport/*.cpp" "netimport/*.h") -set(osm2odr_sources "${osm2odr_sources};${netimport_sources}") - -file(GLOB netimport_vissim_sources "netimport/vissim/*.cpp" "netimport/vissim/*.h") -set(osm2odr_sources "${osm2odr_sources};${netimport_vissim_sources}") - -file(GLOB netimport_vissim_tempstructs_sources "netimport/vissim/tempstructs/*.cpp" "netimport/vissim/tempstructs/*.h") -set(osm2odr_sources "${osm2odr_sources};${netimport_vissim_tempstructs_sources}") - -file(GLOB netimport_vissim_typeloader_sources "netimport/vissim/typeloader/*.cpp" "netimport/vissim/typeloader/*.h") -set(osm2odr_sources "${osm2odr_sources};${netimport_vissim_typeloader_sources}") - -file(GLOB netwrite_sources "netwrite/*.cpp" "netwrite/*.h") -set(osm2odr_sources "${osm2odr_sources};${netwrite_sources}") - -file(GLOB foreign_eulerspiral_sources "foreign/eulerspiral/*.cpp" "foreign/eulerspiral/*.h") -set(osm2odr_sources "${osm2odr_sources};${foreign_eulerspiral_sources}") - -file(GLOB foreign_tcpip_sources "foreign/tcpip/*.cpp" "foreign/tcpip/*.h") -set(osm2odr_sources "${osm2odr_sources};${foreign_tcpip_sources}") - -file(GLOB utils_common_sources "utils/common/*.cpp" "utils/common/*.h") -set(osm2odr_sources "${osm2odr_sources};${utils_common_sources}") - -file(GLOB utils_distribution_sources "utils/distribution/*.cpp" "utils/distribution/*.h") -set(osm2odr_sources "${osm2odr_sources};${utils_distribution_sources}") - -file(GLOB utils_shapes_sources "utils/shapes/*.cpp" "utils/shapes/*.h") -set(osm2odr_sources "${osm2odr_sources};${utils_shapes_sources}") - -file(GLOB utils_options_sources "utils/options/*.cpp" "utils/options/*.h") -set(osm2odr_sources "${osm2odr_sources};${utils_options_sources}") - -file(GLOB utils_xml_sources "utils/xml/*.cpp" "utils/xml/*.h") -set(osm2odr_sources "${osm2odr_sources};${utils_xml_sources}") - -file(GLOB utils_geom_sources "utils/geom/*.cpp" "utils/geom/*.h") -set(osm2odr_sources "${osm2odr_sources};${utils_geom_sources}") - -file(GLOB utils_importio_sources "utils/importio/*.cpp" "utils/importio/*.h") -set(osm2odr_sources "${osm2odr_sources};${utils_importio_sources}") - -file(GLOB utils_iodevices_sources "utils/iodevices/*.cpp" "utils/iodevices/*.h") -set(osm2odr_sources "${osm2odr_sources};${utils_iodevices_sources}") - -file(GLOB utils_traction_wire_sources "utils/traction_wire/*.cpp" "utils/traction_wire/*.h") -set(osm2odr_sources "${osm2odr_sources};${utils_traction_wire_sources}") - -add_library(osm2odr STATIC ${osm2odr_sources}) -target_link_libraries(osm2odr ${XercesC_LIBRARIES} ${ZLIB_LIBRARIES} ${PROJ_LIBRARY}) - -target_compile_definitions(osm2odr PUBLIC "XERCES_STATIC_LIBRARY") - -install(TARGETS osm2odr ARCHIVE DESTINATION lib) -install(FILES OSM2ODR.h DESTINATION include) diff --git a/Util/OSM2ODR/src/OSM2ODR.cpp b/Util/OSM2ODR/src/OSM2ODR.cpp deleted file mode 100644 index 704a50cf0..000000000 --- a/Util/OSM2ODR/src/OSM2ODR.cpp +++ /dev/null @@ -1,143 +0,0 @@ -// Copyright (c) 2020 Computer Vision Center (CVC) at the Universitat Autonoma -// de Barcelona (UAB). -// -// This work is licensed under the terms of the MIT license. -// For a copy, see . - -#include "OSM2ODR.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - - -namespace osm2odr { - - void fillOptions() { - OptionsCont& oc = OptionsCont::getOptions(); - oc.addCallExample("-c ", "generate net with options read from file"); - oc.addCallExample("-n ./nodes.xml -e ./edges.xml -v -t ./owntypes.xml", - "generate net with given nodes, edges, and edge types doing verbose output"); - // insert options sub-topics - SystemFrame::addConfigurationOptions(oc); // this subtopic is filled here, too - oc.addOptionSubTopic("Input"); - oc.addOptionSubTopic("Output"); - GeoConvHelper::addProjectionOptions(oc); - oc.addOptionSubTopic("Processing"); - oc.addOptionSubTopic("Building Defaults"); - oc.addOptionSubTopic("TLS Building"); - oc.addOptionSubTopic("Ramp Guessing"); - oc.addOptionSubTopic("Edge Removal"); - oc.addOptionSubTopic("Unregulated Nodes"); - oc.addOptionSubTopic("Junctions"); - oc.addOptionSubTopic("Pedestrian"); - oc.addOptionSubTopic("Bicycle"); - oc.addOptionSubTopic("Railway"); - oc.addOptionSubTopic("Formats"); - SystemFrame::addReportOptions(oc); // this subtopic is filled here, too - - NIFrame::fillOptions(); - NBFrame::fillOptions(false); - NWFrame::fillOptions(false); - RandHelper::insertRandOptions(); -} - - - bool checkOptions() { - bool ok = NIFrame::checkOptions(); - ok &= NBFrame::checkOptions(); - ok &= NWFrame::checkOptions(); - ok &= SystemFrame::checkOptions(); - return ok; - } - - std::string ConvertOSMToOpenDRIVE(std::string osm_file, OSM2ODRSettings settings) { - std::vector OptionsArgs = { - "--proj", settings.proj_string, - "--geometry.remove", "--ramps.guess", "--edges.join", "--junctions.join", "--roundabouts.guess", - "--keep-edges.by-type", - "highway.motorway,highway.motorway_link,highway.trunk,highway.trunk_link,highway.primary,highway.primary_link,highway.secondary,highway.secondary_link,highway.tertiary,highway.tertiary_link,highway.unclassified,highway.residential", - "--tls.discard-loaded", "--tls.discard-simple", "--default.lanewidth", - std::to_string(settings.default_lane_width), - "--osm-files", "TRUE", "--opendrive-output", "TRUE", // necessary for now to enable osm input and xodr output - }; - if (settings.elevation_layer_height > 0) { - OptionsArgs.emplace_back("--osm.layer-elevation"); - OptionsArgs.emplace_back(std::to_string(settings.elevation_layer_height)); - } - if (settings.use_offsets) { - OptionsArgs.emplace_back("--offset.x"); - OptionsArgs.emplace_back(std::to_string(settings.offset_x)); - OptionsArgs.emplace_back("--offset.y"); - OptionsArgs.emplace_back(std::to_string(settings.offset_y)); - } - if (!settings.center_map) { - OptionsArgs.emplace_back("--offset.disable-normalization"); - OptionsArgs.emplace_back("true"); - } - - // OptionsCont::getOptions().clear(); - OptionsCont& oc = OptionsCont::getOptions(); - oc.input_osm_file = osm_file; - - XMLSubSys::init(); - fillOptions(); - OptionsIO::setArgs(OptionsArgs); - OptionsIO::getOptions(); - if (oc.processMetaOptions(OptionsArgs.size() < 2)) { - SystemFrame::close(); - return 0; - } - XMLSubSys::setValidation(oc.getString("xml-validation"), oc.getString("xml-validation.net")); - if (oc.isDefault("aggregate-warnings")) { - oc.set("aggregate-warnings", "5"); - } - MsgHandler::initOutputOptions(); - if (!checkOptions()) { - throw ProcessError(); - } - RandHelper::initRandGlobal(); - // build the projection - if (!GeoConvHelper::init(oc)) { - throw ProcessError("Could not build projection!"); - } - NBNetBuilder nb; - nb.applyOptions(oc); - // load data - NILoader nl(nb); - nl.load(oc); - // flush aggregated errors and optionally ignore them - MsgHandler::getErrorInstance()->clear(oc.getBool("ignore-errors")); - // check whether any errors occurred - if (MsgHandler::getErrorInstance()->wasInformed()) { - throw ProcessError(); - } - nb.compute(oc); - // check whether any errors occurred - if (MsgHandler::getErrorInstance()->wasInformed()) { - throw ProcessError(); - } - NWFrame::writeNetwork(oc, nb); - - - DistributionCont::clear(); - SystemFrame::close(); - - return oc.output_xodr_file; - } - -} // namespace OSM2ODR diff --git a/Util/OSM2ODR/src/OSM2ODR.h b/Util/OSM2ODR/src/OSM2ODR.h deleted file mode 100644 index dcd7c04d2..000000000 --- a/Util/OSM2ODR/src/OSM2ODR.h +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) 2020 Computer Vision Center (CVC) at the Universitat Autonoma -// de Barcelona (UAB). -// -// This work is licensed under the terms of the MIT license. -// For a copy, see . - -#pragma once - -#include - -namespace osm2odr { - - struct OSM2ODRSettings { - bool use_offsets = false; - double offset_x = 0; - double offset_y = 0; - double default_lane_width = 4.0; - double elevation_layer_height = 0; - std::string proj_string = "+proj=tmerc"; - bool center_map = true; - }; - - std::string ConvertOSMToOpenDRIVE(std::string osm_file, OSM2ODRSettings settings = OSM2ODRSettings()); - -} // namespace osm2odr diff --git a/Util/OSM2ODR/src/README_Contributing.md b/Util/OSM2ODR/src/README_Contributing.md deleted file mode 100644 index 50052ab08..000000000 --- a/Util/OSM2ODR/src/README_Contributing.md +++ /dev/null @@ -1,46 +0,0 @@ -Please feel free to add and / or modify files here but keep in mind that -EPL requires that "derivative works" be licensed under the terms of the EPL. -If the extension is a separate module and is not published under the EPL -it will not be adopted in the SUMO mainline repository. - -Modifications to the files and directories listed here are considered _derivative work_: - -- activitygen -- dfrouter -- duarouter -- foreign -- gui -- guinetload -- guisim -- jtrrouter -- marouter -- mesogui -- mesosim -- microsim -- netbuild -- netedit -- netgen -- netimport -- netload -- netwrite -- od -- osgview -- polyconvert -- router -- tools -- traci-server -- traci_testclient -- utils -- guisim_main.cpp -- netconvert_main.cpp -- od2trips_main.cpp -- sumo_main.cpp - -Directories containing interface code for _separate modules_ (with separate lists) are: - -- car following models that inherit from MSCFModel (excluding [modifications of the existing models](microsim/cfmodels/README_Contributing.md)) -- lane changing models that inherit from MSAbstractLaneChangeModel (excluding [modifications of the existing models](microsim/lcmodels/README_Contributing.md)) -- simulation output modules (excluding [changes to the existing classes](microsim/output/README_Contributing.md)) -- vehicle device modules (excluding [changes to the existing classes](microsim/devices/README_Contributing.md)) -- network import modules (excluding [changes to the existing classes](netimport/README_Contributing.md)) -- network export modules (excluding [changes to the existing classes](netwrite/README_Contributing.md)) diff --git a/Util/OSM2ODR/src/config.h.cmake b/Util/OSM2ODR/src/config.h.cmake deleted file mode 100644 index 6ca79a2ba..000000000 --- a/Util/OSM2ODR/src/config.h.cmake +++ /dev/null @@ -1,109 +0,0 @@ -/* Macros for Microsoft Visual Studio */ -#ifdef _MSC_VER - - /* Disable "decorated name length exceeded, name was truncated" warnings. */ - #pragma warning(disable: 4503) - /* Disable "identifier truncated in debug info" warnings. */ - #pragma warning(disable: 4786) - /* Disable "C++ Exception Specification ignored" warnings */ - #pragma warning(disable: 4290) - /* Disable DLL-Interface warnings */ - #pragma warning(disable: 4251) - /* Disable integer overflow in arithmetics warnings */ - #pragma warning(disable: 26451) - - /* Disable "unsafe" warnings for crt functions in VC++ 2005. */ - #if _MSC_VER >= 1400 - #define _CRT_SECURE_NO_WARNINGS - #endif - - /* define WIN32 */ - #ifndef WIN32 - #define WIN32 - #endif - - /* Define for dynamic Fox linkage */ - #define FOXDLL 1 - - /* define default constructor for FOX moduls (Visual Studio) */ - #define FOX_CONSTRUCTOR(classname) __pragma(warning(suppress: 26495)) \ - classname() {} - -/* Macros for GNU Compiler */ -#else - - /* defined if we're using MINGW32 */ - #cmakedefine MINGW32 - - /* Windows (MinGW32) */ - #ifdef MINGW32 - - /* Define WIN32 */ - #ifndef WIN32 - #define WIN32 - #endif - - /* Define for dynamic Fox linkage */ - #define FOXDLL 1 - - /* Define default constructor for FOX moduls (MinGW32) */ - #define FOX_CONSTRUCTOR(classname) classname() {} - - /* Linux and OS */ - #else - - /* Define default constructor for FOX moduls (Linux and OS) */ - #define FOX_CONSTRUCTOR(classname) classname() {} - - /* MinGW32 */ - #endif - -/* Visual Studio */ -#endif - - -/* Reporting string for enabled options */ -#define HAVE_ENABLED "@ENABLED_FEATURES@" - -/* defined if Eigen is available */ -#cmakedefine HAVE_EIGEN - -/* defined if ffmpeg is available */ -#cmakedefine HAVE_FFMPEG - -/* defined if FOX is available */ -#cmakedefine HAVE_FOX - -/* defined if GDAL is available */ -#cmakedefine HAVE_GDAL - -/* defined if GL2PS is available */ -#cmakedefine HAVE_GL2PS - -/* defined if osg is available */ -#cmakedefine HAVE_OSG - -/* defined if zlib is available */ -#cmakedefine HAVE_ZLIB - -/* set to proj.h, proj_api.h or empty depending on which proj is available */ -#cmakedefine PROJ_API_FILE "@PROJ_API_FILE@" - -/* defined if python is available */ -#cmakedefine HAVE_PYTHON - -/* Define if auto-generated version.h should be used. */ -#define HAVE_VERSION_H -#ifndef HAVE_VERSION_H - /* Define if auto-generated version.h is unavailable. */ - #define VERSION_STRING "1.6.0" -#endif - -/* defines the epsilon to use on general floating point comparison */ -#define NUMERICAL_EPS 0.001 - -/* defines the epsilon to use on position comparison */ -#define POSITION_EPS 0.1 - -/* Define length for Xerces 3. */ -#define XERCES3_SIZE_t XMLSize_t diff --git a/Util/OSM2ODR/src/foreign/CMakeLists.txt b/Util/OSM2ODR/src/foreign/CMakeLists.txt deleted file mode 100644 index 83fcff5c2..000000000 --- a/Util/OSM2ODR/src/foreign/CMakeLists.txt +++ /dev/null @@ -1,2 +0,0 @@ -add_subdirectory(tcpip) -add_subdirectory(eulerspiral) diff --git a/Util/OSM2ODR/src/foreign/eulerspiral/CMakeLists.txt b/Util/OSM2ODR/src/foreign/eulerspiral/CMakeLists.txt deleted file mode 100644 index 92af87871..000000000 --- a/Util/OSM2ODR/src/foreign/eulerspiral/CMakeLists.txt +++ /dev/null @@ -1,7 +0,0 @@ -set(foreign_eulerspiral_STAT_SRCS - odrSpiral.cpp - odrSpiral.h -) - -add_library(foreign_eulerspiral STATIC ${foreign_eulerspiral_STAT_SRCS}) -set_property(TARGET foreign_eulerspiral PROPERTY PROJECT_LABEL "z_foreign_eulerspiral") diff --git a/Util/OSM2ODR/src/foreign/eulerspiral/LICENSE.TXT b/Util/OSM2ODR/src/foreign/eulerspiral/LICENSE.TXT deleted file mode 100644 index 8dada3eda..000000000 --- a/Util/OSM2ODR/src/foreign/eulerspiral/LICENSE.TXT +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "{}" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright {yyyy} {name of copyright owner} - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/Util/OSM2ODR/src/foreign/eulerspiral/odrSpiral.cpp b/Util/OSM2ODR/src/foreign/eulerspiral/odrSpiral.cpp deleted file mode 100644 index fc7b27c93..000000000 --- a/Util/OSM2ODR/src/foreign/eulerspiral/odrSpiral.cpp +++ /dev/null @@ -1,247 +0,0 @@ -/* =================================================== - * file: euler.h - * --------------------------------------------------- - * purpose: free method for computing spirals - * in OpenDRIVE applications - * --------------------------------------------------- - * using methods of CEPHES library - * --------------------------------------------------- - * first edit: 09.03.2010 by M. Dupuis @ VIRES GmbH - * last mod.: 02.05.2017 by Michael Scholz @ German Aerospace Center (DLR) - * last mod.: 05.07.2017 by Jakob Erdmann @ German Aerospace Center (DLR) - * =================================================== - Copyright 2010 VIRES Simulationstechnologie GmbH - Copyright 2017 German Aerospace Center (DLR) - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - http://www.apache.org/licenses/LICENSE-2.0 - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - - - NOTE: - The methods have been realized using the CEPHES library - http://www.netlib.org/cephes/ - and do neither constitute the only nor the exclusive way of implementing - spirals for OpenDRIVE applications. Their sole purpose is to facilitate - the interpretation of OpenDRIVE spiral data. - */ - -/* ====== INCLUSIONS ====== */ -#include -#include - -/* ====== LOCAL VARIABLES ====== */ -#ifndef M_PI -#define M_PI 3.1415926535897932384626433832795 -#endif - -/* S(x) for small x */ -static double sn[6] = { --2.99181919401019853726E3, - 7.08840045257738576863E5, --6.29741486205862506537E7, - 2.54890880573376359104E9, --4.42979518059697779103E10, - 3.18016297876567817986E11, -}; -static double sd[6] = { -/* 1.00000000000000000000E0,*/ - 2.81376268889994315696E2, - 4.55847810806532581675E4, - 5.17343888770096400730E6, - 4.19320245898111231129E8, - 2.24411795645340920940E10, - 6.07366389490084639049E11, -}; - -/* C(x) for small x */ -static double cn[6] = { --4.98843114573573548651E-8, - 9.50428062829859605134E-6, --6.45191435683965050962E-4, - 1.88843319396703850064E-2, --2.05525900955013891793E-1, - 9.99999999999999998822E-1, -}; -static double cd[7] = { - 3.99982968972495980367E-12, - 9.15439215774657478799E-10, - 1.25001862479598821474E-7, - 1.22262789024179030997E-5, - 8.68029542941784300606E-4, - 4.12142090722199792936E-2, - 1.00000000000000000118E0, -}; - -/* Auxiliary function f(x) */ -static double fn[10] = { - 4.21543555043677546506E-1, - 1.43407919780758885261E-1, - 1.15220955073585758835E-2, - 3.45017939782574027900E-4, - 4.63613749287867322088E-6, - 3.05568983790257605827E-8, - 1.02304514164907233465E-10, - 1.72010743268161828879E-13, - 1.34283276233062758925E-16, - 3.76329711269987889006E-20, -}; -static double fd[10] = { -/* 1.00000000000000000000E0,*/ - 7.51586398353378947175E-1, - 1.16888925859191382142E-1, - 6.44051526508858611005E-3, - 1.55934409164153020873E-4, - 1.84627567348930545870E-6, - 1.12699224763999035261E-8, - 3.60140029589371370404E-11, - 5.88754533621578410010E-14, - 4.52001434074129701496E-17, - 1.25443237090011264384E-20, -}; - -/* Auxiliary function g(x) */ -static double gn[11] = { - 5.04442073643383265887E-1, - 1.97102833525523411709E-1, - 1.87648584092575249293E-2, - 6.84079380915393090172E-4, - 1.15138826111884280931E-5, - 9.82852443688422223854E-8, - 4.45344415861750144738E-10, - 1.08268041139020870318E-12, - 1.37555460633261799868E-15, - 8.36354435630677421531E-19, - 1.86958710162783235106E-22, -}; -static double gd[11] = { -/* 1.00000000000000000000E0,*/ - 1.47495759925128324529E0, - 3.37748989120019970451E-1, - 2.53603741420338795122E-2, - 8.14679107184306179049E-4, - 1.27545075667729118702E-5, - 1.04314589657571990585E-7, - 4.60680728146520428211E-10, - 1.10273215066240270757E-12, - 1.38796531259578871258E-15, - 8.39158816283118707363E-19, - 1.86958710162783236342E-22, -}; - - -static double polevl( double x, double* coef, int n ) -{ - double ans; - double *p = coef; - int i; - - ans = *p++; - i = n; - - do - { - ans = ans * x + *p++; - } - while (--i); - - return ans; -} - -static double p1evl( double x, double* coef, int n ) -{ - double ans; - double *p = coef; - int i; - - ans = x + *p++; - i = n - 1; - - do - { - ans = ans * x + *p++; - } - while (--i); - - return ans; -} - - -static void fresnel( double xxa, double *ssa, double *cca ) -{ - double f, g, cc, ss, c, s, t, u; - double x, x2; - - x = fabs( xxa ); - x2 = x * x; - - if ( x2 < 2.5625 ) - { - t = x2 * x2; - ss = x * x2 * polevl (t, sn, 5) / p1evl (t, sd, 6); - cc = x * polevl (t, cn, 5) / polevl (t, cd, 6); - } - else if ( x > 36974.0 ) - { - cc = 0.5; - ss = 0.5; - } - else - { - x2 = x * x; - t = M_PI * x2; - u = 1.0 / (t * t); - t = 1.0 / t; - f = 1.0 - u * polevl (u, fn, 9) / p1evl(u, fd, 10); - g = t * polevl (u, gn, 10) / p1evl (u, gd, 11); - - t = M_PI * 0.5 * x2; - c = cos (t); - s = sin (t); - t = M_PI * x; - cc = 0.5 + (f * s - g * c) / t; - ss = 0.5 - (f * c + g * s) / t; - } - - if ( xxa < 0.0 ) - { - cc = -cc; - ss = -ss; - } - - *cca = cc; - *ssa = ss; -} - - -/** -* compute the actual "standard" spiral, starting with curvature 0 -* @param s run-length along spiral -* @param cDot first derivative of curvature [1/m2] -* @param x resulting x-coordinate in spirals local co-ordinate system [m] -* @param y resulting y-coordinate in spirals local co-ordinate system [m] -* @param t tangent direction at s [rad] -*/ - -void odrSpiral( double s, double cDot, double *x, double *y, double *t ) -{ - double a; - - a = 1.0 / sqrt( fabs( cDot ) ); - a *= sqrt( M_PI ); - - fresnel( s / a, y, x ); - - *x *= a; - *y *= a; - - if ( cDot < 0.0 ) - *y *= -1.0; - - *t = s * s * cDot * 0.5; -} diff --git a/Util/OSM2ODR/src/foreign/eulerspiral/odrSpiral.h b/Util/OSM2ODR/src/foreign/eulerspiral/odrSpiral.h deleted file mode 100644 index bdc1b7804..000000000 --- a/Util/OSM2ODR/src/foreign/eulerspiral/odrSpiral.h +++ /dev/null @@ -1,32 +0,0 @@ -/* =================================================== - * file: odrSpiral.c - * --------------------------------------------------- - * purpose: free sample for computing spirals - * in OpenDRIVE applications - * --------------------------------------------------- - * first edit: 09.03.2010 by M. Dupuis @ VIRES GmbH - * last mod.: 09.03.2010 by M. Dupuis @ VIRES GmbH - * =================================================== - - Copyright 2010 VIRES Simulationstechnologie GmbH - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - http://www.apache.org/licenses/LICENSE-2.0 - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ - -/** -* compute the actual "standard" spiral, starting with curvature 0 -* @param s run-length along spiral -* @param cDot first derivative of curvature [1/m2] -* @param x resulting x-coordinate in spirals local co-ordinate system [m] -* @param y resulting y-coordinate in spirals local co-ordinate system [m] -* @param t tangent direction at s [rad] -*/ - -extern void odrSpiral( double s, double cDot, double *x, double *y, double *t ); diff --git a/Util/OSM2ODR/src/foreign/rtree/LayeredRTree.h b/Util/OSM2ODR/src/foreign/rtree/LayeredRTree.h deleted file mode 100644 index 14a355fa8..000000000 --- a/Util/OSM2ODR/src/foreign/rtree/LayeredRTree.h +++ /dev/null @@ -1,121 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file LayeredRTree.h -/// @author Jakob Erdmann -/// @date 16.10.2012 -/// -// A wrapper around RT-trees for for efficient storing of SUMO's GL-objects and -// accessing them ordered by their layer -// Note that we only need two layers at this time: -// 1 (GLO_LANE, GLO_VEHICLE, GLO_POI) -// 2 all the rest -// The search order returns layer 2 first because it must be drawn before layer -// 1 for alpha blending to work -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include -#include - -#include "SUMORTree.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -/** @class LayeredRTree - * @brief A RT-tree for efficient storing of SUMO's GL-objects in layers - * - * This class maintains SUMORTrees for each layer (only 2 at the moment) but - * provides the same interface as SUMORTree - */ -class LayeredRTree : public SUMORTree { -public: - /// @brief Constructor - LayeredRTree() { - myLayers.push_back(new SUMORTree()); - myLayers.push_back(new SUMORTree()); - } - - - /// @brief Destructor - ~LayeredRTree() { - for (std::vector::iterator it = myLayers.begin(); it != myLayers.end(); ++it) { - delete *it; - } - myLayers.clear(); - } - - - /** @brief Insert entry (delegate to appropriate layer) - * @param a_min Min of bounding rect - * @param a_max Max of bounding rect - * @param a_dataId Positive Id of data. Maybe zero, but negative numbers not allowed. - */ - void Insert(const float a_min[2], const float a_max[2], GUIGlObject* const & a_dataId) { - myLayers[selectLayer(a_dataId)]->Insert(a_min, a_max, a_dataId); - } - - - /** @brief Remove entry (delegate to appropriate layer) - * @param a_min Min of bounding rect - * @param a_max Max of bounding rect - * @param a_dataId Positive Id of data. Maybe zero, but negative numbers not allowed. - */ - void Remove(const float a_min[2], const float a_max[2], GUIGlObject* const & a_dataId) { - myLayers[selectLayer(a_dataId)]->Remove(a_min, a_max, a_dataId); - } - - /** @brief Find all within search rectangle (searches all layers in order) - * @param a_min Min of search bounding rect - * @param a_max Max of search bounding rect - * @param a_searchResult Search result array. Caller should set grow size. Function will reset, not append to array. - * @param a_resultCallback Callback function to return result. Callback should return 'true' to continue searching - * @param a_context User context to pass as parameter to a_resultCallback - * @return Returns the number of entries found - */ - int Search(const float a_min[2], const float a_max[2], const GUIVisualizationSettings& c) const { - int result = 0; - for (std::vector::const_iterator it = myLayers.begin(); it != myLayers.end(); ++it) { - result += (*it)->Search(a_min, a_max, c); - } - return result; - } - - -protected: - /// @brief the layers for drawing - std::vector myLayers; - -private: - - /// @brief select the appropriate layer for each object - inline size_t selectLayer(GUIGlObject* o) { - switch (o->getType()) { - case GLO_EDGE: - case GLO_LANE: - case GLO_POI: - case GLO_VEHICLE: - case GLO_PERSON: - return 1; - break; - default: - return 0; - } - } - -}; diff --git a/Util/OSM2ODR/src/foreign/rtree/README.TXT b/Util/OSM2ODR/src/foreign/rtree/README.TXT deleted file mode 100644 index 77766f2a1..000000000 --- a/Util/OSM2ODR/src/foreign/rtree/README.TXT +++ /dev/null @@ -1,32 +0,0 @@ - -TITLE - - R-TREES: A DYNAMIC INDEX STRUCTURE FOR SPATIAL SEARCHING - -DESCRIPTION - - A C++ templated version of the RTree algorithm. - For more information please read the comments in RTree.h - -AUTHORS - - * 1983 Original algorithm and test code by Antonin Guttman and Michael Stonebraker, UC Berkely - * 1994 ANCI C ported from original test code by Melinda Green - melinda@superliminal.com - * 1995 Sphere volume fix for degeneracy problem submitted by Paul Brook - * 2004 Templated C++ port by Greg Douglas - -LICENSE: - - Entirely free for all uses. Enjoy! - -FILES - * RTree.h The C++ templated RTree implementation. Well commented. - * Test.cpp A simple test program, ported from the original C version. - * MemoryTest.cpp A more rigourous test to validate memory use. - * README.TXT This file. - -TO BUILD - - To build a test, compile only one of the test files with RTree.h. - Both test files contain a main() function. - diff --git a/Util/OSM2ODR/src/foreign/rtree/RTree.h b/Util/OSM2ODR/src/foreign/rtree/RTree.h deleted file mode 100644 index 5891a46a0..000000000 --- a/Util/OSM2ODR/src/foreign/rtree/RTree.h +++ /dev/null @@ -1,1608 +0,0 @@ -#ifndef RTREE_H -#define RTREE_H - -// NOTE This file compiles under MSVC 6 SP5 and MSVC .Net 2003 it may not work on other compilers without modification. - -// NOTE These next few lines may be win32 specific, you may need to modify them to compile on other platform -#include -#include -#include -#include - -#define ASSERT assert // RTree uses ASSERT( condition ) -#ifndef Min - #define Min __min -#endif //Min -#ifndef Max - #define Max __max -#endif //Max - -#define rtree_min(a,b) (ab?a:b) - - - -// -// RTree.h -// - -#define RTREE_TEMPLATE template -#define RTREE_QUAL RTree - -#define RTREE_DONT_USE_MEMPOOLS // This version does not contain a fixed memory allocator, fill in lines with EXAMPLE to implement one. -#define RTREE_USE_SPHERICAL_VOLUME // Better split classification, may be slower on some systems - -#undef RTREE_WANTS_IO - -// Fwd decl -#ifdef RTREE_WANTS_IO -class RTFileStream; // File I/O helper class, look below for implementation and notes. -#endif - - -/// \class RTree -/// Implementation of RTree, a multidimensional bounding rectangle tree. -/// Example usage: For a 3-dimensional tree use RTree myTree; -/// -/// This modified, templated C++ version by Greg Douglas at Auran (http://www.auran.com) -/// -/// DATATYPE Referenced data, should be int, void*, obj* etc. no larger than sizeof and simple type -/// ELEMTYPE Type of element such as int or float -/// NUMDIMS Number of dimensions such as 2 or 3 -/// ELEMTYPEREAL Type of element that allows fractional and large values such as float or double, for use in volume calcs -/// -/// NOTES: Inserting and removing data requires the knowledge of its constant Minimal Bounding Rectangle. -/// This version uses new/delete for nodes, I recommend using a fixed size allocator for efficiency. -/// Instead of using a callback function for returned results, I recommend and efficient pre-sized, grow-only memory -/// array similar to MFC CArray or STL Vector for returning search query result. -/// -template -class RTree -{ -protected: - - struct Node; // Fwd decl. Used by other internal structs and iterator - -public: - - // These constant must be declared after Branch and before Node struct - // Stuck up here for MSVC 6 compiler. NSVC .NET 2003 is much happier. - enum - { - MAXNODES = TMAXNODES, ///< Max elements in node - MINNODES = TMINNODES ///< Min elements in node - }; - - -public: - typedef void(DATATYPENP::* Operation)(const CONTEXT &) const; - - RTree(Operation operation); - virtual ~RTree(); - - /// Insert entry - /// \param a_min Min of bounding rect - /// \param a_max Max of bounding rect - /// \param a_dataId Positive Id of data. Maybe zero, but negative numbers not allowed. - virtual void Insert(const ELEMTYPE a_min[NUMDIMS], const ELEMTYPE a_max[NUMDIMS], const DATATYPE& a_dataId); - - /// Remove entry - /// \param a_min Min of bounding rect - /// \param a_max Max of bounding rect - /// \param a_dataId Positive Id of data. Maybe zero, but negative numbers not allowed. - virtual void Remove(const ELEMTYPE a_min[NUMDIMS], const ELEMTYPE a_max[NUMDIMS], const DATATYPE& a_dataId); - - - /// DK 15.10.2008 - begin - //typedef void(DATATYPENP::* Operation)(const CONTEXT &) const; - - /// Find all within search rectangle - /// \param a_min Min of search bounding rect - /// \param a_max Max of search bounding rect - /// \param a_searchResult Search result array. Caller should set grow size. Function will reset, not append to array. - /// \param a_resultCallback Callback function to return result. Callback should return 'true' to continue searching - /// \param a_context User context to pass as parameter to a_resultCallback - /// \return Returns the number of entries found - virtual int Search(const ELEMTYPE a_min[NUMDIMS], const ELEMTYPE a_max[NUMDIMS], const CONTEXT &c) const; - - /// DK 15.10.2008 - end - - /// Remove all entries from tree - void RemoveAll(); - - /// Count the data elements in this container. This is slow as no internal counter is maintained. - int Count(); - -#ifdef RTREE_WANTS_IO - /// Load tree contents from file - bool Load(const char* a_fileName); - /// Load tree contents from stream - bool Load(RTFileStream& a_stream); - - - /// Save tree contents to file - bool Save(const char* a_fileName); - /// Save tree contents to stream - bool Save(RTFileStream& a_stream); -#endif - - /// Iterator is not remove safe. - class Iterator - { - private: - - enum { MAX_STACK = 32 }; // Max stack size. Allows almost n^32 where n is number of branches in node - - struct StackElement - { - Node* m_node; - int m_branchIndex; - }; - - public: - - Iterator() { Init(); } - - ~Iterator() { } - - /// Is iterator invalid - bool IsNull() { return (m_tos <= 0); } - - /// Is iterator pointing to valid data - bool IsNotNull() { return (m_tos > 0); } - - /// Access the current data element. Caller must be sure iterator is not NULL first. - DATATYPE& operator*() - { - ASSERT(IsNotNull()); - StackElement& curTos = m_stack[m_tos - 1]; - return curTos.m_node->m_branch[curTos.m_branchIndex].m_data; - } - - /// Access the current data element. Caller must be sure iterator is not NULL first. - const DATATYPE& operator*() const - { - ASSERT(IsNotNull()); - StackElement& curTos = m_stack[m_tos - 1]; - return curTos.m_node->m_branch[curTos.m_branchIndex].m_data; - } - - /// Find the next data element - bool operator++() { return FindNextData(); } - - private: - - /// Reset iterator - void Init() { m_tos = 0; } - - /// Find the next data element in the tree (For internal use only) - bool FindNextData() - { - for(;;) - { - if(m_tos <= 0) - { - return false; - } - StackElement curTos = Pop(); // Copy stack top cause it may change as we use it - - if(curTos.m_node->IsLeaf()) - { - // Keep walking through data while we can - if(curTos.m_branchIndex+1 < curTos.m_node->m_count) - { - // There is more data, just point to the next one - Push(curTos.m_node, curTos.m_branchIndex + 1); - return true; - } - // No more data, so it will fall back to previous level - } - else - { - if(curTos.m_branchIndex+1 < curTos.m_node->m_count) - { - // Push sibling on for future tree walk - // This is the 'fall back' node when we finish with the current level - Push(curTos.m_node, curTos.m_branchIndex + 1); - } - // Since cur node is not a leaf, push first of next level to get deeper into the tree - Node* nextLevelnode = curTos.m_node->m_branch[curTos.m_branchIndex].m_child; - Push(nextLevelnode, 0); - - // If we pushed on a new leaf, exit as the data is ready at TOS - if(nextLevelnode->IsLeaf()) - { - return true; - } - } - } - } - - /// Push node and branch onto iteration stack (For internal use only) - void Push(Node* a_node, int a_branchIndex) - { - m_stack[m_tos].m_node = a_node; - m_stack[m_tos].m_branchIndex = a_branchIndex; - ++m_tos; - ASSERT(m_tos <= MAX_STACK); - } - - /// Pop element off iteration stack (For internal use only) - StackElement& Pop() - { - ASSERT(m_tos > 0); - --m_tos; - return m_stack[m_tos]; - } - - StackElement m_stack[MAX_STACK]; ///< Stack as we are doing iteration instead of recursion - int m_tos; ///< Top Of Stack index - - friend class RTree; // Allow hiding of non-public functions while allowing manipulation by logical owner - }; - - /// Get 'first' for iteration - void GetFirst(Iterator& a_it) - { - a_it.Init(); - if(m_root && (m_root->m_count > 0)) - { - a_it.Push(m_root, 0); - a_it.FindNextData(); - } - } - - /// Get Next for iteration - void GetNext(Iterator& a_it) { ++a_it; } - - /// Is iterator NULL, or at end? - bool IsNull(Iterator& a_it) { return a_it.IsNull(); } - - /// Get object at iterator position - DATATYPE& GetAt(Iterator& a_it) { return *a_it; } - -protected: - - /// Minimal bounding rectangle (n-dimensional) - struct Rect - { - ELEMTYPE m_min[NUMDIMS]; ///< Min dimensions of bounding box - ELEMTYPE m_max[NUMDIMS]; ///< Max dimensions of bounding box - }; - - /// May be data or may be another subtree - /// The parents level determines this. - /// If the parents level is 0, then this is data - struct Branch - { - Rect m_rect; ///< Bounds - union - { - Node* m_child; ///< Child node - DATATYPE m_data; ///< Data Id or Ptr - }; - }; - - /// Node for each branch level - struct Node - { - bool IsInternalNode() const { return (m_level > 0); } // Not a leaf, but a internal node - bool IsLeaf() const { return (m_level == 0); } // A leaf, contains data - - int m_count; ///< Count - int m_level; ///< Leaf is zero, others positive - Branch m_branch[MAXNODES]; ///< Branch - }; - - /// A link list of nodes for reinsertion after a delete operation - struct ListNode - { - ListNode* m_next; ///< Next in list - Node* m_node; ///< Node - }; - - /// Variables for finding a split partition - struct PartitionVars - { - int m_partition[MAXNODES+1]; - int m_total; - int m_minFill; - int m_taken[MAXNODES+1]; - int m_count[2]; - Rect m_cover[2]; - ELEMTYPEREAL m_area[2]; - - Branch m_branchBuf[MAXNODES+1]; - int m_branchCount; - Rect m_coverSplit; - ELEMTYPEREAL m_coverSplitArea; - }; - - Node* AllocNode(); - void FreeNode(Node* a_node); - void InitNode(Node* a_node); - void InitRect(Rect* a_rect); - bool InsertRectRec(Rect* a_rect, const DATATYPE& a_id, Node* a_node, Node** a_newNode, int a_level); - bool InsertRect(Rect* a_rect, const DATATYPE& a_id, Node** a_root, int a_level); - Rect NodeCover(Node* a_node); - bool AddBranch(Branch* a_branch, Node* a_node, Node** a_newNode); - void DisconnectBranch(Node* a_node, int a_index); - int PickBranch(Rect* a_rect, Node* a_node); - Rect CombineRect(Rect* a_rectA, Rect* a_rectB); - void SplitNode(Node* a_node, Branch* a_branch, Node** a_newNode); - ELEMTYPEREAL RectSphericalVolume(Rect* a_rect); - ELEMTYPEREAL RectVolume(Rect* a_rect); - ELEMTYPEREAL CalcRectVolume(Rect* a_rect); - void GetBranches(Node* a_node, Branch* a_branch, PartitionVars* a_parVars); - void ChoosePartition(PartitionVars* a_parVars, int a_minFill); - void LoadNodes(Node* a_nodeA, Node* a_nodeB, PartitionVars* a_parVars); - void InitParVars(PartitionVars* a_parVars, int a_maxRects, int a_minFill); - void PickSeeds(PartitionVars* a_parVars); - void Classify(int a_index, int a_group, PartitionVars* a_parVars); - bool RemoveRect(Rect* a_rect, const DATATYPE& a_id, Node** a_root); - bool RemoveRectRec(Rect* a_rect, const DATATYPE& a_id, Node* a_node, ListNode** a_listNode); - ListNode* AllocListNode(); - void FreeListNode(ListNode* a_listNode); - bool Overlap(Rect* a_rectA, Rect* a_rectB) const; - void ReInsert(Node* a_node, ListNode** a_listNode); - bool Search(Node* a_node, Rect* a_rect, int& a_foundCount, const CONTEXT &c) const; - void RemoveAllRec(Node* a_node); - void Reset(); - void CountRec(Node* a_node, int& a_count); - -#ifdef RTREE_WANTS_IO - bool SaveRec(Node* a_node, RTFileStream& a_stream); - bool LoadRec(Node* a_node, RTFileStream& a_stream); -#endif - - Node* m_root; ///< Root of tree - ELEMTYPEREAL m_unitSphereVolume; ///< Unit sphere constant for required number of dimensions - Operation myOperation; -}; - - -#ifdef RTREE_WANTS_IO -// Because there is not stream support, this is a quick and dirty file I/O helper. -// Users will likely replace its usage with a Stream implementation from their favorite API. -class RTFileStream -{ - FILE* m_file; - -public: - - - RTFileStream() - { - m_file = NULL; - } - - ~RTFileStream() - { - Close(); - } - - bool OpenRead(const char* a_fileName) - { - m_file = fopen(a_fileName, "rb"); - if(!m_file) - { - return false; - } - return true; - } - - bool OpenWrite(const char* a_fileName) - { - m_file = fopen(a_fileName, "wb"); - if(!m_file) - { - return false; - } - return true; - } - - void Close() - { - if(m_file) - { - fclose(m_file); - m_file = NULL; - } - } - - template< typename TYPE > - size_t Write(const TYPE& a_value) - { - ASSERT(m_file); - return fwrite((void*)&a_value, sizeof(a_value), 1, m_file); - } - - template< typename TYPE > - size_t WriteArray(const TYPE* a_array, int a_count) - { - ASSERT(m_file); - return fwrite((void*)a_array, sizeof(TYPE) * a_count, 1, m_file); - } - - template< typename TYPE > - size_t Read(TYPE& a_value) - { - ASSERT(m_file); - return fread((void*)&a_value, sizeof(a_value), 1, m_file); - } - - template< typename TYPE > - size_t ReadArray(TYPE* a_array, int a_count) - { - ASSERT(m_file); - return fread((void*)a_array, sizeof(TYPE) * a_count, 1, m_file); - } -}; -#endif - - -RTREE_TEMPLATE -RTREE_QUAL::RTree(Operation operation) -: myOperation(operation) -{ - ASSERT(MAXNODES > MINNODES); - ASSERT(MINNODES > 0); - - - // We only support machine word size simple data type eg. integer index or object pointer. - // Since we are storing as union with non data branch - ASSERT(sizeof(DATATYPE) == sizeof(void*) || sizeof(DATATYPE) == sizeof(int)); - - // Precomputed volumes of the unit spheres for the first few dimensions - const float UNIT_SPHERE_VOLUMES[] = { - 0.000000f, 2.000000f, 3.141593f, // Dimension 0,1,2 - 4.188790f, 4.934802f, 5.263789f, // Dimension 3,4,5 - 5.167713f, 4.724766f, 4.058712f, // Dimension 6,7,8 - 3.298509f, 2.550164f, 1.884104f, // Dimension 9,10,11 - 1.335263f, 0.910629f, 0.599265f, // Dimension 12,13,14 - 0.381443f, 0.235331f, 0.140981f, // Dimension 15,16,17 - 0.082146f, 0.046622f, 0.025807f, // Dimension 18,19,20 - }; - - m_root = AllocNode(); - m_root->m_level = 0; - m_unitSphereVolume = (ELEMTYPEREAL)UNIT_SPHERE_VOLUMES[NUMDIMS]; -} - - -RTREE_TEMPLATE -RTREE_QUAL::~RTree() -{ - Reset(); // Free, or reset node memory -} - - -RTREE_TEMPLATE -void RTREE_QUAL::Insert(const ELEMTYPE a_min[NUMDIMS], const ELEMTYPE a_max[NUMDIMS], const DATATYPE& a_dataId) -{ -#ifdef _DEBUG - for(int index=0; indexIsInternalNode()) // not a leaf node - { - for(int index = 0; index < a_node->m_count; ++index) - { - CountRec(a_node->m_branch[index].m_child, a_count); - } - } - else // A leaf node - { - a_count += a_node->m_count; - } -} - - -#ifdef RTREE_WANTS_IO -RTREE_TEMPLATE -bool RTREE_QUAL::Load(const char* a_fileName) -{ - RemoveAll(); // Clear existing tree - - RTFileStream stream; - if(!stream.OpenRead(a_fileName)) - { - return false; - } - - bool result = Load(stream); - - stream.Close(); - - return result; -} - - - -RTREE_TEMPLATE -bool RTREE_QUAL::Load(RTFileStream& a_stream) -{ - // Write some kind of header - int _dataFileId = ('R'<<0)|('T'<<8)|('R'<<16)|('E'<<24); - int _dataSize = sizeof(DATATYPE); - int _dataNumDims = NUMDIMS; - int _dataElemSize = sizeof(ELEMTYPE); - int _dataElemRealSize = sizeof(ELEMTYPEREAL); - int _dataMaxNodes = TMAXNODES; - int _dataMinNodes = TMINNODES; - - int dataFileId = 0; - int dataSize = 0; - int dataNumDims = 0; - int dataElemSize = 0; - int dataElemRealSize = 0; - int dataMaxNodes = 0; - int dataMinNodes = 0; - - a_stream.Read(dataFileId); - a_stream.Read(dataSize); - a_stream.Read(dataNumDims); - a_stream.Read(dataElemSize); - a_stream.Read(dataElemRealSize); - a_stream.Read(dataMaxNodes); - a_stream.Read(dataMinNodes); - - bool result = false; - - // Test if header was valid and compatible - if( (dataFileId == _dataFileId) - && (dataSize == _dataSize) - && (dataNumDims == _dataNumDims) - && (dataElemSize == _dataElemSize) - && (dataElemRealSize == _dataElemRealSize) - && (dataMaxNodes == _dataMaxNodes) - && (dataMinNodes == _dataMinNodes) - ) - { - // Recursively load tree - result = LoadRec(m_root, a_stream); - } - - return result; -} - - -RTREE_TEMPLATE -bool RTREE_QUAL::LoadRec(Node* a_node, RTFileStream& a_stream) -{ - a_stream.Read(a_node->m_level); - a_stream.Read(a_node->m_count); - - if(a_node->IsInternalNode()) // not a leaf node - { - for(int index = 0; index < a_node->m_count; ++index) - { - Branch* curBranch = &a_node->m_branch[index]; - - a_stream.ReadArray(curBranch->m_rect.m_min, NUMDIMS); - a_stream.ReadArray(curBranch->m_rect.m_max, NUMDIMS); - - curBranch->m_child = AllocNode(); - LoadRec(curBranch->m_child, a_stream); - } - } - else // A leaf node - { - for(int index = 0; index < a_node->m_count; ++index) - { - Branch* curBranch = &a_node->m_branch[index]; - - a_stream.ReadArray(curBranch->m_rect.m_min, NUMDIMS); - a_stream.ReadArray(curBranch->m_rect.m_max, NUMDIMS); - - a_stream.Read(curBranch->m_data); - } - } - - return true; // Should do more error checking on I/O operations -} - - -RTREE_TEMPLATE -bool RTREE_QUAL::Save(const char* a_fileName) -{ - RTFileStream stream; - if(!stream.OpenWrite(a_fileName)) - { - return false; - } - - bool result = Save(stream); - - stream.Close(); - - return result; -} - - -RTREE_TEMPLATE -bool RTREE_QUAL::Save(RTFileStream& a_stream) -{ - // Write some kind of header - int dataFileId = ('R'<<0)|('T'<<8)|('R'<<16)|('E'<<24); - int dataSize = sizeof(DATATYPE); - int dataNumDims = NUMDIMS; - int dataElemSize = sizeof(ELEMTYPE); - int dataElemRealSize = sizeof(ELEMTYPEREAL); - int dataMaxNodes = TMAXNODES; - int dataMinNodes = TMINNODES; - - a_stream.Write(dataFileId); - a_stream.Write(dataSize); - a_stream.Write(dataNumDims); - a_stream.Write(dataElemSize); - a_stream.Write(dataElemRealSize); - a_stream.Write(dataMaxNodes); - a_stream.Write(dataMinNodes); - - // Recursively save tree - bool result = SaveRec(m_root, a_stream); - - return result; -} - - -RTREE_TEMPLATE -bool RTREE_QUAL::SaveRec(Node* a_node, RTFileStream& a_stream) -{ - a_stream.Write(a_node->m_level); - a_stream.Write(a_node->m_count); - - if(a_node->IsInternalNode()) // not a leaf node - { - for(int index = 0; index < a_node->m_count; ++index) - { - Branch* curBranch = &a_node->m_branch[index]; - - a_stream.WriteArray(curBranch->m_rect.m_min, NUMDIMS); - a_stream.WriteArray(curBranch->m_rect.m_max, NUMDIMS); - - SaveRec(curBranch->m_child, a_stream); - } - } - else // A leaf node - { - for(int index = 0; index < a_node->m_count; ++index) - { - Branch* curBranch = &a_node->m_branch[index]; - - a_stream.WriteArray(curBranch->m_rect.m_min, NUMDIMS); - a_stream.WriteArray(curBranch->m_rect.m_max, NUMDIMS); - - a_stream.Write(curBranch->m_data); - } - } - - return true; // Should do more error checking on I/O operations -} -#endif - - -RTREE_TEMPLATE -void RTREE_QUAL::RemoveAll() -{ - // Delete all existing nodes - Reset(); - - m_root = AllocNode(); - m_root->m_level = 0; -} - - -RTREE_TEMPLATE -void RTREE_QUAL::Reset() -{ -#ifdef RTREE_DONT_USE_MEMPOOLS - // Delete all existing nodes - RemoveAllRec(m_root); -#else // RTREE_DONT_USE_MEMPOOLS - // Just reset memory pools. We are not using complex types - // EXAMPLE -#endif // RTREE_DONT_USE_MEMPOOLS -} - - -RTREE_TEMPLATE -void RTREE_QUAL::RemoveAllRec(Node* a_node) -{ - ASSERT(a_node); - ASSERT(a_node->m_level >= 0); - - if(a_node->IsInternalNode()) // This is an internal node in the tree - { - for(int index=0; index < a_node->m_count; ++index) - { - RemoveAllRec(a_node->m_branch[index].m_child); - } - } - FreeNode(a_node); -} - - -RTREE_TEMPLATE -typename RTREE_QUAL::Node* RTREE_QUAL::AllocNode() -{ - Node* newNode; -#ifdef RTREE_DONT_USE_MEMPOOLS - newNode = new Node; -#else // RTREE_DONT_USE_MEMPOOLS - // EXAMPLE -#endif // RTREE_DONT_USE_MEMPOOLS - InitNode(newNode); - return newNode; -} - - -RTREE_TEMPLATE -void RTREE_QUAL::FreeNode(Node* a_node) -{ - ASSERT(a_node); - -#ifdef RTREE_DONT_USE_MEMPOOLS - delete a_node; -#else // RTREE_DONT_USE_MEMPOOLS - // EXAMPLE -#endif // RTREE_DONT_USE_MEMPOOLS -} - - -// Allocate space for a node in the list used in DeletRect to -// store Nodes that are too empty. -RTREE_TEMPLATE -typename RTREE_QUAL::ListNode* RTREE_QUAL::AllocListNode() -{ -#ifdef RTREE_DONT_USE_MEMPOOLS - return new ListNode; -#else // RTREE_DONT_USE_MEMPOOLS - // EXAMPLE -#endif // RTREE_DONT_USE_MEMPOOLS -} - - -RTREE_TEMPLATE -void RTREE_QUAL::FreeListNode(ListNode* a_listNode) -{ -#ifdef RTREE_DONT_USE_MEMPOOLS - delete a_listNode; -#else // RTREE_DONT_USE_MEMPOOLS - // EXAMPLE -#endif // RTREE_DONT_USE_MEMPOOLS -} - - -RTREE_TEMPLATE -void RTREE_QUAL::InitNode(Node* a_node) -{ - a_node->m_count = 0; - a_node->m_level = -1; -} - - -RTREE_TEMPLATE -void RTREE_QUAL::InitRect(Rect* a_rect) -{ - for(int index = 0; index < NUMDIMS; ++index) - { - a_rect->m_min[index] = (ELEMTYPE)0; - a_rect->m_max[index] = (ELEMTYPE)0; - } -} - - -// Inserts a new data rectangle into the index structure. -// Recursively descends tree, propagates splits back up. -// Returns 0 if node was not split. Old node updated. -// If node was split, returns 1 and sets the pointer pointed to by -// new_node to point to the new node. Old node updated to become one of two. -// The level argument specifies the number of steps up from the leaf -// level to insert; e.g. a data rectangle goes in at level = 0. -RTREE_TEMPLATE -bool RTREE_QUAL::InsertRectRec(Rect* a_rect, const DATATYPE& a_id, Node* a_node, Node** a_newNode, int a_level) -{ - ASSERT(a_rect && a_node && a_newNode); - ASSERT(a_level >= 0 && a_level <= a_node->m_level); - - int index; - Branch branch; - Node* otherNode; - - // Still above level for insertion, go down tree recursively - if(a_node->m_level > a_level) - { - index = PickBranch(a_rect, a_node); - if (!InsertRectRec(a_rect, a_id, a_node->m_branch[index].m_child, &otherNode, a_level)) - { - // Child was not split - a_node->m_branch[index].m_rect = CombineRect(a_rect, &(a_node->m_branch[index].m_rect)); - return false; - } - else // Child was split - { - a_node->m_branch[index].m_rect = NodeCover(a_node->m_branch[index].m_child); - branch.m_child = otherNode; - branch.m_rect = NodeCover(otherNode); - return AddBranch(&branch, a_node, a_newNode); - } - } - else if(a_node->m_level == a_level) // Have reached level for insertion. Add rect, split if necessary - { - branch.m_rect = *a_rect; - branch.m_child = (Node*) a_id; - // Child field of leaves contains id of data record - return AddBranch(&branch, a_node, a_newNode); - } - else - { - // Should never occur - ASSERT(0); - return false; - } -} - - -// Insert a data rectangle into an index structure. -// InsertRect provides for splitting the root; -// returns 1 if root was split, 0 if it was not. -// The level argument specifies the number of steps up from the leaf -// level to insert; e.g. a data rectangle goes in at level = 0. -// InsertRect2 does the recursion. -// -RTREE_TEMPLATE -bool RTREE_QUAL::InsertRect(Rect* a_rect, const DATATYPE& a_id, Node** a_root, int a_level) -{ - ASSERT(a_rect && a_root); - ASSERT(a_level >= 0 && a_level <= (*a_root)->m_level); -#ifdef _DEBUG - for(int index=0; index < NUMDIMS; ++index) - { - ASSERT(a_rect->m_min[index] <= a_rect->m_max[index]); - } -#endif //_DEBUG - - Node* newRoot; - Node* newNode; - Branch branch; - - if(InsertRectRec(a_rect, a_id, *a_root, &newNode, a_level)) // Root split - { - newRoot = AllocNode(); // Grow tree taller and new root - newRoot->m_level = (*a_root)->m_level + 1; - branch.m_rect = NodeCover(*a_root); - branch.m_child = *a_root; - AddBranch(&branch, newRoot, NULL); - branch.m_rect = NodeCover(newNode); - branch.m_child = newNode; - AddBranch(&branch, newRoot, NULL); - *a_root = newRoot; - return true; - } - - return false; -} - - -// Find the smallest rectangle that includes all rectangles in branches of a node. -RTREE_TEMPLATE -typename RTREE_QUAL::Rect RTREE_QUAL::NodeCover(Node* a_node) -{ - ASSERT(a_node); - - int firstTime = true; - Rect rect; - InitRect(&rect); - - for(int index = 0; index < a_node->m_count; ++index) - { - if(firstTime) - { - rect = a_node->m_branch[index].m_rect; - firstTime = false; - } - else - { - rect = CombineRect(&rect, &(a_node->m_branch[index].m_rect)); - } - } - - return rect; -} - - -// Add a branch to a node. Split the node if necessary. -// Returns 0 if node not split. Old node updated. -// Returns 1 if node split, sets *new_node to address of new node. -// Old node updated, becomes one of two. -RTREE_TEMPLATE -bool RTREE_QUAL::AddBranch(Branch* a_branch, Node* a_node, Node** a_newNode) -{ - ASSERT(a_branch); - ASSERT(a_node); - - if(a_node->m_count < MAXNODES) // Split won't be necessary - { - a_node->m_branch[a_node->m_count] = *a_branch; - ++a_node->m_count; - - return false; - } - else - { - ASSERT(a_newNode); - - SplitNode(a_node, a_branch, a_newNode); - return true; - } -} - - -// Disconnect a dependent node. -// Caller must return (or stop using iteration index) after this as count has changed -RTREE_TEMPLATE -void RTREE_QUAL::DisconnectBranch(Node* a_node, int a_index) -{ - ASSERT(a_node && (a_index >= 0) && (a_index < MAXNODES)); - ASSERT(a_node->m_count > 0); - - // Remove element by swapping with the last element to prevent gaps in array - a_node->m_branch[a_index] = a_node->m_branch[a_node->m_count - 1]; - - --a_node->m_count; -} - - -// Pick a branch. Pick the one that will need the smallest increase -// in area to accomodate the new rectangle. This will result in the -// least total area for the covering rectangles in the current node. -// In case of a tie, pick the one which was smaller before, to get -// the best resolution when searching. -RTREE_TEMPLATE -int RTREE_QUAL::PickBranch(Rect* a_rect, Node* a_node) -{ - ASSERT(a_rect && a_node); - - bool firstTime = true; - ELEMTYPEREAL increase; - ELEMTYPEREAL bestIncr = (ELEMTYPEREAL)-1; - ELEMTYPEREAL area; - ELEMTYPEREAL bestArea = 0; - int best = 0; - Rect tempRect; - - for(int index=0; index < a_node->m_count; ++index) - { - Rect* curRect = &a_node->m_branch[index].m_rect; - area = CalcRectVolume(curRect); - tempRect = CombineRect(a_rect, curRect); - increase = CalcRectVolume(&tempRect) - area; - if((increase < bestIncr) || firstTime) - { - best = index; - bestArea = area; - bestIncr = increase; - firstTime = false; - } - else if((increase == bestIncr) && (area < bestArea)) - { - best = index; - bestArea = area; - bestIncr = increase; - } - } - return best; -} - - -// Combine two rectangles into larger one containing both -RTREE_TEMPLATE -typename RTREE_QUAL::Rect RTREE_QUAL::CombineRect(Rect* a_rectA, Rect* a_rectB) -{ - ASSERT(a_rectA && a_rectB); - - Rect newRect; - - for(int index = 0; index < NUMDIMS; ++index) - { - newRect.m_min[index] = rtree_min(a_rectA->m_min[index], a_rectB->m_min[index]); - newRect.m_max[index] = rtree_max(a_rectA->m_max[index], a_rectB->m_max[index]); - } - - return newRect; -} - - - -// Split a node. -// Divides the nodes branches and the extra one between two nodes. -// Old node is one of the new ones, and one really new one is created. -// Tries more than one method for choosing a partition, uses best result. -RTREE_TEMPLATE -void RTREE_QUAL::SplitNode(Node* a_node, Branch* a_branch, Node** a_newNode) -{ - ASSERT(a_node); - ASSERT(a_branch); - - // Could just use local here, but member or external is faster since it is reused - PartitionVars localVars; - PartitionVars* parVars = &localVars; - int level; - - // Load all the branches into a buffer, initialize old node - level = a_node->m_level; - GetBranches(a_node, a_branch, parVars); - - // Find partition - ChoosePartition(parVars, MINNODES); - - // Put branches from buffer into 2 nodes according to chosen partition - *a_newNode = AllocNode(); - (*a_newNode)->m_level = a_node->m_level = level; - LoadNodes(a_node, *a_newNode, parVars); - - ASSERT((a_node->m_count + (*a_newNode)->m_count) == parVars->m_total); -} - - -// Calculate the n-dimensional volume of a rectangle -RTREE_TEMPLATE -ELEMTYPEREAL RTREE_QUAL::RectVolume(Rect* a_rect) -{ - ASSERT(a_rect); - - ELEMTYPEREAL volume = (ELEMTYPEREAL)1; - - for(int index=0; indexm_max[index] - a_rect->m_min[index]; - } - - ASSERT(volume >= (ELEMTYPEREAL)0); - - return volume; -} - - -// The exact volume of the bounding sphere for the given Rect -RTREE_TEMPLATE -ELEMTYPEREAL RTREE_QUAL::RectSphericalVolume(Rect* a_rect) -{ - ASSERT(a_rect); - - ELEMTYPEREAL sumOfSquares = (ELEMTYPEREAL)0; - ELEMTYPEREAL radius; - - for(int index=0; index < NUMDIMS; ++index) - { - ELEMTYPEREAL halfExtent = ((ELEMTYPEREAL)a_rect->m_max[index] - (ELEMTYPEREAL)a_rect->m_min[index]) * 0.5f; - sumOfSquares += halfExtent * halfExtent; - } - - radius = (ELEMTYPEREAL)sqrt(sumOfSquares); - - // Pow maybe slow, so test for common dims like 2,3 and just use x*x, x*x*x. - if(NUMDIMS == 3) - { - return (radius * radius * radius * m_unitSphereVolume); - } - else if(NUMDIMS == 2) - { - return (radius * radius * m_unitSphereVolume); - } - else - { - return (ELEMTYPEREAL)(pow(radius, NUMDIMS) * m_unitSphereVolume); - } -} - - -// Use one of the methods to calculate retangle volume -RTREE_TEMPLATE -ELEMTYPEREAL RTREE_QUAL::CalcRectVolume(Rect* a_rect) -{ -#ifdef RTREE_USE_SPHERICAL_VOLUME - return RectSphericalVolume(a_rect); // Slower but helps certain merge cases -#else // RTREE_USE_SPHERICAL_VOLUME - return RectVolume(a_rect); // Faster but can cause poor merges -#endif // RTREE_USE_SPHERICAL_VOLUME -} - - -// Load branch buffer with branches from full node plus the extra branch. -RTREE_TEMPLATE -void RTREE_QUAL::GetBranches(Node* a_node, Branch* a_branch, PartitionVars* a_parVars) -{ - ASSERT(a_node); - ASSERT(a_branch); - - ASSERT(a_node->m_count == MAXNODES); - - // Load the branch buffer - int index; - for(index=0; index < MAXNODES; ++index) - { - a_parVars->m_branchBuf[index] = a_node->m_branch[index]; - } - a_parVars->m_branchBuf[MAXNODES] = *a_branch; - a_parVars->m_branchCount = MAXNODES + 1; - - // Calculate rect containing all in the set - a_parVars->m_coverSplit = a_parVars->m_branchBuf[0].m_rect; - for(index=1; index < MAXNODES+1; ++index) - { - a_parVars->m_coverSplit = CombineRect(&a_parVars->m_coverSplit, &a_parVars->m_branchBuf[index].m_rect); - } - a_parVars->m_coverSplitArea = CalcRectVolume(&a_parVars->m_coverSplit); - - InitNode(a_node); -} - - -// Method #0 for choosing a partition: -// As the seeds for the two groups, pick the two rects that would waste the -// most area if covered by a single rectangle, i.e. evidently the worst pair -// to have in the same group. -// Of the remaining, one at a time is chosen to be put in one of the two groups. -// The one chosen is the one with the greatest difference in area expansion -// depending on which group - the rect most strongly attracted to one group -// and repelled from the other. -// If one group gets too full (more would force other group to violate min -// fill requirement) then other group gets the rest. -// These last are the ones that can go in either group most easily. -RTREE_TEMPLATE -void RTREE_QUAL::ChoosePartition(PartitionVars* a_parVars, int a_minFill) -{ - ASSERT(a_parVars); - - ELEMTYPEREAL biggestDiff; - int group, chosen = 0, betterGroup = 0; - - InitParVars(a_parVars, a_parVars->m_branchCount, a_minFill); - PickSeeds(a_parVars); - - while (((a_parVars->m_count[0] + a_parVars->m_count[1]) < a_parVars->m_total) - && (a_parVars->m_count[0] < (a_parVars->m_total - a_parVars->m_minFill)) - && (a_parVars->m_count[1] < (a_parVars->m_total - a_parVars->m_minFill))) - { - biggestDiff = (ELEMTYPEREAL) -1; - for(int index=0; indexm_total; ++index) - { - if(!a_parVars->m_taken[index]) - { - Rect* curRect = &a_parVars->m_branchBuf[index].m_rect; - Rect rect0 = CombineRect(curRect, &a_parVars->m_cover[0]); - Rect rect1 = CombineRect(curRect, &a_parVars->m_cover[1]); - ELEMTYPEREAL growth0 = CalcRectVolume(&rect0) - a_parVars->m_area[0]; - ELEMTYPEREAL growth1 = CalcRectVolume(&rect1) - a_parVars->m_area[1]; - ELEMTYPEREAL diff = growth1 - growth0; - if(diff >= 0) - { - group = 0; - } - else - { - group = 1; - diff = -diff; - } - - if(diff > biggestDiff) - { - biggestDiff = diff; - chosen = index; - betterGroup = group; - } - else if((diff == biggestDiff) && (a_parVars->m_count[group] < a_parVars->m_count[betterGroup])) - { - chosen = index; - betterGroup = group; - } - } - } - Classify(chosen, betterGroup, a_parVars); - } - - // If one group too full, put remaining rects in the other - if((a_parVars->m_count[0] + a_parVars->m_count[1]) < a_parVars->m_total) - { - if(a_parVars->m_count[0] >= a_parVars->m_total - a_parVars->m_minFill) - { - group = 1; - } - else - { - group = 0; - } - for(int index=0; indexm_total; ++index) - { - if(!a_parVars->m_taken[index]) - { - Classify(index, group, a_parVars); - } - } - } - - ASSERT((a_parVars->m_count[0] + a_parVars->m_count[1]) == a_parVars->m_total); - ASSERT((a_parVars->m_count[0] >= a_parVars->m_minFill) && - (a_parVars->m_count[1] >= a_parVars->m_minFill)); -} - - -// Copy branches from the buffer into two nodes according to the partition. -RTREE_TEMPLATE -void RTREE_QUAL::LoadNodes(Node* a_nodeA, Node* a_nodeB, PartitionVars* a_parVars) -{ - ASSERT(a_nodeA); - ASSERT(a_nodeB); - ASSERT(a_parVars); - - for(int index=0; index < a_parVars->m_total; ++index) - { - ASSERT(a_parVars->m_partition[index] == 0 || a_parVars->m_partition[index] == 1); - - if(a_parVars->m_partition[index] == 0) - { - AddBranch(&a_parVars->m_branchBuf[index], a_nodeA, NULL); - } - else if(a_parVars->m_partition[index] == 1) - { - AddBranch(&a_parVars->m_branchBuf[index], a_nodeB, NULL); - } - } -} - - -// Initialize a PartitionVars structure. -RTREE_TEMPLATE -void RTREE_QUAL::InitParVars(PartitionVars* a_parVars, int a_maxRects, int a_minFill) -{ - ASSERT(a_parVars); - - a_parVars->m_count[0] = a_parVars->m_count[1] = 0; - a_parVars->m_area[0] = a_parVars->m_area[1] = (ELEMTYPEREAL)0; - a_parVars->m_total = a_maxRects; - a_parVars->m_minFill = a_minFill; - for(int index=0; index < a_maxRects; ++index) - { - a_parVars->m_taken[index] = false; - a_parVars->m_partition[index] = -1; - } -} - - -RTREE_TEMPLATE -void RTREE_QUAL::PickSeeds(PartitionVars* a_parVars) -{ - int seed0=0, seed1=1; - ELEMTYPEREAL worst, waste; - ELEMTYPEREAL area[MAXNODES+1]; - - for(int index=0; indexm_total; ++index) - { - area[index] = CalcRectVolume(&a_parVars->m_branchBuf[index].m_rect); - } - - worst = -a_parVars->m_coverSplitArea - 1; - for(int indexA=0; indexA < a_parVars->m_total-1; ++indexA) - { - for(int indexB = indexA+1; indexB < a_parVars->m_total; ++indexB) - { - Rect oneRect = CombineRect(&a_parVars->m_branchBuf[indexA].m_rect, &a_parVars->m_branchBuf[indexB].m_rect); - waste = CalcRectVolume(&oneRect) - area[indexA] - area[indexB]; - if(waste > worst) - { - worst = waste; - seed0 = indexA; - seed1 = indexB; - } - } - } - Classify(seed0, 0, a_parVars); - Classify(seed1, 1, a_parVars); -} - - -// Put a branch in one of the groups. -RTREE_TEMPLATE -void RTREE_QUAL::Classify(int a_index, int a_group, PartitionVars* a_parVars) -{ - ASSERT(a_parVars); - ASSERT(!a_parVars->m_taken[a_index]); - - a_parVars->m_partition[a_index] = a_group; - a_parVars->m_taken[a_index] = true; - - if (a_parVars->m_count[a_group] == 0) - { - a_parVars->m_cover[a_group] = a_parVars->m_branchBuf[a_index].m_rect; - } - else - { - a_parVars->m_cover[a_group] = CombineRect(&a_parVars->m_branchBuf[a_index].m_rect, &a_parVars->m_cover[a_group]); - } - a_parVars->m_area[a_group] = CalcRectVolume(&a_parVars->m_cover[a_group]); - ++a_parVars->m_count[a_group]; -} - - -// Delete a data rectangle from an index structure. -// Pass in a pointer to a Rect, the tid of the record, ptr to ptr to root node. -// Returns 1 if record not found, 0 if success. -// RemoveRect provides for eliminating the root. -RTREE_TEMPLATE -bool RTREE_QUAL::RemoveRect(Rect* a_rect, const DATATYPE& a_id, Node** a_root) -{ - ASSERT(a_rect && a_root); - ASSERT(*a_root); - - Node* tempNode; - ListNode* reInsertList = NULL; - - if(!RemoveRectRec(a_rect, a_id, *a_root, &reInsertList)) - { - // Found and deleted a data item - // Reinsert any branches from eliminated nodes - while(reInsertList) - { - tempNode = reInsertList->m_node; - - for(int index = 0; index < tempNode->m_count; ++index) - { - InsertRect(&(tempNode->m_branch[index].m_rect), - tempNode->m_branch[index].m_data, - a_root, - tempNode->m_level); - } - - ListNode* remLNode = reInsertList; - reInsertList = reInsertList->m_next; - - FreeNode(remLNode->m_node); - FreeListNode(remLNode); - } - - // Check for redundant root (not leaf, 1 child) and eliminate - if((*a_root)->m_count == 1 && (*a_root)->IsInternalNode()) - { - tempNode = (*a_root)->m_branch[0].m_child; - - ASSERT(tempNode); - FreeNode(*a_root); - *a_root = tempNode; - } - return false; - } - else - { - return true; - } -} - - -// Delete a rectangle from non-root part of an index structure. -// Called by RemoveRect. Descends tree recursively, -// merges branches on the way back up. -// Returns 1 if record not found, 0 if success. -RTREE_TEMPLATE -bool RTREE_QUAL::RemoveRectRec(Rect* a_rect, const DATATYPE& a_id, Node* a_node, ListNode** a_listNode) -{ - ASSERT(a_rect && a_node && a_listNode); - ASSERT(a_node->m_level >= 0); - - if(a_node->IsInternalNode()) // not a leaf node - { - for(int index = 0; index < a_node->m_count; ++index) - { - if(Overlap(a_rect, &(a_node->m_branch[index].m_rect))) - { - if(!RemoveRectRec(a_rect, a_id, a_node->m_branch[index].m_child, a_listNode)) - { - if(a_node->m_branch[index].m_child->m_count >= MINNODES) - { - // child removed, just resize parent rect - a_node->m_branch[index].m_rect = NodeCover(a_node->m_branch[index].m_child); - } - else - { - // child removed, not enough entries in node, eliminate node - ReInsert(a_node->m_branch[index].m_child, a_listNode); - DisconnectBranch(a_node, index); // Must return after this call as count has changed - } - return false; - } - } - } - return true; - } - else // A leaf node - { - for(int index = 0; index < a_node->m_count; ++index) - { - if(a_node->m_branch[index].m_child == (Node*)a_id) - { - DisconnectBranch(a_node, index); // Must return after this call as count has changed - return false; - } - } - return true; - } -} - - -// Decide whether two rectangles overlap. -RTREE_TEMPLATE -bool RTREE_QUAL::Overlap(Rect* a_rectA, Rect* a_rectB) const -{ - ASSERT(a_rectA && a_rectB); - - for(int index=0; index < NUMDIMS; ++index) - { - if (a_rectA->m_min[index] > a_rectB->m_max[index] || - a_rectB->m_min[index] > a_rectA->m_max[index]) - { - return false; - } - } - return true; -} - - -// Add a node to the reinsertion list. All its branches will later -// be reinserted into the index structure. -RTREE_TEMPLATE -void RTREE_QUAL::ReInsert(Node* a_node, ListNode** a_listNode) -{ - ListNode* newListNode; - - newListNode = AllocListNode(); - newListNode->m_node = a_node; - newListNode->m_next = *a_listNode; - *a_listNode = newListNode; -} - - - -// Search in an index tree or subtree for all data retangles that overlap the argument rectangle. -RTREE_TEMPLATE -bool RTREE_QUAL::Search(Node* a_node, Rect* a_rect, int& a_foundCount, const CONTEXT &c) const -{ - ASSERT(a_node); - ASSERT(a_node->m_level >= 0); - ASSERT(a_rect); - - if(a_node->IsInternalNode()) // This is an internal node in the tree - { - for(int index=0; index < a_node->m_count; ++index) - { - if(Overlap(a_rect, &a_node->m_branch[index].m_rect)) - { - if(!Search(a_node->m_branch[index].m_child, a_rect, a_foundCount, c)) - { - return false; // Don't continue searching - } - } - } - } - else // This is a leaf node - { - for(int index=0; index < a_node->m_count; ++index) - { - if(Overlap(a_rect, &a_node->m_branch[index].m_rect)) - { - DATATYPE& id = a_node->m_branch[index].m_data; - - // NOTE: There are different ways to return results. Here's where to modify -/* if(&a_resultCallback) - {*/ - ++a_foundCount; - (id->*myOperation)(c); - /* - if(!a_resultCallback(id, a_context)) - { - return false; // Don't continue searching - } - */ -// } - } - } - } - - return true; // Continue searching -} - - - - -#undef RTREE_TEMPLATE -#undef RTREE_QUAL - -#endif //RTREE_H - - - diff --git a/Util/OSM2ODR/src/foreign/rtree/SUMORTree.h b/Util/OSM2ODR/src/foreign/rtree/SUMORTree.h deleted file mode 100644 index 69425eb77..000000000 --- a/Util/OSM2ODR/src/foreign/rtree/SUMORTree.h +++ /dev/null @@ -1,193 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file SUMORTree.h -/// @author Daniel Krajzewicz -/// @date 27.10.2008 -/// -// A RT-tree for efficient storing of SUMO's GL-objects -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include -#include -#include -#include - -#include "RTree.h" - - -#define GUI_RTREE_QUAL RTree - -// specialized implementation for speedup and avoiding warnings - -template<> -inline float GUI_RTREE_QUAL::RectSphericalVolume(Rect* a_rect) { - ASSERT(a_rect); - const float extent0 = a_rect->m_max[0] - a_rect->m_min[0]; - const float extent1 = a_rect->m_max[1] - a_rect->m_min[1]; - return .78539816f * (extent0 * extent0 + extent1 * extent1); -} - -template<> -inline GUI_RTREE_QUAL::Rect GUI_RTREE_QUAL::CombineRect(Rect* a_rectA, Rect* a_rectB) { - ASSERT(a_rectA && a_rectB); - Rect newRect; - newRect.m_min[0] = rtree_min(a_rectA->m_min[0], a_rectB->m_min[0]); - newRect.m_max[0] = rtree_max(a_rectA->m_max[0], a_rectB->m_max[0]); - newRect.m_min[1] = rtree_min(a_rectA->m_min[1], a_rectB->m_min[1]); - newRect.m_max[1] = rtree_max(a_rectA->m_max[1], a_rectB->m_max[1]); - return newRect; -} - - -// =========================================================================== -// class definitions -// =========================================================================== -/** @class SUMORTree - * @brief A RT-tree for efficient storing of SUMO's GL-objects - * - * This class specialises the used RT-tree implementation from "rttree.h" and - * extends it by a mutex for avoiding parallel change and traversal of the tree. - */ -class SUMORTree : private GUI_RTREE_QUAL, public Boundary { -public: - /// @brief Constructor - SUMORTree() : - GUI_RTREE_QUAL(&GUIGlObject::drawGL), - myLock(true) { - } - - /// @brief Destructor - virtual ~SUMORTree() { - // check if lock is locked before insert objects - if (myLock.locked()) { - // cannot throw exception in destructor - WRITE_ERROR("Mutex of SUMORTree is locked during call of the destructor"); - } - // show information in gui testing debug gl mode - WRITE_GLDEBUG("Number of objects in SUMORTree during call of the destructor: " + toString(myTreeDebug.size())); - } - - /** @brief Insert entry - * @param a_min Min of bounding rect - * @param a_max Max of bounding rect - * @param a_dataId Positive Id of data. Maybe zero, but negative numbers not allowed. - * @see RTree::Insert - */ - virtual void Insert(const float a_min[2], const float a_max[2], GUIGlObject* const & a_dataId) { - FXMutexLock locker(myLock); - GUI_RTREE_QUAL::Insert(a_min, a_max, a_dataId); - } - - /** @brief Remove entry - * @param a_min Min of bounding rect - * @param a_max Max of bounding rect - * @param a_dataId Positive Id of data. Maybe zero, but negative numbers not allowed. - * @see RTree::Remove - */ - virtual void Remove(const float a_min[2], const float a_max[2], GUIGlObject* const & a_dataId) { - FXMutexLock locker(myLock); - GUI_RTREE_QUAL::Remove(a_min, a_max, a_dataId); - } - - /** @brief Find all within search rectangle - * @param a_min Min of search bounding rect - * @param a_max Max of search bounding rect - * @param a_searchResult Search result array. Caller should set grow size. Function will reset, not append to array. - * @param a_resultCallback Callback function to return result. Callback should return 'true' to continue searching - * @param a_context User context to pass as parameter to a_resultCallback - * @return Returns the number of entries found - * @see RTree::Search - */ - virtual int Search(const float a_min[2], const float a_max[2], const GUIVisualizationSettings& c) const { - FXMutexLock locker(myLock); - return GUI_RTREE_QUAL::Search(a_min, a_max, c); - } - - /** @brief Adds an additional object (detector/shape/trigger) for visualisation - * @param[in] o The object to add - */ - void addAdditionalGLObject(GUIGlObject *o) { - // check if lock is locked before insert objects - if (myLock.locked()) { - throw ProcessError("Mutex of SUMORTree is locked before object insertion"); - } - // lock mutex - FXMutexLock locker(myLock); - // obtain boundary of object - Boundary b = o->getCenteringBoundary(); - // show information in gui testing debug gl mode - if (MsgHandler::writeDebugGLMessages()) { - if ((b.getWidth() == 0) || (b.getHeight() == 0)) { - throw ProcessError("Boundary of GUIGlObject " + o->getMicrosimID() + " has an invalid size"); - } else if (myTreeDebug.count(o) > 0) { - throw ProcessError("GUIGlObject was already inserted"); - } else { - myTreeDebug[o] = b; - // write GL Debug - WRITE_GLDEBUG("\tInserted " + o->getFullName() + " into SUMORTree with boundary " + toString(b)); - } - } - // insert it in Tree - const float cmin[2] = {(float) b.xmin(), (float) b.ymin()}; - const float cmax[2] = {(float) b.xmax(), (float) b.ymax()}; - Insert(cmin, cmax, o); - } - - /** @brief Removes an additional object (detector/shape/trigger) from being visualised - * @param[in] o The object to remove - */ - void removeAdditionalGLObject(GUIGlObject *o) { - // check if lock is locked remove insert objects - if (myLock.locked()) { - throw ProcessError("Mutex of SUMORTree is locked before object remove"); - } - // lock mutex - FXMutexLock locker(myLock); - // obtain boundary of object - Boundary b = o->getCenteringBoundary(); - // show information in gui testing debug gl mode - if (MsgHandler::writeDebugGLMessages()) { - if ((b.getWidth() == 0) || (b.getHeight() == 0)) { - throw ProcessError("Boundary of GUIGlObject " + o->getMicrosimID() + " has an invalid size"); - } else if (myTreeDebug.count(o) == 0) { - throw ProcessError("GUIGlObject wasn't inserted"); - } else if (toString(b) != toString(myTreeDebug.at(o))) { - // show information in console before throwing exception - std::cout << "Tree: " << toString(myTreeDebug.at(o)) << " original: " << toString(b) << std::endl; - throw ProcessError("add boundary of GUIGlObject " + o->getMicrosimID() + " is different of removed boundary (" + toString(b) + " != " + toString(myTreeDebug.at(o)) + ")"); - } else { - myTreeDebug.erase(o); - WRITE_GLDEBUG("\tRemoved object " + o->getFullName() + " from SUMORTree with boundary " + toString(b)); - } - } - // remove it from Tree - const float cmin[2] = {(float) b.xmin(), (float) b.ymin()}; - const float cmax[2] = {(float) b.xmax(), (float) b.ymax()}; - Remove(cmin, cmax, o); - } - -protected: - /// @brief A mutex avoiding parallel change and traversal of the tree - mutable FXMutex myLock; - -private: - /**@brief Map only used for check that SUMORTree works as expected, only is used if option "gui-testing-debug-gl" is enabled. - * @note Warning: DO NOT USE in release mode and use it in debug mode carefully, due it produces a slowdown. - */ - std::map myTreeDebug; -}; diff --git a/Util/OSM2ODR/src/foreign/tcpip/CMakeLists.txt b/Util/OSM2ODR/src/foreign/tcpip/CMakeLists.txt deleted file mode 100644 index fbef2bce9..000000000 --- a/Util/OSM2ODR/src/foreign/tcpip/CMakeLists.txt +++ /dev/null @@ -1,12 +0,0 @@ -set(foreign_tcpip_STAT_SRCS - socket.h - socket.cpp - storage.h - storage.cpp -) - -add_library(foreign_tcpip STATIC ${foreign_tcpip_STAT_SRCS}) -set_property(TARGET foreign_tcpip PROPERTY PROJECT_LABEL "z_foreign_tcpip") -if (SUMO_UTILS) - install(TARGETS foreign_tcpip DESTINATION lib) -endif () diff --git a/Util/OSM2ODR/src/foreign/tcpip/socket.cpp b/Util/OSM2ODR/src/foreign/tcpip/socket.cpp deleted file mode 100644 index d61164587..000000000 --- a/Util/OSM2ODR/src/foreign/tcpip/socket.cpp +++ /dev/null @@ -1,650 +0,0 @@ -/************************************************************************ - ** This file is part of the network simulator Shawn. ** - ** Copyright (C) 2004-2007 by the SwarmNet (www.swarmnet.de) project ** - ** Shawn is free software; you can redistribute it and/or modify it ** - ** under the terms of the BSD License. Refer to the shawn-licence.txt ** - ** file in the root of the Shawn source tree for further details. ** - ************************************************************************/ - -#ifdef SHAWN - #include - #include -#else - #include "socket.h" -#endif - -#ifdef BUILD_TCPIP - - -#ifndef WIN32 - #include - #include - #include - #include - #include - #include - #include - #include - #include -#else - #ifdef ERROR - #undef ERROR - #endif - - #include - #include - - #ifndef vsnprintf - #define vsnprintf _vsnprintf - #endif - -#endif - -#include -#include -#include -#include -#include -#include -#include -#include -#include - - -#ifdef SHAWN - extern "C" void init_tcpip( shawn::SimulationController& sc ) - { - // std::cout << "tcpip init" << std::endl; - } -#endif - -namespace tcpip -{ - const int Socket::lengthLen = 4; - -#ifdef WIN32 - bool Socket::init_windows_sockets_ = true; - bool Socket::windows_sockets_initialized_ = false; - int Socket::instance_count_ = 0; -#endif - - // ---------------------------------------------------------------------- - Socket:: - Socket(std::string host, int port) - : host_( host ), - port_( port ), - socket_(-1), - server_socket_(-1), - blocking_(true), - verbose_(false) - { - init(); - } - - // ---------------------------------------------------------------------- - Socket:: - Socket(int port) - : host_(""), - port_( port ), - socket_(-1), - server_socket_(-1), - blocking_(true), - verbose_(false) - { - init(); - } - - // ---------------------------------------------------------------------- - void - Socket:: - init() - { -#ifdef WIN32 - instance_count_++; - - if( init_windows_sockets_ && !windows_sockets_initialized_ ) - { - WSAData wsaData; - if( WSAStartup(MAKEWORD(1, 1), &wsaData) != 0 ) - BailOnSocketError("Unable to init WSA Sockets"); - windows_sockets_initialized_ = true; - } -#endif - } - - - int - Socket:: - getFreeSocketPort() - { - // Create socket to find a random free port that can be handed to the app - int sock = static_cast(socket( AF_INET, SOCK_STREAM, 0 )); - struct sockaddr_in self; - memset(&self, 0, sizeof(self)); - self.sin_family = AF_INET; - self.sin_port = htons(0); - self.sin_addr.s_addr = htonl(INADDR_ANY); - - socklen_t address_len = sizeof(self); - // bind with port==0 assigns free port - if ( bind(sock, (struct sockaddr*) &self, address_len) < 0) - BailOnSocketError("tcpip::Socket::getFreeSocketPort() Unable to bind socket"); - // get the assigned port with getsockname - if ( getsockname(sock, (struct sockaddr*) &self, &address_len) < 0) - BailOnSocketError("tcpip::Socket::getFreeSocketPort() Unable to get socket name"); - const int port = ntohs(self.sin_port); -#ifdef WIN32 - ::closesocket( sock ); -#else - ::close( sock ); -#endif - return port; - } - - - // ---------------------------------------------------------------------- - Socket:: - ~Socket() - { - // Close first an existing client connection ... - close(); -#ifdef WIN32 - instance_count_--; -#endif - - // ... then the server socket - if( server_socket_ >= 0 ) - { -#ifdef WIN32 - ::closesocket( server_socket_ ); -#else - ::close( server_socket_ ); -#endif - server_socket_ = -1; - } - -#ifdef WIN32 - if( server_socket_ == -1 && socket_ == -1 - && init_windows_sockets_ && instance_count_ == 0 ) - WSACleanup(); - windows_sockets_initialized_ = false; -#endif - } - - // ---------------------------------------------------------------------- - void - Socket:: - BailOnSocketError( std::string context) - { -#ifdef WIN32 - int e = WSAGetLastError(); - std::string msg = GetWinsockErrorString( e ); -#else - std::string msg = strerror( errno ); -#endif - throw SocketException( context + ": " + msg ); - } - - // ---------------------------------------------------------------------- - int - Socket:: - port() - { - return port_; - } - - - // ---------------------------------------------------------------------- - bool - Socket:: - datawaiting(int sock) - const - { - fd_set fds; - FD_ZERO( &fds ); - FD_SET( (unsigned int)sock, &fds ); - - struct timeval tv; - tv.tv_sec = 0; - tv.tv_usec = 0; - - int r = select( sock+1, &fds, nullptr, nullptr, &tv); - - if (r < 0) - BailOnSocketError("tcpip::Socket::datawaiting @ select"); - - if( FD_ISSET( sock, &fds ) ) - return true; - else - return false; - } - - // ---------------------------------------------------------------------- - bool - Socket:: - atoaddr( std::string address, struct sockaddr_in& addr) - { - int status; - struct addrinfo *servinfo; // will point to the results - - struct addrinfo hints; - memset(&hints, 0, sizeof hints); // make sure the struct is empty - hints.ai_family = AF_INET; // restrict to IPv4? - hints.ai_socktype = SOCK_STREAM; // TCP stream sockets - hints.ai_flags = AI_PASSIVE; // fill in my IP for me - - if ((status = getaddrinfo(address.c_str(), nullptr, &hints, &servinfo)) != 0) { - return false; - } - - bool valid = false; - - for (struct addrinfo *p = servinfo; p != nullptr; p = p->ai_next) { - if (p->ai_family == AF_INET) { // IPv4 - addr = *(struct sockaddr_in *)p->ai_addr; - addr.sin_port = htons((unsigned short)port_); - valid = true; - break; - } - } - - freeaddrinfo(servinfo); // free the linked list - - return valid; - } - - - // ---------------------------------------------------------------------- - Socket* - Socket:: - accept(const bool create) - { - if( socket_ >= 0 ) - return nullptr; - - struct sockaddr_in client_addr; -#ifdef WIN32 - int addrlen = sizeof(client_addr); -#else - socklen_t addrlen = sizeof(client_addr); -#endif - - if( server_socket_ < 0 ) - { - struct sockaddr_in self; - - //Create the server socket - server_socket_ = static_cast(socket( AF_INET, SOCK_STREAM, 0 )); - if( server_socket_ < 0 ) - BailOnSocketError("tcpip::Socket::accept() @ socket"); - - //"Address already in use" error protection - { - - #ifdef WIN32 - //setsockopt(server_socket_, SOL_SOCKET, SO_REUSEADDR, (const char*)&reuseaddr, sizeof(reuseaddr)); - // No address reuse in Windows!!! - #else - int reuseaddr = 1; - setsockopt(server_socket_, SOL_SOCKET, SO_REUSEADDR, &reuseaddr, sizeof(reuseaddr)); - #endif - } - - // Initialize address/port structure - memset(&self, 0, sizeof(self)); - self.sin_family = AF_INET; - self.sin_port = htons((unsigned short)port_); - self.sin_addr.s_addr = htonl(INADDR_ANY); - - // Assign a port number to the socket - if ( bind(server_socket_, (struct sockaddr*)&self, sizeof(self)) != 0 ) - BailOnSocketError("tcpip::Socket::accept() Unable to create listening socket"); - - - // Make it a "listening socket" - if ( listen(server_socket_, 10) == -1 ) - BailOnSocketError("tcpip::Socket::accept() Unable to listen on server socket"); - - // Make the newly created socket blocking or not - set_blocking(blocking_); - } - - socket_ = static_cast(::accept(server_socket_, (struct sockaddr*)&client_addr, &addrlen)); - - if( socket_ >= 0 ) - { - int x = 1; - setsockopt(socket_, IPPROTO_TCP, TCP_NODELAY, (const char*)&x, sizeof(x)); - if (create) { - Socket* result = new Socket(0); - result->socket_ = socket_; - socket_ = -1; - return result; - } - } - return nullptr; - } - - // ---------------------------------------------------------------------- - void - Socket:: - set_blocking(bool blocking) - { - blocking_ = blocking; - - if( server_socket_ > 0 ) - { -#ifdef WIN32 - ULONG NonBlock = blocking_ ? 0 : 1; - if (ioctlsocket(server_socket_, FIONBIO, &NonBlock) == SOCKET_ERROR) - BailOnSocketError("tcpip::Socket::set_blocking() Unable to initialize non blocking I/O"); -#else - long arg = fcntl(server_socket_, F_GETFL, NULL); - if (blocking_) - { - arg &= ~O_NONBLOCK; - } else { - arg |= O_NONBLOCK; - } - fcntl(server_socket_, F_SETFL, arg); -#endif - } - - } - - // ---------------------------------------------------------------------- - void - Socket:: - connect() - { - sockaddr_in address; - - if( !atoaddr( host_.c_str(), address) ) - BailOnSocketError("tcpip::Socket::connect() @ Invalid network address"); - - socket_ = static_cast(socket( PF_INET, SOCK_STREAM, 0 )); - if( socket_ < 0 ) - BailOnSocketError("tcpip::Socket::connect() @ socket"); - - if( ::connect( socket_, (sockaddr const*)&address, sizeof(address) ) < 0 ) - BailOnSocketError("tcpip::Socket::connect() @ connect"); - - if( socket_ >= 0 ) - { - int x = 1; - setsockopt(socket_, IPPROTO_TCP, TCP_NODELAY, (const char*)&x, sizeof(x)); - } - } - - // ---------------------------------------------------------------------- - void - Socket:: - close() - { - // Close client-connection - if( socket_ >= 0 ) - { -#ifdef WIN32 - ::closesocket( socket_ ); -#else - ::close( socket_ ); -#endif - - socket_ = -1; - } - } - - // ---------------------------------------------------------------------- - void - Socket:: - send( const std::vector &buffer) - { - if( socket_ < 0 ) - return; - - printBufferOnVerbose(buffer, "Send"); - - size_t numbytes = buffer.size(); - unsigned char const *bufPtr = &buffer[0]; - while( numbytes > 0 ) - { -#ifdef WIN32 - int bytesSent = ::send( socket_, (const char*)bufPtr, static_cast(numbytes), 0 ); -#else - int bytesSent = ::send( socket_, bufPtr, numbytes, 0 ); -#endif - if( bytesSent < 0 ) - BailOnSocketError( "send failed" ); - - numbytes -= bytesSent; - bufPtr += bytesSent; - } - } - - - - // ---------------------------------------------------------------------- - - void - Socket:: - sendExact( const Storage &b) - { - int length = static_cast(b.size()); - Storage length_storage; - length_storage.writeInt(lengthLen + length); - - // Sending length_storage and b independently would probably be possible and - // avoid some copying here, but both parts would have to go through the - // TCP/IP stack on their own which probably would cost more performance. - std::vector msg; - msg.insert(msg.end(), length_storage.begin(), length_storage.end()); - msg.insert(msg.end(), b.begin(), b.end()); - send(msg); - } - - - // ---------------------------------------------------------------------- - size_t - Socket:: - recvAndCheck(unsigned char * const buffer, std::size_t len) - const - { -#ifdef WIN32 - const int bytesReceived = recv( socket_, (char*)buffer, static_cast(len), 0 ); -#else - const int bytesReceived = static_cast(recv( socket_, buffer, len, 0 )); -#endif - if( bytesReceived == 0 ) - throw SocketException( "tcpip::Socket::recvAndCheck @ recv: peer shutdown" ); - if( bytesReceived < 0 ) - BailOnSocketError( "tcpip::Socket::recvAndCheck @ recv" ); - - return static_cast(bytesReceived); - } - - - // ---------------------------------------------------------------------- - void - Socket:: - receiveComplete(unsigned char * buffer, size_t len) - const - { - while (len > 0) - { - const size_t bytesReceived = recvAndCheck(buffer, len); - len -= bytesReceived; - buffer += bytesReceived; - } - } - - - // ---------------------------------------------------------------------- - void - Socket:: - printBufferOnVerbose(const std::vector buffer, const std::string &label) - const - { - if (verbose_) - { - std::cerr << label << " " << buffer.size() << " bytes via tcpip::Socket: ["; - // cache end iterator for performance - const std::vector::const_iterator end = buffer.end(); - for (std::vector::const_iterator it = buffer.begin(); end != it; ++it) - std::cerr << " " << static_cast(*it) << " "; - std::cerr << "]" << std::endl; - } - } - - - // ---------------------------------------------------------------------- - std::vector - Socket:: - receive(int bufSize) - { - std::vector buffer; - - if( socket_ < 0 ) - connect(); - - if( !datawaiting( socket_) ) - return buffer; - - buffer.resize(bufSize); - const size_t bytesReceived = recvAndCheck(&buffer[0], bufSize); - - buffer.resize(bytesReceived); - - printBufferOnVerbose(buffer, "Rcvd"); - - return buffer; - } - - // ---------------------------------------------------------------------- - - - bool - Socket:: - receiveExact( Storage &msg ) - { - // buffer for received bytes - // According to the C++ standard elements of a std::vector are stored - // contiguously. Explicitly &buffer[n] == &buffer[0] + n for 0 <= n < buffer.size(). - std::vector buffer(lengthLen); - - // receive length of TraCI message - receiveComplete(&buffer[0], lengthLen); - Storage length_storage(&buffer[0], lengthLen); - const int totalLen = length_storage.readInt(); - assert(totalLen > lengthLen); - - // extent buffer - buffer.resize(totalLen); - - // receive remaining TraCI message - receiveComplete(&buffer[lengthLen], totalLen - lengthLen); - - // copy message content into passed Storage - msg.reset(); - msg.writePacket(&buffer[lengthLen], totalLen - lengthLen); - - printBufferOnVerbose(buffer, "Rcvd Storage with"); - - return true; - } - - - // ---------------------------------------------------------------------- - bool - Socket:: - has_client_connection() - const - { - return socket_ >= 0; - } - - // ---------------------------------------------------------------------- - bool - Socket:: - is_blocking() - { - return blocking_; - } - - -#ifdef WIN32 - // ---------------------------------------------------------------------- - std::string - Socket:: - GetWinsockErrorString(int err) - { - - switch( err) - { - case 0: return "No error"; - case WSAEINTR: return "Interrupted system call"; - case WSAEBADF: return "Bad file number"; - case WSAEACCES: return "Permission denied"; - case WSAEFAULT: return "Bad address"; - case WSAEINVAL: return "Invalid argument"; - case WSAEMFILE: return "Too many open sockets"; - case WSAEWOULDBLOCK: return "Operation would block"; - case WSAEINPROGRESS: return "Operation now in progress"; - case WSAEALREADY: return "Operation already in progress"; - case WSAENOTSOCK: return "Socket operation on non-socket"; - case WSAEDESTADDRREQ: return "Destination address required"; - case WSAEMSGSIZE: return "Message too long"; - case WSAEPROTOTYPE: return "Protocol wrong type for socket"; - case WSAENOPROTOOPT: return "Bad protocol option"; - case WSAEPROTONOSUPPORT: return "Protocol not supported"; - case WSAESOCKTNOSUPPORT: return "Socket type not supported"; - case WSAEOPNOTSUPP: return "Operation not supported on socket"; - case WSAEPFNOSUPPORT: return "Protocol family not supported"; - case WSAEAFNOSUPPORT: return "Address family not supported"; - case WSAEADDRINUSE: return "Address already in use"; - case WSAEADDRNOTAVAIL: return "Can't assign requested address"; - case WSAENETDOWN: return "Network is down"; - case WSAENETUNREACH: return "Network is unreachable"; - case WSAENETRESET: return "Net Socket reset"; - case WSAECONNABORTED: return "Software caused tcpip::Socket abort"; - case WSAECONNRESET: return "Socket reset by peer"; - case WSAENOBUFS: return "No buffer space available"; - case WSAEISCONN: return "Socket is already connected"; - case WSAENOTCONN: return "Socket is not connected"; - case WSAESHUTDOWN: return "Can't send after socket shutdown"; - case WSAETOOMANYREFS: return "Too many references, can't splice"; - case WSAETIMEDOUT: return "Socket timed out"; - case WSAECONNREFUSED: return "Socket refused"; - case WSAELOOP: return "Too many levels of symbolic links"; - case WSAENAMETOOLONG: return "File name too long"; - case WSAEHOSTDOWN: return "Host is down"; - case WSAEHOSTUNREACH: return "No route to host"; - case WSAENOTEMPTY: return "Directory not empty"; - case WSAEPROCLIM: return "Too many processes"; - case WSAEUSERS: return "Too many users"; - case WSAEDQUOT: return "Disc quota exceeded"; - case WSAESTALE: return "Stale NFS file handle"; - case WSAEREMOTE: return "Too many levels of remote in path"; - case WSASYSNOTREADY: return "Network system is unavailable"; - case WSAVERNOTSUPPORTED: return "Winsock version out of range"; - case WSANOTINITIALISED: return "WSAStartup not yet called"; - case WSAEDISCON: return "Graceful shutdown in progress"; - case WSAHOST_NOT_FOUND: return "Host not found"; - case WSANO_DATA: return "No host data of that type was found"; - } - - return "unknown"; - } - -#endif // WIN32 - -} // namespace tcpip - -#endif // BUILD_TCPIP - -/*----------------------------------------------------------------------- -* Source $Source: $ -* Version $Revision: 645 $ -* Date $Date: 2012-04-27 14:03:33 +0200 (Fri, 27 Apr 2012) $ -*----------------------------------------------------------------------- -* $Log: $ -*-----------------------------------------------------------------------*/ diff --git a/Util/OSM2ODR/src/foreign/tcpip/socket.h b/Util/OSM2ODR/src/foreign/tcpip/socket.h deleted file mode 100644 index 393d562c2..000000000 --- a/Util/OSM2ODR/src/foreign/tcpip/socket.h +++ /dev/null @@ -1,145 +0,0 @@ -/************************************************************************ - ** This file is part of the network simulator Shawn. ** - ** Copyright (C) 2004-2007 by the SwarmNet (www.swarmnet.de) project ** - ** Shawn is free software; you can redistribute it and/or modify it ** - ** under the terms of the BSD License. Refer to the shawn-licence.txt ** - ** file in the root of the Shawn source tree for further details. ** - ************************************************************************/ - -#ifndef __SHAWN_APPS_TCPIP_SOCKET_H -#define __SHAWN_APPS_TCPIP_SOCKET_H - -#ifdef SHAWN - #include - #include "_apps_enable_cmake.h" - #ifdef ENABLE_TCPIP - #define BUILD_TCPIP - #endif -#else - #define BUILD_TCPIP -#endif - - -#ifdef BUILD_TCPIP - -// Get Storage -#ifdef SHAWN - #include -#else - #include "storage.h" -#endif - -#ifdef SHAWN - namespace shawn - { class SimulationController; } - - // Dummy function is called when Shawn Simulation starts. Does nothing up to now. - extern "C" void init_tcpip( shawn::SimulationController& ); -#endif - -#include -#include -#include -#include -#include -#include -#include - - -struct sockaddr_in; - -namespace tcpip -{ - - class SocketException: public std::runtime_error - { - public: - SocketException(std::string what) : std::runtime_error(what.c_str()) {} - }; - - class Socket - { - friend class Response; - public: - /// Constructor that prepare to connect to host:port - Socket(std::string host, int port); - - /// Constructor that prepare for accepting a connection on given port - Socket(int port); - - /// Destructor - ~Socket(); - - /// @brief Returns an free port on the system - /// @note This is done by binding a socket with port=0, getting the assigned port, and closing the socket again - static int getFreeSocketPort(); - - /// Connects to host_:port_ - void connect(); - - /// Wait for a incoming connection to port_ - Socket* accept(const bool create = false); - - void send( const std::vector &buffer); - void sendExact( const Storage & ); - /// Receive up to \p bufSize available bytes from Socket::socket_ - std::vector receive( int bufSize = 2048 ); - /// Receive a complete TraCI message from Socket::socket_ - bool receiveExact( Storage &); - void close(); - int port(); - void set_blocking(bool); - bool is_blocking(); - bool has_client_connection() const; - - // If verbose, each send and received data is written to stderr - bool verbose() { return verbose_; } - void set_verbose(bool newVerbose) { verbose_ = newVerbose; } - - protected: - /// Length of the message length part of a TraCI message - static const int lengthLen; - - /// Receive \p len bytes from Socket::socket_ - void receiveComplete(unsigned char * const buffer, std::size_t len) const; - /// Receive up to \p len available bytes from Socket::socket_ - size_t recvAndCheck(unsigned char * const buffer, std::size_t len) const; - /// Print \p label and \p buffer to stderr if Socket::verbose_ is set - void printBufferOnVerbose(const std::vector buffer, const std::string &label) const; - - private: - void init(); - static void BailOnSocketError(std::string context); -#ifdef WIN32 - static std::string GetWinsockErrorString(int err); -#endif - bool atoaddr(std::string, struct sockaddr_in& addr); - bool datawaiting(int sock) const; - - std::string host_; - int port_; - int socket_; - int server_socket_; - bool blocking_; - - bool verbose_; -#ifdef WIN32 - static bool init_windows_sockets_; - static bool windows_sockets_initialized_; - static int instance_count_; -#endif - }; - -} // namespace tcpip - -#endif // BUILD_TCPIP - -#endif - -/*----------------------------------------------------------------------- -* Source $Source: $ -* Version $Revision: 612 $ -* Date $Date: 2011-06-14 15:16:52 +0200 (Tue, 14 Jun 2011) $ -*----------------------------------------------------------------------- -* $Log:$ -*-----------------------------------------------------------------------*/ diff --git a/Util/OSM2ODR/src/foreign/tcpip/storage.cpp b/Util/OSM2ODR/src/foreign/tcpip/storage.cpp deleted file mode 100644 index e7b7c8676..000000000 --- a/Util/OSM2ODR/src/foreign/tcpip/storage.cpp +++ /dev/null @@ -1,474 +0,0 @@ -/************************************************************************ - ** This file is part of the network simulator Shawn. ** - ** Copyright (C) 2004-2007 by the SwarmNet (www.swarmnet.de) project ** - ** Shawn is free software; you can redistribute it and/or modify it ** - ** under the terms of the BSD License. Refer to the shawn-licence.txt ** - ** file in the root of the Shawn source tree for further details. ** - ************************************************************************ - ** ** - ** \author Axel Wegener ** - ** \author Bjoern Hendriks ** - ** ** - ************************************************************************/ - -#include "storage.h" - -#ifdef BUILD_TCPIP - -#include -#include -#include -#include -#include -#include - - -//#define NULLITER static_cast::iterator>(0) - -namespace tcpip -{ - - // ---------------------------------------------------------------------- - Storage::Storage() - { - init(); - } - - - // ---------------------------------------------------------------------- - Storage::Storage(const unsigned char packet[], int length) - { - assert(length >= 0); // fixed MB, 2015-04-21 - - store.reserve(length); - // Get the content - for(int i = 0; i < length; ++i) store.push_back(packet[i]); - - init(); - } - - - // ---------------------------------------------------------------------- - void Storage::init() - { - // Initialize local variables - iter_ = store.begin(); - - short a = 0x0102; - unsigned char *p_a = reinterpret_cast(&a); - bigEndian_ = (p_a[0] == 0x01); // big endian? - } - - - // ---------------------------------------------------------------------- - Storage::~Storage() - {} - - - // ---------------------------------------------------------------------- - bool Storage::valid_pos() - { - return (iter_ != store.end()); // this implies !store.empty() - } - - - // ---------------------------------------------------------------------- - unsigned int Storage::position() const - { - // According to C++ standard std::distance will simply compute the iterators - // difference for random access iterators as std::vector provides. - return static_cast(std::distance(store.begin(), iter_)); - } - - - // ---------------------------------------------------------------------- - void Storage::reset() - { - store.clear(); - iter_ = store.begin(); - } - - - // ---------------------------------------------------------------------- - /** - * Reads a char form the array - * @return The read char (between 0 and 255) - */ - unsigned char Storage::readChar() - { - if ( !valid_pos() ) - { - throw std::invalid_argument("Storage::readChar(): invalid position"); - } - return readCharUnsafe(); - } - - - // ---------------------------------------------------------------------- - /** - * - */ - void Storage::writeChar(unsigned char value) - { - store.push_back(value); - iter_ = store.begin(); - } - - - // ---------------------------------------------------------------------- - /** - * Reads a byte form the array - * @return The read byte (between -128 and 127) - */ - int Storage::readByte() - { - int i = static_cast(readChar()); - if (i < 128) return i; - else return (i - 256); - } - - - // ---------------------------------------------------------------------- - /** - * - */ - void Storage::writeByte(int value) - { - if (value < -128 || value > 127) - { - throw std::invalid_argument("Storage::writeByte(): Invalid value, not in [-128, 127]"); - } - writeChar( static_cast( (value+256) % 256 ) ); - } - - - // ---------------------------------------------------------------------- - /** - * Reads an unsigned byte form the array - * @return The read byte (between 0 and 255) - */ - int Storage::readUnsignedByte() - { - return static_cast(readChar()); - } - - - // ---------------------------------------------------------------------- - /** - * - */ - void Storage::writeUnsignedByte(int value) - { - if (value < 0 || value > 255) - { - throw std::invalid_argument("Storage::writeUnsignedByte(): Invalid value, not in [0, 255]"); - } - writeChar( static_cast( value )); - } - - - // ----------------------------------------------------------------------- - /** - * Reads a string form the array - * @return The read string - */ - std::string Storage::readString() - { - int len = readInt(); - checkReadSafe(len); - StorageType::const_iterator end = iter_; - std::advance(end, len); - const std::string tmp(iter_, end); - iter_ = end; - return tmp; - } - - - // ---------------------------------------------------------------------- - /** - * Writes a string into the array; - * @param s The string to be written - */ - void Storage::writeString(const std::string &s) - { - writeInt(static_cast(s.length())); - - store.insert(store.end(), s.begin(), s.end()); - iter_ = store.begin(); - } - - - // ----------------------------------------------------------------------- - /** - * Reads a string list form the array - * @return The read string - */ - std::vector Storage::readStringList() - { - std::vector tmp; - const int len = readInt(); - tmp.reserve(len); - for (int i = 0; i < len; i++) - { - tmp.push_back(readString()); - } - return tmp; - } - - - // ----------------------------------------------------------------------- - /** - * Reads a double list from the array - * @return The read double list - */ - std::vector Storage::readDoubleList() - { - std::vector tmp; - const int len = readInt(); - tmp.reserve(len); - for (int i = 0; i < len; i++) - { - tmp.push_back(readDouble()); - } - return tmp; - } - - - // ---------------------------------------------------------------------- - /** - * Writes a string into the array; - * @param s The string to be written - */ - void Storage::writeStringList(const std::vector &s) - { - writeInt(static_cast(s.size())); - for (std::vector::const_iterator it = s.begin(); it!=s.end() ; it++) - { - writeString(*it); - } - } - - - // ---------------------------------------------------------------------- - /** - * Writes a double list into the array; - * @param s The double list to be written - */ - void Storage::writeDoubleList(const std::vector &s) - { - writeInt(static_cast(s.size())); - for (std::vector::const_iterator it = s.begin(); it!=s.end() ; it++) - { - writeDouble(*it); - } - } - - - // ---------------------------------------------------------------------- - /** - * Restores an integer, which was split up in two bytes according to the - * specification, it must have been split by its row byte representation - * with MSBF-order - * - * @return the unspoiled integer value (between -32768 and 32767) - */ - int Storage::readShort() - { - short value = 0; - unsigned char *p_value = reinterpret_cast(&value); - readByEndianess(p_value, 2); - return value; - } - - - // ---------------------------------------------------------------------- - void Storage::writeShort( int value ) - { - if (value < -32768 || value > 32767) - { - throw std::invalid_argument("Storage::writeShort(): Invalid value, not in [-32768, 32767]"); - } - - short svalue = static_cast(value); - unsigned char *p_svalue = reinterpret_cast(&svalue); - writeByEndianess(p_svalue, 2); - } - - - // ---------------------------------------------------------------------- - /** - * restores an integer, which was split up in four bytes acording to the - * specification, it must have been split by its row byte representation - * with MSBF-order - * - * @return the unspoiled integer value (between -2.147.483.648 and 2.147.483.647) - */ - int Storage::readInt() - { - int value = 0; - unsigned char *p_value = reinterpret_cast(&value); - readByEndianess(p_value, 4); - return value; - } - - - // ---------------------------------------------------------------------- - void Storage::writeInt( int value ) - { - unsigned char *p_value = reinterpret_cast(&value); - writeByEndianess(p_value, 4); - } - - - // ---------------------------------------------------------------------- - /** - * restores a float , which was split up in four bytes acording to the - * specification, it must have been split by its row byte representation - * with MSBF-order - * - * @return the unspoiled float value - */ - float Storage::readFloat() - { - float value = 0; - unsigned char *p_value = reinterpret_cast(&value); - readByEndianess(p_value, 4); - return value; - } - - - // ---------------------------------------------------------------------- - void Storage::writeFloat( float value ) - { - unsigned char *p_value = reinterpret_cast(&value); - writeByEndianess(p_value, 4); - } - - - // ---------------------------------------------------------------------- - void Storage::writeDouble( double value ) - { - unsigned char *p_value = reinterpret_cast(&value); - writeByEndianess(p_value, 8); - } - - - // ---------------------------------------------------------------------- - double Storage::readDouble( ) - { - double value = 0; - unsigned char *p_value = reinterpret_cast(&value); - readByEndianess(p_value, 8); - return value; - } - - - // ---------------------------------------------------------------------- - void Storage::writePacket(unsigned char* packet, int length) - { - store.insert(store.end(), &(packet[0]), &(packet[length])); - iter_ = store.begin(); // reserve() invalidates iterators - } - - - // ---------------------------------------------------------------------- - void Storage::writePacket(const std::vector &packet) - { - std::copy(packet.begin(), packet.end(), std::back_inserter(store)); - iter_ = store.begin(); - } - - - // ---------------------------------------------------------------------- - void Storage::writeStorage(tcpip::Storage& other) - { - // the compiler cannot deduce to use a const_iterator as source - store.insert(store.end(), other.iter_, other.store.end()); - iter_ = store.begin(); - } - - - // ---------------------------------------------------------------------- - void Storage::checkReadSafe(unsigned int num) const - { - if (std::distance(iter_, store.end()) < static_cast(num)) - { - std::ostringstream msg; - msg << "tcpip::Storage::readIsSafe: want to read " << num << " bytes from Storage, " - << "but only " << std::distance(iter_, store.end()) << " remaining"; - throw std::invalid_argument(msg.str()); - } - } - - - // ---------------------------------------------------------------------- - unsigned char Storage::readCharUnsafe() - { - char hb = *iter_; - ++iter_; - return hb; - } - - - // ---------------------------------------------------------------------- - void Storage::writeByEndianess(const unsigned char * begin, unsigned int size) - { - const unsigned char * end = &(begin[size]); - if (bigEndian_) - store.insert(store.end(), begin, end); - else - store.insert(store.end(), std::reverse_iterator(end), std::reverse_iterator(begin)); - iter_ = store.begin(); - } - - - // ---------------------------------------------------------------------- - void Storage::readByEndianess(unsigned char * array, int size) - { - checkReadSafe(size); - if (bigEndian_) - { - for (int i = 0; i < size; ++i) - array[i] = readCharUnsafe(); - } - else - { - for (int i = size - 1; i >= 0; --i) - array[i] = readCharUnsafe(); - } - } - - - // ---------------------------------------------------------------------- - std::string Storage::hexDump() const - { - static const int width = 2; - - std::ostringstream dump; - // adapt stream attributes - // 'showbase' inserts "0x", 'internal' makes leading '0' appear between "0x" and hex digits - dump.setf(std::ostream::hex | std::ostream::showbase | std::ostream::internal); - dump.fill('0'); - - for(StorageType::const_iterator it = store.begin(); it != store.end(); ++it) - { - // insert spaces between values - if (it != store.begin()) - dump << " "; - dump << std::setw(width) << static_cast(*it); - } - - return dump.str(); - } - -} - -#endif // BUILD_TCPIP - -/*----------------------------------------------------------------------- - * Source $Source: $ - * Version $Revision: 620 $ - * Date $Date: 2011-07-08 17:39:10 +0200 (Fri, 08 Jul 2011) $ - *----------------------------------------------------------------------- - * $Log: $ - *-----------------------------------------------------------------------*/ diff --git a/Util/OSM2ODR/src/foreign/tcpip/storage.h b/Util/OSM2ODR/src/foreign/tcpip/storage.h deleted file mode 100644 index b662c619a..000000000 --- a/Util/OSM2ODR/src/foreign/tcpip/storage.h +++ /dev/null @@ -1,136 +0,0 @@ -/************************************************************************ - ** This file is part of the network simulator Shawn. ** - ** Copyright (C) 2004-2007 by the SwarmNet (www.swarmnet.de) project ** - ** Shawn is free software; you can redistribute it and/or modify it ** - ** under the terms of the BSD License. Refer to the shawn-licence.txt ** - ** file in the root of the Shawn source tree for further details. ** - ************************************************************************ - ** ** - ** \author Axel Wegener ** - ** \author Bjoern Hendriks ** - ** ** - ************************************************************************/ -#ifndef __SHAWN_APPS_TCPIP_STORAGE_H -#define __SHAWN_APPS_TCPIP_STORAGE_H - -#ifdef SHAWN - #include - #include "_apps_enable_cmake.h" - #ifdef ENABLE_TCPIP - #define BUILD_TCPIP - #endif -#else - #define BUILD_TCPIP -#endif - - -#ifdef BUILD_TCPIP - -#include -#include -#include -#include - -namespace tcpip -{ - -class Storage -{ - -public: - typedef std::vector StorageType; - -private: - StorageType store; - StorageType::const_iterator iter_; - - // sortation of bytes forwards or backwards? - bool bigEndian_; - - /// Used in constructors to initialize local variables - void init(); - - /// Check if the next \p num bytes can be read safely - void checkReadSafe(unsigned int num) const; - /// Read a byte \em without validity check - unsigned char readCharUnsafe(); - /// Write \p size elements of array \p begin according to endianess - void writeByEndianess(const unsigned char * begin, unsigned int size); - /// Read \p size elements into \p array according to endianess - void readByEndianess(unsigned char * array, int size); - - -public: - - /// Standard Constructor - Storage(); - - /// Constructor, that fills the storage with an char array. If length is -1, the whole array is handed over - Storage(const unsigned char[], int length=-1); - - // Destructor - virtual ~Storage(); - - virtual bool valid_pos(); - virtual unsigned int position() const; - - void reset(); - /// Dump storage content as series of hex values - std::string hexDump() const; - - virtual unsigned char readChar(); - virtual void writeChar(unsigned char); - - virtual int readByte(); - virtual void writeByte(int); -// virtual void writeByte(unsigned char); - - virtual int readUnsignedByte(); - virtual void writeUnsignedByte(int); - - virtual std::string readString(); - virtual void writeString(const std::string& s); - - virtual std::vector readStringList(); - virtual void writeStringList(const std::vector &s); - - virtual std::vector readDoubleList(); - virtual void writeDoubleList(const std::vector &s); - - virtual int readShort(); - virtual void writeShort(int); - - virtual int readInt(); - virtual void writeInt(int); - - virtual float readFloat(); - virtual void writeFloat( float ); - - virtual double readDouble(); - virtual void writeDouble( double ); - - virtual void writePacket(unsigned char* packet, int length); - virtual void writePacket(const std::vector &packet); - - virtual void writeStorage(tcpip::Storage& store); - - // Some enabled functions of the underlying std::list - StorageType::size_type size() const { return store.size(); } - - StorageType::const_iterator begin() const { return store.begin(); } - StorageType::const_iterator end() const { return store.end(); } - -}; - -} // namespace tcpip - -#endif // BUILD_TCPIP - -#endif -/*----------------------------------------------------------------------- - * Source $Source: $ - * Version $Revision: 620 $ - * Date $Date: 2011-07-08 17:39:10 +0200 (Fri, 08 Jul 2011) $ - *----------------------------------------------------------------------- - * $Log: $ - *-----------------------------------------------------------------------*/ diff --git a/Util/OSM2ODR/src/foreign/zstr/LICENSE b/Util/OSM2ODR/src/foreign/zstr/LICENSE deleted file mode 100644 index 841c72145..000000000 --- a/Util/OSM2ODR/src/foreign/zstr/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2015 Matei David, Ontario Institute for Cancer Research - -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. diff --git a/Util/OSM2ODR/src/foreign/zstr/strict_fstream.hpp b/Util/OSM2ODR/src/foreign/zstr/strict_fstream.hpp deleted file mode 100644 index e1542bbb9..000000000 --- a/Util/OSM2ODR/src/foreign/zstr/strict_fstream.hpp +++ /dev/null @@ -1,203 +0,0 @@ -#ifndef __STRICT_FSTREAM_HPP -#define __STRICT_FSTREAM_HPP - -#define __STDC_WANT_LIB_EXT1__ 1 -#include -#include -#include -#include - -#ifndef _MSC_VER -#define NOEXCEPT noexcept -#else -#define NOEXCEPT -#endif - -/** - * This namespace defines wrappers for std::ifstream, std::ofstream, and - * std::fstream objects. The wrappers perform the following steps: - * - check the open modes make sense - * - check that the call to open() is successful - * - (for input streams) check that the opened file is peek-able - * - turn on the badbit in the exception mask - */ -namespace strict_fstream -{ - -/// Overload of error-reporting function, to enable use with VS. -/// Ref: http://stackoverflow.com/a/901316/717706 -static std::string strerror() -{ - std::string buff(80, '\0'); -#if defined _WIN32 || defined __STDC_LIB_EXT1__ - if (strerror_s(&buff[0], buff.size(), errno) != 0) - { - buff = "Unknown error"; - } -#else - if (strerror_r(errno, &buff[0], buff.size()) != 0) - { - buff = "Unknown error"; - } -#endif - buff.resize(buff.find('\0')); - return buff; -} - -/// Exception class thrown by failed operations. -class Exception - : public std::exception -{ -public: - Exception(const std::string& msg) : _msg(msg) {} - const char * what() const NOEXCEPT { return _msg.c_str(); } -private: - std::string _msg; -}; // class Exception - -namespace detail -{ - -struct static_method_holder -{ - static std::string mode_to_string(std::ios_base::openmode mode) - { - static const int n_modes = 6; - static const std::ios_base::openmode mode_val_v[n_modes] = - { - std::ios_base::in, - std::ios_base::out, - std::ios_base::app, - std::ios_base::ate, - std::ios_base::trunc, - std::ios_base::binary - }; - - static const char * mode_name_v[n_modes] = - { - "in", - "out", - "app", - "ate", - "trunc", - "binary" - }; - std::string res; - for (int i = 0; i < n_modes; ++i) - { - if (mode & mode_val_v[i]) - { - res += (! res.empty()? "|" : ""); - res += mode_name_v[i]; - } - } - if (res.empty()) res = "none"; - return res; - } - static void check_mode(const std::string& filename, std::ios_base::openmode mode) - { - if ((mode & std::ios_base::trunc) && ! (mode & std::ios_base::out)) - { - throw Exception(std::string("strict_fstream: open('") + filename + "'): mode error: trunc and not out"); - } - else if ((mode & std::ios_base::app) && ! (mode & std::ios_base::out)) - { - throw Exception(std::string("strict_fstream: open('") + filename + "'): mode error: app and not out"); - } - else if ((mode & std::ios_base::trunc) && (mode & std::ios_base::app)) - { - throw Exception(std::string("strict_fstream: open('") + filename + "'): mode error: trunc and app"); - } - } - static void check_open(std::ios * s_p, const std::string& filename, std::ios_base::openmode mode) - { - if (s_p->fail()) - { - throw Exception(std::string("strict_fstream: open('") - + filename + "'," + mode_to_string(mode) + "): open failed: " - + strerror()); - } - } - static void check_peek(std::istream * is_p, const std::string& filename, std::ios_base::openmode mode) - { - bool peek_failed = true; - try - { - is_p->peek(); - peek_failed = is_p->fail(); - } - catch (std::ios_base::failure e) {} - if (peek_failed) - { - throw Exception(std::string("strict_fstream: open('") - + filename + "'," + mode_to_string(mode) + "): peek failed: " - + strerror()); - } - is_p->clear(); - } -}; // struct static_method_holder - -} // namespace detail - -class ifstream - : public std::ifstream -{ -public: - ifstream() = default; - ifstream(const std::string& filename, std::ios_base::openmode mode = std::ios_base::in) - { - open(filename, mode); - } - void open(const std::string& filename, std::ios_base::openmode mode = std::ios_base::in) - { - mode |= std::ios_base::in; - exceptions(std::ios_base::badbit); - detail::static_method_holder::check_mode(filename, mode); - std::ifstream::open(filename, mode); - detail::static_method_holder::check_open(this, filename, mode); - detail::static_method_holder::check_peek(this, filename, mode); - } -}; // class ifstream - -class ofstream - : public std::ofstream -{ -public: - ofstream() = default; - ofstream(const std::string& filename, std::ios_base::openmode mode = std::ios_base::out) - { - open(filename, mode); - } - void open(const std::string& filename, std::ios_base::openmode mode = std::ios_base::out) - { - mode |= std::ios_base::out; - exceptions(std::ios_base::badbit); - detail::static_method_holder::check_mode(filename, mode); - std::ofstream::open(filename, mode); - detail::static_method_holder::check_open(this, filename, mode); - } -}; // class ofstream - -class fstream - : public std::fstream -{ -public: - fstream() = default; - fstream(const std::string& filename, std::ios_base::openmode mode = std::ios_base::in) - { - open(filename, mode); - } - void open(const std::string& filename, std::ios_base::openmode mode = std::ios_base::in) - { - if (! (mode & std::ios_base::out)) mode |= std::ios_base::in; - exceptions(std::ios_base::badbit); - detail::static_method_holder::check_mode(filename, mode); - std::fstream::open(filename, mode); - detail::static_method_holder::check_open(this, filename, mode); - detail::static_method_holder::check_peek(this, filename, mode); - } -}; // class fstream - -} // namespace strict_fstream - -#endif diff --git a/Util/OSM2ODR/src/foreign/zstr/zstr.hpp b/Util/OSM2ODR/src/foreign/zstr/zstr.hpp deleted file mode 100644 index f4dfed27f..000000000 --- a/Util/OSM2ODR/src/foreign/zstr/zstr.hpp +++ /dev/null @@ -1,408 +0,0 @@ -//--------------------------------------------------------- -// Copyright 2015 Ontario Institute for Cancer Research -// Written by Matei David (matei@cs.toronto.edu) -//--------------------------------------------------------- - -// Reference: -// http://stackoverflow.com/questions/14086417/how-to-write-custom-input-stream-in-c - -#ifndef __ZSTR_HPP -#define __ZSTR_HPP - -#include -#include -#include -#include -#include "strict_fstream.hpp" - -namespace zstr -{ - -/// Exception class thrown by failed zlib operations. -class Exception - : public std::exception -{ -public: - Exception(z_stream * zstrm_p, int ret) - : _msg("zlib: ") - { - switch (ret) - { - case Z_STREAM_ERROR: - _msg += "Z_STREAM_ERROR: "; - break; - case Z_DATA_ERROR: - _msg += "Z_DATA_ERROR: "; - break; - case Z_MEM_ERROR: - _msg += "Z_MEM_ERROR: "; - break; - case Z_VERSION_ERROR: - _msg += "Z_VERSION_ERROR: "; - break; - case Z_BUF_ERROR: - _msg += "Z_BUF_ERROR: "; - break; - default: - std::ostringstream oss; - oss << ret; - _msg += "[" + oss.str() + "]: "; - break; - } - _msg += zstrm_p->msg; - } - Exception(const std::string msg) : _msg(msg) {} - const char * what() const NOEXCEPT { return _msg.c_str(); } -private: - std::string _msg; -}; // class Exception - -namespace detail -{ - -class z_stream_wrapper - : public z_stream -{ -public: - z_stream_wrapper(bool _is_input = true, int _level = Z_DEFAULT_COMPRESSION) - : is_input(_is_input) - { - this->zalloc = Z_NULL; - this->zfree = Z_NULL; - this->opaque = Z_NULL; - int ret; - if (is_input) - { - this->avail_in = 0; - this->next_in = Z_NULL; - ret = inflateInit2(this, 15+32); - } - else - { - ret = deflateInit2(this, _level, Z_DEFLATED, 15+16, 8, Z_DEFAULT_STRATEGY); - } - if (ret != Z_OK) throw Exception(this, ret); - } - ~z_stream_wrapper() - { - if (is_input) - { - inflateEnd(this); - } - else - { - deflateEnd(this); - } - } -private: - bool is_input; -}; // class z_stream_wrapper - -} // namespace detail - -class istreambuf - : public std::streambuf -{ -public: - istreambuf(std::streambuf * _sbuf_p, - std::size_t _buff_size = default_buff_size, bool _auto_detect = true) - : sbuf_p(_sbuf_p), - zstrm_p(nullptr), - buff_size(_buff_size), - auto_detect(_auto_detect), - auto_detect_run(false), - is_text(false) - { - assert(sbuf_p); - in_buff = new char [buff_size]; - in_buff_start = in_buff; - in_buff_end = in_buff; - out_buff = new char [buff_size]; - setg(out_buff, out_buff, out_buff); - } - - istreambuf(const istreambuf &) = delete; - istreambuf & operator = (const istreambuf &) = delete; - - virtual ~istreambuf() - { - delete [] in_buff; - delete [] out_buff; - if (zstrm_p) delete zstrm_p; - } - - virtual std::streambuf::int_type underflow() - { - if (this->gptr() == this->egptr()) - { - // pointers for free region in output buffer - char * out_buff_free_start = out_buff; - do - { - // read more input if none available - if (in_buff_start == in_buff_end) - { - // empty input buffer: refill from the start - in_buff_start = in_buff; - std::streamsize sz = sbuf_p->sgetn(in_buff, buff_size); - in_buff_end = in_buff + sz; - if (in_buff_end == in_buff_start) break; // end of input - } - // auto detect if the stream contains text or deflate data - if (auto_detect && ! auto_detect_run) - { - auto_detect_run = true; - unsigned char b0 = *reinterpret_cast< unsigned char * >(in_buff_start); - unsigned char b1 = *reinterpret_cast< unsigned char * >(in_buff_start + 1); - // Ref: - // http://en.wikipedia.org/wiki/Gzip - // http://stackoverflow.com/questions/9050260/what-does-a-zlib-header-look-like - is_text = ! (in_buff_start + 2 <= in_buff_end - && ((b0 == 0x1F && b1 == 0x8B) // gzip header - || (b0 == 0x78 && (b1 == 0x01 // zlib header - || b1 == 0x9C - || b1 == 0xDA)))); - } - if (is_text) - { - // simply swap in_buff and out_buff, and adjust pointers - assert(in_buff_start == in_buff); - std::swap(in_buff, out_buff); - out_buff_free_start = in_buff_end; - in_buff_start = in_buff; - in_buff_end = in_buff; - } - else - { - // run inflate() on input - if (! zstrm_p) zstrm_p = new detail::z_stream_wrapper(true); - zstrm_p->next_in = reinterpret_cast< decltype(zstrm_p->next_in) >(in_buff_start); - zstrm_p->avail_in = (uInt)(in_buff_end - in_buff_start); - zstrm_p->next_out = reinterpret_cast< decltype(zstrm_p->next_out) >(out_buff_free_start); - zstrm_p->avail_out = (uInt)((out_buff + buff_size) - out_buff_free_start); - int ret = inflate(zstrm_p, Z_NO_FLUSH); - // process return code - if (ret != Z_OK && ret != Z_STREAM_END) throw Exception(zstrm_p, ret); - // update in&out pointers following inflate() - in_buff_start = reinterpret_cast< decltype(in_buff_start) >(zstrm_p->next_in); - in_buff_end = in_buff_start + zstrm_p->avail_in; - out_buff_free_start = reinterpret_cast< decltype(out_buff_free_start) >(zstrm_p->next_out); - assert(out_buff_free_start + zstrm_p->avail_out == out_buff + buff_size); - // if stream ended, deallocate inflator - if (ret == Z_STREAM_END) - { - delete zstrm_p; - zstrm_p = nullptr; - } - } - } while (out_buff_free_start == out_buff); - // 2 exit conditions: - // - end of input: there might or might not be output available - // - out_buff_free_start != out_buff: output available - this->setg(out_buff, out_buff, out_buff_free_start); - } - return this->gptr() == this->egptr() - ? traits_type::eof() - : traits_type::to_int_type(*this->gptr()); - } -private: - std::streambuf * sbuf_p; - char * in_buff; - char * in_buff_start; - char * in_buff_end; - char * out_buff; - detail::z_stream_wrapper * zstrm_p; - std::size_t buff_size; - bool auto_detect; - bool auto_detect_run; - bool is_text; - - static const std::size_t default_buff_size = (std::size_t)1 << 20; -}; // class istreambuf - -class ostreambuf - : public std::streambuf -{ -public: - ostreambuf(std::streambuf * _sbuf_p, - std::size_t _buff_size = default_buff_size, int _level = Z_DEFAULT_COMPRESSION) - : sbuf_p(_sbuf_p), - zstrm_p(new detail::z_stream_wrapper(false, _level)), - buff_size(_buff_size) - { - assert(sbuf_p); - in_buff = new char [buff_size]; - out_buff = new char [buff_size]; - setp(in_buff, in_buff + buff_size); - } - - ostreambuf(const ostreambuf &) = delete; - ostreambuf & operator = (const ostreambuf &) = delete; - - int deflate_loop(int flush) - { - int ret = Z_OK; - while (ret != Z_STREAM_END && ret != Z_BUF_ERROR) - { - zstrm_p->next_out = reinterpret_cast< decltype(zstrm_p->next_out) >(out_buff); - zstrm_p->avail_out = (uInt)buff_size; - ret = deflate(zstrm_p, flush); - if (ret != Z_OK && ret != Z_STREAM_END && ret != Z_BUF_ERROR) throw Exception(zstrm_p, ret); - std::streamsize sz = sbuf_p->sputn(out_buff, reinterpret_cast< decltype(out_buff) >(zstrm_p->next_out) - out_buff); - if (sz != reinterpret_cast< decltype(out_buff) >(zstrm_p->next_out) - out_buff) - { - // there was an error in the sink stream - return -1; - } - if (sz == 0) - { - break; - } - } - return 0; - } - - virtual ~ostreambuf() - { - // flush the zlib stream - // - // NOTE: Errors here (sync() return value not 0) are ignored, because we - // cannot throw in a destructor. This mirrors the behaviour of - // std::basic_filebuf::~basic_filebuf(). To see an exception on error, - // close the ofstream with an explicit call to close(), and do not rely - // on the implicit call in the destructor. - // - sync(); - delete [] in_buff; - delete [] out_buff; - delete zstrm_p; - } - virtual std::streambuf::int_type overflow(std::streambuf::int_type c = traits_type::eof()) - { - zstrm_p->next_in = reinterpret_cast< decltype(zstrm_p->next_in) >(pbase()); - zstrm_p->avail_in = (uInt)(pptr() - pbase()); - while (zstrm_p->avail_in > 0) - { - int r = deflate_loop(Z_NO_FLUSH); - if (r != 0) - { - setp(nullptr, nullptr); - return traits_type::eof(); - } - } - setp(in_buff, in_buff + buff_size); - return traits_type::eq_int_type(c, traits_type::eof()) ? traits_type::eof() : sputc((char)c); - } - virtual int sync() - { - // first, call overflow to clear in_buff - overflow(); - if (! pptr()) return -1; - // then, call deflate asking to finish the zlib stream - zstrm_p->next_in = nullptr; - zstrm_p->avail_in = 0; - if (deflate_loop(Z_FINISH) != 0) return -1; - deflateReset(zstrm_p); - return 0; - } -private: - std::streambuf * sbuf_p; - char * in_buff; - char * out_buff; - detail::z_stream_wrapper * zstrm_p; - std::size_t buff_size; - - static const std::size_t default_buff_size = (std::size_t)1 << 20; -}; // class ostreambuf - -class istream - : public std::istream -{ -public: - istream(std::istream & is) - : std::istream(new istreambuf(is.rdbuf())) - { - exceptions(std::ios_base::badbit); - } - explicit istream(std::streambuf * sbuf_p) - : std::istream(new istreambuf(sbuf_p)) - { - exceptions(std::ios_base::badbit); - } - virtual ~istream() - { - delete rdbuf(); - } -}; // class istream - -class ostream - : public std::ostream -{ -public: - ostream(std::ostream & os) - : std::ostream(new ostreambuf(os.rdbuf())) - { - exceptions(std::ios_base::badbit); - } - explicit ostream(std::streambuf * sbuf_p) - : std::ostream(new ostreambuf(sbuf_p)) - { - exceptions(std::ios_base::badbit); - } - virtual ~ostream() - { - delete rdbuf(); - } -}; // class ostream - -namespace detail -{ - -template < typename FStream_Type > -struct strict_fstream_holder -{ - strict_fstream_holder(const std::string& filename, std::ios_base::openmode mode = std::ios_base::in) - : _fs(filename, mode) - {} - FStream_Type _fs; -}; // class strict_fstream_holder - -} // namespace detail - -class ifstream - : private detail::strict_fstream_holder< strict_fstream::ifstream >, - public std::istream -{ -public: - explicit ifstream(const std::string& filename, std::ios_base::openmode mode = std::ios_base::in) - : detail::strict_fstream_holder< strict_fstream::ifstream >(filename, mode), - std::istream(new istreambuf(_fs.rdbuf())) - { - exceptions(std::ios_base::badbit); - } - virtual ~ifstream() - { - if (rdbuf()) delete rdbuf(); - } -}; // class ifstream - -class ofstream - : private detail::strict_fstream_holder< strict_fstream::ofstream >, - public std::ostream -{ -public: - explicit ofstream(const std::string& filename, std::ios_base::openmode mode = std::ios_base::out) - : detail::strict_fstream_holder< strict_fstream::ofstream >(filename, mode | std::ios_base::binary), - std::ostream(new ostreambuf(_fs.rdbuf())) - { - exceptions(std::ios_base::badbit); - } - virtual ~ofstream() - { - if (rdbuf()) delete rdbuf(); - } -}; // class ofstream - -} // namespace zstr - -#endif diff --git a/Util/OSM2ODR/src/libsumo/Helper.h b/Util/OSM2ODR/src/libsumo/Helper.h deleted file mode 100644 index a47efb834..000000000 --- a/Util/OSM2ODR/src/libsumo/Helper.h +++ /dev/null @@ -1,281 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2012-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file Helper.h -/// @author Robert Hilbrich -/// @author Leonhard Luecken -/// @date 15.09.2017 -/// -// C++ TraCI client API implementation -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include -#include - - -// =========================================================================== -// class declarations -// =========================================================================== -class Position; -class PositionVector; -class RGBColor; -class MSEdge; -class SUMOTrafficObject; -class MSPerson; -class MSVehicle; -class MSBaseVehicle; -class MSVehicleType; - - -// =========================================================================== -// type definitions -// =========================================================================== -typedef std::map > LaneCoverageInfo; // also declared in MSLane.h! - -// =========================================================================== -// class definitions -// =========================================================================== - -class LaneStoringVisitor { -public: - /// @brief Constructor - LaneStoringVisitor(std::set& objects, const PositionVector& shape, - const double range, const int domain) - : myObjects(objects), myShape(shape), myRange(range), myDomain(domain) {} - - /// @brief Destructor - ~LaneStoringVisitor() {} - - /// @brief Adds the given object to the container - void add(const MSLane* const l) const; - - /// @brief The container - std::set& myObjects; - const PositionVector& myShape; - const double myRange; - const int myDomain; - -private: - /// @brief invalidated copy constructor - LaneStoringVisitor(const LaneStoringVisitor& src); - - /// @brief invalidated assignment operator - LaneStoringVisitor& operator=(const LaneStoringVisitor& src); -}; - -#define LANE_RTREE_QUAL RTree -template<> -inline float LANE_RTREE_QUAL::RectSphericalVolume(Rect* a_rect) { - ASSERT(a_rect); - const float extent0 = a_rect->m_max[0] - a_rect->m_min[0]; - const float extent1 = a_rect->m_max[1] - a_rect->m_min[1]; - return .78539816f * (extent0 * extent0 + extent1 * extent1); -} - -template<> -inline LANE_RTREE_QUAL::Rect LANE_RTREE_QUAL::CombineRect(Rect* a_rectA, Rect* a_rectB) { - ASSERT(a_rectA && a_rectB); - Rect newRect; - newRect.m_min[0] = rtree_min(a_rectA->m_min[0], a_rectB->m_min[0]); - newRect.m_max[0] = rtree_max(a_rectA->m_max[0], a_rectB->m_max[0]); - newRect.m_min[1] = rtree_min(a_rectA->m_min[1], a_rectB->m_min[1]); - newRect.m_max[1] = rtree_max(a_rectA->m_max[1], a_rectB->m_max[1]); - return newRect; -} - -namespace libsumo { - -/** -* @class Helper -* @brief C++ TraCI client API implementation -*/ -class Helper { -public: - static void subscribe(const int commandId, const std::string& id, const std::vector& variables, - const double beginTime, const double endTime, const int contextDomain = 0, const double range = 0.); - - static void addSubscriptionParam(double param); - - static void handleSubscriptions(const SUMOTime t); - - static bool needNewSubscription(libsumo::Subscription& s, std::vector& subscriptions, libsumo::Subscription*& modifiedSubscription); - - static void clearSubscriptions(); - - static Subscription* addSubscriptionFilter(SubscriptionFilterType filter); - - /// @brief helper functions - static TraCIPositionVector makeTraCIPositionVector(const PositionVector& positionVector); - static TraCIPosition makeTraCIPosition(const Position& position, const bool includeZ = false); - static Position makePosition(const TraCIPosition& position); - - static PositionVector makePositionVector(const TraCIPositionVector& vector); - static TraCIColor makeTraCIColor(const RGBColor& color); - static RGBColor makeRGBColor(const TraCIColor& color); - - static MSEdge* getEdge(const std::string& edgeID); - static const MSLane* getLaneChecking(const std::string& edgeID, int laneIndex, double pos); - static std::pair convertCartesianToRoadMap(const Position& pos, const SUMOVehicleClass vClass); - static double getDrivingDistance(std::pair& roadPos1, std::pair& roadPos2); - - static MSBaseVehicle* getVehicle(const std::string& id); - static MSPerson* getPerson(const std::string& id); - static SUMOTrafficObject* getTrafficObject(int domain, const std::string& id); - static const MSVehicleType& getVehicleType(const std::string& vehicleID); - - static void findObjectShape(int domain, const std::string& id, PositionVector& shape); - - static void collectObjectsInRange(int domain, const PositionVector& shape, double range, std::set& into); - static void collectObjectIDsInRange(int domain, const PositionVector& shape, double range, std::set& into); - - /** - * @brief Filter the given ID-Set (which was obtained from an R-Tree search) - * according to the filters set by the subscription or firstly build the object ID list if - * the filters rather demand searching along the road network than considering a geometric range. - * @param[in] s Subscription which holds the filter specification to be applied - * @param[in/out] objIDs Set of object IDs that is to be filtered. Result is stored in place. - * @note Currently this assumes that the objects are vehicles. - */ - static void applySubscriptionFilters(const Subscription& s, std::set& objIDs); - - static void applySubscriptionFilterFieldOfVision(const Subscription& s, std::set& objIDs); - - static void applySubscriptionFilterLateralDistanceSinglePass(const Subscription& s, - std::set& objIDs, - std::set& vehs, - const std::vector& lanes, - double posOnLane, double posLat, bool isDownstream); - - static void setRemoteControlled(MSVehicle* v, Position xyPos, MSLane* l, double pos, double posLat, double angle, - int edgeOffset, ConstMSEdgeVector route, SUMOTime t); - - static void setRemoteControlled(MSPerson* p, Position xyPos, MSLane* l, double pos, double posLat, double angle, - int edgeOffset, ConstMSEdgeVector route, SUMOTime t); - - static void postProcessRemoteControl(); - - static void cleanup(); - - static void registerVehicleStateListener(); - - static const std::vector& getVehicleStateChanges(const MSNet::VehicleState state); - - static void clearVehicleStates(); - - /// @name functions for moveToXY - /// @{ - static bool moveToXYMap(const Position& pos, double maxRouteDistance, bool mayLeaveNetwork, const std::string& origID, - const double angle, double speed, const ConstMSEdgeVector& currentRoute, const int routePosition, - MSLane* currentLane, double currentLanePos, bool onRoad, SUMOVehicleClass vClass, bool setLateralPos, - double& bestDistance, MSLane** lane, double& lanePos, int& routeOffset, ConstMSEdgeVector& edges); - - static bool moveToXYMap_matchingRoutePosition(const Position& pos, const std::string& origID, - const ConstMSEdgeVector& currentRoute, int routeIndex, - SUMOVehicleClass vClass, bool setLateralPos, - double& bestDistance, MSLane** lane, double& lanePos, int& routeOffset); - - static bool findCloserLane(const MSEdge* edge, const Position& pos, SUMOVehicleClass vClass, double& bestDistance, MSLane** lane); - - class LaneUtility { - public: - LaneUtility(double dist_, double perpendicularDist_, double lanePos_, double angleDiff_, bool ID_, - bool onRoute_, bool sameEdge_, const MSEdge* prevEdge_, const MSEdge* nextEdge_) : - dist(dist_), perpendicularDist(perpendicularDist_), lanePos(lanePos_), angleDiff(angleDiff_), ID(ID_), - onRoute(onRoute_), sameEdge(sameEdge_), prevEdge(prevEdge_), nextEdge(nextEdge_) {} - ~LaneUtility() {} - - double dist; - double perpendicularDist; - double lanePos; - double angleDiff; - bool ID; - bool onRoute; - bool sameEdge; - const MSEdge* prevEdge; - const MSEdge* nextEdge; - }; - /// @} - - class SubscriptionWrapper final : public VariableWrapper { - public: - SubscriptionWrapper(VariableWrapper::SubscriptionHandler handler, SubscriptionResults& into, ContextSubscriptionResults& context); - void setContext(const std::string& refID); - void setParams(const std::vector* params); - const std::vector* getParams() const { - return myParams; - } - void clear(); - bool wrapDouble(const std::string& objID, const int variable, const double value); - bool wrapInt(const std::string& objID, const int variable, const int value); - bool wrapString(const std::string& objID, const int variable, const std::string& value); - bool wrapStringList(const std::string& objID, const int variable, const std::vector& value); - bool wrapPosition(const std::string& objID, const int variable, const TraCIPosition& value); - bool wrapColor(const std::string& objID, const int variable, const TraCIColor& value); - bool wrapRoadPosition(const std::string& objID, const int variable, const TraCIRoadPosition& value); - private: - SubscriptionResults& myResults; - ContextSubscriptionResults& myContextResults; - SubscriptionResults* myActiveResults; - const std::vector* myParams = nullptr; - private: - /// @brief Invalidated assignment operator - SubscriptionWrapper& operator=(const SubscriptionWrapper& s) = delete; - }; - -private: - static void handleSingleSubscription(const Subscription& s); - - /// @brief Adds lane coverage information from newLaneCoverage into aggregatedLaneCoverage - /// @param[in/out] aggregatedLaneCoverage - aggregated lane coverage info, to which the new will be added - /// @param[in] newLaneCoverage - new lane coverage to be added - /// @todo Disjunct ranges are not handled (LaneCoverageInfo definition would need to allow several intervals per lane) but - /// the intermediate range is simply assimilated. - static void fuseLaneCoverage(std::shared_ptr aggregatedLaneCoverage, const std::shared_ptr newLaneCoverage); - - static void debugPrint(const SUMOTrafficObject* veh); - -private: - class VehicleStateListener : public MSNet::VehicleStateListener { - public: - void vehicleStateChanged(const SUMOVehicle* const vehicle, MSNet::VehicleState to, const std::string& info = ""); - /// @brief Changes in the states of simulated vehicles - std::map > myVehicleStateChanges; - }; - - /// @brief The list of known, still valid subscriptions - static std::vector mySubscriptions; - - /// @brief The last context subscription - static Subscription* myLastContextSubscription; - - /// @brief Map of commandIds -> their executors; applicable if the executor applies to the method footprint - static std::map > myWrapper; - - /// @brief Changes in the states of simulated vehicles - static VehicleStateListener myVehicleStateListener; - - /// @brief A storage of lanes - static LANE_RTREE_QUAL* myLaneTree; - - static std::map myRemoteControlledVehicles; - static std::map myRemoteControlledPersons; - - /// @brief invalidated standard constructor - Helper() = delete; -}; - -} diff --git a/Util/OSM2ODR/src/libsumo/Subscription.h b/Util/OSM2ODR/src/libsumo/Subscription.h deleted file mode 100644 index bc97b2f9d..000000000 --- a/Util/OSM2ODR/src/libsumo/Subscription.h +++ /dev/null @@ -1,165 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file Subscription.h -/// @author Michael Behrisch -/// @date 2007/10/24 -/// -// Subscription representation for libsumo and TraCI -/****************************************************************************/ -#pragma once -#include -#include -#include - - -// =========================================================================== -// class definitions -// =========================================================================== -namespace libsumo { - -/** @brief Filter types for context subscriptions - */ -enum SubscriptionFilterType { - // No filters - SUBS_FILTER_NONE = 0, - // Filter by list of lanes relative to ego vehicle - SUBS_FILTER_LANES = 1, - // Exclude vehicles on opposite (and other) lanes from context subscription result - SUBS_FILTER_NOOPPOSITE = 1 << 1, - // Specify maximal downstream distance for vehicles in context subscription result - SUBS_FILTER_DOWNSTREAM_DIST = 1 << 2, - // Specify maximal upstream distance for vehicles in context subscription result - SUBS_FILTER_UPSTREAM_DIST = 1 << 3, - // Only return leader and follower on specified lanes in context subscription result - SUBS_FILTER_LEAD_FOLLOW = 1 << 4, - // Only return foes on upcoming junction in context subscription result - SUBS_FILTER_TURN = 1 << 6, - // Only return vehicles of the given vClass in context subscription result - SUBS_FILTER_VCLASS = 1 << 7, - // Only return vehicles of the given vType in context subscription result - SUBS_FILTER_VTYPE = 1 << 8, - // Only return vehicles within field of vision in context subscription result - // NOTE: relies on rTree, therefore incompatible with SUBS_FILTER_NO_RTREE - SUBS_FILTER_FIELD_OF_VISION = 1 << 9, - // Only return vehicles within the given lateral distance in context subscription result - SUBS_FILTER_LATERAL_DIST = 1 << 10, - // Filter category for measuring distances along the road network instead of using the usual rtree query - SUBS_FILTER_NO_RTREE = SUBS_FILTER_LANES | SUBS_FILTER_DOWNSTREAM_DIST | SUBS_FILTER_UPSTREAM_DIST | SUBS_FILTER_LEAD_FOLLOW | SUBS_FILTER_TURN | SUBS_FILTER_LATERAL_DIST, - // Filter category for maneuver filters - SUBS_FILTER_MANEUVER = SUBS_FILTER_LEAD_FOLLOW | SUBS_FILTER_TURN, -}; - -/** @class Subscription - * @brief Representation of a subscription - */ -class Subscription { -public: - /** @brief Constructor - * @param[in] commandIdArg The command id of the subscription - * @param[in] idArg The id of the object that is subscribed - * @param[in] variablesArg The subscribed variables - * @param[in] paramsArg The parameters for the subscribed variables - * @param[in] beginTimeArg The begin time of the subscription - * @param[in] endTimeArg The end time of the subscription - * @param[in] contextDomainArg The domain ID of the context - * @param[in] rangeArg The range of the context - */ - Subscription(int commandIdArg, const std::string& idArg, - const std::vector& variablesArg, - const std::vector>& paramsArg, - SUMOTime beginTimeArg, SUMOTime endTimeArg, - int contextDomainArg, double rangeArg) - : commandId(commandIdArg), - id(idArg), - variables(variablesArg), - parameters(paramsArg), - beginTime(beginTimeArg), - endTime(endTimeArg), - contextDomain(contextDomainArg), - range(rangeArg), - activeFilters(SUBS_FILTER_NONE), - filterLanes(), - filterDownstreamDist(-1), - filterUpstreamDist(-1), - filterVTypes(), - filterVClasses(0), - filterFieldOfVisionOpeningAngle(-1), - filterLateralDist(-1) {} - - bool isVehicleToVehicleContextSubscription() const { - return commandId == CMD_SUBSCRIBE_VEHICLE_CONTEXT && contextDomain == CMD_GET_VEHICLE_VARIABLE; - } - - bool isVehicleToPersonContextSubscription() const { - return commandId == CMD_SUBSCRIBE_VEHICLE_CONTEXT && contextDomain == CMD_GET_PERSON_VARIABLE; - } - - /// @brief commandIdArg The command id of the subscription - int commandId; - /// @brief The id of the object that is subscribed - std::string id; - /// @brief The subscribed variables - std::vector variables; - /// @brief The parameters for the subscribed variables - std::vector > parameters; - /// @brief The begin time of the subscription - SUMOTime beginTime; - /// @brief The end time of the subscription - SUMOTime endTime; - /// @brief The domain ID of the context - int contextDomain; - /// @brief The range of the context - double range; - - /// @brief Active filters for the subscription (bitset, @see SubscriptionFilterType) - int activeFilters; - /// @brief lanes specified by the lanes filter - std::vector filterLanes; - /// @brief Downstream distance specified by the downstream distance filter - double filterDownstreamDist; - /// @brief Upstream distance specified by the upstream distance filter - double filterUpstreamDist; - /// @brief vTypes specified by the vTypes filter - std::set filterVTypes; - /// @brief vClasses specified by the vClasses filter, @see SVCPermissions - int filterVClasses; - /// @brief Opening angle (in deg) specified by the field of vision filter - double filterFieldOfVisionOpeningAngle; - /// @brief Lateral distance specified by the lateral distance filter - double filterLateralDist; -}; - -class VariableWrapper { -public: - /// @brief Definition of a method to be called for serving an associated commandID - typedef bool(*SubscriptionHandler)(const std::string& objID, const int variable, VariableWrapper* wrapper); - VariableWrapper(SubscriptionHandler handler = nullptr) : handle(handler) {} - SubscriptionHandler handle; - virtual void setContext(const std::string& /* refID */) {} - virtual void setParams(const std::vector* /* params */) {} - virtual const std::vector* getParams() const { - return nullptr; - } - virtual void clear() {} - virtual bool wrapDouble(const std::string& objID, const int variable, const double value) = 0; - virtual bool wrapInt(const std::string& objID, const int variable, const int value) = 0; - virtual bool wrapString(const std::string& objID, const int variable, const std::string& value) = 0; - virtual bool wrapStringList(const std::string& objID, const int variable, const std::vector& value) = 0; - virtual bool wrapPosition(const std::string& objID, const int variable, const TraCIPosition& value) = 0; - virtual bool wrapColor(const std::string& objID, const int variable, const TraCIColor& value) = 0; - virtual bool wrapRoadPosition(const std::string& objID, const int variable, const TraCIRoadPosition& value) = 0; -}; -} - - diff --git a/Util/OSM2ODR/src/libsumo/TraCIConstants.h b/Util/OSM2ODR/src/libsumo/TraCIConstants.h deleted file mode 100644 index f54b76350..000000000 --- a/Util/OSM2ODR/src/libsumo/TraCIConstants.h +++ /dev/null @@ -1,1239 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2007-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file TraCIConstants.h -/// @author Axel Wegener -/// @author Friedemann Wesner -/// @author Bjoern Hendriks -/// @author Daniel Krajzewicz -/// @author Thimor Bohn -/// @author Tino Morenz -/// @author Michael Behrisch -/// @author Christoph Sommer -/// @author Mario Krumnow -/// @author Jakob Erdmann -/// @author Laura Bieker -/// @date 2007/10/24 -/// -// holds codes used for TraCI -/****************************************************************************/ -#pragma once - -#if __cplusplus >= 201103L -#define TRACI_CONST constexpr -#else -#define TRACI_CONST const -#endif - -namespace libsumo { - -// **************************************** -// VERSION -// **************************************** -TRACI_CONST int TRACI_VERSION = 20; - -// **************************************** -// COMMANDS -// **************************************** -// command: get version -TRACI_CONST int CMD_GETVERSION = 0x00; - -// command: load -TRACI_CONST int CMD_LOAD = 0x01; - -// command: simulation step -TRACI_CONST int CMD_SIMSTEP = 0x02; - -// command: set connection priority (execution order) -TRACI_CONST int CMD_SETORDER = 0x03; - -// command: stop node -TRACI_CONST int CMD_STOP = 0x12; - -// command: reroute to parking area -TRACI_CONST int CMD_REROUTE_TO_PARKING = 0xc2; - -// command: Resume from parking -TRACI_CONST int CMD_RESUME = 0x19; - -// command: set lane -TRACI_CONST int CMD_CHANGELANE = 0x13; - -// command: slow down -TRACI_CONST int CMD_SLOWDOWN = 0x14; - -// command: set sublane (vehicle) -TRACI_CONST int CMD_CHANGESUBLANE = 0x15; - -// command: open gap -TRACI_CONST int CMD_OPENGAP = 0x16; - -// command: change target -TRACI_CONST int CMD_CHANGETARGET = 0x31; - -// command: close sumo -TRACI_CONST int CMD_CLOSE = 0x7F; - -// command: add subscription filter -TRACI_CONST int CMD_ADD_SUBSCRIPTION_FILTER = 0x7e; - - -// command: subscribe induction loop (e1) context -TRACI_CONST int CMD_SUBSCRIBE_INDUCTIONLOOP_CONTEXT = 0x80; -// response: subscribe induction loop (e1) context -TRACI_CONST int RESPONSE_SUBSCRIBE_INDUCTIONLOOP_CONTEXT = 0x90; -// command: get induction loop (e1) variable -TRACI_CONST int CMD_GET_INDUCTIONLOOP_VARIABLE = 0xa0; -// response: get induction loop (e1) variable -TRACI_CONST int RESPONSE_GET_INDUCTIONLOOP_VARIABLE = 0xb0; -// command: set induction loop (e1) variable, not used yet -//TRACI_CONST int CMD_GET_INDUCTIONLOOP_VARIABLE = 0xc0; -// command: subscribe induction loop (e1) variable -TRACI_CONST int CMD_SUBSCRIBE_INDUCTIONLOOP_VARIABLE = 0xd0; -// response: subscribe induction loop (e1) variable -TRACI_CONST int RESPONSE_SUBSCRIBE_INDUCTIONLOOP_VARIABLE = 0xe0; - -// command: subscribe multi-entry/multi-exit detector (e3) context -TRACI_CONST int CMD_SUBSCRIBE_MULTIENTRYEXIT_CONTEXT = 0x81; -// response: subscribe multi-entry/multi-exit detector (e3) context -TRACI_CONST int RESPONSE_SUBSCRIBE_MULTIENTRYEXIT_CONTEXT = 0x91; -// command: get multi-entry/multi-exit detector (e3) variable -TRACI_CONST int CMD_GET_MULTIENTRYEXIT_VARIABLE = 0xa1; -// response: get multi-entry/multi-exit detector (e3) variable -TRACI_CONST int RESPONSE_GET_MULTIENTRYEXIT_VARIABLE = 0xb1; -// command: set multi-entry/multi-exit detector (e3) variable, not used yet -//TRACI_CONST int CMD_GET_MULTIENTRYEXIT_VARIABLE = 0xc1; -// command: subscribe multi-entry/multi-exit detector (e3) variable -TRACI_CONST int CMD_SUBSCRIBE_MULTIENTRYEXIT_VARIABLE = 0xd1; -// response: subscribe multi-entry/multi-exit detector (e3) variable -TRACI_CONST int RESPONSE_SUBSCRIBE_MULTIENTRYEXIT_VARIABLE = 0xe1; - -// command: subscribe traffic lights context -TRACI_CONST int CMD_SUBSCRIBE_TL_CONTEXT = 0x82; -// response: subscribe traffic lights context -TRACI_CONST int RESPONSE_SUBSCRIBE_TL_CONTEXT = 0x92; -// command: get traffic lights variable -TRACI_CONST int CMD_GET_TL_VARIABLE = 0xa2; -// response: get traffic lights variable -TRACI_CONST int RESPONSE_GET_TL_VARIABLE = 0xb2; -// command: set traffic lights variable -TRACI_CONST int CMD_SET_TL_VARIABLE = 0xc2; -// command: subscribe traffic lights variable -TRACI_CONST int CMD_SUBSCRIBE_TL_VARIABLE = 0xd2; -// response: subscribe traffic lights variable -TRACI_CONST int RESPONSE_SUBSCRIBE_TL_VARIABLE = 0xe2; - -// command: subscribe lane context -TRACI_CONST int CMD_SUBSCRIBE_LANE_CONTEXT = 0x83; -// response: subscribe lane context -TRACI_CONST int RESPONSE_SUBSCRIBE_LANE_CONTEXT = 0x93; -// command: get lane variable -TRACI_CONST int CMD_GET_LANE_VARIABLE = 0xa3; -// response: get lane variable -TRACI_CONST int RESPONSE_GET_LANE_VARIABLE = 0xb3; -// command: set lane variable -TRACI_CONST int CMD_SET_LANE_VARIABLE = 0xc3; -// command: subscribe lane variable -TRACI_CONST int CMD_SUBSCRIBE_LANE_VARIABLE = 0xd3; -// response: subscribe lane variable -TRACI_CONST int RESPONSE_SUBSCRIBE_LANE_VARIABLE = 0xe3; - -// command: subscribe vehicle context -TRACI_CONST int CMD_SUBSCRIBE_VEHICLE_CONTEXT = 0x84; -// response: subscribe vehicle context -TRACI_CONST int RESPONSE_SUBSCRIBE_VEHICLE_CONTEXT = 0x94; -// command: get vehicle variable -TRACI_CONST int CMD_GET_VEHICLE_VARIABLE = 0xa4; -// response: get vehicle variable -TRACI_CONST int RESPONSE_GET_VEHICLE_VARIABLE = 0xb4; -// command: set vehicle variable -TRACI_CONST int CMD_SET_VEHICLE_VARIABLE = 0xc4; -// command: subscribe vehicle variable -TRACI_CONST int CMD_SUBSCRIBE_VEHICLE_VARIABLE = 0xd4; -// response: subscribe vehicle variable -TRACI_CONST int RESPONSE_SUBSCRIBE_VEHICLE_VARIABLE = 0xe4; - -// command: subscribe vehicle type context -TRACI_CONST int CMD_SUBSCRIBE_VEHICLETYPE_CONTEXT = 0x85; -// response: subscribe vehicle type context -TRACI_CONST int RESPONSE_SUBSCRIBE_VEHICLETYPE_CONTEXT = 0x95; -// command: get vehicle type variable -TRACI_CONST int CMD_GET_VEHICLETYPE_VARIABLE = 0xa5; -// response: get vehicle type variable -TRACI_CONST int RESPONSE_GET_VEHICLETYPE_VARIABLE = 0xb5; -// command: set vehicle type variable -TRACI_CONST int CMD_SET_VEHICLETYPE_VARIABLE = 0xc5; -// command: subscribe vehicle type variable -TRACI_CONST int CMD_SUBSCRIBE_VEHICLETYPE_VARIABLE = 0xd5; -// response: subscribe vehicle type variable -TRACI_CONST int RESPONSE_SUBSCRIBE_VEHICLETYPE_VARIABLE = 0xe5; - -// command: subscribe route context -TRACI_CONST int CMD_SUBSCRIBE_ROUTE_CONTEXT = 0x86; -// response: subscribe route context -TRACI_CONST int RESPONSE_SUBSCRIBE_ROUTE_CONTEXT = 0x96; -// command: get route variable -TRACI_CONST int CMD_GET_ROUTE_VARIABLE = 0xa6; -// response: get route variable -TRACI_CONST int RESPONSE_GET_ROUTE_VARIABLE = 0xb6; -// command: set route variable -TRACI_CONST int CMD_SET_ROUTE_VARIABLE = 0xc6; -// command: subscribe route variable -TRACI_CONST int CMD_SUBSCRIBE_ROUTE_VARIABLE = 0xd6; -// response: subscribe route variable -TRACI_CONST int RESPONSE_SUBSCRIBE_ROUTE_VARIABLE = 0xe6; - -// command: subscribe poi context -TRACI_CONST int CMD_SUBSCRIBE_POI_CONTEXT = 0x87; -// response: subscribe poi context -TRACI_CONST int RESPONSE_SUBSCRIBE_POI_CONTEXT = 0x97; -// command: get poi variable -TRACI_CONST int CMD_GET_POI_VARIABLE = 0xa7; -// response: get poi variable -TRACI_CONST int RESPONSE_GET_POI_VARIABLE = 0xb7; -// command: set poi variable -TRACI_CONST int CMD_SET_POI_VARIABLE = 0xc7; -// command: subscribe poi variable -TRACI_CONST int CMD_SUBSCRIBE_POI_VARIABLE = 0xd7; -// response: subscribe poi variable -TRACI_CONST int RESPONSE_SUBSCRIBE_POI_VARIABLE = 0xe7; - -// command: subscribe polygon context -TRACI_CONST int CMD_SUBSCRIBE_POLYGON_CONTEXT = 0x88; -// response: subscribe polygon context -TRACI_CONST int RESPONSE_SUBSCRIBE_POLYGON_CONTEXT = 0x98; -// command: get polygon variable -TRACI_CONST int CMD_GET_POLYGON_VARIABLE = 0xa8; -// response: get polygon variable -TRACI_CONST int RESPONSE_GET_POLYGON_VARIABLE = 0xb8; -// command: set polygon variable -TRACI_CONST int CMD_SET_POLYGON_VARIABLE = 0xc8; -// command: subscribe polygon variable -TRACI_CONST int CMD_SUBSCRIBE_POLYGON_VARIABLE = 0xd8; -// response: subscribe polygon variable -TRACI_CONST int RESPONSE_SUBSCRIBE_POLYGON_VARIABLE = 0xe8; - -// command: subscribe junction context -TRACI_CONST int CMD_SUBSCRIBE_JUNCTION_CONTEXT = 0x89; -// response: subscribe junction context -TRACI_CONST int RESPONSE_SUBSCRIBE_JUNCTION_CONTEXT = 0x99; -// command: get junction variable -TRACI_CONST int CMD_GET_JUNCTION_VARIABLE = 0xa9; -// response: get junction variable -TRACI_CONST int RESPONSE_GET_JUNCTION_VARIABLE = 0xb9; -// command: set junction variable -TRACI_CONST int CMD_SET_JUNCTION_VARIABLE = 0xc9; -// command: subscribe junction variable -TRACI_CONST int CMD_SUBSCRIBE_JUNCTION_VARIABLE = 0xd9; -// response: subscribe junction variable -TRACI_CONST int RESPONSE_SUBSCRIBE_JUNCTION_VARIABLE = 0xe9; - -// command: subscribe edge context -TRACI_CONST int CMD_SUBSCRIBE_EDGE_CONTEXT = 0x8a; -// response: subscribe edge context -TRACI_CONST int RESPONSE_SUBSCRIBE_EDGE_CONTEXT = 0x9a; -// command: get edge variable -TRACI_CONST int CMD_GET_EDGE_VARIABLE = 0xaa; -// response: get edge variable -TRACI_CONST int RESPONSE_GET_EDGE_VARIABLE = 0xba; -// command: set edge variable -TRACI_CONST int CMD_SET_EDGE_VARIABLE = 0xca; -// command: subscribe edge variable -TRACI_CONST int CMD_SUBSCRIBE_EDGE_VARIABLE = 0xda; -// response: subscribe edge variable -TRACI_CONST int RESPONSE_SUBSCRIBE_EDGE_VARIABLE = 0xea; - -// command: subscribe simulation context -TRACI_CONST int CMD_SUBSCRIBE_SIM_CONTEXT = 0x8b; -// response: subscribe simulation context -TRACI_CONST int RESPONSE_SUBSCRIBE_SIM_CONTEXT = 0x9b; -// command: get simulation variable -TRACI_CONST int CMD_GET_SIM_VARIABLE = 0xab; -// response: get simulation variable -TRACI_CONST int RESPONSE_GET_SIM_VARIABLE = 0xbb; -// command: set simulation variable -TRACI_CONST int CMD_SET_SIM_VARIABLE = 0xcb; -// command: subscribe simulation variable -TRACI_CONST int CMD_SUBSCRIBE_SIM_VARIABLE = 0xdb; -// response: subscribe simulation variable -TRACI_CONST int RESPONSE_SUBSCRIBE_SIM_VARIABLE = 0xeb; - -// command: subscribe GUI context -TRACI_CONST int CMD_SUBSCRIBE_GUI_CONTEXT = 0x8c; -// response: subscribe GUI context -TRACI_CONST int RESPONSE_SUBSCRIBE_GUI_CONTEXT = 0x9c; -// command: get GUI variable -TRACI_CONST int CMD_GET_GUI_VARIABLE = 0xac; -// response: get GUI variable -TRACI_CONST int RESPONSE_GET_GUI_VARIABLE = 0xbc; -// command: set GUI variable -TRACI_CONST int CMD_SET_GUI_VARIABLE = 0xcc; -// command: subscribe GUI variable -TRACI_CONST int CMD_SUBSCRIBE_GUI_VARIABLE = 0xdc; -// response: subscribe GUI variable -TRACI_CONST int RESPONSE_SUBSCRIBE_GUI_VARIABLE = 0xec; - -// command: subscribe lane area detector (e2) context -TRACI_CONST int CMD_SUBSCRIBE_LANEAREA_CONTEXT = 0x8d; -// response: subscribe lane area detector (e2) context -TRACI_CONST int RESPONSE_SUBSCRIBE_LANEAREA_CONTEXT = 0x9d; -// command: get lane area detector (e2) variable -TRACI_CONST int CMD_GET_LANEAREA_VARIABLE = 0xad; -// response: get lane area detector (e2) variable -TRACI_CONST int RESPONSE_GET_LANEAREA_VARIABLE = 0xbd; -// command: set lane area detector (e2) variable, not used yet -//TRACI_CONST int CMD_GET_LANEAREA_VARIABLE = 0xcd; -// command: subscribe lane area detector (e2) variable -TRACI_CONST int CMD_SUBSCRIBE_LANEAREA_VARIABLE = 0xdd; -// response: subscribe lane area detector (e2) variable -TRACI_CONST int RESPONSE_SUBSCRIBE_LANEAREA_VARIABLE = 0xed; - -// command: subscribe person context -TRACI_CONST int CMD_SUBSCRIBE_PERSON_CONTEXT = 0x8e; -// response: subscribe person context -TRACI_CONST int RESPONSE_SUBSCRIBE_PERSON_CONTEXT = 0x9e; -// command: get person variable -TRACI_CONST int CMD_GET_PERSON_VARIABLE = 0xae; -// response: get person variable -TRACI_CONST int RESPONSE_GET_PERSON_VARIABLE = 0xbe; -// command: set person variable -TRACI_CONST int CMD_SET_PERSON_VARIABLE = 0xce; -// command: subscribe person variable -TRACI_CONST int CMD_SUBSCRIBE_PERSON_VARIABLE = 0xde; -// response: subscribe person variable -TRACI_CONST int RESPONSE_SUBSCRIBE_PERSON_VARIABLE = 0xee; - -// command: subscribe busstop context -TRACI_CONST int CMD_SUBSCRIBE_BUSSTOP_CONTEXT = 0x8f; -// response: subscribe busstop context -TRACI_CONST int RESPONSE_SUBSCRIBE_BUSSTOP_CONTEXT = 0x9f; -// command: get busstop variable -TRACI_CONST int CMD_GET_BUSSTOP_VARIABLE = 0xaf; -// response: get busstop variable -TRACI_CONST int RESPONSE_GET_BUSSTOP_VARIABLE = 0xbf; -// command: set busstop variable, not used yet -TRACI_CONST int CMD_SET_BUSSTOP_VARIABLE = 0xcf; -// command: subscribe busstop variable -TRACI_CONST int CMD_SUBSCRIBE_BUSSTOP_VARIABLE = 0xdf; -// response: subscribe busstop variable -TRACI_CONST int RESPONSE_SUBSCRIBE_BUSSTOP_VARIABLE = 0xef; - -// command: subscribe parkingarea context -TRACI_CONST int CMD_SUBSCRIBE_PARKINGAREA_CONTEXT = 0x04; -// response: subscribe parkingarea context -TRACI_CONST int RESPONSE_SUBSCRIBE_PARKINGAREA_CONTEXT = 0x14; -// command: get parkingarea variable -TRACI_CONST int CMD_GET_PARKINGAREA_VARIABLE = 0x24; -// response: get parkingarea variable -TRACI_CONST int RESPONSE_GET_PARKINGAREA_VARIABLE = 0x34; -// command: set parkingarea variable -TRACI_CONST int CMD_SET_PARKINGAREA_VARIABLE = 0x44; -// command: subscribe parkingarea variable -TRACI_CONST int CMD_SUBSCRIBE_PARKINGAREA_VARIABLE = 0x54; -// response: subscribe parkingarea variable -TRACI_CONST int RESPONSE_SUBSCRIBE_PARKINGAREA_VARIABLE = 0x64; - -// command: subscribe chargingstation context -TRACI_CONST int CMD_SUBSCRIBE_CHARGINGSTATION_CONTEXT = 0x05; -// response: subscribe chargingstation context -TRACI_CONST int RESPONSE_SUBSCRIBE_CHARGINGSTATION_CONTEXT = 0x15; -// command: get chargingstation variable -TRACI_CONST int CMD_GET_CHARGINGSTATION_VARIABLE = 0x25; -// response: get chargingstation variable -TRACI_CONST int RESPONSE_GET_CHARGINGSTATION_VARIABLE = 0x35; -// command: set chargingstation variable -TRACI_CONST int CMD_SET_CHARGINGSTATION_VARIABLE = 0x45; -// command: subscribe chargingstation variable -TRACI_CONST int CMD_SUBSCRIBE_CHARGINGSTATION_VARIABLE = 0x55; -// response: subscribe chargingstation variable -TRACI_CONST int RESPONSE_SUBSCRIBE_CHARGINGSTATION_VARIABLE = 0x65; - -// command: subscribe routeprobe context -TRACI_CONST int CMD_SUBSCRIBE_ROUTEPROBE_CONTEXT = 0x06; -// response: subscribe routeprobe context -TRACI_CONST int RESPONSE_SUBSCRIBE_ROUTEPROBE_CONTEXT = 0x16; -// command: get routeprobe variable -TRACI_CONST int CMD_GET_ROUTEPROBE_VARIABLE = 0x26; -// response: get routeprobe variable -TRACI_CONST int RESPONSE_GET_ROUTEPROBE_VARIABLE = 0x36; -// command: set routeprobe variable -TRACI_CONST int CMD_SET_ROUTEPROBE_VARIABLE = 0x46; -// command: subscribe routeprobe variable -TRACI_CONST int CMD_SUBSCRIBE_ROUTEPROBE_VARIABLE = 0x56; -// response: subscribe routeprobe variable -TRACI_CONST int RESPONSE_SUBSCRIBE_ROUTEPROBE_VARIABLE = 0x66; - -// command: subscribe calibrator context -TRACI_CONST int CMD_SUBSCRIBE_CALIBRATOR_CONTEXT = 0x07; -// response: subscribe calibrator context -TRACI_CONST int RESPONSE_SUBSCRIBE_CALIBRATOR_CONTEXT = 0x17; -// command: get calibrator variable -TRACI_CONST int CMD_GET_CALIBRATOR_VARIABLE = 0x27; -// response: get calibrator variable -TRACI_CONST int RESPONSE_GET_CALIBRATOR_VARIABLE = 0x37; -// command: set calibrator variable -TRACI_CONST int CMD_SET_CALIBRATOR_VARIABLE = 0x47; -// command: subscribe calibrator variable -TRACI_CONST int CMD_SUBSCRIBE_CALIBRATOR_VARIABLE = 0x57; -// response: subscribe calibrator variable -TRACI_CONST int RESPONSE_SUBSCRIBE_CALIBRATOR_VARIABLE = 0x67; - -// command: subscribe rerouter context -TRACI_CONST int CMD_SUBSCRIBE_REROUTER_CONTEXT = 0x08; -// response: subscribe rerouter context -TRACI_CONST int RESPONSE_SUBSCRIBE_REROUTER_CONTEXT = 0x18; -// command: get rerouter variable -TRACI_CONST int CMD_GET_REROUTER_VARIABLE = 0x28; -// response: get rerouter variable -TRACI_CONST int RESPONSE_GET_REROUTER_VARIABLE = 0x38; -// command: set rerouter variable -TRACI_CONST int CMD_SET_REROUTER_VARIABLE = 0x48; -// command: subscribe rerouter variable -TRACI_CONST int CMD_SUBSCRIBE_REROUTER_VARIABLE = 0x58; -// response: subscribe rerouter variable -TRACI_CONST int RESPONSE_SUBSCRIBE_REROUTER_VARIABLE = 0x68; - -// command: subscribe variablespeedsign context -TRACI_CONST int CMD_SUBSCRIBE_VARIABLESPEEDSIGN_CONTEXT = 0x09; -// response: subscribe variablespeedsign context -TRACI_CONST int RESPONSE_SUBSCRIBE_VARIABLESPEEDSIGN_CONTEXT = 0x19; -// command: get variablespeedsign variable -TRACI_CONST int CMD_GET_VARIABLESPEEDSIGN_VARIABLE = 0x29; -// response: get variablespeedsign variable -TRACI_CONST int RESPONSE_GET_VARIABLESPEEDSIGN_VARIABLE = 0x39; -// command: set variablespeedsign variable -TRACI_CONST int CMD_SET_VARIABLESPEEDSIGN_VARIABLE = 0x49; -// command: subscribe variablespeedsign variable -TRACI_CONST int CMD_SUBSCRIBE_VARIABLESPEEDSIGN_VARIABLE = 0x59; -// response: subscribe variablespeedsign variable -TRACI_CONST int RESPONSE_SUBSCRIBE_VARIABLESPEEDSIGN_VARIABLE = 0x69; - -// command: subscribe meandata context -TRACI_CONST int CMD_SUBSCRIBE_MEANDATA_CONTEXT = 0x0a; -// response: subscribe meandata context -TRACI_CONST int RESPONSE_SUBSCRIBE_MEANDATA_CONTEXT = 0x1a; -// command: get meandata variable -TRACI_CONST int CMD_GET_MEANDATA_VARIABLE = 0x2a; -// response: get meandata variable -TRACI_CONST int RESPONSE_GET_MEANDATA_VARIABLE = 0x3a; -// command: set meandata variable, not used yet -//TRACI_CONST int CMD_SET_MEANDATA_VARIABLE = 0x4a; -// command: subscribe meandata variable -TRACI_CONST int CMD_SUBSCRIBE_MEANDATA_VARIABLE = 0x5a; -// response: subscribe meandata variable -TRACI_CONST int RESPONSE_SUBSCRIBE_MEANDATA_VARIABLE = 0x6a; - -// command: subscribe overheadwire context -TRACI_CONST int CMD_SUBSCRIBE_OVERHEADWIRE_CONTEXT = 0x0b; -// response: subscribe overheadwire context -TRACI_CONST int RESPONSE_SUBSCRIBE_OVERHEADWIRE_CONTEXT = 0x1b; -// command: get overheadwire variable -TRACI_CONST int CMD_GET_OVERHEADWIRE_VARIABLE = 0x2b; -// response: get overheadwire variable -TRACI_CONST int RESPONSE_GET_OVERHEADWIRE_VARIABLE = 0x3b; -// command: set overheadwire variable -TRACI_CONST int CMD_SET_OVERHEADWIRE_VARIABLE = 0x4b; -// command: subscribe overheadwire variable -TRACI_CONST int CMD_SUBSCRIBE_OVERHEADWIRE_VARIABLE = 0x5b; -// response: subscribe overheadwire variable -TRACI_CONST int RESPONSE_SUBSCRIBE_OVERHEADWIRE_VARIABLE = 0x6b; - - -// **************************************** -// POSITION REPRESENTATIONS -// **************************************** -// Position in geo-coordinates -TRACI_CONST int POSITION_LON_LAT = 0x00; -// 2D cartesian coordinates -TRACI_CONST int POSITION_2D = 0x01; -// Position in geo-coordinates with altitude -TRACI_CONST int POSITION_LON_LAT_ALT = 0x02; -// 3D cartesian coordinates -TRACI_CONST int POSITION_3D = 0x03; -// Position on road map -TRACI_CONST int POSITION_ROADMAP = 0x04; - - -// **************************************** -// DATA TYPES -// **************************************** -// Polygon (2*n doubles) -TRACI_CONST int TYPE_POLYGON = 0x06; -// unsigned byte -TRACI_CONST int TYPE_UBYTE = 0x07; -// signed byte -TRACI_CONST int TYPE_BYTE = 0x08; -// 32 bit signed integer -TRACI_CONST int TYPE_INTEGER = 0x09; -// double precision float -TRACI_CONST int TYPE_DOUBLE = 0x0B; -// 8 bit ASCII string -TRACI_CONST int TYPE_STRING = 0x0C; -// list of strings -TRACI_CONST int TYPE_STRINGLIST = 0x0E; -// compound object -TRACI_CONST int TYPE_COMPOUND = 0x0F; -// list of double precision floats -TRACI_CONST int TYPE_DOUBLELIST = 0x10; -// color (four ubytes) -TRACI_CONST int TYPE_COLOR = 0x11; - - -// **************************************** -// RESULT TYPES -// **************************************** -// result type: Ok -TRACI_CONST int RTYPE_OK = 0x00; -// result type: not implemented -TRACI_CONST int RTYPE_NOTIMPLEMENTED = 0x01; -// result type: error -TRACI_CONST int RTYPE_ERR = 0xFF; - -// **************************************** -// special return or parameter values -// **************************************** -// return value for invalid queries (especially vehicle is not on the road), see Position::INVALID -TRACI_CONST double INVALID_DOUBLE_VALUE = -1073741824.0; -// return value for invalid queries (especially vehicle is not on the road), see Position::INVALID -TRACI_CONST int INVALID_INT_VALUE = -1073741824; -// maximum value for client ordering (2 ^ 30) -TRACI_CONST int MAX_ORDER = 1073741824; - - -// **************************************** -// DIFFERENT DISTANCE REQUESTS -// **************************************** -// air distance -TRACI_CONST int REQUEST_AIRDIST = 0x00; -// driving distance -TRACI_CONST int REQUEST_DRIVINGDIST = 0x01; - - -// **************************************** -// VEHICLE REMOVAL REASONS -// **************************************** -// vehicle started teleport -TRACI_CONST int REMOVE_TELEPORT = 0x00; -// vehicle removed while parking -TRACI_CONST int REMOVE_PARKING = 0x01; -// vehicle arrived -TRACI_CONST int REMOVE_ARRIVED = 0x02; -// vehicle was vaporized -TRACI_CONST int REMOVE_VAPORIZED = 0x03; -// vehicle finished route during teleport -TRACI_CONST int REMOVE_TELEPORT_ARRIVED = 0x04; - -// **************************************** -// VEHICLE MOVE REASONS -// **************************************** -// infer reason from move distance -TRACI_CONST int MOVE_AUTOMATIC = 0x00; -// vehicle teleports to another location -TRACI_CONST int MOVE_TELEPORT = 0x01; -// vehicle moved normally -TRACI_CONST int MOVE_NORMAL = 0x02; - -// **************************************** -// PERSON/CONTAINER STAGES -// **************************************** -// person / container stopping -TRACI_CONST int STAGE_WAITING_FOR_DEPART = 0x00; -// person / container stopping -TRACI_CONST int STAGE_WAITING = 0x01; -// person walking -TRACI_CONST int STAGE_WALKING = 0x02; -// person riding / container being transported -TRACI_CONST int STAGE_DRIVING = 0x03; -// person accessing stopping place -TRACI_CONST int STAGE_ACCESS = 0x04; -// stage for encoding abstract travel demand -TRACI_CONST int STAGE_TRIP = 0x05; -// person / container transhiping -TRACI_CONST int STAGE_TRANSHIP = 0x06; - -// **************************************** -// Stop Flags -// **************************************** -TRACI_CONST int STOP_DEFAULT = 0x00; -TRACI_CONST int STOP_PARKING = 0x01; -TRACI_CONST int STOP_TRIGGERED = 0x02; -TRACI_CONST int STOP_CONTAINER_TRIGGERED = 0x04; -TRACI_CONST int STOP_BUS_STOP = 0x08; -TRACI_CONST int STOP_CONTAINER_STOP = 0x10; -TRACI_CONST int STOP_CHARGING_STATION = 0x20; -TRACI_CONST int STOP_PARKING_AREA = 0x40; - -// **************************************** -// Departure Flags -// **************************************** -TRACI_CONST int DEPARTFLAG_TRIGGERED = -0x01; -TRACI_CONST int DEPARTFLAG_CONTAINER_TRIGGERED = -0x02; -TRACI_CONST int DEPARTFLAG_NOW = -0x03; - -TRACI_CONST int DEPARTFLAG_SPEED_RANDOM = -0x02; -TRACI_CONST int DEPARTFLAG_SPEED_MAX = -0x03; - -TRACI_CONST int DEPARTFLAG_LANE_RANDOM = -0x02; -TRACI_CONST int DEPARTFLAG_LANE_FREE = -0x03; -TRACI_CONST int DEPARTFLAG_LANE_ALLOWED_FREE = -0x04; -TRACI_CONST int DEPARTFLAG_LANE_BEST_FREE = -0x05; -TRACI_CONST int DEPARTFLAG_LANE_FIRST_ALLOWED = -0x06; - -TRACI_CONST int DEPARTFLAG_POS_RANDOM = -0x02; -TRACI_CONST int DEPARTFLAG_POS_FREE = -0x03; -TRACI_CONST int DEPARTFLAG_POS_BASE = -0x04; -TRACI_CONST int DEPARTFLAG_POS_LAST = -0x05; -TRACI_CONST int DEPARTFLAG_POS_RANDOM_FREE = -0x06; - -TRACI_CONST int ARRIVALFLAG_LANE_CURRENT = -0x02; -TRACI_CONST int ARRIVALFLAG_SPEED_CURRENT = -0x02; - -TRACI_CONST int ARRIVALFLAG_POS_RANDOM = -0x02; -TRACI_CONST int ARRIVALFLAG_POS_MAX = -0x03; - -// **************************************** -// Routing modes -// **************************************** -// use custom weights if available, fall back to loaded weights and then to free-flow speed -TRACI_CONST int ROUTING_MODE_DEFAULT = 0x00; -// use aggregated travel times from device.rerouting -TRACI_CONST int ROUTING_MODE_AGGREGATED = 0x01; -// use loaded efforts -TRACI_CONST int ROUTING_MODE_EFFORT = 0x02; -// use combined costs -TRACI_CONST int ROUTING_MODE_COMBINED = 0x03; - -// **************************************** -// FILTER TYPES (for context subscription filters) -// **************************************** - -// Reset all filters -TRACI_CONST int FILTER_TYPE_NONE = 0x00; - -// Filter by list of lanes relative to ego vehicle -TRACI_CONST int FILTER_TYPE_LANES = 0x01; - -// Exclude vehicles on opposite (and other) lanes from context subscription result -TRACI_CONST int FILTER_TYPE_NOOPPOSITE = 0x02; - -// Specify maximal downstream distance for vehicles in context subscription result -TRACI_CONST int FILTER_TYPE_DOWNSTREAM_DIST = 0x03; - -// Specify maximal upstream distance for vehicles in context subscription result -TRACI_CONST int FILTER_TYPE_UPSTREAM_DIST = 0x04; - -// Only return leader and follower on the specified lanes in context subscription result -TRACI_CONST int FILTER_TYPE_LEAD_FOLLOW = 0x05; - -// Only return foes on upcoming junction in context subscription result -TRACI_CONST int FILTER_TYPE_TURN = 0x07; - -// Only return vehicles of the given vClass in context subscription result -TRACI_CONST int FILTER_TYPE_VCLASS = 0x08; - -// Only return vehicles of the given vType in context subscription result -TRACI_CONST int FILTER_TYPE_VTYPE = 0x09; - -// Only return vehicles within field of vision in context subscription result -TRACI_CONST int FILTER_TYPE_FIELD_OF_VISION = 0x0A; - -// Only return vehicles within the given lateral distance in context subscription result -TRACI_CONST int FILTER_TYPE_LATERAL_DIST = 0x0B; - -// **************************************** -// VARIABLE TYPES (for CMD_GET_*_VARIABLE) -// **************************************** -// list of instances' ids (get: all) -TRACI_CONST int TRACI_ID_LIST = 0x00; - -// count of instances (get: all) -TRACI_CONST int ID_COUNT = 0x01; - -// subscribe object variables (get: all) -TRACI_CONST int AUTOMATIC_VARIABLES_SUBSCRIPTION = 0x02; - -// subscribe context variables (get: all) -TRACI_CONST int AUTOMATIC_CONTEXT_SUBSCRIPTION = 0x03; - -// generic attributes (get/set: all) -TRACI_CONST int GENERIC_ATTRIBUTE = 0x03; - -// last step vehicle number (get: induction loops, multi-entry/multi-exit detector, lanes, edges) -TRACI_CONST int LAST_STEP_VEHICLE_NUMBER = 0x10; - -// last step vehicle number (get: induction loops, multi-entry/multi-exit detector, lanes, edges) -TRACI_CONST int LAST_STEP_MEAN_SPEED = 0x11; - -// last step vehicle list (get: induction loops, multi-entry/multi-exit detector, lanes, edges) -TRACI_CONST int LAST_STEP_VEHICLE_ID_LIST = 0x12; - -// last step occupancy (get: induction loops, lanes, edges) -TRACI_CONST int LAST_STEP_OCCUPANCY = 0x13; - -// last step vehicle halting number (get: multi-entry/multi-exit detector, lanes, edges) -TRACI_CONST int LAST_STEP_VEHICLE_HALTING_NUMBER = 0x14; - -// last step mean vehicle length (get: induction loops, lanes, edges) -TRACI_CONST int LAST_STEP_LENGTH = 0x15; - -// last step time since last detection (get: induction loops) -TRACI_CONST int LAST_STEP_TIME_SINCE_DETECTION = 0x16; - -// entry times -TRACI_CONST int LAST_STEP_VEHICLE_DATA = 0x17; - -// last step jam length in vehicles -TRACI_CONST int JAM_LENGTH_VEHICLE = 0x18; - -// last step jam length in meters -TRACI_CONST int JAM_LENGTH_METERS = 0x19; - -// last step person list (get: edges, vehicles) -TRACI_CONST int LAST_STEP_PERSON_ID_LIST = 0x1a; - -// full name (get: edges, simulation, trafficlight) -TRACI_CONST int VAR_NAME = 0x1b; - -// carFollowModel function followSpeed (get: vehicle) -TRACI_CONST int VAR_FOLLOW_SPEED = 0x1c; - -// carFollowModel function stopSpeed (get: vehicle) -TRACI_CONST int VAR_STOP_SPEED = 0x1d; - -// carFollowModel function getSecureGap (get: vehicle) -TRACI_CONST int VAR_SECURE_GAP = 0x1e; - -// estimated delay for next stop -TRACI_CONST int VAR_STOP_DELAY = 0x1f; - -// begin time(get: calibrator) -TRACI_CONST int VAR_BEGIN = 0x1c; - -// end time(get: calibrator) -TRACI_CONST int VAR_END = 0x1d; - -// vtype list (get: calibrator) -TRACI_CONST int VAR_VTYPES = 0x1e; - -// vehicles per hour (get: calibrator) -TRACI_CONST int VAR_VEHSPERHOUR = 0x13; - -// passed vehicle count (get: calibrator) -TRACI_CONST int VAR_PASSED = 0x14; - -// inserted vehicle count (get: calibrator) -TRACI_CONST int VAR_INSERTED = 0x15; - -// removed vehicle count (get: calibrator) -TRACI_CONST int VAR_REMOVED = 0x16; - -// routeProbe id (get: calibrator) -TRACI_CONST int VAR_ROUTE_PROBE = 0x17; - -// routeProbe id (get: calibrator) -TRACI_CONST int CMD_SET_FLOW = 0x18; - -// traffic light states, encoded as rRgGyYoO tuple (get: traffic lights) -TRACI_CONST int TL_RED_YELLOW_GREEN_STATE = 0x20; - -// index of the phase (set: traffic lights) -TRACI_CONST int TL_PHASE_INDEX = 0x22; - -// traffic light program (set: traffic lights) -TRACI_CONST int TL_PROGRAM = 0x23; - -// phase duration (set: traffic lights) -TRACI_CONST int TL_PHASE_DURATION = 0x24; - -// vehicles that block passing the given signal (get: traffic lights) -TRACI_CONST int TL_BLOCKING_VEHICLES = 0x25; - -// controlled lanes (get: traffic lights) -TRACI_CONST int TL_CONTROLLED_LANES = 0x26; - -// controlled links (get: traffic lights) -TRACI_CONST int TL_CONTROLLED_LINKS = 0x27; - -// index of the current phase (get: traffic lights) -TRACI_CONST int TL_CURRENT_PHASE = 0x28; - -// name of the current program (get: traffic lights) -TRACI_CONST int TL_CURRENT_PROGRAM = 0x29; - -// vehicles that also wish to pass the given signal (get: traffic lights) -TRACI_CONST int TL_RIVAL_VEHICLES = 0x30; - -// vehicles that also wish to pass the given signal and have higher priority (get: traffic lights) -TRACI_CONST int TL_PRIORITY_VEHICLES = 0x31; - -// controlled junctions (get: traffic lights) -TRACI_CONST int TL_CONTROLLED_JUNCTIONS = 0x2a; - -// complete definition (get: traffic lights) -TRACI_CONST int TL_COMPLETE_DEFINITION_RYG = 0x2b; - -// complete program (set: traffic lights) -TRACI_CONST int TL_COMPLETE_PROGRAM_RYG = 0x2c; - -// assumed time to next switch (get: traffic lights) -TRACI_CONST int TL_NEXT_SWITCH = 0x2d; - -// current state, using external signal names (get: traffic lights) -TRACI_CONST int TL_EXTERNAL_STATE = 0x2e; - -// outgoing link number (get: lanes) -TRACI_CONST int LANE_LINK_NUMBER = 0x30; - -// id of parent edge (get: lanes) -TRACI_CONST int LANE_EDGE_ID = 0x31; - -// outgoing link definitions (get: lanes) -TRACI_CONST int LANE_LINKS = 0x33; - -// list of allowed vehicle classes (get&set: lanes) -TRACI_CONST int LANE_ALLOWED = 0x34; - -// list of not allowed vehicle classes (get&set: lanes) -TRACI_CONST int LANE_DISALLOWED = 0x35; - -// list of foe lanes (get: lanes) -TRACI_CONST int VAR_FOES = 0x37; - -// slope (get: edge, lane, vehicle, person) -TRACI_CONST int VAR_SLOPE = 0x36; - -// speed (get: vehicle) -TRACI_CONST int VAR_SPEED = 0x40; - -// lateral speed (get: vehicle) -TRACI_CONST int VAR_SPEED_LAT = 0x32; - -// maximum allowed/possible speed (get: vehicle types, lanes, set: edges, lanes) -TRACI_CONST int VAR_MAXSPEED = 0x41; - -// position (2D) (get: vehicle, poi, inductionloop, lane area detector; set: poi) -TRACI_CONST int VAR_POSITION = 0x42; - -// position (3D) (get: vehicle, poi, set: poi) -TRACI_CONST int VAR_POSITION3D = 0x39; - -// angle (get: vehicle, poi; set: poi) -TRACI_CONST int VAR_ANGLE = 0x43; - -// angle (get: vehicle types, lanes, lane area detector, set: lanes) -TRACI_CONST int VAR_LENGTH = 0x44; - -// color (get: vehicles, vehicle types, polygons, pois) -TRACI_CONST int VAR_COLOR = 0x45; - -// max. acceleration (get: vehicles, vehicle types) -TRACI_CONST int VAR_ACCEL = 0x46; - -// max. comfortable deceleration (get: vehicles, vehicle types) -TRACI_CONST int VAR_DECEL = 0x47; - -// max. (physically possible) deceleration (get: vehicles, vehicle types) -TRACI_CONST int VAR_EMERGENCY_DECEL = 0x7b; - -// apparent deceleration (get: vehicles, vehicle types) -TRACI_CONST int VAR_APPARENT_DECEL = 0x7c; - -// action step length (get: vehicles, vehicle types) -TRACI_CONST int VAR_ACTIONSTEPLENGTH = 0x7d; - -// last action time (get: vehicles) -TRACI_CONST int VAR_LASTACTIONTIME = 0x7f; - -// driver's desired headway (get: vehicle types) -TRACI_CONST int VAR_TAU = 0x48; - -// vehicle class (get: vehicle types) -TRACI_CONST int VAR_VEHICLECLASS = 0x49; - -// emission class (get: vehicle types) -TRACI_CONST int VAR_EMISSIONCLASS = 0x4a; - -// shape class (get: vehicle types) -TRACI_CONST int VAR_SHAPECLASS = 0x4b; - -// minimum gap (get: vehicle types) -TRACI_CONST int VAR_MINGAP = 0x4c; - -// width (get: vehicle types, lanes, polygons, poi) -TRACI_CONST int VAR_WIDTH = 0x4d; - -// shape (get: polygons) -TRACI_CONST int VAR_SHAPE = 0x4e; - -// type id (get: vehicles, polygons, pois) -TRACI_CONST int VAR_TYPE = 0x4f; - -// road id (get: vehicles) -TRACI_CONST int VAR_ROAD_ID = 0x50; - -// lane id (get: vehicles, inductionloop, lane area detector) -TRACI_CONST int VAR_LANE_ID = 0x51; - -// lane index (get: vehicle, edge) -TRACI_CONST int VAR_LANE_INDEX = 0x52; - -// route id (get & set: vehicles) -TRACI_CONST int VAR_ROUTE_ID = 0x53; - -// edges (get: routes, vehicles) -TRACI_CONST int VAR_EDGES = 0x54; - -// update bestLanes (set: vehicle) -TRACI_CONST int VAR_UPDATE_BESTLANES = 0x6a; - -// filled? (get: polygons) -TRACI_CONST int VAR_FILL = 0x55; - -// get/set image file (poi, poly, vehicle, person, simulation) -TRACI_CONST int VAR_IMAGEFILE = 0x93; - -// position (1D along lane) (get: vehicle) -TRACI_CONST int VAR_LANEPOSITION = 0x56; - -// route (set: vehicles) -TRACI_CONST int VAR_ROUTE = 0x57; - -// travel time information (get&set: vehicle) -TRACI_CONST int VAR_EDGE_TRAVELTIME = 0x58; - -// effort information (get&set: vehicle) -TRACI_CONST int VAR_EDGE_EFFORT = 0x59; - -// last step travel time (get: edge, lane) -TRACI_CONST int VAR_CURRENT_TRAVELTIME = 0x5a; - -// signals state (get/set: vehicle) -TRACI_CONST int VAR_SIGNALS = 0x5b; - -// vehicle: new lane/position along (set: vehicle) -TRACI_CONST int VAR_MOVE_TO = 0x5c; - -// polygon: add dynamics (set: polygon) -TRACI_CONST int VAR_ADD_DYNAMICS = 0x5c; - -// vehicle: highlight (set: vehicle, poi) -TRACI_CONST int VAR_HIGHLIGHT = 0x6c; - -// driver imperfection (set: vehicle) -TRACI_CONST int VAR_IMPERFECTION = 0x5d; - -// speed factor (set: vehicle) -TRACI_CONST int VAR_SPEED_FACTOR = 0x5e; - -// speed deviation (set: vehicle) -TRACI_CONST int VAR_SPEED_DEVIATION = 0x5f; - -// routing mode (get/set: vehicle) -TRACI_CONST int VAR_ROUTING_MODE = 0x89; - -// speed without TraCI influence (get: vehicle) -TRACI_CONST int VAR_SPEED_WITHOUT_TRACI = 0xb1; - -// best lanes (get: vehicle) -TRACI_CONST int VAR_BEST_LANES = 0xb2; - -// how speed is set (set: vehicle) -TRACI_CONST int VAR_SPEEDSETMODE = 0xb3; - -// move vehicle to explicit (remote controlled) position (set: vehicle) -TRACI_CONST int MOVE_TO_XY = 0xb4; - -// is the vehicle stopped, and if so parked and/or triggered? -// value = stopped + 2 * parking + 4 * triggered -TRACI_CONST int VAR_STOPSTATE = 0xb5; - -// how lane changing is performed (get/set: vehicle) -TRACI_CONST int VAR_LANECHANGE_MODE = 0xb6; - -// maximum speed regarding max speed on the current lane and speed factor (get: vehicle) -TRACI_CONST int VAR_ALLOWED_SPEED = 0xb7; - -// position (1D lateral position relative to center of the current lane) (get: vehicle) -TRACI_CONST int VAR_LANEPOSITION_LAT = 0xb8; - -// get/set prefered lateral alignment within the lane (vehicle) -TRACI_CONST int VAR_LATALIGNMENT = 0xb9; - -// get/set maximum lateral speed (vehicle, vtypes) -TRACI_CONST int VAR_MAXSPEED_LAT = 0xba; - -// get/set minimum lateral gap (vehicle, vtypes) -TRACI_CONST int VAR_MINGAP_LAT = 0xbb; - -// get/set vehicle height (vehicle, vtypes, poi) -TRACI_CONST int VAR_HEIGHT = 0xbc; - -// get/set vehicle line -TRACI_CONST int VAR_LINE = 0xbd; - -// get/set vehicle via -TRACI_CONST int VAR_VIA = 0xbe; - -// get (lane change relevant) neighboring vehicles (vehicles) -TRACI_CONST int VAR_NEIGHBORS = 0xbf; - -// current CO2 emission of a node (get: vehicle, lane, edge) -TRACI_CONST int VAR_CO2EMISSION = 0x60; - -// current CO emission of a node (get: vehicle, lane, edge) -TRACI_CONST int VAR_COEMISSION = 0x61; - -// current HC emission of a node (get: vehicle, lane, edge) -TRACI_CONST int VAR_HCEMISSION = 0x62; - -// current PMx emission of a node (get: vehicle, lane, edge) -TRACI_CONST int VAR_PMXEMISSION = 0x63; - -// current NOx emission of a node (get: vehicle, lane, edge) -TRACI_CONST int VAR_NOXEMISSION = 0x64; - -// current fuel consumption of a node (get: vehicle, lane, edge) -TRACI_CONST int VAR_FUELCONSUMPTION = 0x65; - -// current noise emission of a node (get: vehicle, lane, edge) -TRACI_CONST int VAR_NOISEEMISSION = 0x66; - -// current person number (get: vehicle, trafficlight) -TRACI_CONST int VAR_PERSON_NUMBER = 0x67; - -// person capacity (vehicle , vehicle type) -TRACI_CONST int VAR_PERSON_CAPACITY = 0x38; - -TRACI_CONST int VAR_BUS_STOP_ID_LIST = 0x9f; - -// number of persons waiting at a defined bus stop (get: simulation) -TRACI_CONST int VAR_BUS_STOP_WAITING = 0x67; - -// ids of persons waiting at a defined bus stop (get: simulation) -TRACI_CONST int VAR_BUS_STOP_WAITING_IDS = 0xef; - -// current leader together with gap (get: vehicle) -TRACI_CONST int VAR_LEADER = 0x68; - -// edge index in current route (get: vehicle) -TRACI_CONST int VAR_ROUTE_INDEX = 0x69; - -// current waiting time (get: vehicle, lane) -TRACI_CONST int VAR_WAITING_TIME = 0x7a; - -// current waiting time (get: vehicle) -TRACI_CONST int VAR_ACCUMULATED_WAITING_TIME = 0x87; - -// upcoming traffic lights (get: vehicle) -TRACI_CONST int VAR_NEXT_TLS = 0x70; - -// upcoming stops (get: vehicle) -TRACI_CONST int VAR_NEXT_STOPS = 0x73; - -// upcoming stops with selection (get: vehicle) -TRACI_CONST int VAR_NEXT_STOPS2 = 0x74; - -// current acceleration (get: vehicle) -TRACI_CONST int VAR_ACCELERATION = 0x72; - -// add log message (set: simulation) -TRACI_CONST int CMD_MESSAGE = 0x65; - -// current time in seconds (get: simulation) -TRACI_CONST int VAR_TIME = 0x66; - -// current time step (get: simulation) -TRACI_CONST int VAR_TIME_STEP = 0x70; - -// current electricity consumption of a node (get: vehicle, lane, edge) -TRACI_CONST int VAR_ELECTRICITYCONSUMPTION = 0x71; - -// number of loaded vehicles (get: simulation) -TRACI_CONST int VAR_LOADED_VEHICLES_NUMBER = 0x71; - -// loaded vehicle ids (get: simulation) -TRACI_CONST int VAR_LOADED_VEHICLES_IDS = 0x72; - -// number of departed vehicle (get: simulation) -TRACI_CONST int VAR_DEPARTED_VEHICLES_NUMBER = 0x73; - -// departed vehicle ids (get: simulation) -TRACI_CONST int VAR_DEPARTED_VEHICLES_IDS = 0x74; - -// number of vehicles starting to teleport (get: simulation) -TRACI_CONST int VAR_TELEPORT_STARTING_VEHICLES_NUMBER = 0x75; - -// ids of vehicles starting to teleport (get: simulation) -TRACI_CONST int VAR_TELEPORT_STARTING_VEHICLES_IDS = 0x76; - -// number of vehicles ending to teleport (get: simulation) -TRACI_CONST int VAR_TELEPORT_ENDING_VEHICLES_NUMBER = 0x77; - -// ids of vehicles ending to teleport (get: simulation) -TRACI_CONST int VAR_TELEPORT_ENDING_VEHICLES_IDS = 0x78; - -// number of arrived vehicles (get: simulation) -TRACI_CONST int VAR_ARRIVED_VEHICLES_NUMBER = 0x79; - -// ids of arrived vehicles (get: simulation) -TRACI_CONST int VAR_ARRIVED_VEHICLES_IDS = 0x7a; - -// delta t (get: simulation) -TRACI_CONST int VAR_DELTA_T = 0x7b; - -// bounding box (get: simulation) -TRACI_CONST int VAR_NET_BOUNDING_BOX = 0x7c; - -// minimum number of expected vehicles (get: simulation) -TRACI_CONST int VAR_MIN_EXPECTED_VEHICLES = 0x7d; - -// number of vehicles starting to park (get: simulation) -TRACI_CONST int VAR_STOP_STARTING_VEHICLES_NUMBER = 0x68; - -// ids of vehicles starting to park (get: simulation) -TRACI_CONST int VAR_STOP_STARTING_VEHICLES_IDS = 0x69; - -// number of vehicles ending to park (get: simulation) -TRACI_CONST int VAR_STOP_ENDING_VEHICLES_NUMBER = 0x6a; - -// ids of vehicles ending to park (get: simulation) -TRACI_CONST int VAR_STOP_ENDING_VEHICLES_IDS = 0x6b; - -// number of vehicles starting to park (get: simulation) -TRACI_CONST int VAR_PARKING_STARTING_VEHICLES_NUMBER = 0x6c; - -// ids of vehicles starting to park (get: simulation) -TRACI_CONST int VAR_PARKING_STARTING_VEHICLES_IDS = 0x6d; - -// number of vehicles maneuvering (get: simulation) -TRACI_CONST int VAR_PARKING_MANEUVERING_VEHICLES_NUMBER = 0x3a; - -// ids of vehicles maneuvering (get: simulation) -TRACI_CONST int VAR_PARKING_MANEUVERING_VEHICLES_IDS = 0x3b; - -// number of vehicles ending to park (get: simulation) -TRACI_CONST int VAR_PARKING_ENDING_VEHICLES_NUMBER = 0x6e; - -// ids of vehicles ending to park (get: simulation) -TRACI_CONST int VAR_PARKING_ENDING_VEHICLES_IDS = 0x6f; - -// number of vehicles involved in a collision (get: simulation) -TRACI_CONST int VAR_COLLIDING_VEHICLES_NUMBER = 0x80; - -// ids of vehicles involved in a collision (get: simulation) -TRACI_CONST int VAR_COLLIDING_VEHICLES_IDS = 0x81; - -// number of vehicles involved in a collision (get: simulation) -TRACI_CONST int VAR_EMERGENCYSTOPPING_VEHICLES_NUMBER = 0x89; - -// ids of vehicles involved in a collision (get: simulation) -TRACI_CONST int VAR_EMERGENCYSTOPPING_VEHICLES_IDS = 0x8a; - -// clears the simulation of all not inserted vehicles (set: simulation) -TRACI_CONST int CMD_CLEAR_PENDING_VEHICLES = 0x94; - -// triggers saving simulation state (set: simulation) -TRACI_CONST int CMD_SAVE_SIMSTATE = 0x95; - -// triggers saving simulation state (set: simulation) -TRACI_CONST int CMD_LOAD_SIMSTATE = 0x96; - -// sets/retrieves abstract parameter -TRACI_CONST int VAR_PARAMETER = 0x7e; - -// retrieves abstract parameter and returns (key, value) tuple -TRACI_CONST int VAR_PARAMETER_WITH_KEY = 0x3e; - - -// add an instance (poi, polygon, vehicle, person, route) -TRACI_CONST int ADD = 0x80; - -// remove an instance (poi, polygon, vehicle, person) -TRACI_CONST int REMOVE = 0x81; - -// copy an instance (vehicle type, other TBD.) -TRACI_CONST int COPY = 0x88; - -// convert coordinates -TRACI_CONST int POSITION_CONVERSION = 0x82; - -// distance between points or vehicles -TRACI_CONST int DISTANCE_REQUEST = 0x83; - -// the current driving distance -TRACI_CONST int VAR_DISTANCE = 0x84; - -// add a fully specified instance (vehicle) -TRACI_CONST int ADD_FULL = 0x85; - -// find a car based route -TRACI_CONST int FIND_ROUTE = 0x86; - -// find an intermodal route -TRACI_CONST int FIND_INTERMODAL_ROUTE = 0x87; - -// force rerouting based on travel time (vehicles) -TRACI_CONST int CMD_REROUTE_TRAVELTIME = 0x90; - -// force rerouting based on effort (vehicles) -TRACI_CONST int CMD_REROUTE_EFFORT = 0x91; - -// validates current route (vehicles) -TRACI_CONST int VAR_ROUTE_VALID = 0x92; - -// retrieve information regarding the current person/container stage -TRACI_CONST int VAR_STAGE = 0xc0; - -// retrieve information regarding the next edge including crossings and walkingAreas (pedestrians only) -TRACI_CONST int VAR_NEXT_EDGE = 0xc1; - -// retrieve information regarding the number of remaining stages -TRACI_CONST int VAR_STAGES_REMAINING = 0xc2; - -// retrieve the current vehicle id for the driving stage (person, container) -TRACI_CONST int VAR_VEHICLE = 0xc3; - -// append a person stage (person) -TRACI_CONST int APPEND_STAGE = 0xc4; - -// replace a person stage (person) -TRACI_CONST int REPLACE_STAGE = 0xcd; - -// append a person stage (person) -TRACI_CONST int REMOVE_STAGE = 0xc5; - -// zoom -TRACI_CONST int VAR_VIEW_ZOOM = 0xa0; - -// view position -TRACI_CONST int VAR_VIEW_OFFSET = 0xa1; - -// view schema -TRACI_CONST int VAR_VIEW_SCHEMA = 0xa2; - -// view by boundary -TRACI_CONST int VAR_VIEW_BOUNDARY = 0xa3; - -// screenshot -TRACI_CONST int VAR_SCREENSHOT = 0xa5; - -// track vehicle -TRACI_CONST int VAR_TRACK_VEHICLE = 0xa6; - -// presence of view -TRACI_CONST int VAR_HAS_VIEW = 0xa7; - -} // namespace libsumo - -#undef TRACI_CONST - diff --git a/Util/OSM2ODR/src/libsumo/TraCIDefs.h b/Util/OSM2ODR/src/libsumo/TraCIDefs.h deleted file mode 100644 index d46bab13c..000000000 --- a/Util/OSM2ODR/src/libsumo/TraCIDefs.h +++ /dev/null @@ -1,427 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2012-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file TraCIDefs.h -/// @author Daniel Krajzewicz -/// @author Mario Krumnow -/// @author Michael Behrisch -/// @author Robert Hilbrich -/// @date 30.05.2012 -/// -// C++ TraCI client API implementation -/****************************************************************************/ -#pragma once -// we do not include config.h here, since we should be independent of a special sumo build -#include -#include -#include -#include -#include -#include -#include -#include - - -// =========================================================================== -// global definitions -// =========================================================================== - -#define LIBSUMO_SUBSCRIPTION_API \ -static void subscribe(const std::string& objectID, const std::vector& varIDs = std::vector({-1}), double begin = libsumo::INVALID_DOUBLE_VALUE, double end = libsumo::INVALID_DOUBLE_VALUE); \ -static void unsubscribe(const std::string& objectID); \ -static void subscribeContext(const std::string& objectID, int domain, double dist, const std::vector& varIDs = std::vector({-1}), double begin = libsumo::INVALID_DOUBLE_VALUE, double end = libsumo::INVALID_DOUBLE_VALUE); \ -static void unsubscribeContext(const std::string& objectID, int domain, double dist); \ -static const SubscriptionResults getAllSubscriptionResults(); \ -static const TraCIResults getSubscriptionResults(const std::string& objectID); \ -static const ContextSubscriptionResults getAllContextSubscriptionResults(); \ -static const SubscriptionResults getContextSubscriptionResults(const std::string& objectID); - -#define LIBSUMO_SUBSCRIPTION_IMPLEMENTATION(CLASS, DOMAIN) \ -void \ -CLASS::subscribe(const std::string& objectID, const std::vector& varIDs, double begin, double end) { \ - libsumo::Helper::subscribe(CMD_SUBSCRIBE_##DOMAIN##_VARIABLE, objectID, varIDs, begin, end); \ -} \ -void \ -CLASS::unsubscribe(const std::string& objectID) { \ - libsumo::Helper::subscribe(CMD_SUBSCRIBE_##DOMAIN##_VARIABLE, objectID, std::vector(), libsumo::INVALID_DOUBLE_VALUE, libsumo::INVALID_DOUBLE_VALUE); \ -} \ -void \ -CLASS::subscribeContext(const std::string& objectID, int domain, double dist, const std::vector& varIDs, double begin, double end) { \ - libsumo::Helper::subscribe(CMD_SUBSCRIBE_##DOMAIN##_CONTEXT, objectID, varIDs, begin, end, domain, dist); \ -} \ -void \ -CLASS::unsubscribeContext(const std::string& objectID, int domain, double dist) { \ - libsumo::Helper::subscribe(CMD_SUBSCRIBE_##DOMAIN##_CONTEXT, objectID, std::vector(), libsumo::INVALID_DOUBLE_VALUE, libsumo::INVALID_DOUBLE_VALUE, domain, dist); \ -} \ -const SubscriptionResults \ -CLASS::getAllSubscriptionResults() { \ - return mySubscriptionResults; \ -} \ -const TraCIResults \ -CLASS::getSubscriptionResults(const std::string& objectID) { \ - return mySubscriptionResults[objectID]; \ -} \ -const ContextSubscriptionResults \ -CLASS::getAllContextSubscriptionResults() { \ - return myContextSubscriptionResults; \ -} \ -const SubscriptionResults \ -CLASS::getContextSubscriptionResults(const std::string& objectID) { \ - return myContextSubscriptionResults[objectID]; \ -} - - -#define LIBSUMO_GET_PARAMETER_WITH_KEY_API \ -static const std::pair getParameterWithKey(const std::string& objectID, const std::string& key); - -#define LIBSUMO_GET_PARAMETER_WITH_KEY_IMPLEMENTATION(CLASS) \ -const std::pair \ -CLASS::getParameterWithKey(const std::string& objectID, const std::string& key) { \ - return std::make_pair(key, getParameter(objectID, key)); \ -} - - -// =========================================================================== -// class and type definitions -// =========================================================================== -namespace libsumo { -/** -* @class TraCIException -*/ -class TraCIException : public std::runtime_error { -public: - /** constructor */ - TraCIException(std::string what) - : std::runtime_error(what) {} -}; - -/// @name Structures definitions -/// @{ - -struct TraCIResult { - virtual ~TraCIResult() {} - virtual std::string getString() { - return ""; - } -}; - -/** @struct TraCIPosition - * @brief A 3D-position - */ -struct TraCIPosition : TraCIResult { - std::string getString() { - std::ostringstream os; - os << "TraCIPosition(" << x << "," << y << "," << z << ")"; - return os.str(); - } - double x = INVALID_DOUBLE_VALUE, y = INVALID_DOUBLE_VALUE, z = INVALID_DOUBLE_VALUE; -}; - -/** @struct TraCIRoadPosition - * @brief An edgeId, position and laneIndex - */ -struct TraCIRoadPosition : TraCIResult { - std::string getString() { - std::ostringstream os; - os << "TraCIRoadPosition(" << edgeID << "_" << laneIndex << "," << pos << ")"; - return os.str(); - } - std::string edgeID; - double pos; - int laneIndex = INVALID_INT_VALUE; -}; - -/** @struct TraCIColor - * @brief A color - */ -struct TraCIColor : TraCIResult { - TraCIColor() : r(0), g(0), b(0), a(255) {} - TraCIColor(int r, int g, int b, int a = 255) : r(r), g(g), b(b), a(a) {} - std::string getString() { - std::ostringstream os; - os << "TraCIColor(" << r << "," << g << "," << b << "," << a << ")"; - return os.str(); - } - int r, g, b, a; -}; - - -/** @struct TraCILeaderDistance - * @brief A leaderId and distance to leader - */ -struct TraCILeaderDistance : TraCIResult { - std::string getString() { - std::ostringstream os; - os << "TraCILeaderDistance(" << leaderID << "," << dist << ")"; - return os.str(); - } - std::string leaderID; - double dist; -}; - - -/** @struct TraCIPositionVector - * @brief A list of positions - */ -typedef std::vector TraCIPositionVector; - - -struct TraCIInt : TraCIResult { - TraCIInt() : value(0) {} - TraCIInt(int v) : value(v) {} - std::string getString() { - std::ostringstream os; - os << value; - return os.str(); - } - int value; -}; - - -struct TraCIDouble : TraCIResult { - TraCIDouble() : value(0.) {} - TraCIDouble(double v) : value(v) {} - std::string getString() { - std::ostringstream os; - os << value; - return os.str(); - } - double value; -}; - - -struct TraCIString : TraCIResult { - TraCIString() : value("") {} - TraCIString(std::string v) : value(v) {} - std::string getString() { - return value; - } - std::string value; -}; - - -struct TraCIStringList : TraCIResult { - std::string getString() { - std::ostringstream os; - os << "["; - for (std::string v : value) { - os << v << ","; - } - os << "]"; - return os.str(); - } - std::vector value; -}; - - -/// @brief {variable->value} -typedef std::map > TraCIResults; -/// @brief {object->{variable->value}} -typedef std::map SubscriptionResults; -typedef std::map ContextSubscriptionResults; - - -class TraCIPhase { -public: - TraCIPhase() {} - TraCIPhase(const double _duration, const std::string& _state, const double _minDur = libsumo::INVALID_DOUBLE_VALUE, - const double _maxDur = libsumo::INVALID_DOUBLE_VALUE, - const std::vector& _next = std::vector(), - const std::string& _name = "") : - duration(_duration), state(_state), minDur(_minDur), maxDur(_maxDur), next(_next), name(_name) {} - ~TraCIPhase() {} - - double duration; - std::string state; - double minDur, maxDur; - std::vector next; - std::string name; -}; -} - - -#ifdef SWIG -%template(TraCIPhaseVector) std::vector; // *NOPAD* -#endif - - -namespace libsumo { -class TraCILogic { -public: - TraCILogic() {} - TraCILogic(const std::string& _programID, const int _type, const int _currentPhaseIndex, - const std::vector& _phases = std::vector()) - : programID(_programID), type(_type), currentPhaseIndex(_currentPhaseIndex), phases(_phases) {} - ~TraCILogic() {} - - std::string programID; - int type; - int currentPhaseIndex; - std::vector phases; - std::map subParameter; -}; - - -class TraCILink { -public: - TraCILink(const std::string& _from, const std::string& _via, const std::string& _to) - : fromLane(_from), viaLane(_via), toLane(_to) {} - ~TraCILink() {} - - std::string fromLane; - std::string viaLane; - std::string toLane; -}; - - -class TraCIConnection { -public: - TraCIConnection() {} // this is needed by SWIG when building a vector of this type, please don't use it - TraCIConnection(const std::string& _approachedLane, const bool _hasPrio, const bool _isOpen, const bool _hasFoe, - const std::string _approachedInternal, const std::string _state, const std::string _direction, const double _length) - : approachedLane(_approachedLane), hasPrio(_hasPrio), isOpen(_isOpen), hasFoe(_hasFoe), - approachedInternal(_approachedInternal), state(_state), direction(_direction), length(_length) {} - ~TraCIConnection() {} - - std::string approachedLane; - bool hasPrio; - bool isOpen; - bool hasFoe; - std::string approachedInternal; - std::string state; - std::string direction; - double length; -}; - - -/// @brief mirrors MSInductLoop::VehicleData -struct TraCIVehicleData { - /// @brief The id of the vehicle - std::string id; - /// @brief Length of the vehicle - double length; - /// @brief Entry-time of the vehicle in [s] - double entryTime; - /// @brief Leave-time of the vehicle in [s] - double leaveTime; - /// @brief Type of the vehicle in - std::string typeID; -}; - - -struct TraCINextTLSData { - /// @brief The id of the next tls - std::string id; - /// @brief The tls index of the controlled link - int tlIndex; - /// @brief The distance to the tls - double dist; - /// @brief The current state of the tls - char state; -}; - - -struct TraCINextStopData : TraCIResult { - std::string getString() { - std::ostringstream os; - os << "TraCINextStopData(" << lane << "," << endPos << "," << stoppingPlaceID << "," << stopFlags << "," << duration << "," << until << ")"; - return os.str(); - } - - /// @brief The lane to stop at - std::string lane; - /// @brief The stopping position end - double endPos; - /// @brief Id assigned to the stop - std::string stoppingPlaceID; - /// @brief Stop flags - int stopFlags; - /// @brief The stopping duration - double duration; - /// @brief The time at which the vehicle may continue its journey - double until; -}; - - -/** @struct TraCINextStopDataVector - * @brief A list of vehicle stops - * @see TraCINextStopData - */ -struct TraCINextStopDataVector : TraCIResult { - std::string getString() { - std::ostringstream os; - os << "TraCINextStopDataVector["; - for (TraCINextStopData v : value) { - os << v.getString() << ","; - } - os << "]"; - return os.str(); - } - - std::vector value; -}; - - -struct TraCIBestLanesData { - /// @brief The id of the lane - std::string laneID; - /// @brief The length than can be driven from that lane without lane change - double length; - /// @brief The traffic density along length - double occupation; - /// @brief The offset of this lane from the best lane - int bestLaneOffset; - /// @brief Whether this lane allows continuing the route - bool allowsContinuation; - /// @brief The sequence of lanes that best allows continuing the route without lane change - std::vector continuationLanes; -}; - - -class TraCIStage { -public: - TraCIStage(int type = INVALID_INT_VALUE, const std::string& vType = "", const std::string& line = "", const std::string& destStop = "", - const std::vector& edges = std::vector(), - double travelTime = INVALID_DOUBLE_VALUE, double cost = INVALID_DOUBLE_VALUE, double length = INVALID_DOUBLE_VALUE, - const std::string& intended = "", double depart = INVALID_DOUBLE_VALUE, double departPos = INVALID_DOUBLE_VALUE, - double arrivalPos = INVALID_DOUBLE_VALUE, const std::string& description = "") : - type(type), vType(vType), line(line), destStop(destStop), edges(edges), travelTime(travelTime), cost(cost), - length(length), intended(intended), depart(depart), departPos(departPos), arrivalPos(arrivalPos), description(description) {} - /// @brief The type of stage (walking, driving, ...) - int type; - /// @brief The vehicle type when using a private car or bike - std::string vType; - /// @brief The line or the id of the vehicle type - std::string line; - /// @brief The id of the destination stop - std::string destStop; - /// @brief The sequence of edges to travel - std::vector edges; - /// @brief duration of the stage in seconds - double travelTime; - /// @brief effort needed - double cost; - /// @brief length in m - double length; - /// @brief id of the intended vehicle for public transport ride - std::string intended; - /// @brief intended depart time for public transport ride or INVALID_DOUBLE_VALUE - double depart; - /// @brief position on the lane when starting the stage - double departPos; - /// @brief position on the lane when ending the stage - double arrivalPos; - /// @brief arbitrary description string - std::string description; -}; -} diff --git a/Util/OSM2ODR/src/microsim/MSJunction.h b/Util/OSM2ODR/src/microsim/MSJunction.h deleted file mode 100644 index 5dacc9c37..000000000 --- a/Util/OSM2ODR/src/microsim/MSJunction.h +++ /dev/null @@ -1,174 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file MSJunction.h -/// @author Christian Roessel -/// @author Daniel Krajzewicz -/// @author Sascha Krieg -/// @author Michael Behrisch -/// @date Wed, 12 Dez 2001 -/// -// The base class for an intersection -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - - -// =========================================================================== -// class declarations -// =========================================================================== -class MSVehicle; -class MSLink; -class MSLane; -class MSEdge; -class MSJunctionLogic; - -typedef std::vector MSEdgeVector; -typedef std::vector ConstMSEdgeVector; - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class MSJunction - * @brief The base class for an intersection - */ -class MSJunction : public Named, public Parameterised { -public: - /** @brief Constructor - * @param[in] id The id of the junction - * @param[in] position The position of the junction - * @param[in] shape The shape of the junction - */ - MSJunction(const std::string& id, - SumoXMLNodeType type, - const Position& position, - const PositionVector& shape, - const std::string& name); - - - /// @brief Destructor. - virtual ~MSJunction(); - - - /** performs some initialisation after the loading - (e.g., link map computation) */ - virtual void postloadInit(); - - - /** returns the junction's position */ - const Position& getPosition() const; - - - /** @brief Returns this junction's shape - * @return The shape of this junction - */ - const PositionVector& getShape() const { - return myShape; - } - - /// @brief return the junction name - const std::string& getName() const { - return myName; - } - - virtual const std::vector& getFoeLinks(const MSLink* const /*srcLink*/) const { - return myEmptyLinks; - } - - virtual const std::vector& getFoeInternalLanes(const MSLink* const /*srcLink*/) const { - return myEmptyLanes; - } - - inline const ConstMSEdgeVector& getIncoming() const { - return myIncoming; - } - - int getNrOfIncomingLanes() const; - - inline const ConstMSEdgeVector& getOutgoing() const { - return myOutgoing; - } - - /** @brief Returns all internal lanes on the junction - */ - virtual const std::vector getInternalLanes() const { - return myEmptyLanes; - } - - void addIncoming(MSEdge* edge) { - myIncoming.push_back(edge); - } - - void addOutgoing(MSEdge* edge) { - myOutgoing.push_back(edge); - } - - /// @brief return the type of this Junction - SumoXMLNodeType getType() const { - return myType; - } - - /// @brief erase vehicle from myLinkLeaders - void passedJunction(const MSVehicle* vehicle); - - // @brief return the underlying right-of-way and conflict matrix - virtual const MSJunctionLogic* getLogic() const { - return nullptr; - } - -protected: - /// @brief Tye type of this junction - SumoXMLNodeType myType; - - /// @brief The position of the junction - Position myPosition; - - /// @brief The shape of the junction - PositionVector myShape; - - /// @briefh The (optional) junction name - std::string myName; - - std::vector myEmptyLinks; - std::vector myEmptyLanes; - - - /// @brief incoming edges - ConstMSEdgeVector myIncoming; - /// @brief outgoing edges - ConstMSEdgeVector myOutgoing; - - /// @brief definition of the static dictionary type - typedef std::map DictType; - -private: - /// @brief Invalidated copy constructor. - MSJunction(const MSJunction&); - - /// @brief Invalidated assignment operator. - MSJunction& operator=(const MSJunction&); - -}; diff --git a/Util/OSM2ODR/src/microsim/MSLane.h b/Util/OSM2ODR/src/microsim/MSLane.h deleted file mode 100644 index a390bfba7..000000000 --- a/Util/OSM2ODR/src/microsim/MSLane.h +++ /dev/null @@ -1,1621 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file MSLane.h -/// @author Christian Roessel -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Christoph Sommer -/// @author Tino Morenz -/// @author Michael Behrisch -/// @author Mario Krumnow -/// @author Leonhard Luecken -/// @date Mon, 12 Mar 2001 -/// -// Representation of a lane in the micro simulation -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "MSLinkCont.h" -#include "MSLeaderInfo.h" -#include "MSMoveReminder.h" -#include - -#include -#ifdef HAVE_FOX -#include -#endif - - -// =========================================================================== -// class declarations -// =========================================================================== -class MSEdge; -class MSVehicle; -class MSLaneChanger; -class MSLink; -class MSVehicleTransfer; -class MSVehicleControl; -class OutputDevice; -class MSLeaderInfo; - - -// =========================================================================== -// type definitions -// =========================================================================== -/// Coverage info -typedef std::map > LaneCoverageInfo; // also declared in libsumo/Helper.h! - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class MSLane - * @brief Representation of a lane in the micro simulation - * - * Class which represents a single lane. Somekind of the main class of the - * simulation. Allows moving vehicles. - */ -class MSLane : public Named, public Parameterised { -public: - /// needs access to myTmpVehicles (this maybe should be done via double-buffering!!!) - friend class MSLaneChanger; - friend class MSLaneChangerSublane; - - friend class MSQueueExport; - friend class AnyVehicleIterator; - - /// Container for vehicles. - typedef std::vector VehCont; - - /** Function-object in order to find the vehicle, that has just - passed the detector. */ - struct VehPosition : public std::binary_function < const MSVehicle*, double, bool > { - /// compares vehicle position to the detector position - bool operator()(const MSVehicle* cmp, double pos) const; - }; - - // TODO: Better documentation - /// @brief AnyVehicleIterator is a structure, which manages the iteration through all vehicles on the lane, - /// that may be of importance for the car-following dynamics along that lane. The relevant types of vehicles are: - /// 1) vehicles with their front on the lane (myVehicles), - /// 2) vehicles intersecting the lane but with front on another lane (myPartialVehicles) - /// - /// In the context of retrieving linkLeaders during lane changing a third group of vehicles is checked: - /// 3) vehicles processed during lane changing (myTmpVehicles) - class AnyVehicleIterator { - public: - AnyVehicleIterator( - const MSLane* lane, - int i1, - int i2, - int i3, - const int i1End, - const int i2End, - const int i3End, - bool downstream = true) : - myLane(lane), - myI1(i1), - myI2(i2), - myI3(i3), - myI1End(i1End), - myI2End(i2End), - myI3End(i3End), - myDownstream(downstream), - myDirection(downstream ? 1 : -1) { - } - - bool operator== (AnyVehicleIterator const& other) const { - return (myI1 == other.myI1 - && myI2 == other.myI2 - && myI3 == other.myI3 - && myI1End == other.myI1End - && myI2End == other.myI2End - && myI3End == other.myI3End); - } - - bool operator!= (AnyVehicleIterator const& other) const { - return !(*this == other); - } - - const MSVehicle* operator->() { - return **this; - } - - const MSVehicle* operator*(); - - AnyVehicleIterator& operator++(); - - private: - bool nextIsMyVehicles() const; - - /// @brief the lane that is being iterated - const MSLane* myLane; - /// @brief index for myVehicles - int myI1; - /// @brief index for myPartialVehicles - int myI2; - /// @brief index for myTmpVehicles - int myI3; - /// @brief end index for myVehicles - int myI1End; - /// @brief end index for myPartialVehicles - int myI2End; - /// @brief end index for myTmpVehicles - int myI3End; - /// @brief iteration direction - bool myDownstream; - /// @brief index delta - int myDirection; - - }; - - -public: - /** @enum ChangeRequest - * @brief Requests set via TraCI - */ - enum CollisionAction { - COLLISION_ACTION_NONE, - COLLISION_ACTION_WARN, - COLLISION_ACTION_TELEPORT, - COLLISION_ACTION_REMOVE - }; - - /** @brief Constructor - * - * @param[in] id The lane's id - * @param[in] maxSpeed The speed allowed on this lane - * @param[in] length The lane's length - * @param[in] edge The edge this lane belongs to - * @param[in] numericalID The numerical id of the lane - * @param[in] shape The shape of the lane - * @param[in] width The width of the lane - * @param[in] permissions Encoding of the Vehicle classes that may drive on this lane - * @param[in] index The index of this lane within its parent edge - * @param[in] isRampAccel Whether this lane is an acceleration lane - * @see SUMOVehicleClass - */ - MSLane(const std::string& id, double maxSpeed, double length, MSEdge* const edge, - int numericalID, const PositionVector& shape, double width, - SVCPermissions permissions, int index, bool isRampAccel, - const std::string& type); - - - /// @brief Destructor - virtual ~MSLane(); - - /// @brief sets the associated RNG index - void setRNGIndex(const int rngIndex) { - myRNGIndex = rngIndex; - } - - /// @brief returns the associated RNG index - int getRNGIndex() const { - return myRNGIndex; - } - - /// @brief return the associated RNG - std::mt19937* getRNG() const { - return &myRNGs[myRNGIndex]; - } - - /// @brief return the number of RNGs - static int getNumRNGs() { - return (int)myRNGs.size(); - } - - /// @brief save random number generator states to the given output device - static void saveRNGStates(OutputDevice& out); - - /// @brief load random number generator state for the given rng index - static void loadRNGState(int index, const std::string& state); - - /// @name Additional initialisation - /// @{ - - /** @brief Delayed initialization - * - * Not all lane-members are known at the time the lane is born, above all the pointers - * to other lanes, so we have to add them later. - * - * @param[in] link An outgoing link - */ - void addLink(MSLink* link); - - /** @brief Adds a neighbor to this lane - * - * @param[in] id The lane's id - */ - void addNeigh(const std::string& id); - ///@} - - - - /// @name interaction with MSMoveReminder - /// @{ - - /** @brief Add a move-reminder to move-reminder container - * - * The move reminder will not be deleted by the lane. - * - * @param[in] rem The move reminder to add - */ - virtual void addMoveReminder(MSMoveReminder* rem); - - - /** @brief Return the list of this lane's move reminders - * @return Previously added move reminder - */ - inline const std::vector< MSMoveReminder* >& getMoveReminders() const { - return myMoveReminders; - } - ///@} - - - - /// @name Vehicle insertion - ///@{ - - /** @brief Tries to insert the given vehicle - * - * The insertion position and speed are determined in dependence - * to the vehicle's departure definition, first. - * - * Then, the vehicle is tried to be inserted into the lane - * using these values by a call to "isInsertionSuccess". The result of - * "isInsertionSuccess" is returned. - * - * @param[in] v The vehicle to insert - * @return Whether the vehicle could be inserted - * @see isInsertionSuccess - * @see MSVehicle::getDepartureDefinition - * @see MSVehicle::DepartArrivalDefinition - */ - bool insertVehicle(MSVehicle& v); - - - /** @brief Tries to insert the given vehicle with the given state (speed and pos) - * - * Checks whether the vehicle can be inserted at the given position with the - * given speed so that no collisions with leader/follower occur and the speed - * does not cause unexpected behaviour on consecutive lanes. Returns false - * if the vehicle can not be inserted. - * - * If the insertion can take place, incorporateVehicle() is called and true is returned. - * - * @param[in] vehicle The vehicle to insert - * @param[in] speed The speed with which it shall be inserted - * @param[in] pos The position at which it shall be inserted - * @param[in] posLat The lateral position at which it shall be inserted - * @param[in] recheckNextLanes Forces patching the speed for not being too fast on next lanes - * @param[in] notification The cause of insertion (i.e. departure, teleport, parking) defaults to departure - * @return Whether the vehicle could be inserted - * @see MSVehicle::enterLaneAtInsertion - */ - bool isInsertionSuccess(MSVehicle* vehicle, double speed, double pos, double posLat, - bool recheckNextLanes, - MSMoveReminder::Notification notification); - - // XXX: Documentation? - bool checkFailure(const MSVehicle* aVehicle, double& speed, double& dist, const double nspeed, const bool patchSpeed, const std::string errorMsg) const; - - /** @brief inserts vehicle as close as possible to the last vehicle on this - * lane (or at the end of the lane if there is no leader) - */ - bool lastInsertion(MSVehicle& veh, double mspeed, double posLat, bool patchSpeed); - - /** @brief Tries to insert the given vehicle on any place - * - * @param[in] veh The vehicle to insert - * @param[in] speed The maximum insertion speed - * @param[in] notification The cause of insertion (i.e. departure, teleport, parking) defaults to departure - * @return Whether the vehicle could be inserted - */ - bool freeInsertion(MSVehicle& veh, double speed, double posLat, - MSMoveReminder::Notification notification = MSMoveReminder::NOTIFICATION_DEPARTED); - - - /** @brief Inserts the given vehicle at the given position - * - * No checks are done, vehicle insertion using this method may - * generate collisions (possibly delayed). - * @param[in] veh The vehicle to insert - * @param[in] pos The position at which the vehicle shall be inserted - * @param[in] notification The cause of insertion (i.e. departure, teleport, parking) defaults to departure - * @param[in] posLat The lateral position at which the vehicle shall be inserted - */ - void forceVehicleInsertion(MSVehicle* veh, double pos, MSMoveReminder::Notification notification, double posLat = 0); - /// @} - - - - /// @name Handling vehicles lapping into several lanes (-> partial occupation) - /// or which committed a maneuver that will lead them into another (sublane case -> maneuver reservations) - /// @{ - /** @brief Sets the information about a vehicle lapping into this lane - * - * This vehicle is added to myVehicles and may be distinguished from regular - * vehicles by the disparity between this lane and v->getLane() - * @param[in] v The vehicle which laps into this lane - * @return This lane's length - */ - virtual double setPartialOccupation(MSVehicle* v); - - /** @brief Removes the information about a vehicle lapping into this lane - * @param[in] v The vehicle which laps into this lane - */ - virtual void resetPartialOccupation(MSVehicle* v); - - /** @brief Registers the lane change intentions (towards this lane) for the given vehicle - */ - virtual void setManeuverReservation(MSVehicle* v); - - /** @brief Unregisters a vehicle, which previously registered for maneuvering into this lane - * @param[in] v The vehicle - */ - virtual void resetManeuverReservation(MSVehicle* v); - - /** @brief Returns the last vehicles on the lane - * - * The information about the last vehicles in this lanes in all sublanes - * occupied by ego are - * returned. Partial occupators are included - * @param[in] ego The vehicle for which to restrict the returned leaderInfo - * @param[in] minPos The minimum position from which to start search for leaders - * @param[in] allowCached Whether the cached value may be used - * @return Information about the last vehicles - */ - const MSLeaderInfo getLastVehicleInformation(const MSVehicle* ego, double latOffset, double minPos = 0, bool allowCached = true) const; - - /// @brief analogue to getLastVehicleInformation but in the upstream direction - const MSLeaderInfo getFirstVehicleInformation(const MSVehicle* ego, double latOffset, bool onlyFrontOnLane, double maxPos = std::numeric_limits::max(), bool allowCached = true) const; - - /// @} - - /// @name Access to vehicles - /// @{ - - /** @brief Returns the number of vehicles on this lane (for which this lane - * is responsible) - * @return The number of vehicles with their front on this lane - */ - int getVehicleNumber() const { - return (int)myVehicles.size(); - } - - /** @brief Returns the number of vehicles on this lane (including partial - * occupators) - * @return The number of vehicles with intersecting this lane - */ - int getVehicleNumberWithPartials() const { - return (int)myVehicles.size() + (int)myPartialVehicles.size(); - } - - /** @brief Returns the number of vehicles partially on this lane (for which this lane - * is not responsible) - * @return The number of vehicles touching this lane but with their front on another lane - */ - int getPartialVehicleNumber() const { - return (int)myPartialVehicles.size(); - } - - - /** @brief Returns the vehicles container; locks it for microsimulation - * - * Please note that it is necessary to release the vehicles container - * afterwards using "releaseVehicles". - * @return The vehicles on this lane - */ - virtual const VehCont& getVehiclesSecure() const { - return myVehicles; - } - - - /// @brief begin iterator for iterating over all vehicles touching this lane in downstream direction - AnyVehicleIterator anyVehiclesBegin() const { - return AnyVehicleIterator(this, 0, 0, 0, - (int)myVehicles.size(), (int)myPartialVehicles.size(), (int)myTmpVehicles.size(), true); - } - - /// @brief end iterator for iterating over all vehicles touching this lane in downstream direction - AnyVehicleIterator anyVehiclesEnd() const { - return AnyVehicleIterator(this, (int)myVehicles.size(), (int)myPartialVehicles.size(), (int)myTmpVehicles.size(), - (int)myVehicles.size(), (int)myPartialVehicles.size(), (int)myTmpVehicles.size(), true); - } - - /// @brief begin iterator for iterating over all vehicles touching this lane in upstream direction - AnyVehicleIterator anyVehiclesUpstreamBegin() const { - return AnyVehicleIterator(this, (int)myVehicles.size() - 1, (int)myPartialVehicles.size() - 1, (int)myTmpVehicles.size() - 1, - -1, -1, -1, false); - } - - /// @brief end iterator for iterating over all vehicles touching this lane in upstream direction - AnyVehicleIterator anyVehiclesUpstreamEnd() const { - return AnyVehicleIterator(this, -1, -1, -1, -1, -1, -1, false); - } - - /** @brief Allows to use the container for microsimulation again - */ - virtual void releaseVehicles() const { } - /// @} - - - - /// @name Atomar value getter - /// @{ - - - /** @brief Returns this lane's numerical id - * @return This lane's numerical id - */ - inline int getNumericalID() const { - return myNumericalID; - } - - - /** @brief Returns this lane's shape - * @return This lane's shape - */ - inline const PositionVector& getShape() const { - return myShape; - } - - /// @brief return shape.length() / myLength - inline double getLengthGeometryFactor() const { - return myLengthGeometryFactor; - } - - /// @brief return whether this lane is an acceleration lane - inline bool isAccelLane() const { - return myIsRampAccel; - } - - /// @brief return the type of this lane - const std::string& getLaneType() const { - return myLaneType; - } - - /* @brief fit the given lane position to a visibly suitable geometry position - * (lane length might differ from geometry length) */ - inline double interpolateLanePosToGeometryPos(double lanePos) const { - return lanePos * myLengthGeometryFactor; - } - - /* @brief fit the given lane position to a visibly suitable geometry position - * and return the coordinates */ - inline const Position geometryPositionAtOffset(double offset, double lateralOffset = 0) const { - return myShape.positionAtOffset(interpolateLanePosToGeometryPos(offset), lateralOffset); - } - - /* @brief fit the given geometry position to a valid lane position - * (lane length might differ from geometry length) */ - inline double interpolateGeometryPosToLanePos(double geometryPos) const { - return geometryPos / myLengthGeometryFactor; - } - - /** @brief Returns the lane's maximum speed, given a vehicle's speed limit adaptation - * @param[in] The vehicle to return the adapted speed limit for - * @return This lane's resulting max. speed - */ - inline double getVehicleMaxSpeed(const SUMOTrafficObject* const veh) const { - if (myRestrictions != nullptr) { - std::map::const_iterator r = myRestrictions->find(veh->getVClass()); - if (r != myRestrictions->end()) { - return MIN2(veh->getMaxSpeed(), r->second * veh->getChosenSpeedFactor()); - } - } - return MIN2(veh->getMaxSpeed(), myMaxSpeed * veh->getChosenSpeedFactor()); - } - - - /** @brief Returns the lane's maximum allowed speed - * @return This lane's maximum allowed speed - */ - inline double getSpeedLimit() const { - return myMaxSpeed; - } - - - /** @brief Returns the lane's length - * @return This lane's length - */ - inline double getLength() const { - return myLength; - } - - - /** @brief Returns the vehicle class permissions for this lane - * @return This lane's allowed vehicle classes - */ - inline SVCPermissions getPermissions() const { - return myPermissions; - } - - - /** @brief Returns the lane's width - * @return This lane's width - */ - double getWidth() const { - return myWidth; - } - - /** @brief Returns the lane's index - * @return This lane's index - */ - int getIndex() const { - return myIndex; - } - /// @} - - /// @brief return the index of the link to the next crossing if this is walkingArea, else -1 - int getCrossingIndex() const; - - - /// @name Vehicle movement (longitudinal) - /// @{ - - /** @brief Compute safe velocities for all vehicles based on positions and - * speeds from the last time step. Also registers - * ApproachingVehicleInformation for all links - * - * This method goes through all vehicles calling their "planMove" method. - * @see MSVehicle::planMove - */ - virtual void planMovements(const SUMOTime t); - - /** @brief Register junction approaches for all vehicles after velocities - * have been planned. - * - * This method goes through all vehicles calling their * "setApproachingForAllLinks" method. - */ - virtual void setJunctionApproaches(const SUMOTime t) const; - - /** @brief This updates the MSLeaderInfo argument with respect to the given MSVehicle. - * All leader-vehicles on the same edge, which are relevant for the vehicle - * (i.e. with position > vehicle's position) and not already integrated into - * the LeaderInfo, are integrated. - * The given iterators vehPart and vehRes give access to these vehicles which are - * either partial occupators or have issued a maneuver reservation for the lane - * (the latter occurs only for the sublane model). - */ - void updateLeaderInfo(const MSVehicle* veh, VehCont::reverse_iterator& vehPart, VehCont::reverse_iterator& vehRes, MSLeaderInfo& ahead) const; - - /** @brief Executes planned vehicle movements with regards to right-of-way - * - * This method goes through all vehicles calling their executeMove method - * which causes vehicles to update their positions and speeds. - * Vehicles wich move to the next lane are stored in the targets lane buffer - * - * @return Returns true, if all vehicles left the lane. - * - * @see MSVehicle::executeMove - */ - virtual void executeMovements(const SUMOTime t); - - /// Insert buffered vehicle into the real lane. - virtual void integrateNewVehicles(); - - /// @brief updated current vehicle length sum (delayed to avoid lane-order-dependency) - void updateLengthSum(); - ///@} - - - /// @brief short-circut collision check if nothing changed since the last check - inline bool needsCollisionCheck() const { - return myNeedsCollisionCheck; - } - - /// @brief require another collision check due to relevant changes in the simulation - inline void requireCollisionCheck() { - myNeedsCollisionCheck = true; - } - - /// Check if vehicles are too close. - virtual void detectCollisions(SUMOTime timestep, const std::string& stage); - - - /** Returns the information whether this lane may be used to continue - the current route */ - virtual bool appropriate(const MSVehicle* veh); - - - /// returns the container with all links !!! - const MSLinkCont& getLinkCont() const; - - /// returns the link to the given lane or 0, if it is not connected - MSLink* getLinkTo(const MSLane*) const; - - /// Returns the entry link if this is an internal lane, else 0 - MSLink* getEntryLink() const; - - - /// Returns true if there is not a single vehicle on the lane. - bool empty() const { - assert(myVehBuffer.size() == 0); - return myVehicles.empty(); - } - - /** @brief Sets a new maximum speed for the lane (used by TraCI and MSCalibrator) - * @param[in] val the new speed in m/s - */ - void setMaxSpeed(double val); - - /** @brief Sets a new length for the lane (used by TraCI only) - * @param[in] val the new length in m - */ - void setLength(double val); - - /** @brief Returns the lane's edge - * @return This lane's edge - */ - MSEdge& getEdge() const { - return *myEdge; - } - - - /** @brief Returns the lane's follower if it is an internal lane, the edge of the lane otherwise - * @return This lane's follower - */ - const MSEdge* getNextNormal() const; - - - /** @brief Returns 0 if the lane is not internal. Otherwise the first part of the - * connection (sequence of internal lanes along junction) corresponding to the lane - * is returned and the offset is set to the distance of the begin of this lane - * to the begin of the returned. - */ - const MSLane* getFirstInternalInConnection(double& offset) const; - - - /// @brief Static (sic!) container methods - /// { - - /** @brief Inserts a MSLane into the static dictionary - * - * Returns true if the key id isn't already in the dictionary. - * Otherwise returns false. - * @param[in] id The id of the lane - * @param[in] lane The lane itself - * @return Whether the lane was added - * @todo make non-static - * @todo why is the id given? The lane is named - */ - static bool dictionary(const std::string& id, MSLane* lane); - - - /** @brief Returns the MSLane associated to the key id - * - * The lane is returned if exists, otherwise 0 is returned. - * @param[in] id The id of the lane - * @return The lane - */ - static MSLane* dictionary(const std::string& id); - - - /** @brief Clears the dictionary */ - static void clear(); - - - /** @brief Returns the number of stored lanes - * @return The number of stored lanes - */ - static int dictSize() { - return (int)myDict.size(); - } - - - /** @brief Adds the ids of all stored lanes into the given vector - * @param[in, filled] into The vector to add the IDs into - */ - static void insertIDs(std::vector& into); - - - /** @brief Fills the given RTree with lane instances - * @param[in, filled] into The RTree to fill - * @see TraCILaneRTree - */ - template - static void fill(RTREE& into); - - - /// @brief initialize rngs - static void initRNGs(const OptionsCont& oc); - /// @} - - - - // XXX: succLink does not exist... Documentation? - /** Same as succLink, but does not throw any assertions when - the succeeding link could not be found; - Returns the myLinks.end() instead; Further, the number of edges to - look forward may be given */ - static MSLinkCont::const_iterator succLinkSec(const SUMOVehicle& veh, - int nRouteSuccs, - const MSLane& succLinkSource, - const std::vector& conts); - - - /** Returns the information whether the given link shows at the end - of the list of links (is not valid) */ - bool isLinkEnd(MSLinkCont::const_iterator& i) const; - - /** Returns the information whether the given link shows at the end - of the list of links (is not valid) */ - bool isLinkEnd(MSLinkCont::iterator& i); - - /** Returns the information whether the lane is has no vehicle and no - partial occupation*/ - bool isEmpty() const; - - /** Returns whether the lane pertains to an internal edge*/ - bool isInternal() const; - - /// @brief returns the last vehicle for which this lane is responsible or 0 - MSVehicle* getLastFullVehicle() const; - - /// @brief returns the first vehicle for which this lane is responsible or 0 - MSVehicle* getFirstFullVehicle() const; - - /// @brief returns the last vehicle that is fully or partially on this lane - MSVehicle* getLastAnyVehicle() const; - - /// @brief returns the first vehicle that is fully or partially on this lane - MSVehicle* getFirstAnyVehicle() const; - - /* @brief remove the vehicle from this lane - * @param[notify] whether moveReminders of the vehicle shall be triggered - */ - virtual MSVehicle* removeVehicle(MSVehicle* remVehicle, MSMoveReminder::Notification notification, bool notify = true); - - void leftByLaneChange(MSVehicle* v); - void enteredByLaneChange(MSVehicle* v); - - /** @brief Returns the lane with the given offset parallel to this one or 0 if it does not exist - * @param[in] offset The offset of the result lane - */ - MSLane* getParallelLane(int offset, bool includeOpposite = true) const; - - - /** @brief Sets the permissions to the given value. If a transientID is given, the permissions are recored as temporary - * @param[in] permissions The new permissions - * @param[in] transientID The id of the permission-modification or the special value PERMANENT - */ - void setPermissions(SVCPermissions permissions, long long transientID); - void resetPermissions(long long transientID); - - - inline bool allowsVehicleClass(SUMOVehicleClass vclass) const { - return (myPermissions & vclass) == vclass; - } - - void addIncomingLane(MSLane* lane, MSLink* viaLink); - - - struct IncomingLaneInfo { - MSLane* lane; - double length; - MSLink* viaLink; - }; - - const std::vector& getIncomingLanes() const { - return myIncomingLanes; - } - - - void addApproachingLane(MSLane* lane, bool warnMultiCon); - bool isApproachedFrom(MSEdge* const edge); - bool isApproachedFrom(MSEdge* const edge, MSLane* const lane); - - /// @brief Returns vehicle class specific stopOffset for the vehicle - double getStopOffset(const MSVehicle* veh) const; - - /// @brief Returns vehicle class specific stopOffsets - const std::map& getStopOffsets() const { - return myStopOffsets; - }; - - /// @brief Set vehicle class specific stopOffsets - void setStopOffsets(std::map stopOffsets) { - myStopOffsets = stopOffsets; - }; - - /// @brief return the sublane followers with the largest missing rear gap among all predecessor lanes (within dist) - MSLeaderDistanceInfo getFollowersOnConsecutive(const MSVehicle* ego, double backOffset, - bool allSublanes, double searchDist = -1, bool ignoreMinorLinks = false) const; - - /// @brief return by how much further the leader must be inserted to avoid rear end collisions - double getMissingRearGap(const MSVehicle* leader, double backOffset, double leaderSpeed) const; - - /** @brief Returns the immediate leader of veh and the distance to veh - * starting on this lane - * - * Iterates over the current lane to find a leader and then uses - * getLeaderOnConsecutive() - * @param[in] veh The vehicle for which the information shall be computed - * @param[in] vehPos The vehicle position relative to this lane (may be negative) - * @param[in] bestLaneConts The succeding lanes that shall be checked (if any) - * @param[in] dist Optional distance to override default (ego stopDist) - * @param[in] checkTmpVehicles Whether myTmpVehicles should be used instead of myVehicles - * @return - */ - std::pair getLeader(const MSVehicle* veh, const double vehPos, const std::vector& bestLaneConts, double dist = -1, bool checkTmpVehicles = false) const; - - /** @brief Returns the immediate leader and the distance to him - * - * Goes along the vehicle's estimated used lanes (bestLaneConts). For each link, - * it is determined whether the vehicle will pass it. If so, the subsequent lane - * is investigated. If a vehicle (leader) is found, it is returned, together with the length - * of the investigated lanes until this vehicle's end, including the already seen - * place (seen). - * - * If no leading vehicle was found, <0, -1> is returned. - * - * Pretty slow, as it has to go along lanes. - * - * @todo: There are some oddities: - * - what about crossing a link at red, or if a link is closed? Has a following vehicle to be regarded or not? - * - * @param[in] dist The distance to investigate - * @param[in] seen The already seen place (normally the place in front on own lane) - * @param[in] speed The speed of the vehicle used for determining whether a subsequent link will be opened at arrival time - * @param[in] veh The vehicle for which the information shall be computed - * @param[in] bestLaneConts The lanes the vehicle will use in future - * @return - */ - std::pair getLeaderOnConsecutive(double dist, double seen, - double speed, const MSVehicle& veh, const std::vector& bestLaneConts) const; - - /// @brief Returns the immediate leaders and the distance to them (as getLeaderOnConsecutive but for the sublane case) - void getLeadersOnConsecutive(double dist, double seen, double speed, const MSVehicle* ego, - const std::vector& bestLaneConts, MSLeaderDistanceInfo& result) const; - - /** @brief Returns the most dangerous leader and the distance to him - * - * Goes along the vehicle's estimated used lanes (bestLaneConts). For each link, - * it is determined whether the ego vehicle will pass it. If so, the subsequent lane - * is investigated. Check all lanes up to the stopping distance of ego. - * Return the leader vehicle (and the gap) which puts the biggest speed constraint on ego. - * - * If no leading vehicle was found, <0, -1> is returned. - * - * Pretty slow, as it has to go along lanes. - * - * @param[in] dist The distance to investigate - * @param[in] seen The already seen place (normally the place in front on own lane) - * @param[in] speed The speed of the vehicle used for determining whether a subsequent link will be opened at arrival time - * @param[in] veh The (ego) vehicle for which the information shall be computed - * @return - */ - std::pair getCriticalLeader(double dist, double seen, double speed, const MSVehicle& veh) const; - - /* @brief return the partial vehicle closest behind ego or 0 - * if no such vehicle exists */ - MSVehicle* getPartialBehind(const MSVehicle* ego) const; - - /// @brief get all vehicles that are inlapping from consecutive edges - MSLeaderInfo getPartialBeyond() const; - - /// @brief Returns all vehicles closer than downstreamDist along the along the road network starting on the given - /// position. Predecessor lanes are searched upstream for the given upstreamDistance - /// @note Re-implementation of the corresponding method in MSDevice_SSM, which cannot be easily adapted, as it gathers - /// additional information for conflict lanes, etc. - /// @param[in] lanes - sequence of lanes to search along - /// @param[in] startPos - start position of the search on the first lane - /// @param[in] downstreamDist - distance to search downstream - /// @param[in] upstreamDist - distance to search upstream - /// @param[in/out] checkedLanes - lanes, which were already scanned (current lane is added, if not present, - /// otherwise the scan is aborted; TODO: this may disregard unscanned parts of the lane in specific circular set ups.) - /// @return vehs - List of vehicles found - std::set getSurroundingVehicles(double startPos, double downstreamDist, double upstreamDist, std::shared_ptr checkedLanes) const; - - /// @brief Returns all vehicles on the lane overlapping with the interval [a,b] - /// @note Does not consider vehs with front on subsequent lanes - std::set getVehiclesInRange(const double a, const double b) const; - - - /// @brief Returns all upcoming junctions within given range along the given (non-internal) continuation lanes measured from given position - std::vector getUpcomingJunctions(double pos, double range, const std::vector& contLanes) const; - /// @brief Returns all upcoming links within given range along the given (non-internal) continuation lanes measured from given position - std::vector getUpcomingLinks(double pos, double range, const std::vector& contLanes) const; - - /** @brief get the most likely precedecessor lane (sorted using by_connections_to_sorter). - * The result is cached in myLogicalPredecessorLane - */ - MSLane* getLogicalPredecessorLane() const; - - /** @brief get normal lane leading to this internal lane, for normal lanes, - * the lane itself is returned - */ - const MSLane* getNormalPredecessorLane() const; - - /** @brief return the (first) predecessor lane from the given edge - */ - MSLane* getLogicalPredecessorLane(const MSEdge& fromEdge) const; - - - /** Return the main predecessor lane for the current. - * If there are several incoming lanes, the first attempt is to return the priorized. - * If this does not yield an unambiguous lane, the one with the least angle difference - * to the current is selected. - */ - MSLane* getCanonicalPredecessorLane() const; - - - /** Return the main successor lane for the current. - * If there are several outgoing lanes, the first attempt is to return the priorized. - * If this does not yield an unambiguous lane, the one with the least angle difference - * to the current is selected. - */ - MSLane* getCanonicalSuccessorLane() const; - - /// @brief get the state of the link from the logical predecessor to this lane - LinkState getIncomingLinkState() const; - - /// @brief get the list of outgoing lanes - const std::vector > getOutgoingViaLanes() const; - - /// @brief get the list of all direct (disregarding internal predecessors) non-internal predecessor lanes of this lane - std::vector getNormalIncomingLanes() const; - - /// @name Current state retrieval - //@{ - - /** @brief Returns the mean speed on this lane - * @return The average speed of vehicles during the last step; default speed if no vehicle was on this lane - */ - double getMeanSpeed() const; - - /// @brief get the mean speed of all bicycles on this lane - double getMeanSpeedBike() const; - - /** @brief Returns the overall waiting time on this lane - * @return The sum of the waiting time of all vehicles during the last step; - */ - double getWaitingSeconds() const; - - - /** @brief Returns the brutto (including minGaps) occupancy of this lane during the last step - * @return The occupancy during the last step - */ - double getBruttoOccupancy() const; - - - /** @brief Returns the netto (excluding minGaps) occupancy of this lane during the last step (including minGaps) - * @return The occupancy during the last step - */ - double getNettoOccupancy() const; - - - /** @brief Returns the sum of lengths of vehicles, including their minGaps, which were on the lane during the last step - * @return The sum of vehicle lengths of vehicles in the last step - */ - inline double getBruttoVehLenSum() const { - return myBruttoVehicleLengthSum; - } - - - /** @brief Returns the sum of last step CO2 emissions - * @return CO2 emissions of vehicles on this lane during the last step - */ - double getCO2Emissions() const; - - - /** @brief Returns the sum of last step CO emissions - * @return CO emissions of vehicles on this lane during the last step - */ - double getCOEmissions() const; - - - /** @brief Returns the sum of last step PMx emissions - * @return PMx emissions of vehicles on this lane during the last step - */ - double getPMxEmissions() const; - - - /** @brief Returns the sum of last step NOx emissions - * @return NOx emissions of vehicles on this lane during the last step - */ - double getNOxEmissions() const; - - - /** @brief Returns the sum of last step HC emissions - * @return HC emissions of vehicles on this lane during the last step - */ - double getHCEmissions() const; - - - /** @brief Returns the sum of last step fuel consumption - * @return fuel consumption of vehicles on this lane during the last step - */ - double getFuelConsumption() const; - - - /** @brief Returns the sum of last step electricity consumption - * @return electricity consumption of vehicles on this lane during the last step - */ - double getElectricityConsumption() const; - - - /** @brief Returns the sum of last step noise emissions - * @return noise emissions of vehicles on this lane during the last step - */ - double getHarmonoise_NoiseEmissions() const; - /// @} - - void setRightSideOnEdge(double value, int rightmostSublane) { - myRightSideOnEdge = value; - myRightmostSublane = rightmostSublane; - } - - /// @brief initialized vClass-specific speed limits - void initRestrictions(); - - void checkBufferType(); - - double getRightSideOnEdge() const { - return myRightSideOnEdge; - } - - int getRightmostSublane() const { - return myRightmostSublane; - } - - double getCenterOnEdge() const { - return myRightSideOnEdge + 0.5 * myWidth; - } - - /// @brief sorts myPartialVehicles - void sortPartialVehicles(); - - /// @brief sorts myManeuverReservations - void sortManeuverReservations(); - - /// @brief return the opposite direction lane for lane changing or 0 - MSLane* getOpposite() const; - - /// @brief return the corresponding position on the opposite lane - double getOppositePos(double pos) const; - - /* @brief find leader for a vehicle depending on the relative driving direction - * @param[in] ego The ego vehicle - * @param[in] dist The look-ahead distance when looking at consecutive lanes - * @param[in] oppositeDir Whether the lane has the opposite driving direction of ego - * @return the leader vehicle and it's gap to ego - */ - std::pair getOppositeLeader(const MSVehicle* ego, double dist, bool oppositeDir) const; - - /* @brief find follower for a vehicle that is located on the opposite of this lane - * @param[in] ego The ego vehicle - * @return the follower vehicle and it's gap to ego - */ - std::pair getOppositeFollower(const MSVehicle* ego) const; - - - /** @brief Find follower vehicle for the given ego vehicle (which may be on the opposite direction lane) - * @param[in] ego The ego vehicle - * @param[in] egoPos The ego position mapped to the current lane - * @param[in] dist The look-back distance when looking at consecutive lanes - * @param[in] ignoreMinorLinks Whether backward search should stop at minor links - * @return the follower vehicle and it's gap to ego - */ - std::pair getFollower(const MSVehicle* ego, double egoPos, double dist, bool ignoreMinorLinks) const; - - - ///@brief add parking vehicle. This should only used during state loading - void addParking(MSVehicle* veh); - - ///@brief remove parking vehicle. This must be syncrhonized when running with GUI - virtual void removeParking(MSVehicle* veh); - - /// @brief retrieve the parking vehicles (see GUIParkingArea) - const std::set& getParkingVehicles() const { - return myParkingVehicles; - } - - /// @brief whether this lane is selected in the GUI - virtual bool isSelected() const { - return false; - } - - /// @brief retrieve bidirectional lane or nullptr - MSLane* getBidiLane() const; - - /// @brief whether this lane must check for junction collisions - bool mustCheckJunctionCollisions() const; - -#ifdef HAVE_FOX - FXWorkerThread::Task* getPlanMoveTask(const SUMOTime time) { - mySimulationTask.init(&MSLane::planMovements, time); - return &mySimulationTask; - } - - FXWorkerThread::Task* getExecuteMoveTask(const SUMOTime time) { - mySimulationTask.init(&MSLane::executeMovements, time); - return &mySimulationTask; - } - - FXWorkerThread::Task* getLaneChangeTask(const SUMOTime time) { - mySimulationTask.init(&MSLane::changeLanes, time); - return &mySimulationTask; - } -#endif - - void changeLanes(const SUMOTime time); - - /// @name State saving/loading - /// @{ - - /** @brief Saves the state of this lane into the given stream - * - * Basically, a list of vehicle ids - * - * @param[in, filled] out The (possibly binary) device to write the state into - * @todo What about throwing an IOError? - */ - void saveState(OutputDevice& out); - - /** @brief Remove all vehicles before quick-loading state */ - void clearState(); - - /** @brief Loads the state of this segment with the given parameters - * - * This method is called for every internal que the segment has. - * Every vehicle is retrieved from the given MSVehicleControl and added to this - * lane. - * - * @param[in] vehIDs The vehicle ids for the current que - * @param[in] vc The vehicle control to retrieve references vehicles from - * @todo What about throwing an IOError? - * @todo What about throwing an error if something else fails (a vehicle can not be referenced)? - */ - void loadState(const std::vector& vehIDs, MSVehicleControl& vc); - /// @} - - - /** @brief Callback for visiting the lane when traversing an RTree - * - * This is used in the TraCIServerAPI_Lane for context subscriptions. - * - * @param[in] cont The context doing all the work - * @see libsumo::Helper::LaneStoringVisitor::add - */ - void visit(const LaneStoringVisitor& cont) const { - cont.add(this); - } - - /// @brief whether the lane has pedestrians on it - bool hasPedestrians() const; - - /// This is just a wrapper around MSPModel::nextBlocking. You should always check using hasPedestrians before calling this method. - std::pair nextBlocking(double minPos, double minRight, double maxLeft, double stopTime = 0) const; - - static void initCollisionOptions(const OptionsCont& oc); - - static bool teleportOnCollision() { - return myCollisionAction == COLLISION_ACTION_TELEPORT; - } - - static CollisionAction getCollisionAction() { - return myCollisionAction; - } - - static const long CHANGE_PERMISSIONS_PERMANENT = 0; - static const long CHANGE_PERMISSIONS_GUI = 1; - -protected: - /// moves myTmpVehicles int myVehicles after a lane change procedure - virtual void swapAfterLaneChange(SUMOTime t); - - /** @brief Inserts the vehicle into this lane, and informs it about entering the network - * - * Calls the vehicles enterLaneAtInsertion function, - * updates statistics and modifies the active state as needed - * @param[in] veh The vehicle to be incorporated - * @param[in] pos The position of the vehicle - * @param[in] speed The speed of the vehicle - * @param[in] posLat The lateral position of the vehicle - * @param[in] at - * @param[in] notification The cause of insertion (i.e. departure, teleport, parking) defaults to departure - */ - virtual void incorporateVehicle(MSVehicle* veh, double pos, double speed, double posLat, - const MSLane::VehCont::iterator& at, - MSMoveReminder::Notification notification = MSMoveReminder::NOTIFICATION_DEPARTED); - - /// @brief detect whether a vehicle collids with pedestrians on the junction - void detectPedestrianJunctionCollision(const MSVehicle* collider, const PositionVector& colliderBoundary, const MSLane* foeLane, - SUMOTime timestep, const std::string& stage); - - /// @brief detect whether there is a collision between the two vehicles - bool detectCollisionBetween(SUMOTime timestep, const std::string& stage, MSVehicle* collider, MSVehicle* victim, - std::set& toRemove, - std::set& toTeleport) const; - - /// @brief take action upon collision - void handleCollisionBetween(SUMOTime timestep, const std::string& stage, MSVehicle* collider, MSVehicle* victim, - double gap, double latGap, - std::set& toRemove, - std::set& toTeleport) const; - - /// @brief compute maximum braking distance on this lane - double getMaximumBrakeDist() const; - - /* @brief determine depart speed and whether it may be patched - * @param[in] veh The departing vehicle - * @param[out] whether the speed may be patched to account for safety - * @return the depart speed - */ - double getDepartSpeed(const MSVehicle& veh, bool& patchSpeed); - - /* @brief determine the lateral depart position - * @param[in] veh The departing vehicle - * @return the lateral depart position - */ - double getDepartPosLat(const MSVehicle& veh); - - /** @brief return the maximum safe speed for insertion behind leaders - * (a negative value indicates that safe insertion is impossible) */ - double safeInsertionSpeed(const MSVehicle* veh, double seen, const MSLeaderInfo& leaders, double speed); - - /// @brief check whether pedestrians on this lane interfere with vehicle insertion - bool checkForPedestrians(const MSVehicle* aVehicle, double& speed, double& dist, double pos, bool patchSpeed) const; - - /// Unique numerical ID (set on reading by netload) - int myNumericalID; - - /// The shape of the lane - PositionVector myShape; - - /// The lane index - int myIndex; - - /** @brief The lane's vehicles. - This container holds all vehicles that have their front (longitudinally) - and their center (laterally) on this lane. - These are the vehicles that this lane is 'responsibly' for (i.e. when executing movements) - - The entering vehicles are inserted at the front - of this container and the leaving ones leave from the back, e.g. the - vehicle in front of the junction (often called first) is - myVehicles.back() (if it exists). And if it is an iterator at a - vehicle, ++it points to the vehicle in front. This is the interaction - vehicle. */ - VehCont myVehicles; - - /** @brief The lane's partial vehicles. - This container holds all vehicles that are partially on this lane but which are - in myVehicles of another lane. - Reasons for partial occupancies include the following - - the back is still on this lane during regular movement - - the vehicle is performing a continuous lane-change maneuver - - sub-lane simulation where vehicles can freely move laterally among the lanes of an edge - - The entering vehicles are inserted at the front - of this container and the leaving ones leave from the back. */ - VehCont myPartialVehicles; - - /** @brief Container for lane-changing vehicles. After completion of lane-change- - process, the containers will be swapped with myVehicles. */ - VehCont myTmpVehicles; - - /** @brief Buffer for vehicles that moved from their previous lane onto this one. - * Integrated after all vehicles executed their moves*/ - FXSynchQue > myVehBuffer; - - /** @brief The vehicles which registered maneuvering into the lane within their current action step. - * This is currently only relevant for sublane simulation, since continuous lanechanging - * uses the partial vehicle mechanism. - * - * The entering vehicles are inserted at the front - * of this container and the leaving ones leave from the back. */ - VehCont myManeuverReservations; - - /* @brief list of vehicles that are parking near this lane - * (not necessarily on the road but having reached their stop on this lane) - * */ - std::set myParkingVehicles; - - /// Lane length [m] - double myLength; - - /// Lane width [m] - const double myWidth; - - /// Lane's vClass specific stop offset [m]. The map is either of length 0, which means no - /// special stopOffset was set, or of length 1, where the key is a bitset representing a subset - /// of the SUMOVehicleClass Enum and the value is the offset in meters. - std::map myStopOffsets; - - /// The lane's edge, for routing only. - MSEdge* const myEdge; - - /// Lane-wide speedlimit [m/s] - double myMaxSpeed; - - /// The vClass permissions for this lane - SVCPermissions myPermissions; - - /// The original vClass permissions for this lane (before temporary modifications) - SVCPermissions myOriginalPermissions; - - /// The vClass speed restrictions for this lane - const std::map* myRestrictions; - - /// All direct predecessor lanes - std::vector myIncomingLanes; - - /// - mutable MSLane* myLogicalPredecessorLane; - - /// Similar to LogicalPredecessorLane, @see getCanonicalPredecessorLane() - mutable MSLane* myCanonicalPredecessorLane; - - /// Main successor lane, @see getCanonicalSuccessorLane() - mutable MSLane* myCanonicalSuccessorLane; - - /// @brief The current length of all vehicles on this lane, including their minGaps - double myBruttoVehicleLengthSum; - - /// @brief The current length of all vehicles on this lane, excluding their minGaps - double myNettoVehicleLengthSum; - - /// @brief The length of all vehicles that have left this lane in the current step (this lane, including their minGaps) - double myBruttoVehicleLengthSumToRemove; - - /// @brief The length of all vehicles that have left this lane in the current step (this lane, excluding their minGaps) - double myNettoVehicleLengthSumToRemove; - - /** The lane's Links to it's succeeding lanes and the default - right-of-way rule, i.e. blocked or not blocked. */ - MSLinkCont myLinks; - - /// All direct internal and direct (disregarding internal predecessors) non-internal predecessor lanes of this lane - std::map > myApproachingLanes; - - /// @brief leaders on all sublanes as seen by approaching vehicles (cached) - mutable MSLeaderInfo myLeaderInfo; - /// @brief followers on all sublanes as seen by vehicles on consecutive lanes (cached) - mutable MSLeaderInfo myFollowerInfo; - - /// @brief time step for which myLeaderInfo was last updated - mutable SUMOTime myLeaderInfoTime; - /// @brief time step for which myFollowerInfo was last updated - mutable SUMOTime myFollowerInfoTime; - - /// @brief precomputed myShape.length / myLength - const double myLengthGeometryFactor; - - /// @brief whether this lane is an acceleration lane - const bool myIsRampAccel; - - /// @brief the type of this lane - const std::string myLaneType; - - /// @brief the combined width of all lanes with lower index on myEdge - double myRightSideOnEdge; - /// @brief the index of the rightmost sublane of this lane on myEdge - int myRightmostSublane; - - /// @brief whether a collision check is currently needed - bool myNeedsCollisionCheck; - - // @brief the ids of neighboring lanes - std::vector myNeighs; - - // @brief transient changes in permissions - std::map myPermissionChanges; - - // @brief index of the associated thread-rng - int myRNGIndex; - - /// definition of the static dictionary type - typedef std::map< std::string, MSLane* > DictType; - - /// Static dictionary to associate string-ids with objects. - static DictType myDict; - - static std::vector myRNGs; - -private: - /// @brief This lane's move reminder - std::vector< MSMoveReminder* > myMoveReminders; - - /// @brief the action to take on collisions - static CollisionAction myCollisionAction; - static bool myCheckJunctionCollisions; - static SUMOTime myCollisionStopTime; - static double myCollisionMinGapFactor; - static bool myExtrapolateSubstepDepart; - - /** - * @class vehicle_position_sorter - * @brief Sorts vehicles by their position (descending) - */ - class vehicle_position_sorter { - public: - /// @brief Constructor - explicit vehicle_position_sorter(const MSLane* lane) : - myLane(lane) { - } - - - /** @brief Comparing operator - * @param[in] v1 First vehicle to compare - * @param[in] v2 Second vehicle to compare - * @return Whether the first vehicle is further on the lane than the second - */ - int operator()(MSVehicle* v1, MSVehicle* v2) const; - - const MSLane* myLane; - - }; - - /** - * @class vehicle_reverse_position_sorter - * @brief Sorts vehicles by their position (ascending) - */ - class vehicle_natural_position_sorter { - public: - /// @brief Constructor - explicit vehicle_natural_position_sorter(const MSLane* lane) : - myLane(lane) { - } - - - /** @brief Comparing operator - * @param[in] v1 First vehicle to compare - * @param[in] v2 Second vehicle to compare - * @return Whether the first vehicle is further on the lane than the second - */ - int operator()(MSVehicle* v1, MSVehicle* v2) const; - - const MSLane* myLane; - - }; - - /** @class by_connections_to_sorter - * @brief Sorts edges by their angle relative to the given edge (straight comes first) - * - */ - class by_connections_to_sorter { - public: - /// @brief constructor - explicit by_connections_to_sorter(const MSEdge* const e); - - /// @brief comparing operator - int operator()(const MSEdge* const e1, const MSEdge* const e2) const; - - private: - by_connections_to_sorter& operator=(const by_connections_to_sorter&); // just to avoid a compiler warning - private: - const MSEdge* const myEdge; - double myLaneDir; - }; - - - - /** @class incoming_lane_priority_sorter - * @brief Sorts lanes (IncomingLaneInfos) by their priority or, if this doesn't apply, - * wrt. the angle difference magnitude relative to the target lane's angle (straight comes first) - */ - class incoming_lane_priority_sorter { - public: - /// @brief constructor - explicit incoming_lane_priority_sorter(const MSLane* targetLane); - - /// @brief comparing operator - int operator()(const IncomingLaneInfo& lane1, const IncomingLaneInfo& lane2) const; - - private: - incoming_lane_priority_sorter& operator=(const incoming_lane_priority_sorter&); // just to avoid a compiler warning - private: - const MSLane* const myLane; - double myLaneDir; - }; - - - /** @class outgoing_lane_priority_sorter - * @brief Sorts lanes (their origin link) by the priority of their noninternal target edges or, if this doesn't yield an unambiguous result, - * wrt. the angle difference magnitude relative to the target lane's angle (straight comes first) - */ - class outgoing_lane_priority_sorter { - public: - /// @brief constructor - explicit outgoing_lane_priority_sorter(const MSLane* sourceLane); - - /// @brief comparing operator - int operator()(const MSLink* link1, const MSLink* link2) const; - - private: - outgoing_lane_priority_sorter& operator=(const outgoing_lane_priority_sorter&); // just to avoid a compiler warning - private: - const MSLane* const myLane; - double myLaneDir; - }; - - /** - * @class edge_finder - */ - class edge_finder { - public: - edge_finder(MSEdge* e) : myEdge(e) {} - bool operator()(const IncomingLaneInfo& ili) const { - return &(ili.lane->getEdge()) == myEdge; - } - private: - edge_finder& operator=(const edge_finder&); // just to avoid a compiler warning - private: - const MSEdge* const myEdge; - }; - -#ifdef HAVE_FOX - /// Type of the function that is called for the simulation stage (e.g. planMovements). - typedef void(MSLane::*Operation)(const SUMOTime); - - /** - * @class SimulationTask - * @brief the routing task which mainly calls reroute of the vehicle - */ - class SimulationTask : public FXWorkerThread::Task { - public: - SimulationTask(MSLane& l, const SUMOTime time) - : myLane(l), myTime(time) {} - void init(Operation operation, const SUMOTime time) { - myOperation = operation; - myTime = time; - } - void run(FXWorkerThread* /*context*/) { - try { - (myLane.*(myOperation))(myTime); - } catch (ProcessError& e) { - WRITE_ERROR(e.what()); - } - } - private: - Operation myOperation = nullptr; - MSLane& myLane; - SUMOTime myTime; - private: - /// @brief Invalidated assignment operator. - SimulationTask& operator=(const SimulationTask&) = delete; - }; - - SimulationTask mySimulationTask; - /// @brief Mutex for access to the cached leader info value - mutable FXMutex myLeaderInfoMutex; - /// @brief Mutex for access to the cached follower info value - mutable FXMutex myFollowerInfoMutex; - /// @brief Mutex for access to the cached follower info value - mutable FXMutex myPartialOccupatorMutex; -#endif -private: - /// @brief invalidated copy constructor - MSLane(const MSLane&); - - /// @brief invalidated assignment operator - MSLane& operator=(const MSLane&); - - -}; diff --git a/Util/OSM2ODR/src/microsim/MSLeaderInfo.h b/Util/OSM2ODR/src/microsim/MSLeaderInfo.h deleted file mode 100644 index e6d450040..000000000 --- a/Util/OSM2ODR/src/microsim/MSLeaderInfo.h +++ /dev/null @@ -1,225 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2002-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file MSLeaderInfo.h -/// @author Jakob Erdmann -/// @date Oct 2015 -/// -// Information about vehicles ahead (may be multiple vehicles if -// lateral-resolution is active) -/****************************************************************************/ -#pragma once -#include - -#include -#include - - -// =========================================================================== -// class declarations -// =========================================================================== -class MSVehicle; -class MSLane; - - -// =========================================================================== -// types definitions -// =========================================================================== -typedef std::pair CLeaderDist; -typedef std::pair LeaderDist; - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class MSLeaderInfo - */ -class MSLeaderInfo { -public: - /// Constructor - MSLeaderInfo(const MSLane* lane, const MSVehicle* ego = 0, double latOffset = 0); - - /// Destructor - virtual ~MSLeaderInfo(); - - /* @brief adds this vehicle as a leader in the appropriate sublanes - * @param[in] veh The vehicle to add - * @param[in] beyond Whether the vehicle is beyond the existing leaders (and thus may be shadowed by them) - * @param[in] latOffset The lateral offset that must be added to the position of veh - * @return The number of free sublanes - */ - virtual int addLeader(const MSVehicle* veh, bool beyond, double latOffset = 0); - - /// @brief discard all information - virtual void clear(); - - /* @brief returns sublanes occupied by veh - * @param[in] veh The vehicle to check - * @param[in] latOffset The offset value to add to the vehicle position - * @param[out] rightmost The rightmost sublane occupied by veh - * @param[out] leftmost The rightmost sublane occupied by veh - */ - void getSubLanes(const MSVehicle* veh, double latOffset, int& rightmost, int& leftmost) const; - - /* @brief returns the sublane boundaries of the ith sublane - * @param[in] sublane The sublane to check - * @param[in] latOffset The offset value to add to the result - * @param[out] rightSide The right border of the given sublane - * @param[out] leftSide The left border of the given sublane - */ - void getSublaneBorders(int sublane, double latOffset, double& rightSide, double& leftSide) const; - - /// @brief return the vehicle for the given sublane - const MSVehicle* operator[](int sublane) const; - - int numSublanes() const { - return (int)myVehicles.size(); - } - - int numFreeSublanes() const { - return myFreeSublanes; - } - - bool hasVehicles() const { - return myHasVehicles; - } - - const std::vector& getVehicles() const { - return myVehicles; - } - - /// @brief whether a stopped vehicle is leader - bool hasStoppedVehicle() const; - - /// @brief print a debugging representation - virtual std::string toString() const; - -protected: - - /// @brief the width of the lane to which this instance applies - // @note: not const to simplify assignment - double myWidth; - - std::vector myVehicles; - - /// @brief the number of free sublanes - // if an ego vehicle is given in the constructor, the number of free - // sublanes of those covered by ego - int myFreeSublanes; - - /// @brief borders of the ego vehicle for filtering of free sublanes - int egoRightMost; - int egoLeftMost; - - bool myHasVehicles; - -}; - - -/// @brief saves leader/follower vehicles and their distances relative to an ego vehicle -class MSLeaderDistanceInfo : public MSLeaderInfo { -public: - /// Constructor - MSLeaderDistanceInfo(const MSLane* lane, const MSVehicle* ego, double latOffset); - - /// @brief Construct for the non-sublane-case - MSLeaderDistanceInfo(const CLeaderDist& cLeaderDist, const MSLane* dummy); - - /// Destructor - virtual ~MSLeaderDistanceInfo(); - - /* @brief adds this vehicle as a leader in the appropriate sublanes - * @param[in] veh The vehicle to add - * @param[in] gap The gap between the egoFront+minGap to the back of veh - * or from the back of ego to the front+minGap of veh - * @param[in] latOffset The lateral offset that must be added to the position of veh - * @param[in] sublane The single sublane to which this leader shall be checked (-1 means: check for all) - * @return The number of free sublanes - */ - virtual int addLeader(const MSVehicle* veh, double gap, double latOffset = 0, int sublane = -1); - - virtual int addLeader(const MSVehicle* veh, bool beyond, double latOffset = 0) { - UNUSED_PARAMETER(veh); - UNUSED_PARAMETER(beyond); - UNUSED_PARAMETER(latOffset); - throw ProcessError("Method not supported"); - } - - /// @brief discard all information - virtual void clear(); - - /// @brief return the vehicle and its distance for the given sublane - CLeaderDist operator[](int sublane) const; - - /// @brief print a debugging representation - virtual std::string toString() const; - - const std::vector& getDistances() const { - return myDistances; - } - -protected: - - std::vector myDistances; - -}; - - -/* @brief saves follower vehicles and their distances as well as their required gap relative to an ego vehicle - * when adding new followers, the one with the largest required gap is recored - * (rather than the one with the smallest gap) */ -class MSCriticalFollowerDistanceInfo : public MSLeaderDistanceInfo { -public: - /// Constructor - MSCriticalFollowerDistanceInfo(const MSLane* lane, const MSVehicle* ego, double latOffset); - - /// Destructor - virtual ~MSCriticalFollowerDistanceInfo(); - - /* @brief adds this vehicle as a follower in the appropriate sublanes - * @param[in] veh The vehicle to add - * @param[in] ego The vehicle which is being followed - * @param[in] gap The distance from the back of ego to the follower - * @param[in] latOffset The lateral offset that must be added to the position of veh - * @param[in] sublane The single sublane to which this leader shall be checked (-1 means: check for all) - * @return The number of free sublanes - */ - int addFollower(const MSVehicle* veh, const MSVehicle* ego, double gap, double latOffset = 0, int sublane = -1); - - virtual int addLeader(const MSVehicle* veh, double gap, double latOffset = 0, int sublane = -1) { - UNUSED_PARAMETER(veh); - UNUSED_PARAMETER(gap); - UNUSED_PARAMETER(latOffset); - UNUSED_PARAMETER(sublane); - throw ProcessError("Method not supported"); - } - - virtual int addLeader(const MSVehicle* veh, bool beyond, double latOffset = 0) { - UNUSED_PARAMETER(veh); - UNUSED_PARAMETER(beyond); - UNUSED_PARAMETER(latOffset); - throw ProcessError("Method not supported"); - } - - /// @brief discard all information - void clear(); - - /// @brief print a debugging representation - std::string toString() const; - -protected: - - // @brief the differences between requriedGap and actual gap for each of the followers - std::vector myMissingGaps; - -}; diff --git a/Util/OSM2ODR/src/microsim/MSLink.h b/Util/OSM2ODR/src/microsim/MSLink.h deleted file mode 100644 index 6260fdfa4..000000000 --- a/Util/OSM2ODR/src/microsim/MSLink.h +++ /dev/null @@ -1,682 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2002-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file MSLink.h -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date Sept 2002 -/// -// A connnection between lanes -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include -#include -#include -#include - - -// =========================================================================== -// class declarations -// =========================================================================== -class MSLane; -class MSJunction; -class MSVehicle; -class MSPerson; -class OutputDevice; -class MSTrafficLightLogic; - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class MSLinks - * @brief A connnection between lanes - * - * A link is basically a connection between two lanes, stored within the - * originating (the one that is being left) lane and pointing to the - * approached lane. When using inner-junction simulation, additionally - * a "via-lane" is stored, the one that is used to cross the junction - * and which represents the links shape. - * - * Because right-of-way rules are controlled by the junctions, the link - * stores the information about where to write information about approaching - * vehicles (the "request") and where to get the information whether the - * vehicle really may drive (the "respond"). - * - * Because a link is a connection over a junction, it basically also has a - * length. This length is needed to assure that vehicles have the correct halting - * distance before approaching the link. In the case of using internal lanes, - * the link's length is 0. - */ -class MSLink { -public: - - // distance to link in m below which adaptation for zipper-merging should take place - static const double ZIPPER_ADAPT_DIST; - - struct LinkLeader { - LinkLeader(MSVehicle* _veh, double _gap, double _distToCrossing, bool _fromLeft = true) : - vehAndGap(std::make_pair(_veh, _gap)), - distToCrossing(_distToCrossing), - fromLeft(_fromLeft) { - } - - std::pair vehAndGap; - double distToCrossing; - bool fromLeft; - }; - - typedef std::vector LinkLeaders; - - /** @struct ApproachingVehicleInformation - * @brief A structure holding the information about vehicles approaching a link - */ - struct ApproachingVehicleInformation { - /** @brief Constructor - * @param[in] waitingTime The time during which the vehicle is waiting at this link - * this needs to be placed here because MSVehicle::myWaitingTime is updated in between - * calls to opened() causing order dependencies - **/ - ApproachingVehicleInformation(const SUMOTime _arrivalTime, const SUMOTime _leavingTime, - const double _arrivalSpeed, const double _leaveSpeed, - const bool _willPass, - const SUMOTime _arrivalTimeBraking, - const double _arrivalSpeedBraking, - const SUMOTime _waitingTime, - const double _dist, - const double _speed - ) : - arrivalTime(_arrivalTime), leavingTime(_leavingTime), - arrivalSpeed(_arrivalSpeed), leaveSpeed(_leaveSpeed), - willPass(_willPass), - arrivalTimeBraking(_arrivalTimeBraking), - arrivalSpeedBraking(_arrivalSpeedBraking), - waitingTime(_waitingTime), - dist(_dist), - speed(_speed) { - } - - /// @brief The time the vehicle's front arrives at the link - const SUMOTime arrivalTime; - /// @brief The estimated time at which the vehicle leaves the link - const SUMOTime leavingTime; - /// @brief The estimated speed with which the vehicle arrives at the link (for headway computation) - const double arrivalSpeed; - /// @brief The estimated speed with which the vehicle leaves the link (for headway computation) - const double leaveSpeed; - /// @brief Whether the vehicle wants to pass the link (@todo: check semantics) - const bool willPass; - /// @brief The time the vehicle's front arrives at the link if it starts braking - const SUMOTime arrivalTimeBraking; - /// @brief The estimated speed with which the vehicle arrives at the link if it starts braking(for headway computation) - const double arrivalSpeedBraking; - /// @brief The waiting duration at the current link - const SUMOTime waitingTime; - /// @brief The distance up to the current link - const double dist; - /// @brief The current speed - const double speed; - - private: - /// invalidated assignment operator - ApproachingVehicleInformation& operator=(const ApproachingVehicleInformation& s); - - }; - - typedef std::map ApproachInfos; - typedef std::vector BlockingFoes; - - /** @brief Constructor for simulation which uses internal lanes - * - * @param[in] succLane The lane approached by this link - * @param[in] via The lane to use within the junction - * @param[in] dir The direction of this link - * @param[in] state The state of this link - * @param[in] length The length of this link - */ - MSLink(MSLane* predLane, MSLane* succLane, MSLane* via, LinkDirection dir, LinkState state, double length, double foeVisibilityDistance, bool keepClear, MSTrafficLightLogic* logic, int tlLinkIdx); - - - /// @brief Destructor - ~MSLink(); - - - /** @brief Sets the request information - * - * Because traffic lights and junction logics are loaded after links, - * we have to assign the information about the right-of-way - * requests and responses after the initialisation. - * @todo Unsecure! - */ - void setRequestInformation(int index, bool hasFoes, bool isCont, - const std::vector& foeLinks, const std::vector& foeLanes, - MSLane* internalLaneBefore = 0); - - /// @brief add walkingarea as foe (when entering the junction) - void addWalkingAreaFoe(const MSLane* lane) { - myWalkingAreaFoe = lane; - } - - /// @brief add walkingarea as foe (when leaving the junction) - void addWalkingAreaFoeExit(const MSLane* lane) { - myWalkingAreaFoeExit = lane; - } - - /// @brief get walkingarea as foes - const MSLane* getWalkingAreaFoe() { - return myWalkingAreaFoe; - } - const MSLane* getWalkingAreaFoeExit() { - return myWalkingAreaFoeExit; - } - - /** @brief Sets the information about an approaching vehicle - * - * The information is stored in myApproachingVehicles. - */ - void setApproaching(const SUMOVehicle* approaching, const SUMOTime arrivalTime, - const double arrivalSpeed, const double leaveSpeed, const bool setRequest, - const SUMOTime arrivalTimeBraking, const double arrivalSpeedBraking, - const SUMOTime waitingTime, double dist); - - /** @brief Sets the information about an approaching vehicle */ - void setApproaching(const SUMOVehicle* approaching, ApproachingVehicleInformation ai); - - /// @brief removes the vehicle from myApproachingVehicles - void removeApproaching(const SUMOVehicle* veh); - - void addBlockedLink(MSLink* link); - - /* @brief return information about this vehicle if it is registered as - * approaching (dummy values otherwise) - * @note used for visualisation of link items */ - ApproachingVehicleInformation getApproaching(const SUMOVehicle* veh) const; - - /// @brief return all approaching vehicles - const ApproachInfos& getApproaching() const { - return myApproachingVehicles; - } - - /** @brief Remove all approaching vehicles before quick-loading state */ - void clearState(); - - /** @brief Returns the information whether the link may be passed - * - * Valid after the junctions have set their reponds - * - * @param[in] collectFoes If a vector is passed, all blocking foes are collected and inserted into this vector - * @return Whether this link may be passed. - */ - bool opened(SUMOTime arrivalTime, double arrivalSpeed, double leaveSpeed, double vehicleLength, - double impatience, double decel, SUMOTime waitingTime, - double posLat = 0, - BlockingFoes* collectFoes = nullptr, - bool ignoreRed = false, - const SUMOVehicle* ego = nullptr) const; - - /** @brief Returns the information whether this link is blocked - * Valid after the vehicles have set their requests - * @param[in] arrivalTime The arrivalTime of the vehicle who checks for an approaching foe - * @param[in] leaveTime The leaveTime of the vehicle who checks for an approaching foe - * @param[in] arrivalSpeed The speed with which the checking vehicle plans to arrive at the link - * @param[in] leaveSpeed The speed with which the checking vehicle plans to leave the link - * @param[in] sameTargetLane Whether the link that calls this method has the same target lane as this link - * @param[in] impatience The impatience of the checking vehicle - * @param[in] decel The maximum deceleration of the checking vehicle - * @param[in] waitingTime The waiting time of the checking vehicle - * @param[in] collectFoes If a vector is passed the return value is always False, instead all blocking foes are collected and inserted into this vector - * @return Whether this link is blocked - * @note Since this needs to be called without a SUMOVehicle (TraCI), we cannot simply pass the checking vehicle itself - **/ - bool blockedAtTime(SUMOTime arrivalTime, SUMOTime leaveTime, double arrivalSpeed, double leaveSpeed, - bool sameTargetLane, double impatience, double decel, SUMOTime waitingTime, - BlockingFoes* collectFoes = nullptr, const SUMOVehicle* ego = nullptr) const; - - - bool isBlockingAnyone() const { - return myApproachingVehicles.size() != 0; - } - - bool willHaveBlockedFoe() const; - - - - /** @brief Returns the information whether a vehicle is approaching on one of the link's foe streams - * - * Valid after the vehicles have set their requests - * @param[in] arrivalTime The arrivalTime of the vehicle who checks for an approaching foe - * @param[in] leaveTime The leaveTime of the vehicle who checks for an approaching foe - * @param[in] speed The speed with which the checking vehicle plans to leave the link - * @param[in] decel The maximum deceleration of the checking vehicle - * @return Whether a foe of this link is approaching - */ - bool hasApproachingFoe(SUMOTime arrivalTime, SUMOTime leaveTime, double speed, double decel) const; - - /** @brief get the foe vehicle that is closest to the intersection or nullptr along with the foe link - * This function is used for finding circular deadlock at right_before_left junctions - * @param[in] wrapAround The link on which the ego vehicle wants to enter the junction - */ - std::pair getFirstApproachingFoe(const MSLink* wrapAround) const; - - MSJunction* getJunction() const { - return myJunction; - } - - - /** @brief Returns the current state of the link - * - * @return The current state of this link - */ - LinkState getState() const { - return myState; - } - - - /** @brief Returns the off-state for the link - * - * @return The current state of this link - */ - LinkState getOffState() const { - return myOffState; - } - - - //@brief Returns the time of the last state change - inline SUMOTime getLastStateChange() const { - return myLastStateChange; - } - - - /** @brief Returns the direction the vehicle passing this link take - * - * @return The direction of this link - */ - LinkDirection getDirection() const; - - - /** @brief Sets the current tl-state - * - * @param[in] state The current state of the link - * @param[in] t The time of the state change - */ - void setTLState(LinkState state, SUMOTime t); - - - /** @brief Returns the connected lane - * - * @return The lane approached by this link - */ - MSLane* getLane() const; - - - /** @brief Returns the respond index (for visualization) - * - * @return The respond index for this link - */ - inline int getIndex() const { - return myIndex; - } - - /** @brief Returns the TLS index */ - inline int getTLIndex() const { - return myTLIndex; - } - - /** @brief Returns the TLS index */ - inline const MSTrafficLightLogic* getTLLogic() const { - return myLogic; - } - - /** @brief Returns whether this link is a major link - * @return Whether the link has a large priority - */ - inline bool havePriority() const { - return myState >= 'A' && myState <= 'Z'; - } - - /** @brief Returns whether this link is blocked by a red (or redyellow) traffic light - * @return Whether the link has a red light - */ - inline bool haveRed() const { - return myState == LINKSTATE_TL_RED || myState == LINKSTATE_TL_REDYELLOW; - } - - inline bool haveYellow() const { - return myState == LINKSTATE_TL_YELLOW_MINOR || myState == LINKSTATE_TL_YELLOW_MAJOR; - } - - inline bool haveGreen() const { - return myState == LINKSTATE_TL_GREEN_MAJOR || myState == LINKSTATE_TL_GREEN_MINOR; - } - - inline bool isTLSControlled() const { - return myLogic != 0; - } - - /** @brief Returns the length of this link - * - * @return The length of this link - */ - double getLength() const { - return myLength; - } - - - /** @brief Returns the distance on the approaching lane from which an - * approaching vehicle is able to see all relevant foes and - * may accelerate if the link is minor and no foe is approaching. - * - * @return The foe-visibility-distance - */ - double getFoeVisibilityDistance() const { - return myFoeVisibilityDistance; - } - - - /** @brief Returns whether this link belongs to a junction where more than one edge is incoming - * - * @return Whether any foe links exist - */ - bool hasFoes() const { - return myHasFoes; - } - - // @brief return whether the vehicle may continute past this link to wait within the intersection - bool isCont() const; - - - /// @brief whether the junction after this link must be kept clear - bool keepClear() const { - return myKeepClear; - } - - /// @brief whether this is a link past an internal junction which currently has priority - bool lastWasContMajor() const; - - /// @brief whether this is a link past an internal junction which currently has green major - bool lastWasContMajorGreen() const; - - /** @brief Returns the cumulative length of all internal lanes after this link - * @return sum of the lengths of all internal lanes following this link - */ - double getInternalLengthsAfter() const; - - /** @brief Returns the cumulative length of all internal lanes before this link - * @return sum of the lengths of all internal lanes before this link - */ - double getInternalLengthsBefore() const; - - /** @brief Returns the sum of the lengths along internal lanes following this link - * to the crossing with the given foe lane, if the lane is no foe - * lane to any of the internal lanes, INVALID_DOUBLE is returned. - * @see getLengthBeforeCrossing() - */ - double getLengthsBeforeCrossing(const MSLane* foeLane) const; - - - /** @brief Returns the internal length from the beginning of the link's internal lane before - * to the crossing with the given foe lane if applicable, if the lane is no foe - * lane to the link, INVALID_DOUBLE is returned. - * @see getLengthsBeforeCrossing() - */ - double getLengthBeforeCrossing(const MSLane* foeLane) const; - - - /** @brief Returns the following inner lane - * - * @return The inner lane to use to cross the junction - */ - MSLane* getViaLane() const; - - /** @brief Returns all potential link leaders (vehicles on foeLanes) - * Valid during the planMove() phase - * @param[in] ego The ego vehicle that is looking for leaders - * @param[in] dist The distance of the vehicle who is asking about the leader to this link - * @param[out] blocking Return blocking pedestrians if a vector is given - * @param[in] isShadowLink whether this link is a shadowLink for ego - * @return The all vehicles on foeLanes and their (virtual) distances to the asking vehicle - */ - LinkLeaders getLeaderInfo(const MSVehicle* ego, double dist, std::vector* collectBlockers = 0, bool isShadowLink = false) const; - - /// @brief check for persons on walkingarea in the path of ego vehicle - void checkWalkingAreaFoe(const MSVehicle* ego, const MSLane* foeLane, std::vector* collectBlockers, LinkLeaders& result) const; - - /// @brief return the speed at which ego vehicle must approach the zipper link - double getZipperSpeed(const MSVehicle* ego, const double dist, double vSafe, - SUMOTime arrivalTime, - BlockingFoes* collectFoes) const; - - /// @brief return the via lane if it exists and the lane otherwise - MSLane* getViaLaneOrLane() const; - - /// @brief return the internalLaneBefore if it exists and the laneBefore otherwise - const MSLane* getLaneBefore() const; - - /// @brief return myInternalLaneBefore (always 0 when compiled without internal lanes) - const MSLane* getInternalLaneBefore() const; - - /// @brief return the expected time at which the given vehicle will clear the link - SUMOTime getLeaveTime(const SUMOTime arrivalTime, const double arrivalSpeed, const double leaveSpeed, const double vehicleLength) const; - - /// @brief write information about all approaching vehicles to the given output device - void writeApproaching(OutputDevice& od, const std::string fromLaneID) const; - - /// @brief return the link that is parallel to this lane or 0 - MSLink* getParallelLink(int direction) const; - - /// @brief return whether the fromLane of this link is an internal lane - bool fromInternalLane() const; - - /// @brief return whether the toLane of this link is an internal lane and fromLane is a normal lane - bool isEntryLink() const; - - /// @brief return whether this link enters the conflict area (not a continuation link) - bool isConflictEntryLink() const; - - /// @brief return whether the fromLane of this link is an internal lane and toLane is a normal lane - bool isExitLink() const; - - /// @brief return whether the fromLane of this link is an internal lane and its incoming lane is also an internal lane - bool isExitLinkAfterInternalJunction() const; - - /// @brief returns the corresponding exit link for entryLinks to a junction. - MSLink* getCorrespondingExitLink() const; - - /// @brief return whether the fromLane and the toLane of this link are internal lanes - bool isInternalJunctionLink() const; - - /** @brief Returns the time penalty for passing a tls-controlled link (meso) */ - SUMOTime getMesoTLSPenalty() const { - return myMesoTLSPenalty; - } - - /** @brief Returns the average proportion of green time to cycle time */ - double getGreenFraction() const { - return myGreenFraction; - } - - /** @brief Sets the time penalty for passing a tls-controlled link (meso) */ - void setMesoTLSPenalty(const SUMOTime penalty) { - myMesoTLSPenalty = penalty; - } - - /** @brief Sets the green fraction for passing a tls-controlled link (meso) */ - void setGreenFraction(const double fraction) { - myGreenFraction = fraction; - } - - const std::vector& getFoeLanes() const { - return myFoeLanes; - } - - const std::vector >& getLengthsBehindCrossing() const { - return myLengthsBehindCrossing; - } - - const std::vector& getFoeLinks() const { - return myFoeLinks; - } - - /// @brief initialize parallel links (to be called after all links are loaded) - void initParallelLinks(); - - /// @brief return lateral shift that must be applied when passing this link - double getLateralShift() { - return myLateralShift; - } - - /// @brief get string description for this link - std::string getDescription() const; - -private: - /// @brief return whether the given vehicles may NOT merge safely - static inline bool unsafeMergeSpeeds(double leaderSpeed, double followerSpeed, double leaderDecel, double followerDecel) { - // XXX mismatch between continuous an discrete deceleration - return (leaderSpeed * leaderSpeed / leaderDecel) <= (followerSpeed * followerSpeed / followerDecel); - } - - /// @brief whether follower could stay behind leader (possibly by braking) - static bool couldBrakeForLeader(double followDist, double leaderDist, const MSVehicle* follow, const MSVehicle* leader); - - MSLink* computeParallelLink(int direction); - - bool blockedByFoe(const SUMOVehicle* veh, const ApproachingVehicleInformation& avi, - SUMOTime arrivalTime, SUMOTime leaveTime, double arrivalSpeed, double leaveSpeed, - bool sameTargetLane, double impatience, double decel, SUMOTime waitingTime, - const SUMOVehicle* ego) const; - - /// @brief figure out whether the cont status remains in effect when switching off the tls - bool checkContOff() const; - - /// @brief check if the lane intersects with a foe cont-lane - bool contIntersect(const MSLane* lane, const MSLane* foe); - -private: - /// @brief The lane behind the junction approached by this link - MSLane* myLane; - - /// @brief The lane approaching this link - MSLane* myLaneBefore; - - ApproachInfos myApproachingVehicles; - std::set myBlockedFoeLinks; - - /// @brief The position within this respond - int myIndex; - - /// @brief the traffic light index - const int myTLIndex; - - /// @brief the controlling logic or 0 - const MSTrafficLightLogic* myLogic; - - /// @brief The state of the link - LinkState myState; - /// @brief The state of the link when switching of traffic light control - const LinkState myOffState; - - /// @brief The time of the last state change - SUMOTime myLastStateChange; - - /// @brief An abstract (hopefully human readable) definition of the link's direction - LinkDirection myDirection; - - /// @brief The length of the link - /// @note This is not equal to the result of getInternalLengthsAfter for links with more than one internal lane. - double myLength; - - /// @brief distance from which an approaching vehicle is able to - /// see all relevant foes and may accelerate if the link is minor - /// and no foe is approaching. Defaults to 4.5m. - double myFoeVisibilityDistance; - - /// @brief Whether any foe links exist - bool myHasFoes; - - // @brief whether vehicles may continue past this link to wait within the intersection - bool myAmCont; - // @brief whether vehicles may continue past this link to wait within the intersection after switching of the traffic light at this intersection - bool myAmContOff; - - // @brief whether vehicles must keep the intersection clear if there is a downstream jam - bool myKeepClear; - - /// @brief The following junction-internal lane if used - MSLane* const myInternalLane; - - /* @brief The preceding junction-internal lane, only used at - * - exit links (from internal lane to normal lane) - * - internal junction links (from internal lane to internal lane) - */ - const MSLane* myInternalLaneBefore; - - /// @brief penalty time at tls for mesoscopic simulation - SUMOTime myMesoTLSPenalty; - /// @brief green fraction at tls for mesoscopic simulation - double myGreenFraction; - - /// @brief lateral shift to be applied when passing this link - double myLateralShift; - - /* @brief lengths after the crossing point with foeLane - * (lengthOnThis, lengthOnFoe) - * (index corresponds to myFoeLanes) - * empty vector for entry links - * */ - std::vector > myLengthsBehindCrossing; - - // TODO: documentation - std::vector myFoeLinks; - std::vector myFoeLanes; - - /// @brief walkingArea that must be checked when entering the intersection - const MSLane* myWalkingAreaFoe; - /// @brief walkingArea that must be checked when leaving the intersection - const MSLane* myWalkingAreaFoeExit; - - /// @brief whether on of myFoeLanes is a crossing - bool myHavePedestrianCrossingFoe; - - /* @brief Links with the same origin lane and the same destination edge that may - be in conflict for sublane simulation */ - std::vector mySublaneFoeLinks; - /* @brief Links with the same origin lane and different destination edge that may - be in conflict for sublane simulation */ - std::vector mySublaneFoeLinks2; - - /* @brief Internal Lanes with the same origin lane and the same destination edge that may - be in conflict for sublane simulation */ - std::vector mySublaneFoeLanes; - - static const SUMOTime myLookaheadTime; - static const SUMOTime myLookaheadTimeZipper; - - MSLink* myParallelRight; - MSLink* myParallelLeft; - - /// @brief the junction to which this link belongs - MSJunction* myJunction; - - /// invalidated copy constructor - MSLink(const MSLink& s); - - /// invalidated assignment operator - MSLink& operator=(const MSLink& s); - -}; diff --git a/Util/OSM2ODR/src/microsim/MSLinkCont.h b/Util/OSM2ODR/src/microsim/MSLinkCont.h deleted file mode 100644 index 000053aae..000000000 --- a/Util/OSM2ODR/src/microsim/MSLinkCont.h +++ /dev/null @@ -1,63 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2002-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file MSLinkCont.h -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @date Sept 2002 -/// -// A vector of links -/****************************************************************************/ -#pragma once -#include - -#include -#include "MSLink.h" - - -// =========================================================================== -// class declarations -// =========================================================================== -class MSEdge; -class MSLane; - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class MSLinkCont - * A simple contanier of definitions about how a lane may be left - */ -typedef std::vector MSLinkCont; - - -/** - * @class MSLinkContHelper - * Some helping functions for dealing with links. - */ -class MSLinkContHelper { -public: - /** @brief Returns the internal lane that must be passed in order to get to the desired edge - Returns 0 if no such edge exists */ - static const MSEdge* getInternalFollowingEdge(const MSLane* fromLane, - const MSEdge* followerAfterInternal); - - static const MSLane* getInternalFollowingLane(const MSLane* fromLane, - const MSLane* followerAfterInternal); - - /** @brief Returns the link connecting both lanes - Both lanes have to be non-internal; 0 may be returned if no connection - exists */ - static MSLink* getConnectingLink(const MSLane& from, const MSLane& to); -}; diff --git a/Util/OSM2ODR/src/microsim/MSMoveReminder.h b/Util/OSM2ODR/src/microsim/MSMoveReminder.h deleted file mode 100644 index 3cac38246..000000000 --- a/Util/OSM2ODR/src/microsim/MSMoveReminder.h +++ /dev/null @@ -1,275 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2003-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file MSMoveReminder.h -/// @author Christian Roessel -/// @author Daniel Krajzewicz -/// @author Sascha Krieg -/// @author Michael Behrisch -/// @author Jakob Erdmann -/// @date 2003-05-21 -/// -// Something on a lane to be noticed about vehicle movement -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include -#include -#ifdef HAVE_FOX -#include -#endif - - -// =========================================================================== -// class declarations -// =========================================================================== -class SUMOTrafficObject; -class MSLane; - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class MSMoveReminder - * @brief Something on a lane to be noticed about vehicle movement - * - * Base class of all move-reminders. During move, the vehicles call - * notifyMove() for all reminders on their current lane (all lanes - * they pass during one step). If a vehicle enters the lane the reminder is - * positioned at during insertion or lanechange notifyEnter() is - * called. If a vehicle leaves the reminder lane it calls notifyLeave(). - * - * The reminder knows whom to tell about move, insertion and lanechange. The - * vehicles will remove the reminder that is not notifyMove() from - * their reminder container. - * - * @see MSLane::addMoveReminder - * @see MSLane::getMoveReminder - * @note: cannot inherit from Named because it would couse double inheritance - */ -class MSMoveReminder { -public: - /** @brief Constructor. - * - * @param[in] lane Lane on which the reminder will work. - * @param[in] doAdd whether to add the reminder to the lane - */ - MSMoveReminder(const std::string& description, MSLane* const lane = 0, const bool doAdd = true); - - - /** @brief Destructor - */ - virtual ~MSMoveReminder() {} - - - /** @brief Returns the lane the reminder works on. - * - * @return The lane the reminder is anchored on. - */ - const MSLane* getLane() const { - return myLane; - } - - - /// @brief Definition of a vehicle state - enum Notification { - /// @brief The vehicle has departed (was inserted into the network) - NOTIFICATION_DEPARTED, - /// @brief The vehicle arrived at a junction - NOTIFICATION_JUNCTION, - /// @brief The vehicle changes the segment (meso only) - NOTIFICATION_SEGMENT, - /// @brief The vehicle changes lanes (micro only) - NOTIFICATION_LANE_CHANGE, - /* All notifications below must result in the vehicle not being on the net - * (onLeaveLane sets amOnNet=false if reason>=NOTIFICATION_TELEPORT) */ - /// @brief The vehicle is being teleported - NOTIFICATION_TELEPORT, - /// @brief The vehicle starts or ends parking - NOTIFICATION_PARKING, - /// @brief The vehicle needs another parking area - NOTIFICATION_PARKING_REROUTE, - /// @brief The vehicle arrived at its destination (is deleted) - NOTIFICATION_ARRIVED, // arrived and everything after is treated as permanent deletion from the net - /// @brief The vehicle was teleported out of the net - NOTIFICATION_TELEPORT_ARRIVED, - /// @brief The vehicle got removed by a calibrator - NOTIFICATION_VAPORIZED_CALIBRATOR, - /// @brief The vehicle got removed by a collision - NOTIFICATION_VAPORIZED_COLLISION, - /// @brief The vehicle got removed via TraCI - NOTIFICATION_VAPORIZED_TRACI, - /// @brief The vehicle got removed via the GUI - NOTIFICATION_VAPORIZED_GUI, - /// @brief The vehicle got vaporized with a vaporizer - NOTIFICATION_VAPORIZED_VAPORIZER - }; - - - /// @name Interface methods, to be derived by subclasses - /// @{ - - /** @brief Checks whether the reminder is activated by a vehicle entering the lane - * - * Lane change means in this case that the vehicle changes to the lane - * the reminder is placed at. - * - * @param[in] veh The entering vehicle. - * @param[in] reason how the vehicle enters the lane - * @return True if vehicle enters the reminder. - * @see Notification - */ - virtual bool notifyEnter(SUMOTrafficObject& veh, Notification reason, const MSLane* enteredLane) { - UNUSED_PARAMETER(reason); - UNUSED_PARAMETER(&veh); - UNUSED_PARAMETER(&enteredLane); - return true; - } - - - /** @brief Checks whether the reminder still has to be notified about the vehicle moves - * - * Indicator if the reminders is still active for the passed - * vehicle/parameters. If false, the vehicle will erase this reminder - * from it's reminder-container. - * - * @param[in] veh Vehicle that asks this reminder. - * @param[in] oldPos Position before move. - * @param[in] newPos Position after move with newSpeed. - * @param[in] newSpeed Moving speed. - * - * @return True if vehicle hasn't passed the reminder completely. - */ - virtual bool notifyMove(SUMOTrafficObject& veh, - double oldPos, - double newPos, - double newSpeed) { - UNUSED_PARAMETER(oldPos); - UNUSED_PARAMETER(newPos); - UNUSED_PARAMETER(newSpeed); - UNUSED_PARAMETER(&veh); - return true; - } - - /** @brief Computes idling emission values and adds them to the emission sums - * - * Idling implied by zero velocity, acceleration and slope - * - * @param[in] veh The vehicle - * - * @see MSMoveReminder::notifyMove - * @see PollutantsInterface - */ - virtual bool notifyIdle(SUMOTrafficObject& veh) { - UNUSED_PARAMETER(&veh); - return true; - } - - /** @brief Called if the vehicle leaves the reminder's lane - * - * Informs if vehicle leaves reminder lane (due to lane change, removal - * from the network, or leaving to the next lane). - * The default is to do nothing. - * - * @param[in] veh The leaving vehicle. - * @param[in] lastPos Position on the lane when leaving. - * @param[in] reason how the vehicle leaves the lane - * @see Notification - * - * @return True if the reminder wants to receive further info. - */ - virtual bool notifyLeave(SUMOTrafficObject& veh, double lastPos, Notification reason, const MSLane* enteredLane = 0) { - UNUSED_PARAMETER(&veh); - UNUSED_PARAMETER(lastPos); - UNUSED_PARAMETER(reason); - UNUSED_PARAMETER(enteredLane); - return true; - } - - - // TODO: Documentation - void updateDetector(SUMOTrafficObject& veh, double entryPos, double leavePos, - SUMOTime entryTime, SUMOTime currentTime, SUMOTime leaveTime, - bool cleanUp); - - /// @} - - /** @brief Internal notification about the vehicle moves. - * @note meso uses this though it never calls notifyMove() - * - * Indicator if the reminders is still active for the passed - * vehicle/parameters. If false, the vehicle will erase this reminder - * from it's reminder-container. - * - * @param[in] veh Vehicle that asks this reminder. - * @param[in] frontOnLane time the front of the vehicle spent on the lane. - * @param[in] timeOnLane time some part of the vehicle spent on the lane. - * @param[in] meanSpeedFrontOnLane Average speed for the time that the front is on the lane. - * @param[in] meanSpeedVehicleOnLane Average speed for the time that the vehicle is on the lane (with front or back). - * @param[in] travelledDistanceFrontOnLane distance travelled while overlapping with the lane. - * @param[in] travelledDistanceVehicleOnLane distance travelled while front was on the lane. - * @param[in] meanLengthOnLane the average length of the vehicle's part on the lane during the last step (==complete length in meso case) - */ - virtual void notifyMoveInternal(const SUMOTrafficObject& veh, - const double frontOnLane, - const double timeOnLane, - const double meanSpeedFrontOnLane, - const double meanSpeedVehicleOnLane, - const double travelledDistanceFrontOnLane, - const double travelledDistanceVehicleOnLane, - const double meanLengthOnLane) { - UNUSED_PARAMETER(meanLengthOnLane); - UNUSED_PARAMETER(travelledDistanceFrontOnLane); - UNUSED_PARAMETER(travelledDistanceVehicleOnLane); - UNUSED_PARAMETER(meanSpeedVehicleOnLane); - UNUSED_PARAMETER(meanSpeedFrontOnLane); - UNUSED_PARAMETER(frontOnLane); - UNUSED_PARAMETER(timeOnLane); - UNUSED_PARAMETER(&veh); - } - - void setDescription(const std::string& description) { - myDescription = description; - } - - const std::string& getDescription() const { - return myDescription; - } - -protected: - void removeFromVehicleUpdateValues(SUMOTrafficObject& veh); - -protected: - - /// @brief Lane on which the reminder works - MSLane* const myLane; - /// @brief a description of this moveReminder - std::string myDescription; - -#ifdef HAVE_FOX - /// @brief the mutex for notifications - mutable FXMutex myNotificationMutex; -#endif - -private: - std::map > myLastVehicleUpdateValues; - - -private: - MSMoveReminder& operator=(const MSMoveReminder&); // just to avoid a compiler warning - -}; diff --git a/Util/OSM2ODR/src/microsim/MSNet.h b/Util/OSM2ODR/src/microsim/MSNet.h deleted file mode 100644 index d7d4167e9..000000000 --- a/Util/OSM2ODR/src/microsim/MSNet.h +++ /dev/null @@ -1,891 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file MSNet.h -/// @author Christian Roessel -/// @author Jakob Erdmann -/// @author Daniel Krajzewicz -/// @author Thimor Bohn -/// @author Eric Nicolay -/// @author Clemens Honomichl -/// @author Michael Behrisch -/// @author Leonhard Luecken -/// @date Mon, 12 Mar 2001 -/// -// The simulated network and simulation performer -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "MSJunction.h" - -#ifdef HAVE_FOX -#include -#endif - - -// =========================================================================== -// class declarations -// =========================================================================== -class MSEdge; -class MSEdgeControl; -class MSEventControl; -class MSVehicleControl; -class MSJunctionControl; -class MSInsertionControl; -class SUMORouteLoaderControl; -class MSTransportableControl; -class MSVehicle; -class MSRoute; -class MSLane; -class MSTLLogicControl; -class MSTrafficLightLogic; -class MSDetectorControl; -class ShapeContainer; -class MSDynamicShapeUpdater; -class PolygonDynamics; -class MSEdgeWeightsStorage; -class SUMOVehicle; -class MSTractionSubstation; -class MSStoppingPlace; -template -class IntermodalRouter; -template -class PedestrianRouter; -class OptionsCont; - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class MSNet - * @brief The simulated network and simulation perfomer - */ -class MSNet { -public: - /** @enum SimulationState - * @brief Possible states of a simulation - running or stopped with different reasons - */ - enum SimulationState { - /// @brief The simulation is loading - SIMSTATE_LOADING, - /// @brief The simulation is running - SIMSTATE_RUNNING, - /// @brief The final simulation step has been performed - SIMSTATE_END_STEP_REACHED, - /// @brief The simulation does not contain further vehicles - SIMSTATE_NO_FURTHER_VEHICLES, - /// @brief The connection to a client was closed by the client - SIMSTATE_CONNECTION_CLOSED, - /// @brief An error occurred during the simulation step - SIMSTATE_ERROR_IN_SIM, - /// @brief An external interrupt occured - SIMSTATE_INTERRUPTED, - /// @brief The simulation had too many teleports - SIMSTATE_TOO_MANY_TELEPORTS - }; - - typedef PedestrianRouter MSPedestrianRouter; - typedef IntermodalRouter MSIntermodalRouter; - - -public: - /** @brief Returns the pointer to the unique instance of MSNet (singleton). - * @return Pointer to the unique MSNet-instance - * @exception ProcessError If a network was not yet constructed - */ - static MSNet* getInstance(); - - /** - * @brief Returns whether this is a GUI Net - */ - virtual bool isGUINet() const { - return false; - } - - /// @brief Place for static initializations of simulation components (called after successful net build) - static void initStatic(); - - /// @brief Place for static initializations of simulation components (called after successful net build) - static void cleanupStatic(); - - - /** @brief Returns whether the network was already constructed - * @return whether the network was already constructed - */ - static bool hasInstance() { - return myInstance != nullptr; - } - - - /** @brief Constructor - * - * This constructor builds a net of which only some basic structures are initialised. - * It prepares the network for being filled while loading. - * As soon as all edge/junction/traffic lights and other containers are build, they - * must be initialised using "closeBuilding". - * @param[in] vc The vehicle control to use - * @param[in] beginOfTimestepEvents The event control to use for simulation step begin events - * @param[in] endOfTimestepEvents The event control to use for simulation step end events - * @param[in] insertionEvents The event control to use for insertion events - * @param[in] shapeCont The shape container to use - * @exception ProcessError If a network was already constructed - * @see closeBuilding - */ - MSNet(MSVehicleControl* vc, MSEventControl* beginOfTimestepEvents, - MSEventControl* endOfTimestepEvents, - MSEventControl* insertionEvents, - ShapeContainer* shapeCont = 0); - - - /// @brief Destructor - virtual ~MSNet(); - - - /** @brief Closes the network's building process - * - * Assigns the structures built while loading to this network. - * @param[in] oc The options to use - * @param[in] edges The control of edges which belong to this network - * @param[in] junctions The control of junctions which belong to this network - * @param[in] routeLoaders The route loaders used - * @param[in] tlc The control of traffic lights which belong to this network - * @param[in] stateDumpTimes List of time steps at which state shall be written - * @param[in] stateDumpFiles Filenames for states - * @param[in] hasInternalLinks Whether the network actually contains internal links - * @param[in] version The network version - * @todo Try to move all this to the constructor? - */ - void closeBuilding(const OptionsCont& oc, MSEdgeControl* edges, MSJunctionControl* junctions, - SUMORouteLoaderControl* routeLoaders, MSTLLogicControl* tlc, - std::vector stateDumpTimes, std::vector stateDumpFiles, - bool hasInternalLinks, bool hasNeighs, - double version); - - - /** @brief Returns whether the network has specific vehicle class permissions - * @return whether permissions are present - */ - bool hasPermissions() const { - return myHavePermissions; - } - - - /// @brief Labels the network to contain vehicle class permissions - void setPermissionsFound() { - myHavePermissions = true; - } - - - /** @brief Adds a restriction for an edge type - * @param[in] id The id of the type - * @param[in] svc The vehicle class the restriction refers to - * @param[in] speed The restricted speed - */ - void addRestriction(const std::string& id, const SUMOVehicleClass svc, const double speed); - - - /** @brief Returns the restrictions for an edge type - * If no restrictions are present, 0 is returned. - * @param[in] id The id of the type - * @return The mapping of vehicle classes to maximum speeds - */ - const std::map* getRestrictions(const std::string& id) const; - - - /** @brief Clears all dictionaries - * @todo Try to move all this to the destructor - */ - static void clearAll(); - - - /** @brief Simulates from timestep start to stop - * @param[in] start The begin time step of the simulation - * @param[in] stop The end time step of the simulation - * @return Returns always 0 - * @todo Recheck return value - * @todo What exceptions may occure? - */ - SimulationState simulate(SUMOTime start, SUMOTime stop); - - - /** @brief Performs a single simulation step - * @todo Which exceptions may occur? - */ - void simulationStep(); - - - /** @brief loads routes for the next few steps */ - void loadRoutes(); - - - /** @brief Writes performance output and running vehicle stats - * - * @param[in] start The step the simulation was started with - */ - const std::string generateStatistics(SUMOTime start); - - /// @brief write statistic output to (xml) file - void writeStatistics() const; - - /** @brief Closes the simulation (all files, connections, etc.) - * - * Writes also performance output - * - * @param[in] start The step the simulation was started with - */ - void closeSimulation(SUMOTime start, const std::string& reason = ""); - - - /** @brief This method returns the current simulation state. It should not modify status. - * @param[in] stopTime The time the simulation shall stop at - * @return The current simulation state - * @see SimulationState - */ - SimulationState simulationState(SUMOTime stopTime) const; - - - /** @brief Called after a simulation step, this method adapts the current simulation state if necessary - * @param[in] state The current simulation state - * @return The new simulation state - * @see SimulationState - */ - SimulationState adaptToState(const SimulationState state) const; - - - /** @brief Returns the message to show if a certain state occurs - * @return Readable description of the state - */ - static std::string getStateMessage(SimulationState state); - - - /** @brief Returns the current simulation step - * @return the current simulation step - */ - inline SUMOTime getCurrentTimeStep() const { - return myStep; - } - - - /** @brief Sets the current simulation step (used by state loading) - * @param step the current simulation step - */ - inline void setCurrentTimeStep(const SUMOTime step) { - myStep = step; - } - - - /** @brief Resets events when quick-loading state - * @param step The new simulation step - */ - void clearState(const SUMOTime step); - - /** @brief Write netstate, summary and detector output - * @todo Which exceptions may occur? - */ - void writeOutput(); - - - /** @brief Returns whether duration shall be logged - * @return Whether duration shall be logged - */ - bool logSimulationDuration() const; - - - - /// @name Output during the simulation - //@{ - - /** @brief Prints the current step number - * - * Called on the begin of a simulation step - */ - void preSimStepOutput() const; - - - /** @brief Prints the statistics of the step at its end - * - * Called on the end of a simulation step - */ - void postSimStepOutput() const; - //} - - - - /// @name Retrieval of references to substructures - /// @{ - - /** @brief Returns the vehicle control - * @return The vehicle control - * @see MSVehicleControl - * @see myVehicleControl - */ - MSVehicleControl& getVehicleControl() { - return *myVehicleControl; - } - - - /** @brief Returns the person control - * - * If the person control does not exist, yet, it is created. - * - * @return The person control - * @see MSPersonControl - * @see myPersonControl - */ - virtual MSTransportableControl& getPersonControl(); - - /** @brief Returns whether persons are simulated - */ - bool hasPersons() const { - return myPersonControl != nullptr; - } - - /** @brief Returns the container control - * - * If the container control does not exist, yet, it is created. - * - * @return The container control - * @see MSContainerControl - * @see myContainerControl - */ - virtual MSTransportableControl& getContainerControl(); - - /** @brief Returns whether containers are simulated - */ - bool hasContainers() const { - return myContainerControl != nullptr; - } - - - /** @brief Returns the edge control - * @return The edge control - * @see MSEdgeControl - * @see myEdges - */ - MSEdgeControl& getEdgeControl() { - return *myEdges; - } - - - /** @brief Returns the insertion control - * @return The insertion control - * @see MSInsertionControl - * @see myInserter - */ - MSInsertionControl& getInsertionControl() { - return *myInserter; - } - - - /** @brief Returns the detector control - * @return The detector control - * @see MSDetectorControl - * @see myDetectorControl - */ - MSDetectorControl& getDetectorControl() { - return *myDetectorControl; - } - - - /** @brief Returns the tls logics control - * @return The tls logics control - * @see MSTLLogicControl - * @see myLogics - */ - MSTLLogicControl& getTLSControl() { - return *myLogics; - } - - - /** @brief Returns the junctions control - * @return The junctions control - * @see MSJunctionControl - * @see myJunctions - */ - MSJunctionControl& getJunctionControl() { - return *myJunctions; - } - - - /** @brief Returns the event control for events executed at the begin of a time step - * @return The control responsible for events that are executed at the begin of a time step - * @see MSEventControl - * @see myBeginOfTimestepEvents - */ - MSEventControl* getBeginOfTimestepEvents() { - return myBeginOfTimestepEvents; - } - - - /** @brief Returns the event control for events executed at the end of a time step - * @return The control responsible for events that are executed at the end of a time step - * @see MSEventControl - * @see myEndOfTimestepEvents - */ - MSEventControl* getEndOfTimestepEvents() { - return myEndOfTimestepEvents; - } - - - /** @brief Returns the event control for insertion events - * @return The control responsible for insertion events - * @see MSEventControl - * @see myInsertionEvents - */ - MSEventControl* getInsertionEvents() { - return myInsertionEvents; - } - - - /** @brief Returns the shapes container - * @return The shapes container - * @see ShapeContainer - * @see myShapeContainer - */ - ShapeContainer& getShapeContainer() { - return *myShapeContainer; - } - - /** @brief Returns the dynamic shapes updater - * @see PolygonDynamics - */ - MSDynamicShapeUpdater* getDynamicShapeUpdater() { - return myDynamicShapeUpdater.get(); - } - - /** @brief Creates and returns a dynamic shapes updater - * @see PolygonDynamics - */ - MSDynamicShapeUpdater* makeDynamicShapeUpdater(); - - /** @brief Returns the net's internal edge travel times/efforts container - * - * If the net does not have such a container, it is built. - * @return The net's knowledge about edge weights - */ - MSEdgeWeightsStorage& getWeightsStorage(); - /// @} - - /// @name Insertion and retrieval of stopping places - /// @{ - - /** @brief Adds a stopping place - * - * If another stop with the same id and category exists, false is returned. - * Otherwise, the stop is added to the internal stopping place container. - * - * This control gets responsible for deletion of the added stop. - * - * @param[in] stop The stop to add - * @return Whether the stop could be added - */ - bool addStoppingPlace(const SumoXMLTag category, MSStoppingPlace* stop); - - - /** @brief Adds a traction substation - * - * If another traction substation with the same id and category exists, false is returned. - * Otherwise, the traction substation is added to the internal substations container. - * - * @param[in] substation The traction substation to add - * @return Whether the stop could be added - */ - bool addTractionSubstation(MSTractionSubstation* substation); - - - /** @brief Returns the named stopping place of the given category - * @param[in] id The id of the stop to return. - * @param[in] category The type of stop - * @return The named stop, or 0 if no such stop exists - */ - MSStoppingPlace* getStoppingPlace(const std::string& id, const SumoXMLTag category) const; - - /** @brief Returns the stop of the given category close to the given position - * @param[in] lane the lane of the stop to return. - * @param[in] pos the position of the stop to return. - * @param[in] category The type of stop - * @return The stop id on the location, or "" if no such stop exists - */ - std::string getStoppingPlaceID(const MSLane* lane, const double pos, const SumoXMLTag category) const; - /// @} - - const NamedObjectCont& getStoppingPlaces(SumoXMLTag category) const; - - /// @brief write charging station output - void writeChargingStationOutput() const; - - /// @brief write rail signal block output - void writeRailSignalBlocks() const; - - /// @brief creates a wrapper for the given logic (see GUINet) - virtual void createTLWrapper(MSTrafficLightLogic*) {}; - - /// @brief write the output generated by an overhead wire segment - void writeOverheadWireSegmentOutput() const; - - /// @brief write electrical substation output - void writeSubstationOutput() const; - - /// @brief return wheter the given logic (or rather it's wrapper) is selected in the GUI - virtual bool isSelected(const MSTrafficLightLogic*) const { - return false; - } - - /// @name Notification about vehicle state changes - /// @{ - - /// @brief Definition of a vehicle state - enum VehicleState { - /// @brief The vehicle was built, but has not yet departed - VEHICLE_STATE_BUILT, - /// @brief The vehicle has departed (was inserted into the network) - VEHICLE_STATE_DEPARTED, - /// @brief The vehicle started to teleport - VEHICLE_STATE_STARTING_TELEPORT, - /// @brief The vehicle ended being teleported - VEHICLE_STATE_ENDING_TELEPORT, - /// @brief The vehicle arrived at his destination (is deleted) - VEHICLE_STATE_ARRIVED, - /// @brief The vehicle got a new route - VEHICLE_STATE_NEWROUTE, - /// @brief The vehicles starts to park - VEHICLE_STATE_STARTING_PARKING, - /// @brief The vehicle ends to park - VEHICLE_STATE_ENDING_PARKING, - /// @brief The vehicles starts to stop - VEHICLE_STATE_STARTING_STOP, - /// @brief The vehicle ends to stop - VEHICLE_STATE_ENDING_STOP, - /// @brief The vehicle is involved in a collision - VEHICLE_STATE_COLLISION, - /// @brief The vehicle had to brake harder than permitted - VEHICLE_STATE_EMERGENCYSTOP, - /// @brief Vehicle maneuvering either entering or exiting a parking space - VEHICLE_STATE_MANEUVERING - }; - - - /** @class VehicleStateListener - * @brief Interface for objects listening to vehicle state changes - */ - class VehicleStateListener { - public: - /// @brief Constructor - VehicleStateListener() { } - - /// @brief Destructor - virtual ~VehicleStateListener() { } - - /** @brief Called if a vehicle changes its state - * @param[in] vehicle The vehicle which changed its state - * @param[in] to The state the vehicle has changed to - * @param[in] info Additional information on the state change - */ - virtual void vehicleStateChanged(const SUMOVehicle* const vehicle, VehicleState to, const std::string& info = "") = 0; - - }; - - - /** @brief Adds a vehicle states listener - * @param[in] listener The listener to add - */ - void addVehicleStateListener(VehicleStateListener* listener); - - - /** @brief Removes a vehicle states listener - * @param[in] listener The listener to remove - */ - void removeVehicleStateListener(VehicleStateListener* listener); - - - /** @brief Informs all added listeners about a vehicle's state change - * @param[in] vehicle The vehicle which changed its state - * @param[in] to The state the vehicle has changed to - * @param[in] info Information regarding the replacement - * @see VehicleStateListener:vehicleStateChanged - */ - void informVehicleStateListener(const SUMOVehicle* const vehicle, VehicleState to, const std::string& info = ""); - /// @} - - - - /** @brief Returns the travel time to pass an edge - * @param[in] e The edge for which the travel time to be passed shall be returned - * @param[in] v The vehicle that is rerouted - * @param[in] t The time for which the travel time shall be returned [s] - * @return The travel time for an edge - * @see DijkstraRouter_ByProxi - */ - static double getTravelTime(const MSEdge* const e, const SUMOVehicle* const v, double t); - - - /** @brief Returns the effort to pass an edge - * @param[in] e The edge for which the effort to be passed shall be returned - * @param[in] v The vehicle that is rerouted - * @param[in] t The time for which the effort shall be returned [s] - * @return The effort (abstract) for an edge - * @see DijkstraRouter_ByProxi - */ - static double getEffort(const MSEdge* const e, const SUMOVehicle* const v, double t); - - - /* @brief get the router, initialize on first use - * @param[in] prohibited The vector of forbidden edges (optional) - */ - SUMOAbstractRouter& getRouterTT(const int rngIndex, - const MSEdgeVector& prohibited = MSEdgeVector()) const; - SUMOAbstractRouter& getRouterEffort(const int rngIndex, - const MSEdgeVector& prohibited = MSEdgeVector()) const; - MSPedestrianRouter& getPedestrianRouter(const int rngIndex, const MSEdgeVector& prohibited = MSEdgeVector()) const; - MSIntermodalRouter& getIntermodalRouter(const int rngIndex, const int routingMode = 0, const MSEdgeVector& prohibited = MSEdgeVector()) const; - - static void adaptIntermodalRouter(MSIntermodalRouter& router); - - - /// @brief return whether the network contains internal links - bool hasInternalLinks() const { - return myHasInternalLinks; - } - - /// @brief return whether the network contains elevation data - bool hasElevation() const { - return myHasElevation; - } - - /// @brief return whether the network contains walkingareas and crossings - bool hasPedestrianNetwork() const { - return myHasPedestrianNetwork; - - } - /// @brief return whether the network contains bidirectional rail edges - bool hasBidiEdges() const { - return myHasBidiEdges; - } - - /// @brief return the network version - double getNetworkVersion() const { - return myVersion; - } - - /// @brief return whether a warning regarding the given object shall be issued - bool warnOnce(const std::string& typeAndID); - - void interrupt() { - myAmInterrupted = true; - } - - bool isInterrupted() const { - return myAmInterrupted; - } - - /// @brief find electrical substation by its id - MSTractionSubstation* findTractionSubstation(const std::string& substationId); - - /// @brief return whether given electrical substation exists in the network - bool existTractionSubstation(const std::string& substationId); - -protected: - /// @brief check all lanes for elevation data - bool checkElevation(); - - /// @brief check all lanes for type walkingArea - bool checkWalkingarea(); - - /// @brief check wether bidirectional edges occur in the network - bool checkBidiEdges(); - -protected: - /// @brief Unique instance of MSNet - static MSNet* myInstance; - - /// @brief Route loader for dynamic loading of routes - SUMORouteLoaderControl* myRouteLoaders; - - /// @brief Current time step. - SUMOTime myStep; - - /// @brief Maximum number of teleports. - int myMaxTeleports; - - /// @brief whether an interrupt occured - bool myAmInterrupted; - - - - /// @name Substructures - /// @{ - - /// @brief Controls vehicle building and deletion; @see MSVehicleControl - MSVehicleControl* myVehicleControl; - /// @brief Controls person building and deletion; @see MSTransportableControl - MSTransportableControl* myPersonControl; - /// @brief Controls container building and deletion; @see MSTransportableControl - MSTransportableControl* myContainerControl; - /// @brief Controls edges, performs vehicle movement; @see MSEdgeControl - MSEdgeControl* myEdges; - /// @brief Controls junctions, realizes right-of-way rules; @see MSJunctionControl - MSJunctionControl* myJunctions; - /// @brief Controls tls logics, realizes waiting on tls rules; @see MSJunctionControl - MSTLLogicControl* myLogics; - /// @brief Controls vehicle insertion; @see MSInsertionControl - MSInsertionControl* myInserter; - /// @brief Controls detectors; @see MSDetectorControl - MSDetectorControl* myDetectorControl; - /// @brief Controls events executed at the begin of a time step; @see MSEventControl - MSEventControl* myBeginOfTimestepEvents; - /// @brief Controls events executed at the end of a time step; @see MSEventControl - MSEventControl* myEndOfTimestepEvents; - /// @brief Controls insertion events; @see MSEventControl - MSEventControl* myInsertionEvents; - /// @brief A container for geometrical shapes; @see ShapeContainer - ShapeContainer* myShapeContainer; - /// @brief The net's knowledge about edge efforts/travel times; @see MSEdgeWeightsStorage - MSEdgeWeightsStorage* myEdgeWeights; - /// @} - - - - /// @name data needed for computing performance values - /// @{ - - /// @brief Information whether the simulation duration shall be logged - bool myLogExecutionTime; - - /// @brief Information whether the number of the simulation step shall be logged - bool myLogStepNumber; - /// @brief Period between successive step-log outputs - int myLogStepPeriod; - - /// @brief The last simulation step duration - long myTraCIStepDuration = 0, mySimStepDuration = 0; - - /// @brief The overall simulation duration - long mySimBeginMillis; - - /// @brief The overall number of vehicle movements - long long int myVehiclesMoved; - long long int myPersonsMoved; - //} - - - - /// @name State output variables - /// @{ - - /// @brief Times at which a state shall be written - std::vector myStateDumpTimes; - /// @brief The names for the state files - std::vector myStateDumpFiles; - /// @brief The period for writing state - SUMOTime myStateDumpPeriod; - /// @brief name components for periodic state - std::string myStateDumpPrefix; - std::string myStateDumpSuffix; - /// @} - - - - /// @brief Whether the network contains edges which not all vehicles may pass - bool myHavePermissions; - - /// @brief The vehicle class specific speed restrictions - std::map > myRestrictions; - - /// @brief Whether the network contains internal links/lanes/edges - bool myHasInternalLinks; - - /// @brief Whether the network contains elevation data - bool myHasElevation; - - /// @brief Whether the network contains pedestrian network elements - bool myHasPedestrianNetwork; - - /// @brief Whether the network contains bidirectional rail edges - bool myHasBidiEdges; - - /// @brief Whether the network was built for left-hand traffic - bool myLefthand; - - /// @brief the network version - double myVersion; - - /// @brief end of loaded edgeData - SUMOTime myEdgeDataEndTime; - - /// @brief Dictionary of bus / container stops - std::map > myStoppingPlaces; - - /// @brief Dictionary of traction substations - std::vector myTractionSubstations; - - /// @brief Container for vehicle state listener - std::vector myVehicleStateListeners; - -#ifdef HAVE_FOX - /// @brief to avoid concurrent access to the state update function - FXMutex myStateListenerMutex; -#endif - - /// @brief container to record warnings that shall only be issued once - std::map myWarnedOnce; - - /* @brief The router instance for routing by trigger and by traci - * @note MSDevice_Routing has its own instance since it uses a different weight function - * @note we provide one member for every switchable router type - * because the class structure makes it inconvenient to use a superclass - */ - mutable std::map*> myRouterTT; - mutable std::map*> myRouterEffort; - mutable std::map myPedestrianRouter; - mutable std::map myIntermodalRouter; - - /// @brief An RTree structure holding lane IDs - mutable std::pair myLanesRTree; - - /// @brief Updater for dynamic shapes that are tracking traffic objects - /// (ensures removal of shape dynamics when the objects are removed) - /// @see utils/shapes/PolygonDynamics - std::unique_ptr myDynamicShapeUpdater; - - - /// @brief string constants for simstep stages - static const std::string STAGE_EVENTS; - static const std::string STAGE_MOVEMENTS; - static const std::string STAGE_LANECHANGE; - static const std::string STAGE_INSERTIONS; - -private: - /// @brief Invalidated copy constructor. - MSNet(const MSNet&); - - /// @brief Invalidated assignment operator. - MSNet& operator=(const MSNet&); - - -}; diff --git a/Util/OSM2ODR/src/netbuild/CMakeLists.txt b/Util/OSM2ODR/src/netbuild/CMakeLists.txt deleted file mode 100644 index 00c7b15c6..000000000 --- a/Util/OSM2ODR/src/netbuild/CMakeLists.txt +++ /dev/null @@ -1,66 +0,0 @@ -set(netbuild_STAT_SRCS - NBAlgorithms.cpp - NBAlgorithms.h - NBAlgorithms_Ramps.cpp - NBAlgorithms_Ramps.h - NBAlgorithms_Railway.cpp - NBAlgorithms_Railway.h - NBCapacity2Lanes.h - NBConnection.cpp - NBConnection.h - NBConnectionDefs.h - NBCont.h - NBContHelper.cpp - NBContHelper.h - NBDistrict.cpp - NBDistrict.h - NBDistrictCont.cpp - NBDistrictCont.h - NBEdge.cpp - NBEdge.h - NBEdgeCont.cpp - NBEdgeCont.h - NBFrame.cpp - NBFrame.h - NBHeightMapper.cpp - NBHeightMapper.h - NBHelpers.cpp - NBHelpers.h - NBLinkPossibilityMatrix.h - NBNode.cpp - NBNode.h - NBNodeCont.cpp - NBNodeCont.h - NBNodeShapeComputer.cpp - NBNodeShapeComputer.h - NBParking.cpp - NBParking.h - NBPTStop.cpp - NBPTStop.h - NBPTStopCont.cpp - NBPTStopCont.h - NBRequest.cpp - NBRequest.h - NBTrafficLightDefinition.cpp - NBTrafficLightDefinition.h - NBTrafficLightLogic.cpp - NBTrafficLightLogic.h - NBTrafficLightLogicCont.cpp - NBTrafficLightLogicCont.h - NBTypeCont.cpp - NBTypeCont.h - NBSign.cpp - NBSign.h - NBOwnTLDef.cpp - NBOwnTLDef.h - NBLoadedTLDef.cpp - NBLoadedTLDef.h - NBLoadedSUMOTLDef.cpp - NBLoadedSUMOTLDef.h - NBVehicle.h - NBNetBuilder.cpp - NBNetBuilder.h - NBPTLine.cpp NBPTLine.h NBPTLineCont.cpp NBPTLineCont.h NBPTPlatform.cpp NBPTPlatform.h) - -add_library(netbuild STATIC ${netbuild_STAT_SRCS}) -set_property(TARGET netbuild PROPERTY PROJECT_LABEL "z_netbuild") diff --git a/Util/OSM2ODR/src/netbuild/NBAlgorithms.cpp b/Util/OSM2ODR/src/netbuild/NBAlgorithms.cpp deleted file mode 100644 index 80e424ca4..000000000 --- a/Util/OSM2ODR/src/netbuild/NBAlgorithms.cpp +++ /dev/null @@ -1,520 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2012-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NBAlgorithms.cpp -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @date 02. March 2012 -/// -// Algorithms for network computation -/****************************************************************************/ -#include - -#include -#include -#include -#include -#include -#include -#include -#include "NBEdge.h" -#include "NBOwnTLDef.h" -#include "NBTrafficLightLogicCont.h" -#include "NBNodeCont.h" -#include "NBTypeCont.h" -#include "NBNode.h" -#include "NBAlgorithms.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -// --------------------------------------------------------------------------- -// NBTurningDirectionsComputer -// --------------------------------------------------------------------------- -void -NBTurningDirectionsComputer::computeTurnDirections(NBNodeCont& nc, bool warn) { - for (std::map::const_iterator i = nc.begin(); i != nc.end(); ++i) { - computeTurnDirectionsForNode(i->second, warn); - } -} - -void -NBTurningDirectionsComputer::computeTurnDirectionsForNode(NBNode* node, bool warn) { - const std::vector& incoming = node->getIncomingEdges(); - const std::vector& outgoing = node->getOutgoingEdges(); - // reset turning directions since this may be called multiple times - for (std::vector::const_iterator k = incoming.begin(); k != incoming.end(); ++k) { - (*k)->setTurningDestination(nullptr); - } - std::vector combinations; - const bool geometryLike = node->geometryLike(); - for (std::vector::const_iterator j = outgoing.begin(); j != outgoing.end(); ++j) { - NBEdge* outedge = *j; - for (std::vector::const_iterator k = incoming.begin(); k != incoming.end(); ++k) { - NBEdge* e = *k; - // @todo: check whether NBHelpers::relAngle is properly defined and whether it should really be used, here - const double signedAngle = NBHelpers::normRelAngle(e->getAngleAtNode(node), outedge->getAngleAtNode(node)); - if (signedAngle > 0 && signedAngle < 177 && e->getGeometry().back().distanceTo2D(outedge->getGeometry().front()) < POSITION_EPS) { - // backwards curving edges can only be turnaround when there are - // non-default endpoints - continue; - } - double angle = fabs(signedAngle); - // std::cout << "incoming=" << e->getID() << " outgoing=" << outedge->getID() << " relAngle=" << NBHelpers::relAngle(e->getAngleAtNode(node), outedge->getAngleAtNode(node)) << "\n"; - const bool badPermissions = ((outedge->getPermissions() & e->getPermissions() & ~SVC_PEDESTRIAN) == 0 - && !geometryLike - && outedge->getPermissions() != e->getPermissions()); - if (e->getFromNode() == outedge->getToNode() - && (angle > 120 || e->getFromNode()->getPosition() == e->getToNode()->getPosition()) - && !badPermissions) { - // they connect the same nodes; should be the turnaround direction - // we'll assign a maximum number - // - // @todo: indeed, we have observed some pathological intersections - // see "294831560" in OSM/adlershof. Here, several edges are connecting - // same nodes. We have to do the angle check before... - // - // @todo: and well, there are some other as well, see plain import - // of delphi_muenchen (elmar), intersection "59534191". Not that it would - // be realistic in any means; we will warn, here. - angle += 360; - } - if (angle < 160) { - continue; - } - if (badPermissions) { - // penalty - angle -= 90; - } - Combination c; - c.from = e; - c.to = outedge; - c.angle = angle; - combinations.push_back(c); - } - } - // sort combinations so that the ones with the highest angle are at the begin - std::sort(combinations.begin(), combinations.end(), combination_by_angle_sorter()); - std::set seen; - //std::cout << "check combinations at " << node->getID() << "\n"; - for (std::vector::const_iterator j = combinations.begin(); j != combinations.end(); ++j) { - //std::cout << " from=" << (*j).from->getID() << " to=" << (*j).to->getID() << " a=" << (*j).angle << "\n"; - if (seen.find((*j).from) != seen.end() || seen.find((*j).to) != seen.end()) { - // do not regard already set edges - if ((*j).angle > 360 && warn) { - WRITE_WARNINGF("Ambiguity in turnarounds computation at junction '%'.", node->getID()); - //std::cout << " already seen: " << toString(seen) << "\n"; - warn = false; - } - continue; - } - // mark as seen - seen.insert((*j).from); - seen.insert((*j).to); - // set turnaround information - bool onlyPossible = (*j).from->getConnections().size() != 0 && !(*j).from->isConnectedTo((*j).to); - //std::cout << " setTurningDestination from=" << (*j).from->getID() << " to=" << (*j).to->getID() << " onlyPossible=" << onlyPossible << "\n"; - (*j).from->setTurningDestination((*j).to, onlyPossible); - } -} - - -// --------------------------------------------------------------------------- -// NBNodesEdgesSorter -// --------------------------------------------------------------------------- -void -NBNodesEdgesSorter::sortNodesEdges(NBNodeCont& nc, bool useNodeShape) { - for (std::map::const_iterator i = nc.begin(); i != nc.end(); ++i) { - i->second->sortEdges(useNodeShape); - } -} - - -void -NBNodesEdgesSorter::swapWhenReversed(const NBNode* const n, - const std::vector::iterator& i1, - const std::vector::iterator& i2) { - NBEdge* e1 = *i1; - NBEdge* e2 = *i2; - // @todo: The difference between "isTurningDirectionAt" and "isTurnaround" - // is not nice. Maybe we could get rid of it if we would always mark edges - // as turnarounds, even if they do not have to be added, as mentioned in - // notes on NBTurningDirectionsComputer::computeTurnDirectionsForNode - if (e2->getToNode() == n && e2->isTurningDirectionAt(e1)) { - std::swap(*i1, *i2); - } -} - - -// --------------------------------------------------------------------------- -// NBNodeTypeComputer -// --------------------------------------------------------------------------- -void -NBNodeTypeComputer::computeNodeTypes(NBNodeCont& nc, NBTrafficLightLogicCont& tlc) { - validateRailCrossings(nc, tlc); - const OptionsCont& oc = OptionsCont::getOptions(); - const double rightBeforeLeftSpeed = oc.getFloat("junctions.right-before-left.speed-threshold"); - for (std::map::const_iterator i = nc.begin(); i != nc.end(); ++i) { - NBNode* const n = (*i).second; - // the type may already be set from the data - if (n->myType != SumoXMLNodeType::UNKNOWN && n->myType != SumoXMLNodeType::DEAD_END) { - n->myTypeWasGuessed = false; - continue; - } - // check whether the node was set to be unregulated by the user - if (oc.getBool("keep-nodes-unregulated") || oc.isInStringVector("keep-nodes-unregulated.explicit", n->getID()) - || (oc.getBool("keep-nodes-unregulated.district-nodes") && (n->isNearDistrict() || n->isDistrict()))) { - n->myType = SumoXMLNodeType::NOJUNCTION; - continue; - } - // check whether the node is a waterway node. Set to unregulated by default - bool waterway = true; - for (NBEdge* e : n->getEdges()) { - if (!isWaterway(e->getPermissions())) { - waterway = false; - break; - } - } - if (waterway && (n->myType == SumoXMLNodeType::UNKNOWN || n->myType == SumoXMLNodeType::DEAD_END)) { - n->myType = SumoXMLNodeType::NOJUNCTION; - continue; - } - - // check whether the junction is not a real junction - if (n->myIncomingEdges.size() == 1) { - n->myType = SumoXMLNodeType::PRIORITY; - continue; - } - // @todo "isSimpleContinuation" should be revalidated - if (n->isSimpleContinuation()) { - n->myType = SumoXMLNodeType::PRIORITY; - continue; - } - if (isRailwayNode(n)) { - // priority instead of unregulated to ensure that collisions can be detected - n->myType = SumoXMLNodeType::PRIORITY; - continue; - } - // determine the type - SumoXMLNodeType type = SumoXMLNodeType::RIGHT_BEFORE_LEFT; - for (EdgeVector::const_iterator i = n->myIncomingEdges.begin(); i != n->myIncomingEdges.end(); i++) { - for (EdgeVector::const_iterator j = i + 1; j != n->myIncomingEdges.end(); j++) { - // @todo "getOppositeIncoming" should probably be refactored into something the edge knows - if (n->getOppositeIncoming(*j) == *i && n->myIncomingEdges.size() > 2) { - continue; - } - // @todo check against a legal document - // @todo figure out when SumoXMLNodeType::PRIORITY_STOP is appropriate - const double s1 = (*i)->getSpeed(); - const double s2 = (*j)->getSpeed(); - const int p1 = (*i)->getPriority(); - const int p2 = (*j)->getPriority(); - if (fabs(s1 - s2) > (9.5 / 3.6) || MAX2(s1, s2) >= rightBeforeLeftSpeed || p1 != p2) { - type = SumoXMLNodeType::PRIORITY; - break; - } - } - } - // save type - n->myType = type; - n->myTypeWasGuessed = true; - } -} - - -void -NBNodeTypeComputer::validateRailCrossings(NBNodeCont& nc, NBTrafficLightLogicCont& tlc) { - for (std::map::const_iterator i = nc.begin(); i != nc.end(); ++i) { - NBNode* n = (*i).second; - if (n->myType == SumoXMLNodeType::RAIL_CROSSING) { - // check if it really is a rail crossing - int numRailway = 0; - int numNonRailway = 0; - int numNonRailwayNonPed = 0; - for (NBEdge* e : n->getIncomingEdges()) { - if ((e->getPermissions() & ~SVC_RAIL_CLASSES) != 0) { - numNonRailway++; - if (e->getPermissions() != SVC_PEDESTRIAN) { - numNonRailwayNonPed++; - } - } else if ((e->getPermissions() & SVC_RAIL_CLASSES) != 0) { - numRailway++; - } - } - for (NBEdge* e : n->getOutgoingEdges()) { - if (e->getPermissions() == SVC_PEDESTRIAN) { - numNonRailway++; - } - } - if (numNonRailway == 0 || numRailway == 0) { - // not a crossing (maybe unregulated or rail_signal) - n->myType = SumoXMLNodeType::PRIORITY; - } else if (numNonRailwayNonPed > 2) { - // does not look like a rail crossing (roads in conflict). maybe a traffic light? - WRITE_WARNINGF("Converting invalid rail_crossing to traffic_light at junction '%'.", n->getID()); - TrafficLightType type = SUMOXMLDefinitions::TrafficLightTypes.get(OptionsCont::getOptions().getString("tls.default-type")); - NBTrafficLightDefinition* tlDef = new NBOwnTLDef(n->getID(), n, 0, type); - n->myType = SumoXMLNodeType::TRAFFIC_LIGHT; - if (!tlc.insert(tlDef)) { - // actually, nothing should fail here - n->removeTrafficLight(tlDef); - n->myType = SumoXMLNodeType::PRIORITY; - delete tlDef; - WRITE_WARNINGF("Could not allocate tls '%'.", n->getID()); - } - } - } - } -} - - -bool -NBNodeTypeComputer::isRailwayNode(const NBNode* n) { - bool hasRailway = false; - for (NBEdge* e : n->getIncomingEdges()) { - if ((e->getPermissions() & ~SVC_RAIL_CLASSES) != 0) { - return false; - } else if ((e->getPermissions() & SVC_RAIL_CLASSES) != 0) { - hasRailway = true; - } - } - return hasRailway; -} - -// --------------------------------------------------------------------------- -// NBEdgePriorityComputer -// --------------------------------------------------------------------------- -void -NBEdgePriorityComputer::computeEdgePriorities(NBNodeCont& nc) { - for (const auto& node : nc) { - // preset all junction's edge priorities to zero - for (NBEdge* const edge : node.second->myAllEdges) { - edge->setJunctionPriority(node.second, NBEdge::JunctionPriority::MINOR_ROAD); - } - node.second->markBentPriority(false); - // check if the junction is not a real junction - if (node.second->myIncomingEdges.size() == 1 && node.second->myOutgoingEdges.size() == 1) { - continue; - } - // compute the priorities on junction when needed - if (node.second->getType() != SumoXMLNodeType::RIGHT_BEFORE_LEFT && node.second->getType() != SumoXMLNodeType::ALLWAY_STOP && node.second->getType() != SumoXMLNodeType::NOJUNCTION) { - if (node.second->getRightOfWay() == RightOfWay::EDGEPRIORITY) { - for (NBEdge* e : node.second->getIncomingEdges()) { - e->setJunctionPriority(node.second, e->getPriority()); - } - } else { - setPriorityJunctionPriorities(*node.second); - } - } - } -} - - -void -NBEdgePriorityComputer::setPriorityJunctionPriorities(NBNode& n) { - if (n.myIncomingEdges.size() == 0 || n.myOutgoingEdges.size() == 0) { - return; - } - EdgeVector incoming = n.myIncomingEdges; - EdgeVector outgoing = n.myOutgoingEdges; - // what we do want to have is to extract the pair of roads that are - // the major roads for this junction - // let's get the list of incoming edges with the highest priority - std::sort(incoming.begin(), incoming.end(), NBContHelper::edge_by_priority_sorter()); - EdgeVector bestIncoming; - NBEdge* best = incoming[0]; - while (incoming.size() > 0 && samePriority(best, incoming[0])) { - bestIncoming.push_back(*incoming.begin()); - incoming.erase(incoming.begin()); - } - // now, let's get the list of best outgoing - assert(outgoing.size() != 0); - sort(outgoing.begin(), outgoing.end(), NBContHelper::edge_by_priority_sorter()); - EdgeVector bestOutgoing; - best = outgoing[0]; - while (outgoing.size() > 0 && samePriority(best, outgoing[0])) { //->getPriority()==best->getPriority()) { - bestOutgoing.push_back(*outgoing.begin()); - outgoing.erase(outgoing.begin()); - } - // special case: user input makes mainDirection unambiguous - const bool mainDirectionExplicit = ( - bestIncoming.size() == 1 && n.myIncomingEdges.size() <= 2 - && (incoming.size() == 0 || bestIncoming[0]->getPriority() > incoming[0]->getPriority()) - && bestOutgoing.size() == 1 && n.myOutgoingEdges.size() <= 2 - && (outgoing.size() == 0 || bestOutgoing[0]->getPriority() > outgoing[0]->getPriority()) - && !bestIncoming[0]->isTurningDirectionAt(bestOutgoing[0])); - // now, let's compute for each of the best incoming edges - // the incoming which is most opposite - // the outgoing which is most opposite - EdgeVector::iterator i; - std::map counterIncomingEdges; - std::map counterOutgoingEdges; - incoming = n.myIncomingEdges; - outgoing = n.myOutgoingEdges; - for (i = bestIncoming.begin(); i != bestIncoming.end(); ++i) { - std::sort(incoming.begin(), incoming.end(), NBContHelper::edge_opposite_direction_sorter(*i, &n, true)); - counterIncomingEdges[*i] = *incoming.begin(); - std::sort(outgoing.begin(), outgoing.end(), NBContHelper::edge_opposite_direction_sorter(*i, &n, true)); - counterOutgoingEdges[*i] = *outgoing.begin(); - } - //std::cout << "n=" << n.getID() << " best=" << best->getID() << " bestIncoming=" << toString(bestIncoming) << "\n incoming=" << toString(incoming) << "\n outgoing=" << toString(outgoing) << "\n mainExplicit=" << mainDirectionExplicit << " counterBest=" << counterIncomingEdges.find(bestIncoming[0])->second->getID() << "\n"; - // ok, let's try - // 1) there is one best incoming road - if (bestIncoming.size() == 1) { - // let's mark this road as the best - NBEdge* best1 = extractAndMarkFirst(n, bestIncoming); - if (!mainDirectionExplicit && counterIncomingEdges.find(best1) != counterIncomingEdges.end()) { - // ok, look, what we want is the opposit of the straight continuation edge - // but, what if such an edge does not exist? By now, we'll determine it - // geometrically - NBEdge* s = counterIncomingEdges.find(best1)->second; - const double minAngleDiff = GeomHelper::getMinAngleDiff(best1->getAngleAtNode(&n), s->getAngleAtNode(&n)); - if (minAngleDiff > 180 - 45 - || (minAngleDiff > 75 && s->getPriority() == best1->getPriority() && hasDifferentPriorities(incoming, best1))) { - s->setJunctionPriority(&n, NBEdge::PRIORITY_ROAD); - } - } - markBestParallel(n, best1, nullptr); - assert(bestOutgoing.size() != 0); - // mark the best outgoing as the continuation - sort(bestOutgoing.begin(), bestOutgoing.end(), NBContHelper::edge_similar_direction_sorter(best1)); - // assign extra priority if the priorities are unambiguous (regardless of geometry) - NBEdge* bestOut = extractAndMarkFirst(n, bestOutgoing); - if (!mainDirectionExplicit && counterOutgoingEdges.find(bestOut) != counterOutgoingEdges.end()) { - NBEdge* s = counterOutgoingEdges.find(bestOut)->second; - if (GeomHelper::getMinAngleDiff(bestOut->getAngleAtNode(&n), s->getAngleAtNode(&n)) > 180 - 45) { - s->setJunctionPriority(&n, 1); - } - } - n.markBentPriority(n.getDirection(best1, bestOut) != LinkDirection::STRAIGHT); - return; - } - - // ok, what we want to do in this case is to determine which incoming - // has the best continuation... - // This means, when several incoming roads have the same priority, - // we want a (any) straight connection to be more priorised than a turning - double bestAngle = 0; - NBEdge* bestFirst = nullptr; - NBEdge* bestSecond = nullptr; - bool hadBest = false; - for (i = bestIncoming.begin(); i != bestIncoming.end(); ++i) { - EdgeVector::iterator j; - NBEdge* t1 = *i; - double angle1 = t1->getAngleAtNode(&n) + 180; - if (angle1 >= 360) { - angle1 -= 360; - } - for (j = i + 1; j != bestIncoming.end(); ++j) { - NBEdge* t2 = *j; - double angle2 = t2->getAngleAtNode(&n) + 180; - if (angle2 >= 360) { - angle2 -= 360; - } - double angle = GeomHelper::getMinAngleDiff(angle1, angle2); - if (!hadBest || angle > bestAngle) { - bestAngle = angle; - bestFirst = *i; - bestSecond = *j; - hadBest = true; - } - } - } - bestFirst->setJunctionPriority(&n, 1); - sort(bestOutgoing.begin(), bestOutgoing.end(), NBContHelper::edge_similar_direction_sorter(bestFirst)); - if (bestOutgoing.size() != 0) { - extractAndMarkFirst(n, bestOutgoing); - } - bestSecond->setJunctionPriority(&n, 1); - sort(bestOutgoing.begin(), bestOutgoing.end(), NBContHelper::edge_similar_direction_sorter(bestSecond)); - if (bestOutgoing.size() != 0) { - extractAndMarkFirst(n, bestOutgoing); - } - n.markBentPriority(GeomHelper::getMinAngleDiff(bestFirst->getAngleAtNode(&n), bestSecond->getAngleAtNode(&n)) < 135); - markBestParallel(n, bestFirst, bestSecond); -} - - -void -NBEdgePriorityComputer::markBestParallel(const NBNode& n, NBEdge* bestFirst, NBEdge* bestSecond) { - // edges running parallel to the main direction should also be prioritised - const double a1 = bestFirst->getAngleAtNode(&n); - const double a2 = bestSecond == nullptr ? a1 : bestSecond->getAngleAtNode(&n); - SVCPermissions p1 = bestFirst->getPermissions(); - SVCPermissions p2 = bestSecond == nullptr ? p1 : bestSecond->getPermissions(); - for (NBEdge* e : n.getIncomingEdges()) { - // @note: this rule might also apply if there are common permissions but - // then we would not further rules to resolve the priority between the best edge and its parallel edge - SVCPermissions perm = e->getPermissions(); - if (((GeomHelper::getMinAngleDiff(e->getAngleAtNode(&n), a1) < 10 - || GeomHelper::getMinAngleDiff(e->getAngleAtNode(&n), a2) < 10)) - && (p1 & perm) == 0 && (p2 & perm) == 0) { - e->setJunctionPriority(&n, 1); - } - } -} - - -NBEdge* -NBEdgePriorityComputer::extractAndMarkFirst(NBNode& n, std::vector& s, int prio) { - if (s.size() == 0) { - return nullptr; - } - NBEdge* ret = s.front(); - s.erase(s.begin()); - ret->setJunctionPriority(&n, prio); - return ret; -} - - -bool -NBEdgePriorityComputer::samePriority(const NBEdge* const e1, const NBEdge* const e2) { - if (e1 == e2) { - return true; - } - if (e1->getPriority() != e2->getPriority()) { - return false; - } - if ((int) e1->getSpeed() != (int) e2->getSpeed()) { - return false; - } - return (int) e1->getNumLanes() == (int) e2->getNumLanes(); -} - - -bool -NBEdgePriorityComputer::hasDifferentPriorities(const EdgeVector& edges, const NBEdge* excluded) { - if (edges.size() < 2) { - return false; - } - int prio = edges[0] == excluded ? edges[1]->getPriority() : edges[0]->getPriority(); - for (auto e : edges) { - if (e != excluded && e->getPriority() != prio) { - return true; - } - } - return false; -} - - -NBNodesEdgesSorter::crossing_by_junction_angle_sorter::crossing_by_junction_angle_sorter(const NBNode* node, const EdgeVector& ordering) { - // reorder based on getAngleAtNodeToCenter - myOrdering = ordering; - sort(myOrdering.begin(), myOrdering.end(), NBContHelper::edge_by_angle_to_nodeShapeCentroid_sorter(node)); - // let the first edge remain the first - rotate(myOrdering.begin(), std::find(myOrdering.begin(), myOrdering.end(), ordering.front()), myOrdering.end()); -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netbuild/NBAlgorithms.h b/Util/OSM2ODR/src/netbuild/NBAlgorithms.h deleted file mode 100644 index 6bd841629..000000000 --- a/Util/OSM2ODR/src/netbuild/NBAlgorithms.h +++ /dev/null @@ -1,258 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2012-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NBAlgorithms.h -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @date 02. March 2012 -/// -// Algorithms for network computation -/****************************************************************************/ -#pragma once -#include - -#include -#include "NBEdgeCont.h" -#include "NBNodeCont.h" - -// =========================================================================== -// class declarations -// =========================================================================== -class NBEdge; -class NBNode; - -// =========================================================================== -// class definitions -// =========================================================================== -// --------------------------------------------------------------------------- -// NBTurningDirectionsComputer -// --------------------------------------------------------------------------- -/* @class NBTurningDirectionsComputer - * @brief Computes turnaround destinations for all edges (if exist) - */ -class NBTurningDirectionsComputer { -public: - /** @brief Computes turnaround destinations for all edges (if exist) - * @param[in] nc The container of nodes to loop along - * @param[in] warn Whether warnings shall be issued - */ - static void computeTurnDirections(NBNodeCont& nc, bool warn = true); - - /** @brief Computes turnaround destinations for all incoming edges of the given nodes (if any) - * @param[in] node The node for which to compute turnaround destinations - * @param[in] warn Whether warnings shall be issued - * @note: This is needed by NETEDIT - */ - static void computeTurnDirectionsForNode(NBNode* node, bool warn); - -private: - /** @struct Combination - * @brief Stores the information about the angle between an incoming ("from") and an outgoing ("to") edge - * - * Note that the angle is increased by 360 if the edges connect the same two nodes in - * opposite direction. - */ - struct Combination { - NBEdge* from; - NBEdge* to; - double angle; - }; - - - /** @class combination_by_angle_sorter - * @brief Sorts "Combination"s by decreasing angle - */ - class combination_by_angle_sorter { - public: - explicit combination_by_angle_sorter() { } - int operator()(const Combination& c1, const Combination& c2) const { - if (c1.angle != c2.angle) { - return c1.angle > c2.angle; - } - if (c1.from != c2.from) { - return c1.from->getID() < c2.from->getID(); - } - return c1.to->getID() < c2.to->getID(); - } - }; -}; - - - -// --------------------------------------------------------------------------- -// NBNodesEdgesSorter -// --------------------------------------------------------------------------- -/* @class NBNodesEdgesSorter - * @brief Sorts a node's edges clockwise regarding driving direction - */ -class NBNodesEdgesSorter { -public: - /** @brief Sorts a node's edges clockwise regarding driving direction - * @param[in] nc The container of nodes to loop along - * @param[in] useNodeShape Whether to sort based on the node shape (instead of only the edge angle) - */ - static void sortNodesEdges(NBNodeCont& nc, bool useNodeShape = false); - - /** @class crossing_by_junction_angle_sorter - * @brief Sorts crossings by minimum clockwise clockwise edge angle. Use the - * ordering found in myAllEdges of the given node - */ - class crossing_by_junction_angle_sorter { - public: - explicit crossing_by_junction_angle_sorter(const NBNode* node, const EdgeVector& ordering); - - int operator()(const std::unique_ptr& c1, const std::unique_ptr& c2) const { - const int r1 = getMinRank(c1->edges); - const int r2 = getMinRank(c2->edges); - if (r1 == r2) { - return c1->edges.size() > c2->edges.size(); - } else { - return (int)(r1 < r2); - } - } - - private: - /// @brief retrieves the minimum index in myAllEdges - int getMinRank(const EdgeVector& e) const { - int result = (int)myOrdering.size(); - for (EdgeVector::const_iterator it = e.begin(); it != e.end(); ++it) { - int rank = (int)std::distance(myOrdering.begin(), std::find(myOrdering.begin(), myOrdering.end(), *it)); - result = MIN2(result, rank); - } - return result; - } - - private: - EdgeVector myOrdering; - - private: - /// @brief invalidated assignment operator - crossing_by_junction_angle_sorter& operator=(const crossing_by_junction_angle_sorter& s); - - }; - /** @brief Assures correct order for same-angle opposite-direction edges - * @param[in] n The currently processed node - * @param[in] i1 Pointer to first edge - * @param[in] i2 Pointer to second edge - */ - static void swapWhenReversed(const NBNode* const n, - const std::vector::iterator& i1, - const std::vector::iterator& i2); - - - /** @class edge_by_junction_angle_sorter - * @brief Sorts incoming and outgoing edges clockwise around the given node - */ - class edge_by_junction_angle_sorter { - public: - explicit edge_by_junction_angle_sorter(NBNode* n) : myNode(n) {} - int operator()(NBEdge* e1, NBEdge* e2) const { - return getConvAngle(e1) < getConvAngle(e2); - } - - protected: - /// @brief Converts the angle of the edge if it is an incoming edge - double getConvAngle(NBEdge* e) const { - double angle = e->getAngleAtNode(myNode); - if (angle < 0.) { - angle = 360. + angle; - } - // convert angle if the edge is an outgoing edge - if (e->getFromNode() == myNode) { - angle += (double) 180.; - if (angle >= (double) 360.) { - angle -= (double) 360.; - } - } - if (angle < 0.1 || angle > 359.9) { - angle = (double) 0.; - } - assert(angle >= 0 && angle < (double)360); - return angle; - } - - private: - /// @brief The node to compute the relative angle of - NBNode* myNode; - - }; - -}; - - - -// --------------------------------------------------------------------------- -// NBNodeTypeComputer -// --------------------------------------------------------------------------- -/* @class NBNodeTypeComputer - * @brief Computes node types - */ -class NBNodeTypeComputer { -public: - /** @brief Computes node types - * @param[in] nc The container of nodes to loop along - */ - static void computeNodeTypes(NBNodeCont& nc, NBTrafficLightLogicCont& tlc); - - /** @brief Checks rail_crossing for validity - * @param[in] nc The container of nodes to loop along - */ - static void validateRailCrossings(NBNodeCont& nc, NBTrafficLightLogicCont& tlc); - - /// @brief whether the given node only has rail edges - static bool isRailwayNode(const NBNode* n); -}; - - - -// --------------------------------------------------------------------------- -// NBEdgePriorityComputer -// --------------------------------------------------------------------------- -/* @class NBEdgePriorityComputer - * @brief Computes edge priorities within a node - */ -class NBEdgePriorityComputer { -public: - /** @brief Computes edge priorities within a node - * @param[in] nc The container of nodes to loop along - */ - static void computeEdgePriorities(NBNodeCont& nc); - -private: - /** @brief Sets the priorites in case of a priority junction - * @param[in] n The node to set edges' priorities - */ - static void setPriorityJunctionPriorities(NBNode& n); - - /// @brief set priority for edges that are parallel to the best edges - static void markBestParallel(const NBNode& n, NBEdge* bestFirst, NBEdge* bestSecond); - - /** @brief Sets the priorites in case of a priority junction - * @param[in] n The node to set edges' priorities - * @param[in] s The vector of edges to get and mark the first from - * @param[in] prio The priority to assign - * @return The vector's first edge - */ - static NBEdge* extractAndMarkFirst(NBNode& n, std::vector& s, int prio = 1); - - /** @brief Returns whether both edges have the same priority - * @param[in] e1 The first edge - * @param[in] e2 The second edge - * Whether both edges have the same priority - */ - static bool samePriority(const NBEdge* const e1, const NBEdge* const e2); - - /// @brief return whether the priorite attribute can be used to distinguish the edges - static bool hasDifferentPriorities(const EdgeVector& edges, const NBEdge* excluded); - -}; diff --git a/Util/OSM2ODR/src/netbuild/NBAlgorithms_Railway.cpp b/Util/OSM2ODR/src/netbuild/NBAlgorithms_Railway.cpp deleted file mode 100644 index 76cfab2f7..000000000 --- a/Util/OSM2ODR/src/netbuild/NBAlgorithms_Railway.cpp +++ /dev/null @@ -1,1167 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2012-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NBAlgorithms_Railway.cpp -/// @author Jakob Erdmann -/// @author Melanie Weber -/// @date 29. March 2018 -/// -// Algorithms for highway on-/off-ramps computation -/****************************************************************************/ -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include "NBNetBuilder.h" -#include "NBAlgorithms.h" -#include "NBNodeCont.h" -#include "NBEdgeCont.h" -#include "NBNode.h" -#include "NBEdge.h" -#include "NBVehicle.h" -#include "NBAlgorithms_Railway.h" - -//#define DEBUG_SEQSTOREVERSE -//#define DEBUG_DIRECTION_PRIORITY - -#define DEBUGNODEID "gneJ34" -#define DEBUGNODEID2 "28842974" -#define DEBUGEDGEID "22820560#0" -#define DEBUGCOND(obj) ((obj != 0 && (obj)->getID() == DEBUGNODEID)) - -#define SHARP_THRESHOLD_SAMEDIR 100 -#define SHARP_THRESHOLD 80 - -// =========================================================================== -// static members -// =========================================================================== - -// --------------------------------------------------------------------------- -// Track methods -// --------------------------------------------------------------------------- - -void -NBRailwayTopologyAnalyzer::Track::addSuccessor(Track* track) { - successors.push_back(track); - viaSuccessors.push_back(std::make_pair(track, nullptr)); - minPermissions &= track->edge->getPermissions(); -} - -const std::vector& -NBRailwayTopologyAnalyzer::Track::getSuccessors(SUMOVehicleClass svc) const { - if ((minPermissions & svc) != 0) { - return successors; - } else { - if (svcSuccessors.count(svc) == 0) { - std::vector succ; - for (Track* t : successors) { - if ((t->edge->getPermissions() & svc) != 0) { - succ.push_back(t); - } - } - svcSuccessors[svc] = succ; - } - return svcSuccessors[svc]; - } -} - -const std::vector >& -NBRailwayTopologyAnalyzer::Track::getViaSuccessors(SUMOVehicleClass svc) const { - if ((minPermissions & svc) != 0) { - return viaSuccessors; - } else { - if (svcViaSuccessors.count(svc) == 0) { - std::vector >& succ = svcViaSuccessors[svc]; - for (const Track* const t : successors) { - if ((t->edge->getPermissions() & svc) != 0) { - succ.push_back(std::make_pair(t, nullptr)); - } - } - } - return svcViaSuccessors[svc]; - } -} - -// =========================================================================== -// method definitions -// =========================================================================== -void -NBRailwayTopologyAnalyzer::analyzeTopology(NBNetBuilder& nb) { - getBrokenRailNodes(nb, true); -} - - -void -NBRailwayTopologyAnalyzer::repairTopology(NBNetBuilder& nb) { - extendBidiEdges(nb); - reverseEdges(nb); - addBidiEdgesForBufferStops(nb); - addBidiEdgesBetweenSwitches(nb); - addBidiEdgesForStops(nb); - if (OptionsCont::getOptions().getBool("railway.topology.repair.connect-straight")) { - addBidiEdgesForStraightConnectivity(nb, true); - addBidiEdgesForStraightConnectivity(nb, false); - extendBidiEdges(nb); - } -} - - -void -NBRailwayTopologyAnalyzer::makeAllBidi(NBNetBuilder& nb) { - int numRailEdges = 0; - int numBidiEdges = 0; - int numNotCenterEdges = 0; - int numAddedBidiEdges = 0; - std::string inputfile = OptionsCont::getOptions().getString("railway.topology.all-bidi.input-file"); - std::vector edges; - if (inputfile == "") { - for (NBEdge* edge : nb.getEdgeCont().getAllEdges()) { - edges.push_back(edge); - } - } else { - std::set edgeIDs; - NBHelpers::loadEdgesFromFile(inputfile, edgeIDs); - for (const std::string& edgeID : edgeIDs) { - NBEdge* edge = nb.getEdgeCont().retrieve(edgeID); - if (edge != nullptr) { - edges.push_back(edge); - } - } - } - for (NBEdge* edge : edges) { - if ((edge->getPermissions() & SVC_RAIL_CLASSES) != 0) { - numRailEdges++; - // rebuild connections if given from an earlier network - edge->invalidateConnections(true); - if (!edge->isBidiRail()) { - if (edge->getLaneSpreadFunction() == LaneSpreadFunction::CENTER) { - NBEdge* e2 = addBidiEdge(nb, edge, false); - if (e2 != nullptr) { - numAddedBidiEdges++; - } - } else { - numNotCenterEdges++; - } - } else { - numBidiEdges++; - } - } - } - WRITE_MESSAGE("Added " + toString(numAddedBidiEdges) + " bidi-edges to ensure that all tracks are usable in both directions."); - if (numNotCenterEdges) { - WRITE_WARNING("Ignore " + toString(numNotCenterEdges) + " edges because they have the wrong spreadType"); - } -} - -NBEdge* -NBRailwayTopologyAnalyzer::addBidiEdge(NBNetBuilder& nb, NBEdge* edge, bool update) { - assert(edge->getLaneSpreadFunction() == LaneSpreadFunction::CENTER); - assert(!edge->isBidiRail()); - const std::string id2 = (edge->getID()[0] == '-' - ? edge->getID().substr(1) - : "-" + edge->getID()); - if (nb.getEdgeCont().retrieve(id2) == nullptr) { - NBEdge* e2 = new NBEdge(id2, edge->getToNode(), edge->getFromNode(), - edge, edge->getGeometry().reverse()); - nb.getEdgeCont().insert(e2); - if (update) { - updateTurns(edge); - // reconnected added edges - e2->getFromNode()->invalidateIncomingConnections(); - } - return e2; - } else { - WRITE_WARNING("Could not add bidi-edge '" + id2 + "'."); - return nullptr; - } -} - -void -NBRailwayTopologyAnalyzer::getRailEdges(const NBNode* node, - EdgeVector& inEdges, EdgeVector& outEdges) { - for (NBEdge* e : node->getIncomingEdges()) { - if ((e->getPermissions() & SVC_RAIL_CLASSES) != 0) { - inEdges.push_back(e); - } - } - for (NBEdge* e : node->getOutgoingEdges()) { - if ((e->getPermissions() & SVC_RAIL_CLASSES) != 0) { - outEdges.push_back(e); - } - } -} - - - -std::set -NBRailwayTopologyAnalyzer::getBrokenRailNodes(NBNetBuilder& nb, bool verbose) { - std::set brokenNodes; - OutputDevice& device = OutputDevice::getDevice(verbose - ? OptionsCont::getOptions().getString("railway.topology.output") - : "/dev/null"); - - device.writeXMLHeader("railwayTopology", ""); - std::set railNodes = getRailNodes(nb, verbose); - std::map, std::set > types; - std::set bidiEdges; - std::set bufferStops; - for (NBNode* node : railNodes) { - EdgeVector inEdges, outEdges; - getRailEdges(node, inEdges, outEdges); - types[std::make_pair((int)inEdges.size(), (int)outEdges.size())].insert(node); - for (NBEdge* e : outEdges) { - if (e->isBidiRail() && bidiEdges.count(e->getTurnDestination(true)) == 0) { - NBEdge* primary = e; - NBEdge* secondary = e->getTurnDestination(true); - if (e->getID()[0] == '-') { - std::swap(primary, secondary); - } else if (primary->getID()[0] != '-' && secondary->getID()[0] != '-' && secondary->getID() < primary->getID()) { - std::swap(primary, secondary); - } - if (bidiEdges.count(secondary) == 0) { - // avoid duplicate when both ids start with '-' - bidiEdges.insert(primary); - } - } - } - } - - int numBrokenA = 0; - int numBrokenB = 0; - int numBrokenC = 0; - int numBrokenD = 0; - int numBufferStops = 0; - if (verbose && types.size() > 0) { - WRITE_MESSAGE("Railway nodes by number of incoming,outgoing edges:") - } - device.openTag("legend"); - device.openTag("error"); - device.writeAttr(SUMO_ATTR_ID, "a"); - device.writeAttr("meaning", "edge pair angle supports driving but both are outgoing"); - device.closeTag(); - device.openTag("error"); - device.writeAttr(SUMO_ATTR_ID, "b"); - device.writeAttr("meaning", "edge pair angle supports driving but both are incoming"); - device.closeTag(); - device.openTag("error"); - device.writeAttr(SUMO_ATTR_ID, "c"); - device.writeAttr("meaning", "an incoming edge has a sharp angle to all outgoing edges"); - device.closeTag(); - device.openTag("error"); - device.writeAttr(SUMO_ATTR_ID, "d"); - device.writeAttr("meaning", "an outgoing edge has a sharp angle from all incoming edges"); - device.closeTag(); - device.closeTag(); - - for (auto it : types) { - int numBrokenType = 0; - device.openTag("railNodeType"); - int in = it.first.first; - int out = it.first.second; - device.writeAttr("in", in); - device.writeAttr("out", out); - for (NBNode* n : it.second) { - device.openTag(SUMO_TAG_NODE); - device.writeAttr(SUMO_ATTR_ID, n->getID()); - EdgeVector inRail, outRail; - getRailEdges(n, inRail, outRail); - // check if there is a mismatch between angle and edge direction - // (see above) - - std::string broken = ""; - if (in < 2 && hasStraightPair(n, outRail, outRail)) { - broken += "a"; - numBrokenA++; - } - if (out < 2 && hasStraightPair(n, inRail, inRail)) { - broken += "b"; - numBrokenB++; - } - if (out > 0) { - for (NBEdge* e : inRail) { - EdgeVector tmp; - tmp.push_back(e); - if (allSharp(n, tmp, outRail)) { - broken += "c"; - numBrokenC++; - break; - } - } - } - if (in > 0) { - for (NBEdge* e : outRail) { - EdgeVector tmp; - tmp.push_back(e); - if (allSharp(n, inRail, tmp)) { - broken += "d"; - numBrokenD++; - break; - } - } - } - // do not mark bidi nodes as broken - if (((in == 1 && out == 1) || (in == 2 && out == 2)) - && allBidi(inRail) && allBidi(outRail)) { - broken = ""; - } - - if (broken.size() > 0) { - device.writeAttr("broken", broken); - brokenNodes.insert(n); - numBrokenType++; - } - if (StringUtils::toBool(n->getParameter("buffer_stop", "false"))) { - device.writeAttr("buffer_stop", "true"); - numBufferStops++; - } - device.closeTag(); - } - device.closeTag(); - if (verbose) { - WRITE_MESSAGE(" " + toString(it.first.first) + "," + toString(it.first.second) - + " count: " + toString(it.second.size()) + " broken: " + toString(numBrokenType)); - } - - } - if (verbose) { - WRITE_MESSAGE("Found " + toString(brokenNodes.size()) + " broken railway nodes " - + "(A=" + toString(numBrokenA) - + " B=" + toString(numBrokenB) - + " C=" + toString(numBrokenC) - + " D=" + toString(numBrokenD) - + ")"); - WRITE_MESSAGE("Found " + toString(numBufferStops) + " railway nodes marked as buffer_stop"); - } - - for (NBEdge* e : bidiEdges) { - device.openTag("bidiEdge"); - device.writeAttr(SUMO_ATTR_ID, e->getID()); - device.writeAttr("bidi", e->getTurnDestination(true)->getID()); - device.closeTag(); - } - if (verbose) { - WRITE_MESSAGE("Found " + toString(bidiEdges.size()) + " bidirectional rail edges"); - } - - device.close(); - return brokenNodes; -} - - -std::set -NBRailwayTopologyAnalyzer::getRailNodes(NBNetBuilder& nb, bool verbose) { - std::set railNodes; - - NBEdgeCont& ec = nb.getEdgeCont(); - int numRailEdges = 0; - for (auto it = ec.begin(); it != ec.end(); it++) { - if (isRailway(it->second->getPermissions())) { - numRailEdges++; - railNodes.insert(it->second->getFromNode()); - railNodes.insert(it->second->getToNode()); - - } - } - std::set railSignals; - for (NBNode* node : railNodes) { - if (node->getType() == SumoXMLNodeType::RAIL_SIGNAL) { - railSignals.insert(node); - } - } - if (verbose) { - WRITE_MESSAGE("Found " + toString(numRailEdges) + " railway edges and " + toString(railNodes.size()) + " railway nodes (" + toString(railSignals.size()) + " signals)."); - } - return railNodes; -} - - -bool -NBRailwayTopologyAnalyzer::isStraight(const NBNode* node, const NBEdge* e1, const NBEdge* e2) { - const double relAngle = NBHelpers::normRelAngle(e1->getAngleAtNode(node), e2->getAngleAtNode(node)); - /* - std::cout << " isStraight n=" << node->getID() - << " e1=" << e1->getID() - << " e2=" << e2->getID() - << " a1=" << e1->getAngleAtNode(node) - << " a2=" << e2->getAngleAtNode(node) - << " rel=" << relAngle - << "\n"; - */ - if ((e1->getToNode() == node && e2->getFromNode() == node) - || (e1->getFromNode() == node && e2->getToNode() == node)) { - // edges go in the same direction - return fabs(relAngle) < SHARP_THRESHOLD; - } else { - // edges go in the opposite direction (both incoming or outgoing) - return fabs(relAngle) > SHARP_THRESHOLD_SAMEDIR; - } -} - - -bool -NBRailwayTopologyAnalyzer::hasStraightPair(const NBNode* node, const EdgeVector& edges, - const EdgeVector& edges2) { -#ifdef DEBUG_SEQSTOREVERSE - //if (node->getID() == DEBUGNODEID2) { - // std::cout << " edges=" << toString(edges) << " edges2=" << toString(edges2) << "\n"; - //} -#endif - for (NBEdge* e1 : edges) { - for (NBEdge* e2 : edges2) { - //if (e1->getID() == "195411601#2" && e2->getID() == "93584120#3") { - // std::cout - // << " DEBUG normRelA=" << NBHelpers::normRelAngle( - // e1->getAngleAtNode(node), - // e2->getAngleAtNode(node)) - // << "\n"; - //} - if (e1 != e2 && isStraight(node, e1, e2)) { - return true; - } - } - } - return false; -} - - -bool -NBRailwayTopologyAnalyzer::allBroken(const NBNode* node, NBEdge* candOut, const EdgeVector& in, const EdgeVector& out) { - for (NBEdge* e : in) { - if (e != candOut && isStraight(node, e, candOut)) { - if (gDebugFlag1) { - std::cout << " isStraight e=" << e->getID() << " candOut=" << candOut->getID() << "\n"; - } - return false; - } - } - for (NBEdge* e : out) { - if (e != candOut && !isStraight(node, e, candOut)) { - if (gDebugFlag1) { - std::cout << " isSharp e=" << e->getID() << " candOut=" << candOut->getID() << "\n"; - } - return false; - } - } - return true; -} - - -bool -NBRailwayTopologyAnalyzer::allSharp(const NBNode* node, const EdgeVector& in, const EdgeVector& out, bool countBidiAsSharp) { - bool allBidi = true; - for (NBEdge* e1 : in) { - for (NBEdge* e2 : out) { - if (e1 != e2 && isStraight(node, e1, e2)) { - return false; - } - if (!e1->isBidiRail(true)) { - //std::cout << " allSharp node=" << node->getID() << " e1=" << e1->getID() << " is not bidi\n"; - allBidi = false; - } - } - } - return !allBidi || countBidiAsSharp; -} - - -bool -NBRailwayTopologyAnalyzer::allBidi(const EdgeVector& edges) { - for (NBEdge* e : edges) { - if (!e->isBidiRail()) { - return false; - } - } - return true; -} - - -int -NBRailwayTopologyAnalyzer::extendBidiEdges(NBNetBuilder& nb) { - int added = 0; - NBEdgeCont& ec = nb.getEdgeCont(); - for (auto it = ec.begin(); it != ec.end(); it++) { - NBEdge* e = it->second; - if (e->isBidiRail()) { - added += extendBidiEdges(nb, e->getFromNode(), e->getTurnDestination(true)); - added += extendBidiEdges(nb, e->getToNode(), e); - } - } - if (added > 0) { - WRITE_MESSAGE("Added " + toString(added) + " bidi-edges as extension of existing bidi edges."); - } - return added; -} - - -int -NBRailwayTopologyAnalyzer::extendBidiEdges(NBNetBuilder& nb, NBNode* node, NBEdge* bidiIn) { - assert(bidiIn->getToNode() == node); - NBEdge* bidiOut = bidiIn->getTurnDestination(true); - if (bidiOut == nullptr) { - WRITE_WARNING("Could not find bidi-edge for edge '" + bidiIn->getID() + "'"); - return 0; - } - EdgeVector tmpBidiOut; - tmpBidiOut.push_back(bidiOut); - EdgeVector tmpBidiIn; - tmpBidiIn.push_back(bidiIn); - int added = 0; - EdgeVector inRail, outRail; - getRailEdges(node, inRail, outRail); - for (NBEdge* cand : outRail) { - //std::cout << " extendBidiEdges n=" << node->getID() << " bidiIn=" << bidiIn->getID() << " cand=" << cand->getID() << " isStraight=" << isStraight(node, bidiIn, cand) << " allSharp=" << allSharp(node, inRail, tmpBidiOut, true) << "\n"; - if (!cand->isBidiRail() && isStraight(node, bidiIn, cand) - && cand->getLaneSpreadFunction() == LaneSpreadFunction::CENTER - && allSharp(node, inRail, tmpBidiOut, true)) { - NBEdge* e2 = addBidiEdge(nb, cand); - if (e2 != nullptr) { - added += 1 + extendBidiEdges(nb, cand->getToNode(), cand); - } - } - } - for (NBEdge* cand : inRail) { - //std::cout << " extendBidiEdges n=" << node->getID() << " bidiOut=" << bidiOut->getID() << " cand=" << cand->getID() << " isStraight=" << isStraight(node, cand, bidiOut) << " allSharp=" << allSharp(node, outRail, tmpBidiIn, true) << "\n"; - if (!cand->isBidiRail() && isStraight(node, cand, bidiOut) - && cand->getLaneSpreadFunction() == LaneSpreadFunction::CENTER - && allSharp(node, outRail, tmpBidiIn, true)) { - NBEdge* e2 = addBidiEdge(nb, cand); - if (e2 != nullptr) { - added += 1 + extendBidiEdges(nb, cand->getFromNode(), e2); - } - } - } - return added; -} - - -void -NBRailwayTopologyAnalyzer::reverseEdges(NBNetBuilder& nb) { - std::set brokenNodes = getBrokenRailNodes(nb); - // find reversible edge sequences between broken nodes - std::vector seqsToReverse; - for (NBNode* n : brokenNodes) { - EdgeVector inRail, outRail; - getRailEdges(n, inRail, outRail); - for (NBEdge* start : outRail) { - EdgeVector tmp; - tmp.push_back(start); - // only reverse edges where the node would be unbroken afterwards - if (!allBroken(n, start, inRail, outRail) - || (inRail.size() == 1 && outRail.size() == 1)) { -#ifdef DEBUG_SEQSTOREVERSE - if (n->getID() == DEBUGNODEID) { - std::cout << " abort at start n=" << n->getID() << " (not all broken)\n"; - } -#endif - continue; - } - //std::cout << " get sequences from " << start->getID() << "\n"; - bool forward = true; - EdgeVector seq; - while (forward) { - seq.push_back(start); - //std::cout << " seq=" << toString(seq) << "\n"; - NBNode* n2 = start->getToNode(); - EdgeVector inRail2, outRail2; - getRailEdges(n2, inRail2, outRail2); - if (brokenNodes.count(n2) != 0) { - EdgeVector tmp2; - tmp2.push_back(start); - if (allBroken(n2, start, outRail2, inRail2)) { - seqsToReverse.push_back(seq); - } else { -#ifdef DEBUG_SEQSTOREVERSE - if (n->getID() == DEBUGNODEID) { - std::cout << " abort at n2=" << n2->getID() << " (not all broken)\n"; - } -#endif - } - forward = false; - } else { - if (outRail2.size() == 0) { - // stop at network border - forward = false; -#ifdef DEBUG_SEQSTOREVERSE - if (n->getID() == DEBUGNODEID) { - std::cout << " abort at n2=" << n2->getID() << " (border)\n"; - } -#endif - } else if (outRail2.size() > 1 || inRail2.size() > 1) { - // stop at switch - forward = false; -#ifdef DEBUG_SEQSTOREVERSE - if (n->getID() == DEBUGNODEID) { - std::cout << " abort at n2=" << n2->getID() << " (switch)\n"; - } -#endif - } else { - start = outRail2.front(); - } - } - } - } - } - // sort by sequence length - if (seqsToReverse.size() > 0) { - WRITE_MESSAGE("Found " + toString(seqsToReverse.size()) + " reversible edge sequences between broken rail nodes"); - } - std::sort(seqsToReverse.begin(), seqsToReverse.end(), - [](const EdgeVector & a, const EdgeVector & b) { - return a.size() < b.size(); - }); - int numReversed = 0; - std::set affectedEndpoints; - std::set reversedIDs; - std::map seqLengths; - for (EdgeVector& seq : seqsToReverse) { - NBNode* seqStart = seq.front()->getFromNode(); - NBNode* seqEnd = seq.back()->getToNode(); - // avoid reversing sequenes on both sides of a broken node - if (affectedEndpoints.count(seqStart) == 0 - && affectedEndpoints.count(seqEnd) == 0) { - affectedEndpoints.insert(seqStart); - affectedEndpoints.insert(seqEnd); - //WRITE_MESSAGE(" reversed seq=" + toString(seq)); - for (NBEdge* e : seq) { - e->reinitNodes(e->getToNode(), e->getFromNode()); - e->setGeometry(e->getGeometry().reverse()); - reversedIDs.insert(e->getID()); - } - seqLengths[(int)seq.size()]++; - numReversed++; - } - } - if (numReversed > 0) { - WRITE_MESSAGE("Reversed " + toString(numReversed) + " sequences (count by length: " + joinToString(seqLengths, " ", ":") + ")"); - for (auto& item : nb.getPTStopCont().getStops()) { - if (reversedIDs.count(item.second->getEdgeId())) { - item.second->findLaneAndComputeBusStopExtent(nb.getEdgeCont()); - } - } - } -} - - -void -NBRailwayTopologyAnalyzer::addBidiEdgesForBufferStops(NBNetBuilder& nb) { - std::set brokenNodes = getBrokenRailNodes(nb); - std::set railNodes = getRailNodes(nb); - // find buffer stops and ensure that thay are connect to the network in both directions - int numBufferStops = 0; - int numAddedBidiTotal = 0; - for (NBNode* node : railNodes) { - if (StringUtils::toBool(node->getParameter("buffer_stop", "false"))) { - if (node->getEdges().size() != 1) { - WRITE_WARNING("Ignoring buffer stop junction '" + node->getID() + "' with " + toString(node->getEdges().size()) + " edges\n"); - continue; - } - int numAddedBidi = 0; - numBufferStops++; - NBEdge* prev = nullptr; - NBEdge* prev2 = nullptr; - EdgeVector inRail, outRail; - getRailEdges(node, inRail, outRail); - bool addAway = true; // add new edges away from buffer stop - while (prev == nullptr || (inRail.size() + outRail.size()) == 3) { - NBEdge* e = nullptr; - if (prev == nullptr) { - assert(node->getEdges().size() == 1); - e = node->getEdges().front(); - addAway = node == e->getToNode(); - } else { - if (addAway) { - // XXX if node is broken we need to switch direction - assert(inRail.size() == 2); - e = inRail.front() == prev2 ? inRail.back() : inRail.front(); - } else { - // XXX if node is broken we need to switch direction - assert(outRail.size() == 2); - e = outRail.front() == prev2 ? outRail.back() : outRail.front(); - } - } - e->setLaneSpreadFunction(LaneSpreadFunction::CENTER); - NBNode* e2From = nullptr; - NBNode* e2To = nullptr; - if (addAway) { - e2From = node; - e2To = e->getFromNode(); - node = e2To; - } else { - e2From = e->getToNode(); - e2To = node; - node = e2From; - } - NBEdge* e2 = addBidiEdge(nb, e); - if (e2 == nullptr) { - break; - } - prev = e; - prev2 = e2; - numAddedBidi++; - numAddedBidiTotal++; - inRail.clear(); - outRail.clear(); - getRailEdges(node, inRail, outRail); - } - //if (numAddedBidi > 0) { - // WRITE_MESSAGE(" added " + toString(numAddedBidi) + " edges between buffer stop junction '" + bufferStop->getID() + "' and junction '" + node->getID() + "'"); - //} - } - } - if (numAddedBidiTotal > 0) { - WRITE_MESSAGE("Added " + toString(numAddedBidiTotal) + " edges to connect " + toString(numBufferStops) + " buffer stops in both directions."); - } -} - -NBEdge* -NBRailwayTopologyAnalyzer::isBidiSwitch(const NBNode* n) { - EdgeVector inRail, outRail; - getRailEdges(n, inRail, outRail); - if (inRail.size() == 2 && outRail.size() == 1 && isStraight(n, inRail.front(), inRail.back())) { - if (isStraight(n, inRail.front(), outRail.front())) { - return inRail.front(); - } else if (isStraight(n, inRail.back(), outRail.front())) { - return inRail.back(); - } - } - if (inRail.size() == 1 && outRail.size() == 2 && isStraight(n, outRail.front(), outRail.back())) { - if (isStraight(n, outRail.front(), inRail.front())) { - return outRail.front(); - } else if (isStraight(n, outRail.back(), inRail.front())) { - return outRail.back(); - } - } - return nullptr; -} - - -void -NBRailwayTopologyAnalyzer::addBidiEdgesBetweenSwitches(NBNetBuilder& nb) { - std::set brokenNodes = getBrokenRailNodes(nb); - std::map seqLengths; - int numAdded = 0; - int numSeqs = 0; - for (NBNode* n : brokenNodes) { - NBEdge* edge = isBidiSwitch(n); - if (edge != nullptr) { - std::vector nodeSeq; - EdgeVector edgeSeq; - NBNode* prev = n; - nodeSeq.push_back(prev); - edgeSeq.push_back(edge); - bool forward = true; - //std::cout << "Looking for potential bidi-edge sequence starting at junction '" << n->getID() << "' with edge '" + edge->getID() << "'\n"; - // find a suitable end point for adding bidi edges - while (forward) { - NBNode* next = edge->getFromNode() == prev ? edge->getToNode() : edge->getFromNode(); - EdgeVector allRail; - getRailEdges(next, allRail, allRail); - if (allRail.size() == 2 && isStraight(next, allRail.front(), allRail.back())) { - prev = next; - edge = allRail.front() == edge ? allRail.back() : allRail.front(); - nodeSeq.push_back(prev); - edgeSeq.push_back(edge); - } else { - forward = false; - EdgeVector inRail2, outRail2; - getRailEdges(next, inRail2, outRail2); - if (isBidiSwitch(next) == edge) { - // suitable switch found as endpoint, add reverse edges - //WRITE_MESSAGE("Adding " + toString(edgeSeq.size()) - // + " bidi-edges between switches junction '" + n->getID() + "' and junction '" + next->getID() + "'"); - for (NBEdge* e : edgeSeq) { - addBidiEdge(nb, e); - } - seqLengths[(int)edgeSeq.size()]++; - numSeqs++; - numAdded += (int)edgeSeq.size(); - } else { - //std::cout << " sequence ended at junction " << next->getID() - // << " in=" << inRail2.size() - // << " out=" << outRail2.size() - // << " bidiSwitch=" << Named::getIDSecure(isBidiSwitch(next)) - // << "\n"; - } - - } - } - - } - } - if (seqLengths.size() > 0) { - WRITE_MESSAGE("Added " + toString(numAdded) + " bidi-edges between " + toString(numSeqs) + " pairs of railway switches (count by length: " + joinToString(seqLengths, " ", ":") + ")"); - } -} - - -void -NBRailwayTopologyAnalyzer::addBidiEdgesForStops(NBNetBuilder& nb) { - // generate bidirectional routing graph - NBEdgeCont& ec = nb.getEdgeCont(); - std::vector tracks; - for (NBEdge* edge : nb.getEdgeCont().getAllEdges()) { - tracks.push_back(new Track(edge)); - } - const int numEdges = (int)tracks.size(); - for (NBEdge* edge : nb.getEdgeCont().getAllEdges()) { - tracks.push_back(new Track(edge, (int)tracks.size(), edge->getID() + "_reverse")); - } - // add special tracks for starting end ending in both directions - std::map > stopTracks; - for (NBEdge* edge : nb.getEdgeCont().getAllEdges()) { - if ((edge->getPermissions() & SVC_RAIL_CLASSES) != 0) { - Track* start = new Track(edge, (int)tracks.size(), edge->getID() + "_start"); - tracks.push_back(start); - Track* end = new Track(edge, (int)tracks.size(), edge->getID() + "_end"); - tracks.push_back(end); - stopTracks[edge] = std::make_pair(start, end); - } - } - // set successors based on angle (connections are not yet built) - for (NBNode* node : getRailNodes(nb)) { - EdgeVector railEdges; - getRailEdges(node, railEdges, railEdges); - for (NBEdge* e1 : railEdges) { - for (NBEdge* e2 : railEdges) { - if (e1 != e2 && isStraight(node, e1, e2)) { - int i = e1->getNumericalID(); - int i2 = e2->getNumericalID(); - if (e1->getToNode() == node) { - if (e2->getFromNode() == node) { - // case 1) plain forward connection - tracks[i]->addSuccessor(tracks[i2]); - // reverse edge (numerical id incremented by numEdges) - tracks[i2 + numEdges]->addSuccessor(tracks[i + numEdges]); - } else { - // case 2) both edges pointing towards each ohter - tracks[i]->addSuccessor(tracks[i2 + numEdges]); - tracks[i2]->addSuccessor(tracks[i + numEdges]); - } - } else { - if (e2->getFromNode() == node) { - // case 3) both edges pointing away from each other - tracks[i + numEdges]->addSuccessor(tracks[i2]); - tracks[i2 + numEdges]->addSuccessor(tracks[i]); - } else { - // already handled via case 1) - } - } - - } - } - } - } - // define start and end successors - for (auto& item : stopTracks) { - const int index = item.first->getNumericalID(); - // start - item.second.first->addSuccessor(tracks[index]); - item.second.first->addSuccessor(tracks[index + numEdges]); - // end - tracks[index]->addSuccessor(item.second.second); - tracks[index + numEdges]->addSuccessor(item.second.second); - } - // DEBUG - /* - for (Track* t : tracks) { - std::cout << "track " << t->getID() << " e=" << t->edge->getID() << " i=" << t->getNumericalID() << " succ:\n"; - for (Track* s : t->getSuccessors(SVC_IGNORING)) { - std::cout << " succ=" << s->getID() << "\n"; - } - } - */ - - SUMOAbstractRouter* const router = new DijkstraRouter( - tracks, true, &NBRailwayTopologyAnalyzer::getTravelTimeStatic, nullptr, true); - - int added = 0; - int numDisconnected = 0; - std::set addBidiStops; - std::set addBidiEdges; - std::set > visited; - for (const auto& item : nb.getPTLineCont().getLines()) { - NBPTLine* line = item.second; - std::vector stops = line->getStopEdges(ec); - NBEdge* routeStart = line->getRouteStart(ec); - NBEdge* routeEnd = line->getRouteEnd(ec); - if (routeStart != nullptr) { - stops.insert(stops.begin(), routeStart); - } - if (routeEnd != nullptr) { - stops.push_back(routeEnd); - } - if (stops.size() < 2) { - continue; - } - for (auto it = stops.begin(); it + 1 != stops.end(); ++it) { - NBEdge* fromEdge = *it; - NBEdge* toEdge = *(it + 1); - std::pair trip(fromEdge, toEdge); - //std::cout << " trip=" << Named::getIDSecure(fromEdge) << "->" << Named::getIDSecure(toEdge) << " visited=" << (visited.count(trip) != 0) << "\n"; - if (visited.count(trip) != 0) { - continue; - } else { - visited.insert(trip); - } - if (stopTracks.count(fromEdge) == 0 - || stopTracks.count(toEdge) == 0) { - continue; - } - NBVehicle veh(line->getRef(), (SUMOVehicleClass)(fromEdge->getPermissions() & SVC_RAIL_CLASSES)); - std::vector route; - router->compute(stopTracks[fromEdge].first, stopTracks[toEdge].second, &veh, 0, route); - //if (fromEdge->getID() == "356053025#1" && toEdge->getID() == "23256161") { - // std::cout << "DEBUG: route=" << toString(route) << "\n"; - //} - if (route.size() > 0) { - assert(route.size() > 2); - for (int i = 1; i < (int)route.size() - 1; ++i) { - if (route[i]->getNumericalID() >= numEdges) { - NBEdge* edge = route[i]->edge; - if (addBidiEdges.count(edge) == 0) { - if (!edge->isBidiRail(true)) { - bool isStop = i == 1 || i == (int)route.size() - 2; - if (edge->getLaneSpreadFunction() == LaneSpreadFunction::CENTER) { - addBidiEdges.insert(edge); - if (isStop) { - addBidiStops.insert(edge); - } - } else { - if (isStop) { - WRITE_WARNING("Stop on edge " + fromEdge->getID() + " can only be reached in reverse but edge has the wrong spreadType"); - } - } - } - } - } - } - } else { - WRITE_WARNING("No connection found between stops on edge '" + fromEdge->getID() + "' and edge '" + toEdge->getID() + "'"); - numDisconnected++; - } - } - } - for (NBEdge* edge : addBidiEdges) { - if (!edge->isBidiRail()) { - NBEdge* e2 = addBidiEdge(nb, edge); - //std::cout << " add bidiEdge for stop at edge " << edge->getID() << "\n"; - if (e2 != nullptr) { - added++; - added += extendBidiEdges(nb, edge->getToNode(), edge); - added += extendBidiEdges(nb, edge->getFromNode(), e2); - } - } - } - - if (addBidiEdges.size() > 0 || numDisconnected > 0) { - WRITE_MESSAGE("Added " + toString(addBidiStops.size()) + " bidi-edges for public transport stops and a total of " - + toString(added) + " bidi-edges to ensure connectivity of stops (" - + toString(numDisconnected) + " stops remain disconnected)"); - } - - // clean up - for (Track* t : tracks) { - delete t; - } - delete router; -} - - -void -NBRailwayTopologyAnalyzer::addBidiEdgesForStraightConnectivity(NBNetBuilder& nb, bool geometryLike) { - int added = 0; - std::set brokenNodes = getBrokenRailNodes(nb); - for (const auto& e : nb.getEdgeCont()) { - if (!isRailway(e.second->getPermissions())) { - continue; - } - NBNode* const from = e.second->getFromNode(); - NBNode* const to = e.second->getToNode(); - if (brokenNodes.count(from) == 0 && brokenNodes.count(to) == 0) { - continue; - } - if (e.second->isBidiRail()) { - continue; - } - EdgeVector inRailFrom, outRailFrom, inRailTo, outRailTo; - getRailEdges(from, inRailFrom, outRailFrom); - getRailEdges(to, inRailTo, outRailTo); - // check whether there is a straight edge pointing away from this one at the from-node - // and there is no straight incoming edge at the from-node - bool haveStraight = false; - bool haveStraightReverse = false; - if (!geometryLike || outRailFrom.size() + inRailFrom.size() == 2) { - for (const NBEdge* fromStraightCand : outRailFrom) { - if (fromStraightCand != e.second && isStraight(from, fromStraightCand, e.second)) { - haveStraightReverse = true; - //std::cout << " haveStraightReverse outRailFrom=" << fromStraightCand->getID() << "\n"; - break; - } - } - if (haveStraightReverse) { - for (const NBEdge* fromStraightCand : inRailFrom) { - if (fromStraightCand != e.second && isStraight(from, fromStraightCand, e.second)) { - haveStraight = true; - //std::cout << " haveStraight inRailFrom=" << fromStraightCand->getID() << "\n"; - break; - } - } - } - } - if ((!haveStraightReverse || haveStraight) && (!geometryLike || outRailTo.size() + inRailTo.size() == 2)) { - // check whether there is a straight edge pointing towards this one at the to-node - // and there is no straight outoing edge at the to-node - haveStraight = false; - haveStraightReverse = false; - for (const NBEdge* toStraightCand : inRailTo) { - if (toStraightCand != e.second && isStraight(to, toStraightCand, e.second)) { - haveStraightReverse = true; - //std::cout << " haveStraightReverse inRailTo=" << toStraightCand->getID() << "\n"; - break; - } - } - if (haveStraightReverse) { - for (const NBEdge* toStraightCand : outRailTo) { - if (toStraightCand != e.second && isStraight(to, toStraightCand, e.second)) { - haveStraight = true; - //std::cout << " haveStraightReverse outRailTo=" << toStraightCand->getID() << "\n"; - break; - } - } - } - } - //std::cout << "edge=" << e.second->getID() << " haveStraight=" << haveStraight << " haveStraightReverse=" << haveStraightReverse << "\n"; - if (haveStraightReverse && !haveStraight) { - NBEdge* e2 = addBidiEdge(nb, e.second); - //std::cout << " add bidiEdge for straight connectivity at edge " << e.second->getID() << " fromBroken=" << brokenNodes.count(from) << " toBroken=" << brokenNodes.count(to) << "\n"; - if (e2 != nullptr) { - added++; - added += extendBidiEdges(nb, to, e.second); - added += extendBidiEdges(nb, from, e2); - } - } - } - if (added > 0) { - if (geometryLike) { - WRITE_MESSAGE("Added " + toString(added) + " bidi-edges to ensure connectivity of straight tracks at geometry-like nodes."); - } else { - WRITE_MESSAGE("Added " + toString(added) + " bidi-edges to ensure connectivity of straight tracks at switches."); - } - } -} - - -void -NBRailwayTopologyAnalyzer::updateTurns(NBEdge* edge) { - NBTurningDirectionsComputer::computeTurnDirectionsForNode(edge->getFromNode(), false); - NBTurningDirectionsComputer::computeTurnDirectionsForNode(edge->getToNode(), false); -} - - -double -NBRailwayTopologyAnalyzer::getTravelTimeStatic(const Track* const track, const NBVehicle* const veh, double time) { - return NBEdge::getTravelTimeStatic(track->edge, veh, time); -} - -void -NBRailwayTopologyAnalyzer::assignDirectionPriority(NBNetBuilder& nb) { - // assign priority value for each railway edge: - // 4: edge is unidirectional - // 3: edge is in main direction of bidirectional track - // 2: edge is part of bidirectional track, main direction unknown - both edges are extensions of unidirectional edges - // 1: edge is part of bidirectional track, main direction unknown - neither edge is an extension of a unidirectional edge - // 0: edge is part of bidirectional track in reverse of main direction - - EdgeSet bidi; - EdgeSet uni; - for (NBEdge* edge : nb.getEdgeCont().getAllEdges()) { - if (isRailway(edge->getPermissions())) { - if (!edge->isBidiRail()) { - edge->setPriority(4); - uni.insert(edge); - } else { - bidi.insert(edge); - } - } - } - if (uni.size() == 0) { - if (bidi.size() != 0) { - WRITE_WARNING("Cannot assign track direction priority because there are no unidirectional tracks"); - } - return; - } - EdgeSet seen; - EdgeSet check = uni; - EdgeSet forward; - while (!check.empty()) { - NBEdge* edge = *check.begin(); - check.erase(edge); - if (seen.count(edge) != 0) { - continue; - } - seen.insert(edge); - NBEdge* straightOut = edge->getStraightContinuation(edge->getPermissions()); - if (straightOut != nullptr && straightOut->getStraightPredecessor(straightOut->getPermissions()) == edge) { - forward.insert(straightOut); - check.insert(straightOut); - } - NBEdge* straightIn = edge->getStraightPredecessor(edge->getPermissions()); - if (straightIn != nullptr && straightIn->getStraightContinuation(straightIn->getPermissions()) == edge) { - forward.insert(straightIn); - check.insert(straightIn); - } -#ifdef DEBUG_DIRECTION_PRIORITY - std::cout << "edge=" << edge->getID() << " in=" << Named::getIDSecure(straightIn) << " out=" << Named::getIDSecure(straightOut) - << " outPred=" << (straightOut != nullptr ? Named::getIDSecure(straightOut->getStraightPredecessor(straightOut->getPermissions())) : "") - << " inSucc=" << (straightIn != nullptr ? Named::getIDSecure(straightIn->getStraightContinuation(straightIn->getPermissions())) : "") - << "\n"; -#endif - } - - for (NBEdge* edge : bidi) { - NBEdge* bidiEdge = const_cast(edge->getBidiEdge()); - if (forward.count(edge) != 0) { - if (forward.count(bidiEdge) == 0) { - edge->setPriority(3); - bidiEdge->setPriority(0); - } else { - // both forward - edge->setPriority(2); - bidiEdge->setPriority(2); - } - } else { - if (forward.count(bidiEdge) != 0) { - edge->setPriority(0); - bidiEdge->setPriority(3); - } else { - // neither forward - edge->setPriority(1); - bidiEdge->setPriority(1); - } - } - } - std::map numPrios; - for (NBEdge* edge : bidi) { - numPrios[edge->getPriority()]++; - } - WRITE_MESSAGE("Assigned edge priority based on main direction: " + joinToString(numPrios, " ", ":") + ".") -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netbuild/NBAlgorithms_Railway.h b/Util/OSM2ODR/src/netbuild/NBAlgorithms_Railway.h deleted file mode 100644 index c0443c16c..000000000 --- a/Util/OSM2ODR/src/netbuild/NBAlgorithms_Railway.h +++ /dev/null @@ -1,146 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2012-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NBAlgorithms_Railway.h -/// @author Jakob Erdmann -/// @author Melanie Weber -/// @date 29. March 2018 -/// -// Algorithms for railways -/****************************************************************************/ -#pragma once -#include - -#include -#include "NBEdge.h" - - -// =========================================================================== -// class declarations -// =========================================================================== -class NBNetBuilder; -class OptionsCont; -class NBVehicle; - - -// =========================================================================== -// class definitions -// =========================================================================== -// --------------------------------------------------------------------------- -// NBAlgorithms_Railway -// --------------------------------------------------------------------------- -/* @class NBRampsComputer - * @brief Computes highway on-/off-ramps (if wished) - */ -class NBRailwayTopologyAnalyzer { -public: - /** @brief Computes highway on-/off-ramps (if wished) - * @param[in, changed] nb The network builder which contains the current network representation - * @param[in] oc The options container - */ - static void analyzeTopology(NBNetBuilder& nb); - static void repairTopology(NBNetBuilder& nb); - static void makeAllBidi(NBNetBuilder& nb); - static void assignDirectionPriority(NBNetBuilder& nb); - - /// routing edge - class Track { - public: - Track(NBEdge* e, int i = -1, const std::string& _id = "") : - edge(e), - index(i < 0 ? edge->getNumericalID() : i), - id(_id == "" ? edge->getID() : _id), - minPermissions(edge->getPermissions()) { - } - - void addSuccessor(Track* track); - const std::vector& getSuccessors(SUMOVehicleClass svc = SVC_IGNORING) const; - const std::vector >& getViaSuccessors(SUMOVehicleClass svc = SVC_IGNORING) const; - - const std::string& getID() const { - return id; - } - int getNumericalID() const { - return index; - } - double getLength() const { - return 0.; - } - const Track* getBidiEdge() const { - return this; - } - bool isInternal() const { - return false; - } - inline bool prohibits(const NBVehicle* const /*veh*/) const { - return false; - } - inline bool restricts(const NBVehicle* const /*veh*/) const { - return false; - } - - NBEdge* edge; - - private: - const int index; - const std::string id; - std::vector successors; - std::vector > viaSuccessors; - SVCPermissions minPermissions; - mutable std::map > svcSuccessors; - mutable std::map > > svcViaSuccessors; - - Track& operator=(const Track&) = delete; - }; - static double getTravelTimeStatic(const Track* const track, const NBVehicle* const veh, double time); - -private: - static std::set getRailNodes(NBNetBuilder& nb, bool verbose = false); - static std::set getBrokenRailNodes(NBNetBuilder& nb, bool verbose = false); - - /// @brief filter out rail edges among all edges of a the given node - static void getRailEdges(const NBNode* node, EdgeVector& inEdges, EdgeVector& outEdges); - - static bool isStraight(const NBNode* node, const NBEdge* e1, const NBEdge* e2); - static bool hasStraightPair(const NBNode* node, const EdgeVector& edges, const EdgeVector& edges2); - static bool allBroken(const NBNode* node, NBEdge* candOut, const EdgeVector& in, const EdgeVector& out); - static bool allSharp(const NBNode* node, const EdgeVector& in, const EdgeVector& out, bool countBidiAsSharp = false); - static bool allBidi(const EdgeVector& edges); - static NBEdge* isBidiSwitch(const NBNode* n); - - /// @brief add bidi-edge for the given edge - static NBEdge* addBidiEdge(NBNetBuilder& nb, NBEdge* edge, bool update = true); - - /// @brief add further bidi-edges near existing bidi-edges - static int extendBidiEdges(NBNetBuilder& nb); - static int extendBidiEdges(NBNetBuilder& nb, NBNode* node, NBEdge* bidiIn); - - /// @brief reverse edges sequences that are to broken nodes on both sides - static void reverseEdges(NBNetBuilder& nb); - - /// @brief add bidi-edges to connect buffers stops in both directions - static void addBidiEdgesForBufferStops(NBNetBuilder& nb); - - /// @brief add bidi-edges to connect switches that are approached in both directions - static void addBidiEdgesBetweenSwitches(NBNetBuilder& nb); - - /// @brief add bidi-edges to connect successive public transport stops - static void addBidiEdgesForStops(NBNetBuilder& nb); - - /// @brief add bidi-edges to connect straight tracks - static void addBidiEdgesForStraightConnectivity(NBNetBuilder& nb, bool geometryLike); - - /// recompute turning directions for both nodes of the given edge - static void updateTurns(NBEdge* edge); - -}; diff --git a/Util/OSM2ODR/src/netbuild/NBAlgorithms_Ramps.cpp b/Util/OSM2ODR/src/netbuild/NBAlgorithms_Ramps.cpp deleted file mode 100644 index 3f6c0ec46..000000000 --- a/Util/OSM2ODR/src/netbuild/NBAlgorithms_Ramps.cpp +++ /dev/null @@ -1,633 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2012-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NBAlgorithms_Ramps.cpp -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date 29. March 2012 -/// -// Algorithms for highway on-/off-ramps computation -/****************************************************************************/ -#include - -#include -#include -#include -#include -#include "NBNetBuilder.h" -#include "NBNodeCont.h" -#include "NBNode.h" -#include "NBEdge.h" -#include "NBAlgorithms_Ramps.h" - -#define OFFRAMP_LOOKBACK 500 - -//#define DEBUG_RAMPS -#define DEBUGNODEID "260479469" -#define DEBUGCOND(obj) ((obj != 0 && (obj)->getID() == DEBUGNODEID)) - -// =========================================================================== -// static members -// =========================================================================== -const std::string NBRampsComputer::ADDED_ON_RAMP_EDGE("-AddedOnRampEdge"); - -// =========================================================================== -// method definitions -// =========================================================================== -// --------------------------------------------------------------------------- -// NBRampsComputer -// --------------------------------------------------------------------------- -void -NBRampsComputer::computeRamps(NBNetBuilder& nb, OptionsCont& oc) { - const bool guessAndAdd = oc.getBool("ramps.guess"); - const double minHighwaySpeed = oc.getFloat("ramps.min-highway-speed"); - const double maxRampSpeed = oc.getFloat("ramps.max-ramp-speed"); - const double rampLength = oc.getFloat("ramps.ramp-length"); - const double minWeaveLength = oc.getFloat("ramps.min-weave-length"); - const bool dontSplit = oc.getBool("ramps.no-split"); - NBEdgeCont& ec = nb.getEdgeCont(); - std::set incremented; - // collect join exclusions - std::set noramps; - if (oc.isSet("ramps.unset")) { - std::vector edges = oc.getStringVector("ramps.unset"); - noramps.insert(edges.begin(), edges.end()); - } - // exclude roundabouts - const std::set& roundabouts = ec.getRoundabouts(); - for (std::set::const_iterator it_round = roundabouts.begin(); - it_round != roundabouts.end(); ++it_round) { - for (EdgeSet::const_iterator it_edge = it_round->begin(); it_edge != it_round->end(); ++it_edge) { - noramps.insert((*it_edge)->getID()); - } - } - // exclude public transport edges - nb.getPTStopCont().addEdges2Keep(oc, noramps); - nb.getPTLineCont().addEdges2Keep(oc, noramps); - nb.getParkingCont().addEdges2Keep(oc, noramps); - - // check whether on-off ramps shall be guessed - if (guessAndAdd || oc.getBool("ramps.guess-acceleration-lanes")) { - NBNodeCont& nc = nb.getNodeCont(); - NBEdgeCont& ec = nb.getEdgeCont(); - NBDistrictCont& dc = nb.getDistrictCont(); - for (auto it = ec.begin(); it != ec.end(); ++it) { - it->second->markOffRamp(false); - } - - // if an edge is part of two ramps, ordering is important - std::set potOnRamps; - std::set potOffRamps; - for (std::map::const_iterator i = nc.begin(); i != nc.end(); ++i) { - NBNode* cur = (*i).second; - if (mayNeedOnRamp(cur, minHighwaySpeed, maxRampSpeed, noramps, minWeaveLength)) { - potOnRamps.insert(cur); - } - if (mayNeedOffRamp(cur, minHighwaySpeed, maxRampSpeed, noramps)) { - potOffRamps.insert(cur); - } - } - for (std::set::const_iterator i = potOnRamps.begin(); i != potOnRamps.end(); ++i) { - buildOnRamp(*i, nc, ec, dc, rampLength, dontSplit || !guessAndAdd, guessAndAdd); - } - for (std::set::const_iterator i = potOffRamps.begin(); i != potOffRamps.end(); ++i) { - buildOffRamp(*i, nc, ec, dc, rampLength, dontSplit || !guessAndAdd, guessAndAdd, potOnRamps); - } - } - // check whether on-off ramps are specified - if (oc.isSet("ramps.set")) { - std::vector edges = oc.getStringVector("ramps.set"); - NBNodeCont& nc = nb.getNodeCont(); - NBEdgeCont& ec = nb.getEdgeCont(); - NBDistrictCont& dc = nb.getDistrictCont(); - std::set potOnRamps; - for (std::vector::iterator i = edges.begin(); i != edges.end(); ++i) { - NBEdge* e = ec.retrieve(*i); - if (noramps.count(*i) != 0) { - WRITE_WARNING("Can not build ramp on edge '" + *i + "' - the edge is unsuitable."); - continue; - } - if (e == nullptr) { - WRITE_WARNING("Can not build on ramp on edge '" + *i + "' - the edge is not known."); - continue; - } - NBNode* from = e->getFromNode(); - if (from->getIncomingEdges().size() == 2 && from->getOutgoingEdges().size() == 1) { - buildOnRamp(from, nc, ec, dc, rampLength, dontSplit, true); - potOnRamps.insert(from); - } - // load edge again to check offramps - e = ec.retrieve(*i); - if (e == nullptr) { - WRITE_WARNING("Can not build off ramp on edge '" + *i + "' - the edge is not known."); - continue; - } - NBNode* to = e->getToNode(); - if (to->getIncomingEdges().size() == 1 && to->getOutgoingEdges().size() == 2) { - buildOffRamp(to, nc, ec, dc, rampLength, dontSplit, true, potOnRamps); - } - } - } -} - - -bool -NBRampsComputer::mayNeedOnRamp(NBNode* cur, double minHighwaySpeed, double maxRampSpeed, const std::set& noramps, double minWeaveLength) { - if (cur->getOutgoingEdges().size() != 1 || cur->getIncomingEdges().size() != 2) { - return false; - } - NBEdge* potHighway, *potRamp, *cont; - getOnRampEdges(cur, &potHighway, &potRamp, &cont); - // may be an on-ramp - if (fulfillsRampConstraints(potHighway, potRamp, cont, minHighwaySpeed, maxRampSpeed, noramps)) { - // prevent short weaving section - double seen = cont->getLength(); - while (seen < minWeaveLength) { - if (cont->getToNode()->getOutgoingEdges().size() > 1) { - return false; - } else if (cont->getToNode()->getOutgoingEdges().size() == 0) { - return true; - } - cont = cont->getToNode()->getOutgoingEdges().front(); - seen += cont->getLength(); - } - return true; - } else { - return false; - } -} - - -bool -NBRampsComputer::mayNeedOffRamp(NBNode* cur, double minHighwaySpeed, double maxRampSpeed, const std::set& noramps) { - if (cur->getIncomingEdges().size() != 1 || cur->getOutgoingEdges().size() != 2) { - return false; - } - // may be an off-ramp - NBEdge* potHighway, *potRamp, *prev; - getOffRampEdges(cur, &potHighway, &potRamp, &prev); - return fulfillsRampConstraints(potHighway, potRamp, prev, minHighwaySpeed, maxRampSpeed, noramps); -} - - -void -NBRampsComputer::buildOnRamp(NBNode* cur, NBNodeCont& nc, NBEdgeCont& ec, NBDistrictCont& dc, double rampLength, bool dontSplit, bool addLanes) { - NBEdge* potHighway, *potRamp, *cont; - getOnRampEdges(cur, &potHighway, &potRamp, &cont); -#ifdef DEBUG_RAMPS - if (DEBUGCOND(cur)) { - std::cout << "buildOnRamp cur=" << cur->getID() << " hw=" << potHighway->getID() << " ramp=" << potRamp->getID() << " cont=" << cont->getID() << "\n"; - } -#endif - // compute the number of lanes to append - const int firstLaneNumber = cont->getNumLanes(); - int toAdd = (potRamp->getNumLanes() + potHighway->getNumLanes()) - firstLaneNumber; - NBEdge* first = cont; - NBEdge* last = cont; - NBEdge* curr = cont; - std::set incremented; - if (addLanes && toAdd > 0 && std::find(incremented.begin(), incremented.end(), cont) == incremented.end()) { - double currLength = 0; - while (curr != nullptr && currLength + curr->getGeometry().length() - POSITION_EPS < rampLength) { - if (find(incremented.begin(), incremented.end(), curr) == incremented.end()) { - curr->incLaneNo(toAdd); - if (curr->getStep() < NBEdge::EdgeBuildingStep::LANES2LANES_USER) { - curr->invalidateConnections(true); - } - incremented.insert(curr); - moveRampRight(curr, toAdd); - currLength += curr->getGeometry().length(); // !!! loaded length? - last = curr; - // mark acceleration lanes - for (int i = 0; i < curr->getNumLanes() - potHighway->getNumLanes(); ++i) { - curr->setAcceleration(i, true); - } - } - NBNode* nextN = curr->getToNode(); - if (nextN->getOutgoingEdges().size() == 1 && nextN->getIncomingEdges().size() == 1) { - curr = nextN->getOutgoingEdges()[0]; - if (curr->getNumLanes() != firstLaneNumber) { - // the number of lanes changes along the computation; we'll stop... - curr = nullptr; - } else if (curr->isTurningDirectionAt(last)) { - // turnarounds certainly should not be included in a ramp - curr = nullptr; - } else if (curr == potHighway || curr == potRamp) { - // circular connectivity. do not split! - curr = nullptr; - } - } else { - // ambigous; and, in fact, what should it be? ...stop - curr = nullptr; - } - } - // check whether a further split is necessary - if (curr != nullptr && !dontSplit && currLength - POSITION_EPS < rampLength && curr->getNumLanes() == firstLaneNumber && std::find(incremented.begin(), incremented.end(), curr) == incremented.end()) { - // there is enough place to build a ramp; do it - bool wasFirst = first == curr; - NBNode* rn = new NBNode(curr->getID() + "-AddedOnRampNode", curr->getGeometry().positionAtOffset(rampLength - currLength)); - if (!nc.insert(rn)) { - throw ProcessError("Ups - could not build on-ramp for edge '" + curr->getID() + "' (node could not be build)!"); - } - std::string name = curr->getID(); - bool ok = ec.splitAt(dc, curr, rn, curr->getID() + ADDED_ON_RAMP_EDGE, curr->getID(), curr->getNumLanes() + toAdd, curr->getNumLanes()); - if (!ok) { - WRITE_ERROR("Ups - could not build on-ramp for edge '" + curr->getID() + "'!"); - return; - } - //ec.retrieve(name)->invalidateConnections(); - curr = ec.retrieve(name + ADDED_ON_RAMP_EDGE); - incremented.insert(curr); - last = curr; - moveRampRight(curr, toAdd); - if (wasFirst) { - first = curr; - } - // mark acceleration lanes - for (int i = 0; i < curr->getNumLanes() - potHighway->getNumLanes(); ++i) { - curr->setAcceleration(i, true); - } - } - if (curr == cont && dontSplit && addLanes) { - WRITE_WARNING("Could not build on-ramp for edge '" + curr->getID() + "' due to option '--ramps.no-split'"); - return; - } - } else { - // mark acceleration lanes - for (int i = 0; i < firstLaneNumber - potHighway->getNumLanes(); ++i) { - cont->setAcceleration(i, true); - } - } - // set connections from ramp/highway to added ramp - if (addLanes) { - if (potHighway->getStep() < NBEdge::EdgeBuildingStep::LANES2LANES_USER) { - if (!potHighway->addLane2LaneConnections(0, first, potRamp->getNumLanes(), MIN2(first->getNumLanes() - potRamp->getNumLanes(), potHighway->getNumLanes()), NBEdge::Lane2LaneInfoType::VALIDATED, true)) { - throw ProcessError("Could not set connection!"); - } - } - if (potRamp->getStep() < NBEdge::EdgeBuildingStep::LANES2LANES_USER) { - if (!potRamp->addLane2LaneConnections(0, first, 0, potRamp->getNumLanes(), NBEdge::Lane2LaneInfoType::VALIDATED, true)) { - throw ProcessError("Could not set connection!"); - } - } - patchRampGeometry(potRamp, first, potHighway, false); - } -} - - -void -NBRampsComputer::buildOffRamp(NBNode* cur, NBNodeCont& nc, NBEdgeCont& ec, NBDistrictCont& dc, double rampLength, bool dontSplit, bool addLanes, - const std::set& potOnRamps) { - NBEdge* potHighway, *potRamp, *prev; - getOffRampEdges(cur, &potHighway, &potRamp, &prev); -#ifdef DEBUG_RAMPS - if (DEBUGCOND(cur)) { - std::cout << "buildOffRamp cur=" << cur->getID() << " hw=" << potHighway->getID() << " ramp=" << potRamp->getID() << " prev=" << prev->getID() << "\n"; - } -#endif - // compute the number of lanes to append - const int firstLaneNumber = prev->getNumLanes(); - int toAdd = (potRamp->getNumLanes() + potHighway->getNumLanes()) - firstLaneNumber; - NBEdge* first = prev; - NBEdge* last = prev; - NBEdge* curr = prev; - std::set incremented; - if (addLanes && toAdd > 0 && std::find(incremented.begin(), incremented.end(), prev) == incremented.end()) { - double currLength = 0; - while (curr != nullptr && currLength + curr->getGeometry().length() - POSITION_EPS < rampLength) { - if (find(incremented.begin(), incremented.end(), curr) == incremented.end()) { - curr->incLaneNo(toAdd); - if (curr->getStep() < NBEdge::EdgeBuildingStep::LANES2LANES_USER) { - curr->invalidateConnections(true); - } - incremented.insert(curr); - moveRampRight(curr, toAdd); - currLength += curr->getGeometry().length(); // !!! loaded length? - last = curr; - } - NBNode* prevN = curr->getFromNode(); - if (prevN->getIncomingEdges().size() == 1 && prevN->getOutgoingEdges().size() == 1) { - curr = prevN->getIncomingEdges()[0]; - if (curr->getStep() < NBEdge::EdgeBuildingStep::LANES2LANES_USER && toAdd != 0) { - // curr might be an onRamp. In this case connections need to be rebuilt - curr->invalidateConnections(); - } - if (curr->getNumLanes() != firstLaneNumber) { - // the number of lanes changes along the computation; we'll stop... - curr = nullptr; - } else if (last->isTurningDirectionAt(curr)) { - // turnarounds certainly should not be included in a ramp - curr = nullptr; - } else if (curr == potHighway || curr == potRamp) { - // circular connectivity. do not split! - curr = nullptr; - } - } else { - // ambigous; and, in fact, what should it be? ...stop - curr = nullptr; - } - } - // check whether a further split is necessary - if (curr != nullptr && !dontSplit && currLength - POSITION_EPS < rampLength && curr->getNumLanes() == firstLaneNumber && std::find(incremented.begin(), incremented.end(), curr) == incremented.end()) { - // there is enough place to build a ramp; do it - bool wasFirst = first == curr; - Position pos = curr->getGeometry().positionAtOffset(curr->getGeometry().length() - (rampLength - currLength)); - NBNode* rn = new NBNode(curr->getID() + "-AddedOffRampNode", pos); - if (!nc.insert(rn)) { - throw ProcessError("Ups - could not build off-ramp for edge '" + curr->getID() + "' (node could not be build)!"); - } - std::string name = curr->getID(); - bool ok = ec.splitAt(dc, curr, rn, curr->getID(), curr->getID() + "-AddedOffRampEdge", curr->getNumLanes(), curr->getNumLanes() + toAdd); - if (!ok) { - WRITE_ERROR("Ups - could not build off-ramp for edge '" + curr->getID() + "'!"); - return; - } - curr = ec.retrieve(name + "-AddedOffRampEdge"); - incremented.insert(curr); - last = curr; - moveRampRight(curr, toAdd); - if (wasFirst) { - first = curr; - } - } - if (curr == prev && dontSplit && addLanes) { - WRITE_WARNING("Could not build off-ramp for edge '" + curr->getID() + "' due to option '--ramps.no-split'"); - return; - } - } - NBEdge* toMark = first; - toMark->markOffRamp(true); - double markedLength = toMark->getLoadedLength(); - while (markedLength < OFFRAMP_LOOKBACK) { - if (toMark != first && toMark->getToNode()->getOutgoingEdges().size() != 1) { - break; - } - NBNode* from = toMark->getFromNode(); - if (from->getIncomingEdges().size() == 1) { - toMark = from->getIncomingEdges()[0]; - } else if (potOnRamps.count(from) == 1) { - NBEdge* potOnRamp, *cont; - getOnRampEdges(from, &toMark, &potOnRamp, &cont); - } else { - break; - } - toMark->markOffRamp(true); - markedLength += toMark->getLoadedLength(); - } - // set connections from added ramp to ramp/highway - if (addLanes) { - if (first->getStep() < NBEdge::EdgeBuildingStep::LANES2LANES_USER) { - if (!first->addLane2LaneConnections(potRamp->getNumLanes(), potHighway, 0, MIN2(first->getNumLanes() - 1, potHighway->getNumLanes()), NBEdge::Lane2LaneInfoType::VALIDATED, true)) { - throw ProcessError("Could not set connection!"); - } - if (!first->addLane2LaneConnections(0, potRamp, 0, potRamp->getNumLanes(), NBEdge::Lane2LaneInfoType::VALIDATED, false)) { - throw ProcessError("Could not set connection!"); - } - } - patchRampGeometry(potRamp, first, potHighway, true); - } -} - - -void -NBRampsComputer::moveRampRight(NBEdge* ramp, int addedLanes) { - if (ramp->getLaneSpreadFunction() != LaneSpreadFunction::CENTER) { - return; - } - try { - PositionVector g = ramp->getGeometry(); - const double offset = (0.5 * addedLanes * - (ramp->getLaneWidth() == NBEdge::UNSPECIFIED_WIDTH ? SUMO_const_laneWidth : ramp->getLaneWidth())); - g.move2side(offset); - ramp->setGeometry(g); - } catch (InvalidArgument&) { - WRITE_WARNING("For edge '" + ramp->getID() + "': could not compute shape."); - } -} - - -bool -NBRampsComputer::determinedBySpeed(NBEdge** potHighway, NBEdge** potRamp) { - if (fabs((*potHighway)->getSpeed() - (*potRamp)->getSpeed()) < .1) { - return false; - } - if ((*potHighway)->getSpeed() < (*potRamp)->getSpeed()) { - std::swap(*potHighway, *potRamp); - } - return true; -} - - -bool -NBRampsComputer::determinedByLaneNumber(NBEdge** potHighway, NBEdge** potRamp) { - if ((*potHighway)->getNumLanes() == (*potRamp)->getNumLanes()) { - return false; - } - if ((*potHighway)->getNumLanes() < (*potRamp)->getNumLanes()) { - std::swap(*potHighway, *potRamp); - } - return true; -} - - -void -NBRampsComputer::getOnRampEdges(NBNode* n, NBEdge** potHighway, NBEdge** potRamp, NBEdge** other) { - *other = n->getOutgoingEdges()[0]; - const std::vector& edges = n->getIncomingEdges(); - assert(edges.size() == 2); - *potHighway = edges[0]; - *potRamp = edges[1]; - /* - // heuristic: highway is faster than ramp - if(determinedBySpeed(potHighway, potRamp)) { - return; - } - // heuristic: highway has more lanes than ramp - if(determinedByLaneNumber(potHighway, potRamp)) { - return; - } - */ - // heuristic: ramp comes from right - if (NBContHelper::relative_incoming_edge_sorter(*other)(*potRamp, *potHighway)) { - std::swap(*potHighway, *potRamp); - } -} - - -void -NBRampsComputer::getOffRampEdges(NBNode* n, NBEdge** potHighway, NBEdge** potRamp, NBEdge** other) { - *other = n->getIncomingEdges()[0]; - const std::vector& edges = n->getOutgoingEdges(); - *potHighway = edges[0]; - *potRamp = edges[1]; - assert(edges.size() == 2); - /* - // heuristic: highway is faster than ramp - if(determinedBySpeed(potHighway, potRamp)) { - return; - } - // heuristic: highway has more lanes than ramp - if(determinedByLaneNumber(potHighway, potRamp)) { - return; - } - */ - // heuristic: ramp goes to right - const std::vector& edges2 = n->getEdges(); -#ifdef DEBUG_RAMPS - if (DEBUGCOND(n)) { - std::cout << " edges=" << toString(edges) << " edges2=" << toString(edges2) << "\n"; - } -#endif - std::vector::const_iterator i = std::find(edges2.begin(), edges2.end(), *other); - NBContHelper::nextCW(edges2, i); - if ((*i) == *potRamp) { - std::swap(*potHighway, *potRamp); - } - // the following would be better but runs afoul of misleading angles when both edges - // have the same geometry start point but different references lanes are - // chosen for NBEdge::computeAngle() - //if (NBContHelper::relative_outgoing_edge_sorter(*other)(*potHighway, *potRamp)) { - // std::swap(*potHighway, *potRamp); - //} -} - - -bool -NBRampsComputer::fulfillsRampConstraints( - NBEdge* potHighway, NBEdge* potRamp, NBEdge* other, double minHighwaySpeed, double maxRampSpeed, - const std::set& noramps) { - // check modes that are not appropriate for rampsdo not build ramps on rail edges - if (hasWrongMode(potHighway) || hasWrongMode(potRamp) || hasWrongMode(other)) { - return false; - } - // do not build ramps at traffic lights - if (NBNode::isTrafficLight(potRamp->getToNode()->getType())) { - return false; - } - // do not build ramps on connectors - if (potHighway->isMacroscopicConnector() || potRamp->isMacroscopicConnector() || other->isMacroscopicConnector()) { - return false; - } - // check whether a lane is missing - if (potHighway->getNumLanes() + potRamp->getNumLanes() < other->getNumLanes()) { - return false; - } - // is it really a highway? - double maxSpeed = MAX3(potHighway->getSpeed(), other->getSpeed(), potRamp->getSpeed()); - if (maxSpeed < minHighwaySpeed) { - return false; - } - // is any of the connections a turnaround? - if (other->getToNode() == potHighway->getFromNode()) { - // off ramp - if (other->isTurningDirectionAt(potHighway) || - other->isTurningDirectionAt(potRamp)) { - return false; - } - } else { - // on ramp - if (other->isTurningDirectionAt(potHighway) || - other->isTurningDirectionAt(potRamp)) { - return false; - } - } - // are the angles between highway and other / ramp and other more or less straight? - const NBNode* node = ((potHighway->getToNode() == potRamp->getToNode() && potHighway->getToNode() == other->getFromNode()) - ? potHighway->getToNode() : potHighway->getFromNode()); - double angle = fabs(NBHelpers::relAngle(potHighway->getAngleAtNode(node), other->getAngleAtNode(node))); - if (angle >= 60) { - return false; - } - angle = fabs(NBHelpers::relAngle(potRamp->getAngleAtNode(node), other->getAngleAtNode(node))); - if (angle >= 60) { - return false; - } - /* - if (potHighway->getSpeed() < minHighwaySpeed || other->getSpeed() < minHighwaySpeed) { - return false; - } - */ - // is it really a ramp? - if (maxRampSpeed > 0 && maxRampSpeed < potRamp->getSpeed()) { - return false; - } - if (noramps.find(other->getID()) != noramps.end()) { - return false; - } - return true; -} - - -bool -NBRampsComputer::hasWrongMode(NBEdge* edge) { - // must allow passenger vehicles - if ((edge->getPermissions() & SVC_PASSENGER) == 0) { - return true; - } - // must not have a green verge or a lane that is only for soft modes - for (int i = 0; i < (int)edge->getNumLanes(); ++i) { - if ((edge->getPermissions(i) & ~(SVC_PEDESTRIAN | SVC_BICYCLE)) == 0) { - return true; - } - } - return false; -} - -void -NBRampsComputer::patchRampGeometry(NBEdge* potRamp, NBEdge* first, NBEdge* potHighway, bool onRamp) { - // geometry of first and highway should allign on the left side - if (first->getLaneSpreadFunction() == LaneSpreadFunction::CENTER && first->hasDefaultGeometryEndpoints()) { - const NBNode* n = onRamp ? potHighway->getToNode() : potHighway->getFromNode(); - if (potHighway->hasDefaultGeometryEndpointAtNode(n)) { - PositionVector p2 = first->getGeometry(); - try { - p2.move2side((first->getNumLanes() - potHighway->getNumLanes()) * first->getLaneWidth(0) * 0.5); - first->setGeometry(p2); - } catch (InvalidArgument&) {} - } - } - - // ramp should merge smoothly with first - PositionVector p = potRamp->getGeometry(); - double offset = 0; - int firstIndex = MAX2(0, MIN2(potRamp->getNumLanes(), first->getNumLanes()) - 1); - if (potRamp->getLaneSpreadFunction() == LaneSpreadFunction::RIGHT) { - offset = -first->getLaneWidth(firstIndex) / 2; - } else { - if (firstIndex % 2 == 1) { - // even number of lanes - offset = -first->getLaneWidth(firstIndex / 2) / 2; - } - firstIndex /= 2; // integer division - } - // reset lane shape (might be affected by earlier junctions.join step. see #947) - first->resetLaneShapes(); - PositionVector l = first->getLaneShape(firstIndex); - try { - l.move2side(offset); - } catch (InvalidArgument&) {} - //std::cout << " ramp=" << potRamp->getID() << " firstIndex=" << firstIndex << " offset=" << offset << " l=" << l << "\n"; - - if (onRamp) { - p[0] = l[-1]; - } else { - p.pop_back(); - p.push_back(l[0]); - } - potRamp->setGeometry(p); - -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netbuild/NBAlgorithms_Ramps.h b/Util/OSM2ODR/src/netbuild/NBAlgorithms_Ramps.h deleted file mode 100644 index 20e89f869..000000000 --- a/Util/OSM2ODR/src/netbuild/NBAlgorithms_Ramps.h +++ /dev/null @@ -1,139 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2012-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NBAlgorithms_Ramps.h -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @date 29. March 2012 -/// -// Algorithms for highway on-/off-ramps computation -/****************************************************************************/ -#pragma once -#include - -#include - - -// =========================================================================== -// class declarations -// =========================================================================== -class NBNetBuilder; -class OptionsCont; -class NBNode; -class NBEdgeCont; -class NBDistrictCont; - - -// =========================================================================== -// class definitions -// =========================================================================== -// --------------------------------------------------------------------------- -// NBAlgorithms_Ramps -// --------------------------------------------------------------------------- -/* @class NBRampsComputer - * @brief Computes highway on-/off-ramps (if wished) - */ -class NBRampsComputer { -public: - /** @brief Computes highway on-/off-ramps (if wished) - * @param[in, changed] nb The network builder which contains the current network representation - * @param[in] oc The options container - */ - static void computeRamps(NBNetBuilder& nb, OptionsCont& oc); - - /// @brief suffix for newly generated on-ramp edges - static const std::string ADDED_ON_RAMP_EDGE; - -private: - /** @brief Determines whether the given node may be an on-ramp begin - * @param[in] cur The node to check - * @param[in] minHighwaySpeed The minimum speed limit a highway must have for being a highway - * @param[in] maxRampSpeed The maximum speed limit a ramp must have for being a ramp - * @param[in] noramps Edges that shall not be treated as ramps - * @param[in] minWeaveLength The minimum length for weaving areas - * @return Whether the node is assumed to be an on-ramp begin - */ - static bool mayNeedOnRamp(NBNode* cur, double minHighwaySpeed, double maxRampSpeed, - const std::set& noramps, double minWeaveLength); - - - /** @brief Determines whether the given node may be an off-ramp end - * @param[in] cur The node to check - * @param[in] minHighwaySpeed The minimum speed limit a highway must have for being a highway - * @param[in] maxRampSpeed The maximum speed limit a ramp must have for being a ramp - * @param[in] noramps Edges that shall not be treated as ramps - * @return Whether the node is assumed to be an off-ramp end - */ - static bool mayNeedOffRamp(NBNode* cur, double minHighwaySpeed, double maxRampSpeed, - const std::set& noramps); - - - /** @brief Builds an on-ramp starting at the given node - * @param[in] cur The node at which the on-ramp shall begin - * @param[in] nc The container of nodes - * @param[in] ec The container of edges - * @param[in] dc The container of districts - * @param[in] rampLength The wished ramp length - * @param[in] dontSplit Whether no edges shall be split - * @param[in, filled] incremented The list of edges which lane number was already incremented - */ - static void buildOnRamp(NBNode* cur, NBNodeCont& nc, NBEdgeCont& ec, NBDistrictCont& dc, double rampLength, bool dontSplit, bool addLanes); - - - /** @brief Builds an off-ramp ending at the given node - * @param[in] cur The node at which the off-ramp shall end - * @param[in] nc The container of nodes - * @param[in] ec The container of edges - * @param[in] dc The container of districts - * @param[in] rampLength The wished ramp length - * @param[in] dontSplit Whether no edges shall be split - * @param[in, filled] incremented The list of edges which lane number was already incremented - */ - static void buildOffRamp(NBNode* cur, NBNodeCont& nc, NBEdgeCont& ec, NBDistrictCont& dc, double rampLength, bool dontSplit, bool addLanes, - const std::set& potOnRamps); - - - static void getOnRampEdges(NBNode* n, NBEdge** potHighway, NBEdge** potRamp, NBEdge** other); - static void getOffRampEdges(NBNode* n, NBEdge** potHighway, NBEdge** potRamp, NBEdge** other); - static bool determinedBySpeed(NBEdge** potHighway, NBEdge** potRamp); - static bool determinedByLaneNumber(NBEdge** potHighway, NBEdge** potRamp); - - /** @brief Checks whether an on-/off-ramp can be bult here - * - * - none of the participating edges must be a macroscopic connector - * - ramp+highways together must have more lanes than the continuation - * - speeds must match the defined swells - * @param[in] potHighway The highway part to check - * @param[in] potRamp The ramp part to check - * @param[in] other The successor/predecessor edge - * @param[in] minHighwaySpeed The minimum speed limit a highway must have for being a highway - * @param[in] maxRampSpeed The maximum speed limit a ramp must have for being a ramp - * @param[in] noramps Edges that shall not be treated as ramps - * @return Whether a ramp can be built here - */ - static bool fulfillsRampConstraints(NBEdge* potHighway, NBEdge* potRamp, NBEdge* other, double minHighwaySpeed, double maxRampSpeed, - const std::set& noramps); - - - /** @brief Moves the ramp to the right, as new lanes were added - * @param[in] ramp The ramp to move - * @param[in] addedLanes The number of added lanes - */ - static void moveRampRight(NBEdge* ramp, int addedLanes); - - /// @brief whether the edge has a mode that does not indicate a ramp edge - static bool hasWrongMode(NBEdge* edge); - - /// @brief shift ramp geometry to merge smoothly with the motorway - static void patchRampGeometry(NBEdge* potRamp, NBEdge* first, NBEdge* potHighway, bool onRamp); -}; diff --git a/Util/OSM2ODR/src/netbuild/NBCapacity2Lanes.h b/Util/OSM2ODR/src/netbuild/NBCapacity2Lanes.h deleted file mode 100644 index 6f4caeecb..000000000 --- a/Util/OSM2ODR/src/netbuild/NBCapacity2Lanes.h +++ /dev/null @@ -1,74 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NBCapacity2Lanes.h -/// @author Daniel Krajzewicz -/// @author Sascha Krieg -/// @date Fri, 19 Jul 2002 -/// -// A helper class which computes the lane number from given capacity -/****************************************************************************/ -#pragma once -#include - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NBCapacity2Lanes - * @brief A helper class which computes the lane number from given capacity - * - * A helper class for the computation of the number of lanes an edge has - * in dependence to this edge's capacity. The computation is done by the - * (trivial) assumption, the number of lanes increases linear with the - * number of lanes. - */ -class NBCapacity2Lanes { -public: - /** @brief Donstructor - * - * @param[in] divider Value for the norming divider - */ - NBCapacity2Lanes(double divider) : myDivider(divider) { } - - - /// @brief Destructor - ~NBCapacity2Lanes() { } - - - /** @brief Returns the number of lanes computed from the given capacity - * - * Returns the estimated number of lanes by returning the given capacity - * divided by the norming divider given in the constructor. - * - * @param[in] capacity The capacity to convert - * @return The capacity converted to the number of lanes - */ - int get(double capacity) const { - capacity /= myDivider; - if (capacity > (int) capacity) { - capacity += 1; - } - // just assure that the number of lanes is not zero - if (capacity == 0) { - capacity = 1; - } - return (int) capacity; - } - -private: - /// @brief The norming divider - double myDivider; - -}; diff --git a/Util/OSM2ODR/src/netbuild/NBConnection.cpp b/Util/OSM2ODR/src/netbuild/NBConnection.cpp deleted file mode 100644 index 484380fd1..000000000 --- a/Util/OSM2ODR/src/netbuild/NBConnection.cpp +++ /dev/null @@ -1,267 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NBConnection.cpp -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date Sept 2002 -/// -// The class holds a description of a connection between two edges -/****************************************************************************/ -#include - -#include -#include -#include -#include "NBEdgeCont.h" -#include "NBEdge.h" -#include "NBConnection.h" - - -// =========================================================================== -// static members -// =========================================================================== -const int NBConnection::InvalidTlIndex = -1; -const NBConnection NBConnection::InvalidConnection("invalidFrom", nullptr, "invalidTo", nullptr); - -// =========================================================================== -// method definitions -// =========================================================================== -NBConnection::NBConnection(NBEdge* from, NBEdge* to) : - myFrom(from), myTo(to), - myFromID(from->getID()), myToID(to->getID()), - myFromLane(-1), myToLane(-1), - myTlIndex(InvalidTlIndex), - myTlIndex2(InvalidTlIndex) { -} - - -NBConnection::NBConnection(const std::string& fromID, NBEdge* from, - const std::string& toID, NBEdge* to) : - myFrom(from), myTo(to), - myFromID(fromID), myToID(toID), - myFromLane(-1), myToLane(-1), - myTlIndex(InvalidTlIndex), - myTlIndex2(InvalidTlIndex) { -} - - -NBConnection::NBConnection(NBEdge* from, int fromLane, - NBEdge* to, int toLane, int tlIndex, int tlIndex2) : - myFrom(from), myTo(to), - myFromLane(fromLane), myToLane(toLane), - myTlIndex(tlIndex), - myTlIndex2(tlIndex2) { - /* @todo what should we assert here? - assert(myFromLane<0||from->getNumLanes()>(int) myFromLane); - assert(myToLane<0||to->getNumLanes()>(int) myToLane); - */ - myFromID = from != nullptr ? from->getID() : ""; - myToID = to != nullptr ? to->getID() : ""; -} - - -NBConnection::~NBConnection() {} - - -NBConnection::NBConnection(const NBConnection& c) : - myFrom(c.myFrom), myTo(c.myTo), - myFromID(c.myFromID), myToID(c.myToID), - myFromLane(c.myFromLane), myToLane(c.myToLane), - myTlIndex(c.myTlIndex), - myTlIndex2(c.myTlIndex2) { -} - - -NBEdge* -NBConnection::getFrom() const { - return myFrom; -} - - -NBEdge* -NBConnection::getTo() const { - return myTo; -} - - -bool -NBConnection::replaceFrom(NBEdge* which, NBEdge* by) { - if (myFrom == which) { - myFrom = by; - if (myFrom != nullptr) { - myFromID = myFrom->getID(); - } else { - myFromID = "invalidFrom"; - } - return true; - } - return false; -} - - -bool -NBConnection::replaceFrom(NBEdge* which, int whichLane, - NBEdge* by, int byLane) { - if (myFrom == which && (myFromLane == whichLane || myFromLane < 0 || whichLane < 0)) { - myFrom = by; - if (myFrom != nullptr) { - myFromID = myFrom->getID(); - } else { - myFromID = "invalidFrom"; - } - if (byLane >= 0) { - myFromLane = byLane; - } - return true; - } - return false; -} - - -bool -NBConnection::replaceTo(NBEdge* which, NBEdge* by) { - if (myTo == which) { - myTo = by; - if (myTo != nullptr) { - myToID = myTo->getID(); - } else { - myToID = "invalidTo"; - } - return true; - } - return false; -} - - -bool -NBConnection::replaceTo(NBEdge* which, int whichLane, - NBEdge* by, int byLane) { - if (myTo == which && (myToLane == whichLane || myFromLane < 0 || whichLane < 0)) { - myTo = by; - if (myTo != nullptr) { - myToID = myTo->getID(); - } else { - myToID = "invalidTo"; - } - if (byLane >= 0) { - myToLane = byLane; - } - return true; - } - return false; -} - - -bool -operator<(const NBConnection& c1, const NBConnection& c2) { - if (c1.myFromID != c2.myFromID) { - return c1.myFromID < c2.myFromID; - } - if (c1.myToID != c2.myToID) { - return c1.myToID < c2.myToID; - } - if (c1.myFromLane != c2.myFromLane) { - return c1.myFromLane < c2.myFromLane; - } - return c1.myToLane < c2.myToLane; -} - - -bool -NBConnection::operator==(const NBConnection& c) const { - return (myFrom == c.myFrom && myTo == c.myTo && - myFromID == c.myFromID && myToID == c.myToID && - myFromLane == c.myFromLane && myToLane == c.myToLane && - myTlIndex == c.myTlIndex && - myTlIndex2 == c.myTlIndex2); -} - - -bool -NBConnection::check(const NBEdgeCont& ec) { - myFrom = checkFrom(ec); - myTo = checkTo(ec); - return myFrom != nullptr && myTo != nullptr; -} - - -NBEdge* -NBConnection::checkFrom(const NBEdgeCont& ec) { - NBEdge* e = ec.retrieve(myFromID); - // ok, the edge was not changed - if (e == myFrom) { - return myFrom; - } - // try to get the edge - return ec.retrievePossiblySplit(myFromID, myToID, true); -} - - -NBEdge* -NBConnection::checkTo(const NBEdgeCont& ec) { - NBEdge* e = ec.retrieve(myToID); - // ok, the edge was not changed - if (e == myTo) { - return myTo; - } - // try to get the edge - return ec.retrievePossiblySplit(myToID, myFromID, false); -} - - -std::string -NBConnection::getID() const { - std::stringstream str; - str << myFromID << "_" << myFromLane << "->" << myToID << "_" << myToLane; - return str.str(); -} - - -int -NBConnection::getFromLane() const { - return myFromLane; -} - - -int -NBConnection::getToLane() const { - return myToLane; -} - - -void -NBConnection::shiftLaneIndex(NBEdge* edge, int offset, int threshold) { - if (myFrom == edge && myFromLane > threshold) { - myFromLane += offset; - } else if (myTo == edge && myToLane > threshold) { - myToLane += offset; - } -} - - -std::ostream& -operator<<(std::ostream& os, const NBConnection& c) { - os - << "Con(from=" << Named::getIDSecure(c.getFrom()) - << " fromLane=" << c.getFromLane() - << " to=" << Named::getIDSecure(c.getTo()) - << " toLane=" << c.getToLane() - << " tlIndex=" << c.getTLIndex() - << ")"; - return os; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netbuild/NBConnection.h b/Util/OSM2ODR/src/netbuild/NBConnection.h deleted file mode 100644 index d8e020a06..000000000 --- a/Util/OSM2ODR/src/netbuild/NBConnection.h +++ /dev/null @@ -1,147 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NBConnection.h -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Sascha Krieg -/// @date Sept 2002 -/// -// The class holds a description of a connection between two edges -/****************************************************************************/ -#pragma once -#include - -#include -#include "NBEdge.h" - - -// =========================================================================== -// class declarations -// =========================================================================== -class NBNode; - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NBConnection - */ -class NBConnection { -public: - /// @brief Constructor - NBConnection(NBEdge* from, NBEdge* to); - - /// @brief Constructor - NBConnection(NBEdge* from, int fromLane, NBEdge* to, int toLane, int tlIndex = InvalidTlIndex, int tlIndex2 = InvalidTlIndex); - - /// @brief Constructor - NBConnection(const std::string& fromID, NBEdge* from, - const std::string& toID, NBEdge* to); - - /// @brief Constructor - NBConnection(const NBConnection& c); - - /// @brief Destructor - virtual ~NBConnection(); - - /// @brief returns the from-edge (start of the connection) - NBEdge* getFrom() const; - - /// @brief returns the to-edge (end of the connection) - NBEdge* getTo() const; - - /// @brief replaces the from-edge by the one given - bool replaceFrom(NBEdge* which, NBEdge* by); - - /// @brief replaces the from-edge by the one given - bool replaceFrom(NBEdge* which, int whichLane, NBEdge* by, int byLane); - - /// @brief replaces the to-edge by the one given - bool replaceTo(NBEdge* which, NBEdge* by); - - /// @brief replaces the to-edge by the one given - bool replaceTo(NBEdge* which, int whichLane, NBEdge* by, int byLane); - - /** @brief patches lane indices refering to the given edge and above the - * threshold by the given offset */ - void shiftLaneIndex(NBEdge* edge, int offset, int threshold = -1); - - /// @brief checks whether the edges are still valid - bool check(const NBEdgeCont& ec); - - /// @brief returns the from-lane - int getFromLane() const; - - /// @brief returns the to-lane - int getToLane() const; - - /// @brief returns the index within the controlling tls or InvalidTLIndex if this link is unontrolled - int getTLIndex() const { - return myTlIndex; - } - int getTLIndex2() const { - return myTlIndex2; - } - - // @brief reset the tlIndex - void setTLIndex(int tlIndex) { - myTlIndex = tlIndex; - } - void setTLIndex2(int tlIndex) { - myTlIndex2 = tlIndex; - } - - /// @brief returns the id of the connection (!!! not really pretty) - std::string getID() const; - - /// @brief Compares both connections in order to allow sorting - friend bool operator<(const NBConnection& c1, const NBConnection& c2); - - /// @brief Comparison operator - bool operator==(const NBConnection& c) const; - - /// @brief Comparison operator - bool operator!=(const NBConnection& c) const { - return !(*this == c); - } - - /// @brief Output operator - friend std::ostream& operator<<(std::ostream& os, const NBConnection& c); - - const static int InvalidTlIndex; - const static NBConnection InvalidConnection; - -private: - /// @brief Checks whether the from-edge is still valid - NBEdge* checkFrom(const NBEdgeCont& ec); - - /// @brief Checks whether the to-edge is still valid - NBEdge* checkTo(const NBEdgeCont& ec); - -private: - /// @brief The from- and the to-edges - NBEdge* myFrom, *myTo; - - /// @brief The names of both edges, needed for verification of validity - std::string myFromID, myToID; - - /// @brief The lanes; may be -1 if no certain lane was specified - int myFromLane, myToLane; - - // @brief the index within the controlling tls if this connection is tls-controlled - int myTlIndex; - /// @brief The index of the internal junction within the controlling traffic light (optional) - int myTlIndex2; -}; diff --git a/Util/OSM2ODR/src/netbuild/NBConnectionDefs.h b/Util/OSM2ODR/src/netbuild/NBConnectionDefs.h deleted file mode 100644 index c4c8c32f9..000000000 --- a/Util/OSM2ODR/src/netbuild/NBConnectionDefs.h +++ /dev/null @@ -1,37 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NBConnectionDefs.h -/// @author Daniel Krajzewicz -/// @date Sept 2002 -/// -// Some container for connections -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include "NBConnection.h" - - -// =========================================================================== -// definitions -// =========================================================================== -/// Definition of a connection vector -typedef std::vector NBConnectionVector; - - -/** @brief Definition of a container for connection block dependencies - Includes a list of all connections which prohibit the key connection */ -typedef std::map NBConnectionProhibits; diff --git a/Util/OSM2ODR/src/netbuild/NBCont.h b/Util/OSM2ODR/src/netbuild/NBCont.h deleted file mode 100644 index acc329496..000000000 --- a/Util/OSM2ODR/src/netbuild/NBCont.h +++ /dev/null @@ -1,54 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NBCont.h -/// @author Daniel Krajzewicz -/// @author Sascha Krieg -/// @date Mon, 17 Dec 2001 -/// -// Some typedef definitions fir containers -/****************************************************************************/ -#pragma once -#include -#include -#include - -#include - - -// =========================================================================== -// class declarations -// =========================================================================== -class NBEdge; -class NBNode; -class NBRouterEdge; - - -// =========================================================================== -// container definitions -// =========================================================================== -/// @brief container for (sorted) edges -typedef std::vector EdgeVector; -typedef std::vector RouterEdgeVector; -typedef std::vector ConstRouterEdgeVector; - -typedef std::vector > ConstRouterEdgePairVector; -typedef std::vector > NBViaSuccessor; - -/// @brief container for unique edges -typedef std::set EdgeSet; - -typedef std::set NodeSet; - -/// @brief container for (sorted) lanes. The lanes are sorted from rightmost (id=0) to leftmost (id=nolanes-1) -typedef std::vector LaneVector; diff --git a/Util/OSM2ODR/src/netbuild/NBContHelper.cpp b/Util/OSM2ODR/src/netbuild/NBContHelper.cpp deleted file mode 100644 index 5cd5432f8..000000000 --- a/Util/OSM2ODR/src/netbuild/NBContHelper.cpp +++ /dev/null @@ -1,286 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NBContHelper.cpp -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date Tue, 20 Nov 2001 -/// -// Some methods for traversing lists of edges -/****************************************************************************/ -#include - -#include -#include -#include -#include "NBContHelper.h" -#include - - -// =========================================================================== -// method definitions -// =========================================================================== -/* ------------------------------------------------------------------------- - * utility methods - * ----------------------------------------------------------------------- */ -void -NBContHelper::nextCW(const EdgeVector& edges, EdgeVector::const_iterator& from) { - from++; - if (from == edges.end()) { - from = edges.begin(); - } -} - - -void -NBContHelper::nextCCW(const EdgeVector& edges, EdgeVector::const_iterator& from) { - if (from == edges.begin()) { - from = edges.end() - 1; - } else { - --from; - } -} - - -std::ostream& -NBContHelper::out(std::ostream& os, const std::vector& v) { - for (std::vector::const_iterator i = v.begin(); i != v.end(); i++) { - os << *i; - } - return os; -} - - -NBEdge* -NBContHelper::findConnectingEdge(const EdgeVector& edges, - NBNode* from, NBNode* to) { - for (EdgeVector::const_iterator i = edges.begin(); i != edges.end(); i++) { - if ((*i)->getToNode() == to && (*i)->getFromNode() == from) { - return *i; - } - } - return nullptr; -} - - - -double -NBContHelper::maxSpeed(const EdgeVector& ev) { - assert(ev.size() > 0); - double max = (*(ev.begin()))->getSpeed(); - for (EdgeVector::const_iterator i = ev.begin() + 1; i != ev.end(); i++) { - max = - max > (*i)->getSpeed() - ? max : (*i)->getSpeed(); - } - return max; -} - - - -/* ------------------------------------------------------------------------- - * methods from node_with_incoming_finder - * ----------------------------------------------------------------------- */ -NBContHelper::node_with_incoming_finder::node_with_incoming_finder(const NBEdge* const e) - : myEdge(e) {} - - -bool -NBContHelper::node_with_incoming_finder::operator()(const NBNode* const n) const { - const EdgeVector& incoming = n->getIncomingEdges(); - return std::find(incoming.begin(), incoming.end(), myEdge) != incoming.end(); -} - - - -/* ------------------------------------------------------------------------- - * methods from node_with_outgoing_finder - * ----------------------------------------------------------------------- */ -NBContHelper::node_with_outgoing_finder::node_with_outgoing_finder(const NBEdge* const e) - : myEdge(e) {} - - -bool -NBContHelper::node_with_outgoing_finder::operator()(const NBNode* const n) const { - const EdgeVector& outgoing = n->getOutgoingEdges(); - return std::find(outgoing.begin(), outgoing.end(), myEdge) != outgoing.end(); -} - - -/* ------------------------------------------------------------------------- - * methods from edge_with_destination_finder - * ----------------------------------------------------------------------- */ -NBContHelper::edge_with_destination_finder::edge_with_destination_finder(NBNode* dest) - : myDestinationNode(dest) {} - - -bool -NBContHelper::edge_with_destination_finder::operator()(NBEdge* e) const { - return e->getToNode() == myDestinationNode; -} - - -/* ------------------------------------------------------------------------- - * methods from relative_outgoing_edge_sorter - * ----------------------------------------------------------------------- */ -bool -NBContHelper::relative_outgoing_edge_sorter::operator()(const NBEdge* e1, const NBEdge* e2) const { - assert(e1 != nullptr && e2 != nullptr); - double relAngle1 = NBHelpers::normRelAngle(myAngle, e1->getStartAngle()); - double relAngle2 = NBHelpers::normRelAngle(myAngle, e2->getStartAngle()); - const double length1 = e1->getGeometry().length2D(); - const double length2 = e2->getGeometry().length2D(); - - double lookAhead = 2 * NBEdge::ANGLE_LOOKAHEAD; - while (fabs(relAngle1 - relAngle2) < 3.0) { - // look at further geometry segments to resolve ambiguity - const double offset1 = MAX2(0.0, MIN2(length1, lookAhead)); - const double offset2 = MAX2(0.0, MIN2(length2, lookAhead)); - const Position referencePos1 = e1->getGeometry().positionAtOffset2D(offset1); - const Position referencePos2 = e2->getGeometry().positionAtOffset2D(offset2); - const double angle1 = GeomHelper::legacyDegree(e1->getFromNode()->getPosition().angleTo2D(referencePos1), true); - const double angle2 = GeomHelper::legacyDegree(e2->getFromNode()->getPosition().angleTo2D(referencePos2), true); - relAngle1 = NBHelpers::normRelAngle(myAngle, angle1); - relAngle2 = NBHelpers::normRelAngle(myAngle, angle2); - if (lookAhead > MAX2(length1, length2)) { - break; - } - lookAhead *= 2; - } - if (fabs(relAngle1 - relAngle2) < NUMERICAL_EPS) { - // need to break ties for windows debug version, numerical id may be -1 for both - return e1->getID() > e2->getID(); - } - return relAngle1 > relAngle2; -} - - -/* ------------------------------------------------------------------------- - * methods from relative_incoming_edge_sorter - * ----------------------------------------------------------------------- */ -bool -NBContHelper::relative_incoming_edge_sorter::operator()(const NBEdge* e1, const NBEdge* e2) const { - assert(e1 != nullptr && e2 != nullptr); - double relAngle1 = NBHelpers::normRelAngle(myAngle, e1->getEndAngle()); - double relAngle2 = NBHelpers::normRelAngle(myAngle, e2->getEndAngle()); - const double length1 = e1->getGeometry().length2D(); - const double length2 = e2->getGeometry().length2D(); - - double lookAhead = 2 * NBEdge::ANGLE_LOOKAHEAD; - while (fabs(relAngle1 - relAngle2) < 3.0) { - // look at further geometry segments to resolve ambiguity - const double offset1 = MAX2(0.0, MIN2(length1, length1 - lookAhead)); - const double offset2 = MAX2(0.0, MIN2(length2, length2 - lookAhead)); - const Position referencePos1 = e1->getGeometry().positionAtOffset2D(offset1); - const Position referencePos2 = e2->getGeometry().positionAtOffset2D(offset2); - const double angle1 = GeomHelper::legacyDegree(referencePos1.angleTo2D(e1->getToNode()->getPosition()), true); - const double angle2 = GeomHelper::legacyDegree(referencePos2.angleTo2D(e2->getToNode()->getPosition()), true); - relAngle1 = NBHelpers::normRelAngle(myAngle, angle1); - relAngle2 = NBHelpers::normRelAngle(myAngle, angle2); - if (lookAhead > MAX2(length1, length2)) { - break; - } - lookAhead *= 2; - } - if (fabs(relAngle1 - relAngle2) < NUMERICAL_EPS) { - // need to break ties for windows debug version, numerical id may be -1 for both - return e1->getID() > e2->getID(); - } - return relAngle1 > relAngle2; -} - - -std::ostream& -operator<<(std::ostream& os, const EdgeVector& ev) { - for (EdgeVector::const_iterator i = ev.begin(); i != ev.end(); i++) { - if (i != ev.begin()) { - os << ", "; - } - os << (*i)->getID(); - } - return os; -} - - -double -NBContHelper::getMaxSpeed(const EdgeVector& edges) { - if (edges.size() == 0) { - return -1; - } - double ret = (*(edges.begin()))->getSpeed(); - for (EdgeVector::const_iterator i = edges.begin() + 1; i != edges.end(); i++) { - if ((*i)->getSpeed() > ret) { - ret = (*i)->getSpeed(); - } - } - return ret; -} - - -double -NBContHelper::getMinSpeed(const EdgeVector& edges) { - if (edges.size() == 0) { - return -1; - } - double ret = (*(edges.begin()))->getSpeed(); - for (EdgeVector::const_iterator i = edges.begin() + 1; i != edges.end(); i++) { - if ((*i)->getSpeed() < ret) { - ret = (*i)->getSpeed(); - } - } - return ret; -} - - -bool -NBContHelper::edge_by_angle_to_nodeShapeCentroid_sorter::operator()(const NBEdge* e1, const NBEdge* e2) const { - assert(e1->getFromNode() == myNode || e1->getToNode() == myNode); - assert(e2->getFromNode() == myNode || e2->getToNode() == myNode); - const double angle1 = e1->getAngleAtNodeToCenter(myNode); - const double angle2 = e2->getAngleAtNodeToCenter(myNode); - const double absDiff = fabs(angle1 - angle2); - - // cannot trust the angle difference hence a heuristic: - if (absDiff < 2 || absDiff > (360 - 2)) { - const bool sameDir = ((e1->getFromNode() == myNode && e2->getFromNode() == myNode) - || (e1->getToNode() == myNode && e2->getToNode() == myNode)); - if (sameDir) { - // put edges that allow pedestrians on the 'outside', but be aware if both allow / disallow - const bool e1Peds = (e1->getPermissions() & SVC_PEDESTRIAN) != 0; - const bool e2Peds = (e2->getPermissions() & SVC_PEDESTRIAN) != 0; - if (e1->getToNode() == myNode) { - if (e1Peds && !e2Peds) { - return true; - } else if (!e1Peds && e2Peds) { - return false; - } - } else { - if (!e1Peds && e2Peds) { - return true; - } else if (e1Peds && !e2Peds) { - return false; - } - } - // break ties to ensure strictly weak ordering - return e1->getID() < e2->getID(); - } else { - // sort incoming before outgoing, no need to break ties here - return e1->getToNode() == myNode; - } - } - return angle1 < angle2; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netbuild/NBContHelper.h b/Util/OSM2ODR/src/netbuild/NBContHelper.h deleted file mode 100644 index e795e311e..000000000 --- a/Util/OSM2ODR/src/netbuild/NBContHelper.h +++ /dev/null @@ -1,414 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NBContHelper.h -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date Mon, 17 Dec 2001 -/// -// Some methods for traversing lists of edges -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include -#include -#include -#include "NBHelpers.h" -#include "NBCont.h" -#include "NBEdge.h" -#include "NBNode.h" -#include -#include - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * NBContHelper - * Some static helper methods that traverse a sorted list of edges in both - * directions - */ -class NBContHelper { -public: - /** Moves the given iterator clockwise within the given container - of edges sorted clockwise */ - static void nextCW(const EdgeVector& edges, - EdgeVector::const_iterator& from); - - /** Moves the given iterator counter clockwise within the given container - of edges sorted clockwise */ - static void nextCCW(const EdgeVector& edges, - EdgeVector::const_iterator& from); - - static double getMaxSpeed(const EdgeVector& edges); - - static double getMinSpeed(const EdgeVector& edges); - - /** writes the vector of bools to the given stream */ - static std::ostream& out(std::ostream& os, const std::vector& v); - - - /** - * relative_outgoing_edge_sorter - * Class to sort edges by their angle in relation to the node the - * edge using this class is incoming into. This is normally done to - * sort edges outgoing from the node the using edge is incoming in - * by their angle in relation to the using edge's angle (this angle - * is the reference angle). - */ - class relative_outgoing_edge_sorter { - public: - /// constructor - explicit relative_outgoing_edge_sorter(NBEdge* e) : myAngle(e->getEndAngle()) {} - /// constructor - explicit relative_outgoing_edge_sorter(double angle) : myAngle(angle) {} - - public: - /// comparing operation - bool operator()(const NBEdge* e1, const NBEdge* e2) const; - - private: - /// @brief the reference angle to compare edges agains - double myAngle; - }; - - - /** - * relative_incoming_edge_sorter - * Class to sort edges by their angle in relation to an outgoing edge. - * This is normally done to sort edges incoming at the starting node of this edge - * by their angle in relation to the using edge's angle (this angle - * is the reference angle). - */ - class relative_incoming_edge_sorter { - public: - /// constructor - explicit relative_incoming_edge_sorter(NBEdge* e) : myAngle(e->getStartAngle()) {} - /// constructor - explicit relative_incoming_edge_sorter(double angle) : myAngle(angle) {} - - public: - /// comparing operation - bool operator()(const NBEdge* e1, const NBEdge* e2) const; - - private: - /// @brief the reference angle to compare edges agains - double myAngle; - }; - - - /** - * edge_by_priority_sorter - * Class to sort edges by their priority - */ - class edge_by_priority_sorter { - public: - /// comparing operator - int operator()(NBEdge* e1, NBEdge* e2) const { - if (e1->getPriority() != e2->getPriority()) { - return e1->getPriority() > e2->getPriority(); - } - if (e1->getSpeed() != e2->getSpeed()) { - return e1->getSpeed() > e2->getSpeed(); - } - return e1->getNumLanes() > e2->getNumLanes(); - } - }; - - // --------------------------- - - /** - * @class edge_opposite_direction_sorter - * @brief Class to sort edges by their angle in relation to the given edge - * - * The resulting sorted list has the edge in the most opposite direction - * to the given edge as her first entry. - */ - class edge_opposite_direction_sorter { - public: - /** @brief Constructor - * @param[in] e The edge to which the sorting relates - * @param[in] n The node to consider - */ - explicit edge_opposite_direction_sorter(const NBEdge* const e, const NBNode* const n, bool regardPriority) : - myNode(n), - myEdge(e), - myRegardPriority(regardPriority) { - myAngle = getEdgeAngleAt(e, n); - } - - /** @brief Comparing operation - * @param[in] e1 The first edge to compare - * @param[in] e2 The second edge to compare - * @return Which edge is more opposite to the related one - */ - int operator()(NBEdge* e1, NBEdge* e2) const { - if (!myRegardPriority || e1->getPriority() == e2->getPriority() || e1 == myEdge || e2 == myEdge) { - return getDiff(e1) > getDiff(e2); - } else { - return e1->getPriority() > e2->getPriority(); - } - } - - protected: - /** @brief Computes the angle difference between the related and the given edge - * @param[in] e The edge to compare the angle difference of - * @return The angle difference - */ - double getDiff(const NBEdge* const e) const { - return fabs(GeomHelper::angleDiff(getEdgeAngleAt(e, myNode), myAngle)); - } - - /** @brief Returns the given edge's angle at the given node - * - * Please note that we always consider the "outgoing direction". - * @param[in] e The edge to which the sorting relates - * @param[in] n The node to consider - */ - double getEdgeAngleAt(const NBEdge* const e, const NBNode* const n) const { - if (e->getFromNode() == n) { - return e->getGeometry().angleAt2D(0); - } else { - return e->getGeometry()[-1].angleTo2D(e->getGeometry()[-2]); - } - } - - private: - - /// @brief The related node - const NBNode* const myNode; - - /// @brief the reference edge - const NBEdge* const myEdge; - - /// @brief The angle of the related edge at the given node - double myAngle; - - /// @brief Whether edge priority may override closer angles - bool myRegardPriority; - - private: - /// @brief Invalidated assignment operator - edge_opposite_direction_sorter& operator=(const edge_opposite_direction_sorter& s); - - }; - - // --------------------------- - - /** - * edge_similar_direction_sorter - * Class to sort edges by their angle in relation to the given edge - * The resulting list should have the edge in the most similar direction - * to the given edge as its first entry - */ - class edge_similar_direction_sorter { - public: - /// constructor - explicit edge_similar_direction_sorter(const NBEdge* const e, bool outgoing = true) : - myCompareOutgoing(outgoing), - myAngle(outgoing ? e->getShapeEndAngle() : e->getShapeStartAngle()) - {} - - /// comparing operation - int operator()(const NBEdge* e1, const NBEdge* e2) const { - const double d1 = angleDiff(myCompareOutgoing ? e1->getShapeStartAngle() : e1->getShapeEndAngle(), myAngle); - const double d2 = angleDiff(myCompareOutgoing ? e2->getShapeStartAngle() : e2->getShapeEndAngle(), myAngle); - if (fabs(fabs(d1) - fabs(d2)) < NUMERICAL_EPS) { - if (fabs(d1 - d2) > NUMERICAL_EPS) { - return d1 < d2; - } else { - return e1->getNumericalID() < e2->getNumericalID(); - } - } - return fabs(d1) < fabs(d2); - } - - private: - double angleDiff(const double angle1, const double angle2) const { - double d = angle2 - angle1; - while (d >= 180.) { - d -= 360.; - } - while (d < -180.) { - d += 360.; - } - return d; - } - - - private: - /// the angle to find the edge with the opposite direction - bool myCompareOutgoing; - double myAngle; - }; - - - /** - * @class node_with_incoming_finder - */ - class node_with_incoming_finder { - public: - /// constructor - node_with_incoming_finder(const NBEdge* const e); - - bool operator()(const NBNode* const n) const; - - private: - const NBEdge* const myEdge; - - private: - /// @brief invalidated assignment operator - node_with_incoming_finder& operator=(const node_with_incoming_finder& s); - - }; - - - /** - * @class node_with_outgoing_finder - */ - class node_with_outgoing_finder { - public: - /// constructor - node_with_outgoing_finder(const NBEdge* const e); - - bool operator()(const NBNode* const n) const; - - private: - const NBEdge* const myEdge; - - private: - /// @brief invalidated assignment operator - node_with_outgoing_finder& operator=(const node_with_outgoing_finder& s); - - }; - - - - - class edge_with_destination_finder { - public: - /// constructor - edge_with_destination_finder(NBNode* dest); - - bool operator()(NBEdge* e) const; - - private: - NBNode* myDestinationNode; - - private: - /// @brief invalidated assignment operator - edge_with_destination_finder& operator=(const edge_with_destination_finder& s); - - }; - - - /** Tries to return the first edge within the given container which - connects both given nodes */ - static NBEdge* findConnectingEdge(const EdgeVector& edges, - NBNode* from, NBNode* to); - - - /** returns the maximum speed allowed on the edges */ - static double maxSpeed(const EdgeVector& ev); - - /** - * same_connection_edge_sorter - * This class is used to sort edges which connect the same nodes. - * The edges are sorted in dependence to edges connecting them. The - * rightmost will be the first in the list; the leftmost the last one. - */ - class same_connection_edge_sorter { - public: - /// constructor - explicit same_connection_edge_sorter() { } - - /// comparing operation - int operator()(NBEdge* e1, NBEdge* e2) const { - std::pair mm1 = getMinMaxRelAngles(e1); - std::pair mm2 = getMinMaxRelAngles(e2); - if (mm1.first == mm2.first && mm1.second == mm2.second) { - // ok, let's simply sort them arbitrarily - return e1->getID() < e2->getID(); - } - - assert( - (mm1.first <= mm2.first && mm1.second <= mm2.second) - || - (mm1.first >= mm2.first && mm1.second >= mm2.second)); - return (mm1.first >= mm2.first && mm1.second >= mm2.second); - } - - /** - * - */ - std::pair getMinMaxRelAngles(NBEdge* e) const { - double min = 360; - double max = 360; - const EdgeVector& ev = e->getConnectedEdges(); - for (EdgeVector::const_iterator i = ev.begin(); i != ev.end(); ++i) { - double angle = NBHelpers::normRelAngle( - e->getTotalAngle(), (*i)->getTotalAngle()); - if (min == 360 || min > angle) { - min = angle; - } - if (max == 360 || max < angle) { - max = angle; - } - } - return std::pair(min, max); - } - }; - - - friend std::ostream& operator<<(std::ostream& os, const EdgeVector& ev); - - class opposite_finder { - public: - /// constructor - opposite_finder(NBEdge* edge) - : myReferenceEdge(edge) { } - - bool operator()(NBEdge* e) const { - return e->isTurningDirectionAt(myReferenceEdge) || - myReferenceEdge->isTurningDirectionAt(e); - } - - private: - NBEdge* myReferenceEdge; - - }; - - /** - * edge_by_angle_to_nodeShapeCentroid_sorter - * Class to sort edges by their angle in relation to the node shape - * */ - class edge_by_angle_to_nodeShapeCentroid_sorter { - public: - /// constructor - explicit edge_by_angle_to_nodeShapeCentroid_sorter(const NBNode* n) : myNode(n) {} - - public: - /// comparing operation - bool operator()(const NBEdge* e1, const NBEdge* e2) const; - - private: - /// the edge to compute the relative angle of - const NBNode* myNode; - }; - -}; diff --git a/Util/OSM2ODR/src/netbuild/NBDistrict.cpp b/Util/OSM2ODR/src/netbuild/NBDistrict.cpp deleted file mode 100644 index 37d2a3af0..000000000 --- a/Util/OSM2ODR/src/netbuild/NBDistrict.cpp +++ /dev/null @@ -1,187 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NBDistrict.cpp -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date Sept 2002 -/// -// A class representing a single district -/****************************************************************************/ -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "NBEdge.h" -#include "NBDistrict.h" - - -// =========================================================================== -// member method definitions -// =========================================================================== -NBDistrict::NBDistrict(const std::string& id, const Position& pos) - : Named(StringUtils::convertUmlaute(id)), - myPosition(pos) {} - - -NBDistrict::NBDistrict(const std::string& id) - : Named(id), myPosition(0, 0) {} - - -NBDistrict::~NBDistrict() {} - - -// ----------- Applying offset -void -NBDistrict::reshiftPosition(double xoff, double yoff) { - myPosition.add(xoff, yoff, 0); - myShape.add(xoff, yoff, 0); -} - - -void -NBDistrict::mirrorX() { - myPosition.mul(1, -1); - myShape.mirrorX(); -} - - -bool -NBDistrict::addSource(NBEdge* const source, double weight) { - EdgeVector::iterator i = std::find(mySources.begin(), mySources.end(), source); - if (i != mySources.end()) { - return false; - } - mySources.push_back(source); - mySourceWeights.push_back(weight); - assert(source->getID() != ""); - return true; -} - - -bool -NBDistrict::addSink(NBEdge* const sink, double weight) { - EdgeVector::iterator i = std::find(mySinks.begin(), mySinks.end(), sink); - if (i != mySinks.end()) { - return false; - } - mySinks.push_back(sink); - mySinkWeights.push_back(weight); - assert(sink->getID() != ""); - return true; -} - - -void -NBDistrict::setCenter(const Position& pos) { - myPosition = pos; -} - - -void -NBDistrict::replaceIncoming(const EdgeVector& which, NBEdge* const by) { - // temporary structures - EdgeVector newList; - WeightsCont newWeights; - double joinedVal = 0; - // go through the list of sinks - EdgeVector::iterator i = mySinks.begin(); - WeightsCont::iterator j = mySinkWeights.begin(); - for (; i != mySinks.end(); i++, j++) { - NBEdge* tmp = (*i); - double val = (*j); - if (find(which.begin(), which.end(), tmp) == which.end()) { - // if the current edge shall not be replaced, add to the - // temporary list - newList.push_back(tmp); - newWeights.push_back(val); - } else { - // otherwise, skip it and add its weight to the one to be inserted - // instead - joinedVal += val; - } - } - // add the one to be inserted instead - newList.push_back(by); - newWeights.push_back(joinedVal); - // assign to values - mySinks = newList; - mySinkWeights = newWeights; -} - - -void -NBDistrict::replaceOutgoing(const EdgeVector& which, NBEdge* const by) { - // temporary structures - EdgeVector newList; - WeightsCont newWeights; - double joinedVal = 0; - // go through the list of sinks - EdgeVector::iterator i = mySources.begin(); - WeightsCont::iterator j = mySourceWeights.begin(); - for (; i != mySources.end(); i++, j++) { - NBEdge* tmp = (*i); - double val = (*j); - if (find(which.begin(), which.end(), tmp) == which.end()) { - // if the current edge shall not be replaced, add to the - // temporary list - newList.push_back(tmp); - newWeights.push_back(val); - } else { - // otherwise, skip it and add its weight to the one to be inserted - // instead - joinedVal += val; - } - } - // add the one to be inserted instead - newList.push_back(by); - newWeights.push_back(joinedVal); - // assign to values - mySources = newList; - mySourceWeights = newWeights; -} - - -void -NBDistrict::removeFromSinksAndSources(NBEdge* const e) { - int i; - for (i = 0; i < (int)mySinks.size(); ++i) { - if (mySinks[i] == e) { - mySinks.erase(mySinks.begin() + i); - mySinkWeights.erase(mySinkWeights.begin() + i); - } - } - for (i = 0; i < (int)mySources.size(); ++i) { - if (mySources[i] == e) { - mySources.erase(mySources.begin() + i); - mySourceWeights.erase(mySourceWeights.begin() + i); - } - } -} - - -void -NBDistrict::addShape(const PositionVector& p) { - myShape = p; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netbuild/NBDistrict.h b/Util/OSM2ODR/src/netbuild/NBDistrict.h deleted file mode 100644 index 550162b54..000000000 --- a/Util/OSM2ODR/src/netbuild/NBDistrict.h +++ /dev/null @@ -1,266 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NBDistrict.h -/// @author Daniel Krajzewicz -/// @author Sascha Krieg -/// @author Michael Behrisch -/// @date Sept 2002 -/// -// A class representing a single district -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include -#include "NBCont.h" -#include -#include -#include -#include - - -// =========================================================================== -// class declarations -// =========================================================================== -class NBEdge; -class OutputDevice; - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NBDistrict - * @brief A class representing a single district - * - * A "district" is an area within the network which may be referenced by - * O/D-matrices. It stems from importing VISUM-networks. Work with VISUM- - * -networks also made it necessary that a district knows the edges at - * which new vehicles shall approach the simulated network (sources) and - * those to use when leaving the network (sinks). These connections to the - * network are weighted. - * - * Later work on VISUM required also parsing the shape of a district. This - * information is used by some external tools only, it is even not shown - * within the GUI. - * - * @todo Recheck whether this can be somehow joined with ODDistrict - */ -class NBDistrict : public Named { -public: - /** @brief Constructor with id, and position - * - * @param[in] id The id of the district - * @param[in] pos The position of the district - */ - NBDistrict(const std::string& id, const Position& pos); - - - /** @brief Constructor without position - * - * The position must be computed later - * - * @param[in] id The id of the district - */ - NBDistrict(const std::string& id); - - - /// @brief Destructor - ~NBDistrict(); - - - /** @brief Adds a source - * - * It is checked whether the edge has already been added as a source. false - * is returned in this case. Otherwise, the source is pushed into - * the list of sources and the weight into the list of source weights. - * both lists stay sorted this way. true is returned. - * - * @param[in] source An edge that shall be used as source - * @param[in] weight The weight of the source - * @return Whether the source could be added (was not added before) - * @todo Consider using only one list for sources/weights - */ - bool addSource(NBEdge* const source, double weight); - - - /** @brief Adds a sink - * - * It is checked whether the edge has already been added as a sink. false - * is returned in this case. Otherwise, the sink is pushed into - * the list of sink and the weight into the list of sink weights. - * both lists stay sorted this way. true is returned. - * - * @param[in] sink An edge that shall be used as sink - * @param[in] weight The weight of the sink - * @return Whether the sink could be added (was not added before) - * @todo Consider using only one list for sinks/weights - */ - bool addSink(NBEdge* const sink, double weight); - - - /** @brief Returns the position of this district's center - * - * @return The position of this district's center - * @todo Recheck when this information is set/needed - */ - const Position& getPosition() const { - return myPosition; - } - - - /** @brief Sets the center coordinates - * - * @param[in] pos The new center to assign - * @todo Recheck when this information is set/needed - */ - void setCenter(const Position& pos); - - - /** @brief Replaces incoming edges from the vector (sinks) by the given edge - * - * When an edge is split/joined/removed/etc., it may get necessary to replace prior - * edges by new ones. This method replaces all occurences of the edges from - * "which" within incoming edges (sinks) by the given edge. - * - * The new sink edge's weight is the sum of the weights of the replaced edges. - * - * @param[in] which List of edges to replace - * @param[in] by The replacement - */ - void replaceIncoming(const EdgeVector& which, NBEdge* const by); - - - /** @brief Replaces outgoing edges from the vector (source) by the given edge - * - * When an edge is split/joined/removed/etc., it may get necessary to replace prior - * edges by new ones. This method replaces all occurences of the edges from - * "which" within outgoing edges (sources) by the given edge. - * - * The new source edge's weight is the sum of the weights of the replaced edges. - * - * @param[in] which List of edges to replace - * @param[in] by The replacement - */ - void replaceOutgoing(const EdgeVector& which, NBEdge* const by); - - - /** @brief Removes the given edge from the lists of sources and sinks - * - * The according weights are removed, too. - * - * @param[in] e The edge to remove from sinks/sources - */ - void removeFromSinksAndSources(NBEdge* const e); - - - /** @brief Sets the shape of this district - * - * @param[in] p The new shape - */ - void addShape(const PositionVector& p); - - - /** @brief Returns the weights of the sources - * @return The source weights - */ - const std::vector& getSourceWeights() const { - return mySourceWeights; - } - - - /** @brief Returns the sources - * @return The source edges - */ - const std::vector& getSourceEdges() const { - return mySources; - } - - - /** @brief Returns the weights of the sinks - * @return The sink weights - */ - const std::vector& getSinkWeights() const { - return mySinkWeights; - } - - - /** @brief Returns the sinks - * @return The sink edges - */ - const std::vector& getSinkEdges() const { - return mySinks; - } - - - /** @brief Returns the shape - * @return The district's shape - */ - const PositionVector& getShape() const { - return myShape; - } - - - - /// @name Applying offset - /// @{ - - /** @brief Applies an offset to the district - * @param[in] xoff The x-offset to apply - * @param[in] yoff The y-offset to apply - */ - void reshiftPosition(double xoff, double yoff); - - /// @brief mirror coordinates along the x-axis - void mirrorX(); - /// @} - - - - - -private: - /// @brief Definition of a vector of connection weights - typedef std::vector WeightsCont; - - /// @brief The sources (connection from district to network) - EdgeVector mySources; - - /// @brief The weights of the sources - WeightsCont mySourceWeights; - - /// @brief The sinks (connection from network to district) - EdgeVector mySinks; - - /// @brief The weights of the sinks - WeightsCont mySinkWeights; - - /// @brief The position of the district - Position myPosition; - - /// @brief The shape of the dsitrict - PositionVector myShape; - - -private: - /** invalid copy constructor */ - NBDistrict(const NBDistrict& s); - - /** invalid assignment operator */ - NBDistrict& operator=(const NBDistrict& s); - - -}; diff --git a/Util/OSM2ODR/src/netbuild/NBDistrictCont.cpp b/Util/OSM2ODR/src/netbuild/NBDistrictCont.cpp deleted file mode 100644 index 8f2a6f5da..000000000 --- a/Util/OSM2ODR/src/netbuild/NBDistrictCont.cpp +++ /dev/null @@ -1,103 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NBDistrictCont.cpp -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Tue, 20 Nov 2001 -/// -// A container for districts -/****************************************************************************/ -#include - -#include -#include -#include -#include -#include -#include "NBDistrict.h" -#include "NBDistrictCont.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -NBDistrictCont::NBDistrictCont() {} - - -NBDistrictCont::~NBDistrictCont() { - for (DistrictCont::iterator i = myDistricts.begin(); i != myDistricts.end(); i++) { - delete ((*i).second); - } - myDistricts.clear(); -} - - -bool -NBDistrictCont::insert(NBDistrict* const district) { - DistrictCont::const_iterator i = myDistricts.find(district->getID()); - if (i != myDistricts.end()) { - return false; - } - myDistricts.insert(DistrictCont::value_type(district->getID(), district)); - return true; -} - - -NBDistrict* -NBDistrictCont::retrieve(const std::string& id) const { - DistrictCont::const_iterator i = myDistricts.find(id); - if (i == myDistricts.end()) { - return nullptr; - } - return (*i).second; -} - - -int -NBDistrictCont::size() const { - return (int)myDistricts.size(); -} - - -bool -NBDistrictCont::addSource(const std::string& dist, NBEdge* const source, - double weight) { - NBDistrict* o = retrieve(dist); - if (o == nullptr) { - return false; - } - return o->addSource(source, weight); -} - - -bool -NBDistrictCont::addSink(const std::string& dist, NBEdge* const destination, - double weight) { - NBDistrict* o = retrieve(dist); - if (o == nullptr) { - return false; - } - return o->addSink(destination, weight); -} - - -void -NBDistrictCont::removeFromSinksAndSources(NBEdge* const e) { - for (DistrictCont::iterator i = myDistricts.begin(); i != myDistricts.end(); i++) { - (*i).second->removeFromSinksAndSources(e); - } -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netbuild/NBDistrictCont.h b/Util/OSM2ODR/src/netbuild/NBDistrictCont.h deleted file mode 100644 index 82032a6e6..000000000 --- a/Util/OSM2ODR/src/netbuild/NBDistrictCont.h +++ /dev/null @@ -1,155 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NBDistrictCont.h -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Sept 2002 -/// -// A container for districts -/****************************************************************************/ -#pragma once -#include - -#include -#include - - -// =========================================================================== -// class declarations -// =========================================================================== -class NBDistrict; -class NBEdge; -class NBNodeCont; -class OutputDevice; - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NBDistrictCont - * @brief A container for districts - * - * A simple storage for district instances. Allows addition an retrieval of - * districts, filling them with sources/sinks, and some other methods which - * operate at all stored districts. - * - * @see NBDistrict - */ -class NBDistrictCont { -public: - /// @brief Constructor - NBDistrictCont(); - - - /// @brief Destructor - ~NBDistrictCont(); - - - /** @brief Adds a district to the dictionary - * - * @param[in] district The district to add - * @return false if the districts already was in the dictionary - */ - bool insert(NBDistrict* const district); - - - /** @brief Returns the districts with the given id - * - * @param[in] id The id of the district to retrieve - * @return The district with the given id if there was one having it, 0 otherwise - */ - NBDistrict* retrieve(const std::string& id) const; - - - /** @brief Returns the pointer to the begin of the stored districts - * @return The iterator to the beginning of stored edges - */ - std::map::const_iterator begin() const { - return myDistricts.begin(); - } - - - /** @brief Returns the pointer to the end of the stored districts - * @return The iterator to the end of stored edges - */ - std::map::const_iterator end() const { - return myDistricts.end(); - } - - - /** @brief Returns the number of districts inside the container */ - int size() const; - - - /** @brief Adds a source to the named district - * - * At first, the district is tried to be retrieved. If this fails, false is - * returned. Otherwise the retrieved districts NBDistrict::addSource-method - * is called. - * - * @see NBDistrict::addSource - * @param[in] dist The id of the district to add the source to - * @param[in] source An edge that shall be used as source - * @param[in] weight An optional weight of the source - * @return Whether the source could be added (the district exists and the suorce was not added to it before) - */ - bool addSource(const std::string& dist, NBEdge* const source, - double weight); - - - /** @brief Adds a sink to the named district - * - * At first, the district is tried to be retrieved. If this fails, false is - * returned. Otherwise the retrieved districts NBDistrict::addSink-method - * is called. - * - * @see NBDistrict::addSink - * @param[in] dist The id of the district to add the sink to - * @param[in] source An edge that shall be used as sink - * @param[in] weight An optional weight of the source - * @return Whether the source could be added (the district exists and the suorce was not added to it before) - */ - bool addSink(const std::string& dist, NBEdge* const destination, - double weight); - - - /** @brief Removes the given edge from the lists of sources and sinks in all stored districts - * - * This method simply goes through all stored districts and calls their method - * NBDistrict::removeFromSinksAndSources. - * - * @see NBDistrict::removeFromSinksAndSources - * @param[in] e The edge to remove from sinks/sources - */ - void removeFromSinksAndSources(NBEdge* const e); - - -private: - /// @brief The type of the dictionary where a node may be found by her id - typedef std::map DistrictCont; - - /// @brief The instance of the dictionary - DistrictCont myDistricts; - - -private: - /** invalid copy constructor */ - NBDistrictCont(const NBDistrictCont& s); - - /** invalid assignment operator */ - NBDistrictCont& operator=(const NBDistrictCont& s); - - -}; diff --git a/Util/OSM2ODR/src/netbuild/NBEdge.cpp b/Util/OSM2ODR/src/netbuild/NBEdge.cpp deleted file mode 100644 index 30f17859e..000000000 --- a/Util/OSM2ODR/src/netbuild/NBEdge.cpp +++ /dev/null @@ -1,4084 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NBEdge.cpp -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Sascha Krieg -/// @author Michael Behrisch -/// @author Laura Bieker -/// @author Leonhard Luecken -/// @date Tue, 20 Nov 2001 -/// -// Methods for the representation of a single edge -/****************************************************************************/ -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "NBEdgeCont.h" -#include "NBNode.h" -#include "NBNodeCont.h" -#include "NBContHelper.h" -#include "NBHelpers.h" -#include "NBTrafficLightDefinition.h" -#include "NBTypeCont.h" -#include "NBEdge.h" - -//#define ADDITIONAL_WARNINGS -//#define DEBUG_CONNECTION_GUESSING -//#define DEBUG_ANGLES -//#define DEBUG_NODE_BORDER -//#define DEBUG_REPLACECONNECTION -#define DEBUGID "" -#define DEBUGCOND (getID() == DEBUGID) -//#define DEBUGCOND (StringUtils::startsWith(getID(), DEBUGID)) -//#define DEBUGCOND (getID() == "22762377#1" || getID() == "146511467") -#define DEBUGCOND2(obj) ((obj != 0 && (obj)->getID() == DEBUGID)) -//#define DEBUGCOND (true) - -// =========================================================================== -// static members -// =========================================================================== -const double NBEdge::UNSPECIFIED_WIDTH = -1; -const double NBEdge::UNSPECIFIED_OFFSET = 0; -const double NBEdge::UNSPECIFIED_SPEED = -1; -const double NBEdge::UNSPECIFIED_CONTPOS = -1; -const double NBEdge::UNSPECIFIED_VISIBILITY_DISTANCE = -1; - -const double NBEdge::UNSPECIFIED_SIGNAL_OFFSET = -1; -const double NBEdge::UNSPECIFIED_LOADED_LENGTH = -1; -const double NBEdge::ANGLE_LOOKAHEAD = 10.0; -const int NBEdge::UNSPECIFIED_INTERNAL_LANE_INDEX = -1; -const bool NBEdge::UNSPECIFIED_CONNECTION_UNCONTROLLED = false; - -double NBEdge::myDefaultConnectionLength = NBEdge::UNSPECIFIED_LOADED_LENGTH; - -NBEdge NBEdge::DummyEdge; - -ConstRouterEdgePairVector NBEdge::Connection::myViaSuccessors = ConstRouterEdgePairVector({ std::pair(nullptr, nullptr) }); - -// =========================================================================== -// method definitions -// =========================================================================== -std::string -NBEdge::Connection::getInternalLaneID() const { - return id + "_" + toString(internalLaneIndex); -} - - -std::string -NBEdge::Connection::getDescription(const NBEdge* parent) const { - return Named::getIDSecure(parent) + "_" + toString(fromLane) + "->" + Named::getIDSecure(toEdge) + "_" + toString(toLane); -} - - -NBEdge::Connection::Connection(int fromLane_, NBEdge* toEdge_, int toLane_) : - fromLane(fromLane_), - toEdge(toEdge_), - toLane(toLane_), - tlLinkIndex(-1), - tlLinkIndex2(-1), - mayDefinitelyPass(false), - keepClear(true), - contPos(UNSPECIFIED_CONTPOS), - visibility(UNSPECIFIED_VISIBILITY_DISTANCE), - speed(UNSPECIFIED_SPEED), - customLength(myDefaultConnectionLength), - permissions(SVC_UNSPECIFIED), - id(toEdge_ == nullptr ? "" : toEdge->getFromNode()->getID()), - haveVia(false), - internalLaneIndex(UNSPECIFIED_INTERNAL_LANE_INDEX), - uncontrolled(false) { -} - - -NBEdge::Connection::Connection(int fromLane_, NBEdge* toEdge_, int toLane_, bool mayDefinitelyPass_, bool keepClear_, double contPos_, - double visibility_, double speed_, double length_, bool haveVia_, bool uncontrolled_, const PositionVector& customShape_, SVCPermissions permissions_) : - fromLane(fromLane_), - toEdge(toEdge_), - toLane(toLane_), - tlLinkIndex(-1), - tlLinkIndex2(-1), - mayDefinitelyPass(mayDefinitelyPass_), - keepClear(keepClear_), - contPos(contPos_), - visibility(visibility_), - speed(speed_), - customLength(length_), - customShape(customShape_), - permissions(permissions_), - id(toEdge_ == nullptr ? "" : toEdge->getFromNode()->getID()), - vmax(UNSPECIFIED_SPEED), - haveVia(haveVia_), - internalLaneIndex(UNSPECIFIED_INTERNAL_LANE_INDEX), - uncontrolled(uncontrolled_) -{ } - - -NBEdge::Lane::Lane(NBEdge* e, const std::string& origID_) : - speed(e->getSpeed()), - permissions(SVCAll), - preferred(0), - endOffset(e->getEndOffset()), - stopOffsets(e->getStopOffsets()), - width(e->getLaneWidth()), - accelRamp(false), - connectionsDone(false) { - if (origID_ != "") { - setParameter(SUMO_PARAM_ORIGID, origID_); - } -} - - -/* ------------------------------------------------------------------------- - * NBEdge::ToEdgeConnectionsAdder-methods - * ----------------------------------------------------------------------- */ -void -NBEdge::ToEdgeConnectionsAdder::execute(const int lane, const int virtEdge) { - // check - assert((int)myTransitions.size() > virtEdge); - // get the approached edge - NBEdge* succEdge = myTransitions[virtEdge]; - std::vector lanes; - - // check whether the currently regarded, approached edge has already - // a connection starting at the edge which is currently being build - std::map >::iterator i = myConnections.find(succEdge); - if (i != myConnections.end()) { - // if there were already lanes assigned, get them - lanes = (*i).second; - } - - // check whether the current lane was already used to connect the currently - // regarded approached edge - std::vector::iterator j = std::find(lanes.begin(), lanes.end(), lane); - if (j == lanes.end()) { - // if not, add it to the list - lanes.push_back(lane); - } - // set information about connecting lanes - myConnections[succEdge] = lanes; -} - - - -/* ------------------------------------------------------------------------- - * NBEdge::MainDirections-methods - * ----------------------------------------------------------------------- */ -NBEdge::MainDirections::MainDirections(const EdgeVector& outgoing, NBEdge* parent, NBNode* to, const std::vector& availableLanes) : myStraightest(-1) { - NBContHelper::edge_similar_direction_sorter sorter(parent); - const NBEdge* straight = nullptr; - for (const NBEdge* const out : outgoing) { - const int outPerms = out->getPermissions(); - for (const int l : availableLanes) { - if ((parent->myLanes[l].permissions & outPerms) != 0) { - if (straight == nullptr || sorter(out, straight)) { - straight = out; - } - break; - } - } - } - if (straight == nullptr) { - return; - } - myStraightest = (int)std::distance(outgoing.begin(), std::find(outgoing.begin(), outgoing.end(), straight)); - - // check whether the right turn has a higher priority - assert(outgoing.size() > 0); - const LinkDirection straightestDir = to->getDirection(parent, straight); -#ifdef DEBUG_CONNECTION_GUESSING - if (DEBUGCOND2(parent)) { - std::cout << " MainDirections edge=" << parent->getID() << " straightest=" << straight->getID() << " dir=" << toString(straightestDir) << "\n"; - } -#endif - if (NBNode::isTrafficLight(to->getType()) && - (straightestDir == LinkDirection::STRAIGHT || straightestDir == LinkDirection::PARTLEFT || straightestDir == LinkDirection::PARTRIGHT)) { - myDirs.push_back(MainDirections::Direction::FORWARD); - return; - } - if (outgoing[0]->getJunctionPriority(to) == 1) { - myDirs.push_back(MainDirections::Direction::RIGHTMOST); - } - // check whether the left turn has a higher priority - if (outgoing.back()->getJunctionPriority(to) == 1) { - // ok, the left turn belongs to the higher priorised edges on the junction - // let's check, whether it has also a higher priority (lane number/speed) - // than the current - if (outgoing.back()->getPriority() > straight->getPriority()) { - myDirs.push_back(MainDirections::Direction::LEFTMOST); - } else { - if (outgoing.back()->getNumLanes() > straight->getNumLanes()) { - myDirs.push_back(MainDirections::Direction::LEFTMOST); - } - } - } - // check whether the forward direction has a higher priority - // check whether it has a higher priority and is going straight - if (straight->getJunctionPriority(to) == 1 && to->getDirection(parent, straight) == LinkDirection::STRAIGHT) { - myDirs.push_back(MainDirections::Direction::FORWARD); - } -} - - -NBEdge::MainDirections::~MainDirections() {} - - -bool -NBEdge::MainDirections::empty() const { - return myDirs.empty(); -} - - -bool -NBEdge::MainDirections::includes(Direction d) const { - return std::find(myDirs.begin(), myDirs.end(), d) != myDirs.end(); -} - - -/* ------------------------------------------------------------------------- - * NBEdge::connections_relative_edgelane_sorter-methods - * ----------------------------------------------------------------------- */ -int -NBEdge::connections_relative_edgelane_sorter::operator()(const Connection& c1, const Connection& c2) const { - if (c1.toEdge != c2.toEdge) { - return NBContHelper::relative_outgoing_edge_sorter(myEdge)(c1.toEdge, c2.toEdge); - } - return c1.toLane < c2.toLane; -} - - -/* ------------------------------------------------------------------------- - * NBEdge-methods - * ----------------------------------------------------------------------- */ -NBEdge::NBEdge(const std::string& id, NBNode* from, NBNode* to, - std::string type, double speed, int nolanes, - int priority, double laneWidth, double endOffset, - const std::string& streetName, - LaneSpreadFunction spread) : - Named(StringUtils::convertUmlaute(id)), - myStep(EdgeBuildingStep::INIT), - myType(StringUtils::convertUmlaute(type)), - myFrom(from), myTo(to), - myStartAngle(0), myEndAngle(0), myTotalAngle(0), - myPriority(priority), mySpeed(speed), - myDistance(0), - myTurnDestination(nullptr), - myPossibleTurnDestination(nullptr), - myFromJunctionPriority(-1), myToJunctionPriority(-1), - myLaneSpreadFunction(spread), myEndOffset(endOffset), - myStopOffsets(), - myLaneWidth(laneWidth), - myLoadedLength(UNSPECIFIED_LOADED_LENGTH), - myAmInTLS(false), myAmMacroscopicConnector(false), - myStreetName(streetName), - mySignalPosition(Position::INVALID), - mySignalNode(nullptr), - myIsOffRamp(false), - myIndex(-1) { - init(nolanes, false, ""); -} - - -NBEdge::NBEdge(const std::string& id, NBNode* from, NBNode* to, - std::string type, double speed, int nolanes, - int priority, double laneWidth, double endOffset, - PositionVector geom, - const std::string& streetName, - const std::string& origID, - LaneSpreadFunction spread, bool tryIgnoreNodePositions) : - Named(StringUtils::convertUmlaute(id)), - myStep(EdgeBuildingStep::INIT), - myType(StringUtils::convertUmlaute(type)), - myFrom(from), myTo(to), - myStartAngle(0), myEndAngle(0), myTotalAngle(0), - myPriority(priority), mySpeed(speed), - myDistance(0), - myTurnDestination(nullptr), - myPossibleTurnDestination(nullptr), - myFromJunctionPriority(-1), myToJunctionPriority(-1), - myGeom(geom), myLaneSpreadFunction(spread), myEndOffset(endOffset), - myStopOffsets(), - myLaneWidth(laneWidth), - myLoadedLength(UNSPECIFIED_LOADED_LENGTH), - myAmInTLS(false), myAmMacroscopicConnector(false), - myStreetName(streetName), - mySignalPosition(Position::INVALID), - mySignalNode(nullptr), - myIsOffRamp(false), - myIndex(-1) { - init(nolanes, tryIgnoreNodePositions, origID); -} - - -NBEdge::NBEdge(const std::string& id, NBNode* from, NBNode* to, const NBEdge* tpl, const PositionVector& geom, int numLanes) : - Named(StringUtils::convertUmlaute(id)), - myStep(EdgeBuildingStep::INIT), - myType(tpl->getTypeID()), - myFrom(from), myTo(to), - myStartAngle(0), myEndAngle(0), myTotalAngle(0), - myPriority(tpl->getPriority()), mySpeed(tpl->getSpeed()), - myDistance(0), - myTurnDestination(nullptr), - myPossibleTurnDestination(nullptr), - myFromJunctionPriority(-1), myToJunctionPriority(-1), - myGeom(geom), - myLaneSpreadFunction(tpl->getLaneSpreadFunction()), - myEndOffset(tpl->getEndOffset()), - myStopOffsets(tpl->getStopOffsets()), - myLaneWidth(tpl->getLaneWidth()), - myLoadedLength(UNSPECIFIED_LOADED_LENGTH), - myAmInTLS(false), - myAmMacroscopicConnector(false), - myStreetName(tpl->getStreetName()), - mySignalPosition(to == tpl->myTo ? tpl->mySignalPosition : Position::INVALID), - mySignalNode(to == tpl->myTo ? tpl->mySignalNode : nullptr) { - init(numLanes > 0 ? numLanes : tpl->getNumLanes(), myGeom.size() > 0, ""); - for (int i = 0; i < getNumLanes(); i++) { - const int tplIndex = MIN2(i, tpl->getNumLanes() - 1); - setSpeed(i, tpl->getLaneSpeed(tplIndex)); - setPermissions(tpl->getPermissions(tplIndex), i); - setLaneWidth(i, tpl->myLanes[tplIndex].width); - myLanes[i].updateParameters(tpl->myLanes[tplIndex].getParametersMap()); - if (to == tpl->myTo) { - setEndOffset(i, tpl->myLanes[tplIndex].endOffset); - setStopOffsets(i, tpl->myLanes[tplIndex].stopOffsets); - } - } - if (tpl->myLoadedLength > 0 && to == tpl->getFromNode() && from == tpl->getToNode() && geom == tpl->getGeometry().reverse()) { - myLoadedLength = tpl->myLoadedLength; - } - updateParameters(tpl->getParametersMap()); -} - - -NBEdge::NBEdge() : - Named("DUMMY") { -} - - -void -NBEdge::reinit(NBNode* from, NBNode* to, const std::string& type, - double speed, int nolanes, int priority, - PositionVector geom, double laneWidth, double endOffset, - const std::string& streetName, - LaneSpreadFunction spread, - bool tryIgnoreNodePositions) { - if (myFrom != from) { - myFrom->removeEdge(this, false); - } - if (myTo != to) { - myTo->removeEdge(this, false); - } - myType = StringUtils::convertUmlaute(type); - myFrom = from; - myTo = to; - myPriority = priority; - //?myTurnDestination(0), - //?myFromJunctionPriority(-1), myToJunctionPriority(-1), - myGeom = geom; - myLaneSpreadFunction = spread; - myLoadedLength = UNSPECIFIED_LOADED_LENGTH; - myStreetName = streetName; - //?, myAmTurningWithAngle(0), myAmTurningOf(0), - //?myAmInTLS(false), myAmMacroscopicConnector(false) - - // preserve lane-specific settings (geometry must be recomputed) - // if new lanes are added they copy the values from the leftmost lane (if specified) - const std::vector oldLanes = myLanes; - init(nolanes, tryIgnoreNodePositions, oldLanes.empty() ? "" : oldLanes[0].getParameter(SUMO_PARAM_ORIGID)); - for (int i = 0; i < (int)nolanes; ++i) { - PositionVector newShape = myLanes[i].shape; - myLanes[i] = oldLanes[MIN2(i, (int)oldLanes.size() - 1)]; - myLanes[i].shape = newShape; - } - // however, if the new edge defaults are explicityly given, they override the old settings - if (endOffset != UNSPECIFIED_OFFSET) { - setEndOffset(-1, endOffset); - } - if (laneWidth != UNSPECIFIED_WIDTH) { - setLaneWidth(-1, laneWidth); - } - if (speed != UNSPECIFIED_SPEED) { - setSpeed(-1, speed); - } -} - - -void -NBEdge::reinitNodes(NBNode* from, NBNode* to) { - // connections may still be valid - if (from == nullptr || to == nullptr) { - throw ProcessError("At least one of edge's '" + myID + "' nodes is not known."); - } - if (myFrom != from) { - myFrom->removeEdge(this, false); - } - if (myTo != to) { - myTo->removeEdge(this, false); - } - // remove first from both nodes and then add to the new nodes - // (otherwise reversing does not work) - if (myFrom != from) { - myFrom = from; - myFrom->addOutgoingEdge(this); - } - if (myTo != to) { - myTo = to; - myTo->addIncomingEdge(this); - } - computeAngle(); -} - - -void -NBEdge::init(int noLanes, bool tryIgnoreNodePositions, const std::string& origID) { - if (noLanes == 0) { - throw ProcessError("Edge '" + myID + "' needs at least one lane."); - } - if (myFrom == nullptr || myTo == nullptr) { - throw ProcessError("At least one of edge's '" + myID + "' nodes is not known."); - } - if (!SUMOXMLDefinitions::isValidNetID(myID)) { - throw ProcessError("Invalid edge id '" + myID + "'."); - } - // revisit geometry - // should have at least two points at the end... - // and in dome cases, the node positions must be added - myGeom.removeDoublePoints(myGeom.size() > 2 ? POSITION_EPS : NUMERICAL_EPS); - if (!tryIgnoreNodePositions || myGeom.size() < 2) { - if (myGeom.size() == 0) { - myGeom.push_back(myFrom->getPosition()); - myGeom.push_back(myTo->getPosition()); - } else { - myGeom.push_back_noDoublePos(myTo->getPosition()); - myGeom.push_front_noDoublePos(myFrom->getPosition()); - } - } - if (myGeom.size() < 2) { - myGeom.clear(); - myGeom.push_back(myFrom->getPosition()); - myGeom.push_back(myTo->getPosition()); - } - if (myGeom.size() == 2 && myGeom[0] == myGeom[1]) { - WRITE_WARNINGF("Edge's '%' from- and to-node are at the same position.", myID); - int patchIndex = myFrom->getID() < myTo->getID() ? 1 : 0; - myGeom[patchIndex].add(Position(POSITION_EPS, POSITION_EPS)); - } - // - myFrom->addOutgoingEdge(this); - myTo->addIncomingEdge(this); - // prepare container - myLength = myFrom->getPosition().distanceTo(myTo->getPosition()); - assert(myGeom.size() >= 2); - if ((int)myLanes.size() > noLanes) { - // remove connections starting at the removed lanes - for (int lane = noLanes; lane < (int)myLanes.size(); ++lane) { - removeFromConnections(nullptr, lane, -1); - } - // remove connections targeting the removed lanes - const EdgeVector& incoming = myFrom->getIncomingEdges(); - for (EdgeVector::const_iterator i = incoming.begin(); i != incoming.end(); i++) { - for (int lane = noLanes; lane < (int)myLanes.size(); ++lane) { - (*i)->removeFromConnections(this, -1, lane); - } - } - } - myLanes.clear(); - for (int i = 0; i < noLanes; i++) { - myLanes.push_back(Lane(this, origID)); - } - computeLaneShapes(); - computeAngle(); - -#ifdef DEBUG_CONNECTION_GUESSING - if (DEBUGCOND) { - std::cout << "init edge=" << getID() << "\n"; - for (Connection& c : myConnections) { - std::cout << " conn " << c.getDescription(this) << "\n"; - } - for (Connection& c : myConnectionsToDelete) { - std::cout << " connToDelete " << c.getDescription(this) << "\n"; - } - } -#endif -} - - -NBEdge::~NBEdge() {} - - -// ----------- Applying offset -void -NBEdge::reshiftPosition(double xoff, double yoff) { - myGeom.add(xoff, yoff, 0); - for (Lane& lane : myLanes) { - lane.customShape.add(xoff, yoff, 0); - } - computeLaneShapes(); // old shapes are dubious if computed with large coordinates - for (std::vector::iterator i = myConnections.begin(); i != myConnections.end(); ++i) { - (*i).customShape.add(xoff, yoff, 0); - } - if (mySignalPosition != Position::INVALID) { - mySignalPosition.add(xoff, yoff); - } - myFromBorder.add(xoff, yoff, 0); - myToBorder.add(xoff, yoff, 0); - computeEdgeShape(); - computeAngle(); // update angles because they are numerically sensitive (especially where based on centroids) -} - - -void -NBEdge::mirrorX() { - myGeom.mirrorX(); - for (int i = 0; i < (int)myLanes.size(); i++) { - myLanes[i].shape.mirrorX(); - myLanes[i].customShape.mirrorX(); - } - for (Connection& c : myConnections) { - c.shape.mirrorX(); - c.viaShape.mirrorX(); - c.customShape.mirrorX(); - } - computeAngle(); // update angles because they are numerically sensitive (especially where based on centroids) -} - - -// ----------- Edge geometry access and computation -const PositionVector -NBEdge::getInnerGeometry() const { - return myGeom.getSubpartByIndex(1, (int)myGeom.size() - 2); -} - - -bool -NBEdge::hasDefaultGeometry() const { - return myGeom.size() == 2 && hasDefaultGeometryEndpoints(); -} - - -bool -NBEdge::hasDefaultGeometryEndpoints() const { - return myGeom.front().almostSame(myFrom->getPosition(), 0.01) && - myGeom.back().almostSame(myTo->getPosition(), 0.01); -} - - -bool -NBEdge::hasDefaultGeometryEndpointAtNode(const NBNode* node) const { - // do not extend past the node position - if (node == myFrom) { - return myGeom.front() == node->getPosition(); - } else { - assert(node == myTo); - return myGeom.back() == node->getPosition(); - } -} - -Position -NBEdge::getEndpointAtNode(const NBNode* node) const { - return node == myFrom ? myGeom.front() : myGeom.back(); -} - -void -NBEdge::setGeometry(const PositionVector& s, bool inner) { - Position begin = myGeom.front(); // may differ from node position - Position end = myGeom.back(); // may differ from node position - myGeom = s; - if (inner) { - myGeom.insert(myGeom.begin(), begin); - myGeom.push_back(end); - } - computeLaneShapes(); - computeAngle(); -} - - -void -NBEdge::extendGeometryAtNode(const NBNode* node, double maxExtent) { - //std::cout << "extendGeometryAtNode edge=" << getID() << " node=" << node->getID() << " nodePos=" << node->getPosition() << " extent=" << maxExtent << " geom=" << myGeom; - if (node == myFrom) { - myGeom.extrapolate(maxExtent, true); - double offset = myGeom.nearest_offset_to_point2D(node->getPosition()); - //std::cout << " geom2=" << myGeom << " offset=" << offset; - if (offset != GeomHelper::INVALID_OFFSET) { - myGeom = myGeom.getSubpart2D(MIN2(offset, myGeom.length2D() - 2 * POSITION_EPS), myGeom.length2D()); - } - } else { - assert(node == myTo); - myGeom.extrapolate(maxExtent, false, true); - double offset = myGeom.nearest_offset_to_point2D(node->getPosition()); - //std::cout << " geom2=" << myGeom << " offset=" << offset; - if (offset != GeomHelper::INVALID_OFFSET) { - myGeom = myGeom.getSubpart2D(0, MAX2(offset, 2 * POSITION_EPS)); - } - } - //std::cout << " geom3=" << myGeom << "\n"; -} - - -void -NBEdge::shortenGeometryAtNode(const NBNode* node, double reduction) { - //std::cout << "shortenGeometryAtNode edge=" << getID() << " node=" << node->getID() << " nodePos=" << node->getPosition() << " reduction=" << reduction << " geom=" << myGeom; - reduction = MIN2(reduction, myGeom.length2D() - 2 * POSITION_EPS); - if (node == myFrom) { - myGeom = myGeom.getSubpart2D(reduction, myGeom.length2D()); - } else { - myGeom = myGeom.getSubpart2D(0, myGeom.length2D() - reduction); - } - computeLaneShapes(); - //std::cout << " geom2=" << myGeom << "\n"; -} - - -void -NBEdge::setNodeBorder(const NBNode* node, const Position& p, const Position& p2, bool rectangularCut) { - PositionVector border; - if (rectangularCut) { - const double extend = 100; - border = myGeom.getOrthogonal(p, extend, node == myTo); - } else { - border.push_back(p); - border.push_back(p2); - } - if (border.size() == 2) { - double edgeWidth = 0; - for (int i = 0; i < (int)myLanes.size(); i++) { - edgeWidth += getLaneWidth(i); - } - border.extrapolate2D(getTotalWidth()); - if (node == myFrom) { - myFromBorder = border; - } else { - assert(node == myTo); - myToBorder = border; - } - } -#ifdef DEBUG_NODE_BORDER - gDebugFlag1 = DEBUGCOND; - if (DEBUGCOND) std::cout << "setNodeBorder edge=" << getID() << " node=" << node->getID() - << " rect=" << rectangularCut - << " p=" << p << " p2=" << p2 - << " border=" << border - << " myGeom=" << myGeom - << "\n"; - -#endif -} - - -const PositionVector& -NBEdge::getNodeBorder(const NBNode* node) { - if (node == myFrom) { - return myFromBorder; - } else { - assert(node == myTo); - return myToBorder; - } -} - - -void -NBEdge::resetNodeBorder(const NBNode* node) { - if (node == myFrom) { - myFromBorder.clear(); - } else { - assert(node == myTo); - myToBorder.clear(); - } -} - - -bool -NBEdge::isBidiRail(bool ignoreSpread) const { - return (isRailway(getPermissions()) - && (ignoreSpread || myLaneSpreadFunction == LaneSpreadFunction::CENTER) - && myPossibleTurnDestination != nullptr - && (ignoreSpread || myPossibleTurnDestination->getLaneSpreadFunction() == LaneSpreadFunction::CENTER) - && isRailway(myPossibleTurnDestination->getPermissions()) - && myPossibleTurnDestination->getGeometry().reverse() == getGeometry()); -} - - -bool -NBEdge::isRailDeadEnd() const { - if (!isRailway(getPermissions())) { - return false; - } - for (NBEdge* out : myTo->getOutgoingEdges()) { - if (isRailway(out->getPermissions()) && - out != getTurnDestination(true)) { - return true; - } - } - return true; -} - - -PositionVector -NBEdge::cutAtIntersection(const PositionVector& old) const { - PositionVector shape = old; - shape = startShapeAt(shape, myFrom, myFromBorder); - if (shape.size() < 2) { - // only keep the last snippet - const double oldLength = old.length(); - shape = old.getSubpart(oldLength - 2 * POSITION_EPS, oldLength); - } - shape = startShapeAt(shape.reverse(), myTo, myToBorder).reverse(); - // sanity checks - if (shape.length() < POSITION_EPS) { - if (old.length() < 2 * POSITION_EPS) { - shape = old; - } else { - const double midpoint = old.length() / 2; - // EPS*2 because otherwhise shape has only a single point - shape = old.getSubpart(midpoint - POSITION_EPS, midpoint + POSITION_EPS); - assert(shape.size() >= 2); - assert(shape.length() > 0); - } - } else { - // @note If the node shapes are overlapping we may get a shape which goes in the wrong direction - // in this case the result shape should shortened - if (DEG2RAD(135) < fabs(GeomHelper::angleDiff(shape.beginEndAngle(), old.beginEndAngle()))) { - // eliminate intermediate points - PositionVector tmp; - tmp.push_back(shape[0]); - tmp.push_back(shape[-1]); - shape = tmp; - if (tmp.length() < POSITION_EPS) { - // fall back to original shape - if (old.length() < 2 * POSITION_EPS) { - shape = old; - } else { - const double midpoint = old.length() / 2; - // EPS*2 because otherwhise shape has only a single point - shape = old.getSubpart(midpoint - POSITION_EPS, midpoint + POSITION_EPS); - assert(shape.size() >= 2); - assert(shape.length() > 0); - } - } else { - const double midpoint = shape.length() / 2; - // cut to size and reverse - shape = shape.getSubpart(midpoint - POSITION_EPS, midpoint + POSITION_EPS); - if (shape.length() < POSITION_EPS) { - assert(false); - // the shape has a sharp turn near the midpoint - } - shape = shape.reverse(); - } - // make short edge flat (length <= 2 * POSITION_EPS) - const double z = (shape[0].z() + shape[1].z()) / 2; - shape[0].setz(z); - shape[1].setz(z); - } - } - return shape; -} - - -void -NBEdge::computeEdgeShape(double smoothElevationThreshold) { - if (smoothElevationThreshold > 0 && myGeom.hasElevation()) { - PositionVector cut = cutAtIntersection(myGeom); - // cutting and patching z-coordinate may cause steep grades which should be smoothed - if (!myFrom->geometryLike()) { - cut[0].setz(myFrom->getPosition().z()); - const double d = cut[0].distanceTo2D(cut[1]); - const double dZ = fabs(cut[0].z() - cut[1].z()); - if (dZ / smoothElevationThreshold > d) { - cut = cut.smoothedZFront(MIN2(cut.length2D() / 2, dZ / smoothElevationThreshold)); - } - } - if (!myTo->geometryLike()) { - cut[-1].setz(myTo->getPosition().z()); - const double d = cut[-1].distanceTo2D(cut[-2]); - const double dZ = fabs(cut[-1].z() - cut[-2].z()); - if (dZ / smoothElevationThreshold > d) { - cut = cut.reverse().smoothedZFront(MIN2(cut.length2D() / 2, dZ / smoothElevationThreshold)).reverse(); - } - } - cut[0] = myGeom[0]; - cut[-1] = myGeom[-1]; - if (cut != myGeom) { - myGeom = cut; - computeLaneShapes(); - } - } - for (int i = 0; i < (int)myLanes.size(); i++) { - myLanes[i].shape = cutAtIntersection(myLanes[i].shape); - } - // recompute edge's length as the average of lane lengths - double avgLength = 0; - for (int i = 0; i < (int)myLanes.size(); i++) { - avgLength += myLanes[i].shape.length(); - } - myLength = avgLength / (double) myLanes.size(); - computeAngle(); // update angles using the finalized node and lane shapes -} - - -PositionVector -NBEdge::startShapeAt(const PositionVector& laneShape, const NBNode* startNode, PositionVector nodeShape) { - if (nodeShape.size() == 0) { - nodeShape = startNode->getShape(); - nodeShape.closePolygon(); - } - PositionVector lb = laneShape; - lb.extrapolate2D(100.0); - if (nodeShape.intersects(laneShape)) { - // shape intersects directly - std::vector pbv = laneShape.intersectsAtLengths2D(nodeShape); - assert(pbv.size() > 0); - // ensure that the subpart has at least two points - double pb = MIN2(laneShape.length2D() - POSITION_EPS - NUMERICAL_EPS, VectorHelper::maxValue(pbv)); - if (pb < 0) { - return laneShape; - } - PositionVector ns = laneShape.getSubpart2D(pb, laneShape.length2D()); - //PositionVector ns = pb < (laneShape.length() - POSITION_EPS) ? laneShape.getSubpart2D(pb, laneShape.length()) : laneShape; - const double delta = ns[0].z() - laneShape[0].z(); - //std::cout << "a) startNode=" << startNode->getID() << " z=" << startNode->getPosition().z() << " oldZ=" << laneShape[0].z() << " cutZ=" << ns[0].z() << " delta=" << delta << "\n"; - if (fabs(delta) > 2 * POSITION_EPS && (!startNode->geometryLike() || pb < 1)) { - // make "real" intersections and small intersections flat - //std::cout << "a) startNode=" << startNode->getID() << " z=" << startNode->getPosition().z() << " oldZ=" << laneShape[0].z() << " cutZ=" << ns[0].z() << " delta=" << delta << "\n"; - ns[0].setz(startNode->getPosition().z()); - } - assert(ns.size() >= 2); - return ns; - } else if (nodeShape.intersects(lb)) { - // extension of first segment intersects - std::vector pbv = lb.intersectsAtLengths2D(nodeShape); - assert(pbv.size() > 0); - double pb = VectorHelper::maxValue(pbv); - assert(pb >= 0); - PositionVector result = laneShape.getSubpartByIndex(1, (int)laneShape.size() - 1); - Position np = lb.positionAtOffset2D(pb); - const double delta = np.z() - laneShape[0].z(); - //std::cout << "b) startNode=" << startNode->getID() << " z=" << startNode->getPosition().z() << " oldZ=" << laneShape[0].z() << " cutZ=" << np.z() << " delta=" << delta << "\n"; - if (fabs(delta) > 2 * POSITION_EPS && !startNode->geometryLike()) { - // avoid z-overshoot when extrapolating - //std::cout << "b) startNode=" << startNode->getID() << " z=" << startNode->getPosition().z() << " oldZ=" << laneShape[0].z() << " cutZ=" << np.z() << " delta=" << delta << "\n"; - np.setz(startNode->getPosition().z()); - } - result.push_front_noDoublePos(np); - return result; - //if (result.size() >= 2) { - // return result; - //} else { - // WRITE_WARNING(error + " (resulting shape is too short)"); - // return laneShape; - //} - } else { - // could not find proper intersection. Probably the edge is very short - // and lies within nodeShape - // @todo enable warning WRITE_WARNING(error + " (laneShape lies within nodeShape)"); - return laneShape; - } -} - - -const PositionVector& -NBEdge::getLaneShape(int i) const { - return myLanes[i].shape; -} - - -void -NBEdge::setLaneSpreadFunction(LaneSpreadFunction spread) { - myLaneSpreadFunction = spread; -} - - -void -NBEdge::addGeometryPoint(int index, const Position& p) { - if (index >= 0) { - myGeom.insert(myGeom.begin() + index, p); - } else { - myGeom.insert(myGeom.end() + index, p); - } -} - - -void -NBEdge::reduceGeometry(const double minDist) { - if (isBidiRail() && getID() < myPossibleTurnDestination->getID()) { - // ensure symmetrical removal - PositionVector reverse = myGeom.reverse(); - reverse.removeDoublePoints(minDist, true); - myGeom = reverse.reverse(); - } else { - myGeom.removeDoublePoints(minDist, true); - for (Lane& lane : myLanes) { - lane.customShape.removeDoublePoints(minDist, true); - } - } -} - - -void -NBEdge::checkGeometry(const double maxAngle, const double minRadius, bool fix, bool silent) { - if (myGeom.size() < 3) { - return; - } - //std::cout << "checking geometry of " << getID() << " geometry = " << toString(myGeom) << "\n"; - std::vector angles; // absolute segment angles - //std::cout << " absolute angles:"; - for (int i = 0; i < (int)myGeom.size() - 1; ++i) { - angles.push_back(myGeom.angleAt2D(i)); - //std::cout << " " << angles.back(); - } - //std::cout << "\n relative angles: "; - for (int i = 0; i < (int)angles.size() - 1; ++i) { - const double relAngle = fabs(GeomHelper::angleDiff(angles[i], angles[i + 1])); - //std::cout << relAngle << " "; - if (maxAngle > 0 && relAngle > maxAngle && !silent) { - WRITE_WARNINGF("Found angle of % degrees at edge '%', segment %.", RAD2DEG(relAngle), getID(), i); - } - if (relAngle < DEG2RAD(1)) { - continue; - } - if (i == 0 || i == (int)angles.size() - 2) { - const bool start = i == 0; - const double dist = (start ? myGeom[0].distanceTo2D(myGeom[1]) : myGeom[-2].distanceTo2D(myGeom[-1])); - const double r = tan(0.5 * (M_PI - relAngle)) * dist; - //std::cout << (start ? " start" : " end") << " length=" << dist << " radius=" << r << " "; - if (minRadius > 0 && r < minRadius) { - if (fix) { - WRITE_MESSAGE("Removing sharp turn with radius " + toString(r) + " at the " + - (start ? "start" : "end") + " of edge '" + getID() + "'."); - myGeom.erase(myGeom.begin() + (start ? 1 : i + 1)); - checkGeometry(maxAngle, minRadius, fix, silent); - return; - } else if (!silent) { - WRITE_WARNINGF("Found sharp turn with radius % at the " + - toString(start ? "start" : "end") + " of edge '%'.", r, getID()); - } - } - } - } - //std::cout << "\n"; -} - - -// ----------- Setting and getting connections -bool -NBEdge::addEdge2EdgeConnection(NBEdge* dest, bool overrideRemoval) { - if (myStep == EdgeBuildingStep::INIT_REJECT_CONNECTIONS) { - return true; - } - // check whether the node was merged and now a connection between - // not matching edges is tried to be added - // This happens f.e. within the ptv VISSIM-example "Beijing" - if (dest != nullptr && myTo != dest->myFrom) { - return false; - } - if (dest == nullptr) { - invalidateConnections(); - myConnections.push_back(Connection(-1, dest, -1)); - } else if (find_if(myConnections.begin(), myConnections.end(), connections_toedge_finder(dest)) == myConnections.end()) { - myConnections.push_back(Connection(-1, dest, -1)); - } - if (overrideRemoval) { - // override earlier delete decision - for (std::vector::iterator it = myConnectionsToDelete.begin(); it != myConnectionsToDelete.end();) { - if (it->toEdge == dest) { - it = myConnectionsToDelete.erase(it); - } else { - it++; - } - } - } - if (myStep < EdgeBuildingStep::EDGE2EDGES) { - myStep = EdgeBuildingStep::EDGE2EDGES; - } - return true; -} - - -bool -NBEdge::addLane2LaneConnection(int from, NBEdge* dest, - int toLane, Lane2LaneInfoType type, - bool mayUseSameDestination, - bool mayDefinitelyPass, - bool keepClear, - double contPos, - double visibility, - double speed, - double length, - const PositionVector& customShape, - bool uncontrolled, - SVCPermissions permissions, - bool postProcess) { - if (myStep == EdgeBuildingStep::INIT_REJECT_CONNECTIONS) { - return true; - } - // check whether the node was merged and now a connection between - // not matching edges is tried to be added - // This happens f.e. within the ptv VISSIM-example "Beijing" - if (myTo != dest->myFrom) { - return false; - } - if (!addEdge2EdgeConnection(dest)) { - return false; - } - return setConnection(from, dest, toLane, type, mayUseSameDestination, mayDefinitelyPass, keepClear, contPos, visibility, speed, length, customShape, uncontrolled, permissions, postProcess); -} - - -bool -NBEdge::addLane2LaneConnections(int fromLane, - NBEdge* dest, int toLane, - int no, Lane2LaneInfoType type, - bool invalidatePrevious, - bool mayDefinitelyPass) { - if (invalidatePrevious) { - invalidateConnections(true); - } - bool ok = true; - for (int i = 0; i < no && ok; i++) { - ok &= addLane2LaneConnection(fromLane + i, dest, toLane + i, type, false, mayDefinitelyPass); - } - return ok; -} - - -bool -NBEdge::setConnection(int lane, NBEdge* destEdge, - int destLane, Lane2LaneInfoType type, - bool mayUseSameDestination, - bool mayDefinitelyPass, - bool keepClear, - double contPos, - double visibility, - double speed, - double length, - const PositionVector& customShape, - bool uncontrolled, - SVCPermissions permissions, - bool postProcess) { - if (myStep == EdgeBuildingStep::INIT_REJECT_CONNECTIONS) { - return false; - } - // some kind of a misbehaviour which may occure when the junction's outgoing - // edge priorities were not properly computed, what may happen due to - // an incomplete or not proper input - // what happens is that under some circumstances a single lane may set to - // be approached more than once by the one of our lanes. - // This must not be! - // we test whether it is the case and do nothing if so - the connection - // will be refused - // - if (!mayUseSameDestination && hasConnectionTo(destEdge, destLane)) { - return false; - } - if (find_if(myConnections.begin(), myConnections.end(), connections_finder(lane, destEdge, destLane)) != myConnections.end()) { - return true; - } - if ((int)myLanes.size() <= lane || destEdge->getNumLanes() <= (int)destLane) { - // problem might be corrigible in post-processing - WRITE_WARNINGF("Could not set connection from '%' to '%'.", getLaneID(lane), destEdge->getLaneID(destLane)); - return false; - } - for (std::vector::iterator i = myConnections.begin(); i != myConnections.end();) { - if ((*i).toEdge == destEdge && ((*i).fromLane == -1 || (*i).toLane == -1)) { - i = myConnections.erase(i); - } else { - ++i; - } - } - myConnections.push_back(Connection(lane, destEdge, destLane)); - if (mayDefinitelyPass) { - myConnections.back().mayDefinitelyPass = true; - } - myConnections.back().keepClear = keepClear; - myConnections.back().contPos = contPos; - myConnections.back().visibility = visibility; - myConnections.back().permissions = permissions; - myConnections.back().speed = speed; - myConnections.back().customLength = length; - myConnections.back().customShape = customShape; - myConnections.back().uncontrolled = uncontrolled; - if (type == Lane2LaneInfoType::USER) { - myStep = EdgeBuildingStep::LANES2LANES_USER; - } else { - // check whether we have to take another look at it later - if (type == Lane2LaneInfoType::COMPUTED) { - // yes, the connection was set using an algorithm which requires a recheck - myStep = EdgeBuildingStep::LANES2LANES_RECHECK; - } else { - // ok, let's only not recheck it if we did no add something that has to be rechecked - if (myStep != EdgeBuildingStep::LANES2LANES_RECHECK) { - myStep = EdgeBuildingStep::LANES2LANES_DONE; - } - } - } - if (postProcess) { - // override earlier delete decision - for (std::vector::iterator it = myConnectionsToDelete.begin(); it != myConnectionsToDelete.end();) { - if ((it->fromLane < 0 || it->fromLane == lane) - && (it->toEdge == nullptr || it->toEdge == destEdge) - && (it->toLane < 0 || it->toLane == destLane)) { - it = myConnectionsToDelete.erase(it); - } else { - it++; - } - } - } - return true; -} - - -std::vector -NBEdge::getConnectionsFromLane(int lane, NBEdge* to, int toLane) const { - std::vector ret; - for (const Connection& c : myConnections) { - if ((lane < 0 || c.fromLane == lane) - && (to == nullptr || to == c.toEdge) - && (toLane < 0 || toLane == c.toLane)) { - ret.push_back(c); - } - } - return ret; -} - - -NBEdge::Connection -NBEdge::getConnection(int fromLane, const NBEdge* to, int toLane) const { - for (std::vector::const_iterator i = myConnections.begin(); i != myConnections.end(); ++i) { - if ( - (*i).fromLane == fromLane - && (*i).toEdge == to - && (*i).toLane == toLane) { - return *i; - } - } - throw ProcessError("Connection from " + getID() + "_" + toString(fromLane) - + " to " + to->getID() + "_" + toString(toLane) + " not found"); -} - -NBEdge::Connection& -NBEdge::getConnectionRef(int fromLane, const NBEdge* to, int toLane) { - for (std::vector::iterator i = myConnections.begin(); i != myConnections.end(); ++i) { - if ( - (*i).fromLane == fromLane - && (*i).toEdge == to - && (*i).toLane == toLane) { - return *i; - } - } - throw ProcessError("Connection from " + getID() + "_" + toString(fromLane) - + " to " + to->getID() + "_" + toString(toLane) + " not found"); -} - - -bool -NBEdge::hasConnectionTo(NBEdge* destEdge, int destLane, int fromLane) const { - return destEdge != nullptr && find_if(myConnections.begin(), myConnections.end(), connections_toedgelane_finder(destEdge, destLane, fromLane)) != myConnections.end(); -} - - -bool -NBEdge::isConnectedTo(const NBEdge* e, const bool ignoreTurnaround) const { - if (!ignoreTurnaround && (e == myTurnDestination)) { - return true; - } - return - find_if(myConnections.begin(), myConnections.end(), connections_toedge_finder(e)) - != - myConnections.end(); - -} - - -const EdgeVector* -NBEdge::getConnectedSorted() { - // check whether connections exist and if not, use edges from the node - EdgeVector outgoing; - if (myConnections.size() == 0) { - outgoing = myTo->getOutgoingEdges(); - } else { - for (std::vector::const_iterator i = myConnections.begin(); i != myConnections.end(); ++i) { - if (find(outgoing.begin(), outgoing.end(), (*i).toEdge) == outgoing.end()) { - outgoing.push_back((*i).toEdge); - } - } - } - for (std::vector::iterator it = myConnectionsToDelete.begin(); it != myConnectionsToDelete.end(); ++it) { - if (it->fromLane < 0 && it->toLane < 0) { - // found an edge that shall not be connected - EdgeVector::iterator forbidden = std::find(outgoing.begin(), outgoing.end(), it->toEdge); - if (forbidden != outgoing.end()) { - outgoing.erase(forbidden); - } - } - } - // allocate the sorted container - int size = (int) outgoing.size(); - EdgeVector* edges = new EdgeVector(); - edges->reserve(size); - for (EdgeVector::const_iterator i = outgoing.begin(); i != outgoing.end(); i++) { - NBEdge* outedge = *i; - if (outedge != nullptr && outedge != myTurnDestination) { - edges->push_back(outedge); - } - } - std::sort(edges->begin(), edges->end(), NBContHelper::relative_outgoing_edge_sorter(this)); - return edges; -} - - -EdgeVector -NBEdge::getConnectedEdges() const { - EdgeVector ret; - for (std::vector::const_iterator i = myConnections.begin(); i != myConnections.end(); ++i) { - if (find(ret.begin(), ret.end(), (*i).toEdge) == ret.end()) { - ret.push_back((*i).toEdge); - } - } - return ret; -} - - -EdgeVector -NBEdge::getIncomingEdges() const { - EdgeVector ret; - const EdgeVector& candidates = myFrom->getIncomingEdges(); - for (EdgeVector::const_iterator i = candidates.begin(); i != candidates.end(); i++) { - if ((*i)->isConnectedTo(this)) { - ret.push_back(*i); - } - } - return ret; -} - - -std::vector -NBEdge::getConnectionLanes(NBEdge* currentOutgoing, bool withBikes) const { - std::vector ret; - if (currentOutgoing != myTurnDestination) { - for (const Connection& c : myConnections) { - if (c.toEdge == currentOutgoing && (withBikes || getPermissions(c.fromLane) != SVC_BICYCLE)) { - ret.push_back(c.fromLane); - } - } - } - return ret; -} - - -void -NBEdge::sortOutgoingConnectionsByAngle() { - sort(myConnections.begin(), myConnections.end(), connections_relative_edgelane_sorter(this)); -} - - -void -NBEdge::sortOutgoingConnectionsByIndex() { - sort(myConnections.begin(), myConnections.end(), connections_sorter); -} - - -void -NBEdge::remapConnections(const EdgeVector& incoming) { - EdgeVector connected = getConnectedEdges(); - for (EdgeVector::const_iterator i = incoming.begin(); i != incoming.end(); i++) { - NBEdge* inc = *i; - // We have to do this - inc->myStep = EdgeBuildingStep::EDGE2EDGES; - // add all connections - for (EdgeVector::iterator j = connected.begin(); j != connected.end(); j++) { - inc->addEdge2EdgeConnection(*j); - } - inc->removeFromConnections(this); - } -} - - -void -NBEdge::removeFromConnections(NBEdge* toEdge, int fromLane, int toLane, bool tryLater, const bool adaptToLaneRemoval, - const bool keepPossibleTurns) { - // remove from "myConnections" - const int fromLaneRemoved = adaptToLaneRemoval && fromLane >= 0 ? fromLane : -1; - const int toLaneRemoved = adaptToLaneRemoval && toLane >= 0 ? toLane : -1; - for (std::vector::iterator i = myConnections.begin(); i != myConnections.end();) { - Connection& c = *i; - if ((toEdge == nullptr || c.toEdge == toEdge) - && (fromLane < 0 || c.fromLane == fromLane) - && (toLane < 0 || c.toLane == toLane)) { - if (myTo->isTLControlled()) { - std::set tldefs = myTo->getControllingTLS(); - for (std::set::iterator it = tldefs.begin(); it != tldefs.end(); it++) { - (*it)->removeConnection(NBConnection(this, c.fromLane, c.toEdge, c.toLane)); - } - } - i = myConnections.erase(i); - tryLater = false; - } else { - if (fromLaneRemoved >= 0 && c.fromLane > fromLaneRemoved) { - if (myTo->isTLControlled()) { - std::set tldefs = myTo->getControllingTLS(); - for (std::set::iterator it = tldefs.begin(); it != tldefs.end(); it++) { - for (NBConnectionVector::iterator tlcon = (*it)->getControlledLinks().begin(); tlcon != (*it)->getControlledLinks().end(); ++tlcon) { - NBConnection& tc = *tlcon; - if (tc.getTo() == c.toEdge && tc.getFromLane() == c.fromLane && tc.getToLane() == c.toLane) { - tc.shiftLaneIndex(this, -1); - } - } - } - } - //std::cout << getID() << " removeFromConnections fromLane=" << fromLane << " to=" << Named::getIDSecure(toEdge) << " toLane=" << toLane << " reduceFromLane=" << c.fromLane << " (to=" << c.toLane << ")\n"; - c.fromLane--; - } - if (toLaneRemoved >= 0 && c.toLane > toLaneRemoved && (toEdge == nullptr || c.toEdge == toEdge)) { - //std::cout << getID() << " removeFromConnections fromLane=" << fromLane << " to=" << Named::getIDSecure(toEdge) << " toLane=" << toLane << " reduceToLane=" << c.toLane << " (from=" << c.fromLane << ")\n"; - c.toLane--; - } - ++i; - } - } - // check whether it was the turn destination - if (myTurnDestination == toEdge && fromLane < 0) { - myTurnDestination = nullptr; - } - if (myPossibleTurnDestination == toEdge && fromLane < 0 && !keepPossibleTurns) { - myPossibleTurnDestination = nullptr; - } - if (tryLater) { - myConnectionsToDelete.push_back(Connection(fromLane, toEdge, toLane)); -#ifdef DEBUG_CONNECTION_GUESSING - if (DEBUGCOND) { - std::cout << "removeFromConnections " << getID() << "_" << fromLane << "->" << toEdge->getID() << "_" << toLane << "\n"; - for (Connection& c : myConnections) { - std::cout << " conn " << c.getDescription(this) << "\n"; - } - for (Connection& c : myConnectionsToDelete) { - std::cout << " connToDelete " << c.getDescription(this) << "\n"; - } - } -#endif - } -} - - -bool -NBEdge::removeFromConnections(const NBEdge::Connection& connectionToRemove) { - // iterate over connections - for (auto i = myConnections.begin(); i != myConnections.end(); i++) { - if ((i->toEdge == connectionToRemove.toEdge) && (i->fromLane == connectionToRemove.fromLane) && (i->toLane == connectionToRemove.toLane)) { - // remove connection - myConnections.erase(i); - return true; - } - } - // assert(false); - return false; -} - - -void -NBEdge::invalidateConnections(bool reallowSetting) { - myTurnDestination = nullptr; - myConnections.clear(); - if (reallowSetting) { - myStep = EdgeBuildingStep::INIT; - } else { - myStep = EdgeBuildingStep::INIT_REJECT_CONNECTIONS; - } -} - - -void -NBEdge::replaceInConnections(NBEdge* which, NBEdge* by, int laneOff) { - // replace in "_connectedEdges" - for (std::vector::iterator i = myConnections.begin(); i != myConnections.end(); ++i) { - if ((*i).toEdge == which) { - (*i).toEdge = by; - (*i).toLane += laneOff; - } - } - // check whether it was the turn destination - if (myTurnDestination == which) { - myTurnDestination = by; - } -} - -void -NBEdge::replaceInConnections(NBEdge* which, const std::vector& origConns) { - std::map laneMap; - int minLane = -1; - int maxLane = -1; - // get lanes used to approach the edge to remap - bool wasConnected = false; - for (std::vector::iterator i = myConnections.begin(); i != myConnections.end(); ++i) { - if ((*i).toEdge != which) { - continue; - } - wasConnected = true; - if ((*i).fromLane != -1) { - int fromLane = (*i).fromLane; - laneMap[(*i).toLane] = fromLane; - if (minLane == -1 || minLane > fromLane) { - minLane = fromLane; - } - if (maxLane == -1 || maxLane < fromLane) { - maxLane = fromLane; - } - } - } - if (!wasConnected) { - return; - } - // add new connections - std::vector conns = origConns; - EdgeVector origTargets = getSuccessors(); - for (std::vector::iterator i = conns.begin(); i != conns.end(); ++i) { - if ((*i).toEdge == which || (*i).toEdge == this - // if we already have connections to the target edge, do not add new ones as they are probably from a circular replacement - || std::find(origTargets.begin(), origTargets.end(), (*i).toEdge) != origTargets.end()) { -#ifdef DEBUG_REPLACECONNECTION - if (DEBUGCOND) { - std::cout << " replaceInConnections edge=" << getID() << " which=" << which->getID() - << " origTargets=" << toString(origTargets) << " newTarget=" << i->toEdge->getID() << " skipped\n"; - } -#endif - continue; - } - if (which->getStep() == EdgeBuildingStep::EDGE2EDGES) { - // do not set lane-level connections - replaceInConnections(which, (*i).toEdge, 0); - continue; - } - int fromLane = (*i).fromLane; - int toUse = -1; - if (laneMap.find(fromLane) == laneMap.end()) { - if (fromLane >= 0 && fromLane <= minLane) { - toUse = minLane; - // patch laneMap to avoid crossed-over connections - for (auto& item : laneMap) { - if (item.first < fromLane) { - item.second = MIN2(item.second, minLane); - } - } - } - if (fromLane >= 0 && fromLane >= maxLane) { - toUse = maxLane; - // patch laneMap to avoid crossed-over connections - for (auto& item : laneMap) { - if (item.first > fromLane) { - item.second = MAX2(item.second, maxLane); - } - } - } - } else { - toUse = laneMap[fromLane]; - } - if (toUse == -1) { - toUse = 0; - } -#ifdef DEBUG_REPLACECONNECTION - if (DEBUGCOND) { - std::cout << " replaceInConnections edge=" << getID() << " which=" << which->getID() << " origTargets=" << toString(origTargets) - << " origFrom=" << fromLane << " laneMap=" << joinToString(laneMap, ":", ",") << " minLane=" << minLane << " maxLane=" << maxLane - << " newTarget=" << i->toEdge->getID() << " fromLane=" << toUse << " toLane=" << i->toLane << "\n"; - } -#endif - setConnection(toUse, i->toEdge, i->toLane, Lane2LaneInfoType::COMPUTED, false, i->mayDefinitelyPass, i->keepClear, - i->contPos, i->visibility, i->speed, i->customLength, i->customShape, i->uncontrolled); - } - // remove the remapped edge from connections - removeFromConnections(which); -} - - -void -NBEdge::copyConnectionsFrom(NBEdge* src) { - myStep = src->myStep; - myConnections = src->myConnections; -} - - -bool -NBEdge::canMoveConnection(const Connection& con, int newFromLane) const { - // only allow using newFromLane if at least 1 vClass is permitted to use - // this connection. If the connection shall be moved to a sidewalk, only create the connection if there is no walking area - const SVCPermissions common = (getPermissions(newFromLane) & con.toEdge->getPermissions(con.toLane)); - return (common > 0 && common != SVC_PEDESTRIAN); -} - - -void -NBEdge::moveConnectionToLeft(int lane) { - int index = 0; - for (int i = 0; i < (int)myConnections.size(); ++i) { - if (myConnections[i].fromLane == (int)(lane) && canMoveConnection(myConnections[i], lane + 1)) { - index = i; - } - } - std::vector::iterator i = myConnections.begin() + index; - Connection c = *i; - myConnections.erase(i); - setConnection(lane + 1, c.toEdge, c.toLane, Lane2LaneInfoType::VALIDATED, false); -} - - -void -NBEdge::moveConnectionToRight(int lane) { - for (std::vector::iterator i = myConnections.begin(); i != myConnections.end(); ++i) { - if ((*i).fromLane == (int)lane && canMoveConnection(*i, lane - 1)) { - Connection c = *i; - i = myConnections.erase(i); - setConnection(lane - 1, c.toEdge, c.toLane, Lane2LaneInfoType::VALIDATED, false); - return; - } - } -} - - -void -NBEdge::buildInnerEdges(const NBNode& n, int noInternalNoSplits, int& linkIndex, int& splitIndex) { - const int numPoints = OptionsCont::getOptions().getInt("junctions.internal-link-detail"); - const bool joinTurns = OptionsCont::getOptions().getBool("junctions.join-turns"); - const double limitTurnSpeed = OptionsCont::getOptions().getFloat("junctions.limit-turn-speed"); - const double limitTurnSpeedMinAngle = DEG2RAD(OptionsCont::getOptions().getFloat("junctions.limit-turn-speed.min-angle")); - const double limitTurnSpeedMinAngleRail = DEG2RAD(OptionsCont::getOptions().getFloat("junctions.limit-turn-speed.min-angle.railway")); - const double limitTurnSpeedWarnStraight = OptionsCont::getOptions().getFloat("junctions.limit-turn-speed.warn.straight"); - const double limitTurnSpeedWarnTurn = OptionsCont::getOptions().getFloat("junctions.limit-turn-speed.warn.turn"); - const bool fromRail = isRailway(getPermissions()); - std::string innerID = ":" + n.getID(); - NBEdge* toEdge = nullptr; - int edgeIndex = linkIndex; - int internalLaneIndex = 0; - int numLanes = 0; // number of lanes that share the same edge - double lengthSum = 0; // total shape length of all lanes that share the same edge - for (std::vector::iterator i = myConnections.begin(); i != myConnections.end(); ++i) { - Connection& con = *i; - con.haveVia = false; // reset first since this may be called multiple times - if (con.toEdge == nullptr) { - continue; - } - LinkDirection dir = n.getDirection(this, con.toEdge); - const bool isRightTurn = (dir == LinkDirection::RIGHT || dir == LinkDirection::PARTRIGHT); - const bool isTurn = (isRightTurn || dir == LinkDirection::LEFT || dir == LinkDirection::PARTLEFT); - - // put turning internal lanes on separate edges - if (con.toEdge != toEdge || (isTurn && !joinTurns)) { - // skip indices to keep some correspondence between edge ids and link indices: - // internalEdgeIndex + internalLaneIndex = linkIndex - edgeIndex = linkIndex; - toEdge = (*i).toEdge; - internalLaneIndex = 0; - assignInternalLaneLength(i, numLanes, lengthSum); - numLanes = 0; - lengthSum = 0; - } - SVCPermissions conPermissions = getPermissions(con.fromLane) & con.toEdge->getPermissions(con.toLane); - int shapeFlag = (conPermissions & ~SVC_PEDESTRIAN) != 0 ? 0 : NBNode::SCURVE_IGNORE; - PositionVector shape = n.computeInternalLaneShape(this, con, numPoints, myTo, shapeFlag); - std::vector foeInternalLinks; - - if (dir != LinkDirection::STRAIGHT && shape.length() < POSITION_EPS && !(isBidiRail() && getTurnDestination(true) == con.toEdge)) { - WRITE_WARNINGF("Connection '%_%->%_%' is only %m short.", getID(), con.fromLane, con.toEdge->getID(), con.toLane, shape.length()); - } - - // crossingPosition, list of foe link indices - std::pair > crossingPositions(-1, std::vector()); - std::set tmpFoeIncomingLanes; - switch (dir) { - case LinkDirection::RIGHT: - case LinkDirection::PARTRIGHT: - case LinkDirection::LEFT: - case LinkDirection::PARTLEFT: - case LinkDirection::TURN: { - int index = 0; - const std::vector& incoming = n.getIncomingEdges(); - for (EdgeVector::const_iterator i2 = incoming.begin(); i2 != incoming.end(); ++i2) { - const std::vector& elv = (*i2)->getConnections(); - for (std::vector::const_iterator k2 = elv.begin(); k2 != elv.end(); k2++) { - if ((*k2).toEdge == nullptr) { - continue; - } - // vehicles are typically less wide than the lane - // they drive on but but bicycle lanes should be kept clear for their whole width - double width2 = (*k2).toEdge->getLaneWidth((*k2).toLane); - if ((*k2).toEdge->getPermissions((*k2).toLane) != SVC_BICYCLE) { - width2 *= 0.5; - } - const bool foes = n.foes(this, con.toEdge, *i2, (*k2).toEdge); - bool needsCont = !isRailway(conPermissions) && n.needsCont(this, *i2, con, *k2); - bool oppositeLeftIntersect = !foes && bothLeftIntersect(n, shape, dir, *i2, *k2, numPoints, width2); - int shapeFlag = 0; - // do not warn if only bicycles pedestrians or delivery vehicles are involved as this is a typical occurence - SVCPermissions warn = SVCAll & ~(SVC_PEDESTRIAN | SVC_BICYCLE | SVC_DELIVERY | SVC_RAIL_CLASSES); - if (oppositeLeftIntersect - && (((*i2)->getPermissions((*k2).fromLane) & warn) != 0 - && ((*k2).toEdge->getPermissions((*k2).toLane) & warn) != 0)) { - // recompute with different curve parameters (unless - // the other connection is "unimportant" - shapeFlag = NBNode::AVOID_INTERSECTING_LEFT_TURNS; - shape = n.computeInternalLaneShape(this, con, numPoints, myTo, shapeFlag); - oppositeLeftIntersect = bothLeftIntersect(n, shape, dir, *i2, *k2, numPoints, width2, shapeFlag); - } - const bool bothPrio = getJunctionPriority(&n) > 0 && (*i2)->getJunctionPriority(&n) > 0; - //std::cout << "n=" << n.getID() << " e1=" << getID() << " prio=" << getJunctionPriority(&n) << " e2=" << (*i2)->getID() << " prio2=" << (*i2)->getJunctionPriority(&n) << " both=" << bothPrio << " bothLeftIntersect=" << bothLeftIntersect(n, shape, dir, *i2, *k2, numPoints, width2) << " needsCont=" << needsCont << "\n"; - // compute the crossing point - if (needsCont || (bothPrio && oppositeLeftIntersect)) { - crossingPositions.second.push_back(index); - const PositionVector otherShape = n.computeInternalLaneShape(*i2, *k2, numPoints, 0, shapeFlag); - const double minDV = firstIntersection(shape, otherShape, width2, - "Could not compute intersection of conflicting internal lanes at node '" + myTo->getID() + "'"); - if (minDV < shape.length() - POSITION_EPS && minDV > POSITION_EPS) { // !!!? - assert(minDV >= 0); - if (crossingPositions.first < 0 || crossingPositions.first > minDV) { - crossingPositions.first = minDV; - } - } - } - const bool rightTurnConflict = NBNode::rightTurnConflict( - this, con.toEdge, con.fromLane, (*i2), (*k2).toEdge, (*k2).fromLane); - // compute foe internal lanes - if (foes || rightTurnConflict || oppositeLeftIntersect) { - foeInternalLinks.push_back(index); - } - // only warn once per pair of intersecting turns - if (oppositeLeftIntersect && getID() > (*i2)->getID() - && (getPermissions(con.fromLane) & warn) != 0 - && (con.toEdge->getPermissions(con.toLane) & warn) != 0 - && ((*i2)->getPermissions((*k2).fromLane) & warn) != 0 - && ((*k2).toEdge->getPermissions((*k2).toLane) & warn) != 0 - // do not warn for unregulated nodes - && n.getType() != SumoXMLNodeType::NOJUNCTION - ) { - WRITE_WARNINGF("Intersecting left turns at junction '%' from lane '%' and lane '%' (increase junction radius to avoid this).", - n.getID(), getLaneID(con.fromLane), (*i2)->getLaneID((*k2).fromLane)); - } - // compute foe incoming lanes - const bool signalised = hasSignalisedConnectionTo(con.toEdge); - if ((n.forbids(*i2, (*k2).toEdge, this, con.toEdge, signalised) || rightTurnConflict) && (needsCont || dir == LinkDirection::TURN)) { - tmpFoeIncomingLanes.insert((*i2)->getID() + "_" + toString((*k2).fromLane)); - } - if (bothPrio && oppositeLeftIntersect && getID() < (*i2)->getID()) { - //std::cout << " c1=" << con.getDescription(this) << " c2=" << (*k2).getDescription(*i2) << " bothPrio=" << bothPrio << " oppositeLeftIntersect=" << oppositeLeftIntersect << "\n"; - // break symmetry using edge id - tmpFoeIncomingLanes.insert(innerID + "_" + toString(index) + "_0"); - } - index++; - } - } - // foe pedestrian crossings - std::vector crossings = n.getCrossings(); - for (auto c : crossings) { - const NBNode::Crossing& crossing = *c; - for (EdgeVector::const_iterator it_e = crossing.edges.begin(); it_e != crossing.edges.end(); ++it_e) { - const NBEdge* edge = *it_e; - // compute foe internal lanes - if (this == edge || con.toEdge == edge) { - foeInternalLinks.push_back(index); - if (con.toEdge == edge && - ((isRightTurn && getJunctionPriority(&n) > 0) || (isTurn && con.tlID != ""))) { - // build internal junctions (not for left turns at uncontrolled intersections) - PositionVector crossingShape = crossing.shape; - crossingShape.extrapolate(5.0); // sometimes shapes miss each other by a small margin - const double minDV = firstIntersection(shape, crossingShape, crossing.width / 2); - if (minDV < shape.length() - POSITION_EPS && minDV > POSITION_EPS) { - assert(minDV >= 0); - if (crossingPositions.first < 0 || crossingPositions.first > minDV) { - crossingPositions.first = minDV; - } - } - } - } - } - index++; - } - - if (dir == LinkDirection::TURN && crossingPositions.first < 0 && crossingPositions.second.size() != 0 && shape.length() > 2. * POSITION_EPS) { - // let turnarounds wait in the middle if no other crossing point was found and it has a sensible length - // (if endOffset is used, the crossing point is in the middle of the part within the junction shape) - crossingPositions.first = (double)(shape.length() + getEndOffset(con.fromLane)) / 2.; - } - } - break; - default: - break; - } - if (con.contPos != UNSPECIFIED_CONTPOS) { - // apply custom internal junction position - if (con.contPos <= 0 || con.contPos >= shape.length()) { - // disable internal junction - crossingPositions.first = -1; - } else { - // set custom position - crossingPositions.first = con.contPos; - } - } - - // @todo compute the maximum speed allowed based on angular velocity - // see !!! for an explanation (with a_lat_mean ~0.3) - /* - double vmax = (double) 0.3 * (double) 9.80778 * - getLaneShape(con.fromLane).back().distanceTo( - con.toEdge->getLaneShape(con.toLane).front()) - / (double) 2.0 / (double) M_PI; - vmax = MIN2(vmax, ((getSpeed() + con.toEdge->getSpeed()) / (double) 2.0)); - */ - if (con.speed == UNSPECIFIED_SPEED) { - con.vmax = (myLanes[con.fromLane].speed + con.toEdge->getLanes()[con.toLane].speed) / (double) 2.0; - if (limitTurnSpeed > 0) { - // see [Odhams and Cole, Models of Driver Speed Choice in Curves, 2004] - const double angleRaw = fabs(GeomHelper::angleDiff( - getLaneShape(con.fromLane).angleAt2D(-2), - con.toEdge->getLaneShape(con.toLane).angleAt2D(0))); - const double angle = MAX2(0.0, angleRaw - (fromRail ? limitTurnSpeedMinAngleRail : limitTurnSpeedMinAngle)); - const double length = shape.length2D(); - // do not trust the radius of tiny junctions - // formula adapted from [Odhams, Andre and Cole, David, Models of Driver Speed Choice in Curves, 2004] - if (angle > 0 && length > 1) { - // permit higher turning speed on wide lanes - const double radius = length / angle + getLaneWidth(con.fromLane) / 4; - const double limit = sqrt(limitTurnSpeed * radius); - const double reduction = con.vmax - limit; - // always treat connctions at roundabout as turns when warning - const bool atRoundabout = getJunctionPriority(myTo) == JunctionPriority::ROUNDABOUT || con.toEdge->getJunctionPriority(myFrom) == JunctionPriority::ROUNDABOUT; - const LinkDirection dir2 = atRoundabout ? LinkDirection::LEFT : dir; - if ((dir2 == LinkDirection::STRAIGHT && reduction > limitTurnSpeedWarnStraight) - || (dir2 != LinkDirection::TURN && reduction > limitTurnSpeedWarnTurn)) { - std::string dirType = std::string(dir == LinkDirection::STRAIGHT ? "straight" : "turning"); - if (atRoundabout) { - dirType = "roundabout"; - } - WRITE_WARNINGF("Speed of % connection '%' reduced by % due to turning radius of % (length=%, angle=%).", - dirType, con.getDescription(this), reduction, radius, length, RAD2DEG(angleRaw)); - } - con.vmax = MIN2(con.vmax, limit); - // value is saved in attribute. Must be set again when importing from .con.xml - // con.speed = con.vmax; - } - assert(con.vmax > 0); - //if (getID() == "-1017000.0.00") { - // std::cout << con.getDescription(this) << " angleRaw=" << angleRaw << " angle=" << RAD2DEG(angle) << " length=" << length << " radius=" << length / angle - // << " vmaxTurn=" << sqrt(limitTurnSpeed * length / angle) << " vmax=" << con.vmax << "\n"; - //} - } else if (fromRail && dir == LinkDirection::TURN) { - con.vmax = 0.01; - } - } else { - con.vmax = con.speed; - } - // - assert(shape.size() >= 2); - // get internal splits if any - con.id = innerID + "_" + toString(edgeIndex); - if (crossingPositions.first >= 0 && crossingPositions.first < shape.length()) { - std::pair split = shape.splitAt(crossingPositions.first); - con.shape = split.first; - con.foeIncomingLanes = std::vector(tmpFoeIncomingLanes.begin(), tmpFoeIncomingLanes.end()); - con.foeInternalLinks = foeInternalLinks; // resolve link indices to lane ids later - con.viaID = innerID + "_" + toString(splitIndex + noInternalNoSplits); - ++splitIndex; - con.viaShape = split.second; - con.haveVia = true; - } else { - con.shape = shape; - } - con.internalLaneIndex = internalLaneIndex; - ++internalLaneIndex; - ++linkIndex; - ++numLanes; - if (con.customLength != UNSPECIFIED_LOADED_LENGTH) { - lengthSum += con.customLength; - } else { - lengthSum += con.shape.length(); - } - } - assignInternalLaneLength(myConnections.end(), numLanes, lengthSum); -} - - -void -NBEdge::assignInternalLaneLength(std::vector::iterator i, int numLanes, double lengthSum) { - // assign average length to all lanes of the same internal edge - // @note the actual length should be used once sumo supports lanes of - // varying length within the same edge - assert(i - myConnections.begin() >= numLanes); - for (int prevIndex = 1; prevIndex <= numLanes; prevIndex++) { - //std::cout << " con=" << (*(i - prevIndex)).getDescription(this) << " numLanes=" << numLanes << " avgLength=" << lengthSum / numLanes << "\n"; - Connection& c = (*(i - prevIndex)); - const double minLength = c.customLength != UNSPECIFIED_LOADED_LENGTH ? pow(10, -gPrecision) : POSITION_EPS; - c.length = MAX2(minLength, lengthSum / numLanes); - if (c.haveVia) { - c.viaLength = c.viaShape.length(); - if (c.customLength != UNSPECIFIED_LOADED_LENGTH) { - // split length proportionally - const double firstLength = c.shape.length(); - const double a = firstLength / (firstLength + c.viaLength); - c.length = MAX2(minLength, a * c.customLength); - c.viaLength = MAX2(minLength, c.customLength - c.length); - } - } - } -} - -double -NBEdge::firstIntersection(const PositionVector& v1, const PositionVector& v2, double width2, const std::string& error) { - double intersect = std::numeric_limits::max(); - if (v2.length() < POSITION_EPS) { - return intersect; - } - try { - PositionVector v2Right = v2; - v2Right.move2side(width2); - - PositionVector v2Left = v2; - v2Left.move2side(-width2); - - // intersect center line of v1 with left and right border of v2 - for (double cand : v1.intersectsAtLengths2D(v2Right)) { - intersect = MIN2(intersect, cand); - } - for (double cand : v1.intersectsAtLengths2D(v2Left)) { - intersect = MIN2(intersect, cand); - } - } catch (InvalidArgument&) { - if (error != "") { - WRITE_WARNING(error); - } - } - //std::cout << " v1=" << v1 << " v2Right=" << v2Right << " v2Left=" << v2Left << "\n"; - //std::cout << " intersectsRight=" << toString(v1.intersectsAtLengths2D(v2Right)) << "\n"; - //std::cout << " intersectsLeft=" << toString(v1.intersectsAtLengths2D(v2Left)) << "\n"; - return intersect; -} - - -bool -NBEdge::bothLeftIntersect(const NBNode& n, const PositionVector& shape, LinkDirection dir, NBEdge* otherFrom, const NBEdge::Connection& otherCon, int numPoints, double width2, int shapeFlag) const { - if (otherFrom == this) { - // not an opposite pair - return false; - } - LinkDirection dir2 = n.getDirection(otherFrom, otherCon.toEdge); - const bool bothLeft = (dir == LinkDirection::LEFT || dir == LinkDirection::PARTLEFT) && (dir2 == LinkDirection::LEFT || dir2 == LinkDirection::PARTLEFT); - if (bothLeft) { - const PositionVector otherShape = n.computeInternalLaneShape(otherFrom, otherCon, numPoints, 0, shapeFlag); - const double minDV = firstIntersection(shape, otherShape, width2); - if (minDV < shape.length() - POSITION_EPS && minDV > POSITION_EPS) { - return true; - } else { - return false; - } - } else { - return false; - } -} - - -// ----------- -int -NBEdge::getJunctionPriority(const NBNode* const node) const { - if (node == myFrom) { - return myFromJunctionPriority; - } else { - return myToJunctionPriority; - } -} - - -void -NBEdge::setJunctionPriority(const NBNode* const node, int prio) { - if (node == myFrom) { - myFromJunctionPriority = prio; - } else { - myToJunctionPriority = prio; - } -} - - -double -NBEdge::getAngleAtNode(const NBNode* const atNode) const { - // myStartAngle, myEndAngle are in [0,360] and this returns results in [-180,180] - if (atNode == myFrom) { - return GeomHelper::legacyDegree(myGeom.angleAt2D(0)); - } else { - assert(atNode == myTo); - return GeomHelper::legacyDegree(myGeom.angleAt2D(-2)); - } -} - - -double -NBEdge::getAngleAtNodeToCenter(const NBNode* const atNode) const { - if (atNode == myFrom) { - double res = myStartAngle - 180; - if (res < 0) { - res += 360; - } - return res; - } else { - assert(atNode == myTo); - return myEndAngle; - } -} - - -void -NBEdge::setTurningDestination(NBEdge* e, bool onlyPossible) { - if (!onlyPossible) { - myTurnDestination = e; - } - myPossibleTurnDestination = e; -} - - -double -NBEdge::getLaneSpeed(int lane) const { - return myLanes[lane].speed; -} - -void -NBEdge::resetLaneShapes() { - computeLaneShapes(); -} - -void -NBEdge::computeLaneShapes() { - // vissim needs this - if (myFrom == myTo) { - return; - } - // compute lane offset, first - std::vector offsets(myLanes.size(), 0.); - double offset = 0; - for (int i = (int)myLanes.size() - 2; i >= 0; --i) { - offset += (getLaneWidth(i) + getLaneWidth(i + 1)) / 2. + SUMO_const_laneOffset; - offsets[i] = offset; - } - if (myLaneSpreadFunction == LaneSpreadFunction::CENTER) { - double width = 0; - for (int i = 0; i < (int)myLanes.size(); ++i) { - width += getLaneWidth(i); - } - width += SUMO_const_laneOffset * double(myLanes.size() - 1); - offset = -width / 2. + getLaneWidth((int)myLanes.size() - 1) / 2.; - } else { - double laneWidth = myLanes.back().width != UNSPECIFIED_WIDTH ? myLanes.back().width : SUMO_const_laneWidth; - offset = (laneWidth + SUMO_const_laneOffset) / 2.; // @note: offset for half of the center-line marking of the road - } - if (myLaneSpreadFunction == LaneSpreadFunction::ROADCENTER) { - for (NBEdge* e : myTo->getOutgoingEdges()) { - if (e->getToNode() == myFrom && getInnerGeometry().reverse() == e->getInnerGeometry()) { - offset += (e->getTotalWidth() - getTotalWidth()) / 2; - break; - } - } - } - - for (int i = 0; i < (int)myLanes.size(); ++i) { - offsets[i] += offset; - } - - // build the shape of each lane - for (int i = 0; i < (int)myLanes.size(); ++i) { - if (myLanes[i].customShape.size() != 0) { - myLanes[i].shape = myLanes[i].customShape; - continue; - } - try { - myLanes[i].shape = computeLaneShape(i, offsets[i]); - } catch (InvalidArgument& e) { - WRITE_WARNINGF("In lane '%': lane shape could not be determined (%).", getLaneID(i), e.what()); - myLanes[i].shape = myGeom; - } - } -} - - -PositionVector -NBEdge::computeLaneShape(int lane, double offset) const { - PositionVector shape = myGeom; - try { - shape.move2side(offset); - } catch (InvalidArgument& e) { - WRITE_WARNINGF("In lane '%': Could not build shape (%).", getLaneID(lane), e.what()); - } - return shape; -} - - -void -NBEdge::computeAngle() { - // taking the angle at the first might be unstable, thus we take the angle - // at a certain distance. (To compare two edges, additional geometry - // segments are considered to resolve ambiguities) - const bool hasFromShape = myFrom->getShape().size() > 0; - const bool hasToShape = myTo->getShape().size() > 0; - Position fromCenter = (hasFromShape ? myFrom->getShape().getCentroid() : myFrom->getPosition()); - Position toCenter = (hasToShape ? myTo->getShape().getCentroid() : myTo->getPosition()); - PositionVector shape = myGeom; - if ((hasFromShape || hasToShape) && getNumLanes() > 0) { - if (myLaneSpreadFunction == LaneSpreadFunction::RIGHT) { - shape = myLanes[getNumLanes() - 1].shape ; - } else { - shape = myLanes[getNumLanes() / 2].shape; - if (getNumLanes() % 2 == 0) { - // there is no center lane. shift to get the center - shape.move2side(getLaneWidth(getNumLanes() / 2) * 0.5); - } - } - } - - // if the junction shape is suspicious we cannot trust the angle to the centroid - const bool suspiciousFromShape = hasFromShape && (myFrom->getShape().distance2D(shape[0]) > 2 * POSITION_EPS - || myFrom->getShape().around(shape[-1]) - || !(myFrom->getShape().around(fromCenter))); - const bool suspiciousToShape = hasToShape && (myTo->getShape().distance2D(shape[-1]) > 2 * POSITION_EPS - || myTo->getShape().around(shape[0]) - || !(myTo->getShape().around(toCenter))); - - const double angleLookahead = MIN2(shape.length2D() / 2, ANGLE_LOOKAHEAD); - const Position referencePosStart = shape.positionAtOffset2D(angleLookahead); - const Position referencePosEnd = shape.positionAtOffset2D(shape.length() - angleLookahead); - - myStartAngle = GeomHelper::legacyDegree(fromCenter.angleTo2D(referencePosStart), true); - const double myStartAngle2 = GeomHelper::legacyDegree(myFrom->getPosition().angleTo2D(referencePosStart), true); - const double myStartAngle3 = getAngleAtNode(myFrom); - myEndAngle = GeomHelper::legacyDegree(referencePosEnd.angleTo2D(toCenter), true); - const double myEndAngle2 = GeomHelper::legacyDegree(referencePosEnd.angleTo2D(myTo->getPosition()), true); - const double myEndAngle3 = getAngleAtNode(myTo); - -#ifdef DEBUG_ANGLES - if (DEBUGCOND) { - if (suspiciousFromShape) { - std::cout << " len=" << shape.length() << " startA=" << myStartAngle << " startA2=" << myStartAngle2 << " startA3=" << myStartAngle3 - << " rel=" << NBHelpers::normRelAngle(myStartAngle, myStartAngle2) - << " fromCenter=" << fromCenter - << " fromPos=" << myFrom->getPosition() - << " refStart=" << referencePosStart - << "\n"; - } - if (suspiciousToShape) { - std::cout << " len=" << shape.length() << " endA=" << myEndAngle << " endA2=" << myEndAngle2 << " endA3=" << myEndAngle3 - << " rel=" << NBHelpers::normRelAngle(myEndAngle, myEndAngle2) - << " toCenter=" << toCenter - << " toPos=" << myTo->getPosition() - << " refEnd=" << referencePosEnd - << "\n"; - } - } -#endif - - if (suspiciousFromShape && shape.length() > 1) { - myStartAngle = myStartAngle2; - } else if (suspiciousToShape && fabs(NBHelpers::normRelAngle(myStartAngle, myStartAngle3)) > 90 - // don't trust footpath angles - && (getPermissions() & ~SVC_PEDESTRIAN) != 0) { - myStartAngle = myStartAngle3; - if (myStartAngle < 0) { - myStartAngle += 360; - } - } - - if (suspiciousToShape && shape.length() > 1) { - myEndAngle = myEndAngle2; - } else if (suspiciousToShape && fabs(NBHelpers::normRelAngle(myEndAngle, myEndAngle3)) > 90 - // don't trust footpath angles - && (getPermissions() & ~SVC_PEDESTRIAN) != 0) { - myEndAngle = myEndAngle3; - if (myEndAngle < 0) { - myEndAngle += 360; - } - } - - myTotalAngle = GeomHelper::legacyDegree(myFrom->getPosition().angleTo2D(myTo->getPosition()), true); -#ifdef DEBUG_ANGLES - if (DEBUGCOND) std::cout << "computeAngle edge=" << getID() - << " fromCenter=" << fromCenter << " toCenter=" << toCenter - << " refStart=" << referencePosStart << " refEnd=" << referencePosEnd << " shape=" << shape - << " hasFromShape=" << hasFromShape - << " hasToShape=" << hasToShape - << " numLanes=" << getNumLanes() - << " shapeLane=" << getNumLanes() / 2 - << " startA=" << myStartAngle << " endA=" << myEndAngle << " totA=" << myTotalAngle << "\n"; -#endif -} - - -double -NBEdge::getShapeStartAngle() const { - const double angleLookahead = MIN2(myGeom.length2D() / 2, ANGLE_LOOKAHEAD); - const Position referencePosStart = myGeom.positionAtOffset2D(angleLookahead); - return GeomHelper::legacyDegree(myGeom.front().angleTo2D(referencePosStart), true); -} - - -double -NBEdge::getShapeEndAngle() const { - const double angleLookahead = MIN2(myGeom.length2D() / 2, ANGLE_LOOKAHEAD); - const Position referencePosEnd = myGeom.positionAtOffset2D(myGeom.length() - angleLookahead); - return GeomHelper::legacyDegree(referencePosEnd.angleTo2D(myGeom.back()), true); -} - - -bool -NBEdge::hasPermissions() const { - for (std::vector::const_iterator i = myLanes.begin(); i != myLanes.end(); ++i) { - if ((*i).permissions != SVCAll) { - return true; - } - } - return false; -} - - -bool -NBEdge::hasLaneSpecificPermissions() const { - std::vector::const_iterator i = myLanes.begin(); - SVCPermissions firstLanePermissions = i->permissions; - i++; - for (; i != myLanes.end(); ++i) { - if (i->permissions != firstLanePermissions) { - return true; - } - } - return false; -} - - -bool -NBEdge::hasLaneSpecificSpeed() const { - for (std::vector::const_iterator i = myLanes.begin(); i != myLanes.end(); ++i) { - if (i->speed != getSpeed()) { - return true; - } - } - return false; -} - - -bool -NBEdge::hasLaneSpecificWidth() const { - for (std::vector::const_iterator i = myLanes.begin(); i != myLanes.end(); ++i) { - if (i->width != myLanes.begin()->width) { - return true; - } - } - return false; -} - - -bool -NBEdge::hasLaneSpecificType() const { - for (std::vector::const_iterator i = myLanes.begin(); i != myLanes.end(); ++i) { - if (i->type != myLanes.begin()->type) { - return true; - } - } - return false; -} - - -bool -NBEdge::hasLaneSpecificEndOffset() const { - for (std::vector::const_iterator i = myLanes.begin(); i != myLanes.end(); ++i) { - if (i->endOffset != myLanes.begin()->endOffset) { - return true; - } - } - return false; -} - - -bool -NBEdge::hasLaneSpecificStopOffsets() const { - for (std::vector::const_iterator i = myLanes.begin(); i != myLanes.end(); ++i) { - if (!i->stopOffsets.empty()) { - const std::pair& offsets = *(i->stopOffsets.begin()); - if (myStopOffsets.empty() || offsets != *(myStopOffsets.begin())) { - return true; - } - } - } - return false; -} - - -bool -NBEdge::hasAccelLane() const { - for (std::vector::const_iterator i = myLanes.begin(); i != myLanes.end(); ++i) { - if (i->accelRamp) { - return true; - } - } - return false; -} - - -bool -NBEdge::hasCustomLaneShape() const { - for (std::vector::const_iterator i = myLanes.begin(); i != myLanes.end(); ++i) { - if (i->customShape.size() > 0) { - return true; - } - } - return false; -} - - -bool -NBEdge::hasLaneParams() const { - for (std::vector::const_iterator i = myLanes.begin(); i != myLanes.end(); ++i) { - if (i->getParametersMap().size() > 0) { - return true; - } - } - return false; -} - -bool -NBEdge::needsLaneSpecificOutput() const { - return (hasLaneSpecificPermissions() - || hasLaneSpecificSpeed() - || hasLaneSpecificWidth() - || hasLaneSpecificType() - || hasLaneSpecificEndOffset() - || hasLaneSpecificStopOffsets() - || hasAccelLane() - || hasCustomLaneShape() - || hasLaneParams() - || (!myLanes.empty() && myLanes.back().oppositeID != "")); -} - - - -bool -NBEdge::computeEdge2Edges(bool noLeftMovers) { -#ifdef DEBUG_CONNECTION_GUESSING - if (DEBUGCOND) { - std::cout << "computeEdge2Edges edge=" << getID() << " step=" << (int)myStep << "\n"; - for (Connection& c : myConnections) { - std::cout << " conn " << c.getDescription(this) << "\n"; - } - for (Connection& c : myConnectionsToDelete) { - std::cout << " connToDelete " << c.getDescription(this) << "\n"; - } - } -#endif - // return if this relationship has been build in previous steps or - // during the import - if (myStep >= EdgeBuildingStep::EDGE2EDGES) { - return true; - } - const EdgeVector& o = myTo->getOutgoingEdges(); - const bool fromRail = isRailway(getPermissions()); - for (EdgeVector::const_iterator i = o.begin(); i != o.end(); ++i) { - if (noLeftMovers && myTo->isLeftMover(this, *i)) { - continue; - } - // avoid sharp railway turns - if (fromRail && isRailway((*i)->getPermissions()) && - fabs(NBHelpers::normRelAngle(getAngleAtNode(myTo), (*i)->getAngleAtNode(myTo))) > 90) { - continue; - } - myConnections.push_back(Connection(-1, *i, -1)); - } - myStep = EdgeBuildingStep::EDGE2EDGES; - return true; -} - - -bool -NBEdge::computeLanes2Edges() { -#ifdef DEBUG_CONNECTION_GUESSING - if (DEBUGCOND) { - std::cout << "computeLanes2Edges edge=" << getID() << " step=" << (int)myStep << "\n"; - for (Connection& c : myConnections) { - std::cout << " conn " << c.getDescription(this) << "\n"; - } - for (Connection& c : myConnectionsToDelete) { - std::cout << " connToDelete " << c.getDescription(this) << "\n"; - } - } -#endif - // return if this relationship has been build in previous steps or - // during the import - if (myStep >= EdgeBuildingStep::LANES2EDGES) { - return true; - } - assert(myStep == EdgeBuildingStep::EDGE2EDGES); - // get list of possible outgoing edges sorted by direction clockwise - // the edge in the backward direction (turnaround) is not in the list - const EdgeVector* edges = getConnectedSorted(); - if (myConnections.size() != 0 && edges->size() == 0) { - // dead end per definition!? - myConnections.clear(); - } else { - // divide the lanes on reachable edges - divideOnEdges(edges); - } - delete edges; - myStep = EdgeBuildingStep::LANES2EDGES; - return true; -} - - -bool -NBEdge::recheckLanes() { -#ifdef DEBUG_CONNECTION_GUESSING - if (DEBUGCOND) { - std::cout << "recheckLanes (initial) edge=" << getID() << "\n"; - for (Connection& c : myConnections) { - std::cout << " conn " << c.getDescription(this) << "\n"; - } - for (Connection& c : myConnectionsToDelete) { - std::cout << " connToDelete " << c.getDescription(this) << "\n"; - } - } -#endif - // check delayed removals - for (std::vector::iterator it = myConnectionsToDelete.begin(); it != myConnectionsToDelete.end(); ++it) { - removeFromConnections(it->toEdge, it->fromLane, it->toLane, false, false, true); - } - std::vector connNumbersPerLane(myLanes.size(), 0); - for (std::vector::iterator i = myConnections.begin(); i != myConnections.end();) { - if ((*i).toEdge == nullptr || (*i).fromLane < 0 || (*i).toLane < 0) { - i = myConnections.erase(i); - } else { - if ((*i).fromLane >= 0) { - ++connNumbersPerLane[(*i).fromLane]; - } - ++i; - } - } - if (myStep != EdgeBuildingStep::LANES2LANES_DONE && myStep != EdgeBuildingStep::LANES2LANES_USER) { - // check #1: - // If there is a lane with no connections and any neighbour lane has - // more than one connections, try to move one of them. - // This check is only done for edges which connections were assigned - // using the standard algorithm. - for (int i = 0; i < (int)myLanes.size(); i++) { - if (connNumbersPerLane[i] == 0 && !isForbidden(getPermissions((int)i))) { - // dead-end lane found - bool hasDeadEnd = true; - // find lane with two connections or more to the right of the current lane - for (int i2 = i - 1; hasDeadEnd && i2 >= 0; i2--) { - if (getPermissions(i) != getPermissions(i2)) { - break; - } - if (connNumbersPerLane[i2] > 1) { - connNumbersPerLane[i2]--; - for (int i3 = i2; i3 != i; i3++) { - moveConnectionToLeft(i3); - sortOutgoingConnectionsByAngle(); - sortOutgoingConnectionsByIndex(); - } - hasDeadEnd = false; - } - } - if (hasDeadEnd) { - // find lane with two connections or more to the left of the current lane - for (int i2 = i + 1; hasDeadEnd && i2 < getNumLanes(); i2++) { - if (getPermissions(i) != getPermissions(i2)) { - break; - } - if (connNumbersPerLane[i2] > 1) { - connNumbersPerLane[i2]--; - for (int i3 = i2; i3 != i; i3--) { - moveConnectionToRight(i3); - sortOutgoingConnectionsByAngle(); - sortOutgoingConnectionsByIndex(); - } - hasDeadEnd = false; - } - } - } - } - } - // check restrictions - for (std::vector::iterator i = myConnections.begin(); i != myConnections.end();) { - Connection& c = *i; - const SVCPermissions common = getPermissions(c.fromLane) & c.toEdge->getPermissions(c.toLane); - if (common == SVC_PEDESTRIAN || getPermissions(c.fromLane) == SVC_PEDESTRIAN) { - // these are computed in NBNode::buildWalkingAreas - i = myConnections.erase(i); - } else if (common == 0) { - // no common permissions. - // try to find a suitable target lane to the right - const int origToLane = c.toLane; - c.toLane = -1; // ignore this connection when calling hasConnectionTo - int toLane = origToLane; - while (toLane > 0 - && (getPermissions(c.fromLane) & c.toEdge->getPermissions(toLane)) == 0 - && !hasConnectionTo(c.toEdge, toLane) - ) { - toLane--; - } - if ((getPermissions(c.fromLane) & c.toEdge->getPermissions(toLane)) != 0 - && !hasConnectionTo(c.toEdge, toLane)) { - c.toLane = toLane; - ++i; - } else { - // try to find a suitable target lane to the left - int toLane = origToLane; - while (toLane < (int)c.toEdge->getNumLanes() - 1 - && (getPermissions(c.fromLane) & c.toEdge->getPermissions(toLane)) == 0 - && !hasConnectionTo(c.toEdge, toLane) - ) { - toLane++; - } - if ((getPermissions(c.fromLane) & c.toEdge->getPermissions(toLane)) != 0 - && !hasConnectionTo(c.toEdge, toLane)) { - c.toLane = toLane; - ++i; - } else { - // no alternative target found - i = myConnections.erase(i); - } - } - } else if (isRailway(getPermissions(c.fromLane)) && isRailway(c.toEdge->getPermissions(c.toLane)) - && isTurningDirectionAt(c.toEdge)) { - // do not allow sharp rail turns - i = myConnections.erase(i); - } else { - ++i; - } - } - } - // check involuntary dead end at "real" junctions - if (getPermissions() != SVC_PEDESTRIAN) { - if (myConnections.empty() && myTo->getOutgoingEdges().size() > 1 && (getPermissions() & ~SVC_PEDESTRIAN) != 0) { - WRITE_WARNINGF("Edge '%' is not connected to outgoing edges at junction '%'.", getID(), myTo->getID()); - } - const EdgeVector& incoming = myFrom->getIncomingEdges(); - if (incoming.size() > 1) { - for (int i = 0; i < (int)myLanes.size(); i++) { - if (getPermissions(i) != 0 && getPermissions(i) != SVC_PEDESTRIAN) { - bool connected = false; - for (std::vector::const_iterator in = incoming.begin(); in != incoming.end(); ++in) { - if ((*in)->hasConnectionTo(this, i)) { - connected = true; - break; - } - } - if (!connected) { - WRITE_WARNINGF("Lane '%' is not connected from any incoming edge at junction '%'.", getLaneID(i), myFrom->getID()); - } - } - } - } - } -#ifdef ADDITIONAL_WARNINGS - // check for connections with bad access permissions - for (const Connection& c : myConnections) { - SVCPermissions fromP = getPermissions(c.fromLane); - SVCPermissions toP = c.toEdge->getPermissions(c.toLane); - if ((fromP & SVC_PASSENGER) != 0 - && toP == SVC_BICYCLE) { - bool hasAlternative = false; - for (const Connection& c2 : myConnections) { - if (c.fromLane == c2.fromLane && c.toEdge == c2.toEdge - && (c.toEdge->getPermissions(c2.toLane) & SVC_PASSENGER) != 0) { - hasAlternative = true; - } - } - if (!hasAlternative) { - WRITE_WARNING("Road lane ends on bikeLane for connection " + c.getDescription(this)); - } - } - } - // check for dead-end passenger lanes when there are still unconnected outgoing edges - int passengerLanes = 0; - int passengerTargetLanes = 0; - for (const Lane& lane : myLanes) { - if ((lane.permissions & SVC_PASSENGER) != 0) { - passengerLanes++; - } - } - for (const NBEdge* out : myTo->getOutgoingEdges()) { - if (!isTurningDirectionAt(out)) { - for (const Lane& lane : out->getLanes()) { - if ((lane.permissions & SVC_PASSENGER) != 0) { - passengerTargetLanes++; - } - } - } - } - if (passengerLanes <= passengerTargetLanes) { - // no need for dead-ends - connNumbersPerLane = std::vector(myLanes.size(), 0); - for (const Connection& c : myConnections) { - connNumbersPerLane[c.fromLane]++; - } - for (int i = 0; i < (int)myLanes.size(); i++) { - if (connNumbersPerLane[i] == 0 && !isForbidden(getPermissions(i))) { - // dead-end lane found - WRITE_WARNING("Found dead-end lane " + getLaneID(i)); - } - } - } - -#endif -#ifdef DEBUG_CONNECTION_GUESSING - if (DEBUGCOND) { - std::cout << "recheckLanes (final) edge=" << getID() << "\n"; - for (Connection& c : myConnections) { - std::cout << " conn " << c.getDescription(this) << "\n"; - } - } -#endif - return true; -} - - -void -NBEdge::divideOnEdges(const EdgeVector* outgoing) { - if (outgoing->size() == 0) { - // we have to do this, because the turnaround may have been added before - myConnections.clear(); - return; - } - -#ifdef DEBUG_CONNECTION_GUESSING - if (DEBUGCOND) { - std::cout << " divideOnEdges " << getID() << " outgoing=" << toString(*outgoing) << "\n"; - } -#endif - - // build connections for miv lanes - std::vector availableLanes; - for (int i = 0; i < (int)myLanes.size(); ++i) { - if ((getPermissions(i) & SVC_PASSENGER) != 0) { - availableLanes.push_back(i); - } - } - if (availableLanes.size() > 0) { - divideSelectedLanesOnEdges(outgoing, availableLanes); - } - // build connections for miscellaneous further modes (more than bike,peds,bus and without passenger) - availableLanes.clear(); - for (int i = 0; i < (int)myLanes.size(); ++i) { - const SVCPermissions perms = getPermissions(i); - if ((perms & ~(SVC_PEDESTRIAN | SVC_BICYCLE | SVC_BUS)) == 0 || (perms & SVC_PASSENGER) != 0 || isForbidden(perms)) { - continue; - } - availableLanes.push_back(i); - } - if (availableLanes.size() > 0) { - divideSelectedLanesOnEdges(outgoing, availableLanes); - } - // build connections for busses (possibly combined with bicycles) - availableLanes.clear(); - for (int i = 0; i < (int)myLanes.size(); ++i) { - const SVCPermissions perms = getPermissions(i); - if (perms != SVC_BUS && perms != (SVC_BUS | SVC_BICYCLE)) { - continue; - } - availableLanes.push_back(i); - } - if (availableLanes.size() > 0) { - divideSelectedLanesOnEdges(outgoing, availableLanes); - } - // build connections for bicycles (possibly combined with pedestrians) - availableLanes.clear(); - for (int i = 0; i < (int)myLanes.size(); ++i) { - const SVCPermissions perms = getPermissions(i); - if (perms != SVC_BICYCLE && perms != (SVC_BICYCLE | SVC_PEDESTRIAN)) { - continue; - } - availableLanes.push_back(i); - } - if (availableLanes.size() > 0) { - divideSelectedLanesOnEdges(outgoing, availableLanes); - } - // clean up unassigned fromLanes - for (std::vector::iterator i = myConnections.begin(); i != myConnections.end();) { - if ((*i).fromLane == -1) { - i = myConnections.erase(i); - } else { - ++i; - } - } - sortOutgoingConnectionsByIndex(); -} - - -void -NBEdge::divideSelectedLanesOnEdges(const EdgeVector* outgoing, const std::vector& availableLanes) { - const std::vector& priorities = prepareEdgePriorities(outgoing, availableLanes); - if (priorities.empty()) { - return; - } -#ifdef DEBUG_CONNECTION_GUESSING - if (DEBUGCOND) { - std::cout << "divideSelectedLanesOnEdges " << getID() << " out=" << toString(*outgoing) << " prios=" << toString(priorities) << " avail=" << toString(availableLanes) << "\n"; - } -#endif - // compute the resulting number of lanes that should be used to reach the following edge - const int numOutgoing = (int)outgoing->size(); - std::vector resultingLanesFactor; - resultingLanesFactor.reserve(numOutgoing); - int minResulting = std::numeric_limits::max(); - for (int i = 0; i < numOutgoing; i++) { - // res / minResulting will be the number of lanes which are meant to reach the current outgoing edge - const int res = priorities[i] * (int)availableLanes.size(); - resultingLanesFactor.push_back(res); - if (minResulting > res && res > 0) { - // prevent minResulting from becoming 0 - minResulting = res; - } - } - // compute the number of virtual edges - // a virtual edge is used as a replacement for a real edge from now on - // it shall allow to divide the existing lanes on this structure without - // regarding the structure of outgoing edges - int numVirtual = 0; - // compute the transition from virtual to real edges - EdgeVector transition; - transition.reserve(numOutgoing); - for (int i = 0; i < numOutgoing; i++) { - // tmpNum will be the number of connections from this edge to the next edge - assert(i < (int)resultingLanesFactor.size()); - const int tmpNum = (resultingLanesFactor[i] + minResulting - 1) / minResulting; // integer division rounding up - numVirtual += tmpNum; - for (int j = 0; j < tmpNum; j++) { - transition.push_back((*outgoing)[i]); - } - } -#ifdef DEBUG_CONNECTION_GUESSING - if (DEBUGCOND) { - std::cout << " minResulting=" << minResulting << " numVirtual=" << numVirtual << " availLanes=" << toString(availableLanes) << " resLanes=" << toString(resultingLanesFactor) << " transition=" << toString(transition) << "\n"; - } -#endif - - // assign lanes to edges - // (conversion from virtual to real edges is done) - ToEdgeConnectionsAdder adder(transition); - Bresenham::compute(&adder, static_cast(availableLanes.size()), numVirtual); - const std::map >& l2eConns = adder.getBuiltConnections(); - for (NBEdge* const target : *outgoing) { - assert(l2eConns.find(target) != l2eConns.end()); - for (const int j : l2eConns.find(target)->second) { - const int fromIndex = availableLanes[j]; - if ((getPermissions(fromIndex) & target->getPermissions()) == 0) { - // exclude connection if fromLane and toEdge have no common permissions - continue; - } - if ((getPermissions(fromIndex) & target->getPermissions()) == SVC_PEDESTRIAN) { - // exclude connection if the only commonly permitted class are pedestrians - // these connections are later built in NBNode::buildWalkingAreas - continue; - } - // avoid building more connections than the edge has viable lanes (earlier - // ones have precedence). This is necessary when running divideSelectedLanesOnEdges more than once. - // @todo To decide which target lanes are still available we need to do a - // preliminary lane-to-lane assignment in regard to permissions (rather than to ordering) - const int numConsToTarget = (int)count_if(myConnections.begin(), myConnections.end(), connections_toedge_finder(target, true)); - int targetLanes = target->getNumLanes(); - if (target->getPermissions(0) == SVC_PEDESTRIAN) { - --targetLanes; - } - if (numConsToTarget >= targetLanes) { - // let bicycles move onto the road to allow continuation - // the speed limit is taken from rural roads (which allow cycles) - // (pending implementation of #1859) - if (getPermissions(fromIndex) == SVC_BICYCLE && getSpeed() <= (101 / 3.6)) { - for (NBEdge::Lane& lane : myLanes) { - if (lane.permissions != SVC_PEDESTRIAN) { - lane.permissions |= SVC_BICYCLE; - } - } - } - continue; - } - if (myLanes[fromIndex].connectionsDone) { - // we already have complete information about connections from - // this lane. do not add anything else -#ifdef DEBUG_CONNECTION_GUESSING - if (DEBUGCOND) { - std::cout << " connectionsDone from " << getID() << "_" << fromIndex << ": "; - for (const Connection& c : getConnectionsFromLane(fromIndex)) { - std::cout << c.getDescription(this) << ", "; - } - std::cout << "\n"; - } -#endif - continue; - } - myConnections.push_back(Connection(fromIndex, target, -1)); -#ifdef DEBUG_CONNECTION_GUESSING - if (DEBUGCOND) { - std::cout << " request connection from " << getID() << "_" << fromIndex << " to " << target->getID() << "\n"; - } -#endif - } - } - - addStraightConnections(outgoing, availableLanes, priorities); -} - - -void -NBEdge::addStraightConnections(const EdgeVector* outgoing, const std::vector& availableLanes, const std::vector& priorities) { - // ensure sufficient straight connections for the (highest-priority) straight target - const int numOutgoing = (int) outgoing->size(); - NBEdge* target = nullptr; - NBEdge* rightOfTarget = nullptr; - NBEdge* leftOfTarget = nullptr; - int maxPrio = 0; - for (int i = 0; i < numOutgoing; i++) { - if (maxPrio < priorities[i]) { - const LinkDirection dir = myTo->getDirection(this, (*outgoing)[i]); - if (dir == LinkDirection::STRAIGHT) { - maxPrio = priorities[i]; - target = (*outgoing)[i]; - rightOfTarget = i == 0 ? outgoing->back() : (*outgoing)[i - 1]; - leftOfTarget = i + 1 == numOutgoing ? outgoing->front() : (*outgoing)[i + 1]; - } - } - } - if (target == nullptr) { - return; - } - int numConsToTarget = (int)count_if(myConnections.begin(), myConnections.end(), connections_toedge_finder(target, true)); - int targetLanes = (int)target->getNumLanes(); - if (target->getPermissions(0) == SVC_PEDESTRIAN) { - --targetLanes; - } - const int numDesiredConsToTarget = MIN2(targetLanes, (int)availableLanes.size()); -#ifdef DEBUG_CONNECTION_GUESSING - if (DEBUGCOND) { - std::cout << " checking extra lanes for target=" << target->getID() << " cons=" << numConsToTarget << " desired=" << numDesiredConsToTarget << "\n"; - } -#endif - std::vector::const_iterator it_avail = availableLanes.begin(); - while (numConsToTarget < numDesiredConsToTarget && it_avail != availableLanes.end()) { - const int fromIndex = *it_avail; - if ( - // not yet connected - (count_if(myConnections.begin(), myConnections.end(), connections_finder(fromIndex, target, -1)) == 0) - // matching permissions - && ((getPermissions(fromIndex) & target->getPermissions()) != 0) - // more than pedestrians - && ((getPermissions(fromIndex) & target->getPermissions()) != SVC_PEDESTRIAN) - // lane not yet fully defined - && !myLanes[fromIndex].connectionsDone - ) { -#ifdef DEBUG_CONNECTION_GUESSING - if (DEBUGCOND) { - std::cout << " candidate from " << getID() << "_" << fromIndex << " to " << target->getID() << "\n"; - } -#endif - // prevent same-edge conflicts - if ( - // no outgoing connections to the right from further left - ((it_avail + 1) == availableLanes.end() || count_if(myConnections.begin(), myConnections.end(), connections_conflict_finder(fromIndex, rightOfTarget, false)) == 0) - // no outgoing connections to the left from further right - && (it_avail == availableLanes.begin() || count_if(myConnections.begin(), myConnections.end(), connections_conflict_finder(fromIndex, leftOfTarget, true)) == 0)) { -#ifdef DEBUG_CONNECTION_GUESSING - if (DEBUGCOND) { - std::cout << " request additional connection from " << getID() << "_" << fromIndex << " to " << target->getID() << "\n"; - } -#endif - myConnections.push_back(Connection(fromIndex, target, -1)); - numConsToTarget++; - } else { -#ifdef DEBUG_CONNECTION_GUESSING - if (DEBUGCOND) std::cout - << " fail check1=" - << ((it_avail + 1) == availableLanes.end() || count_if(myConnections.begin(), myConnections.end(), connections_conflict_finder(fromIndex, rightOfTarget, false)) == 0) - << " check2=" << (it_avail == availableLanes.begin() || count_if(myConnections.begin(), myConnections.end(), connections_conflict_finder(fromIndex, leftOfTarget, true)) == 0) - << " rightOfTarget=" << rightOfTarget->getID() - << " leftOfTarget=" << leftOfTarget->getID() - << "\n"; -#endif - - } - } - ++it_avail; - } -} - - -const std::vector -NBEdge::prepareEdgePriorities(const EdgeVector* outgoing, const std::vector& availableLanes) { - std::vector priorities; - MainDirections mainDirections(*outgoing, this, myTo, availableLanes); - const int dist = mainDirections.getStraightest(); - if (dist == -1) { - return priorities; - } - // copy the priorities first - priorities.reserve(outgoing->size()); - for (const NBEdge* const out : *outgoing) { - int prio = NBNode::isTrafficLight(myTo->getType()) ? 0 : out->getJunctionPriority(myTo); - assert((prio + 1) * 2 > 0); - prio = (prio + 1) * 2; - priorities.push_back(prio); - } - // when the right turning direction has not a higher priority, divide - // the importance by 2 due to the possibility to leave the junction - // faster from this lane -#ifdef DEBUG_CONNECTION_GUESSING - if (DEBUGCOND) std::cout << " prepareEdgePriorities " << getID() - << " outgoing=" << toString(*outgoing) - << " priorities1=" << toString(priorities) - << " dist=" << dist - << "\n"; -#endif - if (dist != 0 && !mainDirections.includes(MainDirections::Direction::RIGHTMOST)) { - assert(priorities.size() > 0); - priorities[0] /= 2; -#ifdef DEBUG_CONNECTION_GUESSING - if (DEBUGCOND) { - std::cout << " priorities2=" << toString(priorities) << "\n"; - } -#endif - } - // HEURISTIC: - // when no higher priority exists, let the forward direction be - // the main direction - if (mainDirections.empty()) { - assert(dist < (int)priorities.size()); - priorities[dist] *= 2; -#ifdef DEBUG_CONNECTION_GUESSING - if (DEBUGCOND) { - std::cout << " priorities3=" << toString(priorities) << "\n"; - } -#endif - } - if (NBNode::isTrafficLight(myTo->getType())) { - priorities[dist] += 1; - } else { - // try to ensure separation of left turns - if (mainDirections.includes(MainDirections::Direction::RIGHTMOST) && mainDirections.includes(MainDirections::Direction::LEFTMOST)) { - priorities[0] /= 4; - priorities[(int)priorities.size() - 1] /= 2; -#ifdef DEBUG_CONNECTION_GUESSING - if (DEBUGCOND) { - std::cout << " priorities6=" << toString(priorities) << "\n"; - } -#endif - } - } - if (mainDirections.includes(MainDirections::Direction::FORWARD)) { - if (myLanes.size() > 2) { - priorities[dist] *= 2; -#ifdef DEBUG_CONNECTION_GUESSING - if (DEBUGCOND) { - std::cout << " priorities4=" << toString(priorities) << "\n"; - } -#endif - } else { - priorities[dist] *= 3; -#ifdef DEBUG_CONNECTION_GUESSING - if (DEBUGCOND) { - std::cout << " priorities5=" << toString(priorities) << "\n"; - } -#endif - } - } - return priorities; -} - - -void -NBEdge::appendTurnaround(bool noTLSControlled, bool noFringe, bool onlyDeadends, bool onlyTurnlane, bool noGeometryLike, bool checkPermissions) { - // do nothing if no turnaround is known - if (myTurnDestination == nullptr || myTo->getType() == SumoXMLNodeType::RAIL_CROSSING) { - return; - } - // do nothing if the destination node is controlled by a tls and no turnarounds - // shall be appended for such junctions - if (noTLSControlled && myTo->isTLControlled()) { - return; - } - if (noFringe && myTo->getFringeType() == FringeType::OUTER) { - return; - } - bool isDeadEnd = true; - for (const Connection& c : myConnections) { - if ((c.toEdge->getPermissions(c.toLane) - & getPermissions(c.fromLane) - & SVC_PASSENGER) != 0 - || (c.toEdge->getPermissions() & getPermissions()) == getPermissions()) { - isDeadEnd = false; - break; - } - } - if (onlyDeadends && !isDeadEnd) { - return; - } - const int fromLane = (int)myLanes.size() - 1; - if (onlyTurnlane) { - for (const Connection& c : getConnectionsFromLane(fromLane)) { - LinkDirection dir = myTo->getDirection(this, c.toEdge); - if (dir != LinkDirection::LEFT && dir != LinkDirection::PARTLEFT) { - return; - } - } - } - const int toLane = (int)myTurnDestination->getNumLanes() - 1; - if (checkPermissions) { - if ((getPermissions(fromLane) & myTurnDestination->getPermissions(toLane)) == 0) { - // exclude connection if fromLane and toEdge have no common permissions - return; - } - if ((getPermissions(fromLane) & myTurnDestination->getPermissions(toLane)) == SVC_PEDESTRIAN) { - // exclude connection if the only commonly permitted class are pedestrians - // these connections are later built in NBNode::buildWalkingAreas - return; - } - } - // avoid railway turn-arounds - if (isRailway(getPermissions()) && isRailway(myTurnDestination->getPermissions()) - && fabs(NBHelpers::normRelAngle(getAngleAtNode(myTo), myTurnDestination->getAngleAtNode(myTo))) > 90) { - // except at dead-ends on bidi-edges where they model a reversal in train direction - // @todo #4382: once the network fringe is tagged, it also should not receive turn-arounds) - if (isBidiRail() && isRailDeadEnd()) { - // add a slow connection because direction-reversal implies stopping - setConnection(fromLane, myTurnDestination, toLane, Lane2LaneInfoType::VALIDATED, false, false, true, UNSPECIFIED_CONTPOS, UNSPECIFIED_VISIBILITY_DISTANCE, SUMO_const_haltingSpeed); - return; - } else { - return; - } - }; - if (noGeometryLike && myTo->geometryLike() && !isDeadEnd) { - // make sure the turnDestination has other incoming edges - EdgeVector turnIncoming = myTurnDestination->getIncomingEdges(); - if (turnIncoming.size() > 1) { - // this edge is always part of incoming - return; - } - } - setConnection(fromLane, myTurnDestination, toLane, Lane2LaneInfoType::VALIDATED); -} - - -bool -NBEdge::isTurningDirectionAt(const NBEdge* const edge) const { - // maybe it was already set as the turning direction - if (edge == myTurnDestination) { - return true; - } else if (myTurnDestination != nullptr) { - // otherwise - it's not if a turning direction exists - return false; - } - return edge == myPossibleTurnDestination; -} - - -NBNode* -NBEdge::tryGetNodeAtPosition(double pos, double tolerance) const { - // return the from-node when the position is at the begin of the edge - if (pos < tolerance) { - return myFrom; - } - // return the to-node when the position is at the end of the edge - if (pos > myLength - tolerance) { - return myTo; - } - return nullptr; -} - - -void -NBEdge::moveOutgoingConnectionsFrom(NBEdge* e, int laneOff) { - int lanes = e->getNumLanes(); - for (int i = 0; i < lanes; i++) { - std::vector elv = e->getConnectionsFromLane(i); - for (std::vector::iterator j = elv.begin(); j != elv.end(); j++) { - NBEdge::Connection el = *j; - assert(el.tlID == ""); - addLane2LaneConnection(i + laneOff, el.toEdge, el.toLane, Lane2LaneInfoType::COMPUTED); - } - } -} - - -bool -NBEdge::lanesWereAssigned() const { - return myStep == EdgeBuildingStep::LANES2LANES_DONE || myStep == EdgeBuildingStep::LANES2LANES_USER; -} - - -double -NBEdge::getMaxLaneOffset() { - return (double) SUMO_const_laneWidthAndOffset * myLanes.size(); -} - - -bool -NBEdge::mayBeTLSControlled(int fromLane, NBEdge* toEdge, int toLane) const { - for (const Connection& c : myConnections) { - if (c.fromLane == fromLane && c.toEdge == toEdge && c.toLane == toLane && c.uncontrolled) { - return false; - } - } - return true; -} - - -bool -NBEdge::setControllingTLInformation(const NBConnection& c, const std::string& tlID) { - const int fromLane = c.getFromLane(); - NBEdge* toEdge = c.getTo(); - const int toLane = c.getToLane(); - const int tlIndex = c.getTLIndex(); - const int tlIndex2 = c.getTLIndex2(); - // check whether the connection was not set as not to be controled previously - if (!mayBeTLSControlled(fromLane, toEdge, toLane)) { - return false; - } - - assert(fromLane < 0 || fromLane < (int) myLanes.size()); - // try to use information about the connections if given - if (fromLane >= 0 && toLane >= 0) { - // find the specified connection - std::vector::iterator i = - find_if(myConnections.begin(), myConnections.end(), connections_finder(fromLane, toEdge, toLane)); - // ok, we have to test this as on the removal of self-loop edges some connections - // will be reassigned - if (i != myConnections.end()) { - // get the connection - Connection& connection = *i; - // set the information about the tl - connection.tlID = tlID; - connection.tlLinkIndex = tlIndex; - connection.tlLinkIndex2 = tlIndex2; - return true; - } - } - // if the original connection was not found, set the information for all - // connections - int no = 0; - bool hadError = false; - for (std::vector::iterator i = myConnections.begin(); i != myConnections.end(); ++i) { - if ((*i).toEdge != toEdge) { - continue; - } - if (fromLane >= 0 && fromLane != (*i).fromLane) { - continue; - } - if (toLane >= 0 && toLane != (*i).toLane) { - continue; - } - if ((*i).tlID == "") { - (*i).tlID = tlID; - (*i).tlLinkIndex = tlIndex; - (*i).tlLinkIndex2 = tlIndex2; - no++; - } else { - if ((*i).tlID != tlID && (*i).tlLinkIndex == tlIndex) { - WRITE_WARNINGF("The lane '%' on edge '%' already had a traffic light signal.", i->fromLane, getID()); - hadError = true; - } - } - } - if (hadError && no == 0) { - WRITE_WARNINGF("Could not set any signal of the tlLogic '%' (unknown group).", tlID); - } - return true; -} - - -void -NBEdge::clearControllingTLInformation() { - for (std::vector::iterator it = myConnections.begin(); it != myConnections.end(); it++) { - it->tlID = ""; - } -} - - -PositionVector -NBEdge::getCWBoundaryLine(const NBNode& n) const { - PositionVector ret; - double width; - int lane; - if (myFrom == (&n)) { - // outgoing - lane = getFirstAllowedLaneIndex(NBNode::FORWARD); - ret = myLanes[lane].shape; - } else { - // incoming - lane = getFirstAllowedLaneIndex(NBNode::BACKWARD); - ret = myLanes[lane].shape.reverse(); - } - width = getLaneWidth(lane); - ret.move2side(width * 0.5); - return ret; -} - - -PositionVector -NBEdge::getCCWBoundaryLine(const NBNode& n) const { - PositionVector ret; - double width; - int lane; - if (myFrom == (&n)) { - // outgoing - lane = getFirstAllowedLaneIndex(NBNode::BACKWARD); - ret = myLanes[lane].shape; - } else { - // incoming - lane = getFirstAllowedLaneIndex(NBNode::FORWARD); - ret = myLanes[lane].shape.reverse(); - } - width = getLaneWidth(lane); - ret.move2side(-width * 0.5); - return ret; -} - - -bool -NBEdge::expandableBy(NBEdge* possContinuation, std::string& reason) const { - // ok, the number of lanes must match - if (myLanes.size() != possContinuation->myLanes.size()) { - reason = "laneNumber"; - return false; - } - // do not create self loops - if (myFrom == possContinuation->myTo) { - reason = "loop"; - return false; - } - // conserve bidi-rails - if (isBidiRail() != possContinuation->isBidiRail()) { - reason = "bidi-rail"; - return false; - } - // also, check whether the connections - if any exit do allow to join - // both edges - // This edge must have a one-to-one connection to the following lanes - switch (myStep) { - case EdgeBuildingStep::INIT_REJECT_CONNECTIONS: - break; - case EdgeBuildingStep::INIT: - break; - case EdgeBuildingStep::EDGE2EDGES: { - // the following edge must be connected - const EdgeVector& conn = getConnectedEdges(); - if (find(conn.begin(), conn.end(), possContinuation) == conn.end()) { - reason = "disconnected"; - return false; - } - } - break; - case EdgeBuildingStep::LANES2EDGES: - case EdgeBuildingStep::LANES2LANES_RECHECK: - case EdgeBuildingStep::LANES2LANES_DONE: - case EdgeBuildingStep::LANES2LANES_USER: { - // the possible continuation must be connected - if (find_if(myConnections.begin(), myConnections.end(), connections_toedge_finder(possContinuation)) == myConnections.end()) { - reason = "disconnected"; - return false; - } - // all lanes must go to the possible continuation - std::vector conns = getConnectionLanes(possContinuation); - const int offset = MAX2(0, getFirstNonPedestrianLaneIndex(NBNode::FORWARD, true)); - if (conns.size() < myLanes.size() - offset) { - reason = "some lanes disconnected"; - return false; - } - } - break; - default: - break; - } - const double minLength = OptionsCont::getOptions().getFloat("geometry.remove.min-length"); - if (minLength > 0 && (possContinuation->getLoadedLength() < minLength || getLoadedLength() < minLength)) { - return true; - } - // the priority, too (?) - if (getPriority() != possContinuation->getPriority()) { - reason = "priority"; - return false; - } - // the speed allowed - if (mySpeed != possContinuation->mySpeed) { - reason = "speed"; - return false; - } - // spreadtype should match or it will look ugly - if (myLaneSpreadFunction != possContinuation->myLaneSpreadFunction) { - reason = "spreadType"; - return false; - } - // matching lanes must have identical properties - for (int i = 0; i < (int)myLanes.size(); i++) { - if (myLanes[i].speed != possContinuation->myLanes[i].speed) { - reason = "lane " + toString(i) + " speed"; - return false; - } else if (myLanes[i].permissions != possContinuation->myLanes[i].permissions) { - reason = "lane " + toString(i) + " permissions"; - return false; - } else if (myLanes[i].width != possContinuation->myLanes[i].width && - fabs(myLanes[i].width - possContinuation->myLanes[i].width) > OptionsCont::getOptions().getFloat("geometry.remove.width-tolerance")) { - reason = "lane " + toString(i) + " width"; - return false; - } - } - - return true; -} - - -void -NBEdge::append(NBEdge* e) { - // append geometry - myGeom.append(e->myGeom); - for (int i = 0; i < (int)myLanes.size(); i++) { - myLanes[i].customShape.append(e->myLanes[i].customShape); - if (myLanes[i].knowsParameter(SUMO_PARAM_ORIGID) || e->myLanes[i].knowsParameter(SUMO_PARAM_ORIGID) - || OptionsCont::getOptions().getBool("output.original-names")) { - const std::string origID = myLanes[i].getParameter(SUMO_PARAM_ORIGID, getID()); - const std::string origID2 = e->myLanes[i].getParameter(SUMO_PARAM_ORIGID, e->getID()); - if (origID != origID2) { - myLanes[i].setParameter(SUMO_PARAM_ORIGID, origID + " " + origID2); - } - } - myLanes[i].connectionsDone = e->myLanes[i].connectionsDone; - } - if (e->getLength() > myLength) { - // possibly some lane attributes differ (when using option geometry.remove.min-length) - // make sure to use the attributes from the longer edge - for (int i = 0; i < (int)myLanes.size(); i++) { - myLanes[i].width = e->myLanes[i].width; - } - } - // recompute length - myLength += e->myLength; - if (myLoadedLength > 0 || e->myLoadedLength > 0) { - myLoadedLength = getFinalLength() + e->getFinalLength(); - } - // copy the connections and the building step if given - myStep = e->myStep; - myConnections = e->myConnections; - myTurnDestination = e->myTurnDestination; - myPossibleTurnDestination = e->myPossibleTurnDestination; - myConnectionsToDelete = e->myConnectionsToDelete; - // set the node - myTo = e->myTo; - myToBorder = e->myToBorder; - if (e->knowsParameter("origTo")) { - setParameter("origTo", e->getParameter("origTo")); - } - if (e->mySignalPosition != Position::INVALID) { - mySignalPosition = e->mySignalPosition; - } - computeAngle(); // myEndAngle may be different now -} - - -bool -NBEdge::hasSignalisedConnectionTo(const NBEdge* const e) const { - for (std::vector::const_iterator i = myConnections.begin(); i != myConnections.end(); ++i) { - if ((*i).toEdge == e && (*i).tlID != "") { - return true; - } - } - return false; -} - - -NBEdge* -NBEdge::getTurnDestination(bool possibleDestination) const { - if (myTurnDestination == nullptr && possibleDestination) { - return myPossibleTurnDestination; - } - return myTurnDestination; -} - - -std::string -NBEdge::getLaneID(int lane) const { - return myID + "_" + toString(lane); -} - - -bool -NBEdge::isNearEnough2BeJoined2(NBEdge* e, double threshold) const { - std::vector distances = myGeom.distances(e->getGeometry()); - assert(distances.size() > 0); - return VectorHelper::maxValue(distances) < threshold; -} - - -void -NBEdge::addLane(int index, bool recomputeShape, bool recomputeConnections, bool shiftIndices) { - assert(index <= (int)myLanes.size()); - myLanes.insert(myLanes.begin() + index, Lane(this, "")); - // copy attributes - if (myLanes.size() > 1) { - int templateIndex = index > 0 ? index - 1 : index + 1; - myLanes[index].speed = myLanes[templateIndex].speed; - myLanes[index].permissions = myLanes[templateIndex].permissions; - myLanes[index].preferred = myLanes[templateIndex].preferred; - myLanes[index].endOffset = myLanes[templateIndex].endOffset; - myLanes[index].width = myLanes[templateIndex].width; - myLanes[index].updateParameters(myLanes[templateIndex].getParametersMap()); - } - const EdgeVector& incs = myFrom->getIncomingEdges(); - if (recomputeShape) { - computeLaneShapes(); - } - if (recomputeConnections) { - for (EdgeVector::const_iterator i = incs.begin(); i != incs.end(); ++i) { - (*i)->invalidateConnections(true); - } - invalidateConnections(true); - } else if (shiftIndices) { - // shift outgoing connections above the added lane to the left - for (Connection& c : myConnections) { - if (c.fromLane >= index) { - c.fromLane += 1; - } - } - // shift incoming connections above the added lane to the left - for (NBEdge* inc : myFrom->getIncomingEdges()) { - for (Connection& c : inc->myConnections) { - if (c.toEdge == this && c.toLane >= index) { - c.toLane += 1; - } - } - } - myFrom->shiftTLConnectionLaneIndex(this, +1, index - 1); - myTo->shiftTLConnectionLaneIndex(this, +1, index - 1); - } -} - -void -NBEdge::incLaneNo(int by) { - int newLaneNo = (int)myLanes.size() + by; - while ((int)myLanes.size() < newLaneNo) { - // recompute shapes on last addition - const bool recompute = ((int)myLanes.size() == newLaneNo - 1) && myStep < EdgeBuildingStep::LANES2LANES_USER; - addLane((int)myLanes.size(), recompute, recompute, false); - } -} - - -void -NBEdge::deleteLane(int index, bool recompute, bool shiftIndices) { - assert(index < (int)myLanes.size()); - myLanes.erase(myLanes.begin() + index); - if (recompute) { - computeLaneShapes(); - const EdgeVector& incs = myFrom->getIncomingEdges(); - for (EdgeVector::const_iterator i = incs.begin(); i != incs.end(); ++i) { - (*i)->invalidateConnections(true); - } - invalidateConnections(true); - } else if (shiftIndices) { - removeFromConnections(nullptr, index, -1, false, true); - for (NBEdge* inc : myFrom->getIncomingEdges()) { - inc->removeFromConnections(this, -1, index, false, true); - } - } -} - - -void -NBEdge::decLaneNo(int by) { - int newLaneNo = (int) myLanes.size() - by; - assert(newLaneNo > 0); - while ((int)myLanes.size() > newLaneNo) { - // recompute shapes on last removal - const bool recompute = (int)myLanes.size() == newLaneNo + 1 && myStep < EdgeBuildingStep::LANES2LANES_USER; - deleteLane((int)myLanes.size() - 1, recompute, false); - } -} - - -void -NBEdge::markAsInLane2LaneState() { - assert(myTo->getOutgoingEdges().size() == 0); - myStep = EdgeBuildingStep::LANES2LANES_DONE; -} - - -void -NBEdge::allowVehicleClass(int lane, SUMOVehicleClass vclass) { - if (lane < 0) { // all lanes are meant... - for (int i = 0; i < (int)myLanes.size(); i++) { - allowVehicleClass(i, vclass); - } - } else { - assert(lane < (int)myLanes.size()); - myLanes[lane].permissions |= vclass; - } -} - - -void -NBEdge::disallowVehicleClass(int lane, SUMOVehicleClass vclass) { - if (lane < 0) { // all lanes are meant... - for (int i = 0; i < (int)myLanes.size(); i++) { - disallowVehicleClass((int) i, vclass); - } - } else { - assert(lane < (int)myLanes.size()); - myLanes[lane].permissions &= ~vclass; - } -} - - -void -NBEdge::preferVehicleClass(int lane, SUMOVehicleClass vclass) { - if (lane < 0) { // all lanes are meant... - for (int i = 0; i < (int)myLanes.size(); i++) { - allowVehicleClass(i, vclass); - } - } else { - assert(lane < (int)myLanes.size()); - myLanes[lane].preferred |= vclass; - } -} - - -void -NBEdge::setLaneWidth(int lane, double width) { - if (lane < 0) { - // all lanes are meant... - myLaneWidth = width; - for (int i = 0; i < (int)myLanes.size(); i++) { - // ... do it for each lane - setLaneWidth(i, width); - } - return; - } - assert(lane < (int)myLanes.size()); - myLanes[lane].width = width; -} - -void -NBEdge::setLaneType(int lane, const std::string& type) { - if (lane < 0) { - for (int i = 0; i < (int)myLanes.size(); i++) { - // ... do it for each lane - setLaneType(i, type); - } - return; - } - assert(lane < (int)myLanes.size()); - myLanes[lane].type = type; -} - - -double -NBEdge::getLaneWidth(int lane) const { - return myLanes[lane].width != UNSPECIFIED_WIDTH - ? myLanes[lane].width - : getLaneWidth() != UNSPECIFIED_WIDTH ? getLaneWidth() : SUMO_const_laneWidth; -} - - -double -NBEdge::getTotalWidth() const { - double result = 0; - for (int i = 0; i < (int)myLanes.size(); i++) { - result += getLaneWidth(i); - } - return result; -} - -double -NBEdge::getEndOffset(int lane) const { - return myLanes[lane].endOffset != UNSPECIFIED_OFFSET ? myLanes[lane].endOffset : getEndOffset(); -} - - -const std::map& -NBEdge::getStopOffsets(int lane) const { - if (lane == -1) { - return myStopOffsets; - } else { - return myLanes[lane].stopOffsets; - } -} - -void -NBEdge::setEndOffset(int lane, double offset) { - if (lane < 0) { - // all lanes are meant... - myEndOffset = offset; - for (int i = 0; i < (int)myLanes.size(); i++) { - // ... do it for each lane - setEndOffset(i, offset); - } - return; - } - assert(lane < (int)myLanes.size()); - myLanes[lane].endOffset = offset; -} - - -bool -NBEdge::setStopOffsets(int lane, std::map offsets, bool overwrite) { - if (lane < 0) { - if (!overwrite && myStopOffsets.size() != 0) { - return false; - } - // all lanes are meant... - if (offsets.size() != 0 && 0 > offsets.begin()->second) { - // Edge length unknown at parsing time, thus check here. - WRITE_WARNINGF("Ignoring invalid stopOffset for edge '%' (negative offset).", getID()); - return false; - } else { - myStopOffsets = offsets; - } - } else { - assert(lane < (int)myLanes.size()); - if (myLanes[lane].stopOffsets.size() == 0 || overwrite) { - if (offsets.size() != 0 && 0 > offsets.begin()->second) { - // Edge length unknown at parsing time, thus check here. - WRITE_WARNINGF("Ignoring invalid stopOffset for lane '%' (negative offset).", getLaneID(lane)); - } else { - myLanes[lane].stopOffsets = offsets; - } - } - } - return true; -} - - -void -NBEdge::setSpeed(int lane, double speed) { - if (lane < 0) { - // all lanes are meant... - mySpeed = speed; - for (int i = 0; i < (int)myLanes.size(); i++) { - // ... do it for each lane - setSpeed(i, speed); - } - return; - } - assert(lane < (int)myLanes.size()); - myLanes[lane].speed = speed; -} - -void -NBEdge::setAcceleration(int lane, bool accelRamp) { - assert(lane >= 0); - assert(lane < (int)myLanes.size()); - myLanes[lane].accelRamp = accelRamp; -} - -void -NBEdge::setLaneShape(int lane, const PositionVector& shape) { - assert(lane >= 0); - assert(lane < (int)myLanes.size()); - myLanes[lane].customShape = shape; -} - - -void -NBEdge::setPermissions(SVCPermissions permissions, int lane) { - if (lane < 0) { - for (int i = 0; i < (int)myLanes.size(); i++) { - // ... do it for each lane - setPermissions(permissions, i); - } - } else { - assert(lane < (int)myLanes.size()); - myLanes[lane].permissions = permissions; - } -} - - -void -NBEdge::setPreferredVehicleClass(SVCPermissions permissions, int lane) { - if (lane < 0) { - for (int i = 0; i < (int)myLanes.size(); i++) { - // ... do it for each lane - setPreferredVehicleClass(permissions, i); - } - } else { - assert(lane < (int)myLanes.size()); - myLanes[lane].preferred = permissions; - } -} - - -SVCPermissions -NBEdge::getPermissions(int lane) const { - if (lane < 0) { - SVCPermissions result = 0; - for (int i = 0; i < (int)myLanes.size(); i++) { - result |= getPermissions(i); - } - return result; - } else { - assert(lane < (int)myLanes.size()); - return myLanes[lane].permissions; - } -} - - -void -NBEdge::setLoadedLength(double val) { - myLoadedLength = val; -} - -void -NBEdge::setAverageLengthWithOpposite(double val) { - myLength = val; -} - - -void -NBEdge::dismissVehicleClassInformation() { - for (std::vector::iterator i = myLanes.begin(); i != myLanes.end(); ++i) { - (*i).permissions = SVCAll; - (*i).preferred = 0; - } -} - - -bool -NBEdge::connections_sorter(const Connection& c1, const Connection& c2) { - if (c1.fromLane != c2.fromLane) { - return c1.fromLane < c2.fromLane; - } - if (c1.toEdge != c2.toEdge) { - return false; // do not change ordering among toEdges as this is determined by angle in an earlier step - } - return c1.toLane < c2.toLane; -} - -double -NBEdge::getSignalOffset() const { - if (mySignalPosition == Position::INVALID) { - return UNSPECIFIED_SIGNAL_OFFSET; - } else { - Position laneEnd = myLaneSpreadFunction == LaneSpreadFunction::RIGHT ? - myLanes.back().shape.back() : myLanes[getNumLanes() / 2].shape.back(); - //std::cout << getID() << " signalPos=" << mySignalPosition << " laneEnd=" << laneEnd << " toShape=" << myTo->getShape() << " toBorder=" << myToBorder << "\n"; - return mySignalPosition.distanceTo2D(laneEnd); - } -} - -int -NBEdge::getFirstNonPedestrianLaneIndex(int direction, bool exclusive) const { - assert(direction == NBNode::FORWARD || direction == NBNode::BACKWARD); - const int start = (direction == NBNode::FORWARD ? 0 : (int)myLanes.size() - 1); - const int end = (direction == NBNode::FORWARD ? (int)myLanes.size() : - 1); - for (int i = start; i != end; i += direction) { - // SVCAll, does not count as a sidewalk, green verges (permissions = 0) do not count as road - // in the exclusive case, lanes that allow pedestrians along with any other class also count as road - if ((exclusive && myLanes[i].permissions != SVC_PEDESTRIAN && myLanes[i].permissions != 0) - || (myLanes[i].permissions == SVCAll || ((myLanes[i].permissions & SVC_PEDESTRIAN) == 0 && myLanes[i].permissions != 0))) { - return i; - } - } - return -1; -} - -int -NBEdge::getSpecialLane(SVCPermissions permissions) const { - for (int i = 0; i < (int)myLanes.size(); i++) { - if (myLanes[i].permissions == permissions) { - return i; - } - } - return -1; -} - -int -NBEdge::getFirstAllowedLaneIndex(int direction) const { - assert(direction == NBNode::FORWARD || direction == NBNode::BACKWARD); - const int start = (direction == NBNode::FORWARD ? 0 : (int)myLanes.size() - 1); - const int end = (direction == NBNode::FORWARD ? (int)myLanes.size() : - 1); - for (int i = start; i != end; i += direction) { - if (myLanes[i].permissions != 0) { - return i; - } - } - return end - direction; -} - - -std::set -NBEdge::getPermissionVariants(int iStart, int iEnd) const { - std::set result; - if (iStart < 0 || iStart >= getNumLanes() || iEnd > getNumLanes()) { - throw ProcessError("invalid indices iStart " + toString(iStart) + " iEnd " + toString(iEnd) + " for edge with " + toString(getNumLanes()) + " lanes."); - } - for (int i = iStart; i < iEnd; ++i) { - result.insert(getPermissions(i)); - } - return result; -} - -int -NBEdge::getNumLanesThatAllow(SVCPermissions permissions) const { - int result = 0; - for (const Lane& lane : myLanes) { - if ((lane.permissions & permissions) == permissions) { - result++; - } - } - return result; -} - -double -NBEdge::getCrossingAngle(NBNode* node) { - double angle = getAngleAtNode(node) + (getFromNode() == node ? 180.0 : 0.0); - if (angle < 0) { - angle += 360.0; - } - if (angle >= 360) { - angle -= 360.0; - } - if (gDebugFlag1) { - std::cout << getID() << " angle=" << getAngleAtNode(node) << " convAngle=" << angle << "\n"; - } - return angle; -} - - -NBEdge::Lane -NBEdge::getFirstNonPedestrianLane(int direction) const { - int index = getFirstNonPedestrianLaneIndex(direction); - if (index < 0) { - throw ProcessError("Edge " + getID() + " allows pedestrians on all lanes"); - } - return myLanes[index]; -} - -std::string -NBEdge::getSidewalkID() { - // see IntermodalEdge::getSidewalk() - for (int i = 0; i < (int)myLanes.size(); i++) { - if (myLanes[i].permissions == SVC_PEDESTRIAN) { - return getLaneID(i); - } - } - for (int i = 0; i < (int)myLanes.size(); i++) { - if ((myLanes[i].permissions & SVC_PEDESTRIAN) != 0) { - return getLaneID(i); - } - } - return getLaneID(0); -} - -void -NBEdge::addSidewalk(double width) { - addRestrictedLane(width, SVC_PEDESTRIAN); -} - - -void -NBEdge::restoreSidewalk(std::vector oldLanes, PositionVector oldGeometry, std::vector oldConnections) { - restoreRestrictedLane(SVC_PEDESTRIAN, oldLanes, oldGeometry, oldConnections); -} - - -void -NBEdge::addBikeLane(double width) { - addRestrictedLane(width, SVC_BICYCLE); -} - - -void -NBEdge::restoreBikelane(std::vector oldLanes, PositionVector oldGeometry, std::vector oldConnections) { - restoreRestrictedLane(SVC_BICYCLE, oldLanes, oldGeometry, oldConnections); -} - -bool -NBEdge::hasRestrictedLane(SUMOVehicleClass vclass) const { - for (const Lane& lane : myLanes) { - if (lane.permissions == vclass) { - return true; - } - } - return false; -} - - -void -NBEdge::addRestrictedLane(double width, SUMOVehicleClass vclass) { - if (hasRestrictedLane(vclass)) { - WRITE_WARNINGF("Edge '%' already has a dedicated lane for %s. Not adding another one.", getID(), toString(vclass)); - return; - } - if (myLaneSpreadFunction == LaneSpreadFunction::CENTER) { - myGeom.move2side(width / 2); - } - // disallow pedestrians on all lanes to ensure that sidewalks are used and - // crossings can be guessed - disallowVehicleClass(-1, vclass); - // add new lane - myLanes.insert(myLanes.begin(), Lane(this, myLanes[0].getParameter(SUMO_PARAM_ORIGID))); - myLanes[0].permissions = vclass; - myLanes[0].width = fabs(width); - // shift outgoing connections to the left - for (std::vector::iterator it = myConnections.begin(); it != myConnections.end(); ++it) { - Connection& c = *it; - if (c.fromLane >= 0) { - c.fromLane += 1; - } - } - // shift incoming connections to the left - const EdgeVector& incoming = myFrom->getIncomingEdges(); - for (EdgeVector::const_iterator it = incoming.begin(); it != incoming.end(); ++it) { - (*it)->shiftToLanesToEdge(this, 1); - } - myFrom->shiftTLConnectionLaneIndex(this, 1); - myTo->shiftTLConnectionLaneIndex(this, 1); - computeLaneShapes(); -} - - -void -NBEdge::restoreRestrictedLane(SUMOVehicleClass vclass, std::vector oldLanes, PositionVector oldGeometry, std::vector oldConnections) { - // check that previously lane was transformed - if (myLanes[0].permissions != vclass) { - WRITE_WARNINGF("Edge '%' doesn't have a dedicated lane for %s. Cannot be restored.", getID(), toString(vclass)); - return; - } - // restore old values - myGeom = oldGeometry; - myLanes = oldLanes; - myConnections = oldConnections; - // shift incoming connections to the right - const EdgeVector& incoming = myFrom->getIncomingEdges(); - for (EdgeVector::const_iterator it = incoming.begin(); it != incoming.end(); ++it) { - (*it)->shiftToLanesToEdge(this, 0); - } - // Shift TL conections - myFrom->shiftTLConnectionLaneIndex(this, 0); - myTo->shiftTLConnectionLaneIndex(this, 0); - computeLaneShapes(); -} - - -void -NBEdge::shiftToLanesToEdge(NBEdge* to, int laneOff) { - /// XXX could we repurpose the function replaceInConnections ? - for (std::vector::iterator it = myConnections.begin(); it != myConnections.end(); ++it) { - if ((*it).toEdge == to && (*it).toLane >= 0) { - (*it).toLane += laneOff; - } - } -} - - -void -NBEdge::shiftPositionAtNode(NBNode* node, NBEdge* other) { - if (myLaneSpreadFunction == LaneSpreadFunction::CENTER && !isRailway(getPermissions())) { - const int i = (node == myTo ? -1 : 0); - const int i2 = (node == myTo ? 0 : -1); - const double dist = myGeom[i].distanceTo2D(node->getPosition()); - const double neededOffset = (getTotalWidth() + getNumLanes() * SUMO_const_laneOffset) / 2; - const double dist2 = MIN2(myGeom.distance2D(other->getGeometry()[i2]), - other->getGeometry().distance2D(myGeom[i])); - const double neededOffset2 = neededOffset + (other->getTotalWidth() + other->getNumLanes() * SUMO_const_laneOffset) / 2; - if (dist < neededOffset && dist2 < neededOffset2) { - PositionVector tmp = myGeom; - // @note this doesn't work well for vissim networks - //tmp.move2side(MIN2(neededOffset - dist, neededOffset2 - dist2)); - try { - tmp.move2side(neededOffset - dist); - myGeom[i] = tmp[i]; - } catch (InvalidArgument&) { - WRITE_WARNINGF("Could not avoid overlapping shape at node '%' for edge '%'.", node->getID(), getID()); - } - } - } -} - - -Position -NBEdge::geometryPositionAtOffset(double offset) const { - if (myLoadedLength > 0) { - return myGeom.positionAtOffset(offset * myLength / myLoadedLength); - } else { - return myGeom.positionAtOffset(offset); - } -} - - -double -NBEdge::getFinalLength() const { - double result = getLoadedLength(); - if (OptionsCont::getOptions().getBool("no-internal-links") && !hasLoadedLength()) { - // use length to junction center even if a modified geometry was given - PositionVector geom = cutAtIntersection(myGeom); - geom.push_back_noDoublePos(getToNode()->getCenter()); - geom.push_front_noDoublePos(getFromNode()->getCenter()); - result = geom.length(); - } - double avgEndOffset = 0; - for (const Lane& lane : myLanes) { - avgEndOffset += lane.endOffset; - } - if (isBidiRail()) { - avgEndOffset += myPossibleTurnDestination->getEndOffset(); - } - avgEndOffset /= myLanes.size(); - return MAX2(result - avgEndOffset, POSITION_EPS); -} - -void -NBEdge::setOrigID(const std::string origID) { - if (origID != "") { - for (int i = 0; i < (int)myLanes.size(); i++) { - myLanes[i].setParameter(SUMO_PARAM_ORIGID, origID); - } - } else { - // do not record empty origID parameter - for (int i = 0; i < (int)myLanes.size(); i++) { - myLanes[i].unsetParameter(SUMO_PARAM_ORIGID); - } - } -} - - -const EdgeVector& -NBEdge::getSuccessors(SUMOVehicleClass vClass) const { - // @todo cache successors instead of recomputing them every time - mySuccessors.clear(); - //std::cout << "getSuccessors edge=" << getID() << " svc=" << toString(vClass) << " cons=" << myConnections.size() << "\n"; - for (const Connection& con : myConnections) { - if (con.fromLane >= 0 && con.toLane >= 0 && con.toEdge != nullptr && - (vClass == SVC_IGNORING || (getPermissions(con.fromLane) - & con.toEdge->getPermissions(con.toLane) & vClass) != 0) - && std::find(mySuccessors.begin(), mySuccessors.end(), con.toEdge) == mySuccessors.end()) { - mySuccessors.push_back(con.toEdge); - //std::cout << " succ=" << con.toEdge->getID() << "\n"; - } - } - return mySuccessors; -} - - -const ConstRouterEdgePairVector& -NBEdge::getViaSuccessors(SUMOVehicleClass vClass) const { - // @todo cache successors instead of recomputing them every time - myViaSuccessors.clear(); - for (const Connection& con : myConnections) { - std::pair pair(con.toEdge, nullptr); - // special case for Persons in Netedit - if (vClass == SVC_PEDESTRIAN) { // - myViaSuccessors.push_back(pair); // - } else if (con.fromLane >= 0 && con.toLane >= 0 && - con.toEdge != nullptr && - (getPermissions(con.fromLane) & con.toEdge->getPermissions(con.toLane) & vClass) != 0) { - // ignore duplicates - if (con.getLength() > 0) { - pair.second = &con; - } - myViaSuccessors.push_back(pair); - } - } - return myViaSuccessors; -} - - -void -NBEdge::debugPrintConnections(bool outgoing, bool incoming) const { - if (outgoing) { - for (const Connection& c : myConnections) { - std::cout << " " << getID() << "_" << c.fromLane << "->" << c.toEdge->getID() << "_" << c.toLane << "\n"; - } - } - if (incoming) { - for (NBEdge* inc : myFrom->getIncomingEdges()) { - for (Connection& c : inc->myConnections) { - if (c.toEdge == this) { - std::cout << " " << inc->getID() << "_" << c.fromLane << "->" << c.toEdge->getID() << "_" << c.toLane << "\n"; - } - } - } - } -} - - -int -NBEdge::getLaneIndexFromLaneID(const std::string laneID) { - return StringUtils::toInt(laneID.substr(laneID.rfind("_") + 1)); -} - -bool -NBEdge::joinLanes(SVCPermissions perms) { - bool haveJoined = false; - int i = 0; - while (i < getNumLanes() - 1) { - if ((getPermissions(i) == perms) && (getPermissions(i + 1) == perms)) { - const double newWidth = getLaneWidth(i) + getLaneWidth(i + 1); - const std::string newType = myLanes[i].type + "|" + myLanes[i + 1].type; - deleteLane(i, false, true); - setLaneWidth(i, newWidth); - setLaneType(i, newType); - haveJoined = true; - } else { - i++; - } - } - return haveJoined; -} - - -EdgeVector -NBEdge::filterByPermissions(const EdgeVector& edges, SVCPermissions permissions) { - EdgeVector result; - for (NBEdge* edge : edges) { - if ((edge->getPermissions() & permissions) != 0) { - result.push_back(edge); - } - } - return result; -} - -NBEdge* -NBEdge::getStraightContinuation(SVCPermissions permissions) const { - EdgeVector cands = filterByPermissions(myTo->getOutgoingEdges(), permissions); - if (cands.size() == 0) { - return nullptr; - } - sort(cands.begin(), cands.end(), NBContHelper::edge_similar_direction_sorter(this)); - NBEdge* best = cands.front(); - if (isTurningDirectionAt(best)) { - return nullptr; - } else { - return best; - } -} - -NBEdge* -NBEdge::getStraightPredecessor(SVCPermissions permissions) const { - EdgeVector cands = filterByPermissions(myFrom->getIncomingEdges(), permissions); - if (cands.size() == 0) { - return nullptr; - } - sort(cands.begin(), cands.end(), NBContHelper::edge_similar_direction_sorter(this, false)); - NBEdge* best = cands.front(); - if (best->isTurningDirectionAt(this)) { - return nullptr; - } else { - return best; - } -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netbuild/NBEdge.h b/Util/OSM2ODR/src/netbuild/NBEdge.h deleted file mode 100644 index 4704eab60..000000000 --- a/Util/OSM2ODR/src/netbuild/NBEdge.h +++ /dev/null @@ -1,1884 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NBEdge.h -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date Tue, 20 Nov 2001 -/// -// The representation of a single edge during network building -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "NBCont.h" -#include "NBHelpers.h" -#include "NBSign.h" - - -// =========================================================================== -// class declarations -// =========================================================================== -class NBNode; -class NBConnection; -class NBNodeCont; -class NBEdgeCont; -class OutputDevice; -class GNELane; -class NBVehicle; - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NBRouterEdge - * @brief Superclass for NBEdge and NBEdge::Connection to initialize Router - */ -class NBRouterEdge { -public: - virtual const std::string& getID() const = 0; - virtual double getSpeed() const = 0; - virtual double getLength() const = 0; - virtual const NBRouterEdge* getBidiEdge() const = 0; - virtual int getNumericalID() const = 0; - virtual const ConstRouterEdgePairVector& getViaSuccessors(SUMOVehicleClass vClass = SVC_IGNORING) const = 0; - virtual bool isInternal() const { - return false; - } - inline bool prohibits(const NBVehicle* const /*veh*/) const { - return false; - } - inline bool restricts(const NBVehicle* const /*veh*/) const { - return false; - } - - - static inline double getTravelTimeStatic(const NBRouterEdge* const edge, const NBVehicle* const /*veh*/, double /*time*/) { - return edge->getLength() / edge->getSpeed(); - } -}; - - -/** - * @class NBEdge - * @brief The representation of a single edge during network building - */ -class NBEdge : public Named, public Parameterised, public NBRouterEdge { - friend class NBEdgeCont; - - /** used for visualization (NETEDIT) */ - friend class GNELane; - friend class GNEEdge; - friend class GNEJunction; - -public: - - /** @enum EdgeBuildingStep - * @brief Current state of the edge within the building process - * - * As the network is build in a cascaded way, considering loaded - * information, a counter holding the current step is needed. This is done - * by using this enumeration. - */ - enum class EdgeBuildingStep { - /// @brief The edge has been loaded and connections shall not be added - INIT_REJECT_CONNECTIONS, - /// @brief The edge has been loaded, nothing is computed yet - INIT, - /// @brief The relationships between edges are computed/loaded - EDGE2EDGES, - /// @brief Lanes to edges - relationships are computed/loaded - LANES2EDGES, - /// @brief Lanes to lanes - relationships are computed; should be recheked - LANES2LANES_RECHECK, - /// @brief Lanes to lanes - relationships are computed; no recheck is necessary/wished - LANES2LANES_DONE, - /// @brief Lanes to lanes - relationships are loaded; no recheck is necessary/wished - LANES2LANES_USER - }; - - - /** @enum Lane2LaneInfoType - * @brief Modes of setting connections between lanes - */ - enum class Lane2LaneInfoType { - /// @brief The connection was computed - COMPUTED, - /// @brief The connection was given by the user - USER, - /// @brief The connection was computed and validated - VALIDATED - }; - - - /** @struct Lane - * @brief An (internal) definition of a single lane of an edge - */ - struct Lane final : public Parameterised { - /// @brief constructor - Lane(NBEdge* e, const std::string& _origID); - - /// @brief The lane's shape - PositionVector shape; - - /// @brief The speed allowed on this lane - double speed; - - /// @brief List of vehicle types that are allowed on this lane - SVCPermissions permissions; - - /// @brief List of vehicle types that are preferred on this lane - SVCPermissions preferred; - - /// @brief This lane's offset to the intersection begin - double endOffset; - - /// @brief stopOffsets.second - The stop offset for vehicles stopping at the lane's end. - /// Applies if vClass is in in stopOffset.first bitset - std::map stopOffsets; - - /// @brief This lane's width - double width; - - /// @brief An opposite lane ID, if given - std::string oppositeID; - - /// @brief Whether this lane is an acceleration lane - bool accelRamp; - - /// @brief Whether connection information for this lane is already completed - // @note (see NIImporter_DlrNavteq::ConnectedLanesHandler) - bool connectionsDone; - - /// @brief A custom shape for this lane set by the user - PositionVector customShape; - - /// @brief the type of this lane - std::string type; - }; - - - /** @struct Connection - * @brief A structure which describes a connection between edges or lanes - */ - struct Connection final : public Parameterised, public NBRouterEdge { - /** @brief Constructor - * @param[in] fromLane_ The lane the connections starts at - * @param[in] toEdge_ The edge the connections yields in - * @param[in] toLane_ The lane the connections yields in - */ - Connection(int fromLane_, NBEdge* toEdge_, int toLane_); - - /// @brief constructor with more parameters - Connection(int fromLane_, NBEdge* toEdge_, int toLane_, bool mayDefinitelyPass_, - bool keepClear_ = true, - double contPos_ = UNSPECIFIED_CONTPOS, - double visibility_ = UNSPECIFIED_VISIBILITY_DISTANCE, - double speed_ = UNSPECIFIED_SPEED, - double length_ = myDefaultConnectionLength, - bool haveVia_ = false, - bool uncontrolled_ = false, - const PositionVector& customShape_ = PositionVector::EMPTY, - SVCPermissions permissions = SVC_UNSPECIFIED); - - /// @brief The lane the connections starts at - int fromLane; - - /// @brief The edge the connections yields in - NBEdge* toEdge; - - /// @brief The lane the connections yields in - int toLane; - - /// @brief The id of the traffic light that controls this connection - std::string tlID; - - /// @brief The index of this connection within the controlling traffic light - int tlLinkIndex; - - /// @brief The index of the internal junction within the controlling traffic light (optional) - int tlLinkIndex2; - - /// @brief Information about being definitely free to drive (on-ramps) - bool mayDefinitelyPass; - - /// @brief whether the junction must be kept clear when using this connection - bool keepClear; - - /// @brief custom position for internal junction on this connection - double contPos; - - /// @brief custom foe visiblity for connection - double visibility; - - /// @brief custom speed for connection - double speed; - - /// @brief custom length for connection - double customLength; - - /// @brief custom shape for connection - PositionVector customShape; - - /// @brief List of vehicle types that are allowed on this connection - SVCPermissions permissions; - - /// @brief id of Connection - std::string id; - - /// @brief shape of Connection - PositionVector shape; - - /// @brief maximum velocity - double vmax; - - /// @brief check if Connection have a Via - bool haveVia; - - /// @brief if Connection have a via, ID of it - std::string viaID; - - /// @brief shape of via - PositionVector viaShape; - - /// @brief the length of the via shape (maybe customized) - double viaLength; - - /// @brief FOE Internal links - std::vector foeInternalLinks; - - /// @brief FOE Incomings lanes - std::vector foeIncomingLanes; - - /// @brief The lane index of this internal lane within the internal edge - int internalLaneIndex; - - /// @brief check if Connection is uncontrolled - bool uncontrolled; - - /// @brief get ID of internal lane - std::string getInternalLaneID() const; - - /// @brief get string describing this connection - std::string getDescription(const NBEdge* parent) const; - - /// @brief computed length (average of all internal lane shape lengths that share an internal edge) - double length; - - /// @name NBRouterEdge interface - /// @{ - static ConstRouterEdgePairVector myViaSuccessors; // always empty - const std::string& getID() const { - return id; - } - double getSpeed() const { - return vmax; - } - double getLength() const { - return shape.length() + viaShape.length(); - } - int getNumericalID() const { - throw ProcessError("NBEdge::Connection does not implement getNumericalID()"); - } - const Connection* getBidiEdge() const { - return nullptr; - } - bool isInternal() const { - return true; - } - const ConstRouterEdgePairVector& getViaSuccessors(SUMOVehicleClass vClass = SVC_IGNORING) const { - UNUSED_PARAMETER(vClass); - return myViaSuccessors; - } - /// }@ - }; - - /// @brief Dummy edge to use when a reference must be supplied in the no-arguments constructor (FOX technicality) - static NBEdge DummyEdge; - - /// @brief unspecified lane width - static const double UNSPECIFIED_WIDTH; - - /// @brief unspecified lane offset - static const double UNSPECIFIED_OFFSET; - - /// @brief unspecified lane speed - static const double UNSPECIFIED_SPEED; - - /// @brief unspecified internal junction position - static const double UNSPECIFIED_CONTPOS; - - /// @brief unspecified foe visibility for connections - static const double UNSPECIFIED_VISIBILITY_DISTANCE; - - /// @brief no length override given - static const double UNSPECIFIED_LOADED_LENGTH; - - /// @brief unspecified signal offset - static const double UNSPECIFIED_SIGNAL_OFFSET; - - /// @brief the distance at which to take the default angle - static const double ANGLE_LOOKAHEAD; - - /// @brief internal lane computation not yet done - static const int UNSPECIFIED_INTERNAL_LANE_INDEX; - - /// @brief TLS-controlled despite its node controlled not specified. - static const bool UNSPECIFIED_CONNECTION_UNCONTROLLED; - - /// @brief junction priority values set by setJunctionPriority - enum JunctionPriority { - MINOR_ROAD = 0, - PRIORITY_ROAD = 1, - ROUNDABOUT = 1000 - }; - - static void setDefaultConnectionLength(double length) { - myDefaultConnectionLength = length; - } - -public: - /** @brief Constructor - * - * Use this if no edge geometry is given. - * - * @param[in] id The id of the edge - * @param[in] from The node the edge starts at - * @param[in] to The node the edge ends at - * @param[in] type The type of the edge (my be =="") - * @param[in] speed The maximum velocity allowed on this edge - * @param[in] nolanes The number of lanes this edge has - * @param[in] priority This edge's priority - * @param[in] width This edge's lane width - * @param[in] endOffset Additional offset to the destination node - * @param[in] streetName The street name (need not be unique) - * @param[in] spread How the lateral offset of the lanes shall be computed - * @see init - * @see LaneSpreadFunction - */ - NBEdge(const std::string& id, - NBNode* from, NBNode* to, std::string type, - double speed, int nolanes, int priority, - double width, double endOffset, - const std::string& streetName = "", - LaneSpreadFunction spread = LaneSpreadFunction::RIGHT); - - - /** @brief Constructor - * - * Use this if the edge's geometry is given. - * - * @param[in] id The id of the edge - * @param[in] from The node the edge starts at - * @param[in] to The node the edge ends at - * @param[in] type The type of the edge (may be =="") - * @param[in] speed The maximum velocity allowed on this edge - * @param[in] nolanes The number of lanes this edge has - * @param[in] priority This edge's priority - * @param[in] width This edge's lane width - * @param[in] endOffset Additional offset to the destination node - * @param[in] geom The edge's geomatry - * @param[in] streetName The street name (need not be unique) - * @param[in] origID The original ID in the source network (need not be unique) - * @param[in] spread How the lateral offset of the lanes shall be computed - * @param[in] tryIgnoreNodePositions Does not add node geometries if geom.size()>=2 - * @see init - * @see LaneSpreadFunction - */ - NBEdge(const std::string& id, - NBNode* from, NBNode* to, std::string type, - double speed, int nolanes, int priority, - double width, double endOffset, - PositionVector geom, - const std::string& streetName = "", - const std::string& origID = "", - LaneSpreadFunction spread = LaneSpreadFunction::RIGHT, - bool tryIgnoreNodePositions = false); - - /** @brief Constructor - * - * Use this to copy attribuets from another edge - * - * @param[in] id The id of the edge - * @param[in] from The node the edge starts at - * @param[in] to The node the edge ends at - * @param[in] tpl The template edge to copy attributes from - * @param[in] geom The geometry to use (may be empty) - * @param[in] numLanes The number of lanes of the new edge (copy from tpl by default) - */ - NBEdge(const std::string& id, - NBNode* from, NBNode* to, - const NBEdge* tpl, - const PositionVector& geom = PositionVector(), - int numLanes = -1); - - - /// @brief Destructor - ~NBEdge(); - - - /** @brief Resets initial values - * - * @param[in] from The node the edge starts at - * @param[in] to The node the edge ends at - * @param[in] type The type of the edge (may be =="") - * @param[in] speed The maximum velocity allowed on this edge - * @param[in] nolanes The number of lanes this edge has - * @param[in] priority This edge's priority - * @param[in] geom The edge's geomatry - * @param[in] width This edge's lane width - * @param[in] endOffset Additional offset to the destination node - * @param[in] streetName The street name (need not be unique) - * @param[in] spread How the lateral offset of the lanes shall be computed - * @param[in] tryIgnoreNodePositions Does not add node geometries if geom.size()>=2 - */ - void reinit(NBNode* from, NBNode* to, const std::string& type, - double speed, int nolanes, int priority, - PositionVector geom, double width, double endOffset, - const std::string& streetName, - LaneSpreadFunction spread = LaneSpreadFunction::RIGHT, - bool tryIgnoreNodePositions = false); - - /** @brief Resets nodes but keeps all other values the same (used when joining) - * @param[in] from The node the edge starts at - * @param[in] to The node the edge ends at - */ - void reinitNodes(NBNode* from, NBNode* to); - - /// @name Applying offset - /// @{ - /** @brief Applies an offset to the edge - * @param[in] xoff The x-offset to apply - * @param[in] yoff The y-offset to apply - */ - void reshiftPosition(double xoff, double yoff); - - /// @brief mirror coordinates along the x-axis - void mirrorX(); - /// @} - - /// @name Atomar getter methods - //@{ - - /** @brief Returns the number of lanes - * @returns This edge's number of lanes - */ - int getNumLanes() const { - return (int)myLanes.size(); - } - - /** @brief Returns the priority of the edge - * @return This edge's priority - */ - int getPriority() const { - return myPriority; - } - - /// @brief Sets the priority of the edge - void setPriority(int priority) { - myPriority = priority; - } - - /** @brief Returns the origin node of the edge - * @return The node this edge starts at - */ - NBNode* getFromNode() const { - return myFrom; - } - - /** @brief Returns the destination node of the edge - * @return The node this edge ends at - */ - NBNode* getToNode() const { - return myTo; - } - - /** @brief Returns the angle at the start of the edge - * (relative to the node shape center) - * The angle is computed in computeAngle() - * @return This edge's start angle - */ - inline double getStartAngle() const { - return myStartAngle; - } - - /** @brief Returns the angle at the end of the edge - * (relative to the node shape center) - * The angle is computed in computeAngle() - * @return This edge's end angle - */ - inline double getEndAngle() const { - return myEndAngle; - } - - /** @brief Returns the angle at the start of the edge - * @note only using edge shape - * @return This edge's start angle - */ - double getShapeStartAngle() const; - - - /** @brief Returns the angle at the end of the edge - * @note only using edge shape - * @note The angle is computed in computeAngle() - * @return This edge's end angle - */ - double getShapeEndAngle() const; - - /** @brief Returns the angle at the start of the edge - * @note The angle is computed in computeAngle() - * @return This edge's angle - */ - inline double getTotalAngle() const { - return myTotalAngle; - } - - /** @brief Returns the computed length of the edge - * @return The edge's computed length - */ - double getLength() const { - return myLength; - } - - - /** @brief Returns the length was set explicitly or the computed length if it wasn't set - * @todo consolidate use of myLength and myLoaded length - * @return The edge's specified length - */ - double getLoadedLength() const { - return myLoadedLength > 0 ? myLoadedLength : myLength; - } - - /// @brief get length that will be assigned to the lanes in the final network - double getFinalLength() const; - - /** @brief Returns whether a length was set explicitly - * @return Wether the edge's length was specified - */ - bool hasLoadedLength() const { - return myLoadedLength > 0; - } - - /** @brief Returns the speed allowed on this edge - * @return The maximum speed allowed on this edge - */ - double getSpeed() const { - return mySpeed; - } - - /** @brief The building step of this edge - * @return The current building step for this edge - * @todo Recheck usage! - * @see EdgeBuildingStep - */ - EdgeBuildingStep getStep() const { - return myStep; - } - - /** @brief Returns the default width of lanes of this edge - * @return The width of lanes of this edge - */ - double getLaneWidth() const { - return myLaneWidth; - } - - /** @brief Returns the width of the lane of this edge - * @return The width of the lane of this edge - */ - double getLaneWidth(int lane) const; - - /// @brief Returns the combined width of all lanes of this edge - double getTotalWidth() const; - - /// @brief Returns the street name of this edge - const std::string& getStreetName() const { - return myStreetName; - } - - /// @brief sets the street name of this edge - void setStreetName(const std::string& name) { - myStreetName = name; - } - - /** @brief Returns the offset to the destination node - * @return The offset to the destination node - */ - double getEndOffset() const { - return myEndOffset; - } - - double getDistance() const { - return myDistance; - } - - /** @brief Returns the stopOffset to the end of the edge - * @return The offset to the end of the edge - */ - const std::map& getStopOffsets() const { - return myStopOffsets; - } - - /** @brief Returns the offset to the destination node a the specified lane - * @return The offset to the destination node - */ - double getEndOffset(int lane) const; - - /** @brief Returns the stop offset to the specified lane's end - * @return The stop offset to the specified lane's end - */ - const std::map& getStopOffsets(int lane) const; - - /// @brief Returns the offset of a traffic signal from the end of this edge - double getSignalOffset() const; - - /// @brief Returns the position of a traffic signal on this edge - const Position& getSignalPosition() const { - return mySignalPosition; - } - - /// @brief Returns the node that (possibly) represents a traffic signal controlling at the end of this edge - const NBNode* getSignalNode() const { - return mySignalNode; - } - - /// @brief sets the offset of a traffic signal from the end of this edge - void setSignalPosition(const Position& pos, const NBNode* signalNode) { - mySignalPosition = pos; - mySignalNode = signalNode; - } - - /** @brief Returns the lane definitions - * @return The stored lane definitions - */ - const std::vector& getLanes() const { - return myLanes; - } - //@} - - /** @brief return the first lane with permissions other than SVC_PEDESTRIAN and 0 - * @param[in] direction The direction in which the lanes shall be checked - * @param[in] exclusive Whether lanes that allow pedestrians along with other classes shall be counted as non-pedestrian - */ - int getFirstNonPedestrianLaneIndex(int direction, bool exclusive = false) const; - - /// @brief return index of the first lane that allows the given permissions - int getSpecialLane(SVCPermissions permissions) const; - - /** @brief return the first lane that permits at least 1 vClass or the last lane if search direction of there is no such lane - * @param[in] direction The direction in which the lanes shall be checked - */ - int getFirstAllowedLaneIndex(int direction) const; - - /// @brif get first non-pedestrian lane - NBEdge::Lane getFirstNonPedestrianLane(int direction) const; - - /// @brief return all permission variants within the specified lane range [iStart, iEnd[ - std::set getPermissionVariants(int iStart, int iEnd) const; - - /// @brief get lane indices that allow the given permissions - int getNumLanesThatAllow(SVCPermissions permissions) const; - - /// @brief return the angle for computing pedestrian crossings at the given node - double getCrossingAngle(NBNode* node); - - /// @brief get the lane id for the canonical sidewalk lane - std::string getSidewalkID(); - - /// @name Edge geometry access and computation - //@{ - /** @brief Returns the geometry of the edge - * @return The edge's geometry - */ - const PositionVector& getGeometry() const { - return myGeom; - } - - /// @brief Returns the geometry of the edge without the endpoints - const PositionVector getInnerGeometry() const; - - /// @brief Returns whether the geometry consists only of the node positions - bool hasDefaultGeometry() const; - - /** @brief Returns whether the geometry is terminated by the node positions - * This default may be violated by initializing with - * tryIgnoreNodePositions=true' or with setGeometry() - * non-default endpoints are useful to control the generated node shape - */ - bool hasDefaultGeometryEndpoints() const; - - /** @brief Returns whether the geometry is terminated by the node positions - * This default may be violated by initializing with - * tryIgnoreNodePositions=true' or with setGeometry() - * non-default endpoints are useful to control the generated node shape - */ - bool hasDefaultGeometryEndpointAtNode(const NBNode* node) const; - - Position getEndpointAtNode(const NBNode* node) const; - - /** @brief (Re)sets the edge's geometry - * - * Replaces the edge's prior geometry by the given. Then, computes - * the geometries of all lanes using computeLaneShapes. - * Definitely not the best way to have it accessable from outside... - * @param[in] g The edge's new geometry - * @param[in] inner whether g should be interpreted as inner points - * @todo Recheck usage, disallow access - * @see computeLaneShapes - */ - void setGeometry(const PositionVector& g, bool inner = false); - - /** @brief Adds a further geometry point - * - * Some importer do not know an edge's geometry when it is initialised. - * This method allows to insert further geometry points after the edge - * has been built. - * - * @param[in] index The position at which the point shall be added - * @param[in] p The point to add - */ - void addGeometryPoint(int index, const Position& p); - - /// @brief linearly extend the geometry at the given node - void extendGeometryAtNode(const NBNode* node, double maxExtent); - - /// @brief linearly extend the geometry at the given node - void shortenGeometryAtNode(const NBNode* node, double reduction); - - /// @brief shift geometry at the given node to avoid overlap - void shiftPositionAtNode(NBNode* node, NBEdge* opposite); - - /// @brief return position taking into account loaded length - Position geometryPositionAtOffset(double offset) const; - - /** @brief Recomputeds the lane shapes to terminate at the node shape - * For every lane the intersection with the fromNode and toNode is - * calculated and the lane shorted accordingly. The edge length is then set - * to the average of all lane lengths (which may differ). This average length is used as the lane - * length when writing the network. - * @note All lanes of an edge in a sumo net must have the same nominal length - * but may differ in actual geomtric length. - * @note Depends on previous call to NBNodeCont::computeNodeShapes - */ - void computeEdgeShape(double smoothElevationThreshold = -1); - - /** @brief Returns the shape of the nth lane - * @return The shape of the lane given by its index (counter from right) - */ - const PositionVector& getLaneShape(int i) const; - - /** @brief (Re)sets how the lanes lateral offset shall be computed - * @param[in] spread The type of lateral offset to apply - * @see LaneSpreadFunction - */ - void setLaneSpreadFunction(LaneSpreadFunction spread); - - /** @brief Returns how this edge's lanes' lateral offset is computed - * @return The type of lateral offset that is applied on this edge - * @see LaneSpreadFunction - */ - LaneSpreadFunction getLaneSpreadFunction() const { - return myLaneSpreadFunction; - } - - /** @brief Removes points with a distance lesser than the given - * @param[in] minDist The minimum distance between two position to keep the second - */ - void reduceGeometry(const double minDist); - - /** @brief Check the angles of successive geometry segments - * @param[in] maxAngle The maximum angle allowed - * @param[in] minRadius The minimum turning radius allowed at the start and end - * @param[in] fix Whether to prune geometry points to avoid sharp turns at start and end - */ - void checkGeometry(const double maxAngle, const double minRadius, bool fix, bool silent); - //@} - - /// @name Setting and getting connections - /// @{ - /** @brief Adds a connection to another edge - * - * If the given edge does not start at the node this edge ends on, false is returned. - * - * All other cases return true. Though, a connection may not been added if this edge - * is in step "INIT_REJECT_CONNECTIONS". Also, this method assures that a connection - * to an edge is set only once, no multiple connections to next edge are stored. - * - * After a first connection to an edge was set, the process step is set to "EDGE2EDGES". - * @note Passing 0 implicitly removes all existing connections - * - * @param[in] dest The connection's destination edge - * @return Whether the connection was valid - */ - bool addEdge2EdgeConnection(NBEdge* dest, bool overrideRemoval = false); - - /** @brief Adds a connection between the specified this edge's lane and an approached one - * - * If the given edge does not start at the node this edge ends on, false is returned. - * - * All other cases return true. Though, a connection may not been added if this edge - * is in step "INIT_REJECT_CONNECTIONS". Before the lane-to-lane connection is set, - * a connection between edges is established using "addEdge2EdgeConnection". Then, - * "setConnection" is called for inserting the lane-to-lane connection. - * - * @param[in] fromLane The connection's starting lane (of this edge) - * @param[in] dest The connection's destination edge - * @param[in] toLane The connection's destination lane - * @param[in] type The connections's type - * @param[in] mayUseSameDestination Whether this connection may be set though connecting an already connected lane - * @param[in] mayDefinitelyPass Whether this connection is definitely undistrubed (special case for on-ramps) - * @return Whether the connection was added / exists - * @see addEdge2EdgeConnection - * @see setConnection - * @todo Check difference between "setConnection" and "addLane2LaneConnection" - */ - bool addLane2LaneConnection(int fromLane, NBEdge* dest, - int toLane, Lane2LaneInfoType type, - bool mayUseSameDestination = false, - bool mayDefinitelyPass = false, - bool keepClear = true, - double contPos = UNSPECIFIED_CONTPOS, - double visibility = UNSPECIFIED_VISIBILITY_DISTANCE, - double speed = UNSPECIFIED_SPEED, - double length = myDefaultConnectionLength, - const PositionVector& customShape = PositionVector::EMPTY, - const bool uncontrolled = UNSPECIFIED_CONNECTION_UNCONTROLLED, - SVCPermissions = SVC_UNSPECIFIED, - bool postProcess = false); - - /** @brief Builds no connections starting at the given lanes - * - * If "invalidatePrevious" is true, a call to "invalidateConnections(true)" is done. - * This method loops through the given connections to set, calling "addLane2LaneConnection" - * for each. - * - * @param[in] fromLane The first of the connections' starting lanes (of this edge) - * @param[in] dest The connections' destination edge - * @param[in] toLane The first of the connections' destination lanes - * @param[in] no The number of connections to set - * @param[in] type The connections' type - * @param[in] invalidatePrevious Whether previously set connection shall be deleted - * @param[in] mayDefinitelyPass Whether these connections are definitely undistrubed (special case for on-ramps) - * @return Whether the connections were added / existed - * @see addLane2LaneConnection - * @see invalidateConnections - */ - bool addLane2LaneConnections(int fromLane, - NBEdge* dest, int toLane, int no, - Lane2LaneInfoType type, bool invalidatePrevious = false, - bool mayDefinitelyPass = false); - - /** @brief Adds a connection to a certain lane of a certain edge - * - * @param[in] lane The connection's starting lane (of this edge) - * @param[in] destEdge The connection's destination edge - * @param[in] destLane The connection's destination lane - * @param[in] type The connections's type - * @param[in] mayUseSameDestination Whether this connection may be set though connecting an already connected lane - * @param[in] mayDefinitelyPass Whether this connection is definitely undistrubed (special case for on-ramps) - * @todo Check difference between "setConnection" and "addLane2LaneConnection" - */ - bool setConnection(int lane, NBEdge* destEdge, - int destLane, - Lane2LaneInfoType type, - bool mayUseSameDestination = false, - bool mayDefinitelyPass = false, - bool keepClear = true, - double contPos = UNSPECIFIED_CONTPOS, - double visibility = UNSPECIFIED_VISIBILITY_DISTANCE, - double speed = UNSPECIFIED_SPEED, - double length = myDefaultConnectionLength, - const PositionVector& customShape = PositionVector::EMPTY, - const bool uncontrolled = UNSPECIFIED_CONNECTION_UNCONTROLLED, - SVCPermissions permissions = SVC_UNSPECIFIED, - bool postProcess = false); - - /** @brief Returns connections from a given lane - * - * This method goes through "myConnections" and copies those which are - * starting at the given lane. - * @param[in] lane The lane which connections shall be returned - * @param[in] to The target Edge (ignore nullptr) - * @param[in] toLane The target lane (ignore if > 0) - * @return The connections from the given lane - * @see NBEdge::Connection - */ - std::vector getConnectionsFromLane(int lane, NBEdge* to = nullptr, int toLane = -1) const; - - /** @brief Returns the specified connection - * This method goes through "myConnections" and returns the specified one - * @see NBEdge::Connection - */ - Connection getConnection(int fromLane, const NBEdge* to, int toLane) const; - - /** @brief Returns reference to the specified connection - * This method goes through "myConnections" and returns the specified one - * @see NBEdge::Connection - */ - Connection& getConnectionRef(int fromLane, const NBEdge* to, int toLane); - - /** @brief Retrieves info about a connection to a certain lane of a certain edge - * - * Turnaround edge is ignored! - * @param[in] destEdge The connection's destination edge - * @param[in] destLane The connection's destination lane - * @param[in] fromLane If a value >= 0 is given, only return true if a connection from the given lane exists - * @return whether a connection to the specified lane exists - */ - bool hasConnectionTo(NBEdge* destEdge, int destLane, int fromLane = -1) const; - - /** @brief Returns the information whethe a connection to the given edge has been added (or computed) - * - * @param[in] e The destination edge - * @param[in] ignoreTurnaround flag to ignore or not Turnaround - * @return Whether a connection to the specified edge exists - */ - bool isConnectedTo(const NBEdge* e, const bool ignoreTurnaround = false) const; - - /** @brief Returns the connections - * @return This edge's connections to following edges - */ - const std::vector& getConnections() const { - return myConnections; - } - - /** @brief Returns the connections - * @return This edge's connections to following edges - */ - std::vector& getConnections() { - return myConnections; - } - - /** @brief Returns the list of outgoing edges without the turnaround sorted in clockwise direction - * @return Connected edges, sorted clockwise - */ - const EdgeVector* getConnectedSorted(); - - /** @brief Returns the list of outgoing edges unsorted - * @return Connected edges - */ - EdgeVector getConnectedEdges() const; - - /** @brief Returns the list of incoming edges unsorted - * @return Connected predecessor edges - */ - EdgeVector getIncomingEdges() const; - - /** @brief Returns the list of lanes that may be used to reach the given edge - * @return Lanes approaching the given edge - */ - std::vector getConnectionLanes(NBEdge* currentOutgoing, bool withBikes = true) const; - - /// @brief sorts the outgoing connections by their angle relative to their junction - void sortOutgoingConnectionsByAngle(); - - /// @brief sorts the outgoing connections by their from-lane-index and their to-lane-index - void sortOutgoingConnectionsByIndex(); - - /** @brief Remaps the connection in a way that allows the removal of it - * - * This edge (which is a self loop edge, in fact) connections are spread over the valid incoming edges - * @todo recheck! - */ - void remapConnections(const EdgeVector& incoming); - - /** @brief Removes the specified connection(s) - * @param[in] toEdge The destination edge - * @param[in] fromLane The lane from which connections shall be removed; -1 means remove all - * @param[in] toLane The lane to which connections shall be removed; -1 means remove all - * @param[in] tryLater If the connection does not exist, try again during recheckLanes() - * @param[in] adaptToLaneRemoval we are in the process of removing a complete lane, adapt all connections accordingly - */ - void removeFromConnections(NBEdge* toEdge, int fromLane = -1, int toLane = -1, bool tryLater = false, const bool adaptToLaneRemoval = false, const bool keepPossibleTurns = false); - - /// @brief remove an existent connection of edge - bool removeFromConnections(const NBEdge::Connection& connectionToRemove); - - /// @brief invalidate current connections of edge - void invalidateConnections(bool reallowSetting = false); - - /// @brief replace in current connections of edge - void replaceInConnections(NBEdge* which, NBEdge* by, int laneOff); - - /// @brief replace in current connections of edge - void replaceInConnections(NBEdge* which, const std::vector& origConns); - - /// @brief copy connections from antoher edge - void copyConnectionsFrom(NBEdge* src); - - /// @brief modifify the toLane for all connections to the given edge - void shiftToLanesToEdge(NBEdge* to, int laneOff); - /// @} - - /** @brief Returns whether the given edge is the opposite direction to this edge - * @param[in] edge The edge which may be the turnaround direction - * @return Whether the given edge is this edge's turnaround direction - * (regardless of whether a connection exists) - */ - bool isTurningDirectionAt(const NBEdge* const edge) const; - - /** @brief Sets the turing destination at the given edge - * @param[in] e The turn destination - * @param[in] onlyPossible If true, only sets myPossibleTurnDestination - */ - void setTurningDestination(NBEdge* e, bool onlyPossible = false); - - /// @name Setting/getting special types - /// @{ - /// @brief Marks this edge as a macroscopic connector - void setAsMacroscopicConnector() { - myAmMacroscopicConnector = true; - } - - /** @brief Returns whether this edge was marked as a macroscopic connector - * @return Whether this edge was marked as a macroscopic connector - */ - bool isMacroscopicConnector() const { - return myAmMacroscopicConnector; - } - - /// @brief Marks this edge being within an intersection - void setInsideTLS(bool inside) { - myAmInTLS = inside; - } - - /** @brief Returns whether this edge was marked as being within an intersection - * @return Whether this edge was marked as being within an intersection - */ - bool isInsideTLS() const { - return myAmInTLS; - } - /// @} - - /** @brief Sets the junction priority of the edge - * @param[in] node The node for which the edge's priority is given - * @param[in] prio The edge's new priority at this node - * @todo Maybe the edge priority whould be stored in the node - */ - void setJunctionPriority(const NBNode* const node, int prio); - - /** @brief Returns the junction priority (normalised for the node currently build) - * - * If the given node is neither the edge's start nor the edge's ending node, the behaviour - * is undefined. - * - * @param[in] node The node for which the edge's priority shall be returned - * @return The edge's priority at the given node - * @todo Maybe the edge priority whould be stored in the node - */ - int getJunctionPriority(const NBNode* const node) const; - - /// @brief set loaded length - void setLoadedLength(double val); - - /// @brief patch average lane length in regard to the opposite edge - void setAverageLengthWithOpposite(double val); - - /// @brief dimiss vehicle class information - void dismissVehicleClassInformation(); - - /// @brief get ID of type - const std::string& getTypeID() const { - return myType; - } - - /// @brief whether at least one lane has values differing from the edges values - bool needsLaneSpecificOutput() const; - - /// @brief whether at least one lane has restrictions - bool hasPermissions() const; - - /// @brief whether lanes differ in allowed vehicle classes - bool hasLaneSpecificPermissions() const; - - /// @brief whether lanes differ in speed - bool hasLaneSpecificSpeed() const; - - /// @brief whether lanes differ in width - bool hasLaneSpecificWidth() const; - - /// @brief whether lanes differ in type - bool hasLaneSpecificType() const; - - /// @brief whether lanes differ in offset - bool hasLaneSpecificEndOffset() const; - - /// @brief whether lanes differ in stopOffsets - bool hasLaneSpecificStopOffsets() const; - - /// @brief whether one of the lanes is an acceleration lane - bool hasAccelLane() const; - - /// @brief whether one of the lanes has a custom shape - bool hasCustomLaneShape() const; - - /// @brief whether one of the lanes has parameters set - bool hasLaneParams() const; - - /// @brief computes the edge (step1: computation of approached edges) - bool computeEdge2Edges(bool noLeftMovers); - - /// @brief computes the edge, step2: computation of which lanes approach the edges) - bool computeLanes2Edges(); - - /// @brief recheck whether all lanes within the edge are all right and optimises the connections once again - bool recheckLanes(); - - /** @brief Add a connection to the previously computed turnaround, if wished - * and a turning direction exists (myTurnDestination!=0) - * @param[in] noTLSControlled Whether the turnaround shall not be connected if the edge is controlled by a tls - * @param[in] noFringe Whether the turnaround shall not be connected if the junction is at the (outer) fringe - * @param[in] onlyDeadends Whether the turnaround shall only be built at deadends - * @param[in] onlyTurnlane Whether the turnaround shall only be built when there is an exclusive (left) turn lane - * @param[in] noGeometryLike Whether the turnaround shall be built at geometry-like nodes - */ - void appendTurnaround(bool noTLSControlled, bool noFringe, bool onlyDeadends, bool onlyTurnlane, bool noGeometryLike, bool checkPermissions); - - /** @brief Returns the node at the given edges length (using an epsilon) - @note When no node is existing at the given position, 0 is returned - The epsilon is a static member of NBEdge, should be setable via program options */ - NBNode* tryGetNodeAtPosition(double pos, double tolerance = 5.0) const; - - /// @brief get max lane offset - double getMaxLaneOffset(); - - /// @brief Check if lanes were assigned - bool lanesWereAssigned() const; - - /// @brief return true if certain connection must be controlled by TLS - bool mayBeTLSControlled(int fromLane, NBEdge* toEdge, int toLane) const; - - /// @brief Returns if the link could be set as to be controlled - bool setControllingTLInformation(const NBConnection& c, const std::string& tlID); - - /// @brief clears tlID for all connections - void clearControllingTLInformation(); - - /// @brief add crossing points as incoming with given outgoing - void addCrossingPointsAsIncomingWithGivenOutgoing(NBEdge* o, PositionVector& into); - - /// @brief get the outer boundary of this edge when going clock-wise around the given node - PositionVector getCWBoundaryLine(const NBNode& n) const; - - /// @brief get the outer boundary of this edge when going counter-clock-wise around the given node - PositionVector getCCWBoundaryLine(const NBNode& n) const; - - /// @brief Check if Node is expandable - bool expandableBy(NBEdge* possContinuation, std::string& reason) const; - - /// @brief append another edge - void append(NBEdge* continuation); - - /// @brief Check if edge has signalised connections - bool hasSignalisedConnectionTo(const NBEdge* const e) const; - - /// @brief move outgoing connection - void moveOutgoingConnectionsFrom(NBEdge* e, int laneOff); - - /* @brief return the turn destination if it exists - * @param[in] possibleDestination Wether myPossibleTurnDestination should be returned if no turnaround connection - * exists - */ - NBEdge* getTurnDestination(bool possibleDestination = false) const; - - /// @brief get lane ID - std::string getLaneID(int lane) const; - - /// @brief get lane speed - double getLaneSpeed(int lane) const; - - /// @brief Check if edge is near enought to be joined to another edge - bool isNearEnough2BeJoined2(NBEdge* e, double threshold) const; - - /** @brief Returns the angle of the edge's geometry at the given node - * - * The angle is signed, regards direction, and starts at 12 o'clock - * (north->south), proceeds positive clockwise. - * @param[in] node The node for which the edge's angle shall be returned - * @return This edge's angle at the given node - */ - double getAngleAtNode(const NBNode* const node) const; - - /** @brief Returns the angle of from the node shape center to where the edge meets - * the node shape - * - * The angle is signed, disregards direction, and starts at 12 o'clock - * (north->south), proceeds positive clockwise. - * @param[in] node The node for which the edge's angle shall be returned - * @return This edge's angle at the given node shape - */ - double getAngleAtNodeToCenter(const NBNode* const node) const; - - /// @brief increment lane - void incLaneNo(int by); - - /// @brief decrement lane - void decLaneNo(int by); - - /// @brief delete lane - void deleteLane(int index, bool recompute, bool shiftIndices); - - /// @brief add lane - void addLane(int index, bool recomputeShape, bool recomputeConnections, bool shiftIndices); - - /// @brief mark edge as in lane to state lane - void markAsInLane2LaneState(); - - /// @brief add a pedestrian sidewalk of the given width and shift existing connctions - void addSidewalk(double width); - - /// @brief restore an previously added sidewalk - void restoreSidewalk(std::vector oldLanes, PositionVector oldGeometry, std::vector oldConnections); - - /// add a bicycle lane of the given width and shift existing connctions - void addBikeLane(double width); - - /// @brief restore an previously added BikeLane - void restoreBikelane(std::vector oldLanes, PositionVector oldGeometry, std::vector oldConnections); - - /// @brief add a lane of the given width, restricted to the given class and shift existing connections - void addRestrictedLane(double width, SUMOVehicleClass vclass); - - /// @brief set allowed/disallowed classes for the given lane or for all lanes if -1 is given - void setPermissions(SVCPermissions permissions, int lane = -1); - - /// @brief set preferred Vehicle Class - void setPreferredVehicleClass(SVCPermissions permissions, int lane = -1); - - /// @brief set allowed class for the given lane or for all lanes if -1 is given - void allowVehicleClass(int lane, SUMOVehicleClass vclass); - - /// @brief set disallowed class for the given lane or for all lanes if -1 is given - void disallowVehicleClass(int lane, SUMOVehicleClass vclass); - - /// @brief prefer certain vehicle class - void preferVehicleClass(int lane, SUMOVehicleClass vclass); - - /// @brief set lane specific width (negative lane implies set for all lanes) - void setLaneWidth(int lane, double width); - - /// @brief set lane specific type (negative lane implies set for all lanes) - void setLaneType(int lane, const std::string& type); - - /// @brief set lane specific end-offset (negative lane implies set for all lanes) - void setEndOffset(int lane, double offset); - - /// @brief set lane specific speed (negative lane implies set for all lanes) - void setSpeed(int lane, double speed); - - /// @brief set lane and vehicle class specific stopOffset (negative lane implies set for all lanes) - /// @return Whether given stop offset was applied. - bool setStopOffsets(int lane, std::map offsets, bool overwrite = false); - - /// @brief marks one lane as acceleration lane - void setAcceleration(int lane, bool accelRamp); - - /// @brief marks this edge has being an offRamp or leading to one (used for connection computation) - void markOffRamp(bool isOffRamp) { - myIsOffRamp = isOffRamp; - } - - bool isOffRamp() const { - return myIsOffRamp; - } - - /// @brief sets a custom lane shape - void setLaneShape(int lane, const PositionVector& shape); - - /// @brief get the union of allowed classes over all lanes or for a specific lane - SVCPermissions getPermissions(int lane = -1) const; - - /// @brief set origID for all lanes - void setOrigID(const std::string origID); - - /// @brief set lane specific speed (negative lane implies set for all lanes) - void setDistance(double distance) { - myDistance = distance; - } - - /// @brief disable connections for TLS - void disableConnection4TLS(int fromLane, NBEdge* toEdge, int toLane); - - // @brief returns a reference to the internal structure for the convenience of NETEDIT - Lane& getLaneStruct(int lane) { - assert(lane >= 0); - assert(lane < (int)myLanes.size()); - return myLanes[lane]; - } - - // @brief returns a reference to the internal structure for the convenience of NETEDIT - const Lane& getLaneStruct(int lane) const { - assert(lane >= 0); - assert(lane < (int)myLanes.size()); - return myLanes[lane]; - } - - /// @brief declares connections as fully loaded. This is needed to avoid recomputing connections if an edge has no connections intentionally. - void declareConnectionsAsLoaded(EdgeBuildingStep step = EdgeBuildingStep::LANES2LANES_USER) { - myStep = step; - } - - /* @brief fill connection attributes shape, viaShape, ... - * - * @param[in,out] edgeIndex The number of connections already handled - * @param[in,out] splitIndex The number of via edges already built - * @param[in] tryIgnoreNodePositions Does not add node geometries if geom.size()>=2 - */ - void buildInnerEdges(const NBNode& n, int noInternalNoSplits, int& linkIndex, int& splitIndex); - - /// @brief get Signs - inline const std::vector& getSigns() const { - return mySigns; - } - - /// @brief add Sign - inline void addSign(NBSign sign) { - mySigns.push_back(sign); - } - - /// @brief cut shape at the intersection shapes - PositionVector cutAtIntersection(const PositionVector& old) const; - - /// @brief Set Node border - void setNodeBorder(const NBNode* node, const Position& p, const Position& p2, bool rectangularCut); - const PositionVector& getNodeBorder(const NBNode* node); - void resetNodeBorder(const NBNode* node); - - /// @brief whether this edge is part of a bidirectional railway - bool isBidiRail(bool ignoreSpread = false) const; - - /// @brief whether this edge is a railway edge that does not continue - bool isRailDeadEnd() const; - - /// @brief debugging helper to print all connections - void debugPrintConnections(bool outgoing = true, bool incoming = false) const; - - /// @brief compute the first intersection point between the given lane geometries considering their rspective widths - static double firstIntersection(const PositionVector& v1, const PositionVector& v2, double width2, const std::string& error = ""); - - /** returns a modified version of laneShape which starts at the outside of startNode. laneShape may be shorted or extended - * @note see [wiki:Developer/Network_Building_Process] - */ - static PositionVector startShapeAt(const PositionVector& laneShape, const NBNode* startNode, PositionVector nodeShape); - - /// @name functions for router usage - //@{ - - static inline double getTravelTimeStatic(const NBEdge* const edge, const NBVehicle* const /*veh*/, double /*time*/) { - return edge->getLength() / edge->getSpeed(); - } - - static int getLaneIndexFromLaneID(const std::string laneID); - - /// @brief sets the index of the edge in the list of all network edges - void setNumericalID(int index) { - myIndex = index; - } - - /** @brief Returns the index (numeric id) of the edge - * @note This is only used in the context of routing - * @return This edge's numerical id - */ - int getNumericalID() const { - return myIndex; - } - - const NBEdge* getBidiEdge() const { - return isBidiRail() ? myPossibleTurnDestination : nullptr; - } - - /** @brief Returns the following edges for the given vClass - */ - const EdgeVector& getSuccessors(SUMOVehicleClass vClass = SVC_IGNORING) const; - - - /** @brief Returns the following edges for the given vClass - */ - const ConstRouterEdgePairVector& getViaSuccessors(SUMOVehicleClass vClass = SVC_IGNORING) const; - - //@} - const std::string& getID() const { - return Named::getID(); - } - - /// @brief join adjacent lanes with the given permissions - bool joinLanes(SVCPermissions perms); - - /// @brief reset lane shapes to what they would be before cutting with the junction shapes - void resetLaneShapes(); - - /// @brief return the straightest follower edge for the given permissions or nullptr (never returns turn-arounds) - /// @note: this method is called before connections are built and simply goes by node graph topology - NBEdge* getStraightContinuation(SVCPermissions permissions) const; - - /// @brief return the straightest predecessor edge for the given permissions or nullptr (never returns turn-arounds) - /// @note: this method is called before connections are built and simply goes by node graph topology - NBEdge* getStraightPredecessor(SVCPermissions permissions) const; - - /// @brief return only those edges that permit at least one of the give permissions - static EdgeVector filterByPermissions(const EdgeVector& edges, SVCPermissions permissions); - -private: - /** @class ToEdgeConnectionsAdder - * @brief A class that being a bresenham-callback assigns the incoming lanes to the edges - */ - class ToEdgeConnectionsAdder : public Bresenham::BresenhamCallBack { - private: - /// @brief map of edges to this edge's lanes that reach them - std::map > myConnections; - - /// @brief the transition from the virtual lane to the edge it belongs to - const EdgeVector& myTransitions; - - public: - /// @brief constructor - ToEdgeConnectionsAdder(const EdgeVector& transitions) - : myTransitions(transitions) { } - - /// @brief destructor - ~ToEdgeConnectionsAdder() { } - - /// @brief executes a bresenham - step - void execute(const int lane, const int virtEdge); - - /// @brief get built connections - const std::map >& getBuiltConnections() const { - return myConnections; - } - - private: - /// @brief Invalidated copy constructor. - ToEdgeConnectionsAdder(const ToEdgeConnectionsAdder&); - - /// @brief Invalidated assignment operator. - ToEdgeConnectionsAdder& operator=(const ToEdgeConnectionsAdder&); - }; - - - /** - * @class MainDirections - * @brief Holds (- relative to the edge it is build from -!!!) the list of - * main directions a vehicle that drives on this street may take on - * the junction the edge ends in - * The back direction is not regarded - */ - class MainDirections { - public: - /// @brief enum of possible directions - enum class Direction { - RIGHTMOST, - LEFTMOST, - FORWARD - }; - - public: - /// @brief constructor - MainDirections(const EdgeVector& outgoing, NBEdge* parent, NBNode* to, const std::vector& availableLanes); - - /// @brief destructor - ~MainDirections(); - - /// @brief returns the index of the straightmost among the given outgoing edges - int getStraightest() const { - return myStraightest; - } - - /// @brief returns the information whether no following street has a higher priority - bool empty() const; - - /// @brief returns the information whether the street in the given direction has a higher priority - bool includes(Direction d) const; - - private: - /// @brief the index of the straightmost among the given outgoing edges - int myStraightest; - - /// @brief list of the main direction within the following junction relative to the edge - std::vector myDirs; - - /// @brief Invalidated copy constructor. - MainDirections(const MainDirections&); - - /// @brief Invalidated assignment operator. - MainDirections& operator=(const MainDirections&); - }; - - /// @brief Computes the shape for the given lane - PositionVector computeLaneShape(int lane, double offset) const; - - /// @brief compute lane shapes - void computeLaneShapes(); - -private: - /** @brief Initialization routines common to all constructors - * - * Checks whether the number of lanes>0, whether the junction's from- - * and to-nodes are given (!=0) and whether they are distict. Throws - * a ProcessError if any of these checks fails. - * - * Adds the nodes positions to geometry if it shall not be ignored or - * if the geometry is empty. - * - * Computes the angle and length, and adds this edge to its node as - * outgoing/incoming. Builds lane informations. - * - * @param[in] noLanes The number of lanes this edge has - * @param[in] tryIgnoreNodePositions Does not add node geometries if geom.size()>=2 - * @param[in] origID The original ID this edge had - */ - void init(int noLanes, bool tryIgnoreNodePositions, const std::string& origID); - - /// @brief divides the lanes on the outgoing edges - void divideOnEdges(const EdgeVector* outgoing); - - /// @brief divide selected lanes on edges - void divideSelectedLanesOnEdges(const EdgeVector* outgoing, const std::vector& availableLanes); - - /// @brief add some straight connections - void addStraightConnections(const EdgeVector* outgoing, const std::vector& availableLanes, const std::vector& priorities); - - /// @brief recomputes the edge priorities and manipulates them for a distribution of lanes on edges which is more like in real-life - const std::vector prepareEdgePriorities(const EdgeVector* outgoing, const std::vector& availableLanes); - - /// @name Setting and getting connections - /// @{ - /** @briefmoves a connection one place to the left; - * @note Attention! no checking for field validity - */ - void moveConnectionToLeft(int lane); - - /** @briefmoves a connection one place to the right; - * @noteAttention! no checking for field validity - */ - void moveConnectionToRight(int lane); - - /// @brief whether the connection can originate on newFromLane - bool canMoveConnection(const Connection& con, int newFromLane) const; - /// @} - - /// @brief computes the angle of this edge and stores it in myAngle - void computeAngle(); - - /// @brief determine conflict between opposite left turns - bool bothLeftIntersect(const NBNode& n, const PositionVector& shape, LinkDirection dir, NBEdge* otherFrom, const NBEdge::Connection& otherCon, int numPoints, double width2, int shapeFlag = 0) const; - - /// @brief returns whether any lane already allows the given vclass exclusively - bool hasRestrictedLane(SUMOVehicleClass vclass) const; - - /// @brief restore a restricted lane - void restoreRestrictedLane(SUMOVehicleClass vclass, std::vector oldLanes, PositionVector oldGeometry, std::vector oldConnections); - - /// @brief assign length to all lanes of an internal edge - void assignInternalLaneLength(std::vector::iterator i, int numLanes, double lengthSum); - -private: - /** @brief The building step - * @see EdgeBuildingStep - */ - EdgeBuildingStep myStep; - - /// @brief The type of the edge - std::string myType; - - /// @brief The source and the destination node - NBNode* myFrom, *myTo; - - /// @brief The length of the edge - double myLength; - - /// @brief The angles of the edge - /// @{ - double myStartAngle; - double myEndAngle; - double myTotalAngle; - /// @} - - /// @brief The priority of the edge - int myPriority; - - /// @brief The maximal speed - double mySpeed; - - /// @brief The mileage/kilometrage at the start of this edge in a linear coordination system - double myDistance; - - /** @brief List of connections to following edges - * @see Connection - */ - std::vector myConnections; - - /// @brief List of connections marked for delayed removal - std::vector myConnectionsToDelete; - - /// @brief The turn destination edge (if a connection exists) - NBEdge* myTurnDestination; - - /// @brief The edge that would be the turn destination if there was one - NBEdge* myPossibleTurnDestination; - - /// @brief The priority normalised for the node the edge is outgoing of - int myFromJunctionPriority; - - /// @brief The priority normalised for the node the edge is incoming in - int myToJunctionPriority; - - /// @brief The geometry for the edge - PositionVector myGeom; - - /// @brief The information about how to spread the lanes - LaneSpreadFunction myLaneSpreadFunction; - - /// @brief This edges's offset to the intersection begin (will be applied to all lanes) - double myEndOffset; - - /// @brief A vClass specific stop offset - assumed of length 0 (unspecified) or 1. - /// For the latter case the int is a bit set specifying the vClasses, - /// the offset applies to (see SUMOVehicleClass.h), and the double is the - /// stopping offset in meters from the lane end - std::map myStopOffsets; - - /// @brief This width of this edge's lanes - double myLaneWidth; - - /** @brief Lane information - * @see Lane - */ - std::vector myLanes; - - /// @brief An optional length to use (-1 if not valid) - double myLoadedLength; - - /// @brief Information whether this is lies within a joined tls - bool myAmInTLS; - - /// @brief Information whether this edge is a (macroscopic) connector - bool myAmMacroscopicConnector; - - /// @brief The street name (or whatever arbitrary string you wish to attach) - std::string myStreetName; - - /// @brief the street signs along this edge - std::vector mySigns; - - /// @brief the position of a traffic light signal on this edge - Position mySignalPosition; - const NBNode* mySignalNode; - - /// @brief intersection borders (because the node shape might be invalid) - /// @{ - PositionVector myFromBorder; - PositionVector myToBorder; - /// @} - - /// @brief whether this edge is an Off-Ramp or leads to one - bool myIsOffRamp; - - /// @brief the index of the edge in the list of all edges. Set by NBEdgeCont and requires re-set whenever the list of edges changes - int myIndex; - - // @brief a static list of successor edges. Set by NBEdgeCont and requires reset when the network changes - mutable EdgeVector mySuccessors; - - // @brief a static list of successor edges. Set by NBEdgeCont and requires reset when the network changes - mutable ConstRouterEdgePairVector myViaSuccessors; - - // @brief default length for overriding connection lengths - static double myDefaultConnectionLength; - -public: - - /// @class connections_toedge_finder - class connections_toedge_finder { - public: - /// @brief constructor - connections_toedge_finder(const NBEdge* const edge2find, bool hasFromLane = false) : - myHasFromLane(hasFromLane), - myEdge2Find(edge2find) { } - - /// @brief operator () - bool operator()(const Connection& c) const { - return c.toEdge == myEdge2Find && (!myHasFromLane || c.fromLane != -1); - } - - private: - /// @brief check if has from lane - const bool myHasFromLane; - - /// @brief edge to find - const NBEdge* const myEdge2Find; - - private: - /// @brief invalidated assignment operator - connections_toedge_finder& operator=(const connections_toedge_finder& s); - }; - - /// @class connections_toedgelane_finder - class connections_toedgelane_finder { - public: - /// @brief constructor - connections_toedgelane_finder(NBEdge* const edge2find, int lane2find, int fromLane2find) : - myEdge2Find(edge2find), - myLane2Find(lane2find), - myFromLane2Find(fromLane2find) { } - - /// @brief operator () - bool operator()(const Connection& c) const { - return c.toEdge == myEdge2Find && c.toLane == myLane2Find && (myFromLane2Find < 0 || c.fromLane == myFromLane2Find); - } - - private: - /// @brief edge to find - NBEdge* const myEdge2Find; - - /// @brief lane to find - int myLane2Find; - - /// @brief from lane to find - int myFromLane2Find; - - private: - /// @brief invalidated assignment operator - connections_toedgelane_finder& operator=(const connections_toedgelane_finder& s); - - }; - - /// @class connections_finder - class connections_finder { - public: - /// @brief constructor - connections_finder(int fromLane, NBEdge* const edge2find, int lane2find, bool invertEdge2find = false) : - myFromLane(fromLane), myEdge2Find(edge2find), myLane2Find(lane2find), myInvertEdge2find(invertEdge2find) { } - - /// @brief operator () - bool operator()(const Connection& c) const { - return ((c.fromLane == myFromLane || myFromLane == -1) - && ((!myInvertEdge2find && c.toEdge == myEdge2Find) || (myInvertEdge2find && c.toEdge != myEdge2Find)) - && (c.toLane == myLane2Find || myLane2Find == -1)); - } - - private: - /// @brief index of from lane - int myFromLane; - - /// @brief edge to find - NBEdge* const myEdge2Find; - - /// @brief lane to find - int myLane2Find; - - /// @brief invert edge to find - bool myInvertEdge2find; - - private: - /// @brief invalidated assignment operator - connections_finder& operator=(const connections_finder& s); - - }; - - /// @class connections_conflict_finder - class connections_conflict_finder { - public: - /// @brief constructor - connections_conflict_finder(int fromLane, NBEdge* const edge2find, bool checkRight) : - myFromLane(fromLane), myEdge2Find(edge2find), myCheckRight(checkRight) { } - - /// @brief operator () - bool operator()(const Connection& c) const { - return (((myCheckRight && c.fromLane < myFromLane) || (!myCheckRight && c.fromLane > myFromLane)) - && c.fromLane >= 0 // already assigned - && c.toEdge == myEdge2Find); - } - - private: - /// @brief index of from lane - int myFromLane; - - /// @brief edge to find - NBEdge* const myEdge2Find; - - /// @brief check if is right - bool myCheckRight; - - private: - /// @brief invalidated assignment operator - connections_conflict_finder& operator=(const connections_conflict_finder& s); - - }; - - /// @class connections_fromlane_finder - class connections_fromlane_finder { - public: - /// @briefconstructor - connections_fromlane_finder(int lane2find) : myLane2Find(lane2find) { } - - /// @brief operator () - bool operator()(const Connection& c) const { - return c.fromLane == myLane2Find; - } - - private: - /// @brief index of lane to find - int myLane2Find; - - private: - /// @brief invalidated assignment operator - connections_fromlane_finder& operator=(const connections_fromlane_finder& s); - - }; - - /// @brief connections_sorter sort by fromLane, toEdge and toLane - static bool connections_sorter(const Connection& c1, const Connection& c2); - - /** - * @class connections_relative_edgelane_sorter - * @brief Class to sort edges by their angle - */ - class connections_relative_edgelane_sorter { - public: - /// @brief constructor - explicit connections_relative_edgelane_sorter(NBEdge* e) : myEdge(e) {} - - public: - /// @brief comparing operation - int operator()(const Connection& c1, const Connection& c2) const; - - private: - /// @brief the edge to compute the relative angle of - NBEdge* myEdge; - }; - -private: - /// @brief invalidated copy constructor - NBEdge(const NBEdge& s); - - /// @brief invalidated assignment operator - NBEdge& operator=(const NBEdge& s); - - /// @brief constructor for dummy edge - NBEdge(); - -}; diff --git a/Util/OSM2ODR/src/netbuild/NBEdgeCont.cpp b/Util/OSM2ODR/src/netbuild/NBEdgeCont.cpp deleted file mode 100644 index c466cf707..000000000 --- a/Util/OSM2ODR/src/netbuild/NBEdgeCont.cpp +++ /dev/null @@ -1,1897 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NBEdgeCont.cpp -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Sascha Krieg -/// @author Michael Behrisch -/// @date Tue, 20 Nov 2001 -/// -// Storage for edges, including some functionality operating on multiple edges -/****************************************************************************/ -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "NBNetBuilder.h" -#include "NBEdgeCont.h" -#include "NBNodeCont.h" -#include "NBPTLineCont.h" -#include "NBHelpers.h" -#include "NBCont.h" -#include "NBTrafficLightLogicCont.h" -#include "NBDistrictCont.h" -#include "NBTypeCont.h" - -#define JOIN_TRAM_MAX_ANGLE 10 -#define JOIN_TRAM_MIN_LENGTH 3 - -//#define DEBUG_GUESS_ROUNDABOUT -//#define DEBUG_JOIN_TRAM -#define DEBUG_EDGE_ID "301241681#2" - -// =========================================================================== -// method definitions -// =========================================================================== -NBEdgeCont::NBEdgeCont(NBTypeCont& tc) : - myTypeCont(tc), - myEdgesSplit(0), - myVehicleClasses2Keep(0), - myVehicleClasses2Remove(0), - myNeedGeoTransformedPruningBoundary(false) { -} - - -NBEdgeCont::~NBEdgeCont() { - clear(); -} - - -void -NBEdgeCont::applyOptions(OptionsCont& oc) { - // set edges dismiss/accept options - myEdgesMinSpeed = oc.getFloat("keep-edges.min-speed"); - myRemoveEdgesAfterJoining = oc.exists("keep-edges.postload") && oc.getBool("keep-edges.postload"); - // we possibly have to load the edges to keep/remove - if (oc.isSet("keep-edges.input-file")) { - NBHelpers::loadEdgesFromFile(oc.getString("keep-edges.input-file"), myEdges2Keep); - } - if (oc.isSet("remove-edges.input-file")) { - NBHelpers::loadEdgesFromFile(oc.getString("remove-edges.input-file"), myEdges2Remove); - } - if (oc.isSet("keep-edges.explicit")) { - const std::vector edges = oc.getStringVector("keep-edges.explicit"); - myEdges2Keep.insert(edges.begin(), edges.end()); - } - if (oc.isSet("remove-edges.explicit")) { - const std::vector edges = oc.getStringVector("remove-edges.explicit"); - myEdges2Remove.insert(edges.begin(), edges.end()); - } - if (oc.exists("keep-edges.by-vclass") && oc.isSet("keep-edges.by-vclass")) { - myVehicleClasses2Keep = parseVehicleClasses(oc.getStringVector("keep-edges.by-vclass")); - } - if (oc.exists("remove-edges.by-vclass") && oc.isSet("remove-edges.by-vclass")) { - myVehicleClasses2Remove = parseVehicleClasses(oc.getStringVector("remove-edges.by-vclass")); - } - if (oc.exists("keep-edges.by-type") && oc.isSet("keep-edges.by-type")) { - const std::vector types = oc.getStringVector("keep-edges.by-type"); - myTypes2Keep.insert(types.begin(), types.end()); - } - if (oc.exists("remove-edges.by-type") && oc.isSet("remove-edges.by-type")) { - const std::vector types = oc.getStringVector("remove-edges.by-type"); - myTypes2Remove.insert(types.begin(), types.end()); - } - - if (oc.isSet("keep-edges.in-boundary") || oc.isSet("keep-edges.in-geo-boundary")) { - - std::string polyPlainString = oc.getValueString(oc.isSet("keep-edges.in-boundary") ? - "keep-edges.in-boundary" : "keep-edges.in-geo-boundary"); - // try interpreting the boundary like shape attribute with spaces - bool ok = true; - PositionVector boundaryShape = GeomConvHelper::parseShapeReporting(polyPlainString, "pruning-boundary", 0, ok, false, false); - if (ok) { - if (boundaryShape.size() < 2) { - throw ProcessError("Invalid boundary: need at least 2 coordinates"); - } else if (boundaryShape.size() == 2) { - // prunning boundary (box) - myPruningBoundary.push_back(boundaryShape[0]); - myPruningBoundary.push_back(Position(boundaryShape[1].x(), boundaryShape[0].y())); - myPruningBoundary.push_back(boundaryShape[1]); - myPruningBoundary.push_back(Position(boundaryShape[0].x(), boundaryShape[1].y())); - } else { - myPruningBoundary = boundaryShape; - } - } else { - // maybe positions are separated by ',' instead of ' ' - std::vector polyS = oc.getStringVector(oc.isSet("keep-edges.in-boundary") ? - "keep-edges.in-boundary" : "keep-edges.in-geo-boundary"); - std::vector poly; - for (std::vector::iterator i = polyS.begin(); i != polyS.end(); ++i) { - poly.push_back(StringUtils::toDouble((*i))); // !!! may throw something anyhow... - } - if (poly.size() < 4) { - throw ProcessError("Invalid boundary: need at least 2 coordinates"); - } else if (poly.size() % 2 != 0) { - throw ProcessError("Invalid boundary: malformed coordinate"); - } else if (poly.size() == 4) { - // prunning boundary (box) - myPruningBoundary.push_back(Position(poly[0], poly[1])); - myPruningBoundary.push_back(Position(poly[2], poly[1])); - myPruningBoundary.push_back(Position(poly[2], poly[3])); - myPruningBoundary.push_back(Position(poly[0], poly[3])); - } else { - for (std::vector::iterator j = poly.begin(); j != poly.end();) { - double x = *j++; - double y = *j++; - myPruningBoundary.push_back(Position(x, y)); - } - } - } - myNeedGeoTransformedPruningBoundary = oc.isSet("keep-edges.in-geo-boundary"); - } -} - - -void -NBEdgeCont::clear() { - for (EdgeCont::iterator i = myEdges.begin(); i != myEdges.end(); i++) { - delete ((*i).second); - } - myEdges.clear(); - for (EdgeCont::iterator i = myExtractedEdges.begin(); i != myExtractedEdges.end(); i++) { - delete ((*i).second); - } - myExtractedEdges.clear(); -} - - - -// ----- edge access methods -bool -NBEdgeCont::insert(NBEdge* edge, bool ignorePrunning) { - if (myEdges.count(edge->getID()) != 0) { - return false; - } - if (!ignorePrunning && ignoreFilterMatch(edge)) { - edge->getFromNode()->removeEdge(edge); - edge->getToNode()->removeEdge(edge); - myIgnoredEdges.insert(edge->getID()); - delete edge; - } else { - OptionsCont& oc = OptionsCont::getOptions(); - if (oc.exists("dismiss-vclasses") && oc.getBool("dismiss-vclasses")) { - edge->dismissVehicleClassInformation(); - } - myEdges[edge->getID()] = edge; - } - return true; -} - - -bool -NBEdgeCont::ignoreFilterMatch(NBEdge* edge) { - // remove edges which allow a speed below a set one (set using "keep-edges.min-speed") - if (edge->getSpeed() < myEdgesMinSpeed) { - return true; - } - // check whether the edge is a named edge to keep - if (!myRemoveEdgesAfterJoining && myEdges2Keep.size() != 0) { - if (myEdges2Keep.count(edge->getID()) == 0) { - // explicit whitelisting may be combined additively with other filters - if (myVehicleClasses2Keep == 0 && myVehicleClasses2Remove == 0 - && myTypes2Keep.size() == 0 && myTypes2Remove.size() == 0 - && myPruningBoundary.size() == 0) { - return true; - } - } else { - // explicit whitelisting overrides other filters - return false; - } - } - // check whether the edge is a named edge to remove - if (myEdges2Remove.size() != 0) { - if (myEdges2Remove.count(edge->getID()) != 0) { - return true; - } - } - // check whether the edge shall be removed because it does not allow any of the wished classes - if (myVehicleClasses2Keep != 0 && (myVehicleClasses2Keep & edge->getPermissions()) == 0) { - return true; - } - // check whether the edge shall be removed due to allowing unwished classes only - if (myVehicleClasses2Remove != 0 && (myVehicleClasses2Remove | edge->getPermissions()) == myVehicleClasses2Remove) { - return true; - } - // check whether the edge shall be removed because it does not have one of the requested types - if (myTypes2Keep.size() != 0) { - if (myTypes2Keep.count(edge->getTypeID()) == 0) { - return true; - } - } - // check whether the edge shall be removed because it has one of the forbidden types - if (myTypes2Remove.size() != 0) { - if (myTypes2Remove.count(edge->getTypeID()) > 0) { - return true; - } - } - // check whether the edge is within the pruning boundary - if (myPruningBoundary.size() != 0) { - if (myNeedGeoTransformedPruningBoundary) { - if (GeoConvHelper::getProcessing().usingGeoProjection()) { - NBNetBuilder::transformCoordinates(myPruningBoundary, false); - } else if (GeoConvHelper::getLoaded().usingGeoProjection()) { - // XXX what if input file with different projections are loaded? - for (int i = 0; i < (int) myPruningBoundary.size(); i++) { - GeoConvHelper::getLoaded().x2cartesian_const(myPruningBoundary[i]); - } - } else { - WRITE_ERROR("Cannot prune edges using a geo-boundary because no projection has been loaded"); - } - myNeedGeoTransformedPruningBoundary = false; - } - if (!(edge->getGeometry().getBoxBoundary().grow(POSITION_EPS).overlapsWith(myPruningBoundary))) { - return true; - } else if (!(edge->getGeometry().partialWithin(myPruningBoundary, 2 * POSITION_EPS) || edge->getGeometry().intersects(myPruningBoundary))) { - // a more detailed check is necessary because the bounding box may be much bigger than the edge - // @note: overlapsWith implicitly closes the edge shape but this is not wanted here - return true; - } - } - if (myTypeCont.knows(edge->getTypeID()) && myTypeCont.getShallBeDiscarded(edge->getTypeID())) { - return true; - } - return false; -} - - -NBEdge* -NBEdgeCont::retrieve(const std::string& id, bool retrieveExtracted) const { - EdgeCont::const_iterator i = myEdges.find(id); - if (i == myEdges.end()) { - if (retrieveExtracted) { - i = myExtractedEdges.find(id); - if (i == myExtractedEdges.end()) { - return nullptr; - } - } else { - return nullptr; - } - } - return (*i).second; -} - -// FIXME: This can't work -/* -NBEdge* -NBEdgeCont::retrievePossiblySplit(const std::string& id, bool downstream) const { - NBEdge* edge = retrieve(id); - if (edge == 0) { - return 0; - } - const EdgeVector* candidates = downstream ? &edge->getToNode()->getOutgoingEdges() : &edge->getFromNode()->getIncomingEdges(); - while (candidates->size() == 1) { - const std::string& nextID = candidates->front()->getID(); - if (nextID.find(id) != 0 || nextID.size() <= id.size() + 1 || (nextID[id.size()] != '.' && nextID[id.size()] != '-')) { - break; - } - edge = candidates->front(); - candidates = downstream ? &edge->getToNode()->getOutgoingEdges() : &edge->getFromNode()->getIncomingEdges(); - } - return edge; -}*/ - -NBEdge* -NBEdgeCont::retrievePossiblySplit(const std::string& id, bool downstream) const { - NBEdge* edge = retrieve(id); - if (edge != nullptr) { - return edge; - } - // NOTE: (TODO) for multiply split edges (e.g. 15[0][0]) one could try recursion - if ((retrieve(id + "[0]") != nullptr) && (retrieve(id + "[1]") != nullptr)) { - // Edge was split during the netbuilding process - if (downstream == true) { - return retrieve(id + "[1]"); - } else { - return retrieve(id + "[0]"); - } - } - return edge; -} - - -NBEdge* -NBEdgeCont::retrievePossiblySplit(const std::string& id, const std::string& hint, bool incoming) const { - // try to retrieve using the given name (iterative) - NBEdge* edge = retrieve(id); - if (edge != nullptr) { - return edge; - } - // now, we did not find it; we have to look over all possibilities - EdgeVector hints; - // check whether at least the hint was not splitted - NBEdge* hintedge = retrieve(hint); - if (hintedge == nullptr) { - hints = getGeneratedFrom(hint); - } else { - hints.push_back(hintedge); - } - EdgeVector candidates = getGeneratedFrom(id); - for (EdgeVector::iterator i = hints.begin(); i != hints.end(); i++) { - NBEdge* hintedge = (*i); - for (EdgeVector::iterator j = candidates.begin(); j != candidates.end(); j++) { - NBEdge* poss_searched = (*j); - NBNode* node = incoming - ? poss_searched->myTo : poss_searched->myFrom; - const EdgeVector& cont = incoming - ? node->getOutgoingEdges() : node->getIncomingEdges(); - if (find(cont.begin(), cont.end(), hintedge) != cont.end()) { - return poss_searched; - } - } - } - return nullptr; -} - - -NBEdge* -NBEdgeCont::retrievePossiblySplit(const std::string& id, double pos) const { - // check whether the edge was not split, yet - NBEdge* edge = retrieve(id); - if (edge != nullptr) { - return edge; - } - int maxLength = 0; - std::string tid = id + "["; - for (EdgeCont::const_iterator i = myEdges.begin(); i != myEdges.end(); ++i) { - if ((*i).first.find(tid) == 0) { - maxLength = MAX2(maxLength, (int)(*i).first.length()); - } - } - // find the part of the edge which matches the position - double seen = 0; - std::vector names; - names.push_back(id + "[1]"); - names.push_back(id + "[0]"); - while (names.size() > 0) { - // retrieve the first subelement (to follow) - std::string cid = names.back(); - names.pop_back(); - edge = retrieve(cid); - // The edge was splitted; check its subparts within the - // next step - if (edge == nullptr) { - if ((int)cid.length() + 3 < maxLength) { - names.push_back(cid + "[1]"); - names.push_back(cid + "[0]"); - } - } - // an edge with the name was found, - // check whether the position lies within it - else { - seen += edge->getLength(); - if (seen >= pos) { - return edge; - } - } - } - return nullptr; -} - - -void -NBEdgeCont::erase(NBDistrictCont& dc, NBEdge* edge) { - extract(dc, edge); - delete edge; -} - - -void -NBEdgeCont::extract(NBDistrictCont& dc, NBEdge* edge, bool remember) { - if (remember) { - myExtractedEdges[edge->getID()] = edge; - } - myEdges.erase(edge->getID()); - edge->myFrom->removeEdge(edge); - edge->myTo->removeEdge(edge); - dc.removeFromSinksAndSources(edge); -} - - -void -NBEdgeCont::rename(NBEdge* edge, const std::string& newID) { - if (myEdges.count(newID) != 0) { - throw ProcessError("Attempt to rename edge using existing id '" + newID + "'"); - } - myEdges.erase(edge->getID()); - edge->setID(newID); - myEdges[newID] = edge; -} - - -// ----- explicit edge manipulation methods - -void -NBEdgeCont::processSplits(NBEdge* e, std::vector splits, - NBNodeCont& nc, NBDistrictCont& dc, NBTrafficLightLogicCont& tlc) { - if (splits.size() == 0) { - return; - } - const std::string origID = e->getID(); - std::vector::iterator i; - sort(splits.begin(), splits.end(), split_sorter()); - int noLanesMax = e->getNumLanes(); - // compute the node positions and sort the lanes - for (i = splits.begin(); i != splits.end(); ++i) { - sort((*i).lanes.begin(), (*i).lanes.end()); - noLanesMax = MAX2(noLanesMax, (int)(*i).lanes.size()); - } - // split the edge - std::vector currLanes; - for (int l = 0; l < e->getNumLanes(); ++l) { - currLanes.push_back(l); - } - if (e->getNumLanes() != (int)splits.back().lanes.size()) { - // invalidate traffic light definitions loaded from a SUMO network - e->getToNode()->invalidateTLS(tlc, true, true); - // if the number of lanes changes the connections should be - // recomputed - e->invalidateConnections(true); - } - - std::string firstID = ""; - double seen = 0; - for (i = splits.begin(); i != splits.end(); ++i) { - const Split& exp = *i; - assert(exp.lanes.size() != 0); - if (exp.pos > 0 && e->getGeometry().length() + seen > exp.pos && exp.pos > seen) { - nc.insert(exp.node); - nc.markAsSplit(exp.node); - // split the edge - std::string idBefore = exp.idBefore == "" ? e->getID() : exp.idBefore; - std::string idAfter = exp.idAfter == "" ? exp.nameID : exp.idAfter; - if (firstID == "") { - firstID = idBefore; - } - const bool ok = splitAt(dc, e, exp.pos - seen, exp.node, - idBefore, idAfter, e->getNumLanes(), (int) exp.lanes.size(), exp.speed); - if (!ok) { - WRITE_WARNING("Error on parsing a split (edge '" + origID + "')."); - } - seen = exp.pos; - std::vector newLanes = exp.lanes; - NBEdge* pe = retrieve(idBefore); - NBEdge* ne = retrieve(idAfter); - // reconnect lanes - pe->invalidateConnections(true); - // new on right - int rightMostP = currLanes[0]; - int rightMostN = newLanes[0]; - for (int l = 0; l < (int) rightMostP - (int) rightMostN; ++l) { - pe->addLane2LaneConnection(0, ne, l, NBEdge::Lane2LaneInfoType::VALIDATED, true); - } - // new on left - int leftMostP = currLanes.back(); - int leftMostN = newLanes.back(); - for (int l = 0; l < (int) leftMostN - (int) leftMostP; ++l) { - pe->addLane2LaneConnection(pe->getNumLanes() - 1, ne, leftMostN - l - rightMostN, NBEdge::Lane2LaneInfoType::VALIDATED, true); - } - // all other connected - for (int l = 0; l < noLanesMax; ++l) { - if (find(currLanes.begin(), currLanes.end(), l) == currLanes.end()) { - continue; - } - if (find(newLanes.begin(), newLanes.end(), l) == newLanes.end()) { - continue; - } - pe->addLane2LaneConnection(l - rightMostP, ne, l - rightMostN, NBEdge::Lane2LaneInfoType::VALIDATED, true); - } - // if there are edges at this node which are not connected - // we can assume that this split was attached to an - // existing node. Reset all connections to let the default - // algorithm recompute them - if (exp.node->getIncomingEdges().size() > 1 || exp.node->getOutgoingEdges().size() > 1) { - for (NBEdge* in : exp.node->getIncomingEdges()) { - in->invalidateConnections(true); - } - } - // move to next - e = ne; - currLanes = newLanes; - } else if (exp.pos == 0) { - const int laneCountDiff = e->getNumLanes() - (int)exp.lanes.size(); - if (laneCountDiff < 0) { - e->incLaneNo(-laneCountDiff); - } else { - e->decLaneNo(laneCountDiff); - } - currLanes = exp.lanes; - // invalidate traffic light definition loaded from a SUMO network - // XXX it would be preferable to reconstruct the phase definitions heuristically - e->getFromNode()->invalidateTLS(tlc, true, true); - } else { - WRITE_WARNING("Split at '" + toString(exp.pos) + "' lies beyond the edge's length (edge '" + origID + "')."); - } - } - // patch lane offsets - e = retrieve(firstID); - if (splits.front().pos != 0) { - // add a dummy split at the beginning to ensure correct offset - Split start; - start.pos = 0; - for (int lane = 0; lane < (int)e->getNumLanes(); ++lane) { - start.lanes.push_back(lane); - } - start.offset = splits.front().offset; - start.offsetFactor = splits.front().offsetFactor; - splits.insert(splits.begin(), start); - } - i = splits.begin(); - if (e != nullptr) { - for (; i != splits.end(); ++i) { - int maxLeft = (*i).lanes.back(); - double offset = (*i).offset; - if (maxLeft < noLanesMax) { - if (e->getLaneSpreadFunction() == LaneSpreadFunction::RIGHT) { - offset += (*i).offsetFactor * SUMO_const_laneWidthAndOffset * (noLanesMax - 1 - maxLeft); - } else { - offset += (*i).offsetFactor * SUMO_const_halfLaneAndOffset * (noLanesMax - 1 - maxLeft); - } - } - int maxRight = (*i).lanes.front(); - if (maxRight > 0 && e->getLaneSpreadFunction() == LaneSpreadFunction::CENTER) { - offset -= (*i).offsetFactor * SUMO_const_halfLaneAndOffset * maxRight; - } - //std::cout << " processSplits " << origID << " splitOffset=" << (*i).offset << " offset=" << offset << "\n"; - if (offset != 0) { - PositionVector g = e->getGeometry(); - g.move2side(offset); - e->setGeometry(g); - } - if (e->getToNode()->getOutgoingEdges().size() != 0) { - e = e->getToNode()->getOutgoingEdges()[0]; - } - } - } -} - - -bool -NBEdgeCont::splitAt(NBDistrictCont& dc, NBEdge* edge, NBNode* node) { - return splitAt(dc, edge, node, edge->getID() + "[0]", edge->getID() + "[1]", - (int) edge->myLanes.size(), (int) edge->myLanes.size()); -} - - -bool -NBEdgeCont::splitAt(NBDistrictCont& dc, NBEdge* edge, NBNode* node, - const std::string& firstEdgeName, - const std::string& secondEdgeName, - int noLanesFirstEdge, int noLanesSecondEdge, - const double speed, - const int changedLeft) { - double pos; - pos = edge->getGeometry().nearest_offset_to_point2D(node->getPosition()); - if (pos <= 0) { - pos = GeomHelper::nearest_offset_on_line_to_point2D( - edge->myFrom->getPosition(), edge->myTo->getPosition(), - node->getPosition()); - } - if (pos <= 0 || pos + POSITION_EPS > edge->getGeometry().length()) { - return false; - } - return splitAt(dc, edge, pos, node, firstEdgeName, secondEdgeName, - noLanesFirstEdge, noLanesSecondEdge, speed, changedLeft); -} - - -bool -NBEdgeCont::splitAt(NBDistrictCont& dc, - NBEdge* edge, double pos, NBNode* node, - const std::string& firstEdgeName, - const std::string& secondEdgeName, - int noLanesFirstEdge, int noLanesSecondEdge, - const double speed, - const int changedLeft - ) { - // there must be at least some overlap between first and second edge - assert(changedLeft > -((int)noLanesFirstEdge)); - assert(changedLeft < (int)noLanesSecondEdge); - - // build the new edges' geometries - std::pair geoms = - edge->getGeometry().splitAt(pos); - // build and insert the edges - NBEdge* one = new NBEdge(firstEdgeName, edge->myFrom, node, edge, geoms.first, noLanesFirstEdge); - NBEdge* two = new NBEdge(secondEdgeName, node, edge->myTo, edge, geoms.second, noLanesSecondEdge); - if (OptionsCont::getOptions().getBool("output.original-names")) { - const std::string origID = edge->getLaneStruct(0).getParameter(SUMO_PARAM_ORIGID, edge->getID()); - if (firstEdgeName != origID) { - one->setOrigID(origID); - } - if (secondEdgeName != origID) { - two->setOrigID(origID); - } - } - two->copyConnectionsFrom(edge); - if (speed != -1.) { - two->setSpeed(-1, speed); - } - // replace information about this edge within the nodes - edge->myFrom->replaceOutgoing(edge, one, 0); - edge->myTo->replaceIncoming(edge, two, 0); - // patch tls - std::set fromTLS = edge->myFrom->getControllingTLS(); - for (std::set::iterator i = fromTLS.begin(); i != fromTLS.end(); ++i) { - (*i)->replaceRemoved(edge, -1, one, -1, false); - } - std::set toTLS = edge->myTo->getControllingTLS(); - for (std::set::iterator i = toTLS.begin(); i != toTLS.end(); ++i) { - (*i)->replaceRemoved(edge, -1, two, -1, true); - } - // the edge is now occuring twice in both nodes... - // clean up - edge->myFrom->removeDoubleEdges(); - edge->myTo->removeDoubleEdges(); - // add connections from the first to the second edge - // there will be as many connections as there are lanes on the second edge - // by default lanes will be added / discontinued on the right side - // (appropriate for highway on-/off-ramps) - const int offset = (int)one->getNumLanes() - (int)two->getNumLanes() + changedLeft; - for (int i2 = 0; i2 < (int)two->getNumLanes(); i2++) { - const int i1 = MIN2(MAX2((int)0, i2 + offset), (int)one->getNumLanes()); - if (!one->addLane2LaneConnection(i1, two, i2, NBEdge::Lane2LaneInfoType::COMPUTED)) { - throw ProcessError("Could not set connection!"); - } - } - if (myRemoveEdgesAfterJoining) { - if (myEdges2Keep.count(edge->getID()) != 0) { - myEdges2Keep.insert(one->getID()); - myEdges2Keep.insert(two->getID()); - } - if (myEdges2Remove.count(edge->getID()) != 0) { - myEdges2Remove.insert(one->getID()); - myEdges2Remove.insert(two->getID()); - } - } - // erase the splitted edge - patchRoundabouts(edge, one, two, myRoundabouts); - patchRoundabouts(edge, one, two, myGuessedRoundabouts); - const std::string oldID = edge->getID(); - extract(dc, edge); - if (!insert(one, true)) { - WRITE_ERROR("Could not insert edge '" + one->getID() + "' before split of edge '" + oldID + "'"); - }; - if (!insert(two, true)) { - WRITE_ERROR("Could not insert edge '" + two->getID() + "' after split of edge '" + oldID + "'"); - } - myEdgesSplit++; - return true; -} - - -void -NBEdgeCont::patchRoundabouts(NBEdge* orig, NBEdge* part1, NBEdge* part2, std::set& roundabouts) { - std::set addLater; - for (std::set::iterator it = roundabouts.begin(); it != roundabouts.end(); ++it) { - EdgeSet roundaboutSet = *it; - if (roundaboutSet.count(orig) > 0) { - roundaboutSet.erase(orig); - roundaboutSet.insert(part1); - roundaboutSet.insert(part2); - } - addLater.insert(roundaboutSet); - } - roundabouts.clear(); - roundabouts.insert(addLater.begin(), addLater.end()); -} - - -// ----- container access methods -std::vector -NBEdgeCont::getAllNames() const { - std::vector ret; - for (EdgeCont::const_iterator i = myEdges.begin(); i != myEdges.end(); ++i) { - ret.push_back((*i).first); - } - return ret; -} - - -// ----- Adapting the input -void -NBEdgeCont::removeUnwishedEdges(NBDistrictCont& dc) { - EdgeVector toRemove; - for (EdgeCont::iterator i = myEdges.begin(); i != myEdges.end(); ++i) { - NBEdge* edge = (*i).second; - if (!myEdges2Keep.count(edge->getID())) { - edge->getFromNode()->removeEdge(edge); - edge->getToNode()->removeEdge(edge); - toRemove.push_back(edge); - } - } - for (EdgeVector::iterator j = toRemove.begin(); j != toRemove.end(); ++j) { - erase(dc, *j); - } -} - - -void -NBEdgeCont::splitGeometry(NBDistrictCont& dc, NBNodeCont& nc) { - // make a copy of myEdges because splitting will modify it - EdgeCont edges = myEdges; - for (auto& item : edges) { - NBEdge* edge = item.second; - if (edge->getGeometry().size() < 3) { - continue; - } - PositionVector geom = edge->getGeometry(); - const std::string id = edge->getID(); - double offset = 0; - for (int i = 1; i < (int)geom.size() - 1; i++) { - offset += geom[i - 1].distanceTo(geom[i]); - std::string nodeID = id + "." + toString((int)offset); - if (!nc.insert(nodeID, geom[i])) { - WRITE_WARNING("Could not split geometry of edge '" + id + "' at index " + toString(i)); - continue; - } - NBNode* node = nc.retrieve(nodeID); - splitAt(dc, edge, node, edge->getID(), nodeID, edge->getNumLanes(), edge->getNumLanes()); - edge = retrieve(nodeID); - } - } -} - - -void -NBEdgeCont::reduceGeometries(const double minDist) { - for (EdgeCont::iterator i = myEdges.begin(); i != myEdges.end(); ++i) { - (*i).second->reduceGeometry(minDist); - } -} - - -void -NBEdgeCont::checkGeometries(const double maxAngle, const double minRadius, bool fix, bool fixRailways, bool silent) { - if (maxAngle > 0 || minRadius > 0) { - for (auto& item : myEdges) { - if (isSidewalk(item.second->getPermissions()) || isForbidden(item.second->getPermissions())) { - continue; - } - item.second->checkGeometry(maxAngle, minRadius, fix || (fixRailways && isRailway(item.second->getPermissions())), silent); - } - } -} - - -// ----- processing methods -void -NBEdgeCont::clearControllingTLInformation() const { - for (EdgeCont::const_iterator i = myEdges.begin(); i != myEdges.end(); i++) { - (*i).second->clearControllingTLInformation(); - } -} - - -void -NBEdgeCont::sortOutgoingLanesConnections() { - for (EdgeCont::iterator i = myEdges.begin(); i != myEdges.end(); i++) { - (*i).second->sortOutgoingConnectionsByAngle(); - } -} - - -void -NBEdgeCont::computeEdge2Edges(bool noLeftMovers) { - for (EdgeCont::iterator i = myEdges.begin(); i != myEdges.end(); i++) { - (*i).second->computeEdge2Edges(noLeftMovers); - } -} - - -void -NBEdgeCont::computeLanes2Edges() { - for (EdgeCont::iterator i = myEdges.begin(); i != myEdges.end(); i++) { - (*i).second->computeLanes2Edges(); - } -} - - -void -NBEdgeCont::recheckLanes() { - const bool fixOppositeLengths = OptionsCont::getOptions().getBool("opposites.guess.fix-lengths"); - for (EdgeCont::iterator i = myEdges.begin(); i != myEdges.end(); i++) { - NBEdge* edge = i->second; - edge->recheckLanes(); - // check opposites - if (edge->getNumLanes() > 0) { - const std::string& oppositeID = edge->getLanes().back().oppositeID; - if (oppositeID != "" && oppositeID != "-") { - NBEdge* oppEdge = retrieve(oppositeID.substr(0, oppositeID.rfind("_"))); - if (oppEdge == nullptr || oppEdge->getLaneID(oppEdge->getNumLanes() - 1) != oppositeID) { - WRITE_WARNING("Removing unknown opposite lane '" + oppositeID + "' for edge '" + edge->getID() + "'."); - edge->getLaneStruct(edge->getNumLanes() - 1).oppositeID = ""; - continue; - } - if (fabs(oppEdge->getLoadedLength() - edge->getLoadedLength()) > NUMERICAL_EPS) { - if (fixOppositeLengths) { - const double avgLength = 0.5 * (edge->getFinalLength() + oppEdge->getFinalLength()); - WRITE_WARNING("Averaging edge lengths for lane '" + oppositeID + "' (length " + toString(oppEdge->getLoadedLength()) + ") and edge '" + edge->getID() + "' (length " - + toString(edge->getLoadedLength()) + ")."); - edge->setLoadedLength(avgLength); - oppEdge->setLoadedLength(avgLength); - } else { - WRITE_ERROR("Opposite lane '" + oppositeID + "' (length " + toString(oppEdge->getLoadedLength()) + ") differs in length from edge '" + edge->getID() + "' (length " - + toString(edge->getLoadedLength()) + "). Set --opposites.guess.fix-lengths to fix this."); - edge->getLaneStruct(edge->getNumLanes() - 1).oppositeID = ""; - continue; - } - } - if (oppEdge->getFromNode() != edge->getToNode() || oppEdge->getToNode() != edge->getFromNode()) { - WRITE_ERROR("Opposite lane '" + oppositeID + "' does not connect the same nodes as edge '" + edge->getID() + "'!"); - edge->getLaneStruct(edge->getNumLanes() - 1).oppositeID = ""; - } - } - // check oppositeID stored in other lanes - for (int i = 0; i < (int)edge->getNumLanes() - 1; i++) { - const std::string& oppositeID = edge->getLanes()[i].oppositeID; - if (oppositeID != "" && oppositeID != "-") { - WRITE_WARNING("Removing unknown opposite lane '" + oppositeID + "' for lane '" + edge->getLaneID(i) + "'."); - edge->getLaneStruct(i).oppositeID = ""; - } - } - } - } -} - - -void -NBEdgeCont::appendTurnarounds(bool noTLSControlled, bool noFringe, bool onlyDeadends, bool onlyTurnlane, bool noGeometryLike) { - for (EdgeCont::iterator i = myEdges.begin(); i != myEdges.end(); i++) { - (*i).second->appendTurnaround(noTLSControlled, noFringe, onlyDeadends, onlyTurnlane, noGeometryLike, true); - } -} - - -void -NBEdgeCont::appendTurnarounds(const std::set& ids, bool noTLSControlled) { - for (std::set::const_iterator it = ids.begin(); it != ids.end(); it++) { - myEdges[*it]->appendTurnaround(noTLSControlled, false, false, false, false, false); - } -} - - -void -NBEdgeCont::appendRailwayTurnarounds(const NBPTStopCont& sc) { - std::set stopEdgeIDs; - for (auto& stopItem : sc.getStops()) { - stopEdgeIDs.insert(stopItem.second->getEdgeId()); - } - for (auto& item : myEdges) { - NBEdge* edge = item.second; - if (edge->isBidiRail() - && (stopEdgeIDs.count(item.first) > 0 || - stopEdgeIDs.count(edge->getTurnDestination(true)->getID()) > 0)) { - NBEdge* to = edge->getTurnDestination(true); - assert(to != 0); - edge->setConnection(edge->getNumLanes() - 1, - to, to->getNumLanes() - 1, NBEdge::Lane2LaneInfoType::VALIDATED, false, false, true, - NBEdge::UNSPECIFIED_CONTPOS, NBEdge::UNSPECIFIED_VISIBILITY_DISTANCE, - SUMO_const_haltingSpeed); - } - } -} - -void -NBEdgeCont::computeEdgeShapes(double smoothElevationThreshold) { - for (EdgeCont::iterator i = myEdges.begin(); i != myEdges.end(); i++) { - (*i).second->computeEdgeShape(smoothElevationThreshold); - } - // equalize length of opposite edges - for (EdgeCont::iterator i = myEdges.begin(); i != myEdges.end(); i++) { - NBEdge* edge = i->second; - const std::string& oppositeID = edge->getLanes().back().oppositeID; - if (oppositeID != "" && oppositeID != "-") { - NBEdge* oppEdge = retrieve(oppositeID.substr(0, oppositeID.rfind("_"))); - if (oppEdge == nullptr || oppEdge->getLaneID(oppEdge->getNumLanes() - 1) != oppositeID) { - continue; - } - if (fabs(oppEdge->getLength() - edge->getLength()) > NUMERICAL_EPS) { - double avgLength = (oppEdge->getLength() + edge->getLength()) / 2; - edge->setAverageLengthWithOpposite(avgLength); - oppEdge->setAverageLengthWithOpposite(avgLength); - } - } - } -} - - -void -NBEdgeCont::computeLaneShapes() { - for (EdgeCont::iterator i = myEdges.begin(); i != myEdges.end(); ++i) { - (*i).second->computeLaneShapes(); - } -} - - -void -NBEdgeCont::joinSameNodeConnectingEdges(NBDistrictCont& dc, - NBTrafficLightLogicCont& tlc, - EdgeVector edges) { - // !!! Attention! - // No merging of the geometry to come is being done - // The connections are moved from one edge to another within - // the replacement where the edge is a node's incoming edge. - - // count the number of lanes, the speed and the id - int nolanes = 0; - double speed = 0; - int priority = 0; - std::string id; - sort(edges.begin(), edges.end(), NBContHelper::same_connection_edge_sorter()); - // retrieve the connected nodes - NBEdge* tpledge = *(edges.begin()); - NBNode* from = tpledge->getFromNode(); - NBNode* to = tpledge->getToNode(); - EdgeVector::const_iterator i; - for (i = edges.begin(); i != edges.end(); i++) { - // some assertions - assert((*i)->getFromNode() == from); - assert((*i)->getToNode() == to); - // ad the number of lanes the current edge has - nolanes += (*i)->getNumLanes(); - // build the id - if (i != edges.begin()) { - id += "+"; - } - id += (*i)->getID(); - // compute the speed - speed += (*i)->getSpeed(); - // build the priority - priority = MAX2(priority, (*i)->getPriority()); - } - speed /= edges.size(); - // build the new edge - NBEdge* newEdge = new NBEdge(id, from, to, "", speed, nolanes, priority, - NBEdge::UNSPECIFIED_WIDTH, NBEdge::UNSPECIFIED_OFFSET, - tpledge->getStreetName(), tpledge->myLaneSpreadFunction); - // copy lane attributes - int laneIndex = 0; - for (i = edges.begin(); i != edges.end(); ++i) { - const std::vector& lanes = (*i)->getLanes(); - for (int j = 0; j < (int)lanes.size(); ++j) { - newEdge->setPermissions(lanes[j].permissions, laneIndex); - newEdge->setLaneWidth(laneIndex, lanes[j].width); - newEdge->setEndOffset(laneIndex, lanes[j].endOffset); - laneIndex++; - } - } - insert(newEdge, true); - // replace old edge by current within the nodes - // and delete the old - from->replaceOutgoing(edges, newEdge); - to->replaceIncoming(edges, newEdge); - // patch connections - // add edge2edge-information - for (i = edges.begin(); i != edges.end(); i++) { - EdgeVector ev = (*i)->getConnectedEdges(); - for (EdgeVector::iterator j = ev.begin(); j != ev.end(); j++) { - newEdge->addEdge2EdgeConnection(*j); - } - } - // copy outgoing connections to the new edge - int currLane = 0; - for (i = edges.begin(); i != edges.end(); i++) { - newEdge->moveOutgoingConnectionsFrom(*i, currLane); - currLane += (*i)->getNumLanes(); - } - // patch tl-information - currLane = 0; - for (i = edges.begin(); i != edges.end(); i++) { - int noLanes = (*i)->getNumLanes(); - for (int j = 0; j < noLanes; j++, currLane++) { - // replace in traffic lights - tlc.replaceRemoved(*i, j, newEdge, currLane, true); - tlc.replaceRemoved(*i, j, newEdge, currLane, false); - } - } - // delete joined edges - for (i = edges.begin(); i != edges.end(); i++) { - extract(dc, *i, true); - } -} - - -void -NBEdgeCont::guessOpposites() { - //@todo magic values - const double distanceThreshold = 7; - for (EdgeCont::iterator i = myEdges.begin(); i != myEdges.end(); ++i) { - NBEdge* edge = i->second; - const int numLanes = edge->getNumLanes(); - if (numLanes > 0) { - NBEdge::Lane& lastLane = edge->getLaneStruct(numLanes - 1); - if (lastLane.oppositeID == "") { - NBEdge* opposite = nullptr; - //double minOppositeDist = std::numeric_limits::max(); - for (EdgeVector::const_iterator j = edge->getToNode()->getOutgoingEdges().begin(); j != edge->getToNode()->getOutgoingEdges().end(); ++j) { - if ((*j)->getToNode() == edge->getFromNode() && !(*j)->getLanes().empty()) { - const double distance = VectorHelper::maxValue(lastLane.shape.distances((*j)->getLanes().back().shape)); - if (distance < distanceThreshold) { - //minOppositeDist = distance; - opposite = *j; - } - } - } - if (opposite != nullptr) { - lastLane.oppositeID = opposite->getLaneID(opposite->getNumLanes() - 1); - } - } - } - } -} - - -void -NBEdgeCont::recheckLaneSpread() { - for (EdgeCont::iterator i = myEdges.begin(); i != myEdges.end(); ++i) { - NBEdge* opposite = getOppositeByID(i->first); - if (opposite != nullptr) { - i->second->setLaneSpreadFunction(LaneSpreadFunction::RIGHT); - opposite->setLaneSpreadFunction(LaneSpreadFunction::RIGHT); - } else { - i->second->setLaneSpreadFunction(LaneSpreadFunction::CENTER); - } - } -} - - -NBEdge* -NBEdgeCont::getOppositeByID(const std::string& edgeID) const { - const std::string oppositeID = edgeID[0] == '-' ? edgeID.substr(1) : "-" + edgeID; - EdgeCont::const_iterator it = myEdges.find(oppositeID); - return it != myEdges.end() ? it->second : (NBEdge*)nullptr; -} - -NBEdge* -NBEdgeCont::getByID(const std::string& edgeID) const { - EdgeCont::const_iterator it = myEdges.find(edgeID); - return it != myEdges.end() ? it->second : (NBEdge*)nullptr; -} - -// ----- other -void -NBEdgeCont::addPostProcessConnection(const std::string& from, int fromLane, const std::string& to, int toLane, bool mayDefinitelyPass, - bool keepClear, double contPos, double visibility, double speed, double length, - const PositionVector& customShape, bool uncontrolled, bool warnOnly, SVCPermissions permissions) { - myConnections[from].push_back(PostProcessConnection(from, fromLane, to, toLane, mayDefinitelyPass, keepClear, contPos, visibility, - speed, length, customShape, uncontrolled, warnOnly, permissions)); -} - -bool -NBEdgeCont::hasPostProcessConnection(const std::string& from, const std::string& to) { - if (myConnections.count(from) == 0) { - return false; - } else { - if (to == "") { - // wildcard - return true; - } - for (const auto& ppc : myConnections[from]) { - if (ppc.to == to) { - return true; - } - } - return false; - } -} - -void -NBEdgeCont::recheckPostProcessConnections() { - const bool warnOnly = OptionsCont::getOptions().exists("ignore-errors.connections") && OptionsCont::getOptions().getBool("ignore-errors.connections"); - for (const auto& item : myConnections) { - for (std::vector::const_iterator i = item.second.begin(); i != item.second.end(); ++i) { - NBEdge* from = retrievePossiblySplit((*i).from, true); - NBEdge* to = retrievePossiblySplit((*i).to, false); - if (from == nullptr || to == nullptr || - !from->addLane2LaneConnection((*i).fromLane, to, (*i).toLane, NBEdge::Lane2LaneInfoType::USER, true, (*i).mayDefinitelyPass, - (*i).keepClear, (*i).contPos, (*i).visibility, (*i).speed, (*i).customLength, (*i).customShape, - (*i).uncontrolled, SVC_UNSPECIFIED, - true)) { - const std::string msg = "Could not insert connection between '" + (*i).from + "' and '" + (*i).to + "' after build."; - if (warnOnly || (*i).warnOnly) { - WRITE_WARNING(msg); - } else { - WRITE_ERROR(msg); - } - } - } - } - // during loading we also kept some ambiguous connections in hope they might be valid after processing - // we need to make sure that all invalid connections are removed now - for (EdgeCont::iterator it = myEdges.begin(); it != myEdges.end(); ++it) { - NBEdge* edge = it->second; - NBNode* to = edge->getToNode(); - // make a copy because we may delete connections - std::vector connections = edge->getConnections(); - for (std::vector::iterator it_con = connections.begin(); it_con != connections.end(); ++it_con) { - NBEdge::Connection& c = *it_con; - if (c.toEdge != nullptr && c.toEdge->getFromNode() != to) { - WRITE_WARNING("Found and removed invalid connection from edge '" + edge->getID() + - "' to edge '" + c.toEdge->getID() + "' via junction '" + to->getID() + "'."); - edge->removeFromConnections(c.toEdge); - } - } - } -} - - -EdgeVector -NBEdgeCont::getGeneratedFrom(const std::string& id) const { - int len = (int)id.length(); - EdgeVector ret; - for (EdgeCont::const_iterator i = myEdges.begin(); i != myEdges.end(); ++i) { - std::string curr = (*i).first; - // the next check makes it possibly faster - we don not have - // to compare the names - if ((int)curr.length() <= len) { - continue; - } - // the name must be the same as the given id but something - // beginning with a '[' must be appended to it - if (curr.substr(0, len) == id && curr[len] == '[') { - ret.push_back((*i).second); - continue; - } - // ok, maybe the edge is a compound made during joining of edges - std::string::size_type pos = curr.find(id); - // surely not - if (pos == std::string::npos) { - continue; - } - // check leading char - if (pos > 0) { - if (curr[pos - 1] != ']' && curr[pos - 1] != '+') { - // actually, this is another id - continue; - } - } - if (pos + id.length() < curr.length()) { - if (curr[pos + id.length()] != '[' && curr[pos + id.length()] != '+') { - // actually, this is another id - continue; - } - } - ret.push_back((*i).second); - } - return ret; -} - - -int -NBEdgeCont::guessRoundabouts() { - myGuessedRoundabouts.clear(); - std::set loadedRoundaboutEdges; - for (std::set::const_iterator it = myRoundabouts.begin(); it != myRoundabouts.end(); ++it) { - loadedRoundaboutEdges.insert(it->begin(), it->end()); - } - // step 1: keep only those edges which have no turnarounds and which are not - // part of a loaded roundabout - std::set candidates; - SVCPermissions valid = SVCAll & ~SVC_PEDESTRIAN; - for (EdgeCont::const_iterator i = myEdges.begin(); i != myEdges.end(); ++i) { - NBEdge* e = (*i).second; - NBNode* const to = e->getToNode(); - if (e->getTurnDestination() == nullptr - && to->getConnectionTo(e->getFromNode()) == nullptr - && loadedRoundaboutEdges.count(e) == 0 - && (e->getPermissions() & valid) != 0) { - candidates.insert(e); - } - } - - // step 2: - std::set visited; - for (std::set::const_iterator i = candidates.begin(); i != candidates.end(); ++i) { - EdgeVector loopEdges; - // start with a random edge (this doesn't have to be a roundabout edge) - // loop over connected edges (using always the leftmost one) - // and keep the list in loopEdges - // continue until we loop back onto a loopEdges and extract the loop - NBEdge* e = (*i); - if (visited.count(e) > 0) { - // already seen - continue; - } - loopEdges.push_back(e); - bool doLoop = true; -#ifdef DEBUG_GUESS_ROUNDABOUT - gDebugFlag1 = false; -#endif - do { -#ifdef DEBUG_GUESS_ROUNDABOUT - if (e->getID() == DEBUG_EDGE_ID || gDebugFlag1) { - std::cout << " e=" << e->getID() << " loopEdges=" << toString(loopEdges) << "\n"; - gDebugFlag1 = true; - } -#endif - visited.insert(e); - const EdgeVector& edges = e->getToNode()->getEdges(); - if (e->getToNode()->getType() == SumoXMLNodeType::RIGHT_BEFORE_LEFT && !e->getToNode()->typeWasGuessed()) { - doLoop = false; -#ifdef DEBUG_GUESS_ROUNDABOUT - if (gDebugFlag1) { - std::cout << " rbl\n"; - } - gDebugFlag1 = false; -#endif - break; - } - if (edges.size() < 2) { - doLoop = false; -#ifdef DEBUG_GUESS_ROUNDABOUT - if (gDebugFlag1) { - std::cout << " deadend\n"; - } - gDebugFlag1 = false; -#endif - break; - } - if (e->getTurnDestination() != nullptr || e->getToNode()->getConnectionTo(e->getFromNode()) != nullptr) { - // do not follow turn-arounds while in a (tentative) loop - doLoop = false; -#ifdef DEBUG_GUESS_ROUNDABOUT - if (gDebugFlag1) { - std::cout << " turn\n"; - } - gDebugFlag1 = false; -#endif - break; - } - EdgeVector::const_iterator me = std::find(edges.begin(), edges.end(), e); - NBContHelper::nextCW(edges, me); - NBEdge* left = *me; - while ((left->getPermissions() & valid) == 0 && left != e) { - NBContHelper::nextCW(edges, me); - left = *me; - } - if (left == e) { - // no usable continuation edge found - doLoop = false; -#ifdef DEBUG_GUESS_ROUNDABOUT - if (gDebugFlag1) { - std::cout << " noContinuation\n"; - } - gDebugFlag1 = false; -#endif - break; - } - NBContHelper::nextCW(edges, me); - NBEdge* nextLeft = *me; - double angle = fabs(NBHelpers::relAngle(e->getAngleAtNode(e->getToNode()), left->getAngleAtNode(e->getToNode()))); - double nextAngle = nextLeft == e ? 180 : fabs(NBHelpers::relAngle(e->getAngleAtNode(e->getToNode()), nextLeft->getAngleAtNode(e->getToNode()))); -#ifdef DEBUG_GUESS_ROUNDABOUT - if (gDebugFlag1) { - std::cout << " angle=" << angle << " nextAngle=" << nextAngle << "\n"; - } -#endif - if (angle >= 120 - || (angle >= 90 && - // if the edges are long or the junction shape is small we should expect roundness (low angles) - (MAX2(e->getLength(), left->getLength()) > 5 - || e->getLaneShape(0).back().distanceTo2D(left->getLaneShape(0).front()) < 10 - // there should be no straigher edge further left - || (nextAngle < 45) - ))) { - // roundabouts do not have sharp turns (or they wouldn't be called 'round') - // however, if the roundabout is very small then most of the roundness may be in the junction so the angle may be as high as 120 - doLoop = false; -#ifdef DEBUG_GUESS_ROUNDABOUT - if (gDebugFlag1) { - std::cout << " angle=" << angle << "\n"; - } - gDebugFlag1 = false; -#endif - break; - } - EdgeVector::const_iterator loopClosed = std::find(loopEdges.begin(), loopEdges.end(), left); - const int loopSize = (int)(loopEdges.end() - loopClosed); - if (loopSize > 0) { - // loop found - if (loopSize < 3) { - doLoop = false; // need at least 3 edges for a roundabout - } else if (loopSize < (int)loopEdges.size()) { - // remove initial edges not belonging to the loop - EdgeVector(loopEdges.begin() + (loopEdges.size() - loopSize), loopEdges.end()).swap(loopEdges); - } - // count attachments to the outside. need at least 3 or a roundabout doesn't make much sense - int attachments = 0; - for (EdgeVector::const_iterator j = loopEdges.begin(); j != loopEdges.end(); ++j) { - if ((*j)->getToNode()->getEdges().size() > 2) { - attachments++; - } - } - if (attachments < 3) { - doLoop = false; -#ifdef DEBUG_GUESS_ROUNDABOUT - if (gDebugFlag1) { - std::cout << " attachments=" << attachments << "\n"; - } - gDebugFlag1 = false; -#endif - } - break; - } - if (visited.count(left) > 0) { - doLoop = false; - } else { - // keep going - loopEdges.push_back(left); - e = left; - } - } while (doLoop); -#ifdef DEBUG_GUESS_ROUNDABOUT - gDebugFlag1 = false; -#endif - if (doLoop) { - // check form factor to avoid elongated shapes (circle: 1, square: ~0.79) - if (formFactor(loopEdges) > 0.6) { - // collected edges are marked in markRoundabouts - myGuessedRoundabouts.insert(EdgeSet(loopEdges.begin(), loopEdges.end())); - } - } - } - return (int)myGuessedRoundabouts.size(); -} - - -double -NBEdgeCont::formFactor(const EdgeVector& loopEdges) { - PositionVector points; - for (EdgeVector::const_iterator it = loopEdges.begin(); it != loopEdges.end(); ++it) { - points.append((*it)->getGeometry()); - } - double circumference = points.length2D(); - return 4 * M_PI * points.area() / (circumference * circumference); -} - - -const std::set -NBEdgeCont::getRoundabouts() const { - std::set result = myRoundabouts; - result.insert(myGuessedRoundabouts.begin(), myGuessedRoundabouts.end()); - return result; -} - - -void -NBEdgeCont::addRoundabout(const EdgeSet& roundabout) { - if (roundabout.size() > 0) { - if (find(myRoundabouts.begin(), myRoundabouts.end(), roundabout) != myRoundabouts.end()) { - WRITE_WARNING("Ignoring duplicate roundabout: " + toString(roundabout)); - } else { - myRoundabouts.insert(roundabout); - } - } -} - -void -NBEdgeCont::removeRoundabout(const NBNode* node) { - for (auto it = myRoundabouts.begin(); it != myRoundabouts.end(); ++it) { - for (NBEdge* e : *it) { - if (e->getToNode() == node) { - myRoundabouts.erase(it); - return; - } - } - } -} - - -void -NBEdgeCont::markRoundabouts() { - for (const EdgeSet& roundaboutSet : getRoundabouts()) { - for (NBEdge* const edge : roundaboutSet) { - // disable turnarounds on incoming edges - NBNode* const node = edge->getToNode(); - for (NBEdge* const inEdge : node->getIncomingEdges()) { - if (roundaboutSet.count(inEdge) > 0) { - continue; - } - if (inEdge->getStep() >= NBEdge::EdgeBuildingStep::LANES2LANES_USER) { - continue; - } - if (inEdge->getTurnDestination() != nullptr) { - inEdge->removeFromConnections(inEdge->getTurnDestination(), -1); - } - } - // let the connections to succeeding roundabout edge have a higher priority - edge->setJunctionPriority(node, NBEdge::JunctionPriority::ROUNDABOUT); - edge->setJunctionPriority(edge->getFromNode(), NBEdge::JunctionPriority::ROUNDABOUT); - node->setRoundabout(); - } - } -} - - -void -NBEdgeCont::generateStreetSigns() { - for (EdgeCont::iterator i = myEdges.begin(); i != myEdges.end(); ++i) { - NBEdge* e = i->second; - const double offset = MAX2(0., e->getLength() - 3); - if (e->getToNode()->isSimpleContinuation(false)) { - // not a "real" junction? - continue; - } - const SumoXMLNodeType nodeType = e->getToNode()->getType(); - switch (nodeType) { - case SumoXMLNodeType::PRIORITY: - // yield or major? - if (e->getJunctionPriority(e->getToNode()) > 0) { - e->addSign(NBSign(NBSign::SIGN_TYPE_PRIORITY, offset)); - } else { - e->addSign(NBSign(NBSign::SIGN_TYPE_YIELD, offset)); - } - break; - case SumoXMLNodeType::PRIORITY_STOP: - // yield or major? - if (e->getJunctionPriority(e->getToNode()) > 0) { - e->addSign(NBSign(NBSign::SIGN_TYPE_PRIORITY, offset)); - } else { - e->addSign(NBSign(NBSign::SIGN_TYPE_STOP, offset)); - } - break; - case SumoXMLNodeType::ALLWAY_STOP: - e->addSign(NBSign(NBSign::SIGN_TYPE_ALLWAY_STOP, offset)); - break; - case SumoXMLNodeType::RIGHT_BEFORE_LEFT: - e->addSign(NBSign(NBSign::SIGN_TYPE_RIGHT_BEFORE_LEFT, offset)); - break; - default: - break; - } - } -} - - -int -NBEdgeCont::guessSpecialLanes(SUMOVehicleClass svc, double width, double minSpeed, double maxSpeed, bool fromPermissions, const std::string& excludeOpt) { - int lanesCreated = 0; - std::vector edges; - if (excludeOpt != "") { - edges = OptionsCont::getOptions().getStringVector(excludeOpt); - } - std::set exclude(edges.begin(), edges.end()); - for (EdgeCont::iterator it = myEdges.begin(); it != myEdges.end(); it++) { - NBEdge* edge = it->second; - if (// not excluded - exclude.count(edge->getID()) == 0 - // does not yet have a sidewalk - && !edge->hasRestrictedLane(svc) - && ( - // guess.from-permissions - (fromPermissions && (edge->getPermissions() & svc) != 0) - // guess from speed - || (!fromPermissions && edge->getSpeed() > minSpeed && edge->getSpeed() <= maxSpeed) - )) { - edge->addRestrictedLane(width, svc); - lanesCreated += 1; - } - } - return lanesCreated; -} - - -int -NBEdgeCont::remapIDs(bool numericaIDs, bool reservedIDs, const std::string& prefix, NBPTStopCont& sc) { - bool startGiven = !OptionsCont::getOptions().isDefault("numerical-ids.edge-start"); - std::vector avoid; - if (startGiven) { - avoid.push_back(toString(OptionsCont::getOptions().getInt("numerical-ids.edge-start") - 1)); - } else { - avoid = getAllNames(); - } - std::set reserve; - if (reservedIDs) { - NBHelpers::loadPrefixedIDsFomFile(OptionsCont::getOptions().getString("reserved-ids"), "edge:", reserve); - avoid.insert(avoid.end(), reserve.begin(), reserve.end()); - } - IDSupplier idSupplier("", avoid); - std::set toChange; - for (EdgeCont::iterator it = myEdges.begin(); it != myEdges.end(); it++) { - if (startGiven) { - toChange.insert(it->second); - continue; - } - if (numericaIDs) { - try { - StringUtils::toLong(it->first); - } catch (NumberFormatException&) { - toChange.insert(it->second); - } - } - if (reservedIDs && reserve.count(it->first) > 0) { - toChange.insert(it->second); - } - } - - std::map > stopsOnEdge; - for (const auto& item : sc.getStops()) { - stopsOnEdge[item.second->getEdgeId()].push_back(item.second); - } - - const bool origNames = OptionsCont::getOptions().getBool("output.original-names"); - for (NBEdge* edge : toChange) { - myEdges.erase(edge->getID()); - } - for (NBEdge* edge : toChange) { - const std::string origID = edge->getID(); - if (origNames) { - edge->setOrigID(origID); - } - edge->setID(idSupplier.getNext()); - myEdges[edge->getID()] = edge; - for (NBPTStop* stop : stopsOnEdge[origID]) { - stop->setEdgeId(prefix + edge->getID(), *this); - } - } - if (prefix.empty()) { - return (int)toChange.size(); - } else { - int renamed = 0; - // make a copy because we will modify the map - auto oldEdges = myEdges; - for (auto item : oldEdges) { - if (!StringUtils::startsWith(item.first, prefix)) { - rename(item.second, prefix + item.first); - renamed++; - } - } - return renamed; - } -} - - -void -NBEdgeCont::checkOverlap(double threshold, double zThreshold) const { - for (EdgeCont::const_iterator it = myEdges.begin(); it != myEdges.end(); it++) { - const NBEdge* e1 = it->second; - Boundary b1 = e1->getGeometry().getBoxBoundary(); - b1.grow(e1->getTotalWidth()); - PositionVector outline1 = e1->getCCWBoundaryLine(*e1->getFromNode()); - outline1.append(e1->getCCWBoundaryLine(*e1->getToNode())); - // check is symmetric. only check once per pair - for (EdgeCont::const_iterator it2 = it; it2 != myEdges.end(); it2++) { - const NBEdge* e2 = it2->second; - if (e1 == e2) { - continue; - } - Boundary b2 = e2->getGeometry().getBoxBoundary(); - b2.grow(e2->getTotalWidth()); - if (b1.overlapsWith(b2)) { - PositionVector outline2 = e2->getCCWBoundaryLine(*e2->getFromNode()); - outline2.append(e2->getCCWBoundaryLine(*e2->getToNode())); - const double overlap = outline1.getOverlapWith(outline2, zThreshold); - if (overlap > threshold) { - WRITE_WARNINGF("Edge '%' overlaps with edge '%' by %.", e1->getID(), e2->getID(), toString(overlap)); - } - } - } - } -} - - -void -NBEdgeCont::checkGrade(double threshold) const { - for (EdgeCont::const_iterator it = myEdges.begin(); it != myEdges.end(); it++) { - const NBEdge* edge = it->second; - for (int i = 0; i < (int)edge->getNumLanes(); i++) { - double maxJump = 0; - const double grade = edge->getLaneShape(i).getMaxGrade(maxJump); - if (maxJump > 0.01) { - WRITE_WARNINGF("Edge '%s' has a vertical jump of %sm.", edge->getID(), toString(maxJump)); - } else if (grade > threshold) { - WRITE_WARNINGF("Edge '%' has a grade of %%.", edge->getID(), toString(grade * 100), "%"); - break; - } - } - const std::vector& connections = edge->getConnections(); - for (std::vector::const_iterator it_con = connections.begin(); it_con != connections.end(); ++it_con) { - const NBEdge::Connection& c = *it_con; - double maxJump = 0; - const double grade = MAX2(c.shape.getMaxGrade(maxJump), c.viaShape.getMaxGrade(maxJump)); - if (maxJump > 0.01) { - WRITE_WARNINGF("Connection '%' has a vertical jump of %m.", c.getDescription(edge), toString(maxJump)); - } else if (grade > threshold) { - WRITE_WARNINGF("Connection '%' has a grade of %%.", c.getDescription(edge), toString(grade * 100), "%"); - break; - } - } - } -} - -int -NBEdgeCont::joinLanes(SVCPermissions perms) { - int affectedEdges = 0; - for (auto item : myEdges) { - if (item.second->joinLanes(perms)) { - affectedEdges++; - } - } - return affectedEdges; -} - - -int -NBEdgeCont::joinTramEdges(NBDistrictCont& dc, NBPTLineCont& lc, double maxDist) { - // this is different from joinSimilarEdges because there don't need to be - // shared nodes and tram edges may be split - std::set tramEdges; - std::set targetEdges; - for (auto item : myEdges) { - SVCPermissions permissions = item.second->getPermissions(); - if (permissions == SVC_TRAM) { - if (item.second->getNumLanes() == 1) { - tramEdges.insert(item.second); - } else { - WRITE_WARNINGF("Not joining tram edge '%s' with % lanes", item.second->getID(), item.second->getNumLanes()); - } - } else if ((permissions & SVC_PASSENGER) != 0) { - targetEdges.insert(item.second); - } - } - if (tramEdges.size() == 0 || targetEdges.size() == 0) { - return 0; - } - int numJoined = 0; - NamedRTree tramTree; - for (NBEdge* edge : tramEdges) { - const Boundary& bound = edge->getGeometry().getBoxBoundary(); - float min[2] = { static_cast(bound.xmin()), static_cast(bound.ymin()) }; - float max[2] = { static_cast(bound.xmax()), static_cast(bound.ymax()) }; - tramTree.Insert(min, max, edge); - } - // {targetEdge, laneIndex : tramEdge} - std::map, NBEdge*> matches; - - for (NBEdge* edge : targetEdges) { - Boundary bound = edge->getGeometry().getBoxBoundary(); - bound.grow(maxDist + edge->getTotalWidth()); - float min[2] = { static_cast(bound.xmin()), static_cast(bound.ymin()) }; - float max[2] = { static_cast(bound.xmax()), static_cast(bound.ymax()) }; - std::set nearby; - Named::StoringVisitor visitor(nearby); - tramTree.Search(min, max, visitor); - for (const Named* namedEdge : nearby) { - // find a continous stretch of tramEdge that runs along one of the - // lanes of the road edge - NBEdge* tramEdge = const_cast(dynamic_cast(namedEdge)); - const PositionVector& tramShape = tramEdge->getGeometry(); - double minEdgeDist = maxDist + 1; - int minLane = -1; - // find the lane where the maximum distance from the tram geometry - // is minimal and within maxDist - for (int i = 0; i < edge->getNumLanes(); i++) { - double maxLaneDist = -1; - if ((edge->getPermissions(i) & SVC_PASSENGER) != 0) { - const PositionVector& laneShape = edge->getLaneShape(i); - for (Position pos : laneShape) { - const double dist = tramShape.distance2D(pos, false); -#ifdef DEBUG_JOIN_TRAM - //if (edge->getID() == "106838214#1") { - // std::cout << " edge=" << edge->getID() << " tramEdge=" << tramEdge->getID() << " lane=" << i << " pos=" << pos << " dist=" << dist << "\n"; - //} -#endif - if (dist == GeomHelper::INVALID_OFFSET || dist > maxDist) { - maxLaneDist = -1; - break; - } - maxLaneDist = MAX2(maxLaneDist, dist); - } - if (maxLaneDist >= 0 && maxLaneDist < minEdgeDist) { - minEdgeDist = maxLaneDist; - minLane = i; - } - } - } - if (minLane >= 0) { - // edge could run in the wrong direction and still fit the threshold we check the angle as well - const PositionVector& laneShape = edge->getLaneShape(minLane); - const double offset1 = tramShape.nearest_offset_to_point2D(laneShape.front(), false); - const double offset2 = tramShape.nearest_offset_to_point2D(laneShape.back(), false); - Position p1 = tramShape.positionAtOffset2D(offset1); - Position p2 = tramShape.positionAtOffset2D(offset2); - double tramAngle = GeomHelper::legacyDegree(p1.angleTo2D(p2), true); - bool angleOK = GeomHelper::getMinAngleDiff(tramAngle, edge->getTotalAngle()) < JOIN_TRAM_MAX_ANGLE; - if (angleOK && offset2 > offset1) { - std::pair key = std::make_pair(edge, minLane); - if (matches.count(key) == 0) { - matches[key] = tramEdge; - } else { - WRITE_WARNINGF("Ambigous tram edges '%' and '%' for lane '%'", matches[key]->getID(), tramEdge->getID(), edge->getLaneID(minLane)); - } -#ifdef DEBUG_JOIN_TRAM - std::cout << edge->getLaneID(minLane) << " is close to tramEdge " << tramEdge->getID() << " maxLaneDist=" << minEdgeDist << " tramLength=" << tramEdge->getLength() << " edgeLength=" << edge->getLength() << " tramAngle=" << tramAngle << " edgeAngle=" << edge->getTotalAngle() << "\n"; -#endif - } - } - } - } - if (matches.size() == 0) { - return 0; - } - // find continous runs of matched edges for each tramEdge - for (NBEdge* tramEdge : tramEdges) { - std::vector > > roads; - for (auto item : matches) { - if (item.second == tramEdge) { - NBEdge* road = item.first.first; - int laneIndex = item.first.second; - const PositionVector& laneShape = road->getLaneShape(laneIndex); - double tramPos = tramEdge->getGeometry().nearest_offset_to_point2D(laneShape.front(), false); - roads.push_back(std::make_pair(tramPos, item.first)); - } - } - if (roads.size() != 0) { - - sort(roads.begin(), roads.end()); -#ifdef DEBUG_JOIN_TRAM - std::cout << " tramEdge=" << tramEdge->getID() << " roads="; - for (auto item : roads) { - std::cout << item.second.first->getLaneID(item.second.second) << ","; - } - std::cout << " offsets="; - for (auto item : roads) { - std::cout << item.first << ","; - } - std::cout << "\n"; -#endif - // merge tramEdge into road lanes - EdgeVector replacement; - double pos = 0; - int tramPart = 0; - std::string tramEdgeID = tramEdge->getID(); - NBNode* tramFrom = tramEdge->getFromNode(); - PositionVector tramShape = tramEdge->getGeometry(); - const double tramLength = tramShape.length(); - EdgeVector incoming = tramFrom->getIncomingEdges(); - bool erasedLast = false; - for (auto item : roads) { - const double gap = item.first - pos; - NBEdge* road = item.second.first; - int laneIndex = item.second.second; - if (gap >= JOIN_TRAM_MIN_LENGTH) { -#ifdef DEBUG_JOIN_TRAM - std::cout << " splitting tramEdge=" << tramEdge->getID() << " at " << item.first << " (gap=" << gap << ")\n"; -#endif - const std::string firstPartID = tramEdgeID + "#" + toString(tramPart++); - splitAt(dc, tramEdge, gap, road->getFromNode(), firstPartID, tramEdgeID, 1 , 1); - tramEdge = retrieve(tramEdgeID); // second part; - NBEdge* firstPart = retrieve(firstPartID); - firstPart->invalidateConnections(true); - incoming.clear(); - incoming.push_back(firstPart); - replacement.push_back(firstPart); - } - pos = item.first + road->getGeometry().length(); - numJoined++; - replacement.push_back(road); - // merge section of tramEdge into road lane - if (road->getToNode() != tramEdge->getToNode() && (tramLength - pos) >= JOIN_TRAM_MIN_LENGTH) { - tramEdge->reinitNodes(road->getToNode(), tramEdge->getToNode()); - tramEdge->setGeometry(tramShape.getSubpart(pos, tramShape.length())); - erasedLast = false; -#ifdef DEBUG_JOIN_TRAM - std::cout << " shorted tramEdge=" << tramEdge->getID() << " (joined with roadEdge=" << road->getID() << "\n"; -#endif - } else { -#ifdef DEBUG_JOIN_TRAM - std::cout << " erased tramEdge=" << tramEdge->getID() << "\n"; -#endif - extract(dc, tramEdge); - erasedLast = true; - } - road->setPermissions(road->getPermissions(laneIndex) | SVC_TRAM, laneIndex); - for (NBEdge* in : incoming) { - if (in->getPermissions() == SVC_TRAM && !in->isConnectedTo(road)) { - if (in->getFromNode() != road->getFromNode()) { - in->reinitNodes(in->getFromNode(), road->getFromNode()); - } else { - extract(dc, in); -#ifdef DEBUG_JOIN_TRAM - std::cout << " erased incoming tramEdge=" << in->getID() << "\n"; -#endif - } - } - } - incoming.clear(); - } - NBEdge* lastRoad = roads.back().second.first; - if (erasedLast) { - for (NBEdge* out : tramEdge->getToNode()->getOutgoingEdges()) { - if (out->getPermissions() == SVC_TRAM && !lastRoad->isConnectedTo(out)) { - if (lastRoad->getToNode() != out->getToNode()) { - out->reinitNodes(lastRoad->getToNode(), out->getToNode()); - } else { - extract(dc, out); -#ifdef DEBUG_JOIN_TRAM - std::cout << " erased outgoing tramEdge=" << out->getID() << "\n"; -#endif - - } - } - } - } else { - replacement.push_back(tramEdge); - } - // update ptlines - lc.replaceEdge(tramEdgeID, replacement); - } - } - - return numJoined; -} - - -EdgeVector -NBEdgeCont::getAllEdges() const { - EdgeVector result; - for (auto item : myEdges) { - item.second->setNumericalID((int)result.size()); - result.push_back(item.second); - } - return result; -} - -RouterEdgeVector -NBEdgeCont::getAllRouterEdges() const { - EdgeVector all = getAllEdges(); - return RouterEdgeVector(all.begin(), all.end()); -} - -bool -NBEdgeCont::checkConsistency(const NBNodeCont& nc) { - bool ok = true; - for (const auto& item : myEdges) { - NBEdge* e = item.second; - if (nc.retrieve(e->getFromNode()->getID()) == nullptr) { - WRITE_ERROR("Edge's '" + e->getID() + "' from-node '" + e->getFromNode()->getID() + "' is not known."); - ok = false; - } - if (nc.retrieve(e->getToNode()->getID()) == nullptr) { - WRITE_ERROR("Edge's '" + e->getID() + "' to-node '" + e->getToNode()->getID() + "' is not known."); - ok = false; - } - - } - return ok; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netbuild/NBEdgeCont.h b/Util/OSM2ODR/src/netbuild/NBEdgeCont.h deleted file mode 100644 index 304f35079..000000000 --- a/Util/OSM2ODR/src/netbuild/NBEdgeCont.h +++ /dev/null @@ -1,758 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NBEdgeCont.h -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date Tue, 20 Nov 2001 -/// -// Storage for edges, including some functionality operating on multiple edges -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include -#include -#include -#include "NBCont.h" -#include -#include -#include -#include - - -// =========================================================================== -// class declarations -// =========================================================================== -class OptionsCont; -class OutputDevice; -class NBNodeCont; -class NBTypeCont; -class NBEdge; -class NBNode; -class NBDistrictCont; -class NBTrafficLightLogicCont; -class NBPTStopCont; -class NBPTLineCont; - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NBEdgeCont - * @brief Storage for edges, including some functionality operating on multiple edges - */ -class NBEdgeCont { -public: - /** @brief Constructor - * @param[in] tc The net builded; used to obtain types - */ - NBEdgeCont(NBTypeCont& tc); - - - /// @brief Destructor - ~NBEdgeCont(); - - - /** @brief Initialises the storage by applying given options - * - * Options, mainly steering the acceptance of edges, are parsed - * and the according internal variables are set. - * - * @param[in] oc The options container to read options from - * @todo Recheck exceptions - */ - void applyOptions(OptionsCont& oc); - - - /** @brief Deletes all edges */ - void clear(); - - - - - /// @name edge access methods - /// @{ - - /** @brief Adds an edge to the dictionary - * - * First, it is determined whether the edge shall not be discarded due to any - * reasons (being outside a boundary, or not in the optional list of edges to - * import, etc.). If so, the edge is deleted and "true" is returned. - * "true" is also returned if the edge is accepted - no edge with the same - * name exists within this container. If another edge with the same name - * exists, false is returned. - * - * @param[in] edge The edge to add - * @param[in] ignorePrunning Whether this edge must not be prunned - * @return Whether the edge was valid (no edge with the same id is already known) - */ - bool insert(NBEdge* edge, bool ignorePrunning = false); - - - /** @brief Returns the edge that has the given id - * - * If no edge that has the given id is known, 0 is returned. - * - * @param[in] id The id of the edge to retrieve - * @param[in] bool Whether extracted edges shall be retrieved as well - * @return The edge with the given id, 0 if no such edge exists - */ - NBEdge* retrieve(const std::string& id, bool retrieveExtracted = false) const; - - - /** @brief Tries to retrieve an edge, even if it is splitted - * - * The edge given with the id should exist and is followed downstream or upstream, - * depending on the parameter to the last edge still starting with the id. - * - * @param[in] id The id of the edge to retrieve - * @param[in] downstream search direction - * @return The searched edge - * @todo Recheck usage - */ - NBEdge* retrievePossiblySplit(const std::string& id, bool downstream) const; - - - /** @brief Tries to retrieve an edge, even if it is splitted - * - * To describe which part of the edge shall be returned, the - * id of a second edge, participating at the node and the information - * whether to return the outgoing or the incoming is needed. - * - * @param[in] id The id of the edge to retrieve - * @param[in] hint An additional information which helps to retrieve the correct edge - * @param[in] incoming Whether the edge to find is an incoming edge at the node "hint" participates - * @return The searched edge - * @todo Recheck usage - */ - NBEdge* retrievePossiblySplit(const std::string& id, const std::string& hint, bool incoming) const; - - - /** @brief Tries to retrieve an edge, even if it is splitted - * - * To describe which part of the edge shall be returned, a - * position hint is supplied. - * - * @param[in] id The id of the edge to retrieve - * @param[in] pos An additional about the position of the basic edge's subpart - * @return The searched edge - * @todo Recheck usage - */ - NBEdge* retrievePossiblySplit(const std::string& id, double pos) const; - - - /** @brief Removes the given edge from the container (deleting it) - * - * @param[in] dc The district container, in order to remove the edge from sources/sinks - * @param[in] edge The edge to remove - * @todo Recheck whether the district cont is needed - if districts are processed using an external tool - */ - void erase(NBDistrictCont& dc, NBEdge* edge); - - - /** @brief Removes the given edge from the container like erase but does not - * delete it - * - * @param[in] dc The district container, in order to remove the edge from sources/sinks - * @param[in] edge The edge to remove - * @param[in] remember Whether to keep this edge for future reference - * @todo Recheck whether the district cont is needed - if districts are processed using an external tool - * @todo Recheck whether this is used at all and why - */ - void extract(NBDistrictCont& dc, NBEdge* edge, bool remember = false); - - - /** @brief Returns the pointer to the begin of the stored edges - * @return The iterator to the beginning of stored edges - */ - std::map::const_iterator begin() const { - return myEdges.begin(); - } - - - /** @brief Returns the pointer to the end of the stored edges - * @return The iterator to the end of stored edges - */ - std::map::const_iterator end() const { - return myEdges.end(); - } - /// @} - - - - /// @name explicit edge manipulation methods - /// @{ - - /** @struct Split - * @brief A structure which describes changes of lane number or speed along the road - */ - struct Split { - /// @brief The lanes after this change - std::vector lanes; - /// @brief The position of this change - double pos = INVALID_DOUBLE; - /// @brief The speed after this change - double speed = INVALID_DOUBLE; - /// @brief The new node that is created for this split - NBNode* node = nullptr; - /// @brief The id for the edge before the split - std::string idBefore; - /// @brief The id for the edge after the split - std::string idAfter; - /// @brief the default node id - std::string nameID; - /// @brief lateral offset to edge geometry - double offset = 0.; - /// @brief direction in which to apply the offset (used by netgenerate for lefthand networks) - int offsetFactor = 1; - }; - - void processSplits(NBEdge* e, std::vector splits, - NBNodeCont& nc, NBDistrictCont& dc, NBTrafficLightLogicCont& tlc); - - - /** @brief Splits the edge at the position nearest to the given node - * - * Uses "splitAt(NBDistrictCont &, NBEdge *, NBNode *, const std::string &, const std::string &, int , int)" - * to perform the split; the edge names are built by appending "[0]" and "[1]", - * respectively. Both edges will have the same number of lanes. - * - * @param[in] dc The district container, in order to remove/add the edge from/to sources/sinks - * @param[in] edge The edge to split - * @param[in] node The node to split the edge at - * @return Whether the edge could be split - * @exception ProcessError If connections between the edges can not be built - * @see NBEdge::splitAt(NBDistrictCont &, NBEdge *, NBNode *, const std::string &, const std::string &, int , int) - */ - bool splitAt(NBDistrictCont& dc, NBEdge* edge, NBNode* node); - - - /** @brief Splits the edge at the position nearest to the given node using the given modifications - * - * Determines the position of the split by finding the nearest position on the - * edge to the given node. If this position is too near to the edges begin/end, - * false is returned. - * - * Otherwise, "splitAt(NBDistrictCont &, NBEdge *, double, NBNode *, const std::string &, const std::string &, int , int)" - * is used to perform the split. - * - * @param[in] dc The district container, in order to remove/add the edge from/to sources/sinks - * @param[in] edge The edge to split - * @param[in] node The node to split the edge at - * @param[in] firstEdgeName The id the first part of the split edge shall have - * @param[in] secondEdgeName The id the second part of the split edge shall have - * @param[in] noLanesFirstEdge The number of lanes the second part of the split edge shall have - * @param[in] noLanesSecondEdge The number of lanes the second part of the split edge shall have - * @param[in] speed The speed for the edge after the split - * @param[in] changedLeft The number of lanes that is added or removed on the left side of the edge - * (By default all added/removed lanes are assumed to be on the right when computing connections) - * @return Whether the edge could be split - * @exception ProcessError If connections between the edges can not be built - * @see NBEdge::splitAt(NBDistrictCont &, NBEdge *, double, NBNode *, const std::string &, const std::string &, int , int) - */ - bool splitAt(NBDistrictCont& dc, NBEdge* edge, NBNode* node, - const std::string& firstEdgeName, const std::string& secondEdgeName, - int noLanesFirstEdge, int noLanesSecondEdge, - const double speed = -1., const int changedLeft = 0); - - - /** @brief Splits the edge at the position nearest to the given node using the given modifications - * - * @param[in] dc The district container, in order to remove/add the edge from/to sources/sinks - * @param[in] edge The edge to split - * @param[in] node The node to split the edge at - * @param[in] firstEdgeName The id the first part of the split edge shall have - * @param[in] secondEdgeName The id the second part of the split edge shall have - * @param[in] noLanesFirstEdge The number of lanes the second part of the split edge shall have - * @param[in] noLanesSecondEdge The number of lanes the second part of the split edge shall have - * @param[in] speed The speed for the edge after the split - * @param[in] changedLeft The number of lanes that is added or removed on the left side of the edge - * (By default all added/removed lanes are assumed to be on the right when computing connections) - * @return Whether the edge could be split - * @exception ProcessError If connections between the edges can not be built - */ - bool splitAt(NBDistrictCont& dc, NBEdge* edge, double edgepos, NBNode* node, - const std::string& firstEdgeName, const std::string& secondEdgeName, - int noLanesFirstEdge, int noLanesSecondEdge, - const double speed = -1., const int changedLeft = 0); - /// @} - - - - /// @name container access methods - /// @{ - - /** @brief Returns the number of edges - * @return The number of edges stored in this container - */ - int size() const { - return (int) myEdges.size(); - } - - - /** @brief Returns all ids of known edges - * @return All ids of known edges - * @todo Recheck usage, probably, filling a given vector would be better... - */ - std::vector getAllNames() const; - - - /** @brief Returns the number of edge splits - * @return How often an edge was split - */ - int getNoEdgeSplits() const { - return myEdgesSplit; - } - /// @} - - - - /// @name Adapting the input - /// @{ - - /** @brief Removes unwished edges (not in keep-edges) - * @param[in, opt. changed] dc The district container needed to remove edges - * @todo Recheck usage; check whether keep-edges.postload is really useful - */ - void removeUnwishedEdges(NBDistrictCont& dc); - - - /** @brief Splits edges into multiple if they have a complex geometry - * - * Calls "NBEdge::splitGeometry" for all edges within the container which - * have more than three positions in their geometry. - * - * @param[in] nc The node container needed to build (geometry) nodes - * @see NBEdge::splitGeometry - */ - void splitGeometry(NBDistrictCont& dc, NBNodeCont& nc); - - - /** @brief - * @param[in] nc The node container needed to build (geometry) nodes - * @see NBEdge::reduceGeometry - */ - void reduceGeometries(const double minDist); - - - /** @brief - * @param[in] maxAngle The maximum geometry angle allowed - * @param[in] minRadius The minimum turning radius allowed at the start and end - * @param[in] fix Whether to prune geometry points to avoid sharp turns at start and end - * @see NBEdge::checkGeometry - */ - void checkGeometries(const double maxAngle, const double minRadius, bool fix, bool fixRailways, bool silent = false); - /// @} - - - - /// @name processing methods - /// @{ - - /** @brief Sorts all lanes of all edges within the container by their direction - * - * Calls "NBEdge::sortOutgoingLanesConnections" for all edges within the container. - * - * @todo Recheck whether a visitor-pattern should be used herefor - * @see NBEdge::sortOutgoingLanesConnections - */ - void sortOutgoingLanesConnections(); - - - /** @brief Computes for each edge the approached edges - * - * Calls "NBEdge::computeEdge2Edges" for all edges within the container. - * - * @param[in] noLeftMovers Whether left-moving connections shall be omitted - * @todo Recheck whether a visitor-pattern should be used herefor - * @see NBEdge::computeEdge2Edges - */ - void computeEdge2Edges(bool noLeftMovers); - - - /** @brief Computes for each edge which lanes approach the next edges - * - * Calls "NBEdge::computeLanes2Edges" for all edges within the container. - * - * @todo Recheck whether a visitor-pattern should be used herefor - * @see NBEdge::computeLanes2Edges - */ - void computeLanes2Edges(); - - - /** @brief Rechecks whether all lanes have a successor for each of the stored edges - * - * Calls "NBEdge::recheckLanes" for all edges within the container. - * - * @todo Recheck whether a visitor-pattern should be used herefor - * @see NBEdge::recheckLanes - */ - void recheckLanes(); - - - /** @brief Appends turnarounds to all edges stored in the container - * - * Calls "NBEdge::appendTurnaround" for all edges within the container. - * - * @param[in] noTLSControlled Whether the turnaround shall not be connected if the edge is controlled by a tls - * @param[in] noFringe Whether the turnaround shall not be connected if the junction is at the (outer) fringe - * @param[in] onlyDeadends Whether the turnaround shall only be built at deadends - * @param[in] onlyTurnlane Whether the turnaround shall only be built when there is an exclusive (left) turn lane - * @param[in] noGeometryLike Whether the turnaround shall be built at geometry-like nodes - * @see NBEdge::appendTurnaround - */ - void appendTurnarounds(bool noTLSControlled, bool noFringe, bool onlyDeadends, bool onlyTurnlane, bool noGeometryLike); - - - /** @brief Appends turnarounds to all edges stored in the container - * Calls "NBEdge::appendTurnaround" for edges with the given ids - * @param[in] ids The list of ids for which to append a turnaround - * @param[in] noTLSControlled Whether the turnaround shall not be connected if the edge is controlled by a tls - * @see NBEdge::appendTurnaround - */ - void appendTurnarounds(const std::set& ids, bool noTLSControlled); - - /** @brief Appends turnarounds to all bidiRail edges with stops - */ - void appendRailwayTurnarounds(const NBPTStopCont& sc); - - - /** @brief Computes the shapes of all edges stored in the container - * - * Calls "NBEdge::computeEdgeShape" for all edges within the container. - * - * @todo Recheck whether a visitor-pattern should be used herefor - * @todo Recheck usage - * @see NBEdge::computeEdgeShape - */ - void computeEdgeShapes(double smoothElevationThreshold = -1); - - - /** @brief Computes the shapes of all lanes of all edges stored in the container - * - * Calls "NBEdge::computeLaneShapes" for all edges within the container. - * - * @todo Recheck whether a visitor-pattern should be used herefor - * @todo Recheck usage - * @see NBEdge::computeLaneShapes - */ - void computeLaneShapes(); - - - /** @brief Clears information about controlling traffic lights for all connenections of all edges - */ - void clearControllingTLInformation() const; - - - /** @brief Joins the given edges because they connect the same nodes - * - * @param[in] dc The district container needed to remove edges - * @param[in] tlc The tls container needed to remove edges - * @param[in] edges The edges to join - * @todo Recheck and describe usage - */ - void joinSameNodeConnectingEdges(NBDistrictCont& dc, - NBTrafficLightLogicCont& tlc, EdgeVector edges); - - - /** @brief Sets opposite lane information for geometrically close edges - */ - void guessOpposites(); - - - /** @brief Rechecks whether the lane spread is proper - * - * @todo Recheck usage; check whether this is really needed and whether it works at all - */ - void recheckLaneSpread(); - - /// @} - - /// @brief Returns the edge with negated id if it exists - NBEdge* getOppositeByID(const std::string& edgeID) const; - - /// @brief Returns the edge with id if it exists - NBEdge* getByID(const std::string& edgeID) const; - - /** @brief Determines which edges belong to roundabouts and increases their priority - * @param[out] marked Edges which belong to a roundabout are stored here - * @return The number of guessed roundabouts - */ - int guessRoundabouts(); - - - /** @brief Returns whether the edge with the id was ignored during parsing - * @return Whether the edge with the id was ignored during parsing - */ - bool wasIgnored(std::string id) const { - return myIgnoredEdges.count(id) != 0; - } - - /// @brief mark the given edge id as ignored - void ignore(std::string id) { - myIgnoredEdges.insert(id); - } - - /** @brief Returns whether the edge with the id was deleted explicitly - */ - bool wasRemoved(std::string id) const { - return myExtractedEdges.count(id) != 0; - } - - /** @brief Renames the edge. Throws exception if newID already exists - */ - void rename(NBEdge* edge, const std::string& newID); - - - - /// @name Connections handling - /// @{ - - /** @brief Adds a connection which could not be set during loading - * @param[in] from The id of the edge the connection starts at - * @param[in] fromLane The number of the lane the connection starts at - * @param[in] to The id of the edge the connection ends at - * @param[in] toLane The number of the lane the connection ends at - * @param[in] mayDefinitelyPass Whether the connection may be passed without braking - * @param[in] keepClear Whether the connection must check to keep the junction clear - * @param[in] contPos Custom position for internal junction - * @param[in] visibility Custom foe visiblity connection - * @param[in] speed Custom speed - * @param[in] customShape Custom shape - * @param[in] warnOnly Whether a failure to set this connection should only result in a warning - */ - void addPostProcessConnection(const std::string& from, int fromLane, const std::string& to, int toLane, bool mayDefinitelyPass, - bool keepClear, double contPos, double visibility, - double speed, double length, - const PositionVector& customShape, - bool uncontrolled, - bool warnOnly, - SVCPermissions permissions = SVC_UNSPECIFIED); - - bool hasPostProcessConnection(const std::string& from, const std::string& to = ""); - - - /** @brief Try to set any stored connections - */ - void recheckPostProcessConnections(); - /// @} - - /// @brief assigns street signs to edges based on toNode types - void generateStreetSigns(); - - /// @brief add sidwalks to edges within the given limits or permissions and return the number of edges affected - int guessSpecialLanes(SUMOVehicleClass svc, double width, double minSpeed, double maxSpeed, bool fromPermissions, const std::string& excludeOpt); - - - /** @brief Returns the determined roundabouts - * @return The list of roundabout edges - */ - const std::set getRoundabouts() const; - - /// @brief add user specified roundabout - void addRoundabout(const EdgeSet& roundabout); - - /// @brief remove roundabout that contains the given node - void removeRoundabout(const NBNode* node); - - /// @brief mark edge priorities and prohibit turn-arounds for all roundabout edges - void markRoundabouts(); - - /// @brief fix roundabout information after splitting an edge - void patchRoundabouts(NBEdge* orig, NBEdge* part1, NBEdge* part2, std::set& roundabouts); - - /// @brief Returns true if this edge matches one of the removal criteria - bool ignoreFilterMatch(NBEdge* edge); - - /// @brief remap node IDs accoring to options --numerical-ids and --reserved-ids - int remapIDs(bool numericaIDs, bool reservedIDs, const std::string& prefix, NBPTStopCont& sc); - - /// @brief check whether edges overlap - void checkOverlap(double threshold, double zThreshold) const; - - /// @brief check whether edges are to steep - void checkGrade(double threshold) const; - - - /** @brief Returns the edges which have been built by splitting the edge of the given id - * - * @param[in] id The id of the original edge - * @return List of all edges which have been built by splitting the original edge - * @todo Recheck usage - */ - EdgeVector getGeneratedFrom(const std::string& id) const; - - /// @brief join adjacent lanes with the given permissions - int joinLanes(SVCPermissions perms); - - /// @brief join tram edges into adjacent lanes - int joinTramEdges(NBDistrictCont& dc, NBPTLineCont& lc, double maxDist); - - /// @brief return all edges - EdgeVector getAllEdges() const; - RouterEdgeVector getAllRouterEdges() const; - - /// @brief ensure that all edges have valid nodes - bool checkConsistency(const NBNodeCont& nc); - -private: - /// @brief compute the form factor for a loop of edges - static double formFactor(const EdgeVector& loopEdges); - -private: - /// @brief The network builder; used to obtain type information - NBTypeCont& myTypeCont; - - /** @struct PostProcessConnection - * @brief A structure representing a connection between two lanes - */ - struct PostProcessConnection { - public: - /** @brief Constructor - * @param[in] from The id of the edge the connection starts at - * @param[in] fromLane The number of the lane the connection starts at - * @param[in] to The id of the edge the connection ends at - * @param[in] toLane The number of the lane the connection ends at - * @param[in] mayDefinitelyPass Whether the connection may be passed without braking - */ - PostProcessConnection(const std::string& from_, int fromLane_, const std::string& to_, int toLane_, - bool mayDefinitelyPass_, bool keepClear_, double contPos_, double visibility_, double speed_, - double length_, - const PositionVector& customShape_, - bool uncontrolled_, - bool warnOnly_, SVCPermissions permissions_) : - from(from_), fromLane(fromLane_), to(to_), toLane(toLane_), mayDefinitelyPass(mayDefinitelyPass_), keepClear(keepClear_), contPos(contPos_), - visibility(visibility_), - speed(speed_), - customLength(length_), - customShape(customShape_), - uncontrolled(uncontrolled_), - permissions(permissions_), - warnOnly(warnOnly_) - {} - /// @brief The id of the edge the connection starts at - std::string from; - /// @brief The number of the lane the connection starts at - int fromLane; - /// @brief The id of the edge the connection ends at - std::string to; - /// @brief The number of the lane the connection ends at - int toLane; - /// @brief Whether the connection may be passed without braking - bool mayDefinitelyPass; - /// @brief Whether the connection may be passed without braking - bool keepClear; - /// @brief custom position for internal junction on this connection - double contPos; - /// @brief custom foe visiblity for connection - double visibility; - /// @brief custom speed for connection - double speed; - /// @brief custom length for connection - double customLength; - /// @brief custom shape for connection - PositionVector customShape; - /// @brief whether this connection shall not be controlled by a traffic light - bool uncontrolled; - /// @brief custom permissions for connection - SVCPermissions permissions; - /// @brief whether a failure to set this connection is a warning or an error - bool warnOnly; - }; - - /// @brief The list of connections to recheck - std::map > myConnections; - - - /// @brief The type of the dictionary where an edge may be found by its id - typedef std::map EdgeCont; - - /// @brief The instance of the dictionary (id->edge) - EdgeCont myEdges; - - /// @brief The extracted nodes which are kept for reference - EdgeCont myExtractedEdges; - - /// @brief The ids of ignored edges - std::set myIgnoredEdges; - - /// @brief the number of splits of edges during the building - int myEdgesSplit; - - /// @name Settings for accepting/dismissing edges - /// @{ - - /// @brief The minimum speed an edge may have in order to be kept (default: -1) - double myEdgesMinSpeed; - - /// @brief Whether edges shall be joined first, then removed - bool myRemoveEdgesAfterJoining; - - /// @brief Set of ids of edges which shall explicitly be kept - std::set myEdges2Keep; - - /// @brief Set of ids of edges which shall explicitly be removed - std::set myEdges2Remove; - - /// @brief Set of vehicle types which must be allowed on edges in order to keep them - SVCPermissions myVehicleClasses2Keep; - - /// @brief Set of vehicle types which need not be supported (edges which allow ONLY these are removed) - SVCPermissions myVehicleClasses2Remove; - - /// @brief Set of edges types which shall be kept - std::set myTypes2Keep; - - /// @brief Set of edges types which shall be removed - std::set myTypes2Remove; - - /// @brief Boundary within which an edge must be located in order to be kept - PositionVector myPruningBoundary; - - /// @brief whether a geo transform has been applied to the pruning boundary - bool myNeedGeoTransformedPruningBoundary; - /// @} - - /// @brief Edges marked as belonging to a roundabout by the user (each EdgeVector is a roundabout) - std::set myRoundabouts; - /// @brief Edges marked as belonging to a roundabout after guessing - std::set myGuessedRoundabouts; - - /** @class split_sorter - * @brief Sorts splits by their position (increasing) - */ - class split_sorter { - public: - /// @brief Constructor - explicit split_sorter() { } - - /// @brief Comparing operator - int operator()(const Split& e1, const Split& e2) const { - return e1.pos < e2.pos; - } - }; - - -private: - /// @brief invalidated copy constructor - NBEdgeCont(const NBEdgeCont& s); - - /// @brief invalidated assignment operator - NBEdgeCont& operator=(const NBEdgeCont& s); - -}; diff --git a/Util/OSM2ODR/src/netbuild/NBFrame.cpp b/Util/OSM2ODR/src/netbuild/NBFrame.cpp deleted file mode 100644 index c3b065b5d..000000000 --- a/Util/OSM2ODR/src/netbuild/NBFrame.cpp +++ /dev/null @@ -1,706 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NBFrame.cpp -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date 09.05.2011 -/// -// Sets and checks options for netbuild -/****************************************************************************/ -#include - -#include -#include -#include "NBFrame.h" -#include "NBNodeCont.h" -#include "NBEdgeCont.h" -#include "NBTrafficLightLogicCont.h" -#include "NBDistrictCont.h" -#include "NBRequest.h" -#include "NBTypeCont.h" -#include -#include -#include -#include -#include -#include -#include -#include - - -// =========================================================================== -// method definitions -// =========================================================================== -void -NBFrame::fillOptions(bool forNetgen) { - OptionsCont& oc = OptionsCont::getOptions(); - // register building defaults - oc.doRegister("default.lanenumber", 'L', new Option_Integer(1)); - oc.addSynonyme("default.lanenumber", "lanenumber", true); - oc.addDescription("default.lanenumber", "Building Defaults", "The default number of lanes in an edge"); - - oc.doRegister("default.lanewidth", new Option_Float(NBEdge::UNSPECIFIED_WIDTH)); - oc.addSynonyme("default.lanewidth", "lanewidth", true); - oc.addDescription("default.lanewidth", "Building Defaults", "The default width of lanes"); - - oc.doRegister("default.spreadtype", new Option_String("right")); - oc.addDescription("default.spreadtype", "Building Defaults", "The default method for computing lane shapes from edge shapes"); - - oc.doRegister("default.speed", 'S', new Option_Float((double) 13.89)); - oc.addSynonyme("default.speed", "speed", true); - oc.addDescription("default.speed", "Building Defaults", "The default speed on an edge (in m/s)"); - - oc.doRegister("default.priority", 'P', new Option_Integer(-1)); - oc.addSynonyme("default.priority", "priority", true); - oc.addDescription("default.priority", "Building Defaults", "The default priority of an edge"); - - oc.doRegister("default.type", new Option_String()); - oc.addDescription("default.type", "Building Defaults", "The default edge type"); - - oc.doRegister("default.sidewalk-width", new Option_Float((double) 2.0)); - oc.addDescription("default.sidewalk-width", "Building Defaults", "The default width of added sidewalks"); - - oc.doRegister("default.bikelane-width", new Option_Float((double) 1.0)); - oc.addDescription("default.bikelane-width", "Building Defaults", "The default width of added bike lanes"); - - oc.doRegister("default.crossing-width", new Option_Float((double) 4.0)); - oc.addDescription("default.crossing-width", "Building Defaults", "The default width of a pedestrian crossing"); - - oc.doRegister("default.disallow", new Option_String()); - oc.addDescription("default.disallow", "Building Defaults", "The default for disallowed vehicle classes"); - - oc.doRegister("default.junctions.keep-clear", new Option_Bool(true)); - oc.addDescription("default.junctions.keep-clear", "Building Defaults", "Whether junctions should be kept clear by default"); - - oc.doRegister("default.junctions.radius", new Option_Float(4)); - oc.addDescription("default.junctions.radius", "Building Defaults", "The default turning radius of intersections"); - - oc.doRegister("default.connection-length", new Option_Float((double) NBEdge::UNSPECIFIED_LOADED_LENGTH)); - oc.addDescription("default.connection-length", "Building Defaults", "The default length when overriding connection lengths"); - - oc.doRegister("default.right-of-way", new Option_String("default")); - oc.addDescription("default.right-of-way", "Building Defaults", "The default algorithm for computing right of way rules ('default', 'edgePriority')"); - - oc.doRegister("junctions.right-before-left.speed-threshold", new Option_Float(49 / 3.6)); - oc.addDescription("junctions.right-before-left.speed-threshold", "Junctions", "Allow building right-before-left junctions when the incoming edge speeds are below FLOAT (m/s)"); - - // register the data processing options - oc.doRegister("no-internal-links", new Option_Bool(false)); // !!! not described - oc.addDescription("no-internal-links", "Junctions", "Omits internal links"); - - oc.doRegister("numerical-ids", new Option_Bool(false)); - oc.addDescription("numerical-ids", "Processing", "Remaps alphanumerical IDs of nodes and edges to ensure that all IDs are integers"); - - oc.doRegister("numerical-ids.node-start", new Option_Integer(std::numeric_limits::max())); - oc.addDescription("numerical-ids.node-start", "Processing", "Remaps IDs of nodes to integers starting at INT"); - - oc.doRegister("numerical-ids.edge-start", new Option_Integer(std::numeric_limits::max())); - oc.addDescription("numerical-ids.edge-start", "Processing", "Remaps IDs of edges to integers starting at INT"); - - /// @todo not working for netgen - oc.doRegister("reserved-ids", new Option_FileName()); - oc.addDescription("reserved-ids", "Processing", "Ensures that generated ids do not included any of the typed IDs from FILE (SUMO-GUI selection file format)"); - - if (!forNetgen) { - oc.doRegister("dismiss-vclasses", new Option_Bool(false)); - oc.addDescription("dismiss-vclasses", "Processing", "Removes vehicle class restrictions from imported edges"); - } - - oc.doRegister("no-turnarounds", new Option_Bool(false)); - oc.addDescription("no-turnarounds", "Junctions", "Disables building turnarounds"); - - oc.doRegister("no-turnarounds.tls", new Option_Bool(false)); - oc.addSynonyme("no-turnarounds.tls", "no-tls-turnarounds", true); - oc.addDescription("no-turnarounds.tls", "Junctions", "Disables building turnarounds at tls-controlled junctions"); - - oc.doRegister("no-turnarounds.geometry", new Option_Bool(true)); - oc.addDescription("no-turnarounds.geometry", "Junctions", "Disables building turnarounds at geometry-like junctions"); - - oc.doRegister("no-turnarounds.except-deadend", new Option_Bool(false)); - oc.addDescription("no-turnarounds.except-deadend", "Junctions", "Disables building turnarounds except at dead end junctions"); - - oc.doRegister("no-turnarounds.except-turnlane", new Option_Bool(false)); - oc.addDescription("no-turnarounds.except-turnlane", "Junctions", "Disables building turnarounds except at at junctions with a dedicated turning lane"); - - oc.doRegister("no-turnarounds.fringe", new Option_Bool(false)); - oc.addDescription("no-turnarounds.fringe", "Junctions", "Disables building turnarounds at fringe junctions"); - - oc.doRegister("no-left-connections", new Option_Bool(false)); - oc.addDescription("no-left-connections", "Junctions", "Disables building connections to left"); - - if (!forNetgen) { - oc.doRegister("geometry.split", new Option_Bool(false)); // !!!not described - oc.addSynonyme("geometry.split", "split-geometry", true); - oc.addDescription("geometry.split", "Processing", "Splits edges across geometry nodes"); - - oc.doRegister("geometry.remove", 'R', new Option_Bool(false)); - oc.addSynonyme("geometry.remove", "remove-geometry", true); - oc.addDescription("geometry.remove", "Processing", "Replace nodes which only define edge geometry by geometry points (joins edges)"); - - oc.doRegister("geometry.remove.keep-edges.explicit", new Option_StringVector()); - oc.addDescription("geometry.remove.keep-edges.explicit", "Processing", "Ensure that the given list of edges is not modified"); - - oc.doRegister("geometry.remove.keep-edges.input-file", new Option_FileName()); - oc.addDescription("geometry.remove.keep-edges.input-file", "Processing", - "Ensure that the edges in FILE are not modified (Each id on a single line. Selection files from SUMO-GUI are also supported)"); - - oc.doRegister("geometry.remove.min-length", new Option_Float(0)); - oc.addDescription("geometry.remove.min-length", "Processing", - "Allow merging edges with differing attributes when their length is below min-length"); - - oc.doRegister("geometry.remove.width-tolerance", new Option_Float(0)); - oc.addDescription("geometry.remove.width-tolerance", "Processing", - "Allow merging edges with differing lane widths if the difference is below FLOAT"); - - oc.doRegister("geometry.max-segment-length", new Option_Float(0)); - oc.addDescription("geometry.max-segment-length", "Processing", "splits geometry to restrict segment length"); - - oc.doRegister("geometry.min-dist", new Option_Float(-1)); - oc.addDescription("geometry.min-dist", "Processing", "reduces too similar geometry points"); - - oc.doRegister("geometry.max-angle", new Option_Float(99)); - oc.addDescription("geometry.max-angle", "Processing", "Warn about edge geometries with an angle above DEGREES in successive segments"); - - oc.doRegister("geometry.min-radius", new Option_Float(9)); - oc.addDescription("geometry.min-radius", "Processing", "Warn about edge geometries with a turning radius less than METERS at the start or end"); - - oc.doRegister("geometry.min-radius.fix", new Option_Bool(false)); - oc.addDescription("geometry.min-radius.fix", "Processing", "Straighten edge geometries to avoid turning radii less than geometry.min-radius"); - - oc.doRegister("geometry.min-radius.fix.railways", new Option_Bool(true)); - oc.addDescription("geometry.min-radius.fix.railways", "Processing", "Straighten edge geometries to avoid turning radii less than geometry.min-radius (only railways)"); - - oc.doRegister("geometry.junction-mismatch-threshold", new Option_Float(20)); - oc.addDescription("geometry.junction-mismatch-threshold", "Processing", "Warn if the junction shape is to far away from the original node position"); - - oc.doRegister("geometry.check-overlap", new Option_Float(0)); - oc.addDescription("geometry.check-overlap", "Processing", "Warn if edges overlap by more than the given threshold value"); - - oc.doRegister("geometry.check-overlap.vertical-threshold", new Option_Float(4)); - oc.addDescription("geometry.check-overlap.vertical-threshold", "Processing", "Ignore overlapping edges if they are separated vertically by the given threshold."); - - oc.doRegister("geometry.avoid-overlap", new Option_Bool(true)); - oc.addDescription("geometry.avoid-overlap", "Processing", "Modify edge geometries to avoid overlap at junctions"); - - oc.doRegister("join-lanes", new Option_Bool(false)); - oc.addDescription("join-lanes", "Processing", "join adjacent lanes that have the same permissions and which do not admit lane-changing (sidewalks and disallowed lanes)"); - - oc.doRegister("ptline.match-dist", new Option_Float(100)); - oc.addDescription("ptline.match-dist", "Processing", "Matches stops outside the road network to the referencing pt line when below the given distance"); - // railway processing options - - oc.doRegister("railway.topology.repair", new Option_Bool(false)); - oc.addDescription("railway.topology.repair", "Railway", "Repair topology of the railway network"); - - oc.doRegister("railway.topology.repair.connect-straight", new Option_Bool(false)); - oc.addDescription("railway.topology.repair.connect-straight", "Railway", "Allow bidiretional rail use wherever rails with opposite directions meet at a straight angle"); - - oc.doRegister("railway.topology.repair.stop-turn", new Option_Bool(false)); - oc.addDescription("railway.topology.repair.stop-turn", "Railway", "Add turn-around connections at all loaded stops."); - - oc.doRegister("railway.topology.all-bidi", new Option_Bool(false)); - oc.addDescription("railway.topology.all-bidi", "Railway", "Make all rails usable in both direction"); - - oc.doRegister("railway.topology.all-bidi.input-file", new Option_FileName()); - oc.addDescription("railway.topology.all-bidi.input-file", "Railway", "Make all rails edge ids from FILE usable in both direction"); - - oc.doRegister("railway.topology.direction-priority", new Option_Bool(false)); - oc.addDescription("railway.topology.direction-priority", "Railway", "Set edge priority values based on estimated main direction"); - - oc.doRegister("railway.access-distance", new Option_Float(150.f)); - oc.addDescription("railway.access-distance", "Railway", "The search radius for finding suitable road accesses for rail stops"); - oc.addSynonyme("railway.access-distance", "osm.stop-output.footway-access-distance", true); - - oc.doRegister("railway.max-accesses", new Option_Integer(5)); - oc.addDescription("railway.max-accesses", "Railway", "The maximum roud accesses registered per rail stops"); - oc.addSynonyme("railway.max-accesses", "osm.stop-output.footway-max-accesses", true); - - oc.doRegister("railway.access-factor", new Option_Float(1.5)); - oc.addDescription("railway.access-factor", "Railway", "The walking length of the access is computed as air-line distance multiplied by FLOAT"); - oc.addSynonyme("railway.access-factor", "osm.stop-output.footway-access-factor", true); - - oc.doRegister("ptstop-output.no-bidi", new Option_Bool(false)); - oc.addDescription("ptstop-output.no-bidi", "Processing", "Skips automatic generation of stops on the bidi-edge of a loaded stop"); - } - - oc.doRegister("geometry.max-grade", new Option_Float(10)); - oc.addDescription("geometry.max-grade", "Processing", "Warn about edge geometries with a grade in % above FLOAT."); - - oc.doRegister("geometry.max-grade.fix", new Option_Bool(true)); - oc.addDescription("geometry.max-grade.fix", "Processing", "Smooth edge edge geometries with a grade in above the warning threshold."); - - oc.doRegister("offset.disable-normalization", new Option_Bool(false)); - oc.addSynonyme("offset.disable-normalization", "disable-normalize-node-positions", true); - oc.addDescription("offset.disable-normalization", "Processing", "Turn off normalizing node positions"); - - oc.doRegister("offset.x", new Option_Float(0)); - oc.addSynonyme("offset.x", "x-offset-to-apply", true); - oc.addDescription("offset.x", "Processing", "Adds FLOAT to net x-positions"); - - oc.doRegister("offset.y", new Option_Float(0)); - oc.addSynonyme("offset.y", "y-offset-to-apply", true); - oc.addDescription("offset.y", "Processing", "Adds FLOAT to net y-positions"); - - oc.doRegister("offset.z", new Option_Float(0)); - oc.addDescription("offset.z", "Processing", "Adds FLOAT to net z-positions"); - - oc.doRegister("flip-y-axis", new Option_Bool(false)); - oc.addSynonyme("flip-y-axis", "flip-y"); - oc.addDescription("flip-y-axis", "Processing", "Flips the y-coordinate along zero"); - - oc.doRegister("roundabouts.guess", new Option_Bool(true)); - oc.addSynonyme("roundabouts.guess", "guess-roundabouts", true); - oc.addDescription("roundabouts.guess", "Processing", "Enable roundabout-guessing"); - - oc.doRegister("opposites.guess", new Option_Bool(false)); - oc.addDescription("opposites.guess", "Processing", "Enable guessing of opposite direction lanes usable for overtaking"); - - oc.doRegister("opposites.guess.fix-lengths", new Option_Bool(false)); - oc.addDescription("opposites.guess.fix-lengths", "Processing", "Ensure that opposite edges have the same length"); - - oc.doRegister("fringe.guess", new Option_Bool(false)); - oc.addDescription("fringe.guess", "Processing", "Enable guessing of network fringe nodes"); - - oc.doRegister("lefthand", new Option_Bool(false)); - oc.addDescription("lefthand", "Processing", "Assumes left-hand traffic on the network"); - - oc.doRegister("edges.join", new Option_Bool(false)); - oc.addDescription("edges.join", "Processing", - "Merges edges which connect the same nodes and are close to each other (recommended for VISSIM import)"); - - oc.doRegister("junctions.join", new Option_Bool(false)); - oc.addDescription("junctions.join", "Junctions", - "Joins junctions that are close to each other (recommended for OSM import)"); - - oc.doRegister("junctions.join-dist", new Option_Float(10)); - oc.addDescription("junctions.join-dist", "Junctions", - "Determines the maximal distance for joining junctions (defaults to 10)"); - - if (!forNetgen) { - oc.doRegister("junctions.join-exclude", new Option_StringVector()); - oc.addDescription("junctions.join-exclude", "Junctions", "Interprets STR[] as list of junctions to exclude from joining"); - - oc.doRegister("speed.offset", new Option_Float(0)); - oc.addDescription("speed.offset", "Processing", "Modifies all edge speeds by adding FLOAT"); - - oc.doRegister("speed.factor", new Option_Float(1)); - oc.addDescription("speed.factor", "Processing", "Modifies all edge speeds by multiplying by FLOAT"); - - oc.doRegister("speed.minimum", new Option_Float(0)); - oc.addDescription("speed.minimum", "Processing", "Modifies all edge speeds to at least FLOAT"); - - oc.doRegister("edges.join-tram-dist", new Option_Float(-1)); - oc.addDescription("edges.join-tram-dist", "Processing", - "Joins tram edges into road lanes with similar geometry (within FLOAT distance)"); - } - - oc.doRegister("junctions.corner-detail", new Option_Integer(5)); - oc.addDescription("junctions.corner-detail", "Junctions", "Generate INT intermediate points to smooth out intersection corners"); - - oc.doRegister("junctions.internal-link-detail", new Option_Integer(5)); - oc.addDescription("junctions.internal-link-detail", "Junctions", "Generate INT intermediate points to smooth out lanes within the intersection"); - - oc.doRegister("junctions.scurve-stretch", new Option_Float(0)); - oc.addDescription("junctions.scurve-stretch", "Junctions", "Generate longer intersections to allow for smooth s-curves when the number of lanes changes"); - - oc.doRegister("junctions.join-turns", new Option_Bool(false)); - oc.addDescription("junctions.join-turns", "Junctions", - "Builds common edges for turning connections with common from- and to-edge. This causes discrepancies between geometrical length and assigned length due to averaging but enables lane-changing while turning"); - - oc.doRegister("junctions.limit-turn-speed", new Option_Float(5.5)); - oc.addDescription("junctions.limit-turn-speed", "Junctions", - "Limits speed on junctions to an average lateral acceleration of at most FLOAT m/s^2)"); - - oc.doRegister("junctions.limit-turn-speed.min-angle", new Option_Float(15)); - oc.addDescription("junctions.limit-turn-speed.min-angle", "Junctions", - "Do not limit turn speed for angular changes below FLOAT (degrees). The value is subtracted from the geometric angle before computing the turning radius."); - - oc.doRegister("junctions.limit-turn-speed.min-angle.railway", new Option_Float(35)); - oc.addDescription("junctions.limit-turn-speed.min-angle.railway", "Junctions", - "Do not limit turn speed for angular changes below FLOAT (degrees) on railway edges. The value is subtracted from the geometric angle before computing the turning radius."); - - oc.doRegister("junctions.limit-turn-speed.warn.straight", new Option_Float(5)); - oc.addDescription("junctions.limit-turn-speed.warn.straight", "Junctions", - "Warn about turn speed limits that reduce the speed of straight connections by more than FLOAT"); - - oc.doRegister("junctions.limit-turn-speed.warn.turn", new Option_Float(22)); - oc.addDescription("junctions.limit-turn-speed.warn.turn", "Junctions", - "Warn about turn speed limits that reduce the speed of turning connections (no u-turns) by more than FLOAT"); - - - oc.doRegister("junctions.small-radius", new Option_Float(1.5)); - oc.addDescription("junctions.small-radius", "Junctions", - "Default radius for junctions that do not require wide vehicle turns"); - - oc.doRegister("rectangular-lane-cut", new Option_Bool(false)); - oc.addDescription("rectangular-lane-cut", "Junctions", "Forces rectangular cuts between lanes and intersections"); - - oc.doRegister("check-lane-foes.roundabout", new Option_Bool(true)); - oc.addDescription("check-lane-foes.roundabout", "Junctions", - "Allow driving onto a multi-lane road if there are foes on other lanes (at roundabouts)"); - - oc.doRegister("check-lane-foes.all", new Option_Bool(false)); - oc.addDescription("check-lane-foes.all", "Junctions", - "Allow driving onto a multi-lane road if there are foes on other lanes (everywhere)"); - - oc.doRegister("sidewalks.guess", new Option_Bool(false)); - oc.addDescription("sidewalks.guess", "Pedestrian", - "Guess pedestrian sidewalks based on edge speed"); - - oc.doRegister("sidewalks.guess.max-speed", new Option_Float((double) 13.89)); - oc.addDescription("sidewalks.guess.max-speed", "Pedestrian", - "Add sidewalks for edges with a speed equal or below the given limit"); - - oc.doRegister("sidewalks.guess.min-speed", new Option_Float((double) 5.8)); - oc.addDescription("sidewalks.guess.min-speed", "Pedestrian", - "Add sidewalks for edges with a speed above the given limit"); - - oc.doRegister("sidewalks.guess.from-permissions", new Option_Bool(false)); - oc.addDescription("sidewalks.guess.from-permissions", "Pedestrian", - "Add sidewalks for edges that allow pedestrians on any of their lanes regardless of speed"); - - oc.doRegister("sidewalks.guess.exclude", new Option_StringVector()); - oc.addDescription("sidewalks.guess.exclude", "Pedestrian", - "Do not guess sidewalks for the given list of edges"); - - oc.doRegister("bikelanes.guess", new Option_Bool(false)); - oc.addDescription("bikelanes.guess", "Bicycle", - "Guess bike lanes based on edge speed"); - - oc.doRegister("bikelanes.guess.max-speed", new Option_Float((double) 22.22)); - oc.addDescription("bikelanes.guess.max-speed", "Bicycle", - "Add bike lanes for edges with a speed equal or below the given limit"); - - oc.doRegister("bikelanes.guess.min-speed", new Option_Float((double) 5.8)); - oc.addDescription("bikelanes.guess.min-speed", "Bicycle", - "Add bike lanes for edges with a speed above the given limit"); - - oc.doRegister("bikelanes.guess.from-permissions", new Option_Bool(false)); - oc.addDescription("bikelanes.guess.from-permissions", "Bicycle", - "Add bike lanes for edges that allow bicycles on any of their lanes regardless of speed"); - - oc.doRegister("bikelanes.guess.exclude", new Option_StringVector()); - oc.addDescription("bikelanes.guess.exclude", "Bicycle", - "Do not guess bikelanes for the given list of edges"); - - oc.doRegister("crossings.guess", new Option_Bool(false)); - oc.addDescription("crossings.guess", "Pedestrian", - "Guess pedestrian crossings based on the presence of sidewalks"); - - oc.doRegister("crossings.guess.speed-threshold", new Option_Float(13.89)); - oc.addDescription("crossings.guess.speed-threshold", "Pedestrian", - "At uncontrolled nodes, do not build crossings across edges with a speed above the threshold"); - - oc.doRegister("walkingareas", new Option_Bool(false)); - oc.addDescription("walkingareas", "Pedestrian", "Always build walking areas even if there are no crossings"); - - // tls setting options - // explicit tls - oc.doRegister("tls.set", new Option_StringVector()); - oc.addSynonyme("tls.set", "explicite-tls", true); - oc.addDescription("tls.set", "TLS Building", "Interprets STR[] as list of junctions to be controlled by TLS"); - - oc.doRegister("tls.unset", new Option_StringVector()); - oc.addSynonyme("tls.unset", "explicite-no-tls", true); - oc.addDescription("tls.unset", "TLS Building", "Interprets STR[] as list of junctions to be not controlled by TLS"); - - // tls-guessing - oc.doRegister("tls.guess", new Option_Bool(false)); - oc.addSynonyme("tls.guess", "guess-tls", true); - oc.addDescription("tls.guess", "TLS Building", "Turns on TLS guessing"); - - oc.doRegister("tls.guess.threshold", new Option_Float(250 / 3.6)); - oc.addDescription("tls.guess.threshold", "TLS Building", "Sets minimum value for the sum of all incoming lane speeds when guessing TLS"); - - if (!forNetgen) { - oc.doRegister("tls.taz-nodes", new Option_Bool(false)); - oc.addSynonyme("tls.taz-nodes", "tls-guess.district-nodes", true); - oc.addDescription("tls.taz-nodes", "TLS Building", "Sets district nodes as tls-controlled"); // !!! describe - } - - oc.doRegister("tls.guess.joining", new Option_Bool(false)); - oc.addSynonyme("tls.guess.joining", "tls-guess.joining", true); - oc.addDescription("tls.guess.joining", "TLS Building", "Includes node clusters into guess"); // !!! describe - - oc.doRegister("tls.join", new Option_Bool(false)); - oc.addSynonyme("tls.join", "try-join-tls", true); - oc.addDescription("tls.join", "TLS Building", "Tries to cluster tls-controlled nodes"); // !!! describe - - oc.doRegister("tls.join-dist", new Option_Float(20)); - oc.addDescription("tls.join-dist", "TLS Building", - "Determines the maximal distance for joining traffic lights (defaults to 20)"); - - oc.doRegister("tls.uncontrolled-within", new Option_Bool(false)); - oc.addDescription("tls.uncontrolled-within", "TLS Building", - "Do not control edges that lie fully within a joined traffic light. This may cause collisions but allows old traffic light plans to be used"); - - oc.doRegister("tls.ignore-internal-junction-jam", new Option_Bool(false)); - oc.addDescription("tls.ignore-internal-junction-jam", "TLS Building", - "Do not build mutually conflicting response matrix, potentially ignoring vehicles that are stuck at an internal junction when their phase has ended"); - - if (!forNetgen) { - oc.doRegister("tls.guess-signals", new Option_Bool(false)); - oc.addDescription("tls.guess-signals", "TLS Building", "Interprets tls nodes surrounding an intersection as signal positions for a larger TLS. This is typical pattern for OSM-derived networks"); - - oc.doRegister("tls.guess-signals.dist", new Option_Float(25)); - oc.addDescription("tls.guess-signals.dist", "TLS Building", "Distance for interpreting nodes as signal locations"); - } - - - // computational - oc.doRegister("tls.cycle.time", new Option_Integer(90)); - oc.addDescription("tls.cycle.time", "TLS Building", "Use INT as cycle duration"); - - oc.doRegister("tls.green.time", new Option_Integer(31)); - oc.addSynonyme("tls.green.time", "traffic-light-green", true); - oc.addDescription("tls.green.time", "TLS Building", "Use INT as green phase duration"); - - oc.doRegister("tls.yellow.min-decel", 'D', new Option_Float(3.0)); - oc.addSynonyme("tls.yellow.min-decel", "min-decel", true); - oc.addDescription("tls.yellow.min-decel", "TLS Building", "Defines smallest vehicle deceleration"); - - oc.doRegister("tls.yellow.patch-small", new Option_Bool(false)); - oc.addSynonyme("tls.yellow.patch-small", "patch-small-tyellow", true); - oc.addDescription("tls.yellow.patch-small", "TLS Building", "Given yellow times are patched even if being too short"); - - oc.doRegister("tls.yellow.time", new Option_Integer(-1)); - oc.addSynonyme("tls.yellow.time", "traffic-light-yellow", true); - oc.addDescription("tls.yellow.time", "TLS Building", "Set INT as fixed time for yellow phase durations"); - - oc.doRegister("tls.red.time", new Option_Integer(5)); - oc.addDescription("tls.red.time", "TLS Building", "Set INT as fixed time for red phase duration at traffic lights that do not have a conflicting flow"); - - oc.doRegister("tls.allred.time", new Option_Integer(0)); - oc.addDescription("tls.allred.time", "TLS Building", "Set INT as fixed time for intermediate red phase after every switch"); - - oc.doRegister("tls.minor-left.max-speed", new Option_Float(19.44)); // 70km/h - oc.addDescription("tls.minor-left.max-speed", "TLS Building", "Use FLOAT as threshold for allowing left-turning vehicles to move in the same phase as oncoming straight-going vehicles"); - - oc.doRegister("tls.left-green.time", new Option_Integer(6)); - oc.addDescription("tls.left-green.time", "TLS Building", "Use INT as green phase duration for left turns (s). Setting this value to 0 disables additional left-turning phases"); - - oc.doRegister("tls.crossing-min.time", new Option_Integer(4)); - oc.addDescription("tls.crossing-min.time", "TLS Building", "Use INT as minimum green duration for pedestrian crossings (s)."); - - oc.doRegister("tls.crossing-clearance.time", new Option_Integer(5)); - oc.addDescription("tls.crossing-clearance.time", "TLS Building", "Use INT as clearance time for pedestrian crossings (s)."); - - oc.doRegister("tls.scramble.time", new Option_Integer(5)); - oc.addDescription("tls.scramble.time", "TLS Building", "Use INT as green phase duration for pedestrian scramble phase (s)."); - - // tls-shifts - oc.doRegister("tls.half-offset", new Option_StringVector()); - oc.addSynonyme("tls.half-offset", "tl-logics.half-offset", true); - oc.addDescription("tls.half-offset", "TLS Building", "TLSs in STR[] will be shifted by half-phase"); - - oc.doRegister("tls.quarter-offset", new Option_StringVector()); - oc.addSynonyme("tls.quarter-offset", "tl-logics.quarter-offset", true); - oc.addDescription("tls.quarter-offset", "TLS Building", "TLSs in STR[] will be shifted by quarter-phase"); - - // tls type - oc.doRegister("tls.default-type", new Option_String("static")); - oc.addDescription("tls.default-type", "TLS Building", "TLSs with unspecified type will use STR as their algorithm"); - - oc.doRegister("tls.layout", new Option_String("opposites")); - oc.addDescription("tls.layout", "TLS Building", "Set phase layout four grouping opposite directions or grouping all movements for one incoming edge ['opposites', 'incoming']"); - - oc.doRegister("tls.min-dur", new Option_Integer(5)); - oc.addDescription("tls.min-dur", "TLS Building", "Default minimum phase duration for traffic lights with variable phase length"); - - oc.doRegister("tls.max-dur", new Option_Integer(50)); - oc.addDescription("tls.max-dur", "TLS Building", "Default maximum phase duration for traffic lights with variable phase length"); - - oc.doRegister("tls.group-signals", new Option_Bool(false)); - oc.addDescription("tls.group-signals", "TLS Building", "Assign the same tls link index to connections that share the same states"); - - oc.doRegister("tls.ungroup-signals", new Option_Bool(false)); - oc.addDescription("tls.ungroup-signals", "TLS Building", "Assign a distinct tls link index to every connection"); - - // edge pruning - oc.doRegister("keep-edges.min-speed", new Option_Float(-1)); - oc.addSynonyme("keep-edges.min-speed", "edges-min-speed", true); - oc.addDescription("keep-edges.min-speed", "Edge Removal", "Only keep edges with speed in meters/second > FLOAT"); - - oc.doRegister("remove-edges.explicit", new Option_StringVector()); - oc.addSynonyme("remove-edges.explicit", "remove-edges"); - oc.addDescription("remove-edges.explicit", "Edge Removal", "Remove edges in STR[]"); - - oc.doRegister("keep-edges.explicit", new Option_StringVector()); - oc.addSynonyme("keep-edges.explicit", "keep-edges"); - oc.addDescription("keep-edges.explicit", "Edge Removal", "Only keep edges in STR[] or those which are kept due to other keep-edges or remove-edges options"); - - oc.doRegister("keep-edges.input-file", new Option_FileName()); - oc.addDescription("keep-edges.input-file", "Edge Removal", "Only keep edges in FILE (Each id on a single line. Selection files from SUMO-GUI are also supported) or those which are kept due to other keep-edges or remove-edges options"); - - oc.doRegister("remove-edges.input-file", new Option_FileName()); - oc.addDescription("remove-edges.input-file", "Edge Removal", "Remove edges in FILE. (Each id on a single line. Selection files from SUMO-GUI are also supported)"); - - if (!forNetgen) { - oc.doRegister("keep-edges.postload", new Option_Bool(false)); - oc.addDescription("keep-edges.postload", "Edge Removal", "Remove edges after joining"); - } - - oc.doRegister("keep-edges.in-boundary", new Option_StringVector()); - oc.addDescription("keep-edges.in-boundary", "Edge Removal", "Only keep edges which are located within the given boundary (given either as CARTESIAN corner coordinates or as polygon )"); - - oc.doRegister("keep-edges.in-geo-boundary", new Option_StringVector()); - oc.addDescription("keep-edges.in-geo-boundary", "Edge Removal", "Only keep edges which are located within the given boundary (given either as GEODETIC corner coordinates or as polygon )"); - - if (!forNetgen) { - oc.doRegister("keep-edges.by-vclass", new Option_StringVector()); - oc.addDescription("keep-edges.by-vclass", "Edge Removal", "Only keep edges which allow one of the vclasss in STR[]"); - - oc.doRegister("remove-edges.by-vclass", new Option_StringVector()); - oc.addDescription("remove-edges.by-vclass", "Edge Removal", "Remove edges which allow only vclasses from STR[]"); - - oc.doRegister("keep-edges.by-type", new Option_StringVector()); - oc.addDescription("keep-edges.by-type", "Edge Removal", "Only keep edges where type is in STR[]"); - - oc.doRegister("keep-edges.components", new Option_Integer(0)); - oc.addDescription("keep-edges.components", "Edge Removal", "Only keep the INT largest weakly connected components"); - - oc.doRegister("remove-edges.by-type", new Option_StringVector()); - oc.addDescription("remove-edges.by-type", "Edge Removal", "Remove edges where type is in STR[]"); - - oc.doRegister("remove-edges.isolated", new Option_Bool(false)); - oc.addSynonyme("remove-edges.isolated", "remove-isolated", true); - oc.addDescription("remove-edges.isolated", "Edge Removal", "Removes isolated edges"); - } - - - // unregulated nodes options - oc.doRegister("keep-nodes-unregulated", new Option_Bool(false)); - oc.addSynonyme("keep-nodes-unregulated", "keep-unregulated"); - oc.addDescription("keep-nodes-unregulated", "Unregulated Nodes", "All nodes will be unregulated"); - - oc.doRegister("keep-nodes-unregulated.explicit", new Option_StringVector()); - oc.addSynonyme("keep-nodes-unregulated.explicit", "keep-unregulated.explicit"); - oc.addSynonyme("keep-nodes-unregulated.explicit", "keep-unregulated.nodes", true); - oc.addDescription("keep-nodes-unregulated.explicit", "Unregulated Nodes", "Do not regulate nodes in STR[]"); - - oc.doRegister("keep-nodes-unregulated.district-nodes", new Option_Bool(false)); - oc.addSynonyme("keep-nodes-unregulated.district-nodes", "keep-unregulated.district-nodes"); - oc.addDescription("keep-nodes-unregulated.district-nodes", "Unregulated Nodes", "Do not regulate district nodes"); - - // ramp guessing options - if (!forNetgen) { - oc.doRegister("ramps.guess", new Option_Bool(false)); - oc.addSynonyme("ramps.guess", "guess-ramps", true); - oc.addDescription("ramps.guess", "Ramp Guessing", "Enable ramp-guessing"); - - oc.doRegister("ramps.guess-acceleration-lanes", new Option_Bool(true)); - oc.addDescription("ramps.guess-acceleration-lanes", "Ramp Guessing", "Guess on-ramps and mark acceleration lanes if they exist but do not add new lanes"); - - oc.doRegister("ramps.max-ramp-speed", new Option_Float(-1)); - oc.addSynonyme("ramps.max-ramp-speed", "ramp-guess.max-ramp-speed", true); - oc.addDescription("ramps.max-ramp-speed", "Ramp Guessing", "Treat edges with speed > FLOAT as no ramps"); - - oc.doRegister("ramps.min-highway-speed", new Option_Float((double)(79 / 3.6))); - oc.addSynonyme("ramps.min-highway-speed", "ramp-guess.min-highway-speed", true); - oc.addDescription("ramps.min-highway-speed", "Ramp Guessing", "Treat edges with speed < FLOAT as no highways"); - - oc.doRegister("ramps.ramp-length", new Option_Float(100)); - oc.addSynonyme("ramps.ramp-length", "ramp-guess.ramp-length", true); - oc.addDescription("ramps.ramp-length", "Ramp Guessing", "Use FLOAT as ramp-length"); - - //The Weaving Length Limit for Short Free Onramps, Chiu Liu, Zhongren WangPhD even suggest 70m - oc.doRegister("ramps.min-weave-length", new Option_Float(50)); - oc.addDescription("ramps.min-weave-length", "Ramp Guessing", "Use FLOAT as minimum ramp-length"); - - oc.doRegister("ramps.set", new Option_StringVector()); - oc.addSynonyme("ramps.set", "ramp-guess.explicite", true); - oc.addDescription("ramps.set", "Ramp Guessing", "Tries to handle the given edges as ramps"); - - oc.doRegister("ramps.unset", new Option_StringVector()); - oc.addDescription("ramps.unset", "Ramp Guessing", "Do not consider the given edges as ramps"); - - oc.doRegister("ramps.no-split", new Option_Bool(false)); - oc.addSynonyme("ramps.no-split", "ramp-guess.no-split", true); - oc.addDescription("ramps.no-split", "Ramp Guessing", "Avoids edge splitting"); - } -} - - -bool -NBFrame::checkOptions() { - OptionsCont& oc = OptionsCont::getOptions(); - bool ok = true; - // - if (!SUMOXMLDefinitions::TrafficLightTypes.hasString(oc.getString("tls.default-type"))) { - WRITE_ERROR("unsupported value '" + oc.getString("tls.default-type") + "' for option '--tls.default-type'"); - ok = false; - } - if (oc.isSet("keep-edges.in-boundary") && oc.isSet("keep-edges.in-geo-boundary")) { - WRITE_ERROR("only one of the options 'keep-edges.in-boundary' or 'keep-edges.in-geo-boundary' may be given"); - ok = false; - } - if (oc.getBool("no-internal-links") && oc.getBool("crossings.guess")) { - WRITE_ERROR("only one of the options 'no-internal-links' or 'crossings.guess' may be given"); - ok = false; - } - if (oc.getBool("no-internal-links") && oc.getBool("walkingareas")) { - WRITE_ERROR("only one of the options 'no-internal-links' or 'walkareas' may be given"); - ok = false; - } - if (!oc.isDefault("tls.green.time") && !oc.isDefault("tls.cycle.time")) { - WRITE_ERROR("only one of the options 'tls.green.time' or 'tls.cycle.time' may be given"); - ok = false; - } - if (oc.getInt("junctions.internal-link-detail") < 2) { - WRITE_ERROR("junctions.internal-link-detail must >= 2"); - ok = false; - } - if (oc.getFloat("junctions.scurve-stretch") > 0) { - if (oc.getBool("no-internal-links")) { - WRITE_WARNING("option 'junctions.scurve-stretch' requires internal lanes to work. Option '--no-internal-links' was disabled."); - } - // make sure the option is set so heuristics cannot ignore it - oc.set("no-internal-links", "false"); - } - if (oc.getFloat("junctions.small-radius") > oc.getFloat("default.junctions.radius") && oc.getFloat("default.junctions.radius") >= 0) { - if (!oc.isDefault("junctions.small-radius")) { - WRITE_ERROR("option 'default.junctions.radius' cannot be smaller than option 'junctions.small-radius'"); - ok = false; - } else { - oc.set("junctions.small-radius", oc.getValueString("default.junctions.radius")); - } - } - if (oc.getString("tls.layout") != "opposites" && oc.getString("tls.layout") != "incoming") { - WRITE_ERROR("tls.layout must be 'opposites' or 'incoming'"); - ok = false; - } - if (!oc.isDefault("default.right-of-way") && - !SUMOXMLDefinitions::RightOfWayValues.hasString(oc.getString("default.right-of-way"))) { - WRITE_ERROR("default.right-of-way must be one of '" + toString(SUMOXMLDefinitions::RightOfWayValues.getStrings()) + "'"); - ok = false; - } - if (oc.isDefault("railway.topology.repair") && oc.getBool("railway.topology.repair.connect-straight")) { - oc.set("railway.topology.repair", "true"); - } - if (oc.isDefault("railway.topology.all-bidi") && !oc.isDefault("railway.topology.all-bidi.input-file")) { - oc.set("railway.topology.all-bidi", "true"); - } - if (oc.isDefault("railway.topology.repair.stop-turn") && !oc.isDefault("railway.topology.repair")) { - oc.set("railway.topology.repair.stop-turn", "true"); - } - if (!SUMOXMLDefinitions::LaneSpreadFunctions.hasString(oc.getString("default.spreadtype"))) { - WRITE_ERROR("Unknown value for default.spreadtype '" + oc.getString("default.spreadtype") + "'."); - ok = false; - } - return ok; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netbuild/NBFrame.h b/Util/OSM2ODR/src/netbuild/NBFrame.h deleted file mode 100644 index f5921381b..000000000 --- a/Util/OSM2ODR/src/netbuild/NBFrame.h +++ /dev/null @@ -1,58 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NBFrame.h -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date 09.05.2011 -/// -// Sets and checks options for netbuild -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include -#include -#include "NBEdgeCont.h" -#include "NBTypeCont.h" -#include "NBNodeCont.h" -#include "NBNode.h" -#include "NBTrafficLightLogicCont.h" -#include "NBDistrictCont.h" -#include - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NBFrame - * @brief Sets and checks options for netbuild - */ -class NBFrame { -public: - /** @brief Inserts options used by the network converter - * @param[in] forNetgen Whether netconvert options shall be omitted - */ - static void fillOptions(bool forNetgen); - - - /** @brief Checks set options from the OptionsCont-singleton for being valid - * @return Whether needed (netbuild) options are set and have proper values - */ - static bool checkOptions(); - - -}; diff --git a/Util/OSM2ODR/src/netbuild/NBHeightMapper.cpp b/Util/OSM2ODR/src/netbuild/NBHeightMapper.cpp deleted file mode 100644 index 73922064f..000000000 --- a/Util/OSM2ODR/src/netbuild/NBHeightMapper.cpp +++ /dev/null @@ -1,386 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2011-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NBHeightMapper.cpp -/// @author Jakob Erdmann -/// @author Laura Bieker -/// @author Michael Behrisch -/// @date Sept 2011 -/// -// Set z-values for all network positions based on data from a height map -/****************************************************************************/ -#include - -#include -#include -#include -#include -#include -#include -#include "NBHeightMapper.h" -#include -#include - -#ifdef HAVE_GDAL -#if __GNUC__ > 3 -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wpedantic" -#endif -#include -#include -#include -#if __GNUC__ > 3 -#pragma GCC diagnostic pop -#endif -#endif - -// =========================================================================== -// static members -// =========================================================================== -NBHeightMapper NBHeightMapper::myInstance; - - -// =========================================================================== -// method definitions -// =========================================================================== -NBHeightMapper::NBHeightMapper(): - myRTree(&Triangle::addSelf) { -} - - -NBHeightMapper::~NBHeightMapper() { - clearData(); -} - - -const NBHeightMapper& -NBHeightMapper::get() { - return myInstance; -} - - -bool -NBHeightMapper::ready() const { - return myRasters.size() > 0 || myTriangles.size() > 0; -} - - -double -NBHeightMapper::getZ(const Position& geo) const { - if (!ready()) { - WRITE_WARNING("Cannot supply height since no height data was loaded"); - return 0; - } - for (auto& item : myRasters) { - const Boundary& boundary = item.first; - int16_t* raster = item.second; - double result = -1e6; - if (boundary.around(geo)) { - const int xSize = int((boundary.xmax() - boundary.xmin()) / mySizeOfPixel.x() + .5); - const double normX = (geo.x() - boundary.xmin()) / mySizeOfPixel.x(); - const double normY = (geo.y() - boundary.ymax()) / mySizeOfPixel.y(); - PositionVector corners; - corners.push_back(Position(floor(normX) + 0.5, floor(normY) + 0.5, raster[(int)normY * xSize + (int)normX])); - if (normX - floor(normX) > 0.5) { - corners.push_back(Position(floor(normX) + 1.5, floor(normY) + 0.5, raster[(int)normY * xSize + (int)normX + 1])); - } else { - corners.push_back(Position(floor(normX) - 0.5, floor(normY) + 0.5, raster[(int)normY * xSize + (int)normX - 1])); - } - if (normY - floor(normY) > 0.5) { - corners.push_back(Position(floor(normX) + 0.5, floor(normY) + 1.5, raster[((int)normY + 1) * xSize + (int)normX])); - } else { - corners.push_back(Position(floor(normX) + 0.5, floor(normY) - 0.5, raster[((int)normY - 1) * xSize + (int)normX])); - } - result = Triangle(corners).getZ(Position(normX, normY)); - } - if (result > -1e5 && result < 1e5) { - return result; - } - } - // coordinates in degrees hence a small search window - float minB[2]; - float maxB[2]; - minB[0] = (float)geo.x() - 0.00001f; - minB[1] = (float)geo.y() - 0.00001f; - maxB[0] = (float)geo.x() + 0.00001f; - maxB[1] = (float)geo.y() + 0.00001f; - QueryResult queryResult; - int hits = myRTree.Search(minB, maxB, queryResult); - Triangles result = queryResult.triangles; - assert(hits == (int)result.size()); - UNUSED_PARAMETER(hits); // only used for assertion - - for (Triangles::iterator it = result.begin(); it != result.end(); it++) { - const Triangle* triangle = *it; - if (triangle->contains(geo)) { - return triangle->getZ(geo); - } - } - WRITE_WARNING("Could not get height data for coordinate " + toString(geo)); - return 0; -} - - -void -NBHeightMapper::addTriangle(PositionVector corners) { - Triangle* triangle = new Triangle(corners); - myTriangles.push_back(triangle); - Boundary b = corners.getBoxBoundary(); - const float cmin[2] = {(float) b.xmin(), (float) b.ymin()}; - const float cmax[2] = {(float) b.xmax(), (float) b.ymax()}; - myRTree.Insert(cmin, cmax, triangle); -} - - -void -NBHeightMapper::loadIfSet(OptionsCont& oc) { - if (oc.isSet("heightmap.geotiff")) { - // parse file(s) - std::vector files = oc.getStringVector("heightmap.geotiff"); - for (std::vector::const_iterator file = files.begin(); file != files.end(); ++file) { - PROGRESS_BEGIN_MESSAGE("Parsing from GeoTIFF '" + *file + "'"); - int numFeatures = myInstance.loadTiff(*file); - MsgHandler::getMessageInstance()->endProcessMsg( - " done (parsed " + toString(numFeatures) + - " features, Boundary: " + toString(myInstance.getBoundary()) + ")."); - } - } - if (oc.isSet("heightmap.shapefiles")) { - // parse file(s) - std::vector files = oc.getStringVector("heightmap.shapefiles"); - for (std::vector::const_iterator file = files.begin(); file != files.end(); ++file) { - PROGRESS_BEGIN_MESSAGE("Parsing from shape-file '" + *file + "'"); - int numFeatures = myInstance.loadShapeFile(*file); - MsgHandler::getMessageInstance()->endProcessMsg( - " done (parsed " + toString(numFeatures) + - " features, Boundary: " + toString(myInstance.getBoundary()) + ")."); - } - } -} - - -int -NBHeightMapper::loadShapeFile(const std::string& file) { -#ifdef HAVE_GDAL -#if GDAL_VERSION_MAJOR < 2 - OGRRegisterAll(); - OGRDataSource* ds = OGRSFDriverRegistrar::Open(file.c_str(), FALSE); -#else - GDALAllRegister(); - GDALDataset* ds = (GDALDataset*)GDALOpenEx(file.c_str(), GDAL_OF_VECTOR | GA_ReadOnly, nullptr, nullptr, nullptr); -#endif - if (ds == nullptr) { - throw ProcessError("Could not open shape file '" + file + "'."); - } - - // begin file parsing - OGRLayer* layer = ds->GetLayer(0); - layer->ResetReading(); - - // triangle coordinates are stored in WGS84 and later matched with network coordinates in WGS84 - // build coordinate transformation - OGRSpatialReference* sr_src = layer->GetSpatialRef(); - OGRSpatialReference sr_dest; - sr_dest.SetWellKnownGeogCS("WGS84"); - OGRCoordinateTransformation* toWGS84 = OGRCreateCoordinateTransformation(sr_src, &sr_dest); - if (toWGS84 == nullptr) { - WRITE_WARNING("Could not create geocoordinates converter; check whether proj.4 is installed."); - } - - int numFeatures = 0; - OGRFeature* feature; - layer->ResetReading(); - while ((feature = layer->GetNextFeature()) != nullptr) { - OGRGeometry* geom = feature->GetGeometryRef(); - assert(geom != 0); - - // @todo gracefull handling of shapefiles with unexpected contents or any error handling for that matter - assert(std::string(geom->getGeometryName()) == std::string("POLYGON")); - // try transform to wgs84 - geom->transform(toWGS84); - OGRLinearRing* cgeom = ((OGRPolygon*) geom)->getExteriorRing(); - // assume TIN with with 4 points and point0 == point3 - assert(cgeom->getNumPoints() == 4); - PositionVector corners; - for (int j = 0; j < 3; j++) { - Position pos((double) cgeom->getX(j), (double) cgeom->getY(j), (double) cgeom->getZ(j)); - corners.push_back(pos); - myBoundary.add(pos); - } - addTriangle(corners); - numFeatures++; - - /* - OGRwkbGeometryType gtype = geom->getGeometryType(); - switch (gtype) { - case wkbPolygon: { - break; - } - case wkbPoint: { - WRITE_WARNING("got wkbPoint"); - break; - } - case wkbLineString: { - WRITE_WARNING("got wkbLineString"); - break; - } - case wkbMultiPoint: { - WRITE_WARNING("got wkbMultiPoint"); - break; - } - case wkbMultiLineString: { - WRITE_WARNING("got wkbMultiLineString"); - break; - } - case wkbMultiPolygon: { - WRITE_WARNING("got wkbMultiPolygon"); - break; - } - default: - WRITE_WARNING("Unsupported shape type occurred"); - break; - } - */ - OGRFeature::DestroyFeature(feature); - } -#if GDAL_VERSION_MAJOR < 2 - OGRDataSource::DestroyDataSource(ds); -#else - GDALClose(ds); -#endif - OCTDestroyCoordinateTransformation(reinterpret_cast(toWGS84)); - OGRCleanupAll(); - return numFeatures; -#else - UNUSED_PARAMETER(file); - WRITE_ERROR("Cannot load shape file since SUMO was compiled without GDAL support."); - return 0; -#endif -} - - -int -NBHeightMapper::loadTiff(const std::string& file) { -#ifdef HAVE_GDAL - GDALAllRegister(); - GDALDataset* poDataset = (GDALDataset*)GDALOpen(file.c_str(), GA_ReadOnly); - if (poDataset == 0) { - WRITE_ERROR("Cannot load GeoTIFF file."); - return 0; - } - Boundary boundary; - const int xSize = poDataset->GetRasterXSize(); - const int ySize = poDataset->GetRasterYSize(); - double adfGeoTransform[6]; - if (poDataset->GetGeoTransform(adfGeoTransform) == CE_None) { - Position topLeft(adfGeoTransform[0], adfGeoTransform[3]); - mySizeOfPixel.set(adfGeoTransform[1], adfGeoTransform[5]); - const double horizontalSize = xSize * mySizeOfPixel.x(); - const double verticalSize = ySize * mySizeOfPixel.y(); - boundary.add(topLeft); - boundary.add(topLeft.x() + horizontalSize, topLeft.y() + verticalSize); - } else { - WRITE_ERROR("Could not parse geo information from " + file + "."); - return 0; - } - const int picSize = xSize * ySize; - int16_t* raster = (int16_t*)CPLMalloc(sizeof(int16_t) * picSize); - for (int i = 1; i <= poDataset->GetRasterCount(); i++) { - GDALRasterBand* poBand = poDataset->GetRasterBand(i); - if (poBand->GetColorInterpretation() != GCI_GrayIndex) { - WRITE_ERROR("Unknown color band in " + file + "."); - clearData(); - break; - } - if (poBand->GetRasterDataType() != GDT_Int16) { - WRITE_ERROR("Unknown data type in " + file + "."); - clearData(); - break; - } - assert(xSize == poBand->GetXSize() && ySize == poBand->GetYSize()); - if (poBand->RasterIO(GF_Read, 0, 0, xSize, ySize, raster, xSize, ySize, GDT_Int16, 0, 0) == CE_Failure) { - WRITE_ERROR("Failure in reading " + file + "."); - clearData(); - break; - } - } - GDALClose(poDataset); - myRasters.push_back(std::make_pair(boundary, raster)); - return picSize; -#else - UNUSED_PARAMETER(file); - WRITE_ERROR("Cannot load GeoTIFF file since SUMO was compiled without GDAL support."); - return 0; -#endif -} - - -void -NBHeightMapper::clearData() { - for (Triangles::iterator it = myTriangles.begin(); it != myTriangles.end(); it++) { - delete *it; - } - myTriangles.clear(); -#ifdef HAVE_GDAL - for (auto& item : myRasters) { - CPLFree(item.second); - } - myRasters.clear(); -#endif - myBoundary.reset(); -} - - -// =========================================================================== -// Triangle member methods -// =========================================================================== -NBHeightMapper::Triangle::Triangle(const PositionVector& corners): - myCorners(corners) { - assert(myCorners.size() == 3); - // @todo assert non-colinearity -} - - -void -NBHeightMapper::Triangle::addSelf(const QueryResult& queryResult) const { - queryResult.triangles.push_back(this); -} - - -bool -NBHeightMapper::Triangle::contains(const Position& pos) const { - return myCorners.around(pos); -} - - -double -NBHeightMapper::Triangle::getZ(const Position& geo) const { - // en.wikipedia.org/wiki/Line-plane_intersection - Position p0 = myCorners.front(); - Position line(0, 0, 1); - p0.sub(geo); // p0 - l0 - Position normal = normalVector(); - return p0.dotProduct(normal) / line.dotProduct(normal); -} - - -Position -NBHeightMapper::Triangle::normalVector() const { - // @todo maybe cache result to avoid multiple computations? - Position side1 = myCorners[1] - myCorners[0]; - Position side2 = myCorners[2] - myCorners[0]; - return side1.crossProduct(side2); -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netbuild/NBHeightMapper.h b/Util/OSM2ODR/src/netbuild/NBHeightMapper.h deleted file mode 100644 index ff7abea85..000000000 --- a/Util/OSM2ODR/src/netbuild/NBHeightMapper.h +++ /dev/null @@ -1,194 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2011-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NBHeightMapper.h -/// @author Jakob Erdmann -/// @author Laura Bieker -/// @author Michael Behrisch -/// @date Sept 2011 -/// -// Set z-values for all network positions based on data from a height map -/****************************************************************************/ -#pragma once -#include - -#ifdef WIN32 -typedef __int16 int16_t; -#else -#include -#endif - -#include -#include -#include -#include -#include - -#define TRIANGLE_RTREE_QUAL RTree - -// =========================================================================== -// class declarations -// =========================================================================== -class OptionsCont; - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NBHeightMapper - * @brief Set z-values for all network positions based on data from a height map - * - * Importing data from '.shp'-files works only if SUMO was compiled with GDAL-support. - * If not, an error message is generated. - */ -class NBHeightMapper { - - friend class NBHeightMapperTest; - -public: - /** @brief loads height map data if any loading options are set - * - * @param[in] oc The options container to get further options from - * @exception ProcessError if something fails - */ - static void loadIfSet(OptionsCont& oc); - - /// @brief return the singleton instance (maybe 0) - static const NBHeightMapper& get(); - - /// @brief returns whether the NBHeightMapper has data - bool ready() const; - - /// @brief returns the convex boundary of all known triangles - const Boundary& getBoundary() { - return myInstance.myBoundary; - } - - /// @brief returns height for the given geo coordinate (WGS84) - double getZ(const Position& geo) const; - - class QueryResult; - /* @brief content class for the rtree. Since we wish to be able to use the - * rtree for spatial querying we have to jump through some minor hoops: - * We let each found triangle callback the NBHeightMapper and add itself the - * the query result - * */ - class Triangle { - - public: - Triangle(const PositionVector& corners); - ~Triangle() {}; - - /// @brief callback for RTree search - void addSelf(const QueryResult& queryResult) const; - - /// @brief checks whether pos lies within triangle (only checks x,y) - bool contains(const Position& pos) const; - - /// @brief returns the projection of the give geoCoordinate (WGS84) onto triangle plane - double getZ(const Position& geo) const; - - /// @brief returns the normal vector for this triangles plane - Position normalVector() const; - - /// @brief the corners of the triangle - PositionVector myCorners; - - }; - - typedef std::vector Triangles; - - /// @brief class for cirumventing the const-restriction of RTree::Search-context - class QueryResult { - public: - QueryResult() {}; - ~QueryResult() {}; - // @brief method not realy const - void add(Triangle* triangle) const { - triangles.push_back(triangle); - }; - mutable Triangles triangles; - }; - -private: - /// @brief the singleton instance - static NBHeightMapper myInstance; - - Triangles myTriangles; - - /// @brief The RTree for spatial queries - TRIANGLE_RTREE_QUAL myRTree; - - /// @brief raster height information in m for all loaded files - std::vector > myRasters; - - /// @brief dimensions of one pixel in raster data - Position mySizeOfPixel; - - /// @brief convex boundary of all known triangles; - Boundary myBoundary; - -private: - /// @brief private constructor and destructor (Singleton) - NBHeightMapper(); - ~NBHeightMapper(); - - /// @brief adds one triangles worth of height data - void addTriangle(PositionVector corners); - - /** @brief load height data from Arcgis-shape file and returns the number of parsed features - * @return The number of parsed features - * @throws ProcessError - */ - int loadShapeFile(const std::string& file); - - /** @brief load height data from GeoTIFF file and returns the number of non void pixels - * @return The number of valid pixels - * @throws ProcessError - */ - int loadTiff(const std::string& file); - - /// @brief clears loaded data - void clearData(); - - /// @brief Invalidated copy constructor. - NBHeightMapper(const NBHeightMapper&); - - /// @brief Invalidated assignment operator. - NBHeightMapper& operator=(const NBHeightMapper&); - -}; - - -// =========================================================================== -// RTree specialization for speedup and avoiding warnings (ripped from SUMORTree.h) -// =========================================================================== -template<> -inline float TRIANGLE_RTREE_QUAL::RectSphericalVolume(Rect* a_rect) { - ASSERT(a_rect); - const float extent0 = a_rect->m_max[0] - a_rect->m_min[0]; - const float extent1 = a_rect->m_max[1] - a_rect->m_min[1]; - return .78539816f * (extent0 * extent0 + extent1 * extent1); -} - -template<> -inline TRIANGLE_RTREE_QUAL::Rect TRIANGLE_RTREE_QUAL::CombineRect(Rect* a_rectA, Rect* a_rectB) { - ASSERT(a_rectA && a_rectB); - Rect newRect; - newRect.m_min[0] = rtree_min(a_rectA->m_min[0], a_rectB->m_min[0]); - newRect.m_max[0] = rtree_max(a_rectA->m_max[0], a_rectB->m_max[0]); - newRect.m_min[1] = rtree_min(a_rectA->m_min[1], a_rectB->m_min[1]); - newRect.m_max[1] = rtree_max(a_rectA->m_max[1], a_rectB->m_max[1]); - return newRect; -} diff --git a/Util/OSM2ODR/src/netbuild/NBHelpers.cpp b/Util/OSM2ODR/src/netbuild/NBHelpers.cpp deleted file mode 100644 index 920dd2b3c..000000000 --- a/Util/OSM2ODR/src/netbuild/NBHelpers.cpp +++ /dev/null @@ -1,135 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NBHelpers.cpp -/// @author Daniel Krajzewicz -/// @author Sascha Krieg -/// @author Michael Behrisch -/// @author Jakob Erdmann -/// @date Tue, 20 Nov 2001 -/// -// Some mathematical helper methods -/****************************************************************************/ -#include - -#include -#include -#include -#include -#include -//#include -#include -#include -#include -#include -#include -#include -#include "NBNode.h" -#include "NBHelpers.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -double -NBHelpers::relAngle(double angle1, double angle2) { - angle2 -= angle1; - while (angle2 > 180.) { - angle2 -= 360.; - } - while (angle2 < -180.) { - angle2 += 360.; - } - return angle2; -} - - -double -NBHelpers::normRelAngle(double angle1, double angle2) { - double rel = relAngle(angle1, angle2); - if (rel + NUMERICAL_EPS >= 180) { - return -180; - } else { - return rel; - } -} - - -std::string -NBHelpers::normalIDRepresentation(const std::string& id) { - std::stringstream strm1(id); - long numid; - strm1 >> numid; - std::stringstream strm2; - strm2 << numid; - return strm2.str(); -} - - -double -NBHelpers::distance(NBNode* node1, NBNode* node2) { - return node1->getPosition().distanceTo(node2->getPosition()); -} - - -void -NBHelpers::loadEdgesFromFile(const std::string& file, std::set& into) { - std::ifstream strm(file.c_str()); - if (!strm.good()) { - throw ProcessError("Could not load names of edges too keep from '" + file + "'."); - } - while (strm.good()) { - std::string name; - strm >> name; - into.insert(name); - // maybe we're loading an edge-selection - if (StringUtils::startsWith(name, "edge:")) { - into.insert(name.substr(5)); - } - } -} - - -void -NBHelpers::loadPrefixedIDsFomFile(const std::string& file, const std::string prefix, std::set& into) { - std::ifstream strm(file.c_str()); - if (!strm.good()) { - throw ProcessError("Could not load IDs from '" + file + "'."); - } - while (strm.good()) { - std::string prefixedID; - strm >> prefixedID; - if (StringUtils::startsWith(prefixedID, prefix)) { - into.insert(prefixedID.substr(prefix.size())); - } - } -} - -void -NBHelpers::interpretLaneID(const std::string& lane_id, std::string& edge_id, int& index) { - // assume lane_id = edge_id + '_' + index - const std::string::size_type sep_index = lane_id.rfind('_'); - if (sep_index == std::string::npos) { - WRITE_ERROR("Invalid lane id '" + lane_id + "' (missing '_')."); - } - edge_id = lane_id.substr(0, sep_index); - std::string index_string = lane_id.substr(sep_index + 1); - try { - index = StringUtils::toInt(index_string); - } catch (NumberFormatException&) { - WRITE_ERROR("Invalid lane index '" + index_string + "' for lane '" + lane_id + "'."); - } -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netbuild/NBHelpers.h b/Util/OSM2ODR/src/netbuild/NBHelpers.h deleted file mode 100644 index d5acacb8a..000000000 --- a/Util/OSM2ODR/src/netbuild/NBHelpers.h +++ /dev/null @@ -1,70 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NBHelpers.h -/// @author Daniel Krajzewicz -/// @author Sascha Krieg -/// @author Michael Behrisch -/// @author Jakob Erdmann -/// @date Tue, 20 Nov 2001 -/// -// Some mathematical helper methods -/****************************************************************************/ -#pragma once -#include - -#include -#include - - -// =========================================================================== -// class declarations -// =========================================================================== -class NBNode; -class Position; - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NBHelpers - * Some mathmatical methods for the computation of angles - */ -class NBHelpers { -public: - /// @brief computes the relative angle between the two angles - static double relAngle(double angle1, double angle2); - - /// @brief ensure that reverse relAngles (>=179.999) always count as turnarounds (-180) - static double normRelAngle(double angle1, double angle2); - - /// @brief converts the numerical id to its "normal" string representation - static std::string normalIDRepresentation(const std::string& id); - - /// @brief returns the distance between both nodes - static double distance(NBNode* node1, NBNode* node2); - - /// @brief Add edge ids defined in file (either ID or edge:ID per line) into the given set - static void loadEdgesFromFile(const std::string& file, std::set& into); - - /// @brief Add prefixed ids defined in file - static void loadPrefixedIDsFomFile(const std::string& file, const std::string prefix, std::set& into); - - /** @brief parses edge-id and index from lane-id - * @param[in] lane_id The lane-id - * @param[out] edge_id ID of this lane's edge - * @param[out] index Index of this lane - */ - static void interpretLaneID(const std::string& lane_id, std::string& edge_id, int& index); -}; diff --git a/Util/OSM2ODR/src/netbuild/NBLinkPossibilityMatrix.h b/Util/OSM2ODR/src/netbuild/NBLinkPossibilityMatrix.h deleted file mode 100644 index 8b494ed8b..000000000 --- a/Util/OSM2ODR/src/netbuild/NBLinkPossibilityMatrix.h +++ /dev/null @@ -1,37 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NBLinkPossibilityMatrix.h -/// @author Daniel Krajzewicz -/// @author Sascha Krieg -/// @author Michael Behrisch -/// @date Sept 2002 -/// -// A matric to describe whether two links are foes to each other -/****************************************************************************/ -#pragma once -#include - -#include -#include - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NBLinkPossibilityMatrix - * Storing the information which links may be used simultanously, this matrix - * is simply made by a vector of bitsets - */ -typedef std::vector > NBLinkPossibilityMatrix; diff --git a/Util/OSM2ODR/src/netbuild/NBLoadedSUMOTLDef.cpp b/Util/OSM2ODR/src/netbuild/NBLoadedSUMOTLDef.cpp deleted file mode 100644 index 8dd357495..000000000 --- a/Util/OSM2ODR/src/netbuild/NBLoadedSUMOTLDef.cpp +++ /dev/null @@ -1,861 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2011-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NBLoadedSUMOTLDef.cpp -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @author Jakob Erdmann -/// @date Mar 2011 -/// -// A complete traffic light logic loaded from a sumo-net. (opted to reimplement -// since NBLoadedTLDef is quite vissim specific) -/****************************************************************************/ -#include - -#include -#include -#include -#include -#include -#include -#include -#include "NBTrafficLightLogic.h" -#include "NBOwnTLDef.h" -#include "NBTrafficLightDefinition.h" -#include "NBLoadedSUMOTLDef.h" -#include "NBNetBuilder.h" -#include "NBOwnTLDef.h" -#include "NBNode.h" - -//#define DEBUG_RECONSTRUCTION - -// =========================================================================== -// method definitions -// =========================================================================== - -NBLoadedSUMOTLDef::NBLoadedSUMOTLDef(const std::string& id, const std::string& programID, - SUMOTime offset, TrafficLightType type) : - NBTrafficLightDefinition(id, programID, offset, type), - myTLLogic(nullptr), - myReconstructAddedConnections(false), - myReconstructRemovedConnections(false), - myPhasesLoaded(false) { - myTLLogic = new NBTrafficLightLogic(id, programID, 0, offset, type); -} - - -NBLoadedSUMOTLDef::NBLoadedSUMOTLDef(const NBTrafficLightDefinition& def, const NBTrafficLightLogic& logic) : - // allow for adding a new program for the same def: take the offset and programID from the new logic - NBTrafficLightDefinition(def.getID(), logic.getProgramID(), logic.getOffset(), def.getType()), - myTLLogic(new NBTrafficLightLogic(logic)), - myReconstructAddedConnections(false), - myReconstructRemovedConnections(false), - myPhasesLoaded(false) { - assert(def.getType() == logic.getType()); - myControlledLinks = def.getControlledLinks(); - myControlledNodes = def.getNodes(); - const NBLoadedSUMOTLDef* sumoDef = dynamic_cast(&def); - updateParameters(def.getParametersMap()); - if (sumoDef != nullptr) { - myReconstructAddedConnections = sumoDef->myReconstructAddedConnections; - myReconstructRemovedConnections = sumoDef->myReconstructRemovedConnections; - } -} - - -NBLoadedSUMOTLDef::~NBLoadedSUMOTLDef() { - delete myTLLogic; -} - - -NBTrafficLightLogic* -NBLoadedSUMOTLDef::myCompute(int brakingTimeSeconds) { - // @todo what to do with those parameters? - UNUSED_PARAMETER(brakingTimeSeconds); - reconstructLogic(); - myTLLogic->closeBuilding(false); - patchIfCrossingsAdded(); - myTLLogic->closeBuilding(); - return new NBTrafficLightLogic(myTLLogic); -} - - -void -NBLoadedSUMOTLDef::addConnection(NBEdge* from, NBEdge* to, int fromLane, int toLane, int linkIndex, int linkIndex2, bool reconstruct) { - assert(myTLLogic->getNumLinks() > 0); // logic should be loaded by now - if (linkIndex >= (int)myTLLogic->getNumLinks()) { - throw ProcessError("Invalid linkIndex " + toString(linkIndex) + " for traffic light '" + getID() + - "' with " + toString(myTLLogic->getNumLinks()) + " links."); - } - if (linkIndex2 >= (int)myTLLogic->getNumLinks()) { - throw ProcessError("Invalid linkIndex2 " + toString(linkIndex2) + " for traffic light '" + getID() + - "' with " + toString(myTLLogic->getNumLinks()) + " links."); - } - NBConnection conn(from, fromLane, to, toLane, linkIndex, linkIndex2); - // avoid duplicates - auto newEnd = remove_if(myControlledLinks.begin(), myControlledLinks.end(), connection_equal(conn)); - // remove_if does not remove, only re-order - myControlledLinks.erase(newEnd, myControlledLinks.end()); - myControlledLinks.push_back(conn); - addNode(from->getToNode()); - addNode(to->getFromNode()); - // added connections are definitely controlled. make sure none are removed because they lie within the tl - // myControlledInnerEdges.insert(from->getID()); // @todo recheck: this appears to be obsolete - // set this information now so that it can be used while loading diffs - from->setControllingTLInformation(conn, getID()); - myReconstructAddedConnections |= reconstruct; -} - -void -NBLoadedSUMOTLDef::setProgramID(const std::string& programID) { - NBTrafficLightDefinition::setProgramID(programID); - myTLLogic->setProgramID(programID); -} - -void -NBLoadedSUMOTLDef::setTLControllingInformation() const { - if (myReconstructAddedConnections) { - NBOwnTLDef dummy(DummyID, myControlledNodes, 0, getType()); - dummy.setParticipantsInformation(); - dummy.setTLControllingInformation(); - for (std::vector::const_iterator i = myControlledNodes.begin(); i != myControlledNodes.end(); i++) { - (*i)->removeTrafficLight(&dummy); - } - } - if (myReconstructRemovedConnections) { - return; // will be called again in reconstructLogic() - } - // if nodes have been removed our links may have been invalidated as well - // since no logic will be built anyway there is no reason to inform any edges - if (amInvalid()) { - return; - } - // set the information about the link's positions within the tl into the - // edges the links are starting at, respectively - for (NBConnectionVector::const_iterator it = myControlledLinks.begin(); it != myControlledLinks.end(); it++) { - const NBConnection& c = *it; - if (c.getTLIndex() >= (int)myTLLogic->getNumLinks()) { - throw ProcessError("Invalid linkIndex " + toString(c.getTLIndex()) + " for traffic light '" + getID() + - "' with " + toString(myTLLogic->getNumLinks()) + " links."); - } - NBEdge* edge = c.getFrom(); - if (edge != nullptr && edge->getNumLanes() > c.getFromLane()) { - // logic may have yet to be reconstructed - edge->setControllingTLInformation(c, getID()); - } - } -} - - -void -NBLoadedSUMOTLDef::remapRemoved(NBEdge*, const EdgeVector&, const EdgeVector&) {} - - -void -NBLoadedSUMOTLDef::replaceRemoved(NBEdge* removed, int removedLane, NBEdge* by, int byLane, bool incoming) { - for (NBConnectionVector::iterator it = myControlledLinks.begin(); it != myControlledLinks.end(); ++it) { - if (incoming) { - (*it).replaceFrom(removed, removedLane, by, byLane); - } else { - (*it).replaceTo(removed, removedLane, by, byLane); - } - } -} - - -void -NBLoadedSUMOTLDef::addPhase(SUMOTime duration, const std::string& state, SUMOTime minDur, SUMOTime maxDur, const std::vector& next, const std::string& name) { - myTLLogic->addStep(duration, state, minDur, maxDur, next, name); -} - - -bool -NBLoadedSUMOTLDef::amInvalid() const { - if (myControlledLinks.size() == 0) { - return true; - } - if (myIncomingEdges.size() == 0) { - return true; - } - return false; -} - - -void -NBLoadedSUMOTLDef::removeConnection(const NBConnection& conn, bool reconstruct) { - for (auto it = myControlledLinks.begin(); it != myControlledLinks.end();) { - if ((it->getFrom() == conn.getFrom() && - it->getTo() == conn.getTo() && - it->getFromLane() == conn.getFromLane() && - it->getToLane() == conn.getToLane()) - || (it->getTLIndex() == conn.getTLIndex() && - conn.getTLIndex() != conn.InvalidTlIndex && - (it->getFrom() == nullptr || it->getTo() == nullptr))) { - if (reconstruct) { - myReconstructRemovedConnections = true; - it++; - } else { - it = myControlledLinks.erase(it); - } - } else { - it++; - } - } -} - - -void -NBLoadedSUMOTLDef::setOffset(SUMOTime offset) { - myOffset = offset; - myTLLogic->setOffset(offset); -} - - -void -NBLoadedSUMOTLDef::setType(TrafficLightType type) { - myType = type; - myTLLogic->setType(type); -} - - -void -NBLoadedSUMOTLDef::collectEdges() { - if (myControlledLinks.size() == 0) { - NBTrafficLightDefinition::collectEdges(); - } - myIncomingEdges.clear(); - EdgeVector myOutgoing; - // collect the edges from the participating nodes - for (std::vector::iterator i = myControlledNodes.begin(); i != myControlledNodes.end(); i++) { - const EdgeVector& incoming = (*i)->getIncomingEdges(); - copy(incoming.begin(), incoming.end(), back_inserter(myIncomingEdges)); - const EdgeVector& outgoing = (*i)->getOutgoingEdges(); - copy(outgoing.begin(), outgoing.end(), back_inserter(myOutgoing)); - } - // check which of the edges are completely within the junction - // and which are uncontrolled as well (we already know myControlledLinks) - for (EdgeVector::iterator j = myIncomingEdges.begin(); j != myIncomingEdges.end();) { - NBEdge* edge = *j; - edge->setInsideTLS(false); // reset - // an edge lies within the logic if it is outgoing as well as incoming - EdgeVector::iterator k = std::find(myOutgoing.begin(), myOutgoing.end(), edge); - if (k != myOutgoing.end()) { - if (myControlledInnerEdges.count(edge->getID()) == 0) { - bool controlled = false; - for (NBConnectionVector::iterator it = myControlledLinks.begin(); it != myControlledLinks.end(); it++) { - if ((*it).getFrom() == edge) { - controlled = true; - break; - } - } - if (controlled) { - myControlledInnerEdges.insert(edge->getID()); - } else { - myEdgesWithin.push_back(edge); - edge->setInsideTLS(true); - ++j; //j = myIncomingEdges.erase(j); - continue; - } - } - } - ++j; - } -} - - -void -NBLoadedSUMOTLDef::collectLinks() { - if (myControlledLinks.size() == 0) { - // maybe we only loaded a different program for a default traffic light. - // Try to build links now. - collectAllLinks(myControlledLinks); - } -} - - -/// @brief patches signal plans by modifying lane indices -void -NBLoadedSUMOTLDef::shiftTLConnectionLaneIndex(NBEdge* edge, int offset, int threshold) { - // avoid shifting twice if the edge is incoming and outgoing to a joined TLS - if (myShifted.count(edge) == 0) { - /// XXX what if an edge should really be shifted twice? - myShifted.insert(edge); - for (NBConnectionVector::iterator it = myControlledLinks.begin(); it != myControlledLinks.end(); it++) { - (*it).shiftLaneIndex(edge, offset, threshold); - } - } -} - -void -NBLoadedSUMOTLDef::patchIfCrossingsAdded() { - const int size = myTLLogic->getNumLinks(); - int noLinksAll = 0; - for (NBConnectionVector::const_iterator it = myControlledLinks.begin(); it != myControlledLinks.end(); it++) { - const NBConnection& c = *it; - if (c.getTLIndex() != NBConnection::InvalidTlIndex) { - noLinksAll = MAX2(noLinksAll, (int)c.getTLIndex() + 1); - } - } - const int numNormalLinks = noLinksAll; - int oldCrossings = 0; - // collect crossings - bool customIndex = false; - std::vector crossings; - for (std::vector::iterator i = myControlledNodes.begin(); i != myControlledNodes.end(); i++) { - const std::vector& c = (*i)->getCrossings(); - // set tl indices for crossings - customIndex |= (*i)->setCrossingTLIndices(getID(), noLinksAll); - copy(c.begin(), c.end(), std::back_inserter(crossings)); - noLinksAll += (int)c.size(); - oldCrossings += (*i)->numCrossingsFromSumoNet(); - } - if ((int)crossings.size() != oldCrossings) { - std::vector phases = myTLLogic->getPhases(); - // do not rebuilt crossing states there are custom indices and the state string is long enough - if (phases.size() > 0 && ( - (int)(phases.front().state.size()) < noLinksAll || - ((int)(phases.front().state.size()) > noLinksAll && !customIndex))) { - // collect edges - EdgeVector fromEdges(size, (NBEdge*)nullptr); - EdgeVector toEdges(size, (NBEdge*)nullptr); - std::vector fromLanes(size, 0); - collectEdgeVectors(fromEdges, toEdges, fromLanes); - const std::string crossingDefaultState(crossings.size(), 'r'); - - // rebuild the logic (see NBOwnTLDef.cpp::myCompute) - NBTrafficLightLogic* newLogic = new NBTrafficLightLogic(getID(), getProgramID(), 0, myOffset, myType); - SUMOTime brakingTime = TIME2STEPS(computeBrakingTime(OptionsCont::getOptions().getFloat("tls.yellow.min-decel"))); - //std::cout << "patchIfCrossingsAdded for " << getID() << " numPhases=" << phases.size() << "\n"; - for (std::vector::const_iterator it = phases.begin(); it != phases.end(); it++) { - const std::string state = it->state.substr(0, numNormalLinks) + crossingDefaultState; - NBOwnTLDef::addPedestrianPhases(newLogic, it->duration, it->minDur, it->maxDur, state, crossings, fromEdges, toEdges); - } - NBOwnTLDef::addPedestrianScramble(newLogic, noLinksAll, TIME2STEPS(10), brakingTime, crossings, fromEdges, toEdges); - - delete myTLLogic; - myTLLogic = newLogic; - } else if (phases.size() == 0) { - WRITE_WARNING("Could not patch tlLogic '" + getID() + "' for changed crossings"); - } - } -} - - -void -NBLoadedSUMOTLDef::collectEdgeVectors(EdgeVector& fromEdges, EdgeVector& toEdges, std::vector& fromLanes) const { - assert(fromEdges.size() > 0); - assert(fromEdges.size() == toEdges.size()); - const int size = (int)fromEdges.size(); - - for (NBConnectionVector::const_iterator it = myControlledLinks.begin(); it != myControlledLinks.end(); it++) { - const NBConnection& c = *it; - if (c.getTLIndex() != NBConnection::InvalidTlIndex) { - if (c.getTLIndex() >= size) { - throw ProcessError("Invalid linkIndex " + toString(c.getTLIndex()) + " for traffic light '" + getID() + - "' with " + toString(size) + " links."); - } - fromEdges[c.getTLIndex()] = c.getFrom(); - toEdges[c.getTLIndex()] = c.getTo(); - fromLanes[c.getTLIndex()] = c.getFromLane(); - } - } -} - - -void -NBLoadedSUMOTLDef::initNeedsContRelation() const { - if (!amInvalid() && !myNeedsContRelationReady) { - myNeedsContRelation.clear(); - myRightOnRedConflicts.clear(); - const bool controlledWithin = !OptionsCont::getOptions().getBool("tls.uncontrolled-within"); - const std::vector phases = myTLLogic->getPhases(); - for (std::vector::const_iterator it = phases.begin(); it != phases.end(); it++) { - const std::string state = (*it).state; - for (NBConnectionVector::const_iterator it1 = myControlledLinks.begin(); it1 != myControlledLinks.end(); it1++) { - const NBConnection& c1 = *it1; - const int i1 = c1.getTLIndex(); - if (i1 == NBConnection::InvalidTlIndex || (state[i1] != 'g' && state[i1] != 's') || c1.getFrom() == nullptr || c1.getTo() == nullptr) { - continue; - } - for (NBConnectionVector::const_iterator it2 = myControlledLinks.begin(); it2 != myControlledLinks.end(); it2++) { - const NBConnection& c2 = *it2; - const int i2 = c2.getTLIndex(); - if (i2 != NBConnection::InvalidTlIndex - && i2 != i1 - && (state[i2] == 'G' || state[i2] == 'g') - && c2.getFrom() != nullptr && c2.getTo() != nullptr) { - const bool rightTurnConflict = NBNode::rightTurnConflict( - c1.getFrom(), c1.getTo(), c1.getFromLane(), c2.getFrom(), c2.getTo(), c2.getFromLane()); - const bool forbidden = forbids(c2.getFrom(), c2.getTo(), c1.getFrom(), c1.getTo(), true, controlledWithin); - const bool isFoes = foes(c2.getFrom(), c2.getTo(), c1.getFrom(), c1.getTo()) && !c2.getFrom()->isTurningDirectionAt(c2.getTo()); - if (forbidden || rightTurnConflict) { - myNeedsContRelation.insert(StreamPair(c1.getFrom(), c1.getTo(), c2.getFrom(), c2.getTo())); - } - if (isFoes && state[i1] == 's') { - myRightOnRedConflicts.insert(std::make_pair(i1, i2)); - //std::cout << getID() << " prog=" << getProgramID() << " phase=" << (it - phases.begin()) << " rightOnRedConflict i1=" << i1 << " i2=" << i2 << "\n"; - } - //std::cout << getID() << " i1=" << i1 << " i2=" << i2 << " rightTurnConflict=" << rightTurnConflict << " forbidden=" << forbidden << " isFoes=" << isFoes << "\n"; - } - } - } - } - } - myNeedsContRelationReady = true; - myRightOnRedConflictsReady = true; -} - - -bool -NBLoadedSUMOTLDef::rightOnRedConflict(int index, int foeIndex) const { - if (amInvalid()) { - return false; - } - if (!myRightOnRedConflictsReady) { - initNeedsContRelation(); - assert(myRightOnRedConflictsReady); - } - return std::find(myRightOnRedConflicts.begin(), myRightOnRedConflicts.end(), std::make_pair(index, foeIndex)) != myRightOnRedConflicts.end(); -} - - -void -NBLoadedSUMOTLDef::registerModifications(bool addedConnections, bool removedConnections) { - myReconstructAddedConnections |= addedConnections; - myReconstructRemovedConnections |= removedConnections; -} - -void -NBLoadedSUMOTLDef::reconstructLogic() { - const bool netedit = NBNetBuilder::runningNetedit(); -#ifdef DEBUG_RECONSTRUCTION - bool debugPrintModified = myReconstructAddedConnections || myReconstructRemovedConnections; - std::cout << getID() << " reconstructLogic added=" << myReconstructAddedConnections - << " removed=" << myReconstructRemovedConnections - << " valid=" << hasValidIndices() - << " phasesLoaded=" << myPhasesLoaded - << " oldLinks:\n"; - for (NBConnectionVector::iterator it = myControlledLinks.begin(); it != myControlledLinks.end(); ++it) { - std::cout << " " << *it << "\n"; - } -#endif - if (myReconstructAddedConnections) { - myReconstructAddedConnections = false; - // do not rebuild the logic when running netedit and all links are already covered by the program - if (!myPhasesLoaded && !(netedit && hasValidIndices())) { - // rebuild the logic from scratch - // XXX if a connection with the same from- and to-edge already exisits, its states could be copied instead - NBOwnTLDef dummy(DummyID, myControlledNodes, 0, getType()); - dummy.setParticipantsInformation(); - dummy.setProgramID(getProgramID()); - dummy.setTLControllingInformation(); - NBTrafficLightLogic* newLogic = dummy.compute(OptionsCont::getOptions()); - myIncomingEdges = dummy.getIncomingEdges(); - myControlledLinks = dummy.getControlledLinks(); - for (std::vector::const_iterator i = myControlledNodes.begin(); i != myControlledNodes.end(); i++) { - (*i)->removeTrafficLight(&dummy); - } - delete myTLLogic; - myTLLogic = newLogic; - if (newLogic != nullptr) { - newLogic->setID(getID()); - newLogic->setType(getType()); - newLogic->setOffset(getOffset()); - setTLControllingInformation(); - // reset crossing custom indices - for (NBNode* n : myControlledNodes) { - for (NBNode::Crossing* c : n->getCrossings()) { - c->customTLIndex = NBConnection::InvalidTlIndex; - } - } - - } - } else { - setTLControllingInformation(); - } - } - if (myReconstructRemovedConnections) { - myReconstructRemovedConnections = false; - // for each connection, check whether it is still valid - for (NBConnectionVector::iterator it = myControlledLinks.begin(); it != myControlledLinks.end();) { - const NBConnection con = (*it); - if (// edge still exists - std::find(myIncomingEdges.begin(), myIncomingEdges.end(), con.getFrom()) != myIncomingEdges.end() - // connection still exists - && con.getFrom()->hasConnectionTo(con.getTo(), con.getToLane(), con.getFromLane()) - // connection is still set to be controlled - && con.getFrom()->mayBeTLSControlled(con.getFromLane(), con.getTo(), con.getToLane())) { - it++; - } else { - // remove connection - const int removed = con.getTLIndex(); - it = myControlledLinks.erase(it); - // no automatic modificaions when running netedit - if (!myPhasesLoaded && !(netedit && hasValidIndices())) { - // shift index off successive connections and remove entry from all phases if the tlIndex was only used by this connection - bool exclusive = true; - for (NBConnection& other : myControlledLinks) { - if (other != con && other.getTLIndex() == removed) { - exclusive = false; - break; - } - } - if (exclusive) { - // shift indices above the removed index downward - for (NBConnection& other : myControlledLinks) { - if (other.getTLIndex() > removed) { - other.setTLIndex(other.getTLIndex() - 1); - } - } - // shift crossing custom indices above the removed index downward - for (NBNode* n : myControlledNodes) { - for (NBNode::Crossing* c : n->getCrossings()) { - if (c->customTLIndex > removed) { - c->customTLIndex--; - } - } - } - // rebuild the logic - NBTrafficLightLogic* newLogic = new NBTrafficLightLogic(getID(), getProgramID(), 0, myOffset, myType); - for (const NBTrafficLightLogic::PhaseDefinition& phase : myTLLogic->getPhases()) { - std::string newState = phase.state; - newState.erase(newState.begin() + removed); - newLogic->addStep(phase.duration, newState); - } - delete myTLLogic; - myTLLogic = newLogic; - } - } - } - } - setTLControllingInformation(); - } -#ifdef DEBUG_RECONSTRUCTION - if (debugPrintModified) { - std::cout << " newLinks:\n"; - for (NBConnectionVector::iterator it = myControlledLinks.begin(); it != myControlledLinks.end(); ++it) { - std::cout << " " << *it << "\n"; - } - } -#endif -} - - -int -NBLoadedSUMOTLDef::getMaxIndex() { - int maxIndex = -1; - for (const NBConnection& c : myControlledLinks) { - maxIndex = MAX2(maxIndex, c.getTLIndex()); - maxIndex = MAX2(maxIndex, c.getTLIndex2()); - } - for (NBNode* n : myControlledNodes) { - for (NBNode::Crossing* c : n->getCrossings()) { - maxIndex = MAX2(maxIndex, c->tlLinkIndex); - maxIndex = MAX2(maxIndex, c->tlLinkIndex2); - } - } - return maxIndex; -} - - -int -NBLoadedSUMOTLDef::getMaxValidIndex() { - return myTLLogic->getNumLinks() - 1; -} - - -bool -NBLoadedSUMOTLDef::hasValidIndices() const { - for (const NBConnection& c : myControlledLinks) { - if (c.getTLIndex() == NBConnection::InvalidTlIndex) { - return false; - } - } - for (NBNode* n : myControlledNodes) { - for (NBNode::Crossing* c : n->getCrossings()) { - if (c->tlLinkIndex == NBConnection::InvalidTlIndex) { - return false; - } - } - } - // method getMaxIndex() is const but cannot be declare as such due to inheritance - return const_cast(this)->getMaxIndex() < myTLLogic->getNumLinks(); -} - - -std::string -NBLoadedSUMOTLDef::getStates(int index) { - assert(index >= 0); - assert(index <= getMaxIndex()); - std::string result; - for (auto& pd : myTLLogic->getPhases()) { - result += pd.state[index]; - } - return result; -} - -bool -NBLoadedSUMOTLDef::isUsed(int index) { - for (const NBConnection& c : myControlledLinks) { - if (c.getTLIndex() == index || c.getTLIndex2() == index) { - return true; - } - } - for (NBNode* n : myControlledNodes) { - for (NBNode::Crossing* c : n->getCrossings()) { - if (c->tlLinkIndex == index || c->tlLinkIndex2 == index) { - return true; - } - } - } - return false; -} - -std::set -NBLoadedSUMOTLDef::getEdgesUsingIndex(int index) const { - std::set result; - for (const NBConnection& c : myControlledLinks) { - if (c.getTLIndex() == index || c.getTLIndex2() == index) { - result.insert(c.getFrom()); - } - } - return result; -} - - -void -NBLoadedSUMOTLDef::replaceIndex(int oldIndex, int newIndex) { - if (oldIndex == newIndex) { - return; - } - for (NBConnection& c : myControlledLinks) { - if (c.getTLIndex() == oldIndex) { - c.setTLIndex(newIndex); - } - if (c.getTLIndex2() == oldIndex) { - c.setTLIndex2(newIndex); - } - } - for (NBNode* n : myControlledNodes) { - for (NBNode::Crossing* c : n->getCrossings()) { - if (c->tlLinkIndex == oldIndex) { - c->tlLinkIndex = newIndex; - } - if (c->tlLinkIndex2 == oldIndex) { - c->tlLinkIndex2 = newIndex; - } - } - } -} - -void -NBLoadedSUMOTLDef::groupSignals() { - const int maxIndex = getMaxIndex(); - std::vector unusedIndices; - for (int i = 0; i <= maxIndex; i++) { - if (isUsed(i)) { - std::set edges = getEdgesUsingIndex(i); - // compactify - replaceIndex(i, i - (int)unusedIndices.size()); - if (edges.size() == 0) { - // do not group pedestrian crossing signals - continue; - } - std::string states = getStates(i); - for (int j = i + 1; j <= maxIndex; j++) { - // only group signals from the same edges as is commonly done by - // traffic engineers - if (states == getStates(j) && edges == getEdgesUsingIndex(j)) { - replaceIndex(j, i - (int)unusedIndices.size()); - } - } - } else { - unusedIndices.push_back(i); - } - } - for (int i = (int)unusedIndices.size() - 1; i >= 0; i--) { - myTLLogic->deleteStateIndex(unusedIndices[i]); - } - cleanupStates(); - //std::cout << "oldMaxIndex=" << maxIndex << " newMaxIndex=" << getMaxIndex() << " unused=" << toString(unusedIndices) << "\n"; - setTLControllingInformation(); -} - -void -NBLoadedSUMOTLDef::ungroupSignals() { - NBConnectionVector defaultOrdering; - collectAllLinks(defaultOrdering); - myTLLogic->setStateLength((int)myControlledLinks.size()); - std::vector states; // organized per link rather than phase - int index = 0; - for (NBConnection& c : defaultOrdering) { - NBConnection& c2 = *find_if(myControlledLinks.begin(), myControlledLinks.end(), connection_equal(c)); - states.push_back(getStates(c2.getTLIndex())); - c2.setTLIndex(index++); - } - for (NBNode* n : myControlledNodes) { - for (NBNode::Crossing* c : n->getCrossings()) { - states.push_back(getStates(c->tlLinkIndex)); - c->tlLinkIndex = index++; - if (c->tlLinkIndex2 != NBConnection::InvalidTlIndex) { - states.push_back(getStates(c->tlLinkIndex2)); - c->tlLinkIndex2 = index++; - } - } - } - for (int i = 0; i < (int)states.size(); i++) { - for (int p = 0; p < (int)states[i].size(); p++) { - myTLLogic->setPhaseState(p, i, (LinkState)states[i][p]); - } - } - setTLControllingInformation(); -} - - -void -NBLoadedSUMOTLDef::copyIndices(NBTrafficLightDefinition* def) { - std::map oldStates; // organized per link index rather than phase - std::map newStates; // organized per link index rather than phase - for (NBConnection& c : def->getControlledLinks()) { - NBConnection& c2 = *find_if(myControlledLinks.begin(), myControlledLinks.end(), connection_equal(c)); - const int oldIndex = c2.getTLIndex(); - const int newIndex = c.getTLIndex(); - std::string states = getStates(oldIndex); - oldStates[oldIndex] = states; - if (newStates.count(newIndex) != 0 && newStates[newIndex] != states) { - WRITE_WARNING("Signal groups from program '" + def->getProgramID() + "' are incompatible with the states of program '" + getProgramID() + "' at tlLogic '" + getID() - + "'. Possibly unsafe program."); - } else { - newStates[newIndex] = states; - } - c2.setTLIndex(newIndex); - } - const int maxIndex = getMaxIndex(); - myTLLogic->setStateLength(maxIndex + 1); - for (int i = 0; i < (int)newStates.size(); i++) { - for (int p = 0; p < (int)newStates[i].size(); p++) { - myTLLogic->setPhaseState(p, i, (LinkState)newStates[i][p]); - } - } - setTLControllingInformation(); -} - - -bool -NBLoadedSUMOTLDef::cleanupStates() { - const int maxIndex = getMaxIndex(); - std::vector unusedIndices; - for (int i = 0; i <= maxIndex; i++) { - if (isUsed(i)) { - if (unusedIndices.size() > 0) { - replaceIndex(i, i - (int)unusedIndices.size()); - } - } else { - unusedIndices.push_back(i); - } - } - for (int i = (int)unusedIndices.size() - 1; i >= 0; i--) { - myTLLogic->deleteStateIndex(unusedIndices[i]); - } - if (unusedIndices.size() > 0) { - myTLLogic->setStateLength(maxIndex + 1 - (int)unusedIndices.size()); - setTLControllingInformation(); - return true; - } else { - return false; - } -} - - -void -NBLoadedSUMOTLDef::joinLogic(NBTrafficLightDefinition* def) { - def->setParticipantsInformation(); - def->compute(OptionsCont::getOptions()); - const int maxIndex = MAX2(getMaxIndex(), def->getMaxIndex()); - myTLLogic->setStateLength(maxIndex + 1); - myControlledLinks.insert(myControlledLinks.end(), def->getControlledLinks().begin(), def->getControlledLinks().end()); -} - -bool -NBLoadedSUMOTLDef::usingSignalGroups() const { - // count how often each index is used - std::map indexUsage; - for (const NBConnection& c : myControlledLinks) { - indexUsage[c.getTLIndex()]++; - } - for (NBNode* n : myControlledNodes) { - for (NBNode::Crossing* c : n->getCrossings()) { - indexUsage[c->tlLinkIndex]++; - indexUsage[c->tlLinkIndex2]++; - } - } - for (auto it : indexUsage) { - if (it.first >= 0 && it.second > 1) { - return true; - } - } - return false; -} - -void -NBLoadedSUMOTLDef::guessMinMaxDuration() { - bool hasMinMaxDur = false; - for (auto phase : myTLLogic->getPhases()) { - if (phase.maxDur != UNSPECIFIED_DURATION) { - //std::cout << " phase=" << phase.state << " maxDur=" << phase.maxDur << "\n"; - hasMinMaxDur = true; - } - } - if (!hasMinMaxDur) { - const SUMOTime minMinDur = TIME2STEPS(OptionsCont::getOptions().getInt("tls.min-dur")); - const SUMOTime maxDur = TIME2STEPS(OptionsCont::getOptions().getInt("tls.max-dur")); - std::set yellowIndices; - for (auto phase : myTLLogic->getPhases()) { - for (int i = 0; i < (int)phase.state.size(); i++) { - if (phase.state[i] == 'y' || phase.state[i] == 'Y') { - yellowIndices.insert(i); - } - } - } - for (int ip = 0; ip < (int)myTLLogic->getPhases().size(); ip++) { - bool needMinMaxDur = false; - auto phase = myTLLogic->getPhases()[ip]; - std::set greenIndices; - if (phase.state.find_first_of("yY") != std::string::npos) { - continue; - } - for (int i = 0; i < (int)phase.state.size(); i++) { - if (yellowIndices.count(i) != 0 && phase.state[i] == 'G') { - needMinMaxDur = true; - greenIndices.insert(i); - } - } - if (needMinMaxDur) { - double maxSpeed = 0; - for (NBConnection& c : myControlledLinks) { - if (greenIndices.count(c.getTLIndex()) != 0) { - maxSpeed = MAX2(maxSpeed, c.getFrom()->getLaneSpeed(c.getFromLane())); - } - } - // 5s at 50km/h, 10s at 80km/h, rounded to full seconds - const double minDurBySpeed = maxSpeed * 3.6 / 6 - 3.3; - SUMOTime minDur = MAX2(minMinDur, TIME2STEPS(floor(minDurBySpeed + 0.5))); - myTLLogic->setPhaseMinDuration(ip, minDur); - myTLLogic->setPhaseMaxDuration(ip, maxDur); - } - } - } -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netbuild/NBLoadedSUMOTLDef.h b/Util/OSM2ODR/src/netbuild/NBLoadedSUMOTLDef.h deleted file mode 100644 index 921a8eef7..000000000 --- a/Util/OSM2ODR/src/netbuild/NBLoadedSUMOTLDef.h +++ /dev/null @@ -1,253 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2011-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NBLoadedSUMOTLDef.h -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date Mar 2011 -/// -// A complete traffic light logic loaded from a sumo-net. (opted to reimplement -// since NBLoadedTLDef is quite vissim specific) -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include -#include "NBNode.h" -#include "NBEdgeCont.h" -#include "NBTrafficLightDefinition.h" -#include "NBTrafficLightLogic.h" -#include - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NBLoadedSUMOTLDef - * @brief A loaded (complete) traffic light logic - */ -class NBLoadedSUMOTLDef : public NBTrafficLightDefinition { -public: - - /** @brief Constructor - * @param[in] id The id of the tls - * @param[in] programID The programID for the computed logic - * @param[in] offset The offset for the computed logic - * @param[in] type The algorithm type for the computed logic - */ - NBLoadedSUMOTLDef(const std::string& id, const std::string& programID, SUMOTime offset, TrafficLightType type); - - /** @brief Constructor that copies from an existing definition and its computed logic (used by NETEDIT) - * @param[in] def The definition to copy - * @param[in] logic The computed logic of the given def - */ - NBLoadedSUMOTLDef(const NBTrafficLightDefinition& def, const NBTrafficLightLogic& logic); - - - /// @brief Destructor - ~NBLoadedSUMOTLDef(); - - /** @brief Sets the programID - * @param[in] programID The new ID of the program (subID) - */ - void setProgramID(const std::string& programID); - - /** @brief Informs edges about being controlled by a tls - */ - void setTLControllingInformation() const; - - /** @brief Replaces occurences of the removed edge in incoming/outgoing edges of all definitions - * @param[in] removed The removed edge - * @param[in] incoming The edges to use instead if an incoming edge was removed - * @param[in] outgoing The edges to use instead if an outgoing edge was removed - */ - void remapRemoved(NBEdge* removed, - const EdgeVector& incoming, const EdgeVector& outgoing); - - - /** @brief Replaces a removed edge/lane - * @param[in] removed The edge to replace - * @param[in] removedLane The lane of this edge to replace - * @param[in] by The edge to insert instead - * @param[in] byLane This edge's lane to insert instead - */ - void replaceRemoved(NBEdge* removed, int removedLane, - NBEdge* by, int byLane, bool incoming); - - /** @brief patches signal plans by modifying lane indices - * with the given offset, only indices with a value above threshold are modified - */ - void shiftTLConnectionLaneIndex(NBEdge* edge, int offset, int threshold = -1); - - /** @brief Adds a phase to the logic - * the new phase is inserted at the end of the list of already added phases - * @param[in] duration The duration of the phase to add - * @param[in] state The state definition of a tls phase - * @param[in] minDur The minimum duration of the phase to add - * @param[in] maxDur The maximum duration of the phase to add - */ - void addPhase(SUMOTime duration, const std::string& state, SUMOTime minDur, SUMOTime maxDur, const std::vector& next, const std::string& name); - - /// @brief mark phases as load - void phasesLoaded() { - myPhasesLoaded = true; - } - - /** @brief Adds a connection and immediately informs the edges - */ - void addConnection(NBEdge* from, NBEdge* to, int fromLane, int toLane, int linkIndex, int linkIndex2, bool reconstruct = true); - - - /** @brief removes the given connection from the traffic light - * if recontruct=true, reconstructs the logic and informs the edges for immediate use in NETEDIT - * @note: tlIndex is not necessarily unique. we need the whole connection data here - */ - void removeConnection(const NBConnection& conn, bool reconstruct = true); - - /// @brief register changes that necessitate recomputation - void registerModifications(bool addedConnections, bool removedConnections); - - /** @brief Returns the internal logic - */ - NBTrafficLightLogic* getLogic() { - return myTLLogic; - } - - /** @brief Sets the offset of this tls - * @param[in] offset The offset of this cycle - */ - void setOffset(SUMOTime offset); - - /** @brief Sets the algorithm type of this tls - * @param[in] offset The algorithm type of this tls - */ - void setType(TrafficLightType type); - - /// @brief whether the given index must yield to the foeIndex while turing right on a red light - bool rightOnRedConflict(int index, int foeIndex) const; - - /* @brief shortens phase states to remove states that are not referenced by - * any controlled link and returns whether states were shortened - */ - bool cleanupStates(); - - /// @brief whether this definition uses signal group (multiple connections with the same link index) - bool usingSignalGroups() const; - - /// @brief join nodes and states from the given logic (append red state) - void joinLogic(NBTrafficLightDefinition* def); - - /// @brief heuristically add minDur and maxDur when switching from tlType fixed to actuated - void guessMinMaxDuration(); - - /// @brief let connections with the same state use the same link index - void groupSignals(); - - /// @brief let all connections use a distinct link index - void ungroupSignals(); - - /// @brief copy the assignment of link indices to connections from the given definition and rebuilt the states to match - // Note: Issues a warning when the grouping of def is incompatible with the current states - void copyIndices(NBTrafficLightDefinition* def); - -protected: - /** @brief Collects the links participating in this traffic light - * (only if not previously loaded) - */ - void collectLinks(); - - /** @brief Build the list of participating edges - */ - void collectEdges(); - - /** @brief Computes the traffic light logic finally in dependence to the type - * @param[in] brakingTime Duration a vehicle needs for braking in front of the tls in seconds - * @return The computed logic - */ - NBTrafficLightLogic* myCompute(int brakingTimeSeconds); - - bool amInvalid() const; - - /* initialize myNeedsContRelation and set myNeedsContRelationReady to true */ - void initNeedsContRelation() const; - - /// @brief return the highest known tls link index used by any controlled connection or crossing - int getMaxIndex(); - - ///@brief Returns the maximum index controlled by this traffic light - int getMaxValidIndex(); - - /// @brief get all states for the given link index - std::string getStates(int index); - - /// @brief return whether the given link index is used by any connectons - bool isUsed(int index); - - /// @brief replace the given link index in all connections - void replaceIndex(int oldIndex, int newIndex); - - /// brief retrieve all edges with connections that use the given traffic light index - std::set getEdgesUsingIndex(int index) const; - -private: - - /** @brief phases are added directly to myTLLogic which is then returned in myCompute() */ - NBTrafficLightLogic* myTLLogic; - - /// @brief repair the plan if controlled nodes received pedestrian crossings - void patchIfCrossingsAdded(); - - /// @brief set of edges with shifted lane indices (to avoid shifting twice) - std::set myShifted; - - /// @brief whether the logic must be reconstructed - bool myReconstructAddedConnections; - bool myReconstructRemovedConnections; - bool myPhasesLoaded; - - /** @brief Collects the edges for each tlIndex - * @param[out] fromEdges The from-edge for each controlled tlIndex - * @param[out] toEdges The to-edge for each controlled tlIndex - * @param[out] fromLanes The from-lanes for each controlled tlIndex - */ - void collectEdgeVectors(EdgeVector& fromEdges, EdgeVector& toEdges, std::vector& fromLanes) const; - - /// @brief adapt to removal or addition of connections - void reconstructLogic(); - - /// @brief return whether all tls link indices are valid - bool hasValidIndices() const; - -private: - /// @brief class for identifying connections - class connection_equal { - public: - /// constructor - connection_equal(const NBConnection& c) : myC(c) {} - - bool operator()(const NBConnection& c) const { - return c.getFrom() == myC.getFrom() && c.getTo() == myC.getTo() && - c.getFromLane() == myC.getFromLane() && c.getToLane() == myC.getToLane(); - } - private: - const NBConnection& myC; - private: - /// @brief invalidated assignment operator - connection_equal& operator=(const connection_equal& s); - - }; - -}; diff --git a/Util/OSM2ODR/src/netbuild/NBLoadedTLDef.cpp b/Util/OSM2ODR/src/netbuild/NBLoadedTLDef.cpp deleted file mode 100644 index 8a0a6f076..000000000 --- a/Util/OSM2ODR/src/netbuild/NBLoadedTLDef.cpp +++ /dev/null @@ -1,669 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NBLoadedTLDef.cpp -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Sascha Krieg -/// @author Michael Behrisch -/// @date Tue, 29.05.2005 -/// -// A loaded (complete) traffic light logic -/****************************************************************************/ -#include - -#include -#include -#include -#include -#include -#include -#include -#include "NBTrafficLightLogic.h" -#include "NBTrafficLightDefinition.h" -#include "NBLoadedTLDef.h" -#include "NBNode.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -/* ------------------------------------------------------------------------- - * NBLoadedTLDef::SignalGroup-methods - * ----------------------------------------------------------------------- */ -NBLoadedTLDef::SignalGroup::SignalGroup(const std::string& id) - : Named(id) {} - -NBLoadedTLDef::SignalGroup::~SignalGroup() {} - -void -NBLoadedTLDef::SignalGroup::addConnection(const NBConnection& c) { - assert(c.getFromLane() < 0 || c.getFrom()->getNumLanes() > c.getFromLane()); - myConnections.push_back(c); -} - - -void -NBLoadedTLDef::SignalGroup::addPhaseBegin(SUMOTime time, TLColor color) { - myPhases.push_back(PhaseDef(time, color)); -} - - -void -NBLoadedTLDef::SignalGroup::setYellowTimes(SUMOTime tRedYellow, SUMOTime tYellow) { - myTRedYellow = tRedYellow; - myTYellow = tYellow; -} - - -void -NBLoadedTLDef::SignalGroup::sortPhases() { - sort(myPhases.begin(), myPhases.end(), phase_by_time_sorter()); -} - - -void -NBLoadedTLDef::SignalGroup::patchTYellow(int tyellow, bool forced) { - if (myTYellow < 0) { - // was not set before (was not loaded) - myTYellow = tyellow; - } else if (forced && myTYellow < tyellow) { - WRITE_WARNING("TYellow of signal group '" + getID() + "' was less than the computed one; patched (was:" + toString(myTYellow) + ", is:" + toString(tyellow) + ")"); - myTYellow = tyellow; - } -} - - -std::vector -NBLoadedTLDef::SignalGroup::getTimes(SUMOTime cycleDuration) const { - // within the phase container, we should have the green and red phases add their times - std::vector ret; // !!! time vector - for (std::vector::const_iterator i = myPhases.begin(); i != myPhases.end(); i++) { - ret.push_back((double)(*i).myTime); - } - // further, we possibly should set the yellow phases - if (myTYellow > 0) { - for (std::vector::const_iterator i = myPhases.begin(); i != myPhases.end(); i++) { - if ((*i).myColor == TLCOLOR_RED) { - SUMOTime time = (SUMOTime)(*i).myTime + myTYellow; - if (time > cycleDuration) { - time = time - cycleDuration; - } - ret.push_back((double) time); - } - } - } - return ret; -} - - -int -NBLoadedTLDef::SignalGroup::getLinkNo() const { - return (int) myConnections.size(); -} - - -bool -NBLoadedTLDef::SignalGroup::mayDrive(SUMOTime time) const { - assert(myPhases.size() != 0); - for (std::vector::const_reverse_iterator i = myPhases.rbegin(); i != myPhases.rend(); i++) { - SUMOTime nextTime = (*i).myTime; - if (time >= nextTime) { - return (*i).myColor == TLCOLOR_GREEN; - } - } - return (*(myPhases.end() - 1)).myColor == TLCOLOR_GREEN; -} - - -bool -NBLoadedTLDef::SignalGroup::hasYellow(SUMOTime time) const { - bool has_red_now = !mayDrive(time); - bool had_green = mayDrive(time - myTYellow); - return has_red_now && had_green; -} - - -bool -NBLoadedTLDef::SignalGroup::containsConnection(NBEdge* from, NBEdge* to) const { - for (NBConnectionVector::const_iterator i = myConnections.begin(); i != myConnections.end(); i++) { - if ((*i).getFrom() == from && (*i).getTo() == to) { - return true; - } - } - return false; - -} - - -const NBConnection& -NBLoadedTLDef::SignalGroup::getConnection(int pos) const { - assert(pos < (int)myConnections.size()); - return myConnections[pos]; -} - - -bool -NBLoadedTLDef::SignalGroup::containsIncoming(NBEdge* from) const { - for (NBConnectionVector::const_iterator i = myConnections.begin(); i != myConnections.end(); i++) { - if ((*i).getFrom() == from) { - return true; - } - } - return false; -} - - -void -NBLoadedTLDef::SignalGroup::remapIncoming(NBEdge* which, const EdgeVector& by) { - NBConnectionVector newConns; - for (NBConnectionVector::iterator i = myConnections.begin(); i != myConnections.end();) { - if ((*i).getFrom() == which) { - NBConnection conn((*i).getFrom(), (*i).getTo()); - i = myConnections.erase(i); - for (EdgeVector::const_iterator j = by.begin(); j != by.end(); j++) { - NBConnection curr(conn); - if (!curr.replaceFrom(which, *j)) { - throw ProcessError("Could not replace edge '" + which->getID() + "' by '" + (*j)->getID() + "'.\nUndefined..."); - } - newConns.push_back(curr); - } - } else { - i++; - } - } - copy(newConns.begin(), newConns.end(), - back_inserter(myConnections)); -} - - -bool -NBLoadedTLDef::SignalGroup::containsOutgoing(NBEdge* to) const { - for (NBConnectionVector::const_iterator i = myConnections.begin(); i != myConnections.end(); i++) { - if ((*i).getTo() == to) { - return true; - } - } - return false; -} - - -void -NBLoadedTLDef::SignalGroup::remapOutgoing(NBEdge* which, const EdgeVector& by) { - NBConnectionVector newConns; - for (NBConnectionVector::iterator i = myConnections.begin(); i != myConnections.end();) { - if ((*i).getTo() == which) { - NBConnection conn((*i).getFrom(), (*i).getTo()); - i = myConnections.erase(i); - for (EdgeVector::const_iterator j = by.begin(); j != by.end(); j++) { - NBConnection curr(conn); - if (!curr.replaceTo(which, *j)) { - throw ProcessError("Could not replace edge '" + which->getID() + "' by '" + (*j)->getID() + "'.\nUndefined..."); - } - newConns.push_back(curr); - } - } else { - i++; - } - } - copy(newConns.begin(), newConns.end(), - back_inserter(myConnections)); -} - - -void -NBLoadedTLDef::SignalGroup::remap(NBEdge* removed, int removedLane, - NBEdge* by, int byLane) { - for (NBConnectionVector::iterator i = myConnections.begin(); i != myConnections.end(); i++) { - if ((*i).getTo() == removed - && - ((*i).getToLane() == removedLane - || - (*i).getToLane() == -1)) { - (*i).replaceTo(removed, removedLane, by, byLane); - - } else if ((*i).getTo() == removed && removedLane == -1) { - (*i).replaceTo(removed, by); - } - - if ((*i).getFrom() == removed - && - ((*i).getFromLane() == removedLane - || - (*i).getFromLane() == -1)) { - (*i).replaceFrom(removed, removedLane, by, byLane); - - } else if ((*i).getFrom() == removed && removedLane == -1) { - (*i).replaceFrom(removed, by); - } - } -} - - -/* ------------------------------------------------------------------------- - * NBLoadedTLDef::Phase-methods - * ----------------------------------------------------------------------- */ -NBLoadedTLDef::NBLoadedTLDef(const NBEdgeCont& ec, const std::string& id, - const std::vector& junctions, SUMOTime offset, TrafficLightType type) : - NBTrafficLightDefinition(id, junctions, DefaultProgramID, offset, type), - myEdgeCont(&ec) { -} - - -NBLoadedTLDef::NBLoadedTLDef(const NBEdgeCont& ec, const std::string& id, NBNode* junction, SUMOTime offset, TrafficLightType type) : - NBTrafficLightDefinition(id, junction, DefaultProgramID, offset, type), - myEdgeCont(&ec) { -} - - -NBLoadedTLDef::NBLoadedTLDef(const NBEdgeCont& ec, const std::string& id, SUMOTime offset, TrafficLightType type) : - NBTrafficLightDefinition(id, DefaultProgramID, offset, type), - myEdgeCont(&ec) { -} - - -NBLoadedTLDef::~NBLoadedTLDef() { - for (SignalGroupCont::iterator i = mySignalGroups.begin(); i != mySignalGroups.end(); ++i) { - delete (*i).second; - } -} - - -NBTrafficLightLogic* -NBLoadedTLDef::myCompute(int brakingTimeSeconds) { - MsgHandler::getWarningInstance()->clear(); // !!! - NBLoadedTLDef::SignalGroupCont::const_iterator i; - // compute the switching times - std::set tmpSwitchTimes; - for (i = mySignalGroups.begin(); i != mySignalGroups.end(); i++) { - NBLoadedTLDef::SignalGroup* group = (*i).second; - // needed later - group->sortPhases(); - // patch the yellow time for this group - group->patchTYellow(brakingTimeSeconds, OptionsCont::getOptions().getBool("tls.yellow.patch-small")); - // copy the now valid times into the container - // both the given red and green phases are added and also the - // yellow times - std::vector gtimes = group->getTimes(myCycleDuration); - for (std::vector::const_iterator k = gtimes.begin(); k != gtimes.end(); k++) { - tmpSwitchTimes.insert(*k); - } - } - std::vector switchTimes; - copy(tmpSwitchTimes.begin(), tmpSwitchTimes.end(), back_inserter(switchTimes)); - sort(switchTimes.begin(), switchTimes.end()); - - // count the signals - int noSignals = 0; - for (i = mySignalGroups.begin(); i != mySignalGroups.end(); i++) { - noSignals += (*i).second->getLinkNo(); - } - // build the phases - NBTrafficLightLogic* logic = new NBTrafficLightLogic(getID(), getProgramID(), noSignals, myOffset, myType); - for (std::vector::iterator l = switchTimes.begin(); l != switchTimes.end(); l++) { - // compute the duration of the current phase - int duration; - if (l != switchTimes.end() - 1) { - // get from the difference to the next switching time - duration = (int)((*(l + 1)) - (*l)); - } else { - // get from the differenc to the first switching time - duration = (int)(myCycleDuration - (*l) + * (switchTimes.begin())); - } - // no information about yellow times will be generated - assert((*l) >= 0); - logic->addStep(TIME2STEPS(duration), buildPhaseState((int)(*l))); - } - // check whether any warnings were printed - if (MsgHandler::getWarningInstance()->wasInformed()) { - WRITE_WARNING("During computation of traffic light '" + getID() + "'."); - } - logic->closeBuilding(); - - // initialize myNeedsContRelation - myNeedsContRelation.clear(); - const bool controlledWithin = !OptionsCont::getOptions().getBool("tls.uncontrolled-within"); - const std::vector phases = logic->getPhases(); - for (std::vector::const_iterator it = phases.begin(); it != phases.end(); it++) { - const std::string state = (*it).state; - for (NBConnectionVector::const_iterator it1 = myControlledLinks.begin(); it1 != myControlledLinks.end(); it1++) { - const NBConnection& c1 = *it1; - const int i1 = c1.getTLIndex(); - if (i1 == NBConnection::InvalidTlIndex || state[i1] != 'g' || c1.getFrom() == nullptr || c1.getTo() == nullptr) { - continue; - } - for (NBConnectionVector::const_iterator it2 = myControlledLinks.begin(); it2 != myControlledLinks.end(); it2++) { - const NBConnection& c2 = *it2; - const int i2 = c2.getTLIndex(); - if (i2 != NBConnection::InvalidTlIndex - && i2 != i1 - && (state[i2] == 'G' || state[i2] == 'g') - && c2.getFrom() != nullptr && c2.getTo() != nullptr) { - const bool rightTurnConflict = NBNode::rightTurnConflict( - c1.getFrom(), c1.getTo(), c1.getFromLane(), c2.getFrom(), c2.getTo(), c2.getFromLane()); - if (forbids(c2.getFrom(), c2.getTo(), c1.getFrom(), c1.getTo(), true, controlledWithin) || rightTurnConflict) { - myNeedsContRelation.insert(StreamPair(c1.getFrom(), c1.getTo(), c2.getFrom(), c2.getTo())); - } - } - } - } - } - myNeedsContRelationReady = true; - - return logic; -} - - -void -NBLoadedTLDef::setTLControllingInformation() const { - // assign the tl-indices to the edge connections - for (NBConnectionVector::const_iterator it = myControlledLinks.begin(); it != myControlledLinks.end(); it++) { - const NBConnection& c = *it; - if (c.getTLIndex() != NBConnection::InvalidTlIndex) { - c.getFrom()->setControllingTLInformation(c, getID()); - } - } -} - - -std::string -NBLoadedTLDef::buildPhaseState(int time) const { - int pos = 0; - std::string state; - // set the green and yellow information first; - // the information whether other have to break needs those masks - // completely filled - for (SignalGroupCont::const_iterator i = mySignalGroups.begin(); i != mySignalGroups.end(); i++) { - SignalGroup* group = (*i).second; - int linkNo = group->getLinkNo(); - bool mayDrive = group->mayDrive(time); - bool hasYellow = group->hasYellow(time); - char c = 'r'; - if (mayDrive) { - c = 'g'; - } - if (hasYellow) { - c = 'y'; - } - for (int j = 0; j < linkNo; j++) { - const NBConnection& conn = group->getConnection(j); - NBConnection assConn(conn); - // assert that the connection really exists - if (assConn.check(*myEdgeCont)) { - state = state + c; - ++pos; - } - } - } - // set the braking mask - pos = 0; - for (SignalGroupCont::const_iterator i = mySignalGroups.begin(); i != mySignalGroups.end(); i++) { - SignalGroup* group = (*i).second; - int linkNo = group->getLinkNo(); - for (int j = 0; j < linkNo; j++) { - const NBConnection& conn = group->getConnection(j); - NBConnection assConn(conn); - if (assConn.check(*myEdgeCont)) { - if (!mustBrake(assConn, state, pos)) { - if (state[pos] == 'g') { - state[pos] = 'G'; - } - if (state[pos] == 'y') { - state[pos] = 'Y'; - } - } - pos++; - } - } - } - return state; -} - - -bool -NBLoadedTLDef::mustBrake(const NBConnection& possProhibited, - const std::string& state, - int strmpos) const { - // check whether the stream has red - if (state[strmpos] != 'g' && state[strmpos] != 'G') { - return true; - } - - // check whether another stream which has green is a higher - // priorised foe to the given - int pos = 0; - for (SignalGroupCont::const_iterator i = mySignalGroups.begin(); i != mySignalGroups.end(); i++) { - SignalGroup* group = (*i).second; - // get otherlinks that have green - int linkNo = group->getLinkNo(); - for (int j = 0; j < linkNo; j++) { - // get the current connection (possible foe) - const NBConnection& other = group->getConnection(j); - NBConnection possProhibitor(other); - // if the connction ist still valid ... - if (possProhibitor.check(*myEdgeCont)) { - // ... do nothing if it starts at the same edge - if (possProhibited.getFrom() == possProhibitor.getFrom()) { - pos++; - continue; - } - if (state[pos] == 'g' || state[pos] == 'G') { - if (NBTrafficLightDefinition::mustBrake(possProhibited, possProhibitor, true)) { - return true; - } - } - pos++; - } - } - } - return false; -} - - -void -NBLoadedTLDef::setParticipantsInformation() { - // assign participating nodes to the request - collectNodes(); - // collect the information about participating edges and links - collectEdges(); - collectLinks(); -} - -void -NBLoadedTLDef::collectNodes() { - myControlledNodes.clear(); - SignalGroupCont::const_iterator m; - for (m = mySignalGroups.begin(); m != mySignalGroups.end(); m++) { - SignalGroup* group = (*m).second; - int linkNo = group->getLinkNo(); - for (int j = 0; j < linkNo; j++) { - const NBConnection& conn = group->getConnection(j); - NBEdge* edge = conn.getFrom(); - NBNode* node = edge->getToNode(); - myControlledNodes.push_back(node); - } - } - std::sort(myControlledNodes.begin(), myControlledNodes.end(), NBNode::nodes_by_id_sorter()); -} - - -void -NBLoadedTLDef::collectLinks() { - myControlledLinks.clear(); - // build the list of links which are controled by the traffic light - for (EdgeVector::iterator i = myIncomingEdges.begin(); i != myIncomingEdges.end(); i++) { - NBEdge* incoming = *i; - int noLanes = incoming->getNumLanes(); - for (int j = 0; j < noLanes; j++) { - std::vector elv = incoming->getConnectionsFromLane(j); - for (std::vector::iterator k = elv.begin(); k != elv.end(); k++) { - NBEdge::Connection el = *k; - if (el.toEdge != nullptr) { - myControlledLinks.push_back(NBConnection(incoming, j, el.toEdge, el.toLane)); - } - } - } - } - - // assign tl-indices to myControlledLinks - int pos = 0; - for (SignalGroupCont::const_iterator m = mySignalGroups.begin(); m != mySignalGroups.end(); m++) { - SignalGroup* group = (*m).second; - int linkNo = group->getLinkNo(); - for (int j = 0; j < linkNo; j++) { - const NBConnection& conn = group->getConnection(j); - assert(conn.getFromLane() < 0 || (int) conn.getFrom()->getNumLanes() > conn.getFromLane()); - NBConnection tst(conn); - tst.setTLIndex(pos); - if (tst.check(*myEdgeCont)) { - if (tst.getFrom()->mayBeTLSControlled(tst.getFromLane(), tst.getTo(), tst.getToLane())) { - for (NBConnectionVector::iterator it = myControlledLinks.begin(); it != myControlledLinks.end(); it++) { - NBConnection& c = *it; - if (c.getTLIndex() == NBConnection::InvalidTlIndex - && tst.getFrom() == c.getFrom() && tst.getTo() == c.getTo() - && (tst.getFromLane() < 0 || tst.getFromLane() == c.getFromLane()) - && (tst.getToLane() < 0 || tst.getToLane() == c.getToLane())) { - c.setTLIndex(pos); - } - } - //std::cout << getID() << " group=" << (*m).first << " tst=" << tst << "\n"; - pos++; - } - } else { - WRITE_WARNING("Could not set signal on connection (signal: " + getID() + ", group: " + group->getID() + ")"); - } - } - } -} - - -NBLoadedTLDef::SignalGroup* -NBLoadedTLDef::findGroup(NBEdge* from, NBEdge* to) const { - for (SignalGroupCont::const_iterator i = mySignalGroups.begin(); i != mySignalGroups.end(); i++) { - if ((*i).second->containsConnection(from, to)) { - return (*i).second; - } - } - return nullptr; -} - - -bool -NBLoadedTLDef::addToSignalGroup(const std::string& groupid, - const NBConnection& connection) { - if (mySignalGroups.find(groupid) == mySignalGroups.end()) { - return false; - } - mySignalGroups[groupid]->addConnection(connection); - NBNode* n1 = connection.getFrom()->getToNode(); - if (n1 != nullptr) { - addNode(n1); - n1->addTrafficLight(this); - } - NBNode* n2 = connection.getTo()->getFromNode(); - if (n2 != nullptr) { - addNode(n2); - n2->addTrafficLight(this); - } - return true; -} - - -bool -NBLoadedTLDef::addToSignalGroup(const std::string& groupid, - const NBConnectionVector& connections) { - bool ok = true; - for (NBConnectionVector::const_iterator i = connections.begin(); i != connections.end(); i++) { - ok &= addToSignalGroup(groupid, *i); - } - return ok; -} - - -void -NBLoadedTLDef::addSignalGroup(const std::string& id) { - assert(mySignalGroups.find(id) == mySignalGroups.end()); - mySignalGroups[id] = new SignalGroup(id); -} - - -void -NBLoadedTLDef::addSignalGroupPhaseBegin(const std::string& groupid, SUMOTime time, - TLColor color) { - assert(mySignalGroups.find(groupid) != mySignalGroups.end()); - mySignalGroups[groupid]->addPhaseBegin(time, color); -} - -void -NBLoadedTLDef::setSignalYellowTimes(const std::string& groupid, - SUMOTime myTRedYellow, SUMOTime myTYellow) { - assert(mySignalGroups.find(groupid) != mySignalGroups.end()); - mySignalGroups[groupid]->setYellowTimes(myTRedYellow, myTYellow); -} - - -void -NBLoadedTLDef::setCycleDuration(int cycleDur) { - myCycleDuration = cycleDur; -} - - -void -NBLoadedTLDef::remapRemoved(NBEdge* removed, - const EdgeVector& incoming, - const EdgeVector& outgoing) { - for (SignalGroupCont::const_iterator i = mySignalGroups.begin(); i != mySignalGroups.end(); i++) { - SignalGroup* group = (*i).second; - if (group->containsIncoming(removed)) { - group->remapIncoming(removed, incoming); - } - if (group->containsOutgoing(removed)) { - group->remapOutgoing(removed, outgoing); - } - } -} - - -void -NBLoadedTLDef::replaceRemoved(NBEdge* removed, int removedLane, - NBEdge* by, int byLane, bool incoming) { - for (SignalGroupCont::const_iterator i = mySignalGroups.begin(); i != mySignalGroups.end(); i++) { - SignalGroup* group = (*i).second; - if ((incoming && group->containsIncoming(removed)) || (!incoming && group->containsOutgoing(removed))) { - group->remap(removed, removedLane, by, byLane); - } - } -} - - -void -NBLoadedTLDef::initNeedsContRelation() const { - if (!myNeedsContRelationReady) { - throw ProcessError("myNeedsContRelation was not propperly initialized\n"); - } -} - - -int -NBLoadedTLDef::getMaxIndex() { - setParticipantsInformation(); - NBTrafficLightLogic* logic = compute(OptionsCont::getOptions()); - if (logic != nullptr) { - return logic->getNumLinks() - 1; - } else { - return -1; - } -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netbuild/NBLoadedTLDef.h b/Util/OSM2ODR/src/netbuild/NBLoadedTLDef.h deleted file mode 100644 index 9649a1bdd..000000000 --- a/Util/OSM2ODR/src/netbuild/NBLoadedTLDef.h +++ /dev/null @@ -1,386 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NBLoadedTLDef.h -/// @author Daniel Krajzewicz -/// @author Sascha Krieg -/// @date Fri, 29.04.2005 -/// -// A loaded (complete) traffic light logic -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include -#include "NBTrafficLightDefinition.h" -#include "NBNode.h" -#include - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NBLoadedTLDef - * @brief A loaded (complete) traffic light logic - */ -class NBLoadedTLDef : public NBTrafficLightDefinition { -public: - /** @class SignalGroup - * @brief A single signal group, may control several connections - */ - class SignalGroup : public Named { - public: - /** @brief Constructor - * @param[in] id The id of the signal group - */ - SignalGroup(const std::string& id); - - /// @brief Destructor - ~SignalGroup(); - - /** @brief Inserts a controlled connection - * @param[in] c The connection to be controlled by this signal group - */ - void addConnection(const NBConnection& c); - - /** @brief Sets the begin of a phase - * @param[in] time The time at which the phase starts - * @param[in] color The color of this signal starting at the given time - */ - void addPhaseBegin(SUMOTime time, TLColor color); - - /** @brief Sets the times for redyellow and yellow - * @param[in] tRedYellowe The duration of the redyellow phase - * @param[in] tYellow The duration of the yellow phase - */ - void setYellowTimes(SUMOTime tRedYellowe, SUMOTime tYellow); - - /** @brief Returns the times at which the signal switches - * @param[in] cycleDuration The duration of the complete cycle - * @return The switch times of this signal - */ - std::vector getTimes(SUMOTime cycleDuration) const; - - /** @brief Sorts the phases */ - void sortPhases(); - - /** @brief Returns the number of links (connection) controlled by this signal - * @return The number of links controlled by this signal - */ - int getLinkNo() const; - - /** @brief Returns whether vehicles on controlled links may drive at the given time - * @param[in] time The regarded time - * @return Whether vehicles may drive at this time - */ - bool mayDrive(SUMOTime time) const; - - /** @brief Returns whether controlled links have yellow at the given time - * @param[in] time The regarded time - * @return Whether controlled links are yellow at this time - */ - bool hasYellow(SUMOTime time) const; - - /** @brief Returns whether the given connection is controlled by this signal - * @param[in] from The connection's start edge - * @param[in] from The connection's end edge - * @return Whether the connection is controlled by this signal - */ - bool containsConnection(NBEdge* from, NBEdge* to) const; - - /** @brief Returns whether this signal controls the given edge - * @param[in] from The incoming edge - * @return Whether this edge is controlled by this signal - */ - bool containsIncoming(NBEdge* from) const; - - /** @brief Replaces the given incoming edge by the others given - * @param[in] which The edge to replace - * @param[in] by The replacements - */ - void remapIncoming(NBEdge* which, const EdgeVector& by); - - /** @brief Returns whether this signal controls a connection where the given edge is the destination - * @param[in] from The outgoing edge - * @return Whether this edge's predecessing edge is controlled by this signal - */ - bool containsOutgoing(NBEdge* to) const; - - /** @brief Replaces the given outgoing edge by the others given - * @param[in] which The edge to replace - * @param[in] by The replacements - */ - void remapOutgoing(NBEdge* which, const EdgeVector& by); - - /** @brief Returns the connection at the given index - * @param[in] pos The position within this signal - * @return The connection at the given index - */ - const NBConnection& getConnection(int pos) const; - - /** @brief Sets the yellow time - * @param[in] tyellow The yellow time to set in seconds - * @param[in] forced Whether resetting tyellow was forced by the user by setting "tls.yellow.patch-small" - */ - void patchTYellow(int tyellow, bool forced); - - /** @brief Replaces a removed edge/lane - * @param[in] removed The edge to replace - * @param[in] removedLane The lane of this edge to replace - * @param[in] by The edge to insert instead - * @param[in] byLane This edge's lane to insert instead - */ - void remap(NBEdge* removed, int removedLane, NBEdge* by, int byLane); - - /** @class PhaseDef - * @brief Definition of a single, loaded phase - */ - class PhaseDef { - public: - /** @brief Constructor - * @param[in] time The begin time of this phase - * @param[in] color A signal's color from this time - */ - PhaseDef(SUMOTime time, TLColor color) - : myTime(time), myColor(color) { } - - /// @brief The begin time of this phase - SUMOTime myTime; - /// @brief A signal's color from this time - TLColor myColor; - }; - - /** @class phase_by_time_sorter - * @brief Sorts phases by their begin time - */ - class phase_by_time_sorter { - public: - /// @brief Constructor - explicit phase_by_time_sorter() { } - - /** @brief Sorts phases by their begin time - * @param[in] p1 a phase definition - * @param[in] p2 a phase definition - */ - int operator()(const PhaseDef& p1, const PhaseDef& p2) { - return p1.myTime < p2.myTime; - } - }; - - private: - /// @brief Connections controlled by this signal - NBConnectionVector myConnections; - /// @brief The phases of this signal - std::vector myPhases; - /// @brief The times of redyellow and yellow - SUMOTime myTRedYellow, myTYellow; - }; - - - - /// @brief Definition of the container for signal groups - typedef std::map SignalGroupCont; - - - /** @brief Constructor - * @param[in] id The id of the tls - * @param[in] junctions Junctions controlled by this tls - * @param[in] offset The offset of the plan - * @param[in] type The algorithm type for the computed traffic light - */ - NBLoadedTLDef(const NBEdgeCont& ec, const std::string& id, - const std::vector& junctions, SUMOTime offset, - TrafficLightType type); - - - /** @brief Constructor - * @param[in] id The id of the tls - * @param[in] junction The junction controlled by this tls - * @param[in] offset The offset of the plan - * @param[in] type The algorithm type for the computed traffic light - */ - NBLoadedTLDef(const NBEdgeCont& ec, const std::string& id, NBNode* junction, SUMOTime offset, - TrafficLightType type); - - - /** @brief Constructor - * @param[in] id The id of the tls - * @param[in] offset The offset of the plan - * @param[in] type The algorithm type for the computed traffic light - */ - NBLoadedTLDef(const NBEdgeCont& ec, const std::string& id, SUMOTime offset, - TrafficLightType type); - - - /// @brief Destructor - ~NBLoadedTLDef(); - - - /** @brief Returns the signal group which is responsible for the given connection - * @param[in] from The connection's start edge - * @param[in] to The connection's end edge - * @return The signal group which controls the given connection - */ - SignalGroup* findGroup(NBEdge* from, NBEdge* to) const; - - - /** @brief Sets the duration of a cycle - * @param[in] cycleDur The duration of the cycle - */ - void setCycleDuration(int cycleDur); - - - /** @brief Adds a signal group - * @param[in] id The id of the signal group - */ - void addSignalGroup(const std::string& id); - - - /** @brief Adds a connection to a signal group - * @param[in] groupid The id of the signal group to add the connection to - * @param[in] connection The connection to add - */ - bool addToSignalGroup(const std::string& groupid, - const NBConnection& connection); - - - /** @brief Adds a list of connections to a signal group - * @param[in] groupid The id of the signal group to add the connections to - * @param[in] connections The connections to add - */ - bool addToSignalGroup(const std::string& groupid, - const NBConnectionVector& connections); - - - /** @brief Sets the information about the begin of a phase - * @param[in] groupid The id of the signal group to add the phase to - * @param[in] time The time the phase starts at - * @param[in] color The color of the signal during this phase - */ - void addSignalGroupPhaseBegin(const std::string& groupid, - SUMOTime time, TLColor color); - - - /** @brief Sets the times the light is yellow or red/yellow - * @param[in] groupid The id of the signal group to add the phase to - * @param[in] tRedYellow The duration of redyellow - * @param[in] tYellow The duration of yellow - */ - void setSignalYellowTimes(const std::string& groupid, - SUMOTime tRedYellow, SUMOTime tYellow); - - - /// @name Public methods from NBTrafficLightDefinition-interface - /// @{ - - /** @brief Informs edges about being controlled by a tls - * @param[in] ec The container of edges - * @see NBTrafficLightDefinition::setTLControllingInformation - */ - void setTLControllingInformation() const; - - - /** @brief Replaces occurences of the removed edge in incoming/outgoing edges of all definitions - * @param[in] removed The removed edge - * @param[in] incoming The edges to use instead if an incoming edge was removed - * @param[in] outgoing The edges to use instead if an outgoing edge was removed - * @see NBTrafficLightDefinition::remapRemoved - */ - void remapRemoved(NBEdge* removed, - const EdgeVector& incoming, const EdgeVector& outgoing); - - /* initialize myNeedsContRelation and set myNeedsContRelationReady to true */ - void initNeedsContRelation() const; - - ///@brief Returns the maximum index controlled by this traffic light - int getMaxIndex(); - - /// @} - - -protected: - /// @name Protected methods from NBTrafficLightDefinition-interface - /// @{ - - /** @brief Computes the traffic light logic finally in dependence to the type - * @param[in] brakingTime Duration a vehicle needs for braking in front of the tls in seconds - * @return The computed logic - * @see NBTrafficLightDefinition::myCompute - */ - NBTrafficLightLogic* myCompute(int brakingTimeSeconds); - - /** @brief Builds the list of participating nodes/edges/links - * @see NBTrafficLightDefinition::setParticipantsInformation - */ - void setParticipantsInformation(); - - - /** @brief Collects the nodes participating in this traffic light - * @see NBTrafficLightDefinition::collectNodes - */ - void collectNodes(); - - - /** @brief Collects the links participating in this traffic light - * @exception ProcessError If a link could not be found - * @see NBTrafficLightDefinition::collectLinks - */ - void collectLinks(); - - - /** @brief Returns the information whether a connection must brake, given a phase - * @param[in] possProhibited The connection to investigate - * @param[in] state The state - * @param[in] strmpos The index of this connection within the masks - * @return Whether the given connection must brake - */ - bool mustBrake(const NBConnection& possProhibited, - const std::string& state, - int strmpos) const; - - - /** @brief Replaces a removed edge/lane - * @param[in] removed The edge to replace - * @param[in] removedLane The lane of this edge to replace - * @param[in] by The edge to insert instead - * @param[in] byLane This edge's lane to insert instead - * @see NBTrafficLightDefinition::replaceRemoved - */ - void replaceRemoved(NBEdge* removed, int removedLane, - NBEdge* by, int byLane, bool incoming); - /// @} - -private: - /** @brief Builds the phase for a given time - * @param[in] ec The edge control to use - * @param[in] time The time to build the phase for - * @return The phase of this tls for the given time - */ - std::string buildPhaseState(int time) const; - - // pointer to the NBEdgeCont for checking edges - const NBEdgeCont* myEdgeCont; - - -private: - /// @brief Controlled signal groups - SignalGroupCont mySignalGroups; - - /// @brief The duration of a single cycle - int myCycleDuration; - - -}; diff --git a/Util/OSM2ODR/src/netbuild/NBNetBuilder.cpp b/Util/OSM2ODR/src/netbuild/NBNetBuilder.cpp deleted file mode 100644 index 0804243c7..000000000 --- a/Util/OSM2ODR/src/netbuild/NBNetBuilder.cpp +++ /dev/null @@ -1,754 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NBNetBuilder.cpp -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Thimor Bohn -/// @author Sascha Krieg -/// @author Michael Behrisch -/// @author Walter Bamberger -/// @date 20 Nov 2001 -/// -// Instance responsible for building networks -/****************************************************************************/ -#include - -#include -#include -#include "NBNetBuilder.h" -#include "NBNodeCont.h" -#include "NBEdgeCont.h" -#include "NBTrafficLightLogicCont.h" -#include "NBDistrictCont.h" -#include "NBDistrict.h" -#include "NBRequest.h" -#include "NBTypeCont.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include "NBAlgorithms.h" -#include "NBAlgorithms_Ramps.h" -#include "NBAlgorithms_Railway.h" -#include "NBHeightMapper.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -NBNetBuilder::NBNetBuilder() : - myEdgeCont(myTypeCont), - myNetworkHaveCrossings(false) { -} - - -NBNetBuilder::~NBNetBuilder() {} - - -void -NBNetBuilder::applyOptions(OptionsCont& oc) { - // apply options to type control - myTypeCont.setDefaults(oc.getInt("default.lanenumber"), oc.getFloat("default.lanewidth"), oc.getFloat("default.speed"), - oc.getInt("default.priority"), parseVehicleClasses("", oc.getString("default.disallow"))); - // apply options to edge control - myEdgeCont.applyOptions(oc); - // apply options to traffic light logics control - myTLLCont.applyOptions(oc); - NBEdge::setDefaultConnectionLength(oc.getFloat("default.connection-length")); -} - - -void -NBNetBuilder::compute(OptionsCont& oc, const std::set& explicitTurnarounds, bool mayAddOrRemove) { - GeoConvHelper& geoConvHelper = GeoConvHelper::getProcessing(); - - const bool lefthand = oc.getBool("lefthand"); - if (lefthand) { - mirrorX(); - } - - // MODIFYING THE SETS OF NODES AND EDGES - // Removes edges that are connecting the same node - long before = PROGRESS_BEGIN_TIME_MESSAGE("Removing self-loops"); - myNodeCont.removeSelfLoops(myDistrictCont, myEdgeCont, myTLLCont); - PROGRESS_TIME_MESSAGE(before); - if (mayAddOrRemove && oc.exists("remove-edges.isolated") && oc.getBool("remove-edges.isolated")) { - before = PROGRESS_BEGIN_TIME_MESSAGE("Finding isolated roads"); - myNodeCont.removeIsolatedRoads(myDistrictCont, myEdgeCont); - PROGRESS_TIME_MESSAGE(before); - } - if (mayAddOrRemove && oc.exists("keep-edges.components") && oc.getInt("keep-edges.components") > 0) { - before = PROGRESS_BEGIN_TIME_MESSAGE("Finding largest components"); - myNodeCont.removeComponents(myDistrictCont, myEdgeCont, oc.getInt("keep-edges.components")); - PROGRESS_TIME_MESSAGE(before); - } - if (mayAddOrRemove && oc.exists("keep-edges.postload") && oc.getBool("keep-edges.postload")) { - if (oc.isSet("keep-edges.explicit") || oc.isSet("keep-edges.input-file")) { - before = PROGRESS_BEGIN_TIME_MESSAGE("Removing unwished edges"); - myEdgeCont.removeUnwishedEdges(myDistrictCont); - PROGRESS_TIME_MESSAGE(before); - } - } - // Processing pt stops and lines - if (oc.exists("ptstop-output") && oc.isSet("ptstop-output")) { - before = PROGRESS_BEGIN_TIME_MESSAGE("Processing public transport stops"); - if (!(oc.exists("ptline-output") && oc.isSet("ptline-output")) - && !oc.getBool("ptstop-output.no-bidi")) { - myPTStopCont.localizePTStops(myEdgeCont); - } - myPTStopCont.assignLanes(myEdgeCont); - PROGRESS_TIME_MESSAGE(before); - } - - if (oc.exists("ptline-output") && oc.isSet("ptline-output")) { - before = PROGRESS_BEGIN_TIME_MESSAGE("Revising public transport stops based on pt lines"); - myPTLineCont.process(myEdgeCont, myPTStopCont); - PROGRESS_TIME_MESSAGE(before); - } - - if (oc.exists("ptline-output") && oc.isSet("ptline-output")) { - if (oc.exists("ptline-clean-up") && oc.getBool("ptline-clean-up")) { - before = PROGRESS_BEGIN_TIME_MESSAGE("Cleaning up public transport stops that are not served by any line"); - myPTStopCont.postprocess(myPTLineCont.getServedPTStops()); - PROGRESS_TIME_MESSAGE(before); - } else { - int numDeletedStops = myPTStopCont.cleanupDeleted(myEdgeCont); - if (numDeletedStops > 0) { - WRITE_WARNING("Removed " + toString(numDeletedStops) + " pt stops because they could not be assigned to the network"); - } - } - } - - if (oc.exists("ptstop-output") && oc.isSet("ptstop-output") && !oc.getBool("ptstop-output.no-bidi")) { - before = PROGRESS_BEGIN_TIME_MESSAGE("Align pt stop id signs with corresponding edge id signs"); - myPTStopCont.alignIdSigns(); - PROGRESS_TIME_MESSAGE(before); - } - - // analyse and fix railway topology - if (oc.exists("railway.topology.all-bidi") && oc.getBool("railway.topology.all-bidi")) { - NBTurningDirectionsComputer::computeTurnDirections(myNodeCont, false); - NBRailwayTopologyAnalyzer::makeAllBidi(*this); - } else if (oc.exists("railway.topology.repair") && oc.getBool("railway.topology.repair")) { - // correct railway angles for angle-based connectivity heuristic - myEdgeCont.checkGeometries(0, - oc.getFloat("geometry.min-radius"), false, - oc.getBool("geometry.min-radius.fix.railways"), true); - NBTurningDirectionsComputer::computeTurnDirections(myNodeCont, false); - NBRailwayTopologyAnalyzer::repairTopology(*this); - } - if (oc.exists("railway.topology.direction-priority") && oc.getBool("railway.topology.direction-priority")) { - NBTurningDirectionsComputer::computeTurnDirections(myNodeCont, false); // recompute after new edges were added - NBRailwayTopologyAnalyzer::assignDirectionPriority(*this); - } - if (oc.exists("railway.topology.output") && oc.isSet("railway.topology.output")) { - NBTurningDirectionsComputer::computeTurnDirections(myNodeCont, false); // recompute after new edges were added - NBRailwayTopologyAnalyzer::analyzeTopology(*this); - } - - - if (mayAddOrRemove && oc.exists("edges.join-tram-dist") && oc.getFloat("edges.join-tram-dist") >= 0) { - // should come before joining junctions - before = PROGRESS_BEGIN_TIME_MESSAGE("Joining tram edges"); - int numJoinedTramEdges = myEdgeCont.joinTramEdges(myDistrictCont, myPTLineCont, oc.getFloat("edges.join-tram-dist")); - PROGRESS_TIME_MESSAGE(before); - if (numJoinedTramEdges > 0) { - WRITE_MESSAGE(" Joined " + toString(numJoinedTramEdges) + " tram edges into roads."); - } - } - if (oc.getBool("junctions.join") - || (oc.exists("ramps.guess") && oc.getBool("ramps.guess")) - || oc.getBool("tls.guess.joining") - || (oc.exists("tls.guess-signals") && oc.getBool("tls.guess-signals"))) { - // preliminary geometry computations to determine the length of edges - // This depends on turning directions and sorting of edge list - // in case junctions are joined geometry computations have to be repeated - // preliminary roundabout computations to avoid damaging roundabouts via junctions.join or ramps.guess - NBTurningDirectionsComputer::computeTurnDirections(myNodeCont, false); - NBNodesEdgesSorter::sortNodesEdges(myNodeCont); - myEdgeCont.computeLaneShapes(); - myNodeCont.computeNodeShapes(); - myEdgeCont.computeEdgeShapes(); - if (oc.getBool("roundabouts.guess")) { - myEdgeCont.guessRoundabouts(); - } - const std::set& roundabouts = myEdgeCont.getRoundabouts(); - for (std::set::const_iterator it_round = roundabouts.begin(); - it_round != roundabouts.end(); ++it_round) { - std::vector nodeIDs; - for (EdgeSet::const_iterator it_edge = it_round->begin(); it_edge != it_round->end(); ++it_edge) { - nodeIDs.push_back((*it_edge)->getToNode()->getID()); - } - myNodeCont.addJoinExclusion(nodeIDs); - } - NBNodeTypeComputer::validateRailCrossings(myNodeCont, myTLLCont); - } - // join junctions (may create new "geometry"-nodes so it needs to come before removing these - if (mayAddOrRemove && oc.exists("junctions.join-exclude") && oc.isSet("junctions.join-exclude")) { - myNodeCont.addJoinExclusion(oc.getStringVector("junctions.join-exclude")); - } - int numJoined = myNodeCont.joinLoadedClusters(myDistrictCont, myEdgeCont, myTLLCont); - if (mayAddOrRemove && oc.getBool("junctions.join")) { - before = PROGRESS_BEGIN_TIME_MESSAGE("Joining junction clusters"); - numJoined += myNodeCont.joinJunctions(oc.getFloat("junctions.join-dist"), myDistrictCont, myEdgeCont, myTLLCont, myPTStopCont); - PROGRESS_TIME_MESSAGE(before); - } - if (numJoined > 0) { - // bit of a misnomer since we're already done - WRITE_MESSAGE(" Joined " + toString(numJoined) + " junction cluster(s)."); - } - // - if (mayAddOrRemove && oc.exists("join-lanes") && oc.getBool("join-lanes")) { - before = PROGRESS_BEGIN_TIME_MESSAGE("Joining lanes"); - const int num = myEdgeCont.joinLanes(SVC_IGNORING) + myEdgeCont.joinLanes(SVC_PEDESTRIAN); - PROGRESS_TIME_MESSAGE(before); - WRITE_MESSAGE(" Joined lanes on " + toString(num) + " edges."); - } - // - if (mayAddOrRemove) { - int no = 0; - const bool removeGeometryNodes = oc.exists("geometry.remove") && oc.getBool("geometry.remove"); - before = PROGRESS_BEGIN_TIME_MESSAGE("Removing empty nodes" + std::string(removeGeometryNodes ? " and geometry nodes" : "")); - // removeUnwishedNodes needs turnDirections. @todo: try to call this less often - NBTurningDirectionsComputer::computeTurnDirections(myNodeCont, false); - no = myNodeCont.removeUnwishedNodes(myDistrictCont, myEdgeCont, myTLLCont, myPTStopCont, myPTLineCont, myParkingCont, removeGeometryNodes); - PROGRESS_TIME_MESSAGE(before); - WRITE_MESSAGE(" " + toString(no) + " nodes removed."); - } - - // MOVE TO ORIGIN - // compute new boundary after network modifications have taken place - Boundary boundary; - for (std::map::const_iterator it = myNodeCont.begin(); it != myNodeCont.end(); ++it) { - boundary.add(it->second->getPosition()); - } - for (std::map::const_iterator it = myEdgeCont.begin(); it != myEdgeCont.end(); ++it) { - boundary.add(it->second->getGeometry().getBoxBoundary()); - } - geoConvHelper.setConvBoundary(boundary); - - if (!oc.getBool("offset.disable-normalization") && oc.isDefault("offset.x") && oc.isDefault("offset.y")) { - moveToOrigin(geoConvHelper, lefthand); - } - geoConvHelper.computeFinal(lefthand); // information needed for location element fixed at this point - - if (oc.exists("geometry.min-dist") && !oc.isDefault("geometry.min-dist")) { - before = PROGRESS_BEGIN_TIME_MESSAGE("Reducing geometries"); - myEdgeCont.reduceGeometries(oc.getFloat("geometry.min-dist")); - PROGRESS_TIME_MESSAGE(before); - } - // @note: removing geometry can create similar edges so joinSimilarEdges must come afterwards - // @note: likewise splitting can destroy similarities so joinSimilarEdges must come before - if (mayAddOrRemove && oc.getBool("edges.join")) { - before = PROGRESS_BEGIN_TIME_MESSAGE("Joining similar edges"); - myNodeCont.joinSimilarEdges(myDistrictCont, myEdgeCont, myTLLCont); - PROGRESS_TIME_MESSAGE(before); - } - if (oc.getBool("opposites.guess")) { - PROGRESS_BEGIN_MESSAGE("guessing opposite direction edges"); - myEdgeCont.guessOpposites(); - PROGRESS_DONE_MESSAGE(); - } - // - if (mayAddOrRemove && oc.exists("geometry.split") && oc.getBool("geometry.split")) { - before = PROGRESS_BEGIN_TIME_MESSAGE("Splitting geometry edges"); - myEdgeCont.splitGeometry(myDistrictCont, myNodeCont); - PROGRESS_TIME_MESSAGE(before); - } - // turning direction - before = PROGRESS_BEGIN_TIME_MESSAGE("Computing turning directions"); - NBTurningDirectionsComputer::computeTurnDirections(myNodeCont); - PROGRESS_TIME_MESSAGE(before); - // correct edge geometries to avoid overlap - if (oc.exists("geometry.avoid-overlap") && oc.getBool("geometry.avoid-overlap")) { - myNodeCont.avoidOverlap(); - } - - // GUESS TLS POSITIONS - before = PROGRESS_BEGIN_TIME_MESSAGE("Assigning nodes to traffic lights"); - if (oc.isSet("tls.set")) { - std::vector tlControlledNodes = oc.getStringVector("tls.set"); - TrafficLightType type = SUMOXMLDefinitions::TrafficLightTypes.get(oc.getString("tls.default-type")); - for (std::vector::const_iterator i = tlControlledNodes.begin(); i != tlControlledNodes.end(); ++i) { - NBNode* node = myNodeCont.retrieve(*i); - if (node == nullptr) { - WRITE_WARNING("Building a tl-logic for junction '" + *i + "' is not possible." + "\n The junction '" + *i + "' is not known."); - } else { - myNodeCont.setAsTLControlled(node, myTLLCont, type); - } - } - } - myNodeCont.guessTLs(oc, myTLLCont); - PROGRESS_TIME_MESSAGE(before); - - // guess ramps (after guessing tls because ramps should not be build at traffic lights) - const bool modifyRamps = mayAddOrRemove && ( - (oc.exists("ramps.guess") && oc.getBool("ramps.guess")) - || (oc.exists("ramps.set") && oc.isSet("ramps.set"))); - if (modifyRamps || (oc.exists("ramps.guess-acceleration-lanes") && oc.getBool("ramps.guess-acceleration-lanes"))) { - before = SysUtils::getCurrentMillis(); - if (modifyRamps) { - PROGRESS_BEGIN_MESSAGE("Guessing and setting on-/off-ramps"); - } - NBNodesEdgesSorter::sortNodesEdges(myNodeCont); - NBRampsComputer::computeRamps(*this, oc); - if (modifyRamps) { - PROGRESS_TIME_MESSAGE(before); - } - } - // guess bike lanes - int addedLanes = 0; - if (mayAddOrRemove && ((oc.getBool("bikelanes.guess") || oc.getBool("bikelanes.guess.from-permissions")))) { - const int bikelanes = myEdgeCont.guessSpecialLanes(SVC_BICYCLE, oc.getFloat("default.bikelane-width"), - oc.getFloat("bikelanes.guess.min-speed"), - oc.getFloat("bikelanes.guess.max-speed"), - oc.getBool("bikelanes.guess.from-permissions"), - "bikelanes.guess.exclude"); - WRITE_MESSAGE("Guessed " + toString(bikelanes) + " bike lanes."); - addedLanes += bikelanes; - } - - // guess sidewalks - if (mayAddOrRemove && ((oc.getBool("sidewalks.guess") || oc.getBool("sidewalks.guess.from-permissions")))) { - const int sidewalks = myEdgeCont.guessSpecialLanes(SVC_PEDESTRIAN, oc.getFloat("default.sidewalk-width"), - oc.getFloat("sidewalks.guess.min-speed"), - oc.getFloat("sidewalks.guess.max-speed"), - oc.getBool("sidewalks.guess.from-permissions"), - "sidewalks.guess.exclude"); - WRITE_MESSAGE("Guessed " + toString(sidewalks) + " sidewalks."); - addedLanes += sidewalks; - } - // re-adapt stop lanes after adding special lanes - if (oc.exists("ptstop-output") && oc.isSet("ptstop-output") && addedLanes > 0) { - myPTStopCont.assignLanes(myEdgeCont); - } - - // check whether any not previously setable connections may be set now - myEdgeCont.recheckPostProcessConnections(); - - // remap ids if wished - int numChangedEdges = myEdgeCont.remapIDs(oc.getBool("numerical-ids"), oc.isSet("reserved-ids"), oc.getString("prefix"), myPTStopCont); - int numChangedNodes = myNodeCont.remapIDs(oc.getBool("numerical-ids"), oc.isSet("reserved-ids"), oc.getString("prefix")); - if (numChangedEdges + numChangedNodes > 0) { - WRITE_MESSAGE("Remapped " + toString(numChangedEdges) + " edge IDs and " + toString(numChangedNodes) + " node IDs."); - } - - // - if (oc.exists("geometry.max-angle")) { - myEdgeCont.checkGeometries( - DEG2RAD(oc.getFloat("geometry.max-angle")), - oc.getFloat("geometry.min-radius"), - oc.getBool("geometry.min-radius.fix"), - oc.getBool("geometry.min-radius.fix.railways")); - } - - // GEOMETRY COMPUTATION - // - before = PROGRESS_BEGIN_TIME_MESSAGE("Sorting nodes' edges"); - NBNodesEdgesSorter::sortNodesEdges(myNodeCont); - PROGRESS_TIME_MESSAGE(before); - myEdgeCont.computeLaneShapes(); - // - before = PROGRESS_BEGIN_TIME_MESSAGE("Computing node shapes"); - if (oc.exists("geometry.junction-mismatch-threshold")) { - myNodeCont.computeNodeShapes(oc.getFloat("geometry.junction-mismatch-threshold")); - } else { - myNodeCont.computeNodeShapes(); - } - PROGRESS_TIME_MESSAGE(before); - // - before = PROGRESS_BEGIN_TIME_MESSAGE("Computing edge shapes"); - myEdgeCont.computeEdgeShapes(oc.getBool("geometry.max-grade.fix") ? oc.getFloat("geometry.max-grade") / 100 : -1); - PROGRESS_TIME_MESSAGE(before); - // resort edges based on the node and edge shapes - NBNodesEdgesSorter::sortNodesEdges(myNodeCont, true); - NBTurningDirectionsComputer::computeTurnDirections(myNodeCont, false); - - // APPLY SPEED MODIFICATIONS - if (oc.exists("speed.offset")) { - const double speedOffset = oc.getFloat("speed.offset"); - const double speedFactor = oc.getFloat("speed.factor"); - const double speedMin = oc.getFloat("speed.minimum"); - if (speedOffset != 0 || speedFactor != 1 || speedMin > 0) { - before = PROGRESS_BEGIN_TIME_MESSAGE("Applying speed modifications"); - for (std::map::const_iterator i = myEdgeCont.begin(); i != myEdgeCont.end(); ++i) { - (*i).second->setSpeed(-1, MAX2((*i).second->getSpeed() * speedFactor + speedOffset, speedMin)); - } - PROGRESS_TIME_MESSAGE(before); - } - } - - // CONNECTIONS COMPUTATION - // - before = PROGRESS_BEGIN_TIME_MESSAGE("Computing node types"); - NBNodeTypeComputer::computeNodeTypes(myNodeCont, myTLLCont); - PROGRESS_TIME_MESSAGE(before); - // - myNetworkHaveCrossings = oc.getBool("walkingareas"); - if (mayAddOrRemove && oc.getBool("crossings.guess")) { - myNetworkHaveCrossings = true; - int crossings = 0; - for (std::map::const_iterator i = myNodeCont.begin(); i != myNodeCont.end(); ++i) { - crossings += (*i).second->guessCrossings(); - } - WRITE_MESSAGE("Guessed " + toString(crossings) + " pedestrian crossings."); - } - if (!myNetworkHaveCrossings) { - // recheck whether we had crossings in the input - for (std::map::const_iterator i = myNodeCont.begin(); i != myNodeCont.end(); ++i) { - if (i->second->getCrossingsIncludingInvalid().size() > 0) { - myNetworkHaveCrossings = true; - break; - } - } - } - - if (!mayAddOrRemove && myNetworkHaveCrossings) { - // crossings added via netedit - oc.resetWritable(); - oc.set("no-internal-links", "false"); - } - - // - before = PROGRESS_BEGIN_TIME_MESSAGE("Computing priorities"); - NBEdgePriorityComputer::computeEdgePriorities(myNodeCont); - PROGRESS_TIME_MESSAGE(before); - // - before = PROGRESS_BEGIN_TIME_MESSAGE("Computing approached edges"); - myEdgeCont.computeEdge2Edges(oc.getBool("no-left-connections")); - PROGRESS_TIME_MESSAGE(before); - // - if (oc.getBool("roundabouts.guess")) { - before = PROGRESS_BEGIN_TIME_MESSAGE("Guessing and setting roundabouts"); - const int numGuessed = myEdgeCont.guessRoundabouts(); - if (numGuessed > 0) { - WRITE_MESSAGE(" Guessed " + toString(numGuessed) + " roundabout(s)."); - } - PROGRESS_TIME_MESSAGE(before); - } - myEdgeCont.markRoundabouts(); - // - before = PROGRESS_BEGIN_TIME_MESSAGE("Computing approaching lanes"); - myEdgeCont.computeLanes2Edges(); - PROGRESS_TIME_MESSAGE(before); - // - before = PROGRESS_BEGIN_TIME_MESSAGE("Dividing of lanes on approached lanes"); - myNodeCont.computeLanes2Lanes(); - myEdgeCont.sortOutgoingLanesConnections(); - PROGRESS_TIME_MESSAGE(before); - // - if (oc.getBool("fringe.guess")) { - before = PROGRESS_BEGIN_TIME_MESSAGE("Guessing Network fringe"); - const int numGuessed = myNodeCont.guessFringe(); - if (numGuessed > 0) { - WRITE_MESSAGE(" Guessed " + toString(numGuessed) + " fringe nodes."); - } - PROGRESS_TIME_MESSAGE(before); - } - // - before = PROGRESS_BEGIN_TIME_MESSAGE("Processing turnarounds"); - if (!oc.getBool("no-turnarounds")) { - myEdgeCont.appendTurnarounds( - oc.getBool("no-turnarounds.tls"), - oc.getBool("no-turnarounds.fringe"), - oc.getBool("no-turnarounds.except-deadend"), - oc.getBool("no-turnarounds.except-turnlane"), - oc.getBool("no-turnarounds.geometry")); - } else { - myEdgeCont.appendTurnarounds(explicitTurnarounds, oc.getBool("no-turnarounds.tls")); - } - if (oc.exists("railway.topology.repair.stop-turn") && oc.getBool("railway.topology.repair.stop-turn") - && myPTStopCont.getStops().size() > 0) { - // allow direction reversal at all bidi-edges with stops - myEdgeCont.appendRailwayTurnarounds(myPTStopCont); - } - PROGRESS_TIME_MESSAGE(before); - // - before = PROGRESS_BEGIN_TIME_MESSAGE("Rechecking of lane endings"); - myEdgeCont.recheckLanes(); - PROGRESS_TIME_MESSAGE(before); - - if (myNetworkHaveCrossings && !oc.getBool("no-internal-links")) { - for (std::map::const_iterator i = myNodeCont.begin(); i != myNodeCont.end(); ++i) { - i->second->buildCrossingsAndWalkingAreas(); - } - } else { - for (std::map::const_iterator i = myNodeCont.begin(); i != myNodeCont.end(); ++i) { - // needed by netedit if the last crossings was deleted from the network - // and walkingareas have been invalidated since the last call to compute() - i->second->discardWalkingareas(); - } - if (oc.getBool("no-internal-links")) { - for (std::map::const_iterator i = myNodeCont.begin(); i != myNodeCont.end(); ++i) { - i->second->discardAllCrossings(false); - } - } - } - // join traffic lights (after building connections) - if (oc.getBool("tls.join")) { - before = PROGRESS_BEGIN_TIME_MESSAGE("Joining traffic light nodes"); - myNodeCont.joinTLS(myTLLCont, oc.getFloat("tls.join-dist")); - PROGRESS_TIME_MESSAGE(before); - } - - // COMPUTING RIGHT-OF-WAY AND TRAFFIC LIGHT PROGRAMS - // - before = PROGRESS_BEGIN_TIME_MESSAGE("Computing traffic light control information"); - myTLLCont.setTLControllingInformation(myEdgeCont, myNodeCont); - if (oc.exists("opendrive-files") && oc.isSet("opendrive-files")) { - myTLLCont.setOpenDriveSignalParameters(); - } - PROGRESS_TIME_MESSAGE(before); - // - before = PROGRESS_BEGIN_TIME_MESSAGE("Computing node logics"); - myNodeCont.computeLogics(myEdgeCont); - PROGRESS_TIME_MESSAGE(before); - - // - before = PROGRESS_BEGIN_TIME_MESSAGE("Computing traffic light logics"); - std::pair numbers = myTLLCont.computeLogics(oc); - PROGRESS_TIME_MESSAGE(before); - std::string progCount = ""; - if (numbers.first != numbers.second) { - progCount = "(" + toString(numbers.second) + " programs) "; - } - WRITE_MESSAGE(" " + toString(numbers.first) + " traffic light(s) " + progCount + "computed."); - - for (std::map::const_iterator i = myEdgeCont.begin(); i != myEdgeCont.end(); ++i) { - (*i).second->sortOutgoingConnectionsByIndex(); - } - // FINISHING INNER EDGES - if (!oc.getBool("no-internal-links")) { - before = PROGRESS_BEGIN_TIME_MESSAGE("Building inner edges"); - // walking areas shall only be built if crossings are wished as well - for (std::map::const_iterator i = myNodeCont.begin(); i != myNodeCont.end(); ++i) { - (*i).second->buildInnerEdges(); - } - PROGRESS_TIME_MESSAGE(before); - } - // PATCH NODE SHAPES - if (oc.getFloat("junctions.scurve-stretch") > 0) { - // @note: nodes have collected correction hints in buildInnerEdges() - before = PROGRESS_BEGIN_TIME_MESSAGE("stretching junctions to smooth geometries"); - myEdgeCont.computeLaneShapes(); - myNodeCont.computeNodeShapes(); - myEdgeCont.computeEdgeShapes(oc.getBool("geometry.max-grade.fix") ? oc.getFloat("geometry.max-grade") / 100 : -1); - for (std::map::const_iterator i = myNodeCont.begin(); i != myNodeCont.end(); ++i) { - (*i).second->buildInnerEdges(); - } - PROGRESS_TIME_MESSAGE(before); - } - // compute lane-to-lane node logics (require traffic lights and inner edges to be done) - myNodeCont.computeLogics2(myEdgeCont, oc); - - // remove guessed traffic lights at junctions without conflicts (requires computeLogics2) - myNodeCont.recheckGuessedTLS(myTLLCont); - - // - if (oc.isSet("street-sign-output")) { - before = PROGRESS_BEGIN_TIME_MESSAGE("Generating street signs"); - myEdgeCont.generateStreetSigns(); - PROGRESS_TIME_MESSAGE(before); - } - - - if (lefthand != oc.getBool("flip-y-axis")) { - mirrorX(); - }; - - if (oc.exists("geometry.check-overlap") && oc.getFloat("geometry.check-overlap") > 0) { - before = PROGRESS_BEGIN_TIME_MESSAGE("Checking overlapping edges"); - myEdgeCont.checkOverlap(oc.getFloat("geometry.check-overlap"), oc.getFloat("geometry.check-overlap.vertical-threshold")); - PROGRESS_TIME_MESSAGE(before); - } - if (geoConvHelper.getConvBoundary().getZRange() > 0 && oc.getFloat("geometry.max-grade") > 0) { - before = PROGRESS_BEGIN_TIME_MESSAGE("Checking edge grade"); - // user input is in % - myEdgeCont.checkGrade(oc.getFloat("geometry.max-grade") / 100); - PROGRESS_TIME_MESSAGE(before); - } - - //find accesses for pt rail stops and add bidi-stops - if (oc.exists("ptstop-output") && oc.isSet("ptstop-output")) { - before = SysUtils::getCurrentMillis(); - int numBidiStops = 0; - if (!oc.getBool("ptstop-output.no-bidi")) { - numBidiStops = myPTStopCont.generateBidiStops(myEdgeCont); - } - PROGRESS_BEGIN_MESSAGE("Find accesses for pt rail stops"); - double maxRadius = oc.getFloat("railway.access-distance"); - double accessFactor = oc.getFloat("railway.access-factor"); - int maxCount = oc.getInt("railway.max-accesses"); - myPTStopCont.findAccessEdgesForRailStops(myEdgeCont, maxRadius, maxCount, accessFactor); - PROGRESS_TIME_MESSAGE(before); - if (numBidiStops > 0) { - if (oc.exists("ptline-output") && oc.isSet("ptline-output")) { - myPTLineCont.fixBidiStops(myEdgeCont); - } - } - } - - // report - WRITE_MESSAGE("-----------------------------------------------------"); - WRITE_MESSAGE("Summary:"); - myNodeCont.printBuiltNodesStatistics(); - WRITE_MESSAGE(" Network boundaries:"); - WRITE_MESSAGE(" Original boundary : " + toString(geoConvHelper.getOrigBoundary())); - WRITE_MESSAGE(" Applied offset : " + toString(geoConvHelper.getOffsetBase())); - WRITE_MESSAGE(" Converted boundary : " + toString(geoConvHelper.getConvBoundary())); - WRITE_MESSAGE("-----------------------------------------------------"); - NBRequest::reportWarnings(); - // report on very large networks - if (MAX2(geoConvHelper.getConvBoundary().xmax(), geoConvHelper.getConvBoundary().ymax()) > 50000 || - MIN2(geoConvHelper.getConvBoundary().xmin(), geoConvHelper.getConvBoundary().ymin()) < -50000) { - WRITE_WARNING("Network contains very large coordinates and could cause problems with Unreal Engine coordinates. The recomended maximum value in any axis is 50000"); - } -} - - -/* -void -NBNetBuilder::computeSingleNode(NBNode* node, OptionsCont& oc, const std::set& explicitTurnarounds, bool mayAddOrRemove) { - // for a single node do the following: - // sortEdges - // computeLaneShapes - // computeNodeShapes - // computeEdgeShapes -} -*/ - - -void -NBNetBuilder::moveToOrigin(GeoConvHelper& geoConvHelper, bool lefthand) { - long before = PROGRESS_BEGIN_TIME_MESSAGE("Moving network to origin"); - Boundary boundary = geoConvHelper.getConvBoundary(); - // Center the network - const double x = -(boundary.xmin() + boundary.xmax())*0.5; - const double y = -(boundary.ymin() + boundary.ymax())*0.5; - //if (lefthand) { - // y = boundary.ymax(); - //} - for (std::map::const_iterator i = myNodeCont.begin(); i != myNodeCont.end(); ++i) { - (*i).second->reshiftPosition(x, y); - } - for (std::map::const_iterator i = myEdgeCont.begin(); i != myEdgeCont.end(); ++i) { - (*i).second->reshiftPosition(x, y); - } - for (std::map::const_iterator i = myDistrictCont.begin(); i != myDistrictCont.end(); ++i) { - (*i).second->reshiftPosition(x, y); - } - for (std::map::const_iterator i = myPTStopCont.begin(); i != myPTStopCont.end(); ++i) { - (*i).second->reshiftPosition(x, y); - } - geoConvHelper.moveConvertedBy(x, y); - PROGRESS_TIME_MESSAGE(before); -} - - -void -NBNetBuilder::mirrorX() { - // mirror the network along the X-axis - for (std::map::const_iterator i = myNodeCont.begin(); i != myNodeCont.end(); ++i) { - (*i).second->mirrorX(); - } - for (std::map::const_iterator i = myEdgeCont.begin(); i != myEdgeCont.end(); ++i) { - (*i).second->mirrorX(); - } - for (std::map::const_iterator i = myDistrictCont.begin(); i != myDistrictCont.end(); ++i) { - (*i).second->mirrorX(); - } - for (std::map::const_iterator i = myPTStopCont.begin(); i != myPTStopCont.end(); ++i) { - (*i).second->mirrorX(); - } -} - - -bool -NBNetBuilder::transformCoordinate(Position& from, bool includeInBoundary, GeoConvHelper* from_srs) { - Position orig(from); - bool ok = true; - if (GeoConvHelper::getNumLoaded() > 1 - && GeoConvHelper::getLoaded().usingGeoProjection() - && from_srs != nullptr - && from_srs->usingGeoProjection() - && *from_srs != GeoConvHelper::getLoaded()) { - from_srs->cartesian2geo(from); - ok &= GeoConvHelper::getLoaded().x2cartesian(from, false); - } - ok &= GeoConvHelper::getProcessing().x2cartesian(from, includeInBoundary); - if (ok) { - const NBHeightMapper& hm = NBHeightMapper::get(); - if (hm.ready()) { - if (from_srs != nullptr && from_srs->usingGeoProjection()) { - from_srs->cartesian2geo(orig); - } - from.setz(hm.getZ(orig)); - } - } - return ok; -} - - -bool -NBNetBuilder::transformCoordinates(PositionVector& from, bool includeInBoundary, GeoConvHelper* from_srs) { - const double maxLength = OptionsCont::getOptions().getFloat("geometry.max-segment-length"); - if (maxLength > 0 && from.size() > 1) { - // transformation to cartesian coordinates must happen before we can check segment length - PositionVector copy = from; - for (int i = 0; i < (int) from.size(); i++) { - transformCoordinate(copy[i], false); - } - addGeometrySegments(from, copy, maxLength); - } - bool ok = true; - for (int i = 0; i < (int) from.size(); i++) { - ok = ok && transformCoordinate(from[i], includeInBoundary, from_srs); - } - return ok; -} - -int -NBNetBuilder::addGeometrySegments(PositionVector& from, const PositionVector& cartesian, const double maxLength) { - // check lengths and insert new points where needed (in the original - // coordinate system) - int inserted = 0; - for (int i = 0; i < (int)cartesian.size() - 1; i++) { - Position start = from[i + inserted]; - Position end = from[i + inserted + 1]; - double length = cartesian[i].distanceTo(cartesian[i + 1]); - const Position step = (end - start) * (maxLength / length); - int steps = 0; - while (length > maxLength) { - length -= maxLength; - steps++; - from.insert(from.begin() + i + inserted + 1, start + (step * steps)); - inserted++; - } - } - return inserted; -} - - -bool -NBNetBuilder::runningNetedit() { - // see GNELoadThread::fillOptions - return OptionsCont::getOptions().exists("new"); -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netbuild/NBNetBuilder.h b/Util/OSM2ODR/src/netbuild/NBNetBuilder.h deleted file mode 100644 index 8e6b365d7..000000000 --- a/Util/OSM2ODR/src/netbuild/NBNetBuilder.h +++ /dev/null @@ -1,279 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NBNetBuilder.h -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Sascha Krieg -/// @author Michael Behrisch -/// @author Gregor Laemmel -/// @date Fri, 29.04.2005 -/// -// Instance responsible for building networks -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include -#include -#include -#include "NBEdgeCont.h" -#include "NBTypeCont.h" -#include "NBNodeCont.h" -#include "NBNode.h" -#include "NBParking.h" -#include "NBTrafficLightLogicCont.h" -#include "NBDistrictCont.h" -#include "NBPTStopCont.h" -#include "NBPTLineCont.h" -#include - - -// =========================================================================== -// class declarations -// =========================================================================== -class OptionsCont; -class OutputDevice; -class GeoConvHelper; - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NBNetBuilder - * @brief Instance responsible for building networks - * - * The class' - and the netbuild module's - functionality is embedded within the - * compute() method. - * - * @addtogroup netbuild - * @{ - * - * -# Removing self loops - * \n Removes edges which end at the node they start at using NBNodeCont::removeSelfLoops(). - * -# Joining double connections - * \n Joins edges between same nodes using NBNodeCont::recheckEdges(). - * -# Finding isolated roads (optional) - * -# Removing empty nodes and geometry nodes (optional) - * \n Removed nodes with no incoming/outgoing edges and nodes which can be transformed into - * geometry point using NBNodeCont::removeUnwishedNodes(). - * -# Removing unwished edges (optional) - * \n If "keep-edges.postload" and "keep-edges.explicit" are set, the edges not within "keep-edges.explicit" are - * removed from the network using NBEdgeCont::removeUnwishedEdges(). - * -# Rechecking nodes after edge removal (optional) - * \n If any of the edge removing options was set ("keep-edges.explicit", "remove-edges.explicit", "keep-edges.postload", - * "keep-edges.by-vclass", "keep-edges.input-file"), the now orphaned nodes are removed using - * NBNodeCont::removeUnwishedNodes(). - * -# Splitting geometry edges (optional) - * \n If "geometry.split" is set, edge geometries are converted to nodes using - * NBEdgeCont::splitGeometry(). - * -# Normalising/transposing node positions - * \n If "offset.disable-normalization", "offset.x", and "offset.y" are not - * set, the road graph's instances are moved to the origin. - * -# Guessing and setting on-/off-ramps - * -# Guessing and setting TLs - * -# Computing turning directions - * -# Sorting nodes' edges - * -# Guessing and setting roundabouts - * -# Computing Approached Edges - * -# Computing Approaching Lanes - * -# Dividing of Lanes on Approached Lanes - * -# Appending Turnarounds (optional) - * -# Rechecking of lane endings - * -# Computing node shapes - * -# Computing edge shapes - * -# Computing tls logics - * -# Computing node logics - * -# Computing traffic light logics - * - * @todo Removing unwished edges: Recheck whether this can be done during loading - whether this option/step is really needed. - * @todo Finding isolated roads: Describe - * @bug Removing empty nodes and geometry nodes: Ok, empty nodes should be removed, uh? But this is only done if "geometry.remove" is set. - * @} - */ -class NBNetBuilder { - friend class GNENet; // for triggering intermediate build steps - -public: - /// @brief Constructor - NBNetBuilder(); - - /// @brief Destructor - ~NBNetBuilder(); - - /** @brief Initialises the storage by applying given options - * - * Options, mainly steering the acceptance of edges, are parsed - * and the according internal variables are set. - * - * @param[in] oc The options container to read options from - * @exception ProcessError If something fails (message is included) - */ - void applyOptions(OptionsCont& oc); - - /** @brief Performs the network building steps - * - * @param[in] oc Container that contains options for building - * @param[in] explicitTurnarounds List of edge ids for which turn-arounds should be added (used by NETEDIT) - * @param[in] mayAddOrRemove whether processing steps which cause nodes and edges to be added or removed shall be triggered (used by netedit) - * @exception ProcessError (recheck) - */ - void compute(OptionsCont& oc, const std::set& explicitTurnarounds = std::set(), bool mayAddOrRemove = true); - - /** @brief Updates the shape for a single Node - * - * @param[in] oc Container that contains options for building - * @param[in] explicitTurnarounds List of edge ids for which turn-arounds should be added (used by NETEDIT) - * @param[in] mayAddOrRemove whether processing steps which cause nodes and edges to be added or removed shall be triggered (used by netedit) - * @exception ProcessError (recheck) - */ - //void computeSingleNode(NBNode* node, OptionsCont& oc, const std::set& explicitTurnarounds = std::set(), bool mayAddOrRemove = true); - - /// @name Retrieval of subcontainers - /// @{ - /// @brief Returns a reference to edge container - NBEdgeCont& getEdgeCont() { - return myEdgeCont; - } - - /// @brief Returns a reference to the node container - NBNodeCont& getNodeCont() { - return myNodeCont; - } - - /// @brief Returns a reference to the type container - NBTypeCont& getTypeCont() { - return myTypeCont; - } - - /// @brief Returns a reference to the traffic light logics container - NBTrafficLightLogicCont& getTLLogicCont() { - return myTLLCont; - } - - /// @brief Returns a reference the districts container - NBDistrictCont& getDistrictCont() { - return myDistrictCont; - } - - - /// @brief Returns a reference to the pt stop container - NBPTStopCont& getPTStopCont() { - return myPTStopCont; - } - - /// @brief Returns a reference to the pt line container - NBPTLineCont& getPTLineCont() { - return myPTLineCont; - } - /// @} - - NBParkingCont& getParkingCont() { - return myParkingCont; - } - - ShapeContainer& getShapeCont() { - return myShapeCont; - } - - /// @brief notify about style of loaded network (Without Crossings) - bool haveNetworkCrossings() { - return myNetworkHaveCrossings; - } - - /// @brief enable crossing in networks - void setHaveNetworkCrossings(bool value) { - myNetworkHaveCrossings = value; - } - - /** - * @brief transforms loaded coordinates - * handles projections, offsets (using GeoConvHelper) and import of height data (using NBHeightMapper) - * @param[in,out] from The coordinate to be transformed - * @param[in] includeInBoundary Whether to patch the convex boundary of the GeoConvHelper default instance - * @param[in] from_srs The spatial reference system of the input coordinate - * @notde These methods are located outside of GeoConvHelper to avoid linker-dependencies on GDAL for libgeom - */ - static bool transformCoordinate(Position& from, bool includeInBoundary = true, GeoConvHelper* from_srs = 0); - static bool transformCoordinates(PositionVector& from, bool includeInBoundary = true, GeoConvHelper* from_srs = 0); - - /// @brief insertion geometry points to ensure maximum segment length between points - static int addGeometrySegments(PositionVector& from, const PositionVector& cartesian, const double maxLength); - - /// @brief whether netbuilding takes place in the context of NETEDIT - static bool runningNetedit(); - - -protected: - /** - * @class by_id_sorter - * @brief Sorts nodes by their ids - */ - class by_id_sorter { - public: - /// @brief constructor - explicit by_id_sorter() {} - - /// @brief selection operator - int operator()(const NBNode* n1, const NBNode* n2) const { - return n1->getID() < n2->getID(); - } - }; - -protected: - /// @brief The used container for nodes - NBNodeCont myNodeCont; - - /// @brief The used container for street types - NBTypeCont myTypeCont; - - /// @brief The used container for edges - NBEdgeCont myEdgeCont; - - /// @brief The used container for traffic light logics - NBTrafficLightLogicCont myTLLCont; - - /// @brief The used container for districts - NBDistrictCont myDistrictCont; - - /// @brief The used container for pt stops - NBPTStopCont myPTStopCont; - - /// @brief The used container for pt stops - NBPTLineCont myPTLineCont; - - NBParkingCont myParkingCont; - - /// @brief container for loaded polygon data - ShapeContainer myShapeCont; - - /// @brief flag to indicate that network has crossings - bool myNetworkHaveCrossings; - -private: - /// @brief shift network so its lower left corner is at 0,0 - void moveToOrigin(GeoConvHelper& geoConvHelper, bool lefthand); - - /// @brief mirror the network along the X-axis - void mirrorX(); - -private: - /// @brief invalidated copy constructor - NBNetBuilder(const NBNetBuilder& s); - - /// @brief invalidated assignment operator - NBNetBuilder& operator=(const NBNetBuilder& s); -}; diff --git a/Util/OSM2ODR/src/netbuild/NBNode.cpp b/Util/OSM2ODR/src/netbuild/NBNode.cpp deleted file mode 100644 index d140577da..000000000 --- a/Util/OSM2ODR/src/netbuild/NBNode.cpp +++ /dev/null @@ -1,3472 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NBNode.cpp -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Sascha Krieg -/// @author Michael Behrisch -/// @date Tue, 20 Nov 2001 -/// -// The representation of a single node -/****************************************************************************/ -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "NBNode.h" -#include "NBAlgorithms.h" -#include "NBNodeCont.h" -#include "NBNodeShapeComputer.h" -#include "NBEdgeCont.h" -#include "NBTypeCont.h" -#include "NBHelpers.h" -#include "NBDistrict.h" -#include "NBContHelper.h" -#include "NBRequest.h" -#include "NBOwnTLDef.h" -#include "NBLoadedSUMOTLDef.h" -#include "NBTrafficLightLogicCont.h" -#include "NBTrafficLightDefinition.h" - -// allow to extend a crossing across multiple edges -#define EXTEND_CROSSING_ANGLE_THRESHOLD 35.0 // degrees -// create intermediate walking areas if either of the following thresholds is exceeded -#define SPLIT_CROSSING_WIDTH_THRESHOLD 1.5 // meters -#define SPLIT_CROSSING_ANGLE_THRESHOLD 5 // degrees - -// minimum length for a weaving section at a combined on-off ramp -#define MIN_WEAVE_LENGTH 20.0 - -//#define DEBUG_CONNECTION_GUESSING -//#define DEBUG_SMOOTH_GEOM -//#define DEBUG_PED_STRUCTURES -//#define DEBUG_EDGE_SORTING -//#define DEBUGCOND true -#define DEBUG_NODE_ID "F" -#define DEBUGCOND (getID() == DEBUG_NODE_ID) -#define DEBUGCOND2(obj) ((obj != 0 && (obj)->getID() == DEBUG_NODE_ID)) - -// =========================================================================== -// static members -// =========================================================================== -const int NBNode::FORWARD(1); -const int NBNode::BACKWARD(-1); -const double NBNode::UNSPECIFIED_RADIUS = -1; -const int NBNode::AVOID_WIDE_LEFT_TURN(1); -const int NBNode::AVOID_WIDE_RIGHT_TURN(2); -const int NBNode::FOUR_CONTROL_POINTS(4); -const int NBNode::AVOID_INTERSECTING_LEFT_TURNS(8); -const int NBNode::SCURVE_IGNORE(16); - -// =========================================================================== -// method definitions -// =========================================================================== -/* ------------------------------------------------------------------------- - * NBNode::ApproachingDivider-methods - * ----------------------------------------------------------------------- */ -NBNode::ApproachingDivider::ApproachingDivider( - const EdgeVector& approaching, NBEdge* currentOutgoing) : - myApproaching(approaching), - myCurrentOutgoing(currentOutgoing), - myIsBikeEdge(currentOutgoing->getPermissions() == SVC_BICYCLE) { - // collect lanes which are expliclity targeted - std::set approachedLanes; - for (const NBEdge* const approachingEdge : myApproaching) { - for (const NBEdge::Connection& con : approachingEdge->getConnections()) { - if (con.toEdge == myCurrentOutgoing) { - approachedLanes.insert(con.toLane); - } - } - } - // compute the indices of lanes that should be targeted (excluding pedestrian - // lanes that will be connected from walkingAreas and forbidden lanes) - // if the lane is targeted by an explicitly set connection we need - // to make it available anyway - for (int i = 0; i < currentOutgoing->getNumLanes(); ++i) { - if ((currentOutgoing->getPermissions(i) == SVC_PEDESTRIAN - // don't consider bicycle lanes as targets unless the target - // edge is exclusively for bicycles - || (currentOutgoing->getPermissions(i) == SVC_BICYCLE && !myIsBikeEdge) - || isForbidden(currentOutgoing->getPermissions(i))) - && approachedLanes.count(i) == 0) { - continue; - } - myAvailableLanes.push_back(i); - } -} - - -NBNode::ApproachingDivider::~ApproachingDivider() {} - - -void -NBNode::ApproachingDivider::execute(const int src, const int dest) { - assert((int)myApproaching.size() > src); - // get the origin edge - NBEdge* incomingEdge = myApproaching[src]; - if (incomingEdge->getStep() == NBEdge::EdgeBuildingStep::LANES2LANES_DONE || incomingEdge->getStep() == NBEdge::EdgeBuildingStep::LANES2LANES_USER) { - return; - } - if (myAvailableLanes.size() == 0) { - return; - } - std::vector approachingLanes = incomingEdge->getConnectionLanes(myCurrentOutgoing, myIsBikeEdge || incomingEdge->getPermissions() == SVC_BICYCLE); - if (approachingLanes.size() == 0) { - return; - } -#ifdef DEBUG_CONNECTION_GUESSING - if (DEBUGCOND2(incomingEdge->getToNode())) { - std::cout << "Bre:ex src=" << src << " dest=" << dest << " in=" << incomingEdge->getID() << " apLanes=" << toString(approachingLanes) << "\n"; - } - -#endif - std::deque* approachedLanes = spread(approachingLanes, dest); - assert(approachedLanes->size() <= myAvailableLanes.size()); - // set lanes - for (int i = 0; i < (int)approachedLanes->size(); i++) { - assert((int)approachingLanes.size() > i); - int approached = myAvailableLanes[(*approachedLanes)[i]]; - incomingEdge->setConnection(approachingLanes[i], myCurrentOutgoing, approached, NBEdge::Lane2LaneInfoType::COMPUTED); - } - delete approachedLanes; -} - - -std::deque* -NBNode::ApproachingDivider::spread(const std::vector& approachingLanes, int dest) const { - std::deque* ret = new std::deque(); - const int numLanes = (int)approachingLanes.size(); - // when only one lane is approached, we check, whether the double-value - // is assigned more to the left or right lane - if (numLanes == 1) { - ret->push_back(dest); - return ret; - } - - const int numOutgoingLanes = (int)myAvailableLanes.size(); - // - ret->push_back(dest); - int noSet = 1; - int roffset = 1; - int loffset = 1; - while (noSet < numLanes) { - // It may be possible, that there are not enough lanes the source - // lanes may be divided on - // In this case, they remain unset - // !!! this is only a hack. It is possible, that this yields in - // uncommon divisions - if (numOutgoingLanes == noSet) { - return ret; - } - - // as due to the conversion of double->uint the numbers will be lower - // than they should be, we try to append to the left side first - // - // check whether the left boundary of the approached street has - // been overridden; if so, move all lanes to the right - if (dest + loffset >= numOutgoingLanes) { - loffset -= 1; - roffset += 1; - for (int i = 0; i < (int)ret->size(); i++) { - (*ret)[i] = (*ret)[i] - 1; - } - } - // append the next lane to the left of all edges - // increase the position (destination edge) - ret->push_back(dest + loffset); - noSet++; - loffset += 1; - - // as above - if (numOutgoingLanes == noSet) { - return ret; - } - - // now we try to append the next lane to the right side, when needed - if (noSet < numLanes) { - // check whether the right boundary of the approached street has - // been overridden; if so, move all lanes to the right - if (dest < roffset) { - loffset += 1; - roffset -= 1; - for (int i = 0; i < (int)ret->size(); i++) { - (*ret)[i] = (*ret)[i] + 1; - } - } - ret->push_front(dest - roffset); - noSet++; - roffset += 1; - } - } - return ret; -} - - -NBNode::Crossing::Crossing(const NBNode* _node, const EdgeVector& _edges, double _width, bool _priority, int _customTLIndex, int _customTLIndex2, const PositionVector& _customShape) : - Parameterised(), - node(_node), - edges(_edges), - customWidth(_width), - width(_width), - priority(_priority), - customShape(_customShape), - tlLinkIndex(_customTLIndex), - tlLinkIndex2(_customTLIndex2), - customTLIndex(_customTLIndex), - customTLIndex2(_customTLIndex2), - valid(true) { -} - -/* ------------------------------------------------------------------------- - * NBNode-methods - * ----------------------------------------------------------------------- */ -NBNode::NBNode(const std::string& id, const Position& position, - SumoXMLNodeType type) : - Named(StringUtils::convertUmlaute(id)), - myPosition(position), - myType(type), - myDistrict(nullptr), - myHaveCustomPoly(false), - myRequest(nullptr), - myRadius(UNSPECIFIED_RADIUS), - myKeepClear(OptionsCont::getOptions().getBool("default.junctions.keep-clear")), - myRightOfWay(SUMOXMLDefinitions::RightOfWayValues.get(OptionsCont::getOptions().getString("default.right-of-way"))), - myFringeType(FringeType::DEFAULT), - myDiscardAllCrossings(false), - myCrossingsLoadedFromSumoNet(0), - myDisplacementError(0), - myIsBentPriority(false), - myTypeWasGuessed(false) { - if (!SUMOXMLDefinitions::isValidNetID(myID)) { - throw ProcessError("Invalid node id '" + myID + "'."); - } -} - - -NBNode::NBNode(const std::string& id, const Position& position, NBDistrict* district) : - Named(StringUtils::convertUmlaute(id)), - myPosition(position), - myType(district == nullptr ? SumoXMLNodeType::UNKNOWN : SumoXMLNodeType::DISTRICT), - myDistrict(district), - myHaveCustomPoly(false), - myRequest(nullptr), - myRadius(UNSPECIFIED_RADIUS), - myKeepClear(OptionsCont::getOptions().getBool("default.junctions.keep-clear")), - myRightOfWay(SUMOXMLDefinitions::RightOfWayValues.get(OptionsCont::getOptions().getString("default.right-of-way"))), - myFringeType(FringeType::DEFAULT), - myDiscardAllCrossings(false), - myCrossingsLoadedFromSumoNet(0), - myDisplacementError(0), - myIsBentPriority(false), - myTypeWasGuessed(false) { - if (!SUMOXMLDefinitions::isValidNetID(myID)) { - throw ProcessError("Invalid node id '" + myID + "'."); - } -} - - -NBNode::~NBNode() { - delete myRequest; -} - - -void -NBNode::reinit(const Position& position, SumoXMLNodeType type, - bool updateEdgeGeometries) { - myPosition = position; - // patch type - myType = type; - if (!isTrafficLight(myType)) { - removeTrafficLights(); - } - if (updateEdgeGeometries) { - for (EdgeVector::iterator i = myIncomingEdges.begin(); i != myIncomingEdges.end(); i++) { - PositionVector geom = (*i)->getGeometry(); - geom[-1] = myPosition; - (*i)->setGeometry(geom); - } - for (EdgeVector::iterator i = myOutgoingEdges.begin(); i != myOutgoingEdges.end(); i++) { - PositionVector geom = (*i)->getGeometry(); - geom[0] = myPosition; - (*i)->setGeometry(geom); - } - } -} - - - -// ----------- Applying offset -void -NBNode::reshiftPosition(double xoff, double yoff) { - myPosition.add(xoff, yoff, 0); - myPoly.add(xoff, yoff, 0); - for (auto& wacs : myWalkingAreaCustomShapes) { - wacs.shape.add(xoff, yoff, 0); - } - for (auto& c : myCrossings) { - c->customShape.add(xoff, yoff, 0); - } -} - - -void -NBNode::mirrorX() { - myPosition.mul(1, -1); - myPoly.mirrorX(); - // mirror pre-computed geometry of crossings and walkingareas - for (auto& c : myCrossings) { - c->customShape.mirrorX(); - c->shape.mirrorX(); - } - for (auto& wa : myWalkingAreas) { - wa.shape.mirrorX(); - } - for (auto& wacs : myWalkingAreaCustomShapes) { - wacs.shape.mirrorX(); - } -} - - -// ----------- Methods for dealing with assigned traffic lights -void -NBNode::addTrafficLight(NBTrafficLightDefinition* tlDef) { - myTrafficLights.insert(tlDef); - // rail signals receive a temporary traffic light in order to set connection tl-linkIndex - if (!isTrafficLight(myType) && myType != SumoXMLNodeType::RAIL_SIGNAL && myType != SumoXMLNodeType::RAIL_CROSSING) { - myType = SumoXMLNodeType::TRAFFIC_LIGHT; - } -} - - -void -NBNode::removeTrafficLight(NBTrafficLightDefinition* tlDef) { - tlDef->removeNode(this); - myTrafficLights.erase(tlDef); -} - - -void -NBNode::removeTrafficLights(bool setAsPriority) { - std::set trafficLights = myTrafficLights; // make a copy because we will modify the original - for (std::set::const_iterator i = trafficLights.begin(); i != trafficLights.end(); ++i) { - removeTrafficLight(*i); - } - if (setAsPriority) { - myType = myRequest != nullptr ? SumoXMLNodeType::PRIORITY : ( - myType == SumoXMLNodeType::TRAFFIC_LIGHT_NOJUNCTION ? SumoXMLNodeType::NOJUNCTION : SumoXMLNodeType::DEAD_END); - } -} - - -void -NBNode::invalidateTLS(NBTrafficLightLogicCont& tlCont, bool removedConnections, bool addedConnections) { - if (isTLControlled()) { - std::set oldDefs(myTrafficLights); - for (std::set::iterator it = oldDefs.begin(); it != oldDefs.end(); ++it) { - NBTrafficLightDefinition* orig = *it; - if (dynamic_cast(orig) != nullptr) { - dynamic_cast(orig)->registerModifications(removedConnections, addedConnections); - } else if (dynamic_cast(orig) == nullptr) { - NBTrafficLightDefinition* newDef = new NBOwnTLDef(orig->getID(), orig->getOffset(), orig->getType()); - const std::vector& nodes = orig->getNodes(); - while (!nodes.empty()) { - newDef->addNode(nodes.front()); - nodes.front()->removeTrafficLight(orig); - } - tlCont.removeFully(orig->getID()); - tlCont.insert(newDef); - } - } - } -} - - -void -NBNode::shiftTLConnectionLaneIndex(NBEdge* edge, int offset, int threshold) { - for (std::set::iterator it = myTrafficLights.begin(); it != myTrafficLights.end(); ++it) { - (*it)->shiftTLConnectionLaneIndex(edge, offset, threshold); - } -} - -// ----------- Prunning the input -int -NBNode::removeSelfLoops(NBDistrictCont& dc, NBEdgeCont& ec, NBTrafficLightLogicCont& tc) { - int ret = 0; - int pos = 0; - EdgeVector::const_iterator j = myIncomingEdges.begin(); - while (j != myIncomingEdges.end()) { - // skip edges which are only incoming and not outgoing - if (find(myOutgoingEdges.begin(), myOutgoingEdges.end(), *j) == myOutgoingEdges.end()) { - ++j; - ++pos; - continue; - } - // an edge with both its origin and destination being the current - // node should be removed - NBEdge* dummy = *j; - WRITE_WARNINGF(" Removing self-looping edge '%'", dummy->getID()); - // get the list of incoming edges connected to the self-loop - EdgeVector incomingConnected = dummy->getIncomingEdges(); - // get the list of outgoing edges connected to the self-loop - EdgeVector outgoingConnected = dummy->getConnectedEdges(); - // let the self-loop remap its connections - dummy->remapConnections(incomingConnected); - remapRemoved(tc, dummy, incomingConnected, outgoingConnected); - // delete the self-loop - ec.erase(dc, dummy); - j = myIncomingEdges.begin() + pos; - ++ret; - } - return ret; -} - - -// ----------- -void -NBNode::addIncomingEdge(NBEdge* edge) { - assert(edge != 0); - if (find(myIncomingEdges.begin(), myIncomingEdges.end(), edge) == myIncomingEdges.end()) { - myIncomingEdges.push_back(edge); - myAllEdges.push_back(edge); - } -} - - -void -NBNode::addOutgoingEdge(NBEdge* edge) { - assert(edge != 0); - if (find(myOutgoingEdges.begin(), myOutgoingEdges.end(), edge) == myOutgoingEdges.end()) { - myOutgoingEdges.push_back(edge); - myAllEdges.push_back(edge); - } -} - - -bool -NBNode::isSimpleContinuation(bool checkLaneNumbers, bool checkWidth) const { - // one in, one out->continuation - if (myIncomingEdges.size() == 1 && myOutgoingEdges.size() == 1) { - NBEdge* in = myIncomingEdges.front(); - NBEdge* out = myOutgoingEdges.front(); - // both must have the same number of lanes - return ((!checkLaneNumbers || in->getNumLanes() == out->getNumLanes()) - && (!checkWidth || in->getTotalWidth() == out->getTotalWidth())); - } - // two in and two out and both in reverse direction - if (myIncomingEdges.size() == 2 && myOutgoingEdges.size() == 2) { - for (EdgeVector::const_iterator i = myIncomingEdges.begin(); i != myIncomingEdges.end(); i++) { - NBEdge* in = *i; - EdgeVector::const_iterator opposite = find_if(myOutgoingEdges.begin(), myOutgoingEdges.end(), NBContHelper::opposite_finder(in)); - // must have an opposite edge - if (opposite == myOutgoingEdges.end()) { - return false; - } - // both must have the same number of lanes - NBContHelper::nextCW(myOutgoingEdges, opposite); - if (checkLaneNumbers && in->getNumLanes() != (*opposite)->getNumLanes()) { - return false; - } - if (checkWidth && in->getTotalWidth() != (*opposite)->getTotalWidth()) { - return false; - } - } - return true; - } - // nope - return false; -} - - -PositionVector -NBNode::computeSmoothShape(const PositionVector& begShape, - const PositionVector& endShape, - int numPoints, - bool isTurnaround, - double extrapolateBeg, - double extrapolateEnd, - NBNode* recordError, - int shapeFlag) const { - - bool ok = true; - PositionVector init = bezierControlPoints(begShape, endShape, isTurnaround, extrapolateBeg, extrapolateEnd, ok, recordError, DEG2RAD(5), shapeFlag); -#ifdef DEBUG_SMOOTH_GEOM - if (DEBUGCOND) { - std::cout << "computeSmoothShape node " << getID() << " init=" << init << "\n"; - } -#endif - if (init.size() == 0) { - PositionVector ret; - ret.push_back(begShape.back()); - ret.push_back(endShape.front()); - return ret; - } else { - return init.bezier(numPoints).smoothedZFront(); - } -} - -PositionVector -NBNode::bezierControlPoints( - const PositionVector& begShape, - const PositionVector& endShape, - bool isTurnaround, - double extrapolateBeg, - double extrapolateEnd, - bool& ok, - NBNode* recordError, - double straightThresh, - int shapeFlag) { - - const Position beg = begShape.back(); - const Position end = endShape.front(); - const double dist = beg.distanceTo2D(end); - PositionVector init; - if (dist < POSITION_EPS || beg.distanceTo2D(begShape[-2]) < POSITION_EPS || end.distanceTo2D(endShape[1]) < POSITION_EPS) { -#ifdef DEBUG_SMOOTH_GEOM - if (DEBUGCOND2(recordError)) std::cout << " bezierControlPoints failed beg=" << beg << " end=" << end - << " dist=" << dist - << " distBegLast=" << beg.distanceTo2D(begShape[-2]) - << " distEndFirst=" << end.distanceTo2D(endShape[1]) - << "\n"; -#endif - // typically, this node a is a simpleContinuation. see also #2539 - return init; - } else { - init.push_back(beg); - if (isTurnaround) { - // turnarounds: - // - end of incoming lane - // - position between incoming/outgoing end/begin shifted by the distance orthogonally - // - begin of outgoing lane - Position center = PositionVector::positionAtOffset2D(beg, end, beg.distanceTo2D(end) / (double) 2.); - center.sub(beg.y() - end.y(), end.x() - beg.x()); - init.push_back(center); - } else { - const double angle = GeomHelper::angleDiff(begShape.angleAt2D(-2), endShape.angleAt2D(0)); - PositionVector endShapeBegLine(endShape[0], endShape[1]); - PositionVector begShapeEndLineRev(begShape[-1], begShape[-2]); - endShapeBegLine.extrapolate2D(100, true); - begShapeEndLineRev.extrapolate2D(100, true); - if (fabs(angle) < M_PI / 4.) { - // very low angle: could be an s-shape or a straight line - const double displacementAngle = GeomHelper::angleDiff(begShape.angleAt2D(-2), beg.angleTo2D(end)); - const double bendDeg = RAD2DEG(fabs(displacementAngle - angle)); - const double halfDistance = dist / 2; - if (fabs(displacementAngle) <= straightThresh && fabs(angle) <= straightThresh) { -#ifdef DEBUG_SMOOTH_GEOM - if (DEBUGCOND2(recordError)) std::cout << " bezierControlPoints identified straight line beg=" << beg << " end=" << end - << " angle=" << RAD2DEG(angle) << " displacementAngle=" << RAD2DEG(displacementAngle) << "\n"; -#endif - return PositionVector(); - } else if (bendDeg > 22.5 && pow(bendDeg / 45, 2) / dist > 0.13) { - // do not allow s-curves with extreme bends - // (a linear dependency is to restrictive at low displacementAngles and too permisive at high angles) -#ifdef DEBUG_SMOOTH_GEOM - if (DEBUGCOND2(recordError)) std::cout << " bezierControlPoints found extreme s-curve, falling back to straight line beg=" << beg << " end=" << end - << " angle=" << RAD2DEG(angle) << " displacementAngle=" << RAD2DEG(displacementAngle) - << " dist=" << dist << " bendDeg=" << bendDeg << " bd2=" << pow(bendDeg / 45, 2) - << " displacementError=" << sin(displacementAngle) * dist - << " begShape=" << begShape << " endShape=" << endShape << "\n"; -#endif - ok = false; - if (recordError != nullptr && (shapeFlag & SCURVE_IGNORE) == 0) { - recordError->myDisplacementError = MAX2(recordError->myDisplacementError, (double)fabs(sin(displacementAngle) * dist)); - } - return PositionVector(); - } else { - const double endLength = begShape[-2].distanceTo2D(begShape[-1]); - const double off1 = endLength + MIN2(extrapolateBeg, halfDistance); - init.push_back(PositionVector::positionAtOffset2D(begShapeEndLineRev[1], begShapeEndLineRev[0], off1)); - const double off2 = 100. - MIN2(extrapolateEnd, halfDistance); - init.push_back(PositionVector::positionAtOffset2D(endShapeBegLine[0], endShapeBegLine[1], off2)); -#ifdef DEBUG_SMOOTH_GEOM - if (DEBUGCOND2(recordError)) std::cout << " bezierControlPoints found s-curve beg=" << beg << " end=" << end - << " angle=" << RAD2DEG(angle) << " displacementAngle=" << RAD2DEG(displacementAngle) - << " halfDistance=" << halfDistance << "\n"; -#endif - } - } else { - // turning - // - end of incoming lane - // - intersection of the extrapolated lanes - // - begin of outgoing lane - // attention: if there is no intersection, use a straight line - Position intersect = endShapeBegLine.intersectionPosition2D(begShapeEndLineRev); - if (intersect == Position::INVALID) { -#ifdef DEBUG_SMOOTH_GEOM - if (DEBUGCOND2(recordError)) { - std::cout << " bezierControlPoints failed beg=" << beg << " end=" << end << " intersect=" << intersect - << " endShapeBegLine=" << endShapeBegLine - << " begShapeEndLineRev=" << begShapeEndLineRev - << "\n"; - } -#endif - ok = false; - if (recordError != nullptr && (shapeFlag & SCURVE_IGNORE) == 0) { - // it's unclear if this error can be solved via stretching the intersection. - recordError->myDisplacementError = MAX2(recordError->myDisplacementError, (double)1.0); - } - return PositionVector(); - } - const double minControlLength = MIN2((double)1.0, dist / 2); - const double distBeg = intersect.distanceTo2D(beg); - const double distEnd = intersect.distanceTo2D(end); - const bool lengthenBeg = distBeg <= minControlLength; - const bool lengthenEnd = distEnd <= minControlLength; - if (lengthenBeg && lengthenEnd) { -#ifdef DEBUG_SMOOTH_GEOM - if (DEBUGCOND2(recordError)) std::cout << " bezierControlPoints failed beg=" << beg << " end=" << end << " intersect=" << intersect - << " distBeg=" << distBeg << " distEnd=" << distEnd << "\n"; -#endif - if (recordError != nullptr && (shapeFlag & SCURVE_IGNORE) == 0) { - // This should be fixable with minor stretching - recordError->myDisplacementError = MAX2(recordError->myDisplacementError, (double)1.0); - } - ok = false; - return PositionVector(); - } else if ((shapeFlag & FOUR_CONTROL_POINTS)) { - init.push_back(begShapeEndLineRev.positionAtOffset2D(100 - extrapolateBeg)); - init.push_back(endShapeBegLine.positionAtOffset2D(100 - extrapolateEnd)); - } else if (lengthenBeg || lengthenEnd) { - init.push_back(begShapeEndLineRev.positionAtOffset2D(100 - minControlLength)); - init.push_back(endShapeBegLine.positionAtOffset2D(100 - minControlLength)); - } else if ((shapeFlag & AVOID_WIDE_LEFT_TURN) != 0 - // there are two reasons for enabling special geometry rules: - // 1) sharp edge angles which could cause overshoot - // 2) junction geometries with a large displacement between opposite left turns - // which would cause the default geometry to overlap - && ((shapeFlag & AVOID_INTERSECTING_LEFT_TURNS) != 0 - || (angle > DEG2RAD(95) && (distBeg > 20 || distEnd > 20)))) { - //std::cout << " bezierControlPoints intersect=" << intersect << " dist=" << dist << " distBeg=" << distBeg << " distEnd=" << distEnd << " angle=" << RAD2DEG(angle) << " flag=" << shapeFlag << "\n"; - const double factor = ((shapeFlag & AVOID_INTERSECTING_LEFT_TURNS) == 0 ? 1 - : MIN2(0.6, 16 / dist)); - init.push_back(begShapeEndLineRev.positionAtOffset2D(100 - MIN2(distBeg * factor / 1.2, dist * factor / 1.8))); - init.push_back(endShapeBegLine.positionAtOffset2D(100 - MIN2(distEnd * factor / 1.2, dist * factor / 1.8))); - } else if ((shapeFlag & AVOID_WIDE_RIGHT_TURN) != 0 && angle < DEG2RAD(-95) && (distBeg > 20 || distEnd > 20)) { - //std::cout << " bezierControlPoints intersect=" << intersect << " distBeg=" << distBeg << " distEnd=" << distEnd << "\n"; - init.push_back(begShapeEndLineRev.positionAtOffset2D(100 - MIN2(distBeg / 1.4, dist / 2))); - init.push_back(endShapeBegLine.positionAtOffset2D(100 - MIN2(distEnd / 1.4, dist / 2))); - } else { - double z; - const double z1 = begShapeEndLineRev.positionAtOffset2D(begShapeEndLineRev.nearest_offset_to_point2D(intersect)).z(); - const double z2 = endShapeBegLine.positionAtOffset2D(endShapeBegLine.nearest_offset_to_point2D(intersect)).z(); - const double z3 = 0.5 * (beg.z() + end.z()); - // if z1 and z2 are on the same side in regard to z3 then we - // can use their avarage. Otherwise, the intersection in 3D - // is not good and we are better of using z3 - if ((z1 <= z3 && z2 <= z3) || (z1 >= z3 && z2 >= z3)) { - z = 0.5 * (z1 + z2); - } else { - z = z3; - } - intersect.set(intersect.x(), intersect.y(), z); - init.push_back(intersect); - } - } - } - init.push_back(end); - } - return init; -} - - -PositionVector -NBNode::computeInternalLaneShape(NBEdge* fromE, const NBEdge::Connection& con, int numPoints, NBNode* recordError, int shapeFlag) const { - if (con.fromLane >= fromE->getNumLanes()) { - throw ProcessError("Connection '" + con.getDescription(fromE) + "' starts at a non-existant lane."); - } - if (con.toLane >= con.toEdge->getNumLanes()) { - throw ProcessError("Connection '" + con.getDescription(fromE) + "' targets a non-existant lane."); - } - PositionVector fromShape = fromE->getLaneShape(con.fromLane); - PositionVector toShape = con.toEdge->getLaneShape(con.toLane); - PositionVector ret; - bool useCustomShape = con.customShape.size() > 0; - if (useCustomShape) { - // ensure that the shape starts and ends at the intersection boundary - PositionVector startBorder = fromE->getNodeBorder(this); - if (startBorder.size() == 0) { - startBorder = fromShape.getOrthogonal(fromShape.back(), 1, true); - } - PositionVector tmp = NBEdge::startShapeAt(con.customShape, this, startBorder); - if (tmp.size() < 2) { - WRITE_WARNINGF("Could not use custom shape for connection %.", con.getDescription(fromE)); - useCustomShape = false; - } else { - if (tmp.length2D() > con.customShape.length2D() + POSITION_EPS) { - // shape was lengthened at the start, make sure it attaches at the center of the lane - tmp[0] = fromShape.back(); - } else if (recordError != nullptr) { - const double offset = tmp[0].distanceTo2D(fromShape.back()); - if (offset > fromE->getLaneWidth(con.fromLane) / 2) { - WRITE_WARNINGF("Custom shape has distance % to incoming lane for connection %.", offset, con.getDescription(fromE)); - } - } - PositionVector endBorder = con.toEdge->getNodeBorder(this); - if (endBorder.size() == 0) { - endBorder = toShape.getOrthogonal(toShape.front(), 1, false); - } - ret = NBEdge::startShapeAt(tmp.reverse(), this, endBorder).reverse(); - if (ret.size() < 2) { - WRITE_WARNINGF("Could not use custom shape for connection %.", con.getDescription(fromE)); - useCustomShape = false; - } else if (ret.length2D() > tmp.length2D() + POSITION_EPS) { - // shape was lengthened at the end, make sure it attaches at the center of the lane - ret[-1] = toShape.front(); - } else if (recordError != nullptr) { - const double offset = ret[-1].distanceTo2D(toShape.front()); - if (offset > con.toEdge->getLaneWidth(con.toLane) / 2) { - WRITE_WARNINGF("Custom shape has distance % to outgoing lane for connection %.", offset, con.getDescription(fromE)); - } - } - } - } - if (!useCustomShape) { - displaceShapeAtWidthChange(fromE, con, fromShape, toShape); - double extrapolateBeg = 5. * fromE->getNumLanes(); - double extrapolateEnd = 5. * con.toEdge->getNumLanes(); - LinkDirection dir = getDirection(fromE, con.toEdge); - if (dir == LinkDirection::LEFT || dir == LinkDirection::TURN) { - shapeFlag += AVOID_WIDE_LEFT_TURN; - } -#ifdef DEBUG_SMOOTH_GEOM - if (DEBUGCOND) { - std::cout << "computeInternalLaneShape node " << getID() << " fromE=" << fromE->getID() << " toE=" << con.toEdge->getID() << "\n"; - } -#endif - ret = computeSmoothShape(fromShape, toShape, - numPoints, fromE->getTurnDestination() == con.toEdge, - extrapolateBeg, extrapolateEnd, recordError, shapeFlag); - } - const NBEdge::Lane& lane = fromE->getLaneStruct(con.fromLane); - if (lane.endOffset > 0) { - PositionVector beg = lane.shape.getSubpart(lane.shape.length() - lane.endOffset, lane.shape.length()); - beg.append(ret); - ret = beg; - } - if (con.toEdge->isBidiRail() && con.toEdge->getTurnDestination(true)->getEndOffset() > 0) { - PositionVector end = toShape.getSubpart(0, con.toEdge->getTurnDestination(true)->getEndOffset()); - ret.append(end); - } - return ret; -} - - -bool -NBNode::isConstantWidthTransition() const { - return (myIncomingEdges.size() == 1 - && myOutgoingEdges.size() == 1 - && myIncomingEdges[0]->getNumLanes() != myOutgoingEdges[0]->getNumLanes() - && myIncomingEdges[0]->getTotalWidth() == myOutgoingEdges[0]->getTotalWidth()); -} - -void -NBNode::displaceShapeAtWidthChange(const NBEdge* from, const NBEdge::Connection& con, - PositionVector& fromShape, PositionVector& toShape) const { - if (isConstantWidthTransition()) { - // displace shapes - NBEdge* in = myIncomingEdges[0]; - NBEdge* out = myOutgoingEdges[0]; - double outCenter = out->getLaneWidth(con.toLane) / 2; - for (int i = 0; i < con.toLane; ++i) { - outCenter += out->getLaneWidth(i); - } - double inCenter = in->getLaneWidth(con.fromLane) / 2; - for (int i = 0; i < con.fromLane; ++i) { - inCenter += in->getLaneWidth(i); - } - //std::cout << "displaceShapeAtWidthChange inCenter=" << inCenter << " outCenter=" << outCenter << "\n"; - try { - if (in->getNumLanes() > out->getNumLanes()) { - // shift toShape so the internal lane ends straight at the displaced entry point - toShape.move2side(outCenter - inCenter); - } else { - // shift fromShape so the internal lane starts straight at the displaced exit point - fromShape.move2side(inCenter - outCenter); - - } - } catch (InvalidArgument&) { } - } else { - SVCPermissions fromP = from->getPermissions(con.fromLane); - SVCPermissions toP = con.toEdge->getPermissions(con.toLane); - if ((fromP & toP) == SVC_BICYCLE && (fromP | toP) != SVC_BICYCLE) { - double shift = (from->getLaneWidth(con.fromLane) - con.toEdge->getLaneWidth(con.toLane)) / 2; - if (toP == SVC_BICYCLE) { - // let connection to dedicated bicycle lane start on the right side of a mixed lane for straight an right-going connections - // (on the left side for left turns) - // XXX indirect left turns should also start on the right side - LinkDirection dir = getDirection(from, con.toEdge); - if (dir == LinkDirection::LEFT || dir == LinkDirection::PARTLEFT || dir == LinkDirection::TURN) { - fromShape.move2side(-shift); - } else { - fromShape.move2side(shift); - } - } else if (fromP == SVC_BICYCLE) { - // let connection from dedicated bicycle end on the right side of a mixed lane - toShape.move2side(-shift); - } - } - } -} - -bool -NBNode::needsCont(const NBEdge* fromE, const NBEdge* otherFromE, - const NBEdge::Connection& c, const NBEdge::Connection& otherC) const { - const NBEdge* toE = c.toEdge; - const NBEdge* otherToE = otherC.toEdge; - - if (myType == SumoXMLNodeType::RIGHT_BEFORE_LEFT || myType == SumoXMLNodeType::ALLWAY_STOP) { - return false; - } - LinkDirection d1 = getDirection(fromE, toE); - const bool thisRight = (d1 == LinkDirection::RIGHT || d1 == LinkDirection::PARTRIGHT); - const bool rightTurnConflict = (thisRight && - NBNode::rightTurnConflict(fromE, toE, c.fromLane, otherFromE, otherToE, otherC.fromLane)); - if (thisRight && !rightTurnConflict) { - return false; - } - if (!(foes(otherFromE, otherToE, fromE, toE) || myRequest == nullptr || rightTurnConflict)) { - // if they do not cross, no waiting place is needed - return false; - } - LinkDirection d2 = getDirection(otherFromE, otherToE); - if (d2 == LinkDirection::TURN) { - return false; - } - const bool thisLeft = (d1 == LinkDirection::LEFT || d1 == LinkDirection::TURN); - const bool otherLeft = (d2 == LinkDirection::LEFT || d2 == LinkDirection::TURN); - const bool bothLeft = thisLeft && otherLeft; - if (fromE == otherFromE && !thisRight) { - // ignore same edge links except for right-turns - return false; - } - if (thisRight && d2 != LinkDirection::STRAIGHT) { - return false; - } - if (c.tlID != "" && !bothLeft) { - assert(myTrafficLights.size() > 0 || myType == SumoXMLNodeType::RAIL_CROSSING || myType == SumoXMLNodeType::RAIL_SIGNAL); - for (std::set::const_iterator it = myTrafficLights.begin(); it != myTrafficLights.end(); ++it) { - if ((*it)->needsCont(fromE, toE, otherFromE, otherToE)) { - return true; - } - } - return false; - } - if (fromE->getJunctionPriority(this) > 0 && otherFromE->getJunctionPriority(this) > 0) { - return mustBrake(fromE, toE, c.fromLane, c.toLane, false); - } - return false; -} - -bool -NBNode::tlsContConflict(const NBEdge* from, const NBEdge::Connection& c, - const NBEdge* foeFrom, const NBEdge::Connection& foe) const { - return (foe.haveVia && isTLControlled() && c.tlLinkIndex >= 0 && foe.tlLinkIndex >= 0 - && !foeFrom->isTurningDirectionAt(foe.toEdge) - && foes(from, c.toEdge, foeFrom, foe.toEdge) - && !needsCont(foeFrom, from, foe, c)); -} - - -void -NBNode::removeJoinedTrafficLights() { - std::set trafficLights = myTrafficLights; // make a copy because we will modify the original - for (std::set::const_iterator i = trafficLights.begin(); i != trafficLights.end(); ++i) { - // if this is the only controlled node we keep the tlDef as it is to generate a warning later - if ((*i)->getNodes().size() > 1) { - myTrafficLights.erase(*i); - (*i)->removeNode(this); - (*i)->setParticipantsInformation(); - (*i)->setTLControllingInformation(); - } - } -} - - -void -NBNode::computeLogic(const NBEdgeCont& ec) { - delete myRequest; // possibly recomputation step - myRequest = nullptr; - if (myIncomingEdges.size() == 0 || myOutgoingEdges.size() == 0) { - // no logic if nothing happens here - myType = SumoXMLNodeType::DEAD_END; - removeJoinedTrafficLights(); - return; - } - // compute the logic if necessary or split the junction - if (myType != SumoXMLNodeType::NOJUNCTION && myType != SumoXMLNodeType::DISTRICT && myType != SumoXMLNodeType::TRAFFIC_LIGHT_NOJUNCTION) { - // build the request - myRequest = new NBRequest(ec, this, myAllEdges, myIncomingEdges, myOutgoingEdges, myBlockedConnections); - // check whether it is not too large - int numConnections = numNormalConnections(); - if (numConnections >= SUMO_MAX_CONNECTIONS) { - // yep -> make it untcontrolled, warn - delete myRequest; - myRequest = nullptr; - if (myType == SumoXMLNodeType::TRAFFIC_LIGHT) { - myType = SumoXMLNodeType::TRAFFIC_LIGHT_NOJUNCTION; - } else { - myType = SumoXMLNodeType::NOJUNCTION; - } - WRITE_WARNINGF("Junction '%' is too complicated (% connections, max %); will be set to %.", - getID(), numConnections, SUMO_MAX_CONNECTIONS, toString(myType)); - } else if (numConnections == 0) { - delete myRequest; - myRequest = nullptr; - myType = SumoXMLNodeType::DEAD_END; - removeJoinedTrafficLights(); - } else { - myRequest->buildBitfieldLogic(); - } - } -} - - -void -NBNode::computeLogic2(bool checkLaneFoes) { - if (myRequest != nullptr) { - myRequest->computeLogic(checkLaneFoes); - } -} - - -bool -NBNode::writeLogic(OutputDevice& into) const { - if (myRequest) { - myRequest->writeLogic(into); - return true; - } - return false; -} - - -const std::string -NBNode::getFoes(int linkIndex) const { - if (myRequest == nullptr) { - return ""; - } else { - return myRequest->getFoes(linkIndex); - } -} - - -const std::string -NBNode::getResponse(int linkIndex) const { - if (myRequest == nullptr) { - return ""; - } else { - return myRequest->getResponse(linkIndex); - } -} - -bool -NBNode::hasConflict() const { - if (myRequest == nullptr) { - return false; - } else { - return myRequest->hasConflict(); - } -} - -void -NBNode::updateSurroundingGeometry() { - sortEdges(false); - computeNodeShape(-1); - for (NBEdge* edge : myAllEdges) { - edge->computeEdgeShape(); - } -} - -void -NBNode::computeNodeShape(double mismatchThreshold) { - if (myHaveCustomPoly) { - return; - } - if (myIncomingEdges.size() == 0 && myOutgoingEdges.size() == 0) { - // may be an intermediate step during network editing - myPoly.clear(); - myPoly.push_back(myPosition); - return; - } - if (OptionsCont::getOptions().getFloat("default.junctions.radius") < 0) { - // skip shape computation by option - return; - } - try { - NBNodeShapeComputer computer(*this); - myPoly = computer.compute(); - if (myRadius == UNSPECIFIED_RADIUS && !OptionsCont::getOptions().isDefault("default.junctions.radius")) { - myRadius = computer.getRadius(); - } - if (myPoly.size() > 0) { - PositionVector tmp = myPoly; - tmp.push_back_noDoublePos(tmp[0]); // need closed shape - if (mismatchThreshold >= 0 - && !tmp.around(myPosition) - && tmp.distance2D(myPosition) > mismatchThreshold) { - WRITE_WARNINGF("Shape for junction '%' has distance % to its given position.", myID, tmp.distance2D(myPosition)); - } - } - } catch (InvalidArgument&) { - WRITE_WARNINGF("For junction '%': could not compute shape.", myID); - // make sure our shape is not empty because our XML schema forbids empty attributes - myPoly.clear(); - myPoly.push_back(myPosition); - } -} - - -void -NBNode::computeLanes2Lanes() { - // special case a): - // one in, one out, the outgoing has more lanes - if (myIncomingEdges.size() == 1 && myOutgoingEdges.size() == 1) { - NBEdge* in = myIncomingEdges[0]; - NBEdge* out = myOutgoingEdges[0]; - // check if it's not the turnaround - if (in->getTurnDestination() == out) { - // will be added later or not... - return; - } -#ifdef DEBUG_CONNECTION_GUESSING - if (DEBUGCOND) { - std::cout << "l2l node=" << getID() << " specialCase a\n"; - } -#endif - int inOffset, outOffset, addedLanes; - getReduction(out, in, outOffset, inOffset, addedLanes); - if (in->getStep() <= NBEdge::EdgeBuildingStep::LANES2EDGES - && addedLanes > 0 - && in->isConnectedTo(out)) { - const int addedRight = addedLanesRight(out, addedLanes); - const int addedLeft = addedLanes - addedRight; - // "straight" connections - for (int i = inOffset; i < in->getNumLanes(); ++i) { - in->setConnection(i, out, i - inOffset + outOffset + addedRight, NBEdge::Lane2LaneInfoType::COMPUTED); - } - // connect extra lane on the right - for (int i = 0; i < addedRight; ++i) { - in->setConnection(inOffset, out, outOffset + i, NBEdge::Lane2LaneInfoType::COMPUTED); - } - // connect extra lane on the left - const int inLeftMost = in->getNumLanes() - 1; - const int outOffset2 = outOffset + addedRight + in->getNumLanes() - inOffset; - for (int i = 0; i < addedLeft; ++i) { - in->setConnection(inLeftMost, out, outOffset2 + i, NBEdge::Lane2LaneInfoType::COMPUTED); - } - return; - } - } - // special case b): - // two in, one out, the outgoing has the same number of lanes as the sum of the incoming - // --> highway on-ramp - if (myIncomingEdges.size() == 2 && myOutgoingEdges.size() == 1) { - NBEdge* out = myOutgoingEdges[0]; - NBEdge* in1 = myIncomingEdges[0]; - NBEdge* in2 = myIncomingEdges[1]; - const int outOffset = MAX2(0, out->getFirstNonPedestrianLaneIndex(FORWARD, true)); - int in1Offset = MAX2(0, in1->getFirstNonPedestrianLaneIndex(FORWARD, true)); - int in2Offset = MAX2(0, in2->getFirstNonPedestrianLaneIndex(FORWARD, true)); - if (in1->getNumLanes() + in2->getNumLanes() - in1Offset - in2Offset == out->getNumLanes() - outOffset - && (in1->getStep() <= NBEdge::EdgeBuildingStep::LANES2EDGES) - && (in2->getStep() <= NBEdge::EdgeBuildingStep::LANES2EDGES) - && in1 != out - && in2 != out - && in1->isConnectedTo(out) - && in2->isConnectedTo(out) - && in1->getSpecialLane(SVC_BICYCLE) == -1 - && in2->getSpecialLane(SVC_BICYCLE) == -1 - && out->getSpecialLane(SVC_BICYCLE) == -1 - && isLongEnough(out, MIN_WEAVE_LENGTH)) { -#ifdef DEBUG_CONNECTION_GUESSING - if (DEBUGCOND) { - std::cout << "l2l node=" << getID() << " specialCase b\n"; - } -#endif - // for internal: check which one is the rightmost - double a1 = in1->getAngleAtNode(this); - double a2 = in2->getAngleAtNode(this); - double ccw = GeomHelper::getCCWAngleDiff(a1, a2); - double cw = GeomHelper::getCWAngleDiff(a1, a2); - if (ccw > cw) { - std::swap(in1, in2); - std::swap(in1Offset, in2Offset); - } - in1->addLane2LaneConnections(in1Offset, out, outOffset, in1->getNumLanes() - in1Offset, NBEdge::Lane2LaneInfoType::VALIDATED, true); - in2->addLane2LaneConnections(in2Offset, out, in1->getNumLanes() + outOffset - in1Offset, in2->getNumLanes() - in2Offset, NBEdge::Lane2LaneInfoType::VALIDATED, true); - return; - } - } - // special case c): - // one in, two out, the incoming has the same number of lanes or only 1 lane less than the sum of the outgoing lanes - // --> highway off-ramp - if (myIncomingEdges.size() == 1 && myOutgoingEdges.size() == 2) { - NBEdge* in = myIncomingEdges[0]; - NBEdge* out1 = myOutgoingEdges[0]; - NBEdge* out2 = myOutgoingEdges[1]; - const int inOffset = MAX2(0, in->getFirstNonPedestrianLaneIndex(FORWARD, true)); - int out1Offset = MAX2(0, out1->getFirstNonPedestrianLaneIndex(FORWARD, true)); - int out2Offset = MAX2(0, out2->getFirstNonPedestrianLaneIndex(FORWARD, true)); - const int deltaLaneSum = (out2->getNumLanes() + out1->getNumLanes() - out1Offset - out2Offset) - (in->getNumLanes() - inOffset); - if ((deltaLaneSum == 0 || (deltaLaneSum == 1 && in->getPermissionVariants(inOffset, in->getNumLanes()).size() == 1)) - && (in->getStep() <= NBEdge::EdgeBuildingStep::LANES2EDGES) - && in != out1 - && in != out2 - && in->isConnectedTo(out1) - && in->isConnectedTo(out2) - && !in->isTurningDirectionAt(out1) - && !in->isTurningDirectionAt(out2) - ) { -#ifdef DEBUG_CONNECTION_GUESSING - if (DEBUGCOND) { - std::cout << "l2l node=" << getID() << " specialCase c\n"; - } -#endif - // for internal: check which one is the rightmost - if (NBContHelper::relative_outgoing_edge_sorter(in)(out2, out1)) { - std::swap(out1, out2); - std::swap(out1Offset, out2Offset); - } - in->addLane2LaneConnections(inOffset, out1, out1Offset, out1->getNumLanes() - out1Offset, NBEdge::Lane2LaneInfoType::VALIDATED, true); - in->addLane2LaneConnections(out1->getNumLanes() + inOffset - out1Offset - deltaLaneSum, out2, out2Offset, out2->getNumLanes() - out2Offset, NBEdge::Lane2LaneInfoType::VALIDATED, false); - return; - } - } - // special case d): - // one in, one out, the outgoing has one lane less and node has type 'zipper' - if (myIncomingEdges.size() == 1 && myOutgoingEdges.size() == 1 && myType == SumoXMLNodeType::ZIPPER) { - NBEdge* in = myIncomingEdges[0]; - NBEdge* out = myOutgoingEdges[0]; - // check if it's not the turnaround - if (in->getTurnDestination() == out) { - // will be added later or not... - return; - } -#ifdef DEBUG_CONNECTION_GUESSING - if (DEBUGCOND) { - std::cout << "l2l node=" << getID() << " specialCase d\n"; - } -#endif - const int inOffset = MAX2(0, in->getFirstNonPedestrianLaneIndex(FORWARD, true)); - const int outOffset = MAX2(0, out->getFirstNonPedestrianLaneIndex(FORWARD, true)); - if (in->getStep() <= NBEdge::EdgeBuildingStep::LANES2EDGES - && in->getNumLanes() - inOffset == out->getNumLanes() - outOffset + 1 - && in != out - && in->isConnectedTo(out)) { - for (int i = inOffset; i < in->getNumLanes(); ++i) { - in->setConnection(i, out, MIN2(outOffset + i, out->getNumLanes() - 1), NBEdge::Lane2LaneInfoType::COMPUTED, true); - } - return; - } - } - // special case f): - // one in, one out, out has reduced or same number of lanes - if (myIncomingEdges.size() == 1 && myOutgoingEdges.size() == 1) { - NBEdge* in = myIncomingEdges[0]; - NBEdge* out = myOutgoingEdges[0]; - // check if it's not the turnaround - if (in->getTurnDestination() == out) { - // will be added later or not... - return; - } -#ifdef DEBUG_CONNECTION_GUESSING - if (DEBUGCOND) { - std::cout << "l2l node=" << getID() << " specialCase f\n"; - } -#endif - int inOffset, outOffset, reduction; - getReduction(in, out, inOffset, outOffset, reduction); - if (in->getStep() <= NBEdge::EdgeBuildingStep::LANES2EDGES - && reduction >= 0 - && in != out - && in->isConnectedTo(out)) { - // in case of reduced lane number, let the rightmost lanse end - inOffset += reduction; - for (int i = outOffset; i < out->getNumLanes(); ++i) { - in->setConnection(i + inOffset - outOffset, out, i, NBEdge::Lane2LaneInfoType::COMPUTED); - } - //std::cout << " special case f at node=" << getID() << " inOffset=" << inOffset << " outOffset=" << outOffset << "\n"; - return; - } - } - - // go through this node's outgoing edges - // for every outgoing edge, compute the distribution of the node's - // incoming edges on this edge when approaching this edge - // the incoming edges' steps will then also be marked as LANE2LANE_RECHECK... - EdgeVector approaching; - for (NBEdge* currentOutgoing : myOutgoingEdges) { - // get the information about edges that do approach this edge - getEdgesThatApproach(currentOutgoing, approaching); - const int numApproaching = (int)approaching.size(); - if (numApproaching != 0) { - ApproachingDivider divider(approaching, currentOutgoing); - Bresenham::compute(÷r, numApproaching, divider.numAvailableLanes()); - } -#ifdef DEBUG_CONNECTION_GUESSING - if (DEBUGCOND) { - std::cout << "l2l node=" << getID() << " bresenham:\n"; - for (NBEdge* e : myIncomingEdges) { - const std::vector& elv = e->getConnections(); - for (std::vector::const_iterator k = elv.begin(); k != elv.end(); ++k) { - std::cout << " " << e->getID() << "_" << (*k).fromLane << " -> " << (*k).toEdge->getID() << "_" << (*k).toLane << "\n"; - } - } - } -#endif - int bikeLaneTarget = currentOutgoing->getSpecialLane(SVC_BICYCLE); - - // ensure that all modes have a connection if possible - for (NBEdge* incoming : myIncomingEdges) { - if (incoming->getConnectionLanes(currentOutgoing).size() > 0 && incoming->getStep() <= NBEdge::EdgeBuildingStep::LANES2LANES_DONE) { - // no connections are needed for pedestrians during this step - // no satisfaction is possible if the outgoing edge disallows - SVCPermissions unsatisfied = incoming->getPermissions() & currentOutgoing->getPermissions() & ~SVC_PEDESTRIAN; - //std::cout << "initial unsatisfied modes from edge=" << incoming->getID() << " toEdge=" << currentOutgoing->getID() << " deadModes=" << getVehicleClassNames(unsatisfied) << "\n"; - const std::vector& elv = incoming->getConnections(); - for (std::vector::const_iterator k = elv.begin(); k != elv.end(); ++k) { - const NBEdge::Connection& c = *k; - if (c.toEdge == currentOutgoing && c.toLane >= 0) { - const SVCPermissions satisfied = (incoming->getPermissions(c.fromLane) & c.toEdge->getPermissions(c.toLane)); - //std::cout << " from=" << incoming->getID() << "_" << c.fromLane << " to=" << c.toEdge->getID() << "_" << c.toLane << " satisfied=" << getVehicleClassNames(satisfied) << "\n"; - unsatisfied &= ~satisfied; - } - } - if (unsatisfied != 0) { -#ifdef DEBUG_CONNECTION_GUESSING - if (DEBUGCOND) { - std::cout << " unsatisfied modes from edge=" << incoming->getID() << " toEdge=" << currentOutgoing->getID() << " deadModes=" << getVehicleClassNames(unsatisfied) << "\n"; - } -#endif - int fromLane = 0; - while (unsatisfied != 0 && fromLane < incoming->getNumLanes()) { - if ((incoming->getPermissions(fromLane) & unsatisfied) != 0) { - for (int toLane = 0; toLane < currentOutgoing->getNumLanes(); ++toLane) { - const SVCPermissions satisfied = incoming->getPermissions(fromLane) & currentOutgoing->getPermissions(toLane) & unsatisfied; - if (satisfied != 0 && !incoming->getLaneStruct(fromLane).connectionsDone) { - bool mayUseSameDestination = unsatisfied == SVC_TRAM; - incoming->setConnection((int)fromLane, currentOutgoing, toLane, NBEdge::Lane2LaneInfoType::COMPUTED, mayUseSameDestination); -#ifdef DEBUG_CONNECTION_GUESSING - if (DEBUGCOND) { - std::cout << " new connection from=" << fromLane << " to=" << currentOutgoing->getID() << "_" << toLane << " satisfies=" << getVehicleClassNames(satisfied) << "\n"; - } -#endif - unsatisfied &= ~satisfied; - } - } - } - fromLane++; - } -#ifdef DEBUG_CONNECTION_GUESSING - if (DEBUGCOND) { - if (unsatisfied != 0) { - std::cout << " still unsatisfied modes from edge=" << incoming->getID() << " toEdge=" << currentOutgoing->getID() << " deadModes=" << getVehicleClassNames(unsatisfied) << "\n"; - } - } -#endif - } - } - // prevent dead-end bicycle lanes (they were excluded by the ApproachingDivider) - // and the bicycle mode might already be satisfied by other lanes - // assume that left-turns and turn-arounds are better satisfied from lanes to the left - LinkDirection dir = getDirection(incoming, currentOutgoing); - if (incoming->getStep() <= NBEdge::EdgeBuildingStep::LANES2LANES_DONE - && ((bikeLaneTarget >= 0 && dir != LinkDirection::TURN) - || dir == LinkDirection::RIGHT || dir == LinkDirection::PARTRIGHT || dir == LinkDirection::STRAIGHT)) { - bool builtConnection = false; - for (int i = 0; i < (int)incoming->getNumLanes(); i++) { - if (incoming->getPermissions(i) == SVC_BICYCLE - && incoming->getConnectionsFromLane(i, currentOutgoing).size() == 0) { - // find a dedicated bike lane as target - if (bikeLaneTarget >= 0) { - incoming->setConnection(i, currentOutgoing, bikeLaneTarget, NBEdge::Lane2LaneInfoType::COMPUTED); - builtConnection = true; - } else { - // use any lane that allows bicycles - for (int i2 = 0; i2 < (int)currentOutgoing->getNumLanes(); i2++) { - if ((currentOutgoing->getPermissions(i2) & SVC_BICYCLE) != 0) { - // possibly a double-connection - // XXX could use 'true' here but this requires additional work on tls generation - incoming->setConnection(i, currentOutgoing, i2, NBEdge::Lane2LaneInfoType::COMPUTED, false); - builtConnection = true; - break; - } - } - } - } - } - if (!builtConnection && bikeLaneTarget >= 0 - && incoming->getConnectionsFromLane(-1, currentOutgoing, bikeLaneTarget).size() == 0) { - // find origin lane that allows bicycles - int start = 0; - int end = (int)incoming->getNumLanes(); - int inc = 1; - if (dir == LinkDirection::TURN || dir == LinkDirection::LEFT || dir == LinkDirection::PARTLEFT) { - std::swap(start, end); - inc = -1; - } - for (int i = start; i < end; i += inc) { - if ((incoming->getPermissions(i) & SVC_BICYCLE) != 0) { - incoming->setConnection(i, currentOutgoing, bikeLaneTarget, NBEdge::Lane2LaneInfoType::COMPUTED); - break; - } - } - } - } - } - } - // special case e): rail_crossing - // there should only be straight connections here - if (myType == SumoXMLNodeType::RAIL_CROSSING) { - for (EdgeVector::const_iterator i = myIncomingEdges.begin(); i != myIncomingEdges.end(); i++) { - const std::vector cons = (*i)->getConnections(); - for (std::vector::const_iterator k = cons.begin(); k != cons.end(); ++k) { - if (getDirection(*i, (*k).toEdge) == LinkDirection::TURN) { - (*i)->removeFromConnections((*k).toEdge); - } - } - } - } - - // ... but we may have the case that there are no outgoing edges - // In this case, we have to mark the incoming edges as being in state - // LANE2LANE( not RECHECK) by hand - if (myOutgoingEdges.size() == 0) { - for (NBEdge* incoming : myIncomingEdges) { - incoming->markAsInLane2LaneState(); - } - } - -#ifdef DEBUG_CONNECTION_GUESSING - if (DEBUGCOND) { - std::cout << "final connections at " << getID() << "\n"; - for (NBEdge* e : myIncomingEdges) { - const std::vector& elv = e->getConnections(); - for (std::vector::const_iterator k = elv.begin(); k != elv.end(); ++k) { - std::cout << " " << e->getID() << "_" << (*k).fromLane << " -> " << (*k).toEdge->getID() << "_" << (*k).toLane << "\n"; - } - } - } -#endif -} - - -void -NBNode::getReduction(const NBEdge* in, const NBEdge* out, int& inOffset, int& outOffset, int& reduction) const { - inOffset = MAX2(0, in->getFirstNonPedestrianLaneIndex(FORWARD, true)); - outOffset = MAX2(0, out->getFirstNonPedestrianLaneIndex(FORWARD, true)); - reduction = (in->getNumLanes() - inOffset) - (out->getNumLanes() - outOffset); -} - - -int -NBNode::addedLanesRight(NBEdge* out, int addedLanes) const { - if (out->isOffRamp()) { - return addedLanes; - } - NBNode* to = out->getToNode(); - // check whether a right lane ends - if (to->getIncomingEdges().size() == 1 - && to->getOutgoingEdges().size() == 1) { - int inOffset, outOffset, reduction; - to->getReduction(out, to->getOutgoingEdges()[0], inOffset, outOffset, reduction); - if (reduction > 0) { - return reduction; - } - } - // check for the presence of right and left turns at the next intersection - int outLanesRight = 0; - int outLanesLeft = 0; - int outLanesStraight = 0; - for (NBEdge* succ : to->getOutgoingEdges()) { - if (out->isConnectedTo(succ)) { - const int outOffset = MAX2(0, succ->getFirstNonPedestrianLaneIndex(FORWARD, true)); - const int usableLanes = succ->getNumLanes() - outOffset; - LinkDirection dir = to->getDirection(out, succ); - if (dir == LinkDirection::STRAIGHT) { - outLanesStraight += usableLanes; - } else if (dir == LinkDirection::RIGHT || dir == LinkDirection::PARTRIGHT) { - outLanesRight += usableLanes; - } else { - outLanesLeft += usableLanes; - } - } - } - const int outOffset = MAX2(0, out->getFirstNonPedestrianLaneIndex(FORWARD, true)); - const int usableLanes = out->getNumLanes() - outOffset; - int addedTurnLanes = MIN3( - addedLanes, - MAX2(0, usableLanes - outLanesStraight), - outLanesRight + outLanesLeft); - if (outLanesLeft == 0) { - return addedTurnLanes; - } else { - return MIN2(addedTurnLanes / 2, outLanesRight); - } -} - - -bool -NBNode::isLongEnough(NBEdge* out, double minLength) { - double seen = out->getLoadedLength(); - while (seen < minLength) { - // advance along trivial continuations - if (out->getToNode()->getOutgoingEdges().size() != 1 - || out->getToNode()->getIncomingEdges().size() != 1) { - return false; - } else { - out = out->getToNode()->getOutgoingEdges()[0]; - seen += out->getLoadedLength(); - } - } - return true; -} - - -void -NBNode::getEdgesThatApproach(NBEdge* currentOutgoing, EdgeVector& approaching) { - // get the position of the node to get the approaching nodes of - EdgeVector::const_iterator i = std::find(myAllEdges.begin(), - myAllEdges.end(), currentOutgoing); - // get the first possible approaching edge - NBContHelper::nextCW(myAllEdges, i); - // go through the list of edges clockwise and add the edges - approaching.clear(); - for (; *i != currentOutgoing;) { - // check only incoming edges - if ((*i)->getToNode() == this && (*i)->getTurnDestination() != currentOutgoing) { - std::vector connLanes = (*i)->getConnectionLanes(currentOutgoing); - if (connLanes.size() != 0) { - approaching.push_back(*i); - } - } - NBContHelper::nextCW(myAllEdges, i); - } -} - - -void -NBNode::replaceOutgoing(NBEdge* which, NBEdge* by, int laneOff) { - // replace the edge in the list of outgoing nodes - EdgeVector::iterator i = std::find(myOutgoingEdges.begin(), myOutgoingEdges.end(), which); - if (i != myOutgoingEdges.end()) { - (*i) = by; - i = std::find(myAllEdges.begin(), myAllEdges.end(), which); - (*i) = by; - } - // replace the edge in connections of incoming edges - for (i = myIncomingEdges.begin(); i != myIncomingEdges.end(); ++i) { - (*i)->replaceInConnections(which, by, laneOff); - } - // replace within the connetion prohibition dependencies - replaceInConnectionProhibitions(which, by, 0, laneOff); -} - - -void -NBNode::replaceOutgoing(const EdgeVector& which, NBEdge* by) { - // replace edges - int laneOff = 0; - for (EdgeVector::const_iterator i = which.begin(); i != which.end(); i++) { - replaceOutgoing(*i, by, laneOff); - laneOff += (*i)->getNumLanes(); - } - // removed double occurences - removeDoubleEdges(); - // check whether this node belongs to a district and the edges - // must here be also remapped - if (myDistrict != nullptr) { - myDistrict->replaceOutgoing(which, by); - } -} - - -void -NBNode::replaceIncoming(NBEdge* which, NBEdge* by, int laneOff) { - // replace the edge in the list of incoming nodes - EdgeVector::iterator i = std::find(myIncomingEdges.begin(), myIncomingEdges.end(), which); - if (i != myIncomingEdges.end()) { - (*i) = by; - i = std::find(myAllEdges.begin(), myAllEdges.end(), which); - (*i) = by; - } - // replace within the connetion prohibition dependencies - replaceInConnectionProhibitions(which, by, laneOff, 0); -} - - -void -NBNode::replaceIncoming(const EdgeVector& which, NBEdge* by) { - // replace edges - int laneOff = 0; - for (EdgeVector::const_iterator i = which.begin(); i != which.end(); i++) { - replaceIncoming(*i, by, laneOff); - laneOff += (*i)->getNumLanes(); - } - // removed double occurences - removeDoubleEdges(); - // check whether this node belongs to a district and the edges - // must here be also remapped - if (myDistrict != nullptr) { - myDistrict->replaceIncoming(which, by); - } -} - - - -void -NBNode::replaceInConnectionProhibitions(NBEdge* which, NBEdge* by, - int whichLaneOff, int byLaneOff) { - // replace in keys - NBConnectionProhibits::iterator j = myBlockedConnections.begin(); - while (j != myBlockedConnections.end()) { - bool changed = false; - NBConnection c = (*j).first; - if (c.replaceFrom(which, whichLaneOff, by, byLaneOff)) { - changed = true; - } - if (c.replaceTo(which, whichLaneOff, by, byLaneOff)) { - changed = true; - } - if (changed) { - myBlockedConnections[c] = (*j).second; - myBlockedConnections.erase(j); - j = myBlockedConnections.begin(); - } else { - j++; - } - } - // replace in values - for (j = myBlockedConnections.begin(); j != myBlockedConnections.end(); j++) { - NBConnectionVector& prohibiting = (*j).second; - for (NBConnectionVector::iterator k = prohibiting.begin(); k != prohibiting.end(); k++) { - NBConnection& sprohibiting = *k; - sprohibiting.replaceFrom(which, whichLaneOff, by, byLaneOff); - sprohibiting.replaceTo(which, whichLaneOff, by, byLaneOff); - } - } -} - - - -void -NBNode::removeDoubleEdges() { - // check incoming - for (int i = 0; myIncomingEdges.size() > 0 && i < (int)myIncomingEdges.size() - 1; i++) { - int j = i + 1; - while (j < (int)myIncomingEdges.size()) { - if (myIncomingEdges[i] == myIncomingEdges[j]) { - myIncomingEdges.erase(myIncomingEdges.begin() + j); - } else { - j++; - } - } - } - // check outgoing - for (int i = 0; myOutgoingEdges.size() > 0 && i < (int)myOutgoingEdges.size() - 1; i++) { - int j = i + 1; - while (j < (int)myOutgoingEdges.size()) { - if (myOutgoingEdges[i] == myOutgoingEdges[j]) { - myOutgoingEdges.erase(myOutgoingEdges.begin() + j); - } else { - j++; - } - } - } - // check all - for (int i = 0; myAllEdges.size() > 0 && i < (int)myAllEdges.size() - 1; i++) { - int j = i + 1; - while (j < (int)myAllEdges.size()) { - if (myAllEdges[i] == myAllEdges[j]) { - myAllEdges.erase(myAllEdges.begin() + j); - } else { - j++; - } - } - } -} - - -bool -NBNode::hasIncoming(const NBEdge* const e) const { - return std::find(myIncomingEdges.begin(), myIncomingEdges.end(), e) != myIncomingEdges.end(); -} - - -bool -NBNode::hasOutgoing(const NBEdge* const e) const { - return std::find(myOutgoingEdges.begin(), myOutgoingEdges.end(), e) != myOutgoingEdges.end(); -} - - -NBEdge* -NBNode::getOppositeIncoming(NBEdge* e) const { - EdgeVector edges = myIncomingEdges; - if (find(edges.begin(), edges.end(), e) != edges.end()) { - edges.erase(find(edges.begin(), edges.end(), e)); - } - if (edges.size() == 0) { - return nullptr; - } - if (e->getToNode() == this) { - sort(edges.begin(), edges.end(), NBContHelper::edge_opposite_direction_sorter(e, this, false)); - } else { - sort(edges.begin(), edges.end(), NBContHelper::edge_similar_direction_sorter(e)); - } - return edges[0]; -} - - -void -NBNode::addSortedLinkFoes(const NBConnection& mayDrive, - const NBConnection& mustStop) { - if (mayDrive.getFrom() == nullptr || - mayDrive.getTo() == nullptr || - mustStop.getFrom() == nullptr || - mustStop.getTo() == nullptr) { - - WRITE_WARNING("Something went wrong during the building of a connection..."); - return; // !!! mark to recompute connections - } - NBConnectionVector conn = myBlockedConnections[mustStop]; - conn.push_back(mayDrive); - myBlockedConnections[mustStop] = conn; -} - - -NBEdge* -NBNode::getPossiblySplittedIncoming(const std::string& edgeid) { - int size = (int) edgeid.length(); - for (EdgeVector::iterator i = myIncomingEdges.begin(); i != myIncomingEdges.end(); i++) { - std::string id = (*i)->getID(); - if (id.substr(0, size) == edgeid) { - return *i; - } - } - return nullptr; -} - - -NBEdge* -NBNode::getPossiblySplittedOutgoing(const std::string& edgeid) { - int size = (int) edgeid.length(); - for (EdgeVector::iterator i = myOutgoingEdges.begin(); i != myOutgoingEdges.end(); i++) { - std::string id = (*i)->getID(); - if (id.substr(0, size) == edgeid) { - return *i; - } - } - return nullptr; -} - - -void -NBNode::removeEdge(NBEdge* edge, bool removeFromConnections) { - EdgeVector::iterator i = std::find(myAllEdges.begin(), myAllEdges.end(), edge); - if (i != myAllEdges.end()) { - myAllEdges.erase(i); - i = std::find(myOutgoingEdges.begin(), myOutgoingEdges.end(), edge); - if (i != myOutgoingEdges.end()) { - myOutgoingEdges.erase(i); - } else { - i = std::find(myIncomingEdges.begin(), myIncomingEdges.end(), edge); - if (i != myIncomingEdges.end()) { - myIncomingEdges.erase(i); - } else { - // edge must have been either incoming or outgoing - assert(false); - } - } - if (removeFromConnections) { - for (i = myAllEdges.begin(); i != myAllEdges.end(); ++i) { - (*i)->removeFromConnections(edge); - } - } - // invalidate controlled connections for loaded traffic light plans - const bool incoming = edge->getToNode() == this; - for (std::set::iterator i = myTrafficLights.begin(); i != myTrafficLights.end(); ++i) { - (*i)->replaceRemoved(edge, -1, nullptr, -1, incoming); - } - } -} - - -Position -NBNode::getEmptyDir() const { - Position pos(0, 0); - EdgeVector::const_iterator i; - for (i = myIncomingEdges.begin(); i != myIncomingEdges.end(); i++) { - NBNode* conn = (*i)->getFromNode(); - Position toAdd = conn->getPosition(); - toAdd.sub(myPosition); - toAdd.mul((double) 1.0 / sqrt(toAdd.x()*toAdd.x() + toAdd.y()*toAdd.y())); - pos.add(toAdd); - } - for (i = myOutgoingEdges.begin(); i != myOutgoingEdges.end(); i++) { - NBNode* conn = (*i)->getToNode(); - Position toAdd = conn->getPosition(); - toAdd.sub(myPosition); - toAdd.mul((double) 1.0 / sqrt(toAdd.x()*toAdd.x() + toAdd.y()*toAdd.y())); - pos.add(toAdd); - } - pos.mul((double) - 1.0 / (myIncomingEdges.size() + myOutgoingEdges.size())); - if (pos.x() == 0 && pos.y() == 0) { - pos = Position(1, 0); - } - pos.norm2d(); - return pos; -} - - - -void -NBNode::invalidateIncomingConnections() { - for (EdgeVector::const_iterator i = myIncomingEdges.begin(); i != myIncomingEdges.end(); i++) { - (*i)->invalidateConnections(); - } -} - - -void -NBNode::invalidateOutgoingConnections() { - for (EdgeVector::const_iterator i = myOutgoingEdges.begin(); i != myOutgoingEdges.end(); i++) { - (*i)->invalidateConnections(); - } -} - - -bool -NBNode::mustBrake(const NBEdge* const from, const NBEdge* const to, int fromLane, int toLane, bool includePedCrossings) const { - // unregulated->does not need to brake - if (myRequest == nullptr) { - return false; - } - // vehicles which do not have a following lane must always decelerate to the end - if (to == nullptr) { - return true; - } - // check whether any other connection on this node prohibits this connection - return myRequest->mustBrake(from, to, fromLane, toLane, includePedCrossings); -} - -bool -NBNode::mustBrakeForCrossing(const NBEdge* const from, const NBEdge* const to, const NBNode::Crossing& crossing) const { - return NBRequest::mustBrakeForCrossing(this, from, to, crossing); -} - - -bool -NBNode::rightTurnConflict(const NBEdge* from, const NBEdge* to, int fromLane, - const NBEdge* prohibitorFrom, const NBEdge* prohibitorTo, int prohibitorFromLane) { - if (from != prohibitorFrom) { - return false; - } - if (from->isTurningDirectionAt(to) - || prohibitorFrom->isTurningDirectionAt(prohibitorTo)) { - // XXX should warn if there are any non-turning connections left of this - return false; - } - // conflict if to is between prohibitorTo and from when going clockwise - if (to->getStartAngle() == prohibitorTo->getStartAngle()) { - // reduce rounding errors - return false; - } - const LinkDirection d1 = from->getToNode()->getDirection(from, to); - // must be a right turn to qualify as rightTurnConflict - if (d1 == LinkDirection::STRAIGHT) { - // no conflict for straight going connections - // XXX actually this should check the main direction (which could also - // be a turn) - return false; - } else { - const LinkDirection d2 = prohibitorFrom->getToNode()->getDirection(prohibitorFrom, prohibitorTo); - /* std::cout - << "from=" << from->getID() << " to=" << to->getID() << " fromLane=" << fromLane - << " pFrom=" << prohibitorFrom->getID() << " pTo=" << prohibitorTo->getID() << " pFromLane=" << prohibitorFromLane - << " d1=" << toString(d1) << " d2=" << toString(d2) - << "\n"; */ - bool flip = false; - if (d1 == LinkDirection::LEFT || d1 == LinkDirection::PARTLEFT) { - // check for leftTurnConflicht - flip = !flip; - if (d2 == LinkDirection::RIGHT || d1 == LinkDirection::PARTRIGHT) { - // assume that the left-turning bicycle goes straight at first - // and thus gets precedence over a right turning vehicle - return false; - } - } - if ((!flip && fromLane <= prohibitorFromLane) || - (flip && fromLane >= prohibitorFromLane)) { - return false; - } - const double toAngleAtNode = fmod(to->getStartAngle() + 180, (double)360.0); - const double prohibitorToAngleAtNode = fmod(prohibitorTo->getStartAngle() + 180, (double)360.0); - return (flip != (GeomHelper::getCWAngleDiff(from->getEndAngle(), toAngleAtNode) < - GeomHelper::getCWAngleDiff(from->getEndAngle(), prohibitorToAngleAtNode))); - } -} - - -bool -NBNode::turnFoes(const NBEdge* from, const NBEdge* to, int fromLane, - const NBEdge* from2, const NBEdge* to2, int fromLane2, - bool lefthand) const { - UNUSED_PARAMETER(lefthand); - if (from != from2 || to == to2 || fromLane == fromLane2) { - return false; - } - if (from->isTurningDirectionAt(to) - || from2->isTurningDirectionAt(to2)) { - // XXX should warn if there are any non-turning connections left of this - return false; - } - bool result = false; - EdgeVector::const_iterator it = std::find(myAllEdges.begin(), myAllEdges.end(), from); - if (fromLane < fromLane2) { - // conflict if 'to' comes before 'to2' going clockwise starting at 'from' - while (*it != to2) { - if (*it == to) { - result = true; - } - NBContHelper::nextCW(myAllEdges, it); - } - } else { - // conflict if 'to' comes before 'to2' going counter-clockwise starting at 'from' - while (*it != to2) { - if (*it == to) { - result = true; - } - NBContHelper::nextCCW(myAllEdges, it); - } - } - /* - if (result) { - std::cout << "turnFoes node=" << getID() - << " from=" << from->getLaneID(fromLane) - << " to=" << to->getID() - << " from2=" << from2->getLaneID(fromLane2) - << " to2=" << to2->getID() - << "\n"; - } - */ - return result; -} - - -bool -NBNode::isLeftMover(const NBEdge* const from, const NBEdge* const to) const { - // when the junction has only one incoming edge, there are no - // problems caused by left blockings - if (myIncomingEdges.size() == 1 || myOutgoingEdges.size() == 1) { - return false; - } - double fromAngle = from->getAngleAtNode(this); - double toAngle = to->getAngleAtNode(this); - double cw = GeomHelper::getCWAngleDiff(fromAngle, toAngle); - double ccw = GeomHelper::getCCWAngleDiff(fromAngle, toAngle); - std::vector::const_iterator i = std::find(myAllEdges.begin(), myAllEdges.end(), from); - do { - NBContHelper::nextCW(myAllEdges, i); - } while ((!hasOutgoing(*i) || from->isTurningDirectionAt(*i)) && *i != from); - return cw < ccw && (*i) == to && myOutgoingEdges.size() > 2; -} - - -bool -NBNode::forbids(const NBEdge* const possProhibitorFrom, const NBEdge* const possProhibitorTo, - const NBEdge* const possProhibitedFrom, const NBEdge* const possProhibitedTo, - bool regardNonSignalisedLowerPriority) const { - return myRequest != nullptr && myRequest->forbids(possProhibitorFrom, possProhibitorTo, - possProhibitedFrom, possProhibitedTo, - regardNonSignalisedLowerPriority); -} - - -bool -NBNode::foes(const NBEdge* const from1, const NBEdge* const to1, - const NBEdge* const from2, const NBEdge* const to2) const { - return myRequest != nullptr && myRequest->foes(from1, to1, from2, to2); -} - - -void -NBNode::remapRemoved(NBTrafficLightLogicCont& tc, - NBEdge* removed, const EdgeVector& incoming, - const EdgeVector& outgoing) { - assert(find(incoming.begin(), incoming.end(), removed) == incoming.end()); - bool changed = true; - while (changed) { - changed = false; - NBConnectionProhibits blockedConnectionsTmp = myBlockedConnections; - NBConnectionProhibits blockedConnectionsNew; - // remap in connections - for (NBConnectionProhibits::iterator i = blockedConnectionsTmp.begin(); i != blockedConnectionsTmp.end(); i++) { - const NBConnection& blocker = (*i).first; - const NBConnectionVector& blocked = (*i).second; - // check the blocked connections first - // check whether any of the blocked must be changed - bool blockedChanged = false; - NBConnectionVector newBlocked; - NBConnectionVector::const_iterator j; - for (j = blocked.begin(); j != blocked.end(); j++) { - const NBConnection& sblocked = *j; - if (sblocked.getFrom() == removed || sblocked.getTo() == removed) { - blockedChanged = true; - } - } - // adapt changes if so - for (j = blocked.begin(); blockedChanged && j != blocked.end(); j++) { - const NBConnection& sblocked = *j; - if (sblocked.getFrom() == removed && sblocked.getTo() == removed) { - /* for(EdgeVector::const_iterator k=incoming.begin(); k!=incoming.end(); k++) { - !!! newBlocked.push_back(NBConnection(*k, *k)); - }*/ - } else if (sblocked.getFrom() == removed) { - assert(sblocked.getTo() != removed); - for (EdgeVector::const_iterator k = incoming.begin(); k != incoming.end(); k++) { - newBlocked.push_back(NBConnection(*k, sblocked.getTo())); - } - } else if (sblocked.getTo() == removed) { - assert(sblocked.getFrom() != removed); - for (EdgeVector::const_iterator k = outgoing.begin(); k != outgoing.end(); k++) { - newBlocked.push_back(NBConnection(sblocked.getFrom(), *k)); - } - } else { - newBlocked.push_back(NBConnection(sblocked.getFrom(), sblocked.getTo())); - } - } - if (blockedChanged) { - blockedConnectionsNew[blocker] = newBlocked; - changed = true; - } - // if the blocked were kept - else { - if (blocker.getFrom() == removed && blocker.getTo() == removed) { - changed = true; - /* for(EdgeVector::const_iterator k=incoming.begin(); k!=incoming.end(); k++) { - !!! blockedConnectionsNew[NBConnection(*k, *k)] = blocked; - }*/ - } else if (blocker.getFrom() == removed) { - assert(blocker.getTo() != removed); - changed = true; - for (EdgeVector::const_iterator k = incoming.begin(); k != incoming.end(); k++) { - blockedConnectionsNew[NBConnection(*k, blocker.getTo())] = blocked; - } - } else if (blocker.getTo() == removed) { - assert(blocker.getFrom() != removed); - changed = true; - for (EdgeVector::const_iterator k = outgoing.begin(); k != outgoing.end(); k++) { - blockedConnectionsNew[NBConnection(blocker.getFrom(), *k)] = blocked; - } - } else { - blockedConnectionsNew[blocker] = blocked; - } - } - } - myBlockedConnections = blockedConnectionsNew; - } - // remap in traffic lights - tc.remapRemoved(removed, incoming, outgoing); -} - - -NBEdge* -NBNode::getNextCompatibleOutgoing(const NBEdge* incoming, SVCPermissions vehPerm, EdgeVector::const_iterator itOut, bool clockwise) const { - EdgeVector::const_iterator i = itOut; - while (*i != incoming) { - if (clockwise) { - NBContHelper::nextCW(myAllEdges, i); - } else { - NBContHelper::nextCCW(myAllEdges, i); - } - if ((*i)->getFromNode() != this) { - // only look for outgoing edges - // @note we use myAllEdges to stop at the incoming edge - continue; - } - if (incoming->isTurningDirectionAt(*i)) { - return nullptr; - } - if ((vehPerm & (*i)->getPermissions()) != 0 || vehPerm == 0) { - return *i; - } - } - return nullptr; -} - - -LinkDirection -NBNode::getDirection(const NBEdge* const incoming, const NBEdge* const outgoing, bool leftHand) const { - // ok, no connection at all -> dead end - if (outgoing == nullptr) { - return LinkDirection::NODIR; - } - if (incoming->getJunctionPriority(this) == NBEdge::JunctionPriority::ROUNDABOUT && outgoing->getJunctionPriority(this) == NBEdge::JunctionPriority::ROUNDABOUT) { - return LinkDirection::STRAIGHT; - } - // turning direction - if (incoming->isTurningDirectionAt(outgoing)) { - return leftHand ? LinkDirection::TURN_LEFTHAND : LinkDirection::TURN; - } - // get the angle between incoming/outgoing at the junction - const double angle = NBHelpers::normRelAngle(incoming->getAngleAtNode(this), outgoing->getAngleAtNode(this)); - // ok, should be a straight connection - EdgeVector::const_iterator itOut = std::find(myAllEdges.begin(), myAllEdges.end(), outgoing); - SVCPermissions vehPerm = incoming->getPermissions() & outgoing->getPermissions(); - if (vehPerm != SVC_PEDESTRIAN) { - vehPerm &= ~SVC_PEDESTRIAN; - } - if (abs((int) angle) + 1 < 45) { - // check whether there is a straighter edge - NBEdge* outCW = getNextCompatibleOutgoing(incoming, vehPerm, itOut, true); - if (outCW != nullptr) { - const double angle2 = NBHelpers::normRelAngle(incoming->getAngleAtNode(this), outCW->getAngleAtNode(this)); - if (fabs(angle2) < fabs(angle)) { - if (fabs(angle2 - angle) > 5) { - if (angle2 > angle) { - return LinkDirection::PARTLEFT; - } else { - return LinkDirection::PARTRIGHT; - } - } - } - } - NBEdge* outCCW = getNextCompatibleOutgoing(incoming, vehPerm, itOut, false); - if (outCCW != nullptr) { - const double angle2 = NBHelpers::normRelAngle(incoming->getAngleAtNode(this), outCCW->getAngleAtNode(this)); - if (fabs(angle2) < fabs(angle)) { - if (fabs(angle2 - angle) > 5) { - if (angle2 > angle) { - return LinkDirection::PARTLEFT; - } else { - return LinkDirection::PARTRIGHT; - } - } - } - } - return LinkDirection::STRAIGHT; - } - - if (angle > 0) { - // check whether any other edge goes further to the right - if (angle > 90) { - return LinkDirection::RIGHT; - } - NBEdge* outCW = getNextCompatibleOutgoing(incoming, vehPerm, itOut, !leftHand); - if (outCW != nullptr) { - return LinkDirection::PARTRIGHT; - } else { - return LinkDirection::RIGHT; - } - } else { - // check whether any other edge goes further to the left - if (angle < -90) { - return LinkDirection::LEFT; - } - NBEdge* outCCW = getNextCompatibleOutgoing(incoming, vehPerm, itOut, leftHand); - if (outCCW != nullptr) { - return LinkDirection::PARTLEFT; - } else { - return LinkDirection::LEFT; - } - } -} - - -LinkState -NBNode::getLinkState(const NBEdge* incoming, NBEdge* outgoing, int fromlane, int toLane, - bool mayDefinitelyPass, const std::string& tlID) const { - if (myType == SumoXMLNodeType::RAIL_CROSSING && isRailway(incoming->getPermissions())) { - return LINKSTATE_MAJOR; // the trains must run on time - } - if (tlID != "") { - return mustBrake(incoming, outgoing, fromlane, toLane, true) ? LINKSTATE_TL_OFF_BLINKING : LINKSTATE_TL_OFF_NOSIGNAL; - } - if (outgoing == nullptr) { // always off - return LINKSTATE_TL_OFF_NOSIGNAL; - } - if (myType == SumoXMLNodeType::RIGHT_BEFORE_LEFT) { - return LINKSTATE_EQUAL; // all the same - } - if (myType == SumoXMLNodeType::ALLWAY_STOP) { - return LINKSTATE_ALLWAY_STOP; // all drive, first one to arrive may drive first - } - if (myType == SumoXMLNodeType::ZIPPER && mustBrake(incoming, outgoing, fromlane, toLane, false)) { - return LINKSTATE_ZIPPER; - } - if (!mayDefinitelyPass - && mustBrake(incoming, outgoing, fromlane, toLane, true) - // legacy mode - && (!incoming->isInsideTLS() || getDirection(incoming, outgoing) != LinkDirection::STRAIGHT) - // avoid linkstate minor at pure railway nodes - && !NBNodeTypeComputer::isRailwayNode(this)) { - return myType == SumoXMLNodeType::PRIORITY_STOP ? LINKSTATE_STOP : LINKSTATE_MINOR; // minor road - } - // traffic lights are not regarded here - return LINKSTATE_MAJOR; -} - -bool -NBNode::checkIsRemovable() const { - std::string reason; - return checkIsRemovableReporting(reason); -} - -bool -NBNode::checkIsRemovableReporting(std::string& reason) const { - // check whether this node is included in a traffic light or crossing - if (myTrafficLights.size() != 0) { - reason = "TLS"; - return false; - } - if (myType == SumoXMLNodeType::RAIL_SIGNAL) { - reason = "rail_signal"; - return false; - } - if (myCrossings.size() != 0) { - reason = "crossing"; - return false; - } - EdgeVector::const_iterator i; - // one in, one out -> just a geometry ... - if (myOutgoingEdges.size() == 1 && myIncomingEdges.size() == 1) { - // ... if types match ... - if (!myIncomingEdges[0]->expandableBy(myOutgoingEdges[0], reason)) { - reason = "edges incompatible: " + reason; - return false; - } - if (myIncomingEdges[0]->getTurnDestination(true) == myOutgoingEdges[0]) { - reason = "turnaround"; - return false; - } - return true; - } - // two in, two out -> may be something else - if (myOutgoingEdges.size() == 2 && myIncomingEdges.size() == 2) { - // check whether the origin nodes of the incoming edges differ - std::set origSet; - for (i = myIncomingEdges.begin(); i != myIncomingEdges.end(); i++) { - origSet.insert((*i)->getFromNode()); - } - if (origSet.size() < 2) { - return false; - } - // check whether this node is an intermediate node of - // a two-directional street - for (i = myIncomingEdges.begin(); i != myIncomingEdges.end(); i++) { - // each of the edges must have an opposite direction edge - NBEdge* opposite = (*i)->getTurnDestination(true); - if (opposite != nullptr) { - // the other outgoing edges must be the continuation of the current - NBEdge* continuation = opposite == myOutgoingEdges.front() ? myOutgoingEdges.back() : myOutgoingEdges.front(); - // check whether the types allow joining - if (!(*i)->expandableBy(continuation, reason)) { - reason = "edges incompatible: " + reason; - return false; - } - } else { - // ok, at least one outgoing edge is not an opposite - // of an incoming one - reason = "not opposites"; - return false; - } - } - return true; - } - // ok, a real node - reason = "intersection"; - return false; -} - - -std::vector > -NBNode::getEdgesToJoin() const { - assert(checkIsRemovable()); - std::vector > ret; - // one in, one out-case - if (myOutgoingEdges.size() == 1 && myIncomingEdges.size() == 1) { - ret.push_back( - std::pair( - myIncomingEdges[0], myOutgoingEdges[0])); - return ret; - } - // two in, two out-case - for (EdgeVector::const_iterator i = myIncomingEdges.begin(); i != myIncomingEdges.end(); i++) { - // join with the edge that is not a turning direction - NBEdge* opposite = (*i)->getTurnDestination(true); - assert(opposite != 0); - NBEdge* continuation = opposite == myOutgoingEdges.front() ? myOutgoingEdges.back() : myOutgoingEdges.front(); - ret.push_back(std::pair(*i, continuation)); - } - return ret; -} - - -const PositionVector& -NBNode::getShape() const { - return myPoly; -} - - -void -NBNode::setCustomShape(const PositionVector& shape) { - myPoly = shape; - myHaveCustomPoly = (myPoly.size() > 1); - if (myHaveCustomPoly) { - for (EdgeVector::iterator i = myAllEdges.begin(); i != myAllEdges.end(); i++) { - (*i)->resetNodeBorder(this); - } - } -} - - -NBEdge* -NBNode::getConnectionTo(NBNode* n) const { - for (NBEdge* e : myOutgoingEdges) { - if (e->getToNode() == n && e->getPermissions() != 0) { - return e; - } - } - return nullptr; -} - - -bool -NBNode::isNearDistrict() const { - if (isDistrict()) { - return false; - } - for (const NBEdge* const t : getEdges()) { - const NBNode* const other = t->getToNode() == this ? t->getFromNode() : t->getToNode(); - for (const NBEdge* const k : other->getEdges()) { - if (k->getFromNode()->isDistrict() || k->getToNode()->isDistrict()) { - return true; - } - } - } - return false; -} - - -bool -NBNode::isDistrict() const { - return myType == SumoXMLNodeType::DISTRICT; -} - - -int -NBNode::guessCrossings() { -#ifdef DEBUG_PED_STRUCTURES - gDebugFlag1 = DEBUGCOND; -#endif - int numGuessed = 0; - if (myCrossings.size() > 0 || myDiscardAllCrossings) { - // user supplied crossings, do not guess - return numGuessed; - } - if (gDebugFlag1) { - std::cout << "guess crossings for " << getID() << "\n"; - } - EdgeVector allEdges = getEdgesSortedByAngleAtNodeCenter(); - // check for pedestrial lanes going clockwise around the node - std::vector > normalizedLanes; - for (EdgeVector::const_iterator it = allEdges.begin(); it != allEdges.end(); ++it) { - NBEdge* edge = *it; - const std::vector& lanes = edge->getLanes(); - if (edge->getFromNode() == this) { - for (std::vector::const_reverse_iterator it_l = lanes.rbegin(); it_l != lanes.rend(); ++it_l) { - normalizedLanes.push_back(std::make_pair(edge, ((*it_l).permissions & SVC_PEDESTRIAN) != 0)); - } - } else { - for (std::vector::const_iterator it_l = lanes.begin(); it_l != lanes.end(); ++it_l) { - normalizedLanes.push_back(std::make_pair(edge, ((*it_l).permissions & SVC_PEDESTRIAN) != 0)); - } - } - } - // do we even have a pedestrian lane? - int firstSidewalk = -1; - for (int i = 0; i < (int)normalizedLanes.size(); ++i) { - if (normalizedLanes[i].second) { - firstSidewalk = i; - break; - } - } - int hadCandidates = 0; - std::vector connectedCandidates; // number of crossings that were built for each connected candidate - if (firstSidewalk != -1) { - // rotate lanes to ensure that the first one allows pedestrians - std::vector > tmp; - copy(normalizedLanes.begin() + firstSidewalk, normalizedLanes.end(), std::back_inserter(tmp)); - copy(normalizedLanes.begin(), normalizedLanes.begin() + firstSidewalk, std::back_inserter(tmp)); - normalizedLanes = tmp; - // find candidates - EdgeVector candidates; - for (int i = 0; i < (int)normalizedLanes.size(); ++i) { - NBEdge* edge = normalizedLanes[i].first; - const bool allowsPed = normalizedLanes[i].second; - if (gDebugFlag1) { - std::cout << " cands=" << toString(candidates) << " edge=" << edge->getID() << " allowsPed=" << allowsPed << "\n"; - } - if (!allowsPed && (candidates.size() == 0 || candidates.back() != edge)) { - candidates.push_back(edge); - } else if (allowsPed) { - if (candidates.size() > 0) { - if (hadCandidates > 0 || forbidsPedestriansAfter(normalizedLanes, i)) { - hadCandidates++; - const int n = checkCrossing(candidates); - numGuessed += n; - if (n > 0) { - connectedCandidates.push_back(n); - } - } - candidates.clear(); - } - } - } - if (hadCandidates > 0 && candidates.size() > 0) { - // avoid wrapping around to the same sidewalk - hadCandidates++; - const int n = checkCrossing(candidates); - numGuessed += n; - if (n > 0) { - connectedCandidates.push_back(n); - } - } - } - // Avoid duplicate crossing between the same pair of walkingareas - if (gDebugFlag1) { - std::cout << " hadCandidates=" << hadCandidates << " connectedCandidates=" << toString(connectedCandidates) << "\n"; - } - if (hadCandidates == 2 && connectedCandidates.size() == 2) { - // One or both of them might be split: remove the one with less splits - if (connectedCandidates.back() <= connectedCandidates.front()) { - numGuessed -= connectedCandidates.back(); - myCrossings.erase(myCrossings.end() - connectedCandidates.back(), myCrossings.end()); - } else { - numGuessed -= connectedCandidates.front(); - myCrossings.erase(myCrossings.begin(), myCrossings.begin() + connectedCandidates.front()); - } - } - std::sort(myCrossings.begin(), myCrossings.end(), NBNodesEdgesSorter::crossing_by_junction_angle_sorter(this, myAllEdges)); - if (gDebugFlag1) { - std::cout << "guessedCrossings:\n"; - for (auto& crossing : myCrossings) { - std::cout << " edges=" << toString(crossing->edges) << "\n"; - } - } - return numGuessed; -} - - -int -NBNode::checkCrossing(EdgeVector candidates) { - if (gDebugFlag1) { - std::cout << "checkCrossing candidates=" << toString(candidates) << "\n"; - } - if (candidates.size() == 0) { - if (gDebugFlag1) { - std::cout << "no crossing added (numCandidates=" << candidates.size() << ")\n"; - } - return 0; - } else { - // check whether the edges may be part of a common crossing due to having similar angle - double prevAngle = -100000; // dummy - for (int i = 0; i < (int)candidates.size(); ++i) { - NBEdge* edge = candidates[i]; - double angle = edge->getCrossingAngle(this); - // edges should be sorted by angle but this only holds true approximately - if (i > 0 && fabs(NBHelpers::relAngle(angle, prevAngle)) > EXTEND_CROSSING_ANGLE_THRESHOLD) { - if (gDebugFlag1) { - std::cout << "no crossing added (found angle difference of " << fabs(NBHelpers::relAngle(angle, prevAngle)) << " at i=" << i << "\n"; - } - return 0; - } - if (!isTLControlled() && myType != SumoXMLNodeType::RAIL_CROSSING && edge->getSpeed() > OptionsCont::getOptions().getFloat("crossings.guess.speed-threshold")) { - if (gDebugFlag1) { - std::cout << "no crossing added (uncontrolled, edge with speed > " << edge->getSpeed() << ")\n"; - } - return 0; - } - prevAngle = angle; - } - if (candidates.size() == 1 || getType() == SumoXMLNodeType::RAIL_CROSSING) { - addCrossing(candidates, NBEdge::UNSPECIFIED_WIDTH, isTLControlled()); - if (gDebugFlag1) { - std::cout << "adding crossing: " << toString(candidates) << "\n"; - } - return 1; - } else { - // check for intermediate walking areas - double prevAngle = -100000; // dummy - for (EdgeVector::iterator it = candidates.begin(); it != candidates.end(); ++it) { - double angle = (*it)->getCrossingAngle(this); - if (it != candidates.begin()) { - NBEdge* prev = *(it - 1); - NBEdge* curr = *it; - Position prevPos, currPos; - int laneI; - // compute distance between candiate edges - double intermediateWidth = 0; - if (prev->getToNode() == this) { - laneI = prev->getNumLanes() - 1; - prevPos = prev->getLanes()[laneI].shape[-1]; - } else { - laneI = 0; - prevPos = prev->getLanes()[laneI].shape[0]; - } - intermediateWidth -= 0.5 * prev->getLaneWidth(laneI); - if (curr->getFromNode() == this) { - laneI = curr->getNumLanes() - 1; - currPos = curr->getLanes()[laneI].shape[0]; - } else { - laneI = 0; - currPos = curr->getLanes()[laneI].shape[-1]; - } - intermediateWidth -= 0.5 * curr->getLaneWidth(laneI); - intermediateWidth += currPos.distanceTo2D(prevPos); - if (gDebugFlag1) { - std::cout - << " prevAngle=" << prevAngle - << " angle=" << angle - << " intermediateWidth=" << intermediateWidth - << "\n"; - } - if (fabs(NBHelpers::relAngle(prevAngle, angle)) > SPLIT_CROSSING_ANGLE_THRESHOLD - || (intermediateWidth > SPLIT_CROSSING_WIDTH_THRESHOLD)) { - return checkCrossing(EdgeVector(candidates.begin(), it)) - + checkCrossing(EdgeVector(it, candidates.end())); - } - } - prevAngle = angle; - } - addCrossing(candidates, NBEdge::UNSPECIFIED_WIDTH, isTLControlled()); - if (gDebugFlag1) { - std::cout << "adding crossing: " << toString(candidates) << "\n"; - } - return 1; - } - } -} - - -bool -NBNode::checkCrossingDuplicated(EdgeVector edges) { - // sort edge vector - std::sort(edges.begin(), edges.end()); - // iterate over crossing to find a crossing with the same edges - for (auto& crossing : myCrossings) { - // sort edges of crossing before compare - EdgeVector edgesOfCrossing = crossing->edges; - std::sort(edgesOfCrossing.begin(), edgesOfCrossing.end()); - if (edgesOfCrossing == edges) { - return true; - } - } - return false; -} - - -bool -NBNode::forbidsPedestriansAfter(std::vector > normalizedLanes, int startIndex) { - for (int i = startIndex; i < (int)normalizedLanes.size(); ++i) { - if (!normalizedLanes[i].second) { - return true; - } - } - return false; -} - - -void -NBNode::buildCrossingsAndWalkingAreas() { - buildCrossings(); - buildWalkingAreas(OptionsCont::getOptions().getInt("junctions.corner-detail")); - // ensure that all crossings are properly connected - for (auto& crossing : myCrossings) { - if (crossing->prevWalkingArea == "" || crossing->nextWalkingArea == "" || !crossing->valid) { - if (crossing->valid) { - WRITE_WARNINGF("Discarding invalid crossing '%' at junction '%' with edges [%] (no walkingarea found).", - crossing->id, getID(), toString(crossing->edges)); - } - for (WalkingArea& wa : myWalkingAreas) { - std::vector::iterator it_nc = std::find(wa.nextCrossings.begin(), wa.nextCrossings.end(), crossing->id); - if (it_nc != wa.nextCrossings.end()) { - wa.nextCrossings.erase(it_nc); - } - } - crossing->valid = false; - crossing->prevWalkingArea = ""; - crossing->nextWalkingArea = ""; - } - } -} - -std::vector -NBNode::getCrossings() const { - std::vector result; - for (auto& c : myCrossings) { - if (c->valid) { - result.push_back(c.get()); - } - } - //if (myCrossings.size() > 0) { - // std::cout << "valid crossings at " << getID() << "\n"; - // for (std::vector::const_iterator it = result.begin(); it != result.end(); ++it) { - // std::cout << " " << toString((*it)->edges) << "\n"; - // } - //} - return result; -} - - -void -NBNode::discardAllCrossings(bool rejectAll) { - myCrossings.clear(); - // also discard all further crossings - if (rejectAll) { - myDiscardAllCrossings = true; - } -} - - -void -NBNode::discardWalkingareas() { - myWalkingAreas.clear(); -} - - -void -NBNode::buildInnerEdges() { - // myDisplacementError is computed during this operation. reset first - myDisplacementError = 0; - // build inner edges for vehicle movements across the junction - int noInternalNoSplits = 0; - for (EdgeVector::const_iterator i = myIncomingEdges.begin(); i != myIncomingEdges.end(); i++) { - const std::vector& elv = (*i)->getConnections(); - for (std::vector::const_iterator k = elv.begin(); k != elv.end(); ++k) { - if ((*k).toEdge == nullptr) { - continue; - } - noInternalNoSplits++; - } - } - int lno = 0; - int splitNo = 0; - for (EdgeVector::const_iterator i = myIncomingEdges.begin(); i != myIncomingEdges.end(); i++) { - (*i)->buildInnerEdges(*this, noInternalNoSplits, lno, splitNo); - } -} - - -int -NBNode::buildCrossings() { -#ifdef DEBUG_PED_STRUCTURES - gDebugFlag1 = DEBUGCOND; -#endif - if (gDebugFlag1) { - std::cout << "build crossings for " << getID() << ":\n"; - } - if (myDiscardAllCrossings) { - myCrossings.clear(); - } - int index = 0; - const double defaultWidth = OptionsCont::getOptions().getFloat("default.crossing-width"); - for (auto& c : myCrossings) { - c->valid = true; - if (!isTLControlled()) { - c->tlID = ""; // reset for Netedit, set via setCrossingTLIndices() - } - c->id = ":" + getID() + "_c" + toString(index++); - c->width = (c->customWidth == NBEdge::UNSPECIFIED_WIDTH) ? defaultWidth : c->customWidth; - // reset fields, so repeated computation (Netedit) will sucessfully perform the checks - // in buildWalkingAreas (split crossings) and buildInnerEdges (sanity check) - c->nextWalkingArea = ""; - c->prevWalkingArea = ""; - EdgeVector& edges = c->edges; - if (gDebugFlag1) { - std::cout << " crossing=" << c->id << " edges=" << toString(edges); - } - // sorting the edges in the right way is imperative. We want to sort - // them by getAngleAtNodeToCenter() but need to be extra carefull to avoid wrapping around 0 somewhere in between - std::sort(edges.begin(), edges.end(), NBContHelper::edge_by_angle_to_nodeShapeCentroid_sorter(this)); - if (gDebugFlag1) { - std::cout << " sortedEdges=" << toString(edges) << "\n"; - }; - // rotate the edges so that the largest relative angle difference comes at the end - double maxAngleDiff = 0; - int maxAngleDiffIndex = 0; // index before maxDist - for (int i = 0; i < (int) edges.size(); i++) { - double diff = NBHelpers::relAngle(edges[i]->getAngleAtNodeToCenter(this), - edges[(i + 1) % edges.size()]->getAngleAtNodeToCenter(this)); - if (diff < 0) { - diff += 360; - } - if (gDebugFlag1) { - std::cout << " i=" << i << " a1=" << edges[i]->getAngleAtNodeToCenter(this) << " a2=" << edges[(i + 1) % edges.size()]->getAngleAtNodeToCenter(this) << " diff=" << diff << "\n"; - } - if (diff > maxAngleDiff) { - maxAngleDiff = diff; - maxAngleDiffIndex = i; - } - } - if (maxAngleDiff > 2 && maxAngleDiff < 360 - 2) { - // if the angle differences is too small, we better not rotate - std::rotate(edges.begin(), edges.begin() + (maxAngleDiffIndex + 1) % edges.size(), edges.end()); - if (gDebugFlag1) { - std::cout << " rotatedEdges=" << toString(edges); - } - } - // reverse to get them in CCW order (walking direction around the node) - std::reverse(edges.begin(), edges.end()); - if (gDebugFlag1) { - std::cout << " finalEdges=" << toString(edges) << "\n"; - } - // compute shape - c->shape.clear(); - const int begDir = (edges.front()->getFromNode() == this ? FORWARD : BACKWARD); - const int endDir = (edges.back()->getToNode() == this ? FORWARD : BACKWARD); - if (edges.front()->getFirstNonPedestrianLaneIndex(begDir) < 0 - || edges.back()->getFirstNonPedestrianLaneIndex(endDir) < 0) { - // invalid crossing - WRITE_WARNINGF("Discarding invalid crossing '%' at junction '%' with edges [%] (no vehicle lanes to cross).", c->id, getID(), toString(c->edges)); - c->valid = false; - } else if (c->customShape.size() != 0) { - c->shape = c->customShape; - } else { - NBEdge::Lane crossingBeg = edges.front()->getFirstNonPedestrianLane(begDir); - NBEdge::Lane crossingEnd = edges.back()->getFirstNonPedestrianLane(endDir); - crossingBeg.width = (crossingBeg.width == NBEdge::UNSPECIFIED_WIDTH ? SUMO_const_laneWidth : crossingBeg.width); - crossingEnd.width = (crossingEnd.width == NBEdge::UNSPECIFIED_WIDTH ? SUMO_const_laneWidth : crossingEnd.width); - crossingBeg.shape.move2side(begDir * crossingBeg.width / 2); - crossingEnd.shape.move2side(endDir * crossingEnd.width / 2); - crossingBeg.shape.extrapolate(c->width / 2); - crossingEnd.shape.extrapolate(c->width / 2); - // check if after all changes shape are NAN (in these case, discard) - if (crossingBeg.shape.isNAN() || crossingEnd.shape.isNAN()) { - WRITE_WARNINGF("Discarding invalid crossing '%' at junction '%' with edges [%] (invalid shape).", c->id, getID(), toString(c->edges)); - c->valid = false; - } else { - c->shape.push_back(crossingBeg.shape[begDir == FORWARD ? 0 : -1]); - c->shape.push_back(crossingEnd.shape[endDir == FORWARD ? -1 : 0]); - } - } - } - return index; -} - - -void -NBNode::buildWalkingAreas(int cornerDetail) { -#ifdef DEBUG_PED_STRUCTURES - gDebugFlag1 = DEBUGCOND; -#endif - int index = 0; - myWalkingAreas.clear(); - if (gDebugFlag1) { - std::cout << "build walkingAreas for " << getID() << ":\n"; - } - if (myAllEdges.size() == 0) { - return; - } - EdgeVector allEdges = getEdgesSortedByAngleAtNodeCenter(); - // shapes are all pointing away from the intersection - std::vector > normalizedLanes; - for (EdgeVector::const_iterator it = allEdges.begin(); it != allEdges.end(); ++it) { - NBEdge* edge = *it; - const std::vector& lanes = edge->getLanes(); - if (edge->getFromNode() == this) { - for (std::vector::const_reverse_iterator it_l = lanes.rbegin(); it_l != lanes.rend(); ++it_l) { - NBEdge::Lane l = *it_l; - l.shape = l.shape.getSubpartByIndex(0, 2); - l.width = (l.width == NBEdge::UNSPECIFIED_WIDTH ? SUMO_const_laneWidth : l.width); - normalizedLanes.push_back(std::make_pair(edge, l)); - } - } else { - for (std::vector::const_iterator it_l = lanes.begin(); it_l != lanes.end(); ++it_l) { - NBEdge::Lane l = *it_l; - l.shape = l.shape.reverse(); - l.shape = l.shape.getSubpartByIndex(0, 2); - l.width = (l.width == NBEdge::UNSPECIFIED_WIDTH ? SUMO_const_laneWidth : l.width); - normalizedLanes.push_back(std::make_pair(edge, l)); - } - } - } - //if (gDebugFlag1) std::cout << " normalizedLanes=" << normalizedLanes.size() << "\n"; - // collect [start,count[ indices in normalizedLanes that belong to a walkingArea - std::vector > waIndices; - int start = -1; - NBEdge* prevEdge = normalizedLanes.back().first; - for (int i = 0; i < (int)normalizedLanes.size(); ++i) { - NBEdge* edge = normalizedLanes[i].first; - NBEdge::Lane& l = normalizedLanes[i].second; - if (start == -1) { - if ((l.permissions & SVC_PEDESTRIAN) != 0) { - start = i; - } - } else { - if ((l.permissions & SVC_PEDESTRIAN) == 0 || crossingBetween(edge, prevEdge)) { - waIndices.push_back(std::make_pair(start, i - start)); - if ((l.permissions & SVC_PEDESTRIAN) != 0) { - start = i; - } else { - start = -1; - } - - } - } - if (gDebugFlag1) std::cout << " i=" << i << " edge=" << edge->getID() << " start=" << start << " ped=" << ((l.permissions & SVC_PEDESTRIAN) != 0) - << " waI=" << waIndices.size() << " crossingBetween=" << crossingBetween(edge, prevEdge) << "\n"; - prevEdge = edge; - } - // deal with wrap-around issues - if (start != - 1) { - const int waNumLanes = (int)normalizedLanes.size() - start; - if (waIndices.size() == 0) { - waIndices.push_back(std::make_pair(start, waNumLanes)); - if (gDebugFlag1) { - std::cout << " single wa, end at wrap-around\n"; - } - } else { - if (waIndices.front().first == 0) { - NBEdge* edge = normalizedLanes.front().first; - NBEdge* prevEdge = normalizedLanes.back().first; - if (crossingBetween(edge, prevEdge)) { - // do not wrap-around if there is a crossing in between - waIndices.push_back(std::make_pair(start, waNumLanes)); - if (gDebugFlag1) { - std::cout << " do not wrap around, turn-around in between\n"; - } - } else { - // first walkingArea wraps around - waIndices.front().first = start; - waIndices.front().second = waNumLanes + waIndices.front().second; - if (gDebugFlag1) { - std::cout << " wrapping around\n"; - } - } - } else { - // last walkingArea ends at the wrap-around - waIndices.push_back(std::make_pair(start, waNumLanes)); - if (gDebugFlag1) { - std::cout << " end at wrap-around\n"; - } - } - } - } - if (gDebugFlag1) { - std::cout << " normalizedLanes=" << normalizedLanes.size() << " waIndices:\n"; - for (int i = 0; i < (int)waIndices.size(); ++i) { - std::cout << " " << waIndices[i].first << ", " << waIndices[i].second << "\n"; - } - } - // build walking areas connected to a sidewalk - for (int i = 0; i < (int)waIndices.size(); ++i) { - const bool buildExtensions = waIndices[i].second != (int)normalizedLanes.size(); - const int start = waIndices[i].first; - const int prev = start > 0 ? start - 1 : (int)normalizedLanes.size() - 1; - const int count = waIndices[i].second; - const int end = (start + count) % normalizedLanes.size(); - - WalkingArea wa(":" + getID() + "_w" + toString(index++), 1); - if (gDebugFlag1) { - std::cout << "build walkingArea " << wa.id << " start=" << start << " end=" << end << " count=" << count << " prev=" << prev << ":\n"; - } - double endCrossingWidth = 0; - double startCrossingWidth = 0; - PositionVector endCrossingShape; - PositionVector startCrossingShape; - // check for connected crossings - bool connectsCrossing = false; - std::vector connectedPoints; - for (auto c : getCrossings()) { - if (gDebugFlag1) { - std::cout << " crossing=" << c->id << " sortedEdges=" << toString(c->edges) << "\n"; - } - if (c->edges.back() == normalizedLanes[end].first - && (normalizedLanes[end].second.permissions & SVC_PEDESTRIAN) == 0) { - // crossing ends - if (c->nextWalkingArea != "") { - WRITE_WARNINGF("Invalid pedestrian topology at junction '%'; crossing '%' targets '%' and '%'.", - getID(), c->id, c->nextWalkingArea, wa.id); - c->valid = false; - } - c->nextWalkingArea = wa.id; - if ((int)c->edges.size() < wa.minPrevCrossingEdges) { - // if there are multiple crossings, use the shape of the one that crosses fewer edges - endCrossingWidth = c->width; - endCrossingShape = c->shape; - wa.width = MAX2(wa.width, endCrossingWidth); - connectsCrossing = true; - connectedPoints.push_back(c->shape[-1]); - wa.minPrevCrossingEdges = (int)c->edges.size(); - } - if (gDebugFlag1) { - std::cout << " crossing " << c->id << " ends\n"; - } - } - if (c->edges.front() == normalizedLanes[prev].first - && (normalizedLanes[prev].second.permissions & SVC_PEDESTRIAN) == 0) { - // crossing starts - if (c->prevWalkingArea != "") { - WRITE_WARNINGF("Invalid pedestrian topology at junction '%'; crossing '%' is targeted by '%' and '%'.", - getID(), c->id, c->prevWalkingArea, wa.id); - c->valid = false; - } - c->prevWalkingArea = wa.id; - wa.nextCrossings.push_back(c->id); - if ((int)c->edges.size() < wa.minNextCrossingEdges) { - // if there are multiple crossings, use the shape of the one that crosses fewer edges - startCrossingWidth = c->width; - startCrossingShape = c->shape; - wa.width = MAX2(wa.width, startCrossingWidth); - connectsCrossing = true; - connectedPoints.push_back(c->shape[0]); - wa.minNextCrossingEdges = (int)c->edges.size(); - } - if (gDebugFlag1) { - std::cout << " crossing " << c->id << " starts\n"; - } - } - if (gDebugFlag1) std::cout << " check connections to crossing " << c->id - << " cFront=" << c->edges.front()->getID() << " cBack=" << c->edges.back()->getID() - << " wEnd=" << normalizedLanes[end].first->getID() << " wStart=" << normalizedLanes[start].first->getID() - << " wStartPrev=" << normalizedLanes[prev].first->getID() - << "\n"; - } - if (count < 2 && !connectsCrossing) { - // not relevant for walking - if (gDebugFlag1) { - std::cout << " not relevant for walking: count=" << count << " connectsCrossing=" << connectsCrossing << "\n"; - } - continue; - } - // build shape and connections - std::set connected; - for (int j = 0; j < count; ++j) { - const int nlI = (start + j) % normalizedLanes.size(); - NBEdge* edge = normalizedLanes[nlI].first; - NBEdge::Lane l = normalizedLanes[nlI].second; - wa.width = MAX2(wa.width, l.width); - if (connected.count(edge) == 0) { - if (edge->getFromNode() == this) { - wa.nextSidewalks.push_back(edge->getSidewalkID()); - connectedPoints.push_back(edge->getLaneShape(0)[0]); - } else { - wa.prevSidewalks.push_back(edge->getSidewalkID()); - connectedPoints.push_back(edge->getLaneShape(0)[-1]); - } - connected.insert(edge); - } - l.shape.move2side(-l.width / 2); - wa.shape.push_back(l.shape[0]); - l.shape.move2side(l.width); - wa.shape.push_back(l.shape[0]); - } - if (buildExtensions) { - // extension at starting crossing - if (startCrossingShape.size() > 0) { - if (gDebugFlag1) { - std::cout << " extension at startCrossing shape=" << startCrossingShape << "\n"; - } - startCrossingShape.move2side(startCrossingWidth / 2); - wa.shape.push_front_noDoublePos(startCrossingShape[0]); // right corner - startCrossingShape.move2side(-startCrossingWidth); - wa.shape.push_front_noDoublePos(startCrossingShape[0]); // left corner goes first - } - // extension at ending crossing - if (endCrossingShape.size() > 0) { - if (gDebugFlag1) { - std::cout << " extension at endCrossing shape=" << endCrossingShape << "\n"; - } - endCrossingShape.move2side(endCrossingWidth / 2); - wa.shape.push_back_noDoublePos(endCrossingShape[-1]); - endCrossingShape.move2side(-endCrossingWidth); - wa.shape.push_back_noDoublePos(endCrossingShape[-1]); - } - } - if (connected.size() == 2 && !connectsCrossing && wa.nextSidewalks.size() == 1 && wa.prevSidewalks.size() == 1 - && normalizedLanes.size() == 2) { - // do not build a walkingArea since a normal connection exists - NBEdge* e1 = *connected.begin(); - NBEdge* e2 = *(++connected.begin()); - if (e1->hasConnectionTo(e2, 0, 0) || e2->hasConnectionTo(e1, 0, 0)) { - if (gDebugFlag1) { - std::cout << " not building a walkingarea since normal connections exist\n"; - } - continue; - } - } - // build smooth inner curve (optional) - if (cornerDetail > 0) { - int smoothEnd = end; - int smoothPrev = prev; - // extend to green verge - if (endCrossingWidth > 0 && normalizedLanes[smoothEnd].second.permissions == 0) { - smoothEnd = (smoothEnd + 1) % normalizedLanes.size(); - } - if (startCrossingWidth > 0 && normalizedLanes[smoothPrev].second.permissions == 0) { - if (smoothPrev == 0) { - smoothPrev = (int)normalizedLanes.size() - 1; - } else { - smoothPrev--; - } - } - PositionVector begShape = normalizedLanes[smoothEnd].second.shape; - begShape = begShape.reverse(); - //begShape.extrapolate(endCrossingWidth); - begShape.move2side(normalizedLanes[smoothEnd].second.width / 2); - PositionVector endShape = normalizedLanes[smoothPrev].second.shape; - endShape.move2side(normalizedLanes[smoothPrev].second.width / 2); - //endShape.extrapolate(startCrossingWidth); - PositionVector curve; - if ((normalizedLanes[smoothEnd].first->getPermissions() & normalizedLanes[smoothPrev].first->getPermissions() & - ~(SVC_PEDESTRIAN | SVC_RAIL_CLASSES)) != 0) { - curve = computeSmoothShape(begShape, endShape, cornerDetail + 2, false, 25, 25); - } else { - const double extend = MIN2(10.0, begShape.back().distanceTo2D(endShape.front()) / 2); - curve = computeSmoothShape(begShape, endShape, cornerDetail + 2, false, extend, extend, nullptr, FOUR_CONTROL_POINTS); - } - if (gDebugFlag1) std::cout - << " end=" << smoothEnd << " prev=" << smoothPrev - << " endCrossingWidth=" << endCrossingWidth << " startCrossingWidth=" << startCrossingWidth - << " begShape=" << begShape << " endShape=" << endShape << " smooth curve=" << curve << "\n"; - if (curve.size() > 2) { - curve.erase(curve.begin()); - curve.pop_back(); - if (endCrossingWidth > 0) { - wa.shape.pop_back(); - } - if (startCrossingWidth > 0) { - wa.shape.erase(wa.shape.begin()); - } - wa.shape.append(curve, 0); - } - } - // apply custom shapes - if (myWalkingAreaCustomShapes.size() > 0) { - for (auto wacs : myWalkingAreaCustomShapes) { - // every edge in wasc.edges must be part of connected - if (wacs.shape.size() != 0 && includes(connected, wacs.edges)) { - wa.shape = wacs.shape; - wa.hasCustomShape = true; - } - } - } - // determine length (average of all possible connections) - double lengthSum = 0; - int combinations = 0; - for (std::vector::const_iterator it1 = connectedPoints.begin(); it1 != connectedPoints.end(); ++it1) { - for (std::vector::const_iterator it2 = connectedPoints.begin(); it2 != connectedPoints.end(); ++it2) { - const Position& p1 = *it1; - const Position& p2 = *it2; - if (p1 != p2) { - lengthSum += p1.distanceTo2D(p2); - combinations += 1; - } - } - } - if (gDebugFlag1) { - std::cout << " combinations=" << combinations << " connectedPoints=" << connectedPoints << "\n"; - } - wa.length = POSITION_EPS; - if (combinations > 0) { - wa.length = MAX2(POSITION_EPS, lengthSum / combinations); - } - myWalkingAreas.push_back(wa); - } - // build walkingAreas between split crossings - std::vector validCrossings = getCrossings(); - for (std::vector::iterator it = validCrossings.begin(); it != validCrossings.end(); ++it) { - Crossing& prev = **it; - Crossing& next = (it != validCrossings.begin() ? **(it - 1) :** (validCrossings.end() - 1)); - if (gDebugFlag1) { - std::cout << " checkIntermediate: prev=" << prev.id << " next=" << next.id << " prev.nextWA=" << prev.nextWalkingArea << "\n"; - } - if (prev.nextWalkingArea == "") { - if (next.prevWalkingArea != "" || &prev == &next) { - WRITE_WARNINGF("Invalid pedestrian topology: crossing '%' across [%] has no target.", prev.id, toString(prev.edges)); - prev.valid = false; - continue; - } - WalkingArea wa(":" + getID() + "_w" + toString(index++), prev.width); - prev.nextWalkingArea = wa.id; - wa.nextCrossings.push_back(next.id); - next.prevWalkingArea = wa.id; - // back of previous crossing - PositionVector tmp = prev.shape; - tmp.move2side(-prev.width / 2); - wa.shape.push_back(tmp[-1]); - tmp.move2side(prev.width); - wa.shape.push_back(tmp[-1]); - // front of next crossing - tmp = next.shape; - tmp.move2side(prev.width / 2); - wa.shape.push_back(tmp[0]); - tmp.move2side(-prev.width); - wa.shape.push_back(tmp[0]); - // apply custom shapes - if (myWalkingAreaCustomShapes.size() > 0) { - std::set crossed(prev.edges.begin(), prev.edges.end()); - crossed.insert(next.edges.begin(), next.edges.end()); - for (auto wacs : myWalkingAreaCustomShapes) { - // every edge in wacs.edges must be part of crossed - if (wacs.shape.size() != 0 && wacs.edges.size() > 1 && includes(crossed, wacs.edges)) { - wa.shape = wacs.shape; - wa.hasCustomShape = true; - } - } - } - // length (special case) - wa.length = MAX2(POSITION_EPS, prev.shape.back().distanceTo2D(next.shape.front())); - myWalkingAreas.push_back(wa); - if (gDebugFlag1) { - std::cout << " build wa=" << wa.id << "\n"; - } - } - } -} - -bool -NBNode::includes(const std::set& super, - const std::set& sub) { - // for some reason std::include does not work reliably - for (const NBEdge* e : sub) { - if (super.count(const_cast(e)) == 0) { - return false; - } - } - return true; -} - - -bool -NBNode::crossingBetween(const NBEdge* e1, const NBEdge* e2) const { - if (e1 == e2) { - return false; - } - if (myAllEdges.size() > 3) { - // pedestrian scramble - return false; - } - for (auto c : getCrossings()) { - const EdgeVector& edges = c->edges; - EdgeVector::const_iterator it1 = std::find(edges.begin(), edges.end(), e1); - EdgeVector::const_iterator it2 = std::find(edges.begin(), edges.end(), e2); - if (it1 != edges.end() && it2 != edges.end()) { - return true; - } - } - return false; -} - - -EdgeVector -NBNode::edgesBetween(const NBEdge* e1, const NBEdge* e2) const { - EdgeVector result; - EdgeVector::const_iterator it = std::find(myAllEdges.begin(), myAllEdges.end(), e1); - assert(it != myAllEdges.end()); - NBContHelper::nextCW(myAllEdges, it); - EdgeVector::const_iterator it_end = std::find(myAllEdges.begin(), myAllEdges.end(), e2); - assert(it_end != myAllEdges.end()); - while (it != it_end) { - result.push_back(*it); - NBContHelper::nextCW(myAllEdges, it); - } - return result; -} - - -void -NBNode::addWalkingAreaShape(EdgeVector edges, const PositionVector& shape) { - WalkingAreaCustomShape wacs; - wacs.edges.insert(edges.begin(), edges.end()); - wacs.shape = shape; - myWalkingAreaCustomShapes.push_back(wacs); -} - - -bool -NBNode::geometryLike() const { - return geometryLike(myIncomingEdges, myOutgoingEdges); -} - -bool -NBNode::geometryLike(const EdgeVector& incoming, const EdgeVector& outgoing) const { - if (incoming.size() == 1 && outgoing.size() == 1) { - return true; - } - if (incoming.size() == 2 && outgoing.size() == 2) { - // check whether the incoming and outgoing edges are pairwise (near) parallel and - // thus the only cross-connections could be turn-arounds - NBEdge* in0 = incoming[0]; - NBEdge* in1 = incoming[1]; - NBEdge* out0 = outgoing[0]; - NBEdge* out1 = outgoing[1]; - if ((in0->isTurningDirectionAt(out0) || in0->isTurningDirectionAt(out1)) - && (in1->isTurningDirectionAt(out0) || in1->isTurningDirectionAt(out1))) { - return true; - } - for (EdgeVector::const_iterator it = incoming.begin(); it != incoming.end(); ++it) { - NBEdge* inEdge = *it; - double angle0 = fabs(NBHelpers::relAngle(inEdge->getAngleAtNode(this), out0->getAngleAtNode(this))); - double angle1 = fabs(NBHelpers::relAngle(inEdge->getAngleAtNode(this), out1->getAngleAtNode(this))); - if (MAX2(angle0, angle1) <= 160) { - // neither of the outgoing edges is parallel to inEdge - return false; - } - } - return true; - } - return false; -} - -void -NBNode::setRoundabout() { - if (myType == SumoXMLNodeType::RIGHT_BEFORE_LEFT) { - myType = SumoXMLNodeType::PRIORITY; - } -} - -bool -NBNode::isRoundabout() const { - for (NBEdge* out : myOutgoingEdges) { - if (out->getJunctionPriority(this) == NBEdge::JunctionPriority::ROUNDABOUT) { - return true; - } - } - return false; -} - -NBNode::Crossing* -NBNode::addCrossing(EdgeVector edges, double width, bool priority, int tlIndex, int tlIndex2, - const PositionVector& customShape, bool fromSumoNet) { - Crossing* c = new Crossing(this, edges, width, priority, tlIndex, tlIndex2, customShape); - myCrossings.push_back(std::unique_ptr(c)); - if (fromSumoNet) { - myCrossingsLoadedFromSumoNet += 1; - } - return c; -} - - -void -NBNode::removeCrossing(const EdgeVector& edges) { - EdgeSet edgeSet(edges.begin(), edges.end()); - for (auto it = myCrossings.begin(); it != myCrossings.end();) { - EdgeSet edgeSet2((*it)->edges.begin(), (*it)->edges.end()); - if (edgeSet == edgeSet2) { - it = myCrossings.erase(it); - } else { - ++it; - } - } -} - - -NBNode::Crossing* -NBNode::getCrossing(const std::string& id) const { - for (auto& c : myCrossings) { - if (c->id == id) { - return c.get(); - } - } - throw ProcessError("Request for unknown crossing '" + id + "'"); -} - - -NBNode::Crossing* -NBNode::getCrossing(const EdgeVector& edges, bool hardFail) const { - EdgeSet edgeSet(edges.begin(), edges.end()); - for (auto& it : myCrossings) { - EdgeSet edgeSet2(it->edges.begin(), it->edges.end()); - if (edgeSet == edgeSet2) { - return it.get(); - } - } - if (!hardFail) { - return nullptr; - } else { - throw ProcessError("Request for unknown crossing for the given Edges"); - } -} - - -bool -NBNode::setCrossingTLIndices(const std::string& tlID, int startIndex) { - bool usedCustom = false; - for (auto c : getCrossings()) { - c->tlLinkIndex = startIndex++; - c->tlID = tlID; - if (c->customTLIndex != -1) { - usedCustom |= (c->tlLinkIndex != c->customTLIndex); - c->tlLinkIndex = c->customTLIndex; - } - c->tlLinkIndex2 = c->customTLIndex2; - } - return usedCustom; -} - - -int -NBNode::numNormalConnections() const { - if (myRequest == nullptr) { - // could be an uncontrolled type - int result = 0; - for (const NBEdge* const edge : myIncomingEdges) { - result += (int)edge->getConnections().size(); - } - return result; - } else { - return myRequest->getSizes().second; - } -} - - -int -NBNode::getConnectionIndex(const NBEdge* from, const NBEdge::Connection& con) const { - int result = 0; - for (EdgeVector::const_iterator i = myIncomingEdges.begin(); i != myIncomingEdges.end(); i++) { - const std::vector& elv = (*i)->getConnections(); - for (std::vector::const_iterator k = elv.begin(); k != elv.end(); ++k) { - const NBEdge::Connection& cand = *k; - if (*i == from - && cand.fromLane == con.fromLane - && cand.toLane == con.toLane - && cand.toEdge == con.toEdge) { - return result; - }; - result++; - } - } - return -1; -} - -Position -NBNode::getCenter() const { - /* Conceptually, the center point would be identical with myPosition. - * However, if the shape is influenced by custom geometry endpoints of the adjoining edges, - * myPosition may fall outside the shape. In this case it is better to use - * the center of the shape - **/ - PositionVector tmp = myPoly; - tmp.closePolygon(); - //std::cout << getID() << " around=" << tmp.around(myPosition) << " dist=" << tmp.distance2D(myPosition) << "\n"; - if (tmp.size() < 3 || tmp.around(myPosition) || tmp.distance2D(myPosition) < POSITION_EPS) { - return myPosition; - } else { - return myPoly.getPolygonCenter(); - } -} - - -EdgeVector -NBNode::getEdgesSortedByAngleAtNodeCenter() const { - EdgeVector result = myAllEdges; - if (gDebugFlag1) { - std::cout << " angles:\n"; - for (EdgeVector::const_iterator it = result.begin(); it != result.end(); ++it) { - std::cout << " edge=" << (*it)->getID() << " edgeAngle=" << (*it)->getAngleAtNode(this) << " angleToShape=" << (*it)->getAngleAtNodeToCenter(this) << "\n"; - } - std::cout << " allEdges before: " << toString(result) << "\n"; - } - sort(result.begin(), result.end(), NBContHelper::edge_by_angle_to_nodeShapeCentroid_sorter(this)); - // let the first edge in myAllEdges remain the first - if (gDebugFlag1) { - std::cout << " allEdges sorted: " << toString(result) << "\n"; - } - rotate(result.begin(), std::find(result.begin(), result.end(), *myAllEdges.begin()), result.end()); - if (gDebugFlag1) { - std::cout << " allEdges rotated: " << toString(result) << "\n"; - } - return result; -} - - -std::string -NBNode::getNodeIDFromInternalLane(const std::string id) { - // this relies on the fact that internal ids always have the form - // :__ - // i.e. :C_3_0, :C_c1_0 :C_w0_0 - assert(id[0] == ':'); - std::string::size_type sep_index = id.rfind('_'); - if (sep_index == std::string::npos) { - WRITE_ERROR("Invalid lane id '" + id + "' (missing '_')."); - return ""; - } - sep_index = id.substr(0, sep_index).rfind('_'); - if (sep_index == std::string::npos) { - WRITE_ERROR("Invalid lane id '" + id + "' (missing '_')."); - return ""; - } - return id.substr(1, sep_index - 1); -} - - -void -NBNode::avoidOverlap() { - // simple case: edges with LaneSpreadFunction::CENTER and a (possible) turndirection at the same node - for (EdgeVector::iterator it = myIncomingEdges.begin(); it != myIncomingEdges.end(); it++) { - NBEdge* edge = *it; - NBEdge* turnDest = edge->getTurnDestination(true); - if (turnDest != nullptr) { - edge->shiftPositionAtNode(this, turnDest); - turnDest->shiftPositionAtNode(this, edge); - } - } - // @todo: edges in the same direction with sharp angles starting/ending at the same position -} - - -bool -NBNode::isTrafficLight(SumoXMLNodeType type) { - return type == SumoXMLNodeType::TRAFFIC_LIGHT - || type == SumoXMLNodeType::TRAFFIC_LIGHT_NOJUNCTION - || type == SumoXMLNodeType::TRAFFIC_LIGHT_RIGHT_ON_RED; -} - - -bool -NBNode::rightOnRedConflict(int index, int foeIndex) const { - for (NBTrafficLightDefinition* def : myTrafficLights) { - if (def->rightOnRedConflict(index, foeIndex)) { - return true; - } - } - return false; -} - - -void -NBNode::sortEdges(bool useNodeShape) { - if (myAllEdges.size() == 0) { - return; - } - EdgeVector allEdgesOriginal = myAllEdges; - EdgeVector& allEdges = myAllEdges; - EdgeVector& incoming = myIncomingEdges; - EdgeVector& outgoing = myOutgoingEdges; - - // sort the edges by angle (this is the canonical sorting) - std::sort(allEdges.begin(), allEdges.end(), NBNodesEdgesSorter::edge_by_junction_angle_sorter(this)); - std::sort(incoming.begin(), incoming.end(), NBNodesEdgesSorter::edge_by_junction_angle_sorter(this)); - std::sort(outgoing.begin(), outgoing.end(), NBNodesEdgesSorter::edge_by_junction_angle_sorter(this)); - std::vector::iterator j; - for (j = allEdges.begin(); j != allEdges.end() - 1 && j != allEdges.end(); ++j) { - NBNodesEdgesSorter::swapWhenReversed(this, j, j + 1); - } - if (allEdges.size() > 1 && j != allEdges.end()) { - NBNodesEdgesSorter::swapWhenReversed(this, allEdges.end() - 1, allEdges.begin()); - } - - // sort again using additional geometry information - NBEdge* firstOfAll = allEdges.front(); - NBEdge* firstOfIncoming = incoming.size() > 0 ? incoming.front() : 0; - NBEdge* firstOfOutgoing = outgoing.size() > 0 ? outgoing.front() : 0; - // sort by the angle between the node shape center and the point where the edge meets the node shape - std::sort(allEdges.begin(), allEdges.end(), NBContHelper::edge_by_angle_to_nodeShapeCentroid_sorter(this)); - std::sort(incoming.begin(), incoming.end(), NBContHelper::edge_by_angle_to_nodeShapeCentroid_sorter(this)); - std::sort(outgoing.begin(), outgoing.end(), NBContHelper::edge_by_angle_to_nodeShapeCentroid_sorter(this)); - // let the first edge remain the first - rotate(allEdges.begin(), std::find(allEdges.begin(), allEdges.end(), firstOfAll), allEdges.end()); - if (firstOfIncoming != nullptr) { - rotate(incoming.begin(), std::find(incoming.begin(), incoming.end(), firstOfIncoming), incoming.end()); - } - if (firstOfOutgoing != nullptr) { - rotate(outgoing.begin(), std::find(outgoing.begin(), outgoing.end(), firstOfOutgoing), outgoing.end()); - } -#ifdef DEBUG_EDGE_SORTING - if (DEBUGCOND) { - std::cout << "sortedEdges:\n"; - for (NBEdge* e : allEdges) { - std::cout << " " << e->getID() - << " angleToCenter=" << e->getAngleAtNodeToCenter(this) - << " junctionAngle=" << e->getAngleAtNode(this) << "\n"; - } - } -#endif - - // fixing some pathological all edges orderings - // if every of the edges a,b,c has a turning edge a',b',c' the all edges ordering should be a,a',b,b',c,c' - if (incoming.size() == outgoing.size() && incoming.front() == allEdges.front()) { - std::vector::const_iterator in, out; - std::vector allTmp; - for (in = incoming.begin(), out = outgoing.begin(); in != incoming.end(); ++in, ++out) { - if ((*in)->isTurningDirectionAt(*out)) { - allTmp.push_back(*in); - allTmp.push_back(*out); - } else { - break; - } - } - if (allTmp.size() == allEdges.size()) { - allEdges = allTmp; - } - } - // sort the crossings - std::sort(myCrossings.begin(), myCrossings.end(), NBNodesEdgesSorter::crossing_by_junction_angle_sorter(this, allEdges)); - //if (crossings.size() > 0) { - // std::cout << " crossings at " << getID() << "\n"; - // for (std::vector::iterator it = crossings.begin(); it != crossings.end(); ++it) { - // std::cout << " " << toString((*it)->edges) << "\n"; - // } - //} - - if (useNodeShape && myAllEdges != allEdgesOriginal) { - // sorting order changed after node shape was computed. - computeNodeShape(-1); - for (NBEdge* e : myAllEdges) { - e->computeEdgeShape(); - } - } -} - -std::vector > -NBNode::getEndPoints() const { - // using a set would be nicer but we want to have some slack in position identification - std::vector >result; - for (NBEdge* e : myAllEdges) { - Position pos = this == e->getFromNode() ? e->getGeometry().front() : e->getGeometry().back(); - const std::string origID = e->getParameter(this == e->getFromNode() ? "origFrom" : "origTo"); - bool unique = true; - for (const auto& pair : result) { - if (pos.almostSame(pair.first) || (origID != "" && pair.second == origID)) { - unique = false; - break; - } - } - if (unique) { - result.push_back(std::make_pair(pos, origID)); - } - } - return result; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netbuild/NBNode.h b/Util/OSM2ODR/src/netbuild/NBNode.h deleted file mode 100644 index 86c1972e7..000000000 --- a/Util/OSM2ODR/src/netbuild/NBNode.h +++ /dev/null @@ -1,914 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NBNode.h -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Yun-Pang Floetteroed -/// @author Michael Behrisch -/// @date Tue, 20 Nov 2001 -/// -// The representation of a single node -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "NBEdge.h" -#include "NBConnection.h" -#include "NBConnectionDefs.h" -#include "NBContHelper.h" - - -// =========================================================================== -// class declarations -// =========================================================================== -class NBRequest; -class NBDistrict; -class OptionsCont; -class NBTrafficLightDefinition; -class NBTypeCont; -class NBTrafficLightLogicCont; -class NBDistrictCont; -class OutputDevice; - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NBNode - * @brief Represents a single node (junction) during network building - */ -class NBNode : public Named, public Parameterised { - friend class NBNodeCont; - friend class GNEJunction; // < used for visualization (NETEDIT) - friend class NBNodesEdgesSorter; // < sorts the edges - friend class NBNodeTypeComputer; // < computes type - friend class NBEdgePriorityComputer; // < computes priorities of edges per intersection - -public: - /** - * @class ApproachingDivider - * @brief Computes lane-2-lane connections - * - * Being a bresenham-callback, this class computes which lanes - * are approached by the current lane (first callback parameter). - * The second callback parameter is the destination lane that is the - * middle of the computed lanes. - * The lanes are spreaded from this middle position both to left and right - * but may also be transposed in full when there is not enough space. - */ - class ApproachingDivider : public Bresenham::BresenhamCallBack { - public: - /**@brief Constructor - * @param[in] approaching The list of the edges that approach the outgoing edge - * @param[in] currentOutgoing The outgoing edge - */ - ApproachingDivider(const EdgeVector& approaching, NBEdge* currentOutgoing); - - /// @brief Destructor - ~ApproachingDivider(); - - /// @ get number of avaliable lanes - int numAvailableLanes() const { - return (int)myAvailableLanes.size(); - } - - /// @brief the bresenham-callback - void execute(const int src, const int dest); - - /// @brief the method that spreads the wished number of lanes from the the lane given by the bresenham-call to both left and right - std::deque* spread(const std::vector& approachingLanes, int dest) const; - - private: - /// @brief The list of edges that approach the current edge - const EdgeVector& myApproaching; - - /// @brief The approached current edge - NBEdge* myCurrentOutgoing; - - /// @brief The available lanes to which connections shall be built - std::vector myAvailableLanes; - - /// @brief whether the outgoing edge is exclusively used by bikes - bool myIsBikeEdge; - - private: - /// @brief Invalidated assignment operator. - ApproachingDivider& operator=(const ApproachingDivider&) = delete; - - }; - - /** @struct Crossing - * @brief A definition of a pedestrian crossing - */ - struct Crossing : public Parameterised { - /// @brief constructor - Crossing(const NBNode* _node, const EdgeVector& _edges, double _width, bool _priority, int _customTLIndex, int _customTLIndex2, const PositionVector& _customShape); - /// @brief The parent node of this crossing - const NBNode* node; - /// @brief The edges being crossed - EdgeVector edges; - /// @brief The crossing's shape - PositionVector shape; - /// @brief This crossing's width - double customWidth; - /// @brief This crossing's width - double width; - /// @brief the (edge)-id of this crossing - std::string id; - /// @brief the lane-id of the previous walkingArea - std::string prevWalkingArea; - /// @brief the lane-id of the next walkingArea - std::string nextWalkingArea; - /// @brief whether the pedestrians have priority - bool priority; - /// @brief optional customShape for this crossing - PositionVector customShape; - /// @brief the traffic light index of this crossing (if controlled) - int tlLinkIndex; - int tlLinkIndex2; - /// @brief the custom traffic light index of this crossing (if controlled) - int customTLIndex; - int customTLIndex2; - /// @brief The id of the traffic light that controls this connection - std::string tlID; - /// @brief whether this crossing is valid (and can be written to the net.xml). This is needed for netedit because validity can only be checked during junction computation - bool valid; - }; - - - /** @struct WalkingArea - * @brief A definition of a pedestrian walking area - */ - struct WalkingArea { - /// @brief constructor - WalkingArea(const std::string& _id, double _width) : - id(_id), - width(_width) { - } - /// @brief the (edge)-id of this walkingArea - std::string id; - /// @brief This lane's width - double width; - /// @brief This lane's width - double length = INVALID_DOUBLE; - /// @brief The polygonal shape - PositionVector shape; - /// @brief the lane-id of the next crossing(s) - std::vector nextCrossings; - /// @brief the lane-id of the next sidewalk lane or "" - std::vector nextSidewalks; - /// @brief the lane-id of the previous sidewalk lane or "" - std::vector prevSidewalks; - /// @brief whether this walkingArea has a custom shape - bool hasCustomShape = false; - /// @brief minimum number of edges crossed by nextCrossings - int minNextCrossingEdges = std::numeric_limits::max(); - /// @brief minimum number of edges crossed by incoming crossings - int minPrevCrossingEdges = std::numeric_limits::max(); - }; - - struct WalkingAreaCustomShape { - std::set edges; - PositionVector shape; - }; - - /// @brief edge directions (for pedestrian related stuff) - static const int FORWARD; - static const int BACKWARD; - - /// @brief unspecified lane width - static const double UNSPECIFIED_RADIUS; - - /// @brief flags for controlling shape generation - static const int AVOID_WIDE_RIGHT_TURN; - static const int AVOID_WIDE_LEFT_TURN; - static const int FOUR_CONTROL_POINTS; - static const int AVOID_INTERSECTING_LEFT_TURNS; - static const int SCURVE_IGNORE; - -public: - /**@brief Constructor - * @param[in] id The id of the node - * @param[in] position The position of the node - * @param[in] type The type of the node - */ - NBNode(const std::string& id, const Position& position, SumoXMLNodeType type); - - /**@brief Constructor - * @param[in] id The id of the node - * @param[in] position The position of the node - * @param[in] district The district this district node represents, 0 means no district node - */ - NBNode(const std::string& id, const Position& position, NBDistrict* district = 0); - - /// @brief Destructor - ~NBNode(); - - /**@brief Resets initial values - * @param[in] position The position of the node - * @param[in] type The type of the node - * @param[in] updateEdgeGeometries Whether the geometires of all - * connected edges shall be updated - */ - void reinit(const Position& position, SumoXMLNodeType type, - bool updateEdgeGeometries = false); - - /// @name Atomar getter methods - /// @{ - /// @brief Returns the position of this node - const Position& getPosition() const { - return myPosition; - } - - /// @brief Returns a position that is guaranteed to lie within the node shape - Position getCenter() const; - - /// @brief Returns this node's incoming edges (The edges which yield in this node) - const EdgeVector& getIncomingEdges() const { - return myIncomingEdges; - } - - /// @brief Returns this node's outgoing edges (The edges which start at this node) - const EdgeVector& getOutgoingEdges() const { - return myOutgoingEdges; - } - - /// @brief Returns all edges which participate in this node (Edges that start or end at this node) - const EdgeVector& getEdges() const { - return myAllEdges; - } - - /**@brief Returns the type of this node - * @see SumoXMLNodeType - */ - SumoXMLNodeType getType() const { - return myType; - } - - /// @brief Returns the turning radius of this node - double getRadius() const { - return myRadius; - } - - /// @brief Returns the keepClear flag - bool getKeepClear() const { - return myKeepClear; - } - - /// @brief Returns hint on how to compute right of way - RightOfWay getRightOfWay() const { - return myRightOfWay; - } - - /// @brief Returns fringe type - FringeType getFringeType() const { - return myFringeType; - } - - /// @brief Returns intersection name - const std::string& getName() const { - return myName; - } - /// @} - - /// @name Methods for dealing with assigned traffic lights - /// @{ - /**@brief Adds a traffic light to the list of traffic lights that control this node - * @param[in] tld The traffic light that controls this node - */ - void addTrafficLight(NBTrafficLightDefinition* tlDef); - - /// @brief Removes the given traffic light from this node - void removeTrafficLight(NBTrafficLightDefinition* tlDef); - - /// @brief Removes all references to traffic lights that control this tls - void removeTrafficLights(bool setAsPriority = false); - - /**@brief Returns whether this node is controlled by any tls - * @return Whether a traffic light was assigned to this node - */ - bool isTLControlled() const { - return myTrafficLights.size() != 0; - } - - /// @brief Returns the traffic lights that were assigned to this node (The set of tls that control this node) - const std::set& getControllingTLS() const { - return myTrafficLights; - } - - /// @brief causes the traffic light to be computed anew - void invalidateTLS(NBTrafficLightLogicCont& tlCont, bool removedConnections, bool addedConnections); - - /// @brief patches loaded signal plans by modifying lane indices above threshold by the given offset - void shiftTLConnectionLaneIndex(NBEdge* edge, int offset, int threshold = -1); - /// @} - - - /// @name Prunning the input - /// @{ - - /**@brief Removes edges which are both incoming and outgoing into this node - * - * If given, the connections to other edges participating in this node are updated - * - * @param[in, opt. changed] dc The districts container to update - * @param[in, opt. changed] ec The edge container to remove the edges from - * @param[in, opt. changed] tc The traffic lights container to update - * @return The number of removed edges - */ - int removeSelfLoops(NBDistrictCont& dc, NBEdgeCont& ec, NBTrafficLightLogicCont& tc); - /// @} - - - /// @name Applying offset - /// @{ - /**@brief Applies an offset to the node - * @param[in] xoff The x-offset to apply - * @param[in] yoff The y-offset to apply - */ - void reshiftPosition(double xoff, double yoff); - - /// @brief mirror coordinates along the x-axis - void mirrorX(); - /// @} - - /// @brief adds an incoming edge - void addIncomingEdge(NBEdge* edge); - - /// @brief adds an outgoing edge - void addOutgoingEdge(NBEdge* edge); - - /// @brief computes the connections of lanes to edges - void computeLanes2Lanes(); - - /// @brief computes the node's type, logic and traffic light - void computeLogic(const NBEdgeCont& ec); - - /// @brief compute right-of-way logic for all lane-to-lane connections - void computeLogic2(bool checkLaneFoes); - - /// @brief writes the XML-representation of the logic as a bitset-logic XML representation - bool writeLogic(OutputDevice& into) const; - - /// @brief get the 'foes' string (conflict bit set) of the right-of-way logic - const std::string getFoes(int linkIndex) const; - - /// @brief get the 'response' string (right-of-way bit set) of the right-of-way logic - const std::string getResponse(int linkIndex) const; - - /// @brief whether there are conflicting streams of traffic at this node - bool hasConflict() const; - - /// @brief Returns something like the most unused direction Should only be used to add source or sink nodes - Position getEmptyDir() const; - - /**@brief Returns whether the given edge ends at this node - * @param[in] e The edge - * @return Whether the given edge is one of this node's incoming edges - */ - bool hasIncoming(const NBEdge* const e) const; - - /**@brief Returns whether the given edge starts at this node - * @param[in] e The edge - * @return Whether the given edge is one of this node's outgoing edges - */ - bool hasOutgoing(const NBEdge* const e) const; - - /// @brief returns the opposite incoming edge of certain edge - NBEdge* getOppositeIncoming(NBEdge* e) const; - - /// @brief invalidate incoming connections - void invalidateIncomingConnections(); - - /// @brief invalidate outgoing connections - void invalidateOutgoingConnections(); - - /// @brief remove duble edges - void removeDoubleEdges(); - - /// @brief get connection to certain node - NBEdge* getConnectionTo(NBNode* n) const; - - /// @brief add shorted link FOES - void addSortedLinkFoes(const NBConnection& mayDrive, const NBConnection& mustStop); - - /// @brief get possibly splitted incoming edge - NBEdge* getPossiblySplittedIncoming(const std::string& edgeid); - - /// @brief get possibly splitted outgoing edge - NBEdge* getPossiblySplittedOutgoing(const std::string& edgeid); - - /// @brief Removes edge from this node and optionally removes connections as well - void removeEdge(NBEdge* edge, bool removeFromConnections = true); - - /**@brief Computes whether the given connection is a left mover across the junction - * - * It is assumed, that it is a left-mover if the clockwise angle is lower - * than the counter-clockwise angle. - * - * @param[in] from The incoming edge (the begin of the connection) - * @param[in] from The outgoing edge (the end of the connection) - * @return Whether the described connection is a left-mover - */ - bool isLeftMover(const NBEdge* const from, const NBEdge* const to) const; - - /**@brief Returns the information whether the described flow must let any other flow pass - * @param[in] from The connection's start edge - * @param[in] to The connection's end edge - * @param[in] fromLane The lane the connection start at - * @param[in] toLane The lane the connection ends at - * @param[in] includePedCrossings Whether braking due to a pedestrian crossing counts - * @return Whether the described connection must brake (has higher priorised foes) - */ - bool mustBrake(const NBEdge* const from, const NBEdge* const to, int fromLane, int toLane, bool includePedCrossings) const; - - /**@brief Returns the information whether the described flow must brake for the given crossing - * @param[in] from The connection's start edge - * @param[in] to The connection's end edge - * @param[in] crossing The pedestrian crossing to check - * @return Whether the described connection must brake (has higher priorised foes) - */ - bool mustBrakeForCrossing(const NBEdge* const from, const NBEdge* const to, const Crossing& crossing) const; - - /// @brief return whether the given laneToLane connection is a right turn which must yield to a bicycle crossings - static bool rightTurnConflict(const NBEdge* from, const NBEdge* to, int fromLane, - const NBEdge* prohibitorFrom, const NBEdge* prohibitorTo, int prohibitorFromLane); - - /// @brief return whether the given laneToLane connection originate from the same edge and are in conflict due to turning across each other - bool turnFoes(const NBEdge* from, const NBEdge* to, int fromLane, - const NBEdge* from2, const NBEdge* to2, int fromLane2, - bool lefthand = false) const; - - /**@brief Returns the information whether "prohibited" flow must let "prohibitor" flow pass - * @param[in] possProhibitedFrom The maybe prohibited connection's begin - * @param[in] possProhibitedTo The maybe prohibited connection's end - * @param[in] possProhibitorFrom The maybe prohibiting connection's begin - * @param[in] possProhibitorTo The maybe prohibiting connection's end - * @param[in] regardNonSignalisedLowerPriority Whether the right of way rules without traffic lights shall be regarded - * @return Whether the second flow prohibits the first one - */ - bool forbids(const NBEdge* const possProhibitorFrom, const NBEdge* const possProhibitorTo, - const NBEdge* const possProhibitedFrom, const NBEdge* const possProhibitedTo, - bool regardNonSignalisedLowerPriority) const; - - /**@brief Returns the information whether the given flows cross - * @param[in] from1 The starting edge of the first stream - * @param[in] to1 The ending edge of the first stream - * @param[in] from2 The starting edge of the second stream - * @param[in] to2 The ending edge of the second stream - * @return Whether both stream are foes (cross) - */ - bool foes(const NBEdge* const from1, const NBEdge* const to1, - const NBEdge* const from2, const NBEdge* const to2) const; - - /**@brief Returns the representation of the described stream's direction - * @param[in] incoming The edge the stream starts at - * @param[in] outgoing The edge the stream ends at - * @param[in] leftHand Whether a lefthand network is being built. Should only be set at writing time - * @return The direction of the stream - */ - LinkDirection getDirection(const NBEdge* const incoming, const NBEdge* const outgoing, bool leftHand = false) const; - - /// @brief get link state - LinkState getLinkState(const NBEdge* incoming, NBEdge* outgoing, - int fromLane, int toLane, bool mayDefinitelyPass, const std::string& tlID) const; - - /**@brief Compute the junction shape for this node - * @param[in] mismatchThreshold The threshold for warning about shapes which are away from myPosition - */ - void computeNodeShape(double mismatchThreshold); - - /// @brief update geometry of node and surrounding edges - void updateSurroundingGeometry(); - - /// @brief retrieve the junction shape - const PositionVector& getShape() const; - - /// @brief set the junction shape - void setCustomShape(const PositionVector& shape); - - /// @brief set the turning radius - void setRadius(double radius) { - myRadius = radius; - } - - /// @brief set the keepClear flag - void setKeepClear(bool keepClear) { - myKeepClear = keepClear; - } - - /// @brief set method for computing right-of-way - void setRightOfWay(RightOfWay rightOfWay) { - myRightOfWay = rightOfWay; - } - - /// @brief set method for computing right-of-way - void setFringeType(FringeType fringeType) { - myFringeType = fringeType; - } - - /// @brief set intersection name - void setName(const std::string& name) { - myName = name; - } - - /// @brief return whether the shape was set by the user - bool hasCustomShape() const { - return myHaveCustomPoly; - } - - /// @brief check if node is removable - bool checkIsRemovable() const; - - /// @brief check if node is removable and return reason if not - bool checkIsRemovableReporting(std::string& reason) const; - - /// @brief get edges to join - std::vector > getEdgesToJoin() const; - - /// @chech if node is near district - bool isNearDistrict() const; - - /// @brief check if node is a district - bool isDistrict() const; - - /// @brief whether an internal junction should be built at from and respect other - bool needsCont(const NBEdge* fromE, const NBEdge* otherFromE, - const NBEdge::Connection& c, const NBEdge::Connection& otherC) const; - - /// @brief whether the connection must yield if the foe remains on the intersection after its phase ends - bool tlsContConflict(const NBEdge* from, const NBEdge::Connection& c, - const NBEdge* foeFrom, const NBEdge::Connection& foe) const; - - - /**@brief Compute the shape for an internal lane - * @param[in] fromE The starting edge - * @param[in] con The connection for this internal lane - * @param[in] numPoints The number of geometry points for the internal lane - * @param[in] recordError The node itself if the displacement error during shape computation shall be recorded - * @return The shape of the internal lane - */ - PositionVector computeInternalLaneShape(NBEdge* fromE, const NBEdge::Connection& con, int numPoints, NBNode* recordError = 0, int shapeFlag = 0) const; - - /**@brief Compute a smooth curve between the given geometries - * @param[in] begShape The geometry at the start - * @param[in] endShape The geometry at the end - * @param[in] numPoints The number of geometry points for the internal lane - * @param[in] isTurnaround Whether this shall be the shape for a turnaround - * @param[in] extrapolateBeg Extrapolation distance at the beginning - * @param[in] extrapolateEnd Extrapolation distance at the end - * @param[in] recordError The node itself if the displacement error during shape computation shall be recorded - * @return The shape of the internal lane - */ - PositionVector computeSmoothShape(const PositionVector& begShape, const PositionVector& endShape, int numPoints, - bool isTurnaround, double extrapolateBeg, double extrapolateEnd, - NBNode* recordError = 0, int shapeFlag = 0) const; - /// @brief get bezier control points - static PositionVector bezierControlPoints(const PositionVector& begShape, const PositionVector& endShape, - bool isTurnaround, double extrapolateBeg, double extrapolateEnd, - bool& ok, NBNode* recordError = 0, double straightThresh = DEG2RAD(5), - int shapeFlag = 0); - - - /// @brief compute the displacement error during s-curve computation - double getDisplacementError() const { - return myDisplacementError; - } - - /// @brief Replaces occurences of the first edge within the list of incoming by the second Connections are remapped, too - void replaceIncoming(NBEdge* which, NBEdge* by, int laneOff); - - /// @brief Replaces occurences of every edge from the given list within the list of incoming by the second Connections are remapped, too - void replaceIncoming(const EdgeVector& which, NBEdge* by); - - /// @brief Replaces occurences of the first edge within the list of outgoing by the second Connections are remapped, too - void replaceOutgoing(NBEdge* which, NBEdge* by, int laneOff); - - /// @brief Replaces occurences of every edge from the given list within the list of outgoing by the second Connections are remapped, too - void replaceOutgoing(const EdgeVector& which, NBEdge* by); - - /// @brief guess pedestrian crossings and return how many were guessed - int guessCrossings(); - - /* @brief check whether a crossing should be build for the candiate edges and build 0 to n crossings - * @param[in] candidates The candidate vector of edges to be crossed - * @return The number of crossings built - * */ - int checkCrossing(EdgeVector candidates); - - /// @brief return true if there already exist a crossing with the same edges as the input - bool checkCrossingDuplicated(EdgeVector edges); - - /// @brief build internal lanes, pedestrian crossings and walking areas - void buildInnerEdges(); - - /**@brief build pedestrian crossings - * @return The next index for creating internal lanes - **/ - int buildCrossings(); - - /**@brief build pedestrian walking areas and set connections from/to walkingAreas - * @param[in] cornerDetail The detail level when generating the inner curve - */ - void buildWalkingAreas(int cornerDetail); - - /// @brief build crossings, and walkingareas. Also removes invalid loaded crossings if wished - void buildCrossingsAndWalkingAreas(); - - /// @brief return all edges that lie clockwise between the given edges - EdgeVector edgesBetween(const NBEdge* e1, const NBEdge* e2) const; - - /// @brief return true if the given edges are connected by a crossing - bool crossingBetween(const NBEdge* e1, const NBEdge* e2) const; - - /// @brief get prohibitions (BLocked connections) - const NBConnectionProhibits& getProhibitions() { - return myBlockedConnections; - } - - /// @brief whether this is structurally similar to a geometry node - bool geometryLike() const; - bool geometryLike(const EdgeVector& incoming, const EdgeVector& outgoing) const; - - /// @brief update the type of this node as a roundabout - void setRoundabout(); - - /// @brief return whether this node is part of a roundabout - bool isRoundabout() const; - - /// @brief add a pedestrian crossing to this node - NBNode::Crossing* addCrossing(EdgeVector edges, double width, bool priority, int tlIndex = -1, int tlIndex2 = -1, - const PositionVector& customShape = PositionVector::EMPTY, bool fromSumoNet = false); - - /// @brief add custom shape for walkingArea - void addWalkingAreaShape(EdgeVector edges, const PositionVector& shape); - - /// @brief remove a pedestrian crossing from this node (identified by its edges) - void removeCrossing(const EdgeVector& edges); - - /// @brief discard all current (and optionally future) crossings - void discardAllCrossings(bool rejectAll); - - /// @brief discard previously built walkingareas (required for repeated computation by netedit) - void discardWalkingareas(); - - /// @brief get num of crossings from sumo net - int numCrossingsFromSumoNet() const { - return myCrossingsLoadedFromSumoNet; - } - - /// @brief return this junctions pedestrian crossings - std::vector getCrossings() const; - inline const std::vector >& getCrossingsIncludingInvalid() const { - return myCrossings; - } - - /// @brief return this junctions pedestrian walking areas - inline const std::vector& getWalkingAreas() const { - return myWalkingAreas; - } - - const std::vector& getWalkingAreaCustomShapes() const { - return myWalkingAreaCustomShapes; - } - - /// @brief return the crossing with the given id - Crossing* getCrossing(const std::string& id) const; - - /// @brief return the crossing with the given Edges - Crossing* getCrossing(const EdgeVector& edges, bool hardFail = true) const; - - /* @brief set tl indices of this nodes crossing starting at the given index - * @return Whether a custom index was used - */ - bool setCrossingTLIndices(const std::string& tlID, int startIndex); - - /// @brief return the number of lane-to-lane connections at this junction (excluding crossings) - int numNormalConnections() const; - - /// @brief fix overlap - void avoidOverlap(); - - /// @brief whether the given index must yield to the foeIndex while turing right on a red light - bool rightOnRedConflict(int index, int foeIndex) const; - - /// @brief sort all edge containers for this node - void sortEdges(bool useNodeShape); - - /// @brief return the index of the given connection - int getConnectionIndex(const NBEdge* from, const NBEdge::Connection& con) const; - - /** - * @class nodes_by_id_sorter - * @brief Used for sorting the cells by the begin time they describe - */ - class nodes_by_id_sorter { - public: - /// @brief Constructor - explicit nodes_by_id_sorter() { } - - /// @brief Comparing operator - int operator()(NBNode* n1, NBNode* n2) const { - return n1->getID() < n2->getID(); - } - }; - - /** @class edge_by_direction_sorter - * @brief Sorts outgoing before incoming edges - */ - class edge_by_direction_sorter { - public: - /// @brief constructor - explicit edge_by_direction_sorter(NBNode* n) : myNode(n) {} - - /// @brief operator of selection - int operator()(NBEdge* e1, NBEdge* e2) const { - UNUSED_PARAMETER(e2); - return e1->getFromNode() == myNode; - } - - private: - /// @brief The node to compute the relative angle of - NBNode* myNode; - - }; - - /// @brief returns the node id for internal lanes, crossings and walkingareas - static std::string getNodeIDFromInternalLane(const std::string id); - - - /// @brief return whether the given type is a traffic light - static bool isTrafficLight(SumoXMLNodeType type); - - /// @brief check if node is a simple continuation - bool isSimpleContinuation(bool checkLaneNumbers = true, bool checkWidth = false) const; - - /// @brief mark whether a priority road turns at this node - void markBentPriority(bool isBent) { - myIsBentPriority = isBent; - } - - /// @brief return whether a priority road turns at this node - bool isBentPriority() const { - return myIsBentPriority; - } - - /// @brief return whether a priority road turns at this node - bool typeWasGuessed() const { - return myTypeWasGuessed; - } - - /// @brief detects whether a given junction splits or merges lanes while keeping constant road width - bool isConstantWidthTransition() const; - - /// @brief return list of unique endpoint coordinates of all edges at this node - std::vector > getEndPoints() const; - -private: - /// @brief sets the priorites in case of a priority junction - void setPriorityJunctionPriorities(); - - /// @brief returns a list of edges which are connected to the given outgoing edge - void getEdgesThatApproach(NBEdge* currentOutgoing, EdgeVector& approaching); - - /// @brief replace incoming connections prohibitions - void replaceInConnectionProhibitions(NBEdge* which, NBEdge* by, int whichLaneOff, int byLaneOff); - - /// @brief remap removed - void remapRemoved(NBTrafficLightLogicCont& tc, NBEdge* removed, const EdgeVector& incoming, const EdgeVector& outgoing); - - /// @brief return whether there is a non-sidewalk lane after the given index; - bool forbidsPedestriansAfter(std::vector > normalizedLanes, int startIndex); - - /// @brief returns the list of all edges sorted clockwise by getAngleAtNodeToCenter - EdgeVector getEdgesSortedByAngleAtNodeCenter() const; - - /// @brief check if is long enough - static bool isLongEnough(NBEdge* out, double minLength); - - /// @brief remove all traffic light definitions that are part of a joined tls - void removeJoinedTrafficLights(); - - /// @brief displace lane shapes to account for change in lane width at this node - void displaceShapeAtWidthChange(const NBEdge* from, const NBEdge::Connection& con, PositionVector& fromShape, PositionVector& toShape) const; - - /// @brief returns whether sub is a subset of super - static bool includes(const std::set& super, - const std::set& sub); - - NBEdge* getNextCompatibleOutgoing(const NBEdge* incoming, SVCPermissions vehPerm, EdgeVector::const_iterator start, bool clockwise) const; - - /// @brief get the reduction in driving lanes at this junction - void getReduction(const NBEdge* in, const NBEdge* out, int& inOffset, int& outOffset, int& reduction) const; - - /// @brief check whether this edge has extra lanes on the right side - int addedLanesRight(NBEdge* out, int addedLanes) const; - -private: - /// @brief The position the node lies at - Position myPosition; - - /// @brief Vector of incoming edges - EdgeVector myIncomingEdges; - - /// @brief Vector of outgoing edges - EdgeVector myOutgoingEdges; - - /// @brief Vector of incoming and outgoing edges - EdgeVector myAllEdges; - - /// @brief Vector of crossings - std::vector > myCrossings; - - /// @brief Vector of walking areas - std::vector myWalkingAreas; - - /// @brief Vector of custom walking areas shapes - std::vector myWalkingAreaCustomShapes; - - /// @brief The type of the junction - SumoXMLNodeType myType; - - /// @brief The container for connection block dependencies - NBConnectionProhibits myBlockedConnections; - - /// @brief The district the node is the centre of - NBDistrict* myDistrict; - - /// @brief the (outer) shape of the junction - PositionVector myPoly; - - /// @brief whether this nodes shape was set by the user - bool myHaveCustomPoly; - - /// @brief Node requests - NBRequest* myRequest; - - /// @brief traffic lights of node - std::set myTrafficLights; - - /// @brief the turning radius (for all corners) at this node in m. - double myRadius; - - /// @brief whether the junction area must be kept clear - bool myKeepClear; - - /// @brief how to compute right of way for this node - RightOfWay myRightOfWay; - - /// @brief fringe type of this node - FringeType myFringeType; - - /// @brief The intersection name (or whatever arbitrary string you wish to attach) - std::string myName; - - /// @brief whether to discard all pedestrian crossings - bool myDiscardAllCrossings; - - /// @brief number of crossings loaded from a sumo net - int myCrossingsLoadedFromSumoNet; - - /// @brief geometry error after computation of internal lane shapes - double myDisplacementError; - - /* @brief whether this junction is a bent priority junction (main direction turns) - * @note see NBEdgePriorityComputer - */ - bool myIsBentPriority; - - /// @brief whether the node type was guessed rather than loaded - bool myTypeWasGuessed; - -private: - /// @brief invalidated copy constructor - NBNode(const NBNode& s); - - /// @brief invalidated assignment operator - NBNode& operator=(const NBNode& s); -}; diff --git a/Util/OSM2ODR/src/netbuild/NBNodeCont.cpp b/Util/OSM2ODR/src/netbuild/NBNodeCont.cpp deleted file mode 100644 index 8ed71a80f..000000000 --- a/Util/OSM2ODR/src/netbuild/NBNodeCont.cpp +++ /dev/null @@ -1,2439 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NBNodeCont.cpp -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Yun-Pang Floetteroed -/// @author Walter Bamberger -/// @author Laura Bieker -/// @author Michael Behrisch -/// @author Sascha Krieg -/// @date Tue, 20 Nov 2001 -/// -// Container for nodes during the netbuilding process -/****************************************************************************/ -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "NBHelpers.h" -#include "NBAlgorithms.h" -#include "NBDistrict.h" -#include "NBEdgeCont.h" -#include "NBTrafficLightLogicCont.h" -#include "NBOwnTLDef.h" -#include "NBNodeCont.h" -#include "NBPTStopCont.h" -#include "NBPTLineCont.h" -#include "NBParking.h" - -// =========================================================================== -// Algorithm constants -// =========================================================================== -#define MAX_SLIPLANE_LENGTH 1000 - -// =========================================================================== -// Debug Flags -// =========================================================================== - -//#define DEBUG_JOINJUNCTIONS -//#define DEBUG_GUESSSIGNALS -#define DEBUGNODEID "3513423881" -#define DEBUGNODEID2 "" -//#define DEBUGNODEID "5548037023" -#define DEBUGCOND(obj) ((obj) != 0 && ((obj)->getID() == DEBUGNODEID || (obj)->getID() == DEBUGNODEID2)) -//#define DEBUGCOND(obj) (true) - - -// =========================================================================== -// method definitions -// =========================================================================== -NBNodeCont::NBNodeCont() - : myInternalID(1) { -} - - -NBNodeCont::~NBNodeCont() { - clear(); -} - - -// ----------- Insertion/removal/retrieval of nodes -bool -NBNodeCont::insert(const std::string& id, const Position& position, - NBDistrict* district) { - NodeCont::iterator i = myNodes.find(id); - if (i != myNodes.end()) { - return false; - } - NBNode* node = new NBNode(id, position, district); - myNodes[id] = node; - const float pos[2] = {(float)position.x(), (float)position.y()}; - myRTree.Insert(pos, pos, node); - return true; -} - - -bool -NBNodeCont::insert(NBNode* node) { - std::string id = node->getID(); - NodeCont::iterator i = myNodes.find(id); - if (i != myNodes.end()) { - return false; - } - myNodes[id] = node; - const float pos[2] = {(float)node->getPosition().x(), (float)node->getPosition().y()}; - myRTree.Insert(pos, pos, node); - return true; -} - - -NBNode* -NBNodeCont::retrieve(const std::string& id) const { - NodeCont::const_iterator i = myNodes.find(id); - if (i == myNodes.end()) { - return nullptr; - } - return (*i).second; -} - - -NBNode* -NBNodeCont::retrieve(const Position& position, const double offset) const { - const double extOffset = offset + POSITION_EPS; - const float cmin[2] = {(float)(position.x() - extOffset), (float)(position.y() - extOffset)}; - const float cmax[2] = {(float)(position.x() + extOffset), (float)(position.y() + extOffset)}; - std::set into; - Named::StoringVisitor sv(into); - myRTree.Search(cmin, cmax, sv); - for (const Named* namedNode : into) { - NBNode* node = const_cast(dynamic_cast(namedNode)); - if (fabs(node->getPosition().x() - position.x()) <= offset - && - fabs(node->getPosition().y() - position.y()) <= offset) { - return node; - } - } - return nullptr; -} - - -bool -NBNodeCont::erase(NBNode* node) { - if (extract(node)) { - delete node; - return true; - } else { - return false; - } -} - - -bool -NBNodeCont::extract(NBNode* node, bool remember) { - NodeCont::iterator i = myNodes.find(node->getID()); - if (i == myNodes.end()) { - return false; - } - myNodes.erase(i); - const float pos[2] = {(float)node->getPosition().x(), (float)node->getPosition().y()}; - myRTree.Remove(pos, pos, node); - node->removeTrafficLights(); - if (remember) { - myExtractedNodes[node->getID()] = node; - } - return true; -} - - -// ----------- Adapting the input -void -NBNodeCont::removeSelfLoops(NBDistrictCont& dc, NBEdgeCont& ec, NBTrafficLightLogicCont& tc) { - int no = 0; - for (NodeCont::iterator i = myNodes.begin(); i != myNodes.end(); i++) { - no += (*i).second->removeSelfLoops(dc, ec, tc); - } - if (no != 0) { - WRITE_WARNING(toString(no) + " self-looping edge(s) removed."); - } -} - - -void -NBNodeCont::joinSimilarEdges(NBDistrictCont& dc, NBEdgeCont& ec, NBTrafficLightLogicCont& tlc) { - // magic values - const double distanceThreshold = 7.; // don't merge edges further apart - const double lengthThreshold = 0.10; // don't merge edges with higher relative length-difference - - for (NodeCont::iterator i = myNodes.begin(); i != myNodes.end(); i++) { - // count the edges to other nodes outgoing from the current node - std::map connectionCount; - const EdgeVector& outgoing = (*i).second->getOutgoingEdges(); - for (EdgeVector::const_iterator j = outgoing.begin(); j != outgoing.end(); j++) { - connectionCount[(*j)->getToNode()].push_back(*j); - } - // check whether more than a single edge connect another node and join them - std::map::iterator k; - for (k = connectionCount.begin(); k != connectionCount.end(); k++) { - // possibly we do not have anything to join... - if ((*k).second.size() < 2) { - continue; - } - // for the edges that seem to be a single street, - // check whether the geometry is similar - const EdgeVector& ev = (*k).second; - const NBEdge* const first = ev.front(); - EdgeVector::const_iterator jci; // join candidate iterator - for (jci = ev.begin() + 1; jci != ev.end(); ++jci) { - const double relativeLengthDifference = fabs(first->getLoadedLength() - (*jci)->getLoadedLength()) / first->getLoadedLength(); - if ((!first->isNearEnough2BeJoined2(*jci, distanceThreshold)) || - (relativeLengthDifference > lengthThreshold) || - (fabs(first->getSpeed() - (*jci)->getSpeed()) >= 0.01) || // output accuracy - (first->getPermissions() != (*jci)->getPermissions()) - ) { - break; - } - } - // @bug If there are 3 edges of which 2 can be joined, no joining will - // take place with the current implementation - if (jci == ev.end()) { - ec.joinSameNodeConnectingEdges(dc, tlc, ev); - } - } - } -} - - -void -NBNodeCont::removeIsolatedRoads(NBDistrictCont& dc, NBEdgeCont& ec) { - // Warn of isolated edges, i.e. a single edge with no connection to another edge - const std::vector& edgeNames = ec.getAllNames(); - for (std::vector::const_iterator it = edgeNames.begin(); it != edgeNames.end(); ++it) { - // Test whether this node starts at a dead end, i.e. it has only one adjacent node - // to which an edge exists and from which an edge may come. - NBEdge* e = ec.retrieve(*it); - if (e == nullptr) { - continue; - } - NBNode* from = e->getFromNode(); - const EdgeVector& outgoingEdges = from->getOutgoingEdges(); - if (outgoingEdges.size() != 1) { - // At this node, several edges or no edge start; so, this node is no dead end. - continue; - } - const EdgeVector& incomingEdges = from->getIncomingEdges(); - if (incomingEdges.size() > 1) { - // At this node, several edges end; so, this node is no dead end. - continue; - } else if (incomingEdges.size() == 1) { - NBNode* fromNodeOfIncomingEdge = incomingEdges[0]->getFromNode(); - NBNode* toNodeOfOutgoingEdge = outgoingEdges[0]->getToNode(); - if (fromNodeOfIncomingEdge != toNodeOfOutgoingEdge) { - // At this node, an edge ends which is not the inverse direction of - // the starting node. - continue; - } - } - // Now we know that the edge e starts a dead end. - // Next we test if the dead end is isolated, i.e. does not lead to a junction - bool hasJunction = false; - EdgeVector road; - NBEdge* eOld = nullptr; - NBNode* to; - NodeSet adjacentNodes; - do { - road.push_back(e); - eOld = e; - from = e->getFromNode(); - to = e->getToNode(); - const EdgeVector& outgoingEdgesOfToNode = to->getOutgoingEdges(); - const EdgeVector& incomingEdgesOfToNode = to->getIncomingEdges(); - adjacentNodes.clear(); - for (EdgeVector::const_iterator itOfOutgoings = outgoingEdgesOfToNode.begin(); itOfOutgoings != outgoingEdgesOfToNode.end(); ++itOfOutgoings) { - if ((*itOfOutgoings)->getToNode() != from // The back path - && (*itOfOutgoings)->getToNode() != to // A loop / dummy edge - ) { - e = *itOfOutgoings; // Probably the next edge - } - adjacentNodes.insert((*itOfOutgoings)->getToNode()); - } - for (EdgeVector::const_iterator itOfIncomings = incomingEdgesOfToNode.begin(); itOfIncomings != incomingEdgesOfToNode.end(); ++itOfIncomings) { - adjacentNodes.insert((*itOfIncomings)->getFromNode()); - } - adjacentNodes.erase(to); // Omit loops - if (adjacentNodes.size() > 2) { - hasJunction = true; - } - } while (!hasJunction && eOld != e); - if (!hasJunction) { - std::string warningString; - for (EdgeVector::iterator roadIt = road.begin(); roadIt != road.end(); ++roadIt) { - if (roadIt == road.begin()) { - warningString += (*roadIt)->getID(); - } else { - warningString += "," + (*roadIt)->getID(); - } - - NBNode* fromNode = (*roadIt)->getFromNode(); - NBNode* toNode = (*roadIt)->getToNode(); - ec.erase(dc, *roadIt); - if (fromNode->getIncomingEdges().size() == 0 && fromNode->getOutgoingEdges().size() == 0) { - // Node is empty; can be removed - erase(fromNode); - } - if (toNode->getIncomingEdges().size() == 0 && toNode->getOutgoingEdges().size() == 0) { - // Node is empty; can be removed - erase(toNode); - } - } - WRITE_WARNINGF("Removed a road without junctions: %.", warningString); - } - } -} - - -void -NBNodeCont::removeComponents(NBDistrictCont& dc, NBEdgeCont& ec, const int numKeep) { - std::vector > components; - // need to use ids here to have the same ordering on all platforms - std::set edgesLeft; - for (std::map::const_iterator edgeIt = ec.begin(); edgeIt != ec.end(); ++edgeIt) { - edgesLeft.insert(edgeIt->first); - } - EdgeVector queue; - std::set toRemove; - while (!edgesLeft.empty()) { - queue.push_back(ec.getByID(*edgesLeft.begin())); - std::set component; - while (!queue.empty()) { - NBEdge* const e = queue.back(); - queue.pop_back(); - component.insert(e); - std::vector edgeLists; - edgeLists.push_back(e->getFromNode()->getOutgoingEdges()); - edgeLists.push_back(e->getFromNode()->getIncomingEdges()); - edgeLists.push_back(e->getToNode()->getOutgoingEdges()); - edgeLists.push_back(e->getToNode()->getIncomingEdges()); - for (std::vector::const_iterator listIt = edgeLists.begin(); listIt != edgeLists.end(); ++listIt) { - for (EdgeVector::const_iterator edgeIt = listIt->begin(); edgeIt != listIt->end(); ++edgeIt) { - std::set::iterator leftIt = edgesLeft.find((*edgeIt)->getID()); - if (leftIt != edgesLeft.end()) { - queue.push_back(*edgeIt); - edgesLeft.erase(leftIt); - } - } - } - } - std::vector >::iterator cIt; - for (cIt = components.begin(); cIt != components.end(); ++cIt) { - if (cIt->size() < component.size()) { - break; - } - } - components.insert(cIt, component); - if ((int)components.size() > numKeep) { - toRemove.insert(components.back().begin(), components.back().end()); - components.pop_back(); - } - } - for (std::set::iterator edgeIt = toRemove.begin(); edgeIt != toRemove.end(); ++edgeIt) { - NBNode* const fromNode = (*edgeIt)->getFromNode(); - NBNode* const toNode = (*edgeIt)->getToNode(); - ec.erase(dc, *edgeIt); - if (fromNode->getIncomingEdges().size() == 0 && fromNode->getOutgoingEdges().size() == 0) { - erase(fromNode); - } - if (toNode->getIncomingEdges().size() == 0 && toNode->getOutgoingEdges().size() == 0) { - erase(toNode); - } - } -} - - -int -NBNodeCont::removeUnwishedNodes(NBDistrictCont& dc, NBEdgeCont& ec, - NBTrafficLightLogicCont& tlc, NBPTStopCont& sc, NBPTLineCont& lc, - NBParkingCont& pc, - bool removeGeometryNodes) { - // load edges that shall not be modified - std::set edges2keep; - if (removeGeometryNodes) { - const OptionsCont& oc = OptionsCont::getOptions(); - if (oc.isSet("geometry.remove.keep-edges.input-file")) { - NBHelpers::loadEdgesFromFile(oc.getString("geometry.remove.keep-edges.input-file"), edges2keep); - } - if (oc.isSet("geometry.remove.keep-edges.explicit")) { - const std::vector edges = oc.getStringVector("geometry.remove.keep-edges.explicit"); - edges2keep.insert(edges.begin(), edges.end()); - } - sc.addEdges2Keep(oc, edges2keep); - UNUSED_PARAMETER(lc); // no need to keep all route edges. They are validated again before writing - pc.addEdges2Keep(oc, edges2keep); - } - int no = 0; - std::vector toRemove; - for (NodeCont::iterator i = myNodes.begin(); i != myNodes.end(); i++) { - NBNode* current = (*i).second; - bool remove = false; - std::vector > toJoin; - // check for completely empty nodes - if (current->getOutgoingEdges().size() == 0 && current->getIncomingEdges().size() == 0) { - // remove if empty - remove = true; - } - // check for nodes which are only geometry nodes - if (removeGeometryNodes && mySplit.count(current) == 0) { - if ((current->getOutgoingEdges().size() == 1 && current->getIncomingEdges().size() == 1) - || - (current->getOutgoingEdges().size() == 2 && current->getIncomingEdges().size() == 2)) { - // ok, one in, one out or two in, two out - // -> ask the node whether to join - remove = current->checkIsRemovable(); - // check whether any of the edges must be kept - for (EdgeVector::const_iterator it_edge = current->getEdges().begin(); it_edge != current->getEdges().end(); ++it_edge) { - if (edges2keep.find((*it_edge)->getID()) != edges2keep.end()) { - remove = false; - break; - } - } - if (remove) { - toJoin = current->getEdgesToJoin(); - } - } - } - // remove the node and join the geometries when wished - if (!remove) { - continue; - } - for (std::vector >::iterator j = toJoin.begin(); j != toJoin.end(); j++) { - NBEdge* begin = (*j).first; - NBEdge* continuation = (*j).second; - begin->append(continuation); - continuation->getToNode()->replaceIncoming(continuation, begin, 0); - tlc.replaceRemoved(continuation, -1, begin, -1, true); - ec.extract(dc, continuation, true); - } - toRemove.push_back(current); - no++; - } - // erase all - for (std::vector::iterator j = toRemove.begin(); j != toRemove.end(); ++j) { - extract(*j, true); - } - return no; -} - - -void -NBNodeCont::avoidOverlap() { - for (NodeCont::iterator i = myNodes.begin(); i != myNodes.end(); i++) { - (*i).second->avoidOverlap(); - } -} - -// ----------- (Helper) methods for joining nodes -void -NBNodeCont::generateNodeClusters(double maxDist, NodeClusters& into) const { - std::set visited; - for (NodeCont::const_iterator i = myNodes.begin(); i != myNodes.end(); i++) { - std::vector toProc; - if (visited.find((*i).second) != visited.end()) { - continue; - } - toProc.push_back(std::make_pair((*i).second, 0)); - NodeSet c; - while (!toProc.empty()) { - NodeAndDist nodeAndDist = toProc.back(); - NBNode* n = nodeAndDist.first; - double dist = nodeAndDist.second; - toProc.pop_back(); - if (visited.find(n) != visited.end()) { - continue; - } - visited.insert(n); - bool pureRail = true; - bool railAndPeds = true; - for (NBEdge* e : n->getEdges()) { - if ((e->getPermissions() & ~(SVC_RAIL_CLASSES | SVC_PEDESTRIAN)) != 0) { - railAndPeds = false; - pureRail = false; - break; - } - if ((e->getPermissions() & ~(SVC_RAIL_CLASSES)) != 0) { - pureRail = false; - } - } - if (pureRail) { - // do not join pure rail nodes - continue; - } - c.insert(n); - for (NBEdge* e : n->getEdges()) { - NBNode* s = n->hasIncoming(e) ? e->getFromNode() : e->getToNode(); - const double length = e->getLoadedLength(); -#ifdef DEBUG_JOINJUNCTIONS - if (DEBUGCOND(s)) { - std::cout << "generateNodeClusters: consider s=" << s->getID() - << " clusterNode=" << n->getID() << " edge=" << e->getID() << " length=" << length << " with cluster " << joinNamedToString(c, ' ') << "\n"; - } -#endif - if (railAndPeds && n->getType() != SumoXMLNodeType::RAIL_CROSSING) { - bool railAndPeds2 = true; - for (NBEdge* e : n->getEdges()) { - if ((e->getPermissions() & ~(SVC_RAIL_CLASSES | SVC_PEDESTRIAN)) != 0) { - railAndPeds2 = false; - break; - } - } - if (railAndPeds2 && s->getType() != SumoXMLNodeType::RAIL_CROSSING) { - // do not join rail/ped nodes unless at a rail crossing - // (neither nodes nor the traffic lights) - continue; - } - } - const bool bothCrossing = n->getType() == SumoXMLNodeType::RAIL_CROSSING && s->getType() == SumoXMLNodeType::RAIL_CROSSING; - const bool joinPedCrossings = bothCrossing && e->getPermissions() == SVC_PEDESTRIAN; - if ( // never join pedestrian stuff (unless at a rail crossing - !joinPedCrossings && ( - e->getPermissions() == SVC_PEDESTRIAN - // only join edges for regular passenger traffic or edges that are extremely short - || (length > 3 * POSITION_EPS - && (e->getPermissions() & (SVC_PASSENGER | SVC_TRAM)) == 0 - && n->getPosition().distanceTo2D(s->getPosition()) > SUMO_const_laneWidth))) { - continue; - } - // never join rail_crossings with other node types unless the crossing is only for tram - if ((n->getType() == SumoXMLNodeType::RAIL_CROSSING && s->getType() != SumoXMLNodeType::RAIL_CROSSING) - || (n->getType() != SumoXMLNodeType::RAIL_CROSSING && s->getType() == SumoXMLNodeType::RAIL_CROSSING)) { - const SVCPermissions railNoTram = (SVC_RAIL_CLASSES & ~SVC_TRAM); - bool foundRail = false; - NBNode* crossingNode = n->getType() == SumoXMLNodeType::RAIL_CROSSING ? n : s; - for (NBEdge* e2 : crossingNode->getIncomingEdges()) { - if ((e2->getPermissions() & railNoTram) != 0) { - foundRail = true; - break; - } - } - if (foundRail) { - continue; - } - } - // never join rail_crossings via a rail edge - if (bothCrossing && (e->getPermissions() & ~SVC_RAIL_CLASSES) == 0) { - continue; - } - if (visited.find(s) != visited.end()) { - continue; - } - if (length + dist < maxDist) { - if (s->geometryLike()) { - toProc.push_back(std::make_pair(s, dist + length)); - } else { - toProc.push_back(std::make_pair(s, 0)); - } - } - } - } - if (c.size() < 2) { - continue; - } -#ifdef DEBUG_JOINJUNCTIONS - std::cout << " DEBUG: consider cluster " << joinNamedToString(c, ' ') << "\n"; -#endif - into.push_back(c); - } -} - - -void -NBNodeCont::addJoinExclusion(const std::vector& ids, bool check) { - for (std::vector::const_iterator it = ids.begin(); it != ids.end(); it++) { - // error handling has to take place here since joinExclusions could be - // loaded from multiple files / command line - if (myJoined.count(*it) > 0) { - WRITE_WARNINGF("Ignoring join exclusion for junction '%' since it already occurred in a list of nodes to be joined.", *it); - } else if (check && retrieve(*it) == nullptr) { - WRITE_WARNINGF("Ignoring join exclusion for unknown junction '%'.", *it); - } else { - myJoinExclusions.insert(*it); - } - } -} - - -void -NBNodeCont::addCluster2Join(std::set cluster, NBNode* node) { - // error handling has to take place here since joins could be loaded from multiple files - std::set validCluster; - for (std::string nodeID : cluster) { - if (myJoinExclusions.count(nodeID) > 0) { - WRITE_WARNINGF("Ignoring join-cluster because junction '%' was already excluded from joining.", nodeID); - return; - } else if (myJoined.count(nodeID) > 0) { - WRITE_WARNINGF("Ignoring join-cluster because junction '%' already occurred in another join-cluster.", nodeID); - return; - } else { - NBNode* const node = retrieve(nodeID); - if (node != nullptr) { - validCluster.insert(nodeID); - } else { - if (StringUtils::startsWith(nodeID, "cluster_")) { - // assume join directive came from a pre-processed network. try to use component IDs - std::set subIDs; - for (std::string nID : StringTokenizer(nodeID.substr(8), "_").getVector()) { - if (retrieve(nID) != nullptr) { - validCluster.insert(nID); - } else { - WRITE_ERROR("Unknown junction '" + nodeID + "' in join-cluster (componentID)."); - } - } - } else { - WRITE_ERROR("Unknown junction '" + nodeID + "' in join-cluster."); - } - } - } - } - if (validCluster.size() > 1) { - myJoined.insert(validCluster.begin(), validCluster.end()); - myClusters2Join.push_back(std::make_pair(validCluster, node)); - } else { - WRITE_WARNINGF("Ignoring join-cluster '%s' because it has size '%'.", node->getID(), validCluster.size()); - } -} - - -int -NBNodeCont::joinLoadedClusters(NBDistrictCont& dc, NBEdgeCont& ec, NBTrafficLightLogicCont& tlc) { - int numJoined = 0; - for (auto& item : myClusters2Join) { - // verify loaded cluster - NodeSet cluster; - for (std::string nodeID : item.first) { - NBNode* node = retrieve(nodeID); - if (node == nullptr) { - WRITE_ERROR("unknown junction '" + nodeID + "' while joining."); - } else { - cluster.insert(node); - } - } - if (cluster.size() > 1) { - joinNodeCluster(cluster, dc, ec, tlc, item.second); - numJoined++; - myJoinExclusions.insert(item.second->getID()); - } - } - myClusters2Join.clear(); // make save for recompute - return numJoined; -} - - -int -NBNodeCont::joinJunctions(double maxDist, NBDistrictCont& dc, NBEdgeCont& ec, NBTrafficLightLogicCont& tlc, NBPTStopCont& sc) { -#ifdef DEBUG_JOINJUNCTIONS - std::cout << "joinJunctions...\n"; -#endif - NodeClusters cands; - NodeClusters clusters; - generateNodeClusters(maxDist, cands); - for (NodeClusters::iterator i = cands.begin(); i != cands.end(); ++i) { - NodeSet cluster = (*i); -#ifdef DEBUG_JOINJUNCTIONS - gDebugFlag1 = false; - for (NBNode* n : cluster) { - if (DEBUGCOND(n)) { - gDebugFlag1 = true; - } - } -#endif - // remove join exclusions - for (NodeSet::iterator j = cluster.begin(); j != cluster.end();) { - NodeSet::iterator check = j; - ++j; - if (myJoinExclusions.count((*check)->getID()) > 0) { - cluster.erase(check); - } - } - // remove nodes that can be eliminated by geometry.remove - pruneClusterFringe(cluster); - // avoid removal of long edges (must have been added via an alternative path). - pruneLongEdges(cluster, maxDist); - // remove nodes that are part of a bypass lane (typically for turning right without waiting at a traffic light) - pruneSlipLaneNodes(cluster); - if (cluster.size() < 2) { - continue; - } - std::string reason; - std::string origReason; - std::string origCluster; - bool feasible = feasibleCluster(cluster, ec, sc, origReason); - if (!feasible) { -#ifdef DEBUG_JOINJUNCTIONS - if (gDebugFlag1) { - std::cout << " try to reduce to 4-circle nodes=" << joinNamedToString(cluster, ',') << "\n"; - } -#endif - origCluster = joinNamedToString(cluster, ','); - if (reduceToCircle(cluster, 4, cluster)) { - feasible = feasibleCluster(cluster, ec, sc, reason); - if (feasible) { - WRITE_WARNINGF("Reducing junction cluster % (%).", origCluster, origReason); - } - } - } - if (!feasible) { -#ifdef DEBUG_JOINJUNCTIONS - if (gDebugFlag1) { - std::cout << " try to reduce to 2-circle nodes=" << joinNamedToString(cluster, ',') << "\n"; - } -#endif - origCluster = joinNamedToString(cluster, ','); - if (reduceToCircle(cluster, 2, cluster)) { - feasible = feasibleCluster(cluster, ec, sc, reason); - if (feasible) { - WRITE_WARNINGF("Reducing junction cluster % (%).", origCluster, origReason); - } - } - } - if (!feasible) { - WRITE_WARNINGF("Not joining junctions % (%).", origCluster, origReason); - continue; - } - // compute all connected components of this cluster - // (may be more than 1 if intermediate nodes were removed) - NodeClusters components; - for (NBNode* current : cluster) { - // merge all connected components into newComp - NodeSet newComp; - //std::cout << "checking connectivity for " << current->getID() << "\n"; - newComp.insert(current); - for (NodeClusters::iterator it_comp = components.begin(); it_comp != components.end();) { - NodeClusters::iterator check = it_comp; - //std::cout << " connected with " << toString(*check) << "?\n"; - bool connected = false; - for (NBNode* k : *check) { - if (current->getConnectionTo(k) != nullptr || k->getConnectionTo(current) != nullptr) { - //std::cout << "joining with connected component " << toString(*check) << "\n"; - newComp.insert((*check).begin(), (*check).end()); - it_comp = components.erase(check); - connected = true; - break; - } - } - if (!connected) { - it_comp++; - } - } - //std::cout << "adding new component " << toString(newComp) << "\n"; - components.push_back(newComp); - } - for (NodeClusters::iterator it_comp = components.begin(); it_comp != components.end(); ++it_comp) { - if ((*it_comp).size() > 1) { - //std::cout << "adding cluster " << toString(*it_comp) << "\n"; - clusters.push_back(*it_comp); - } - } -#ifdef DEBUG_JOINJUNCTIONS - gDebugFlag1 = false; -#endif - } - joinNodeClusters(clusters, dc, ec, tlc); - return (int)clusters.size(); -} - - -void -NBNodeCont::pruneClusterFringe(NodeSet& cluster) const { -#ifdef DEBUG_JOINJUNCTIONS - if (gDebugFlag1) { - std::cout << "pruning cluster=" << joinNamedToString(cluster, ' ') << "\n"; - } -#endif - // iteratively remove the fringe - bool pruneFringe = true; - // collect nodes that shall be joined due to distance but are not connected - // to the cluster for passenger traffic - while (pruneFringe) { - pruneFringe = false; - for (NodeSet::iterator j = cluster.begin(); j != cluster.end();) { - NodeSet::iterator check = j; - NBNode* n = *check; - ++j; - - // compute clusterDist for node (length of shortest edge which connects this node to the cluster) - double clusterDist = std::numeric_limits::max(); - bool touchingCluster = false; - for (EdgeVector::const_iterator it_edge = n->getOutgoingEdges().begin(); it_edge != n->getOutgoingEdges().end(); ++it_edge) { - NBNode* neighbor = (*it_edge)->getToNode(); - if (cluster.count(neighbor) != 0) { - clusterDist = MIN2(clusterDist, (*it_edge)->getLoadedLength()); - touchingCluster |= n->getPosition().distanceTo2D(neighbor->getPosition()) <= SUMO_const_laneWidth; - } - } - for (EdgeVector::const_iterator it_edge = n->getIncomingEdges().begin(); it_edge != n->getIncomingEdges().end(); ++it_edge) { - NBNode* neighbor = (*it_edge)->getFromNode(); - if (cluster.count(neighbor) != 0) { - clusterDist = MIN2(clusterDist, (*it_edge)->getLoadedLength()); - touchingCluster |= n->getPosition().distanceTo2D(neighbor->getPosition()) <= SUMO_const_laneWidth; - } - } - // remove geometry-like nodes at fringe of the cluster - // (they have 1 neighbor in the cluster and at most 1 neighbor outside the cluster) - std::set outsideNeighbors; - std::set clusterNeighbors; - const double pedestrianFringeThreshold = 0.3; - for (NBEdge* e : n->getEdges()) { - NBNode* neighbor = e->getFromNode() == n ? e->getToNode() : e->getFromNode(); - if (cluster.count(neighbor) == 0) { - if ((e->getPermissions() & SVC_PASSENGER) != 0 - || isRailway(e->getPermissions()) // join railway crossings - || clusterDist <= pedestrianFringeThreshold - || touchingCluster) { - outsideNeighbors.insert(neighbor); - } - } else { - clusterNeighbors.insert(neighbor); - } - } -#ifdef DEBUG_JOINJUNCTIONS - if (gDebugFlag1) std::cout << " check n=" << n->getID() - << " clusterDist=" << clusterDist - << " cdisTLControlled())) { - cluster.erase(check); - pruneFringe = true; // other nodes could belong to the fringe now -#ifdef DEBUG_JOINJUNCTIONS - if (gDebugFlag1) { - std::cout << " pruned n=" << n->getID() << "\n"; - } -#endif - } - } - } -} - - -void -NBNodeCont::pruneLongEdges(NodeSet& cluster, double maxDist) { - std::set toRemove; - int maxPassengerLanes = 0; - for (NBNode* n : cluster) { - for (NBEdge* edge : n->getEdges()) { - maxPassengerLanes = MAX2(maxPassengerLanes, edge->getNumLanesThatAllow(SVC_PASSENGER)); - } - } - for (NBNode* n : cluster) { - for (NBEdge* edge : n->getOutgoingEdges()) { - // we must track the edge length accross geometry like nodes - // Also, intersecions that are geometry-like - // from the perspective of passenger traffic should be tracked accross - std::vector passed; - double length = 0; - NBEdge* cur = edge; - NBNode* to = edge->getToNode(); - while (cluster.count(to) != 0) { - length += cur->getLoadedLength(); - bool goStraight = (std::find(passed.begin(), passed.end(), to) == passed.end() - && (edge->getPermissions() & SVC_PASSENGER) != 0 - && to->geometryLike( - NBEdge::filterByPermissions(to->getIncomingEdges(), SVC_PASSENGER), - NBEdge::filterByPermissions(to->getOutgoingEdges(), SVC_PASSENGER))); - passed.push_back(to); - if (goStraight) { - cur = cur->getStraightContinuation(SVC_PASSENGER); - if (cur != nullptr) { - to = cur->getToNode(); - } else { - break; - } - } else { - break; - } - } - // allow higher threshold at larger junctions - double longThreshold = maxDist + SUMO_const_laneWidth * MAX2(0, maxPassengerLanes - 1); -#ifdef DEBUG_JOINJUNCTIONS - if (gDebugFlag1) { - std::cout << "check edge length " << edge->getID() << " (" << length << ", passed=" << passed.size() << ", max=" << longThreshold << ")\n"; - } -#endif - if (length > longThreshold) { - // we found an edge that should not be removed. Maybe we can - // still keep the start or end in the cluster - // (keep the start if the end can be removed and vice versa) - const bool keepStart = getClusterNeighbors(passed.back(), cluster).size() == 1; - const bool keepEnd = !keepStart && getClusterNeighbors(n, cluster).size() == 1; -#ifdef DEBUG_JOINJUNCTIONS - if (gDebugFlag1) { - std::cout << "node=" << n->getID() << " long edge " << edge->getID() << " (" << length << ", passed=" << toString(passed) << ", max=" << longThreshold << ") keepStart=" << keepStart << " keepEnd=" << keepEnd << "\n"; - } -#endif - if (!keepStart) { - toRemove.insert(n); - } - toRemove.insert(passed.begin(), passed.end() - 1); - if (!keepEnd) { - toRemove.insert(passed.back()); - } - - } - } - } - for (std::set::iterator j = toRemove.begin(); j != toRemove.end(); ++j) { - cluster.erase(*j); - } -} - - -NodeSet -NBNodeCont::getClusterNeighbors(const NBNode* n, NodeSet& cluster) { - NodeSet result; - for (NBEdge* e : n->getEdges()) { - NBNode* neighbor = e->getFromNode() == n ? e->getToNode() : e->getFromNode(); - if (cluster.count(neighbor) != 0) { - result.insert(neighbor); - } - } - return result; -} - - -void -NBNodeCont::pruneSlipLaneNodes(NodeSet& cluster) const { -#ifdef DEBUG_JOINJUNCTIONS - if (gDebugFlag1) { - std::cout << "pruning slip-lanes at cluster=" << joinNamedToString(cluster, ' ') << "\n"; - } -#endif - // fringe has already been removed - if (cluster.size() <= 2) { - return; - } - NodeSet toRemove; - for (NBNode* n : cluster) { - EdgeVector outgoing; - double inAngle; - // find slip lanes where the start is part of the cluster - if (maybeSlipLaneStart(n, outgoing, inAngle)) { - // potential slip lane start but we don't know which of the outgoing edges it is -#ifdef DEBUG_JOINJUNCTIONS - if (gDebugFlag1) { - std::cout << " candidate slip-lane start=" << n->getID() << " outgoing=" << toString(outgoing) << "\n"; - } -#endif - for (NBEdge* contEdge : outgoing) { - if ((contEdge->getPermissions() & SVC_PASSENGER) == 0) { - continue; - } - double slipLength = contEdge->getLength(); - NBNode* cont = contEdge->getToNode(); - NodeSet cands; - cands.insert(n); - while (cont->getIncomingEdges().size() == 1 && cont->getOutgoingEdges().size() == 1 && slipLength < MAX_SLIPLANE_LENGTH) { - if (cands.count(cont) != 0) { - break; // circle, should not happen - } - cands.insert(cont); -#ifdef DEBUG_JOINJUNCTIONS - if (gDebugFlag1) { - std::cout << " candidate slip-lane cont=" << cont->getID() << "\n"; - } -#endif - NBEdge* next = cont->getOutgoingEdges().front(); - slipLength += next->getLength(); - cont = next->getToNode(); - } -#ifdef DEBUG_JOINJUNCTIONS - if (gDebugFlag1) { - std::cout << " candidate slip-lane end=" << cont->getID() << " slipLength=" << slipLength << "\n"; - } -#endif - if (cont->getIncomingEdges().size() >= 2 && cont->getOutgoingEdges().size() == 1 && - // slip lanes are for turning so there needs to be a sufficient angle - abs(NBHelpers::relAngle(inAngle, cont->getOutgoingEdges().front()->getAngleAtNode(cont))) > 45) { - // check whether the other continuation at n is also connected to the sliplane end - NBEdge* otherEdge = (contEdge == outgoing.front() ? outgoing.back() : outgoing.front()); - double otherLength = otherEdge->getLength(); - NBNode* cont2 = otherEdge->getToNode(); - - NodeSet visited; - visited.insert(n); - std::vector toProc; - toProc.push_back(std::make_pair(cont2, otherLength)); - bool found = false; - while (!toProc.empty()) { - NodeAndDist nodeAndDist = toProc.back(); - NBNode* cont2 = nodeAndDist.first; - double dist = nodeAndDist.second; -#ifdef DEBUG_JOINJUNCTIONS - if (gDebugFlag1) { - std::cout << " search alternative cont2=" << cont2->getID() << " dist=" << dist << "\n"; - } -#endif - toProc.pop_back(); - if (visited.find(cont2) != visited.end()) { - continue; - } - visited.insert(cont2); - if (cont2 == cont) { - found = true; - break; - } - for (NBEdge* e : cont2->getOutgoingEdges()) { - const double dist2 = dist + e->getLength(); - if (dist2 < slipLength * 2 && (e->getPermissions() & SVC_PASSENGER) != 0) { - toProc.push_back(std::make_pair(e->getToNode(), dist2)); - } - } - } - if (found) { - // found slip lane - cands.insert(cont); - toRemove.insert(cands.begin(), cands.end()); -#ifdef DEBUG_JOINJUNCTIONS - if (gDebugFlag1) { - std::cout << " found slip-lane with nodes=" << joinNamedToString(cands, ' ') << "\n"; - } -#endif - } - } - } - } - - EdgeVector incoming; - double outAngle; - // find slip lanes where the end is part of the cluster - if (maybeSlipLaneEnd(n, incoming, outAngle)) { - // potential slip lane end but we don't know which of the incoming edges it is -#ifdef DEBUG_JOINJUNCTIONS - if (gDebugFlag1) { - std::cout << " candidate slip-lane end=" << n->getID() << " incoming=" << toString(incoming) << "\n"; - } -#endif - for (NBEdge* contEdge : incoming) { - if ((contEdge->getPermissions() & SVC_PASSENGER) == 0) { - continue; - } - double slipLength = contEdge->getLength(); - NBNode* cont = contEdge->getFromNode(); - NodeSet cands; - cands.insert(n); - while (cont->getIncomingEdges().size() == 1 && cont->getOutgoingEdges().size() == 1 && slipLength < MAX_SLIPLANE_LENGTH) { - if (cands.count(cont) != 0) { - break; // circle, should not happen - } - cands.insert(cont); -#ifdef DEBUG_JOINJUNCTIONS - if (gDebugFlag1) { - std::cout << " candidate slip-lane cont=" << cont->getID() << "\n"; - } -#endif - NBEdge* next = cont->getIncomingEdges().front(); - slipLength += next->getLength(); - cont = next->getFromNode(); - } -#ifdef DEBUG_JOINJUNCTIONS - if (gDebugFlag1) { - std::cout << " candidate slip-lane start=" << cont->getID() << " slipLength=" << slipLength << "\n"; - } -#endif - if (cont->getOutgoingEdges().size() >= 2 && cont->getIncomingEdges().size() == 1 && - // slip lanes are for turning so there needs to be a sufficient angle - abs(NBHelpers::relAngle(outAngle, cont->getIncomingEdges().front()->getAngleAtNode(cont))) > 45) { - // check whether the other continuation at n is also connected to the sliplane end - NBEdge* otherEdge = (contEdge == incoming.front() ? incoming.back() : incoming.front()); - double otherLength = otherEdge->getLength(); - NBNode* cont2 = otherEdge->getFromNode(); - - NodeSet visited; - visited.insert(n); - std::vector toProc; - toProc.push_back(std::make_pair(cont2, otherLength)); - bool found = false; - while (!toProc.empty()) { - NodeAndDist nodeAndDist = toProc.back(); - NBNode* cont2 = nodeAndDist.first; - double dist = nodeAndDist.second; -#ifdef DEBUG_JOINJUNCTIONS - if (gDebugFlag1) { - std::cout << " search alternative cont2=" << cont2->getID() << " dist=" << dist << "\n"; - } -#endif - toProc.pop_back(); - if (visited.find(cont2) != visited.end()) { - continue; - } - visited.insert(cont2); - if (cont2 == cont) { - found = true; - break; - } - for (NBEdge* e : cont2->getIncomingEdges()) { - const double dist2 = dist + e->getLength(); - if (dist2 < slipLength * 2 && (e->getPermissions() & SVC_PASSENGER) != 0) { - toProc.push_back(std::make_pair(e->getFromNode(), dist2)); - } - } - } - if (found) { - // found slip lane - cands.insert(cont); - toRemove.insert(cands.begin(), cands.end()); -#ifdef DEBUG_JOINJUNCTIONS - if (gDebugFlag1) { - std::cout << " found slip-lane start with nodes=" << joinNamedToString(cands, ' ') << "\n"; - } -#endif - } - } - } - } - - - - } - int numRemoved = 0; - for (NBNode* n : toRemove) { - numRemoved += (int)cluster.erase(n); - } - if (numRemoved > 0) { -#ifdef DEBUG_JOINJUNCTIONS - if (gDebugFlag1) { - std::cout << " removed " << numRemoved << " nodes from cluster: " << joinNamedToString(toRemove, ' ') << "\n"; - } -#endif - pruneClusterFringe(cluster); - } -} - - -bool -NBNodeCont::maybeSlipLaneStart(const NBNode* n, EdgeVector& outgoing, double& inAngle) const { - if (n->getIncomingEdges().size() == 1 && n->getOutgoingEdges().size() == 2) { - outgoing.insert(outgoing.begin(), n->getOutgoingEdges().begin(), n->getOutgoingEdges().end()); - inAngle = n->getIncomingEdges().front()->getAngleAtNode(n); - return true; - } else if (n->getIncomingEdges().size() >= 2 && n->getOutgoingEdges().size() == 3) { - // check if the incoming edges are going in opposite directions and then - // use the incoming edge that has 2 almost-straight outgoing edges - const double inRelAngle = fabs(NBHelpers::relAngle(n->getIncomingEdges().front()->getAngleAtNode(n), n->getIncomingEdges().back()->getAngleAtNode(n))); - //std::cout << "n=" << n->getID() << " inRelAngle=" << inRelAngle << "\n"; - if (inRelAngle < 135) { - return false; // not opposite incoming - } - for (NBEdge* in : n->getIncomingEdges()) { - EdgeVector straight; - int numReverse = 0; - for (NBEdge* out : n->getOutgoingEdges()) { - const double outRelAngle = fabs(NBHelpers::relAngle(in->getAngleAtNode(n), out->getAngleAtNode(n))); - if (outRelAngle <= 45) { - straight.push_back(out); - } else if (outRelAngle >= 135) { - numReverse++; - } - } - if (straight.size() == 2 && numReverse == 1) { - outgoing.insert(outgoing.begin(), straight.begin(), straight.end()); - inAngle = in->getAngleAtNode(n); - return true; - } - } - } - return false; -} - - -bool -NBNodeCont::maybeSlipLaneEnd(const NBNode* n, EdgeVector& incoming, double& outAngle) const { - if (n->getIncomingEdges().size() == 2 && n->getOutgoingEdges().size() == 1) { - incoming.insert(incoming.begin(), n->getIncomingEdges().begin(), n->getIncomingEdges().end()); - outAngle = n->getOutgoingEdges().front()->getAngleAtNode(n); - return true; - } else if (n->getIncomingEdges().size() == 3 && n->getOutgoingEdges().size() >= 2) { - // check if the outgoing edges are going in opposite directions and then - // use the outgoing edge that has 2 almost-straight incoming edges - const double outRelAngle = fabs(NBHelpers::relAngle(n->getOutgoingEdges().front()->getAngleAtNode(n), n->getOutgoingEdges().back()->getAngleAtNode(n))); - //std::cout << "n=" << n->getID() << " outRelAngle=" << outRelAngle << "\n"; - if (outRelAngle < 135) { - return false; // not opposite outgoing - } - for (NBEdge* out : n->getOutgoingEdges()) { - EdgeVector straight; - int numReverse = 0; - for (NBEdge* in : n->getIncomingEdges()) { - const double inRelAngle = fabs(NBHelpers::relAngle(in->getAngleAtNode(n), out->getAngleAtNode(n))); - if (inRelAngle <= 45) { - straight.push_back(in); - } else if (inRelAngle >= 135) { - numReverse++; - } - } - if (straight.size() == 2 && numReverse == 1) { - incoming.insert(incoming.begin(), straight.begin(), straight.end()); - outAngle = out->getAngleAtNode(n); - return true; - } - } - } - return false; -} - -bool -NBNodeCont::feasibleCluster(const NodeSet& cluster, const NBEdgeCont& ec, const NBPTStopCont& sc, std::string& reason) const { - // check for clusters which are to complex and probably won't work very well - // we count the incoming edges of the final junction - std::map finalIncomingAngles; - std::map finalOutgoingAngles; - for (NodeSet::const_iterator j = cluster.begin(); j != cluster.end(); ++j) { - for (EdgeVector::const_iterator it_edge = (*j)->getIncomingEdges().begin(); it_edge != (*j)->getIncomingEdges().end(); ++it_edge) { - NBEdge* edge = *it_edge; - if (cluster.count(edge->getFromNode()) == 0 && (edge->getPermissions() & SVC_PASSENGER) != 0) { - // incoming edge, does not originate in the cluster - finalIncomingAngles[edge->getID()] = edge->getAngleAtNode(edge->getToNode()); - } - } - for (EdgeVector::const_iterator it_edge = (*j)->getOutgoingEdges().begin(); it_edge != (*j)->getOutgoingEdges().end(); ++it_edge) { - NBEdge* edge = *it_edge; - if (cluster.count(edge->getToNode()) == 0 && (edge->getPermissions() & SVC_PASSENGER) != 0) { - // outgoing edge, does not end in the cluster - finalOutgoingAngles[edge->getID()] = edge->getAngleAtNode(edge->getFromNode()); - } - } - - } -#ifdef DEBUG_JOINJUNCTIONS - for (NBNode* n : cluster) { - if (DEBUGCOND(n)) { - std::cout << "feasibleCluster c=" << joinNamedToString(cluster, ',') - << "\n inAngles=" << joinToString(finalIncomingAngles, ' ', ':') - << "\n outAngles=" << joinToString(finalOutgoingAngles, ' ', ':') - << "\n"; - } - } -#endif - if (finalIncomingAngles.size() > 4) { - reason = toString(finalIncomingAngles.size()) + " incoming edges"; - return false; - } - // check for incoming parallel edges - const double PARALLEL_INCOMING_THRESHOLD = 10.0; - bool foundParallel = false; - for (std::map::const_iterator j = finalIncomingAngles.begin(); j != finalIncomingAngles.end() && !foundParallel; ++j) { - std::map::const_iterator k = j; - for (++k; k != finalIncomingAngles.end() && !foundParallel; ++k) { - if (fabs(j->second - k->second) < PARALLEL_INCOMING_THRESHOLD) { - reason = "parallel incoming " + j->first + "," + k->first; - return false; - } - } - } - // check for outgoing parallel edges - for (std::map::const_iterator j = finalOutgoingAngles.begin(); j != finalOutgoingAngles.end() && !foundParallel; ++j) { - std::map::const_iterator k = j; - for (++k; k != finalOutgoingAngles.end() && !foundParallel; ++k) { - if (fabs(j->second - k->second) < PARALLEL_INCOMING_THRESHOLD) { - reason = "parallel outgoing " + j->first + "," + k->first; - return false; - } - } - } - // check for stop edges within the cluster - if (OptionsCont::getOptions().isSet("ptstop-output")) { - for (auto it = sc.begin(); it != sc.end(); it++) { - NBEdge* edge = ec.retrieve(it->second->getEdgeId()); - if (edge != nullptr && cluster.count(edge->getFromNode()) != 0 && cluster.count(edge->getToNode()) != 0) { - reason = "it contains stop '" + it->first + "'"; - return false; - } - } - } - int numTLS = 0; - for (NBNode* n : cluster) { - if (n->isTLControlled()) { - numTLS++; - }; - } - const bool hasTLS = numTLS > 0; - // prevent removal of long edges unless there is weak circle or a traffic light - if (cluster.size() > 2) { - // find the nodes with the biggests physical distance between them - double maxDist = -1; - NBEdge* maxEdge = nullptr; - for (NBNode* n1 : cluster) { - for (NBNode* n2 : cluster) { - NBEdge* e1 = n1->getConnectionTo(n2); - NBEdge* e2 = n2->getConnectionTo(n1); - if (e1 != nullptr && e1->getLoadedLength() > maxDist) { - maxDist = e1->getLoadedLength(); - maxEdge = e1; - } - if (e2 != nullptr && e2->getLoadedLength() > maxDist) { - maxDist = e2->getLoadedLength(); - maxEdge = e2; - } - } - } -#ifdef DEBUG_JOINJUNCTIONS - for (NBNode* n : cluster) { - if (DEBUGCOND(n)) { - std::cout << "feasible hasTLS=" << hasTLS << " maxDist=" << maxDist << " maxEdge=" << maxEdge->getID() << "\n"; - } - } -#endif - if (!hasTLS && maxDist > 5) { - // find a weak circle within cluster that does not use maxEdge - std::vector toCheck; - std::set visited; - toCheck.push_back(maxEdge->getToNode()); - bool foundCircle = false; - while (!toCheck.empty()) { - NBNode* n = toCheck.back(); - if (n == maxEdge->getFromNode()) { - foundCircle = true; - break; - } - toCheck.pop_back(); - visited.insert(n); - for (NBEdge* e : n->getEdges()) { - if (e != maxEdge) { - NBNode* cand = e->getFromNode() == n ? e->getToNode() : e->getFromNode(); - if (visited.count(cand) == 0 && cluster.count(cand) != 0) { - toCheck.push_back(cand); - } - } - } - } - if (!foundCircle) { - reason = "not compact (maxEdge=" + maxEdge->getID() + " length=" + toString(maxDist) + ")"; - return false; - } - } - } - // prevent joining of simple merging/spreading structures - if (!hasTLS && cluster.size() >= 2) { - int entryNodes = 0; - int exitNodes = 0; - int outsideIncoming = 0; - int outsideOutgoing = 0; - int edgesWithin = 0; - for (NBNode* n : cluster) { - bool foundOutsideIncoming = false; - for (NBEdge* e : n->getIncomingEdges()) { - if (cluster.count(e->getFromNode()) == 0) { - // edge entering from outside the cluster - outsideIncoming++; - foundOutsideIncoming = true; - } else { - edgesWithin++; - } - } - if (foundOutsideIncoming) { - entryNodes++; - } - bool foundOutsideOutgoing = false; - for (NBEdge* e : n->getOutgoingEdges()) { - if (cluster.count(e->getToNode()) == 0) { - // edge leaving cluster - outsideOutgoing++; - foundOutsideOutgoing = true; - } - } - if (foundOutsideOutgoing) { - exitNodes++; - } - } - if (entryNodes < 2) { - reason = "only 1 entry node"; - return false; - } - if (exitNodes < 2) { - reason = "only 1 exit node"; - return false; - } - if (cluster.size() == 2) { - if (edgesWithin == 1 && outsideIncoming < 3 && outsideOutgoing < 3) { - reason = "only 1 edge within and no cross-traffic"; - return false; - } - } - } - return true; -} - - -bool -NBNodeCont::reduceToCircle(NodeSet& cluster, int circleSize, NodeSet startNodes, std::vector cands) const { - //std::cout << "reduceToCircle cs=" << circleSize << " cands=" << toString(cands, ',') << " startNodes=" << joinNamedToString(startNodes, ',') << "\n"; - assert(circleSize >= 2); - if ((int)cands.size() == circleSize) { - if (cands.back()->getConnectionTo(cands.front()) != nullptr) { - // cluster found - NodeSet candCluster; - candCluster.insert(cands.begin(), cands.end()); - pruneClusterFringe(candCluster); - const bool feasible = (int)candCluster.size() == circleSize; - if (feasible) { - cluster.clear(); - cluster.insert(cands.begin(), cands.end()); - } - return feasible; - } else { - return false; - } - } - if ((int)cluster.size() <= circleSize || startNodes.size() == 0) { - // no reduction possible - //std::cout << " abort\n"; - return false; - } - if (cands.size() == 0) { - // try to find a circle starting from another start node - NBEdge* e = shortestEdge(cluster, startNodes, cands); - if (e != nullptr) { - cands.push_back(e->getFromNode()); - startNodes.erase(e->getFromNode()); - if (reduceToCircle(cluster, circleSize, startNodes, cands)) { - return true; - } else { - // try another start node - return reduceToCircle(cluster, circleSize, startNodes); - } - } - } else { - NodeSet singleStart; - singleStart.insert(cands.back()); - NBEdge* e = shortestEdge(cluster, singleStart, cands); - if (e != nullptr) { - std::vector cands2(cands); - cands2.push_back(e->getToNode()); - if (reduceToCircle(cluster, circleSize, startNodes, cands2)) { - return true; - } - } - } - //std::cout << " abort2\n"; - return false; -} - - -NBEdge* -NBNodeCont::shortestEdge(const NodeSet& cluster, const NodeSet& startNodes, const std::vector& exclude) const { - double minDist = std::numeric_limits::max(); - NBEdge* result = nullptr; - for (NBNode* n : startNodes) { - for (NBEdge* e : n->getOutgoingEdges()) { - NBNode* neigh = e->getToNode(); - if (cluster.count(neigh) != 0 && std::find(exclude.begin(), exclude.end(), neigh) == exclude.end()) { - const double dist = n->getPosition().distanceTo2D(neigh->getPosition()); - //std::cout << " e=" << e->getID() << " dist=" << dist << " minD=" << minDist << "\n"; - if (dist < minDist) { - minDist = dist; - result = e; - } - } - } - } - //std::cout << "closestNeighbor startNodes=" << toString(startNodes) << " result=" << Named::getIDSecure(result) << "\n"; - return result; -} - -void -NBNodeCont::joinNodeClusters(NodeClusters clusters, - NBDistrictCont& dc, NBEdgeCont& ec, NBTrafficLightLogicCont& tlc) { - for (NodeSet cluster : clusters) { - joinNodeCluster(cluster, dc, ec, tlc); - } -} - - -void -NBNodeCont::joinNodeCluster(NodeSet cluster, NBDistrictCont& dc, NBEdgeCont& ec, NBTrafficLightLogicCont& tlc, NBNode* predefined) { - const bool origNames = OptionsCont::getOptions().getBool("output.original-names"); - assert(cluster.size() > 1); - Position pos; - bool setTL; - std::string id = "cluster"; - TrafficLightType type; - SumoXMLNodeType nodeType = SumoXMLNodeType::UNKNOWN; - analyzeCluster(cluster, id, pos, setTL, type, nodeType); - NBNode* newNode = nullptr; - if (predefined != nullptr) { - newNode = predefined; - } else { - if (!insert(id, pos)) { - // should not fail - WRITE_WARNINGF("Could not join junctions %.", id); - return; - } - newNode = retrieve(id); - } - std::string tlID = id; - if (predefined != nullptr) { - if (predefined->getType() != SumoXMLNodeType::UNKNOWN) { - nodeType = predefined->getType(); - } - Position ppos = predefined->getPosition(); - if (ppos.x() != Position::INVALID.x()) { - pos.setx(ppos.x()); - } - if (ppos.y() != Position::INVALID.y()) { - pos.sety(ppos.y()); - } - if (ppos.z() != Position::INVALID.z()) { - pos.setz(ppos.z()); - } - } - newNode->reinit(pos, nodeType); - if (setTL && !newNode->isTLControlled()) { - NBTrafficLightDefinition* tlDef = new NBOwnTLDef(tlID, newNode, 0, type); - if (!tlc.insert(tlDef)) { - // actually, nothing should fail here - delete tlDef; - throw ProcessError("Could not allocate tls '" + id + "'."); - } - } - // collect edges - EdgeSet allEdges; - for (NBNode* n : cluster) { - const EdgeVector& edges = n->getEdges(); - allEdges.insert(edges.begin(), edges.end()); - } - // determine edges with are incoming or fully inside - EdgeSet clusterIncoming; - EdgeSet inside; - for (NBEdge* e : allEdges) { - if (cluster.count(e->getToNode()) > 0) { - if (cluster.count(e->getFromNode()) > 0) { - inside.insert(e); - } else { - clusterIncoming.insert(e); - } - } - } -#ifdef DEBUG_JOINJUNCTIONS - std::cout << "joining cluster " << joinNamedToString(cluster, ' ') << "\n" - << " incoming=" << toString(clusterIncoming) << "\n" - << " inside=" << toString(inside) << "\n"; -#endif - - // determine possible connectivity from outside edges - std::map reachable; - for (NBEdge* e : clusterIncoming) { - EdgeVector open; - EdgeSet seen; - open.push_back(e); - while (open.size() > 0) { - NBEdge* cur = open.back(); - //std::cout << " e=" << e->getID() << " cur=" << cur->getID() << " open=" << toString(open) << "\n"; - seen.insert(cur); - open.pop_back(); - if (cluster.count(cur->getToNode()) == 0) { - //std::cout << " continue\n"; - continue; - } - const auto& cons = cur->getConnections(); - if (cons.size() == 0 || ec.hasPostProcessConnection(cur->getID()) || cur->getStep() == NBEdge::EdgeBuildingStep::INIT) { - // check permissions to determine reachability - for (NBEdge* out : cur->getToNode()->getOutgoingEdges()) { - if (seen.count(out) == 0 - && allEdges.count(out) != 0 - && (out->getPermissions() & cur->getPermissions() & ~SVC_PEDESTRIAN) != 0) { - open.push_back(out); - } - } - } else { - // check existing connections - for (const auto& con : cons) { - if (con.toEdge != nullptr - && seen.count(con.toEdge) == 0 - && allEdges.count(con.toEdge) != 0) { - open.push_back(con.toEdge); - } - } - } - } - seen.erase(e); - for (NBEdge* reached : seen) { - // filter out inside edges from reached - if (inside.count(reached) == 0) { - reachable[e].insert(reached); - } - } -#ifdef DEBUG_JOINJUNCTIONS - std::cout << " reachable e=" << e->getID() << " seen=" << toString(seen) << " reachable=" << toString(reachable[e]) << "\n"; -#endif - } - - // remap and remove edges which are completely within the new intersection - for (NBEdge* e : inside) { - for (NBEdge* e2 : allEdges) { - if (e != e2) { - e2->replaceInConnections(e, e->getConnections()); - } - } - ec.extract(dc, e, true); - allEdges.erase(e); - } - - // remap edges which are incoming / outgoing - for (NBEdge* e : allEdges) { - std::vector conns = e->getConnections(); - const bool outgoing = cluster.count(e->getFromNode()) > 0; - NBNode* from = outgoing ? newNode : e->getFromNode(); - NBNode* to = outgoing ? e->getToNode() : newNode; - if (origNames) { - if (outgoing) { - e->setParameter("origFrom", e->getFromNode()->getID()); - } else { - e->setParameter("origTo", e->getToNode()->getID()); - } - } - e->reinitNodes(from, to); - // re-add connections which previously existed and may still valid. - // connections to removed edges will be ignored - for (std::vector::iterator k = conns.begin(); k != conns.end(); ++k) { - e->addLane2LaneConnection((*k).fromLane, (*k).toEdge, (*k).toLane, NBEdge::Lane2LaneInfoType::USER, false, (*k).mayDefinitelyPass); - if ((*k).fromLane >= 0 && (*k).fromLane < e->getNumLanes() && e->getLaneStruct((*k).fromLane).connectionsDone) { - // @note (see NIImporter_DlrNavteq::ConnectedLanesHandler) - e->declareConnectionsAsLoaded(NBEdge::EdgeBuildingStep::INIT); - } - } - } - // disable connections that were impossible with the old topology - for (NBEdge* in : newNode->getIncomingEdges()) { - for (NBEdge* out : newNode->getOutgoingEdges()) { - if (reachable[in].count(out) == 0 && !ec.hasPostProcessConnection(in->getID(), out->getID())) { - //std::cout << " removeUnreachable in=" << in->getID() << " out=" << out->getID() << "\n"; - in->removeFromConnections(out, -1, -1, true, false, true); - } - } - } - - // remove original nodes - registerJoinedCluster(cluster); - for (NBNode* n : cluster) { - erase(n); - } -} - - -void -NBNodeCont::registerJoinedCluster(const NodeSet& cluster) { - std::set ids; - for (NBNode* n : cluster) { - ids.insert(n->getID()); - } - myJoinedClusters.push_back(ids); -} - - -void -NBNodeCont::analyzeCluster(NodeSet cluster, std::string& id, Position& pos, - bool& hasTLS, TrafficLightType& type, SumoXMLNodeType& nodeType) { - id += "_" + joinNamedToString(cluster, '_'); - hasTLS = false; - bool ambiguousType = false; - for (NBNode* j : cluster) { - pos.add(j->getPosition()); - // add a traffic light if any of the cluster members was controlled - if (j->isTLControlled()) { - if (!hasTLS) { - // init type - type = (*j->getControllingTLS().begin())->getType(); - } else if (type != (*j->getControllingTLS().begin())->getType()) { - ambiguousType = true; - } - hasTLS = true; - } - SumoXMLNodeType otherType = j->getType(); - if (nodeType == SumoXMLNodeType::UNKNOWN) { - nodeType = otherType; - } else if (nodeType != otherType) { - if (hasTLS) { - nodeType = SumoXMLNodeType::TRAFFIC_LIGHT; - } else { - if ((nodeType != SumoXMLNodeType::PRIORITY && (nodeType != SumoXMLNodeType::NOJUNCTION || otherType != SumoXMLNodeType::PRIORITY)) - || (otherType != SumoXMLNodeType::NOJUNCTION && otherType != SumoXMLNodeType::UNKNOWN && otherType != SumoXMLNodeType::PRIORITY)) { - WRITE_WARNINGF("Ambiguous node type for node cluster '%' (%,%), setting to '" + toString(SumoXMLNodeType::PRIORITY) + "'.", id, toString(nodeType), toString(otherType)); - } - nodeType = SumoXMLNodeType::PRIORITY; - } - } - } - pos.mul(1.0 / cluster.size()); - if (ambiguousType) { - type = SUMOXMLDefinitions::TrafficLightTypes.get(OptionsCont::getOptions().getString("tls.default-type")); - WRITE_WARNINGF("Ambiguous traffic light type for node cluster '%', setting to '%'.", id, toString(type)); - } -} - - -// ----------- (Helper) methods for guessing/computing traffic lights -bool -NBNodeCont::shouldBeTLSControlled(const NodeSet& c, double laneSpeedThreshold) const { - bool tooFast = false; - double laneSpeedSum = 0; - std::set seen; - for (NBNode* j : c) { - const EdgeVector& edges = j->getEdges(); - for (EdgeVector::const_iterator k = edges.begin(); k != edges.end(); ++k) { - if (c.find((*k)->getFromNode()) != c.end() && c.find((*k)->getToNode()) != c.end()) { - continue; - } - if (j->hasIncoming(*k)) { - laneSpeedSum += (double)(*k)->getNumLanes() * (*k)->getLaneSpeed(0); - } - if ((*k)->getLaneSpeed(0) * 3.6 > 79) { - tooFast = true; - } - } - } - //std::cout << " c=" << joinNamedToString(c, ' ') << " f=" << f << " size=" << c.size() << " thresh=" << laneSpeedThreshold << " tooFast=" << tooFast << "\n"; - return !tooFast && laneSpeedSum >= laneSpeedThreshold && c.size() != 0; -} - -bool -NBNodeCont::onlyCrossings(const NodeSet& c) const { - // check whether all component nodes are solely pedestrian crossings - // (these work fine without joining) - for (NBNode* node : c) { - EdgeVector nonPedIncoming; - EdgeVector nonPedOutgoing; - for (NBEdge* e : node->getIncomingEdges()) { - if (e->getPermissions() != SVC_PEDESTRIAN) { - nonPedIncoming.push_back(e); - } - } - for (NBEdge* e : node->getOutgoingEdges()) { - if (e->getPermissions() != SVC_PEDESTRIAN) { - nonPedOutgoing.push_back(e); - } - } - if (!node->geometryLike(nonPedIncoming, nonPedOutgoing)) { - //for (NBNode* node : c) { - // if (node->getID() == "2480337678") { - // std::cout << " node=" << node->getID() << " nonPedIncoming=" << toString(nonPedIncoming) << " nonPedOutgoing=" << toString(nonPedOutgoing) << "\n"; - // } - //} - return false; - } - } - return true; -} - - -bool -NBNodeCont::customTLID(const NodeSet& c) const { - for (NBNode* node : c) { - if (node->isTLControlled()) { - const std::string tlID = (*node->getControllingTLS().begin())->getID(); - if (tlID != node->getID() - && !StringUtils::startsWith(tlID, "joinedS_") - && !StringUtils::startsWith(tlID, "joinedG_") - && !StringUtils::startsWith(tlID, "GS")) { - return true; - } - } - } - return false; -} - - -void -NBNodeCont::guessTLs(OptionsCont& oc, NBTrafficLightLogicCont& tlc) { - myGuessedTLS.clear(); - // build list of definitely not tls-controlled junctions - const double laneSpeedThreshold = oc.getFloat("tls.guess.threshold"); - std::vector ncontrolled; - if (oc.isSet("tls.unset")) { - std::vector notTLControlledNodes = oc.getStringVector("tls.unset"); - for (std::vector::const_iterator i = notTLControlledNodes.begin(); i != notTLControlledNodes.end(); ++i) { - NBNode* n = NBNodeCont::retrieve(*i); - if (n == nullptr) { - throw ProcessError(" The junction '" + *i + "' to set as not-controlled is not known."); - } - std::set tls = n->getControllingTLS(); - for (std::set::const_iterator j = tls.begin(); j != tls.end(); ++j) { - (*j)->removeNode(n); - } - n->removeTrafficLights(); - ncontrolled.push_back(n); - } - } - - TrafficLightType type = SUMOXMLDefinitions::TrafficLightTypes.get(OptionsCont::getOptions().getString("tls.default-type")); - // loop#1 checking whether the node shall be tls controlled, - // because it is assigned to a district - if (oc.exists("tls.taz-nodes") && oc.getBool("tls.taz-nodes")) { - for (NodeCont::iterator i = myNodes.begin(); i != myNodes.end(); i++) { - NBNode* cur = (*i).second; - if (cur->isNearDistrict() && std::find(ncontrolled.begin(), ncontrolled.end(), cur) == ncontrolled.end()) { - setAsTLControlled(cur, tlc, type); - } - } - } - - // figure out which nodes mark the locations of TLS signals - // This assumes nodes are already joined - if (oc.exists("tls.guess-signals") && oc.getBool("tls.guess-signals")) { - // prepare candidate edges - const double signalDist = oc.getFloat("tls.guess-signals.dist"); - for (const auto& item : myNodes) { - const NBNode* node = item.second; - if (node->isTLControlled() && (node->getIncomingEdges().size() == 1 || node->geometryLike())) { -#ifdef DEBUG_GUESSSIGNALS - if (DEBUGCOND(node) || true) { - std::cout << " propagate TLS from " << node->getID() << " downstream\n"; - } -#endif - for (NBEdge* edge : node->getOutgoingEdges()) { - // do not overwrite closer signals - if (edge->getSignalOffset() == NBEdge::UNSPECIFIED_SIGNAL_OFFSET) { - edge->setSignalPosition(node->getPosition(), node); - } - } - } - } - std::set seen; - std::set check; - for (const auto& item : myNodes) { - for (NBEdge* edge : item.second->getOutgoingEdges()) { - if (edge->getSignalPosition() != Position::INVALID) { - check.insert(edge); - seen.insert(edge); -#ifdef DEBUG_GUESSSIGNALS - if (DEBUGCOND(edge->getSignalNode()) || true) { - std::cout << " primary signalPosition edge=" << edge->getID() << " pos=" << edge->getSignalPosition() << "\n"; - } -#endif - } - } - } - // propagate signal position until the next real intersection - while (check.size() > 0) { - NBEdge* const edge = *check.begin(); - check.erase(check.begin()); - seen.insert(edge); - NBNode* const nextNode = edge->getToNode(); - if (nextNode->geometryLike() && !nextNode->isTLControlled()) { - for (NBEdge* const outEdge : nextNode->getOutgoingEdges()) { - if (seen.count(outEdge) == 0) { - outEdge->setSignalPosition(edge->getSignalPosition(), edge->getSignalNode()); -#ifdef DEBUG_GUESSSIGNALS - if (DEBUGCOND(edge->getSignalNode()) || true) { - std::cout << " setSignalPosition edge=" << outEdge->getID() << " pos=" << edge->getSignalPosition() << "\n"; - } -#endif - check.insert(outEdge); - } - } - } - } - - // check which nodes should be controlled - for (std::map::const_iterator i = myNodes.begin(); i != myNodes.end(); ++i) { - NBNode* node = i->second; - if (find(ncontrolled.begin(), ncontrolled.end(), node) != ncontrolled.end()) { - continue; - } - const EdgeVector& incoming = node->getIncomingEdges(); - const EdgeVector& outgoing = node->getOutgoingEdges(); - if (!node->isTLControlled() && incoming.size() > 1 && !node->geometryLike() - && !NBNodeTypeComputer::isRailwayNode(node) - && node->getType() != SumoXMLNodeType::RAIL_CROSSING) { - std::vector signals; - bool isTLS = true; - // check if there is a signal at every incoming edge - for (EdgeVector::const_iterator it_i = incoming.begin(); it_i != incoming.end(); ++it_i) { - const NBEdge* inEdge = *it_i; - if (inEdge->getSignalOffset() == NBEdge::UNSPECIFIED_SIGNAL_OFFSET && inEdge->getPermissions() != SVC_TRAM) { -#ifdef DEBUG_GUESSSIGNALS - if (DEBUGCOND(node)) { - std::cout << " noTLS, edge=" << inEdge->getID() << "\n"; - } -#endif - isTLS = false; - break; - } - } - if (isTLS) { - node->updateSurroundingGeometry(); - // check if all signals are within the required distance - // (requires detailed geometry computation) - for (EdgeVector::const_iterator it_i = incoming.begin(); it_i != incoming.end(); ++it_i) { - const NBEdge* inEdge = *it_i; - if ((inEdge->getSignalOffset() == NBEdge::UNSPECIFIED_SIGNAL_OFFSET || inEdge->getSignalOffset() > signalDist) - && inEdge->getPermissions() != SVC_TRAM) { -#ifdef DEBUG_GUESSSIGNALS - if (DEBUGCOND(node)) { - std::cout << " noTLS, edge=" << inEdge->getID() << " offset=" << inEdge->getSignalOffset() << " tlsPos=" << inEdge->getSignalPosition() << "\n"; - } -#endif - isTLS = false; - break; - } - const NBNode* signal = inEdge->getSignalNode(); - if (signal != nullptr) { - signals.push_back(signal); - } - } - // outgoing edges may be tagged with pedestrian crossings. These - // should also be merged into the main TLS - for (const NBEdge* outEdge : outgoing) { - NBNode* cand = outEdge->getToNode(); - if (cand->isTLControlled() && cand->geometryLike() && outEdge->getLength() <= signalDist) { -#ifdef DEBUG_GUESSSIGNALS - if (DEBUGCOND(node)) { - std::cout << " node=" << node->getID() << " outEdge=" << outEdge->getID() << " signalNode=" << cand->getID() << " len=" << outEdge->getLength() << "\n"; - } -#endif - signals.push_back(cand); - } - } - } - if (isTLS) { - for (const NBNode* s : signals) { - std::set tls = s->getControllingTLS(); - const_cast(s)->reinit(s->getPosition(), SumoXMLNodeType::PRIORITY); - for (std::set::iterator k = tls.begin(); k != tls.end(); ++k) { - tlc.removeFully(s->getID()); - } - } - //if (true) std::cout << " node=" << node->getID() << " signals=" << toString(signals) << "\n"; - NBTrafficLightDefinition* tlDef = new NBOwnTLDef("GS_" + node->getID(), node, 0, type); - // @todo patch endOffset for all incoming lanes according to the signal positions - if (!tlc.insert(tlDef)) { - // actually, nothing should fail here - WRITE_WARNINGF("Could not build joined tls '%'.", node->getID()); - delete tlDef; - return; - } - } - } - } - } - - // guess joined tls first, if wished - if (oc.getBool("tls.guess.joining")) { - // get node clusters - NodeClusters cands; - generateNodeClusters(oc.getFloat("tls.join-dist"), cands); - // check these candidates (clusters) whether they should be controlled by a tls - for (NodeClusters::iterator i = cands.begin(); i != cands.end();) { - NodeSet& c = (*i); - // regard only junctions which are not yet controlled and are not - // forbidden to be controlled - for (NodeSet::iterator j = c.begin(); j != c.end();) { - if ((*j)->isTLControlled() || std::find(ncontrolled.begin(), ncontrolled.end(), *j) != ncontrolled.end()) { - c.erase(j++); - } else { - ++j; - } - } - // check whether the cluster should be controlled - // to avoid gigantic clusters, assume that at most 4 nodes should be needed for a guessed-joined-tls - if (c.size() == 0 || !shouldBeTLSControlled(c, laneSpeedThreshold * c.size() / MIN2((int)c.size(), 4))) { - i = cands.erase(i); - } else { - ++i; - } - } - // cands now only contain sets of junctions that shall be joined into being tls-controlled - int index = 0; - for (auto nodeSet : cands) { - std::vector nodes; - for (NBNode* node : nodeSet) { - nodes.push_back(node); - myGuessedTLS.insert(node); - } - std::string id = "joinedG_" + toString(index++); - NBTrafficLightDefinition* tlDef = new NBOwnTLDef(id, nodes, 0, type); - if (!tlc.insert(tlDef)) { - // actually, nothing should fail here - WRITE_WARNING("Could not build guessed, joined tls."); - delete tlDef; - return; - } - } - } - - // guess single tls - if (oc.getBool("tls.guess")) { - for (NodeCont::iterator i = myNodes.begin(); i != myNodes.end(); i++) { - NBNode* cur = (*i).second; - // do nothing if already is tl-controlled - if (cur->isTLControlled()) { - continue; - } - // do nothing if in the list of explicit non-controlled junctions - if (find(ncontrolled.begin(), ncontrolled.end(), cur) != ncontrolled.end()) { - continue; - } - NodeSet c; - c.insert(cur); - if (!shouldBeTLSControlled(c, laneSpeedThreshold) || cur->geometryLike()) { - continue; - } - setAsTLControlled(cur, tlc, type); - myGuessedTLS.insert(cur); - } - } -} - -void NBNodeCont::recheckGuessedTLS(NBTrafficLightLogicCont& tlc) { - std::set recompute; - for (NBNode* node : myGuessedTLS) { - if (!node->hasConflict()) { - const std::set& tlDefs = node->getControllingTLS(); - recompute.insert(tlDefs.begin(), tlDefs.end()); - node->removeTrafficLights(true); - for (NBEdge* edge : node->getIncomingEdges()) { - edge->clearControllingTLInformation(); - } - } - } - for (NBTrafficLightDefinition* def : recompute) { - if (def->getNodes().size() == 0) { - tlc.removeFully(def->getID()); - } else { - def->setParticipantsInformation(); - def->setTLControllingInformation(); - tlc.computeSingleLogic(OptionsCont::getOptions(), def); - } - } -} - - -void -NBNodeCont::joinTLS(NBTrafficLightLogicCont& tlc, double maxdist) { - NodeClusters cands; - generateNodeClusters(maxdist, cands); - IDSupplier idSupplier("joinedS_"); - for (NodeSet& c : cands) { - for (NodeSet::iterator j = c.begin(); j != c.end();) { - if (!(*j)->isTLControlled()) { - c.erase(j++); - } else { - ++j; - } - } - if (c.size() < 2 || onlyCrossings(c) || customTLID(c)) { - continue; - } - // figure out type of the joined TLS - Position dummyPos; - bool dummySetTL; - std::string id = "joined"; // prefix (see #3871) - TrafficLightType type; - SumoXMLNodeType nodeType = SumoXMLNodeType::UNKNOWN; - analyzeCluster(c, id, dummyPos, dummySetTL, type, nodeType); - for (NBNode* j : c) { - std::set tls = j->getControllingTLS(); - j->removeTrafficLights(); - for (std::set::iterator k = tls.begin(); k != tls.end(); ++k) { - tlc.removeFully(j->getID()); - } - } - std::vector nodes; - for (NBNode* j : c) { - nodes.push_back(j); - } - id = idSupplier.getNext(); - while (tlc.getPrograms(id).size() > 0) { - id = idSupplier.getNext(); - } - NBTrafficLightDefinition* tlDef = new NBOwnTLDef(id, nodes, 0, type); - if (!tlc.insert(tlDef)) { - // actually, nothing should fail here - WRITE_WARNING("Could not build a joined tls."); - delete tlDef; - return; - } - } -} - - -void -NBNodeCont::setAsTLControlled(NBNode* node, NBTrafficLightLogicCont& tlc, - TrafficLightType type, std::string id) { - if (id == "") { - id = node->getID(); - } - NBTrafficLightDefinition* tlDef = new NBOwnTLDef(id, node, 0, type); - if (!tlc.insert(tlDef)) { - // actually, nothing should fail here - WRITE_WARNINGF("Building a tl-logic for junction '%' twice is not possible.", id); - delete tlDef; - return; - } -} - - -// ----------- -void -NBNodeCont::computeLanes2Lanes() { - for (NodeCont::iterator i = myNodes.begin(); i != myNodes.end(); i++) { - (*i).second->computeLanes2Lanes(); - } -} - - -// computes the "wheel" of incoming and outgoing edges for every node -void -NBNodeCont::computeLogics(const NBEdgeCont& ec) { - for (NodeCont::iterator i = myNodes.begin(); i != myNodes.end(); i++) { - (*i).second->computeLogic(ec); - } -} - - -void -NBNodeCont::computeLogics2(const NBEdgeCont& ec, OptionsCont& oc) { - std::set roundaboutNodes; - const bool checkLaneFoesAll = oc.getBool("check-lane-foes.all"); - const bool checkLaneFoesRoundabout = !checkLaneFoesAll && oc.getBool("check-lane-foes.roundabout"); - if (checkLaneFoesRoundabout) { - const std::set& roundabouts = ec.getRoundabouts(); - for (std::set::const_iterator i = roundabouts.begin(); i != roundabouts.end(); ++i) { - for (EdgeSet::const_iterator j = (*i).begin(); j != (*i).end(); ++j) { - roundaboutNodes.insert((*j)->getToNode()); - } - } - } - for (NodeCont::iterator i = myNodes.begin(); i != myNodes.end(); i++) { - const bool checkLaneFoes = checkLaneFoesAll || (checkLaneFoesRoundabout && roundaboutNodes.count((*i).second) > 0); - (*i).second->computeLogic2(checkLaneFoes); - } -} - - -void -NBNodeCont::clear() { - for (NodeCont::iterator i = myNodes.begin(); i != myNodes.end(); i++) { - delete ((*i).second); - } - myNodes.clear(); - for (auto& item : myExtractedNodes) { - delete item.second; - } - myExtractedNodes.clear(); -} - - -std::string -NBNodeCont::getFreeID() { - int counter = 0; - std::string freeID = "SUMOGenerated" + toString(counter); - // While there is a node with id equal to freeID - while (retrieve(freeID) != nullptr) { - // update counter and generate a new freeID - counter++; - freeID = "SUMOGenerated" + toString(counter); - } - return freeID; -} - - -void -NBNodeCont::computeNodeShapes(double mismatchThreshold) { - for (NodeCont::iterator i = myNodes.begin(); i != myNodes.end(); i++) { - (*i).second->computeNodeShape(mismatchThreshold); - } -} - - -void -NBNodeCont::printBuiltNodesStatistics() const { - int numUnregulatedJunctions = 0; - int numDeadEndJunctions = 0; - int numTrafficLightJunctions = 0; - int numPriorityJunctions = 0; - int numRightBeforeLeftJunctions = 0; - int numAllWayStopJunctions = 0; - int numZipperJunctions = 0; - int numDistrictJunctions = 0; - int numRailCrossing = 0; - int numRailSignals = 0; - for (NodeCont::const_iterator i = myNodes.begin(); i != myNodes.end(); i++) { - switch ((*i).second->getType()) { - case SumoXMLNodeType::NOJUNCTION: - ++numUnregulatedJunctions; - break; - case SumoXMLNodeType::DEAD_END: - ++numDeadEndJunctions; - break; - case SumoXMLNodeType::TRAFFIC_LIGHT: - case SumoXMLNodeType::TRAFFIC_LIGHT_RIGHT_ON_RED: - case SumoXMLNodeType::TRAFFIC_LIGHT_NOJUNCTION: - ++numTrafficLightJunctions; - break; - case SumoXMLNodeType::PRIORITY: - case SumoXMLNodeType::PRIORITY_STOP: - ++numPriorityJunctions; - break; - case SumoXMLNodeType::RIGHT_BEFORE_LEFT: - ++numRightBeforeLeftJunctions; - break; - case SumoXMLNodeType::ALLWAY_STOP: - ++numAllWayStopJunctions; - break; - case SumoXMLNodeType::ZIPPER: - ++numZipperJunctions; - break; - case SumoXMLNodeType::DISTRICT: - ++numDistrictJunctions; - break; - case SumoXMLNodeType::RAIL_CROSSING: - ++numRailCrossing; - break; - case SumoXMLNodeType::RAIL_SIGNAL: - ++numRailSignals; - break; - case SumoXMLNodeType::UNKNOWN: - // should not happen - break; - default: - break; - } - } - WRITE_MESSAGE(" Node type statistics:"); - WRITE_MESSAGE(" Unregulated junctions : " + toString(numUnregulatedJunctions)); - if (numDeadEndJunctions > 0) { - WRITE_MESSAGE(" Dead-end junctions : " + toString(numDeadEndJunctions)); - } - WRITE_MESSAGE(" Priority junctions : " + toString(numPriorityJunctions)); - WRITE_MESSAGE(" Right-before-left junctions : " + toString(numRightBeforeLeftJunctions)); - if (numTrafficLightJunctions > 0) { - WRITE_MESSAGE(" Traffic light junctions : " + toString(numTrafficLightJunctions)); - } - if (numAllWayStopJunctions > 0) { - WRITE_MESSAGE(" All-way stop junctions : " + toString(numAllWayStopJunctions)); - } - if (numZipperJunctions > 0) { - WRITE_MESSAGE(" Zipper-merge junctions : " + toString(numZipperJunctions)); - } - if (numRailCrossing > 0) { - WRITE_MESSAGE(" Rail crossing junctions : " + toString(numRailCrossing)); - } - if (numRailSignals > 0) { - WRITE_MESSAGE(" Rail signal junctions : " + toString(numRailSignals)); - } - if (numDistrictJunctions > 0) { - WRITE_MESSAGE(" District junctions : " + toString(numDistrictJunctions)); - } -} - - -std::vector -NBNodeCont::getAllNames() const { - std::vector ret; - for (NodeCont::const_iterator i = myNodes.begin(); i != myNodes.end(); ++i) { - ret.push_back((*i).first); - } - return ret; -} - - -void -NBNodeCont::rename(NBNode* node, const std::string& newID) { - if (myNodes.count(newID) != 0) { - throw ProcessError("Attempt to rename node using existing id '" + newID + "'"); - } - myNodes.erase(node->getID()); - node->setID(newID); - myNodes[newID] = node; -} - - -void -NBNodeCont::discardTrafficLights(NBTrafficLightLogicCont& tlc, bool geometryLike, bool guessSignals) { - for (NodeCont::const_iterator i = myNodes.begin(); i != myNodes.end(); ++i) { - NBNode* node = i->second; - if (node->isTLControlled() && (!geometryLike || node->geometryLike())) { - // make a copy of tldefs - const std::set tldefs = node->getControllingTLS(); - if (geometryLike && (*tldefs.begin())->getNodes().size() > 1) { - // do not remove joined tls when only removing geometry-like tls - continue; - } - if (guessSignals && node->isTLControlled() && node->geometryLike()) { - // record signal location - for (NBEdge* edge : node->getOutgoingEdges()) { - edge->setSignalPosition(node->getPosition(), nullptr); -#ifdef DEBUG_GUESSSIGNALS - std::cout << " discard-simple " << node->getID() << " edge=" << edge->getID() << " pos=" << edge->getSignalPosition() << "\n"; -#endif - } - } - for (std::set::const_iterator it = tldefs.begin(); it != tldefs.end(); ++it) { - NBTrafficLightDefinition* tlDef = *it; - node->removeTrafficLight(tlDef); - tlc.extract(tlDef); - } - SumoXMLNodeType newType = NBNodeTypeComputer::isRailwayNode(node) ? SumoXMLNodeType::RAIL_SIGNAL : SumoXMLNodeType::UNKNOWN; - node->reinit(node->getPosition(), newType); - } - } -} - - -void -NBNodeCont::discardRailSignals() { - for (auto& item : myNodes) { - NBNode* node = item.second; - if (node->getType() == SumoXMLNodeType::RAIL_SIGNAL) { - node->reinit(node->getPosition(), SumoXMLNodeType::PRIORITY); - } - } -} - - -int -NBNodeCont::remapIDs(bool numericaIDs, bool reservedIDs, const std::string& prefix) { - bool startGiven = !OptionsCont::getOptions().isDefault("numerical-ids.node-start"); - std::vector avoid; - if (startGiven) { - avoid.push_back(toString(OptionsCont::getOptions().getInt("numerical-ids.node-start") - 1)); - } else { - avoid = getAllNames(); - } - std::set reserve; - if (reservedIDs) { - NBHelpers::loadPrefixedIDsFomFile(OptionsCont::getOptions().getString("reserved-ids"), "node:", reserve); // backward compatibility - NBHelpers::loadPrefixedIDsFomFile(OptionsCont::getOptions().getString("reserved-ids"), "junction:", reserve); // selection format - avoid.insert(avoid.end(), reserve.begin(), reserve.end()); - } - IDSupplier idSupplier("", avoid); - NodeSet toChange; - for (NodeCont::iterator it = myNodes.begin(); it != myNodes.end(); it++) { - if (startGiven) { - toChange.insert(it->second); - continue; - } - if (numericaIDs) { - try { - StringUtils::toLong(it->first); - } catch (NumberFormatException&) { - toChange.insert(it->second); - } - } - if (reservedIDs && reserve.count(it->first) > 0) { - toChange.insert(it->second); - } - } - const bool origNames = OptionsCont::getOptions().getBool("output.original-names"); - for (NBNode* node : toChange) { - myNodes.erase(node->getID()); - } - for (NBNode* node : toChange) { - if (origNames) { - node->setParameter(SUMO_PARAM_ORIGID, node->getID()); - } - node->setID(idSupplier.getNext()); - myNodes[node->getID()] = node; - } - if (prefix.empty()) { - return (int)toChange.size(); - } else { - int renamed = 0; - // make a copy because we will modify the map - auto oldNodes = myNodes; - for (auto item : oldNodes) { - if (!StringUtils::startsWith(item.first, prefix)) { - rename(item.second, prefix + item.first); - renamed++; - } - } - return renamed; - } -} - - -int -NBNodeCont::guessFringe() { - NodeSet topRightFront; - NodeSet topLeftFront; - NodeSet bottomRightFront; - NodeSet bottomLeftFront; - for (const auto& item : myNodes) { - paretoCheck(item.second, topRightFront, 1, 1); - paretoCheck(item.second, topLeftFront, -1, 1); - paretoCheck(item.second, bottomRightFront, 1, -1); - paretoCheck(item.second, bottomLeftFront, -1, -1); - } - NodeSet front; - front.insert(topRightFront.begin(), topRightFront.end()); - front.insert(topLeftFront.begin(), topLeftFront.end()); - front.insert(bottomRightFront.begin(), bottomRightFront.end()); - front.insert(bottomLeftFront.begin(), bottomLeftFront.end()); - int numFringe = 0; - for (NBNode* n : front) { - const int in = (int)n->getIncomingEdges().size(); - const int out = (int)n->getOutgoingEdges().size(); - if ((in <= 1 && out <= 1) && - (in == 0 || out == 0 - || n->getIncomingEdges().front()->isTurningDirectionAt(n->getOutgoingEdges().front()))) { - n->setFringeType(FringeType::OUTER); - numFringe++; - } - } - return numFringe; -} - - -void -NBNodeCont::paretoCheck(NBNode* node, NodeSet& frontier, int xSign, int ySign) { - const double x = node->getPosition().x() * xSign; - const double y = node->getPosition().y() * ySign; - std::vector dominated; - for (NBNode* fn : frontier) { - const double x2 = fn->getPosition().x() * xSign; - const double y2 = fn->getPosition().y() * ySign; - if (x2 >= x && y2 >= y) { - return; - } else if (x2 <= x && y2 <= y) { - dominated.push_back(fn); - } - } - frontier.insert(node); - for (NBNode* r : dominated) { - frontier.erase(r); - } -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netbuild/NBNodeCont.h b/Util/OSM2ODR/src/netbuild/NBNodeCont.h deleted file mode 100644 index fac74b5f9..000000000 --- a/Util/OSM2ODR/src/netbuild/NBNodeCont.h +++ /dev/null @@ -1,421 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NBNodeCont.h -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Yun-Pang Floetteroed -/// @author Michael Behrisch -/// @author Walter Bamberger -/// @date Tue, 20 Nov 2001 -/// -// Container for nodes during the netbuilding process -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include -#include -#include -#include -#include "NBCont.h" -#include "NBEdgeCont.h" -#include "NBNode.h" -#include - - -// =========================================================================== -// class declarations -// =========================================================================== -class NBDistrict; -class OptionsCont; -class OutputDevice; -class NBParkingCont; -class NBPTLineCont; -class NBPTStopCont; - - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NBNodeCont - * @brief Container for nodes during the netbuilding process - */ -class NBNodeCont { -public: - /// @brief Definition of a node cluster container - typedef std::vector NodeClusters; - typedef std::pair NodeAndDist; - - /// @brief Constructor - NBNodeCont(); - - /// @brief Destructor - ~NBNodeCont(); - - /// @name Insertion/removal/retrieval of nodes - /// @{ - /** @brief Inserts a node into the map - * @param[in] id The node's id - * @param[in] position The node's position - * @param[in] A district assigned to the node - * @return Whether the node could be added (no other with the same id or position is stored) - */ - bool insert(const std::string& id, const Position& position, NBDistrict* district = 0); - - /** @brief Inserts a node into the map - * @param[in] node The node to insert - * @return Whether the node could be added (no other with the same id or position is stored) - */ - bool insert(NBNode* node); - - /** @brief Removes the given node, deleting it - * @param[in] node The node to delete and remove - * @return Whether the node could be removed (existed) - */ - bool erase(NBNode* node); - - /** @brief Removes the given node but does not delete it - * @param[in] node The node to delete and remove - * @param[in] remember Whether to keep the node for future reference - * @return Whether the node could be removed (existed) - */ - bool extract(NBNode* node, bool remember = false); - - /** @brief Returns the node with the given name - * @param[in] id The id of the node to retrieve - * @return The node with the given id, or 0 if no such node exists - */ - NBNode* retrieve(const std::string& id) const; - - /** @brief Returns the node with the given coordinates - * @param[in] position The position at which the node to retrieve lies - * @param[in] offset An offset which can be applied in the case positions are blurred - * @return The node at the given position, or 0 if no such node exists - */ - NBNode* retrieve(const Position& position, const double offset = 0.) const; - - /// @brief Returns the pointer to the begin of the stored nodes - std::map::const_iterator begin() const { - return myNodes.begin(); - } - - /// @brief Returns the pointer to the end of the stored nodes - std::map::const_iterator end() const { - return myNodes.end(); - } - /// @} - - /// @name Methods for for joining nodes - /// @{ - /* @brief add ids of nodes wich shall not be joined - * @param[in] ids A list of ids to exclude from joining - * @param[in] check Whether to check if these nodes are known - * @note checking is off by default because all nodes may not have been loaded yet - */ - void addJoinExclusion(const std::vector& ids, bool check = false); - - /** @brief add ids of nodes which shall be joined into a single node - * @param[in] cluster The cluster to add - */ - void addCluster2Join(std::set cluster, NBNode* node); - - /// @brief Joins loaded junction clusters (see NIXMLNodesHandler) - int joinLoadedClusters(NBDistrictCont& dc, NBEdgeCont& ec, NBTrafficLightLogicCont& tlc); - - /// @brief Joins junctions that are very close together - int joinJunctions(double maxDist, NBDistrictCont& dc, NBEdgeCont& ec, NBTrafficLightLogicCont& tlc, NBPTStopCont& sc); - - /// @brief remove geometry-like fringe nodes from cluster - void pruneClusterFringe(NodeSet& cluster) const; - - /// @brief avoid removal of long edges when joinining junction clusters - static void pruneLongEdges(NodeSet& cluster, double maxDist); - - /// @brief remove nodes that form a slip lane from cluster - void pruneSlipLaneNodes(NodeSet& cluster) const; - - /// @brief return all cluster neighbors for the given node - static NodeSet getClusterNeighbors(const NBNode* n, NodeSet& cluster); - - /// @brief check whether the given node maybe the start of a slip lane - bool maybeSlipLaneStart(const NBNode* n, EdgeVector& outgoing, double& inAngle) const; - /// @brief check whether the given node maybe the end of a slip lane - bool maybeSlipLaneEnd(const NBNode* n, EdgeVector& incoming, double& outAngle) const; - - /// @brief determine wether the cluster is not too complex for joining - bool feasibleCluster(const NodeSet& cluster, const NBEdgeCont& ec, const NBPTStopCont& sc, std::string& reason) const; - - /// @brief try to find a joinable subset (recursively) - bool reduceToCircle(NodeSet& cluster, int circleSize, NodeSet startNodes, std::vector cands = std::vector()) const; - - /// @brief find closest neighbor for building circle - NBEdge* shortestEdge(const NodeSet& cluster, const NodeSet& startNodes, const std::vector& exclude) const; - /// @} - - /// @name Adapting the input - /// @{ - /** @brief Removes self-loop edges (edges where the source and the destination node are the same) - * @param[in, opt. changed] dc The districts container to update - * @param[in, opt. changed] ec The edge container to remove the edges from - * @param[in, opt. changed] tc The traffic lights container to update - * @post Each edge is a uni-directional connection between two different nodes - */ - void removeSelfLoops(NBDistrictCont& dc, NBEdgeCont& ec, NBTrafficLightLogicCont& tc); - - /** @brief Joins edges connecting the same nodes - * @param[in, opt. changed] dc The districts container to update - * @param[in, opt. changed] ec The edge container to remove the edges from - * @param[in, opt. changed] tc The traffic lights container to update - * @post No two edges with same geometry connecting same nodes exist - */ - void joinSimilarEdges(NBDistrictCont& dc, NBEdgeCont& ec, NBTrafficLightLogicCont& tlc); - - /// @brief fix overlap - void avoidOverlap(); - - /** @brief Removes sequences of edges that are not connected with a junction. - * Simple roads without junctions sometimes remain when converting from OpenStreetMap, - * but they make no sense. Remaining empty nodes are also deleted. - * - * @param[in, opt. changed] dc The district container needed if edges shall be removed - * @param[in, opt. changed] ec The container with the edge to be tested - */ - void removeIsolatedRoads(NBDistrictCont& dc, NBEdgeCont& ec); - - /** @brief Checks the network for weak connectivity and removes all but the largest components. - * The connectivity check is done regardless of edge direction and vclass. - * - * @param[in, opt. changed] dc The district container needed if edges shall be removed - * @param[in, opt. changed] ec The container with the edge to be tested - * @param[in] numKeep The number of components to keep - */ - void removeComponents(NBDistrictCont& dc, NBEdgeCont& ec, const int numKeep); - - /** @brief Removes "unwished" nodes - * - * Removes nodes if a) no incoming/outgoing edges exist or - * b) if the node is a "geometry" node. In the second case, - * edges that participate at the node will be joined. - * Whether the node is a geometry node or not, is determined - * by a call to NBNode::checkIsRemovable. - * The node is removed from the list of tls-controlled nodes. - * @param[in, opt. changed] dc The district container needed if a node shall be removed - * @param[in, opt. changed] ec The edge container needed for joining edges - * @param[in, opt. changed] tlc The traffic lights container to remove nodes from - * @param[in] removeGeometryNodes Whether geometry nodes shall also be removed - * @return The number of removed nodes - */ - int removeUnwishedNodes(NBDistrictCont& dc, NBEdgeCont& ec, NBTrafficLightLogicCont& tlc, - NBPTStopCont& sc, NBPTLineCont& lc, - NBParkingCont& pc, - bool removeGeometryNodes); - /// @} - - /// @name Methods for guessing/computing traffic lights - /// @{ - /** @brief Guesses which junctions or junction clusters shall be controlled by tls - * @param[in] oc The options that steer the guessing process - * @param[filled] tlc The traffic lights control into which new traffic light definitions shall be stored - * @todo Recheck exception handling - */ - void guessTLs(OptionsCont& oc, NBTrafficLightLogicCont& tlc); - - /// @brief recheck myGuessedTLS after node logics are computed - void recheckGuessedTLS(NBTrafficLightLogicCont& tlc); - - /** @brief Builds clusters of tls-controlled junctions and joins the control if possible - * @param[changed] tlc The traffic lights control for adding/removing new/prior tls - * @param[in] maxdist The maximum distance between nodes for clustering - * @todo Recheck exception handling - */ - void joinTLS(NBTrafficLightLogicCont& tlc, double maxdist); - - /** @brief Sets the given node as being controlled by a tls - * @param[in] node The node that shall be controlled by a tls - * @param[in] tlc The traffic lights control into which the new traffic light definition shall be stored - * @param[in] type The type of the new tls - * @param[in] id The id of the tls to add - * @todo Recheck exception handling - */ - void setAsTLControlled(NBNode* node, NBTrafficLightLogicCont& tlc, TrafficLightType type, std::string id = ""); - /// @} - - /** @brief Returns whether the node with the id was deleted explicitly - */ - bool wasRemoved(std::string id) const { - return myExtractedNodes.count(id) != 0; - } - - - /// @brief Renames the node. Throws exception if newID already exists - void rename(NBNode* node, const std::string& newID); - - /// divides the incoming lanes on outgoing lanes - void computeLanes2Lanes(); - - /// @brief build the list of outgoing edges and lanes - void computeLogics(const NBEdgeCont& ec); - - /// @brief compute right-of-way logic for all lane-to-lane connections - void computeLogics2(const NBEdgeCont& ec, OptionsCont& oc); - - /// @brief Returns the number of nodes stored in this container - int size() const { - return (int) myNodes.size(); - } - - /// @brief deletes all nodes - void clear(); - - /// @brief generates a new node ID - std::string getFreeID(); - - /** @brief Compute the junction shape for this node - * @param[in] mismatchThreshold The threshold for warning about shapes which are away from myPosition - */ - void computeNodeShapes(double mismatchThreshold = -1); - - /** @brief Prints statistics about built nodes - * - * Goes through stored nodes, computes the numbers of unregulated, priority and right-before-left - * junctions and prints them. - */ - void printBuiltNodesStatistics() const; - - /// @brief get all node names - std::vector getAllNames() const; - - /* @brief analyzes a cluster of nodes which shall be joined - * @param[in] cluster The nodes to be joined - * @param[out] id The name for the new node - * @param[out] pos The position of the new node - * @param[out] hasTLS Whether the new node has a traffic light - * @param[out] tlType The type of traffic light (if any) - */ - void analyzeCluster(NodeSet cluster, std::string& id, Position& pos, - bool& hasTLS, TrafficLightType& type, SumoXMLNodeType& nodeType); - - /// @brief gets all joined clusters (see doc for myClusters2Join) - void registerJoinedCluster(const NodeSet& cluster); - - /// @brief gets all joined clusters (see doc for myClusters2Join) - const std::vector >& getJoinedClusters() const { - return myJoinedClusters; - } - - /* @brief discards traffic lights - * @param[in] geometryLike Whether only tls at geometry-like nodes shall be discarded - */ - void discardTrafficLights(NBTrafficLightLogicCont& tlc, bool geometryLike, bool guessSignals); - - /* @brief discards rail signals - */ - void discardRailSignals(); - - /// @brief mark a node as being created form a split - void markAsSplit(const NBNode* node) { - mySplit.insert(node); - } - - /// @brief remap node IDs accoring to options --numerical-ids and --reserved-ids - int remapIDs(bool numericaIDs, bool reservedIDs, const std::string& prefix); - - /// @brief guess and mark fringe nodes - int guessFringe(); - -private: - - /// @name Helper methods for for joining nodes - /// @{ - /** @brief Builds node clusters - * - * A node cluster is made up from nodes which are near by (distance NodeCont; - - /// @brief The map of names to nodes - NodeCont myNodes; - - /// @brief The extracted nodes which are kept for reference - NodeCont myExtractedNodes; - - /// @brief set of node ids which should not be joined - std::set myJoinExclusions; - - /// @brief loaded sets of node ids to join (cleared after use) - std::vector, NBNode*> > myClusters2Join; - - /// @brief sets of node ids which were joined - std::vector > myJoinedClusters; - - /// @brief ids found in loaded join clusters used for error checking - std::set myJoined; - - /// @brief nodes that were created when splitting an edge - std::set mySplit; - - /// @brief nodes that received a traffic light due to guessing (--tls.guess) - std::set myGuessedTLS; - - /// @brief node positions for faster lookup - NamedRTree myRTree; - - -private: - /// @brief invalidated copy constructor - NBNodeCont(const NBNodeCont& s); - - /// @brief invalidated assignment operator - NBNodeCont& operator=(const NBNodeCont& s); - -}; diff --git a/Util/OSM2ODR/src/netbuild/NBNodeShapeComputer.cpp b/Util/OSM2ODR/src/netbuild/NBNodeShapeComputer.cpp deleted file mode 100644 index b3204a28d..000000000 --- a/Util/OSM2ODR/src/netbuild/NBNodeShapeComputer.cpp +++ /dev/null @@ -1,1032 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NBNodeShapeComputer.cpp -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date Sept 2002 -/// -// This class computes shapes of junctions -/****************************************************************************/ -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "NBNode.h" -#include "NBNodeShapeComputer.h" - -//#define DEBUG_NODE_SHAPE -//#define DEBUG_SMOOTH_CORNERS -//#define DEBUG_RADIUS -#define DEBUGCOND (myNode.getID() == "C") - - -#define EXT 100.0 -#define EXT2 10.0 - -// foot- and bicycle paths as well as pure service roads should not get larget junctions -// railways also do have have junctions with sharp turns so can be excluded -const SVCPermissions NBNodeShapeComputer::SVC_LARGE_TURN( - SVCAll & ~(SVC_BICYCLE | SVC_PEDESTRIAN | SVC_DELIVERY | SVC_RAIL_CLASSES)); - -// =========================================================================== -// method definitions -// =========================================================================== -NBNodeShapeComputer::NBNodeShapeComputer(const NBNode& node) : - myNode(node), - myRadius(node.getRadius()) { -} - - -NBNodeShapeComputer::~NBNodeShapeComputer() {} - - -PositionVector -NBNodeShapeComputer::compute() { - PositionVector ret; - // check whether the node is a dead end node or a node where only turning is possible - // in this case, we will use "computeNodeShapeSmall" - bool singleDirection = false; - if (myNode.getEdges().size() == 1) { - singleDirection = true; - } - if (myNode.getEdges().size() == 2 && myNode.getIncomingEdges().size() == 1) { - if (myNode.getIncomingEdges()[0]->isTurningDirectionAt(myNode.getOutgoingEdges()[0])) { - singleDirection = true; - } - } -#ifdef DEBUG_NODE_SHAPE - if (DEBUGCOND) { - // annotate edges edges to make their ordering visible - int i = 0; - for (NBEdge* e : myNode.getEdges()) { - e->setStreetName(toString(i)); - i++; - } - } -#endif - if (singleDirection) { - return computeNodeShapeSmall(); - } - // check whether the node is a just something like a geometry - // node (one in and one out or two in and two out, pair-wise continuations) - // also in this case "computeNodeShapeSmall" is used - bool geometryLike = myNode.isSimpleContinuation(true, true); - if (geometryLike) { - // additionally, the angle between the edges must not be larger than 45 degrees - // (otherwise, we will try to compute the shape in a different way) - const EdgeVector& incoming = myNode.getIncomingEdges(); - const EdgeVector& outgoing = myNode.getOutgoingEdges(); - double maxAngle = 0.; - for (EdgeVector::const_iterator i = incoming.begin(); i != incoming.end(); ++i) { - double ia = (*i)->getAngleAtNode(&myNode); - for (EdgeVector::const_iterator j = outgoing.begin(); j != outgoing.end(); ++j) { - double oa = (*j)->getAngleAtNode(&myNode); - double ad = GeomHelper::getMinAngleDiff(ia, oa); - if (22.5 >= ad) { - maxAngle = MAX2(ad, maxAngle); - } - } - } - if (maxAngle > 22.5) { - return computeNodeShapeSmall(); - } - } - - // - ret = computeNodeShapeDefault(geometryLike); - // fail fall-back: use "computeNodeShapeSmall" - if (ret.size() < 3) { - ret = computeNodeShapeSmall(); - } - return ret; -} - - -void -computeSameEnd(PositionVector& l1, PositionVector& l2) { - assert(l1[0].distanceTo2D(l1[1]) >= EXT); - assert(l2[0].distanceTo2D(l2[1]) >= EXT); - PositionVector tmp; - tmp.push_back(PositionVector::positionAtOffset2D(l1[0], l1[1], EXT)); - tmp.push_back(l1[1]); - tmp[1].sub(tmp[0]); - tmp[1].set(-tmp[1].y(), tmp[1].x()); - tmp[1].add(tmp[0]); - tmp.extrapolate2D(EXT); - if (l2.intersects(tmp[0], tmp[1])) { - const double offset = l2.intersectsAtLengths2D(tmp)[0]; - if (l2.length2D() - offset > POSITION_EPS) { - PositionVector tl2 = l2.getSubpart2D(offset, l2.length2D()); - tl2.extrapolate2D(EXT); - l2.erase(l2.begin(), l2.begin() + (l2.size() - tl2.size())); - l2[0] = tl2[0]; - } - } -} - - -PositionVector -NBNodeShapeComputer::computeNodeShapeDefault(bool simpleContinuation) { - // if we have less than two edges, we can not compute the node's shape this way - if (myNode.getEdges().size() < 2) { - return PositionVector(); - } - // magic values - const OptionsCont& oc = OptionsCont::getOptions(); - const double defaultRadius = getDefaultRadius(oc); - const bool useDefaultRadius = myNode.getRadius() == NBNode::UNSPECIFIED_RADIUS || myNode.getRadius() == defaultRadius; - myRadius = (useDefaultRadius ? defaultRadius : myNode.getRadius()); - const double smallRadius = oc.getFloat("junctions.small-radius"); - const int cornerDetail = oc.getInt("junctions.corner-detail"); - const double sCurveStretch = oc.getFloat("junctions.scurve-stretch"); - const bool rectangularCut = oc.getBool("rectangular-lane-cut"); - const bool openDriveOutput = oc.isSet("opendrive-output"); - - // Extend geometries to move the stop line forward. - // In OpenDrive the junction starts whenever the geometry changes. Stop - // line information is not given or ambiguous (sign positions at most) - // In SUMO, stop lines are where the junction starts. This is computed - // heuristically from intersecting the junctions roads geometries. - const double advanceStopLine = oc.exists("opendrive-files") && oc.isSet("opendrive-files") ? oc.getFloat("opendrive.advance-stopline") : 0; - - -#ifdef DEBUG_NODE_SHAPE - if (DEBUGCOND) { - std::cout << "\ncomputeNodeShapeDefault node " << myNode.getID() << " simple=" << simpleContinuation << " useDefaultRadius=" << useDefaultRadius << " radius=" << myRadius << "\n"; - } -#endif - - // initialise - EdgeVector::const_iterator i; - // edges located in the value-vector have the same direction as the key edge - std::map > same; - // the counter-clockwise boundary of the edge regarding possible same-direction edges - GeomsMap geomsCCW; - // the clockwise boundary of the edge regarding possible same-direction edges - GeomsMap geomsCW; - EdgeVector usedEdges = myNode.getEdges(); - computeEdgeBoundaries(usedEdges, geomsCCW, geomsCW); - - // check which edges are parallel - joinSameDirectionEdges(usedEdges, same); - // compute unique direction list - EdgeVector newAll = computeUniqueDirectionList(usedEdges, same, geomsCCW, geomsCW); - // if we have only two "directions", let's not compute the geometry using this method - if (newAll.size() < 2) { - return PositionVector(); - } - - // All geoms are outoing from myNode. - // for every direction in newAll we compute the offset at which the - // intersection ends and the edge starts. This value is saved in 'distances' - // If the geometries need to be extended to get an intersection, this is - // recorded in 'myExtended' - std::map distances; - std::map myExtended; - - for (i = newAll.begin(); i != newAll.end(); ++i) { - EdgeVector::const_iterator cwi = i; - EdgeVector::const_iterator ccwi = i; - double ccad; - double cad; - initNeighbors(newAll, i, geomsCW, geomsCCW, cwi, ccwi, cad, ccad); - assert(geomsCCW.find(*i) != geomsCCW.end()); - assert(geomsCW.find(*ccwi) != geomsCW.end()); - assert(geomsCW.find(*cwi) != geomsCW.end()); - - // there are only 2 directions and they are almost parallel - if (*cwi == *ccwi && - ( - // no change in lane numbers, even low angles still give a good intersection - (simpleContinuation && fabs(ccad - cad) < (double) 0.1) - // lane numbers change, a direct intersection could be far away from the node position - // so we use a larger threshold - || (!simpleContinuation && fabs(ccad - cad) < DEG2RAD(22.5))) - ) { - // compute the mean position between both edges ends ... - Position p; - if (myExtended.find(*ccwi) != myExtended.end()) { - p = geomsCCW[*ccwi][0]; - p.add(geomsCW[*ccwi][0]); - p.mul(0.5); -#ifdef DEBUG_NODE_SHAPE - if (DEBUGCOND) { - std::cout << " extended: p=" << p << " angle=" << (ccad - cad) << "\n"; - } -#endif - } else { - p = geomsCCW[*ccwi][0]; - p.add(geomsCW[*ccwi][0]); - p.add(geomsCCW[*i][0]); - p.add(geomsCW[*i][0]); - p.mul(0.25); -#ifdef DEBUG_NODE_SHAPE - if (DEBUGCOND) { - std::cout << " unextended: p=" << p << " angle=" << (ccad - cad) << "\n"; - } -#endif - } - // ... compute the distance to this point ... - double dist = MAX2( - geomsCCW[*i].nearest_offset_to_point2D(p), - geomsCW[*i].nearest_offset_to_point2D(p)); - if (dist < 0) { - // ok, we have the problem that even the extrapolated geometry - // does not reach the point - // in this case, the geometry has to be extenden... too bad ... - // ... let's append the mean position to the geometry - PositionVector g = (*i)->getGeometry(); - if (myNode.hasIncoming(*i)) { - g.push_back_noDoublePos(p); - } else { - g.push_front_noDoublePos(p); - } - (*i)->setGeometry(g); - // and rebuild previous information - geomsCCW[*i] = (*i)->getCCWBoundaryLine(myNode); - geomsCCW[*i].extrapolate(EXT); - geomsCW[*i] = (*i)->getCWBoundaryLine(myNode); - geomsCW[*i].extrapolate(EXT); - // the distance is now = zero (the point we have appended) - distances[*i] = EXT; - myExtended[*i] = true; -#ifdef DEBUG_NODE_SHAPE - if (DEBUGCOND) { - std::cout << " extending (dist=" << dist << ")\n"; - } -#endif - } else { - if (!simpleContinuation) { - dist += myRadius; - } else { - // if the angles change, junction should have some size to avoid degenerate shape - double radius2 = fabs(ccad - cad) * (*i)->getNumLanes(); - if (radius2 > NUMERICAL_EPS || openDriveOutput) { - radius2 = MAX2(0.15, radius2); - } - dist += radius2; -#ifdef DEBUG_NODE_SHAPE - if (DEBUGCOND) { - std::cout << " using radius=" << fabs(ccad - cad) * (*i)->getNumLanes() << " ccad=" << ccad << " cad=" << cad << "\n"; - } -#endif - } - distances[*i] = dist; - } - - } else { - // the angles are different enough to compute the intersection of - // the outer boundaries directly (or there are more than 2 directions). The "nearer" neighbar causes the furthest distance - const bool ccwCloser = ccad < cad; - const bool cwLargeTurn = needsLargeTurn(*i, *cwi, same); - const bool ccwLargeTurn = needsLargeTurn(*i, *ccwi, same); - const bool neighLargeTurn = ccwCloser ? ccwLargeTurn : cwLargeTurn; - const bool neigh2LargeTurn = ccwCloser ? cwLargeTurn : ccwLargeTurn; - // the border facing the closer neighbor - const PositionVector& currGeom = ccwCloser ? geomsCCW[*i] : geomsCW[*i]; - // the border facing the far neighbor - const PositionVector& currGeom2 = ccwCloser ? geomsCW[*i] : geomsCCW[*i]; - // the border of the closer neighbor - const PositionVector& neighGeom = ccwCloser ? geomsCW[*ccwi] : geomsCCW[*cwi]; - // the border of the far neighbor - const PositionVector& neighGeom2 = ccwCloser ? geomsCCW[*cwi] : geomsCW[*ccwi]; -#ifdef DEBUG_NODE_SHAPE - if (DEBUGCOND) { - std::cout << " i=" << (*i)->getID() << " neigh=" << (*ccwi)->getID() << " neigh2=" << (*cwi)->getID() << "\n"; - std::cout << " ccwCloser=" << ccwCloser - << "\n currGeom=" << currGeom << " neighGeom=" << neighGeom - << "\n currGeom2=" << currGeom2 << " neighGeom2=" << neighGeom2 - << "\n"; - } -#endif - if (!simpleContinuation) { - if (currGeom.intersects(neighGeom)) { - distances[*i] = (neighLargeTurn ? myRadius : smallRadius) + closestIntersection(currGeom, neighGeom, EXT); -#ifdef DEBUG_NODE_SHAPE - if (DEBUGCOND) { - std::cout << " neigh intersects dist=" << distances[*i] << " currGeom=" << currGeom << " neighGeom=" << neighGeom << "\n"; - } -#endif - if (*cwi != *ccwi && currGeom2.intersects(neighGeom2)) { - // also use the second intersection point - // but prevent very large node shapes - const double farAngleDist = ccwCloser ? cad : ccad; - double a1 = distances[*i]; - double a2 = (neigh2LargeTurn ? myRadius : smallRadius) + closestIntersection(currGeom2, neighGeom2, EXT); -#ifdef DEBUG_NODE_SHAPE - if (DEBUGCOND) { - std::cout << " neigh2 also intersects a1=" << a1 << " a2=" << a2 << " ccad=" << RAD2DEG(ccad) << " cad=" << RAD2DEG(cad) << " dist[cwi]=" << distances[*cwi] << " dist[ccwi]=" << distances[*ccwi] << " farAngleDist=" << RAD2DEG(farAngleDist) << " currGeom2=" << currGeom2 << " neighGeom2=" << neighGeom2 << "\n"; - } -#endif - //if (RAD2DEG(farAngleDist) < 175) { - // distances[*i] = MAX2(a1, MIN2(a2, a1 + 180 - RAD2DEG(farAngleDist))); - //} - if (a2 <= EXT) { - distances[*i] = MAX2(a1, a2); - } else if (ccad > DEG2RAD(90. + 45.) && cad > DEG2RAD(90. + 45.)) { - // do nothing. - } else if (farAngleDist < DEG2RAD(135) || (fabs(RAD2DEG(farAngleDist) - 180) > 1 && fabs(a2 - a1) < 10)) { - distances[*i] = MAX2(a1, a2); - } -#ifdef DEBUG_NODE_SHAPE - if (DEBUGCOND) { - std::cout << " a1=" << a1 << " a2=" << a2 << " dist=" << distances[*i] << "\n"; - } -#endif - } - } else { - if (*cwi != *ccwi && currGeom2.intersects(neighGeom2)) { - distances[*i] = (neigh2LargeTurn ? myRadius : smallRadius) + currGeom2.intersectsAtLengths2D(neighGeom2)[0]; -#ifdef DEBUG_NODE_SHAPE - if (DEBUGCOND) { - std::cout << " neigh2 intersects dist=" << distances[*i] << " currGeom2=" << currGeom2 << " neighGeom2=" << neighGeom2 << "\n"; - } -#endif - } else { - distances[*i] = EXT + myRadius; -#ifdef DEBUG_NODE_SHAPE - if (DEBUGCOND) { - std::cout << " no intersects dist=" << distances[*i] << " currGeom=" << currGeom << " neighGeom=" << neighGeom << " currGeom2=" << currGeom2 << " neighGeom2=" << neighGeom2 << "\n"; - } -#endif - } - } - } else { - if (currGeom.intersects(neighGeom)) { - distances[*i] = currGeom.intersectsAtLengths2D(neighGeom)[0]; - } else { - distances[*i] = (double) EXT; - } - } - } - if (useDefaultRadius && sCurveStretch > 0) { - double sCurveWidth = myNode.getDisplacementError(); - if (sCurveWidth > 0) { - const double sCurveRadius = myRadius + sCurveWidth / SUMO_const_laneWidth * sCurveStretch * pow((*i)->getSpeed(), 2 + sCurveStretch) / 1000; - const double stretch = EXT + sCurveRadius - distances[*i]; - if (stretch > 0) { - distances[*i] += stretch; - // fixate extended geometry for repeated computation - const double shorten = distances[*i] - EXT; - (*i)->shortenGeometryAtNode(&myNode, shorten); - for (std::set::iterator k = same[*i].begin(); k != same[*i].end(); ++k) { - (*k)->shortenGeometryAtNode(&myNode, shorten); - } -#ifdef DEBUG_NODE_SHAPE - if (DEBUGCOND) { - std::cout << " stretching junction: sCurveWidth=" << sCurveWidth << " sCurveRadius=" << sCurveRadius << " stretch=" << stretch << " dist=" << distances[*i] << "\n"; - } -#endif - } - } - } - } - - for (i = newAll.begin(); i != newAll.end(); ++i) { - if (distances.find(*i) == distances.end()) { - assert(false); - distances[*i] = EXT; - } - } - // prevent inverted node shapes - // (may happen with near-parallel edges) - const double minDistSum = 2 * (EXT + myRadius); - for (i = newAll.begin(); i != newAll.end(); ++i) { - if (distances[*i] < EXT && (*i)->hasDefaultGeometryEndpointAtNode(&myNode)) { - for (EdgeVector::const_iterator j = newAll.begin(); j != newAll.end(); ++j) { - if (distances[*j] > EXT && (*j)->hasDefaultGeometryEndpointAtNode(&myNode) && distances[*i] + distances[*j] < minDistSum) { - const double angleDiff = fabs(NBHelpers::relAngle((*i)->getAngleAtNode(&myNode), (*j)->getAngleAtNode(&myNode))); - if (angleDiff > 160 || angleDiff < 20) { -#ifdef DEBUG_NODE_SHAPE - if (DEBUGCOND) { - std::cout << " increasing dist for i=" << (*i)->getID() << " because of j=" << (*j)->getID() << " jDist=" << distances[*j] - << " oldI=" << distances[*i] << " newI=" << minDistSum - distances[*j] - << " angleDiff=" << angleDiff - << " geomI=" << (*i)->getGeometry() << " geomJ=" << (*j)->getGeometry() << "\n"; - } -#endif - distances[*i] = minDistSum - distances[*j]; - } - } - } - } - } - - - // build - PositionVector ret; - for (i = newAll.begin(); i != newAll.end(); ++i) { - const PositionVector& ccwBound = geomsCCW[*i]; - const PositionVector& cwBound = geomsCW[*i]; - //double offset = MIN3(distances[*i], cwBound.length2D() - POSITION_EPS, ccwBound.length2D() - POSITION_EPS); - double offset = distances[*i]; - if (!(*i)->hasDefaultGeometryEndpointAtNode(&myNode)) { - // for non geometry-endpoints, only shorten but never extend the geometry - if (advanceStopLine > 0 && offset < EXT) { -#ifdef DEBUG_NODE_SHAPE - std::cout << " i=" << (*i)->getID() << " offset=" << offset << " advanceStopLine=" << advanceStopLine << "\n"; -#endif - // fixate extended geometry for repeated computation - (*i)->extendGeometryAtNode(&myNode, advanceStopLine); - for (std::set::iterator k = same[*i].begin(); k != same[*i].end(); ++k) { - (*k)->extendGeometryAtNode(&myNode, advanceStopLine); - } - } - offset = MAX2(EXT - advanceStopLine, offset); - } - if (offset == -1) { - WRITE_WARNING("Fixing offset for edge '" + (*i)->getID() + "' at node '" + myNode.getID() + "."); - offset = (double) - .1; - } - Position p = ccwBound.positionAtOffset2D(offset); - p.setz(myNode.getPosition().z()); - if (i != newAll.begin()) { - ret.append(getSmoothCorner(geomsCW[*(i - 1)], ccwBound, ret[-1], p, cornerDetail)); - } - ret.push_back_noDoublePos(p); - // - Position p2 = cwBound.positionAtOffset2D(offset); - p2.setz(myNode.getPosition().z()); - ret.push_back_noDoublePos(p2); -#ifdef DEBUG_NODE_SHAPE - if (DEBUGCOND) { - std::cout << " build stopLine for i=" << (*i)->getID() << " offset=" << offset << " dist=" << distances[*i] << " cwLength=" << cwBound.length2D() << " ccwLength=" << ccwBound.length2D() << " p=" << p << " p2=" << p2 << " ccwBound=" << ccwBound << " cwBound=" << cwBound << "\n"; - } -#endif - (*i)->setNodeBorder(&myNode, p, p2, rectangularCut); - for (std::set::iterator k = same[*i].begin(); k != same[*i].end(); ++k) { - (*k)->setNodeBorder(&myNode, p, p2, rectangularCut); - } - } - // final curve segment - ret.append(getSmoothCorner(geomsCW[*(newAll.end() - 1)], geomsCCW[*newAll.begin()], ret[-1], ret[0], cornerDetail)); -#ifdef DEBUG_NODE_SHAPE - if (DEBUGCOND) { - std::cout << " final shape=" << ret << "\n"; - } -#endif - return ret; -} - - -double -NBNodeShapeComputer::closestIntersection(const PositionVector& geom1, const PositionVector& geom2, double offset) { - std::vector intersections = geom1.intersectsAtLengths2D(geom2); - double result = intersections[0]; - for (std::vector::iterator it = intersections.begin() + 1; it != intersections.end(); ++it) { - if (fabs(*it - offset) < fabs(result - offset)) { - result = *it; - } - } - return result; -} - -bool -NBNodeShapeComputer::needsLargeTurn(NBEdge* e1, NBEdge* e2, - std::map >& same) const { - const SVCPermissions p1 = e1->getPermissions(); - const SVCPermissions p2 = e2->getPermissions(); - if ((p1 & p2 & SVC_LARGE_TURN) != 0) { - // note: would could also check whether there is actually a connection - // between those edges - return true; - } - // maybe edges in the same direction need a large turn - for (NBEdge* e2s : same[e2]) { - if ((p1 & e2s->getPermissions() & SVC_LARGE_TURN) != 0 - && (e1->getToNode() == e2s->getFromNode() || e2s->getToNode() == e1->getFromNode())) { - return true; - } - for (NBEdge* e1s : same[e1]) { - if ((e2s->getPermissions() & e1s->getPermissions() & SVC_LARGE_TURN) != 0 - && (e2s->getToNode() == e1s->getFromNode() || e1s->getToNode() == e2s->getFromNode())) { - return true; - } - } - } - for (NBEdge* e1s : same[e1]) { - if ((p2 & e1s->getPermissions() & SVC_LARGE_TURN) != 0 - && (e2->getToNode() == e1s->getFromNode() || e1s->getToNode() == e2->getFromNode())) { - return true; - } - } - //std::cout << " e1=" << e1->getID() << " e2=" << e2->getID() << " sameE1=" << toString(same[e1]) << " sameE2=" << toString(same[e2]) << "\n"; - return false; -} - -PositionVector -NBNodeShapeComputer::getSmoothCorner(PositionVector begShape, PositionVector endShape, - const Position& begPoint, const Position& endPoint, int cornerDetail) { - PositionVector ret; - if (cornerDetail > 0) { - PositionVector begShape2 = begShape.reverse().getSubpart2D(EXT2, begShape.length()); - const double begSplit = begShape2.nearest_offset_to_point2D(begPoint, false); -#ifdef DEBUG_SMOOTH_CORNERS - if (DEBUGCOND) { - std::cout << " begLength=" << begShape2.length2D() << " begSplit=" << begSplit << "\n"; - } -#endif - if (begSplit > POSITION_EPS && begSplit < begShape2.length2D() - POSITION_EPS) { - begShape2 = begShape2.splitAt(begSplit, true).first; - } else { - return ret; - } - PositionVector endShape2 = endShape.getSubpart(0, endShape.length() - EXT2); - const double endSplit = endShape2.nearest_offset_to_point2D(endPoint, false); -#ifdef DEBUG_SMOOTH_CORNERS - if (DEBUGCOND) { - std::cout << " endLength=" << endShape2.length2D() << " endSplit=" << endSplit << "\n"; - } -#endif - if (endSplit > POSITION_EPS && endSplit < endShape2.length2D() - POSITION_EPS) { - endShape2 = endShape2.splitAt(endSplit, true).second; - } else { - return ret; - } - // flatten z to junction z level - begShape2 = begShape2.interpolateZ(myNode.getPosition().z(), myNode.getPosition().z()); - endShape2 = endShape2.interpolateZ(myNode.getPosition().z(), myNode.getPosition().z()); -#ifdef DEBUG_SMOOTH_CORNERS - if (DEBUGCOND) { - std::cout << "getSmoothCorner begPoint=" << begPoint << " endPoint=" << endPoint - << " begShape=" << begShape << " endShape=" << endShape - << " begShape2=" << begShape2 << " endShape2=" << endShape2 - << "\n"; - } -#endif - if (begShape2.size() < 2 || endShape2.size() < 2) { - return ret; - } - const double angle = GeomHelper::angleDiff(begShape2.angleAt2D(-2), endShape2.angleAt2D(0)); - NBNode* recordError = nullptr; -#ifdef DEBUG_SMOOTH_CORNERS - if (DEBUGCOND) { - std::cout << " angle=" << RAD2DEG(angle) << "\n"; - } - recordError = const_cast(&myNode); -#endif - // fill highly acute corners - //if (fabs(angle) > DEG2RAD(135)) { - // return ret; - //} - PositionVector curve = myNode.computeSmoothShape(begShape2, endShape2, cornerDetail + 2, false, 25, 25, recordError, NBNode::AVOID_WIDE_LEFT_TURN); - //PositionVector curve = myNode.computeSmoothShape(begShape2, endShape2, cornerDetail + 2, false, 25, 25, recordError, 0); - const double curvature = curve.length2D() / MAX2(NUMERICAL_EPS, begPoint.distanceTo2D(endPoint)); -#ifdef DEBUG_SMOOTH_CORNERS - if (DEBUGCOND) { - std::cout << " curve=" << curve << " curveLength=" << curve.length2D() << " dist=" << begPoint.distanceTo2D(endPoint) << " curvature=" << curvature << "\n"; - } -#endif - if (curvature > 2 && angle > DEG2RAD(85)) { - // simplify dubious inside corner shape - return ret; - } - if (curve.size() > 2) { - curve.erase(curve.begin()); - curve.pop_back(); - ret = curve; - } - } - return ret; -} - -void -NBNodeShapeComputer::computeEdgeBoundaries(const EdgeVector& edges, - GeomsMap& geomsCCW, - GeomsMap& geomsCW) { - // compute boundary lines and extend it by EXT m - for (NBEdge* edge : edges) { - // store current edge's boundary as current ccw/cw boundary - try { - geomsCCW[edge] = edge->getCCWBoundaryLine(myNode); - } catch (InvalidArgument& e) { - WRITE_WARNING("While computing intersection geometry at junction '" + myNode.getID() + "': " + std::string(e.what())); - geomsCCW[edge] = edge->getGeometry(); - } - try { - geomsCW[edge] = edge->getCWBoundaryLine(myNode); - } catch (InvalidArgument& e) { - WRITE_WARNING("While computing intersection geometry at junction '" + myNode.getID() + "': " + std::string(e.what())); - geomsCW[edge] = edge->getGeometry(); - } - // ensure the boundary is valid - if (geomsCCW[edge].length2D() < NUMERICAL_EPS) { - geomsCCW[edge] = edge->getGeometry(); - } - if (geomsCW[edge].length2D() < NUMERICAL_EPS) { - geomsCW[edge] = edge->getGeometry(); - } - // extend the boundary by extroplating it by EXT m - geomsCCW[edge].extrapolate2D(EXT, true); - geomsCW[edge].extrapolate2D(EXT, true); - geomsCCW[edge].extrapolate(EXT2, false, true); - geomsCW[edge].extrapolate(EXT2, false, true); - } -} - -void -NBNodeShapeComputer::joinSameDirectionEdges(const EdgeVector& edges, std::map >& same) { - // compute same (edges where an intersection doesn't work well - // (always check an edge and its cw neightbor) - // distance to look ahead for a misleading angle - const double angleChangeLookahead = 35; - EdgeSet foundOpposite; - for (EdgeVector::const_iterator i = edges.begin(); i != edges.end(); i++) { - EdgeVector::const_iterator j; - if (i == edges.end() - 1) { - j = edges.begin(); - } else { - j = i + 1; - } - const bool incoming = (*i)->getToNode() == &myNode; - const bool incoming2 = (*j)->getToNode() == &myNode; - const Position positionAtNode = (*i)->getGeometry()[incoming ? -1 : 0]; - const Position positionAtNode2 = (*j)->getGeometry()[incoming2 ? -1 : 0]; - const PositionVector g1 = incoming ? (*i)->getCCWBoundaryLine(myNode) : (*i)->getCWBoundaryLine(myNode); - const PositionVector g2 = incoming ? (*j)->getCCWBoundaryLine(myNode) : (*j)->getCWBoundaryLine(myNode); - const double angle1further = (g1.size() > 2 && g1[0].distanceTo2D(g1[1]) < angleChangeLookahead ? - g1.angleAt2D(1) : g1.angleAt2D(0)); - const double angle2further = (g2.size() > 2 && g2[0].distanceTo2D(g2[1]) < angleChangeLookahead ? - g2.angleAt2D(1) : g2.angleAt2D(0)); - const double angleDiff = GeomHelper::angleDiff(g1.angleAt2D(0), g2.angleAt2D(0)); - const double angleDiffFurther = GeomHelper::angleDiff(angle1further, angle2further); - const bool ambiguousGeometry = ((angleDiff > 0 && angleDiffFurther < 0) || (angleDiff < 0 && angleDiffFurther > 0)); - const bool differentDirs = (incoming != incoming2); - //if (ambiguousGeometry) { - // @todo: this warning would be helpful in many cases. However, if angle and angleFurther jump between 179 and -179 it is misleading - // WRITE_WARNING("Ambigous angles at junction '" + myNode.getID() + "' for edges '" + (*i)->getID() + "' and '" + (*j)->getID() + "'."); - //} -#ifdef DEBUG_NODE_SHAPE - if (DEBUGCOND) { - std::cout << " checkSameDirection " << (*i)->getID() << " " << (*j)->getID() - << " diffDirs=" << differentDirs - << " isOpposite=" << (differentDirs && foundOpposite.count(*i) == 0) - << " angleDiff=" << angleDiff - << " ambiguousGeometry=" << ambiguousGeometry - << " badIntersect=" << badIntersection(*i, *j, EXT) - << "\n"; - - } -#endif - if (fabs(angleDiff) < DEG2RAD(20)) { - const bool isOpposite = differentDirs && foundOpposite.count(*i) == 0; - if (isOpposite) { - foundOpposite.insert(*i); - foundOpposite.insert(*j); - } - if (isOpposite || ambiguousGeometry || badIntersection(*i, *j, EXT)) { - // maintain equivalence relation for all members of the equivalence class - for (std::set::iterator k = same[*i].begin(); k != same[*i].end(); ++k) { - if (*j != *k) { - same[*k].insert(*j); - same[*j].insert(*k); - } - } - for (std::set::iterator k = same[*j].begin(); k != same[*j].end(); ++k) { - if (*i != *k) { - same[*k].insert(*i); - same[*i].insert(*k); - } - } - same[*i].insert(*j); - same[*j].insert(*i); -#ifdef DEBUG_NODE_SHAPE - if (DEBUGCOND) { - std::cout << " joinedSameDirectionEdges " << (*i)->getID() << " " << (*j)->getID() << " isOpposite=" << isOpposite << " ambiguousGeometry=" << ambiguousGeometry << "\n"; - } -#endif - } - } - } -} - - -bool -NBNodeShapeComputer::badIntersection(const NBEdge* e1, const NBEdge* e2, double distance) { - // check whether the two edges are on top of each other. In that case they should be joined - // also, if they never touch along their common length - const double commonLength = MIN3(distance, e1->getGeometry().length(), e2->getGeometry().length()); - PositionVector geom1 = e1->getGeometry(); - PositionVector geom2 = e2->getGeometry(); - // shift to make geom the centerline of the edge regardless of spreadtype - if (e1->getLaneSpreadFunction() == LaneSpreadFunction::RIGHT) { - geom1.move2side(e1->getTotalWidth() / 2); - } - if (e2->getLaneSpreadFunction() == LaneSpreadFunction::RIGHT) { - geom2.move2side(e2->getTotalWidth() / 2); - } - // always let geometry start at myNode - if (e1->getToNode() == &myNode) { - geom1 = geom1.reverse(); - } - if (e2->getToNode() == &myNode) { - geom2 = geom2.reverse(); - } - geom1 = geom1.getSubpart2D(0, commonLength); - geom2 = geom2.getSubpart2D(0, commonLength); - double endAngleDiff = 0; - if (geom1.size() >= 2 && geom2.size() >= 2) { - endAngleDiff = fabs(RAD2DEG(GeomHelper::angleDiff( - geom1.angleAt2D((int)geom1.size() - 2), - geom2.angleAt2D((int)geom2.size() - 2)))); - } - const double minDistanceThreshold = (e1->getTotalWidth() + e2->getTotalWidth()) / 2 + POSITION_EPS; - std::vector distances = geom1.distances(geom2, true); - const double minDist = VectorHelper::minValue(distances); - const double maxDist = VectorHelper::maxValue(distances); - const bool curvingTowards = geom1[0].distanceTo2D(geom2[0]) > minDistanceThreshold && minDist < minDistanceThreshold; - const bool onTop = (maxDist - POSITION_EPS < minDistanceThreshold) && endAngleDiff < 30; - geom1.extrapolate2D(EXT); - geom2.extrapolate2D(EXT); - Position intersect = geom1.intersectionPosition2D(geom2); - const bool intersects = intersect != Position::INVALID && geom1.distance2D(intersect) < POSITION_EPS; -#ifdef DEBUG_NODE_SHAPE - if (DEBUGCOND) { - std::cout << " badIntersect: onTop=" << onTop << " curveTo=" << curvingTowards << " intersects=" << intersects - << " endAngleDiff=" << endAngleDiff - << " geom1=" << geom1 << " geom2=" << geom2 - << " distances=" << toString(distances) << " minDist=" << minDist << " maxDist=" << maxDist << " thresh=" << minDistanceThreshold - << " intersectPos=" << intersect - << "\n"; - } -#endif - return onTop || curvingTowards || !intersects; -} - - -EdgeVector -NBNodeShapeComputer::computeUniqueDirectionList( - const EdgeVector& all, - std::map >& same, - GeomsMap& geomsCCW, - GeomsMap& geomsCW) { - // store relationships - EdgeVector newAll = all; - for (NBEdge* e1 : all) { - // determine which of the edges marks the outer boundary - auto e2NewAll = std::find(newAll.begin(), newAll.end(), e1); -#ifdef DEBUG_NODE_SHAPE - if (DEBUGCOND) std::cout << "computeUniqueDirectionList e1=" << e1->getID() - << " deleted=" << (e2NewAll == newAll.end()) - << " same=" << joinNamedToStringSorting(same[e1], ',') << "\n"; -#endif - if (e2NewAll == newAll.end()) { - continue; - } - auto e1It = std::find(all.begin(), all.end(), e1); - auto bestCCW = e1It; - auto bestCW = e1It; - bool changed = true; - while (changed) { - changed = false; - for (NBEdge* e2 : same[e1]) { -#ifdef DEBUG_NODE_SHAPE - if (DEBUGCOND) { - std::cout << " e2=" << e2->getID() << "\n"; - } -#endif - auto e2It = std::find(all.begin(), all.end(), e2); - if (e2It + 1 == bestCCW || (e2It == (all.end() - 1) && bestCCW == all.begin())) { - bestCCW = e2It; - changed = true; -#ifdef DEBUG_NODE_SHAPE - if (DEBUGCOND) { - std::cout << " bestCCW=" << e2->getID() << "\n"; - } -#endif - } else if (bestCW + 1 == e2It || (bestCW == (all.end() - 1) && e2It == all.begin())) { - bestCW = e2It; - changed = true; -#ifdef DEBUG_NODE_SHAPE - if (DEBUGCOND) { - std::cout << " bestCW=" << e2->getID() << "\n"; - } -#endif - } - } - } - if (bestCW != e1It) { - geomsCW[e1] = geomsCW[*bestCW]; - computeSameEnd(geomsCW[e1], geomsCCW[e1]); - } - if (bestCCW != e1It) { - geomsCCW[e1] = geomsCCW[*bestCCW]; - computeSameEnd(geomsCW[e1], geomsCCW[e1]); - } - // clean up - for (NBEdge* e2 : same[e1]) { - auto e2NewAll = std::find(newAll.begin(), newAll.end(), e2); - if (e2NewAll != newAll.end()) { - newAll.erase(e2NewAll); - } - } - } -#ifdef DEBUG_NODE_SHAPE - if (DEBUGCOND) { - std::cout << " newAll:\n"; - for (NBEdge* e : newAll) { - std::cout << " " << e->getID() << " geomCCW=" << geomsCCW[e] << " geomsCW=" << geomsCW[e] << "\n"; - } - } -#endif - return newAll; -} - - -void -NBNodeShapeComputer::initNeighbors(const EdgeVector& edges, const EdgeVector::const_iterator& current, - GeomsMap& geomsCW, - GeomsMap& geomsCCW, - EdgeVector::const_iterator& cwi, - EdgeVector::const_iterator& ccwi, - double& cad, - double& ccad) { - const double twoPI = (double)(2 * M_PI); - cwi = current; - cwi++; - if (cwi == edges.end()) { - std::advance(cwi, -((int)edges.size())); // set to edges.begin(); - } - ccwi = current; - if (ccwi == edges.begin()) { - std::advance(ccwi, edges.size() - 1); // set to edges.end() - 1; - } else { - ccwi--; - } - - const double angleCurCCW = geomsCCW[*current].angleAt2D(0); - const double angleCurCW = geomsCW[*current].angleAt2D(0); - const double angleCCW = geomsCW[*ccwi].angleAt2D(0); - const double angleCW = geomsCCW[*cwi].angleAt2D(0); - ccad = angleCCW - angleCurCCW; - while (ccad < 0.) { - ccad += twoPI; - } - cad = angleCurCW - angleCW; - while (cad < 0.) { - cad += twoPI; - } -} - - - -PositionVector -NBNodeShapeComputer::computeNodeShapeSmall() { -#ifdef DEBUG_NODE_SHAPE - if (DEBUGCOND) { - std::cout << "computeNodeShapeSmall node=" << myNode.getID() << "\n"; - } -#endif - PositionVector ret; - for (NBEdge* e : myNode.getEdges()) { - // compute crossing with normal - PositionVector edgebound1 = e->getCCWBoundaryLine(myNode).getSubpartByIndex(0, 2); - PositionVector edgebound2 = e->getCWBoundaryLine(myNode).getSubpartByIndex(0, 2); - Position delta = edgebound1[1] - edgebound1[0]; - delta.set(-delta.y(), delta.x()); // rotate 90 degrees - PositionVector cross(myNode.getPosition(), myNode.getPosition() + delta); - cross.extrapolate2D(500); - edgebound1.extrapolate2D(500); - edgebound2.extrapolate2D(500); - if (cross.intersects(edgebound1)) { - Position np = cross.intersectionPosition2D(edgebound1); - np.set(np.x(), np.y(), myNode.getPosition().z()); - ret.push_back_noDoublePos(np); - } - if (cross.intersects(edgebound2)) { - Position np = cross.intersectionPosition2D(edgebound2); - np.set(np.x(), np.y(), myNode.getPosition().z()); - ret.push_back_noDoublePos(np); - } - e->resetNodeBorder(&myNode); - } - return ret; -} - - -double -NBNodeShapeComputer::getDefaultRadius(const OptionsCont& oc) { - // look for incoming/outgoing edge pairs that do not go straight and allow wide vehicles - // (connection information is not available yet) - // @TODO compute the radius for each pair of neighboring edge intersections in computeNodeShapeDefault rather than use the maximum - const double radius = oc.getFloat("default.junctions.radius"); - const double smallRadius = oc.getFloat("junctions.small-radius"); - double maxRightAngle = 0; // rad - double extraWidthRight = 0; // m - double maxLeftAngle = 0; // rad - double extraWidthLeft = 0; // m - int laneDelta = 0; - for (NBEdge* in : myNode.getIncomingEdges()) { - int wideLanesIn = 0; - for (int i = 0; i < in->getNumLanes(); i++) { - if ((in->getPermissions(i) & SVC_LARGE_TURN) != 0) { - wideLanesIn++; - } - } - for (NBEdge* out : myNode.getOutgoingEdges()) { - if ((in->getPermissions() & out->getPermissions() & SVC_LARGE_TURN) != 0) { - if (myNode.getDirection(in, out) == LinkDirection::TURN) { - continue; - }; - const double angle = GeomHelper::angleDiff( - in->getGeometry().angleAt2D(-2), - out->getGeometry().angleAt2D(0)); - if (angle < 0) { - if (maxRightAngle < -angle) { - maxRightAngle = -angle; - extraWidthRight = MAX2(getExtraWidth(in, SVC_LARGE_TURN), getExtraWidth(out, SVC_LARGE_TURN)); - } - } else { - if (maxLeftAngle < angle) { - maxLeftAngle = angle; - // all edges clockwise between in and out count as extra width - extraWidthLeft = 0; - EdgeVector::const_iterator pIn = std::find(myNode.getEdges().begin(), myNode.getEdges().end(), in); - NBContHelper::nextCW(myNode.getEdges(), pIn); - while (*pIn != out) { - extraWidthLeft += (*pIn)->getTotalWidth(); -//#ifdef DEBUG_RADIUS -// if (DEBUGCOND) { -// std::cout << " in=" << in->getID() << " out=" << out->getID() << " extra=" << (*pIn)->getID() << " extraWidthLeft=" << extraWidthLeft << "\n"; -// } -//#endif - NBContHelper::nextCW(myNode.getEdges(), pIn); - } - } - } - int wideLanesOut = 0; - for (int i = 0; i < out->getNumLanes(); i++) { - if ((out->getPermissions(i) & SVC_LARGE_TURN) != 0) { - wideLanesOut++; - } - } - laneDelta = MAX2(laneDelta, abs(wideLanesOut - wideLanesIn)); - } - } - } - // changing the number of wide-vehicle lanes on a straight segment requires a larger junction to allow for smooth driving - // otherwise we can reduce the radius according to the angle - double result = radius; - // left turns are assumed to cross additional edges and thus du not determine the required radius in most cases - double maxTurnAngle = maxRightAngle; - double extraWidth = extraWidthRight; - if (maxRightAngle < DEG2RAD(5)) { - maxTurnAngle = maxLeftAngle; - extraWidth = extraWidthLeft; - } - if (laneDelta == 0 || maxTurnAngle >= DEG2RAD(30) || myNode.isConstantWidthTransition()) { - // subtract radius gained from extra lanes - // do not increase radius for turns that are sharper than a right angle - result = MAX2(smallRadius, radius * tan(0.5 * MIN2(0.5 * M_PI, maxTurnAngle)) - extraWidth); - } -#ifdef DEBUG_RADIUS - if (DEBUGCOND) { - std::cout << "getDefaultRadius n=" << myNode.getID() << " laneDelta=" << laneDelta - << " rightA=" << RAD2DEG(maxRightAngle) - << " leftA=" << RAD2DEG(maxLeftAngle) - << " maxA=" << RAD2DEG(maxTurnAngle) - << " extraWidth=" << extraWidth - << " result=" << result << "\n"; - } -#endif - return result; -} - - -double -NBNodeShapeComputer::getExtraWidth(const NBEdge* e, SVCPermissions exclude) { - double result = 0; - int lane = 0; - while (lane < e->getNumLanes() && e->getPermissions(lane) == 0) { - // ignore forbidden lanes out the outside - lane++; - } - while (lane < e->getNumLanes() && (e->getPermissions(lane) & exclude) == 0) { - result += e->getLaneWidth(lane); - lane++; - } - return result; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netbuild/NBNodeShapeComputer.h b/Util/OSM2ODR/src/netbuild/NBNodeShapeComputer.h deleted file mode 100644 index 10eed52ba..000000000 --- a/Util/OSM2ODR/src/netbuild/NBNodeShapeComputer.h +++ /dev/null @@ -1,167 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NBNodeShapeComputer.h -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date 2004-01-12 -/// -// This class computes shapes of junctions -/****************************************************************************/ -#pragma once -#include - -#include - - -// =========================================================================== -// class definitions -// =========================================================================== -class NBNode; -class NBEdge; - - -// =========================================================================== -// class declarations -// =========================================================================== -/** - * @class NBNodeShapeComputer - * @brief This class computes shapes of junctions - */ -class NBNodeShapeComputer { -public: - /// Constructor - NBNodeShapeComputer(const NBNode& node); - - /// Destructor - ~NBNodeShapeComputer(); - - /// Computes the shape of the assigned junction - PositionVector compute(); - - /// @brief get computed radius for node - double getRadius() const { - return myRadius; - } - -private: - typedef std::map GeomsMap; - - /** @brief Computes the node geometry - * Edges with the same direction are grouped. - * Then the node geometry is built from intersection between the borders - * of adjacent edge groups - */ - PositionVector computeNodeShapeDefault(bool simpleContinuation); - - /** @brief Computes the node geometry using normals - * - * In the case the other method does not work, this method computes the geometry - * of a node by adding points to the polygon which are computed by building - * the normals of participating edges' geometry boundaries (cw/ccw) - * at the node's height (the length of the edge the edge would cross the node - * point). - * - * @note This usually gives a very small node shape, appropriate for - * dead-ends or turn-around-only situations - */ - PositionVector computeNodeShapeSmall(); - - /// @brief compute clockwise/counter-clockwise edge boundaries - void computeEdgeBoundaries(const EdgeVector& edges, - GeomsMap& geomsCCW, - GeomsMap& geomsCW); - - /** @brief Joins edges and computes ccw/cw boundaries - * - * This method goes through all edges and stores each edge's ccw and cw - * boundary in geomsCCW/geomsCW. This boundary is extrapolated by 100m - * at the node's position. - * In addition, "same" is filled so that this map contains a list of - * all edges within the value-vector which direction at the node differs - * less than 1 from the key-edge's direction. - */ - void joinSameDirectionEdges(const EdgeVector& edges, std::map >& same); - - /** @brief Joins edges - * - * This methods joins edges which are in marked as being "same" in the means - * as given by joinSameDirectionEdges. The result (list of so-to-say "directions" - * is returned; - */ - EdgeVector computeUniqueDirectionList( - const EdgeVector& all, - std::map >& same, - GeomsMap& geomsCCW, - GeomsMap& geomsCW); - - /** @brief Compute smoothed corner shape - * @param[in] begShape - * @param[in] endShape - * @param[in] begPoint - * @param[in] endPoint - * @param[in] cornerDetail - * @return shape to be appended between begPoint and endPoint - */ - PositionVector getSmoothCorner(PositionVector begShape, PositionVector endShape, - const Position& begPoint, const Position& endPoint, int cornerDetail); - - /** @brief Initialize neighbors and angles - * @param[in] edges The list of edges sorted in clockwise direction - * @param[in] current An iterator to the current edge - * @param[in] geomsCW geometry map - * @param[in] geomsCCW geometry map - * @param[out] cwi An iterator to the clockwise neighbor - * @param[out] ccwi An iterator to the counter-clockwise neighbor - * @param[out] cad The angle difference to the clockwise neighbor - * @param[out] ccad The angle difference to the counter-clockwise neighbor - */ - static void initNeighbors(const EdgeVector& edges, const EdgeVector::const_iterator& current, - GeomsMap& geomsCW, - GeomsMap& geomsCCW, - EdgeVector::const_iterator& cwi, - EdgeVector::const_iterator& ccwi, - double& cad, - double& ccad); - - /// @return whether trying to intersect these edges would probably fail - bool badIntersection(const NBEdge* e1, const NBEdge* e2, double distance); - - /// @brief return the intersection point closest to the given offset - double closestIntersection(const PositionVector& geom1, const PositionVector& geom2, double offset); - - /// @brief whether the given edges (along with those in the same direction) requires a large turning radius - bool needsLargeTurn(NBEdge* e1, NBEdge* e2, - std::map >& same) const; - - /// @brief determine the default radius appropriate for the current junction - double getDefaultRadius(const OptionsCont& oc); - - /// @brief compute with of rightmost lanes that exlude the given permissions - static double getExtraWidth(const NBEdge* e, SVCPermissions exclude); - -private: - /// The node to compute the geometry for - const NBNode& myNode; - - /// @brief the computed node radius - double myRadius; - - static const SVCPermissions SVC_LARGE_TURN; - -private: - /// @brief Invalidated assignment operator - NBNodeShapeComputer& operator=(const NBNodeShapeComputer& s); - -}; diff --git a/Util/OSM2ODR/src/netbuild/NBOwnTLDef.cpp b/Util/OSM2ODR/src/netbuild/NBOwnTLDef.cpp deleted file mode 100644 index 8f42b47c8..000000000 --- a/Util/OSM2ODR/src/netbuild/NBOwnTLDef.cpp +++ /dev/null @@ -1,1110 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NBOwnTLDef.cpp -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Sascha Krieg -/// @author Michael Behrisch -/// @date Tue, 29.05.2005 -/// -// A traffic light logics which must be computed (only nodes/edges are given) -/****************************************************************************/ -#include - -#include -#include -#include -#include "NBTrafficLightDefinition.h" -#include "NBNode.h" -#include "NBOwnTLDef.h" -#include "NBTrafficLightLogic.h" -#include -#include -#include -#include -#include - -#define HEIGH_WEIGHT 2 -#define LOW_WEIGHT .5; - -#define MIN_GREEN_TIME 5 - -//#define DEBUG_STREAM_ORDERING -//#define DEBUG_PHASES -//#define DEBUGCOND (getID() == "cluster_251050941_280598736_280598739_28902891_3142549227_3142550438") -//#define DEBUGEDGE(edge) (edge->getID() == "23209153#1" || edge->getID() == "319583927#0") -//#define DEBUGCOND (true) -//#define DEBUGEDGE(edge) (true) - -// =========================================================================== -// member method definitions -// =========================================================================== -NBOwnTLDef::NBOwnTLDef(const std::string& id, - const std::vector& junctions, SUMOTime offset, - TrafficLightType type) : - NBTrafficLightDefinition(id, junctions, DefaultProgramID, offset, type), - myHaveSinglePhase(false) { -} - - -NBOwnTLDef::NBOwnTLDef(const std::string& id, NBNode* junction, SUMOTime offset, - TrafficLightType type) : - NBTrafficLightDefinition(id, junction, DefaultProgramID, offset, type), - myHaveSinglePhase(false) { -} - - -NBOwnTLDef::NBOwnTLDef(const std::string& id, SUMOTime offset, - TrafficLightType type) : - NBTrafficLightDefinition(id, DefaultProgramID, offset, type), - myHaveSinglePhase(false) { -} - - -NBOwnTLDef::~NBOwnTLDef() {} - - -int -NBOwnTLDef::getToPrio(const NBEdge* const e) { - return e->getJunctionPriority(e->getToNode()); -} - - -double -NBOwnTLDef::getDirectionalWeight(LinkDirection dir) { - switch (dir) { - case LinkDirection::STRAIGHT: - case LinkDirection::PARTLEFT: - case LinkDirection::PARTRIGHT: - return HEIGH_WEIGHT; - case LinkDirection::LEFT: - case LinkDirection::RIGHT: - return LOW_WEIGHT; - default: - break; - } - return 0; -} - -double -NBOwnTLDef::computeUnblockedWeightedStreamNumber(const NBEdge* const e1, const NBEdge* const e2) { - double val = 0; - for (int e1l = 0; e1l < e1->getNumLanes(); e1l++) { - std::vector approached1 = e1->getConnectionsFromLane(e1l); - for (int e2l = 0; e2l < e2->getNumLanes(); e2l++) { - std::vector approached2 = e2->getConnectionsFromLane(e2l); - for (std::vector::iterator e1c = approached1.begin(); e1c != approached1.end(); ++e1c) { - if (e1->getTurnDestination() == (*e1c).toEdge) { - continue; - } - for (std::vector::iterator e2c = approached2.begin(); e2c != approached2.end(); ++e2c) { - if (e2->getTurnDestination() == (*e2c).toEdge) { - continue; - } - const double sign = (forbids(e1, (*e1c).toEdge, e2, (*e2c).toEdge, true) - || forbids(e2, (*e2c).toEdge, e1, (*e1c).toEdge, true)) ? -1 : 1; - double w1; - double w2; - if (e1->getJunctionPriority(e1->getToNode()) == e2->getJunctionPriority(e2->getToNode())) { - w1 = getDirectionalWeight(e1->getToNode()->getDirection(e1, (*e1c).toEdge)); - w2 = getDirectionalWeight(e2->getToNode()->getDirection(e2, (*e2c).toEdge)); - } else { - if (e1->getJunctionPriority(e1->getToNode()) > e2->getJunctionPriority(e2->getToNode())) { - w1 = HEIGH_WEIGHT; - w2 = LOW_WEIGHT; - } else { - w1 = LOW_WEIGHT; - w2 = HEIGH_WEIGHT; - } - if (sign == -1) { - // extra penalty if edges with different junction priority are in conflict - w1 *= 2; - w2 *= 2; - } - } - val += sign * w1; - val += sign * w2; -#ifdef DEBUG_STREAM_ORDERING - if (DEBUGCOND && DEBUGEDGE(e2) && DEBUGEDGE(e1)) { - std::cout << " sign=" << sign << " w1=" << w1 << " w2=" << w2 << " val=" << val - << " c1=" << (*e1c).getDescription(e1) - << " c2=" << (*e2c).getDescription(e2) - << "\n"; - } -#endif - } - } - } - } -#ifdef DEBUG_STREAM_ORDERING - if (DEBUGCOND && DEBUGEDGE(e2) && DEBUGEDGE(e1)) { - std::cout << " computeUnblockedWeightedStreamNumber e1=" << e1->getID() << " e2=" << e2->getID() << " val=" << val << "\n"; - } -#endif - return val; -} - - -std::pair -NBOwnTLDef::getBestCombination(const EdgeVector& edges) { - std::pair bestPair(static_cast(nullptr), static_cast(nullptr)); - double bestValue = -std::numeric_limits::max(); - for (EdgeVector::const_iterator i = edges.begin(); i != edges.end(); ++i) { - for (EdgeVector::const_iterator j = i + 1; j != edges.end(); ++j) { - const double value = computeUnblockedWeightedStreamNumber(*i, *j); - if (value > bestValue) { - bestValue = value; - bestPair = std::pair(*i, *j); - } else if (value == bestValue) { - const double ca = GeomHelper::getMinAngleDiff((*i)->getAngleAtNode((*i)->getToNode()), (*j)->getAngleAtNode((*j)->getToNode())); - const double oa = GeomHelper::getMinAngleDiff(bestPair.first->getAngleAtNode(bestPair.first->getToNode()), bestPair.second->getAngleAtNode(bestPair.second->getToNode())); - if (fabs(oa - ca) < NUMERICAL_EPS) { // break ties by id - if (bestPair.first->getID() < (*i)->getID()) { - bestPair = std::pair(*i, *j); - } - } else if (oa < ca) { - bestPair = std::pair(*i, *j); - } - } - } - } - if (bestValue <= 0) { - // do not group edges - bestPair.second = nullptr; - - } -#ifdef DEBUG_STREAM_ORDERING - if (DEBUGCOND) { - std::cout << " getBestCombination bestValue=" << bestValue << " best=" << Named::getIDSecure(bestPair.first) << ", " << Named::getIDSecure(bestPair.second) << "\n"; - } -#endif - return bestPair; -} - - -std::pair -NBOwnTLDef::getBestPair(EdgeVector& incoming) { - if (incoming.size() == 1) { - // only one there - return the one - std::pair ret(*incoming.begin(), static_cast(nullptr)); - incoming.clear(); - return ret; - } - // determine the best combination - // by priority, first - EdgeVector used; - std::sort(incoming.begin(), incoming.end(), edge_by_incoming_priority_sorter()); - used.push_back(*incoming.begin()); // the first will definitely be used - // get the ones with the same priority - int prio = getToPrio(*used.begin()); - for (EdgeVector::iterator i = incoming.begin() + 1; i != incoming.end() && prio == getToPrio(*i); ++i) { - used.push_back(*i); - } - // if there only lower priorised, use these, too - if (used.size() < 2) { - used = incoming; - } - std::pair ret = getBestCombination(used); -#ifdef DEBUG_STREAM_ORDERING - if (DEBUGCOND) { - std::cout << "getBestPair tls=" << getID() << " incoming=" << toString(incoming) << " prio=" << prio << " used=" << toString(used) << " best=" << Named::getIDSecure(ret.first) << ", " << Named::getIDSecure(ret.second) << "\n"; - } -#endif - - incoming.erase(find(incoming.begin(), incoming.end(), ret.first)); - if (ret.second != nullptr) { - incoming.erase(find(incoming.begin(), incoming.end(), ret.second)); - } - return ret; -} - -NBTrafficLightLogic* -NBOwnTLDef::myCompute(int brakingTimeSeconds) { - return computeLogicAndConts(brakingTimeSeconds); -} - -NBTrafficLightLogic* -NBOwnTLDef::computeLogicAndConts(int brakingTimeSeconds, bool onlyConts) { - myNeedsContRelation.clear(); - myRightOnRedConflicts.clear(); - const SUMOTime brakingTime = TIME2STEPS(brakingTimeSeconds); - const SUMOTime leftTurnTime = TIME2STEPS(OptionsCont::getOptions().getInt("tls.left-green.time")); - const SUMOTime minMinDur = myType == TrafficLightType::STATIC ? UNSPECIFIED_DURATION : TIME2STEPS(OptionsCont::getOptions().getInt("tls.min-dur")); - const SUMOTime maxDur = myType == TrafficLightType::STATIC ? UNSPECIFIED_DURATION : TIME2STEPS(OptionsCont::getOptions().getInt("tls.max-dur")); - - // build complete lists first - const EdgeVector& incoming = getIncomingEdges(); - EdgeVector fromEdges, toEdges; - std::vector isTurnaround; - std::vector hasTurnLane; - std::vector fromLanes; - std::vector toLanes; - int noLinksAll = 0; - for (NBEdge* const fromEdge : incoming) { - const int numLanes = fromEdge->getNumLanes(); - for (int i2 = 0; i2 < numLanes; i2++) { - bool hasLeft = false; - bool hasStraight = false; - bool hasRight = false; - bool hasTurnaround = false; - for (const NBEdge::Connection& approached : fromEdge->getConnectionsFromLane(i2)) { - if (!fromEdge->mayBeTLSControlled(i2, approached.toEdge, approached.toLane)) { - continue; - } - fromEdges.push_back(fromEdge); - fromLanes.push_back(i2); - toLanes.push_back(approached.toLane); - toEdges.push_back(approached.toEdge); - if (approached.toEdge != nullptr) { - isTurnaround.push_back(fromEdge->isTurningDirectionAt(approached.toEdge)); - } else { - isTurnaround.push_back(true); - } - LinkDirection dir = fromEdge->getToNode()->getDirection(fromEdge, approached.toEdge); - if (dir == LinkDirection::STRAIGHT) { - hasStraight = true; - } else if (dir == LinkDirection::RIGHT || dir == LinkDirection::PARTRIGHT) { - hasRight = true; - } else if (dir == LinkDirection::LEFT || dir == LinkDirection::PARTLEFT) { - hasLeft = true; - } else if (dir == LinkDirection::TURN) { - hasTurnaround = true; - } - noLinksAll++; - } - for (const NBEdge::Connection& approached : fromEdge->getConnectionsFromLane(i2)) { - if (!fromEdge->mayBeTLSControlled(i2, approached.toEdge, approached.toLane)) { - continue; - } - hasTurnLane.push_back( - (hasLeft && !hasStraight && !hasRight) - || (!hasLeft && !hasTurnaround && hasRight)); - } - //std::cout << " from=" << fromEdge->getID() << "_" << i2 << " hasTurnLane=" << hasTurnLane.back() << " s=" << hasStraight << " l=" << hasLeft << " r=" << hasRight << " t=" << hasTurnaround << "\n"; - } - } - // collect crossings - std::vector crossings; - for (NBNode* const node : myControlledNodes) { - const std::vector& c = node->getCrossings(); - if (!onlyConts) { - // set tl indices for crossings - node->setCrossingTLIndices(getID(), noLinksAll); - } - copy(c.begin(), c.end(), std::back_inserter(crossings)); - noLinksAll += (int)c.size(); - } - - NBTrafficLightLogic* logic = new NBTrafficLightLogic(getID(), getProgramID(), noLinksAll, myOffset, myType); - EdgeVector toProc = getConnectedOuterEdges(incoming); - const SUMOTime greenTime = TIME2STEPS(OptionsCont::getOptions().getInt("tls.green.time")); - const SUMOTime allRedTime = TIME2STEPS(OptionsCont::getOptions().getInt("tls.allred.time")); - const double minorLeftSpeedThreshold = OptionsCont::getOptions().getFloat("tls.minor-left.max-speed"); - // left-turn phases do not work well for joined tls, so we build incoming instead - const double groupOpposites = (OptionsCont::getOptions().getString("tls.layout") == "opposites" - && (myControlledNodes.size() <= 2 || corridorLike())); - - // build all phases - std::vector greenPhases; // indices of green phases - std::vector hadGreenMajor(noLinksAll, false); - while (toProc.size() > 0) { - bool groupTram = false; - bool groupOther = false; - std::pair chosen; - if (groupOpposites) { - if (incoming.size() == 2) { - // if there are only 2 incoming edges we need to decide whether they are a crossing or a "continuation" - // @node: this heuristic could be extended to also check the number of outgoing edges - double angle = fabs(NBHelpers::relAngle(incoming[0]->getAngleAtNode(incoming[0]->getToNode()), incoming[1]->getAngleAtNode(incoming[1]->getToNode()))); - // angle would be 180 for straight opposing incoming edges - if (angle < 135) { - chosen = std::pair(toProc[0], static_cast(nullptr)); - toProc.erase(toProc.begin()); - } else { - chosen = getBestPair(toProc); - } - } else { - chosen = getBestPair(toProc); - if (chosen.second == nullptr && chosen.first->getPermissions() == SVC_TRAM) { - groupTram = true; - for (auto it = toProc.begin(); it != toProc.end();) { - if ((*it)->getPermissions() == SVC_TRAM) { - it = toProc.erase(it); - } else { - it++; - } - } - } - } - } else { - NBEdge* chosenEdge = toProc[0]; - chosen = std::pair(chosenEdge, static_cast(nullptr)); - toProc.erase(toProc.begin()); - SVCPermissions perms = chosenEdge->getPermissions(); - if (perms == SVC_TRAM) { - groupTram = true; - } else if ((perms & ~(SVC_PEDESTRIAN | SVC_BICYCLE | SVC_DELIVERY)) == 0) { - groupOther = true; - } - // group all edges with the same permissions into a single phase (later) - if (groupTram || groupOther) { - for (auto it = toProc.begin(); it != toProc.end();) { - if ((*it)->getPermissions() == perms) { - it = toProc.erase(it); - } else { - it++; - } - } - } - } - int pos = 0; - std::string state((int) noLinksAll, 'r'); -#ifdef DEBUG_PHASES - if (DEBUGCOND) { - std::cout << " computing " << getID() << " prog=" << getProgramID() << " cho1=" << Named::getIDSecure(chosen.first) << " cho2=" << Named::getIDSecure(chosen.second) << " toProc=" << toString(toProc) << " bentPrio=" << chosen.first->getToNode()->isBentPriority() << "\n"; - } -#endif - // plain straight movers - double maxSpeed = 0; - bool haveGreen = false; - for (const NBEdge* const fromEdge : incoming) { - const bool inChosen = fromEdge == chosen.first || fromEdge == chosen.second; //chosen.find(fromEdge)!=chosen.end(); - const int numLanes = fromEdge->getNumLanes(); - for (int i2 = 0; i2 < numLanes; i2++) { - for (const NBEdge::Connection& approached : fromEdge->getConnectionsFromLane(i2)) { - if (!fromEdge->mayBeTLSControlled(i2, approached.toEdge, approached.toLane)) { - continue; - } - if (inChosen) { - state[pos] = 'G'; - haveGreen = true; - maxSpeed = MAX2(maxSpeed, fromEdge->getSpeed()); - } else { - state[pos] = 'r'; - } - ++pos; - } - } - } - if (!haveGreen) { - continue; - } - -#ifdef DEBUG_PHASES - if (DEBUGCOND) { - std::cout << " state after plain straight movers " << state << "\n"; - } -#endif - // correct behaviour for those that are not in chosen, but may drive, though - state = allowCompatible(state, fromEdges, toEdges, fromLanes, toLanes); - if (groupTram) { - state = allowByVClass(state, fromEdges, toEdges, SVC_TRAM); - } else if (groupOther) { - state = allowByVClass(state, fromEdges, toEdges, SVC_PEDESTRIAN | SVC_BICYCLE | SVC_DELIVERY); - } -#ifdef DEBUG_PHASES - if (DEBUGCOND) { - std::cout << " state after grouping by vClass " << state << "\n"; - } -#endif - if (groupOpposites || chosen.first->getToNode()->getType() == SumoXMLNodeType::TRAFFIC_LIGHT_RIGHT_ON_RED) { - state = allowUnrelated(state, fromEdges, toEdges, isTurnaround, crossings); - } -#ifdef DEBUG_PHASES - if (DEBUGCOND) { - std::cout << " state after finding allowUnrelated " << state << "\n"; - } -#endif - // correct behaviour for those that have to wait (mainly left-mover) - bool haveForbiddenLeftMover = false; - std::vector rightTurnConflicts(pos, false); - state = correctConflicting(state, fromEdges, toEdges, isTurnaround, fromLanes, hadGreenMajor, haveForbiddenLeftMover, rightTurnConflicts); - for (int i1 = 0; i1 < pos; ++i1) { - if (state[i1] == 'G') { - hadGreenMajor[i1] = true; - } - } -#ifdef DEBUG_PHASES - if (DEBUGCOND) { - std::cout << " state after correcting left movers=" << state << "\n"; - } -#endif - - std::vector leftGreen(pos, false); - // check whether at least one left-turn lane exist - bool foundLeftTurnLane = false; - for (int i1 = 0; i1 < pos; ++i1) { - if (state[i1] == 'g' && !rightTurnConflicts[i1] && hasTurnLane[i1]) { - foundLeftTurnLane = true; - } - } - const bool buildLeftGreenPhase = (haveForbiddenLeftMover && !myHaveSinglePhase && leftTurnTime > 0 && foundLeftTurnLane - && groupOpposites && !groupTram && !groupOther); - - // find indices for exclusive left green phase and apply option minor-left.max-speed - for (int i1 = 0; i1 < pos; ++i1) { - if (state[i1] == 'g' && !rightTurnConflicts[i1] - // only activate turn-around together with a real left-turn - && (!isTurnaround[i1] || (i1 > 0 && leftGreen[i1 - 1]))) { - leftGreen[i1] = true; - if (fromEdges[i1]->getSpeed() > minorLeftSpeedThreshold) { - if (buildLeftGreenPhase) { - state[i1] = 'r'; - //std::cout << " disabling minorLeft " << i1 << " (speed=" << fromEdges[i1]->getSpeed() << " thresh=" << minorLeftSpeedThreshold << ")\n"; - } else if (!isTurnaround[i1]) { - WRITE_WARNINGF("Minor green from edge '%' to edge '%' exceeds %m/s. Maybe a left-turn lane is missing.", - fromEdges[i1]->getID(), toEdges[i1]->getID(), minorLeftSpeedThreshold); - } - } - } - } - -#ifdef DEBUG_PHASES - if (DEBUGCOND) { - std::cout << getID() << " state=" << state << " buildLeft=" << buildLeftGreenPhase << " hFLM=" << haveForbiddenLeftMover << " turnLane=" << foundLeftTurnLane - << " \nrtC=" << toString(rightTurnConflicts) - << " \nhTL=" << toString(hasTurnLane) - << " \nlGr=" << toString(leftGreen) - << "\n"; - } -#endif - - const std::string vehicleState = state; // backup state before pedestrian modifications - greenPhases.push_back((int)logic->getPhases().size()); - - // 5s at 50km/h, 10s at 80km/h, rounded to full seconds - const double minDurBySpeed = maxSpeed * 3.6 / 6 - 3.3; - SUMOTime minDur = MAX2(minMinDur, TIME2STEPS(floor(minDurBySpeed + 0.5))); - if (chosen.first->getPermissions() == SVC_TRAM && (chosen.second == nullptr || chosen.second->getPermissions() == SVC_TRAM)) { - // shorter minDuration for tram phase (only if the phase is - // exclusively for tram) - bool tramExclusive = true; - for (int i1 = 0; i1 < (int)fromEdges.size(); ++i1) { - if (state[i1] == 'G') { - SVCPermissions linkPerm = (fromEdges[i1]->getPermissions() & toEdges[i1]->getPermissions()); - if (linkPerm != SVC_TRAM) { - tramExclusive = false; - break; - } - } - } - if (tramExclusive) { - // one tram per actuated phase - minDur = TIME2STEPS(1); - } - } - - state = addPedestrianPhases(logic, greenTime, minDur, maxDur, state, crossings, fromEdges, toEdges); - // pedestrians have 'r' from here on - for (int i1 = pos; i1 < pos + (int)crossings.size(); ++i1) { - state[i1] = 'r'; - } - if (brakingTime > 0) { - // build yellow (straight) - for (int i1 = 0; i1 < pos; ++i1) { - if (state[i1] != 'G' && state[i1] != 'g') { - continue; - } - if ((vehicleState[i1] >= 'a' && vehicleState[i1] <= 'z') - && buildLeftGreenPhase - && !rightTurnConflicts[i1] - && leftGreen[i1]) { - continue; - } - state[i1] = 'y'; - } - // add step - logic->addStep(brakingTime, state); - // add optional all-red state - buildAllRedState(allRedTime, logic, state); - } - - - if (buildLeftGreenPhase) { - // build left green - for (int i1 = 0; i1 < pos; ++i1) { - if (state[i1] == 'Y' || state[i1] == 'y') { - state[i1] = 'r'; - continue; - } - if (leftGreen[i1]) { - state[i1] = 'G'; - } - } - state = allowCompatible(state, fromEdges, toEdges, fromLanes, toLanes); - state = correctConflicting(state, fromEdges, toEdges, isTurnaround, fromLanes, hadGreenMajor, haveForbiddenLeftMover, rightTurnConflicts); - - // add step - logic->addStep(leftTurnTime, state, minDur, maxDur); - - // build left yellow - if (brakingTime > 0) { - for (int i1 = 0; i1 < pos; ++i1) { - if (state[i1] != 'G' && state[i1] != 'g') { - continue; - } - state[i1] = 'y'; - } - // add step - logic->addStep(brakingTime, state); - // add optional all-red state - buildAllRedState(allRedTime, logic, state); - } - } - } - // fix pedestrian crossings that did not get the green light yet - if (crossings.size() > 0) { - addPedestrianScramble(logic, noLinksAll, TIME2STEPS(10), brakingTime, crossings, fromEdges, toEdges); - } - // add optional red phase if there where no foes - if (logic->getPhases().size() == 2 && brakingTime > 0 - && OptionsCont::getOptions().getInt("tls.red.time") > 0) { - const SUMOTime redTime = TIME2STEPS(OptionsCont::getOptions().getInt("tls.red.time")); - logic->addStep(redTime, std::string(noLinksAll, 'r')); - } - // fix states to account for custom crossing link indices - if (crossings.size() > 0 && !onlyConts) { - checkCustomCrossingIndices(logic); - } - - SUMOTime totalDuration = logic->getDuration(); - if (OptionsCont::getOptions().isDefault("tls.green.time") || !OptionsCont::getOptions().isDefault("tls.cycle.time")) { - const SUMOTime cycleTime = TIME2STEPS(OptionsCont::getOptions().getInt("tls.cycle.time")); - // adapt to cycle time by changing the duration of the green phases - SUMOTime greenPhaseTime = 0; - SUMOTime minGreenDuration = SUMOTime_MAX; - for (std::vector::const_iterator it = greenPhases.begin(); it != greenPhases.end(); ++it) { - const SUMOTime dur = logic->getPhases()[*it].duration; - greenPhaseTime += dur; - minGreenDuration = MIN2(minGreenDuration, dur); - } - const int patchSeconds = (int)(STEPS2TIME(cycleTime - totalDuration) / greenPhases.size()); - const int patchSecondsRest = (int)(STEPS2TIME(cycleTime - totalDuration)) - patchSeconds * (int)greenPhases.size(); - //std::cout << "cT=" << cycleTime << " td=" << totalDuration << " pS=" << patchSeconds << " pSR=" << patchSecondsRest << "\n"; - if (STEPS2TIME(minGreenDuration) + patchSeconds < MIN_GREEN_TIME - || STEPS2TIME(minGreenDuration) + patchSeconds + patchSecondsRest < MIN_GREEN_TIME - || greenPhases.size() == 0) { - if (getID() != DummyID) { - WRITE_WARNINGF("The traffic light '%' cannot be adapted to a cycle time of %.", getID(), time2string(cycleTime)); - } - // @todo use a multiple of cycleTime ? - } else { - for (std::vector::const_iterator it = greenPhases.begin(); it != greenPhases.end(); ++it) { - logic->setPhaseDuration(*it, logic->getPhases()[*it].duration + TIME2STEPS(patchSeconds)); - } - if (greenPhases.size() > 0) { - logic->setPhaseDuration(greenPhases.front(), logic->getPhases()[greenPhases.front()].duration + TIME2STEPS(patchSecondsRest)); - } - totalDuration = logic->getDuration(); - } - } - - myRightOnRedConflictsReady = true; - // this computation only makes sense for single nodes - myNeedsContRelationReady = (myControlledNodes.size() == 1); - if (totalDuration > 0) { - if (totalDuration > 3 * (greenTime + 2 * brakingTime + leftTurnTime)) { - WRITE_WARNINGF("The traffic light '%' has a high cycle time of %.", getID(), time2string(totalDuration)); - } - logic->closeBuilding(); - return logic; - } else { - delete logic; - return nullptr; - } -} - - -bool -NBOwnTLDef::hasCrossing(const NBEdge* from, const NBEdge* to, const std::vector& crossings) { - assert(to != 0); - for (auto c : crossings) { - const NBNode::Crossing& cross = *c; - // only check connections at this crossings node - if (to->getFromNode() == cross.node) { - for (EdgeVector::const_iterator it_e = cross.edges.begin(); it_e != cross.edges.end(); ++it_e) { - const NBEdge* edge = *it_e; - if (edge == from || edge == to) { - return true; - } - } - } - } - return false; -} - - -std::string -NBOwnTLDef::addPedestrianPhases(NBTrafficLightLogic* logic, SUMOTime greenTime, - SUMOTime minDur, SUMOTime maxDur, - std::string state, const std::vector& crossings, const EdgeVector& fromEdges, const EdgeVector& toEdges) { - // compute based on length of the crossing if not set by the user - const SUMOTime pedClearingTime = TIME2STEPS(OptionsCont::getOptions().getInt("tls.crossing-clearance.time")); - // compute if not set by user: must be able to reach the middle of the second "Richtungsfahrbahn" - const SUMOTime minPedTime = TIME2STEPS(OptionsCont::getOptions().getInt("tls.crossing-min.time")); - const std::string orig = state; - state = patchStateForCrossings(state, crossings, fromEdges, toEdges); - if (orig == state) { - // add step - logic->addStep(greenTime, state, minDur, maxDur); - } else { - const SUMOTime pedTime = greenTime - pedClearingTime; - if (pedTime >= minPedTime) { - // ensure clearing time for pedestrians - const int pedStates = (int)crossings.size(); - logic->addStep(pedTime, state, minDur, maxDur); - state = state.substr(0, state.size() - pedStates) + std::string(pedStates, 'r'); - logic->addStep(pedClearingTime, state); - } else { - state = orig; - // not safe for pedestrians. - logic->addStep(greenTime, state, minDur, maxDur); - } - } - return state; -} - - -std::string -NBOwnTLDef::patchStateForCrossings(const std::string& state, const std::vector& crossings, const EdgeVector& fromEdges, const EdgeVector& toEdges) { - std::string result = state; - const int pos = (int)(state.size() - crossings.size()); // number of controlled vehicle links - for (int ic = 0; ic < (int)crossings.size(); ++ic) { - const int i1 = pos + ic; - const NBNode::Crossing& cross = *crossings[ic]; - bool isForbidden = false; - for (int i2 = 0; i2 < pos && !isForbidden; ++i2) { - // only check connections at this crossings node - if (fromEdges[i2] != 0 && toEdges[i2] != 0 && fromEdges[i2]->getToNode() == cross.node) { - for (EdgeVector::const_iterator it = cross.edges.begin(); it != cross.edges.end(); ++it) { - const NBEdge* edge = *it; - const LinkDirection i2dir = cross.node->getDirection(fromEdges[i2], toEdges[i2]); - if (state[i2] != 'r' && state[i2] != 's' && (edge == fromEdges[i2] || - (edge == toEdges[i2] && (i2dir == LinkDirection::STRAIGHT || i2dir == LinkDirection::PARTLEFT || i2dir == LinkDirection::PARTRIGHT)))) { - isForbidden = true; - break; - } - } - } - } - if (!isForbidden) { - result[i1] = 'G'; - } else { - result[i1] = 'r'; - } - } - - // correct behaviour for roads that are in conflict with a pedestrian crossing - for (int i1 = 0; i1 < pos; ++i1) { - if (result[i1] == 'G') { - for (int ic = 0; ic < (int)crossings.size(); ++ic) { - const NBNode::Crossing& crossing = *crossings[ic]; - if (fromEdges[i1] != 0 && toEdges[i1] != 0 && fromEdges[i1]->getToNode() == crossing.node) { - const int i2 = pos + ic; - if (result[i2] == 'G' && crossing.node->mustBrakeForCrossing(fromEdges[i1], toEdges[i1], crossing)) { - result[i1] = 'g'; - break; - } - } - } - } - } - return result; -} - - -void -NBOwnTLDef::collectLinks() { - myControlledLinks.clear(); - collectAllLinks(myControlledLinks); -} - - -void -NBOwnTLDef::setTLControllingInformation() const { - // set the information about the link's positions within the tl into the - // edges the links are starting at, respectively - for (NBConnectionVector::const_iterator j = myControlledLinks.begin(); j != myControlledLinks.end(); ++j) { - const NBConnection& conn = *j; - NBEdge* edge = conn.getFrom(); - edge->setControllingTLInformation(conn, getID()); - } -} - - -void -NBOwnTLDef::remapRemoved(NBEdge* /*removed*/, const EdgeVector& /*incoming*/, - const EdgeVector& /*outgoing*/) {} - - -void -NBOwnTLDef::replaceRemoved(NBEdge* /*removed*/, int /*removedLane*/, - NBEdge* /*by*/, int /*byLane*/, bool /*incoming*/) {} - - -void -NBOwnTLDef::initNeedsContRelation() const { - if (!myNeedsContRelationReady) { - if (myControlledNodes.size() > 0) { - // we use a dummy node just to maintain const-correctness - myNeedsContRelation.clear(); - NBOwnTLDef dummy(DummyID, myControlledNodes, 0, TrafficLightType::STATIC); - dummy.setParticipantsInformation(); - NBTrafficLightLogic* tllDummy = dummy.computeLogicAndConts(0, true); - delete tllDummy; - myNeedsContRelation = dummy.myNeedsContRelation; - for (std::vector::const_iterator i = myControlledNodes.begin(); i != myControlledNodes.end(); i++) { - (*i)->removeTrafficLight(&dummy); - } - } - myNeedsContRelationReady = true; - } -} - - -EdgeVector -NBOwnTLDef::getConnectedOuterEdges(const EdgeVector& incoming) { - EdgeVector result = incoming; - for (EdgeVector::iterator it = result.begin(); it != result.end();) { - if ((*it)->getConnections().size() == 0 || (*it)->isInsideTLS()) { - it = result.erase(it); - } else { - ++it; - } - } - return result; -} - - -std::string -NBOwnTLDef::allowCompatible(std::string state, const EdgeVector& fromEdges, const EdgeVector& toEdges, - const std::vector& fromLanes, const std::vector& toLanes) { - state = allowSingleEdge(state, fromEdges); - state = allowFollowers(state, fromEdges, toEdges); - state = allowPredecessors(state, fromEdges, toEdges, fromLanes, toLanes); - return state; -} - - -std::string -NBOwnTLDef::allowSingleEdge(std::string state, const EdgeVector& fromEdges) { - // if only one edge has green, ensure sure that all connections from that edge are green - const int size = (int)fromEdges.size(); - NBEdge* greenEdge = nullptr; - for (int i1 = 0; i1 < size; ++i1) { - if (state[i1] == 'G') { - if (greenEdge == nullptr) { - greenEdge = fromEdges[i1]; - } else if (greenEdge != fromEdges[i1]) { - return state; - } - } - } - if (greenEdge != nullptr) { - for (int i1 = 0; i1 < size; ++i1) { - if (fromEdges[i1] == greenEdge) { - state[i1] = 'G'; - } - } - } - return state; -} - - -std::string -NBOwnTLDef::allowFollowers(std::string state, const EdgeVector& fromEdges, const EdgeVector& toEdges) { - // check continuation within joined traffic lights - bool check = true; - while (check) { - check = false; - for (int i1 = 0; i1 < (int)fromEdges.size(); ++i1) { - if (state[i1] == 'G') { - continue; - } - //if (forbidden(state, i1, fromEdges, toEdges)) { - // continue; - //} - bool followsChosen = false; - for (int i2 = 0; i2 < (int)fromEdges.size(); ++i2) { - if (state[i2] == 'G' && fromEdges[i1] == toEdges[i2]) { - followsChosen = true; - break; - } - } - if (followsChosen) { - state[i1] = 'G'; - check = true; - } - } - } - return state; -} - - -std::string -NBOwnTLDef::allowPredecessors(std::string state, const EdgeVector& fromEdges, const EdgeVector& toEdges, - const std::vector& fromLanes, const std::vector& toLanes) { - // also allow predecessors of chosen edges if the lanes match and there is no conflict - // (must be done after the followers are done because followers are less specific) - bool check = true; - while (check) { - check = false; - for (int i1 = 0; i1 < (int)fromEdges.size(); ++i1) { - if (state[i1] == 'G') { - continue; - } - if (forbidden(state, i1, fromEdges, toEdges)) { - continue; - } - bool preceedsChosen = false; - for (int i2 = 0; i2 < (int)fromEdges.size(); ++i2) { - if (state[i2] == 'G' && fromEdges[i2] == toEdges[i1] - && fromLanes[i2] == toLanes[i1]) { - preceedsChosen = true; - break; - } - } - if (preceedsChosen) { - state[i1] = 'G'; - check = true; - } - } - } - return state; -} - - -std::string -NBOwnTLDef::allowUnrelated(std::string state, const EdgeVector& fromEdges, const EdgeVector& toEdges, - const std::vector& isTurnaround, - const std::vector& crossings) { - for (int i1 = 0; i1 < (int)fromEdges.size(); ++i1) { - if (state[i1] == 'G') { - continue; - } - bool isForbidden = false; - for (int i2 = 0; i2 < (int)fromEdges.size(); ++i2) { - if (state[i2] == 'G' && !isTurnaround[i2] && - (forbids(fromEdges[i2], toEdges[i2], fromEdges[i1], toEdges[i1], true) || forbids(fromEdges[i1], toEdges[i1], fromEdges[i2], toEdges[i2], true))) { - isForbidden = true; - break; - } - } - if (!isForbidden && !hasCrossing(fromEdges[i1], toEdges[i1], crossings)) { - state[i1] = 'G'; - } - } - return state; -} - - -std::string -NBOwnTLDef::allowByVClass(std::string state, const EdgeVector& fromEdges, const EdgeVector& toEdges, SVCPermissions perm) { - for (int i1 = 0; i1 < (int)fromEdges.size(); ++i1) { - SVCPermissions linkPerm = (fromEdges[i1]->getPermissions() & toEdges[i1]->getPermissions()); - if ((linkPerm & ~perm) == 0) { - state[i1] = 'G'; - } - } - return state; -} - - -bool -NBOwnTLDef::forbidden(const std::string& state, int index, const EdgeVector& fromEdges, const EdgeVector& toEdges) { - for (int i2 = 0; i2 < (int)fromEdges.size(); ++i2) { - if (state[i2] == 'G' && foes(fromEdges[i2], toEdges[i2], fromEdges[index], toEdges[index])) { - return true; - } - } - return false; -} - - -std::string -NBOwnTLDef::correctConflicting(std::string state, const EdgeVector& fromEdges, const EdgeVector& toEdges, - const std::vector& isTurnaround, - const std::vector& fromLanes, - const std::vector& hadGreenMajor, - bool& haveForbiddenLeftMover, - std::vector& rightTurnConflicts) { - const bool controlledWithin = !OptionsCont::getOptions().getBool("tls.uncontrolled-within"); - for (int i1 = 0; i1 < (int)fromEdges.size(); ++i1) { - if (state[i1] == 'G') { - for (int i2 = 0; i2 < (int)fromEdges.size(); ++i2) { - if ((state[i2] == 'G' || state[i2] == 'g')) { - if (NBNode::rightTurnConflict( - fromEdges[i1], toEdges[i1], fromLanes[i1], fromEdges[i2], toEdges[i2], fromLanes[i2])) { - rightTurnConflicts[i1] = true; - } - if (forbids(fromEdges[i2], toEdges[i2], fromEdges[i1], toEdges[i1], true, controlledWithin) || rightTurnConflicts[i1]) { - state[i1] = 'g'; - myNeedsContRelation.insert(StreamPair(fromEdges[i1], toEdges[i1], fromEdges[i2], toEdges[i2])); - if (!isTurnaround[i1] && !hadGreenMajor[i1] && !rightTurnConflicts[i1]) { - haveForbiddenLeftMover = true; - } - } - } - } - } - if (state[i1] == 'r') { - if (fromEdges[i1]->getToNode()->getType() == SumoXMLNodeType::TRAFFIC_LIGHT_RIGHT_ON_RED && - fromEdges[i1]->getToNode()->getDirection(fromEdges[i1], toEdges[i1]) == LinkDirection::RIGHT) { - state[i1] = 's'; - // do not allow right-on-red when in conflict with exclusive left-turn phase - for (int i2 = 0; i2 < (int)fromEdges.size(); ++i2) { - if (state[i2] == 'G' && !isTurnaround[i2] && - (forbids(fromEdges[i2], toEdges[i2], fromEdges[i1], toEdges[i1], true) || - forbids(fromEdges[i1], toEdges[i1], fromEdges[i2], toEdges[i2], true))) { - const LinkDirection foeDir = fromEdges[i2]->getToNode()->getDirection(fromEdges[i2], toEdges[i2]); - if (foeDir == LinkDirection::LEFT || foeDir == LinkDirection::PARTLEFT) { - state[i1] = 'r'; - break; - } - } - } - if (state[i1] == 's') { - // handle right-on-red conflicts - for (int i2 = 0; i2 < (int)fromEdges.size(); ++i2) { - if (state[i2] == 'G' && !isTurnaround[i2] && - (forbids(fromEdges[i2], toEdges[i2], fromEdges[i1], toEdges[i1], true) || - forbids(fromEdges[i1], toEdges[i1], fromEdges[i2], toEdges[i2], true))) { - myRightOnRedConflicts.insert(std::make_pair(i1, i2)); - } - } - } - } - } - } - return state; -} - - -void -NBOwnTLDef::addPedestrianScramble(NBTrafficLightLogic* logic, int noLinksAll, SUMOTime /* greenTime */, SUMOTime brakingTime, - const std::vector& crossings, const EdgeVector& fromEdges, const EdgeVector& toEdges) { - const int vehLinks = noLinksAll - (int)crossings.size(); - std::vector foundGreen(crossings.size(), false); - const std::vector& phases = logic->getPhases(); - for (int i = 0; i < (int)phases.size(); ++i) { - const std::string state = phases[i].state; - for (int j = 0; j < (int)crossings.size(); ++j) { - LinkState ls = (LinkState)state[vehLinks + j]; - if (ls == LINKSTATE_TL_GREEN_MAJOR || ls == LINKSTATE_TL_GREEN_MINOR) { - foundGreen[j] = true; - } - } - } - for (int j = 0; j < (int)foundGreen.size(); ++j) { - if (!foundGreen[j]) { - - // add a phase where all pedestrians may walk, (preceded by a yellow phase and followed by a clearing phase) - if (phases.size() > 0) { - bool needYellowPhase = false; - std::string state = phases.back().state; - for (int i1 = 0; i1 < vehLinks; ++i1) { - if (state[i1] == 'G' || state[i1] == 'g') { - state[i1] = 'y'; - needYellowPhase = true; - } - } - // add yellow step - if (needYellowPhase && brakingTime > 0) { - logic->addStep(brakingTime, state); - } - } - const SUMOTime pedClearingTime = TIME2STEPS(OptionsCont::getOptions().getInt("tls.crossing-clearance.time")); - const SUMOTime scrambleTime = TIME2STEPS(OptionsCont::getOptions().getInt("tls.scramble.time")); - addPedestrianPhases(logic, scrambleTime + pedClearingTime, UNSPECIFIED_DURATION, UNSPECIFIED_DURATION, std::string(noLinksAll, 'r'), crossings, fromEdges, toEdges); - break; - } - } -} - - -void -NBOwnTLDef::buildAllRedState(SUMOTime allRedTime, NBTrafficLightLogic* logic, const std::string& state) { - if (allRedTime > 0) { - // build all-red phase - std::string allRedState = state; - for (int i1 = 0; i1 < (int)state.size(); ++i1) { - if (allRedState[i1] == 'Y' || allRedState[i1] == 'y') { - allRedState[i1] = 'r'; - } - } - logic->addStep(allRedTime, allRedState); - } -} - -void -NBOwnTLDef::checkCustomCrossingIndices(NBTrafficLightLogic* logic) const { - int minCustomIndex = -1; - int maxCustomIndex = -1; - // collect crossings - for (std::vector::const_iterator i = myControlledNodes.begin(); i != myControlledNodes.end(); i++) { - const std::vector& c = (*i)->getCrossings(); - for (auto crossing : c) { - minCustomIndex = MIN2(minCustomIndex, crossing->customTLIndex); - minCustomIndex = MIN2(minCustomIndex, crossing->customTLIndex2); - maxCustomIndex = MAX2(maxCustomIndex, crossing->customTLIndex); - maxCustomIndex = MAX2(maxCustomIndex, crossing->customTLIndex2); - } - } - // custom crossing linkIndex could lead to longer states. ensure that every index has a state - if (maxCustomIndex >= logic->getNumLinks()) { - logic->setStateLength(maxCustomIndex + 1); - } - // XXX shorter state vectors are possible as well - // XXX if the indices are shuffled the guessed crossing states should be shuffled correspondingly - // XXX initialize the backward index to the same state as the forward index -} - - -int -NBOwnTLDef::getMaxIndex() { - setParticipantsInformation(); - NBTrafficLightLogic* logic = compute(OptionsCont::getOptions()); - if (logic != nullptr) { - return logic->getNumLinks() - 1; - } else { - return -1; - } -} - - -bool -NBOwnTLDef::corridorLike() const { - if (getID() == DummyID) { - // avoid infinite recursion - return true; - } - assert(myControlledNodes.size() >= 2); - NBOwnTLDef dummy(DummyID, myControlledNodes, 0, TrafficLightType::STATIC); - dummy.setParticipantsInformation(); - NBTrafficLightLogic* tllDummy = dummy.computeLogicAndConts(0, true); - int greenPhases = 0; - for (const auto& phase : tllDummy->getPhases()) { - if (phase.state.find_first_of("gG") != std::string::npos) { - greenPhases++; - } - } - delete tllDummy; - for (std::vector::const_iterator i = myControlledNodes.begin(); i != myControlledNodes.end(); i++) { - (*i)->removeTrafficLight(&dummy); - } - return greenPhases <= 2; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netbuild/NBOwnTLDef.h b/Util/OSM2ODR/src/netbuild/NBOwnTLDef.h deleted file mode 100644 index 7a748c80f..000000000 --- a/Util/OSM2ODR/src/netbuild/NBOwnTLDef.h +++ /dev/null @@ -1,281 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NBOwnTLDef.h -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Sascha Krieg -/// @date Tue, 29.05.2005 -/// -// A traffic light logics which must be computed (only nodes/edges are given) -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include -#include "NBTrafficLightDefinition.h" -#include "NBNode.h" - - -// =========================================================================== -// class declarations -// =========================================================================== - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NBOwnTLDef - * @brief A traffic light logics which must be computed (only nodes/edges are given) - */ -class NBOwnTLDef : public NBTrafficLightDefinition { -public: - /** @brief Constructor - * @param[in] id The id of the tls - * @param[in] junctions Junctions controlled by this tls - * @param[in] offset The offset of the plan - * @param[in] type The algorithm type for the computed traffic light - */ - NBOwnTLDef(const std::string& id, - const std::vector& junctions, - SUMOTime offset, - TrafficLightType type); - - - /** @brief Constructor - * @param[in] id The id of the tls - * @param[in] junction The junction controlled by this tls - * @param[in] offset The offset of the plan - * @param[in] type The algorithm type for the computed traffic light - */ - NBOwnTLDef(const std::string& id, NBNode* junction, SUMOTime offset, - TrafficLightType type); - - - /** @brief Constructor - * @param[in] id The id of the tls - * @param[in] offset The offset of the plan - * @param[in] type The algorithm type for the computed traffic light - */ - NBOwnTLDef(const std::string& id, SUMOTime offset, TrafficLightType type); - - - /// @brief Destructor - ~NBOwnTLDef(); - - - /// @name Public methods from NBTrafficLightDefinition-interface - /// @{ - - /** @brief Replaces occurences of the removed edge in incoming/outgoing edges of all definitions - * @param[in] removed The removed edge - * @param[in] incoming The edges to use instead if an incoming edge was removed - * @param[in] outgoing The edges to use instead if an outgoing edge was removed - * @see NBTrafficLightDefinition::remapRemoved - */ - void remapRemoved(NBEdge* removed, - const EdgeVector& incoming, const EdgeVector& outgoing); - - - /** @brief Informs edges about being controlled by a tls - * @see NBTrafficLightDefinition::setTLControllingInformation - */ - void setTLControllingInformation() const; - /// @} - - - /** @brief Forces the definition not to compute an additional phase for left-movers - */ - void setSinglePhase() { - myHaveSinglePhase = true; - } - - /// @brief add an additional pedestrian phase if there are crossings that did not get green yet - static void addPedestrianScramble(NBTrafficLightLogic* logic, int noLinksAll, - SUMOTime greenTime, SUMOTime yellowTime, - const std::vector& crossings, const EdgeVector& fromEdges, const EdgeVector& toEdges); - - /// @brief add 1 or 2 phases depending on the presence of pedestrian crossings - static std::string addPedestrianPhases(NBTrafficLightLogic* logic, SUMOTime greenTime, - SUMOTime minDur, SUMOTime maxDur, - std::string state, const std::vector& crossings, const EdgeVector& fromEdges, const EdgeVector& toEdges); - - /// @brief compute phase state in regard to pedestrian crossings - static std::string patchStateForCrossings(const std::string& state, - const std::vector& crossings, const EdgeVector& fromEdges, const EdgeVector& toEdges); - - /** @brief helper function for myCompute - * @param[in] brakingTime Duration a vehicle needs for braking in front of the tls - * @param[in] onlyConts whether the method is only called to compute myNeedsContRelation - * @return The computed logic - */ - NBTrafficLightLogic* computeLogicAndConts(int brakingTimeSeconds, bool onlyConts = false); - - /* initialize myNeedsContRelation and set myNeedsContRelationReady to true */ - void initNeedsContRelation() const; - - /* build optional all-red phase */ - void buildAllRedState(SUMOTime allRedTime, NBTrafficLightLogic* logic, const std::string& state); - - ///@brief Returns the maximum index controlled by this traffic light - int getMaxIndex(); - -protected: - /// @name Protected methods from NBTrafficLightDefinition-interface - /// @{ - - /** @brief Computes the traffic light logic finally in dependence to the type - * @param[in] brakingTime Duration a vehicle needs for braking in front of the tls - * @return The computed logic - * @see NBTrafficLightDefinition::myCompute - */ - NBTrafficLightLogic* myCompute(int brakingTimeSeconds); - - - /** @brief Collects the links participating in this traffic light - * @exception ProcessError If a link could not be found - * @see NBTrafficLightDefinition::collectLinks - */ - void collectLinks(); - - - /** @brief Replaces a removed edge/lane - * @param[in] removed The edge to replace - * @param[in] removedLane The lane of this edge to replace - * @param[in] by The edge to insert instead - * @param[in] byLane This edge's lane to insert instead - * @see NBTrafficLightDefinition::replaceRemoved - */ - void replaceRemoved(NBEdge* removed, int removedLane, - NBEdge* by, int byLane, bool incoming); - /// @} - - -protected: - - /// @brief test whether a joined tls with layout 'opposites' would be built without dedicated left-turn phase - bool corridorLike() const; - - /** @brief Returns the weight of a stream given its direction - * @param[in] dir The direction of the stream - * @return This stream's weight - * @todo There are several magic numbers; describe - */ - double getDirectionalWeight(LinkDirection dir); - - - /** @brief Returns this edge's priority at the node it ends at - * @param[in] e The edge to ask for his priority - * @return The edge's priority at his destination node - */ - int getToPrio(const NBEdge* const e); - - - /** @brief Returns how many streams outgoing from the edges can pass the junction without being blocked - * @param[in] e1 The first edge - * @param[in] e2 The second edge - * @todo There are several magic numbers; describe - */ - double computeUnblockedWeightedStreamNumber(const NBEdge* const e1, const NBEdge* const e2); - - - /** @brief Returns the combination of two edges from the given which has most unblocked streams - * @param[in] edges The list of edges to include in the computation - * @return The two edges for which the weighted number of unblocked streams is the highest - */ - std::pair getBestCombination(const EdgeVector& edges); - - - /** @brief Returns the combination of two edges from the given which has most unblocked streams - * - * The chosen edges are removed from the given vector - * - * @param[in, changed] incoming The list of edges which are participating in the logic - * @return The two edges for which the weighted number of unblocked streams is the highest - */ - std::pair getBestPair(EdgeVector& incoming); - - - /// @brief compute whether the given connection is crossed by pedestrians - static bool hasCrossing(const NBEdge* from, const NBEdge* to, const std::vector& crossings); - - /// @brief get edges that have connections - static EdgeVector getConnectedOuterEdges(const EdgeVector& incoming); - - - /// @brief allow connections that are compatible with the chosen edges - std::string allowCompatible(std::string state, const EdgeVector& fromEdges, const EdgeVector& toEdges, - const std::vector& fromLanes, const std::vector& toLanes); - - std::string allowSingleEdge(std::string state, const EdgeVector& fromEdges); - - std::string allowFollowers(std::string state, const EdgeVector& fromEdges, const EdgeVector& toEdges); - - std::string allowPredecessors(std::string state, const EdgeVector& fromEdges, const EdgeVector& toEdges, - const std::vector& fromLanes, const std::vector& toLanes); - - std::string allowUnrelated(std::string state, const EdgeVector& fromEdges, const EdgeVector& toEdges, - const std::vector& isTurnaround, - const std::vector& crossings); - - std::string allowByVClass(std::string state, const EdgeVector& fromEdges, const EdgeVector& toEdges, SVCPermissions perm); - - /// @brief whether the given index is forbidden by a green link in the current state - bool forbidden(const std::string& state, int index, const EdgeVector& fromEdges, const EdgeVector& toEdges); - - /** @brief change 'G' to 'g' for conflicting connections - * @param[in] state - * @param[in] fromEdges - * @param[in] toEdges - * @param[in] isTurnaround - * @param[in] fromLanes - * @param[in] hadGreenMajor - * @param[out] haveForbiddenLeftMover - * @param[out] rightTurnConflicts - * @return The corrected state - */ - std::string correctConflicting(std::string state, const EdgeVector& fromEdges, const EdgeVector& toEdges, - const std::vector& isTurnaround, - const std::vector& fromLanes, - const std::vector& hadGreenMajor, - bool& haveForbiddenLeftMover, std::vector& rightTurnConflicts); - - /// @brief fix states in regard to custom crossing indices - void checkCustomCrossingIndices(NBTrafficLightLogic* logic) const; - - /** @class edge_by_incoming_priority_sorter - * @brief Sorts edges by their priority within the node they end at - */ - class edge_by_incoming_priority_sorter { - public: - /** @brief comparing operator - * @param[in] e1 an edge - * @param[in] e2 an edge - */ - int operator()(const NBEdge* const e1, const NBEdge* const e2) const { - if (e1->getJunctionPriority(e1->getToNode()) != e2->getJunctionPriority(e2->getToNode())) { - return e1->getJunctionPriority(e1->getToNode()) > e2->getJunctionPriority(e2->getToNode()); - } - return e1->getID() > e2->getID(); - } - }; - - -private: - /// @brief Whether left-mover should not have an additional phase - bool myHaveSinglePhase; - -}; diff --git a/Util/OSM2ODR/src/netbuild/NBPTLine.cpp b/Util/OSM2ODR/src/netbuild/NBPTLine.cpp deleted file mode 100644 index c10f5e03e..000000000 --- a/Util/OSM2ODR/src/netbuild/NBPTLine.cpp +++ /dev/null @@ -1,265 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NBPTLine.cpp -/// @author Gregor Laemmel -/// @author Nikita Cherednychek -/// @date Tue, 20 Mar 2017 -/// -// The representation of one direction of a single pt line -/****************************************************************************/ -#include - -#include -#include -#include -#include -#include "NBEdgeCont.h" -#include "NBPTLine.h" -#include "NBPTStop.h" - -NBPTLine::NBPTLine(const std::string& id, const std::string& name, const std::string& type, const std::string& ref, int interval, const std::string& nightService, - SUMOVehicleClass vClass) : - myName(name), - myType(type), - myPTLineId(id), - myRef(ref != "" ? ref : name), - myInterval(interval), - myNightService(nightService), - myVClass(vClass) -{ } - -void NBPTLine::addPTStop(NBPTStop* pStop) { - myPTStops.push_back(pStop); - -} - -std::vector NBPTLine::getStops() { - return myPTStops; -} - -void NBPTLine::write(OutputDevice& device, NBEdgeCont& ec) { - device.openTag(SUMO_TAG_PT_LINE); - device.writeAttr(SUMO_ATTR_ID, myPTLineId); - if (!myName.empty()) { - device.writeAttr(SUMO_ATTR_NAME, StringUtils::escapeXML(myName)); - } - - device.writeAttr(SUMO_ATTR_LINE, StringUtils::escapeXML(myRef)); - device.writeAttr(SUMO_ATTR_TYPE, myType); - device.writeAttr(SUMO_ATTR_VCLASS, toString(myVClass)); - if (myInterval > 0) { - // write seconds - device.writeAttr(SUMO_ATTR_PERIOD, 60 * myInterval); - } - if (myNightService != "") { - device.writeAttr("nightService", myNightService); - } - device.writeAttr("completeness", toString((double)myPTStops.size() / (double)myNumOfStops)); - - std::vector validEdgeIDs; - // filter out edges that have been removed due to joining junctions - // (the rest of the route is valid) - for (NBEdge* e : myRoute) { - if (ec.retrieve(e->getID())) { - validEdgeIDs.push_back(e->getID()); - } - } - if (!myRoute.empty()) { - device.openTag(SUMO_TAG_ROUTE); - device.writeAttr(SUMO_ATTR_EDGES, validEdgeIDs); - device.closeTag(); - } - - for (auto& myPTStop : myPTStops) { - device.openTag(SUMO_TAG_BUS_STOP); - device.writeAttr(SUMO_ATTR_ID, myPTStop->getID()); - device.writeAttr(SUMO_ATTR_NAME, StringUtils::escapeXML(myPTStop->getName())); - device.closeTag(); - } - device.closeTag(); - -} - -void NBPTLine::addWayNode(long long int way, long long int node) { - std::string wayStr = toString(way); - if (wayStr != myCurrentWay) { - myCurrentWay = wayStr; - myWays.push_back(wayStr); - } - myWaysNodes[wayStr].push_back(node); - -} -const std::vector& NBPTLine::getMyWays() const { - return myWays; -} -std::vector* NBPTLine::getWaysNodes(std::string wayId) { - if (myWaysNodes.find(wayId) != myWaysNodes.end()) { - return &myWaysNodes[wayId]; - } - return nullptr; -} - -void -NBPTLine::setEdges(const std::vector& edges) { - myRoute = edges; - // ensure permissions - for (NBEdge* e : edges) { - SVCPermissions permissions = e->getPermissions(); - if ((permissions & myVClass) != myVClass) { - SVCPermissions nVuln = ~(SVC_PEDESTRIAN | SVC_BICYCLE); - if (permissions != 0 && (permissions & nVuln) == 0) { - // this is a footpath or sidewalk. Add another lane - e->addRestrictedLane(SUMO_const_laneWidth, myVClass); - } else { - // add permissions to the rightmost lane that is not exclusively used for pedestrians / bicycles - for (int i = 0; i < (int)e->getNumLanes(); i++) { - if ((e->getPermissions(i) & nVuln) != 0) { - e->allowVehicleClass(i, myVClass); - break; - } - } - } - } - } -} - -void NBPTLine::setMyNumOfStops(int numStops) { - myNumOfStops = numStops; -} -const std::vector& NBPTLine::getRoute() const { - return myRoute; -} - -std::vector -NBPTLine::getStopEdges(const NBEdgeCont& ec) const { - std::vector result; - for (NBPTStop* stop : myPTStops) { - NBEdge* e = ec.retrieve(stop->getEdgeId()); - if (e != nullptr) { - result.push_back(e); - } - } - return result; -} - -NBEdge* -NBPTLine::getRouteStart(const NBEdgeCont& ec) const { - std::vector validEdges; - // filter out edges that have been removed due to joining junctions - for (NBEdge* e : myRoute) { - if (ec.retrieve(e->getID())) { - validEdges.push_back(e); - } - } - if (validEdges.size() == 0) { - return nullptr; - } - // filter out edges after the first stop - if (myPTStops.size() > 0) { - NBEdge* firstStopEdge = ec.retrieve(myPTStops.front()->getEdgeId()); - if (firstStopEdge == nullptr) { - WRITE_WARNING("Could not retrieve edge '" + myPTStops.front()->getEdgeId() + "' for first stop of line '" + myPTLineId + "'"); - return nullptr; - - } - auto it = std::find(validEdges.begin(), validEdges.end(), firstStopEdge); - if (it == validEdges.end()) { - WRITE_WARNING("First stop edge '" + firstStopEdge->getID() + "' is not part of the route of line '" + myPTLineId + "'"); - return nullptr; - } - } - return validEdges.front(); -} - -NBEdge* -NBPTLine::getRouteEnd(const NBEdgeCont& ec) const { - std::vector validEdges; - // filter out edges that have been removed due to joining junctions - for (NBEdge* e : myRoute) { - if (ec.retrieve(e->getID())) { - validEdges.push_back(e); - } - } - if (validEdges.size() == 0) { - return nullptr; - } - // filter out edges after the last stop - if (myPTStops.size() > 0) { - NBEdge* lastStopEdge = ec.retrieve(myPTStops.back()->getEdgeId()); - if (lastStopEdge == nullptr) { - WRITE_WARNING("Could not retrieve edge '" + myPTStops.back()->getEdgeId() + "' for last stop of line '" + myPTLineId + "'"); - return nullptr; - - } - auto it = std::find(validEdges.begin(), validEdges.end(), lastStopEdge); - if (it == validEdges.end()) { - WRITE_WARNING("Last stop edge '" + lastStopEdge->getID() + "' is not part of the route of line '" + myPTLineId + "'"); - return nullptr; - } - } - return validEdges.back(); -} - -void -NBPTLine::replaceStop(NBPTStop* oldStop, NBPTStop* newStop) { - for (int i = 0; i < (int)myPTStops.size(); i++) { - if (myPTStops[i] == oldStop) { - myPTStops[i] = newStop; - } - } -} - -void -NBPTLine::replaceEdge(const std::string& edgeID, const EdgeVector& replacement) { - EdgeVector oldRoute = myRoute; - int stopIndex = 0; - myRoute.clear(); - std::vector unassigned; - for (NBEdge* e : oldRoute) { - if (e->getID() == edgeID) { - myRoute.insert(myRoute.end(), replacement.begin(), replacement.end()); - } else { - myRoute.push_back(e); - } - while (stopIndex < (int)myPTStops.size() && myPTStops[stopIndex]->getEdgeId() == e->getID()) { - if (e->getID() == edgeID) { - NBPTStop* stop = myPTStops[stopIndex]; - // find best edge among replacement edges - double bestDist = std::numeric_limits::max(); - NBEdge* bestEdge = nullptr; - for (NBEdge* cand : replacement) { - double dist = cand->getGeometry().distance2D(stop->getPosition()); - if (dist < bestDist) { - bestDist = dist; - bestEdge = cand; - } - } - if (bestDist != std::numeric_limits::max()) { - stop->findLaneAndComputeBusStopExtent(bestEdge); - if ((bestEdge->getPermissions() & SVC_PEDESTRIAN) != 0) { - // no need for access - stop->clearAccess(); - } - } else { - WRITE_WARNING("Could not re-assign ptstop '" + stop->getID() + "' after replacing edge '" + edgeID + "'"); - unassigned.push_back(stop); - } - } - stopIndex++; - } - } - for (NBPTStop* stop: unassigned) { - myPTStops.erase(std::find(myPTStops.begin(), myPTStops.end(), stop)); - } -} diff --git a/Util/OSM2ODR/src/netbuild/NBPTLine.h b/Util/OSM2ODR/src/netbuild/NBPTLine.h deleted file mode 100644 index 4269893d3..000000000 --- a/Util/OSM2ODR/src/netbuild/NBPTLine.h +++ /dev/null @@ -1,125 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NBPTLine.h -/// @author Gregor Laemmel -/// @author Nikita Cherednychek -/// @date Tue, 20 Mar 2017 -/// -// The representation of one direction of a single pt line -/****************************************************************************/ -#pragma once - - -#include -#include -#include -#include "NBEdge.h" // Cherednychek - -// =========================================================================== -// class declarations -// =========================================================================== -class OutputDevice; -class NBPTStop; -class NBEdgeCont; - -class NBPTLine { - -public: - explicit NBPTLine(const std::string& id, const std::string& name, - const std::string& type, const std::string& ref, int interval, const std::string& nightService, - SUMOVehicleClass vClass); - - void addPTStop(NBPTStop* pStop); - - const std::string& getLineID() const { - return myPTLineId; - } - - const std::string& getName() const { - return myName; - } - - const std::string& getType() const { - return myType; - } - - std::vector getStops(); - void write(OutputDevice& device, NBEdgeCont& ec); - void addWayNode(long long int way, long long int node); - - void setMyNumOfStops(int numStops); - - /// @brief get line reference (not unique) - const std::string& getRef() const { - return myRef; - } - - void replaceStops(std::vector stops) { - myPTStops = stops; - } - /// @brief get stop edges - std::vector getStopEdges(const NBEdgeCont& ec) const; - - /// @brief return first valid edge of myRoute (if it doest not lie after the first stop) - NBEdge* getRouteStart(const NBEdgeCont& ec) const; - - /// @brief return last valid edge of myRoute (if it doest not lie before the last stop) - NBEdge* getRouteEnd(const NBEdgeCont& ec) const; - - /// @brief replace the given stop - void replaceStop(NBPTStop* oldStop, NBPTStop* newStop); - - /// @brief replace the edge with the given edge list - void replaceEdge(const std::string& edgeID, const EdgeVector& replacement); - - void setName(const std::string& name) { - myName = name; - } - -private: - std::string myName; - std::string myType; - std::vector myPTStops; - -private: - std::map > myWaysNodes; - std::vector myWays; -public: - const std::vector& getMyWays() const; - std::vector* getWaysNodes(std::string wayId); -private: - - std::string myCurrentWay; - std::string myPTLineId; - std::string myRef; - - // @brief the service interval in minutes - int myInterval; - - std::string myNightService; - SUMOVehicleClass myVClass; - -public: - void setEdges(const std::vector& edges); -private: - // route of ptline - std::vector myRoute; -public: - const std::vector& getRoute() const; -private: - - int myNumOfStops; -}; - - diff --git a/Util/OSM2ODR/src/netbuild/NBPTLineCont.cpp b/Util/OSM2ODR/src/netbuild/NBPTLineCont.cpp deleted file mode 100644 index b0547a5f5..000000000 --- a/Util/OSM2ODR/src/netbuild/NBPTLineCont.cpp +++ /dev/null @@ -1,491 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NBPTLineCont.cpp -/// @author Gregor Laemmel -/// @author Nikita Cherednychek -/// @date Tue, 20 Mar 2017 -/// -// Container for NBPTLine during netbuild -/****************************************************************************/ - -#include -#include -#include -#include -#include -#include "NBPTLineCont.h" -#include "NBPTStop.h" -#include "NBEdge.h" -#include "NBNode.h" -#include "NBVehicle.h" -#include "NBPTStopCont.h" - -//#define DEBUG_FIND_WAY -#define DEBUGSTOPID "" - -// =========================================================================== -// static value definitions -// =========================================================================== -const int NBPTLineCont::FWD(1); -const int NBPTLineCont::BWD(-1); -// =========================================================================== -// method definitions -// =========================================================================== - -NBPTLineCont::NBPTLineCont() { } - - -NBPTLineCont::~NBPTLineCont() { - for (auto& myPTLine : myPTLines) { - delete myPTLine.second; - } - myPTLines.clear(); -} - -void -NBPTLineCont::insert(NBPTLine* ptLine) { - myPTLines[ptLine->getLineID()] = ptLine; -} - -void NBPTLineCont::process(NBEdgeCont& ec, NBPTStopCont& sc) { - for (auto& item : myPTLines) { - if (item.second->getMyWays().size() > 0) { - // loaded from OSM rather than ptline input. We can use extra - // information to reconstruct route and stops - constructRoute(item.second, ec); - // map stops to ways, using the constructed route for loose stops - reviseStops(item.second, ec, sc); - } - } -} - -void NBPTLineCont::reviseStops(NBPTLine* line, const NBEdgeCont& ec, NBPTStopCont& sc) { - const std::vector& waysIds = line->getMyWays(); - if (waysIds.size() <= 1) { - WRITE_WARNING("Cannot revise pt stop localization for pt line: " + line->getLineID() + ", which consist of one way only. Ignoring!"); - return; - } - if (line->getRoute().size() == 0) { - WRITE_WARNING("Cannot revise pt stop localization for pt line: " + line->getLineID() + ", which has no route edges. Ignoring!"); - return; - } - std::vector stops = line->getStops(); - for (NBPTStop* stop : stops) { - //get the corresponding and one of the two adjacent ways - stop = findWay(line, stop, ec, sc); - auto waysIdsIt = std::find(waysIds.begin(), waysIds.end(), stop->getOrigEdgeId()); - if (waysIdsIt == waysIds.end()) { - // warning already given - continue; - } - // find directional edge (OSM ways are bidirectional) - std::vector* way = line->getWaysNodes(stop->getOrigEdgeId()); - if (way == nullptr) { - WRITE_WARNING("Cannot assign stop '" + stop->getID() + "' on edge '" + stop->getOrigEdgeId() + "' to pt line '" + line->getLineID() + "' (wayNodes not found). Ignoring!"); - continue; - } - - - int dir; - std::string adjIdPrev; - std::string adjIdNext; - if (waysIdsIt != waysIds.begin()) { - adjIdPrev = *(waysIdsIt - 1); - } - if (waysIdsIt != (waysIds.end() - 1)) { - adjIdNext = *(waysIdsIt + 1); - } - std::vector* wayPrev = line->getWaysNodes(adjIdPrev); - std::vector* wayNext = line->getWaysNodes(adjIdNext); - if (wayPrev == nullptr && wayNext == nullptr) { - WRITE_WARNING("Cannot revise pt stop localization for incomplete pt line: " + line->getLineID() - + ". Ignoring!"); - continue; - } - long long int wayEnds = *(way->end() - 1); - long long int wayBegins = *(way->begin()); - long long int wayPrevEnds = wayPrev != nullptr ? *(wayPrev->end() - 1) : 0; - long long int wayPrevBegins = wayPrev != nullptr ? *(wayPrev->begin()) : 0; - long long int wayNextEnds = wayNext != nullptr ? *(wayNext->end() - 1) : 0; - long long int wayNextBegins = wayNext != nullptr ? *(wayNext->begin()) : 0; - if (wayBegins == wayPrevEnds || wayBegins == wayPrevBegins || wayEnds == wayNextBegins - || wayEnds == wayNextEnds) { - dir = FWD; - } else if (wayEnds == wayPrevBegins || wayEnds == wayPrevEnds || wayBegins == wayNextEnds - || wayBegins == wayNextBegins) { - dir = BWD; - } else { - WRITE_WARNING("Cannot revise pt stop localization for incomplete pt line: " + line->getLineID() - + ". Ignoring!"); - continue; - } - - std::string edgeId = stop->getEdgeId(); - NBEdge* current = ec.getByID(edgeId); - int assignedTo = edgeId.at(0) == '-' ? BWD : FWD; - - if (dir != assignedTo) { - NBEdge* reverse = NBPTStopCont::getReverseEdge(current); - if (reverse == nullptr) { - WRITE_WARNING("Could not re-assign PT stop: " + stop->getID() + " probably broken osm file"); - continue; - } - stop->setEdgeId(reverse->getID(), ec); - WRITE_WARNING("PT stop: " + stop->getID() + " has been moved to edge: " + reverse->getID()); - } - myServedPTStops.insert(stop->getID()); - stop->addLine(line->getRef()); - } -} - -NBPTStop* -NBPTLineCont::findWay(NBPTLine* line, NBPTStop* stop, const NBEdgeCont& ec, NBPTStopCont& sc) const { - const std::vector& waysIds = line->getMyWays(); -#ifdef DEBUG_FIND_WAY - if (stop->getID() == DEBUGSTOPID) { - std::cout << " stop=" << stop->getID() << " line=" << line->getLineID() << " edgeID=" << stop->getEdgeId() << " origID=" << stop->getOrigEdgeId() << "\n"; - } -#endif - if (stop->isLoose()) { - // find closest edge in route - double minDist = std::numeric_limits::max(); - NBEdge* best = nullptr; - for (NBEdge* edge : line->getRoute()) { - const double dist = edge->getLaneShape(0).distance2D(stop->getPosition()); - if (dist < minDist) { - best = edge; - minDist = dist; - } - } -#ifdef DEBUG_FIND_WAY - if (stop->getID() == DEBUGSTOPID) { - std::cout << " best=" << Named::getIDSecure(best) << " minDist=" << minDist << " wayID=" << getWayID(best->getID()) - << " found=" << (std::find(waysIds.begin(), waysIds.end(), getWayID(best->getID())) != waysIds.end()) - << " wayIDs=" << toString(waysIds) << "\n"; - } -#endif - if (minDist < OptionsCont::getOptions().getFloat("ptline.match-dist")) { - const std::string wayID = getWayID(best->getID()); - if (stop->getEdgeId() == "") { - stop->setEdgeId(best->getID(), ec); - stop->setMyOrigEdgeId(wayID); - } else if (stop->getEdgeId() != best->getID()) { - // stop is used by multiple lines and mapped to different edges. - // check if an alterantive stop already exists - NBPTStop* newStop = sc.findStop(wayID, stop->getPosition()); - if (newStop == nullptr) { - newStop = new NBPTStop(stop->getID() + "@" + line->getLineID(), stop->getPosition(), best->getID(), wayID, stop->getLength(), stop->getName(), stop->getPermissions()); - newStop->setEdgeId(best->getID(), ec); // trigger lane assignment - sc.insert(newStop); - } - line->replaceStop(stop, newStop); - stop = newStop; - } - } else { - WRITE_WARNING("Could not assign stop '" + stop->getID() + "' to pt line '" + line->getLineID() - + "' (closest edge '" + best->getID() + "', distance " + toString(minDist) + "). Ignoring!"); - } - } else { - // if the stop is part of an edge, find that edge among the line edges - auto waysIdsIt = waysIds.begin(); - for (; waysIdsIt != waysIds.end(); waysIdsIt++) { - if ((*waysIdsIt) == stop->getOrigEdgeId()) { - break; - } - } - - if (waysIdsIt == waysIds.end()) { - // stop edge not found, try additional edges - for (auto& edgeCand : stop->getMyAdditionalEdgeCandidates()) { - bool found = false; - waysIdsIt = waysIds.begin(); - for (; waysIdsIt != waysIds.end(); waysIdsIt++) { - if ((*waysIdsIt) == edgeCand.first) { - if (stop->setEdgeId(edgeCand.second, ec)) { - stop->setMyOrigEdgeId(edgeCand.first); - found = true; - break; - } - } - } - if (found) { - break; - } - } - if (waysIdsIt == waysIds.end()) { - WRITE_WARNING("Cannot assign stop '" + stop->getID() + "' on edge '" + stop->getOrigEdgeId() + "' to pt line '" + line->getLineID() + "'. Ignoring!"); - } - } - } - return stop; -} - - -void NBPTLineCont::constructRoute(NBPTLine* pTLine, NBEdgeCont& cont) { - std::vector edges; - - NBNode* first = nullptr; - NBNode* last = nullptr; - std::vector prevWayEdges; - std::vector prevWayMinusEdges; - prevWayEdges.clear(); - prevWayMinusEdges.clear(); - std::vector currentWayEdges; - std::vector currentWayMinusEdges; - for (auto it3 = pTLine->getMyWays().begin(); - it3 != pTLine->getMyWays().end(); it3++) { - - if (cont.retrieve(*it3, false) != nullptr) { - currentWayEdges.push_back(cont.retrieve(*it3, false)); - } else { - int i = 0; - while (cont.retrieve(*it3 + "#" + std::to_string(i), false) != nullptr) { - currentWayEdges.push_back(cont.retrieve(*it3 + "#" + std::to_string(i), false)); - i++; - } - } - - if (cont.retrieve("-" + *it3, false) != nullptr) { - currentWayMinusEdges.push_back(cont.retrieve("-" + *it3, false)); - } else { - int i = 0; - while (cont.retrieve("-" + *it3 + "#" + std::to_string(i), false) != nullptr) { - currentWayMinusEdges.insert(currentWayMinusEdges.begin(), - cont.retrieve("-" + *it3 + "#" + std::to_string(i), false)); - i++; - } - } - if (currentWayEdges.empty()) { - continue; - } - if (last == currentWayEdges.front()->getFromNode() && last != nullptr) { - if (!prevWayEdges.empty()) { - edges.insert(edges.end(), prevWayEdges.begin(), prevWayEdges.end()); - prevWayEdges.clear(); - prevWayMinusEdges.clear(); - } - edges.insert(edges.end(), currentWayEdges.begin(), currentWayEdges.end()); - last = currentWayEdges.back()->getToNode(); - } else if (last == currentWayEdges.back()->getToNode() && last != nullptr) { - if (!prevWayEdges.empty()) { - edges.insert(edges.end(), prevWayEdges.begin(), prevWayEdges.end()); - prevWayEdges.clear(); - prevWayMinusEdges.clear(); - } - if (currentWayMinusEdges.empty()) { - currentWayEdges.clear(); - last = nullptr; - continue; - } else { - edges.insert(edges.end(), currentWayMinusEdges.begin(), currentWayMinusEdges.end()); - last = currentWayMinusEdges.back()->getToNode(); - } - } else if (first == currentWayEdges.front()->getFromNode() && first != nullptr) { - edges.insert(edges.end(), prevWayMinusEdges.begin(), prevWayMinusEdges.end()); - edges.insert(edges.end(), currentWayEdges.begin(), currentWayEdges.end()); - last = currentWayEdges.back()->getToNode(); - prevWayEdges.clear(); - prevWayMinusEdges.clear(); - } else if (first == currentWayEdges.back()->getToNode() && first != nullptr) { - edges.insert(edges.end(), prevWayMinusEdges.begin(), prevWayMinusEdges.end()); - if (currentWayMinusEdges.empty()) { - currentWayEdges.clear(); - last = nullptr; - prevWayEdges.clear(); - prevWayMinusEdges.clear(); - continue; - } else { - edges.insert(edges.end(), currentWayMinusEdges.begin(), currentWayMinusEdges.end()); - last = currentWayMinusEdges.back()->getToNode(); - prevWayEdges.clear(); - prevWayMinusEdges.clear(); - } - } else { - if (it3 != pTLine->getMyWays().begin()) { - WRITE_WARNING("Incomplete route for ptline '" + toString(pTLine->getLineID()) + - (pTLine->getName() != "" ? "' (" + pTLine->getName() + ")" : "")); - } - prevWayEdges = currentWayEdges; - prevWayMinusEdges = currentWayMinusEdges; - if (!prevWayEdges.empty()) { - first = prevWayEdges.front()->getFromNode(); - last = prevWayEdges.back()->getToNode(); - } else { - first = nullptr; - last = nullptr; - } - } - currentWayEdges.clear(); - currentWayMinusEdges.clear(); - } - pTLine->setEdges(edges); -} - - -void -NBPTLineCont::addEdges2Keep(const OptionsCont& oc, std::set& into) { - if (oc.isSet("ptline-output")) { - for (auto& item : myPTLines) { - for (auto edge : item.second->getRoute()) { - into.insert(edge->getID()); - } - } - } -} - - -void -NBPTLineCont::replaceEdge(const std::string& edgeID, const EdgeVector& replacement) { - //std::cout << " replaceEdge " << edgeID << " replacement=" << toString(replacement) << "\n"; - for (auto& item : myPTLines) { - item.second->replaceEdge(edgeID, replacement); - } -} - - -std::set& -NBPTLineCont::getServedPTStops() { - return myServedPTStops; -} - - -void -NBPTLineCont::fixBidiStops(const NBEdgeCont& ec) { - std::map types; - types["bus"] = SVC_BUS; - types["tram"] = SVC_TRAM; - types["train"] = SVC_RAIL; - types["subway"] = SVC_RAIL_URBAN; - types["light_rail"] = SVC_RAIL_URBAN; - types["ferry"] = SVC_SHIP; - - SUMOAbstractRouter* const router = new DijkstraRouter( - ec.getAllRouterEdges(), true, &NBRouterEdge::getTravelTimeStatic, nullptr, true); - - for (auto& item : myPTLines) { - NBPTLine* line = item.second; - std::vector stops = line->getStops(); - if (stops.size() < 2) { - continue; - } - if (types.count(line->getType()) == 0) { - WRITE_WARNING("Could not determine vehicle class for public transport line of type '" - + line->getType() + "'."); - continue; - } - NBVehicle veh(line->getRef(), types[line->getType()]); - std::vector newStops; - NBPTStop* from = nullptr; - for (auto it = stops.begin(); it != stops.end(); ++it) { - NBPTStop* to = *it; - NBPTStop* used = *it; - if (to->getBidiStop() != nullptr) { - double best = std::numeric_limits::max(); - NBPTStop* to2 = to->getBidiStop(); - if (from == nullptr) { - if ((it + 1) != stops.end()) { - from = to; - NBPTStop* from2 = to2; - to = *(it + 1); - const double c1 = getCost(ec, *router, from, to, &veh); - const double c2 = getCost(ec, *router, from2, to, &veh); - //std::cout << " from=" << from->getID() << " to=" << to->getID() << " c1=" << MIN2(10000.0, c1) << "\n"; - //std::cout << " from2=" << from2->getID() << " to=" << to->getID() << " c2=" << MIN2(10000.0, c2) << "\n"; - best = c1; - if (to->getBidiStop() != nullptr) { - to2 = to->getBidiStop(); - const double c3 = getCost(ec, *router, from, to2, &veh); - const double c4 = getCost(ec, *router, from2, to2, &veh); - //std::cout << " from=" << from->getID() << " to2=" << to2->getID() << " c3=" << MIN2(10000.0, c3) << "\n"; - //std::cout << " from2=" << from2->getID() << " to2=" << to2->getID() << " c4=" << MIN2(10000.0, c4) << "\n"; - if (c2 < best) { - used = from2; - best = c2; - } - if (c3 < best) { - used = from; - best = c3; - } - if (c4 < best) { - used = from2; - best = c4; - } - } else { - if (c2 < c1) { - used = from2; - best = c2; - } else { - best = c1; - } - } - } - } else { - const double c1 = getCost(ec, *router, from, to, &veh); - const double c2 = getCost(ec, *router, from, to2, &veh); - //std::cout << " from=" << from->getID() << " to=" << to->getID() << " c1=" << MIN2(10000.0, c1) << "\n"; - //std::cout << " from=" << from->getID() << " t2o=" << to2->getID() << " c2=" << MIN2(10000.0, c2) << "\n"; - if (c2 < c1) { - used = to2; - best = c2; - } else { - best = c1; - } - - } - if (best < std::numeric_limits::max()) { - from = used; - } else { - WRITE_WARNING("Could not determine direction for line '" + toString(line->getLineID()) + "' at stop '" + used->getID() + "'"); - }; - } - from = used; - newStops.push_back(used); - } - assert(stops.size() == newStops.size()); - line->replaceStops(newStops); - } - delete router; -} - - -double -NBPTLineCont::getCost(const NBEdgeCont& ec, SUMOAbstractRouter& router, - const NBPTStop* from, const NBPTStop* to, const NBVehicle* veh) { - NBEdge* fromEdge = ec.getByID(from->getEdgeId()); - NBEdge* toEdge = ec.getByID(to->getEdgeId()); - if (fromEdge == nullptr || toEdge == nullptr) { - return std::numeric_limits::max(); - } - std::vector route; - router.compute(fromEdge, toEdge, veh, 0, route); - if (route.size() == 0) { - return std::numeric_limits::max(); - } else { - return router.recomputeCosts(route, veh, 0); - } -} - - -std::string -NBPTLineCont::getWayID(const std::string& edgeID) { - std::size_t found = edgeID.rfind("#"); - std::string result = edgeID; - if (found != std::string::npos) { - result = edgeID.substr(0, found); - } - if (result[0] == '-') { - result = result.substr(1); - } - return result; -} diff --git a/Util/OSM2ODR/src/netbuild/NBPTLineCont.h b/Util/OSM2ODR/src/netbuild/NBPTLineCont.h deleted file mode 100644 index fb17c87fd..000000000 --- a/Util/OSM2ODR/src/netbuild/NBPTLineCont.h +++ /dev/null @@ -1,82 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NBPTLineCont.h -/// @author Gregor Laemmel -/// @date Tue, 20 Mar 2017 -/// -// Container for NBPTLine during netbuild -/****************************************************************************/ - -#pragma once - - -#include -#include "utils/router/SUMOAbstractRouter.h" -#include "NBPTLine.h" -#include "NBEdgeCont.h" - -class NBPTLineCont { - -public: - /// @brief constructor - NBPTLineCont(); - - /// @brief destructor - ~NBPTLineCont(); - - /// @brief insert new line - void insert(NBPTLine* ptLine); - - const std::map& getLines() const { - return myPTLines; - } - - void process(NBEdgeCont& ec, NBPTStopCont& sc); - - /// @brief add edges that must be kept - void addEdges2Keep(const OptionsCont& oc, std::set& into); - - /// @brief replace the edge with the given edge list in all lines - void replaceEdge(const std::string& edgeID, const EdgeVector& replacement); - - /// @brief select the correct stop on superposed rail edges - void fixBidiStops(const NBEdgeCont& ec); - - std::set& getServedPTStops(); -private: - - static const int FWD; - static const int BWD; - - /// @brief The map of names to pt lines - std::map myPTLines; - - /// @brief find directional edge for all stops of the line - void reviseStops(NBPTLine* line, const NBEdgeCont& ec, NBPTStopCont& sc); - - /* @brief find way element corresponding to the stop - * @note: if the edge id is updated, the stop extent is recomputed */ - NBPTStop* findWay(NBPTLine* line, NBPTStop* stop, const NBEdgeCont& ec, NBPTStopCont& sc) const; - - void constructRoute(NBPTLine* myPTLine, NBEdgeCont& cont); - - std::set myServedPTStops; - - static double getCost(const NBEdgeCont& ec, SUMOAbstractRouter& router, - const NBPTStop* from, const NBPTStop* to, const NBVehicle* veh); - - static std::string getWayID(const std::string& edgeID); -}; - - diff --git a/Util/OSM2ODR/src/netbuild/NBPTPlatform.cpp b/Util/OSM2ODR/src/netbuild/NBPTPlatform.cpp deleted file mode 100644 index 3f446900a..000000000 --- a/Util/OSM2ODR/src/netbuild/NBPTPlatform.cpp +++ /dev/null @@ -1,40 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NBPTPlatform.cpp -/// @author Gregor Laemmel -/// @date Tue, 24 Aug 2017 -/// -// The representation of a pt platform -/****************************************************************************/ -#include "NBPTPlatform.h" -NBPTPlatform::NBPTPlatform(Position position, double d): myPos(position), myLength(d) { -} - - -const Position& -NBPTPlatform::getPos() const { - return myPos; -} - - -void -NBPTPlatform::reshiftPosition(const double offsetX, const double offsetY) { - myPos.add(offsetX, offsetY, 0); -} - - -double -NBPTPlatform::getLength() const { - return myLength; -} diff --git a/Util/OSM2ODR/src/netbuild/NBPTPlatform.h b/Util/OSM2ODR/src/netbuild/NBPTPlatform.h deleted file mode 100644 index 8c9b3c6f4..000000000 --- a/Util/OSM2ODR/src/netbuild/NBPTPlatform.h +++ /dev/null @@ -1,37 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NBPTPlatform.h -/// @author Gregor Laemmel -/// @date Tue, 24 Aug 2017 -/// -// The representation of a pt platform -/****************************************************************************/ - -#pragma once - - -#include -class NBPTPlatform { -public: - NBPTPlatform(Position position, double d); -public: - const Position& getPos() const; - void reshiftPosition(const double offsetX, const double offsetY); - double getLength() const; -private: - Position myPos; - double myLength; -}; - - diff --git a/Util/OSM2ODR/src/netbuild/NBPTStop.cpp b/Util/OSM2ODR/src/netbuild/NBPTStop.cpp deleted file mode 100644 index 7807bb024..000000000 --- a/Util/OSM2ODR/src/netbuild/NBPTStop.cpp +++ /dev/null @@ -1,259 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NBPTStop.cpp -/// @author Gregor Laemmel -/// @date Tue, 20 Mar 2017 -/// -// The representation of a single pt stop -/****************************************************************************/ -#include - -#include -#include -#include "NBPTStop.h" -#include "NBEdge.h" -#include "NBEdgeCont.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -NBPTStop::NBPTStop(std::string ptStopId, Position position, std::string edgeId, std::string origEdgeId, double length, - std::string name, SVCPermissions svcPermissions, double parkingLength) : - myPTStopId(ptStopId), - myPosition(position), - myEdgeId(edgeId), - myOrigEdgeId(origEdgeId), - myPTStopLength(length), - myName(name), - myParkingLength(parkingLength), - myPermissions(svcPermissions), - myBidiStop(nullptr), - myIsLoose(origEdgeId == ""), - myIsMultipleStopPositions(false) { -} - -std::string -NBPTStop::getID() const { - return myPTStopId; -} - -const std::string -NBPTStop::getOrigEdgeId() const { - return myOrigEdgeId; -} - - -const std::string -NBPTStop::getEdgeId() const { - return myEdgeId; -} - - -const std::string -NBPTStop::getName() const { - return myName; -} - - -const Position& -NBPTStop::getPosition() const { - return myPosition; -} - -void -NBPTStop::mirrorX() { - myPosition.mul(1, -1); -} - -void -NBPTStop::computeExtent(double center, double edgeLength) { - myStartPos = MAX2(0.0, center - myPTStopLength / 2.); - myEndPos = MIN2(center + myPTStopLength / 2., edgeLength); -} - - -void -NBPTStop::addLine(const std::string& line) { - const std::string l = StringUtils::escapeXML(line); - if (std::find(myLines.begin(), myLines.end(), l) == myLines.end()) { - myLines.push_back(l); - } -} - - -void -NBPTStop::write(OutputDevice& device) { - device.openTag(SUMO_TAG_BUS_STOP); - device.writeAttr(SUMO_ATTR_ID, myPTStopId); - if (!myName.empty()) { - device.writeAttr(SUMO_ATTR_NAME, StringUtils::escapeXML(myName)); - } - device.writeAttr(SUMO_ATTR_LANE, myLaneId); - device.writeAttr(SUMO_ATTR_STARTPOS, myStartPos); - device.writeAttr(SUMO_ATTR_ENDPOS, myEndPos); - device.writeAttr(SUMO_ATTR_FRIENDLY_POS, "true"); - if (myLines.size() > 0) { - device.writeAttr(SUMO_ATTR_LINES, toString(myLines)); - } - if (myParkingLength > 0) { - device.writeAttr(SUMO_ATTR_PARKING_LENGTH, myParkingLength); - } - if (!myAccesses.empty()) { - std::sort(myAccesses.begin(), myAccesses.end()); - for (auto tuple : myAccesses) { - device.openTag(SUMO_TAG_ACCESS); - device.writeAttr(SUMO_ATTR_LANE, std::get<0>(tuple)); - device.writeAttr(SUMO_ATTR_POSITION, std::get<1>(tuple)); - device.writeAttr(SUMO_ATTR_LENGTH, std::get<2>(tuple)); - device.writeAttr(SUMO_ATTR_FRIENDLY_POS, true); - device.closeTag(); - } - } - device.closeTag(); -} - - -void -NBPTStop::reshiftPosition(const double offsetX, const double offsetY) { - myPosition.add(offsetX, offsetY, 0); - for (NBPTPlatform& platformCand : myPlatformCands) { - platformCand.reshiftPosition(offsetX, offsetY); - } -} - - -SVCPermissions -NBPTStop::getPermissions() const { - return myPermissions; -} - - -void -NBPTStop::addPlatformCand(NBPTPlatform platform) { - myPlatformCands.push_back(platform); -} - - -const std::vector& -NBPTStop::getPlatformCands() { - return myPlatformCands; -} - - -bool -NBPTStop::getIsMultipleStopPositions() const { - return myIsMultipleStopPositions; -} - - -void -NBPTStop::setIsMultipleStopPositions(bool multipleStopPositions) { - myIsMultipleStopPositions = multipleStopPositions; -} - - -double -NBPTStop::getLength() const { - return myPTStopLength; -} - - -bool -NBPTStop::setEdgeId(std::string edgeId, const NBEdgeCont& ec) { - myEdgeId = edgeId; - return findLaneAndComputeBusStopExtent(ec); -} - - -void -NBPTStop::registerAdditionalEdge(std::string wayId, std::string edgeId) { - myAdditionalEdgeCandidates[wayId] = edgeId; -} - - -const std::map& -NBPTStop::getMyAdditionalEdgeCandidates() const { - return myAdditionalEdgeCandidates; -} - - -void -NBPTStop::setMyOrigEdgeId(const std::string& myOrigEdgeId) { - NBPTStop::myOrigEdgeId = myOrigEdgeId; -} - - -void -NBPTStop::setMyPTStopLength(double myPTStopLength) { - NBPTStop::myPTStopLength = myPTStopLength; -} - -bool -NBPTStop::findLaneAndComputeBusStopExtent(const NBEdgeCont& ec) { - NBEdge* edge = ec.getByID(myEdgeId); - return findLaneAndComputeBusStopExtent(edge); -} - -bool -NBPTStop::findLaneAndComputeBusStopExtent(const NBEdge* edge) { - if (edge != nullptr) { - myEdgeId = edge->getID(); - int laneNr = -1; - for (const auto& it : edge->getLanes()) { - if ((it.permissions & getPermissions()) == getPermissions()) { - ++laneNr; - break; - } - laneNr++; - } - if (laneNr != -1) { - myLaneId = edge->getLaneID(laneNr); - const PositionVector& shape = edge->getLaneShape(laneNr); - double offset = shape.nearest_offset_to_point2D(getPosition(), false); - offset = offset * edge->getLoadedLength() / edge->getLength(); - computeExtent(offset, edge->getLoadedLength()); - return true; - } - } - return myEdgeId == ""; // loose stop. Try later when processing lines -} - - -void -NBPTStop::setMyPTStopId(std::string id) { - myPTStopId = id; -} - -void -NBPTStop::clearAccess() { - myAccesses.clear(); -} - -void -NBPTStop::addAccess(std::string laneID, double offset, double length) { - const std::string newEdgeID = SUMOXMLDefinitions::getEdgeIDFromLane(laneID); - // avoid duplicate access - for (auto it = myAccesses.begin(); it != myAccesses.end();) { - if (SUMOXMLDefinitions::getEdgeIDFromLane(std::get<0>(*it)) == newEdgeID) { - it = myAccesses.erase(it); - } else { - it++; - } - } - myAccesses.push_back(std::make_tuple(laneID, offset, length)); -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netbuild/NBPTStop.h b/Util/OSM2ODR/src/netbuild/NBPTStop.h deleted file mode 100644 index c6ec54be0..000000000 --- a/Util/OSM2ODR/src/netbuild/NBPTStop.h +++ /dev/null @@ -1,146 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NBPTStop.h -/// @author Gregor Laemmel -/// @date Tue, 20 Mar 2017 -/// -// The representation of a single pt stop -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include "utils/common/SUMOVehicleClass.h" -#include "NBPTPlatform.h" - - -// =========================================================================== -// class declarations -// =========================================================================== -class OutputDevice; -class NBEdgeCont; -class NBEdge; - - -// =========================================================================== -// class definitions -// =========================================================================== -/** -* @class NBPTStop -* @brief The representation of a single pt stop -*/ -class NBPTStop { - -public: - /**@brief Constructor - * @param[in] id The id of the pt stop - * @param[in] position The position of the pt stop - * @param[in] edgeId The edge id of the pt stop - * @param[in] length The length of the pt stop - */ - NBPTStop(std::string ptStopId, Position position, std::string edgeId, std::string origEdgeId, double length, std::string name, - SVCPermissions svcPermissions, double parkingLength = 0); - std::string getID() const; - - const std::string getEdgeId() const; - const std::string getOrigEdgeId() const; - const std::string getName() const; - const Position& getPosition() const; - SVCPermissions getPermissions() const; - void write(OutputDevice& device); - void reshiftPosition(const double offsetX, const double offsetY); - - const std::vector& getPlatformCands(); - bool getIsMultipleStopPositions() const; - void setIsMultipleStopPositions(bool multipleStopPositions); - double getLength() const; - bool setEdgeId(std::string edgeId, const NBEdgeCont& ec); - void registerAdditionalEdge(std::string wayId, std::string edgeId); - void addPlatformCand(NBPTPlatform platform); - bool findLaneAndComputeBusStopExtent(const NBEdgeCont& ec); - - bool findLaneAndComputeBusStopExtent(const NBEdge* edge); - - void setMyPTStopId(std::string id); - void addAccess(std::string laneID, double offset, double length); - - /// @brief remove all access definitions - void clearAccess(); - - /// @brief register line that services this stop (for displaying) - void addLine(const std::string& line); - - void setBidiStop(NBPTStop* bidiStop) { - myBidiStop = bidiStop; - } - - NBPTStop* getBidiStop() const { - return myBidiStop; - } - - bool isLoose() const { - return myIsLoose; - } - - /// @brief mirror coordinates along the x-axis - void mirrorX(); - -private: - void computeExtent(double center, double d); - -private: - std::string myPTStopId; - Position myPosition; - std::string myEdgeId; - std::map myAdditionalEdgeCandidates; -public: - const std::map& getMyAdditionalEdgeCandidates() const; -private: - std::string myOrigEdgeId; -public: - void setMyOrigEdgeId(const std::string& myOrigEdgeId); -private: - double myPTStopLength; -public: - void setMyPTStopLength(double myPTStopLength); -private: - const std::string myName; - const double myParkingLength; - std::string myLaneId; - const SVCPermissions myPermissions; - - double myStartPos; - double myEndPos; - - /// @brief laneId, lanePos, accessLength - std::vector> myAccesses; - - /// @brief list of public transport lines (for displaying) - std::vector myLines; - - NBPTStop* myBidiStop; - - /// @brief whether the stop was not part of the road network and must be mapped - bool myIsLoose; - -private: - /// @brief Invalidated assignment operator. - NBPTStop& operator=(const NBPTStop&); - - - std::vector myPlatformCands; - bool myIsMultipleStopPositions; -}; - diff --git a/Util/OSM2ODR/src/netbuild/NBPTStopCont.cpp b/Util/OSM2ODR/src/netbuild/NBPTStopCont.cpp deleted file mode 100644 index 63df5365f..000000000 --- a/Util/OSM2ODR/src/netbuild/NBPTStopCont.cpp +++ /dev/null @@ -1,428 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NBPTStopCont.cpp -/// @author Gregor Laemmel -/// @date Tue, 20 Mar 2017 -/// -// Container for pt stops during the netbuilding process -/****************************************************************************/ - - -#include -#include -#include -#include -#include "NBPTStopCont.h" -#include "NBEdgeCont.h" -#include "NBEdge.h" -#include "NBNode.h" -#include - - -NBPTStopCont::~NBPTStopCont() { - for (auto& myPTStop : myPTStops) { - delete myPTStop.second; - } - myPTStops.clear(); -} - - -bool -NBPTStopCont::insert(NBPTStop* ptStop) { - std::string id = ptStop->getID(); - auto i = myPTStops.find(id); - if (i != myPTStops.end()) { - return false; - } - myPTStops[id] = ptStop; - return true; -} - - -NBPTStop* -NBPTStopCont::get(std::string id) { - if (myPTStops.find(id) != myPTStops.end()) { - return myPTStops.find(id)->second; - } - return nullptr; -} - - -void -NBPTStopCont::localizePTStops(NBEdgeCont& cont) { - std::vector reverseStops; - //first pass localize pt stop at correct side of the street; create stop for opposite side if needed - for (auto& myPTStop : myPTStops) { - - NBPTStop* stop = myPTStop.second; - - bool multipleStopPositions = stop->getIsMultipleStopPositions(); - bool platformsDefined = !stop->getPlatformCands().empty(); - if (!platformsDefined) { - //create pt stop for reverse edge if edge exists - NBPTStop* reverseStop = getReverseStop(stop, cont); - if (reverseStop != nullptr) { - reverseStops.push_back(reverseStop); - } - } else if (multipleStopPositions) { - //create pt stop for closest platform at corresponding edge - assignPTStopToEdgeOfClosestPlatform(stop, cont); - - } else { - //create pt stop for each side of the street where a platform is defined (create additional pt stop as needed) - NBPTStop* additionalStop = assignAndCreatNewPTStopAsNeeded(stop, cont); - if (additionalStop != nullptr) { - reverseStops.push_back(additionalStop); - } - } - } - - //insrt new stops if any - for (auto& reverseStop : reverseStops) { - insert(reverseStop); - } -} - - -void NBPTStopCont::assignLanes(NBEdgeCont& cont) { - //scnd pass set correct lane - for (auto i = myPTStops.begin(); i != myPTStops.end();) { - NBPTStop* stop = i->second; - - if (!stop->findLaneAndComputeBusStopExtent(cont)) { - WRITE_WARNING("Could not find corresponding edge or compatible lane for pt stop '" + i->first - + "' (" + i->second->getName() + "). Thus, it will be removed!"); - EdgeVector edgeVector = cont.getGeneratedFrom((*i).second->getOrigEdgeId()); - //std::cout << edgeVector.size() << std::endl; - myPTStops.erase(i++); - } else { - i++; - } - } -} - - -int -NBPTStopCont::generateBidiStops(NBEdgeCont& ec) { - //scnd pass set correct lane - std::vector toAdd; - for (auto i = myPTStops.begin(); i != myPTStops.end(); i++) { - NBPTStop* stop = i->second; - NBEdge* edge = ec.getByID(stop->getEdgeId()); - if (edge != nullptr && edge->isBidiRail()) { - NBEdge* bidiEdge = edge->getTurnDestination(true); - assert(bidiEdge != 0); - const std::string id = getReverseID(stop->getID()); - if (myPTStops.count(id) > 0) { - if (myPTStops[id]->getEdgeId() != bidiEdge->getID()) { - WRITE_WARNING("Could not create reverse-direction stop for superposed edge '" + bidiEdge->getID() - + "' (origStop '" + i->first + "'). Stop id '" + id - + "' already in use by stop on edge '" + myPTStops[id]->getEdgeId() + "'."); - } - continue; - } - NBPTStop* bidiStop = new NBPTStop(id, - stop->getPosition(), - bidiEdge->getID(), - stop->getOrigEdgeId(), - stop->getLength(), - stop->getName(), - stop->getPermissions()); - if (bidiStop->findLaneAndComputeBusStopExtent(ec)) { - toAdd.push_back(bidiStop); - stop->setBidiStop(bidiStop); - bidiStop->setBidiStop(stop); - } else { - // should not happen - assert(false); - } - } - } - for (NBPTStop* newStop : toAdd) { - myPTStops[newStop->getID()] = newStop; - } - if (toAdd.size() > 0) { - WRITE_MESSAGE("Added " + toString(toAdd.size()) + " stops for superposed rail edges."); - } - return (int)toAdd.size(); -} - - -NBPTStop* -NBPTStopCont::getReverseStop(NBPTStop* pStop, NBEdgeCont& cont) { - std::string edgeId = pStop->getEdgeId(); - NBEdge* edge = cont.getByID(edgeId); - NBEdge* reverse = NBPTStopCont::getReverseEdge(edge); - if (reverse != nullptr) { - const std::string reverseID = getReverseID(pStop->getID()); - if (myPTStops.count(reverseID) == 0) { - return new NBPTStop(reverseID, pStop->getPosition(), reverse->getID(), reverse->getID(), - pStop->getLength(), pStop->getName(), pStop->getPermissions()); - } else { - return myPTStops[reverseID]; - } - } - return nullptr; -} - - -NBPTStop* -NBPTStopCont::assignAndCreatNewPTStopAsNeeded(NBPTStop* pStop, NBEdgeCont& cont) { - std::string edgeId = pStop->getEdgeId(); - NBEdge* edge = cont.getByID(edgeId); - bool rightOfEdge = false; - bool leftOfEdge = false; - const NBPTPlatform* left = nullptr; - for (const NBPTPlatform& platform : pStop->getPlatformCands()) { - double crossProd = computeCrossProductEdgePosition(edge, platform.getPos()); - //TODO consider driving on the left!!! [GL May '17] - if (crossProd > 0) { - leftOfEdge = true; - left = &platform; - } else { - rightOfEdge = true; - pStop->setMyPTStopLength(platform.getLength()); - } - } - - if (leftOfEdge && rightOfEdge) { - NBPTStop* leftStop = getReverseStop(pStop, cont); - leftStop->setMyPTStopLength(left->getLength()); - return leftStop; - } else if (leftOfEdge) { - NBEdge* reverse = getReverseEdge(edge); - if (reverse != nullptr) { - pStop->setEdgeId(reverse->getID(), cont); - pStop->setMyPTStopLength(left->getLength()); - } - } - - return nullptr; -} - - -void -NBPTStopCont::assignPTStopToEdgeOfClosestPlatform(NBPTStop* pStop, NBEdgeCont& cont) { - std::string edgeId = pStop->getEdgeId(); - NBEdge* edge = cont.getByID(edgeId); - NBEdge* reverse = NBPTStopCont::getReverseEdge(edge); - const NBPTPlatform* closestPlatform = getClosestPlatformToPTStopPosition(pStop); - pStop->setMyPTStopLength(closestPlatform->getLength()); - if (reverse != nullptr) { - - //TODO make isLeft in PositionVector static [GL May '17] -// if (PositionVector::isLeft(edge->getFromNode()->getPosition(),edge->getToNode()->getPosition(),closestPlatform)){ -// -// } - double crossProd = computeCrossProductEdgePosition(edge, closestPlatform->getPos()); - - //TODO consider driving on the left!!! [GL May '17] - if (crossProd > 0) { //pt stop is on the left of the orig edge - pStop->setEdgeId(reverse->getID(), cont); - } - } -} - - -double -NBPTStopCont::computeCrossProductEdgePosition(const NBEdge* edge, const Position& closestPlatform) const { - PositionVector geom = edge->getGeometry(); - int idxTmp = geom.indexOfClosest(closestPlatform); - double offset = geom.nearest_offset_to_point2D(closestPlatform, true); - double offset2 = geom.offsetAtIndex2D(idxTmp); - int idx1, idx2; - if (offset2 < offset) { - idx1 = idxTmp; - idx2 = idx1 + 1; - } else { - idx2 = idxTmp; - idx1 = idxTmp - 1; - } - if (idx1 < 0 || idx1 >= (int) geom.size() || idx2 < 0 || idx2 >= (int) geom.size()) { - WRITE_WARNING("Could not determine cross product"); - return 0; - } - Position p1 = geom[idx1]; - Position p2 = geom[idx2]; - - double x0 = p1.x(); - double y0 = p1.y(); - double x1 = p2.x(); - double y1 = p2.y(); - double x2 = closestPlatform.x(); - double y2 = closestPlatform.y(); - double crossProd = (x1 - x0) * (y2 - y0) - (y1 - y0) * (x2 - x0); - return crossProd; -} - - -const NBPTPlatform* -NBPTStopCont::getClosestPlatformToPTStopPosition(NBPTStop* pStop) { - Position stopPosition = pStop->getPosition(); - const NBPTPlatform* closest = nullptr; - double minSqrDist = std::numeric_limits::max(); - for (const NBPTPlatform& platform : pStop->getPlatformCands()) { - double sqrDist = stopPosition.distanceSquaredTo2D(platform.getPos()); - if (sqrDist < minSqrDist) { - minSqrDist = sqrDist; - closest = &platform; - } - } - return closest; -} - -//static functions - -NBEdge* -NBPTStopCont::getReverseEdge(NBEdge* edge) { - if (edge != nullptr) { - for (auto it = edge->getToNode()->getOutgoingEdges().begin(); - it != edge->getToNode()->getOutgoingEdges().end(); - it++) { - if ((*it)->getToNode() == edge->getFromNode()) { - return (*it); - } - } - } - return nullptr; -} - - -int -NBPTStopCont::cleanupDeleted(NBEdgeCont& cont) { - int numDeleted = 0; - for (auto i = myPTStops.begin(); i != myPTStops.end();) { - if (cont.getByID((*i).second->getEdgeId()) == nullptr) { - WRITE_WARNING("Removing pt stop:" + (*i).first + " on non existing edge: " + (*i).second->getEdgeId()); - myPTStops.erase(i++); - numDeleted++; - } else { - i++; - } - } - return numDeleted; -} - - -void -NBPTStopCont::addEdges2Keep(const OptionsCont& oc, std::set& into) { - if (oc.isSet("ptstop-output")) { - for (auto stop : myPTStops) { - into.insert(stop.second->getEdgeId()); - } - } -} - - -void -NBPTStopCont::postprocess(std::set& usedStops) { - for (auto i = myPTStops.begin(); i != myPTStops.end();) { - if (usedStops.find(i->second->getID()) == usedStops.end()) { - myPTStops.erase(i++); - } else { - i++; - } - } -} - -std::string -NBPTStopCont::getReverseID(const std::string& id) { - return id.size() > 0 && id[0] == '-' ? id.substr(1) : "-" + id; -} - -void -NBPTStopCont::alignIdSigns() { - PTStopsCont stops = myPTStops; - for (auto& i : stops) { - const std::string& stopId = i.second->getID(); - if (i.second->getEdgeId() == "") { - continue; - } - const char edgeSign = i.second->getEdgeId().at(0); - const char stopSign = stopId.at(0); - if (edgeSign != stopSign && (edgeSign == '-' || stopSign == '-')) { - i.second->setMyPTStopId(getReverseID(stopId)); - myPTStops.erase(stopId); - myPTStops[i.second->getID()] = i.second; - } - } -} - - -void -NBPTStopCont::findAccessEdgesForRailStops(NBEdgeCont& cont, double maxRadius, int maxCount, double accessFactor) { - NamedRTree r; - for (auto edge : cont) { - const Boundary& bound = edge.second->getGeometry().getBoxBoundary(); - float min[2] = { static_cast(bound.xmin()), static_cast(bound.ymin()) }; - float max[2] = { static_cast(bound.xmax()), static_cast(bound.ymax()) }; - r.Insert(min, max, edge.second); - } - for (auto& ptStop : myPTStops) { - const std::string& stopEdgeID = ptStop.second->getEdgeId(); - NBEdge* stopEdge = cont.getByID(stopEdgeID); - //std::cout << "findAccessEdgesForRailStops edge=" << stopEdgeID << " exists=" << (stopEdge != 0) << "\n"; - if (stopEdge != nullptr && (stopEdge->getPermissions() & SVC_PEDESTRIAN) == 0) { - //if (stopEdge != 0 && isRailway(stopEdge->getPermissions())) { - std::set edges; - Named::StoringVisitor visitor(edges); - const Position& pos = ptStop.second->getPosition(); - float min[2] = {static_cast(pos.x() - maxRadius), static_cast(pos.y() - maxRadius)}; - float max[2] = {static_cast(pos.x() + maxRadius), static_cast(pos.y() + maxRadius)}; - r.Search(min, max, visitor); - std::vector edgCants; - for (const Named* namedEdge : edges) { - NBEdge* e = const_cast(dynamic_cast(namedEdge)); - edgCants.push_back(e); - } - std::sort(edgCants.begin(), edgCants.end(), [pos](NBEdge * a, NBEdge * b) { - return a->getLaneShape(0).distance2D(pos, false) < b->getLaneShape(0).distance2D(pos, false); - }); - int cnt = 0; - for (auto edge : edgCants) { - int laneIdx = 0; - for (auto lane : edge->getLanes()) { - if ((lane.permissions & SVC_PEDESTRIAN) != 0) { - double offset = lane.shape.nearest_offset_to_point2D(pos, false); - double finalLength = edge->getFinalLength(); - double laneLength = lane.shape.length(); - double accessLength = pos.distanceTo2D(lane.shape.positionAtOffset2D(offset)) * accessFactor; - ptStop.second->addAccess(edge->getLaneID(laneIdx), offset * finalLength / laneLength, accessLength); - cnt++; - break; - } - laneIdx++; - } - if (cnt == maxCount) { - break; - } - } - } - } -} - - -NBPTStop* -NBPTStopCont::findStop(const std::string& origEdgeID, Position pos, double threshold) const { - for (auto& item : myPTStops) { - if (item.second->getOrigEdgeId() == origEdgeID && - item.second->getPosition().distanceTo2D(pos) < threshold) { - return item.second; - } - } - return nullptr; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netbuild/NBPTStopCont.h b/Util/OSM2ODR/src/netbuild/NBPTStopCont.h deleted file mode 100644 index a74748086..000000000 --- a/Util/OSM2ODR/src/netbuild/NBPTStopCont.h +++ /dev/null @@ -1,114 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NBPTStopCont.h -/// @author Gregor Laemmel -/// @date Tue, 20 Mar 2017 -/// -// Container for pt stops during the netbuilding process -/****************************************************************************/ - -#pragma once - -#include -#include -#include "NBPTStop.h" - -class NBEdge; -class NBEdgeCont; - -class NBPTStopCont { - -public: - - ~NBPTStopCont(); - - /** @brief Inserts a node into the map - * @param[in] stop The pt stop to insert - * @return Whether the pt stop could be added - */ - bool insert(NBPTStop* ptStop); - - /// @brief Retrieve a previously inserted pt stop - NBPTStop* get(std::string id); - - /// @brief Returns the number of pt stops stored in this container - int size() const { - return (int) myPTStops.size(); - } - - /** @brief Returns the pointer to the begin of the stored pt stops - * @return The iterator to the beginning of stored pt stops - */ - std::map::const_iterator begin() const { - return myPTStops.begin(); - } - - /** @brief Returns the pointer to the end of the stored pt stops - * @return The iterator to the end of stored pt stops - */ - std::map::const_iterator end() const { - return myPTStops.end(); - } - - const std::map& getStops() const { - return myPTStops; - } - - - /** @brief remove stops on non existing (removed) edges - * - * @param cont - */ - int cleanupDeleted(NBEdgeCont& cont); - - void assignLanes(NBEdgeCont& cont); - - /// @brief duplicate stops for superposed rail edges and return the number of generated stops - int generateBidiStops(NBEdgeCont& cont); - - void localizePTStops(NBEdgeCont& cont); - - void findAccessEdgesForRailStops(NBEdgeCont& cont, double maxRadius, int maxCount, double accessFactor); - - void postprocess(std::set& usedStops); - - /// @brief add edges that must be kept - void addEdges2Keep(const OptionsCont& oc, std::set& into); - - NBPTStop* findStop(const std::string& origEdgeID, Position pos, double threshold = 1) const; - -private: - /// @brief Definition of the map of names to pt stops - typedef std::map PTStopsCont; - - /// @brief The map of names to pt stops - PTStopsCont myPTStops; - - NBPTStop* getReverseStop(NBPTStop* pStop, NBEdgeCont& cont); - - - void assignPTStopToEdgeOfClosestPlatform(NBPTStop* pStop, NBEdgeCont& cont); - const NBPTPlatform* getClosestPlatformToPTStopPosition(NBPTStop* pStop); - NBPTStop* assignAndCreatNewPTStopAsNeeded(NBPTStop* pStop, NBEdgeCont& cont); - double computeCrossProductEdgePosition(const NBEdge* edge, const Position& closestPlatform) const; - - static std::string getReverseID(const std::string& id); - -public: - static NBEdge* getReverseEdge(NBEdge* edge); - - - void alignIdSigns(); -}; - diff --git a/Util/OSM2ODR/src/netbuild/NBParking.cpp b/Util/OSM2ODR/src/netbuild/NBParking.cpp deleted file mode 100644 index 4316508ba..000000000 --- a/Util/OSM2ODR/src/netbuild/NBParking.cpp +++ /dev/null @@ -1,84 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NBParking.cpp -/// @author Jakob Erdmann -/// @date Tue, 14 Nov 2017 -/// -// The representation of an imported parking area -/****************************************************************************/ -#include - -#include -#include -#include -#include "NBParking.h" -#include "NBEdge.h" -#include "NBEdgeCont.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -NBParking::NBParking(const std::string& id, const std::string& edgeID, const std::string& name) : - Named(id), - myEdgeID(edgeID), - myName(name) { -} - -void -NBParking::write(OutputDevice& device, NBEdgeCont& ec) const { - const NBEdge* e = ec.retrieve(myEdgeID); - if (e != nullptr) { - if ((e->getPermissions() & SVC_PASSENGER) == 0) { - WRITE_WARNINGF("Ignoring parking area on edge '%' due to invalid permissions.", e->getID()); - return; - } - // keep minimum distance of 5m to junction corners - const int cornerDistance = 5; - int capacity = (int)((e->getFinalLength() - 2 * cornerDistance) / 7.5); - if (capacity <= 0) { - WRITE_WARNINGF("Ignoring parking area on edge '%' due to insufficient space.", e->getID()); - return; - } - int lane = 0; - for (; lane < e->getNumLanes(); ++lane) { - if ((e->getPermissions(lane) & SVC_PASSENGER) != 0) { - break; - } - } - device.openTag(SUMO_TAG_PARKING_AREA); - device.writeAttr(SUMO_ATTR_ID, getID()); - device.writeAttr(SUMO_ATTR_LANE, e->getLaneID(lane)); - device.writeAttr(SUMO_ATTR_STARTPOS, cornerDistance); - device.writeAttr(SUMO_ATTR_ENDPOS, -cornerDistance); - device.writeAttr(SUMO_ATTR_ROADSIDE_CAPACITY, capacity); - if (!myName.empty()) { - device.writeAttr(SUMO_ATTR_NAME, myName); - } - device.closeTag(); - } else { - WRITE_WARNINGF("could not find edge for parkingArea '%s'", getID()); - } - // XXX else: prevent edge merging via --geometry.remove -} - - -void -NBParkingCont::addEdges2Keep(const OptionsCont& oc, std::set& into) { - if (oc.isSet("parking-output")) { - for (NBParking& p : *this) { - into.insert(p.getEdgeID()); - } - } -} diff --git a/Util/OSM2ODR/src/netbuild/NBParking.h b/Util/OSM2ODR/src/netbuild/NBParking.h deleted file mode 100644 index 2e1703f2e..000000000 --- a/Util/OSM2ODR/src/netbuild/NBParking.h +++ /dev/null @@ -1,71 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NBParking.h -/// @author Jakob Erdmann -/// @date Tue, 14 Nov 2017 -/// -// The representation of an imported parking area -/****************************************************************************/ -#pragma once -#include - -#include -#include "utils/common/Named.h" - - -// =========================================================================== -// class declarations -// =========================================================================== -class OutputDevice; -class NBEdgeCont; -class OptionsCont; - - -// =========================================================================== -// class definitions -// =========================================================================== -/** -* @class NBParking -* @brief The representation of a single pt stop -*/ -class NBParking : public Named { - -public: - /**@brief Constructor - * @param[in] id The id of the pt stop - * @param[in] position The position of the pt stop - * @param[in] edgeId The edge id of the pt stop - * @param[in] length The length of the pt stop - */ - NBParking(const std::string& id, const std::string& edgeID, const std::string& name = ""); - - void write(OutputDevice& device, NBEdgeCont& ec) const; - - const std::string getEdgeID() const { - return myEdgeID; - } - -private: - std::string myEdgeID; - std::string myName; - -}; - -class NBParkingCont : public std::vector { - -public: - /// @brief add edges that must be kept - void addEdges2Keep(const OptionsCont& oc, std::set& into); -}; - diff --git a/Util/OSM2ODR/src/netbuild/NBRequest.cpp b/Util/OSM2ODR/src/netbuild/NBRequest.cpp deleted file mode 100644 index 5a8ef4cc9..000000000 --- a/Util/OSM2ODR/src/netbuild/NBRequest.cpp +++ /dev/null @@ -1,1080 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NBRequest.cpp -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @author Laura Bieker -/// @date Tue, 20 Nov 2001 -/// -// This class computes the logic of a junction -/****************************************************************************/ -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "NBEdge.h" -#include "NBContHelper.h" -#include "NBNode.h" -#include "NBRequest.h" - -//#define DEBUG_RESPONSE -//#define DEBUG_SETBLOCKING -#define DEBUGCOND (myJunction->getID() == "F") - -// =========================================================================== -// static member variables -// =========================================================================== -int NBRequest::myGoodBuilds = 0; -int NBRequest::myNotBuild = 0; - - -// =========================================================================== -// method definitions -// =========================================================================== -NBRequest::NBRequest(const NBEdgeCont& ec, - NBNode* junction, - const EdgeVector& all, - const EdgeVector& incoming, - const EdgeVector& outgoing, - const NBConnectionProhibits& loadedProhibits) : - myJunction(junction), - myAll(all), - myIncoming(incoming), - myOutgoing(outgoing) { - const int variations = numLinks(); - // build maps with information which forbidding connection were - // computed and what's in there - myForbids.reserve(variations); - myDone.reserve(variations); - for (int i = 0; i < variations; i++) { - myForbids.push_back(LinkInfoCont(variations, false)); - myDone.push_back(LinkInfoCont(variations, false)); - } - // insert loaded prohibits - for (NBConnectionProhibits::const_iterator j = loadedProhibits.begin(); j != loadedProhibits.end(); j++) { - NBConnection prohibited = (*j).first; - bool ok1 = prohibited.check(ec); - if (find(myIncoming.begin(), myIncoming.end(), prohibited.getFrom()) == myIncoming.end()) { - ok1 = false; - } - if (find(myOutgoing.begin(), myOutgoing.end(), prohibited.getTo()) == myOutgoing.end()) { - ok1 = false; - } - int idx1 = 0; - if (ok1) { - idx1 = getIndex(prohibited.getFrom(), prohibited.getTo()); - if (idx1 < 0) { - ok1 = false; - } - } - const NBConnectionVector& prohibiting = (*j).second; - for (NBConnectionVector::const_iterator k = prohibiting.begin(); k != prohibiting.end(); k++) { - NBConnection sprohibiting = *k; - bool ok2 = sprohibiting.check(ec); - if (find(myIncoming.begin(), myIncoming.end(), sprohibiting.getFrom()) == myIncoming.end()) { - ok2 = false; - } - if (find(myOutgoing.begin(), myOutgoing.end(), sprohibiting.getTo()) == myOutgoing.end()) { - ok2 = false; - } - if (ok1 && ok2) { - int idx2 = getIndex(sprohibiting.getFrom(), sprohibiting.getTo()); - if (idx2 < 0) { - ok2 = false; - } else { - myForbids[idx2][idx1] = true; - myDone[idx2][idx1] = true; - myDone[idx1][idx2] = true; - myGoodBuilds++; - } - } else { - std::string pfID = prohibited.getFrom() != nullptr ? prohibited.getFrom()->getID() : "UNKNOWN"; - std::string ptID = prohibited.getTo() != nullptr ? prohibited.getTo()->getID() : "UNKNOWN"; - std::string bfID = sprohibiting.getFrom() != nullptr ? sprohibiting.getFrom()->getID() : "UNKNOWN"; - std::string btID = sprohibiting.getTo() != nullptr ? sprohibiting.getTo()->getID() : "UNKNOWN"; - WRITE_WARNING("could not prohibit " + pfID + "->" + ptID + " by " + bfID + "->" + btID); - myNotBuild++; - } - } - } - // ok, check whether someone has prohibited two links vice versa - // (this happens also in some Vissim-networks, when edges are joined) - for (int s1 = 0; s1 < variations; s1++) { - for (int s2 = s1 + 1; s2 < variations; s2++) { - // not set, yet - if (!myDone[s1][s2]) { - continue; - } - // check whether both prohibit vice versa - if (myForbids[s1][s2] && myForbids[s2][s1]) { - // mark unset - let our algorithm fix it later - myDone[s1][s2] = false; - myDone[s2][s1] = false; - } - } - } -} - - -NBRequest::~NBRequest() {} - - -void -NBRequest::buildBitfieldLogic() { - EdgeVector::const_iterator i, j; - for (i = myIncoming.begin(); i != myIncoming.end(); i++) { - for (j = myOutgoing.begin(); j != myOutgoing.end(); j++) { - computeRightOutgoingLinkCrossings(*i, *j); - computeLeftOutgoingLinkCrossings(*i, *j); - } - } - // reset signalised/non-signalised dependencies - resetSignalised(); - // reset foes it the number of lanes matches (or exceeds) the number of incoming connections - resetCooperating(); -} - - -void -NBRequest::computeRightOutgoingLinkCrossings(NBEdge* from, NBEdge* to) { - EdgeVector::const_iterator pfrom = std::find(myAll.begin(), myAll.end(), from); - while (*pfrom != to) { - NBContHelper::nextCCW(myAll, pfrom); - if ((*pfrom)->getToNode() == myJunction) { - EdgeVector::const_iterator pto = std::find(myAll.begin(), myAll.end(), to); - while (*pto != from) { - if (!((*pto)->getToNode() == myJunction)) { - setBlocking(from, to, *pfrom, *pto); - } - NBContHelper::nextCCW(myAll, pto); - } - } - } -} - - -void -NBRequest::computeLeftOutgoingLinkCrossings(NBEdge* from, NBEdge* to) { - EdgeVector::const_iterator pfrom = std::find(myAll.begin(), myAll.end(), from); - while (*pfrom != to) { - NBContHelper::nextCW(myAll, pfrom); - if ((*pfrom)->getToNode() == myJunction) { - EdgeVector::const_iterator pto = std::find(myAll.begin(), myAll.end(), to); - while (*pto != from) { - if (!((*pto)->getToNode() == myJunction)) { - setBlocking(from, to, *pfrom, *pto); - } - NBContHelper::nextCW(myAll, pto); - } - } - } -} - - -void -NBRequest::setBlocking(NBEdge* from1, NBEdge* to1, - NBEdge* from2, NBEdge* to2) { - // check whether one of the links has a dead end - if (to1 == nullptr || to2 == nullptr) { - return; - } - // get the indices of both links - int idx1 = getIndex(from1, to1); - int idx2 = getIndex(from2, to2); - if (idx1 < 0 || idx2 < 0) { - return; // !!! error output? did not happend, yet - } - // check whether the link crossing has already been checked - assert(idx1 < (int)(myIncoming.size() * myOutgoing.size())); - if (myDone[idx1][idx2]) { - return; - } - // mark the crossings as done - myDone[idx1][idx2] = true; - myDone[idx2][idx1] = true; - // special case all-way stop - if (myJunction->getType() == SumoXMLNodeType::ALLWAY_STOP) { - // all ways forbid each other. Conflict resolution happens via arrival time - myForbids[idx1][idx2] = true; - myForbids[idx2][idx1] = true; - return; - } - // check if one of the links is a turn; this link is always not priorised - // true for right-before-left and priority - if (from1->isTurningDirectionAt(to1)) { - myForbids[idx2][idx1] = true; - return; - } - if (from2->isTurningDirectionAt(to2)) { - myForbids[idx1][idx2] = true; - return; - } - // if there are no connections, there are no prohibitions - if (from1->isConnectedTo(to1)) { - if (!from2->isConnectedTo(to2)) { - myForbids[idx1][idx2] = true; - myForbids[idx2][idx1] = false; - return; - } - } else { - if (!from2->isConnectedTo(to2)) { - myForbids[idx1][idx2] = false; - myForbids[idx2][idx1] = false; - return; - } else { - myForbids[idx1][idx2] = false; - myForbids[idx2][idx1] = true; - return; - } - } -#ifdef DEBUG_SETBLOCKING - if (DEBUGCOND) std::cout << "setBlocking" - << " 1:" << from1->getID() << "->" << to1->getID() - << " 2:" << from2->getID() << "->" << to2->getID() << "\n"; -#endif - // check the priorities if required by node type - if (myJunction->getType() != SumoXMLNodeType::RIGHT_BEFORE_LEFT) { - int from1p = from1->getJunctionPriority(myJunction); - int from2p = from2->getJunctionPriority(myJunction); -#ifdef DEBUG_SETBLOCKING - if (DEBUGCOND) std::cout << "setBlocking" - << " 1:" << from1->getID() << "->" << to1->getID() - << " 2:" << from2->getID() << "->" << to2->getID() - << " p1=" << from1p << " p2=" << from2p << "\n"; -#endif - // check if one of the connections is higher priorised when incoming into - // the junction, the connection road will yield - if (from1p > from2p) { - myForbids[idx1][idx2] = true; - return; - } - if (from2p > from1p) { - myForbids[idx2][idx1] = true; - return; - } - } - // straight connections prohibit turning connections if the priorities are equal - // (unless the junction is a bent priority junction) - if (myJunction->getType() != SumoXMLNodeType::RIGHT_BEFORE_LEFT && !myJunction->isBentPriority()) { - LinkDirection ld1 = myJunction->getDirection(from1, to1); - LinkDirection ld2 = myJunction->getDirection(from2, to2); -#ifdef DEBUG_SETBLOCKING - if (DEBUGCOND) std::cout << "setBlocking" - << " 1:" << from1->getID() << "->" << to1->getID() - << " 2:" << from2->getID() << "->" << to2->getID() - << " dir1=" << toString(ld1) << " dir2=" << toString(ld2) << "\n"; -#endif - if (ld1 == LinkDirection::STRAIGHT) { - if (ld2 != LinkDirection::STRAIGHT) { - myForbids[idx1][idx2] = true; - myForbids[idx2][idx1] = false; - return; - } - } else { - if (ld2 == LinkDirection::STRAIGHT) { - myForbids[idx1][idx2] = false; - myForbids[idx2][idx1] = true; - return; - } - } - } - - // check whether one of the connections is higher priorised on - // the outgoing edge when both roads are high priorised - // the connection with the lower priorised outgoing edge will lead - // should be valid for priority junctions only - /* - if (from1p > 0 && from2p > 0) { - assert(myJunction->getType() != SumoXMLNodeType::RIGHT_BEFORE_LEFT); - int to1p = to1->getJunctionPriority(myJunction); - int to2p = to2->getJunctionPriority(myJunction); - if (to1p > to2p) { - myForbids[idx1][idx2] = true; - return; - } - if (to2p > to1p) { - myForbids[idx2][idx1] = true; - return; - } - } - */ - - // compute the yielding due to the right-before-left rule - // get the position of the incoming lanes in the junction-wheel - EdgeVector::const_iterator c1 = std::find(myAll.begin(), myAll.end(), from1); - NBContHelper::nextCW(myAll, c1); - // go through next edges clockwise... - while (*c1 != from1 && *c1 != from2) { - if (*c1 == to2) { - // if we encounter to2 the second one prohibits the first - myForbids[idx2][idx1] = true; - return; - } - NBContHelper::nextCW(myAll, c1); - } - // get the position of the incoming lanes in the junction-wheel - EdgeVector::const_iterator c2 = std::find(myAll.begin(), myAll.end(), from2); - NBContHelper::nextCW(myAll, c2); - // go through next edges clockwise... - while (*c2 != from2 && *c2 != from1) { - if (*c2 == to1) { - // if we encounter to1 the second one prohibits the first - myForbids[idx1][idx2] = true; - return; - } - NBContHelper::nextCW(myAll, c2); - } -#ifdef DEBUG_SETBLOCKING - if (DEBUGCOND) std::cout << "setBlocking" - << " 1:" << from1->getID() << "->" << to1->getID() - << " 2:" << from2->getID() << "->" << to2->getID() - << " noDecision\n"; -#endif -} - - -int -NBRequest::distanceCounterClockwise(NBEdge* from, NBEdge* to) { - EdgeVector::const_iterator p = std::find(myAll.begin(), myAll.end(), from); - int ret = 0; - do { - ret++; - if (p == myAll.begin()) { - p = myAll.end(); - } - p--; - } while (*p != to); - return ret; -} - -const std::string& -NBRequest::getFoes(int linkIndex) const { - assert(linkIndex >= 0); - assert(linkIndex < (int)myFoes.size()); - return myFoes[linkIndex]; -} - - -const std::string& -NBRequest::getResponse(int linkIndex) const { - assert(linkIndex >= 0); - assert(linkIndex < (int)myResponse.size()); - return myResponse[linkIndex]; -} - - -void -NBRequest::writeLogic(OutputDevice& into) const { - int numLinks = (int)myResponse.size(); - assert((int)myFoes.size() == numLinks); - assert((int)myHaveVia.size() == numLinks); - const bool padding = numLinks > 10; - for (int i = 0; i < numLinks; i++) { - into.openTag(SUMO_TAG_REQUEST); - into.writeAttr(SUMO_ATTR_INDEX, i); - if (padding && i < 10) { - into.writePadding(" "); - } - into.writeAttr(SUMO_ATTR_RESPONSE, myResponse[i]); - into.writeAttr(SUMO_ATTR_FOES, myFoes[i]); - if (!OptionsCont::getOptions().getBool("no-internal-links")) { - into.writeAttr(SUMO_ATTR_CONT, myHaveVia[i]); - } - into.closeTag(); - } -} - - -void -NBRequest::computeLogic(const bool checkLaneFoes) { - myResponse.clear(); - myFoes.clear(); - myHaveVia.clear(); - int pos = 0; - EdgeVector::const_iterator i; - // normal connections - for (i = myIncoming.begin(); i != myIncoming.end(); i++) { - int noLanes = (*i)->getNumLanes(); - for (int k = 0; k < noLanes; k++) { - pos = computeLaneResponse(*i, k, pos, checkLaneFoes || myJunction->getType() == SumoXMLNodeType::ZIPPER); - } - } - // crossings - auto crossings = myJunction->getCrossings(); - for (auto c : crossings) { - pos = computeCrossingResponse(*c, pos); - } -} - -void -NBRequest::resetSignalised() { - // go through possible prohibitions - for (EdgeVector::const_iterator i11 = myIncoming.begin(); i11 != myIncoming.end(); i11++) { - int noLanesEdge1 = (*i11)->getNumLanes(); - for (int j1 = 0; j1 < noLanesEdge1; j1++) { - std::vector el1 = (*i11)->getConnectionsFromLane(j1); - for (std::vector::iterator i12 = el1.begin(); i12 != el1.end(); ++i12) { - int idx1 = getIndex((*i11), (*i12).toEdge); - if (idx1 < 0) { - continue; - } - // go through possibly prohibited - for (EdgeVector::const_iterator i21 = myIncoming.begin(); i21 != myIncoming.end(); i21++) { - int noLanesEdge2 = (*i21)->getNumLanes(); - for (int j2 = 0; j2 < noLanesEdge2; j2++) { - std::vector el2 = (*i21)->getConnectionsFromLane(j2); - for (std::vector::iterator i22 = el2.begin(); i22 != el2.end(); i22++) { - int idx2 = getIndex((*i21), (*i22).toEdge); - if (idx2 < 0) { - continue; - } - // check - // same incoming connections do not prohibit each other - if ((*i11) == (*i21)) { - myForbids[idx1][idx2] = false; - myForbids[idx2][idx1] = false; - continue; - } - // check other - // if both are non-signalised or both are signalised - if (((*i12).tlID == "" && (*i22).tlID == "") - || - ((*i12).tlID != "" && (*i22).tlID != "")) { - // do nothing - continue; - } - // supposing, we don not have to - // brake if we are no foes - if (!foes(*i11, (*i12).toEdge, *i21, (*i22).toEdge)) { - continue; - } - // otherwise: - // the non-signalised must break - if ((*i12).tlID != "") { - myForbids[idx1][idx2] = true; - myForbids[idx2][idx1] = false; - } else { - myForbids[idx1][idx2] = false; - myForbids[idx2][idx1] = true; - } - } - } - } - } - } - } -} - - -std::pair -NBRequest::getSizes() const { - int noLanes = 0; - int noLinks = 0; - for (EdgeVector::const_iterator i = myIncoming.begin(); - i != myIncoming.end(); i++) { - int noLanesEdge = (*i)->getNumLanes(); - for (int j = 0; j < noLanesEdge; j++) { - int numConnections = (int)(*i)->getConnectionsFromLane(j).size(); - noLinks += numConnections; - if (numConnections > 0) { - noLanes++; - } - } - } - return std::make_pair(noLanes, noLinks); -} - - -bool -NBRequest::foes(const NBEdge* const from1, const NBEdge* const to1, - const NBEdge* const from2, const NBEdge* const to2) const { - // unconnected edges do not forbid other edges - if (to1 == nullptr || to2 == nullptr) { - return false; - } - // get the indices - int idx1 = getIndex(from1, to1); - int idx2 = getIndex(from2, to2); - if (idx1 < 0 || idx2 < 0) { - return false; // sure? (The connection does not exist within this junction) - } - assert(idx1 < (int)(myIncoming.size() * myOutgoing.size())); - assert(idx2 < (int)(myIncoming.size()*myOutgoing.size())); - return myForbids[idx1][idx2] || myForbids[idx2][idx1]; -} - - -bool -NBRequest::forbids(const NBEdge* const possProhibitorFrom, const NBEdge* const possProhibitorTo, - const NBEdge* const possProhibitedFrom, const NBEdge* const possProhibitedTo, - bool regardNonSignalisedLowerPriority) const { - // unconnected edges do not forbid other edges - if (possProhibitorTo == nullptr || possProhibitedTo == nullptr) { - return false; - } - // get the indices - int possProhibitorIdx = getIndex(possProhibitorFrom, possProhibitorTo); - int possProhibitedIdx = getIndex(possProhibitedFrom, possProhibitedTo); - if (possProhibitorIdx < 0 || possProhibitedIdx < 0) { - return false; // sure? (The connection does not exist within this junction) - } - assert(possProhibitorIdx < (int)(myIncoming.size() * myOutgoing.size())); - assert(possProhibitedIdx < (int)(myIncoming.size() * myOutgoing.size())); - // check simple right-of-way-rules - if (!regardNonSignalisedLowerPriority) { - return myForbids[possProhibitorIdx][possProhibitedIdx]; - } - // if its not forbidden, report - if (!myForbids[possProhibitorIdx][possProhibitedIdx]) { - return false; - } - // do not forbid a signalised stream by a non-signalised - if (!possProhibitorFrom->hasSignalisedConnectionTo(possProhibitorTo)) { - return false; - } - return true; -} - -int -NBRequest::computeLaneResponse(NBEdge* from, int fromLane, int pos, const bool checkLaneFoes) { - for (const NBEdge::Connection& c : from->getConnectionsFromLane(fromLane)) { - assert(c.toEdge != 0); - pos++; - const std::string foes = getFoesString(from, c.toEdge, fromLane, c.toLane, checkLaneFoes); - const std::string response = myJunction->getType() == SumoXMLNodeType::ZIPPER ? foes : getResponseString(from, c, checkLaneFoes); - myFoes.push_back(foes); - myResponse.push_back(response); - myHaveVia.push_back(c.haveVia); - } - return pos; -} - - -int -NBRequest::computeCrossingResponse(const NBNode::Crossing& crossing, int pos) { - std::string foes(myJunction->getCrossings().size(), '0'); - std::string response(myJunction->getCrossings().size(), '0'); - // conflicts with normal connections - for (EdgeVector::const_reverse_iterator i = myIncoming.rbegin(); i != myIncoming.rend(); i++) { - //const std::vector &allConnections = (*i)->getConnections(); - const NBEdge* from = *i; - int noLanes = from->getNumLanes(); - for (int j = noLanes; j-- > 0;) { - std::vector connected = from->getConnectionsFromLane(j); - int size = (int) connected.size(); - for (int k = size; k-- > 0;) { - const NBEdge* to = connected[k].toEdge; - bool foe = false; - for (EdgeVector::const_iterator it_e = crossing.edges.begin(); it_e != crossing.edges.end(); ++it_e) { - if ((*it_e) == from || (*it_e) == to) { - foe = true; - break; - } - } - foes += foe ? '1' : '0'; - response += mustBrakeForCrossing(myJunction, from, to, crossing) || !foe ? '0' : '1'; - } - } - } - pos++; - myResponse.push_back(response); - myFoes.push_back(foes); - myHaveVia.push_back(false); - return pos; -} - - -std::string -NBRequest::getResponseString(const NBEdge* const from, const NBEdge::Connection& c, const bool checkLaneFoes) const { - const NBEdge* const to = c.toEdge; - const int fromLane = c.fromLane; - const int toLane = c.toLane; - int idx = 0; - if (to != nullptr) { - idx = getIndex(from, to); - } - std::string result; - // crossings - auto crossings = myJunction->getCrossings(); - for (std::vector::const_reverse_iterator i = crossings.rbegin(); i != crossings.rend(); i++) { - result += mustBrakeForCrossing(myJunction, from, to, **i) ? '1' : '0'; - } - NBEdge::Connection queryCon = from->getConnection(fromLane, to, toLane); - // normal connections - for (EdgeVector::const_reverse_iterator i = myIncoming.rbegin(); i != myIncoming.rend(); i++) { - //const std::vector &allConnections = (*i)->getConnections(); - int noLanes = (*i)->getNumLanes(); - for (int j = noLanes; j-- > 0;) { - std::vector connected = (*i)->getConnectionsFromLane(j); - int size = (int) connected.size(); - for (int k = size; k-- > 0;) { - if (c.mayDefinitelyPass) { - result += '0'; - } else if ((*i) == from && fromLane == j) { - // do not prohibit a connection by others from same lane - result += '0'; - } else { - assert(connected[k].toEdge != 0); - const int idx2 = getIndex(*i, connected[k].toEdge); - assert(k < (int) connected.size()); - assert(idx < (int)(myIncoming.size() * myOutgoing.size())); - assert(idx2 < (int)(myIncoming.size() * myOutgoing.size())); - // check whether the connection is prohibited by another one -#ifdef DEBUG_RESPONSE - if (DEBUGCOND) { - std::cout << " c=" << queryCon.getDescription(from) << " prohibitC=" << connected[k].getDescription(*i) - << " f=" << myForbids[idx2][idx] - << " clf=" << checkLaneFoes - << " clfbc=" << checkLaneFoesByClass(queryCon, *i, connected[k]) - << " clfbcoop=" << checkLaneFoesByCooperation(from, queryCon, *i, connected[k]) - << " lc=" << laneConflict(from, to, toLane, *i, connected[k].toEdge, connected[k].toLane) - << " rtc=" << NBNode::rightTurnConflict(from, to, fromLane, *i, connected[k].toEdge, connected[k].fromLane) - << " rtc2=" << rightTurnConflict(from, queryCon, *i, connected[k]) - << " mc=" << mergeConflict(from, queryCon, *i, connected[k], false) - << " oltc=" << oppositeLeftTurnConflict(from, queryCon, *i, connected[k], false) - << " rorc=" << myJunction->rightOnRedConflict(c.tlLinkIndex, connected[k].tlLinkIndex) - << " tlscc=" << myJunction->tlsContConflict(from, c, *i, connected[k]) - << "\n"; - } -#endif - const bool hasLaneConflict = (!(checkLaneFoes || checkLaneFoesByClass(queryCon, *i, connected[k]) - || checkLaneFoesByCooperation(from, queryCon, *i, connected[k])) - || laneConflict(from, to, toLane, *i, connected[k].toEdge, connected[k].toLane)); - if ((myForbids[idx2][idx] && hasLaneConflict) - || rightTurnConflict(from, queryCon, *i, connected[k]) - || mergeConflict(from, queryCon, *i, connected[k], false) - || oppositeLeftTurnConflict(from, queryCon, *i, connected[k], false) - || myJunction->rightOnRedConflict(c.tlLinkIndex, connected[k].tlLinkIndex) - || (myJunction->tlsContConflict(from, c, *i, connected[k]) && hasLaneConflict - && !OptionsCont::getOptions().getBool("tls.ignore-internal-junction-jam")) - ) { - result += '1'; - } else { - result += '0'; - } - } - } - } - } - return result; -} - - -std::string -NBRequest::getFoesString(NBEdge* from, NBEdge* to, int fromLane, int toLane, const bool checkLaneFoes) const { - const bool lefthand = OptionsCont::getOptions().getBool("lefthand"); - // remember the case when the lane is a "dead end" in the meaning that - // vehicles must choose another lane to move over the following - // junction - // !!! move to forbidden - std::string result; - // crossings - auto crossings = myJunction->getCrossings(); - for (std::vector::const_reverse_iterator i = crossings.rbegin(); i != crossings.rend(); i++) { - bool foes = false; - for (EdgeVector::const_iterator it_e = (**i).edges.begin(); it_e != (**i).edges.end(); ++it_e) { - if ((*it_e) == from || (*it_e) == to) { - foes = true; - break; - } - } - result += foes ? '1' : '0'; - } - NBEdge::Connection queryCon = from->getConnection(fromLane, to, toLane); - // normal connections - for (EdgeVector::const_reverse_iterator i = myIncoming.rbegin(); - i != myIncoming.rend(); i++) { - - for (int j = (int)(*i)->getNumLanes() - 1; j >= 0; --j) { - std::vector connected = (*i)->getConnectionsFromLane(j); - int size = (int) connected.size(); - for (int k = size; k-- > 0;) { - const bool hasLaneConflict = (!(checkLaneFoes || checkLaneFoesByClass(queryCon, *i, connected[k]) - || checkLaneFoesByCooperation(from, queryCon, *i, connected[k])) - || laneConflict(from, to, toLane, *i, connected[k].toEdge, connected[k].toLane)); - if ((foes(from, to, (*i), connected[k].toEdge) && hasLaneConflict) - || rightTurnConflict(from, queryCon, *i, connected[k]) - || myJunction->turnFoes(from, to, fromLane, *i, connected[k].toEdge, connected[k].fromLane, lefthand) - || mergeConflict(from, queryCon, *i, connected[k], true) - || oppositeLeftTurnConflict(from, queryCon, *i, connected[k], true) - ) { - result += '1'; - } else { - result += '0'; - } - } - } - } - return result; -} - - -bool -NBRequest::rightTurnConflict(const NBEdge* from, const NBEdge::Connection& con, - const NBEdge* prohibitorFrom, const NBEdge::Connection& prohibitorCon) const { - return (!con.mayDefinitelyPass && - (NBNode::rightTurnConflict(from, con.toEdge, con.fromLane, prohibitorFrom, prohibitorCon.toEdge, prohibitorCon.fromLane) - // reverse conflicht (override) - || (prohibitorCon.mayDefinitelyPass && - NBNode::rightTurnConflict(prohibitorFrom, prohibitorCon.toEdge, prohibitorCon.fromLane, from, con.toEdge, con.fromLane)))); - - -} - - -bool -NBRequest::mergeConflict(const NBEdge* from, const NBEdge::Connection& con, - const NBEdge* prohibitorFrom, const NBEdge::Connection& prohibitorCon, bool foes) const { - if (from == prohibitorFrom - && con.toEdge == prohibitorCon.toEdge - && con.toLane == prohibitorCon.toLane - && con.fromLane != prohibitorCon.fromLane - && !myJunction->isConstantWidthTransition()) { - if (foes) { - return true; - } - if (prohibitorCon.mayDefinitelyPass) { - return true; - } - if (con.mayDefinitelyPass) { - return false; - } - const bool bike = from->getPermissions(con.fromLane) == SVC_BICYCLE; - const bool prohibitorBike = prohibitorFrom->getPermissions(prohibitorCon.fromLane) == SVC_BICYCLE; - if (myOutgoing.size() == 1) { - // at on-ramp like situations, right lane should yield - return bike || (con.fromLane < prohibitorCon.fromLane && !prohibitorBike); - } else if (myIncoming.size() == 1) { - // at off-ramp like situations, right lane should pass unless it's a bicycle lane - return bike || (con.fromLane > prohibitorCon.fromLane && !prohibitorBike); - } else { - // priority depends on direction: - // for right turns the rightmost lane gets priority - // otherwise the left lane - LinkDirection dir = myJunction->getDirection(from, con.toEdge); - if (dir == LinkDirection::RIGHT || dir == LinkDirection::PARTRIGHT) { - return con.fromLane > prohibitorCon.fromLane; - } else { - return con.fromLane < prohibitorCon.fromLane; - } - } - - } else { - return false; - } -} - - -bool -NBRequest::oppositeLeftTurnConflict(const NBEdge* from, const NBEdge::Connection& con, - const NBEdge* prohibitorFrom, const NBEdge::Connection& prohibitorCon, bool foes) const { - LinkDirection dir = myJunction->getDirection(from, con.toEdge); - // XXX lefthand issue (solve via #4256) - if (dir != LinkDirection::LEFT && dir != LinkDirection::PARTLEFT) { - return false; - } - dir = myJunction->getDirection(prohibitorFrom, prohibitorCon.toEdge); - if (dir != LinkDirection::LEFT && dir != LinkDirection::PARTLEFT) { - return false; - } - if (from == prohibitorFrom || NBRequest::foes(from, con.toEdge, prohibitorFrom, prohibitorCon.toEdge)) { - // not an opposite pair - return false; - }; - - double width2 = prohibitorCon.toEdge->getLaneWidth(prohibitorCon.toLane) / 2; - PositionVector shape = con.shape; - shape.append(con.viaShape); - PositionVector otherShape = prohibitorCon.shape; - otherShape.append(prohibitorCon.viaShape); - if (shape.size() == 0 || otherShape.size() == 0) { - // no internal lanes built - return false; - } - const double minDV = NBEdge::firstIntersection(shape, otherShape, width2); - if (minDV < shape.length() - POSITION_EPS && minDV > POSITION_EPS) { - // break symmetry using edge id - return foes || from->getID() < prohibitorFrom->getID(); - } else { - return false; - } -} - -bool -NBRequest::checkLaneFoesByClass(const NBEdge::Connection& con, - const NBEdge* prohibitorFrom, const NBEdge::Connection& prohibitorCon) const { - if (con.toEdge != prohibitorCon.toEdge) { - return false; - } - SVCPermissions svc = con.toEdge->getPermissions(con.toLane); - SVCPermissions svc2 = prohibitorFrom->getPermissions(prohibitorCon.fromLane) & prohibitorCon.toEdge->getPermissions(prohibitorCon.toLane); - // check for lane level conflict if the only common classes are bicycles or pedestrians - return (svc & svc2 & ~(SVC_BICYCLE | SVC_PEDESTRIAN)) == 0; -} - - -bool -NBRequest::checkLaneFoesByCooperation(const NBEdge* from, const NBEdge::Connection& con, - const NBEdge* prohibitorFrom, const NBEdge::Connection& prohibitorCon) const { - if (con.toEdge != prohibitorCon.toEdge) { - return false; - } - // if from and prohibitorFrom target distinct lanes for all their - // connections to the common target edge, cooperation is possible - // (and should always happen unless the connections cross for some byzantine reason) - - std::set fromTargetLanes; - for (const auto& c : from->getConnections()) { - if (c.toEdge == con.toEdge) { - fromTargetLanes.insert(c.toLane); - } - } - for (const auto& c : prohibitorFrom->getConnections()) { - if (c.toEdge == con.toEdge && fromTargetLanes.count(c.toLane) != 0) { - //std::cout << " con=" << con->getDescription(from) << " foe=" << prohibitorCon.getDescription(prohibitorFrom) - // << " no cooperation (targets=" << joinToString(fromTargetLanes, ' ') << " index=" << c.toLane << "\n"; - return false; - } - } - return true; -} - - -bool -NBRequest::laneConflict(const NBEdge* from, const NBEdge* to, int toLane, - const NBEdge* prohibitorFrom, const NBEdge* prohibitorTo, int prohibitorToLane) const { - if (to != prohibitorTo) { - return true; - } - // since we know that the edge2edge connections are in conflict, the only - // situation in which the lane2lane connections can be conflict-free is, if - // they target the same edge but do not cross each other - double angle = NBHelpers::relAngle( - from->getAngleAtNode(from->getToNode()), to->getAngleAtNode(to->getFromNode())); - if (angle == 180) { - angle = -180; // turnarounds are left turns - } - const double prohibitorAngle = NBHelpers::relAngle( - prohibitorFrom->getAngleAtNode(prohibitorFrom->getToNode()), to->getAngleAtNode(to->getFromNode())); - const bool rightOfProhibitor = prohibitorFrom->isTurningDirectionAt(to) - || (angle > prohibitorAngle && !from->isTurningDirectionAt(to)); - return rightOfProhibitor ? toLane >= prohibitorToLane : toLane <= prohibitorToLane; -} - -int -NBRequest::getIndex(const NBEdge* const from, const NBEdge* const to) const { - EdgeVector::const_iterator fp = std::find(myIncoming.begin(), myIncoming.end(), from); - EdgeVector::const_iterator tp = std::find(myOutgoing.begin(), myOutgoing.end(), to); - if (fp == myIncoming.end() || tp == myOutgoing.end()) { - return -1; - } - // compute the index - return (int)(distance(myIncoming.begin(), fp) * myOutgoing.size() + distance(myOutgoing.begin(), tp)); -} - - -std::ostream& -operator<<(std::ostream& os, const NBRequest& r) { - int variations = r.numLinks(); - for (int i = 0; i < variations; i++) { - os << i << ' '; - for (int j = 0; j < variations; j++) { - if (r.myForbids[i][j]) { - os << '1'; - } else { - os << '0'; - } - } - os << std::endl; - } - os << std::endl; - return os; -} - - -bool -NBRequest::mustBrake(const NBEdge* const from, const NBEdge* const to, int fromLane, int toLane, bool includePedCrossings) const { - NBEdge::Connection con(fromLane, const_cast(to), toLane); - const int linkIndex = myJunction->getConnectionIndex(from, con); - if (linkIndex >= 0 && (int)myResponse.size() > linkIndex) { - std::string response = getResponse(linkIndex); - if (!includePedCrossings) { - response = response.substr(0, response.size() - myJunction->getCrossings().size()); - } - if (response.find_first_of("1") == std::string::npos) { - return false; - } else if (!myJunction->isTLControlled()) { - return true; - } - // if the link must respond it could also be due to a tlsConflict. This - // must not carry over the the off-state response so we continue with - // the regular check - } - // get the indices - int idx2 = getIndex(from, to); - if (idx2 == -1) { - return false; - } - // go through all (existing) connections; - // check whether any of these forbids the one to determine - assert(idx2 < (int)(myIncoming.size()*myOutgoing.size())); - for (int idx1 = 0; idx1 < numLinks(); idx1++) { - //assert(myDone[idx1][idx2]); - if (myDone[idx1][idx2] && myForbids[idx1][idx2]) { - return true; - } - } - // maybe we need to brake for a pedestrian crossing - if (includePedCrossings) { - auto crossings = myJunction->getCrossings(); - for (std::vector::const_reverse_iterator i = crossings.rbegin(); i != crossings.rend(); i++) { - if (mustBrakeForCrossing(myJunction, from, to, **i)) { - return true; - } - } - } - // maybe we need to brake due to a right-turn conflict with straight-going - // bicycles - NBEdge::Connection queryCon = from->getConnection(fromLane, to, toLane); - LinkDirection dir = myJunction->getDirection(from, to); - if (dir == LinkDirection::RIGHT || dir == LinkDirection::PARTRIGHT) { - for (const NBEdge::Connection& con : from->getConnections()) { - if (rightTurnConflict(from, queryCon, from, con)) { - return true; - } - } - } - // maybe we need to brake due to a merge conflict - for (EdgeVector::const_reverse_iterator i = myIncoming.rbegin(); i != myIncoming.rend(); i++) { - int noLanes = (*i)->getNumLanes(); - for (int j = noLanes; j-- > 0;) { - std::vector connected = (*i)->getConnectionsFromLane(j); - const int size = (int) connected.size(); - for (int k = size; k-- > 0;) { - if ((*i) == from && fromLane != j - && mergeConflict(from, queryCon, *i, connected[k], myJunction->getType() == SumoXMLNodeType::ZIPPER)) { - return true; - } - } - } - } - // maybe we need to brake due to a zipper conflict - if (myJunction->getType() == SumoXMLNodeType::ZIPPER) { - for (int idx1 = 0; idx1 < numLinks(); idx1++) { - //assert(myDone[idx1][idx2]); - if (myDone[idx1][idx2] && myForbids[idx2][idx1]) { - return true; - } - } - } - return false; -} - - -bool -NBRequest::mustBrakeForCrossing(const NBNode* node, const NBEdge* const from, const NBEdge* const to, const NBNode::Crossing& crossing) { - const LinkDirection dir = node->getDirection(from, to); - const bool mustYield = dir == LinkDirection::LEFT || dir == LinkDirection::RIGHT; - if (crossing.priority || mustYield) { - for (EdgeVector::const_iterator it_e = crossing.edges.begin(); it_e != crossing.edges.end(); ++it_e) { - // left and right turns must yield to unprioritized crossings only on their destination edge - if (((*it_e) == from && crossing.priority) || (*it_e) == to) { - return true; - } - } - } - return false; -} - - -bool -NBRequest::mustBrake(const NBEdge* const possProhibitorFrom, const NBEdge* const possProhibitorTo, - const NBEdge* const possProhibitedFrom, const NBEdge* const possProhibitedTo) const { - // get the indices - int idx1 = getIndex(possProhibitorFrom, possProhibitorTo); - int idx2 = getIndex(possProhibitedFrom, possProhibitedTo); - return (myForbids[idx2][idx1]); -} - - -void -NBRequest::reportWarnings() { - // check if any errors occurred on build the link prohibitions - if (myNotBuild != 0) { - WRITE_WARNING(toString(myNotBuild) + " of " + toString(myNotBuild + myGoodBuilds) + " prohibitions were not build."); - } -} - - -void -NBRequest::resetCooperating() { - // map from edge to number of incoming connections - std::map incomingCount; // initialized to 0 - // map from edge to indices of approached lanes - std::map > approachedLanes; - // map from edge to list of incoming edges - std::map incomingEdges; - for (EdgeVector::const_iterator it_e = myIncoming.begin(); it_e != myIncoming.end(); it_e++) { - const std::vector connections = (*it_e)->getConnections(); - for (std::vector::const_iterator it_c = connections.begin(); it_c != connections.end(); ++it_c) { - incomingCount[it_c->toEdge]++; - approachedLanes[it_c->toEdge].insert(it_c->toLane); - incomingEdges[it_c->toEdge].push_back(*it_e); - } - } - for (std::map::iterator it = incomingCount.begin(); it != incomingCount.end(); ++it) { - NBEdge* to = it->first; - // we cannot test against to->getNumLanes() since not all lanes may be used - if ((int)approachedLanes[to].size() >= it->second) { - EdgeVector& incoming = incomingEdges[to]; - // make these connections mutually unconflicting - for (EdgeVector::iterator it_e1 = incoming.begin(); it_e1 != incoming.end(); ++it_e1) { - for (EdgeVector::iterator it_e2 = incoming.begin(); it_e2 != incoming.end(); ++it_e2) { - myForbids[getIndex(*it_e1, to)][getIndex(*it_e2, to)] = false; - } - } - } - } -} - - -bool -NBRequest::hasConflict() const { - for (std::string foes : myFoes) { - if (foes.find_first_of("1") != std::string::npos) { - return true; - } - } - return false; -} - - -int -NBRequest::numLinks() const { - return (int)(myIncoming.size() * myOutgoing.size() + myJunction->getCrossings().size()); -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netbuild/NBRequest.h b/Util/OSM2ODR/src/netbuild/NBRequest.h deleted file mode 100644 index 30faa400f..000000000 --- a/Util/OSM2ODR/src/netbuild/NBRequest.h +++ /dev/null @@ -1,279 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NBRequest.h -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Sascha Krieg -/// @author Michael Behrisch -/// @date Tue, 20 Nov 2001 -/// -// This class computes the logic of a junction -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include -#include -#include "NBConnectionDefs.h" -#include "NBContHelper.h" -#include - - -// =========================================================================== -// class declarations -// =========================================================================== -class NBEdge; -class NBJunctionTypeIO; -class NBTrafficLightLogic; -class OptionsCont; -class NBTrafficLightDefinition; -class NBEdgeCont; -class OutputDevice; - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NBRequest - * Given a special node, this class builds the logic of this (junction) - * regarding the relationships between the incoming and outgoing edges and - * their priorities. The junction's logic is saved when it does not yet exist. - */ -class NBRequest { -public: - /** constructor - The parameter are the logic's lists of edges (all, incoming only and - outgoing only edges). By now no further informations are needed to - describe the junctions. These parameter must not be changed during the - logic's building */ - NBRequest(const NBEdgeCont& ec, - NBNode* junction, - const EdgeVector& all, - const EdgeVector& incoming, - const EdgeVector& outgoing, - const NBConnectionProhibits& loadedProhibits); - - /// @brief destructor - ~NBRequest(); - - /// @brief builds the bitset-representation of the logic - void buildBitfieldLogic(); - - /// @brief @brief returns the number of the junction's lanes and the number of the junction's links in respect. @note: only connected lanes are counted - std::pair getSizes() const; - - /** @brief Returns the information whether "prohibited" flow must let "prohibitor" flow pass - * @param[in] possProhibitorFrom The maybe prohibiting connection's begin - * @param[in] possProhibitorTo The maybe prohibiting connection's end - * @param[in] possProhibitedFrom The maybe prohibited connection's begin - * @param[in] possProhibitedTo The maybe prohibited connection's end - * @return Whether the first flow prohibits the second one - */ - bool mustBrake(const NBEdge* const possProhibitorFrom, const NBEdge* const possProhibitorTo, - const NBEdge* const possProhibitedFrom, const NBEdge* const possProhibitedTo) const; - - - /** @brief Returns the information whether the described flow must let any other flow pass - * @param[in] from The connection's start edge - * @param[in] to The connection's end edge - * @param[in] fromLane The connection starting lane - * @param[in] includePedCrossings Whether braking due to a pedestrian crossing counts - * @return Whether the described connection must brake (has higher priorised foes) - */ - bool mustBrake(const NBEdge* const from, const NBEdge* const to, int fromLane, int toLane, bool includePedCrossings) const; - - /** @brief Returns the information whether the described flow must brake for the given crossing - * @param[in] node The parent node of this request - * @param[in] from The connection's start edge - * @param[in] to The connection's end edge - * @param[in] crossing The pedestrian crossing to check - * @return Whether the described connection must brake (has higher priorised foes) - */ - static bool mustBrakeForCrossing(const NBNode* node, const NBEdge* const from, const NBEdge* const to, const NBNode::Crossing& crossing); - - /** @brief Returns the information whether the given flows cross - * @param[in] from1 The starting edge of the first stream - * @param[in] to1 The ending edge of the first stream - * @param[in] from2 The starting edge of the second stream - * @param[in] to2 The ending edge of the second stream - * @return Whether both stream are foes (cross) - */ - bool foes(const NBEdge* const from1, const NBEdge* const to1, - const NBEdge* const from2, const NBEdge* const to2) const; - - - /** @brief Returns the information whether "prohibited" flow must let "prohibitor" flow pass - * @param[in] possProhibitorFrom The maybe prohibiting connection's begin - * @param[in] possProhibitorTo The maybe prohibiting connection's end - * @param[in] possProhibitedFrom The maybe prohibited connection's begin - * @param[in] possProhibitedTo The maybe prohibited connection's end - * @param[in] regardNonSignalisedLowerPriority Whether the right of way rules without traffic lights shall be regarded - * @return Whether the first flow prohibits the second one - */ - bool forbids(const NBEdge* const possProhibitorFrom, const NBEdge* const possProhibitorTo, - const NBEdge* const possProhibitedFrom, const NBEdge* const possProhibitedTo, - bool regardNonSignalisedLowerPriority) const; - - /// @brief writes the XML-representation of the logic as a bitset-logic XML representation - void computeLogic(const bool checkLaneFoes); - - void writeLogic(OutputDevice& into) const; - - const std::string& getFoes(int linkIndex) const; - const std::string& getResponse(int linkIndex) const; - - /// @brief prints the request - friend std::ostream& operator<<(std::ostream& os, const NBRequest& r); - - /// @brief reports warnings if any occurred - static void reportWarnings(); - - /// @brief whether the given connections crosses the foe connection from the same lane and must yield - bool rightTurnConflict(const NBEdge* from, const NBEdge::Connection& con, - const NBEdge* prohibitorFrom, const NBEdge::Connection& prohibitorCon) const; - - /// @brief whether multple connections from the same edge target the same lane - bool mergeConflict(const NBEdge* from, const NBEdge::Connection& con, - const NBEdge* prohibitorFrom, const NBEdge::Connection& prohibitorCon, bool foes) const; - - /// @brief whether opposite left turns intersect - bool oppositeLeftTurnConflict(const NBEdge* from, const NBEdge::Connection& con, - const NBEdge* prohibitorFrom, const NBEdge::Connection& prohibitorCon, bool foes) const; - - - /// @brief whether there are conflicting streams of traffic at this node - bool hasConflict() const; - -private: - /** sets the information that the edge from1->to1 blocks the edge - from2->to2 (is higher priorised than this) */ - void setBlocking(NBEdge* from1, NBEdge* to1, NBEdge* from2, NBEdge* to2); - - /** @brief computes the response of a certain lane - Returns the next link index within the junction */ - int computeLaneResponse(NBEdge* from, int lane, int pos, const bool checkLaneFoes); - - /** @brief computes the response of a certain crossing - Returns the next link index within the junction */ - int computeCrossingResponse(const NBNode::Crossing& crossing, int pos); - - /** @brief Writes the response of a certain link - * - * For the link (described by the connected edges and lanes), the response in dependence - * to all other links of this junction is computed. Herefor, the method - * goes through all links of this junction and writes a '0' if the link - * is not blocked by the currently investigated one, or '1' if it is. - * - * In the case "mayDefinitelyPass" is true, the link will not be disturbed by - * any other (special case for on-ramps). - * - * @param[in] tlIndex The tl index of the connection for which the responses shall be written - * @param[in] from The link's starting edge - * @param[in] to The link's destination edge - * @param[in] fromLane The link's starting lane - * @param[in] toLane The link's destination lane - * @param[in] mayDefinitelyPass Whether this link is definitely not disturbed - * @return the response string - * @exception IOError not yet implemented - */ - std::string getResponseString(const NBEdge* const from, const NBEdge::Connection& c, const bool checkLaneFoes) const; - - - /** writes which participating links are foes to the given */ - std::string getFoesString(NBEdge* from, NBEdge* to, - int fromLane, int toLane, const bool checkLaneFoes) const; - - - /** @brief Returns the index to the internal combination container for the given edge combination - * - * If one of the edges is not known, -1 is returned. - * - * @param[in] from The starting edge (incoming to this logic) - * @param[in] to The destination edge (outgoing from this logic) - * @return The index within the internal container - */ - int getIndex(const NBEdge* const from, const NBEdge* const to) const; - - - /// @brief returns the distance between the incoming (from) and the outgoing (to) edge clockwise in edges - int distanceCounterClockwise(NBEdge* from, NBEdge* to); - - /// @brief computes the relationships between links outgoing right of the given link */ - void computeRightOutgoingLinkCrossings(NBEdge* from, NBEdge* to); - - /// @brief computes the relationships between links outgoing left of the given link - void computeLeftOutgoingLinkCrossings(NBEdge* from, NBEdge* to); - - - void resetSignalised(); - - /// @brief reset foes it the number of lanes matches (or exceeds) the number of incoming connections for an edge - void resetCooperating(); - - /// @brief whether the given connections must be checked for lane conflicts due to the vClasses involved - bool checkLaneFoesByClass(const NBEdge::Connection& con, - const NBEdge* prohibitorFrom, const NBEdge::Connection& prohibitorCon) const; - - /// @brief whether the given connections must be checked for lane conflicts due to disjunct target lanes - bool checkLaneFoesByCooperation(const NBEdge* from, const NBEdge::Connection& con, - const NBEdge* prohibitorFrom, const NBEdge::Connection& prohibitorCon) const; - - /** @brief return whether the given laneToLane connections prohibit each other - * under the assumption that the edge2edge connections are in conflict - */ - bool laneConflict(const NBEdge* from, const NBEdge* to, int toLane, const NBEdge* prohibitorFrom, const NBEdge* prohibitorTo, int prohibitorToLane) const; - - - /// @brief return to total number of edge-to-edge connections of this request-logic - inline int numLinks() const; - -private: - /// @brief the node the request is assigned to - NBNode* myJunction; - - /// @brief all (icoming and outgoing) of the junctions edges - const EdgeVector& myAll; - - /// @brief edges incoming to the junction - const EdgeVector& myIncoming; - - /// @brief edges outgoing from the junction - const EdgeVector& myOutgoing; - - /// @brief definition of a container to store boolean informations about a link into - typedef std::vector LinkInfoCont; - - /// @brief definition of a container for link(edge->edge) X link(edge->edge) combinations (size = |myIncoming|*|myOutgoing|) - typedef std::vector CombinationsCont; - - /// @brief the link X link blockings - CombinationsCont myForbids; - - /// @brief the link X link is done-checks - CombinationsCont myDone; - - /// @brief precomputed right-of-way matrices for each lane-to-lane link - std::vector myFoes; - std::vector myResponse; - std::vector myHaveVia; - -private: - static int myGoodBuilds, myNotBuild; - - /// @brief Invalidated assignment operator - NBRequest& operator=(const NBRequest& s) = delete; -}; diff --git a/Util/OSM2ODR/src/netbuild/NBSign.cpp b/Util/OSM2ODR/src/netbuild/NBSign.cpp deleted file mode 100644 index 39229a2ee..000000000 --- a/Util/OSM2ODR/src/netbuild/NBSign.cpp +++ /dev/null @@ -1,115 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2012-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NBSign.cpp -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @author Jakob Erdmann -/// @date Nov 2012 -/// -// A class representing a street sign -/****************************************************************************/ -#include - -#include -#include -#include -#include -#include "NBEdge.h" -#include "NBSign.h" - - -// =========================================================================== -// static members -// =========================================================================== -StringBijection::Entry signTypeStringsInitializer[] = { - {"speed limit", NBSign::SIGN_TYPE_SPEED}, - {"yield", NBSign::SIGN_TYPE_YIELD}, - {"stop", NBSign::SIGN_TYPE_STOP}, - {"allway_stop", NBSign::SIGN_TYPE_ALLWAY_STOP}, - {"on ramp", NBSign::SIGN_TYPE_ON_RAMP}, - {"priority", NBSign::SIGN_TYPE_PRIORITY}, - {"right before left", NBSign::SIGN_TYPE_RIGHT_BEFORE_LEFT}, - {"roundabout", NBSign::SIGN_TYPE_ROUNDABOUT}, - {"rail crossing", NBSign::SIGN_TYPE_RAIL_CROSSING}, - {"slope", NBSign::SIGN_TYPE_SLOPE}, - {"city limits", NBSign::SIGN_TYPE_CITY}, - {"info", NBSign::SIGN_TYPE_INFO}, -}; - -StringBijection NBSign::SignTypeStrings( - signTypeStringsInitializer, NBSign::SIGN_TYPE_INFO); - - -// =========================================================================== -// member method definitions -// =========================================================================== - -NBSign::NBSign(SignType type, double offset, const std::string label) : - myType(type), - myOffset(offset), - myLabel(label) { -} - - -NBSign::~NBSign() {} - - -void -NBSign::writeAsPOI(OutputDevice& into, const NBEdge* edge) const { - PositionVector shp = edge->getLanes()[0].shape; - try { - shp.move2side(3); - } catch (InvalidArgument&) { - // we do not write anything, maybe we should - } - Position pos = shp.positionAtOffset(myOffset); - into.openTag(SUMO_TAG_POI); - into.writeAttr(SUMO_ATTR_ID, edge->getID() + "." + toString(myOffset)); - into.writeAttr(SUMO_ATTR_TYPE, SignTypeStrings.getString(myType)); - switch (myType) { /// XXX @todo add default colors - case SIGN_TYPE_SPEED: - case SIGN_TYPE_SLOPE: - case SIGN_TYPE_CITY: - case SIGN_TYPE_INFO: - into.writeAttr(SUMO_ATTR_COLOR, RGBColor::GREY); - break; - case SIGN_TYPE_YIELD: - case SIGN_TYPE_STOP: - case SIGN_TYPE_ALLWAY_STOP: - case SIGN_TYPE_ON_RAMP: - case SIGN_TYPE_RAIL_CROSSING: - into.writeAttr(SUMO_ATTR_COLOR, RGBColor::RED); - break; - case SIGN_TYPE_PRIORITY: - into.writeAttr(SUMO_ATTR_COLOR, RGBColor::YELLOW); - break; - case SIGN_TYPE_RIGHT_BEFORE_LEFT: - into.writeAttr(SUMO_ATTR_COLOR, RGBColor(255, 153, 0, 255)); - break; - case SIGN_TYPE_ROUNDABOUT: - into.writeAttr(SUMO_ATTR_COLOR, RGBColor::BLUE); - break; - } - into.writeAttr(SUMO_ATTR_X, pos.x()); - into.writeAttr(SUMO_ATTR_Y, pos.y()); - into.writeAttr(SUMO_ATTR_ANGLE, 0); // XXX use road angle? - // @todo add image resources and default images for all signs - //into.writeAttr(SUMO_ATTR_IMGFILE, p->getImgFile()); - //into.writeAttr(SUMO_ATTR_WIDTH, p->getWidth()); - //into.writeAttr(SUMO_ATTR_HEIGHT, p->getHeight()); - into.closeTag(); -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netbuild/NBSign.h b/Util/OSM2ODR/src/netbuild/NBSign.h deleted file mode 100644 index ae2609488..000000000 --- a/Util/OSM2ODR/src/netbuild/NBSign.h +++ /dev/null @@ -1,87 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2012-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NBSign.h -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date Nov 2012 -/// -// A class representing a street sign -/****************************************************************************/ -#pragma once -#include - -#include -#include - -// =========================================================================== -// class declarations -// =========================================================================== -class NBEdge; -class OutputDevice; - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NBSign - * @brief A class representing a single street sign - */ -class NBSign { -public: - - enum SignType { - SIGN_TYPE_SPEED, - SIGN_TYPE_YIELD, - SIGN_TYPE_STOP, - SIGN_TYPE_ALLWAY_STOP, - SIGN_TYPE_ON_RAMP, - SIGN_TYPE_PRIORITY, - SIGN_TYPE_RIGHT_BEFORE_LEFT, - SIGN_TYPE_ROUNDABOUT, - SIGN_TYPE_RAIL_CROSSING, - SIGN_TYPE_SLOPE, - SIGN_TYPE_CITY, - SIGN_TYPE_INFO // terminator - }; - - /** @brief Constructor with id, and position - * - * @param[in] type The type of the sign - * @param[in] offset The offset of the sign from the start of its edge - * @param[in] label The (optional) label (for SPEED, SLOPE etc) - */ - NBSign(SignType type, double offset, const std::string label = ""); - - - /// @brief Destructor - ~NBSign(); - - /// @brief write into device as POI positioned relative to the given edge - void writeAsPOI(OutputDevice& into, const NBEdge* edge) const; - - -private: - /// @brief the type of the sign - SignType myType; - - /// @brief The offset of the sign from the start of its edge - double myOffset; - - /// @brief The (optional) label (for SPEED, SLOPE etc) - std::string myLabel; - - static StringBijection SignTypeStrings; - static StringBijection SignTypeColors; -}; diff --git a/Util/OSM2ODR/src/netbuild/NBTrafficLightDefinition.cpp b/Util/OSM2ODR/src/netbuild/NBTrafficLightDefinition.cpp deleted file mode 100644 index bb5404198..000000000 --- a/Util/OSM2ODR/src/netbuild/NBTrafficLightDefinition.cpp +++ /dev/null @@ -1,537 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NBTrafficLightDefinition.cpp -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date Sept 2002 -/// -// The base class for traffic light logic definitions -/****************************************************************************/ -#include - -#include -#include -#include -#include -#include -#include -#include -#include "NBTrafficLightDefinition.h" -#include -#include "NBLinkPossibilityMatrix.h" -#include "NBTrafficLightLogic.h" -#include "NBOwnTLDef.h" -#include "NBContHelper.h" - -//#define DEBUG_RIGHT_OF_WAY -#define DEBUGCOND true - -// =========================================================================== -// static members -// =========================================================================== -const std::string NBTrafficLightDefinition::DefaultProgramID = "0"; -const std::string NBTrafficLightDefinition::DummyID = "dummy"; -const SUMOTime NBTrafficLightDefinition::UNSPECIFIED_DURATION(-1); - -// =========================================================================== -// method definitions -// =========================================================================== -NBTrafficLightDefinition::NBTrafficLightDefinition(const std::string& id, - const std::vector& junctions, const std::string& programID, - SUMOTime offset, TrafficLightType type) : - Named(id), - myControlledNodes(junctions), - mySubID(programID), myOffset(offset), - myType(type), - myNeedsContRelationReady(false), - myRightOnRedConflictsReady(false) { - std::vector::iterator i = myControlledNodes.begin(); - while (i != myControlledNodes.end()) { - for (std::vector::iterator j = i + 1; j != myControlledNodes.end();) { - if (*i == *j) { - j = myControlledNodes.erase(j); - } else { - j++; - } - } - i++; - } - std::sort(myControlledNodes.begin(), myControlledNodes.end(), NBNode::nodes_by_id_sorter()); - for (std::vector::const_iterator i = junctions.begin(); i != junctions.end(); i++) { - (*i)->addTrafficLight(this); - } -} - - -NBTrafficLightDefinition::NBTrafficLightDefinition(const std::string& id, - NBNode* junction, const std::string& programID, SUMOTime offset, TrafficLightType type) : - Named(id), - mySubID(programID), - myOffset(offset), - myType(type), - myNeedsContRelationReady(false), - myRightOnRedConflictsReady(false) { - addNode(junction); -} - - -NBTrafficLightDefinition::NBTrafficLightDefinition(const std::string& id, const std::string& programID, - SUMOTime offset, TrafficLightType type) : - Named(id), - mySubID(programID), - myOffset(offset), - myType(type), - myNeedsContRelationReady(false), - myRightOnRedConflictsReady(false) { -} - - -NBTrafficLightDefinition::~NBTrafficLightDefinition() {} - - -NBTrafficLightLogic* -NBTrafficLightDefinition::compute(OptionsCont& oc) { - // it is not really a traffic light if no incoming edge exists - if (amInvalid()) { - // make a copy of myControlledNodes because it will be modified; - std::vector nodes = myControlledNodes; - for (auto it : nodes) { - it->removeTrafficLight(this); - } - WRITE_WARNING("The traffic light '" + getID() + "' does not control any links; it will not be build."); - return nullptr; - } - // compute the time needed to brake - int brakingTime = computeBrakingTime(oc.getFloat("tls.yellow.min-decel")); - // perform the computation depending on whether the traffic light - // definition was loaded or shall be computed new completely - if (!oc.isDefault("tls.yellow.time")) { - brakingTime = oc.getInt("tls.yellow.time"); - } - NBTrafficLightLogic* ret = myCompute(brakingTime); - ret->updateParameters(getParametersMap()); - return ret; -} - - -bool -NBTrafficLightDefinition::amInvalid() const { - return myControlledLinks.size() == 0; -} - - -int -NBTrafficLightDefinition::computeBrakingTime(double minDecel) const { - if (myIncomingEdges.size() == 0) { - // don't crash - return 3; - } - double vmax = NBContHelper::maxSpeed(myIncomingEdges); - if (vmax < 71 / 3.6) { - // up to 50kmh: 3 seconds , 60km/h: 4, 70kmh: 5 - // @note: these are German regulations, other countries may differ - return 3 + (int)MAX2(0.0, (floor((vmax - 50 / 3.6) * 0.37))); - } else { - // above 70km/h we use a function that grows according to the "natural" - // formula (vmax / 2 * minDecel) but continues smoothly where the german - // rules leave of - return (int)(1.8 + vmax / 2 / minDecel); - } -} - - -void -NBTrafficLightDefinition::setParticipantsInformation() { - // collect the information about participating edges and links - collectEdges(); - collectLinks(); -} - -std::set -NBTrafficLightDefinition::collectReachable(EdgeVector outer, const EdgeVector& within, bool checkControlled) { - std::set reachable; - while (outer.size() > 0) { - NBEdge* from = outer.back(); - outer.pop_back(); - std::vector& cons = from->getConnections(); - for (std::vector::iterator k = cons.begin(); k != cons.end(); k++) { - NBEdge* to = (*k).toEdge; - if (reachable.count(to) == 0 && - (find(within.begin(), within.end(), to) != within.end()) && - (!checkControlled || from->mayBeTLSControlled((*k).fromLane, to, (*k).toLane))) { - reachable.insert(to); - outer.push_back(to); - } - } - } - return reachable; -} - - -void -NBTrafficLightDefinition::collectEdges() { - myIncomingEdges.clear(); - myEdgesWithin.clear(); - EdgeVector myOutgoing; - // collect the edges from the participating nodes - for (std::vector::iterator i = myControlledNodes.begin(); i != myControlledNodes.end(); i++) { - const EdgeVector& incoming = (*i)->getIncomingEdges(); - copy(incoming.begin(), incoming.end(), back_inserter(myIncomingEdges)); - const EdgeVector& outgoing = (*i)->getOutgoingEdges(); - copy(outgoing.begin(), outgoing.end(), back_inserter(myOutgoing)); - } - EdgeVector outer; - // check which of the edges are completely within the junction - // add them to the list of edges lying within the node - for (NBEdge* edge : myIncomingEdges) { - edge->setInsideTLS(false); // reset - // an edge lies within the logic if it is outgoing as well as incoming - EdgeVector::iterator k = std::find(myOutgoing.begin(), myOutgoing.end(), edge); - if (k != myOutgoing.end()) { - myEdgesWithin.push_back(edge); - } else { - outer.push_back(edge); - } - } - // collect edges that are reachable from the outside via controlled connections - std::set reachable = collectReachable(outer, myEdgesWithin, true); - // collect edges that are reachable from the outside regardless of controllability - std::set reachable2 = collectReachable(outer, myEdgesWithin, false); - - const bool uncontrolledWithin = OptionsCont::getOptions().getBool("tls.uncontrolled-within"); - for (EdgeVector::iterator j = myEdgesWithin.begin(); j != myEdgesWithin.end(); ++j) { - NBEdge* edge = *j; - // edges that are marked as 'inner' will not get their own phase when - // computing traffic light logics (unless they cannot be reached from the outside at all) - if (reachable.count(edge) == 1) { - edge->setInsideTLS(true); - // legacy behavior - if (uncontrolledWithin && myControlledInnerEdges.count(edge->getID()) == 0) { - myIncomingEdges.erase(find(myIncomingEdges.begin(), myIncomingEdges.end(), edge)); - } - } - if (reachable2.count(edge) == 0 && edge->getFirstNonPedestrianLaneIndex(NBNode::FORWARD, true) >= 0 - && getID() != DummyID) { - WRITE_WARNING("Unreachable edge '" + edge->getID() + "' within tlLogic '" + getID() + "'"); - } - } -} - - -bool -NBTrafficLightDefinition::mustBrake(const NBEdge* const from, const NBEdge* const to) const { - std::vector::const_iterator i = - find_if(myControlledNodes.begin(), myControlledNodes.end(), - NBContHelper::node_with_incoming_finder(from)); - assert(i != myControlledNodes.end()); - NBNode* node = *i; - if (!node->hasOutgoing(to)) { - return true; // !!! - } - // @todo recheck relevance of lane indices - return node->mustBrake(from, to, -1, -1, true); -} - - -bool -NBTrafficLightDefinition::mustBrake(const NBEdge* const possProhibitedFrom, - const NBEdge* const possProhibitedTo, - const NBEdge* const possProhibitorFrom, - const NBEdge* const possProhibitorTo, - bool regardNonSignalisedLowerPriority) const { - return forbids(possProhibitorFrom, possProhibitorTo, - possProhibitedFrom, possProhibitedTo, - regardNonSignalisedLowerPriority); -} - - -bool -NBTrafficLightDefinition::mustBrake(const NBConnection& possProhibited, - const NBConnection& possProhibitor, - bool regardNonSignalisedLowerPriority) const { - return forbids(possProhibitor.getFrom(), possProhibitor.getTo(), - possProhibited.getFrom(), possProhibited.getTo(), - regardNonSignalisedLowerPriority); -} - - -bool -NBTrafficLightDefinition::forbids(const NBEdge* const possProhibitorFrom, - const NBEdge* const possProhibitorTo, - const NBEdge* const possProhibitedFrom, - const NBEdge* const possProhibitedTo, - bool regardNonSignalisedLowerPriority, - bool sameNodeOnly) const { - if (possProhibitorFrom == nullptr || possProhibitorTo == nullptr || possProhibitedFrom == nullptr || possProhibitedTo == nullptr) { - return false; - } - // retrieve both nodes - std::vector::const_iterator incoming = - find_if(myControlledNodes.begin(), myControlledNodes.end(), NBContHelper::node_with_incoming_finder(possProhibitorFrom)); - std::vector::const_iterator outgoing = - find_if(myControlledNodes.begin(), myControlledNodes.end(), NBContHelper::node_with_outgoing_finder(possProhibitedTo)); - assert(incoming != myControlledNodes.end()); - NBNode* incnode = *incoming; - NBNode* outnode = *outgoing; - EdgeVector::const_iterator i; - -#ifdef DEBUG_RIGHT_OF_WAY - if (DEBUGCOND) { - std::cout << "foribds tls=" << getID() << " from=" << possProhibitedFrom->getID() << " to=" << possProhibitedTo->getID() << " foeFrom=" << possProhibitorFrom->getID() << " foeTo=" << possProhibitorTo->getID() << " rnslp=" << regardNonSignalisedLowerPriority << " sameNodeOnly=" << sameNodeOnly; - } -#endif - if (incnode != outnode) { - if (sameNodeOnly) { -#ifdef DEBUG_RIGHT_OF_WAY - if (DEBUGCOND) { - std::cout << " differentNodes: allows (no check)\n"; - } -#endif - return false; - } - // the links are located at different nodes - const EdgeVector& ev1 = possProhibitedTo->getConnectedEdges(); - // go through the following edge, - // check whether one of these connections is prohibited - for (i = ev1.begin(); i != ev1.end(); ++i) { - std::vector::const_iterator outgoing2 = - find_if(myControlledNodes.begin(), myControlledNodes.end(), NBContHelper::node_with_outgoing_finder(*i)); - if (outgoing2 == myControlledNodes.end()) { - continue; - } - NBNode* outnode2 = *outgoing2; - if (incnode != outnode2) { - continue; - } - if (incnode->getDirection(possProhibitedTo, *i) != LinkDirection::STRAIGHT) { - continue; - } - bool ret1 = incnode->foes(possProhibitorFrom, possProhibitorTo, - possProhibitedTo, *i); - bool ret2 = incnode->forbids(possProhibitorFrom, possProhibitorTo, - possProhibitedTo, *i, - regardNonSignalisedLowerPriority); - bool ret = ret1 || ret2; - if (ret) { -#ifdef DEBUG_RIGHT_OF_WAY - if (DEBUGCOND) { - std::cout << " differentNodes: forbids\n"; - } -#endif - return true; - } - } - - const EdgeVector& ev2 = possProhibitorTo->getConnectedEdges(); - // go through the following edge, - // check whether one of these connections is prohibited - for (i = ev2.begin(); i != ev2.end(); ++i) { - std::vector::const_iterator incoming2 = - find_if(myControlledNodes.begin(), myControlledNodes.end(), NBContHelper::node_with_incoming_finder(possProhibitorTo)); - if (incoming2 == myControlledNodes.end()) { - continue; - } - NBNode* incnode2 = *incoming2; - if (incnode2 != outnode) { - continue; - } - if (incnode2->getDirection(possProhibitorTo, *i) != LinkDirection::STRAIGHT) { - continue; - } - bool ret1 = incnode2->foes(possProhibitorTo, *i, - possProhibitedFrom, possProhibitedTo); - bool ret2 = incnode2->forbids(possProhibitorTo, *i, - possProhibitedFrom, possProhibitedTo, - regardNonSignalisedLowerPriority); - bool ret = ret1 || ret2; - if (ret) { -#ifdef DEBUG_RIGHT_OF_WAY - if (DEBUGCOND) { - std::cout << " differentNodes: forbids (2)\n"; - } -#endif - return true; - } - } -#ifdef DEBUG_RIGHT_OF_WAY - if (DEBUGCOND) { - std::cout << " differentNodes: allows\n"; - } -#endif - return false; - } - // both links are located at the same node - // check using this node's information - const bool result = incnode->forbids(possProhibitorFrom, possProhibitorTo, - possProhibitedFrom, possProhibitedTo, - regardNonSignalisedLowerPriority); -#ifdef DEBUG_RIGHT_OF_WAY - if (DEBUGCOND) { - std::cout << " sameNodes: " << (result ? "forbids" : "allows") << "\n"; - } -#endif - return result; -} - - -bool -NBTrafficLightDefinition::foes(const NBEdge* const from1, const NBEdge* const to1, - const NBEdge* const from2, const NBEdge* const to2) const { - if (to1 == nullptr || to2 == nullptr) { - return false; - } - // retrieve both nodes (it is possible that a connection - std::vector::const_iterator incoming = - find_if(myControlledNodes.begin(), myControlledNodes.end(), - NBContHelper::node_with_incoming_finder(from1)); - std::vector::const_iterator outgoing = - find_if(myControlledNodes.begin(), myControlledNodes.end(), - NBContHelper::node_with_outgoing_finder(to1)); - assert(incoming != myControlledNodes.end()); - NBNode* incnode = *incoming; - NBNode* outnode = *outgoing; - if (incnode != outnode) { - return false; - } - return incnode->foes(from1, to1, from2, to2); -} - - -void -NBTrafficLightDefinition::addNode(NBNode* node) { - if (std::find(myControlledNodes.begin(), myControlledNodes.end(), node) == myControlledNodes.end()) { - myControlledNodes.push_back(node); - std::sort(myControlledNodes.begin(), myControlledNodes.end(), NBNode::nodes_by_id_sorter()); - } - node->addTrafficLight(this); -} - - -void -NBTrafficLightDefinition::removeNode(NBNode* node) { - std::vector::iterator i = std::find(myControlledNodes.begin(), myControlledNodes.end(), node); - if (i != myControlledNodes.end()) { - myControlledNodes.erase(i); - } - // !!! remove in node? -} - - -void -NBTrafficLightDefinition::addControlledInnerEdges(const std::vector& edges) { - myControlledInnerEdges.insert(edges.begin(), edges.end()); -} - - -std::vector -NBTrafficLightDefinition::getControlledInnerEdges() const { - return std::vector(myControlledInnerEdges.begin(), myControlledInnerEdges.end()); -} - - -const EdgeVector& -NBTrafficLightDefinition::getIncomingEdges() const { - return myIncomingEdges; -} - - -void -NBTrafficLightDefinition::collectAllLinks(NBConnectionVector& into) { - int tlIndex = 0; - // build the list of links which are controled by the traffic light - for (EdgeVector::iterator i = myIncomingEdges.begin(); i != myIncomingEdges.end(); i++) { - NBEdge* incoming = *i; - int noLanes = incoming->getNumLanes(); - for (int j = 0; j < noLanes; j++) { - std::vector connected = incoming->getConnectionsFromLane(j); - for (std::vector::iterator k = connected.begin(); k != connected.end(); k++) { - const NBEdge::Connection& el = *k; - if (incoming->mayBeTLSControlled(el.fromLane, el.toEdge, el.toLane)) { - if (el.toEdge != nullptr && el.toLane >= (int) el.toEdge->getNumLanes()) { - throw ProcessError("Connection '" + incoming->getID() + "_" + toString(j) + "->" + el.toEdge->getID() + "_" + toString(el.toLane) + "' yields in a not existing lane."); - } - if (incoming->getToNode()->getType() == SumoXMLNodeType::RAIL_CROSSING - && isRailway(incoming->getPermissions())) { - // railways stay uncontrolled at rail crossing but they - // must be registered in MSRailCrossing - into.push_back(NBConnection(incoming, el.fromLane, el.toEdge, el.toLane, -1)); - } else if (incoming->getToNode()->getType() == SumoXMLNodeType::RAIL_SIGNAL - && incoming->getToNode()->getDirection(incoming, el.toEdge) == LinkDirection::TURN) { - // turnarounds stay uncontrolled at rail signal - } else { - into.push_back(NBConnection(incoming, el.fromLane, el.toEdge, el.toLane, tlIndex++)); - } - } - } - } - } - if (into.size() > 0 && tlIndex == 0) { - WRITE_WARNINGF("The rail crossing '%' does not have any roads.", getID()); - } -} - - -bool -NBTrafficLightDefinition::needsCont(const NBEdge* fromE, const NBEdge* toE, const NBEdge* otherFromE, const NBEdge* otherToE) const { - if (!myNeedsContRelationReady) { - initNeedsContRelation(); - assert(myNeedsContRelationReady); - } - return std::find(myNeedsContRelation.begin(), myNeedsContRelation.end(), - StreamPair(fromE, toE, otherFromE, otherToE)) != myNeedsContRelation.end(); -} - - -void -NBTrafficLightDefinition::initNeedsContRelation() const { - if (!amInvalid()) { - NBOwnTLDef dummy(DummyID, myControlledNodes, 0, TrafficLightType::STATIC); - dummy.initNeedsContRelation(); - myNeedsContRelation = dummy.myNeedsContRelation; - for (std::vector::const_iterator i = myControlledNodes.begin(); i != myControlledNodes.end(); i++) { - (*i)->removeTrafficLight(&dummy); - } - } - myNeedsContRelationReady = true; -} - - -bool -NBTrafficLightDefinition::rightOnRedConflict(int index, int foeIndex) const { - if (!myRightOnRedConflictsReady) { - NBOwnTLDef dummy(DummyID, myControlledNodes, 0, TrafficLightType::STATIC); - dummy.setParticipantsInformation(); - NBTrafficLightLogic* tllDummy = dummy.computeLogicAndConts(0, true); - delete tllDummy; - myRightOnRedConflicts = dummy.myRightOnRedConflicts; - for (std::vector::const_iterator i = myControlledNodes.begin(); i != myControlledNodes.end(); i++) { - (*i)->removeTrafficLight(&dummy); - } - myRightOnRedConflictsReady = true; - //std::cout << " rightOnRedConflicts tls=" << getID() << " pro=" << getProgramID() << "\n"; - //for (RightOnRedConflicts::const_iterator it = myRightOnRedConflicts.begin(); it != myRightOnRedConflicts.end(); ++it) { - // std::cout << " " << it->first << ", " << it->second << "\n"; - //} - } - return std::find(myRightOnRedConflicts.begin(), myRightOnRedConflicts.end(), std::make_pair(index, foeIndex)) != myRightOnRedConflicts.end(); -} - -std::string -NBTrafficLightDefinition::getDescription() const { - return getID() + ':' + getProgramID() + '@' + toString(this); -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netbuild/NBTrafficLightDefinition.h b/Util/OSM2ODR/src/netbuild/NBTrafficLightDefinition.h deleted file mode 100644 index 6237111e6..000000000 --- a/Util/OSM2ODR/src/netbuild/NBTrafficLightDefinition.h +++ /dev/null @@ -1,471 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2002-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NBTrafficLightDefinition.h -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date Sept 2002 -/// -// The base class for traffic light logic definitions -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "NBCont.h" -#include "NBConnection.h" -#include "NBConnectionDefs.h" -#include "NBLinkPossibilityMatrix.h" - - -// =========================================================================== -// class declarations -// =========================================================================== -class NBNode; -class OptionsCont; -class NBTrafficLightLogic; - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NBTrafficLightDefinition - * @brief The base class for traffic light logic definitions - * - * A base class is necessary, as we have two cases: a) the logic is given by - * the imported network, or b) the logic is not given and we have to compute - * it by ourselves. In the first case, NBLoadedTLDef should be used, in the - * second NBOwnTLDef. - * - * @see NBLoadedTLDef - * @see NBOwnTLDef - */ -class NBTrafficLightDefinition : public Named, public Parameterised { -public: - - static const SUMOTime UNSPECIFIED_DURATION; - static const std::string DefaultProgramID; - - /** - * @enum TLColor - * @brief An enumeration of possible tl-signal states - */ - enum TLColor { - /// @brief Signal shows red - TLCOLOR_RED, - /// @brief Signal shows yellow - TLCOLOR_YELLOW, - /// @brief Signal shows red/yellow (unused) - TLCOLOR_REDYELLOW, - /// @brief Signal shows green - TLCOLOR_GREEN, - /// @brief Signal is blinking yellow - TLCOLOR_BLINK - }; - - - /** @brief Constructor - * @param[in] id The id of the tls - * @param[in] junctions List of junctions controlled by this tls - * @param[in] programID The id of the added program ("subID") - * @param[in] offset The offset of the plan - * @param[in] type The algorithm type for the computed traffic light - */ - NBTrafficLightDefinition(const std::string& id, - const std::vector& junctions, - const std::string& programID, - SUMOTime offset, - TrafficLightType type); - - - /** @brief Constructor - * @param[in] id The id of the tls - * @param[in] junction The (single) junction controlled by this tls - * @param[in] programID The id of the added program ("subID") - * @param[in] offset The offset of the plan - * @param[in] type The algorithm type for the computed traffic light - */ - NBTrafficLightDefinition(const std::string& id, - NBNode* junction, - const std::string& programID, - SUMOTime offset, - TrafficLightType type); - - - /** @brief Constructor - * @param[in] id The id of the tls - * @param[in] programID The id of the added program ("subID") - * @param[in] offset The offset of the plan - * @param[in] type The algorithm type for the computed traffic light - */ - NBTrafficLightDefinition(const std::string& id, const std::string& programID, - SUMOTime offset, - TrafficLightType type); - - - /// @brief Destructor - virtual ~NBTrafficLightDefinition(); - - - /** @brief Computes the traffic light logic - * - * Does some initialisation at first, then calls myCompute to finally - * build the tl-logic - * - * @param[in] oc The options container holding options needed during the building - * @return The built logic (may be 0) - */ - NBTrafficLightLogic* compute(OptionsCont& oc); - - - - /// @name Access to controlled nodes - /// @{ - - /** @brief Adds a node to the traffic light logic - * @param[in] node A further node that shall be controlled by the tls - */ - virtual void addNode(NBNode* node); - - - /** @brief Removes the given node from the list of controlled nodes - * @param[in] node The node that shall not be controlled by the tls any more - */ - virtual void removeNode(NBNode* node); - - /** @brief removes the given connection from the traffic light - * if recontruct=true, reconstructs the logic and informs the edges for immediate use in NETEDIT - * @note: tlIndex is not necessarily unique. we need the whole connection data here - */ - virtual void removeConnection(const NBConnection& conn, bool reconstruct = true) { - UNUSED_PARAMETER(conn); - UNUSED_PARAMETER(reconstruct); - } - - /** @brief Returns the list of controlled nodes - * @return Controlled nodes - */ - const std::vector& getNodes() const { - return myControlledNodes; - } - /// @} - - - /** @brief Returns the information whether the described flow must let any other flow pass - * - * If the from/to connection passes only one junction (from is incoming into - * same node as to outgoes from) the node is asked whether the flow must brake- - * Otherwise true is returned (recheck!) - * "from" must be an incoming edge into one of the participating nodes! - * @param[in] from The connection's start edge - * @param[in] to The connection's end edge - * @return Whether the described connection must brake (has higher priorised foes) - */ - bool mustBrake(const NBEdge* const from, const NBEdge* const to) const; - - - /** @brief Returns the information whether the described flow must let the other flow pass - * @param[in] possProhibited The maybe prohibited connection - * @param[in] possProhibitor The maybe prohibiting connection - * @param[in] regardNonSignalisedLowerPriority Whether the right of way rules without traffic lights shall be regarded - * @return Whether the second flow prohibits the first one - * @see forbids - */ - bool mustBrake(const NBConnection& possProhibited, - const NBConnection& possProhibitor, - bool regardNonSignalisedLowerPriority) const; - - /** @brief Returns the information whether the described flow must let any other flow pass - * @param[in] possProhibitedFrom The maybe prohibited connection's begin - * @param[in] possProhibitedTo The maybe prohibited connection's end - * @param[in] possProhibitorFrom The maybe prohibiting connection's begin - * @param[in] possProhibitorTo The maybe prohibiting connection's end - * @param[in] regardNonSignalisedLowerPriority Whether the right of way rules without traffic lights shall be regarded - * @return Whether the second flow prohibits the first one - * @see forbids - */ - bool mustBrake(const NBEdge* const possProhibitedFrom, const NBEdge* const possProhibitedTo, - const NBEdge* const possProhibitorFrom, const NBEdge* const possProhibitorTo, - bool regardNonSignalisedLowerPriority) const; - - - /** @brief Returns the information whether "prohibited" flow must let "prohibitor" flow pass - * @param[in] possProhibitedFrom The maybe prohibited connection's begin - * @param[in] possProhibitedTo The maybe prohibited connection's end - * @param[in] possProhibitorFrom The maybe prohibiting connection's begin - * @param[in] possProhibitorTo The maybe prohibiting connection's end - * @param[in] regardNonSignalisedLowerPriority Whether the right of way rules without traffic lights shall be regarded - * @param[in] sameNodeOnly Whether the check shall only be performed if both edges are incoming to the same node - * @return Whether the second flow prohibits the first one - * @see forbids - */ - bool forbids(const NBEdge* const possProhibitorFrom, const NBEdge* const possProhibitorTo, - const NBEdge* const possProhibitedFrom, const NBEdge* const possProhibitedTo, - bool regardNonSignalisedLowerPriority, - bool sameNodeOnly = false) const; - - - /** @brief Returns the information whether the given flows cross - * @param[in] from1 The starting edge of the first stream - * @param[in] to1 The ending edge of the first stream - * @param[in] from2 The starting edge of the second stream - * @param[in] to2 The ending edge of the second stream - * @return Whether both stream are foes (cross) - */ - bool foes(const NBEdge* const from1, const NBEdge* const to1, - const NBEdge* const from2, const NBEdge* const to2) const; - - - /** @brief Informs edges about being controlled by a tls - */ - virtual void setTLControllingInformation() const = 0; - - - /** @brief Builds the list of participating nodes/edges/links - */ - virtual void setParticipantsInformation(); - - - /** @brief Adds the given ids into the list of inner edges controlled by the tls - * @param[in] edges The list of edge ids which shall be controlled despite lying with the jointly controlled node cluster - */ - void addControlledInnerEdges(const std::vector& edges); - - /** @brief Retrieve the ids of edges explicitly controlled by the tls - */ - std::vector getControlledInnerEdges() const; - - /** @brief Replaces occurences of the removed edge in incoming/outgoing edges of all definitions - * @param[in] removed The removed edge - * @param[in] incoming The edges to use instead if an incoming edge was removed - * @param[in] outgoing The edges to use instead if an outgoing edge was removed - */ - virtual void remapRemoved(NBEdge* removed, - const EdgeVector& incoming, const EdgeVector& outgoing) = 0; - - - /** @brief Replaces a removed edge/lane - * @param[in] removed The edge to replace - * @param[in] removedLane The lane of this edge to replace - * @param[in] by The edge to insert instead - * @param[in] byLane This edge's lane to insert instead - * @param[in] incoming Whether the removed edge is incoming or outgoing - */ - virtual void replaceRemoved(NBEdge* removed, int removedLane, - NBEdge* by, int byLane, bool incoming) = 0; - - /// @brief patches (loaded) signal plans by modifying lane indices - virtual void shiftTLConnectionLaneIndex(NBEdge* edge, int offset, int threshold = -1) { - UNUSED_PARAMETER(edge); - UNUSED_PARAMETER(offset); - UNUSED_PARAMETER(threshold); - } - - /** @brief Returns the list of incoming edges (must be build first) - * @return The edges which are incoming into the tls - */ - const EdgeVector& getIncomingEdges() const; - - - /// @brief returns the controlled links (depends on previous call to collectLinks) - const NBConnectionVector& getControlledLinks() const { - return myControlledLinks; - } - - - /// @brief returns the controlled links (non const version) - NBConnectionVector& getControlledLinks() { - return myControlledLinks; - } - - - /** @brief Returns the ProgramID - * @return The ID of the program (subID) - */ - const std::string& getProgramID() const { - return mySubID; - }; - - - /** @brief Sets the programID - * @param[in] programID The new ID of the program (subID) - */ - virtual void setProgramID(const std::string& programID) { - mySubID = programID; - } - - - /** @brief Returns the offset - * @return Offset - */ - SUMOTime getOffset() { - return myOffset; - } - - - /// @brief get the algorithm type (static etc..) - TrafficLightType getType() const { - return myType; - } - - /// @brief set the algorithm type (static etc..) - virtual void setType(TrafficLightType type) { - myType = type; - } - - /* @brief computes whether the given stream may have green minor while the - * other stream has green major in the same phase - */ - bool needsCont(const NBEdge* fromE, const NBEdge* toE, const NBEdge* otherFromE, const NBEdge* otherToE) const; - - /// @brief whether the given index must yield to the foeIndex while turning right on a red light - virtual bool rightOnRedConflict(int index, int foeIndex) const; - - /* initialize myNeedsContRelation and set myNeedsContRelationReady to true - * This information is a byproduct of NBOwnTLDef::myCompute. All other - * subclasses instantiate a private instance of NBOwnTLDef to answer this query */ - virtual void initNeedsContRelation() const; - - ///@brief Returns the maximum index controlled by this traffic light and assigned to a connection - virtual int getMaxIndex() = 0; - - ///@brief Returns the maximum index controlled by this traffic light - virtual int getMaxValidIndex() { - return getMaxIndex(); - } - - /** @brief Computes the time vehicles may need to brake - * - * This time depends on the maximum speed allowed on incoming junctions. - * It is computed as max_speed_allowed / minimum_vehicle_decleration - */ - int computeBrakingTime(double minDecel) const; - - /// @brief whether this definition uses signal group (multiple connections with the same link index) - virtual bool usingSignalGroups() const { - return false; - }; - - /// @brief get ID and programID together (for convenient debugging) - std::string getDescription() const; - - -protected: - /// @brief id for temporary definitions - static const std::string DummyID; - - /** @brief Computes the traffic light logic finally in dependence to the type - * @param[in] brakingTime Duration a vehicle needs for braking in front of the tls - * @return The computed logic - */ - virtual NBTrafficLightLogic* myCompute(int brakingTime) = 0; - - - /** @brief Collects the links participating in this traffic light - * @exception ProcessError If a link could not be found - */ - virtual void collectLinks() = 0; - - - /** @brief Build the list of participating edges - */ - virtual void collectEdges(); - - - // @return whether this traffic light is invalid and should be computed - virtual bool amInvalid() const; - - /// @brief helper method for use in NBOwnTLDef and NBLoadedSUMOTLDef - void collectAllLinks(NBConnectionVector& into); - -protected: - /// @brief The container with participating nodes - std::vector myControlledNodes; - - /// @brief The list of incoming edges - EdgeVector myIncomingEdges; - - /// @brief The list of edges within the area controlled by the tls - EdgeVector myEdgesWithin; - - /// @brief The list of controlled links - NBConnectionVector myControlledLinks; - - /// @brief Set of inner edges that shall be controlled, though - std::set myControlledInnerEdges; - - /// @brief The tls program's subid - std::string mySubID; - - /// @brief The offset in the program - SUMOTime myOffset; - - /// @brief The algorithm type for the traffic light - TrafficLightType myType; - - /// @brief data structure for caching needsCont information - struct StreamPair { - StreamPair(const NBEdge* _from1, const NBEdge* _to1, const NBEdge* _from2, const NBEdge* _to2): - from1(_from1), - to1(_to1), - from2(_from2), - to2(_to2) {} - - bool operator==(const StreamPair& o) const { - return (from1 == o.from1 && to1 == o.to1 - && from2 == o.from2 && to2 == o.to2); - } - - bool operator<(const StreamPair& o) const { - if (from1 != o.from1) { - return from1 < o.from1; - } - if (to1 != o.to1) { - return to1 < o.to1; - } - if (from2 != o.from2) { - return from2 < o.from2; - } - return to2 < o.to2; - } - - const NBEdge* from1; - const NBEdge* to1; - const NBEdge* from2; - const NBEdge* to2; - }; - typedef std::set NeedsContRelation; - mutable NeedsContRelation myNeedsContRelation; - mutable bool myNeedsContRelationReady; - - typedef std::set > RightOnRedConflicts; - mutable RightOnRedConflicts myRightOnRedConflicts; - mutable bool myRightOnRedConflictsReady; - -private: - static std::set collectReachable(EdgeVector outer, const EdgeVector& within, bool checkControlled); - - -}; diff --git a/Util/OSM2ODR/src/netbuild/NBTrafficLightLogic.cpp b/Util/OSM2ODR/src/netbuild/NBTrafficLightLogic.cpp deleted file mode 100644 index e04329f12..000000000 --- a/Util/OSM2ODR/src/netbuild/NBTrafficLightLogic.cpp +++ /dev/null @@ -1,235 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NBTrafficLightLogic.cpp -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date Sept 2002 -/// -// A SUMO-compliant built logic for a traffic light -/****************************************************************************/ -#include - -#include -#include -#include -#include -#include -#include -#include "NBEdge.h" -#include "NBEdgeCont.h" -#include "NBTrafficLightLogic.h" -#include "NBTrafficLightDefinition.h" -#include -#include -#include -#include -#include -#include - - -// =========================================================================== -// static members -// =========================================================================== - -// =========================================================================== -// member method definitions -// =========================================================================== -NBTrafficLightLogic::NBTrafficLightLogic(const std::string& id, - const std::string& subid, int noLinks, - SUMOTime offset, TrafficLightType type) : - Named(id), myNumLinks(noLinks), mySubID(subid), - myOffset(offset), - myType(type) {} - -NBTrafficLightLogic::NBTrafficLightLogic(const NBTrafficLightLogic* logic) : - Named(logic->getID()), - myNumLinks(logic->myNumLinks), - mySubID(logic->getProgramID()), - myOffset(logic->getOffset()), - myPhases(logic->myPhases.begin(), logic->myPhases.end()), - myType(logic->getType()) {} - - -NBTrafficLightLogic::~NBTrafficLightLogic() {} - -void -NBTrafficLightLogic::addStep(SUMOTime duration, const std::string& state, const std::vector& next, const std::string& name, int index) { - addStep(duration, state, - NBTrafficLightDefinition::UNSPECIFIED_DURATION, - NBTrafficLightDefinition::UNSPECIFIED_DURATION, - next, name, index); -} - -void -NBTrafficLightLogic::addStep(SUMOTime duration, const std::string& state, SUMOTime minDur, SUMOTime maxDur, const std::vector& next, const std::string& name, int index) { - // check state size - if (myNumLinks == 0) { - // initialize - myNumLinks = (int)state.size(); - } else if ((int)state.size() != myNumLinks) { - throw ProcessError("When adding phase to tlLogic '" + getID() + "': state length of " + toString(state.size()) + - " does not match declared number of links " + toString(myNumLinks)); - } - // check state contents - const std::string::size_type illegal = state.find_first_not_of(SUMOXMLDefinitions::ALLOWED_TLS_LINKSTATES); - if (std::string::npos != illegal) { - throw ProcessError("When adding phase: illegal character '" + toString(state[illegal]) + "' in state"); - } - // interpret index - if (index < 0 || index >= (int)myPhases.size()) { - // insert at the end - index = (int)myPhases.size(); - } - myPhases.insert(myPhases.begin() + index, PhaseDefinition(duration, state, minDur, maxDur, next, name)); -} - - -void -NBTrafficLightLogic::deletePhase(int index) { - if (index >= (int)myPhases.size()) { - throw InvalidArgument("Index " + toString(index) + " out of range for logic with " - + toString(myPhases.size()) + " phases."); - } - myPhases.erase(myPhases.begin() + index); -} - - -void -NBTrafficLightLogic::setStateLength(int numLinks, LinkState fill) { - if (myNumLinks > numLinks) { - for (PhaseDefinition& p : myPhases) { - p.state = p.state.substr(0, numLinks); - } - } else { - std::string add(numLinks - myNumLinks, (char)fill); - for (PhaseDefinition& p : myPhases) { - p.state = p.state + add; - } - } - myNumLinks = numLinks; -} - -void -NBTrafficLightLogic::deleteStateIndex(int index) { - assert(index >= 0); - assert(index < myNumLinks); - for (PhaseDefinition& p : myPhases) { - p.state.erase(index, 1); - } - myNumLinks--; -} - - -void -NBTrafficLightLogic::resetPhases() { - myNumLinks = 0; - myPhases.clear(); -} - - -SUMOTime -NBTrafficLightLogic::getDuration() const { - SUMOTime duration = 0; - for (PhaseDefinitionVector::const_iterator i = myPhases.begin(); i != myPhases.end(); ++i) { - duration += (*i).duration; - } - return duration; -} - - -void -NBTrafficLightLogic::closeBuilding(bool checkVarDurations) { - for (int i = 0; i < (int)myPhases.size() - 1;) { - if (myPhases[i].state != myPhases[i + 1].state || myPhases[i].next.size() > 0) { - ++i; - continue; - } - myPhases[i].duration += myPhases[i + 1].duration; - if (myPhases[i + 1].minDur != NBTrafficLightDefinition::UNSPECIFIED_DURATION) { - if (myPhases[i].minDur != NBTrafficLightDefinition::UNSPECIFIED_DURATION) { - myPhases[i].minDur += myPhases[i + 1].minDur; - } else { - myPhases[i].minDur = myPhases[i + 1].minDur; - } - } - if (myPhases[i + 1].maxDur != NBTrafficLightDefinition::UNSPECIFIED_DURATION) { - if (myPhases[i].maxDur != NBTrafficLightDefinition::UNSPECIFIED_DURATION) { - myPhases[i].maxDur += myPhases[i + 1].maxDur; - } else { - myPhases[i].maxDur = myPhases[i + 1].maxDur; - } - } - myPhases.erase(myPhases.begin() + i + 1); - } - // check if actuated lights are defined correctly - if (checkVarDurations) { - if (myType != TrafficLightType::STATIC) { - bool found = false; - for (auto p : myPhases) { - if (p.minDur != NBTrafficLightDefinition::UNSPECIFIED_DURATION - || p.maxDur != NBTrafficLightDefinition::UNSPECIFIED_DURATION) { - found = true; - break; - } - } - if (!found) { - WRITE_WARNING("Non-static traffic light '" + getID() + "' does not define variable phase length."); - } - } - } -} - - -void -NBTrafficLightLogic::setPhaseState(int phaseIndex, int tlIndex, LinkState linkState) { - assert(phaseIndex < (int)myPhases.size()); - std::string& phaseState = myPhases[phaseIndex].state; - assert(tlIndex < (int)phaseState.size()); - phaseState[tlIndex] = (char)linkState; -} - - -void -NBTrafficLightLogic::setPhaseDuration(int phaseIndex, SUMOTime duration) { - assert(phaseIndex < (int)myPhases.size()); - myPhases[phaseIndex].duration = duration; -} - -void -NBTrafficLightLogic::setPhaseMinDuration(int phaseIndex, SUMOTime duration) { - assert(phaseIndex < (int)myPhases.size()); - myPhases[phaseIndex].minDur = duration; -} - -void -NBTrafficLightLogic::setPhaseMaxDuration(int phaseIndex, SUMOTime duration) { - assert(phaseIndex < (int)myPhases.size()); - myPhases[phaseIndex].maxDur = duration; -} - -void -NBTrafficLightLogic::setPhaseNext(int phaseIndex, const std::vector& next) { - assert(phaseIndex < (int)myPhases.size()); - myPhases[phaseIndex].next = next; -} - -void -NBTrafficLightLogic::setPhaseName(int phaseIndex, const std::string& name) { - assert(phaseIndex < (int)myPhases.size()); - myPhases[phaseIndex].name = name; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netbuild/NBTrafficLightLogic.h b/Util/OSM2ODR/src/netbuild/NBTrafficLightLogic.h deleted file mode 100644 index d0f94b69c..000000000 --- a/Util/OSM2ODR/src/netbuild/NBTrafficLightLogic.h +++ /dev/null @@ -1,266 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NBTrafficLightLogic.h -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date Sept 2002 -/// -// A SUMO-compliant built logic for a traffic light -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include -#include -#include -#include "NBConnectionDefs.h" -#include -#include -#include - - -// =========================================================================== -// class declarations -// =========================================================================== -class OutputDevice; - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NBTrafficLightLogic - * @brief A SUMO-compliant built logic for a traffic light - */ -class NBTrafficLightLogic : public Named, public Parameterised { -public: - /** - * @class PhaseDefinition - * @brief The definition of a single phase of the logic - */ - class PhaseDefinition { - public: - /// @brief The duration of the phase in s - SUMOTime duration; - SUMOTime minDur; - SUMOTime maxDur; - - /// @brief The state definition - std::string state; - - /// @brief next phase indices or empty list - std::vector next; - /// @brief option phase name - std::string name; - - /** @brief Constructor - * @param[in] durationArg The duration of the phase - * @param[in] stateArg Signals per link - */ - PhaseDefinition(SUMOTime durationArg, const std::string& stateArg, SUMOTime minDurArg, SUMOTime maxDurArg, const std::vector& nextArg, const std::string& nameArg) : - duration(durationArg), - minDur(minDurArg), - maxDur(maxDurArg), - state(stateArg), - next(nextArg), - name(nameArg) - { } - - /// @brief Destructor - ~PhaseDefinition() { } - - /** @brief Comparison operator - * @param[in] pd A second phase - * @return Whether this and the given phases are same - */ - bool operator!=(const PhaseDefinition& pd) const { - return (pd.duration != duration - || pd.minDur != minDur - || pd.maxDur != maxDur - || pd.state != state - || pd.next != next - || pd.name != name); - } - - }; - - - /** @brief Constructor - * @param[in] id The id of the traffic light - * @param[in] subid The id of the program - * @param[in] noLinks Number of links that are controlled by this tls. 0 means the value is not known beforehand - * @param[in] offset The offset of the program (delay) - * @param[in] type The algorithm type for the computed traffic light - */ - NBTrafficLightLogic(const std::string& id, const std::string& subid, int noLinks, - SUMOTime offset = 0, TrafficLightType type = TrafficLightType::STATIC); - - - /** @brief Copy Constructor - * @param[in] logic The logic to copy - */ - NBTrafficLightLogic(const NBTrafficLightLogic* logic); - - - /// @brief Destructor - ~NBTrafficLightLogic(); - - - /** @brief Adds a phase to the logic - * - * @param[in] duration The duration of the phase to add - * @param[in] state The state definition of a tls phase - * @param[in] minDur The minimum duration of the phase to add - * @param[in] maxDur The maximum duration of the phase to add - * @param[in] name The name of the phase - * @param[in] next The index of the next phase - * @param[in] index The index of the new phase (-1 means append to end) - * @note: the length of the state has to match the number of links - * and the length given in previous calls to addStep (throws ProcessError) - */ - void addStep(SUMOTime duration, const std::string& state, - const std::vector& next = std::vector(), const std::string& name = "", int index = -1); - void addStep(SUMOTime duration, const std::string& state, SUMOTime minDur, SUMOTime maxDur, - const std::vector& next = std::vector(), const std::string& name = "", int index = -1); - - - /** @brief Modifies the state for an existing phase (used by NETEDIT) - * @param[in] phaseIndex The index of the phase to modify - * @param[in] tlIndex The index at which to modify the state - * @param[in] linkState The new link state for the given index - */ - void setPhaseState(int phaseIndex, int tlIndex, LinkState linkState); - - /** @brief Modifies the duration for an existing phase (used by NETEDIT) - * @param[in] phaseIndex The index of the phase to modify - * @param[in] duration The new duration for this phase - */ - void setPhaseDuration(int phaseIndex, SUMOTime duration); - void setPhaseMinDuration(int phaseIndex, SUMOTime duration); - void setPhaseMaxDuration(int phaseIndex, SUMOTime duration); - void setPhaseNext(int phaseIndex, const std::vector& next); - void setPhaseName(int phaseIndex, const std::string& name); - - /* @brief deletes the phase at the given index - * @note thhrows InvalidArgument on out-of range index - */ - void deletePhase(int index); - - /* @brief changes state size either by cutting of at the end or by adding - * new states at the end - */ - void setStateLength(int numLinks, LinkState fill = LINKSTATE_TL_RED); - - /// @brief remove the index from all phase states - void deleteStateIndex(int index); - - /* @brief deletes all phases and reset the expect number of links - */ - void resetPhases(); - - /** @brief closes the building process - * - * Joins equal steps. - */ - void closeBuilding(bool checkVarDurations = true); - - - /** @brief Returns the duration of the complete cycle - * @return The duration of this logic's cycle - */ - SUMOTime getDuration() const; - - - /** @brief Sets the offset of this tls - * @param[in] offset The offset of this cycle - */ - void setOffset(SUMOTime offset) { - myOffset = offset; - } - - - /** @brief Returns the ProgramID - * @return The ID of the program (subID) - */ - const std::string& getProgramID() const { - return mySubID; - }; - - - /** @brief Returns the phases - * @return The phase list - */ - const std::vector& getPhases() const { - return myPhases; - } - - - /** @brief Returns the offset of first switch - * @return The switch offset - */ - SUMOTime getOffset() const { - return myOffset; - }; - - - /** @brief Returns the number of participating links - */ - int getNumLinks() { - return myNumLinks; - } - - /// @brief get the algorithm type (static etc..) - TrafficLightType getType() const { - return myType; - } - - /// @brief set the algorithm type (static etc..) - void setType(TrafficLightType type) { - myType = type; - } - - /** @brief Sets the programID - * @param[in] programID The new ID of the program (subID) - */ - void setProgramID(const std::string& programID) { - mySubID = programID; - } - -private: - /// @brief The number of participating links - int myNumLinks; - - /// @brief The tls program's subid - std::string mySubID; - - /// @brief The tls program's offset - SUMOTime myOffset; - - /// @brief Definition of a vector of traffic light phases - typedef std::vector PhaseDefinitionVector; - - /// @brief The junction logic's storage for traffic light phase list - PhaseDefinitionVector myPhases; - - /// @brief The algorithm type for the traffic light - TrafficLightType myType; - -private: - /// @brief Invalidated assignment operator - NBTrafficLightLogic& operator=(const NBTrafficLightLogic& s); - -}; diff --git a/Util/OSM2ODR/src/netbuild/NBTrafficLightLogicCont.cpp b/Util/OSM2ODR/src/netbuild/NBTrafficLightLogicCont.cpp deleted file mode 100644 index 9eb60b9aa..000000000 --- a/Util/OSM2ODR/src/netbuild/NBTrafficLightLogicCont.cpp +++ /dev/null @@ -1,375 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NBTrafficLightLogicCont.cpp -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date Sept 2002 -/// -// A container for traffic light definitions and built programs -/****************************************************************************/ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "NBTrafficLightLogic.h" -#include "NBTrafficLightLogicCont.h" -#include "NBOwnTLDef.h" -#include "NBLoadedSUMOTLDef.h" -#include "NBEdgeCont.h" -#include "NBNodeCont.h" - - -// =========================================================================== -// static members -// =========================================================================== -const NBTrafficLightLogicCont::Program2Def NBTrafficLightLogicCont::EmptyDefinitions = NBTrafficLightLogicCont::Program2Def(); - -// =========================================================================== -// method definitions -// =========================================================================== -NBTrafficLightLogicCont::NBTrafficLightLogicCont() {} - - -NBTrafficLightLogicCont::~NBTrafficLightLogicCont() { - clear(); -} - - -void -NBTrafficLightLogicCont::applyOptions(OptionsCont& oc) { - // check whether any offsets shall be manipulated by setting - // them to half of the duration - if (oc.isSet("tls.half-offset")) { - std::vector ids = oc.getStringVector("tls.half-offset"); - myHalfOffsetTLS.insert(ids.begin(), ids.end()); - } - // check whether any offsets shall be manipulated by setting - // them to a quarter of the duration - if (oc.isSet("tls.quarter-offset")) { - std::vector ids = oc.getStringVector("tls.quarter-offset"); - myQuarterOffsetTLS.insert(ids.begin(), ids.end()); - } -} - - -bool -NBTrafficLightLogicCont::insert(NBTrafficLightDefinition* logic, bool forceInsert) { - myExtracted.erase(logic); - if (myDefinitions.count(logic->getID())) { - if (myDefinitions[logic->getID()].count(logic->getProgramID())) { - if (forceInsert) { - const Program2Def& programs = myDefinitions[logic->getID()]; - IDSupplier idS("", 0); - for (Program2Def::const_iterator it_prog = programs.begin(); it_prog != programs.end(); it_prog++) { - idS.avoid(it_prog->first); - } - logic->setProgramID(idS.getNext()); - } else { - return false; - } - } - } else { - myDefinitions[logic->getID()] = Program2Def(); - } - myDefinitions[logic->getID()][logic->getProgramID()] = logic; - return true; -} - - -bool -NBTrafficLightLogicCont::removeFully(const std::string id) { - if (myDefinitions.count(id)) { - // delete all programs - for (Program2Def::iterator i = myDefinitions[id].begin(); i != myDefinitions[id].end(); i++) { - delete i->second; - } - myDefinitions.erase(id); - // also delete any logics that were already computed - if (myComputed.count(id)) { - for (Program2Logic::iterator i = myComputed[id].begin(); i != myComputed[id].end(); i++) { - delete i->second; - } - myComputed.erase(id); - } - return true; - } else { - return false; - } -} - - -bool -NBTrafficLightLogicCont::removeProgram(const std::string id, const std::string programID, bool del) { - if (myDefinitions.count(id) && myDefinitions[id].count(programID)) { - if (del) { - delete myDefinitions[id][programID]; - } - myDefinitions[id].erase(programID); - return true; - } else { - return false; - } -} - - -void -NBTrafficLightLogicCont::extract(NBTrafficLightDefinition* definition) { - myExtracted.insert(definition); - removeProgram(definition->getID(), definition->getProgramID(), false); -} - - -std::pair -NBTrafficLightLogicCont::computeLogics(OptionsCont& oc) { - // clean previous logics - Logics logics = getComputed(); - for (Logics::iterator it = logics.begin(); it != logics.end(); it++) { - delete *it; - } - myComputed.clear(); - - if (oc.getBool("tls.group-signals")) { - // replace NBOwnTLDef tld with NBLoadedSUMOTLDef - for (NBTrafficLightDefinition* def : getDefinitions()) { - NBLoadedSUMOTLDef* lDef = dynamic_cast(def); - if (lDef == nullptr) { - NBTrafficLightLogic* logic = def->compute(oc); - if (logic != nullptr) { - lDef = new NBLoadedSUMOTLDef(*def, *logic); - lDef->setParticipantsInformation(); - for (NBNode* node : lDef->getNodes()) { - node->removeTrafficLight(def); - node->addTrafficLight(lDef); - } - removeProgram(def->getID(), def->getProgramID()); - insert(lDef); - } - } - if (lDef != nullptr) { - lDef->groupSignals(); - } - } - } else if (oc.getBool("tls.ungroup-signals")) { - for (NBTrafficLightDefinition* def : getDefinitions()) { - NBLoadedSUMOTLDef* lDef = dynamic_cast(def); - // NBOwnTLDef are always ungrouped - if (lDef != nullptr) { - if (lDef->usingSignalGroups()) { - lDef->ungroupSignals(); - } - } - } - } - int numPrograms = 0; - for (NBTrafficLightDefinition* def : getDefinitions()) { - if (computeSingleLogic(oc, def)) { - numPrograms++; - } - } - return std::pair((int)myComputed.size(), numPrograms); -} - - -bool -NBTrafficLightLogicCont::computeSingleLogic(OptionsCont& oc, NBTrafficLightDefinition* def) { - if (def->getNodes().size() == 0) { - return false; - } - const std::string& id = def->getID(); - const std::string& programID = def->getProgramID(); - // build program - NBTrafficLightLogic* built = def->compute(oc); - if (built == nullptr) { - WRITE_WARNING("Could not build program '" + programID + "' for traffic light '" + id + "'"); - return false; - } - // compute offset - SUMOTime T = built->getDuration(); - if (myHalfOffsetTLS.count(id)) { - built->setOffset(TIME2STEPS(floor(STEPS2TIME(T / 2.)))); - } - if (myQuarterOffsetTLS.count(id)) { - built->setOffset(TIME2STEPS(floor(STEPS2TIME(T / 4.)))); - } - // and insert the result after computation - // make sure we don't leak memory if computeSingleLogic is called externally - if (myComputed[id][programID] != nullptr) { - delete myComputed[id][programID]; - } - myComputed[id][programID] = built; - return true; -} - - -void -NBTrafficLightLogicCont::clear() { - Definitions definitions = getDefinitions(); - for (Definitions::iterator it = definitions.begin(); it != definitions.end(); it++) { - delete *it; - } - myDefinitions.clear(); - Logics logics = getComputed(); - for (Logics::iterator it = logics.begin(); it != logics.end(); it++) { - delete *it; - } - myComputed.clear(); - for (std::set::iterator it = myExtracted.begin(); it != myExtracted.end(); it++) { - delete *it; - } - myExtracted.clear(); -} - - -void -NBTrafficLightLogicCont::remapRemoved(NBEdge* removed, const EdgeVector& incoming, - const EdgeVector& outgoing) { - Definitions definitions = getDefinitions(); - for (Definitions::iterator it = definitions.begin(); it != definitions.end(); it++) { - (*it)->remapRemoved(removed, incoming, outgoing); - } -} - - -void -NBTrafficLightLogicCont::replaceRemoved(NBEdge* removed, int removedLane, - NBEdge* by, int byLane, bool incoming) { - Definitions definitions = getDefinitions(); - for (Definitions::iterator it = definitions.begin(); it != definitions.end(); it++) { - (*it)->replaceRemoved(removed, removedLane, by, byLane, incoming); - } -} - - -NBTrafficLightDefinition* -NBTrafficLightLogicCont::getDefinition(const std::string& id, const std::string& programID) const { - Id2Defs::const_iterator i = myDefinitions.find(id); - if (i != myDefinitions.end()) { - Program2Def programs = i->second; - Program2Def::const_iterator i2 = programs.find(programID); - if (i2 != programs.end()) { - return i2->second; - } - } - return nullptr; -} - -const NBTrafficLightLogicCont::Program2Def& -NBTrafficLightLogicCont::getPrograms(const std::string& id) const { - Id2Defs::const_iterator it = myDefinitions.find(id); - if (it != myDefinitions.end()) { - return it->second; - } else { - return EmptyDefinitions; - } -} - - -NBTrafficLightLogic* -NBTrafficLightLogicCont::getLogic(const std::string& id, const std::string& programID) const { - Id2Logics::const_iterator i = myComputed.find(id); - if (i != myComputed.end()) { - Program2Logic programs = i->second; - Program2Logic::const_iterator i2 = programs.find(programID); - if (i2 != programs.end()) { - return i2->second; - } - } - return nullptr; -} - - -void -NBTrafficLightLogicCont::setTLControllingInformation(const NBEdgeCont& ec, const NBNodeCont& nc) { - Definitions definitions = getDefinitions(); - // set the information about all participants, first - for (Definitions::iterator it = definitions.begin(); it != definitions.end(); it++) { - (*it)->setParticipantsInformation(); - } - // clear previous information because tlDefs may have been removed in NETEDIT - ec.clearControllingTLInformation(); - // insert the information about the tl-controlling - for (Definitions::iterator it = definitions.begin(); it != definitions.end(); it++) { - (*it)->setTLControllingInformation(); - } - // handle rail signals which are not instantiated as normal definitions - for (std::map::const_iterator it = nc.begin(); it != nc.end(); it ++) { - NBNode* n = it->second; - if (n->getType() == SumoXMLNodeType::RAIL_SIGNAL || n->getType() == SumoXMLNodeType::RAIL_CROSSING) { - NBOwnTLDef dummy(n->getID(), n, 0, TrafficLightType::STATIC); - dummy.setParticipantsInformation(); - dummy.setTLControllingInformation(); - n->setCrossingTLIndices(dummy.getID(), (int)dummy.getControlledLinks().size()); - n->removeTrafficLight(&dummy); - } - } -} - - -void -NBTrafficLightLogicCont::setOpenDriveSignalParameters() { - Definitions definitions = getDefinitions(); - for (NBTrafficLightDefinition* def : getDefinitions()) { - std::map defaultSignalIDs; - for (const NBConnection& con : def->getControlledLinks()) { - const NBEdge::Connection& c = con.getFrom()->getConnection(con.getFromLane(), con.getTo(), con.getToLane()); - if (c.knowsParameter("signalID")) { - defaultSignalIDs[con.getFrom()] = c.getParameter("signalID"); - def->setParameter("linkSignalID:" + toString(con.getTLIndex()), c.getParameter("signalID")); - } - } - // oftentimes, signals are placed on connecting road but are meant to apply to all connections from the incoming edge - for (const NBConnection& con : def->getControlledLinks()) { - const NBEdge::Connection& c = con.getFrom()->getConnection(con.getFromLane(), con.getTo(), con.getToLane()); - if (!c.knowsParameter("signalID") && defaultSignalIDs.count(con.getFrom()) != 0) { - WRITE_WARNINGF("Guessing signalID for link index % at traffic light '%'.", con.getTLIndex(), def->getID()); - def->setParameter("linkSignalID:" + toString(con.getTLIndex()), defaultSignalIDs[con.getFrom()]); - } - } - } -} - - -NBTrafficLightLogicCont::Logics -NBTrafficLightLogicCont::getComputed() const { - Logics result; - for (Id2Logics::const_iterator it_id = myComputed.begin(); it_id != myComputed.end(); it_id++) { - const Program2Logic& programs = it_id->second; - for (Program2Logic::const_iterator it_prog = programs.begin(); it_prog != programs.end(); it_prog++) { - result.push_back(it_prog->second); - } - } - return result; -} - - -NBTrafficLightLogicCont::Definitions -NBTrafficLightLogicCont::getDefinitions() const { - Definitions result; - for (Id2Defs::const_iterator it_id = myDefinitions.begin(); it_id != myDefinitions.end(); it_id++) { - const Program2Def& programs = it_id->second; - for (Program2Def::const_iterator it_prog = programs.begin(); it_prog != programs.end(); it_prog++) { - result.push_back(it_prog->second); - } - } - return result; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netbuild/NBTrafficLightLogicCont.h b/Util/OSM2ODR/src/netbuild/NBTrafficLightLogicCont.h deleted file mode 100644 index 5d6bb2f8e..000000000 --- a/Util/OSM2ODR/src/netbuild/NBTrafficLightLogicCont.h +++ /dev/null @@ -1,246 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NBTrafficLightLogicCont.h -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date Sept 2002 -/// -// A container for traffic light definitions and built programs -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include "NBTrafficLightDefinition.h" - - -// =========================================================================== -// class declarations -// =========================================================================== -class OptionsCont; -class NBEdgeCont; -class OutputDevice; - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NBTrafficLightLogicCont - * @brief A container for traffic light definitions and built programs - * - * This container class holds definitions of traffic light logics during - * the loading of the network. After all information has been loaded, these - * definitions are used to build the traffic light logics. - * - * The built traffic light logics are kept stored within this container during - * their building and written to the network file at the end. - * - * @see NBTrafficLightDefinition - * @see NBTrafficLightLogic - */ -class NBTrafficLightLogicCont { -public: - /// @brief Constructor - NBTrafficLightLogicCont(); - - /// @brief Destructor - ~NBTrafficLightLogicCont(); - - /** @brief Initialises the storage by applying given options - * - * Options, mainly setting offsets, are parsed - * and the according internal variables are set. - * - * @param[in] oc The options container to read options from - * @todo Recheck exceptions - */ - void applyOptions(OptionsCont& oc); - - - /** @brief Adds a logic definition to the dictionary - * - * "true" is returned if the logic is accepted - no logic with the same - * name and programID exists within this container. - * - * @param[in] logic The logic to add - * @param[in] forceInsert If true, rename the program to make insertion succeed - * @return Whether the logic was valid (no logic with the same id and programID is already known) - */ - bool insert(NBTrafficLightDefinition* logic, bool forceInsert = false); - - - /** @brief Removes a logic definition (and all programs) from the dictionary - * - * "true" is returned if the logic existed in the dictionary, - * otherwise "false". - * - * @param[in] id The id of the logic to remove - * @return Whether the named logic was within the dictionary - */ - bool removeFully(const std::string id); - - - /** @brief Removes a program of a logic definition from the dictionary - * - * "true" is returned if the program existed in the dictionary, - * otherwise "false". - * - * @param[in] id The id of the logic - * @param[in] programID The id of the program to remove - * @param[in] del Whether the definition shall be deleted - * @return Whether the program was within the dictionary - */ - bool removeProgram(const std::string id, const std::string programID, bool del = true); - - - /** @brief Extracts a traffic light definition from myDefinitions - * but keeps it in myExtracted for eventual * deletion (used by NETEDIT) - */ - void extract(NBTrafficLightDefinition* definition); - - - /// @brief return the number of extracted traffic light definitions - int getNumExtracted() const { - return (int)myExtracted.size(); - } - - - /// @brief Returns a list of all computed logics - std::vector getComputed() const; - - - /** @brief Computes the traffic light logics using the stored definitions and stores the results - * - * Goes through all stored definitions and calls "NBTrafficLightDefinition::compute" - * for each. Stores the result using "insert". - * - * @param[in] oc Options used during the computation - * @return The number of computed tls and programs - * @see NBTrafficLightDefinition::compute - */ - std::pair computeLogics(OptionsCont& oc); - - - /** @brief Computes a specific traffic light logic (using by NETEDIT) - * - * @param[in] oc Options used during the computation - * @return whether the logic was computed successfully - * @see NBTrafficLightDefinition::compute - */ - bool computeSingleLogic(OptionsCont& oc, NBTrafficLightDefinition* def); - - - /** @brief Replaces occurences of the removed edge in incoming/outgoing edges of all definitions - * - * @param[in] removed The removed edge - * @param[in] incoming The edges to use instead if an incoming edge was removed - * @param[in] outgoing The edges to use instead if an outgoing edge was removed - * @todo Recheck usage - */ - void remapRemoved(NBEdge* removed, - const EdgeVector& incoming, const EdgeVector& outgoing); - - - /** @brief Replaces occurences of the removed edge/lane in all definitions by the given edge - * - * @param[in] removed The removed edge - * @param[in] removed The removed lane - * @param[in] by The edge to use instead - * @param[in] byLane The lane to use instead - * @todo Recheck usage - */ - void replaceRemoved(NBEdge* removed, int removedLane, - NBEdge* by, int byLane, bool incoming); - - - /** @brief Returns the named definition - * - * @param[in] id The id of the definition to return - * @param[in] programID The id of the program to return - * @return The named definition, 0 if it is not known - */ - NBTrafficLightDefinition* getDefinition(const std::string& id, const std::string& programID) const; - - - /** @brief Returns all programs for the given tl-id - * - * @param[in] id The tl-id for which to return all programs - * @return The map of programIDs to definitions - */ - const std::map& getPrograms(const std::string& id) const; - - - /** @brief Returns the computed logic for the given name - * - * @param[in] id The id of the logic to return - * @param[in] programID The id of the program to return - * @return The named definition, 0 if it is not known - */ - NBTrafficLightLogic* getLogic(const std::string& id, const std::string& programID) const; - - - /** @brief Informs the edges about being controlled by a tls - * - * Goes through all definition, calling eachs "setParticipantsInformation" method. - * Goes through all definition, calling eachs "setTLControllingInformation" method. - * - * @param[in] ec The ede control to set information into - * @see NBTrafficLightDefinition::setParticipantsInformation - * @see NBTrafficLightDefinition::setTLControllingInformation - */ - void setTLControllingInformation(const NBEdgeCont& ec, const NBNodeCont& nc); - - /// @brief set OpenDRIVE signal reference parameters after all link indices are known - void setOpenDriveSignalParameters(); - - /// @brief Returns a list of all definitions (convenience for easier iteration) - typedef std::vector Definitions; - Definitions getDefinitions() const; - -private: - /// @brief Definition of internal the container types - typedef std::map Program2Logic; - typedef std::map Id2Logics; - typedef std::map Program2Def; - typedef std::map Id2Defs; - typedef std::vector Logics; - - /// @brief The container for previously computed tl-logics - Id2Logics myComputed; - - /// @brief The container for tl-ids to their definitions - Id2Defs myDefinitions; - - /// @brief The container for extracted definitions - std::set myExtracted; - - /// @brief List of tls which shall have an offset of T/2 - std::set myHalfOffsetTLS; - - /// @brief List of tls which shall have an offset of T/2 - std::set myQuarterOffsetTLS; - - static const Program2Def EmptyDefinitions; - -private: - - /** @brief Destroys all stored definitions and logics - */ - void clear(); - - -}; diff --git a/Util/OSM2ODR/src/netbuild/NBTypeCont.cpp b/Util/OSM2ODR/src/netbuild/NBTypeCont.cpp deleted file mode 100644 index 1b3168b7e..000000000 --- a/Util/OSM2ODR/src/netbuild/NBTypeCont.cpp +++ /dev/null @@ -1,253 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NBTypeCont.cpp -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @author Walter Bamberger -/// @date Tue, 20 Nov 2001 -/// -// A storage for the available types of an edge -/****************************************************************************/ -#include - -#include -#include -#include -#include -#include -#include -#include "NBTypeCont.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -void -NBTypeCont::setDefaults(int defaultNumLanes, - double defaultLaneWidth, - double defaultSpeed, - int defaultPriority, - SVCPermissions defaultPermissions) { - myDefaultType.numLanes = defaultNumLanes; - myDefaultType.width = defaultLaneWidth; - myDefaultType.speed = defaultSpeed; - myDefaultType.priority = defaultPriority; - myDefaultType.permissions = defaultPermissions; -} - - -void -NBTypeCont::insert(const std::string& id, int numLanes, double maxSpeed, int prio, - SVCPermissions permissions, double width, bool oneWayIsDefault, - double sidewalkWidth, double bikeLaneWidth, - double widthResolution, - double maxWidth, - double minWidth) { - - TypeDefinition newType(numLanes, maxSpeed, prio, width, permissions, oneWayIsDefault, sidewalkWidth, bikeLaneWidth, widthResolution, maxWidth, minWidth); - TypesCont::iterator old = myTypes.find(id); - if (old != myTypes.end()) { - newType.restrictions.insert(old->second.restrictions.begin(), old->second.restrictions.end()); - newType.attrs.insert(old->second.attrs.begin(), old->second.attrs.end()); - } - myTypes[id] = newType; -} - - -bool -NBTypeCont::knows(const std::string& type) const { - return myTypes.find(type) != myTypes.end(); -} - - -bool -NBTypeCont::markAsToDiscard(const std::string& id) { - TypesCont::iterator i = myTypes.find(id); - if (i == myTypes.end()) { - return false; - } - (*i).second.discard = true; - return true; -} - - -bool -NBTypeCont::markAsSet(const std::string& id, const SumoXMLAttr attr) { - TypesCont::iterator i = myTypes.find(id); - if (i == myTypes.end()) { - return false; - } - (*i).second.attrs.insert(attr); - return true; -} - - -bool -NBTypeCont::addRestriction(const std::string& id, const SUMOVehicleClass svc, const double speed) { - TypesCont::iterator i = myTypes.find(id); - if (i == myTypes.end()) { - return false; - } - (*i).second.restrictions[svc] = speed; - return true; -} - - -bool -NBTypeCont::copyRestrictionsAndAttrs(const std::string& fromId, const std::string& toId) { - TypesCont::iterator from = myTypes.find(fromId); - TypesCont::iterator to = myTypes.find(toId); - if (from == myTypes.end() || to == myTypes.end()) { - return false; - } - to->second.restrictions.insert(from->second.restrictions.begin(), from->second.restrictions.end()); - to->second.attrs.insert(from->second.attrs.begin(), from->second.attrs.end()); - return true; -} - - -void -NBTypeCont::writeTypes(OutputDevice& into) const { - for (TypesCont::const_iterator i = myTypes.begin(); i != myTypes.end(); ++i) { - into.openTag(SUMO_TAG_TYPE); - into.writeAttr(SUMO_ATTR_ID, i->first); - const NBTypeCont::TypeDefinition& type = i->second; - if (type.attrs.count(SUMO_ATTR_PRIORITY) > 0) { - into.writeAttr(SUMO_ATTR_PRIORITY, type.priority); - } - if (type.attrs.count(SUMO_ATTR_NUMLANES) > 0) { - into.writeAttr(SUMO_ATTR_NUMLANES, type.numLanes); - } - if (type.attrs.count(SUMO_ATTR_SPEED) > 0) { - into.writeAttr(SUMO_ATTR_SPEED, type.speed); - } - if (type.attrs.count(SUMO_ATTR_DISALLOW) > 0 || type.attrs.count(SUMO_ATTR_ALLOW) > 0) { - writePermissions(into, type.permissions); - } - if (type.attrs.count(SUMO_ATTR_ONEWAY) > 0) { - into.writeAttr(SUMO_ATTR_ONEWAY, type.oneWay); - } - if (type.attrs.count(SUMO_ATTR_DISCARD) > 0) { - into.writeAttr(SUMO_ATTR_DISCARD, type.discard); - } - if (type.attrs.count(SUMO_ATTR_WIDTH) > 0) { - into.writeAttr(SUMO_ATTR_WIDTH, type.width); - } - if (type.attrs.count(SUMO_ATTR_SIDEWALKWIDTH) > 0) { - into.writeAttr(SUMO_ATTR_SIDEWALKWIDTH, type.sidewalkWidth); - } - if (type.attrs.count(SUMO_ATTR_BIKELANEWIDTH) > 0) { - into.writeAttr(SUMO_ATTR_BIKELANEWIDTH, type.bikeLaneWidth); - } - for (std::map::const_iterator j = type.restrictions.begin(); j != type.restrictions.end(); ++j) { - into.openTag(SUMO_TAG_RESTRICTION); - into.writeAttr(SUMO_ATTR_VCLASS, getVehicleClassNames(j->first)); - into.writeAttr(SUMO_ATTR_SPEED, j->second); - into.closeTag(); - } - into.closeTag(); - } - if (!myTypes.empty()) { - into.lf(); - } -} - - -// ------------ Type-dependant Retrieval methods -int -NBTypeCont::getNumLanes(const std::string& type) const { - return getType(type).numLanes; -} - - -double -NBTypeCont::getSpeed(const std::string& type) const { - return getType(type).speed; -} - - -int -NBTypeCont::getPriority(const std::string& type) const { - return getType(type).priority; -} - - -bool -NBTypeCont::getIsOneWay(const std::string& type) const { - return getType(type).oneWay; -} - - -bool -NBTypeCont::getShallBeDiscarded(const std::string& type) const { - return getType(type).discard; -} - -double -NBTypeCont::getWidthResolution(const std::string& type) const { - return getType(type).widthResolution; -} - -double -NBTypeCont::getMaxWidth(const std::string& type) const { - return getType(type).maxWidth; -} - -double -NBTypeCont::getMinWidth(const std::string& type) const { - return getType(type).minWidth; -} - -bool -NBTypeCont::wasSet(const std::string& type, const SumoXMLAttr attr) const { - return getType(type).attrs.count(attr) > 0; -} - - -SVCPermissions -NBTypeCont::getPermissions(const std::string& type) const { - return getType(type).permissions; -} - - -double -NBTypeCont::getWidth(const std::string& type) const { - return getType(type).width; -} - - -double -NBTypeCont::getSidewalkWidth(const std::string& type) const { - return getType(type).sidewalkWidth; -} - - -double -NBTypeCont::getBikeLaneWidth(const std::string& type) const { - return getType(type).bikeLaneWidth; -} - - -const NBTypeCont::TypeDefinition& -NBTypeCont::getType(const std::string& name) const { - TypesCont::const_iterator i = myTypes.find(name); - if (i == myTypes.end()) { - return myDefaultType; - } - return (*i).second; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netbuild/NBTypeCont.h b/Util/OSM2ODR/src/netbuild/NBTypeCont.h deleted file mode 100644 index f9f64ec75..000000000 --- a/Util/OSM2ODR/src/netbuild/NBTypeCont.h +++ /dev/null @@ -1,352 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NBTypeCont.h -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Sascha Krieg -/// @author Michael Behrisch -/// @author Walter Bamberger -/// @date Tue, 20 Nov 2001 -/// -// A storage for available types of edges -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include -#include - - -// =========================================================================== -// class declarations -// =========================================================================== -class OutputDevice; - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NBTypeCont - * @brief A storage for available types of edges - * - * NBTypeCont stores properties of edge-types of edges. Additionally, a default - * type is stored which is used if no type information is given. - * - * This structure also contains a structure for determining node types using edge - * speeds. - */ -class NBTypeCont { -public: - /// @brief Constructor - NBTypeCont() {} - - - /// @brief Destructor - ~NBTypeCont() {} - - - /** @brief Sets the default values - * @param[in] defaultNumLanes The default number of lanes an edge has - * @param[in] defaultLaneWidth The default width of lanes - * @param[in] defaultSpeed The default speed allowed on an edge - * @param[in] defaultPriority The default priority of an edge - * @param[in] defaultPermissions The default permissions of an edge - */ - void setDefaults(int defaultNumLanes, double defaultLaneWidth, - double defaultSpeed, int defaultPriority, - SVCPermissions defaultPermissions); - - - /** @brief Adds a type into the list - * @param[in] id The id of the type - * @param[in] numLanes The number of lanes an edge of this type has - * @param[in] maxSpeed The speed allowed on an edge of this type - * @param[in] prio The priority of an edge of this type - * @param[in] permissions The encoding of vehicle classes allowed on an edge of this type - * @param[in] width The width of lanes of edgesof this type - * @param[in] oneWayIsDefault Whether edges of this type are one-way per default - * @return Whether the type could be added (no type with the same id existed) - */ - void insert(const std::string& id, int numLanes, - double maxSpeed, int prio, - SVCPermissions permissions, - double width, bool oneWayIsDefault, - double sidewalkWidth, - double bikeLaneWidth, - double widthResolution, - double maxWidth, - double minWidth); - - /** @brief Returns the number of known types - * @return The number of known edge types (excluding the default) - */ - int size() const { - return (int) myTypes.size(); - } - - - /** @brief Returns whether the named type is in the container - * @return Whether the named type is known - */ - bool knows(const std::string& type) const; - - - /** @brief Marks a type as to be discarded - * @param[in] id The id of the type - */ - bool markAsToDiscard(const std::string& id); - - /** @brief Marks an attribute of a type as set - * @param[in] id The id of the type - * @param[in] attr The id of the attribute - */ - bool markAsSet(const std::string& id, const SumoXMLAttr attr); - - /** @brief Adds a restriction to a type - * @param[in] id The id of the type - * @param[in] svc The vehicle class the restriction refers to - * @param[in] speed The restricted speed - */ - bool addRestriction(const std::string& id, const SUMOVehicleClass svc, const double speed); - - /** @brief Copy restrictions to a type - * @param[in] fromId The id of the source type - * @param[in] toId The id of the destination type - */ - bool copyRestrictionsAndAttrs(const std::string& fromId, const std::string& toId); - - /// @brief writes all types a s XML - void writeTypes(OutputDevice& into) const; - - /// @name Type-dependant Retrieval methods - /// @{ - - /** @brief Returns the number of lanes for the given type - * - * If the named type is not known, the default is returned - * @param[in] type The name of the type to return the lane number for - * @return The number of lanes an edge of this type has - */ - int getNumLanes(const std::string& type) const; - - - /** @brief Returns the maximal velocity for the given type [m/s] - * - * If the named type is not known, the default is returned - * @param[in] type The name of the type to return the speed for - * @return The allowed speed on edges of this type - */ - double getSpeed(const std::string& type) const; - - - /** @brief Returns the priority for the given type - * - * If the named type is not known, the default is returned - * @param[in] type The name of the type to return the priority for - * @return The priority of edges of this type - */ - int getPriority(const std::string& type) const; - - - /** @brief Returns whether edges are one-way per default for the given type - * - * If the named type is not known, the default is returned - * @param[in] type The name of the type to return the one-way information for - * @return Whether edges of this type are one-way per default - * @todo There is no default for one-way!? - */ - bool getIsOneWay(const std::string& type) const; - - - /** @brief Returns the information whether edges of this type shall be discarded. - * - * Returns false if the type is not known. - * @param[in] type The id of the type - * @return Whether edges of this type shall be discarded. - */ - bool getShallBeDiscarded(const std::string& type) const; - - /** @brief Returns the resolution for interpreting edge/lane widths of the given - * type - * - * If the named type is not known, the default is returned - * @param[in] type The name of the type to return the width resolution for - * @return The width resolution on edges of this type - */ - double getWidthResolution(const std::string& type) const; - - /** @brief Returns the maximum edge/lane widths of the given - * type - * - * If the named type is not known, the default is returned - * @param[in] type The name of the type to return the maximum width for - * @return The maximum width on edges of this type - */ - double getMaxWidth(const std::string& type) const; - - /** @brief Returns the minimum edge/lane widths of the given - * type - * - * If the named type is not known, the default is returned - * @param[in] type The name of the type to return the maximum width for - * @return The minimum width on edges of this type - */ - double getMinWidth(const std::string& type) const; - - - /** @brief Returns whether an attribute of a type was set - * @param[in] type The id of the type - * @param[in] attr The id of the attribute - * @return Whether the attribute was set - */ - bool wasSet(const std::string& type, const SumoXMLAttr attr) const; - - - /** @brief Returns allowed vehicle classes for the given type - * - * If the named type is not known, the default is returned - * @param[in] type The name of the type to return the list of allowed vehicles classes for - * @return List of vehicles class which may use edges of the given type - */ - SVCPermissions getPermissions(const std::string& type) const; - - - /** @brief Returns the lane width for the given type [m] - * - * If the named type is not known, the default is returned - * @param[in] type The name of the type to return the width for - * @return The width of lanes of edges of this type - */ - double getWidth(const std::string& type) const; - - - /** @brief Returns the lane width for a sidewalk to be added [m] - * - * If the named type is not known, the default is returned - * @param[in] type The name of the type to return the width for - * @return The width of lanes of edges of this type - */ - double getSidewalkWidth(const std::string& type) const; - - - /** @brief Returns the lane width for a bike lane to be added [m] - * - * If the named type is not known, the default is returned - * @param[in] type The name of the type to return the width for - * @return The width of lanes of edges of this type - */ - double getBikeLaneWidth(const std::string& type) const; - /// @} - - -private: - struct TypeDefinition { - /// @brief Constructor - TypeDefinition() : - numLanes(1), speed((double) 13.89), priority(-1), - permissions(SVC_UNSPECIFIED), - oneWay(true), discard(false), - width(NBEdge::UNSPECIFIED_WIDTH), - widthResolution(0), - maxWidth(0), - minWidth(0), - sidewalkWidth(NBEdge::UNSPECIFIED_WIDTH), - bikeLaneWidth(NBEdge::UNSPECIFIED_WIDTH) { - } - - /// @brief Constructor - TypeDefinition(int _numLanes, double _speed, int _priority, - double _width, SVCPermissions _permissions, bool _oneWay, - double _sideWalkWidth, - double _bikeLaneWidth, - double _widthResolution, - double _maxWidth, - double _minWidth) : - numLanes(_numLanes), speed(_speed), priority(_priority), - permissions(_permissions), - oneWay(_oneWay), discard(false), - width(_width), - widthResolution(_widthResolution), - maxWidth(_maxWidth), - minWidth(_minWidth), - sidewalkWidth(_sideWalkWidth), - bikeLaneWidth(_bikeLaneWidth) { - } - - /// @brief The number of lanes of an edge - int numLanes; - /// @brief The maximal velocity on an edge in m/s - double speed; - /// @brief The priority of an edge - int priority; - /// @brief List of vehicle types that are allowed on this edge - SVCPermissions permissions; - /// @brief Whether one-way traffic is mostly common for this type (mostly unused) - bool oneWay; - /// @brief Whether edges of this type shall be discarded - bool discard; - /// @brief The width of lanes of edges of this type [m] - double width; - /// @brief The resolution for interpreting custom (noisy) lane widths of this type [m] - double widthResolution; - /// @brief The maximum width for lanes of this type [m] - double maxWidth; - /// @brief The minimum width for lanes of this type [m] - double minWidth; - /* @brief The width of the sidewalk that should be added as an additional lane - * a value of NBEdge::UNSPECIFIED_WIDTH indicates that no sidewalk should be added */ - double sidewalkWidth; - /* @brief The width of the bike lane that should be added as an additional lane - * a value of NBEdge::UNSPECIFIED_WIDTH indicates that no bike lane should be added */ - double bikeLaneWidth; - /// @brief The vehicle class specific speed restrictions - std::map restrictions; - /// @brief The attributes which have been set - std::set attrs; - - }; - - - /** @brief Retrieve the name or the default type - * - * If no name is given, the default type is returned - * @param[in] name The name of the type to retrieve - * @return The named type - */ - const TypeDefinition& getType(const std::string& name) const; - - -private: - /// @brief The default type - TypeDefinition myDefaultType; - - /// @brief A container of types, accessed by the string id - typedef std::map TypesCont; - - /// @brief The container of types - TypesCont myTypes; - - -private: - /** @brief invalid copy constructor */ - NBTypeCont(const NBTypeCont& s); - - /** @brief invalid assignment operator */ - NBTypeCont& operator=(const NBTypeCont& s); - - -}; diff --git a/Util/OSM2ODR/src/netbuild/NBVehicle.h b/Util/OSM2ODR/src/netbuild/NBVehicle.h deleted file mode 100644 index 8e748ef13..000000000 --- a/Util/OSM2ODR/src/netbuild/NBVehicle.h +++ /dev/null @@ -1,87 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2002-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NBVehicle.h -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @author Jakob Erdmann -/// @date Sept 2002 -/// -// A vehicle as used by router -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include - - -// =========================================================================== -// class declarations -// =========================================================================== - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NBVehicle - * @brief A vehicle as used by router - */ -class NBVehicle { -public: - /** @brief Constructor - * - * @param[in] pars Parameter of this vehicle - * @param[in] route The definition of the route the vehicle shall use - * @param[in] type The type of the vehicle - */ - NBVehicle(const std::string& id, SUMOVehicleClass vClass): - myID(id), myVClass(vClass), myLength(getDefaultVehicleLength(vClass)) {} - - const std::string& getID() const { - return myID; - } - - SUMOVehicleClass getVClass() const { - return myVClass; - } - - double getLength() const { - return myLength; - } - - /// @brief Destructor - virtual ~NBVehicle() {} - - -private: - /// @brief vehicle ID for error reporting - std::string myID; - - /// @brief The vehicle class of the vehicle - SUMOVehicleClass myVClass; - - /// @brief The length of the vehicle (for rail-routing) - double myLength; - - -private: - /// @brief Invalidated copy constructor - NBVehicle(const NBVehicle& src); - - /// @brief Invalidated assignment operator - NBVehicle& operator=(const NBVehicle& src); - -}; diff --git a/Util/OSM2ODR/src/netbuild/_netbuild.dox b/Util/OSM2ODR/src/netbuild/_netbuild.dox deleted file mode 100644 index 58bc0b31f..000000000 --- a/Util/OSM2ODR/src/netbuild/_netbuild.dox +++ /dev/null @@ -1,19 +0,0 @@ -/** - @file _netbuild.dox - @defgoup netbuild Network Building Module - @brief builds SUMO-networks froman internal representation - - @addtogroup netbuild - @{ - - netbuild stores a representation of the road graph (edges/nodes/...) and offers classes and methods - for transferring this representation into loadable sumo networks. - - The internal representation is meant to be filled by classes from the @ref netimport or @ref netgen modules. - - The process of building networks is encapsulated in NBNetBuilder::compute(). Here, the following steps are performed: - - - - @} -*/ \ No newline at end of file diff --git a/Util/OSM2ODR/src/netconvert_main.cpp b/Util/OSM2ODR/src/netconvert_main.cpp deleted file mode 100644 index 81b52252b..000000000 --- a/Util/OSM2ODR/src/netconvert_main.cpp +++ /dev/null @@ -1,172 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file netconvert_main.cpp -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date Tue, 20 Nov 2001 -/// -// Main for NETCONVERT -/****************************************************************************/ -#include - -#ifdef HAVE_VERSION_H -#include -#endif - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - - -// =========================================================================== -// method definitions -// =========================================================================== -void -fillOptions() { - OptionsCont& oc = OptionsCont::getOptions(); - oc.addCallExample("-c ", "generate net with options read from file"); - oc.addCallExample("-n ./nodes.xml -e ./edges.xml -v -t ./owntypes.xml", - "generate net with given nodes, edges, and edge types doing verbose output"); - - // insert options sub-topics - SystemFrame::addConfigurationOptions(oc); // this subtopic is filled here, too - oc.addOptionSubTopic("Input"); - oc.addOptionSubTopic("Output"); - GeoConvHelper::addProjectionOptions(oc); - oc.addOptionSubTopic("Processing"); - oc.addOptionSubTopic("Building Defaults"); - oc.addOptionSubTopic("TLS Building"); - oc.addOptionSubTopic("Ramp Guessing"); - oc.addOptionSubTopic("Edge Removal"); - oc.addOptionSubTopic("Unregulated Nodes"); - oc.addOptionSubTopic("Junctions"); - oc.addOptionSubTopic("Pedestrian"); - oc.addOptionSubTopic("Bicycle"); - oc.addOptionSubTopic("Railway"); - oc.addOptionSubTopic("Formats"); - SystemFrame::addReportOptions(oc); // this subtopic is filled here, too - - NIFrame::fillOptions(); - NBFrame::fillOptions(false); - NWFrame::fillOptions(false); - RandHelper::insertRandOptions(); -} - - -bool -checkOptions() { - bool ok = NIFrame::checkOptions(); - ok &= NBFrame::checkOptions(); - ok &= NWFrame::checkOptions(); - ok &= SystemFrame::checkOptions(); - return ok; -} - - -/* ------------------------------------------------------------------------- - * main - * ----------------------------------------------------------------------- */ -int -main(int argc, char** argv) { - OptionsCont& oc = OptionsCont::getOptions(); - // give some application descriptions - oc.setApplicationDescription("Network importer / builder for the microscopic, multi-modal traffic simulation SUMO."); - oc.setApplicationName("netconvert", "Eclipse SUMO netconvert Version " VERSION_STRING); - int ret = 0; - try { - XMLSubSys::init(); - fillOptions(); - OptionsIO::setArgs(argc, argv); - OptionsIO::getOptions(); - if (oc.processMetaOptions(argc < 2)) { - SystemFrame::close(); - return 0; - } - XMLSubSys::setValidation(oc.getString("xml-validation"), oc.getString("xml-validation.net")); - if (oc.isDefault("aggregate-warnings")) { - oc.set("aggregate-warnings", "5"); - } - MsgHandler::initOutputOptions(); - if (!checkOptions()) { - throw ProcessError(); - } - RandHelper::initRandGlobal(); - // build the projection - if (!GeoConvHelper::init(oc)) { - throw ProcessError("Could not build projection!"); - } - NBNetBuilder nb; - nb.applyOptions(oc); - // load data - NILoader nl(nb); - nl.load(oc); - // flush aggregated errors and optionally ignore them - MsgHandler::getErrorInstance()->clear(oc.getBool("ignore-errors")); - // check whether any errors occurred - if (MsgHandler::getErrorInstance()->wasInformed()) { - throw ProcessError(); - } - nb.compute(oc); - // check whether any errors occurred - if (MsgHandler::getErrorInstance()->wasInformed()) { - throw ProcessError(); - } - NWFrame::writeNetwork(oc, nb); - } catch (const ProcessError& e) { - MsgHandler::getErrorInstance()->clear(false); - if (std::string(e.what()) != std::string("Process Error") && std::string(e.what()) != std::string("")) { - WRITE_ERROR(e.what()); - } - MsgHandler::getErrorInstance()->inform("Quitting (on error).", false); - ret = 1; -#ifndef _DEBUG - } catch (const std::exception& e) { - MsgHandler::getErrorInstance()->clear(false); - if (std::string(e.what()) != std::string("")) { - WRITE_ERROR(e.what()); - } - MsgHandler::getErrorInstance()->inform("Quitting (on error).", false); - ret = 1; - } catch (...) { - MsgHandler::getErrorInstance()->clear(false); - MsgHandler::getErrorInstance()->inform("Quitting (on unknown error).", false); - ret = 1; -#endif - } - DistributionCont::clear(); - SystemFrame::close(); - // report about ending - if (ret == 0) { - std::cout << "Success." << std::endl; - } - return ret; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netgen/NGEdge.h b/Util/OSM2ODR/src/netgen/NGEdge.h deleted file mode 100644 index d0e2d9c39..000000000 --- a/Util/OSM2ODR/src/netgen/NGEdge.h +++ /dev/null @@ -1,116 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NGEdge.h -/// @author Markus Hartinger -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Mar, 2003 -/// -// A netgen-representation of an edge -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include -#include -#include - - -// =========================================================================== -// class declarations -// =========================================================================== -class NGNode; -class NBNode; -class NBEdge; -class NBNetBuilder; - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NGEdge - * @brief A netgen-representation of an edge - * - * Please note that the edge makes itself known to the from- and the to-nodes - * on initialisation and removes this information from the nodes when being - * deleted. This implicates that nodes have to be deleted after the edges. - */ -class NGEdge : public Named { -public: - /** @brief Constructor - * - * Adds itself to the start and the end node's lists of connections. - * - * @param[in] id The id of the link - * @param[in] StarNGNode The begin node - * @param[in] EndNode The end node - */ - NGEdge(const std::string& id, NGNode* startNode, NGNode* endNode); - - - /** @brief Destructor - * - * Removes itself from the start and the end node's lists of connections. - */ - ~NGEdge(); - - - /** @brief Returns this link's start node - * - * @return The start node of the link - */ - NGNode* getStartNode() { - return myStartNode; - }; - - - /** @brief Returns this link's end node - * - * @return The end node of the link - */ - NGNode* getEndNode() { - return myEndNode; - }; - - - /** @brief Builds and returns this link's netbuild-representation - * - * Returns an edge built using the known values. Other values, such as the - * number of lanes, are gathered from defaults. - * The starting and the ending node must have been built in prior. - * - * @param[in] nb The netbuilder to retrieve the referenced nodes from - * @return The built edge - */ - NBEdge* buildNBEdge(NBNetBuilder& nb, const std::string& type) const; - - -private: - /// @brief The node the edge starts at - NGNode* myStartNode; - - /// @brief The node the edge ends at - NGNode* myEndNode; - -}; - - -/** - * @typedef NGEdgeList - * @brief A list of edges (edge pointers) - */ -typedef std::list NGEdgeList; diff --git a/Util/OSM2ODR/src/netgen/NGFrame.h b/Util/OSM2ODR/src/netgen/NGFrame.h deleted file mode 100644 index 75250d355..000000000 --- a/Util/OSM2ODR/src/netgen/NGFrame.h +++ /dev/null @@ -1,44 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NGFrame.h -/// @author Daniel Krajzewicz -/// @date 06.05.2011 -/// -// Sets and checks options for netgen -/****************************************************************************/ -#pragma once -#include - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NGFrame - * @brief Sets and checks options for netgen - */ -class NGFrame { -public: - /** @brief Inserts options used by the network generator - */ - static void fillOptions(); - - - /** @brief Checks set options from the OptionsCont-singleton for being valid - * @return Whether needed (netgen) options are set and have proper values - */ - static bool checkOptions(); - - -}; diff --git a/Util/OSM2ODR/src/netgen/NGNet.h b/Util/OSM2ODR/src/netgen/NGNet.h deleted file mode 100644 index 0203eefd2..000000000 --- a/Util/OSM2ODR/src/netgen/NGNet.h +++ /dev/null @@ -1,221 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NGNet.h -/// @author Markus Hartinger -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Mar, 2003 -/// -// The class storing the generated network -/****************************************************************************/ -#pragma once -#include - -#include -#include "NGEdge.h" -#include "NGNode.h" - - -// =========================================================================== -// class declarations -// =========================================================================== -class NBNetBuilder; - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NGNet - * @brief The class storing the generated network - * - * An instance of this class stores both the edges and the nodes build during - * the generation of a network (using any type of generation algorithm). - * These instances are later transformed into netbuild-structures using toNB(). - */ -class NGNet { -public: - /// @brief Constructor - NGNet(NBNetBuilder& nb); - - - /// @brief Destructor - ~NGNet(); - - - /** @brief Returns the node at the given position - * - * Searches for a node with the given position within myNodeList. - * Returns the matching node, if one exists, or 0 otherwise. - * - * @param[in] xPos The x-position of the searched node - * @param[in] yPos The y-position of the searched node - * @return The node with the given position, or 0 if no such node exists - */ - NGNode* findNode(int xPos, int yPos); - - - /** @brief Returns the next free id - * - * Uses the value of myLastID to return a new (numeric) id. Increases - * myLastID. - * - * @return A new, unique numerical id - */ - std::string getNextFreeID(); - - - /** @brief Returns the x-position resulting from the given radius and angle - * - * @param[in] radius The radius of the circle - * @param[in] phi The angle the position is located at - * @return The x-position at the described circle at angle phi - */ - double radialToX(double radius, double phi); - - - /** @brief Returns the y-position resulting from the given radius and angle - * - * @param[in] radius The radius of the circle - * @param[in] phi The angle the position is located at - * @return The y-position at the described circle at angle phi - */ - double radialToY(double radius, double phi); - - - /** @brief Creates a grid network - * - * Performs a souble-loop over numX, then numY. Builds NGNodes - * at the according positions and connects them using NGNet::connect. - * Stores both the nodes and the edges within the internal container. - * - * The nodes get an id using <RUNNING_X>/<RUNNING_Y>. The ids - * of the links are set in NGNet::connect. - * - * @param[in] numX The number of nodes in x-direction - * @param[in] numY The number of nodes in y-direction - * @param[in] spaceX The space between nodes in x-direction - * @param[in] spaceY The space between nodes in y-direction - * @param[in] attachLength The length of streets attached at the border - * @see NGNet::connect - */ - void createChequerBoard(int numX, int numY, double spaceX, double spaceY, double attachLength); - - - /** @brief Creates a spider network - * - * Creates a spider web by going through all arms and then all circles in a loop. - * Builds the NGNodes at the positions obtained using radialToX and radialToY and - * connects them using NGNet::connect. Builds optionally a center node, and connects - * it, too. - * - * The nodes get an id using <RUNNING_ARM_NUMBER>/<RUNNING_CIRCLE_NUMBER>. - * The ids of the links are set in NGNet::connect. - * - * @param[in] numRadDiv The number of arms to build - * @param[in] numCircles The number of circles to build - * @param[in] spaceRad The distance between the circles - * @param[in] hasCenter Information whether a center node shall be built - * @see NGNet::connect - * @todo consolidate the name of the center node - */ - void createSpiderWeb(int numRadDiv, int numCircles, double spaceRad, bool hasCenter); - - - /** @brief Converts the stored network into its netbuilder-representation - * - * Goes through all stored nodes, first, converts them into their netbuilder - * representations using NGNode::buildNBNode, and stores the built NBNodes into the - * net builder myNetBuilder. - * - * Then, the method goes through all edges, converts them into their netbuilder - * representations using NGEdge::buildNBEdge, and stores the built NBEdges into the - * net builder myNetBuilder. - * - * If one of the nodes is controlled by a tls and the built logic could not be added - * to net builder's storage, a ProcessError is thrown. This in fact may only happen - * when two same ids occur, what is not possible. - * - * @exception ProcessError If a built tls logic could not be added (should never happen) - * @todo Check whether throwing an exception is really necessary, here - */ - void toNB() const; - - - /** @brief Adds the given node to the network - * - * The node is added to myNodeList. - * - * @param[in] node The node to add - */ - void add(NGNode* node); - - - /** @brief Adds the given edge to the network - * - * The edge is added to myEdgeList. - * - * @param[in] edge The edge to add - */ - void add(NGEdge* edge); - - - /** @brief Returns the number of stored nodes - * - * @return The number of stored nodes - */ - int nodeNo() const; - - -private: - /** @brief Connects both nodes with two edges, one for each direction - * - * Builds one link for each direction and appends the links to myEdgeList. - * The name of a link is as following: <FROM_NODE_ID>to<TO_NODE_ID>. - * - * @param[in] node1 The first node to connect - * @param[in] node2 The second node to connect - */ - void connect(NGNode* node1, NGNode* node2); - - /// @brief return a letter code for the given integer index - std::string alphabeticalCode(int i, int iMax); - - /// @brief get distribution from option - static Distribution_Parameterized getDistribution(const std::string& option); - -private: - /// @brief The last ID given to node or link - int myLastID; - - /// @brief Whether to use alphanumericalIDs - const bool myAlphaIDs; - - /// @brief The builder used to build NB*-structures - NBNetBuilder& myNetBuilder; - - /// @brief The list of nodes - NGNodeList myNodeList; - - /// @brief The list of links - NGEdgeList myEdgeList; - -private: - /// @brief Invalidated copy constructor. - NGNet(const NGNet&); - - /// @brief Invalidated assignment operator. - NGNet& operator=(const NGNet&); - -}; diff --git a/Util/OSM2ODR/src/netgen/NGNode.h b/Util/OSM2ODR/src/netgen/NGNode.h deleted file mode 100644 index 7b1b30037..000000000 --- a/Util/OSM2ODR/src/netgen/NGNode.h +++ /dev/null @@ -1,212 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NGNode.h -/// @author Markus Hartinger -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Mar, 2003 -/// -// A netgen-representation of a node -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include -#include -#include -#include "NGEdge.h" - - -// =========================================================================== -// class declarations -// =========================================================================== -class NBNode; -class NBEdge; -class NBNetBuilder; - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NGNode - * @brief A netgen-representation of a node - */ -class NGNode : public Named { -public: - /** @brief Constructor - * - * @param[in] id The id of the node - */ - NGNode(const std::string& id); - - - /** @brief Constructor - * - * @param[in] id The id of the node - * @param[in] xPos The x-position of the node - * @param[in] yPos The y-position of the node - */ - NGNode(const std::string& id, int xPos, int yPos); - - - /** @brief Constructor - * - * @param[in] id The id of the node - * @param[in] xPos The x-position of the node - * @param[in] yPos The y-position of the node - * @param[in] amCenter Information whether this is the center-node of a spider-net - */ - NGNode(const std::string& id, int xID, int yID, bool amCenter); - - - /// @brief Destructor - ~NGNode(); - - - /** @brief Returns this node's position - * - * @return The position of the node - */ - const Position& getPosition() const { - return myPosition; - } - - - /** @brief Returns this node's maximum neighbour number - * - * @return The maximum neighbour number of the node - */ - int getMaxNeighbours() { - return myMaxNeighbours; - } - - - /** @brief Sets this node's maximum neighbour number - * - * @param[in] value The new maximum neighbour number of the node - */ - void setMaxNeighbours(int value) { - myMaxNeighbours = value; - } - - - /** @brief Sets a new value for x-position - * - * @param[in] value The new x-position of this node - */ - void setX(double x) { - myPosition.set(x, myPosition.y()); - } - - - /** @brief Sets a new value for y-position - * - * @param[in] value The new y-position of this node - */ - void setY(double y) { - myPosition.set(myPosition.x(), y); - } - - /// @brief mark node as fringe - void setFringe() { - myAmFringe = true; - } - - /** @brief Builds and returns this node's netbuild-representation - * - * The position of the node is transformed to cartesian using GeoConvHelper::x2cartesian, - * first. If this node is the center node of a spider net, a node of the type - * NBNode::SumoXMLNodeType::NOJUNCTION is returned. - * Otherwise, a plain node is built and it is checked whether the options - * indicate building one of the tls node-types. In this case, a logic is built and - * stored. A ProcessError is thrown if this fails (should never happen, in fact). - * - * @param[in] nb The netbuilder to retrieve the tls-container from - * @return The built node - * @exception ProcessError If the built tls logic could not be added (should never happen) - * @todo There is no interaction with explicit node setting options? Where is this done? - * @todo Check whether throwing an exception is really necessary, here - */ - NBNode* buildNBNode(NBNetBuilder& nb, const Position& perturb) const; - - - /** @brief Adds the given link to the internal list - * - * @param[in] link The link to add - */ - void addLink(NGEdge* link); - - - /** @brief Removes the given link - * - * The given pointer is compared to those in the list. A matching - * pointer is removed, not other same connections. - * - * @param[in] link The link to remove - */ - void removeLink(NGEdge* link); - - - /** @brief Returns whether the other node is connected - * - * @param[in] node The link to check whether it is connected - * @return Whether the given node is connected - */ - bool connected(NGNode* node) const; - - - /** @brief Returns whether the node has the given position - * - * @param[in] node The link to check whether it is connected - * @return Whether the given node is connected - */ - bool samePos(int xPos, int yPos) const { - return xID == xPos && yID == yPos; - } - - // NGRandomNetBuilder needs access to links - friend class NGRandomNetBuilder; - -private: - /// @brief Integer x-position (x-id) - int xID; - - /// @brief Integer y-position (y-id) - int yID; - - /// @brief List of connected links - NGEdgeList LinkList; - - /// @brief The position of the node - Position myPosition; - - /// @brief The maximum number of neighbours - int myMaxNeighbours; - - /// @brief Information whether this is the center of a cpider-net - bool myAmCenter; - - /// @brief Information whether this is the center of a cpider-net - bool myAmFringe; - -}; - -/** - * @typedef NGNodeList - * @brief A list of nodes (node pointers) - */ -typedef std::list NGNodeList; diff --git a/Util/OSM2ODR/src/netgen/NGRandomNetBuilder.h b/Util/OSM2ODR/src/netgen/NGRandomNetBuilder.h deleted file mode 100644 index 0c87d2992..000000000 --- a/Util/OSM2ODR/src/netgen/NGRandomNetBuilder.h +++ /dev/null @@ -1,159 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NGRandomNetBuilder.h -/// @author Markus Hartinger -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Mar, 2003 -/// -// Additional structures for building random nets -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include "NGNet.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NGRandomNetBuilder - * @brief A class that builds random network using an algorithm by Markus Hartinger. - * - * @todo Describe the algorithm - */ -class NGRandomNetBuilder { -public: - /** @brief Constructor - * - * @param[in] net The network to fill with generated structures - * @param[in] minAngle The minimum allowed angle between two streets - * @param[in] minDistance The minimum allowed distance between two nodes - * @param[in] maxDistance The maximum allowed distance between two nodes - * @param[in] connectivity The connectivity factor - * @param[in] numTries ? - * @todo check meanings of connectivity/numTries - */ - NGRandomNetBuilder(NGNet& net, double minAngle, double minDistance, double maxDistance, double connectivity, - int numTries, const RandomDistributor& neighborDist); - - - - /** @brief Builds a NGNet using the set values - * - * @param[in] numNodes Number of iterations (node insertions) to perform - * @todo Describe the algorithm - */ - void createNet(int numNodes, bool gridMode); - - -private: - /** @brief Removes the given node from the list of outer nodes - * - * @param[in] node The node to remove - */ - void removeOuterNode(NGNode* node); - - - /** @brief Checks whether the angle of this node's connections are valid - * - * Checks whether the connections of the nodes are in common with the value of myMinLinkAngle. - * - * @param[in] node The node to check connections of - * @return Whether the settings allow to connect both nodes - */ - bool checkAngles(NGNode* node); - - - /** @brief Checks whether connecting the given two nodes complies with the set restrictions - * - * Checks whether the distance, the angle, and the connectivity is within the defined range - * when both nodes would be connected - * - * @param[in] baseNode The first node of the combination to check - * @param[in] newNode The second node of the combination to check - * @return Whether the settings allow to connect both nodes - */ - bool canConnect(NGNode* baseNode, NGNode* newNode); - - - /** @brief Creates new random node - * - * Returns true, if creation was successfull. - * - * @param[in] baseNode ? - * @todo Describe better - */ - bool createNewNode(NGNode* baseNode, bool gridMode); - - - /** @brief finds possible connections between Node and OuterNodes complying with restrictions - * - * @param[in] node ? - * @todo Describe better - */ - void findPossibleOuterNodes(NGNode* node); - - -private: - /// @brief The network to fill - NGNet& myNet; - - /// @brief The list of outer nodes - NGNodeList myOuterNodes; - - /// @brief The list of outer links - NGEdgeList myOuterLinks; - - // list of possible new connections - NGNodeList myConNodes; - - - /// @name restrictions - //@{ - - /// @brief Minimum angle allowed between two links - double myMinLinkAngle; - - /// @brief Minimum distance allowed between two nodes - double myMinDistance; - - /// @brief Maximum distance allowed between two nodes - double myMaxDistance; - - /// @brief Probability of connecting to a existing node if possible - double myConnectivity; - //@} - - - /// @brief Number of tries to create a new node - int myNumTries; - - /// @brief Number of nodes to be created - int myNumNodes; - - /// @brief The distribution of number of neighbours - RandomDistributor myNeighbourDistribution; - -private: - /// @brief Invalidated copy constructor. - NGRandomNetBuilder(const NGRandomNetBuilder&); - - /// @brief Invalidated assignment operator. - NGRandomNetBuilder& operator=(const NGRandomNetBuilder&); - -}; diff --git a/Util/OSM2ODR/src/netimport/CMakeLists.txt b/Util/OSM2ODR/src/netimport/CMakeLists.txt deleted file mode 100644 index 550a308cb..000000000 --- a/Util/OSM2ODR/src/netimport/CMakeLists.txt +++ /dev/null @@ -1,48 +0,0 @@ -add_subdirectory(vissim) - -set(netimport_STAT_SRCS - NIFrame.cpp - NIFrame.h - NILoader.cpp - NILoader.h - NITypeLoader.cpp - NITypeLoader.h - NIImporter_ArcView.cpp - NIImporter_ArcView.h - NIImporter_DlrNavteq.cpp - NIImporter_DlrNavteq.h - NIImporter_ITSUMO.cpp - NIImporter_ITSUMO.h - NIImporter_MATSim.cpp - NIImporter_MATSim.h - NIImporter_OpenDrive.cpp - NIImporter_OpenDrive.h - NIImporter_OpenStreetMap.cpp - NIImporter_OpenStreetMap.h - NIImporter_SUMO.cpp - NIImporter_SUMO.h - NIImporter_VISUM.cpp - NIImporter_VISUM.h - NIVisumTL.cpp - NIVisumTL.h - NIXMLConnectionsHandler.cpp - NIXMLConnectionsHandler.h - NIXMLEdgesHandler.cpp - NIXMLEdgesHandler.h - NIXMLNodesHandler.cpp - NIXMLNodesHandler.h - NIXMLTypesHandler.cpp - NIXMLTypesHandler.h - NIXMLPTHandler.cpp - NIXMLPTHandler.h - NIXMLShapeHandler.cpp - NIXMLShapeHandler.h - NIXMLTrafficLightsHandler.cpp - NIXMLTrafficLightsHandler.h - NINavTeqHelper.cpp - NINavTeqHelper.h - typemap.h -) - -add_library(netimport STATIC ${netimport_STAT_SRCS}) -set_property(TARGET netimport PROPERTY PROJECT_LABEL "z_netimport") diff --git a/Util/OSM2ODR/src/netimport/NIFrame.cpp b/Util/OSM2ODR/src/netimport/NIFrame.cpp deleted file mode 100644 index 02d993dc2..000000000 --- a/Util/OSM2ODR/src/netimport/NIFrame.cpp +++ /dev/null @@ -1,417 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIFrame.cpp -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @author Gregor Laemmel -/// @date Tue, 20 Nov 2001 -/// -// Sets and checks options for netimport -/****************************************************************************/ -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "NIImporter_DlrNavteq.h" -#include "NIFrame.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -void -NIFrame::fillOptions(bool forNetedit) { - OptionsCont& oc = OptionsCont::getOptions(); - // register input formats - oc.doRegister("sumo-net-file", 's', new Option_FileName()); - oc.addSynonyme("sumo-net-file", "sumo-net", true); - oc.addDescription("sumo-net-file", "Input", "Read SUMO-net from FILE"); - oc.addXMLDefault("sumo-net-file", "net"); - - oc.doRegister("node-files", 'n', new Option_FileName()); - oc.addSynonyme("node-files", "xml-node-files", true); - oc.addSynonyme("node-files", "xml-nodes", true); - oc.addSynonyme("node-files", "nodes"); - oc.addDescription("node-files", "Input", "Read XML-node defs from FILE"); - - oc.doRegister("edge-files", 'e', new Option_FileName()); - oc.addSynonyme("edge-files", "xml-edge-files", true); - oc.addSynonyme("edge-files", "xml-edges", true); - oc.addSynonyme("edge-files", "edges"); - oc.addDescription("edge-files", "Input", "Read XML-edge defs from FILE"); - - oc.doRegister("connection-files", 'x', new Option_FileName()); - oc.addSynonyme("connection-files", "xml-connection-files", true); - oc.addSynonyme("connection-files", "xml-connections", true); - oc.addSynonyme("connection-files", "connections"); - oc.addDescription("connection-files", "Input", "Read XML-connection defs from FILE"); - - oc.doRegister("tllogic-files", 'i', new Option_FileName()); - oc.addDescription("tllogic-files", "Input", "Read XML-traffic light defs from FILE"); - - oc.doRegister("type-files", 't', new Option_FileName()); - oc.addSynonyme("type-files", "xml-type-files", true); - oc.addSynonyme("type-files", "xml-types", true); - oc.addSynonyme("type-files", "types"); - oc.addDescription("type-files", "Input", "Read XML-type defs from FILE"); - - if (!forNetedit) { - // would cause confusion because netedit loads stops and shapes using option --additional-files - oc.doRegister("ptstop-files", new Option_FileName()); - oc.addDescription("ptstop-files", "Input", "Reads public transport stops from FILE"); - oc.doRegister("ptline-files", new Option_FileName()); - oc.addDescription("ptline-files", "Input", "Reads public transport lines from FILE"); - oc.doRegister("polygon-files", new Option_FileName()); - oc.addDescription("polygon-files", "Input", "Reads polygons from FILE for embedding in network where applicable"); - } - - oc.doRegister("shapefile-prefix", new Option_FileName()); - oc.addSynonyme("shapefile-prefix", "shapefile"); - oc.addSynonyme("shapefile-prefix", "arcview", true); - oc.addSynonyme("shapefile-prefix", "tiger", true); - oc.addDescription("shapefile-prefix", "Input", "Read shapefiles (ArcView, Tiger, ...) from files starting with 'FILE'"); - - oc.doRegister("dlr-navteq-prefix", new Option_FileName()); - oc.addSynonyme("dlr-navteq-prefix", "dlr-navteq"); - oc.addSynonyme("dlr-navteq-prefix", "elmar2", true); - oc.addDescription("dlr-navteq-prefix", "Input", "Read converted Navteq GDF data (unsplitted Elmar-network) from path 'FILE'"); - - oc.doRegister("osm-files", new Option_FileName()); - oc.addSynonyme("osm-files", "osm"); - oc.addDescription("osm-files", "Input", "Read OSM-network from path 'FILE(s)'"); - - oc.doRegister("opendrive-files", new Option_FileName()); - oc.addSynonyme("opendrive-files", "opendrive"); - oc.addDescription("opendrive-files", "Input", "Read OpenDRIVE-network from FILE"); - - oc.doRegister("visum-file", new Option_FileName()); - oc.addSynonyme("visum-file", "visum"); - oc.addDescription("visum-file", "Input", "Read VISUM-net from FILE"); - - oc.doRegister("vissim-file", new Option_FileName()); - oc.addSynonyme("vissim-file", "vissim"); - oc.addDescription("vissim-file", "Input", "Read VISSIM-net from FILE"); - - oc.doRegister("robocup-dir", new Option_FileName()); - oc.addSynonyme("robocup-dir", "robocup-net", true); - oc.addSynonyme("robocup-dir", "robocup"); - oc.addDescription("robocup-dir", "Input", "Read RoboCup-net from DIR"); - - oc.doRegister("matsim-files", new Option_FileName()); - oc.addSynonyme("matsim-files", "matsim"); - oc.addDescription("matsim-files", "Input", "Read MATsim-net from FILE"); - - oc.doRegister("itsumo-files", new Option_FileName()); - oc.addSynonyme("itsumo-files", "itsumo"); - oc.addDescription("itsumo-files", "Input", "Read ITSUMO-net from FILE"); - - oc.doRegister("heightmap.shapefiles", new Option_FileName()); - oc.addDescription("heightmap.shapefiles", "Input", "Read heightmap from ArcGIS shapefile"); - - oc.doRegister("heightmap.geotiff", new Option_FileName()); - oc.addDescription("heightmap.geotiff", "Input", "Read heightmap from GeoTIFF"); - - // register basic processing options - oc.doRegister("ignore-errors", new Option_Bool(false)); - oc.addSynonyme("ignore-errors", "dismiss-loading-errors", true); - oc.addDescription("ignore-errors", "Report", "Continue on broken input"); - - oc.doRegister("ignore-errors.connections", new Option_Bool(false)); - oc.addDescription("ignore-errors.connections", "Report", "Continue on invalid connections"); - - oc.doRegister("show-errors.connections-first-try", new Option_Bool(false)); - oc.addDescription("show-errors.connections-first-try", "Report", "Show errors in connections at parsing"); - - oc.doRegister("ignore-errors.edge-type", new Option_Bool(false)); - oc.addDescription("ignore-errors.edge-type", "Report", "Continue on unknown edge types"); - - oc.doRegister("speed-in-kmh", new Option_Bool(false)); - oc.addDescription("speed-in-kmh", "Processing", "vmax is parsed as given in km/h (some)"); - - oc.doRegister("construction-date", new Option_String()); - oc.addDescription("construction-date", "Processing", "Use YYYY-MM-DD date to determine the readiness of features under construction"); - - oc.doRegister("flatten", new Option_Bool(false)); - oc.addDescription("flatten", "Processing", "Remove all z-data"); - - oc.doRegister("discard-params", new Option_StringVector()); - oc.addDescription("discard-params", "Formats", "Remove the list of keys from all params"); - - // register xml options - oc.doRegister("plain.extend-edge-shape", new Option_Bool(false)); - oc.addSynonyme("plain.extend-edge-shape", "xml.keep-shape", true); - oc.addDescription("plain.extend-edge-shape", "Processing", "If edge shapes do not end at the node positions, extend them"); - - // register osm options - oc.doRegister("osm.skip-duplicates-check", new Option_Bool(false)); - oc.addDescription("osm.skip-duplicates-check", "Formats", "Skips the check for duplicate nodes and edges"); - - oc.doRegister("osm.elevation", new Option_Bool(false)); - oc.addDescription("osm.elevation", "Formats", "Imports elevation data"); - - oc.doRegister("osm.layer-elevation", new Option_Float(0)); - oc.addDescription("osm.layer-elevation", "Formats", "Reconstruct (relative) elevation based on layer data. Each layer is raised by FLOAT m"); - - oc.doRegister("osm.layer-elevation.max-grade", new Option_Float(10)); - oc.addDescription("osm.layer-elevation.max-grade", "Formats", "Maximum grade threshold in % at 50km/h when reconstrucing elevation based on layer data. The value is scaled according to road speed."); - - oc.doRegister("osm.oneway-spread-right", new Option_Bool(false)); - oc.addDescription("osm.oneway-spread-right", "Formats", "Whether one-way roads should be spread to the side instead of centered"); - - oc.doRegister("osm.stop-output.length", new Option_Float(25)); - oc.addDescription("osm.stop-output.length", "Formats", "The default length of a public transport stop in FLOAT m"); - oc.doRegister("osm.stop-output.length.bus", new Option_Float(15)); - oc.addDescription("osm.stop-output.length.bus", "Formats", "The default length of a bus stop in FLOAT m"); - oc.doRegister("osm.stop-output.length.tram", new Option_Float(25)); - oc.addDescription("osm.stop-output.length.tram", "Formats", "The default length of a tram stop in FLOAT m"); - oc.doRegister("osm.stop-output.length.train", new Option_Float(200)); - oc.addDescription("osm.stop-output.length.train", "Formats", "The default length of a train stop in FLOAT m"); - - oc.doRegister("osm.all-attributes", new Option_Bool(false)); - oc.addDescription("osm.all-attributes", "Formats", "Whether additional attributes shall be imported"); - - - // register matsim options - oc.doRegister("matsim.keep-length", new Option_Bool(false)); - oc.addDescription("matsim.keep-length", "Formats", "The edge lengths given in the MATSIM-file will be kept"); - - oc.doRegister("matsim.lanes-from-capacity", new Option_Bool(false)); - oc.addDescription("matsim.lanes-from-capacity", "Formats", "The lane number will be computed from the capacity"); - - - // register shapefile options - oc.doRegister("shapefile.street-id", new Option_String()); - oc.addSynonyme("shapefile.street-id", "arcview.street-id", true); - oc.addDescription("shapefile.street-id", "Formats", "Read edge ids from column STR"); - - oc.doRegister("shapefile.from-id", new Option_String()); - oc.addSynonyme("shapefile.from-id", "arcview.from-id", true); - oc.addDescription("shapefile.from-id", "Formats", "Read from-node ids from column STR"); - - oc.doRegister("shapefile.to-id", new Option_String()); - oc.addSynonyme("shapefile.to-id", "arcview.to-id", true); - oc.addDescription("shapefile.to-id", "Formats", "Read to-node ids from column STR"); - - oc.doRegister("shapefile.type-id", new Option_String()); - oc.addSynonyme("shapefile.type-id", "arcview.type-id", true); - oc.addDescription("shapefile.type-id", "Formats", "Read type ids from column STR"); - - oc.doRegister("shapefile.laneNumber", new Option_String()); - oc.addDescription("shapefile.laneNumber", "Formats", "Read lane number from column STR"); - - oc.doRegister("shapefile.speed", new Option_String()); - oc.addDescription("shapefile.speed", "Formats", "Read speed from column STR"); - - oc.doRegister("shapefile.name", new Option_String()); - oc.addDescription("shapefile.name", "Formats", "Read (non-unique) name from column STR"); - - oc.doRegister("shapefile.node-join-dist", new Option_Float(0)); - oc.addDescription("shapefile.node-join-dist", "Formats", "Distance threshold for determining whether distinct shapes are connected (used when from-id and to-id are not available)"); - - oc.doRegister("shapefile.add-params", new Option_StringVector()); - oc.addDescription("shapefile.add-params", "Formats", "Add the list of field names as edge params"); - - oc.doRegister("shapefile.use-defaults-on-failure", new Option_Bool(false)); - oc.addSynonyme("shapefile.use-defaults-on-failure", "arcview.use-defaults-on-failure", true); - oc.addDescription("shapefile.use-defaults-on-failure", "Formats", "Uses edge type defaults on problems"); - - oc.doRegister("shapefile.all-bidirectional", new Option_Bool(false)); - oc.addSynonyme("shapefile.all-bidirectional", "shapefile.all-bidi"); - oc.addSynonyme("shapefile.all-bidirectional", "arcview.all-bidi", true); - oc.addDescription("shapefile.all-bidirectional", "Formats", "Insert edges in both directions"); - - oc.doRegister("shapefile.guess-projection", new Option_Bool(false)); - oc.addSynonyme("shapefile.guess-projection", "arcview.guess-projection", true); - oc.addDescription("shapefile.guess-projection", "Formats", "Guess the proper projection"); - - oc.doRegister("shapefile.traditional-axis-mapping", new Option_Bool(false)); - oc.addDescription("shapefile.traditional-axis-mapping", "Formats", "Use traditional axis order (lon, lat)"); - - - // register dlr-navteq options - oc.doRegister("dlr-navteq.tolerant-permissions", new Option_Bool(false)); - oc.addDescription("dlr-navteq.tolerant-permissions", "Formats", "Allow more vehicle classes by default"); - - - // register vissim options - oc.doRegister("vissim.join-distance", new Option_Float(5.0f)); - oc.addSynonyme("vissim.join-distance", "vissim.offset", true); - oc.addDescription("vissim.join-distance", "Formats", "Structure join offset"); - - oc.doRegister("vissim.default-speed", new Option_Float(50.0f)); - oc.addDescription("vissim.default-speed", "Formats", "Use FLOAT as default speed"); - - oc.doRegister("vissim.speed-norm", new Option_Float(1.0f)); - oc.addDescription("vissim.speed-norm", "Formats", "Factor for edge velocity"); - - oc.doRegister("vissim.report-unset-speeds", new Option_Bool(false)); - oc.addDescription("vissim.report-unset-speeds", "Formats", "Writes lanes without an explicit speed set"); - - - // register visum options - oc.doRegister("visum.language-file", new Option_FileName()); - oc.addDescription("visum.language-file", "Formats", "Load language mappings from FILE"); - - oc.doRegister("visum.use-type-priority", new Option_Bool(false)); - oc.addDescription("visum.use-type-priority", "Formats", "Uses priorities from types"); - - oc.doRegister("visum.use-type-laneno", new Option_Bool(false)); - oc.addDescription("visum.use-type-laneno", "Formats", "Uses lane numbers from types"); - - oc.doRegister("visum.use-type-speed", new Option_Bool(false)); - oc.addDescription("visum.use-type-speed", "Formats", "Uses speeds from types"); - - oc.doRegister("visum.connector-speeds", new Option_Float(100.)); - oc.addDescription("visum.connector-speeds", "Formats", "Sets connector speed"); - - oc.doRegister("visum.connectors-lane-number", new Option_Integer(3)); - oc.addSynonyme("visum.connectors-lane-number", "visum.connector-laneno", true); - oc.addDescription("visum.connectors-lane-number", "Formats", "Sets connector lane number"); - - oc.doRegister("visum.no-connectors", new Option_Bool(true)); - oc.addDescription("visum.no-connectors", "Formats", "Excludes connectors"); - - oc.doRegister("visum.recompute-lane-number", new Option_Bool(false)); - oc.addSynonyme("visum.recompute-lane-number", "visum.recompute-laneno", true); - oc.addDescription("visum.recompute-lane-number", "Formats", "Computes the number of lanes from the edges' capacities"); - - oc.doRegister("visum.verbose-warnings", new Option_Bool(false)); - oc.addDescription("visum.verbose-warnings", "Formats", "Prints all warnings, some of which are due to VISUM misbehaviour"); - - oc.doRegister("visum.lanes-from-capacity.norm", new Option_Float(1800.)); - oc.addSynonyme("visum.lanes-from-capacity.norm", "capacity-norm", true); - oc.addSynonyme("visum.lanes-from-capacity.norm", "lanes-from-capacity.norm"); - oc.addDescription("visum.lanes-from-capacity.norm", "Formats", "The factor for flow to no. lanes conversion"); - - - // register opendrive options - oc.doRegister("opendrive.import-all-lanes", new Option_Bool(false)); - oc.addDescription("opendrive.import-all-lanes", "Formats", "Imports all lane types"); - oc.doRegister("opendrive.ignore-widths", new Option_Bool(false)); - oc.addDescription("opendrive.ignore-widths", "Formats", "Whether lane widths shall be ignored."); - oc.doRegister("opendrive.curve-resolution", new Option_Float(2.0)); - oc.addDescription("opendrive.curve-resolution", "Formats", "The geometry resolution in m when importing curved geometries as line segments."); - oc.doRegister("opendrive.advance-stopline", new Option_Float(0.0)); - oc.addDescription("opendrive.advance-stopline", "Formats", "Allow stop lines to be built beyond the start of the junction if the geometries allow so"); - oc.doRegister("opendrive.min-width", new Option_Float(1.8)); - oc.addDescription("opendrive.min-width", "Formats", "The minimum lane width for determining start or end of variable-width lanes"); - oc.doRegister("opendrive.internal-shapes", new Option_Bool(false)); - oc.addDescription("opendrive.internal-shapes", "Formats", "Import internal lane shapes"); - - // register some additional options - oc.doRegister("tls.discard-loaded", new Option_Bool(false)); - oc.addDescription("tls.discard-loaded", "TLS Building", "Does not instatiate traffic lights loaded from other formats than plain-XML"); - - oc.doRegister("tls.discard-simple", new Option_Bool(false)); - oc.addDescription("tls.discard-simple", "TLS Building", "Does not instatiate traffic lights at geometry-like nodes loaded from other formats than plain-XML"); - - // register railway options - oc.doRegister("railway.signals.discard", new Option_Bool(false)); - oc.addDescription("railway.signals.discard", "Railway", "Discard all railway signal information loaded from other formats than plain-xml"); -} - - -bool -NIFrame::checkOptions() { - OptionsCont& oc = OptionsCont::getOptions(); - bool ok = oc.checkDependingSuboptions("shapefile", "shapefile."); - ok &= oc.checkDependingSuboptions("visum-file", "visum."); - ok &= oc.checkDependingSuboptions("vissim-file", "vissim."); -#ifdef PROJ_API_FILE - int numProjections = oc.getBool("simple-projection") + oc.getBool("proj.utm") + oc.getBool("proj.dhdn") + (oc.getString("proj").length() > 1); - if ((oc.isSet("osm-files") || oc.isSet("dlr-navteq-prefix") || oc.isSet("shapefile-prefix")) && numProjections == 0) { - if (oc.isDefault("proj")) { - oc.set("proj.utm", "true"); - } - } - if (oc.isSet("dlr-navteq-prefix") && oc.isDefault("proj.scale")) { - oc.set("proj.scale", NIImporter_DlrNavteq::GEO_SCALE); - } -#else - if ((oc.isSet("osm-files") || oc.isSet("dlr-navteq-prefix") || oc.isSet("shapefile-prefix")) && !oc.getBool("simple-projection")) { - WRITE_ERROR("Cannot import network data without PROJ-Library. Please install packages proj before building sumo"); - ok = false; - } -#endif - if (oc.isSet("sumo-net-file")) { - if (oc.isWriteable("no-turnarounds")) { - // changed default since turnarounds are loaded from the net file. - oc.set("no-turnarounds", "true"); - } - if (oc.isWriteable("offset.disable-normalization")) { - // changed default since we wish to preserve the network as far as possible - oc.set("offset.disable-normalization", "true"); - } - if (oc.isWriteable("geometry.max-grade.fix")) { - // changed default since we wish to preserve the network as far as possible - oc.set("geometry.max-grade.fix", "false"); - } - if (oc.isWriteable("geometry.min-radius.fix.railways")) { - // changed default since we wish to preserve the network as far as possible - oc.set("geometry.min-radius.fix.railways", "false"); - } - } - if (!oc.isSet("type-files")) { - // const char* sumoPath = std::getenv("SUMO_HOME"); - // if (sumoPath == nullptr) { - // WRITE_WARNING("Environment variable SUMO_HOME is not set, using built in type maps."); - // } else { - // const std::string path = sumoPath + std::string("/data/typemap/"); - // if (oc.isSet("osm-files")) { - // oc.setDefault("type-files", path + "osmNetconvert.typ.xml"); - // } - // if (oc.isSet("opendrive-files")) { - // oc.setDefault("type-files", path + "opendriveNetconvert.typ.xml"); - // } - // } - const std::string path = std::string("data/typemap/"); - if (oc.isSet("osm-files")) { - // oc.setDefault("type-files", path + "osmNetconvert.typ.xml"); - } - if (oc.isSet("opendrive-files")) { - // oc.setDefault("type-files", path + "opendriveNetconvert.typ.xml"); - } - } - if (oc.isSet("opendrive-files")) { - if (oc.isDefault("tls.left-green.time")) { - // legacy behavior. see #2114 - oc.set("tls.left-green.time", "0"); - } - if (oc.isDefault("rectangular-lane-cut")) { - // a better interpretation of imported geometries - oc.set("rectangular-lane-cut", "true"); - } - if (oc.isDefault("geometry.max-grade.fix")) { - // a better interpretation of imported geometries - oc.set("geometry.max-grade.fix", "false"); - } - } - return ok; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/NIFrame.h b/Util/OSM2ODR/src/netimport/NIFrame.h deleted file mode 100644 index 3d68ee6d7..000000000 --- a/Util/OSM2ODR/src/netimport/NIFrame.h +++ /dev/null @@ -1,49 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIFrame.h -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Tue, 20 Nov 2001 -/// -// Sets and checks options for netimport -/****************************************************************************/ -#pragma once -#include - - -// =========================================================================== -// class declarations -// =========================================================================== -/** - * @class NIFrame - * @brief Sets and checks options for netimport - */ -class NIFrame { -public: - /** @brief Inserts options used by the network importer and network building modules - * - * Calls "NBNetBuilder::insertNetBuildOptions" for inserting network - * building options. - */ - static void fillOptions(bool forNetedit = false); - - - /** @brief Checks set options from the OptionsCont-singleton for being valid - * @return Whether all needed options are set - * @todo Unused currently; repair/fill - */ - static bool checkOptions(); - - -}; diff --git a/Util/OSM2ODR/src/netimport/NIImporter_ArcView.cpp b/Util/OSM2ODR/src/netimport/NIImporter_ArcView.cpp deleted file mode 100644 index ae388fc22..000000000 --- a/Util/OSM2ODR/src/netimport/NIImporter_ArcView.cpp +++ /dev/null @@ -1,520 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIImporter_ArcView.cpp -/// @author Daniel Krajzewicz -/// @author Eric Nicolay -/// @author Jakob Erdmann -/// @author Thimor Bohn -/// @author Michael Behrisch -/// @date Sept 2002 -/// -// Importer for networks stored in ArcView-shape format -/****************************************************************************/ -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "NILoader.h" -#include "NIImporter_ArcView.h" - -#ifdef HAVE_GDAL -#if __GNUC__ > 3 -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wpedantic" -#endif -#include -#if __GNUC__ > 3 -#pragma GCC diagnostic pop -#endif -#endif - - -// =========================================================================== -// method definitions -// =========================================================================== -// --------------------------------------------------------------------------- -// static methods (interface in this case) -// --------------------------------------------------------------------------- -void -NIImporter_ArcView::loadNetwork(const OptionsCont& oc, NBNetBuilder& nb) { - if (!oc.isSet("shapefile-prefix")) { - return; - } - // check whether the correct set of entries is given - // and compute both file names - std::string dbf_file = oc.getString("shapefile-prefix") + ".dbf"; - std::string shp_file = oc.getString("shapefile-prefix") + ".shp"; - std::string shx_file = oc.getString("shapefile-prefix") + ".shx"; - // check whether the files do exist - if (!FileHelpers::isReadable(dbf_file)) { - WRITE_ERROR("File not accessible: " + dbf_file); - } - if (!FileHelpers::isReadable(shp_file)) { - WRITE_ERROR("File not accessible: " + shp_file); - } - if (!FileHelpers::isReadable(shx_file)) { - WRITE_ERROR("File not accessible: " + shx_file); - } - if (MsgHandler::getErrorInstance()->wasInformed()) { - return; - } - // load the arcview files - NIImporter_ArcView loader(oc, - nb.getNodeCont(), nb.getEdgeCont(), nb.getTypeCont(), - dbf_file, shp_file, oc.getBool("speed-in-kmh")); - loader.load(); -} - - - -// --------------------------------------------------------------------------- -// loader methods -// --------------------------------------------------------------------------- -NIImporter_ArcView::NIImporter_ArcView(const OptionsCont& oc, - NBNodeCont& nc, - NBEdgeCont& ec, - NBTypeCont& tc, - const std::string& dbf_name, - const std::string& shp_name, - bool speedInKMH) - : myOptions(oc), mySHPName(shp_name), - myNameAddition(0), - myNodeCont(nc), myEdgeCont(ec), myTypeCont(tc), - mySpeedInKMH(speedInKMH), - myRunningEdgeID(0), - myRunningNodeID(0) { - UNUSED_PARAMETER(dbf_name); -} - - -NIImporter_ArcView::~NIImporter_ArcView() {} - - -void -NIImporter_ArcView::load() { -#ifdef HAVE_GDAL - PROGRESS_BEGIN_MESSAGE("Loading data from '" + mySHPName + "'"); -#if GDAL_VERSION_MAJOR < 2 - OGRRegisterAll(); - OGRDataSource* poDS = OGRSFDriverRegistrar::Open(mySHPName.c_str(), FALSE); -#else - GDALAllRegister(); - GDALDataset* poDS = (GDALDataset*)GDALOpenEx(mySHPName.c_str(), GDAL_OF_VECTOR | GA_ReadOnly, NULL, NULL, NULL); -#endif - if (poDS == NULL) { - WRITE_ERROR("Could not open shape description '" + mySHPName + "'."); - return; - } - - // begin file parsing - OGRLayer* poLayer = poDS->GetLayer(0); - poLayer->ResetReading(); - - // build coordinate transformation - OGRSpatialReference* origTransf = poLayer->GetSpatialRef(); - OGRSpatialReference destTransf; - // use wgs84 as destination - destTransf.SetWellKnownGeogCS("WGS84"); -#if GDAL_VERSION_MAJOR > 2 - if (myOptions.getBool("shapefile.traditional-axis-mapping")) { - destTransf.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER); - } -#endif - OGRCoordinateTransformation* poCT = OGRCreateCoordinateTransformation(origTransf, &destTransf); - if (poCT == nullptr) { - if (myOptions.isSet("shapefile.guess-projection")) { - OGRSpatialReference origTransf2; - origTransf2.SetWellKnownGeogCS("WGS84"); - poCT = OGRCreateCoordinateTransformation(&origTransf2, &destTransf); - } - if (poCT == nullptr) { - WRITE_WARNING("Could not create geocoordinates converter; check whether proj.4 is installed."); - } - } - - const bool saveOrigIDs = OptionsCont::getOptions().getBool("output.original-names"); - OGRFeature* poFeature; - poLayer->ResetReading(); - - const double nodeJoinDist = myOptions.getFloat("shapefile.node-join-dist"); - const std::vector params = myOptions.getStringVector("shapefile.add-params"); - - int featureIndex = 0; - bool warnNotUnique = true; - std::string idPrefix = ""; // prefix for non-unique street-id values - std::map idIndex; // running index to make street-id unique - while ((poFeature = poLayer->GetNextFeature()) != NULL) { - // read in edge attributes - if (featureIndex == 0) { - WRITE_MESSAGE("Available fields: " + toString(getFieldNames(poFeature))); - } - std::string id; - std::string name; - std::string from_node; - std::string to_node; - if (!getStringEntry(poFeature, "shapefile.street-id", "LINK_ID", true, id)) { - WRITE_ERROR("Needed field '" + id + "' (street-id) is missing."); - id = ""; - } - if (id == "") { - id = toString(myRunningEdgeID++); - } - - getStringEntry(poFeature, "shapefile.name", "ST_NAME", true, name); - name = StringUtils::replace(name, "&", "&"); - - if (!getStringEntry(poFeature, "shapefile.from-id", "REF_IN_ID", true, from_node)) { - WRITE_ERROR("Needed field '" + from_node + "' (from node id) is missing."); - from_node = ""; - } - if (!getStringEntry(poFeature, "shapefile.to-id", "NREF_IN_ID", true, to_node)) { - WRITE_ERROR("Needed field '" + to_node + "' (to node id) is missing."); - to_node = ""; - } - - if (from_node == "" || to_node == "") { - from_node = toString(myRunningNodeID++); - to_node = toString(myRunningNodeID++); - } - - std::string type; - if (myOptions.isSet("shapefile.type-id") && poFeature->GetFieldIndex(myOptions.getString("shapefile.type-id").c_str()) >= 0) { - type = poFeature->GetFieldAsString(myOptions.getString("shapefile.type-id").c_str()); - } else if (poFeature->GetFieldIndex("ST_TYP_AFT") >= 0) { - type = poFeature->GetFieldAsString("ST_TYP_AFT"); - } - if ((type != "" || myOptions.isSet("shapefile.type-id")) && !myTypeCont.knows(type)) { - WRITE_WARNINGF("Unknown type '%' for edge '%'", type, id); - } - double width = myTypeCont.getWidth(type); - bool oneway = myTypeCont.knows(type) ? myTypeCont.getIsOneWay(type) : false; - double speed = getSpeed(*poFeature, id); - int nolanes = getLaneNo(*poFeature, id, speed); - int priority = getPriority(*poFeature, id); - if (nolanes <= 0 || speed <= 0) { - if (myOptions.getBool("shapefile.use-defaults-on-failure")) { - nolanes = nolanes <= 0 ? myTypeCont.getNumLanes(type) : nolanes; - speed = speed <= 0 ? myTypeCont.getSpeed(type) : speed; - } else { - const std::string lanesField = myOptions.isSet("shapefile.laneNumber") ? myOptions.getString("shapefile.laneNumber") : "nolanes"; - const std::string speedField = myOptions.isSet("shapefile.speed") ? myOptions.getString("shapefile.speed") : "speed"; - WRITE_ERROR("Required field '" + lanesField + "' or '" + speedField + "' is missing (add fields or set option --shapefile.use-defaults-on-failure)."); - WRITE_ERROR("Available fields: " + toString(getFieldNames(poFeature))); - OGRFeature::DestroyFeature(poFeature); - return; - } - } - if (mySpeedInKMH) { - speed = speed / (double) 3.6; - } - - - // read in the geometry - OGRGeometry* poGeometry = poFeature->GetGeometryRef(); - OGRwkbGeometryType gtype = poGeometry->getGeometryType(); - if (gtype != wkbLineString && gtype != wkbLineString25D) { - OGRFeature::DestroyFeature(poFeature); - WRITE_ERROR("Road geometry must be of type 'linestring' or 'linestring25D' (found '" + toString(gtype) + "')"); - return; - } - OGRLineString* cgeom = (OGRLineString*) poGeometry; - if (poCT != nullptr) { - // try transform to wgs84 - cgeom->transform(poCT); - } - - PositionVector shape; - for (int j = 0; j < cgeom->getNumPoints(); j++) { - Position pos((double) cgeom->getX(j), (double) cgeom->getY(j), (double) cgeom->getZ(j)); - if (!NBNetBuilder::transformCoordinate(pos)) { - WRITE_WARNINGF("Unable to project coordinates for edge '%'.", id); - } - shape.push_back_noDoublePos(pos); - } - - // build from-node - NBNode* from = myNodeCont.retrieve(from_node); - if (from == 0) { - Position from_pos = shape[0]; - from = myNodeCont.retrieve(from_pos, nodeJoinDist); - if (from == 0) { - from = new NBNode(from_node, from_pos); - if (!myNodeCont.insert(from)) { - WRITE_ERROR("Node '" + from_node + "' could not be added"); - delete from; - continue; - } - } - } - // build to-node - NBNode* to = myNodeCont.retrieve(to_node); - if (to == 0) { - Position to_pos = shape[-1]; - to = myNodeCont.retrieve(to_pos, nodeJoinDist); - if (to == 0) { - to = new NBNode(to_node, to_pos); - if (!myNodeCont.insert(to)) { - WRITE_ERROR("Node '" + to_node + "' could not be added"); - delete to; - continue; - } - } - } - - if (from == to) { - WRITE_WARNINGF("Edge '%' connects identical nodes, skipping.", id); - continue; - } - - // retrieve the information whether the street is bi-directional - std::string dir; - int index = poFeature->GetDefnRef()->GetFieldIndex("DIR_TRAVEL"); - if (index >= 0 && poFeature->IsFieldSet(index)) { - dir = poFeature->GetFieldAsString(index); - } - const std::string origID = saveOrigIDs ? id : ""; - // check for duplicate ids - NBEdge* existing = myEdgeCont.retrieve(id); - NBEdge* existingReverse = myEdgeCont.retrieve("-" + id); - if (existing != nullptr || existingReverse != nullptr) { - std::string duplicateID = existing != nullptr ? id : existingReverse->getID(); - if ((existing != 0 && existing->getGeometry() == shape) - || (existingReverse != 0 && existingReverse->getGeometry() == shape.reverse())) { - WRITE_ERROR("Edge '" + duplicateID + " is not unique"); - } else { - if (idIndex.count(id) == 0) { - idIndex[id] = 0; - } - idIndex[id]++; - idPrefix = id; - id += "#" + toString(idIndex[id]); - if (warnNotUnique) { - WRITE_WARNING("street-id '" + idPrefix + "' is not unique. Renaming subsequent edge to '" + id + "'"); - warnNotUnique = false; - } - } - } - // add positive direction if wanted - if (dir == "B" || dir == "F" || dir == "" || myOptions.getBool("shapefile.all-bidirectional")) { - if (myEdgeCont.retrieve(id) == 0) { - LaneSpreadFunction spread = dir == "B" || dir == "FALSE" ? LaneSpreadFunction::RIGHT : LaneSpreadFunction::CENTER; - NBEdge* edge = new NBEdge(id, from, to, type, speed, nolanes, priority, width, NBEdge::UNSPECIFIED_OFFSET, shape, name, origID, spread); - edge->setPermissions(myTypeCont.getPermissions(type)); - myEdgeCont.insert(edge); - checkSpread(edge); - addParams(edge, poFeature, params); - } else { - WRITE_ERROR("Could not create edge '" + id + "'. An edge with the same id already exists"); - } - } - // add negative direction if wanted - if ((dir == "B" || dir == "T" || myOptions.getBool("shapefile.all-bidirectional")) && !oneway) { - if (myEdgeCont.retrieve("-" + id) == 0) { - LaneSpreadFunction spread = dir == "B" || dir == "FALSE" ? LaneSpreadFunction::RIGHT : LaneSpreadFunction::CENTER; - NBEdge* edge = new NBEdge("-" + id, to, from, type, speed, nolanes, priority, width, NBEdge::UNSPECIFIED_OFFSET, shape.reverse(), name, origID, spread); - edge->setPermissions(myTypeCont.getPermissions(type)); - myEdgeCont.insert(edge); - checkSpread(edge); - addParams(edge, poFeature, params); - } else { - WRITE_ERROR("Could not create edge '-" + id + "'. An edge with the same id already exists"); - } - } - // - OGRFeature::DestroyFeature(poFeature); - featureIndex++; - } -#if GDAL_VERSION_MAJOR < 2 - OGRDataSource::DestroyDataSource(poDS); -#else - GDALClose(poDS); -#endif - PROGRESS_DONE_MESSAGE(); -#else - WRITE_ERROR("SUMO was compiled without GDAL support."); -#endif -} - -#ifdef HAVE_GDAL -double -NIImporter_ArcView::getSpeed(OGRFeature& poFeature, const std::string& edgeid) { - if (myOptions.isSet("shapefile.speed")) { - int index = poFeature.GetDefnRef()->GetFieldIndex(myOptions.getString("shapefile.speed").c_str()); - if (index >= 0 && poFeature.IsFieldSet(index)) { - const double speed = poFeature.GetFieldAsDouble(index); - if (speed <= 0) { - WRITE_WARNING("invalid value for field: '" - + myOptions.getString("shapefile.laneNumber") - + "': '" + std::string(poFeature.GetFieldAsString(index)) + "'"); - } else { - return speed; - } - } - } - if (myOptions.isSet("shapefile.type-id")) { - return myTypeCont.getSpeed(poFeature.GetFieldAsString((char*)(myOptions.getString("shapefile.type-id").c_str()))); - } - // try to get definitions as to be found in SUMO-XML-definitions - // idea by John Michael Calandrino - int index = poFeature.GetDefnRef()->GetFieldIndex("speed"); - if (index >= 0 && poFeature.IsFieldSet(index)) { - return (double) poFeature.GetFieldAsDouble(index); - } - index = poFeature.GetDefnRef()->GetFieldIndex("SPEED"); - if (index >= 0 && poFeature.IsFieldSet(index)) { - return (double) poFeature.GetFieldAsDouble(index); - } - // try to get the NavTech-information - index = poFeature.GetDefnRef()->GetFieldIndex("SPEED_CAT"); - if (index >= 0 && poFeature.IsFieldSet(index)) { - std::string def = poFeature.GetFieldAsString(index); - return NINavTeqHelper::getSpeed(edgeid, def); - } - return -1; -} - - -int -NIImporter_ArcView::getLaneNo(OGRFeature& poFeature, const std::string& edgeid, - double speed) { - if (myOptions.isSet("shapefile.laneNumber")) { - int index = poFeature.GetDefnRef()->GetFieldIndex(myOptions.getString("shapefile.laneNumber").c_str()); - if (index >= 0 && poFeature.IsFieldSet(index)) { - const int laneNumber = poFeature.GetFieldAsInteger(index); - if (laneNumber <= 0) { - WRITE_WARNING("invalid value for field '" - + myOptions.getString("shapefile.laneNumber") - + "': '" + std::string(poFeature.GetFieldAsString(index)) + "'"); - } else { - return laneNumber; - } - } - } - if (myOptions.isSet("shapefile.type-id")) { - return (int) myTypeCont.getNumLanes(poFeature.GetFieldAsString((char*)(myOptions.getString("shapefile.type-id").c_str()))); - } - // try to get definitions as to be found in SUMO-XML-definitions - // idea by John Michael Calandrino - int index = poFeature.GetDefnRef()->GetFieldIndex("nolanes"); - if (index >= 0 && poFeature.IsFieldSet(index)) { - return (int) poFeature.GetFieldAsInteger(index); - } - index = poFeature.GetDefnRef()->GetFieldIndex("NOLANES"); - if (index >= 0 && poFeature.IsFieldSet(index)) { - return (int) poFeature.GetFieldAsInteger(index); - } - index = poFeature.GetDefnRef()->GetFieldIndex("rnol"); - if (index >= 0 && poFeature.IsFieldSet(index)) { - return (int) poFeature.GetFieldAsInteger(index); - } - index = poFeature.GetDefnRef()->GetFieldIndex("LANE_CAT"); - if (index >= 0 && poFeature.IsFieldSet(index)) { - std::string def = poFeature.GetFieldAsString(index); - return NINavTeqHelper::getLaneNumber(edgeid, def, speed); - } - return 0; -} - - -int -NIImporter_ArcView::getPriority(OGRFeature& poFeature, const std::string& /*edgeid*/) { - if (myOptions.isSet("shapefile.type-id")) { - return myTypeCont.getPriority(poFeature.GetFieldAsString((char*)(myOptions.getString("shapefile.type-id").c_str()))); - } - // try to get definitions as to be found in SUMO-XML-definitions - // idea by John Michael Calandrino - int index = poFeature.GetDefnRef()->GetFieldIndex("priority"); - if (index >= 0 && poFeature.IsFieldSet(index)) { - return poFeature.GetFieldAsInteger(index); - } - index = poFeature.GetDefnRef()->GetFieldIndex("PRIORITY"); - if (index >= 0 && poFeature.IsFieldSet(index)) { - return poFeature.GetFieldAsInteger(index); - } - // try to determine priority from NavTechs FUNC_CLASS attribute - index = poFeature.GetDefnRef()->GetFieldIndex("FUNC_CLASS"); - if (index >= 0 && poFeature.IsFieldSet(index)) { - return poFeature.GetFieldAsInteger(index); - } - return 0; -} - -void -NIImporter_ArcView::checkSpread(NBEdge* e) { - NBEdge* ret = e->getToNode()->getConnectionTo(e->getFromNode()); - if (ret != 0) { - e->setLaneSpreadFunction(LaneSpreadFunction::RIGHT); - ret->setLaneSpreadFunction(LaneSpreadFunction::RIGHT); - } -} - -bool -NIImporter_ArcView::getStringEntry(OGRFeature* poFeature, const std::string& optionName, const char* defaultName, bool prune, std::string& into) { - std::string v(defaultName); - if (myOptions.isSet(optionName)) { - v = myOptions.getString(optionName); - } - if (poFeature->GetFieldIndex(v.c_str()) < 0) { - if (myOptions.isSet(optionName)) { - into = v; - return false; - } - into = ""; - return true; - } - into = poFeature->GetFieldAsString((char*)v.c_str()); - if (prune) { - into = StringUtils::prune(into); - } - return true; -} - -std::vector -NIImporter_ArcView::getFieldNames(OGRFeature* poFeature) const { - std::vector fields; - for (int i = 0; i < poFeature->GetFieldCount(); i++) { - fields.push_back(poFeature->GetFieldDefnRef(i)->GetNameRef()); - } - return fields; -} - -void -NIImporter_ArcView::addParams(NBEdge* edge, OGRFeature* poFeature, const std::vector& params) const { - for (const std::string& p : params) { - int index = poFeature->GetDefnRef()->GetFieldIndex(p.c_str()); - if (index >= 0 && poFeature->IsFieldSet(index)) { - edge->setParameter(p, poFeature->GetFieldAsString(index)); - } - } -} - -#endif - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/NIImporter_ArcView.h b/Util/OSM2ODR/src/netimport/NIImporter_ArcView.h deleted file mode 100644 index d929fb5d5..000000000 --- a/Util/OSM2ODR/src/netimport/NIImporter_ArcView.h +++ /dev/null @@ -1,178 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2002-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIImporter_ArcView.h -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @author Jakob Erdmann -/// @date Sept 2002 -/// -// Importer for networks stored in ArcView-shape format -/****************************************************************************/ -#pragma once -#include - -#include - - -// =========================================================================== -// class declarations -// =========================================================================== -class OptionsCont; -class OGRFeature; - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NIImporter_ArcView - * @brief Importer for networks stored in ArcView-shape format - * - * The current importer works only if SUMO was compiled with GDAL-support. - * If not, an error message is generated. - * - * @todo reinsert import via shapelib - */ -class NIImporter_ArcView { -public: - /** @brief Loads content of the optionally given ArcView Shape files - * - * If the option "shapefile-prefix" is set, the file stored therein is read and - * the network definition stored therein is stored within the given network - * builder. - * - * If the option "shapefile-prefix" is not set, this method simply returns. - * - * @param[in] oc The options to use - * @param[in] nb The network builder to fill - */ - static void loadNetwork(const OptionsCont& oc, NBNetBuilder& nb); - - -protected: - /** @brief Constructor - * @param[in] oc Options container to read options from - * @param[in] nc The node container to store nodes into - * @param[in] ec The edge container to store edges into - * @param[in] tc The type container to get edge types from - * @param[in] dbf_name The name of the according database file - * @param[in] shp_name The name of the according shape file - * @param[in] speedInKMH Whether the speed shall be assumed to be given in km/h - */ - NIImporter_ArcView(const OptionsCont& oc, - NBNodeCont& nc, NBEdgeCont& ec, NBTypeCont& tc, - const std::string& dbf_name, const std::string& shp_name, - bool speedInKMH); - - /// @brief Destructor - ~NIImporter_ArcView(); - - - /** @brief Loads the shape files - */ - void load(); - - -private: -#ifdef HAVE_GDAL - /** @brief Parses the maximum speed allowed on the edge currently processed - * @param[in] f The entry to read the speed from - * @param[in] edgeid The id of the edge for error output - */ - double getSpeed(OGRFeature& f, const std::string& edgeid); - - - /** @brief Parses the number of lanes of the edge currently processed - * @param[in] f The entry to read the lane number from - * @param[in] edgeid The id of the edge for error output - * @param[in] speed The edge's speed used to help determinig the edge's lane number - */ - int getLaneNo(OGRFeature& f, - const std::string& edgeid, double speed); - - /** @brief Parses the priority of the edge currently processed - * @param[in] f The entry to read the priority from - * @param[in] edgeid The id of the edge for error output - */ - int getPriority(OGRFeature& f, const std::string& edgeid); - - - /** @brief Checks whether the lane spread shall be changed - * - * If for the given edge an edge into the vice direction is already - * stored, both edges' lane spread functions are set to LaneSpreadFunction::RIGHT. - * - * @param[in] e The edge to check - */ - void checkSpread(NBEdge* e); - - - /** @brief Sets the value from the named field into "into" - * - * If the field's name was set on the command line, the value is tried to be retrieved, returning true on success. - * If it cannot be retrieved, false is retuned, and the field's name is inserted into "into". - * - * If no field name was given, the standard value (defaultName) is used. In this case, an empty string is returned - * if the field does not exist. - * @param[in] poFeature The feature to read from - * @param[in] optionName The name of the option at which an optional field name is stored - * @param[in] defaultName The field's default name - * @param[in] prune Whether the value shall be prunned - * @param[out] into The read value/missing field is stored here - */ - bool getStringEntry(OGRFeature* poFeature, const std::string& optionName, const char* defaultName, bool prune, std::string& into); - - /// @brief return all fields support by the given feature - std::vector getFieldNames(OGRFeature* poFeature) const; - - /// @brief add list of parameters to edge - void addParams(NBEdge* edge, OGRFeature* poFeature, const std::vector& params) const; - -#endif - -private: - /// @brief The options to use - const OptionsCont& myOptions; - - /// @brief The name of the shape file - std::string mySHPName; - - /// @brief A running number to assure unique edge ids - int myNameAddition; - - /// @brief The container to add nodes to - NBNodeCont& myNodeCont; - - /// @brief The container to add edges to - NBEdgeCont& myEdgeCont; - - /// @brief The container to get the types from - NBTypeCont& myTypeCont; - - /// @brief Whether the speed is given in km/h - bool mySpeedInKMH; - - /// @brief A running number to assure unique ids (as fallback) - int myRunningEdgeID; - int myRunningNodeID; - - -private: - /// @brief Invalidated copy constructor. - NIImporter_ArcView(const NIImporter_ArcView&); - - /// @brief Invalidated assignment operator. - NIImporter_ArcView& operator=(const NIImporter_ArcView&); - -}; diff --git a/Util/OSM2ODR/src/netimport/NIImporter_DlrNavteq.cpp b/Util/OSM2ODR/src/netimport/NIImporter_DlrNavteq.cpp deleted file mode 100644 index 20e583727..000000000 --- a/Util/OSM2ODR/src/netimport/NIImporter_DlrNavteq.cpp +++ /dev/null @@ -1,823 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIImporter_DlrNavteq.cpp -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date Mon, 14.04.2008 -/// -// Importer for networks stored in Elmar's format -/****************************************************************************/ -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "NILoader.h" -#include "NIImporter_DlrNavteq.h" - - -// --------------------------------------------------------------------------- -// static members -// --------------------------------------------------------------------------- -const std::string NIImporter_DlrNavteq::GEO_SCALE("1e-5"); -const int NIImporter_DlrNavteq::EdgesHandler::MISSING_COLUMN = std::numeric_limits::max(); -const std::string NIImporter_DlrNavteq::UNDEFINED("-1"); - -// =========================================================================== -// method definitions -// =========================================================================== -// --------------------------------------------------------------------------- -// static methods -// --------------------------------------------------------------------------- -void -NIImporter_DlrNavteq::loadNetwork(const OptionsCont& oc, NBNetBuilder& nb) { - // check whether the option is set (properly) - if (!oc.isSet("dlr-navteq-prefix")) { - return; - } - time_t csTime; - time(&csTime); - // parse file(s) - LineReader lr; - // load nodes - std::map myGeoms; - PROGRESS_BEGIN_MESSAGE("Loading nodes"); - std::string file = oc.getString("dlr-navteq-prefix") + "_nodes_unsplitted.txt"; - NodesHandler handler1(nb.getNodeCont(), file, myGeoms); - if (!lr.setFile(file)) { - throw ProcessError("The file '" + file + "' could not be opened."); - } - lr.readAll(handler1); - PROGRESS_DONE_MESSAGE(); - - // load street names if given and wished - std::map streetNames; // nameID : name - if (oc.getBool("output.street-names")) { - file = oc.getString("dlr-navteq-prefix") + "_names.txt"; - if (lr.setFile(file)) { - PROGRESS_BEGIN_MESSAGE("Loading street names"); - NamesHandler handler4(file, streetNames); - lr.readAll(handler4); - PROGRESS_DONE_MESSAGE(); - } else { - WRITE_WARNING("Output will not contain street names because the file '" + file + "' was not found"); - } - } - - // load edges - PROGRESS_BEGIN_MESSAGE("Loading edges"); - file = oc.getString("dlr-navteq-prefix") + "_links_unsplitted.txt"; - // parse the file - EdgesHandler handler2(nb.getNodeCont(), nb.getEdgeCont(), nb.getTypeCont(), file, myGeoms, streetNames); - if (!lr.setFile(file)) { - throw ProcessError("The file '" + file + "' could not be opened."); - } - lr.readAll(handler2); - nb.getEdgeCont().recheckLaneSpread(); - PROGRESS_DONE_MESSAGE(); - - // load traffic lights if given - file = oc.getString("dlr-navteq-prefix") + "_traffic_signals.txt"; - if (lr.setFile(file)) { - PROGRESS_BEGIN_MESSAGE("Loading traffic lights"); - TrafficlightsHandler handler3(nb.getNodeCont(), nb.getTLLogicCont(), nb.getEdgeCont(), file); - lr.readAll(handler3); - PROGRESS_DONE_MESSAGE(); - } - - // load prohibited manoeuvres if given - file = oc.getString("dlr-navteq-prefix") + "_prohibited_manoeuvres.txt"; - if (lr.setFile(file)) { - PROGRESS_BEGIN_MESSAGE("Loading prohibited manoeuvres"); - ProhibitionHandler handler6(nb.getEdgeCont(), file, csTime); - lr.readAll(handler6); - PROGRESS_DONE_MESSAGE(); - } - - // load connected lanes if given - file = oc.getString("dlr-navteq-prefix") + "_connected_lanes.txt"; - if (lr.setFile(file)) { - PROGRESS_BEGIN_MESSAGE("Loading connected lanes"); - ConnectedLanesHandler handler7(nb.getEdgeCont()); - lr.readAll(handler7); - PROGRESS_DONE_MESSAGE(); - } - - // load time restrictions if given - file = oc.getString("dlr-navteq-prefix") + "_links_timerestrictions.txt"; - if (lr.setFile(file)) { - PROGRESS_BEGIN_MESSAGE("Loading time restrictions"); - if (!oc.isDefault("construction-date")) { - csTime = readDate(oc.getString("construction-date")); - } - TimeRestrictionsHandler handler5(nb.getEdgeCont(), nb.getDistrictCont(), csTime); - lr.readAll(handler5); - handler5.printSummary(); - PROGRESS_DONE_MESSAGE(); - } -} - -double -NIImporter_DlrNavteq::readVersion(const std::string& line, const std::string& file) { - assert(line[0] == '#'); - const std::string marker = "extraction version: v"; - const std::string lowerCase = StringUtils::to_lower_case(line); - if (lowerCase.find(marker) == std::string::npos) { - return -1; - } - const int vStart = (int)(lowerCase.find(marker) + marker.size()); - const int vEnd = (int)line.find(" ", vStart); - try { - const double version = StringUtils::toDouble(line.substr(vStart, vEnd - vStart)); - if (version < 0) { - throw ProcessError("Invalid version number '" + toString(version) + "' in file '" + file + "'."); - } - return version; - } catch (NumberFormatException&) { - throw ProcessError("Non-numerical value '" + line.substr(vStart, vEnd - vStart) + "' for version string in file '" + file + "'."); - } -} - - -// --------------------------------------------------------------------------- -// definitions of NIImporter_DlrNavteq::NodesHandler-methods -// --------------------------------------------------------------------------- -NIImporter_DlrNavteq::NodesHandler::NodesHandler(NBNodeCont& nc, - const std::string& file, - std::map& geoms) - : myNodeCont(nc), myGeoms(geoms) { - UNUSED_PARAMETER(file); -} - - -NIImporter_DlrNavteq::NodesHandler::~NodesHandler() {} - - -bool -NIImporter_DlrNavteq::NodesHandler::report(const std::string& result) { - if (result[0] == '#') { - return true; - } - std::string id; - double x, y; - int no_geoms, intermediate; - // parse - std::istringstream stream(result); - // id - stream >> id; - if (stream.fail()) { - throw ProcessError("Something is wrong with the following data line\n" + result); - } - // intermediate? - stream >> intermediate; - if (stream.fail()) { - if (myNodeCont.size() == 0) { // be generous with extra data at beginning of file - return true; - } - throw ProcessError("Non-numerical value for intermediate status in node " + id + "."); - } - // number of geometrical information - stream >> no_geoms; - if (stream.fail()) { - throw ProcessError("Non-numerical value for number of geometries in node " + id + "."); - } - // geometrical information - PositionVector geoms; - for (int i = 0; i < no_geoms; i++) { - stream >> x; - if (stream.fail()) { - throw ProcessError("Non-numerical value for x-position in node " + id + "."); - } - stream >> y; - if (stream.fail()) { - throw ProcessError("Non-numerical value for y-position in node " + id + "."); - } - Position pos(x, y); - if (!NBNetBuilder::transformCoordinate(pos, true)) { - throw ProcessError("Unable to project coordinates for node " + id + "."); - } - geoms.push_back(pos); - } - - if (intermediate == 0) { - NBNode* n = new NBNode(id, geoms[0]); - if (!myNodeCont.insert(n)) { - delete n; - throw ProcessError("Could not add node '" + id + "'."); - } - } else { - myGeoms[id] = geoms; - } - return true; -} - - -// --------------------------------------------------------------------------- -// definitions of NIImporter_DlrNavteq::EdgesHandler-methods -// --------------------------------------------------------------------------- -NIImporter_DlrNavteq::EdgesHandler::EdgesHandler(NBNodeCont& nc, NBEdgeCont& ec, - NBTypeCont& tc, const std::string& file, - std::map& geoms, - std::map& streetNames): - myNodeCont(nc), - myEdgeCont(ec), - myTypeCont(tc), - myGeoms(geoms), - myStreetNames(streetNames), - myVersion(0), - myFile(file) { -} - - -NIImporter_DlrNavteq::EdgesHandler::~EdgesHandler() {} - - -bool -NIImporter_DlrNavteq::EdgesHandler::report(const std::string& result) { - // parse version number from first comment line and initialize column definitions - if (result[0] == '#') { - if (!myColumns.empty()) { - return true; - } - const double version = readVersion(result, myFile); - if (version > 0) { - myVersion = version; - // init columns - const int NUM_COLUMNS = 25; // @note arrays must match this size! - const int MC = MISSING_COLUMN; - if (myVersion < 3) { - const int columns[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, MC, 12, 13, 14, 15, 16, 17, 18, 19, 20, MC, MC, -21}; - myColumns = std::vector(columns, columns + NUM_COLUMNS); - } else if (myVersion < 6) { - const int columns[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, MC, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, -23}; - myColumns = std::vector(columns, columns + NUM_COLUMNS); - } else { - const int columns[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24}; - myColumns = std::vector(columns, columns + NUM_COLUMNS); - } - } - return true; - } - if (myColumns.empty()) { - throw ProcessError("Missing version string in file '" + myFile + "'."); - } - // interpret link attributes - StringTokenizer st(result, StringTokenizer::WHITECHARS); - const std::string id = getColumn(st, LINK_ID); - // form of way (for priority and permissions) - int form_of_way; - try { - form_of_way = StringUtils::toInt(getColumn(st, FORM_OF_WAY)); - } catch (NumberFormatException&) { - throw ProcessError("Non-numerical value for form_of_way of link '" + id + "'."); - } - // brunnel type (bridge/tunnel/ferry (for permissions) - int brunnel_type; - try { - brunnel_type = StringUtils::toInt(getColumn(st, BRUNNEL_TYPE)); - } catch (NumberFormatException&) { - throw ProcessError("Non-numerical value for brunnel_type of link '" + id + "'."); - } - // priority based on street_type / frc - int priority; - try { - priority = -StringUtils::toInt(getColumn(st, FUNCTIONAL_ROAD_CLASS)); - // lower priority using form_of_way - if (form_of_way == 11) { - priority -= 1; // frontage road, very often with lowered curb - } else if (form_of_way > 11) { - priority -= 2; // parking/service access assume lowered curb - } - } catch (NumberFormatException&) { - throw ProcessError("Non-numerical value for street_type of link '" + id + "')."); - } - // street name - std::string streetName = getStreetNameFromIDs( - getColumn(st, NAME_ID1_REGIONAL), - getColumn(st, NAME_ID2_LOCAL)); - // try to get the nodes - const std::string fromID = getColumn(st, NODE_ID_FROM); - const std::string toID = getColumn(st, NODE_ID_TO); - NBNode* from = myNodeCont.retrieve(fromID); - NBNode* to = myNodeCont.retrieve(toID); - if (from == nullptr) { - throw ProcessError("The from-node '" + fromID + "' of link '" + id + "' could not be found"); - } - if (to == nullptr) { - throw ProcessError("The to-node '" + toID + "' of link '" + id + "' could not be found"); - } - // speed - double speed; - try { - speed = StringUtils::toInt(getColumn(st, SPEED_RESTRICTION, "-1")) / 3.6; - } catch (NumberFormatException&) { - throw ProcessError("Non-numerical value for the SPEED_RESTRICTION of link '" + id + "'."); - } - if (speed < 0) { - // speed category as fallback - speed = NINavTeqHelper::getSpeed(id, getColumn(st, SPEED_CATEGORY)); - } - // number of lanes - int numLanes; - try { - // EXTENDED_NUMBER_OF_LANES is prefered but may not be defined - numLanes = StringUtils::toInt(getColumn(st, EXTENDED_NUMBER_OF_LANES, "-1")); - if (numLanes == -1) { - numLanes = NINavTeqHelper::getLaneNumber(id, getColumn(st, NUMBER_OF_LANES), speed); - } - } catch (NumberFormatException&) { - throw ProcessError("Non-numerical value for the number of lanes of link '" + id + "'."); - } - - const std::string navTeqTypeId = getColumn(st, VEHICLE_TYPE) + "_" + getColumn(st, FORM_OF_WAY); - // build the edge - NBEdge* e = nullptr; - const std::string interID = getColumn(st, BETWEEN_NODE_ID); - if (interID == "-1") { - e = new NBEdge(id, from, to, myTypeCont.knows(navTeqTypeId) ? navTeqTypeId : "", speed, numLanes, priority, - NBEdge::UNSPECIFIED_WIDTH, NBEdge::UNSPECIFIED_OFFSET, streetName); - } else { - PositionVector geoms = myGeoms[interID]; - if (getColumn(st, CONNECTION, "0") == "1") { - geoms = geoms.reverse(); - } - geoms.insert(geoms.begin(), from->getPosition()); - geoms.push_back(to->getPosition()); - const std::string origID = OptionsCont::getOptions().getBool("output.original-names") ? id : ""; - e = new NBEdge(id, from, to, myTypeCont.knows(navTeqTypeId) ? navTeqTypeId : "", speed, numLanes, priority, - NBEdge::UNSPECIFIED_WIDTH, NBEdge::UNSPECIFIED_OFFSET, geoms, streetName, origID, LaneSpreadFunction::CENTER); - } - - // NavTeq imports can be done with a typemap (if supplied), if not, the old defaults are used - if (myTypeCont.knows(navTeqTypeId)) { - e->setPermissions(myTypeCont.getPermissions(navTeqTypeId)); - } else { - // add vehicle type information to the edge - const SVCPermissions allPermissions = myTypeCont.getPermissions(""); - const SVCPermissions defaultPermissions = OptionsCont::getOptions().getBool("dlr-navteq.tolerant-permissions") ? allPermissions : 0; - if (myVersion < 6.0) { - NINavTeqHelper::addVehicleClasses(*e, getColumn(st, VEHICLE_TYPE), allPermissions, defaultPermissions); - } else { - NINavTeqHelper::addVehicleClassesV6(*e, getColumn(st, VEHICLE_TYPE), allPermissions, defaultPermissions); - } - // permission modifications based on form_of_way - if (form_of_way == 14) { // pedestrian area (fussgaengerzone) - // unfortunately, the veh_type string is misleading in this case - e->disallowVehicleClass(-1, SVC_PASSENGER); - } - // permission modifications based on brunnel_type - if (brunnel_type == 10) { // ferry - e->setPermissions(SVC_SHIP, -1); - } - } - - // insert the edge to the network - if (!myEdgeCont.insert(e)) { - delete e; - throw ProcessError("Could not add edge '" + id + "'."); - } - return true; -} - - -std::string -NIImporter_DlrNavteq::EdgesHandler::getColumn(const StringTokenizer& st, ColumnName name, const std::string fallback) { - assert(!myColumns.empty()); - if (myColumns[name] == MISSING_COLUMN) { - if (fallback == "") { - throw ProcessError("Missing column " + toString(name) + "."); - } else { - return fallback; - } - } else if (myColumns[name] >= 0) { - return st.get((int)(myColumns[name])); - } else { - // negative column number implies an optional column - if ((int) st.size() <= -myColumns[name]) { - // the column is not present - if (fallback == "") { - throw ProcessError("Missing optional column " + toString(name) + " without default value."); - } else { - return fallback; - } - } else { - return st.get((int)(-myColumns[name])); - } - } -} - - -std::string -NIImporter_DlrNavteq::EdgesHandler::getStreetNameFromIDs( - const std::string& regionalID, const std::string& localID) const { - std::string result = ""; - bool hadRegional = false; - if (myStreetNames.count(regionalID) > 0) { - hadRegional = true; - result += myStreetNames[regionalID]; - } - if (myStreetNames.count(localID) > 0) { - if (hadRegional) { - result += " / "; - } - result += myStreetNames[localID]; - } - return result; -} - -// --------------------------------------------------------------------------- -// definitions of NIImporter_DlrNavteq::TrafficlightsHandler-methods -// --------------------------------------------------------------------------- -NIImporter_DlrNavteq::TrafficlightsHandler::TrafficlightsHandler(NBNodeCont& nc, - NBTrafficLightLogicCont& tlc, - NBEdgeCont& ne, - const std::string& file) : - myNodeCont(nc), - myTLLogicCont(tlc), - myEdgeCont(ne) { - UNUSED_PARAMETER(file); -} - - -NIImporter_DlrNavteq::TrafficlightsHandler::~TrafficlightsHandler() {} - - -bool -NIImporter_DlrNavteq::TrafficlightsHandler::report(const std::string& result) { -// #ID POICOL-TYPE DESCRIPTION LONGITUDE LATITUDE NAVTEQ_LINK_ID NODEID - - if (result[0] == '#') { - return true; - } - StringTokenizer st(result, StringTokenizer::WHITECHARS); - const std::string edgeID = st.get(5); - NBEdge* edge = myEdgeCont.retrieve(edgeID); - if (edge == nullptr) { - WRITE_WARNINGF("The traffic light edge '%' could not be found.", edgeID); - } else { - NBNode* node = edge->getToNode(); - if (node->getType() != SumoXMLNodeType::TRAFFIC_LIGHT) { - node->reinit(node->getPosition(), SumoXMLNodeType::TRAFFIC_LIGHT); - // @note. There may be additional information somewhere in the GDF files about traffic light type ... - TrafficLightType type = SUMOXMLDefinitions::TrafficLightTypes.get(OptionsCont::getOptions().getString("tls.default-type")); - // @note actually we could use the navteq node ID here - NBTrafficLightDefinition* tlDef = new NBOwnTLDef(node->getID(), node, 0, type); - if (!myTLLogicCont.insert(tlDef)) { - // actually, nothing should fail here - delete tlDef; - throw ProcessError("Could not allocate tls for '" + node->getID() + "'."); - } - } - } - return true; -} - - -// --------------------------------------------------------------------------- -// definitions of NIImporter_DlrNavteq::NamesHandler-methods -// --------------------------------------------------------------------------- -NIImporter_DlrNavteq::NamesHandler::NamesHandler( - const std::string& file, std::map& streetNames) : - myStreetNames(streetNames) { - UNUSED_PARAMETER(file); -} - - -NIImporter_DlrNavteq::NamesHandler::~NamesHandler() {} - - -bool -NIImporter_DlrNavteq::NamesHandler::report(const std::string& result) { -// # NAME_ID Name - if (result[0] == '#') { - return true; - } - StringTokenizer st(result, StringTokenizer::TAB); - if (st.size() == 1) { - return true; // one line with the number of data containing lines in it (also starts with a comment # since ersion 6.5) - } - assert(st.size() >= 2); - const std::string id = st.next(); - if (st.size() > 2) { - const std::string permanent_id_info = st.next(); - } - myStreetNames[id] = st.next(); - return true; -} - - -// --------------------------------------------------------------------------- -// definitions of NIImporter_DlrNavteq::TimeRestrictionsHandler-methods -// --------------------------------------------------------------------------- -NIImporter_DlrNavteq::TimeRestrictionsHandler::TimeRestrictionsHandler(NBEdgeCont& ec, NBDistrictCont& dc, time_t constructionTime): - myEdgeCont(ec), - myDistrictCont(dc), - myConstructionTime(constructionTime), - myCS_min(std::numeric_limits::max()), - myCS_max(std::numeric_limits::min()), - myConstructionEntries(0), - myNotStarted(0), - myUnderConstruction(0), - myFinished(0), - myRemovedEdges(0) { -} - - -NIImporter_DlrNavteq::TimeRestrictionsHandler::~TimeRestrictionsHandler() {} - - -bool -NIImporter_DlrNavteq::TimeRestrictionsHandler::report(const std::string& result) { -// # NAME_ID Name - if (result[0] == '#') { - return true; - } - StringTokenizer st(result, StringTokenizer::WHITECHARS); - const std::string id = st.next(); - const std::string type = st.next(); - const std::string directionOfFlow = st.next(); // can be ignored since unidirectional edge ids are referenced in the file - const std::string throughTraffic = st.next(); - const std::string vehicleType = st.next(); - const std::string validityPeriod = st.next(); - const std::string warning = "Unrecognized TIME_REC '" + validityPeriod + "'"; - if (type == "CS") { - myConstructionEntries++; - if (validityPeriod.size() > 1024) { - WRITE_WARNING(warning); - } - // construction - char start[1024]; - char duration[1024]; - - int matched; - - matched = sscanf(validityPeriod.c_str(), "[(%[^)]){%[^}]}]", start, duration); - if (matched == 2) { - time_t tStart = readTimeRec(start, ""); - time_t tEnd = readTimeRec(start, duration); - myCS_min = MIN2(myCS_min, tStart); - myCS_max = MAX2(myCS_max, tEnd); - //std::cout << " start=" << start << " tStart=" << tStart<< " translation=" << asctime(localtime(&tStart)) << ""; - //std::cout << " duration=" << duration << " tEnd=" << tEnd << " translation=" << asctime(localtime(&tEnd)) << "\n"; - if (myConstructionTime < tEnd) { - NBEdge* edge = myEdgeCont.retrieve(id); - if (edge != nullptr) { - myRemovedEdges++; - myEdgeCont.extract(myDistrictCont, edge, true); - } - if (myConstructionTime < tStart) { - myNotStarted++; - } else { - myUnderConstruction++; - } - } else { - myFinished++; - } - } else { - WRITE_WARNING(warning); - }; - } - return true; -} - - -void -NIImporter_DlrNavteq::TimeRestrictionsHandler::printSummary() { - if (myConstructionEntries > 0) { - char buff[1024]; - std::ostringstream msg; - strftime(buff, 1024, "%Y-%m-%d", localtime(&myCS_min)); - msg << "Parsed " << myConstructionEntries << " construction entries between " << buff; - strftime(buff, 1024, "%Y-%m-%d", localtime(&myCS_max)); - msg << " and " << buff << ".\n"; - strftime(buff, 1024, "%Y-%m-%d", localtime(&myConstructionTime)); - msg << "Removed " << myRemovedEdges << " edges not yet constructed at " << buff << ".\n"; - msg << " not yet started: " << myNotStarted << "\n"; - msg << " under construction: " << myUnderConstruction << "\n"; - msg << " finished: " << myFinished << "\n"; - WRITE_MESSAGE(msg.str()); - } -} - - -int -NIImporter_DlrNavteq::readPrefixedInt(const std::string& s, const std::string& prefix, int fallBack) { - int result = fallBack; - size_t pos = s.find(prefix); - if (pos != std::string::npos) { - sscanf(s.substr(pos).c_str(), (prefix + "%i").c_str(), &result); - } - return result; -} - -time_t -NIImporter_DlrNavteq::readTimeRec(const std::string& start, const std::string& duration) { - // http://www.cplusplus.com/reference/ctime/mktime/ - struct tm timeinfo; - timeinfo.tm_hour = 0; - timeinfo.tm_min = 0; - timeinfo.tm_sec = 0; - timeinfo.tm_year = 0; - timeinfo.tm_mon = 0; - timeinfo.tm_mday = 1; - timeinfo.tm_wday = 0; - timeinfo.tm_yday = 0; - timeinfo.tm_isdst = 0; - - timeinfo.tm_year = readPrefixedInt(start, "y") + readPrefixedInt(duration, "y") - 1900; - timeinfo.tm_mon = readPrefixedInt(start, "M") + readPrefixedInt(duration, "M") - 1; - timeinfo.tm_mday = 7 * (readPrefixedInt(start, "w") + readPrefixedInt(duration, "w")); - timeinfo.tm_mday += readPrefixedInt(start, "d") + readPrefixedInt(duration, "d"); - - time_t result = mktime(&timeinfo); - return result; -} - - -time_t -NIImporter_DlrNavteq::readDate(const std::string& yyyymmdd) { - struct tm timeinfo; - timeinfo.tm_hour = 0; - timeinfo.tm_min = 0; - timeinfo.tm_sec = 0; - timeinfo.tm_wday = 0; - timeinfo.tm_yday = 0; - timeinfo.tm_isdst = 0; - - if (yyyymmdd.size() == 10 - && yyyymmdd[4] == '-' - && yyyymmdd[7] == '-') { - try { - timeinfo.tm_year = StringUtils::toInt(yyyymmdd.substr(0, 4)) - 1900; - timeinfo.tm_mon = StringUtils::toInt(yyyymmdd.substr(5, 2)) - 1; - timeinfo.tm_mday = StringUtils::toInt(yyyymmdd.substr(8, 2)); - return mktime(&timeinfo); - } catch (...) { - } - } - WRITE_ERROR("Could not parse YYYY-MM-DD date '" + yyyymmdd + "'"); - time_t now; - time(&now); - return now; -} - -// --------------------------------------------------------------------------- -// definitions of NIImporter_DlrNavteq::ProhibitionHandler-methods -// --------------------------------------------------------------------------- -NIImporter_DlrNavteq::ProhibitionHandler::ProhibitionHandler( - NBEdgeCont& ec, const std::string& file, time_t constructionTime) : - myEdgeCont(ec), - myFile(file), - myVersion(0), - myConstructionTime(constructionTime) { -} - - -NIImporter_DlrNavteq::ProhibitionHandler::~ProhibitionHandler() {} - - -bool -NIImporter_DlrNavteq::ProhibitionHandler::report(const std::string& result) { -// # NAME_ID Name - if (result[0] == '#') { - if (myVersion == 0) { - const double version = readVersion(result, myFile); - if (version > 0) { - myVersion = version; - } - } - return true; - } - StringTokenizer st(result, StringTokenizer::TAB); - if (st.size() == 1) { - return true; // one line with the number of data containing lines in it (also starts with a comment # since ersion 6.5) - } - if (myVersion >= 6) { - assert(st.size() >= 7); - const std::string id = st.next(); - const std::string permanent = st.next(); - const std::string validityPeriod = st.next(); - const std::string throughTraffic = st.next(); - const std::string vehicleType = st.next(); - if (validityPeriod != UNDEFINED) { - WRITE_WARNINGF("Ignoring temporary prohibited manoeuvre (%).", validityPeriod); - return true; - } - } - const std::string startEdge = st.next(); - const std::string endEdge = st.get(st.size() - 1); - - NBEdge* from = myEdgeCont.retrieve(startEdge); - if (from == nullptr) { - WRITE_WARNINGF("Ignoring prohibition from unknown start edge '%'.", startEdge); - return true; - } - NBEdge* to = myEdgeCont.retrieve(endEdge); - if (to == nullptr) { - WRITE_WARNINGF("Ignoring prohibition from unknown end edge '%'.", endEdge); - return true; - } - from->removeFromConnections(to, -1, -1, true); - return true; -} - - -// --------------------------------------------------------------------------- -// definitions of NIImporter_DlrNavteq::ConnectedLanesHandler-methods -// --------------------------------------------------------------------------- -NIImporter_DlrNavteq::ConnectedLanesHandler::ConnectedLanesHandler( - NBEdgeCont& ec) : - myEdgeCont(ec) { -} - - -NIImporter_DlrNavteq::ConnectedLanesHandler::~ConnectedLanesHandler() {} - - -bool -NIImporter_DlrNavteq::ConnectedLanesHandler::report(const std::string& result) { - if (result[0] == '#') { - return true; - } - StringTokenizer st(result, StringTokenizer::TAB); - if (st.size() == 1) { - return true; // one line with the number of data containing lines in it (also starts with a comment # since ersion 6.5) - } - assert(st.size() >= 7); - const std::string nodeID = st.next(); - const std::string vehicleType = st.next(); - const std::string fromLaneS = st.next(); - const std::string toLaneS = st.next(); - const std::string throughTraffic = st.next(); - const std::string startEdge = st.next(); - const std::string endEdge = st.get(st.size() - 1); - - NBEdge* from = myEdgeCont.retrieve(startEdge); - if (from == nullptr) { - WRITE_WARNINGF("Ignoring prohibition from unknown start edge '%'.", startEdge); - return true; - } - NBEdge* to = myEdgeCont.retrieve(endEdge); - if (to == nullptr) { - WRITE_WARNINGF("Ignoring prohibition from unknown end edge '%'.", endEdge); - return true; - } - int fromLane = StringUtils::toInt(fromLaneS) - 1; // one based - if (fromLane < 0 || fromLane >= from->getNumLanes()) { - WRITE_WARNINGF("Ignoring invalid lane index '%' in connection from edge '%' with % lanes.", fromLaneS, startEdge, from->getNumLanes()); - return true; - } - int toLane = StringUtils::toInt(toLaneS) - 1; // one based - if (toLane < 0 || toLane >= to->getNumLanes()) { - WRITE_WARNINGF("Ignoring invalid lane index '%' in connection to edge '%' with % lanes", toLaneS, endEdge, to->getNumLanes()); - return true; - } - if (!from->addLane2LaneConnection(fromLane, to, toLane, NBEdge::Lane2LaneInfoType::USER, true)) { - if (OptionsCont::getOptions().getBool("show-errors.connections-first-try")) { - WRITE_WARNINGF("Could not set loaded connection from '%' to '%'.", from->getLaneID(fromLane), to->getLaneID(toLane)); - } - // set as to be re-applied after network processing - // if this connection runs across a node cluster it may not be possible to set this - const bool warnOnly = st.size() > 7; - myEdgeCont.addPostProcessConnection(from->getID(), fromLane, to->getID(), toLane, false, true, - NBEdge::UNSPECIFIED_CONTPOS, NBEdge::UNSPECIFIED_VISIBILITY_DISTANCE, - NBEdge::UNSPECIFIED_SPEED, NBEdge::UNSPECIFIED_LOADED_LENGTH, PositionVector::EMPTY, false, warnOnly); - } - // ensure that connections for other lanes are guessed if not specified - from->declareConnectionsAsLoaded(NBEdge::EdgeBuildingStep::INIT); - from->getLaneStruct(fromLane).connectionsDone = true; - return true; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/NIImporter_DlrNavteq.h b/Util/OSM2ODR/src/netimport/NIImporter_DlrNavteq.h deleted file mode 100644 index 341981808..000000000 --- a/Util/OSM2ODR/src/netimport/NIImporter_DlrNavteq.h +++ /dev/null @@ -1,514 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2008-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIImporter_DlrNavteq.h -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @author Jakob Erdmann -/// @date Mon, 14.04.2008 -/// -// Importer for networks stored in Elmar's format -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include -#include - - -// =========================================================================== -// class declarations -// =========================================================================== -class NBEdgeCont; -class NBNetBuilder; -class NBNodeCont; -class NBTrafficLightLogicCont; -class NBTypeCont; -class OptionsCont; -class PositionVector; -class StringTokenizer; - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NIImporter_DlrNavteq - * @brief Importer for networks stored in Elmar's format - * - */ -class NIImporter_DlrNavteq { -public: - /** @brief Loads content of the optionally given dlr-navteq (aka Elmar-fomat) folder - * - * If the option "dlr-navteq-prefix" is set, the file(s) stored therein is read and - * the network definition stored therein is stored within the given network - * builder. - * - * If the option "dlr-navteq-prefix" is not set, this method simply returns. - * - * @param[in] oc The options to use - * @param[in] nb The network builder to fill - */ - static void loadNetwork(const OptionsCont& oc, NBNetBuilder& nb); - - /// @brief scaling factor for geo coordinates (DLRNavteq format uses this to increase floating point precisions) - static const std::string GEO_SCALE; - - /// @brief magic value for undefined stuff - static const std::string UNDEFINED; - -protected: - /** - * @class NodesHandler - * @brief Importer of nodes stored in unsplit elmar format - * - * Being a LineHandler, this class retrieves each line from a LineReader - * and parses these information assuming they contain node definitions - * in DLRNavteq's unsplit format. - */ - class NodesHandler : public LineHandler { - public: - /** @brief Constructor - * @param[in, filled] nc The node control to insert loaded nodes into - * @param[in] file The name of the parsed file - * @param[in, geoms] geoms Storage for read edge geometries - */ - NodesHandler(NBNodeCont& nc, const std::string& file, - std::map& geoms); - - - /// @brief Destructor - ~NodesHandler(); - - - /** @brief Parsing method - * - * Implementation of the LineHandler-interface called by a LineReader; - * interprets the retrieved information and stores it into "myNodeCont". - * Additionally, edge geometries are parsed and stored into "myGeoms". - * - * @param[in] result The read line - * @return Whether the parsing shall continue - * @exception ProcessError if something fails - * @see LineHandler::report - */ - bool report(const std::string& result); - - - protected: - // @brief The node container to store parsed nodes into - NBNodeCont& myNodeCont; - - /// @brief A container for parsed geometries - std::map& myGeoms; - - - private: - /// @brief Invalidated copy constructor. - NodesHandler(const NodesHandler&); - - /// @brief Invalidated assignment operator. - NodesHandler& operator=(const NodesHandler&); - - }; - - - /** - * @class EdgesHandler - * @brief Importer of edges stored in unsplit elmar format - * - * Being a LineHandler, this class retrieves each line from a LineReader - * and parses these information assuming they contain edge definitions - * in DLRNavteq's unsplit format. - */ - class EdgesHandler : public LineHandler { - - public: - /** @brief Constructor - * @param[in] nc The node control to retrieve nodes from - * @param[in, filled] ec The edge control to insert loaded edges into - * @param[in] tc The type control to retrieve types from - * @param[in] file The name of the parsed file - * @param[in] geoms The previously read edge geometries - * @param[in] streetNames The previously read street names - */ - EdgesHandler(NBNodeCont& nc, NBEdgeCont& ec, NBTypeCont& tc, - const std::string& file, - std::map& geoms, - std::map& streetNames); - - - /// @brief Destructor - ~EdgesHandler(); - - - /** @brief Parsing method - * - * Implementation of the LineHandler-interface called by a LineReader; - * interprets the retrieved information and stores it into "myEdgeCont". - * @param[in] result The read line - * @return Whether the parsing shall continue - * @exception ProcessError if something fails - * @see LineHandler::report - */ - bool report(const std::string& result); - - - protected: - /// @brief The node container to get the referenced nodes from - NBNodeCont& myNodeCont; - - /// @brief The edge container to store loaded edges into - NBEdgeCont& myEdgeCont; - - /// @brief The type container to retrieve type info from - NBTypeCont& myTypeCont; - - /// @brief Previously read edge geometries (manipulated during use) - std::map& myGeoms; - - /// @brief Previously read streat names (non-const because operate[] is more convenient) - std::map& myStreetNames; - - /// @brief Whether node positions shall not be added to the edge's geometry - bool myTryIgnoreNodePositions; - - /// @brief version number of current file - double myVersion; - - /// @brief the version number of the edge file being parsed - std::vector myColumns; - - /// @brief the file being parsed - const std::string myFile; - - static const int MISSING_COLUMN; - - enum ColumnName { - LINK_ID = 0, - NODE_ID_FROM, - NODE_ID_TO, - BETWEEN_NODE_ID, - LENGTH, - VEHICLE_TYPE, - FORM_OF_WAY, - BRUNNEL_TYPE, - FUNCTIONAL_ROAD_CLASS, - SPEED_CATEGORY, - NUMBER_OF_LANES, - SPEED_LIMIT, - SPEED_RESTRICTION, - NAME_ID1_REGIONAL, - NAME_ID2_LOCAL, - HOUSENUMBERS_RIGHT, - HOUSENUMBERS_LEFT, - ZIP_CODE, - AREA_ID, - SUBAREA_ID, - THROUGH_TRAFFIC, - SPECIAL_RESTRICTIONS, - EXTENDED_NUMBER_OF_LANES, - ISRAMP, - CONNECTION - }; - - std::string getColumn(const StringTokenizer& st, ColumnName name, const std::string fallback = ""); - - private: - /// @brief build the street name for the given ids - std::string getStreetNameFromIDs(const std::string& regionalID, const std::string& localID) const; - - - private: - /// @brief Invalidated copy constructor. - EdgesHandler(const EdgesHandler&); - - /// @brief Invalidated assignment operator. - EdgesHandler& operator=(const EdgesHandler&); - - }; - - - /** - * @class TrafficlightsHandler - * @brief Importer of traffic lights stored in DLRNavteq's (aka elmar) format - * - * Being a LineHandler, this class retrieves each line from a LineReader - * and parses these information assuming they contain traffic light definitions - * in DLRNavteq's format. - */ - class TrafficlightsHandler : public LineHandler { - public: - /** @brief Constructor - * @param[in] nc The node control to retrieve nodes from - * @param[in, filled] tlc The traffic lights container to fill - * @param[in] file The name of the parsed file - */ - TrafficlightsHandler(NBNodeCont& nc, NBTrafficLightLogicCont& tlc, - NBEdgeCont& ne, const std::string& file); - - - /// @brief Destructor - ~TrafficlightsHandler(); - - - /** @brief Parsing method - * - * Implementation of the LineHandler-interface called by a LineReader; - * interprets the retrieved information and alters the nodes. - * @param[in] result The read line - * @return Whether the parsing shall continue - * @exception ProcessError if something fails - * @see LineHandler::report - */ - bool report(const std::string& result); - - - protected: - /// @brief The node container to get the referenced nodes from - NBNodeCont& myNodeCont; - - /// @brief The traffic lights container to add built tls to - NBTrafficLightLogicCont& myTLLogicCont; - - /// @brief The edge container to get the referenced edges from - NBEdgeCont& myEdgeCont; - - - private: - /// @brief Invalidated copy constructor. - TrafficlightsHandler(const TrafficlightsHandler&); - - /// @brief Invalidated assignment operator. - TrafficlightsHandler& operator=(const TrafficlightsHandler&); - - }; - - - /** - * @class NamesHandler - * @brief Importer of street names in DLRNavteq's (aka elmar) format - * - * Being a LineHandler, this class retrieves each line from a LineReader - * and parses these information assuming they contain name definitions - * in DLRNavteq's format. - */ - class NamesHandler : public LineHandler { - public: - /** @brief Constructor - * @param[in] file The name of the parsed file - * @param[filled] streetNames output container for read names - */ - NamesHandler(const std::string& file, std::map& streetNames); - - - /// @brief Destructor - ~NamesHandler(); - - - /** @brief Parsing method - * - * Implementation of the LineHandler-interface called by a LineReader; - * interprets the retrieved information and stores the streetNames - * @param[in] result The read line - * @return Whether the parsing shall continue - * @exception ProcessError if something fails - * @see LineHandler::report - */ - bool report(const std::string& result); - - - protected: - /// @brief The container for storing read names - std::map& myStreetNames; - - - private: - /// @brief Invalidated copy constructor. - NamesHandler(const NamesHandler&); - - /// @brief Invalidated assignment operator. - NamesHandler& operator=(const NamesHandler&); - - }; - - - /** - * @class TimeRestrictionsHandler - * @brief Importer of street names in DLRNavteq's (aka elmar) format - * - * Being a LineHandler, this class retrieves each line from a LineReader - * and parses these information assuming they contain name definitions - * in DLRNavteq's format. - */ - class TimeRestrictionsHandler : public LineHandler { - public: - /** @brief Constructor - * @param[in] file The name of the parsed file - * @param[filled] streetNames output container for read names - */ - TimeRestrictionsHandler(NBEdgeCont& ec, NBDistrictCont& dc, time_t constructionTime); - - - /// @brief Destructor - ~TimeRestrictionsHandler(); - - - /** @brief Parsing method - * - * Implementation of the LineHandler-interface called by a LineReader; - * interprets the retrieved information and stores the streetNames - * @param[in] result The read line - * @return Whether the parsing shall continue - * @exception ProcessError if something fails - * @see LineHandler::report - */ - bool report(const std::string& result); - - void printSummary(); - - - protected: - /// @brief The edge container - NBEdgeCont& myEdgeCont; - NBDistrictCont& myDistrictCont; - - /// @brief The date for which to build the network (in case some edges are still under construction) - time_t myConstructionTime; - time_t myCS_min; - time_t myCS_max; - int myConstructionEntries; - int myNotStarted; - int myUnderConstruction; - int myFinished; - int myRemovedEdges; // only counts those not already removed through other options - - - private: - /// @brief Invalidated copy constructor. - TimeRestrictionsHandler(const TimeRestrictionsHandler&); - - /// @brief Invalidated assignment operator. - TimeRestrictionsHandler& operator=(const TimeRestrictionsHandler&); - - }; - - - /** - * @class ProhibitionHandler - * @brief Imports prohibitions regarding connectivity - * - * Being a LineHandler, this class retrieves each line from a LineReader - * and parses these information assuming they contain prohibited manoeuver definitions - * in DLRNavteq's format. - */ - class ProhibitionHandler : public LineHandler { - public: - /** @brief Constructor - * @param[in] file The name of the parsed file - * @param[filled] streetNames output container for read names - */ - ProhibitionHandler(NBEdgeCont& ne, const std::string& file, time_t constructionTime); - - - /// @brief Destructor - ~ProhibitionHandler(); - - - /** @brief Parsing method - * - * Implementation of the LineHandler-interface called by a LineReader; - * interprets the retrieved information and stores the streetNames - * @param[in] result The read line - * @return Whether the parsing shall continue - * @exception ProcessError if something fails - * @see LineHandler::report - */ - bool report(const std::string& result); - - - protected: - /// @brief The edge container to store loaded edges into - NBEdgeCont& myEdgeCont; - const std::string myFile; - double myVersion; - time_t myConstructionTime; - - - private: - /// @brief Invalidated copy constructor. - ProhibitionHandler(const ProhibitionHandler&); - - /// @brief Invalidated assignment operator. - ProhibitionHandler& operator=(const ProhibitionHandler&); - - }; - - - /** - * @class ConnectedLanesHandler - * @brief Imports prohibitions regarding connectivity - * - * Being a LineHandler, this class retrieves each line from a LineReader - * and parses these information assuming they contain prohibited manoeuver definitions - * in DLRNavteq's format. - */ - class ConnectedLanesHandler : public LineHandler { - public: - /** @brief Constructor - * @param[in] file The name of the parsed file - * @param[filled] streetNames output container for read names - */ - ConnectedLanesHandler(NBEdgeCont& ne); - - - /// @brief Destructor - ~ConnectedLanesHandler(); - - - /** @brief Parsing method - * - * Implementation of the LineHandler-interface called by a LineReader; - * interprets the retrieved information and stores the streetNames - * @param[in] result The read line - * @return Whether the parsing shall continue - * @exception ProcessError if something fails - * @see LineHandler::report - */ - bool report(const std::string& result); - - - protected: - /// @brief The edge container to store loaded edges into - NBEdgeCont& myEdgeCont; - - - private: - /// @brief Invalidated copy constructor. - ConnectedLanesHandler(const ConnectedLanesHandler&); - - /// @brief Invalidated assignment operator. - ConnectedLanesHandler& operator=(const ConnectedLanesHandler&); - - }; - - - static double readVersion(const std::string& line, const std::string& file); - static int readPrefixedInt(const std::string& s, const std::string& prefix, int fallBack = 0); - static time_t readTimeRec(const std::string& start, const std::string& duration); - static time_t readDate(const std::string& yyyymmdd); - -}; diff --git a/Util/OSM2ODR/src/netimport/NIImporter_ITSUMO.cpp b/Util/OSM2ODR/src/netimport/NIImporter_ITSUMO.cpp deleted file mode 100644 index 3aa21931f..000000000 --- a/Util/OSM2ODR/src/netimport/NIImporter_ITSUMO.cpp +++ /dev/null @@ -1,300 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2011-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIImporter_ITSUMO.cpp -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date 2011-09-16 -/// -// Importer for networks stored in ITSUMO format -/****************************************************************************/ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "NILoader.h" -#include "NIImporter_ITSUMO.h" - - - -// =========================================================================== -// static variables -// =========================================================================== -StringBijection::Entry NIImporter_ITSUMO::itsumoTags[] = { - { "simulation", NIImporter_ITSUMO::ITSUMO_TAG_SIMULATION }, - { "network_id", NIImporter_ITSUMO::ITSUMO_TAG_NETWORK_ID }, - { "network_name", NIImporter_ITSUMO::ITSUMO_TAG_NETWORK_NAME }, - { "nodes", NIImporter_ITSUMO::ITSUMO_TAG_NODES }, - { "node", NIImporter_ITSUMO::ITSUMO_TAG_NODE }, - { "node_id", NIImporter_ITSUMO::ITSUMO_TAG_NODE_ID }, - { "node_name", NIImporter_ITSUMO::ITSUMO_TAG_NODE_NAME }, - { "x_coord", NIImporter_ITSUMO::ITSUMO_TAG_X_COORD }, - { "y_coord", NIImporter_ITSUMO::ITSUMO_TAG_Y_COORD }, - { "sources", NIImporter_ITSUMO::ITSUMO_TAG_SOURCES }, - { "sinks", NIImporter_ITSUMO::ITSUMO_TAG_SINKS }, - { "traffic_lights", NIImporter_ITSUMO::ITSUMO_TAG_TRAFFIC_LIGHTS }, - { "streets", NIImporter_ITSUMO::ITSUMO_TAG_STREETS }, - { "street", NIImporter_ITSUMO::ITSUMO_TAG_STREET }, - { "street_id", NIImporter_ITSUMO::ITSUMO_TAG_STREET_ID }, - { "street_name", NIImporter_ITSUMO::ITSUMO_TAG_STREET_NAME }, - { "sections", NIImporter_ITSUMO::ITSUMO_TAG_SECTIONS }, - { "section", NIImporter_ITSUMO::ITSUMO_TAG_SECTION }, - { "section_id", NIImporter_ITSUMO::ITSUMO_TAG_SECTION_ID }, - { "section_name", NIImporter_ITSUMO::ITSUMO_TAG_SECTION_NAME }, - { "is_preferencial", NIImporter_ITSUMO::ITSUMO_TAG_IS_PREFERENCIAL }, - { "delimiting_node", NIImporter_ITSUMO::ITSUMO_TAG_DELIMITING_NODE }, - { "lanesets", NIImporter_ITSUMO::ITSUMO_TAG_LANESETS }, - { "laneset", NIImporter_ITSUMO::ITSUMO_TAG_LANESET }, - { "laneset_id", NIImporter_ITSUMO::ITSUMO_TAG_LANESET_ID }, - { "laneset_position", NIImporter_ITSUMO::ITSUMO_TAG_LANESET_POSITION }, - { "start_node", NIImporter_ITSUMO::ITSUMO_TAG_START_NODE }, - { "end_node", NIImporter_ITSUMO::ITSUMO_TAG_END_NODE }, - { "turning_probabilities", NIImporter_ITSUMO::ITSUMO_TAG_TURNING_PROBABILITIES }, - { "direction", NIImporter_ITSUMO::ITSUMO_TAG_DIRECTION }, - { "destination_laneset", NIImporter_ITSUMO::ITSUMO_TAG_DESTINATION_LANESET }, - { "probability", NIImporter_ITSUMO::ITSUMO_TAG_PROBABILITY }, - { "lanes", NIImporter_ITSUMO::ITSUMO_TAG_LANES }, - { "lane", NIImporter_ITSUMO::ITSUMO_TAG_LANE }, - { "lane_id", NIImporter_ITSUMO::ITSUMO_TAG_LANE_ID }, - { "lane_position", NIImporter_ITSUMO::ITSUMO_TAG_LANE_POSITION }, - { "maximum_speed", NIImporter_ITSUMO::ITSUMO_TAG_MAXIMUM_SPEED }, - { "deceleration_prob", NIImporter_ITSUMO::ITSUMO_TAG_DECELERATION_PROB }, - { "", NIImporter_ITSUMO::ITSUMO_TAG_NOTHING } -}; - - -StringBijection::Entry NIImporter_ITSUMO::itsumoAttrs[] = { - { "", NIImporter_ITSUMO::ITSUMO_ATTR_NOTHING } -}; - - -// =========================================================================== -// method definitions -// =========================================================================== -// --------------------------------------------------------------------------- -// static methods -// --------------------------------------------------------------------------- -void -NIImporter_ITSUMO::loadNetwork(const OptionsCont& oc, NBNetBuilder& nb) { - // check whether the option is set (properly) - if (!oc.isSet("itsumo-files")) { - return; - } - /* Parse file(s) - * Each file is parsed twice: first for nodes, second for edges. */ - std::vector files = oc.getStringVector("itsumo-files"); - // load nodes, first - Handler Handler(nb); - for (std::vector::const_iterator file = files.begin(); file != files.end(); ++file) { - // nodes - if (!FileHelpers::isReadable(*file)) { - WRITE_ERROR("Could not open itsumo-file '" + *file + "'."); - return; - } - Handler.setFileName(*file); - PROGRESS_BEGIN_MESSAGE("Parsing nodes from itsumo-file '" + *file + "'"); - if (!XMLSubSys::runParser(Handler, *file)) { - return; - } - PROGRESS_DONE_MESSAGE(); - } -} - - -// --------------------------------------------------------------------------- -// definitions of NIImporter_ITSUMO::Handler-methods -// --------------------------------------------------------------------------- -NIImporter_ITSUMO::Handler::Handler(NBNetBuilder& toFill) - : GenericSAXHandler(itsumoTags, ITSUMO_TAG_NOTHING, itsumoAttrs, ITSUMO_ATTR_NOTHING, "itsumo - file"), myNetBuilder(toFill) { -} - - -NIImporter_ITSUMO::Handler::~Handler() {} - - -void -NIImporter_ITSUMO::Handler::myStartElement(int element, const SUMOSAXAttributes& /* attrs */) { - switch (element) { - case ITSUMO_TAG_NODE: - myParameter.clear(); - break; - case ITSUMO_TAG_LANESET: - myParameter.clear(); - break; - default: - break; - } -} - - -void -NIImporter_ITSUMO::Handler::myCharacters(int element, const std::string& chars) { - std::string mc = StringUtils::prune(chars); - switch (element) { - // node parsing - case ITSUMO_TAG_NODE_ID: - myParameter["id"] = mc; - break; - case ITSUMO_TAG_NODE_NAME: - myParameter["name"] = mc; - break; - case ITSUMO_TAG_X_COORD: - myParameter["x"] = mc; - break; - case ITSUMO_TAG_Y_COORD: - myParameter["y"] = mc; - break; - // section parsing - case ITSUMO_TAG_SECTION_ID: - myParameter["sectionID"] = mc; - break; - // laneset parsing - case ITSUMO_TAG_LANESET_ID: - myParameter["lanesetID"] = mc; - break; - case ITSUMO_TAG_LANESET_POSITION: - myParameter["pos"] = mc; - break; - case ITSUMO_TAG_START_NODE: - myParameter["from"] = mc; - break; - case ITSUMO_TAG_END_NODE: - myParameter["to"] = mc; - break; - // lane parsing - case ITSUMO_TAG_LANE_ID: - myParameter["laneID"] = mc; - break; - case ITSUMO_TAG_LANE_POSITION: - myParameter["i"] = mc; - break; - case ITSUMO_TAG_MAXIMUM_SPEED: - myParameter["v"] = mc; - break; - default: - break; - } -} - - -void -NIImporter_ITSUMO::Handler::myEndElement(int element) { - switch (element) { - case ITSUMO_TAG_SIMULATION: { - for (std::vector::iterator i = mySections.begin(); i != mySections.end(); ++i) { - for (std::vector::iterator j = (*i)->laneSets.begin(); j != (*i)->laneSets.end(); ++j) { - LaneSet* ls = (*j); - NBEdge* edge = new NBEdge(ls->id, ls->from, ls->to, "", ls->v, (int)ls->lanes.size(), -1, NBEdge::UNSPECIFIED_WIDTH, NBEdge::UNSPECIFIED_OFFSET); - if (!myNetBuilder.getEdgeCont().insert(edge)) { - delete edge; - WRITE_ERROR("Could not add edge '" + ls->id + "'. Probably declared twice."); - } - delete ls; - } - delete *i; - } - } - break; - case ITSUMO_TAG_NODE: { - try { - std::string id = myParameter["id"]; - double x = StringUtils::toDouble(myParameter["x"]); - double y = StringUtils::toDouble(myParameter["y"]); - Position pos(x, y); - if (!NBNetBuilder::transformCoordinate(pos)) { - WRITE_ERROR("Unable to project coordinates for node '" + id + "'."); - } - NBNode* node = new NBNode(id, pos); - if (!myNetBuilder.getNodeCont().insert(node)) { - delete node; - WRITE_ERROR("Could not add node '" + id + "'. Probably declared twice."); - } - } catch (NumberFormatException&) { - WRITE_ERROR("Not numeric position information for node '" + myParameter["id"] + "'."); - } catch (EmptyData&) { - WRITE_ERROR("Missing data in node '" + myParameter["id"] + "'."); - } - } - break; - case ITSUMO_TAG_SECTION: { - mySections.push_back(new Section(myParameter["sectionID"], myCurrentLaneSets)); - myCurrentLaneSets.clear(); - } - break; - case ITSUMO_TAG_LANESET: { - try { - std::string id = myParameter["lanesetID"]; - int i = StringUtils::toInt(myParameter["i"]); - std::string fromID = myParameter["from"]; - std::string toID = myParameter["to"]; - NBNode* from = myNetBuilder.getNodeCont().retrieve(fromID); - NBNode* to = myNetBuilder.getNodeCont().retrieve(toID); - if (from == nullptr || to == nullptr) { - WRITE_ERROR("Missing node in laneset '" + myParameter["lanesetID"] + "'."); - } else { - if (myLaneSets.find(id) != myLaneSets.end()) { - WRITE_ERROR("Fond laneset-id '" + id + "' twice."); - } else { - double vSum = 0; - for (std::vector::iterator j = myCurrentLanes.begin(); j != myCurrentLanes.end(); ++j) { - vSum += (*j).v; - } - vSum /= (double) myCurrentLanes.size(); - LaneSet* ls = new LaneSet(id, myCurrentLanes, vSum, i, from, to); - myLaneSets[id] = ls; - myCurrentLaneSets.push_back(ls); - myCurrentLanes.clear(); - } - } - } catch (NumberFormatException&) { - WRITE_ERROR("Not numeric value in laneset '" + myParameter["lanesetID"] + "'."); - } catch (EmptyData&) { - WRITE_ERROR("Missing data in laneset '" + myParameter["lanesetID"] + "'."); - } - } - break; - case ITSUMO_TAG_LANE: { - try { - std::string id = myParameter["laneID"]; - int i = StringUtils::toInt(myParameter["i"]); - double v = StringUtils::toDouble(myParameter["v"]); - myCurrentLanes.push_back(Lane(id, (int) i, v)); - } catch (NumberFormatException&) { - WRITE_ERROR("Not numeric value in lane '" + myParameter["laneID"] + "'."); - } catch (EmptyData&) { - WRITE_ERROR("Missing data in lane '" + myParameter["laneID"] + "'."); - } - } - break; - default: - break; - } -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/NIImporter_ITSUMO.h b/Util/OSM2ODR/src/netimport/NIImporter_ITSUMO.h deleted file mode 100644 index 280b20b72..000000000 --- a/Util/OSM2ODR/src/netimport/NIImporter_ITSUMO.h +++ /dev/null @@ -1,239 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIImporter_ITSUMO.h -/// @author Daniel Krajzewicz -/// @date 2011-09-16 -/// -// Importer for networks stored in ITSUMO format -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include -#include -#include - - -// =========================================================================== -// class declarations -// =========================================================================== -class NBEdge; -class NBEdgeCont; -class NBNetBuilder; -class NBNode; -class NBNodeCont; -class NBTrafficLightLogicCont; -class NBTypeCont; -class OptionsCont; - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NIImporter_ITSUMO - * @brief Importer for networks stored in ITSUMO format - * - */ -class NIImporter_ITSUMO { -public: - /** @brief Loads content of the optionally given ITSUMO network files - * - * If the option "itsumo-files" is set, the file(s) stored therein is read and - * the network definition stored therein is stored within the given network - * builder. - * - * If the option "itsumo-files" is not set, this method simply returns. - * - * @param[in] oc The options to use - * @param[in] nb The network builder to fill - */ - static void loadNetwork(const OptionsCont& oc, NBNetBuilder& nb); - - -private: - /** - * @class NodesHandler - * @brief A class which parses an ITSUMO file - */ - class Handler : public GenericSAXHandler { - public: - /** @brief Contructor - * @param[in] toFill The container to fill - */ - Handler(NBNetBuilder& toFill); - - - /// @brief Destructor - ~Handler(); - - - protected: - /// @name inherited from GenericSAXHandler - //@{ - - /** @brief Called on the opening of a tag; - * - * @param[in] element ID of the currently opened element - * @param[in] attrs Attributes within the currently opened element - * @exception ProcessError If something fails - * @see GenericSAXHandler::myStartElement - */ - void myStartElement(int element, const SUMOSAXAttributes& attrs); - - - /** - * @brief Callback method for characters to implement by derived classes - * - * Called by "endElement" (see there). - * @param[in] element The opened element, given as a int - * @param[in] chars The complete embedded character string - * @exceptions ProcessError These method may throw a ProcessError if something fails - */ - void myCharacters(int element, const std::string& chars); - - - /** @brief Callback method for a closing tag to implement by derived classes - * - * Called by "endElement" (see there). - * @param[in] element The closed element, given as a int - * @exceptions ProcessError These method may throw a ProcessError if something fails - */ - void myEndElement(int element); - //@} - - - private: - /// @brief The container to fill - NBNetBuilder& myNetBuilder; - - /// @brief A temporary parameter map - std::map myParameter; - - - struct Lane { - public: - Lane(const std::string& _id, int _idx, double _v) - : id(_id), index(_idx), v(_v) {} - std::string id; - int index; - double v; - }; - - std::vector myCurrentLanes; - - struct LaneSet { - public: - LaneSet(const std::string& _id, const std::vector& _lanes, double _v, int _pos, NBNode* _from, NBNode* _to) - : id(_id), lanes(_lanes), v(_v), position(_pos), from(_from), to(_to) {} - std::string id; - std::vector lanes; - double v; - int position; - NBNode* from; - NBNode* to; - }; - - std::map myLaneSets; - std::vector myCurrentLaneSets; - - struct Section { - public: - Section(const std::string& _id, const std::vector& _laneSets) - : id(_id), laneSets(_laneSets) {} - std::string id; - std::vector laneSets; - }; - - std::vector mySections; - - - private: - /** @brief invalidated copy constructor */ - Handler(const Handler& s); - - /** @brief invalidated assignment operator */ - Handler& operator=(const Handler& s); - - }; - - - - /** - * @enum ItsumoXMLTag - * @brief Numbers representing ITSUMO-XML - element names - * @see GenericSAXHandler - */ - enum ItsumoXMLTag { - ITSUMO_TAG_NOTHING = 0, - ITSUMO_TAG_SIMULATION, - ITSUMO_TAG_NETWORK_ID, - ITSUMO_TAG_NETWORK_NAME, - ITSUMO_TAG_NODES, - ITSUMO_TAG_NODE, - ITSUMO_TAG_NODE_ID, - ITSUMO_TAG_NODE_NAME, - ITSUMO_TAG_X_COORD, - ITSUMO_TAG_Y_COORD, - ITSUMO_TAG_SOURCES, - ITSUMO_TAG_SINKS, - ITSUMO_TAG_TRAFFIC_LIGHTS, - ITSUMO_TAG_STREETS, - ITSUMO_TAG_STREET, - ITSUMO_TAG_STREET_ID, - ITSUMO_TAG_STREET_NAME, - ITSUMO_TAG_SECTIONS, - ITSUMO_TAG_SECTION, - ITSUMO_TAG_SECTION_ID, - ITSUMO_TAG_SECTION_NAME, - ITSUMO_TAG_IS_PREFERENCIAL, - ITSUMO_TAG_DELIMITING_NODE, - ITSUMO_TAG_LANESETS, - ITSUMO_TAG_LANESET, - ITSUMO_TAG_LANESET_ID, - ITSUMO_TAG_LANESET_POSITION, - ITSUMO_TAG_START_NODE, - ITSUMO_TAG_END_NODE, - ITSUMO_TAG_TURNING_PROBABILITIES, - ITSUMO_TAG_DIRECTION, - ITSUMO_TAG_DESTINATION_LANESET, - ITSUMO_TAG_PROBABILITY, - ITSUMO_TAG_LANES, - ITSUMO_TAG_LANE, - ITSUMO_TAG_LANE_ID, - ITSUMO_TAG_LANE_POSITION, - ITSUMO_TAG_MAXIMUM_SPEED, - ITSUMO_TAG_DECELERATION_PROB - }; - - - /** - * @enum ItsumoXMLAttr - * @brief Numbers representing MATSIM-XML - attributes - * @see GenericSAXHandler - */ - enum ItsumoXMLAttr { - ITSUMO_ATTR_NOTHING = 0 - }; - - /// The names of MATSIM-XML elements (for passing to GenericSAXHandler) - static StringBijection::Entry itsumoTags[]; - - /// The names of MATSIM-XML attributes (for passing to GenericSAXHandler) - static StringBijection::Entry itsumoAttrs[]; - - -}; diff --git a/Util/OSM2ODR/src/netimport/NIImporter_MATSim.cpp b/Util/OSM2ODR/src/netimport/NIImporter_MATSim.cpp deleted file mode 100644 index df3bb549c..000000000 --- a/Util/OSM2ODR/src/netimport/NIImporter_MATSim.cpp +++ /dev/null @@ -1,249 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIImporter_MATSim.cpp -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date Tue, 26.04.2011 -/// -// Importer for networks stored in MATSim format -/****************************************************************************/ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "NILoader.h" -#include "NIImporter_MATSim.h" - - - -// =========================================================================== -// static variables -// =========================================================================== -StringBijection::Entry NIImporter_MATSim::matsimTags[] = { - { "network", NIImporter_MATSim::MATSIM_TAG_NETWORK }, - { "node", NIImporter_MATSim::MATSIM_TAG_NODE }, - { "link", NIImporter_MATSim::MATSIM_TAG_LINK }, - { "links", NIImporter_MATSim::MATSIM_TAG_LINKS }, - { "", NIImporter_MATSim::MATSIM_TAG_NOTHING } -}; - - -StringBijection::Entry NIImporter_MATSim::matsimAttrs[] = { - { "id", NIImporter_MATSim::MATSIM_ATTR_ID }, - { "x", NIImporter_MATSim::MATSIM_ATTR_X }, - { "y", NIImporter_MATSim::MATSIM_ATTR_Y }, - { "from", NIImporter_MATSim::MATSIM_ATTR_FROM }, - { "to", NIImporter_MATSim::MATSIM_ATTR_TO }, - { "length", NIImporter_MATSim::MATSIM_ATTR_LENGTH }, - { "freespeed", NIImporter_MATSim::MATSIM_ATTR_FREESPEED }, - { "capacity", NIImporter_MATSim::MATSIM_ATTR_CAPACITY }, - { "permlanes", NIImporter_MATSim::MATSIM_ATTR_PERMLANES }, - { "oneway", NIImporter_MATSim::MATSIM_ATTR_ONEWAY }, - { "modes", NIImporter_MATSim::MATSIM_ATTR_MODES }, - { "origid", NIImporter_MATSim::MATSIM_ATTR_ORIGID }, - { "capperiod", NIImporter_MATSim::MATSIM_ATTR_CAPPERIOD }, - { "capDivider", NIImporter_MATSim::MATSIM_ATTR_CAPDIVIDER }, - - { "", NIImporter_MATSim::MATSIM_ATTR_NOTHING } -}; - - -// =========================================================================== -// method definitions -// =========================================================================== -// --------------------------------------------------------------------------- -// static methods -// --------------------------------------------------------------------------- -void -NIImporter_MATSim::loadNetwork(const OptionsCont& oc, NBNetBuilder& nb) { - // check whether the option is set (properly) - if (!oc.isSet("matsim-files")) { - return; - } - /* Parse file(s) - * Each file is parsed twice: first for nodes, second for edges. */ - std::vector files = oc.getStringVector("matsim-files"); - // load nodes, first - NodesHandler nodesHandler(nb.getNodeCont()); - for (std::vector::const_iterator file = files.begin(); file != files.end(); ++file) { - // nodes - if (!FileHelpers::isReadable(*file)) { - WRITE_ERROR("Could not open matsim-file '" + *file + "'."); - return; - } - nodesHandler.setFileName(*file); - PROGRESS_BEGIN_MESSAGE("Parsing nodes from matsim-file '" + *file + "'"); - if (!XMLSubSys::runParser(nodesHandler, *file)) { - return; - } - PROGRESS_DONE_MESSAGE(); - } - // load edges, then - EdgesHandler edgesHandler(nb.getNodeCont(), nb.getEdgeCont(), oc.getBool("matsim.keep-length"), - oc.getBool("matsim.lanes-from-capacity"), NBCapacity2Lanes(oc.getFloat("lanes-from-capacity.norm"))); - for (std::vector::const_iterator file = files.begin(); file != files.end(); ++file) { - // edges - edgesHandler.setFileName(*file); - PROGRESS_BEGIN_MESSAGE("Parsing edges from matsim-file '" + *file + "'"); - XMLSubSys::runParser(edgesHandler, *file); - PROGRESS_DONE_MESSAGE(); - } -} - - -// --------------------------------------------------------------------------- -// definitions of NIImporter_MATSim::NodesHandler-methods -// --------------------------------------------------------------------------- -NIImporter_MATSim::NodesHandler::NodesHandler(NBNodeCont& toFill) - : GenericSAXHandler(matsimTags, MATSIM_TAG_NOTHING, - matsimAttrs, MATSIM_ATTR_NOTHING, - "matsim - file"), myNodeCont(toFill) { -} - - -NIImporter_MATSim::NodesHandler::~NodesHandler() {} - - -void -NIImporter_MATSim::NodesHandler::myStartElement(int element, const SUMOSAXAttributes& attrs) { - if (element != MATSIM_TAG_NODE) { - return; - } - // get the id, report a warning if not given or empty... - bool ok = true; - std::string id = attrs.get(MATSIM_ATTR_ID, nullptr, ok); - double x = attrs.get(MATSIM_ATTR_X, id.c_str(), ok); - double y = attrs.get(MATSIM_ATTR_Y, id.c_str(), ok); - if (!ok) { - return; - } - Position pos(x, y); - if (!NBNetBuilder::transformCoordinate(pos)) { - WRITE_ERROR("Unable to project coordinates for node '" + id + "'."); - } - NBNode* node = new NBNode(id, pos); - if (!myNodeCont.insert(node)) { - delete node; - WRITE_ERROR("Could not add node '" + id + "'. Probably declared twice."); - } -} - - - -// --------------------------------------------------------------------------- -// definitions of NIImporter_MATSim::EdgesHandler-methods -// --------------------------------------------------------------------------- -NIImporter_MATSim::EdgesHandler::EdgesHandler(const NBNodeCont& nc, NBEdgeCont& toFill, - bool keepEdgeLengths, bool lanesFromCapacity, - NBCapacity2Lanes capacity2Lanes) - : GenericSAXHandler(matsimTags, MATSIM_TAG_NOTHING, - matsimAttrs, MATSIM_ATTR_NOTHING, "matsim - file"), - myNodeCont(nc), myEdgeCont(toFill), myCapacityNorm(3600), - myKeepEdgeLengths(keepEdgeLengths), myLanesFromCapacity(lanesFromCapacity), - myCapacity2Lanes(capacity2Lanes) { -} - - -NIImporter_MATSim::EdgesHandler::~EdgesHandler() { -} - - -void -NIImporter_MATSim::EdgesHandler::myStartElement(int element, - const SUMOSAXAttributes& attrs) { - if (element == MATSIM_TAG_NETWORK) { - if (attrs.hasAttribute(MATSIM_ATTR_CAPDIVIDER)) { - bool ok = true; - int capDivider = attrs.get(MATSIM_ATTR_CAPDIVIDER, "network", ok); - if (ok) { - myCapacityNorm = (double)(capDivider * 3600); - } - } - } - if (element == MATSIM_TAG_LINKS) { - bool ok = true; - std::string capperiod = attrs.get(MATSIM_ATTR_CAPPERIOD, "links", ok); - StringTokenizer st(capperiod, ":"); - if (st.size() != 3) { - WRITE_ERROR("Bogus capacity period format; requires 'hh:mm:ss'."); - return; - } - try { - int hours = StringUtils::toInt(st.next()); - int minutes = StringUtils::toInt(st.next()); - int seconds = StringUtils::toInt(st.next()); - myCapacityNorm = (double)(hours * 3600 + minutes * 60 + seconds); - } catch (NumberFormatException&) { - } catch (EmptyData&) { - } - return; - } - - // parse "link" elements - if (element != MATSIM_TAG_LINK) { - return; - } - bool ok = true; - std::string id = attrs.get(MATSIM_ATTR_ID, nullptr, ok); - std::string fromNodeID = attrs.get(MATSIM_ATTR_FROM, id.c_str(), ok); - std::string toNodeID = attrs.get(MATSIM_ATTR_TO, id.c_str(), ok); - double length = attrs.get(MATSIM_ATTR_LENGTH, id.c_str(), ok); // override computed? - double freeSpeed = attrs.get(MATSIM_ATTR_FREESPEED, id.c_str(), ok); // - double capacity = attrs.get(MATSIM_ATTR_CAPACITY, id.c_str(), ok); // override permLanes? - double permLanes = attrs.get(MATSIM_ATTR_PERMLANES, id.c_str(), ok); - //bool oneWay = attrs.getOpt(MATSIM_ATTR_ONEWAY, id.c_str(), ok, true); // mandatory? - std::string modes = attrs.getOpt(MATSIM_ATTR_MODES, id.c_str(), ok, ""); // which values? - std::string origid = attrs.getOpt(MATSIM_ATTR_ORIGID, id.c_str(), ok, ""); - NBNode* fromNode = myNodeCont.retrieve(fromNodeID); - NBNode* toNode = myNodeCont.retrieve(toNodeID); - if (fromNode == nullptr) { - WRITE_ERROR("Could not find from-node for edge '" + id + "'."); - } - if (toNode == nullptr) { - WRITE_ERROR("Could not find to-node for edge '" + id + "'."); - } - if (fromNode == nullptr || toNode == nullptr) { - return; - } - if (myLanesFromCapacity) { - permLanes = myCapacity2Lanes.get(capacity); - } - NBEdge* edge = new NBEdge(id, fromNode, toNode, "", freeSpeed, (int) permLanes, -1, NBEdge::UNSPECIFIED_WIDTH, NBEdge::UNSPECIFIED_OFFSET); - edge->setParameter("capacity", toString(capacity)); - if (myKeepEdgeLengths) { - edge->setLoadedLength(length); - } - if (!myEdgeCont.insert(edge)) { - delete edge; - WRITE_ERROR("Could not add edge '" + id + "'. Probably declared twice."); - } -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/NIImporter_MATSim.h b/Util/OSM2ODR/src/netimport/NIImporter_MATSim.h deleted file mode 100644 index 8d0bae65c..000000000 --- a/Util/OSM2ODR/src/netimport/NIImporter_MATSim.h +++ /dev/null @@ -1,228 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIImporter_MATSim.h -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @date Tue, 26.04.2011 -/// -// Importer for networks stored in MATSim format -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include -#include -#include - - -// =========================================================================== -// class declarations -// =========================================================================== -class NBEdge; -class NBEdgeCont; -class NBNetBuilder; -class NBNode; -class NBNodeCont; -class NBTrafficLightLogicCont; -class NBTypeCont; -class OptionsCont; - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NIImporter_MATSim - * @brief Importer for networks stored in MATSim format - * - */ -class NIImporter_MATSim { -public: - /** @brief Loads content of the optionally given MATSIM network files - * - * If the option "matsim-files" is set, the file(s) stored therein is read and - * the network definition stored therein is stored within the given network - * builder. - * - * If the option "matsim-files" is not set, this method simply returns. - * - * @param[in] oc The options to use - * @param[in] nb The network builder to fill - */ - static void loadNetwork(const OptionsCont& oc, NBNetBuilder& nb); - - -private: - /** - * @class NodesHandler - * @brief A class which extracts MATSIM-nodes from a parsed MATSIM-file - */ - class NodesHandler : public GenericSAXHandler { - public: - /** @brief Contructor - * @param[in] toFill The nodes container to fill - */ - NodesHandler(NBNodeCont& toFill); - - - /// @brief Destructor - ~NodesHandler(); - - - protected: - /// @name inherited from GenericSAXHandler - //@{ - - /** @brief Called on the opening of a tag; - * - * @param[in] element ID of the currently opened element - * @param[in] attrs Attributes within the currently opened element - * @exception ProcessError If something fails - * @see GenericSAXHandler::myStartElement - */ - void myStartElement(int element, const SUMOSAXAttributes& attrs); - //@} - - - private: - /// @brief The nodes container to fill - NBNodeCont& myNodeCont; - - - private: - /** @brief invalidated copy constructor */ - NodesHandler(const NodesHandler& s); - - /** @brief invalidated assignment operator */ - NodesHandler& operator=(const NodesHandler& s); - - }; - - - - /** - * @class EdgesHandler - * @brief A class which extracts MATSIM-edges from a parsed MATSIM-file - */ - class EdgesHandler : public GenericSAXHandler { - public: - /** @brief Constructor - * - * @param[in] nc The node container to retrieve nodes form - * @param[in, out] toFill The edges container to fill with read edges - * @param[in] keepEdgeLengths Whether the loaded lengths shal be used - * @param[in] lanesFromCapacity Whether the lane number shall be computed from the capacity - * @param[in] capacity2Lanes The converter from flow to lanes - */ - EdgesHandler(const NBNodeCont& nc, NBEdgeCont& toFill, - bool keepEdgeLengths, bool lanesFromCapacity, - NBCapacity2Lanes capacity2Lanes); - - - /// @brief Destructor - ~EdgesHandler(); - - - protected: - /// @name inherited from GenericSAXHandler - //@{ - - /** @brief Called on the opening of a tag; - * - * @param[in] element ID of the currently opened element - * @param[in] attrs Attributes within the currently opened element - * @exception ProcessError If something fails - * @see GenericSAXHandler::myStartElement - */ - void myStartElement(int element, const SUMOSAXAttributes& attrs); - //@} - - - private: - /// @brief The previously parsed nodes - const NBNodeCont& myNodeCont; - - /// @brief The edge container to fill - NBEdgeCont& myEdgeCont; - - /// @brief The capacity norming - double myCapacityNorm; - - /// @brief Whether the loaded lengths shal be used - bool myKeepEdgeLengths; - - /// @brief Whether the lane number shall be computed from the capacity - bool myLanesFromCapacity; - - /// @brief The converter from flow to lanes - NBCapacity2Lanes myCapacity2Lanes; - - - private: - /** @brief invalidated copy constructor */ - EdgesHandler(const EdgesHandler& s); - - /** @brief invalidated assignment operator */ - EdgesHandler& operator=(const EdgesHandler& s); - - }; - - - /** - * @enum MatsimXMLTag - * @brief Numbers representing MATSIM-XML - element names - * @see GenericSAXHandler - */ - enum MatsimXMLTag { - MATSIM_TAG_NOTHING = 0, - MATSIM_TAG_NETWORK, - MATSIM_TAG_NODE, - MATSIM_TAG_LINK, - MATSIM_TAG_LINKS - }; - - - /** - * @enum MatsimXMLAttr - * @brief Numbers representing MATSIM-XML - attributes - * @see GenericSAXHandler - */ - enum MatsimXMLAttr { - MATSIM_ATTR_NOTHING = 0, - MATSIM_ATTR_ID, - MATSIM_ATTR_X, - MATSIM_ATTR_Y, - MATSIM_ATTR_FROM, - MATSIM_ATTR_TO, - MATSIM_ATTR_LENGTH, - MATSIM_ATTR_FREESPEED, - MATSIM_ATTR_CAPACITY, - MATSIM_ATTR_PERMLANES, - MATSIM_ATTR_ONEWAY, - MATSIM_ATTR_MODES, - MATSIM_ATTR_ORIGID, - MATSIM_ATTR_CAPPERIOD, - MATSIM_ATTR_CAPDIVIDER - }; - - /// The names of MATSIM-XML elements (for passing to GenericSAXHandler) - static StringBijection::Entry matsimTags[]; - - /// The names of MATSIM-XML attributes (for passing to GenericSAXHandler) - static StringBijection::Entry matsimAttrs[]; - - -}; diff --git a/Util/OSM2ODR/src/netimport/NIImporter_OpenDrive.cpp b/Util/OSM2ODR/src/netimport/NIImporter_OpenDrive.cpp deleted file mode 100644 index 11b648c8f..000000000 --- a/Util/OSM2ODR/src/netimport/NIImporter_OpenDrive.cpp +++ /dev/null @@ -1,2697 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIImporter_OpenDrive.cpp -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @author Laura Bieker -/// @date Mon, 14.04.2008 -/// -// Importer for networks stored in openDrive format -/****************************************************************************/ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "NILoader.h" -#include "NIImporter_OpenDrive.h" - -//#define DEBUG_VARIABLE_WIDTHS -//#define DEBUG_VARIABLE_SPEED -//#define DEBUG_CONNECTIONS -//#define DEBUG_SPIRAL -//#define DEBUG_INTERNALSHAPES - -#define DEBUG_COND(road) ((road)->id == "18") -#define DEBUG_COND2(edgeID) (StringUtils::startsWith((edgeID), "-18.")) -#define DEBUG_COND3(roadID) (roadID == "18") - -// =========================================================================== -// definitions -// =========================================================================== - -// =========================================================================== -// static variables -// =========================================================================== -StringBijection::Entry NIImporter_OpenDrive::openDriveTags[] = { - { "header", NIImporter_OpenDrive::OPENDRIVE_TAG_HEADER }, - { "road", NIImporter_OpenDrive::OPENDRIVE_TAG_ROAD }, - { "predecessor", NIImporter_OpenDrive::OPENDRIVE_TAG_PREDECESSOR }, - { "successor", NIImporter_OpenDrive::OPENDRIVE_TAG_SUCCESSOR }, - { "geometry", NIImporter_OpenDrive::OPENDRIVE_TAG_GEOMETRY }, - { "line", NIImporter_OpenDrive::OPENDRIVE_TAG_LINE }, - { "spiral", NIImporter_OpenDrive::OPENDRIVE_TAG_SPIRAL }, - { "arc", NIImporter_OpenDrive::OPENDRIVE_TAG_ARC }, - { "poly3", NIImporter_OpenDrive::OPENDRIVE_TAG_POLY3 }, - { "paramPoly3", NIImporter_OpenDrive::OPENDRIVE_TAG_PARAMPOLY3 }, - { "laneSection", NIImporter_OpenDrive::OPENDRIVE_TAG_LANESECTION }, - { "laneOffset", NIImporter_OpenDrive::OPENDRIVE_TAG_LANEOFFSET }, - { "left", NIImporter_OpenDrive::OPENDRIVE_TAG_LEFT }, - { "center", NIImporter_OpenDrive::OPENDRIVE_TAG_CENTER }, - { "right", NIImporter_OpenDrive::OPENDRIVE_TAG_RIGHT }, - { "lane", NIImporter_OpenDrive::OPENDRIVE_TAG_LANE }, - { "signal", NIImporter_OpenDrive::OPENDRIVE_TAG_SIGNAL }, - { "signalReference", NIImporter_OpenDrive::OPENDRIVE_TAG_SIGNALREFERENCE }, - { "validity", NIImporter_OpenDrive::OPENDRIVE_TAG_VALIDITY }, - { "junction", NIImporter_OpenDrive::OPENDRIVE_TAG_JUNCTION }, - { "connection", NIImporter_OpenDrive::OPENDRIVE_TAG_CONNECTION }, - { "laneLink", NIImporter_OpenDrive::OPENDRIVE_TAG_LANELINK }, - { "width", NIImporter_OpenDrive::OPENDRIVE_TAG_WIDTH }, - { "speed", NIImporter_OpenDrive::OPENDRIVE_TAG_SPEED }, - { "elevation", NIImporter_OpenDrive::OPENDRIVE_TAG_ELEVATION }, - { "geoReference", NIImporter_OpenDrive::OPENDRIVE_TAG_GEOREFERENCE }, - { "object", NIImporter_OpenDrive::OPENDRIVE_TAG_OBJECT }, - { "repeat", NIImporter_OpenDrive::OPENDRIVE_TAG_REPEAT }, - - { "", NIImporter_OpenDrive::OPENDRIVE_TAG_NOTHING } -}; - - -StringBijection::Entry NIImporter_OpenDrive::openDriveAttrs[] = { - { "revMajor", NIImporter_OpenDrive::OPENDRIVE_ATTR_REVMAJOR }, - { "revMinor", NIImporter_OpenDrive::OPENDRIVE_ATTR_REVMINOR }, - { "id", NIImporter_OpenDrive::OPENDRIVE_ATTR_ID }, - { "length", NIImporter_OpenDrive::OPENDRIVE_ATTR_LENGTH }, - { "width", NIImporter_OpenDrive::OPENDRIVE_ATTR_WIDTH }, - { "radius", NIImporter_OpenDrive::OPENDRIVE_ATTR_RADIUS }, - { "distance", NIImporter_OpenDrive::OPENDRIVE_ATTR_DISTANCE }, - { "tStart", NIImporter_OpenDrive::OPENDRIVE_ATTR_TSTART }, - { "tEnd", NIImporter_OpenDrive::OPENDRIVE_ATTR_TEND }, - { "widthStart", NIImporter_OpenDrive::OPENDRIVE_ATTR_WIDTHSTART }, - { "widthEnd", NIImporter_OpenDrive::OPENDRIVE_ATTR_WIDTHEND }, - { "junction", NIImporter_OpenDrive::OPENDRIVE_ATTR_JUNCTION }, - { "elementType", NIImporter_OpenDrive::OPENDRIVE_ATTR_ELEMENTTYPE }, - { "elementId", NIImporter_OpenDrive::OPENDRIVE_ATTR_ELEMENTID }, - { "contactPoint", NIImporter_OpenDrive::OPENDRIVE_ATTR_CONTACTPOINT }, - { "s", NIImporter_OpenDrive::OPENDRIVE_ATTR_S }, - { "t", NIImporter_OpenDrive::OPENDRIVE_ATTR_T }, - { "x", NIImporter_OpenDrive::OPENDRIVE_ATTR_X }, - { "y", NIImporter_OpenDrive::OPENDRIVE_ATTR_Y }, - { "hdg", NIImporter_OpenDrive::OPENDRIVE_ATTR_HDG }, - { "curvStart", NIImporter_OpenDrive::OPENDRIVE_ATTR_CURVSTART }, - { "curvEnd", NIImporter_OpenDrive::OPENDRIVE_ATTR_CURVEND }, - { "curvature", NIImporter_OpenDrive::OPENDRIVE_ATTR_CURVATURE }, - { "a", NIImporter_OpenDrive::OPENDRIVE_ATTR_A }, - { "b", NIImporter_OpenDrive::OPENDRIVE_ATTR_B }, - { "c", NIImporter_OpenDrive::OPENDRIVE_ATTR_C }, - { "d", NIImporter_OpenDrive::OPENDRIVE_ATTR_D }, - { "aU", NIImporter_OpenDrive::OPENDRIVE_ATTR_AU }, - { "bU", NIImporter_OpenDrive::OPENDRIVE_ATTR_BU }, - { "cU", NIImporter_OpenDrive::OPENDRIVE_ATTR_CU }, - { "dU", NIImporter_OpenDrive::OPENDRIVE_ATTR_DU }, - { "aV", NIImporter_OpenDrive::OPENDRIVE_ATTR_AV }, - { "bV", NIImporter_OpenDrive::OPENDRIVE_ATTR_BV }, - { "cV", NIImporter_OpenDrive::OPENDRIVE_ATTR_CV }, - { "dV", NIImporter_OpenDrive::OPENDRIVE_ATTR_DV }, - { "pRange", NIImporter_OpenDrive::OPENDRIVE_ATTR_PRANGE }, - { "type", NIImporter_OpenDrive::OPENDRIVE_ATTR_TYPE }, - { "level", NIImporter_OpenDrive::OPENDRIVE_ATTR_LEVEL }, - { "orientation", NIImporter_OpenDrive::OPENDRIVE_ATTR_ORIENTATION }, - { "dynamic", NIImporter_OpenDrive::OPENDRIVE_ATTR_DYNAMIC }, - { "incomingRoad", NIImporter_OpenDrive::OPENDRIVE_ATTR_INCOMINGROAD }, - { "connectingRoad", NIImporter_OpenDrive::OPENDRIVE_ATTR_CONNECTINGROAD }, - { "from", NIImporter_OpenDrive::OPENDRIVE_ATTR_FROM }, - { "to", NIImporter_OpenDrive::OPENDRIVE_ATTR_TO }, - { "fromLane", NIImporter_OpenDrive::OPENDRIVE_ATTR_FROMLANE }, - { "toLane", NIImporter_OpenDrive::OPENDRIVE_ATTR_TOLANE }, - { "max", NIImporter_OpenDrive::OPENDRIVE_ATTR_MAX }, - { "sOffset", NIImporter_OpenDrive::OPENDRIVE_ATTR_SOFFSET }, - { "name", NIImporter_OpenDrive::OPENDRIVE_ATTR_NAME }, - // towards xodr v1.4 speed:unit - { "unit", NIImporter_OpenDrive::OPENDRIVE_ATTR_UNIT }, - - { "", NIImporter_OpenDrive::OPENDRIVE_ATTR_NOTHING } -}; - - -bool NIImporter_OpenDrive::myImportAllTypes; -bool NIImporter_OpenDrive::myImportWidths; -double NIImporter_OpenDrive::myMinWidth; -bool NIImporter_OpenDrive::myImportInternalShapes; - -// =========================================================================== -// method definitions -// =========================================================================== -// --------------------------------------------------------------------------- -// static methods (interface in this case) -// --------------------------------------------------------------------------- -void -NIImporter_OpenDrive::loadNetwork(const OptionsCont& oc, NBNetBuilder& nb) { - // check whether the option is set (properly) - if (!oc.isUsableFileList("opendrive-files")) { - return; - } - // prepare types - myImportAllTypes = oc.getBool("opendrive.import-all-lanes"); - myImportWidths = !oc.getBool("opendrive.ignore-widths"); - myMinWidth = oc.getFloat("opendrive.min-width"); - myImportInternalShapes = oc.getBool("opendrive.internal-shapes"); - NBTypeCont& tc = nb.getTypeCont(); - NBNodeCont& nc = nb.getNodeCont(); - // build the handler - std::map edges; - NIImporter_OpenDrive handler(nb.getTypeCont(), edges); - // parse file(s) - std::vector files = oc.getStringVector("opendrive-files"); - for (std::vector::const_iterator file = files.begin(); file != files.end(); ++file) { - if (!FileHelpers::isReadable(*file)) { - WRITE_ERROR("Could not open opendrive file '" + *file + "'."); - return; - } - handler.setFileName(*file); - PROGRESS_BEGIN_MESSAGE("Parsing opendrive from '" + *file + "'"); - XMLSubSys::runParser(handler, *file); - PROGRESS_DONE_MESSAGE(); - } - // apply signal reference information - for (auto& item : edges) { - for (OpenDriveSignal& signal : item.second->signals) { - if (signal.type == "") { - if (handler.getSignals().count(signal.id) == 0) { - WRITE_WARNING("Could not find signal reference '" + signal.id + "'."); - } else { - const OpenDriveSignal& ref = handler.getSignals()[signal.id]; - signal.type = ref.type; - signal.name = ref.name; - signal.dynamic = ref.dynamic; - } - } - } - } - - // split inner/outer edges - std::map innerEdges, outerEdges; - for (std::map::iterator i = edges.begin(); i != edges.end(); ++i) { - if ((*i).second->isInner) { - innerEdges[(*i).first] = (*i).second; - } else { - outerEdges[(*i).first] = (*i).second; - } - } - - // convert geometries into a discretised representation - computeShapes(edges); - // check whether lane sections are valid and whether further must be introduced - revisitLaneSections(tc, edges); - - // ------------------------- - // node building - // ------------------------- - // build nodes#1 - // look at all links which belong to a node, collect their bounding boxes - // and place the node in the middle of this bounding box - std::map posMap; - std::map edge2junction; - std::vector joinedNodeIDs; - // compute node positions - for (std::map::iterator i = innerEdges.begin(); i != innerEdges.end(); ++i) { - OpenDriveEdge* e = (*i).second; - assert(e->junction != "-1" && e->junction != ""); - edge2junction[e->id] = e->junction; - if (posMap.find(e->junction) == posMap.end()) { - posMap[e->junction] = Boundary(); - } - posMap[e->junction].add(e->geom.getBoxBoundary()); - } - // build nodes - for (std::map::iterator i = posMap.begin(); i != posMap.end(); ++i) { - //std::cout << " import node=" << (*i).first << " z=" << (*i).second.getCenter() << " boundary=" << (*i).second << "\n"; - if (!nb.getNodeCont().insert((*i).first, (*i).second.getCenter())) { - throw ProcessError("Could not add node '" + (*i).first + "'."); - } - } - // assign built nodes - for (std::map::iterator i = outerEdges.begin(); i != outerEdges.end(); ++i) { - OpenDriveEdge* e = (*i).second; - for (std::vector::iterator j = e->links.begin(); j != e->links.end(); ++j) { - OpenDriveLink& l = *j; - const std::string& nid = l.elementID; - if (l.elementType != OPENDRIVE_ET_ROAD) { - if (nb.getNodeCont().retrieve(nid) == nullptr) { - // not yet seen, build (possibly a junction without connections) - Position pos = l.linkType == OPENDRIVE_LT_SUCCESSOR ? e->geom[-1] : e->geom[0]; - if (!nb.getNodeCont().insert(nid, pos)) { - throw ProcessError("Could not build node '" + nid + "'."); - } - } - // set node information - setNodeSecure(nb.getNodeCont(), *e, l.elementID, l.linkType, joinedNodeIDs); - continue; - } - if (edge2junction.find(l.elementID) != edge2junction.end()) { - // set node information of an internal road - setNodeSecure(nb.getNodeCont(), *e, edge2junction[l.elementID], l.linkType, joinedNodeIDs); - continue; - } - } - } - // we should now have all nodes set for links which are not outer edge-to-outer edge links - - - // build nodes#2 - // build nodes for all outer edge-to-outer edge connections - for (std::map::iterator i = outerEdges.begin(); i != outerEdges.end(); ++i) { - OpenDriveEdge* e = (*i).second; - for (std::vector::iterator j = e->links.begin(); j != e->links.end(); ++j) { - OpenDriveLink& l = *j; - if (l.elementType != OPENDRIVE_ET_ROAD || edge2junction.find(l.elementID) != edge2junction.end()) { - // is a connection to an internal edge, or a node, skip - continue; - } - // we have a direct connection between to external edges - std::string id1 = e->id; - std::string id2 = l.elementID; - if (id1 < id2) { - std::swap(id1, id2); - } - std::string nid = id1 + "." + id2; - if (nb.getNodeCont().retrieve(nid) == nullptr) { - // not yet seen, build - Position pos = l.linkType == OPENDRIVE_LT_SUCCESSOR ? e->geom[-1] : e->geom[0]; - if (!nb.getNodeCont().insert(nid, pos)) { - throw ProcessError("Could not build node '" + nid + "'."); - } - } - /* debug-stuff - else { - Position pos = l.linkType==OPENDRIVE_LT_SUCCESSOR ? e.geom[e.geom.size()-1] : e.geom[0]; - cout << nid << " " << pos << " " << nb.getNodeCont().retrieve(nid)->getPosition() << endl; - } - */ - setNodeSecure(nb.getNodeCont(), *e, nid, l.linkType, joinedNodeIDs); - } - } - // we should now have start/end nodes for all outer edge-to-outer edge connections - - - // build nodes#3 - // assign further nodes generated from inner-edges - // these nodes have not been assigned earlier, because the connections are referenced in inner-edges - for (std::map::iterator i = outerEdges.begin(); i != outerEdges.end(); ++i) { - OpenDriveEdge* e = (*i).second; - if (e->to != nullptr && e->from != nullptr) { - continue; - } - for (std::map::iterator j = innerEdges.begin(); j != innerEdges.end(); ++j) { - OpenDriveEdge* ie = (*j).second; - for (std::vector::iterator k = ie->links.begin(); k != ie->links.end(); ++k) { - OpenDriveLink& il = *k; - if (il.elementType != OPENDRIVE_ET_ROAD || il.elementID != e->id) { - // not conneted to the currently investigated outer edge - continue; - } - std::string nid = edge2junction[ie->id]; - if (il.contactPoint == OPENDRIVE_CP_START) { - setNodeSecure(nb.getNodeCont(), *e, nid, OPENDRIVE_LT_PREDECESSOR, joinedNodeIDs); - } else { - setNodeSecure(nb.getNodeCont(), *e, nid, OPENDRIVE_LT_SUCCESSOR, joinedNodeIDs); - } - } - } - - } - - // build start/end nodes which were not defined previously - for (std::map::iterator i = outerEdges.begin(); i != outerEdges.end(); ++i) { - OpenDriveEdge* e = (*i).second; - if ((e->from == nullptr || e->to == nullptr) && e->geom.size() == 0) { - continue; - } - if (e->from == nullptr) { - const std::string nid = e->id + ".begin"; - e->from = getOrBuildNode(nid, e->geom.front(), nb.getNodeCont()); - } - if (e->to == nullptr) { - const std::string nid = e->id + ".end"; - e->to = getOrBuildNode(nid, e->geom.back(), nb.getNodeCont()); - } - } - - std::map joinedNodes; - for (NodeSet& joined : joinedNodeIDs) { - Position joinedPos(0, 0); - for (NBNode* j : joined) { - joinedPos = joinedPos + j->getPosition(); - } - joinedPos = joinedPos * (1.0 / joined.size()); - const std::string joinedID = "cluster_" + joinNamedToString(joined, "_"); - if (!nc.insert(joinedID, joinedPos)) { - throw ProcessError("Could not add node '" + joinedID + "'."); - } - NBNode* n = nc.retrieve(joinedID); - for (NBNode* j : joined) { - joinedNodes[j] = n; - } - } - for (std::map::iterator i = outerEdges.begin(); i != outerEdges.end(); ++i) { - OpenDriveEdge* e = (*i).second; - if (joinedNodes.count(e->from) != 0) { - nc.extract(e->from, true); - e->from = joinedNodes[e->from]; - } - if (joinedNodes.count(e->to) != 0) { - nc.extract(e->to, true); - e->to = joinedNodes[e->to]; - } - } - - - // ------------------------- - // edge building - // ------------------------- - const double defaultSpeed = tc.getSpeed(""); - const bool saveOrigIDs = OptionsCont::getOptions().getBool("output.original-names"); - // lane-id-map sumoEdge,sumoLaneIndex->odrLaneIndex - std::map, int> laneIndexMap; - // build edges - for (std::map::iterator i = outerEdges.begin(); i != outerEdges.end(); ++i) { - OpenDriveEdge* e = (*i).second; - if (e->geom.size() < 2) { - WRITE_WARNING("Ignoring road '" + e->id + "' without geometry."); - continue; - } - bool lanesBuilt = false; - - // go along the lane sections, build a node in between of each pair - - /// @todo: One could think of determining whether lane sections may be joined when being equal in SUMO's sense - /// Their naming would have to be updated, too, also in TraCI - - /// @todo: probably, the lane offsets to the center are not right - NBNode* sFrom = e->from; - NBNode* sTo = e->to; - int priorityR = e->getPriority(OPENDRIVE_TAG_RIGHT); - int priorityL = e->getPriority(OPENDRIVE_TAG_LEFT); - double sB = 0; - double sE = e->length; - // 0-length geometries are possible if only the inner points are represented - PositionVector geomWithOffset = e->geom; - if (e->laneOffsets.size() > 0) { - try { - geomWithOffset.move2side(e->laneOffsets); - //std::cout << " e=" << e->id << " offsets=" << e->laneOffsets << " geom=" << e->geom << " geom2=" << geomWithOffset << "\n"; - } catch (InvalidArgument&) { - WRITE_WARNING("Could not apply laneOffsets for edge '" + e->id + "'"); - } - } - const double length2D = geomWithOffset.length2D(); - double cF = length2D == 0 ? 1 : e->length / length2D; - NBEdge* prevRight = nullptr; - NBEdge* prevLeft = nullptr; - - // starting at the same node as ending, and no lane sections? - if (sFrom == sTo && e->laneSections.size() == 1) { - // --> loop, split! - OpenDriveLaneSection ls = e->laneSections[0]; - ls.s = e->length / 2.; - e->laneSections.push_back(ls); - WRITE_WARNING("Edge '" + e->id + "' has to be split as it connects same junctions.") - } - sanitizeWidths(e); - if (myMinWidth > 0) { - const double minDist = oc.getFloat("opendrive.curve-resolution"); - splitMinWidths(e, tc, minDist); - } - - // build along lane sections - for (std::vector::iterator j = e->laneSections.begin(); j != e->laneSections.end(); ++j) { - // add internal node if needed - if (j == e->laneSections.end() - 1) { - sTo = e->to; - sE = e->length / cF; - } else { - double nextS = (j + 1)->s; - sTo = new NBNode(e->id + "." + toString(nextS), geomWithOffset.positionAtOffset(nextS)); - if (!nb.getNodeCont().insert(sTo)) { - throw ProcessError("Could not add node '" + sTo->getID() + "'."); - } - sE = nextS / cF; - } - PositionVector geom = geomWithOffset.getSubpart2D(sB, sE); - std::string id = e->id; - if (sFrom != e->from || sTo != e->to) { - id = id + "." + toString((*j).s); - } else if (e->laneSections.size() == 1) { - id = id + ".0.00"; - } -#ifdef DEBUG_VARIABLE_WIDTHS - if (DEBUG_COND(e)) { - std::cout << " id=" << id << " sB=" << sB << " sE=" << sE << " geom=" << geom << "\n"; - } -#endif - - // build lanes to right - NBEdge* currRight = nullptr; - if ((*j).rightLaneNumber > 0) { - currRight = new NBEdge("-" + id, sFrom, sTo, (*j).rightType, defaultSpeed, (*j).rightLaneNumber, priorityR, - NBEdge::UNSPECIFIED_WIDTH, NBEdge::UNSPECIFIED_OFFSET, geom, e->streetName, "", LaneSpreadFunction::RIGHT, true); - lanesBuilt = true; - const std::vector& lanes = (*j).lanesByDir[OPENDRIVE_TAG_RIGHT]; - for (std::vector::const_iterator k = lanes.begin(); k != lanes.end(); ++k) { - std::map::const_iterator lp = (*j).laneMap.find((*k).id); - if (lp != (*j).laneMap.end()) { - int sumoLaneIndex = lp->second; - setLaneAttributes(e, currRight->getLaneStruct(sumoLaneIndex), *k, saveOrigIDs, tc); - laneIndexMap[std::make_pair(currRight, sumoLaneIndex)] = (*k).id; - } - } - if (!nb.getEdgeCont().insert(currRight, myImportAllTypes)) { - throw ProcessError("Could not add edge '" + currRight->getID() + "'."); - } - if (nb.getEdgeCont().wasIgnored(id)) { - prevRight = nullptr; - } else { - // connect lane sections - if (prevRight != nullptr) { - std::map connections = (*j).getInnerConnections(OPENDRIVE_TAG_RIGHT, *(j - 1)); - for (std::map::const_iterator k = connections.begin(); k != connections.end(); ++k) { -#ifdef DEBUG_CONNECTIONS - if (DEBUG_COND(e)) { - std::cout << "addCon1 from=" << prevRight->getID() << "_" << (*k).first << " to=" << currRight->getID() << "_" << (*k).second << "\n"; - } -#endif - prevRight->addLane2LaneConnection((*k).first, currRight, (*k).second, NBEdge::Lane2LaneInfoType::VALIDATED); - } - } - prevRight = currRight; - } - } - - // build lanes to left - NBEdge* currLeft = nullptr; - if ((*j).leftLaneNumber > 0) { - currLeft = new NBEdge(id, sTo, sFrom, (*j).leftType, defaultSpeed, (*j).leftLaneNumber, priorityL, - NBEdge::UNSPECIFIED_WIDTH, NBEdge::UNSPECIFIED_OFFSET, geom.reverse(), e->streetName, "", LaneSpreadFunction::RIGHT, true); - lanesBuilt = true; - const std::vector& lanes = (*j).lanesByDir[OPENDRIVE_TAG_LEFT]; - for (std::vector::const_iterator k = lanes.begin(); k != lanes.end(); ++k) { - std::map::const_iterator lp = (*j).laneMap.find((*k).id); - if (lp != (*j).laneMap.end()) { - int sumoLaneIndex = lp->second; - setLaneAttributes(e, currLeft->getLaneStruct(sumoLaneIndex), *k, saveOrigIDs, tc); - laneIndexMap[std::make_pair(currLeft, sumoLaneIndex)] = (*k).id; - } - } - if (!nb.getEdgeCont().insert(currLeft, myImportAllTypes)) { - throw ProcessError("Could not add edge '" + currLeft->getID() + "'."); - } - if (nb.getEdgeCont().wasIgnored(id)) { - prevLeft = nullptr; - } else { - // connect lane sections - if (prevLeft != nullptr) { - std::map connections = (*j).getInnerConnections(OPENDRIVE_TAG_LEFT, *(j - 1)); - for (std::map::const_iterator k = connections.begin(); k != connections.end(); ++k) { -#ifdef DEBUG_CONNECTIONS - if (DEBUG_COND(e)) { - std::cout << "addCon2 from=" << currLeft->getID() << "_" << (*k).first << " to=" << prevLeft->getID() << "_" << (*k).second << "\n"; - } -#endif - currLeft->addLane2LaneConnection((*k).first, prevLeft, (*k).second, NBEdge::Lane2LaneInfoType::VALIDATED); - } - } - prevLeft = currLeft; - } - } - (*j).sumoID = id; - - - sB = sE; - sFrom = sTo; - } - // optionally write road objects - if (oc.isSet("polygon-output")) { - const bool writeGeo = GeoConvHelper::getLoaded().usingGeoProjection() && ( - oc.isDefault("proj.plain-geo") || oc.getBool("proj.plain-geo")); - OutputDevice& dev = OutputDevice::getDevice(oc.getString("polygon-output")); - dev.writeXMLHeader("additional", "additional_file.xsd"); - //SUMOPolygon poly("road_" + e->id, "road", RGBColor::BLUE, e->geom, true, false); - //poly.writeXML(dev, false); - for (auto& o : e->objects) { - Position ref = e->geom.positionAtOffset2D(o.s, -o.t); - if (o.radius >= 0) { - // cicrular shape - // GeoConvHelper::getFinal is not ready yet - GeoConvHelper::getLoaded().cartesian2geo(ref); - PointOfInterest poly(o.id, o.type, RGBColor::YELLOW, ref, true, "", -1, 0); - poly.setParameter("name", o.name); - poly.writeXML(dev, writeGeo); - } else { - // rectangular shape - PositionVector centerLine; - centerLine.push_back(Position(-o.length / 2, 0)); - centerLine.push_back(Position(o.length / 2, 0)); - double roadHdg = e->geom.rotationAtOffset(o.s); - centerLine.rotate2D(roadHdg + o.hdg); - //PointOfInterest poiRef("ref_" + o.id, "", RGBColor::CYAN, ref, false, "", 0, 0, Shape::DEFAULT_LAYER + 2); - //poiRef.writeXML(dev, false); - centerLine.add(ref); - //SUMOPolygon polyCenter("center_" + o.id, "", RGBColor::MAGENTA, centerLine, true, false, Shape::DEFAULT_LAYER + 1); - //polyCenter.writeXML(dev, false); - centerLine.move2side(o.width / 2); - PositionVector shape = centerLine; - centerLine.move2side(-o.width); - shape.append(centerLine.reverse(), POSITION_EPS); - if (writeGeo) { - // GeoConvHelper::getFinal is not ready yet - for (int i = 0; i < (int) shape.size(); i++) { - GeoConvHelper::getLoaded().cartesian2geo(shape[i]); - } - } - SUMOPolygon poly(o.id, o.type, RGBColor::YELLOW, shape, true, true, 1); - poly.setParameter("name", o.name); - poly.writeXML(dev, writeGeo); - } - } - } - if (!lanesBuilt) { - WRITE_WARNINGF("Edge '%' has no lanes.", e->id); - } - } - - // ------------------------- - // connections building - // ------------------------- - // generate explicit lane-to-lane connections - for (std::map::iterator i = edges.begin(); i != edges.end(); ++i) { - setEdgeLinks2(*(*i).second, edges); - } - // compute connections across intersections, if any - std::vector connections2; - for (std::map::iterator j = edges.begin(); j != edges.end(); ++j) { - const std::set& conns = (*j).second->connections; - - for (std::set::const_iterator i = conns.begin(); i != conns.end(); ++i) { - if (innerEdges.find((*i).fromEdge) != innerEdges.end()) { - // connections starting at inner edges are processed by starting from outer edges - continue; - } - if (innerEdges.find((*i).toEdge) != innerEdges.end()) { - std::set seen; - buildConnectionsToOuter(*i, innerEdges, connections2, seen); - } else { - connections2.push_back(*i); - } - } - } - // set connections - for (std::vector::const_iterator i = connections2.begin(); i != connections2.end(); ++i) { -#ifdef DEBUG_CONNECTIONS - std::cout << "connections2 " << (*i).getDescription() << "\n"; -#endif - std::string fromEdge = (*i).fromEdge; - if (edges.find(fromEdge) == edges.end()) { - WRITE_WARNING("While setting connections: from-edge '" + fromEdge + "' is not known."); - continue; - } - OpenDriveEdge* odFrom = edges[fromEdge]; - int fromLane = (*i).fromLane; - bool fromLast = ((*i).fromCP == OPENDRIVE_CP_END) && ((*i).fromLane < 0); - fromEdge = fromLast ? odFrom->laneSections.back().sumoID : odFrom->laneSections[0].sumoID; - - std::string toEdge = (*i).toEdge; - if (edges.find(toEdge) == edges.end()) { - WRITE_WARNING("While setting connections: to-edge '" + toEdge + "' is not known."); - continue; - } - - OpenDriveEdge* odTo = edges[toEdge]; - int toLane = (*i).toLane; - bool toLast = ((*i).toCP == OPENDRIVE_CP_END) || ((*i).toLane > 0); - toEdge = toLast ? odTo->laneSections.back().sumoID : odTo->laneSections[0].sumoID; - - if (fromLane == UNSET_CONNECTION) { - continue; - } - if (fromLane < 0) { - fromEdge = revertID(fromEdge); - } - if (toLane == UNSET_CONNECTION) { - continue; - } - if (toLane < 0) { - toEdge = revertID(toEdge); - } - fromLane = fromLast ? odFrom->laneSections.back().laneMap[fromLane] : odFrom->laneSections[0].laneMap[fromLane]; - toLane = toLast ? odTo->laneSections.back().laneMap[toLane] : odTo->laneSections[0].laneMap[toLane]; - NBEdge* from = nb.getEdgeCont().retrieve(fromEdge); - NBEdge* to = nb.getEdgeCont().retrieve(toEdge); - if (from == nullptr) { - WRITE_WARNING("Could not find fromEdge representation of '" + fromEdge + "' in connection '" + (*i).origID + "'."); - } - if (to == nullptr) { - WRITE_WARNING("Could not find fromEdge representation of '" + toEdge + "' in connection '" + (*i).origID + "'."); - } - if (from == nullptr || to == nullptr) { - continue; - } - -#ifdef DEBUG_CONNECTIONS - if (DEBUG_COND2(from->getID())) { - std::cout << "addCon3 from=" << from->getID() << "_" << fromLane << " to=" << to->getID() << "_" << toLane << "\n"; - } -#endif - from->addLane2LaneConnection(fromLane, to, toLane, NBEdge::Lane2LaneInfoType::USER, false, false, true, - NBEdge::UNSPECIFIED_CONTPOS, - NBEdge::UNSPECIFIED_VISIBILITY_DISTANCE, - NBEdge::UNSPECIFIED_SPEED, - NBEdge::UNSPECIFIED_LOADED_LENGTH, - (*i).shape); - - if ((*i).origID != "" && saveOrigIDs) { - // @todo: this is the most silly way to determine the connection - std::vector& cons = from->getConnections(); - for (std::vector::iterator k = cons.begin(); k != cons.end(); ++k) { - if ((*k).fromLane == fromLane && (*k).toEdge == to && (*k).toLane == toLane) { - (*k).setParameter(SUMO_PARAM_ORIGID, (*i).origID + "_" + toString((*i).origLane)); - break; - } - } - } - } - - - // ------------------------- - // traffic lights - // ------------------------- - std::map tlsControlled; - for (std::map::iterator i = edges.begin(); i != edges.end(); ++i) { - OpenDriveEdge* e = (*i).second; - for (const OpenDriveSignal& signal : e->signals) { - if (signal.type != "1000001") { // traffic_light (Section 6.11) - continue; - } - if (e->laneSections.size() == 0) { - WRITE_WARNING("Edge '" + e->id + "' has signals but no lane sections."); - continue; - } - std::vector::iterator k = e->laneSections.begin(); - bool found = false; - for (; k != e->laneSections.end() - 1 && !found;) { - if (signal.s > (*k).s && signal.s <= (*(k + 1)).s) { - found = true; - } else { - ++k; - } - } - - std::string id = (*k).sumoID; - if (id == "") { - // traffic light on connecting road - if (e->junction != "") { - //WRITE_WARNING("Found a traffic light signal on an internal edge; will not build it (original edge id='" + e->id + "')."); - std::string fromID, toID; - for (std::vector::const_iterator l = e->links.begin(); l != e->links.end(); ++l) { - if ((*l).linkType == OPENDRIVE_LT_PREDECESSOR && (*l).elementType == OPENDRIVE_ET_ROAD) { - if (fromID != "") { - WRITE_WARNING("Ambigous start of connection."); - } - OpenDriveEdge* e = edges[(*l).elementID]; - if ((*l).contactPoint == OPENDRIVE_CP_START) { - fromID = e->laneSections[0].sumoID; - if (signal.orientation < 0) { - fromID = "-" + fromID; - } - } else { - fromID = e->laneSections.back().sumoID; - if (signal.orientation > 0) { - fromID = "-" + fromID; - } - } - } - if ((*l).linkType == OPENDRIVE_LT_SUCCESSOR && (*l).elementType == OPENDRIVE_ET_ROAD) { - if (toID != "") { - WRITE_WARNING("Ambigous end of connection."); - } - OpenDriveEdge* e = edges[(*l).elementID]; - toID = (*l).contactPoint == OPENDRIVE_CP_START ? e->laneSections[0].sumoID : e->laneSections.back().sumoID; - } - } - // figure out the correct combination of directions - NBEdge* from; - NBEdge* to; - auto fromTo = retrieveSignalEdges(nb, fromID, toID, e->junction); - from = fromTo.first; - to = fromTo.second; - if (from == nullptr) { - WRITE_WARNINGF("Could not find edge '%' for signal '%'.", fromID, signal.id); - continue; - } - - // consider signal validity to determine direction - if (signal.maxLane != 0) { - bool fromForward = from->getID()[0] == '-'; - bool lanesForward = signal.maxLane < 0; - if (fromForward != lanesForward) { - std::swap(fromID, toID); - - auto fromTo = retrieveSignalEdges(nb, fromID, toID, e->junction); - from = fromTo.first; - to = fromTo.second; - if (from == nullptr) { - WRITE_WARNINGF("Could not find edge '%' for signal '%'.", fromID, signal.id); - continue; - } - } - } - for (NBEdge::Connection& c : from->getConnections()) { - if (c.toEdge == to) { - int odLane = laneIndexMap[std::make_pair(from, c.fromLane)]; - //std::cout << " fromLane=" << c.fromLane << " odLane=" << odLane << "\n"; - if (signal.minLane == 0 || (signal.minLane <= odLane && signal.maxLane >= odLane)) { - c.setParameter("signalID", signal.id); - } - } - } - getTLSSecure(from, nb); - //std::cout << "odrEdge=" << e->id << " fromID=" << fromID << " toID=" << toID << " from=" << from->getID() << " to=" << to->getID() - // << " signal=" << signal.id << " minLane=" << signal.minLane << " maxLane=" << signal.maxLane << "\n"; - } else { - WRITE_WARNINGF("Found a traffic light signal on an unknown edge (original edge id='%').", e->id); - continue; - } - } else { - // traffic light on normal road - if (signal.orientation == 1) { - // forward direction has negative lane indices and gets a negative prefix in sumo - id = "-" + id; - } - NBEdge* edge = nb.getEdgeCont().retrieve(id); - if (edge == nullptr) { - WRITE_WARNINGF("Could not find edge '%' for signal '%'.", id, signal.id); - continue; - } - getTLSSecure(edge, nb); - /// XXX consider lane validity - for (NBEdge::Connection& c : edge->getConnections()) { - int odLane = laneIndexMap[std::make_pair(edge, c.fromLane)]; - if (signal.minLane == 0 || (signal.minLane <= odLane && signal.maxLane >= odLane)) { - c.setParameter("signalID", signal.id); - } - } - //std::cout << "odrEdge=" << e->id << " sumoID=" << (*k).sumoID << " sumoEdge=" << edge->getID() - // << " signal=" << signal.id << " minLane=" << signal.minLane << " maxLane=" << signal.maxLane << "\n"; - } - // @note: tls 'signalID' parameters are set via NBTrafficLightLogicCont::setOpenDriveSignalParameters - } - } - - // ------------------------- - // clean up - // ------------------------- - for (std::map::iterator i = edges.begin(); i != edges.end(); ++i) { - delete (*i).second; - } -} - -std::pair -NIImporter_OpenDrive::retrieveSignalEdges(NBNetBuilder& nb, const std::string& fromID, const std::string& toID, const std::string& junction) { - NBEdge* from; - NBEdge* to; - from = nb.getEdgeCont().retrieve(fromID); - if (from == nullptr || from->getToNode()->getID() != junction) { - from = nb.getEdgeCont().retrieve(fromID[0] == '-' ? fromID.substr(1) : "-" + fromID); - } - to = nb.getEdgeCont().retrieve(toID); - if (to == nullptr || to->getFromNode()->getID() != junction) { - to = nb.getEdgeCont().retrieve(toID[0] == '-' ? toID.substr(1) : "-" + toID); - } - return std::make_pair(from, to); -} - - -NBTrafficLightDefinition* -NIImporter_OpenDrive::getTLSSecure(NBEdge* inEdge, NBNetBuilder& nb) { - NBNode* toNode = inEdge->getToNode(); - if (!toNode->isTLControlled()) { - TrafficLightType type = SUMOXMLDefinitions::TrafficLightTypes.get(OptionsCont::getOptions().getString("tls.default-type")); - NBOwnTLDef* tlDef = new NBOwnTLDef(toNode->getID(), toNode, 0, type); - if (!nb.getTLLogicCont().insert(tlDef)) { - // actually, nothing should fail here - delete tlDef; - throw ProcessError(); - } - toNode->addTrafficLight(tlDef); - //tlDef->setSinglePhase(); - } - return *toNode->getControllingTLS().begin(); -} - -void -NIImporter_OpenDrive::setLaneAttributes(const OpenDriveEdge* e, NBEdge::Lane& sumoLane, const OpenDriveLane& odLane, bool saveOrigIDs, const NBTypeCont& tc) { - if (saveOrigIDs) { - sumoLane.setParameter(SUMO_PARAM_ORIGID, e->id + "_" + toString(odLane.id)); - } - sumoLane.speed = odLane.speed != 0 ? odLane.speed : tc.getSpeed(odLane.type); - sumoLane.permissions = tc.getPermissions(odLane.type); - sumoLane.width = myImportWidths && odLane.width != NBEdge::UNSPECIFIED_WIDTH ? odLane.width : tc.getWidth(odLane.type); - sumoLane.type = odLane.type; - - const double widthResolution = tc.getWidthResolution(odLane.type); - const double maxWidth = tc.getMaxWidth(odLane.type); - - const bool forbiddenNarrow = (sumoLane.width < myMinWidth - && (sumoLane.permissions & SVC_PASSENGER) != 0 - && sumoLane.width < tc.getWidth(odLane.type)); - - if (sumoLane.width >= 0 && widthResolution > 0) { - sumoLane.width = floor(sumoLane.width / widthResolution + 0.5) * widthResolution; - if (forbiddenNarrow && sumoLane.width >= myMinWidth) { - sumoLane.width -= widthResolution; - if (sumoLane.width <= 0) { - sumoLane.width = MAX2(POSITION_EPS, myMinWidth - POSITION_EPS); - } - } else if (sumoLane.width == 0) { - // round up when close to 0 - sumoLane.width = widthResolution; - } - } - if (maxWidth > 0) { - sumoLane.width = MIN2(sumoLane.width, maxWidth); - } - if (forbiddenNarrow) { - // avoid narrow passenger car lanes (especially at sections with varying width) - sumoLane.permissions = SVC_EMERGENCY | SVC_AUTHORITY; - } -} - -void -NIImporter_OpenDrive::buildConnectionsToOuter(const Connection& c, const std::map& innerEdges, std::vector& into, std::set& seen) { - - OpenDriveEdge* dest = innerEdges.find(c.toEdge)->second; -#ifdef DEBUG_CONNECTIONS - if (DEBUG_COND3(c.fromEdge)) { - std::cout << " buildConnectionsToOuter " << c.getDescription() << "\n"; - std::cout << " dest=" << (dest == nullptr ? "NULL" : dest->id) << " seenlist="; - for (std::set::const_iterator i = seen.begin(); i != seen.end(); ++i) { - std::cout << " " << (*i).fromEdge << "," << (*i).toEdge << " "; - } - std::cout << "\n"; - } -#endif - if (dest == nullptr) { - /// !!! should not, look in all? - return; - } - seen.insert(c); - const std::set& conts = dest->connections; - for (std::set::const_iterator i = conts.begin(); i != conts.end(); ++i) { - auto innerEdgesIt = innerEdges.find((*i).toEdge); -#ifdef DEBUG_CONNECTIONS - if (DEBUG_COND3(c.fromEdge)) { - std::cout << " toInner=" << (innerEdgesIt != innerEdges.end()) << " destCon " << (*i).getDescription() << "\n"; - } -#endif - if (innerEdgesIt != innerEdges.end()) { - std::vector t; - if (seen.count(*i) == 0) { - buildConnectionsToOuter(*i, innerEdges, t, seen); - for (std::vector::const_iterator j = t.begin(); j != t.end(); ++j) { - // @todo this section is unverified - Connection cn = (*j); - cn.fromEdge = c.fromEdge; - cn.fromLane = c.fromLane; - cn.fromCP = c.fromCP; - cn.all = c.all; // @todo "all" is a hack trying to avoid the "from is zero" problem; - if (myImportInternalShapes) { - cn.shape = innerEdgesIt->second->geom + c.shape; - } - into.push_back(cn); - } - } else { - WRITE_WARNING("Circular connections in junction including roads '" + c.fromEdge + "' and '" + c.toEdge + "', loop size " + toString(seen.size())); - } - } else { - int in = c.toLane; - int out = (*i).fromLane; - if (c.toCP == OPENDRIVE_CP_END) { - // inner edge runs in reverse direction - std::swap(in, out); - } -#ifdef DEBUG_CONNECTIONS - if (DEBUG_COND3(c.fromEdge)) { - std::cout << " laneSectionsConnected dest=" << dest->id << " in=" << in << " out=" << out - << " connected=" << laneSectionsConnected(dest, in, out) << "\n"; - } -#endif - - if (laneSectionsConnected(dest, in, out)) { - Connection cn = (*i); - cn.fromEdge = c.fromEdge; - cn.fromLane = c.fromLane; - cn.fromCP = c.fromCP; - cn.all = c.all; - cn.origID = c.toEdge; - cn.origLane = c.toLane; - if (myImportInternalShapes) { - OpenDriveXMLTag lanesDir; - cn.shape = dest->geom; - // determine which lane of dest belongs to this connection - int referenceLane = 0; - int offsetFactor = 1; - if (c.toCP == OPENDRIVE_CP_END) { - offsetFactor = -1; - lanesDir = OPENDRIVE_TAG_LEFT; - for (const auto& destLane : dest->laneSections.front().lanesByDir[lanesDir]) { - if (destLane.successor == c.fromLane) { - referenceLane = destLane.id; - break; - } - } - } else { - lanesDir = OPENDRIVE_TAG_RIGHT; - for (const auto& destLane : dest->laneSections.front().lanesByDir[lanesDir]) { - if (destLane.predecessor == c.fromLane) { - referenceLane = destLane.id; - break; - } - } - } - // compute offsets - //if (cn.fromEdge == "1014000" && dest->id == "3001022") { - // std::cout << "computeOffsets\n"; - //} - std::vector offsets(dest->geom.size(), 0); - if (dest->laneOffsets.size() > 0) { - offsets = dest->laneOffsets; - } -#ifdef DEBUG_INTERNALSHAPES - std::string destPred; -#endif - double s = 0; - int iShape = 0; - for (int laneSectionIndex = 0; laneSectionIndex < (int)dest->laneSections.size(); laneSectionIndex++) { - auto& laneSection = dest->laneSections[laneSectionIndex]; - const double nextS = laneSectionIndex + 1 < (int)dest->laneSections.size() ? dest->laneSections[laneSectionIndex + 1].s : std::numeric_limits::max(); - int i = iShape; // shape index at the start of the current lane section - double sStart = s; // distance offset a the start of the current lane section - double finalS = s; // final distance value after processing this segment - int finalI = i; - for (const OpenDriveLane& destLane : laneSection.lanesByDir[lanesDir]) { - // each lane of the current segment repeats the same section of shape points and distance offsets - double sectionS = 0; - i = iShape; - s = sStart; -#ifdef DEBUG_INTERNALSHAPES - destPred += " lane=" + toString(destLane.id) - + " pred=" + toString(destLane.predecessor) - + " succ=" + toString(destLane.successor) - + " wStart=" + toString(destLane.widthData.front().computeAt(0)) - + " wEnd=" + toString(destLane.widthData.front().computeAt(cn.shape.length2D())) - + " width=" + toString(destLane.width) + "\n"; -#endif - if (abs(destLane.id) <= abs(referenceLane)) { - const double multiplier = offsetFactor * (destLane.id == referenceLane ? 0.5 : 1); -#ifdef DEBUG_INTERNALSHAPES - destPred += " multiplier=" + toString(multiplier) + "\n"; -#endif - int widthDataIndex = 0; - while (s < nextS && i < (int)cn.shape.size()) { - if (i > 0) { - const double dist = cn.shape[i - 1].distanceTo2D(cn.shape[i]); - s += dist; - sectionS += dist; - - } - while (widthDataIndex + 1 < (int)destLane.widthData.size() - && sectionS >= destLane.widthData[widthDataIndex + 1].s) { - widthDataIndex++; - } - offsets[i] += destLane.widthData[widthDataIndex].computeAt(sectionS) * multiplier; - //if (cn.fromEdge == "1014000" && dest->id == "3001022") { - // std::cout << " i=" << i << " s=" << s << " lane=" << destLane.id << " rlane=" << referenceLane /*<< " nextS=" << nextS << */ << " lsIndex=" << laneSectionIndex << " wI=" << widthDataIndex << " wSize=" << destLane.widthData.size() << " m=" << multiplier << " o=" << offsets[i] << "\n"; - //} - i++; - } - finalS = s; - finalI = i; - } else if (finalS == s) { - // update finalS without changing offsets - while (s < nextS && i < (int)cn.shape.size()) { - if (i > 0) { - const double dist = cn.shape[i - 1].distanceTo2D(cn.shape[i]); - s += dist; - finalS += dist; - - } - i++; - } - finalI = i; - - } - } - // advance values for the next lane section - iShape = finalI; - s = finalS; - } - try { - cn.shape.move2side(offsets); - } catch (InvalidArgument&) { - WRITE_WARNING("Could not import internal lane shape from edge '" + c.fromEdge + "' to edge '" + c.toEdge); - cn.shape.clear(); - } -#ifdef DEBUG_INTERNALSHAPES - std::cout << "internalShape " - << c.getDescription() - << " dest=" << dest->id - << " refLane=" << referenceLane - << " destPred\n" << destPred - << " offsets=" << offsets - << "\n shape=" << dest->geom - << "\n shape2=" << cn.shape - << "\n"; -#endif - if (c.toCP == OPENDRIVE_CP_END) { - cn.shape = cn.shape.reverse(); - } - } -#ifdef DEBUG_CONNECTIONS - if (DEBUG_COND3(c.fromEdge)) { - std::cout << " added connection\n"; - } -#endif - into.push_back(cn); - } - } - } -} - - -bool -NIImporter_OpenDrive::laneSectionsConnected(OpenDriveEdge* edge, int in, int out) { - if (edge->laneSections.size() == 1) { - return in == out; - } else { - // there could be spacing lanes (type 'none') that lead to a shift in lane index - for (auto it = edge->laneSections.begin(); it + 1 < edge->laneSections.end(); it++) { - OpenDriveLaneSection& laneSection = *it; - if (laneSection.lanesByDir.find(OPENDRIVE_TAG_RIGHT) != laneSection.lanesByDir.end()) { - for (OpenDriveLane& lane : laneSection.lanesByDir.find(OPENDRIVE_TAG_RIGHT)->second) { - if (lane.id == in) { - in = lane.successor; - break; - } - } - } - if (laneSection.lanesByDir.find(OPENDRIVE_TAG_LEFT) != laneSection.lanesByDir.end()) { - for (OpenDriveLane& lane : laneSection.lanesByDir.find(OPENDRIVE_TAG_LEFT)->second) { - if (lane.id == in) { - in = lane.successor; - break; - } - } - } - } - return in == out; - } -} - - -void -NIImporter_OpenDrive::setEdgeLinks2(OpenDriveEdge& e, const std::map& edges) { - for (std::vector::iterator i = e.links.begin(); i != e.links.end(); ++i) { - OpenDriveLink& l = *i; - if (l.elementType != OPENDRIVE_ET_ROAD) { - // we assume that links to nodes are later given as connections to edges - continue; - } - // get the right direction of the connected edge - std::string connectedEdge = l.elementID; - std::string edgeID = e.id; - - OpenDriveLaneSection& laneSection = l.linkType == OPENDRIVE_LT_SUCCESSOR ? e.laneSections.back() : e.laneSections[0]; - const std::map& laneMap = laneSection.laneMap; -#ifdef DEBUG_CONNECTIONS - if (DEBUG_COND(&e)) { - std::cout << "edge=" << e.id << " eType=" << l.elementType << " lType=" << l.linkType << " connectedEdge=" << connectedEdge << " laneSection=" << laneSection.s << " map:\n"; - std::cout << joinToString(laneMap, "\n", ":") << "\n"; - } -#endif - if (laneSection.lanesByDir.find(OPENDRIVE_TAG_RIGHT) != laneSection.lanesByDir.end()) { - const std::vector& lanes = laneSection.lanesByDir.find(OPENDRIVE_TAG_RIGHT)->second; - for (std::vector::const_iterator j = lanes.begin(); j != lanes.end(); ++j) { - if (!myImportAllTypes && laneMap.find((*j).id) == laneMap.end()) { - continue; - } - Connection c; // @todo: give Connection a new name and a constructor - c.fromEdge = e.id; - c.fromLane = (*j).id; - c.fromCP = OPENDRIVE_CP_END; - c.toLane = l.linkType == OPENDRIVE_LT_SUCCESSOR ? (*j).successor : (*j).predecessor; - c.toEdge = connectedEdge; - c.toCP = l.contactPoint; - c.all = false; - if (l.linkType != OPENDRIVE_LT_SUCCESSOR) { - std::swap(c.fromEdge, c.toEdge); - std::swap(c.fromLane, c.toLane); - std::swap(c.fromCP, c.toCP); - } - if (edges.find(c.fromEdge) == edges.end()) { - WRITE_ERROR("While setting connections: incoming road '" + c.fromEdge + "' is not known."); - } else { - OpenDriveEdge* src = edges.find(c.fromEdge)->second; - src->connections.insert(c); -#ifdef DEBUG_CONNECTIONS - if (DEBUG_COND(src)) { - std::cout << "insertConRight from=" << src->id << "_" << c.fromLane << " to=" << c.toEdge << "_" << c.toLane << "\n"; - } -#endif - } - } - } - if (laneSection.lanesByDir.find(OPENDRIVE_TAG_LEFT) != laneSection.lanesByDir.end()) { - const std::vector& lanes = laneSection.lanesByDir.find(OPENDRIVE_TAG_LEFT)->second; - for (std::vector::const_iterator j = lanes.begin(); j != lanes.end(); ++j) { - if (!myImportAllTypes && laneMap.find((*j).id) == laneMap.end()) { - continue; - } - Connection c; - c.toEdge = e.id; - c.toLane = (*j).id; - c.toCP = OPENDRIVE_CP_END; - c.fromLane = l.linkType == OPENDRIVE_LT_SUCCESSOR ? (*j).successor : (*j).predecessor; - c.fromEdge = connectedEdge; - c.fromCP = l.contactPoint; - c.all = false; - if (l.linkType != OPENDRIVE_LT_SUCCESSOR) { - std::swap(c.fromEdge, c.toEdge); - std::swap(c.fromLane, c.toLane); - std::swap(c.fromCP, c.toCP); - } - if (edges.find(c.fromEdge) == edges.end()) { - WRITE_ERROR("While setting connections: incoming road '" + c.fromEdge + "' is not known."); - } else { - OpenDriveEdge* src = edges.find(c.fromEdge)->second; - src->connections.insert(c); -#ifdef DEBUG_CONNECTIONS - if (DEBUG_COND(src)) { - std::cout << "insertConLeft from=" << src->id << "_" << c.fromLane << " to=" << c.toEdge << "_" << c.toLane << "\n"; - } -#endif - } - } - } - } -} - - -std::string NIImporter_OpenDrive::revertID(const std::string& id) { - if (id[0] == '-') { - return id.substr(1); - } - return "-" + id; -} - - -NBNode* -NIImporter_OpenDrive::getOrBuildNode(const std::string& id, const Position& pos, - NBNodeCont& nc) { - if (nc.retrieve(id) == nullptr) { - // not yet built; build now - if (!nc.insert(id, pos)) { - // !!! clean up - throw ProcessError("Could not add node '" + id + "'."); - } - } - return nc.retrieve(id); -} - - -void -NIImporter_OpenDrive::setNodeSecure(NBNodeCont& nc, OpenDriveEdge& e, - const std::string& nodeID, NIImporter_OpenDrive::LinkType lt, std::vector& joinedNodeIDs) { - NBNode* n = nc.retrieve(nodeID); - if (n == nullptr) { - throw ProcessError("Could not find node '" + nodeID + "'."); - } - NBNode* toJoin = nullptr; - if (lt == OPENDRIVE_LT_SUCCESSOR) { - if (e.to != nullptr && e.to != n) { - toJoin = e.to; - } - e.to = n; - } else { - if (e.from != nullptr && e.from != n) { - toJoin = e.from; - } - e.from = n; - } - if (toJoin != nullptr) { - // join nodes - NodeSet* set1 = nullptr; - NodeSet* set2 = nullptr; - for (NodeSet& joined : joinedNodeIDs) { - if (joined.count(toJoin) != 0) { - set1 = &joined; - } - if (joined.count(n) != 0) { - set2 = &joined; - } - } - if (set1 == nullptr && set2 == nullptr) { - joinedNodeIDs.push_back(NodeSet()); - joinedNodeIDs.back().insert(n); - joinedNodeIDs.back().insert(toJoin); - } else if (set1 == nullptr && set2 != nullptr) { - set2->insert(toJoin); - } else if (set1 != nullptr && set2 == nullptr) { - set1->insert(n); - } else { - set1->insert(set2->begin(), set2->end()); - joinedNodeIDs.erase(std::find(joinedNodeIDs.begin(), joinedNodeIDs.end(), *set2)); - } - } -} - -bool -NIImporter_OpenDrive::hasNonLinearElevation(OpenDriveEdge& e) { - if (e.elevations.size() > 1) { - return true; - } - for (OpenDriveElevation& el : e.elevations) { - if (el.c != 0 || el.d != 0) { - return true; - } - } - return false; -} - -void -NIImporter_OpenDrive::computeShapes(std::map& edges) { - OptionsCont& oc = OptionsCont::getOptions(); - const double res = oc.getFloat("opendrive.curve-resolution"); - for (std::map::iterator i = edges.begin(); i != edges.end(); ++i) { - OpenDriveEdge& e = *(*i).second; - GeometryType prevType = OPENDRIVE_GT_UNKNOWN; - const double lineRes = hasNonLinearElevation(e) ? res : -1; - Position last; - for (std::vector::iterator j = e.geometries.begin(); j != e.geometries.end(); ++j) { - OpenDriveGeometry& g = *j; - PositionVector geom; - switch (g.type) { - case OPENDRIVE_GT_UNKNOWN: - break; - case OPENDRIVE_GT_LINE: - geom = geomFromLine(e, g, lineRes); - break; - case OPENDRIVE_GT_SPIRAL: - geom = geomFromSpiral(e, g, res); - break; - case OPENDRIVE_GT_ARC: - geom = geomFromArc(e, g, res); - break; - case OPENDRIVE_GT_POLY3: - geom = geomFromPoly(e, g, res); - break; - case OPENDRIVE_GT_PARAMPOLY3: - geom = geomFromParamPoly(e, g, res); - break; - default: - break; - } - if (e.geom.size() > 0 && prevType == OPENDRIVE_GT_LINE) { - // remove redundant end point of the previous geometry segment - // (the start point of the current segment should have the same value) - // this avoids geometry errors due to imprecision - if (!e.geom.back().almostSame(geom.front())) { - const int index = (int)(j - e.geometries.begin()); - WRITE_WARNING("Mismatched geometry for edge '" + e.id + "' between geometry segments " + toString(index - 1) + " and " + toString(index) + "."); - } - e.geom.pop_back(); - } - //std::cout << " adding geometry to road=" << e.id << " old=" << e.geom << " new=" << geom << "\n"; - for (PositionVector::iterator k = geom.begin(); k != geom.end(); ++k) { - last = *k; - e.geom.push_back_noDoublePos(*k); - } - prevType = g.type; - } - if (e.geom.size() == 1 && e.geom.front() != last) { - // avoid length-1 geometry due to almostSame check - e.geom.push_back(last); - } - if (oc.exists("geometry.min-dist") && !oc.isDefault("geometry.min-dist")) { - e.geom.removeDoublePoints(oc.getFloat("geometry.min-dist"), true); - } - if (!NBNetBuilder::transformCoordinates(e.geom)) { - WRITE_ERROR("Unable to project coordinates for edge '" + e.id + "'."); - } - // add z-data - int k = 0; - double pos = 0; - //std::cout << " edge=" << e.id << " geom.size=" << e.geom.size() << " geom.len=" << e.geom.length2D() << " ele.size=" << e.elevations.size() << "\n"; - for (std::vector::iterator j = e.elevations.begin(); j != e.elevations.end(); ++j) { - const OpenDriveElevation& el = *j; - const double sNext = (j + 1) == e.elevations.end() ? std::numeric_limits::max() : (*(j + 1)).s; - while (k < (int)e.geom.size() && pos < sNext) { - const double z = el.computeAt(pos); - //std::cout << " edge=" << e.id << " k=" << k << " sNext=" << sNext << " pos=" << pos << " z=" << z << " el.s=" << el.s << " el.a=" << el.a << " el.b=" << el.b << " el.c=" << el.c << " el.d=" << el.d << "\n"; - e.geom[k].add(0, 0, z); - k++; - if (k < (int)e.geom.size()) { - // XXX pos understimates the actual position since the - // actual geometry between k-1 and k could be curved - pos += e.geom[k - 1].distanceTo2D(e.geom[k]); - } - } - } - // add laneoffset - if (e.offsets.size() > 0) { - // make sure there are intermediate points for each offset-section - for (std::vector::iterator j = e.offsets.begin(); j != e.offsets.end(); ++j) { - const OpenDriveLaneOffset& el = *j; - // check wether we need to insert a new point at dist - Position pS = e.geom.positionAtOffset2D(el.s); - int iS = e.geom.indexOfClosest(pS); - // prevent close spacing to reduce impact of rounding errors in z-axis - if (pS.distanceTo2D(e.geom[iS]) > POSITION_EPS) { - e.geom.insertAtClosest(pS, false); - //std::cout << " edge=" << e.id << " inserting pos=" << pS << " s=" << el.s << " iS=" << iS << " dist=" << pS.distanceTo2D(e.geom[iS]) << "\n"; - } - } - // XXX add further points for sections with non-constant offset - // shift each point orthogonally by the specified offset - int k = 0; - double pos = 0; - for (std::vector::iterator j = e.offsets.begin(); j != e.offsets.end(); ++j) { - const OpenDriveLaneOffset& el = *j; - const double sNext = (j + 1) == e.offsets.end() ? std::numeric_limits::max() : (*(j + 1)).s; - while (k < (int)e.geom.size() && pos < sNext) { - const double offset = el.computeAt(pos); - e.laneOffsets.push_back(fabs(offset) > POSITION_EPS ? -offset : 0); - k++; - if (k < (int)e.geom.size()) { - // XXX pos understimates the actual position since the - // actual geometry between k-1 and k could be curved - pos += e.geom[k - 1].distanceTo2D(e.geom[k]); - } - } - } - } - //std::cout << " loaded geometry " << e.id << "=" << e.geom << "\n"; - } -} - - -void -NIImporter_OpenDrive::revisitLaneSections(const NBTypeCont& tc, std::map& edges) { - for (std::map::iterator i = edges.begin(); i != edges.end(); ++i) { - OpenDriveEdge& e = *(*i).second; -#ifdef DEBUG_VARIABLE_SPEED - if (DEBUG_COND(&e)) { - gDebugFlag1 = true; - std::cout << "revisitLaneSections e=" << e.id << "\n"; - } -#endif - std::vector& laneSections = e.laneSections; - // split by speed limits - std::vector newSections; - for (std::vector::iterator j = laneSections.begin(); j != laneSections.end(); ++j) { - std::vector splitSections; - bool splitBySpeed = (*j).buildSpeedChanges(tc, splitSections); - if (!splitBySpeed) { - newSections.push_back(*j); - } else { - std::copy(splitSections.begin(), splitSections.end(), back_inserter(newSections)); - } - } - - e.laneSections = newSections; - laneSections = e.laneSections; - double lastS = -1; - // check whether the lane sections are in the right order - bool sorted = true; - for (std::vector::const_iterator j = laneSections.begin(); j != laneSections.end() && sorted; ++j) { - if ((*j).s <= lastS) { - sorted = false; - } - lastS = (*j).s; - } - if (!sorted) { - WRITE_WARNING("The sections of edge '" + e.id + "' are not sorted properly."); - sort(e.laneSections.begin(), e.laneSections.end(), sections_by_s_sorter()); - } - // check whether no duplicates of s-value occure - lastS = -1; - laneSections = e.laneSections; - for (std::vector::iterator j = laneSections.begin(); j != laneSections.end();) { - bool simlarToLast = fabs((*j).s - lastS) < POSITION_EPS; - lastS = (*j).s; - // keep all lane sections for connecting roads because they are - // needed to establish connectivity (laneSectionsConnected) - if (simlarToLast && !e.isInner) { - WRITE_WARNING("Almost duplicate s-value '" + toString(lastS) + "' for lane sections occurred at edge '" + e.id + "'; second entry was removed."); - j = laneSections.erase(j); - } else { - ++j; - } - } -#ifdef DEBUG_VARIABLE_SPEED - gDebugFlag1 = false; -#endif - } -} - - -PositionVector -NIImporter_OpenDrive::geomFromLine(const OpenDriveEdge& e, const OpenDriveGeometry& g, double resolution) { - UNUSED_PARAMETER(e); - PositionVector ret; - Position start(g.x, g.y); - Position end = calculateStraightEndPoint(g.hdg, g.length, start); - if (resolution > 0 && g.length > 0) { - const int numPoints = (int)ceil(g.length / resolution) + 1; - double dx = (end.x() - start.x()) / (numPoints - 1); - double dy = (end.y() - start.y()) / (numPoints - 1); - for (int i = 0; i < numPoints; i++) { - ret.push_back(Position(g.x + i * dx, g.y + i * dy)); - } - } else { - ret.push_back(start); - ret.push_back(end); - } - return ret; -} - - -PositionVector -NIImporter_OpenDrive::geomFromSpiral(const OpenDriveEdge& e, const OpenDriveGeometry& g, double resolution) { - UNUSED_PARAMETER(e); - PositionVector ret; - double curveStart = g.params[0]; - double curveEnd = g.params[1]; - try { - double cDot = (curveEnd - curveStart) / g.length; - if (cDot == 0 || g.length == 0) { - WRITE_WARNINGF("Could not compute spiral geometry for edge '%' (cDot=% length=%).", e.id, toString(cDot), toString(g.length)); - ret.push_back(Position(g.x, g.y)); - return ret; - } - double sStart = curveStart / cDot; - double sEnd = curveEnd / cDot; - double x = 0; - double y = 0; - double t = 0; - double tStart = 0; - double s; - odrSpiral(sStart, cDot, &x, &y, &tStart); - for (s = sStart; s <= sEnd; s += resolution) { - odrSpiral(s, cDot, &x, &y, &t); - ret.push_back(Position(x, y)); - } - if (s != sEnd /*&& ret.size() == 1*/) { - odrSpiral(sEnd, cDot, &x, &y, &t); - ret.push_back(Position(x, y)); - } - //if (s != sEnd && ret.size() > 2) { - // ret.pop_back(); - //} - assert(ret.size() >= 2); - assert(ret[0] != ret[1]); - // shift start to coordinate origin - PositionVector ret1 = ret; - ret.add(ret.front() * -1); - // rotate - PositionVector ret2 = ret; - ret.rotate2D(g.hdg - tStart); -#ifdef DEBUG_SPIRAL - std::cout - << std::setprecision(4) - << "edge=" << e.id << " s=" << g.s - << " cStart=" << curveStart - << " cEnd=" << curveEnd - << " cDot=" << cDot - << " sStart=" << sStart - << " sEnd=" << sEnd - << " g.hdg=" << GeomHelper::naviDegree(g.hdg) - << " tStart=" << GeomHelper::naviDegree(tStart) - << "\n beforeShift=" << ret1 - << "\n beforeRot=" << ret2 - << "\n"; -#endif - // shift to geometry start - ret.add(g.x, g.y, 0); - } catch (const std::runtime_error& error) { - WRITE_WARNING("Could not compute spiral geometry for edge '" + e.id + "' (" + error.what() + ")."); - ret.push_back(Position(g.x, g.y)); - } - return ret.getSubpart2D(0, g.length); -} - - -PositionVector -NIImporter_OpenDrive::geomFromArc(const OpenDriveEdge& e, const OpenDriveGeometry& g, double resolution) { - UNUSED_PARAMETER(e); - PositionVector ret; - double dist = 0.0; - double centerX = g.x; - double centerY = g.y; - // left: positive value - double curvature = g.params[0]; - double radius = 1. / curvature; - // center point - calculateCurveCenter(¢erX, ¢erY, radius, g.hdg); - double endX = g.x; - double endY = g.y; - double startX = g.x; - double startY = g.y; - double geo_posS = g.s; - double geo_posE = g.s; - bool end = false; - do { - geo_posE += resolution; - if (geo_posE - g.s > g.length) { - geo_posE = g.s + g.length; - } - if (geo_posE - g.s > g.length) { - geo_posE = g.s + g.length; - } - calcPointOnCurve(&endX, &endY, centerX, centerY, radius, geo_posE - geo_posS); - - dist += (geo_posE - geo_posS); - // - ret.push_back(Position(startX, startY)); - // - startX = endX; - startY = endY; - geo_posS = geo_posE; - - if (geo_posE - (g.s + g.length) < 0.001 && geo_posE - (g.s + g.length) > -0.001) { - end = true; - } - } while (!end); - return ret.getSubpart2D(0, g.length); -} - - -PositionVector -NIImporter_OpenDrive::geomFromPoly(const OpenDriveEdge& e, const OpenDriveGeometry& g, double resolution) { - UNUSED_PARAMETER(e); - const double s = sin(g.hdg); - const double c = cos(g.hdg); - PositionVector ret; - for (double off = 0; off < g.length + 2.; off += resolution) { - double x = off; - double y = g.params[0] + g.params[1] * off + g.params[2] * pow(off, 2.) + g.params[3] * pow(off, 3.); - double xnew = x * c - y * s; - double ynew = x * s + y * c; - ret.push_back(Position(g.x + xnew, g.y + ynew)); - } - return ret.getSubpart2D(0, g.length); -} - - -PositionVector -NIImporter_OpenDrive::geomFromParamPoly(const OpenDriveEdge& e, const OpenDriveGeometry& g, double resolution) { - UNUSED_PARAMETER(e); - const double s = sin(g.hdg); - const double c = cos(g.hdg); - const double pMax = g.params[8] <= 0 ? g.length : g.params[8]; - const double pStep = pMax / ceil(g.length / resolution); - PositionVector ret; - for (double p = 0; p <= pMax + pStep; p += pStep) { - double x = g.params[0] + g.params[1] * p + g.params[2] * pow(p, 2.) + g.params[3] * pow(p, 3.); - double y = g.params[4] + g.params[5] * p + g.params[6] * pow(p, 2.) + g.params[7] * pow(p, 3.); - double xnew = x * c - y * s; - double ynew = x * s + y * c; - ret.push_back(Position(g.x + xnew, g.y + ynew)); - } - return ret.getSubpart2D(0, g.length); -} - - -Position -NIImporter_OpenDrive::calculateStraightEndPoint(double hdg, double length, const Position& start) { - double normx = 1.0f; - double normy = 0.0f; - double x2 = normx * cos(hdg) - normy * sin(hdg); - double y2 = normx * sin(hdg) + normy * cos(hdg); - normx = x2 * length; - normy = y2 * length; - return Position(start.x() + normx, start.y() + normy); -} - - -void -NIImporter_OpenDrive::calculateCurveCenter(double* ad_x, double* ad_y, double ad_radius, double ad_hdg) { - double normX = 1.0; - double normY = 0.0; - double tmpX; - double turn; - if (ad_radius > 0) { - turn = -1.0; - } else { - turn = 1.0; - } - - tmpX = normX; - normX = normX * cos(ad_hdg) + normY * sin(ad_hdg); - normY = tmpX * sin(ad_hdg) + normY * cos(ad_hdg); - - tmpX = normX; - normX = turn * normY; - normY = -turn * tmpX; - - normX = fabs(ad_radius) * normX; - normY = fabs(ad_radius) * normY; - - *ad_x += normX; - *ad_y += normY; -} - - -void -NIImporter_OpenDrive::calcPointOnCurve(double* ad_x, double* ad_y, double ad_centerX, double ad_centerY, - double ad_r, double ad_length) { - double rotAngle = ad_length / fabs(ad_r); - double vx = *ad_x - ad_centerX; - double vy = *ad_y - ad_centerY; - double tmpx; - - double turn; - if (ad_r > 0) { - turn = -1; //left - } else { - turn = 1; //right - } - tmpx = vx; - vx = vx * cos(rotAngle) + turn * vy * sin(rotAngle); - vy = -1 * turn * tmpx * sin(rotAngle) + vy * cos(rotAngle); - *ad_x = vx + ad_centerX; - *ad_y = vy + ad_centerY; -} - - -// --------------------------------------------------------------------------- -// section -// --------------------------------------------------------------------------- -NIImporter_OpenDrive::OpenDriveLaneSection::OpenDriveLaneSection(double sArg) : s(sArg), sOrig(sArg) { - lanesByDir[OPENDRIVE_TAG_LEFT] = std::vector(); - lanesByDir[OPENDRIVE_TAG_RIGHT] = std::vector(); - lanesByDir[OPENDRIVE_TAG_CENTER] = std::vector(); -} - - -void -NIImporter_OpenDrive::OpenDriveLaneSection::buildLaneMapping(const NBTypeCont& tc) { - int sumoLane = 0; - bool singleType = true; - std::vector types; - const std::vector& dirLanesR = lanesByDir.find(OPENDRIVE_TAG_RIGHT)->second; - for (std::vector::const_reverse_iterator i = dirLanesR.rbegin(); i != dirLanesR.rend(); ++i) { - if (myImportAllTypes || (tc.knows((*i).type) && !tc.getShallBeDiscarded((*i).type))) { - laneMap[(*i).id] = sumoLane++; - types.push_back((*i).type); - if (types.front() != types.back()) { - singleType = false; - } - } - } - rightLaneNumber = sumoLane; - rightType = sumoLane > 0 ? (singleType ? types.front() : joinToString(types, "|")) : ""; - sumoLane = 0; - singleType = true; - types.clear(); - const std::vector& dirLanesL = lanesByDir.find(OPENDRIVE_TAG_LEFT)->second; - for (std::vector::const_iterator i = dirLanesL.begin(); i != dirLanesL.end(); ++i) { - if (myImportAllTypes || (tc.knows((*i).type) && !tc.getShallBeDiscarded((*i).type))) { - laneMap[(*i).id] = sumoLane++; - types.push_back((*i).type); - if (types.front() != types.back()) { - singleType = false; - } - } - } - leftLaneNumber = sumoLane; - leftType = sumoLane > 0 ? (singleType ? types.front() : joinToString(types, "|")) : ""; -} - - -std::map -NIImporter_OpenDrive::OpenDriveLaneSection::getInnerConnections(OpenDriveXMLTag dir, const OpenDriveLaneSection& prev) { - std::map ret; - const std::vector& dirLanes = lanesByDir.find(dir)->second; - for (std::vector::const_reverse_iterator i = dirLanes.rbegin(); i != dirLanes.rend(); ++i) { - std::map::const_iterator toP = laneMap.find((*i).id); - if (toP == laneMap.end()) { - // the current lane is not available in SUMO - continue; - } - int to = (*toP).second; - int from = UNSET_CONNECTION; - if ((*i).predecessor != UNSET_CONNECTION) { - from = (*i).predecessor; - } - if (from != UNSET_CONNECTION) { - std::map::const_iterator fromP = prev.laneMap.find(from); - if (fromP != prev.laneMap.end()) { - from = (*fromP).second; - } else { - from = UNSET_CONNECTION; - } - } - if (from != UNSET_CONNECTION && to != UNSET_CONNECTION) { - if (ret.find(from) != ret.end()) { -// WRITE_WARNING("double connection"); - } - if (dir == OPENDRIVE_TAG_LEFT) { - std::swap(from, to); - } - ret[from] = to; - } else { -// WRITE_WARNING("missing connection"); - } - } - return ret; -} - - -NIImporter_OpenDrive::OpenDriveLaneSection -NIImporter_OpenDrive::OpenDriveLaneSection::buildLaneSection(double startPos) { - OpenDriveLaneSection ret(*this); - ret.s += startPos; - for (int k = 0; k < (int)ret.lanesByDir[OPENDRIVE_TAG_RIGHT].size(); ++k) { - OpenDriveLane& l = ret.lanesByDir[OPENDRIVE_TAG_RIGHT][k]; - l.speed = 0; - std::vector >::const_iterator i = std::find_if(l.speeds.begin(), l.speeds.end(), same_position_finder(startPos)); - if (i != l.speeds.end()) { - l.speed = (*i).second; - } - } - for (int k = 0; k < (int)ret.lanesByDir[OPENDRIVE_TAG_LEFT].size(); ++k) { - OpenDriveLane& l = ret.lanesByDir[OPENDRIVE_TAG_LEFT][k]; - std::vector >::const_iterator i = std::find_if(l.speeds.begin(), l.speeds.end(), same_position_finder(startPos)); - l.speed = 0; - if (i != l.speeds.end()) { - l.speed = (*i).second; - } - } - return ret; -} - - -bool -NIImporter_OpenDrive::OpenDriveLaneSection::buildSpeedChanges(const NBTypeCont& tc, std::vector& newSections) { - std::set speedChangePositions; - // collect speed change positions and apply initial speed to the begin - for (std::vector::iterator k = lanesByDir[OPENDRIVE_TAG_RIGHT].begin(); k != lanesByDir[OPENDRIVE_TAG_RIGHT].end(); ++k) { - for (std::vector >::const_iterator l = (*k).speeds.begin(); l != (*k).speeds.end(); ++l) { - speedChangePositions.insert((*l).first); - if ((*l).first == 0) { - (*k).speed = (*l).second; - } - } - } - for (std::vector::iterator k = lanesByDir[OPENDRIVE_TAG_LEFT].begin(); k != lanesByDir[OPENDRIVE_TAG_LEFT].end(); ++k) { - for (std::vector >::const_iterator l = (*k).speeds.begin(); l != (*k).speeds.end(); ++l) { - speedChangePositions.insert((*l).first); - if ((*l).first == 0) { - (*k).speed = (*l).second; - } - } - } - // do nothing if there is none - if (speedChangePositions.size() == 0) { - return false; - } - if (*speedChangePositions.begin() > 0) { - speedChangePositions.insert(0); - } -#ifdef DEBUG_VARIABLE_SPEED - if (gDebugFlag1) std::cout - << " buildSpeedChanges sectionStart=" << s - << " speedChangePositions=" << joinToString(speedChangePositions, ", ") - << "\n"; -#endif - for (std::set::iterator i = speedChangePositions.begin(); i != speedChangePositions.end(); ++i) { - if (i == speedChangePositions.begin()) { - newSections.push_back(*this); - } else { - newSections.push_back(buildLaneSection(*i)); - } - } - // propagate speeds - for (int i = 0; i != (int)newSections.size(); ++i) { - OpenDriveLaneSection& ls = newSections[i]; - std::map >& lanesByDir = ls.lanesByDir; - for (std::map >::iterator k = lanesByDir.begin(); k != lanesByDir.end(); ++k) { - std::vector& lanes = (*k).second; - for (int j = 0; j != (int)lanes.size(); ++j) { - OpenDriveLane& l = lanes[j]; - if (l.speed != 0) { - continue; - } - if (i > 0) { - l.speed = newSections[i - 1].lanesByDir[(*k).first][j].speed; - } else { - tc.getSpeed(l.type); - } - } - } - } - return true; -} - - - -// --------------------------------------------------------------------------- -// edge -// --------------------------------------------------------------------------- -int -NIImporter_OpenDrive::OpenDriveEdge::getPriority(OpenDriveXMLTag dir) const { - // for signal interpretations see https://de.wikipedia.org/wiki/Bildtafel_der_Verkehrszeichen_in_der_Bundesrepublik_Deutschland_seit_2013 - int prio = 1; - for (std::vector::const_iterator i = signals.begin(); i != signals.end(); ++i) { - int tmp = 1; - if ((*i).type == "301" || (*i).type == "306") { // priority road or local priority - tmp = 2; - } - if ((*i).type == "205" /*|| (*i).type == "206"*/) { // yield or stop - tmp = 0; - } - if (tmp != 1 && dir == OPENDRIVE_TAG_RIGHT && (*i).orientation > 0) { - prio = tmp; - } - if (tmp != 1 && dir == OPENDRIVE_TAG_LEFT && (*i).orientation < 0) { - prio = tmp; - } - - } - return prio; -} - - - -// --------------------------------------------------------------------------- -// loader methods -// --------------------------------------------------------------------------- -NIImporter_OpenDrive::NIImporter_OpenDrive(const NBTypeCont& tc, std::map& edges) - : GenericSAXHandler(openDriveTags, OPENDRIVE_TAG_NOTHING, openDriveAttrs, OPENDRIVE_ATTR_NOTHING, "opendrive"), - myTypeContainer(tc), myCurrentEdge("", "", "", -1), myEdges(edges) { -} - - -NIImporter_OpenDrive::~NIImporter_OpenDrive() { -} - - -void -NIImporter_OpenDrive::myStartElement(int element, - const SUMOSAXAttributes& attrs) { - bool ok = true; - switch (element) { - case OPENDRIVE_TAG_HEADER: { - /* - int majorVersion = attrs.get(OPENDRIVE_ATTR_REVMAJOR, nullptr, ok); - int minorVersion = attrs.get(OPENDRIVE_ATTR_REVMINOR, nullptr, ok); - if (majorVersion != 1 || minorVersion != 2) { - // TODO: leave note of exceptions - WRITE_WARNING("Given openDrive file '" + getFileName() + "' uses version " + toString(majorVersion) + "." + toString(minorVersion) + ";\n Version 1.2 is supported."); - } - */ - } - break; - case OPENDRIVE_TAG_ROAD: { - std::string id = attrs.get(OPENDRIVE_ATTR_ID, nullptr, ok); - std::string streetName = attrs.getOpt(OPENDRIVE_ATTR_NAME, nullptr, ok, "", false); - std::string junction = attrs.get(OPENDRIVE_ATTR_JUNCTION, id.c_str(), ok); - double length = attrs.get(OPENDRIVE_ATTR_LENGTH, id.c_str(), ok); - myCurrentEdge = OpenDriveEdge(id, streetName, junction, length); - } - break; - case OPENDRIVE_TAG_PREDECESSOR: { - if (myElementStack.size() >= 2 && myElementStack[myElementStack.size() - 2] == OPENDRIVE_TAG_ROAD) { - std::string elementType = attrs.get(OPENDRIVE_ATTR_ELEMENTTYPE, myCurrentEdge.id.c_str(), ok); - std::string elementID = attrs.get(OPENDRIVE_ATTR_ELEMENTID, myCurrentEdge.id.c_str(), ok); - std::string contactPoint = attrs.hasAttribute(OPENDRIVE_ATTR_CONTACTPOINT) - ? attrs.get(OPENDRIVE_ATTR_CONTACTPOINT, myCurrentEdge.id.c_str(), ok) - : "end"; - addLink(OPENDRIVE_LT_PREDECESSOR, elementType, elementID, contactPoint); - } - if (myElementStack.size() >= 2 && myElementStack[myElementStack.size() - 2] == OPENDRIVE_TAG_LANE) { - int no = attrs.get(OPENDRIVE_ATTR_ID, myCurrentEdge.id.c_str(), ok); - OpenDriveLane& l = myCurrentEdge.laneSections.back().lanesByDir[myCurrentLaneDirection].back(); - l.predecessor = no; - } - } - break; - case OPENDRIVE_TAG_SUCCESSOR: { - if (myElementStack.size() >= 2 && myElementStack[myElementStack.size() - 2] == OPENDRIVE_TAG_ROAD) { - std::string elementType = attrs.get(OPENDRIVE_ATTR_ELEMENTTYPE, myCurrentEdge.id.c_str(), ok); - std::string elementID = attrs.get(OPENDRIVE_ATTR_ELEMENTID, myCurrentEdge.id.c_str(), ok); - std::string contactPoint = attrs.hasAttribute(OPENDRIVE_ATTR_CONTACTPOINT) - ? attrs.get(OPENDRIVE_ATTR_CONTACTPOINT, myCurrentEdge.id.c_str(), ok) - : "start"; - addLink(OPENDRIVE_LT_SUCCESSOR, elementType, elementID, contactPoint); - } - if (myElementStack.size() >= 2 && myElementStack[myElementStack.size() - 2] == OPENDRIVE_TAG_LANE) { - int no = attrs.get(OPENDRIVE_ATTR_ID, myCurrentEdge.id.c_str(), ok); - OpenDriveLane& l = myCurrentEdge.laneSections.back().lanesByDir[myCurrentLaneDirection].back(); - l.successor = no; - } - } - break; - case OPENDRIVE_TAG_GEOMETRY: { - double length = attrs.get(OPENDRIVE_ATTR_LENGTH, myCurrentEdge.id.c_str(), ok); - double s = attrs.get(OPENDRIVE_ATTR_S, myCurrentEdge.id.c_str(), ok); - double x = attrs.get(OPENDRIVE_ATTR_X, myCurrentEdge.id.c_str(), ok); - double y = attrs.get(OPENDRIVE_ATTR_Y, myCurrentEdge.id.c_str(), ok); - double hdg = attrs.get(OPENDRIVE_ATTR_HDG, myCurrentEdge.id.c_str(), ok); - myCurrentEdge.geometries.push_back(OpenDriveGeometry(length, s, x, y, hdg)); - } - break; - case OPENDRIVE_TAG_ELEVATION: { - double s = attrs.get(OPENDRIVE_ATTR_S, myCurrentEdge.id.c_str(), ok); - double a = attrs.get(OPENDRIVE_ATTR_A, myCurrentEdge.id.c_str(), ok); - double b = attrs.get(OPENDRIVE_ATTR_B, myCurrentEdge.id.c_str(), ok); - double c = attrs.get(OPENDRIVE_ATTR_C, myCurrentEdge.id.c_str(), ok); - double d = attrs.get(OPENDRIVE_ATTR_D, myCurrentEdge.id.c_str(), ok); - myCurrentEdge.elevations.push_back(OpenDriveElevation(s, a, b, c, d)); - } - break; - case OPENDRIVE_TAG_LINE: { - if (myElementStack.size() > 0 && myElementStack.back() == OPENDRIVE_TAG_GEOMETRY) { - std::vector vals; - addGeometryShape(OPENDRIVE_GT_LINE, vals); - } - } - break; - case OPENDRIVE_TAG_SPIRAL: { - std::vector vals; - vals.push_back(attrs.get(OPENDRIVE_ATTR_CURVSTART, myCurrentEdge.id.c_str(), ok)); - vals.push_back(attrs.get(OPENDRIVE_ATTR_CURVEND, myCurrentEdge.id.c_str(), ok)); - addGeometryShape(OPENDRIVE_GT_SPIRAL, vals); - } - break; - case OPENDRIVE_TAG_ARC: { - std::vector vals; - vals.push_back(attrs.get(OPENDRIVE_ATTR_CURVATURE, myCurrentEdge.id.c_str(), ok)); - addGeometryShape(OPENDRIVE_GT_ARC, vals); - } - break; - case OPENDRIVE_TAG_POLY3: { - std::vector vals; - vals.push_back(attrs.get(OPENDRIVE_ATTR_A, myCurrentEdge.id.c_str(), ok)); - vals.push_back(attrs.get(OPENDRIVE_ATTR_B, myCurrentEdge.id.c_str(), ok)); - vals.push_back(attrs.get(OPENDRIVE_ATTR_C, myCurrentEdge.id.c_str(), ok)); - vals.push_back(attrs.get(OPENDRIVE_ATTR_D, myCurrentEdge.id.c_str(), ok)); - addGeometryShape(OPENDRIVE_GT_POLY3, vals); - } - break; - case OPENDRIVE_TAG_PARAMPOLY3: { - std::vector vals; - vals.push_back(attrs.get(OPENDRIVE_ATTR_AU, myCurrentEdge.id.c_str(), ok)); - vals.push_back(attrs.get(OPENDRIVE_ATTR_BU, myCurrentEdge.id.c_str(), ok)); - vals.push_back(attrs.get(OPENDRIVE_ATTR_CU, myCurrentEdge.id.c_str(), ok)); - vals.push_back(attrs.get(OPENDRIVE_ATTR_DU, myCurrentEdge.id.c_str(), ok)); - vals.push_back(attrs.get(OPENDRIVE_ATTR_AV, myCurrentEdge.id.c_str(), ok)); - vals.push_back(attrs.get(OPENDRIVE_ATTR_BV, myCurrentEdge.id.c_str(), ok)); - vals.push_back(attrs.get(OPENDRIVE_ATTR_CV, myCurrentEdge.id.c_str(), ok)); - vals.push_back(attrs.get(OPENDRIVE_ATTR_DV, myCurrentEdge.id.c_str(), ok)); - const std::string pRange = attrs.getOpt(OPENDRIVE_ATTR_PRANGE, myCurrentEdge.id.c_str(), ok, "normalized", false); - if (pRange == "normalized") { - vals.push_back(1.0); - } else if (pRange == "arcLength") { - vals.push_back(-1.0); - } else { - WRITE_WARNING("Ignoring invalid pRange value '" + pRange + "' for road '" + myCurrentEdge.id + "'."); - vals.push_back(1.0); - } - addGeometryShape(OPENDRIVE_GT_PARAMPOLY3, vals); - } - break; - case OPENDRIVE_TAG_LANESECTION: { - double s = attrs.get(OPENDRIVE_ATTR_S, myCurrentEdge.id.c_str(), ok); - if (myCurrentEdge.laneSections.size() > 0) { - myCurrentEdge.laneSections.back().length = s - myCurrentEdge.laneSections.back().s; - } - myCurrentEdge.laneSections.push_back(OpenDriveLaneSection(s)); - // possibly updated by the next laneSection - myCurrentEdge.laneSections.back().length = myCurrentEdge.length - s; - } - break; - case OPENDRIVE_TAG_LANEOFFSET: { - double s = attrs.get(OPENDRIVE_ATTR_S, myCurrentEdge.id.c_str(), ok); - double a = attrs.get(OPENDRIVE_ATTR_A, myCurrentEdge.id.c_str(), ok); - double b = attrs.get(OPENDRIVE_ATTR_B, myCurrentEdge.id.c_str(), ok); - double c = attrs.get(OPENDRIVE_ATTR_C, myCurrentEdge.id.c_str(), ok); - double d = attrs.get(OPENDRIVE_ATTR_D, myCurrentEdge.id.c_str(), ok); - myCurrentEdge.offsets.push_back(OpenDriveLaneOffset(s, a, b, c, d)); - } - break; - case OPENDRIVE_TAG_LEFT: - myCurrentLaneDirection = OPENDRIVE_TAG_LEFT; - break; - case OPENDRIVE_TAG_CENTER: - myCurrentLaneDirection = OPENDRIVE_TAG_CENTER; - break; - case OPENDRIVE_TAG_RIGHT: - myCurrentLaneDirection = OPENDRIVE_TAG_RIGHT; - break; - case OPENDRIVE_TAG_LANE: { - std::string type = attrs.get(OPENDRIVE_ATTR_TYPE, myCurrentEdge.id.c_str(), ok); - int id = attrs.get(OPENDRIVE_ATTR_ID, myCurrentEdge.id.c_str(), ok); - std::string level = attrs.hasAttribute(OPENDRIVE_ATTR_LEVEL) - ? attrs.get(OPENDRIVE_ATTR_LEVEL, myCurrentEdge.id.c_str(), ok) - : ""; - OpenDriveLaneSection& ls = myCurrentEdge.laneSections.back(); - ls.lanesByDir[myCurrentLaneDirection].push_back(OpenDriveLane(id, level, type)); - } - break; - case OPENDRIVE_TAG_SIGNAL: { - std::string id = attrs.get(OPENDRIVE_ATTR_ID, myCurrentEdge.id.c_str(), ok); - std::string type = attrs.get(OPENDRIVE_ATTR_TYPE, myCurrentEdge.id.c_str(), ok); - std::string name = attrs.getOpt(OPENDRIVE_ATTR_NAME, myCurrentEdge.id.c_str(), ok, "", false); - const std::string orientation = attrs.get(OPENDRIVE_ATTR_ORIENTATION, myCurrentEdge.id.c_str(), ok); - int orientationCode = orientation == "-" ? -1 : orientation == "+" ? 1 : 0; - double s = attrs.get(OPENDRIVE_ATTR_S, myCurrentEdge.id.c_str(), ok); - bool dynamic = attrs.get(OPENDRIVE_ATTR_DYNAMIC, myCurrentEdge.id.c_str(), ok) == "no" ? false : true; - OpenDriveSignal signal = OpenDriveSignal(id, type, name, orientationCode, dynamic, s); - myCurrentEdge.signals.push_back(signal); - mySignals[id] = signal; - } - break; - case OPENDRIVE_TAG_SIGNALREFERENCE: { - std::string id = attrs.get(OPENDRIVE_ATTR_ID, myCurrentEdge.id.c_str(), ok); - const std::string orientation = attrs.get(OPENDRIVE_ATTR_ORIENTATION, myCurrentEdge.id.c_str(), ok); - int orientationCode = orientation == "-" ? -1 : orientation == "+" ? 1 : 0; - double s = attrs.get(OPENDRIVE_ATTR_S, myCurrentEdge.id.c_str(), ok); - OpenDriveSignal signal = OpenDriveSignal(id, "", "", orientationCode, false, s); - myCurrentEdge.signals.push_back(signal); - } - break; - case OPENDRIVE_TAG_VALIDITY: { - int fromLane = attrs.get(OPENDRIVE_ATTR_FROMLANE, myCurrentEdge.id.c_str(), ok); - int toLane = attrs.get(OPENDRIVE_ATTR_TOLANE, myCurrentEdge.id.c_str(), ok); - myCurrentEdge.signals.back().minLane = fromLane; - myCurrentEdge.signals.back().maxLane = toLane; - } - break; - case OPENDRIVE_TAG_JUNCTION: - myCurrentJunctionID = attrs.get(OPENDRIVE_ATTR_ID, myCurrentJunctionID.c_str(), ok); - break; - case OPENDRIVE_TAG_CONNECTION: { - std::string id = attrs.get(OPENDRIVE_ATTR_ID, myCurrentJunctionID.c_str(), ok); - myCurrentIncomingRoad = attrs.get(OPENDRIVE_ATTR_INCOMINGROAD, myCurrentJunctionID.c_str(), ok); - myCurrentConnectingRoad = attrs.get(OPENDRIVE_ATTR_CONNECTINGROAD, myCurrentJunctionID.c_str(), ok); - std::string cp = attrs.get(OPENDRIVE_ATTR_CONTACTPOINT, myCurrentJunctionID.c_str(), ok); - myCurrentContactPoint = cp == "start" ? OPENDRIVE_CP_START : OPENDRIVE_CP_END; - myConnectionWasEmpty = true; - } - break; - case OPENDRIVE_TAG_LANELINK: { - int from = attrs.get(OPENDRIVE_ATTR_FROM, myCurrentJunctionID.c_str(), ok); - int to = attrs.get(OPENDRIVE_ATTR_TO, myCurrentJunctionID.c_str(), ok); - Connection c; - c.fromEdge = myCurrentIncomingRoad; - c.toEdge = myCurrentConnectingRoad; - c.fromLane = from; - c.toLane = to; - c.fromCP = OPENDRIVE_CP_END; - c.toCP = myCurrentContactPoint; - c.all = false; - if (myEdges.find(c.fromEdge) == myEdges.end()) { - WRITE_ERROR("In laneLink-element: incoming road '" + c.fromEdge + "' is not known."); - } else { - OpenDriveEdge* e = myEdges.find(c.fromEdge)->second; - e->connections.insert(c); - myConnectionWasEmpty = false; - } - } - break; - case OPENDRIVE_TAG_WIDTH: { - if (myElementStack.size() >= 2 && myElementStack[myElementStack.size() - 1] == OPENDRIVE_TAG_LANE) { - const double s = attrs.get(OPENDRIVE_ATTR_SOFFSET, myCurrentEdge.id.c_str(), ok); - const double a = attrs.get(OPENDRIVE_ATTR_A, myCurrentEdge.id.c_str(), ok); - const double b = attrs.get(OPENDRIVE_ATTR_B, myCurrentEdge.id.c_str(), ok); - const double c = attrs.get(OPENDRIVE_ATTR_C, myCurrentEdge.id.c_str(), ok); - const double d = attrs.get(OPENDRIVE_ATTR_D, myCurrentEdge.id.c_str(), ok); - OpenDriveLane& l = myCurrentEdge.laneSections.back().lanesByDir[myCurrentLaneDirection].back(); - l.width = MAX2(l.width, a); - l.widthData.push_back(OpenDriveWidth(s, a, b, c, d)); -#ifdef DEBUG_VARIABLE_WIDTHS - if (DEBUG_COND(&myCurrentEdge)) { - std::cout << " road=" << myCurrentEdge.id - << std::setprecision(gPrecision) - << " junction=" << myCurrentEdge.junction - << " section=" << myCurrentEdge.laneSections.size() - 1 - << " dir=" << myCurrentLaneDirection << " lane=" << l.id - << " type=" << l.type - << " width=" << l.width - << " a=" << a - << " b=" << b - << " c=" << c - << " d=" << d - << " s=" << s - << " entries=" << l.widthData.size() - << "\n"; - } -#endif - } - } - break; - case OPENDRIVE_TAG_SPEED: { - if (myElementStack.size() >= 2 && myElementStack[myElementStack.size() - 1] == OPENDRIVE_TAG_LANE) { - double speed = attrs.get(OPENDRIVE_ATTR_MAX, myCurrentEdge.id.c_str(), ok); - double pos = attrs.get(OPENDRIVE_ATTR_SOFFSET, myCurrentEdge.id.c_str(), ok); - // required for xodr v1.4 - const std::string unit = attrs.getOpt(OPENDRIVE_ATTR_UNIT, myCurrentEdge.id.c_str(), ok, "", false); - // now convert the speed to reasonable default SI [m/s] - if (!unit.empty()) { - // something to be done at all ? - if (unit == "km/h") { - speed /= 3.6; - } - if (unit == "mph") { - speed *= 1.609344 / 3.6; - } - // IGNORING unknown units. - } - myCurrentEdge.laneSections.back().lanesByDir[myCurrentLaneDirection].back().speeds.push_back(std::make_pair(pos, speed)); - } - } - break; - case OPENDRIVE_TAG_OBJECT: { - if (!attrs.hasAttribute(OPENDRIVE_ATTR_ID)) { - WRITE_WARNING("Ignoring object without id at edge '" + toString(myCurrentEdge.id) + "'."); - break; - } - OpenDriveObject o; - o.id = attrs.get(OPENDRIVE_ATTR_ID, 0, ok); - o.type = attrs.getOpt(OPENDRIVE_ATTR_TYPE, o.id.c_str(), ok, "", false); - o.name = attrs.getOpt(OPENDRIVE_ATTR_NAME, o.id.c_str(), ok, "", false); - o.s = attrs.get(OPENDRIVE_ATTR_S, o.id.c_str(), ok); - o.t = attrs.get(OPENDRIVE_ATTR_T, o.id.c_str(), ok); - o.width = attrs.getOpt(OPENDRIVE_ATTR_WIDTH, o.id.c_str(), ok, -1); - o.length = attrs.getOpt(OPENDRIVE_ATTR_LENGTH, o.id.c_str(), ok, -1); - o.radius = attrs.getOpt(OPENDRIVE_ATTR_RADIUS, o.id.c_str(), ok, -1); - o.hdg = attrs.getOpt(OPENDRIVE_ATTR_HDG, o.id.c_str(), ok, 0); - myCurrentEdge.objects.push_back(o); - } - break; - case OPENDRIVE_TAG_REPEAT: { - if (myCurrentEdge.objects.empty()) { - WRITE_ERROR("Repeat without object at edge '" + toString(myCurrentEdge.id) + "'."); - ok = false; - } else { - OpenDriveObject o = myCurrentEdge.objects.back(); - const std::string baseID = o.id; - double dist = attrs.get(OPENDRIVE_ATTR_DISTANCE, o.id.c_str(), ok); - if (dist == 0) { - // continuous feature. Split into parts (XXX exmport as a single polygon #5235) - dist = OptionsCont::getOptions().getFloat("opendrive.curve-resolution"); - } - - myCurrentEdge.objects.pop_back(); - const double length = attrs.get(OPENDRIVE_ATTR_LENGTH, o.id.c_str(), ok); - o.s = attrs.getOpt(OPENDRIVE_ATTR_S, o.id.c_str(), ok, o.s); - double wStart = attrs.getOpt(OPENDRIVE_ATTR_WIDTHSTART, o.id.c_str(), ok, o.width); - double wEnd = attrs.getOpt(OPENDRIVE_ATTR_WIDTHEND, o.id.c_str(), ok, o.width); - double tStart = attrs.getOpt(OPENDRIVE_ATTR_TSTART, o.id.c_str(), ok, o.t); - double tEnd = attrs.getOpt(OPENDRIVE_ATTR_TEND, o.id.c_str(), ok, o.t); - int index = 0; - for (double x = 0; x <= length + NUMERICAL_EPS; x += dist) { - o.id = baseID + "#" + toString(index++); - const double a = x / length; - o.width = wStart * (1 - a) + wEnd * a; - o.t = tStart * (1 - a) + tEnd * a; - myCurrentEdge.objects.push_back(o); - o.s += dist; - } - } - } - break; - default: - break; - } - myElementStack.push_back(element); -} - - -void -NIImporter_OpenDrive::myCharacters(int element, const std::string& cdata) { - if (element == OPENDRIVE_TAG_GEOREFERENCE) { - size_t i = cdata.find("+proj"); - if (i != std::string::npos) { - const std::string proj = cdata.substr(i); - if (proj != "") { - GeoConvHelper* result = nullptr; - Boundary convBoundary; - Boundary origBoundary; - Position networkOffset(0, 0); - // XXX read values from the header - convBoundary.add(Position(0, 0)); - origBoundary.add(Position(0, 0)); - try { - result = new GeoConvHelper(proj, networkOffset, origBoundary, convBoundary); - GeoConvHelper::setLoaded(*result); - } catch (ProcessError& e) { - WRITE_ERROR("Could not set projection. (" + std::string(e.what()) + ")"); - } - } - } else { - WRITE_WARNING("geoReference format '" + cdata + "' currently not supported"); - } - } -} - - -void -NIImporter_OpenDrive::myEndElement(int element) { - myElementStack.pop_back(); - switch (element) { - case OPENDRIVE_TAG_ROAD: - myEdges[myCurrentEdge.id] = new OpenDriveEdge(myCurrentEdge); - break; - case OPENDRIVE_TAG_CONNECTION: - if (myConnectionWasEmpty) { - Connection c; - c.fromEdge = myCurrentIncomingRoad; - c.toEdge = myCurrentConnectingRoad; - c.fromLane = 0; - c.toLane = 0; - c.fromCP = OPENDRIVE_CP_END; - c.toCP = myCurrentContactPoint; - c.all = true; - if (myEdges.find(c.fromEdge) == myEdges.end()) { - WRITE_ERROR("In laneLink-element: incoming road '" + c.fromEdge + "' is not known."); - } else { - OpenDriveEdge* e = myEdges.find(c.fromEdge)->second; - e->connections.insert(c); - } - } - break; - case OPENDRIVE_TAG_LANESECTION: { - myCurrentEdge.laneSections.back().buildLaneMapping(myTypeContainer); - } - break; - default: - break; - } -} - - - -void -NIImporter_OpenDrive::addLink(LinkType lt, const std::string& elementType, - const std::string& elementID, - const std::string& contactPoint) { - OpenDriveLink l(lt, elementID); - // elementType - if (elementType == "road") { - l.elementType = OPENDRIVE_ET_ROAD; - } else if (elementType == "junction") { - l.elementType = OPENDRIVE_ET_JUNCTION; - } - // contact point - if (contactPoint == "start") { - l.contactPoint = OPENDRIVE_CP_START; - } else if (contactPoint == "end") { - l.contactPoint = OPENDRIVE_CP_END; - } - // add - myCurrentEdge.links.push_back(l); -} - - -void -NIImporter_OpenDrive::addGeometryShape(GeometryType type, const std::vector& vals) { - // checks - if (myCurrentEdge.geometries.size() == 0) { - throw ProcessError("Mismatching paranthesis in geometry definition for road '" + myCurrentEdge.id + "'"); - } - OpenDriveGeometry& last = myCurrentEdge.geometries.back(); - if (last.type != OPENDRIVE_GT_UNKNOWN) { - throw ProcessError("Double geometry information for road '" + myCurrentEdge.id + "'"); - } - // set - last.type = type; - last.params = vals; -} - - -bool -operator<(const NIImporter_OpenDrive::Connection& c1, const NIImporter_OpenDrive::Connection& c2) { - if (c1.fromEdge != c2.fromEdge) { - return c1.fromEdge < c2.fromEdge; - } - if (c1.toEdge != c2.toEdge) { - return c1.toEdge < c2.toEdge; - } - if (c1.fromLane != c2.fromLane) { - return c1.fromLane < c2.fromLane; - } - return c1.toLane < c2.toLane; -} - -void -NIImporter_OpenDrive::sanitizeWidths(OpenDriveEdge* e) { -#ifdef DEBUG_VARIABLE_WIDTHS - if (DEBUG_COND(e)) { - gDebugFlag1 = true; - std::cout << "sanitizeWidths e=" << e->id << " sections=" << e->laneSections.size() << "\n"; - } -#endif - for (OpenDriveLaneSection& sec : e->laneSections) { - // filter widths within the current section (#5888). - // @note, Short laneSections could also be worth filtering alltogether - if (sec.rightLaneNumber > 0) { - sanitizeWidths(sec.lanesByDir[OPENDRIVE_TAG_RIGHT], sec.length); - } - if (sec.leftLaneNumber > 0) { - sanitizeWidths(sec.lanesByDir[OPENDRIVE_TAG_LEFT], sec.length); - } - } -} - -void -NIImporter_OpenDrive::sanitizeWidths(std::vector& lanes, double length) { - for (OpenDriveLane& l : lanes) { - if (l.widthData.size() > 0) { - auto& wd = l.widthData; - const double threshold = POSITION_EPS; - double maxNoShort = -std::numeric_limits::max(); - double seen = 0; - for (int i = 0; i < (int)wd.size(); i++) { - const double wdLength = i < (int)wd.size() - 1 ? wd[i + 1].s - wd[i].s : length - seen; - seen += wdLength; - if (wdLength > threshold) { - maxNoShort = MAX2(maxNoShort, wd[i].a); - } - } - if (maxNoShort > 0) { - l.width = maxNoShort; - } - } - } -} - - -void -NIImporter_OpenDrive::splitMinWidths(OpenDriveEdge* e, const NBTypeCont& tc, double minDist) { - std::vector newSections; -#ifdef DEBUG_VARIABLE_WIDTHS - if (DEBUG_COND(e)) { - gDebugFlag1 = true; - std::cout << "splitMinWidths e=" << e->id << " sections=" << e->laneSections.size() << "\n"; - } -#endif - for (std::vector::iterator j = e->laneSections.begin(); j != e->laneSections.end(); ++j) { - OpenDriveLaneSection& sec = *j; - std::vector splitPositions; - const double sectionEnd = (j + 1) == e->laneSections.end() ? e->length : (*(j + 1)).s; - const int section = (int)(j - e->laneSections.begin()); -#ifdef DEBUG_VARIABLE_WIDTHS - if (DEBUG_COND(e)) { - std::cout << " findWidthSplit section=" << section << " sectionStart=" << sec.s << " sectionOrigStart=" << sec.sOrig << " sectionEnd=" << sectionEnd << "\n"; - } -#endif - if (sec.rightLaneNumber > 0) { - findWidthSplit(tc, sec.lanesByDir[OPENDRIVE_TAG_RIGHT], section, sec.sOrig, sectionEnd, splitPositions); - } - if (sec.leftLaneNumber > 0) { - findWidthSplit(tc, sec.lanesByDir[OPENDRIVE_TAG_LEFT], section, sec.sOrig, sectionEnd, splitPositions); - } - newSections.push_back(sec); - std::sort(splitPositions.begin(), splitPositions.end()); - // filter out tiny splits - double prevSplit = sec.s; - for (std::vector::iterator it = splitPositions.begin(); it != splitPositions.end();) { - if ((*it) - prevSplit < minDist || sectionEnd - (*it) < minDist) { - // avoid tiny (or duplicate) splits -#ifdef DEBUG_VARIABLE_WIDTHS - if (DEBUG_COND(e)) { - std::cout << " skip close split=" << (*it) << " prevSplit=" << prevSplit << "\n"; - } -#endif - it = splitPositions.erase(it); - } else if ((*it) < sec.s) { - // avoid splits for another section -#ifdef DEBUG_VARIABLE_WIDTHS - if (DEBUG_COND(e)) { - std::cout << " skip early split=" << (*it) << " s=" << sec.s << "\n"; - } -#endif - it = splitPositions.erase(it); - } else { - prevSplit = *it; - it++; - } - } - - if (splitPositions.size() > 0) { -#ifdef DEBUG_VARIABLE_WIDTHS - if (DEBUG_COND(e)) { - std::cout << " road=" << e->id << " splitMinWidths section=" << section - << " start=" << sec.s - << " origStart=" << sec.sOrig - << " end=" << sectionEnd << " minDist=" << minDist - << " splitPositions=" << toString(splitPositions) << "\n"; - } -#endif -#ifdef DEBUG_VARIABLE_WIDTHS - if (DEBUG_COND(e)) { - std::cout << "first section...\n"; - } -#endif - recomputeWidths(newSections.back(), sec.sOrig, splitPositions.front(), sec.sOrig, sectionEnd); - for (std::vector::iterator it = splitPositions.begin(); it != splitPositions.end(); ++it) { - OpenDriveLaneSection secNew = sec; - secNew.s = *it; -#ifdef DEBUG_VARIABLE_WIDTHS - if (DEBUG_COND(e)) { - std::cout << "splitAt " << secNew.s << "\n"; - } -#endif - newSections.push_back(secNew); - if (secNew.rightLaneNumber > 0) { - setStraightConnections(newSections.back().lanesByDir[OPENDRIVE_TAG_RIGHT]); - } - if (secNew.leftLaneNumber > 0) { - setStraightConnections(newSections.back().lanesByDir[OPENDRIVE_TAG_LEFT]); - } - double end = (it + 1) == splitPositions.end() ? sectionEnd : *(it + 1); - recomputeWidths(newSections.back(), secNew.s, end, sec.sOrig, sectionEnd); - } - } - } - gDebugFlag1 = false; - e->laneSections = newSections; -} - - -void -NIImporter_OpenDrive::findWidthSplit(const NBTypeCont& tc, std::vector& lanes, - int section, double sectionStart, double sectionEnd, - std::vector& splitPositions) { - UNUSED_PARAMETER(section); - for (std::vector::iterator k = lanes.begin(); k != lanes.end(); ++k) { - OpenDriveLane& l = *k; - SVCPermissions permissions = tc.getPermissions(l.type) & ~(SVC_PEDESTRIAN | SVC_BICYCLE); - if (l.widthData.size() > 0 && tc.knows(l.type) && !tc.getShallBeDiscarded(l.type) && permissions != 0) { - double sPrev = l.widthData.front().s; - double wPrev = l.widthData.front().computeAt(sPrev); - if (gDebugFlag1) std::cout - << "findWidthSplit section=" << section - << " sectionStart=" << sectionStart - << " sectionEnd=" << sectionEnd - << " lane=" << l.id - << " type=" << l.type - << " widthEntries=" << l.widthData.size() << "\n" - << " s=" << sPrev - << " w=" << wPrev - << "\n"; - for (std::vector::iterator it_w = l.widthData.begin(); it_w != l.widthData.end(); ++it_w) { - double sEnd = (it_w + 1) != l.widthData.end() ? (*(it_w + 1)).s : sectionEnd - sectionStart; - double w = (*it_w).computeAt(sEnd); - if (gDebugFlag1) std::cout - << " sEnd=" << sEnd - << " s=" << (*it_w).s - << " a=" << (*it_w).a << " b=" << (*it_w).b << " c=" << (*it_w).c << " d=" << (*it_w).d - << " w=" << w - << "\n"; - const double changeDist = fabs(myMinWidth - wPrev); - if (((wPrev < myMinWidth) && (w > myMinWidth)) - || ((wPrev > myMinWidth) && (w < myMinWidth))) { - double splitPos = sPrev + (sEnd - sPrev) / fabs(w - wPrev) * changeDist; - double wSplit = (*it_w).computeAt(splitPos); - if (gDebugFlag1) { - std::cout << " candidate splitPos=" << splitPos << " w=" << wSplit << "\n"; - } - // ensure that the thin part is actually thin enough - while (wSplit > myMinWidth) { - if (wPrev < myMinWidth) { - // getting wider - splitPos -= POSITION_EPS; - if (splitPos < sPrev) { - if (gDebugFlag1) { - std::cout << " aborting search splitPos=" << splitPos << " wSplit=" << wSplit << " sPrev=" << sPrev << " wPrev=" << wPrev << "\n"; - } - splitPos = sPrev; - break; - } - } else { - // getting thinner - splitPos += POSITION_EPS; - if (splitPos > sEnd) { - if (gDebugFlag1) { - std::cout << " aborting search splitPos=" << splitPos << " wSplit=" << wSplit << " sEnd=" << sEnd << " w=" << w << "\n"; - } - splitPos = sEnd; - break; - } - } - wSplit = (*it_w).computeAt(splitPos); - if (gDebugFlag1) { - std::cout << " refined splitPos=" << splitPos << " w=" << wSplit << "\n"; - } - } - splitPositions.push_back(sectionStart + splitPos); - } - // //wPrev = wSplit; - //} else if ((fabs(wPrev) < NUMERICAL_EPS && w > POSITION_EPS) - // || (wPrev > POSITION_EPS && fabs(w) < NUMERICAL_EPS)) { - // splitPositions.push_back(sectionStart + sPrev); - // if (gDebugFlag1) std::cout << " laneDisappears candidate splitPos=" << sPrev << " wPrev=" << wPrev << " w=" << w<< "\n"; - //} - wPrev = w; - sPrev = sEnd; - } - } - } -} - - -void -NIImporter_OpenDrive::setStraightConnections(std::vector& lanes) { - for (std::vector::iterator k = lanes.begin(); k != lanes.end(); ++k) { - (*k).predecessor = (*k).id; - } -} - - -void -NIImporter_OpenDrive::recomputeWidths(OpenDriveLaneSection& sec, double start, double end, double sectionStart, double sectionEnd) { - if (sec.rightLaneNumber > 0) { - recomputeWidths(sec.lanesByDir[OPENDRIVE_TAG_RIGHT], start, end, sectionStart, sectionEnd); - } - if (sec.leftLaneNumber > 0) { - recomputeWidths(sec.lanesByDir[OPENDRIVE_TAG_LEFT], start, end, sectionStart, sectionEnd); - } -} - - -void -NIImporter_OpenDrive::recomputeWidths(std::vector& lanes, double start, double end, double sectionStart, double sectionEnd) { - for (std::vector::iterator k = lanes.begin(); k != lanes.end(); ++k) { - OpenDriveLane& l = *k; - if (l.widthData.size() > 0) { -#ifdef DEBUG_VARIABLE_WIDTHS - if (gDebugFlag1) std::cout - << "recomputeWidths lane=" << l.id - << " type=" << l.type - << " start=" << start - << " end=" << end - << " sectionStart=" << sectionStart - << " sectionEnd=" << sectionEnd - << " widthEntries=" << l.widthData.size() << "\n" - << "\n"; -#endif - l.width = 0; - double sPrev = l.widthData.front().s; - double sPrevAbs = sPrev + sectionStart; - for (std::vector::iterator it_w = l.widthData.begin(); it_w != l.widthData.end(); ++it_w) { - double sEnd = (it_w + 1) != l.widthData.end() ? (*(it_w + 1)).s : sectionEnd - sectionStart; - double sEndAbs = sEnd + sectionStart; -#ifdef DEBUG_VARIABLE_WIDTHS - if (gDebugFlag1) std::cout - << " sPrev=" << sPrev << " sPrevAbs=" << sPrevAbs - << " sEnd=" << sEnd << " sEndAbs=" << sEndAbs - << " widthData s=" << (*it_w).s - << " a=" << (*it_w).a - << " b=" << (*it_w).b - << " c=" << (*it_w).c - << " d=" << (*it_w).d - << "\n"; -#endif - if (sPrevAbs <= start && sEndAbs >= start) { -#ifdef DEBUG_VARIABLE_WIDTHS - if (gDebugFlag1) { - std::cout << " atStart=" << start << " pos=" << start - sectionStart << " w=" << (*it_w).computeAt(start - sectionStart) << "\n"; - } -#endif - l.width = MAX2(l.width, (*it_w).computeAt(start - sectionStart)); - } - if (sPrevAbs <= end && sEndAbs >= end) { -#ifdef DEBUG_VARIABLE_WIDTHS - if (gDebugFlag1) { - std::cout << " atEnd=" << end << " pos=" << end - sectionStart << " w=" << (*it_w).computeAt(end - sectionStart) << "\n"; - } -#endif - l.width = MAX2(l.width, (*it_w).computeAt(end - sectionStart)); - } - if (start <= sPrevAbs && end >= sPrevAbs) { -#ifdef DEBUG_VARIABLE_WIDTHS - if (gDebugFlag1) { - std::cout << " atSPrev=" << sPrev << " w=" << (*it_w).computeAt(sPrev) << "\n"; - } -#endif - l.width = MAX2(l.width, (*it_w).computeAt(sPrev)); - } - if (start <= sEndAbs && end >= sEndAbs) { -#ifdef DEBUG_VARIABLE_WIDTHS - if (gDebugFlag1) { - std::cout << " atSEnd=" << sEnd << " w=" << (*it_w).computeAt(sEnd) << "\n"; - } -#endif - l.width = MAX2(l.width, (*it_w).computeAt(sEnd)); - } -#ifdef DEBUG_VARIABLE_WIDTHS - if (gDebugFlag1) { - std::cout << " sPrev=" << sPrev << " sEnd=" << sEnd << " l.width=" << l.width << "\n"; - } -#endif - sPrev = sEnd; - sPrevAbs = sEndAbs; - } - } - } -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/NIImporter_OpenDrive.h b/Util/OSM2ODR/src/netimport/NIImporter_OpenDrive.h deleted file mode 100644 index 573546b08..000000000 --- a/Util/OSM2ODR/src/netimport/NIImporter_OpenDrive.h +++ /dev/null @@ -1,680 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIImporter_OpenDrive.h -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date Mon, 14.04.2008 -/// -// Importer for networks stored in openDrive format -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include -#include - - -// =========================================================================== -// class declarations -// =========================================================================== -class NBNetBuilder; -class NBEdge; -class OptionsCont; -class NBNode; -class NBNodeCont; - - -#define UNSET_CONNECTION 100000 - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NIImporter_OpenDrive - * @brief Importer for networks stored in openDrive format - * - */ -class NIImporter_OpenDrive : public GenericSAXHandler { -public: - /** @brief Loads content of the optionally given SUMO file - * - * If the option "opendrive-files" is set, the file stored therein is read and - * the network definition stored therein is stored within the given network - * builder. - * - * If the option "opendrive-files" is not set, this method simply returns. - * - * The loading is done by parsing the network definition as an XML file - * using the SAXinterface and handling the incoming data via this class' - * methods. - * - * @param[in] oc The options to use - * @param[in] nb The network builder to fill - */ - static void loadNetwork(const OptionsCont& oc, NBNetBuilder& nb); - - -protected: - - /** - * @enum OpenDriveXMLTag - * @brief Numbers representing openDrive-XML - element names - * @see GenericSAXHandler - */ - enum OpenDriveXMLTag { - OPENDRIVE_TAG_NOTHING, - OPENDRIVE_TAG_HEADER, - OPENDRIVE_TAG_ROAD, - OPENDRIVE_TAG_PREDECESSOR, - OPENDRIVE_TAG_SUCCESSOR, - /// @todo OPENDRIVE_TAG_NEIGHBOR, - /// @todo OPENDRIVE_TAG_TYPE, - OPENDRIVE_TAG_GEOMETRY, - OPENDRIVE_TAG_LINE, - OPENDRIVE_TAG_SPIRAL, - OPENDRIVE_TAG_ARC, - OPENDRIVE_TAG_POLY3, - OPENDRIVE_TAG_PARAMPOLY3, - OPENDRIVE_TAG_LANESECTION, - OPENDRIVE_TAG_LANEOFFSET, - OPENDRIVE_TAG_LEFT, - OPENDRIVE_TAG_CENTER, - OPENDRIVE_TAG_RIGHT, - OPENDRIVE_TAG_LANE, - OPENDRIVE_TAG_SIGNAL, - OPENDRIVE_TAG_SIGNALREFERENCE, - OPENDRIVE_TAG_VALIDITY, - OPENDRIVE_TAG_JUNCTION, - OPENDRIVE_TAG_CONNECTION, - OPENDRIVE_TAG_LANELINK, - OPENDRIVE_TAG_WIDTH, - OPENDRIVE_TAG_SPEED, - OPENDRIVE_TAG_ELEVATION, - OPENDRIVE_TAG_GEOREFERENCE, - OPENDRIVE_TAG_OBJECT, - OPENDRIVE_TAG_REPEAT - }; - - - /** - * @enum OpenDriveXMLAttr - * @brief Numbers representing openDrive-XML - attributes - * @see GenericSAXHandler - */ - enum OpenDriveXMLAttr { - OPENDRIVE_ATTR_NOTHING, - OPENDRIVE_ATTR_REVMAJOR, - OPENDRIVE_ATTR_REVMINOR, - OPENDRIVE_ATTR_ID, - OPENDRIVE_ATTR_LENGTH, - OPENDRIVE_ATTR_WIDTH, - OPENDRIVE_ATTR_RADIUS, - OPENDRIVE_ATTR_DISTANCE, - OPENDRIVE_ATTR_TSTART, - OPENDRIVE_ATTR_TEND, - OPENDRIVE_ATTR_WIDTHSTART, - OPENDRIVE_ATTR_WIDTHEND, - OPENDRIVE_ATTR_JUNCTION, - OPENDRIVE_ATTR_ELEMENTTYPE, - OPENDRIVE_ATTR_ELEMENTID, - OPENDRIVE_ATTR_CONTACTPOINT, - OPENDRIVE_ATTR_S, - OPENDRIVE_ATTR_T, - OPENDRIVE_ATTR_X, - OPENDRIVE_ATTR_Y, - OPENDRIVE_ATTR_HDG, - OPENDRIVE_ATTR_CURVSTART, - OPENDRIVE_ATTR_CURVEND, - OPENDRIVE_ATTR_CURVATURE, - OPENDRIVE_ATTR_A, - OPENDRIVE_ATTR_B, - OPENDRIVE_ATTR_C, - OPENDRIVE_ATTR_D, - OPENDRIVE_ATTR_AU, - OPENDRIVE_ATTR_BU, - OPENDRIVE_ATTR_CU, - OPENDRIVE_ATTR_DU, - OPENDRIVE_ATTR_AV, - OPENDRIVE_ATTR_BV, - OPENDRIVE_ATTR_CV, - OPENDRIVE_ATTR_DV, - OPENDRIVE_ATTR_PRANGE, - OPENDRIVE_ATTR_TYPE, - OPENDRIVE_ATTR_LEVEL, - OPENDRIVE_ATTR_ORIENTATION, - OPENDRIVE_ATTR_DYNAMIC, - OPENDRIVE_ATTR_INCOMINGROAD, - OPENDRIVE_ATTR_CONNECTINGROAD, - OPENDRIVE_ATTR_FROM, - OPENDRIVE_ATTR_TO, - OPENDRIVE_ATTR_FROMLANE, - OPENDRIVE_ATTR_TOLANE, - OPENDRIVE_ATTR_MAX, - OPENDRIVE_ATTR_SOFFSET, - OPENDRIVE_ATTR_NAME, - OPENDRIVE_ATTR_UNIT // xodr v1.4 - }; - - - /** @brief OpenDrive link type enumeration - */ - enum LinkType { - OPENDRIVE_LT_SUCCESSOR, - OPENDRIVE_LT_PREDECESSOR - }; - - - /** @brief OpenDrive element type enumeration - */ - enum ElementType { - OPENDRIVE_ET_UNKNOWN, - OPENDRIVE_ET_ROAD, - OPENDRIVE_ET_JUNCTION - }; - - - /** @brief OpenDrive contact type enumeration - */ - enum ContactPoint { - OPENDRIVE_CP_UNKNOWN, - OPENDRIVE_CP_START, - OPENDRIVE_CP_END - }; - - /** @brief OpenDrive geometry type enumeration - */ - enum GeometryType { - OPENDRIVE_GT_UNKNOWN, - OPENDRIVE_GT_LINE, - OPENDRIVE_GT_SPIRAL, - OPENDRIVE_GT_ARC, - OPENDRIVE_GT_POLY3, - OPENDRIVE_GT_PARAMPOLY3 // rev 1.4 - }; - - - - /** - * @struct OpenDriveLink - * @brief Representation of an OpenDrive link - */ - struct OpenDriveLink { - /** @brief Constructor - * @param[in] linkTypeArg The link type - * @param[in] elementIDArg The element id - */ - OpenDriveLink(LinkType linkTypeArg, const std::string& elementIDArg) - : linkType(linkTypeArg), elementID(elementIDArg), - elementType(OPENDRIVE_ET_UNKNOWN), contactPoint(OPENDRIVE_CP_UNKNOWN) { } - - LinkType linkType; - std::string elementID; - ElementType elementType; - ContactPoint contactPoint; - }; - - - /** - * @struct OpenDriveGeometry - * @brief Representation of an OpenDrive geometry part - */ - struct OpenDriveGeometry { - /** @brief Constructor - * @param[in] lengthArg The length of this geometry part - * @param[in] sArg The offset from the start, counted from the begin - * @param[in] xArg x-position at this part's begin - * @param[in] yArg y-position at this part's begin - * @param[in] hdgArg heading at this part's begin - */ - OpenDriveGeometry(double lengthArg, double sArg, double xArg, double yArg, double hdgArg) - : length(lengthArg), s(sArg), x(xArg), y(yArg), hdg(hdgArg), - type(OPENDRIVE_GT_UNKNOWN) { } - - double length; - double s; - double x; - double y; - double hdg; - GeometryType type; - std::vector params; - }; - - /** - * @struct OpenDriveElevation - * @brief Coefficients of an elevation profile (3rd degree polynomial) - */ - struct Poly3 { - /** @brief Constructor - * @param[in] s The start offset - * @param[in] a constant - * @param[in] b first order - * @param[in] c second order - * @param[in] d third order - */ - Poly3(double _s, double _a, double _b, double _c, double _d) : - s(_s), a(_a), b(_b), c(_c), d(_d) {} - - double computeAt(double pos) const { - const double ds = pos - s; - return a + b * ds + c * ds * ds + d * ds * ds * ds; - } - - double s; - double a; - double b; - double c; - double d; - }; - - /// LaneOffset has the same fields as Elevation - typedef Poly3 OpenDriveElevation; - typedef Poly3 OpenDriveLaneOffset; - typedef Poly3 OpenDriveWidth; - - - /** - * @struct OpenDriveLane - * @brief Representation of a lane - */ - struct OpenDriveLane { - /** @brief Constructor - * @param[in] idArg The OpenDrive id of the lane - * @param[in] levelArg The level - * @param[in] typeArg type of the lane - */ - OpenDriveLane(int idArg, const std::string& levelArg, const std::string& typeArg) : - id(idArg), level(levelArg), type(typeArg), successor(UNSET_CONNECTION), predecessor(UNSET_CONNECTION), - speed(0), width(NBEdge::UNSPECIFIED_WIDTH) { } - - int id; //!< The lane's id - std::string level; //!< The lane's level (not used) - std::string type; //!< The lane's type - int successor; //!< The lane's successor lane - int predecessor; //!< The lane's predecessor lane - std::vector > speeds; //!< List of positions/speeds of speed changes - double speed; //!< The lane's speed (set in post-processing) - double width; //The lane's maximum width - std::vector widthData; - }; - - - /** - * @struct OpenDriveLaneSection - * @brief Representation of a lane section - */ - struct OpenDriveLaneSection { - /** @brief Constructor - * @param[in] sArg The offset from the start, counted from the begin - */ - OpenDriveLaneSection(double sArg); - - - /** @brief Build the mapping from OpenDrive to SUMO lanes - * - * Not all lanes are converted to SUMO-lanes; the mapping includes only those - * which are included in the SUMO network. - * @param[in] tc The type container needed to determine whether a lane shall be imported by using the lane's type - */ - void buildLaneMapping(const NBTypeCont& tc); - - - /** @brief Returns the links from the previous to this lane section - * @param[in] dir The OpenDrive-direction of drive - * @param[in] pre The previous lane section - * @return which lane is approached from which lane of the given previous lane section - */ - std::map getInnerConnections(OpenDriveXMLTag dir, const OpenDriveLaneSection& prev); - - - bool buildSpeedChanges(const NBTypeCont& tc, std::vector& newSections); - OpenDriveLaneSection buildLaneSection(double startPos); - - /// @brief The starting offset of this lane section - double s; - /// @brief The original starting offset of this lane section (differs from s if the section had to be split) - double sOrig; - /// @brief The length of this lane section - double length; - /// @brief A mapping from OpenDrive to SUMO-index (the first is signed, the second unsigned) - std::map laneMap; - /// @brief The lanes, sorted by their direction - std::map > lanesByDir; - /// @brief The id (generic, without the optionally leading '-') of the edge generated for this section - std::string sumoID; - /// @brief The number of lanes on the right and on the left side, respectively - int rightLaneNumber, leftLaneNumber; - /// @brief the composite type built from all used lane types - std::string rightType; - std::string leftType; - }; - - - - /** - * @struct OpenDriveSignal - * @brief Representation of a signal - */ - struct OpenDriveSignal { - /** @brief Constructor - * @param[in] idArg The OpenDrive id of the signal - * @param[in] typeArg The type of the signal - * @param[in] nameArg The type of the signal - * @param[in] orientationArg The direction the signal belongs to - * @param[in] dynamicArg Whether the signal is dynamic - * @param[in] sArg The offset from the start, counted from the begin - */ - OpenDriveSignal(const std::string& idArg, const std::string typeArg, const std::string nameArg, - int orientationArg, bool dynamicArg, double sArg) : - id(idArg), type(typeArg), name(nameArg), - orientation(orientationArg), dynamic(dynamicArg), s(sArg), - minLane(0), maxLane(0) - { } - - /// dummy constructor for use in maps - OpenDriveSignal() {} - - std::string id; - std::string type; - std::string name; - int orientation; - bool dynamic; - double s; - /// @brief signal validity range - int minLane; - int maxLane; - }; - - - /** - * @struct Connection - * @brief A connection between two roads - */ - struct Connection { - std::string fromEdge; - std::string toEdge; - int fromLane; - int toLane; - ContactPoint fromCP; - ContactPoint toCP; - bool all; - std::string origID; - int origLane; - PositionVector shape; - - std::string getDescription() const { - return "Connection from=" + fromEdge + "_" + toString(fromLane) - + " to=" + toEdge + "_" + toString(toLane) - + " fromCP=" + (fromCP == OPENDRIVE_CP_START ? "start" : fromCP == OPENDRIVE_CP_END ? "end" : "unknown") - + " toCP=" + (toCP == OPENDRIVE_CP_START ? "start" : toCP == OPENDRIVE_CP_END ? "end" : "unknown") - + " all=" + toString(all); - //+ " origID=" + origID + " origLane=" + toString(origLane); - } - }; - - /** - * @struct Object - * @brief A road object (e.g. parkingSpace) - */ - struct OpenDriveObject { - std::string type; - std::string name; - std::string id; - double s; - double t; - double zOffset; - double length; - double width; - double height; - double radius; - double hdg; - double pitch; - double roll; - }; - - /** - * @struct OpenDriveEdge - * @brief Representation of an openDrive "link" - */ - struct OpenDriveEdge { - OpenDriveEdge(const std::string& idArg, const std::string& streetNameArg, const std::string& junctionArg, double lengthArg) : - id(idArg), - streetName(streetNameArg), - junction(junctionArg), - length(lengthArg), - from(0), - to(0) { - isInner = junction != "" && junction != "-1"; - } - - - /** @brief Returns the edge's priority, regarding the direction - * - * The priority is determined by evaluating the signs located at the road - * @param[in] dir The direction which priority shall be returned - * @return The priority of the given direction - */ - int getPriority(OpenDriveXMLTag dir) const; - - - /// @brief The id of the edge - std::string id; - /// @brief The road name of the edge - std::string streetName; - /// @brief The id of the junction the edge belongs to - std::string junction; - /// @brief The length of the edge - double length; - std::vector links; - std::vector geometries; - std::vector elevations; - std::vector offsets; - NBNode* from; - NBNode* to; - PositionVector geom; - std::vector laneOffsets; - std::vector laneSections; - std::vector signals; - std::set connections; - std::vector objects; - bool isInner; - }; - - - /** @brief A class for sorting lane sections by their s-value */ - class sections_by_s_sorter { - public: - /// @brief Constructor - explicit sections_by_s_sorter() { } - - /// @brief Sorting function; compares OpenDriveLaneSection::s - int operator()(const OpenDriveLaneSection& ls1, const OpenDriveLaneSection& ls2) { - return ls1.s < ls2.s; - } - }; - - /* @brief A class for search in position/speed tuple vectors for the given position */ - class same_position_finder { - public: - /** @brief constructor */ - explicit same_position_finder(double pos) : myPosition(pos) { } - - /** @brief the comparing function */ - bool operator()(const std::pair& ps) { - return ps.first == myPosition; - } - - private: - same_position_finder& operator=(const same_position_finder&); // just to avoid a compiler warning - private: - /// @brief The position to search for - double myPosition; - - }; - -protected: - /** @brief Constructor - * @param[in] tc The type container used to determine whether a lane shall kept - * @param[in] nc The edge map to fill - */ - NIImporter_OpenDrive(const NBTypeCont& tc, std::map& edges); - - - /// @brief Destructor - ~NIImporter_OpenDrive(); - - - - /// @name inherited from GenericSAXHandler - //@{ - - /** @brief Called on the opening of a tag; - * - * In dependence to the obtained type, an appropriate parsing - * method is called ("addEdge" if an edge encounters, f.e.). - * - * @param[in] element ID of the currently opened element - * @param[in] attrs Attributes within the currently opened element - * @exception ProcessError If something fails - * @see GenericSAXHandler::myStartElement - */ - void myStartElement(int element, const SUMOSAXAttributes& attrs); - - /** - * @brief Callback method for characters to implement by derived classes - * - * Called by "endElement" (see there). - * @param[in] element The opened element, given as a int - * @param[in] chars The complete embedded character string - * @exceptions ProcessError These method may throw a ProcessError if something fails - */ - void myCharacters(int element, const std::string& chars); - - - /** @brief Called when a closing tag occurs - * - * @param[in] element ID of the currently opened element - * @exception ProcessError If something fails - * @see GenericSAXHandler::myEndElement - */ - void myEndElement(int element); - //@} - - std::map& getSignals() { - return mySignals; - } - -private: - void addLink(LinkType lt, const std::string& elementType, const std::string& elementID, - const std::string& contactPoint); - void addGeometryShape(GeometryType type, const std::vector& vals); - static void setEdgeLinks2(OpenDriveEdge& e, const std::map& edges); - static void buildConnectionsToOuter(const Connection& c, const std::map& innerEdges, std::vector& into, std::set& seen); - static bool laneSectionsConnected(OpenDriveEdge* edge, int in, int out); - friend bool operator<(const Connection& c1, const Connection& c2); - static std::string revertID(const std::string& id); - const NBTypeCont& myTypeContainer; - OpenDriveEdge myCurrentEdge; - - std::map& myEdges; - std::vector myElementStack; - OpenDriveXMLTag myCurrentLaneDirection; - std::string myCurrentJunctionID; - std::string myCurrentIncomingRoad; - std::string myCurrentConnectingRoad; - ContactPoint myCurrentContactPoint; - bool myConnectionWasEmpty; - std::map mySignals; - - static bool myImportAllTypes; - static bool myImportWidths; - static double myMinWidth; - static bool myImportInternalShapes; - - -protected: - /** @brief Builds a node or returns the already built - * - * If the node is already known, it is returned. Otherwise, the - * node is built. If the newly built node can not be added to - * the container, a ProcessError is thrown. - * Otherwise this node is returned. - * - * @param[in] id The id of the node to build/get - * @param[in, changed] pos The position of the node to build/get - * @param[filled] nc The node container to retrieve/add the node to - * @return The retrieved/built node - * @exception ProcessError If the node could not be built/retrieved - */ - static NBNode* getOrBuildNode(const std::string& id, const Position& pos, NBNodeCont& nc); - - - static PositionVector geomFromLine(const OpenDriveEdge& e, const OpenDriveGeometry& g, double resolution); - static PositionVector geomFromSpiral(const OpenDriveEdge& e, const OpenDriveGeometry& g, double resolution); - static PositionVector geomFromArc(const OpenDriveEdge& e, const OpenDriveGeometry& g, double resolution); - static PositionVector geomFromPoly(const OpenDriveEdge& e, const OpenDriveGeometry& g, double resolution); - static PositionVector geomFromParamPoly(const OpenDriveEdge& e, const OpenDriveGeometry& g, double resolution); - static Position calculateStraightEndPoint(double hdg, double length, const Position& start); - static void calculateCurveCenter(double* ad_x, double* ad_y, double ad_radius, double ad_hdg); - static void calcPointOnCurve(double* ad_x, double* ad_y, double ad_centerX, double ad_centerY, - double ad_r, double ad_length); - - - /** @brief Computes a polygon representation of each edge's geometry - * @param[in] edges The edges which geometries shall be converted - */ - static void computeShapes(std::map& edges); - - static bool hasNonLinearElevation(OpenDriveEdge& e); - - /** @brief Rechecks lane sections of the given edges - * - * - * @param[in] edges The edges which lane sections shall be reviewed - */ - static void revisitLaneSections(const NBTypeCont& tc, std::map& edges); - - static void setNodeSecure(NBNodeCont& nc, OpenDriveEdge& e, - const std::string& nodeID, NIImporter_OpenDrive::LinkType lt, std::vector& joinedNodeIDs); - - static NBTrafficLightDefinition* getTLSSecure(NBEdge* inEdge, NBNetBuilder& nb); - - - static std::pair retrieveSignalEdges(NBNetBuilder& nb, const std::string& fromID, const std::string& toID, const std::string& junction); - - static void splitMinWidths(OpenDriveEdge* e, const NBTypeCont& tc, double minDist); - - static void findWidthSplit(const NBTypeCont& tc, std::vector& lanes, - int section, double sectionStart, double sectionEnd, - std::vector& splitPositions); - - static void sanitizeWidths(OpenDriveEdge* e); - static void sanitizeWidths(std::vector& lanes, double length); - - static void setStraightConnections(std::vector& lanes); - static void recomputeWidths(OpenDriveLaneSection& sec, double start, double end, double sectionStart, double sectionEnd); - static void recomputeWidths(std::vector& lanes, double start, double end, double sectionStart, double sectionEnd); - static void setLaneAttributes(const OpenDriveEdge* e, NBEdge::Lane& sumoLane, const OpenDriveLane& odLane, bool saveOrigIDs, const NBTypeCont& tc); - - /// The names of openDrive-XML elements (for passing to GenericSAXHandler) - static StringBijection::Entry openDriveTags[]; - - /// The names of openDrive-XML attributes (for passing to GenericSAXHandler) - static StringBijection::Entry openDriveAttrs[]; - - - -}; diff --git a/Util/OSM2ODR/src/netimport/NIImporter_OpenStreetMap.cpp b/Util/OSM2ODR/src/netimport/NIImporter_OpenStreetMap.cpp deleted file mode 100644 index 1c2f07f55..000000000 --- a/Util/OSM2ODR/src/netimport/NIImporter_OpenStreetMap.cpp +++ /dev/null @@ -1,1988 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIImporter_OpenStreetMap.cpp -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @author Walter Bamberger -/// @author Gregor Laemmel -/// @date Mon, 14.04.2008 -/// -// Importer for networks stored in OpenStreetMap format -/****************************************************************************/ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "NILoader.h" -#include "NIImporter_OpenStreetMap.h" - -#define KM_PER_MILE 1.609344 - -//#define DEBUG_LAYER_ELEVATION - -// --------------------------------------------------------------------------- -// static members -// --------------------------------------------------------------------------- -const double NIImporter_OpenStreetMap::MAXSPEED_UNGIVEN = -1; - -const long long int NIImporter_OpenStreetMap::INVALID_ID = std::numeric_limits::max(); - -// =========================================================================== -// Private classes -// =========================================================================== - -/** @brief Functor which compares two Edges - */ -class NIImporter_OpenStreetMap::CompareEdges { -public: - bool operator()(const Edge* e1, const Edge* e2) const { - if (e1->myHighWayType != e2->myHighWayType) { - return e1->myHighWayType > e2->myHighWayType; - } - if (e1->myNoLanes != e2->myNoLanes) { - return e1->myNoLanes > e2->myNoLanes; - } - if (e1->myNoLanesForward != e2->myNoLanesForward) { - return e1->myNoLanesForward > e2->myNoLanesForward; - } - if (e1->myMaxSpeed != e2->myMaxSpeed) { - return e1->myMaxSpeed > e2->myMaxSpeed; - } - if (e1->myIsOneWay != e2->myIsOneWay) { - return e1->myIsOneWay > e2->myIsOneWay; - } - return e1->myCurrentNodes > e2->myCurrentNodes; - } -}; - -// =========================================================================== -// method definitions -// =========================================================================== -// --------------------------------------------------------------------------- -// static methods -// --------------------------------------------------------------------------- -const std::string NIImporter_OpenStreetMap::compoundTypeSeparator("|"); //clang-tidy says: "compundTypeSeparator with -// static storage duration my throw an exception that cannot be caught - -void -NIImporter_OpenStreetMap::loadNetwork(const OptionsCont& oc, NBNetBuilder& nb) { - NIImporter_OpenStreetMap importer; - importer.load(oc, nb); -} - -NIImporter_OpenStreetMap::NIImporter_OpenStreetMap() = default; - -NIImporter_OpenStreetMap::~NIImporter_OpenStreetMap() { - // delete nodes - for (auto myUniqueNode : myUniqueNodes) { - delete myUniqueNode; - } - // delete edges - for (auto& myEdge : myEdges) { - delete myEdge.second; - } - // delete platform shapes - for (auto& myPlatformShape : myPlatformShapes) { - delete myPlatformShape.second; - } -} - -void -NIImporter_OpenStreetMap::load(const OptionsCont& oc, NBNetBuilder& nb) { - // check whether the option is set (properly) - if (!oc.isSet("osm-files")) { - return; - } - /* Parse file(s) - * Each file is parsed twice: first for nodes, second for edges. */ - std::vector files = oc.getStringVector("osm-files"); - // load nodes, first - NodesHandler nodesHandler(myOSMNodes, myUniqueNodes, oc); - // for (std::vector::const_iterator file = files.begin(); file != files.end(); ++file) { - // // nodes - // if (!FileHelpers::isReadable(*file)) { - // WRITE_ERROR("Could not open osm-file '" + *file + "'."); - // return; - // } - // nodesHandler.setFileName(*file); - // PROGRESS_BEGIN_MESSAGE("Parsing nodes from osm-file '" + *file + "'"); - // if (!XMLSubSys::runParser(nodesHandler, *file)) { - // return; - // } - // if (nodesHandler.getDuplicateNodes() > 0) { - // WRITE_MESSAGE("Found and substituted " + toString(nodesHandler.getDuplicateNodes()) + " osm nodes."); - // } - // PROGRESS_DONE_MESSAGE(); - // } - nodesHandler.setFileName("osm_file"); - PROGRESS_BEGIN_MESSAGE("Parsing nodes from osm string"); - if (!XMLSubSys::runParserFromString(nodesHandler, oc.input_osm_file)) { - return; - } - if (nodesHandler.getDuplicateNodes() > 0) { - WRITE_MESSAGE("Found and substituted " + toString(nodesHandler.getDuplicateNodes()) + " osm nodes."); - } - PROGRESS_DONE_MESSAGE(); - - // load edges, then - EdgesHandler edgesHandler(myOSMNodes, myEdges, myPlatformShapes); - // for (std::vector::const_iterator file = files.begin(); file != files.end(); ++file) { - // // edges - // edgesHandler.setFileName(*file); - // PROGRESS_BEGIN_MESSAGE("Parsing edges from osm-file '" + *file + "'"); - // XMLSubSys::runParser(edgesHandler, *file); - // PROGRESS_DONE_MESSAGE(); - // } - // edges - edgesHandler.setFileName("osm_file"); - PROGRESS_BEGIN_MESSAGE("Parsing nodes from osm string"); - XMLSubSys::runParserFromString(edgesHandler, oc.input_osm_file); - PROGRESS_DONE_MESSAGE(); - - - /* Remove duplicate edges with the same shape and attributes */ - if (!oc.getBool("osm.skip-duplicates-check")) { - int numRemoved = 0; - PROGRESS_BEGIN_MESSAGE("Removing duplicate edges"); - if (myEdges.size() > 1) { - std::set dupsFinder; - for (auto it = myEdges.begin(); it != myEdges.end();) { - if (dupsFinder.count(it->second) > 0) { - numRemoved++; - delete it->second; - myEdges.erase(it++); - } else { - dupsFinder.insert(it->second); - it++; - } - } - } - if (numRemoved > 0) { - WRITE_MESSAGE("Removed " + toString(numRemoved) + " duplicate osm edges."); - } - PROGRESS_DONE_MESSAGE(); - } - - /* Mark which nodes are used (by edges or traffic lights). - * This is necessary to detect which OpenStreetMap nodes are for - * geometry only */ - std::map nodeUsage; - // Mark which nodes are used by edges (begin and end) - for (std::map::const_iterator i = myEdges.begin(); i != myEdges.end(); ++i) { - Edge* e = (*i).second; - assert(e->myCurrentIsRoad); - for (std::vector::const_iterator j = e->myCurrentNodes.begin(); - j != e->myCurrentNodes.end(); - ++j) { - if (nodeUsage.find(*j) == nodeUsage.end()) { - nodeUsage[*j] = 0; - } - nodeUsage[*j] = nodeUsage[*j] + 1; - } - } - // Mark which nodes are used by traffic lights - for (std::map::const_iterator nodesIt = myOSMNodes.begin(); - nodesIt != myOSMNodes.end(); - ++nodesIt) { - if (nodesIt->second->tlsControlled || nodesIt->second->railwaySignal /* || nodesIt->second->railwayCrossing*/) { - // If the key is not found in the map, the value is automatically - // initialized with 0. - nodeUsage[nodesIt->first] += 1; - } - } - - /* Instantiate edges - * Only those nodes in the middle of an edge which are used by more than - * one edge are instantiated. Other nodes are considered as geometry nodes. */ - NBNodeCont& nc = nb.getNodeCont(); - NBTrafficLightLogicCont& tlsc = nb.getTLLogicCont(); - for (auto& myEdge : myEdges) { - Edge* e = myEdge.second; - assert(e->myCurrentIsRoad); - if (e->myCurrentNodes.size() < 2) { - WRITE_WARNINGF("Discarding way '%' because it has only % node(s)", e->id, e->myCurrentNodes.size()); - continue; - } - extendRailwayDistances(e, nb.getTypeCont()); - // build nodes; - // - the from- and to-nodes must be built in any case - // - the in-between nodes are only built if more than one edge references them - NBNode* currentFrom = insertNodeChecking(*e->myCurrentNodes.begin(), nc, tlsc); - NBNode* last = insertNodeChecking(*(e->myCurrentNodes.end() - 1), nc, tlsc); - int running = 0; - std::vector passed; - for (auto j = e->myCurrentNodes.begin(); j != e->myCurrentNodes.end(); ++j) { - passed.push_back(*j); - if (nodeUsage[*j] > 1 && j != e->myCurrentNodes.end() - 1 && j != e->myCurrentNodes.begin()) { - NBNode* currentTo = insertNodeChecking(*j, nc, tlsc); - running = insertEdge(e, running, currentFrom, currentTo, passed, nb); - currentFrom = currentTo; - passed.clear(); - passed.push_back(*j); - } - } - if (running == 0) { - running = -1; - } - insertEdge(e, running, currentFrom, last, passed, nb); - } - - const double layerElevation = oc.getFloat("osm.layer-elevation"); - if (layerElevation > 0) { - reconstructLayerElevation(layerElevation, nb); - } - - //revise pt stops; remove stops on deleted edges - if (OptionsCont::getOptions().isSet("ptstop-output")) { - nb.getPTStopCont().cleanupDeleted(nb.getEdgeCont()); - } - - // load relations (after edges are built since we want to apply - // turn-restrictions directly to NBEdges) - RelationHandler relationHandler(myOSMNodes, myEdges, &(nb.getPTStopCont()), myPlatformShapes, - &nb.getPTLineCont(), oc); - // for (std::vector::const_iterator file = files.begin(); file != files.end(); ++file) { - // // relations - // relationHandler.setFileName(*file); - // PROGRESS_BEGIN_MESSAGE("Parsing relations from osm-file '" + *file + "'"); - // XMLSubSys::runParser(relationHandler, *file); - // PROGRESS_DONE_MESSAGE(); - // } - // relations - relationHandler.setFileName("osm-file"); - PROGRESS_BEGIN_MESSAGE("Parsing nodes from osm string"); - XMLSubSys::runParserFromString(edgesHandler, oc.input_osm_file); - PROGRESS_DONE_MESSAGE(); - -} - -NBNode* -NIImporter_OpenStreetMap::insertNodeChecking(long long int id, NBNodeCont& nc, NBTrafficLightLogicCont& tlsc) { - NBNode* node = nc.retrieve(toString(id)); - if (node == nullptr) { - NIOSMNode* n = myOSMNodes.find(id)->second; - Position pos(n->lon, n->lat, n->ele); - if (!NBNetBuilder::transformCoordinate(pos, true)) { - WRITE_ERROR("Unable to project coordinates for junction '" + toString(id) + "'."); - return nullptr; - } - node = new NBNode(toString(id), pos); - if (!nc.insert(node)) { - WRITE_ERROR("Could not insert junction '" + toString(id) + "'."); - delete node; - return nullptr; - } - n->node = node; - if (n->railwayCrossing) { - node->reinit(pos, SumoXMLNodeType::RAIL_CROSSING); - } else if (n->railwaySignal) { - node->reinit(pos, SumoXMLNodeType::RAIL_SIGNAL); - } else if (n->tlsControlled) { - // ok, this node is a traffic light node where no other nodes - // participate - // @note: The OSM-community has not settled on a schema for differentiating between fixed and actuated lights - TrafficLightType type = SUMOXMLDefinitions::TrafficLightTypes.get( - OptionsCont::getOptions().getString("tls.default-type")); - NBOwnTLDef* tlDef = new NBOwnTLDef(toString(id), node, 0, type); - if (!tlsc.insert(tlDef)) { - // actually, nothing should fail here - delete tlDef; - throw ProcessError("Could not allocate tls '" + toString(id) + "'."); - } - } - if (n->railwayBufferStop) { - node->setParameter("buffer_stop", "true"); - } - } - return node; -} - -int -NIImporter_OpenStreetMap::insertEdge(Edge* e, int index, NBNode* from, NBNode* to, - const std::vector& passed, NBNetBuilder& nb) { - NBNodeCont& nc = nb.getNodeCont(); - NBEdgeCont& ec = nb.getEdgeCont(); - NBTypeCont& tc = nb.getTypeCont(); - NBPTStopCont& sc = nb.getPTStopCont(); - - NBTrafficLightLogicCont& tlsc = nb.getTLLogicCont(); - // patch the id - std::string id = toString(e->id); - if (from == nullptr || to == nullptr) { - WRITE_ERROR("Discarding edge '" + id + "' because the nodes could not be built."); - return index; - } - if (index >= 0) { - id = id + "#" + toString(index); - } else { - index = 0; - } - if (from == to) { - assert(passed.size() >= 2); - if (passed.size() == 2) { - WRITE_WARNINGF("Discarding edge '%' which connects two identical nodes without geometry.", id); - return index; - } - // in the special case of a looped way split again using passed - int intermediateIndex = (int) passed.size() / 2; - NBNode* intermediate = insertNodeChecking(passed[intermediateIndex], nc, tlsc); - std::vector part1(passed.begin(), passed.begin() + intermediateIndex + 1); - std::vector part2(passed.begin() + intermediateIndex, passed.end()); - index = insertEdge(e, index, from, intermediate, part1, nb); - return insertEdge(e, index, intermediate, to, part2, nb); - } - const int newIndex = index + 1; - - // convert the shape - PositionVector shape; - double distanceStart = myOSMNodes[passed.front()]->positionMeters; - double distanceEnd = myOSMNodes[passed.back()]->positionMeters; - const bool useDistance = distanceStart != std::numeric_limits::max() && distanceEnd != std::numeric_limits::max(); - if (useDistance) { - // negative sign denotes counting in the other direction - if (distanceStart < distanceEnd) { - distanceStart *= -1; - } else { - distanceEnd *= -1; - } - } else { - distanceStart = 0; - distanceEnd = 0; - } - for (long long i : passed) { - NIOSMNode* n = myOSMNodes.find(i)->second; - if (n->ptStopPosition) { - NBPTStop* existingPtStop = sc.get(toString(n->id)); - if (existingPtStop != nullptr) { - existingPtStop->registerAdditionalEdge(toString(e->id), id); - } else { - Position ptPos(n->lon, n->lat, n->ele); - if (!NBNetBuilder::transformCoordinate(ptPos)) { - WRITE_ERROR("Unable to project coordinates for node '" + toString(n->id) + "'."); - } - NBPTStop* ptStop = new NBPTStop(toString(n->id), ptPos, id, toString(e->id), n->ptStopLength, n->name, - n->permissions); - - sc.insert(ptStop); - } - } - Position pos(n->lon, n->lat, n->ele); - shape.push_back(pos); - } - if (!NBNetBuilder::transformCoordinates(shape)) { - WRITE_ERROR("Unable to project coordinates for edge '" + id + "'."); - } - std::string type = usableType(e->myHighWayType, id, tc); - if (type == "") { - return newIndex; - } - - // otherwise it is not an edge and will be ignored - bool ok = true; - int numLanesForward = tc.getNumLanes(type); - int numLanesBackward = tc.getNumLanes(type); - double speed = tc.getSpeed(type); - bool defaultsToOneWay = tc.getIsOneWay(type); - SVCPermissions permissions = tc.getPermissions(type); - if (e->myCurrentIsElectrified && (permissions & SVC_RAIL) != 0) { - permissions |= (SVC_RAIL_ELECTRIC | SVC_RAIL_FAST); - } - SVCPermissions forwardPermissions = permissions; - SVCPermissions backwardPermissions = permissions; - const std::string streetName = isRailway(forwardPermissions) && e->ref != "" ? e->ref : e->streetName; - if (streetName == e->ref) { - e->unsetParameter("ref"); // avoid superfluous param for railways - } - double forwardWidth = tc.getWidth(type); - double backwardWidth = tc.getWidth(type); - const bool addSidewalk = (tc.getSidewalkWidth(type) != NBEdge::UNSPECIFIED_WIDTH); - const bool addBikeLane = (tc.getBikeLaneWidth(type) != NBEdge::UNSPECIFIED_WIDTH); - // check directions - bool addForward = true; - bool addBackward = true; - if ((e->myIsOneWay == "true" || e->myIsOneWay == "yes" || e->myIsOneWay == "1" - || (defaultsToOneWay && e->myIsOneWay != "no" && e->myIsOneWay != "false" && e->myIsOneWay != "0")) - && e->myRailDirection != WAY_BOTH) { - addBackward = false; - } - if (e->myIsOneWay == "-1" || e->myIsOneWay == "reverse" || e->myRailDirection == WAY_BACKWARD) { - // one-way in reversed direction of way - addForward = false; - addBackward = true; - } - if (!e->myIsOneWay.empty() && e->myIsOneWay != "false" && e->myIsOneWay != "no" && e->myIsOneWay != "true" - && e->myIsOneWay != "yes" && e->myIsOneWay != "-1" && e->myIsOneWay != "1" && e->myIsOneWay != "reverse") { - WRITE_WARNINGF("New value for oneway found: %", e->myIsOneWay); - } - // if we had been able to extract the number of lanes, override the highway type default - if (e->myNoLanes > 0) { - if (addForward && !addBackward) { - numLanesForward = e->myNoLanes; - } else if (!addForward && addBackward) { - numLanesBackward = e->myNoLanes; - } else { - if (e->myNoLanesForward > 0) { - numLanesForward = e->myNoLanesForward; - } else if (e->myNoLanesForward < 0) { - numLanesForward = e->myNoLanes + e->myNoLanesForward; - } else { - numLanesForward = (int) std::ceil(e->myNoLanes / 2.0); - } - numLanesBackward = e->myNoLanes - numLanesForward; - // sometimes ways are tagged according to their physical width of a single - // lane but they are intended for traffic in both directions - numLanesForward = MAX2(1, numLanesForward); - numLanesBackward = MAX2(1, numLanesBackward); - } - } else if (e->myNoLanes == 0) { - WRITE_WARNINGF("Skipping edge '%' because it has zero lanes.", id); - ok = false; - } - // if we had been able to extract the maximum speed, override the type's default - if (e->myMaxSpeed != MAXSPEED_UNGIVEN) { - speed = e->myMaxSpeed / 3.6; - } - double speedBackward = speed; - if (e->myMaxSpeedBackward != MAXSPEED_UNGIVEN) { - speedBackward = e->myMaxSpeedBackward / 3.6; - } - if (speed <= 0 || speedBackward <= 0) { - WRITE_WARNINGF("Skipping edge '%' because it has speed %.", id, speed); - ok = false; - } - // deal with cycleways that run in the opposite direction of a one-way street - WayType cyclewayType = e->myCyclewayType; // make a copy because we do some temporary modifications - if (addBikeLane) { - if (!addForward && (cyclewayType & WAY_FORWARD) != 0) { - addForward = true; - forwardPermissions = SVC_BICYCLE; - forwardWidth = tc.getBikeLaneWidth(type); - numLanesForward = 1; - // do not add an additional cycle lane - cyclewayType = (WayType)(cyclewayType & ~WAY_FORWARD); //clang tidy thinks "!WAY_FORWARD" is always false - } - if (!addBackward && (cyclewayType & WAY_BACKWARD) != 0) { - addBackward = true; - backwardPermissions = SVC_BICYCLE; - backwardWidth = tc.getBikeLaneWidth(type); - numLanesBackward = 1; - // do not add an additional cycle lane - cyclewayType = (WayType)(cyclewayType & ~WAY_BACKWARD); //clang tidy thinks "!WAY_BACKWARD" is always false - } - } - // deal with sidewalks that run in the opposite direction of a one-way street - WayType sidewalkType = e->mySidewalkType; // make a copy because we do some temporary modifications - if (addSidewalk) { - if (!addForward && (sidewalkType & WAY_FORWARD) != 0) { - addForward = true; - forwardPermissions = SVC_PEDESTRIAN; - forwardWidth = tc.getSidewalkWidth(type); - numLanesForward = 1; - // do not add an additional sidewalk - sidewalkType = (WayType)(sidewalkType & ~WAY_FORWARD); //clang tidy thinks "!WAY_FORWARD" is always false - } - if (!addBackward && (sidewalkType & WAY_BACKWARD) != 0) { - addBackward = true; - backwardPermissions = SVC_PEDESTRIAN; - backwardWidth = tc.getSidewalkWidth(type); - numLanesBackward = 1; - // do not add an additional cycle lane - sidewalkType = (WayType)(sidewalkType & ~WAY_BACKWARD); //clang tidy thinks "!WAY_BACKWARD" is always false - } - } - // deal with busways that run in the opposite direction of a one-way street - if (!addForward && (e->myBuswayType & WAY_FORWARD) != 0) { - addForward = true; - forwardPermissions = SVC_BUS; - numLanesForward = 1; - } - if (!addBackward && (e->myBuswayType & WAY_BACKWARD) != 0) { - addBackward = true; - backwardPermissions = SVC_BUS; - numLanesBackward = 1; - } - - const std::string origID = OptionsCont::getOptions().getBool("output.original-names") ? toString(e->id) : ""; - if (ok) { - const int offsetFactor = OptionsCont::getOptions().getBool("lefthand") ? -1 : 1; - LaneSpreadFunction lsf = (addBackward || OptionsCont::getOptions().getBool("osm.oneway-spread-right")) && - e->myRailDirection == WAY_UNKNOWN ? LaneSpreadFunction::RIGHT : LaneSpreadFunction::CENTER; - - id = StringUtils::escapeXML(id); - const std::string reverseID = "-" + id; - - if (addForward) { - assert(numLanesForward > 0); - NBEdge* nbe = new NBEdge(id, from, to, type, speed, numLanesForward, tc.getPriority(type), - forwardWidth, NBEdge::UNSPECIFIED_OFFSET, shape, - StringUtils::escapeXML(streetName), origID, lsf, true); - nbe->setPermissions(forwardPermissions); - if ((e->myBuswayType & WAY_FORWARD) != 0) { - nbe->setPermissions(SVC_BUS, 0); - } - if (addBikeLane && (cyclewayType == WAY_UNKNOWN || (cyclewayType & WAY_FORWARD) != 0)) { - nbe->addBikeLane(tc.getBikeLaneWidth(type) * offsetFactor); - } else if (nbe->getPermissions(0) == SVC_BUS) { - // bikes drive on buslanes if no separate cycle lane is available - nbe->setPermissions(SVC_BUS | SVC_BICYCLE, 0); - } - if (addSidewalk && (sidewalkType == WAY_UNKNOWN || (sidewalkType & WAY_FORWARD) != 0)) { - nbe->addSidewalk(tc.getSidewalkWidth(type) * offsetFactor); - } - nbe->updateParameters(e->getParametersMap()); - nbe->setDistance(distanceStart); - if (!ec.insert(nbe)) { - delete nbe; - throw ProcessError("Could not add edge '" + id + "'."); - } - } - if (addBackward) { - assert(numLanesBackward > 0); - NBEdge* nbe = new NBEdge(reverseID, to, from, type, speedBackward, numLanesBackward, tc.getPriority(type), - backwardWidth, NBEdge::UNSPECIFIED_OFFSET, shape.reverse(), - StringUtils::escapeXML(streetName), origID, lsf, true); - nbe->setPermissions(backwardPermissions); - if ((e->myBuswayType & WAY_BACKWARD) != 0) { - nbe->setPermissions(SVC_BUS, 0); - } - if (addBikeLane && (cyclewayType == WAY_UNKNOWN || (cyclewayType & WAY_BACKWARD) != 0)) { - nbe->addBikeLane(tc.getBikeLaneWidth(type) * offsetFactor); - } else if (nbe->getPermissions(0) == SVC_BUS) { - // bikes drive on buslanes if no separate cycle lane is available - nbe->setPermissions(SVC_BUS | SVC_BICYCLE, 0); - } - if (addSidewalk && (sidewalkType == WAY_UNKNOWN || (sidewalkType & WAY_BACKWARD) != 0)) { - nbe->addSidewalk(tc.getSidewalkWidth(type) * offsetFactor); - } - nbe->updateParameters(e->getParametersMap()); - nbe->setDistance(distanceEnd); - if (!ec.insert(nbe)) { - delete nbe; - throw ProcessError("Could not add edge '-" + id + "'."); - } - } - if ((e->myParkingType & PARKING_BOTH) != 0 && OptionsCont::getOptions().isSet("parking-output")) { - if ((e->myParkingType & PARKING_RIGHT) != 0) { - if (addForward) { - nb.getParkingCont().push_back(NBParking(id, id)); - } else { - /// XXX parking area should be added on the left side of a reverse one-way street - if ((e->myParkingType & PARKING_LEFT) == 0 && !addBackward) { - /// put it on the wrong side (better than nothing) - nb.getParkingCont().push_back(NBParking(reverseID, reverseID)); - } - } - } - if ((e->myParkingType & PARKING_LEFT) != 0) { - if (addBackward) { - nb.getParkingCont().push_back(NBParking(reverseID, reverseID)); - } else { - /// XXX parking area should be added on the left side of an one-way street - if ((e->myParkingType & PARKING_RIGHT) == 0 && !addForward) { - /// put it on the wrong side (better than nothing) - nb.getParkingCont().push_back(NBParking(id, id)); - } - } - } - } - } - return newIndex; -} - -// --------------------------------------------------------------------------- -// definitions of NIImporter_OpenStreetMap::NodesHandler-methods -// --------------------------------------------------------------------------- -NIImporter_OpenStreetMap::NodesHandler::NodesHandler(std::map& toFill, - std::set& uniqueNodes, - const OptionsCont& oc) - - : - SUMOSAXHandler("osm - file"), - myToFill(toFill), - myLastNodeID(-1), - myIsInValidNodeTag(false), - myHierarchyLevel(0), - myUniqueNodes(uniqueNodes), - myImportElevation(oc.getBool("osm.elevation")), - myDuplicateNodes(0), - myOptionsCont(oc) { -} - -NIImporter_OpenStreetMap::NodesHandler::~NodesHandler() = default; - -void -NIImporter_OpenStreetMap::NodesHandler::myStartElement(int element, const SUMOSAXAttributes& attrs) { - ++myHierarchyLevel; - if (element == SUMO_TAG_NODE) { - bool ok = true; - if (myHierarchyLevel != 2) { - WRITE_ERROR("Node element on wrong XML hierarchy level (id='" + toString(attrs.get(SUMO_ATTR_ID, - nullptr, ok)) - + "', level='" + toString(myHierarchyLevel) + "')."); - return; - } - const long long int id = attrs.get(SUMO_ATTR_ID, nullptr, ok); - const std::string action = attrs.hasAttribute("action") ? attrs.getStringSecure("action", "") : ""; - if (action == "delete" || !ok) { - return; - } - myLastNodeID = -1; - if (myToFill.find(id) == myToFill.end()) { - myLastNodeID = id; - // assume we are loading multiple files... - // ... so we won't report duplicate nodes - bool ok2 = true; - double tlat, tlon; - std::istringstream lon(attrs.get(SUMO_ATTR_LON, toString(id).c_str(), ok2)); - if (!ok2) { - return; - } - lon >> tlon; - if (lon.fail()) { - WRITE_ERROR("Node's '" + toString(id) + "' lon information is not numeric."); - return; - } - std::istringstream lat(attrs.get(SUMO_ATTR_LAT, toString(id).c_str(), ok2)); - if (!ok2) { - return; - } - lat >> tlat; - if (lat.fail()) { - WRITE_ERROR("Node's '" + toString(id) + "' lat information is not numeric."); - return; - } - auto* toAdd = new NIOSMNode(id, tlon, tlat); - myIsInValidNodeTag = true; - - auto similarNode = myUniqueNodes.find(toAdd); - if (similarNode == myUniqueNodes.end()) { - myUniqueNodes.insert(toAdd); - } else { - delete toAdd; - toAdd = *similarNode; - myDuplicateNodes++; - } - myToFill[id] = toAdd; - } - } - if (element == SUMO_TAG_TAG && myIsInValidNodeTag) { - if (myHierarchyLevel != 3) { - WRITE_ERROR("Tag element on wrong XML hierarchy level."); - return; - } - bool ok = true; - std::string key = attrs.get(SUMO_ATTR_K, toString(myLastNodeID).c_str(), ok, false); - // we check whether the key is relevant (and we really need to transcode the value) to avoid hitting #1636 - if (key == "highway" || key == "ele" || key == "crossing" || key == "railway" || key == "public_transport" - || key == "name" || key == "train" || key == "bus" || key == "tram" || key == "light_rail" || key == "subway" || key == "station" || key == "noexit" - || StringUtils::startsWith(key, "railway:signal") - || StringUtils::startsWith(key, "railway:position") - ) { - std::string value = attrs.get(SUMO_ATTR_V, toString(myLastNodeID).c_str(), ok, false); - if (key == "highway" && value.find("traffic_signal") != std::string::npos) { - myToFill[myLastNodeID]->tlsControlled = true; - } else if (key == "crossing" && value.find("traffic_signals") != std::string::npos) { - myToFill[myLastNodeID]->tlsControlled = true; - } else if ((key == "noexit" && value == "yes") - || (key == "railway" && value == "buffer_stop")) { - myToFill[myLastNodeID]->railwayBufferStop = true; - } else if (key == "railway" && value.find("crossing") != std::string::npos) { - myToFill[myLastNodeID]->railwayCrossing = true; - } else if (StringUtils::startsWith(key, "railway:signal") && ( - value == "block" || value == "entry" || value == "exit" || value == "intermediate")) { - myToFill[myLastNodeID]->railwaySignal = true; - } else if (StringUtils::startsWith(key, "railway:position") && value.size() > myToFill[myLastNodeID]->position.size()) { - // use the entry with the highest precision (more digits) - myToFill[myLastNodeID]->position = value; - } else if ((key == "public_transport" && value == "stop_position") || - (key == "highway" && value == "bus_stop")) { - myToFill[myLastNodeID]->ptStopPosition = true; - if (myToFill[myLastNodeID]->ptStopLength == 0) { - // default length - myToFill[myLastNodeID]->ptStopLength = myOptionsCont.getFloat("osm.stop-output.length"); - } - } else if (key == "name") { - myToFill[myLastNodeID]->name = value; - } else if (myImportElevation && key == "ele") { - try { - const double elevation = StringUtils::toDouble(value); - if (ISNAN(elevation)) { - WRITE_WARNINGF("Value of key '%' is invalid ('%') in node '%'.", key, value, toString(myLastNodeID)); - } else { - myToFill[myLastNodeID]->ele = elevation; - } - } catch (...) { - WRITE_WARNINGF("Value of key '%' is not numeric ('%') in node '%'.", key, value, toString(myLastNodeID)); - } - } else if (key == "station") { - interpretTransportType(value, myToFill[myLastNodeID]); - } else { - // v="yes" - interpretTransportType(key, myToFill[myLastNodeID]); - } - } - } -} - -void -NIImporter_OpenStreetMap::NodesHandler::myEndElement(int element) { - if (element == SUMO_TAG_NODE && myHierarchyLevel == 2) { - myLastNodeID = -1; - myIsInValidNodeTag = false; - } - --myHierarchyLevel; -} - -// --------------------------------------------------------------------------- -// definitions of NIImporter_OpenStreetMap::EdgesHandler-methods -// --------------------------------------------------------------------------- -NIImporter_OpenStreetMap::EdgesHandler::EdgesHandler( - const std::map& osmNodes, - std::map& toFill, std::map& platformShapes): - SUMOSAXHandler("osm - file"), - myOSMNodes(osmNodes), - myEdgeMap(toFill), - myPlatformShapesMap(platformShapes) { - mySpeedMap["sign"] = MAXSPEED_UNGIVEN; - mySpeedMap["signals"] = MAXSPEED_UNGIVEN; - mySpeedMap["none"] = 142.; // Auswirkungen eines allgemeinen Tempolimits auf Autobahnen im Land Brandeburg (2007) - mySpeedMap["no"] = 142.; - mySpeedMap["walk"] = 5.; - // https://wiki.openstreetmap.org/wiki/Key:source:maxspeed#Commonly_used_values - mySpeedMap["AT:urban"] = 50; - mySpeedMap["AT:rural"] = 100; - mySpeedMap["AT:trunk"] = 100; - mySpeedMap["AT:motorway"] = 130; - mySpeedMap["AU:urban"] = 50; - mySpeedMap["BE:urban"] = 50; - mySpeedMap["BE:zone"] = 30; - mySpeedMap["BE:motorway"] = 120; - mySpeedMap["BE:zone30"] = 30; - mySpeedMap["BE-VLG:rural"] = 70; - mySpeedMap["BE-WAL:rural"] = 90; - mySpeedMap["BE:school"] = 30; - mySpeedMap["CZ:motorway"] = 130; - mySpeedMap["CZ:trunk"] = 110; - mySpeedMap["CZ:rural"] = 90; - mySpeedMap["CZ:urban_motorway"] = 80; - mySpeedMap["CZ:urban_trunk"] = 80; - mySpeedMap["CZ:urban"] = 50; - mySpeedMap["DE:motorway"] = mySpeedMap["none"]; - mySpeedMap["DE:rural"] = 100; - mySpeedMap["DE:urban"] = 50; - mySpeedMap["DE:bicycle_road"] = 30; - mySpeedMap["DK:motorway"] = 130; - mySpeedMap["DK:rural"] = 80; - mySpeedMap["DK:urban"] = 50; - mySpeedMap["EE:urban"] = 50; - mySpeedMap["EE:rural"] = 90; - mySpeedMap["ES:urban"] = 50; - mySpeedMap["ES:zone30"] = 30; - mySpeedMap["FR:motorway"] = 130; // 110 (raining) - mySpeedMap["FR:rural"] = 80; - mySpeedMap["FR:urban"] = 50; - mySpeedMap["FR:zone30"] = 30; - mySpeedMap["HU:living_street"] = 20; - mySpeedMap["HU:motorway"] = 130; - mySpeedMap["HU:rural"] = 90; - mySpeedMap["HU:trunk"] = 110; - mySpeedMap["HU:urban"] = 50; - mySpeedMap["IT:rural"] = 90; - mySpeedMap["IT:motorway"] = 130; - mySpeedMap["IT:urban"] = 50; - mySpeedMap["JP:nsl"] = 60; - mySpeedMap["JP:express"] = 100; - mySpeedMap["LT:rural"] = 90; - mySpeedMap["LT:urban"] = 50; - mySpeedMap["NO:rural"] = 80; - mySpeedMap["NO:urban"] = 50; - mySpeedMap["ON:urban"] = 50; - mySpeedMap["ON:rural"] = 80; - mySpeedMap["PT:motorway"] = 120; - mySpeedMap["PT:rural"] = 90; - mySpeedMap["PT:trunk"] = 100; - mySpeedMap["PT:urban"] = 50; - mySpeedMap["RO:motorway"] = 130; - mySpeedMap["RO:rural"] = 90; - mySpeedMap["RO:trunk"] = 100; - mySpeedMap["RO:urban"] = 50; - mySpeedMap["RS:living_street"] = 30; - mySpeedMap["RS:motorway"] = 130; - mySpeedMap["RS:rural"] = 80; - mySpeedMap["RS:trunk"] = 100; - mySpeedMap["RS:urban"] = 50; - mySpeedMap["RU:living_street"] = 20; - mySpeedMap["RU:urban"] = 60; - mySpeedMap["RU:rural"] = 90; - mySpeedMap["RU:motorway"] = 110; - mySpeedMap["GB:motorway"] = 70 * KM_PER_MILE; - mySpeedMap["GB:nsl_dual"] = 70 * KM_PER_MILE; - mySpeedMap["GB:nsl_single"] = 60 * KM_PER_MILE; - mySpeedMap["UK:motorway"] = 70 * KM_PER_MILE; - mySpeedMap["UK:nsl_dual"] = 70 * KM_PER_MILE; - mySpeedMap["UK:nsl_single"] = 60 * KM_PER_MILE; - mySpeedMap["UZ:living_street"] = 30; - mySpeedMap["UZ:urban"] = 70; - mySpeedMap["UZ:rural"] = 100; - mySpeedMap["UZ:motorway"] = 110; - myAllAttributes = OptionsCont::getOptions().getBool("osm.all-attributes"); -} - -NIImporter_OpenStreetMap::EdgesHandler::~EdgesHandler() = default; - -void -NIImporter_OpenStreetMap::EdgesHandler::myStartElement(int element, - const SUMOSAXAttributes& attrs) { - myParentElements.push_back(element); - // parse "way" elements - if (element == SUMO_TAG_WAY) { - bool ok = true; - const long long int id = attrs.get(SUMO_ATTR_ID, nullptr, ok); - std::string action = attrs.hasAttribute("action") ? attrs.getStringSecure("action", "") : ""; - if (action == "delete" || !ok) { - myCurrentEdge = nullptr; - return; - } - myCurrentEdge = new Edge(id); - } - // parse "nd" (node) elements - if (element == SUMO_TAG_ND && myCurrentEdge != nullptr) { - bool ok = true; - long long int ref = attrs.get(SUMO_ATTR_REF, nullptr, ok); - if (ok) { - auto node = myOSMNodes.find(ref); - if (node == myOSMNodes.end()) { - WRITE_WARNINGF("The referenced geometry information (ref='%') is not known", toString(ref)); - return; - } - - ref = node->second->id; // node may have been substituted - if (myCurrentEdge->myCurrentNodes.empty() || - myCurrentEdge->myCurrentNodes.back() != ref) { // avoid consecutive duplicates - myCurrentEdge->myCurrentNodes.push_back(ref); - } - - } - } - // parse values - if (element == SUMO_TAG_TAG && myParentElements.size() > 2 - && myParentElements[myParentElements.size() - 2] == SUMO_TAG_WAY) { - if (myCurrentEdge == nullptr) { - return; - } - bool ok = true; - std::string key = attrs.get(SUMO_ATTR_K, toString(myCurrentEdge->id).c_str(), ok, false); - if (key.size() > 8 && StringUtils::startsWith(key, "cycleway:")) { - // handle special cycleway keys - const std::string cyclewaySpec = key.substr(9); - key = "cycleway"; - if (cyclewaySpec == "right") { - myCurrentEdge->myCyclewayType = (WayType)(myCurrentEdge->myCyclewayType | WAY_FORWARD); - } else if (cyclewaySpec == "left") { - myCurrentEdge->myCyclewayType = (WayType)(myCurrentEdge->myCyclewayType | WAY_BACKWARD); - } else if (cyclewaySpec == "both") { - myCurrentEdge->myCyclewayType = (WayType)(myCurrentEdge->myCyclewayType | WAY_BOTH); - } else { - key = "ignore"; - } - if ((myCurrentEdge->myCyclewayType & WAY_BOTH) != 0) { - // now we have some info on directionality - myCurrentEdge->myCyclewayType = (WayType)(myCurrentEdge->myCyclewayType & ~WAY_UNKNOWN); - } - } else if (key.size() > 6 && StringUtils::startsWith(key, "busway:")) { - // handle special busway keys - const std::string buswaySpec = key.substr(7); - key = "busway"; - if (buswaySpec == "right") { - myCurrentEdge->myBuswayType = (WayType)(myCurrentEdge->myBuswayType | WAY_FORWARD); - } else if (buswaySpec == "left") { - myCurrentEdge->myBuswayType = (WayType)(myCurrentEdge->myBuswayType | WAY_BACKWARD); - } else if (buswaySpec == "both") { - myCurrentEdge->myBuswayType = (WayType)(myCurrentEdge->myBuswayType | WAY_BOTH); - } else { - key = "ignore"; - } - } - if (myAllAttributes && (key == "bridge" || key == "tunnel")) { - myCurrentEdge->setParameter(key, "true"); // could be differentiated further if necessary - } - // we check whether the key is relevant (and we really need to transcode the value) to avoid hitting #1636 - if (!StringUtils::endsWith(key, "way") && !StringUtils::startsWith(key, "lanes") - && key != "maxspeed" && key != "maxspeed:type" - && key != "maxspeed:forward" && key != "maxspeed:backward" - && key != "junction" && key != "name" && key != "tracks" && key != "layer" - && key != "route" - && key != "sidewalk" - && key != "ref" - && key != "highspeed" - && !StringUtils::startsWith(key, "parking") - && key != "postal_code" - && key != "railway:preferred_direction" - && key != "railway:bidirectional" - && key != "railway:track_ref" - && key != "usage" - && key != "electrified" - && key != "public_transport") { - return; - } - std::string value = attrs.get(SUMO_ATTR_V, toString(myCurrentEdge->id).c_str(), ok, false); - - if ((key == "highway" && value != "platform") || key == "railway" || key == "waterway" || key == "cycleway" - || key == "busway" || key == "route" || key == "sidewalk" || key == "highspeed" - || key == "usage") { - // build type id - std::string singleTypeID = key + "." + value; - myCurrentEdge->myCurrentIsRoad = true; - // special cycleway stuff - if (key == "cycleway") { - if (value == "no") { - return; - } - if (value == "opposite_track") { - myCurrentEdge->myCyclewayType = WAY_BACKWARD; - } else if (value == "opposite_lane") { - myCurrentEdge->myCyclewayType = WAY_BACKWARD; - } - } - // special sidewalk stuff - if (key == "sidewalk") { - if (value == "no" || value == "none") { - myCurrentEdge->mySidewalkType = WAY_NONE; - } else if (value == "both") { - myCurrentEdge->mySidewalkType = WAY_BOTH; - } else if (value == "right") { - myCurrentEdge->mySidewalkType = WAY_FORWARD; - } else if (value == "left") { - myCurrentEdge->mySidewalkType = WAY_BACKWARD; - } - // no need to extend the type id - return; - } - // special busway stuff - if (key == "busway") { - if (value == "no") { - return; - } - if (value == "opposite_track") { - myCurrentEdge->myBuswayType = WAY_BACKWARD; - } else if (value == "opposite_lane") { - myCurrentEdge->myBuswayType = WAY_BACKWARD; - } - // no need to extend the type id - return; - } - if (key == "highspeed") { - if (value == "no") { - return; - } - singleTypeID = "railway.highspeed"; - } - // special case: never build compound type for highspeed rail - if (!myCurrentEdge->myHighWayType.empty() && singleTypeID != "railway.highspeed") { - if (myCurrentEdge->myHighWayType == "railway.highspeed") { - return; - } - // osm-ways may be used by more than one mode (eg railway.tram + highway.residential. this is relevant for multimodal traffic) - // we create a new type for this kind of situation which must then be resolved in insertEdge() - std::vector types = StringTokenizer(myCurrentEdge->myHighWayType, - compoundTypeSeparator).getVector(); - types.push_back(singleTypeID); - myCurrentEdge->myHighWayType = joinToStringSorting(types, compoundTypeSeparator); - } else { - myCurrentEdge->myHighWayType = singleTypeID; - } - } else if (key == "lanes") { - try { - myCurrentEdge->myNoLanes = StringUtils::toInt(value); - } catch (NumberFormatException&) { - // might be a list of values - StringTokenizer st(value, ";", true); - std::vector list = st.getVector(); - if (list.size() >= 2) { - int minLanes = std::numeric_limits::max(); - try { - for (auto& i : list) { - int numLanes = StringUtils::toInt(StringUtils::prune(i)); - minLanes = MIN2(minLanes, numLanes); - } - myCurrentEdge->myNoLanes = minLanes; - WRITE_WARNINGF("Using minimum lane number from list (%) for edge '%'.", value, toString(myCurrentEdge->id)); - } catch (NumberFormatException&) { - WRITE_WARNING("Value of key '" + key + "' is not numeric ('" + value + "') in edge '" + - toString(myCurrentEdge->id) + "'."); - } - } - } catch (EmptyData&) { - WRITE_WARNING("Value of key '" + key + "' is not numeric ('" + value + "') in edge '" + - toString(myCurrentEdge->id) + "'."); - } - } else if (key == "lanes:forward") { - try { - myCurrentEdge->myNoLanesForward = StringUtils::toInt(value); - } catch (...) { - WRITE_WARNING("Value of key '" + key + "' is not numeric ('" + value + "') in edge '" + - toString(myCurrentEdge->id) + "'."); - } - } else if (key == "lanes:backward") { - try { - // denote backwards count with a negative sign - myCurrentEdge->myNoLanesForward = -StringUtils::toInt(value); - } catch (...) { - WRITE_WARNING("Value of key '" + key + "' is not numeric ('" + value + "') in edge '" + - toString(myCurrentEdge->id) + "'."); - } - } else if (myCurrentEdge->myMaxSpeed == MAXSPEED_UNGIVEN && - (key == "maxspeed" || key == "maxspeed:type" || key == "maxspeed:forward")) { - // both 'maxspeed' and 'maxspeed:type' may be given so we must take care not to overwrite an already seen value - myCurrentEdge->myMaxSpeed = interpretSpeed(key, value); - } else if (key == "maxspeed:backward" && myCurrentEdge->myMaxSpeedBackward == MAXSPEED_UNGIVEN) { - myCurrentEdge->myMaxSpeedBackward = interpretSpeed(key, value); - } else if (key == "junction") { - if ((value == "roundabout") && (myCurrentEdge->myIsOneWay.empty())) { - myCurrentEdge->myIsOneWay = "yes"; - } - } else if (key == "oneway") { - myCurrentEdge->myIsOneWay = value; - } else if (key == "name") { - myCurrentEdge->streetName = value; - } else if (key == "ref") { - myCurrentEdge->ref = value; - myCurrentEdge->setParameter("ref", value); - } else if (key == "layer") { - if (myAllAttributes) { - myCurrentEdge->setParameter(key, value); - } - try { - myCurrentEdge->myLayer = StringUtils::toInt(value); - } catch (...) { - WRITE_WARNING("Value of key '" + key + "' is not numeric ('" + value + "') in edge '" + - toString(myCurrentEdge->id) + "'."); - } - } else if (key == "tracks") { - try { - if (StringUtils::toInt(value) == 1) { - myCurrentEdge->myIsOneWay = "true"; - } else { - WRITE_WARNING("Ignoring track count " + value + " for edge '" + toString(myCurrentEdge->id) + "'."); - } - } catch (...) { - WRITE_WARNING("Value of key '" + key + "' is not numeric ('" + value + "') in edge '" + - toString(myCurrentEdge->id) + "'."); - } - } else if (myAllAttributes && key == "postal_code") { - myCurrentEdge->setParameter(key, value); - } else if (key == "railway:preferred_direction") { - if (value == "both") { - myCurrentEdge->myRailDirection = WAY_BOTH; - } else if (value == "backward") { - myCurrentEdge->myRailDirection = WAY_BACKWARD; - } - } else if (key == "railway:bidirectional") { - if (value == "regular") { - myCurrentEdge->myRailDirection = WAY_BOTH; - } - } else if (key == "electrified") { - if (value != "no") { - myCurrentEdge->myCurrentIsElectrified = true; - } - } else if (key == "railway:track_ref") { - myCurrentEdge->setParameter(key, value); - } else if (key == "public_transport" && value == "platform") { - myCurrentEdge->myCurrentIsPlatform = true; - } else if (key == "parking:lane:both" && !StringUtils::startsWith(value, "no")) { - myCurrentEdge->myParkingType |= PARKING_BOTH; - } else if (key == "parking:lane:left" && !StringUtils::startsWith(value, "no")) { - myCurrentEdge->myParkingType |= PARKING_LEFT; - } else if (key == "parking:lane:right" && !StringUtils::startsWith(value, "no")) { - myCurrentEdge->myParkingType |= PARKING_RIGHT; - } - } -} - - -double -NIImporter_OpenStreetMap::EdgesHandler::interpretSpeed(const std::string& key, std::string value) { - if (mySpeedMap.find(value) != mySpeedMap.end()) { - return mySpeedMap[value]; - } else { - double conversion = 1; // OSM default is km/h - if (StringUtils::to_lower_case(value).find("km/h") != std::string::npos) { - value = StringUtils::prune(value.substr(0, value.find_first_not_of("0123456789"))); - } else if (StringUtils::to_lower_case(value).find("mph") != std::string::npos) { - value = StringUtils::prune(value.substr(0, value.find_first_not_of("0123456789"))); - conversion = KM_PER_MILE; - } - try { - return StringUtils::toDouble(value) * conversion; - } catch (...) { - WRITE_WARNING("Value of key '" + key + "' is not numeric ('" + value + "') in edge '" + - toString(myCurrentEdge->id) + "'."); - return MAXSPEED_UNGIVEN; - } - } -} - - -void -NIImporter_OpenStreetMap::EdgesHandler::myEndElement(int element) { - myParentElements.pop_back(); - if (element == SUMO_TAG_WAY && myCurrentEdge != nullptr) { - if (myCurrentEdge->myCurrentIsRoad) { - myEdgeMap[myCurrentEdge->id] = myCurrentEdge; - } else if (myCurrentEdge->myCurrentIsPlatform) { - myPlatformShapesMap[myCurrentEdge->id] = myCurrentEdge; - } else { - delete myCurrentEdge; - } - myCurrentEdge = nullptr; - } -} - -// --------------------------------------------------------------------------- -// definitions of NIImporter_OpenStreetMap::RelationHandler-methods -// --------------------------------------------------------------------------- -NIImporter_OpenStreetMap::RelationHandler::RelationHandler( - const std::map& osmNodes, - const std::map& osmEdges, NBPTStopCont* nbptStopCont, - const std::map& platformShapes, - NBPTLineCont* nbptLineCont, - const OptionsCont& oc) : - SUMOSAXHandler("osm - file"), - myOSMNodes(osmNodes), - myOSMEdges(osmEdges), - myPlatformShapes(platformShapes), - myNBPTStopCont(nbptStopCont), - myNBPTLineCont(nbptLineCont), - myOptionsCont(oc) { - resetValues(); -} - -NIImporter_OpenStreetMap::RelationHandler::~RelationHandler() = default; - -void -NIImporter_OpenStreetMap::RelationHandler::resetValues() { - myCurrentRelation = INVALID_ID; - myIsRestriction = false; - myFromWay = INVALID_ID; - myToWay = INVALID_ID; - myViaNode = INVALID_ID; - myViaWay = INVALID_ID; - myRestrictionType = RESTRICTION_UNKNOWN; - myPlatforms.clear(); - myStops.clear(); - myWays.clear(); - myIsStopArea = false; - myIsRoute = false; - myPTRouteType = ""; -} - -void -NIImporter_OpenStreetMap::RelationHandler::myStartElement(int element, - const SUMOSAXAttributes& attrs) { - myParentElements.push_back(element); - // parse "way" elements - if (element == SUMO_TAG_RELATION) { - bool ok = true; - myCurrentRelation = attrs.get(SUMO_ATTR_ID, nullptr, ok); - const std::string action = attrs.hasAttribute("action") ? attrs.getStringSecure("action", "") : ""; - if (action == "delete" || !ok) { - myCurrentRelation = INVALID_ID; - } - myName = ""; - myRef = ""; - myInterval = -1; - myNightService = ""; - return; - } - if (myCurrentRelation == INVALID_ID) { - return; - } - // parse member elements - if (element == SUMO_TAG_MEMBER) { - bool ok = true; - std::string role = attrs.hasAttribute("role") ? attrs.getStringSecure("role", "") : ""; - auto ref = attrs.get(SUMO_ATTR_REF, nullptr, ok); - if (role == "via") { - // u-turns for divided ways may be given with 2 via-nodes or 1 via-way - std::string memberType = attrs.get(SUMO_ATTR_TYPE, nullptr, ok); - if (memberType == "way" && checkEdgeRef(ref)) { - myViaWay = ref; - } else if (memberType == "node") { - if (myOSMNodes.find(ref) != myOSMNodes.end()) { - myViaNode = ref; - } else { - WRITE_WARNINGF("No node found for reference '%' in relation '%'.", toString(ref), toString(myCurrentRelation)); - } - } - } else if (role == "from" && checkEdgeRef(ref)) { - myFromWay = ref; - } else if (role == "to" && checkEdgeRef(ref)) { - myToWay = ref; - } else if (role == "stop") { - myStops.push_back(ref); - } else if (role == "platform") { - std::string memberType = attrs.get(SUMO_ATTR_TYPE, nullptr, ok); - if (memberType == "way") { - const std::map::const_iterator& wayIt = myPlatformShapes.find(ref); - if (wayIt != myPlatformShapes.end()) { - - NIIPTPlatform platform; - platform.isWay = true; - platform.ref = ref; - myPlatforms.push_back(platform); - } - } else if (memberType == "node") { - if (!myIsStopArea) { - // for routes, a mix of stop and platform members is permitted - myStops.push_back(ref); - } - NIIPTPlatform platform; - platform.isWay = false; - platform.ref = ref; - myPlatforms.push_back(platform); - } - - } else if (role.empty()) { - std::string memberType = attrs.get(SUMO_ATTR_TYPE, nullptr, ok); - if (memberType == "way") { - myWays.push_back(ref); - } else if (memberType == "node") { - myStops.push_back(ref); - } - } - return; - } - // parse values - if (element == SUMO_TAG_TAG) { - bool ok = true; - std::string key = attrs.get(SUMO_ATTR_K, toString(myCurrentRelation).c_str(), ok, false); - // we check whether the key is relevant (and we really need to transcode the value) to avoid hitting #1636 - if (key == "type" || key == "restriction") { - std::string value = attrs.get(SUMO_ATTR_V, toString(myCurrentRelation).c_str(), ok, false); - if (key == "type" && value == "restriction") { - myIsRestriction = true; - return; - } - if (key == "type" && value == "route") { - myIsRoute = true; - return; - } - if (key == "restriction") { - // @note: the 'right/left/straight' part is ignored since the information is - // redundantly encoded in the 'from', 'to' and 'via' members - if (value.substr(0, 5) == "only_") { - myRestrictionType = RESTRICTION_ONLY; - } else if (value.substr(0, 3) == "no_") { - myRestrictionType = RESTRICTION_NO; - } else { - WRITE_WARNINGF("Found unknown restriction type '%' in relation '%'", value, toString(myCurrentRelation)); - } - return; - } - } else if (key == "public_transport") { - std::string value = attrs.get(SUMO_ATTR_V, toString(myCurrentRelation).c_str(), ok, false); - if (value == "stop_area") { - myIsStopArea = true; - } - } else if (key == "route") { - std::string value = attrs.get(SUMO_ATTR_V, toString(myCurrentRelation).c_str(), ok, false); - if (value == "train" || value == "subway" || value == "light_rail" || value == "monorail" || value == "tram" || value == "bus" - || value == "trolleybus" || value == "arialway" || value == "ferry") { - myPTRouteType = value; - } - - } else if (key == "name") { - myName = attrs.get(SUMO_ATTR_V, toString(myCurrentRelation).c_str(), ok, false); - } else if (key == "ref") { - myRef = attrs.get(SUMO_ATTR_V, toString(myCurrentRelation).c_str(), ok, false); - } else if (key == "interval" || key == "headway") { - myInterval = attrs.get(SUMO_ATTR_V, toString(myCurrentRelation).c_str(), ok, false); - } else if (key == "by_night") { - myNightService = attrs.get(SUMO_ATTR_V, toString(myCurrentRelation).c_str(), ok, false); - } - } -} - -bool -NIImporter_OpenStreetMap::RelationHandler::checkEdgeRef(long long int ref) const { - if (myOSMEdges.find(ref) != myOSMEdges.end()) { - return true; - } - - WRITE_WARNINGF("No way found for reference '%' in relation '%'", toString(ref), toString(myCurrentRelation)); - return false; - -} - -void -NIImporter_OpenStreetMap::RelationHandler::myEndElement(int element) { - myParentElements.pop_back(); - if (element == SUMO_TAG_RELATION) { - if (myIsRestriction) { - assert(myCurrentRelation != INVALID_ID); - bool ok = true; - if (myRestrictionType == RESTRICTION_UNKNOWN) { - WRITE_WARNINGF("Ignoring restriction relation '%' with unknown type.", toString(myCurrentRelation)); - ok = false; - } - if (myFromWay == INVALID_ID) { - WRITE_WARNINGF("Ignoring restriction relation '%' with unknown from-way.", toString(myCurrentRelation)); - ok = false; - } - if (myToWay == INVALID_ID) { - WRITE_WARNINGF("Ignoring restriction relation '%' with unknown to-way.", toString(myCurrentRelation)); - ok = false; - } - if (myViaNode == INVALID_ID && myViaWay == INVALID_ID) { - WRITE_WARNINGF("Ignoring restriction relation '%' with unknown via.", toString(myCurrentRelation)); - ok = false; - } - if (ok && !applyRestriction()) { - WRITE_WARNINGF("Ignoring restriction relation '%'.", toString(myCurrentRelation)); - } - } else if (myIsStopArea && OptionsCont::getOptions().isSet("ptstop-output")) { - for (long long ref : myStops) { - if (myOSMNodes.find(ref) == myOSMNodes.end()) { - //WRITE_WARNING( - // "Referenced node: '" + toString(ref) + "' in relation: '" + toString(myCurrentRelation) - // + "' does not exist. Probably OSM file is incomplete."); - continue; - } - - NIOSMNode* n = myOSMNodes.find(ref)->second; - NBPTStop* ptStop = myNBPTStopCont->get(toString(n->id)); - if (ptStop == nullptr) { - //WRITE_WARNING( - // "Relation '" + toString(myCurrentRelation) + "' refers to a non existing pt stop at node: '" - // + toString(n->id) + "'. Probably OSM file is incomplete."); - continue; - } - for (NIIPTPlatform& myPlatform : myPlatforms) { - if (myPlatform.isWay) { - assert(myPlatformShapes.find(myPlatform.ref) != myPlatformShapes.end()); //already tested earlier - Edge* edge = (*myPlatformShapes.find(myPlatform.ref)).second; - if (edge->myCurrentNodes[0] == *(edge->myCurrentNodes.end() - 1)) { - WRITE_WARNINGF("Platform '%' in relation: '%' is given as polygon, which currently is not supported.", myPlatform.ref, myCurrentRelation); - continue; - - } - PositionVector p; - for (auto nodeRef : edge->myCurrentNodes) { - if (myOSMNodes.find(nodeRef) == myOSMNodes.end()) { - //WRITE_WARNING( - // "Referenced node: '" + toString(ref) + "' in relation: '" + toString(myCurrentRelation) - // + "' does not exist. Probably OSM file is incomplete."); - continue; - } - NIOSMNode* pNode = myOSMNodes.find(nodeRef)->second; - Position pNodePos(pNode->lon, pNode->lat, pNode->ele); - if (!NBNetBuilder::transformCoordinate(pNodePos)) { - WRITE_ERROR("Unable to project coordinates for node '" + toString(pNode->id) + "'."); - continue; - } - p.push_back(pNodePos); - } - if (p.size() == 0) { - WRITE_WARNINGF("Referenced platform: '%' in relation: '%' is corrupt. Probably OSM file is incomplete.", - toString(myPlatform.ref), toString(myCurrentRelation)); - continue; - } - NBPTPlatform platform(p[(int)p.size() / 2], p.length()); - ptStop->addPlatformCand(platform); - } else { - if (myOSMNodes.find(myPlatform.ref) == myOSMNodes.end()) { - //WRITE_WARNING( - // "Referenced node: '" + toString(ref) + "' in relation: '" + toString(myCurrentRelation) - // + "' does not exist. Probably OSM file is incomplete."); - continue; - } - NIOSMNode* pNode = myOSMNodes.find(myPlatform.ref)->second; - Position platformPos(pNode->lon, pNode->lat, pNode->ele); - if (!NBNetBuilder::transformCoordinate(platformPos)) { - WRITE_ERROR("Unable to project coordinates for node '" + toString(pNode->id) + "'."); - } - NBPTPlatform platform(platformPos, myOptionsCont.getFloat( - "osm.stop-output.length")); - ptStop->addPlatformCand(platform); - - } - } - ptStop->setIsMultipleStopPositions(myStops.size() > 1); - } - } else if (myPTRouteType != "" && myIsRoute && OptionsCont::getOptions().isSet("ptline-output")) { - NBPTLine* ptLine = new NBPTLine(toString(myCurrentRelation), myName, myPTRouteType, myRef, myInterval, myNightService, interpretTransportType(myPTRouteType)); - ptLine->setMyNumOfStops((int)myStops.size()); - for (long long ref : myStops) { - if (myOSMNodes.find(ref) == myOSMNodes.end()) { - //WRITE_WARNING( - // "Referenced node: '" + toString(ref) + "' in relation: '" + toString(myCurrentRelation) - // + "' does not exist. Probably OSM file is incomplete."); -// resetValues(); -// return; - if (!ptLine->getStops().empty()) { - WRITE_WARNINGF("Done reading first coherent chunk of pt stops. Further stops in relation % are ignored", myCurrentRelation); - break; - } - continue; - } - - NIOSMNode* n = myOSMNodes.find(ref)->second; - NBPTStop* ptStop = myNBPTStopCont->get(toString(n->id)); - if (ptStop == nullptr) { - // loose stop, which must later be mapped onto a line way - Position ptPos(n->lon, n->lat, n->ele); - if (!NBNetBuilder::transformCoordinate(ptPos)) { - WRITE_ERROR("Unable to project coordinates for node '" + toString(n->id) + "'."); - } - ptStop = new NBPTStop(toString(n->id), ptPos, "", "", n->ptStopLength, n->name, n->permissions); - myNBPTStopCont->insert(ptStop); - } - ptLine->addPTStop(ptStop); - } - for (long long& myWay : myWays) { - auto entr = myOSMEdges.find(myWay); - if (entr != myOSMEdges.end()) { - Edge* edge = entr->second; - for (long long& myCurrentNode : edge->myCurrentNodes) { - ptLine->addWayNode(myWay, myCurrentNode); - } - } - } - if (ptLine->getStops().empty()) { - WRITE_WARNINGF("PT line in relation % with no stops ignored. Probably OSM file is incomplete.", myCurrentRelation); - resetValues(); - return; - } - if (myNBPTLineCont->getLines().count(ptLine->getLineID()) == 0) { - myNBPTLineCont->insert(ptLine); - } else { - WRITE_WARNINGF("Ignoring duplicate PT line '%'.", toString(myCurrentRelation)); - delete ptLine; - } - } - // other relations might use similar subelements so reset in any case - resetValues(); - } -} - -bool -NIImporter_OpenStreetMap::RelationHandler::applyRestriction() const { - // since OSM ways are bidirectional we need the via to figure out which direction was meant - if (myViaNode != INVALID_ID) { - NBNode* viaNode = myOSMNodes.find(myViaNode)->second->node; - if (viaNode == nullptr) { - WRITE_WARNINGF("Via-node '%' was not instantiated", toString(myViaNode)); - return false; - } - NBEdge* from = findEdgeRef(myFromWay, viaNode->getIncomingEdges()); - NBEdge* to = findEdgeRef(myToWay, viaNode->getOutgoingEdges()); - if (from == nullptr) { - WRITE_WARNINGF("from-edge '%' of restriction relation could not be determined", toString(myFromWay)); - return false; - } - if (to == nullptr) { - WRITE_WARNINGF("to-edge '%' of restriction relation could not be determined", toString(myToWay)); - return false; - } - if (myRestrictionType == RESTRICTION_ONLY) { - from->addEdge2EdgeConnection(to, true); - // make sure that these connections remain disabled even if network - // modifications (ramps.guess) reset existing connections - for (NBEdge* cand : from->getToNode()->getOutgoingEdges()) { - if (!from->isConnectedTo(cand)) { - from->removeFromConnections(cand, -1, -1, true); - } - } - } else { - from->removeFromConnections(to, -1, -1, true); - } - } else { - // XXX interpreting via-ways or via-node lists not yet implemented - WRITE_WARNINGF("direction of restriction relation could not be determined%", ""); - return false; - } - return true; -} - -NBEdge* -NIImporter_OpenStreetMap::RelationHandler::findEdgeRef(long long int wayRef, - const std::vector& candidates) const { - const std::string prefix = toString(wayRef); - const std::string backPrefix = "-" + prefix; - NBEdge* result = nullptr; - int found = 0; - for (auto candidate : candidates) { - if ((candidate->getID().substr(0, prefix.size()) == prefix) || - (candidate->getID().substr(0, backPrefix.size()) == backPrefix)) { - result = candidate; - found++; - } - } - if (found > 1) { - WRITE_WARNINGF("Ambigous way reference '%' in restriction relation", prefix); - result = nullptr; - } - return result; -} - - -void -NIImporter_OpenStreetMap::reconstructLayerElevation(const double layerElevation, NBNetBuilder& nb) { - NBNodeCont& nc = nb.getNodeCont(); - NBEdgeCont& ec = nb.getEdgeCont(); - // reconstruct elevation from layer info - // build a map of raising and lowering forces (attractor and distance) - // for all nodes unknownElevation - std::map > > layerForces; - - // collect all nodes that belong to a way with layer information - std::set knownElevation; - for (auto& myEdge : myEdges) { - Edge* e = myEdge.second; - if (e->myLayer != 0) { - for (auto j = e->myCurrentNodes.begin(); j != e->myCurrentNodes.end(); ++j) { - NBNode* node = nc.retrieve(toString(*j)); - if (node != nullptr) { - knownElevation.insert(node); - layerForces[node].emplace_back(e->myLayer * layerElevation, POSITION_EPS); - } - } - } - } -#ifdef DEBUG_LAYER_ELEVATION - std::cout << "known elevations:\n"; - for (std::set::iterator it = knownElevation.begin(); it != knownElevation.end(); ++it) { - const std::vector >& primaryLayers = layerForces[*it]; - std::cout << " node=" << (*it)->getID() << " ele="; - for (std::vector >::const_iterator it_ele = primaryLayers.begin(); it_ele != primaryLayers.end(); ++it_ele) { - std::cout << it_ele->first << " "; - } - std::cout << "\n"; - } -#endif - // layer data only provides a lower bound on elevation since it is used to - // resolve the relation among overlapping ways. - // Perform a sanity check for steep inclines and raise the knownElevation if necessary - std::map knownEleMax; - for (auto it : knownElevation) { - double eleMax = -std::numeric_limits::max(); - const std::vector >& primaryLayers = layerForces[it]; - for (const auto& primaryLayer : primaryLayers) { - eleMax = MAX2(eleMax, primaryLayer.first); - } - knownEleMax[it] = eleMax; - } - const double gradeThreshold = OptionsCont::getOptions().getFloat("osm.layer-elevation.max-grade") / 100; - bool changed = true; - while (changed) { - changed = false; - for (auto it = knownElevation.begin(); it != knownElevation.end(); ++it) { - std::map > neighbors = getNeighboringNodes(*it, - knownEleMax[*it] - / gradeThreshold * 3, - knownElevation); - for (auto& neighbor : neighbors) { - if (knownElevation.count(neighbor.first) != 0) { - const double grade = fabs(knownEleMax[*it] - knownEleMax[neighbor.first]) - / MAX2(POSITION_EPS, neighbor.second.first); -#ifdef DEBUG_LAYER_ELEVATION - std::cout << " grade at node=" << (*it)->getID() << " ele=" << knownEleMax[*it] << " neigh=" << it_neigh->first->getID() << " neighEle=" << knownEleMax[it_neigh->first] << " grade=" << grade << " dist=" << it_neigh->second.first << " speed=" << it_neigh->second.second << "\n"; -#endif - if (grade > gradeThreshold * 50 / 3.6 / neighbor.second.second) { - // raise the lower node to the higher level - const double eleMax = MAX2(knownEleMax[*it], knownEleMax[neighbor.first]); - if (knownEleMax[*it] < eleMax) { - knownEleMax[*it] = eleMax; - } else { - knownEleMax[neighbor.first] = eleMax; - } - changed = true; - } - } - } - } - } - - // collect all nodes within a grade-dependent range around knownElevation-nodes and apply knowElevation forces - std::set unknownElevation; - for (auto it = knownElevation.begin(); it != knownElevation.end(); ++it) { - const double eleMax = knownEleMax[*it]; - const double maxDist = fabs(eleMax) * 100 / layerElevation; - std::map > neighbors = getNeighboringNodes(*it, maxDist, knownElevation); - for (auto& neighbor : neighbors) { - if (knownElevation.count(neighbor.first) == 0) { - unknownElevation.insert(neighbor.first); - layerForces[neighbor.first].emplace_back(eleMax, neighbor.second.first); - } - } - } - - // apply forces to ground-level nodes (neither in knownElevation nor unknownElevation) - for (auto it = unknownElevation.begin(); it != unknownElevation.end(); ++it) { - double eleMax = -std::numeric_limits::max(); - const std::vector >& primaryLayers = layerForces[*it]; - for (const auto& primaryLayer : primaryLayers) { - eleMax = MAX2(eleMax, primaryLayer.first); - } - const double maxDist = fabs(eleMax) * 100 / layerElevation; - std::map > neighbors = getNeighboringNodes(*it, maxDist, knownElevation); - for (auto& neighbor : neighbors) { - if (knownElevation.count(neighbor.first) == 0 && unknownElevation.count(neighbor.first) == 0) { - layerForces[*it].emplace_back(0, neighbor.second.first); - } - } - } - // compute the elevation for each node as the weighted average of all forces -#ifdef DEBUG_LAYER_ELEVATION - std::cout << "summation of forces\n"; -#endif - std::map nodeElevation; - for (auto& layerForce : layerForces) { - const std::vector >& forces = layerForce.second; - if (knownElevation.count(layerForce.first) != 0) { - // use the maximum value - /* - double eleMax = -std::numeric_limits::max(); - for (std::vector >::const_iterator it_force = forces.begin(); it_force != forces.end(); ++it_force) { - eleMax = MAX2(eleMax, it_force->first); - } - */ -#ifdef DEBUG_LAYER_ELEVATION - std::cout << " node=" << it->first->getID() << " knownElevation=" << knownEleMax[it->first] << "\n"; -#endif - nodeElevation[layerForce.first] = knownEleMax[layerForce.first]; - } else if (forces.size() == 1) { - nodeElevation[layerForce.first] = forces.front().first; - } else { - // use the weighted sum - double distSum = 0; - for (const auto& force : forces) { - distSum += force.second; - } - double weightSum = 0; - double elevation = 0; -#ifdef DEBUG_LAYER_ELEVATION - std::cout << " node=" << it->first->getID() << " distSum=" << distSum << "\n"; -#endif - for (const auto& force : forces) { - const double weight = (distSum - force.second) / distSum; - weightSum += weight; - elevation += force.first * weight; - -#ifdef DEBUG_LAYER_ELEVATION - std::cout << " force=" << it_force->first << " dist=" << it_force->second << " weight=" << weight << " ele=" << elevation << "\n"; -#endif - } - nodeElevation[layerForce.first] = elevation / weightSum; - } - } -#ifdef DEBUG_LAYER_ELEVATION - std::cout << "final elevations:\n"; - for (std::map::iterator it = nodeElevation.begin(); it != nodeElevation.end(); ++it) { - std::cout << " node=" << (it->first)->getID() << " ele=" << it->second << "\n"; - } -#endif - // apply node elevations - for (auto& it : nodeElevation) { - NBNode* n = it.first; - Position pos = n->getPosition(); - n->reinit(n->getPosition() + Position(0, 0, it.second), n->getType()); - } - - // apply way elevation to all edges that had layer information - for (const auto& it : ec) { - NBEdge* edge = it.second; - const PositionVector& geom = edge->getGeometry(); - const double length = geom.length2D(); - const double zFrom = nodeElevation[edge->getFromNode()]; - const double zTo = nodeElevation[edge->getToNode()]; - // XXX if the from- or to-node was part of multiple ways with - // different layers, reconstruct the layer value from origID - double dist = 0; - PositionVector newGeom; - for (auto it_pos = geom.begin(); it_pos != geom.end(); ++it_pos) { - if (it_pos != geom.begin()) { - dist += (*it_pos).distanceTo2D(*(it_pos - 1)); - } - newGeom.push_back((*it_pos) + Position(0, 0, zFrom + (zTo - zFrom) * dist / length)); - } - edge->setGeometry(newGeom); - } -} - -std::map > -NIImporter_OpenStreetMap::getNeighboringNodes(NBNode* node, double maxDist, const std::set& knownElevation) { - std::map > result; - std::set visited; - std::vector open; - open.push_back(node); - result[node] = std::make_pair(0, 0); - while (!open.empty()) { - NBNode* n = open.back(); - open.pop_back(); - if (visited.count(n) != 0) { - continue; - } - visited.insert(n); - const EdgeVector& edges = n->getEdges(); - for (auto e : edges) { - NBNode* s = nullptr; - if (n->hasIncoming(e)) { - s = e->getFromNode(); - } else { - s = e->getToNode(); - } - const double dist = result[n].first + e->getGeometry().length2D(); - const double speed = MAX2(e->getSpeed(), result[n].second); - if (result.count(s) == 0) { - result[s] = std::make_pair(dist, speed); - } else { - result[s] = std::make_pair(MIN2(dist, result[s].first), MAX2(speed, result[s].second)); - } - if (dist < maxDist && knownElevation.count(s) == 0) { - open.push_back(s); - } - } - } - result.erase(node); - return result; -} - - -std::string -NIImporter_OpenStreetMap::usableType(const std::string& type, const std::string& id, NBTypeCont& tc) { - if (tc.knows(type)) { - return type; - } - if (myUnusableTypes.count(type) > 0) { - return ""; - } - if (myKnownCompoundTypes.count(type) > 0) { - return myKnownCompoundTypes[type]; - } - // this edge has a type which does not yet exist in the TypeContainer - StringTokenizer tok = StringTokenizer(type, compoundTypeSeparator); - std::vector types; - while (tok.hasNext()) { - std::string t = tok.next(); - if (tc.knows(t)) { - if (std::find(types.begin(), types.end(), t) == types.end()) { - types.push_back(t); - } - } else if (tok.size() > 1) { - WRITE_WARNINGF("Discarding unknown compound '%' in type '%' (first occurence for edge '%').", t, type, id); - } - } - if (types.empty()) { - WRITE_WARNINGF("Discarding unusable type '%' (first occurence for edge '%').", type, id); - myUnusableTypes.insert(type); - return ""; - } - const std::string newType = joinToString(types, "|"); - if (tc.knows(newType)) { - myKnownCompoundTypes[type] = newType; - return newType; - } else if (myKnownCompoundTypes.count(newType) > 0) { - return myKnownCompoundTypes[newType]; - } else { - // build a new type by merging all values - int numLanes = 0; - double maxSpeed = 0; - int prio = 0; - double width = NBEdge::UNSPECIFIED_WIDTH; - double sidewalkWidth = NBEdge::UNSPECIFIED_WIDTH; - double bikelaneWidth = NBEdge::UNSPECIFIED_WIDTH; - bool defaultIsOneWay = true; - SVCPermissions permissions = 0; - bool discard = true; - for (auto& type2 : types) { - if (!tc.getShallBeDiscarded(type2)) { - numLanes = MAX2(numLanes, tc.getNumLanes(type2)); - maxSpeed = MAX2(maxSpeed, tc.getSpeed(type2)); - prio = MAX2(prio, tc.getPriority(type2)); - defaultIsOneWay &= tc.getIsOneWay(type2); - //std::cout << "merging component " << type2 << " into type " << newType << " allows=" << getVehicleClassNames(tc.getPermissions(type2)) << " oneway=" << defaultIsOneWay << "\n"; - permissions |= tc.getPermissions(type2); - width = MAX2(width, tc.getWidth(type2)); - sidewalkWidth = MAX2(sidewalkWidth, tc.getSidewalkWidth(type2)); - bikelaneWidth = MAX2(bikelaneWidth, tc.getBikeLaneWidth(type2)); - discard = false; - } - } - if (width != NBEdge::UNSPECIFIED_WIDTH) { - width = MAX2(width, SUMO_const_laneWidth); - } - // ensure pedestrians don't run into trains - if (sidewalkWidth == NBEdge::UNSPECIFIED_WIDTH - && (permissions & SVC_PEDESTRIAN) != 0 - && (permissions & SVC_RAIL_CLASSES) != 0) { - //std::cout << "patching sidewalk for type '" << newType << "' which allows=" << getVehicleClassNames(permissions) << "\n"; - sidewalkWidth = OptionsCont::getOptions().getFloat("default.sidewalk-width"); - } - - if (discard) { - WRITE_WARNINGF("Discarding compound type '%' (first occurence for edge '%').", newType, id); - myUnusableTypes.insert(newType); - return ""; - } - - WRITE_MESSAGE("Adding new type '" + type + "' (first occurence for edge '" + id + "')."); - tc.insert(newType, numLanes, maxSpeed, prio, permissions, width, defaultIsOneWay, - sidewalkWidth, bikelaneWidth, 0, 0, 0); - for (auto& type3 : types) { - if (!tc.getShallBeDiscarded(type3)) { - tc.copyRestrictionsAndAttrs(type3, newType); - } - } - myKnownCompoundTypes[type] = newType; - return newType; - } -} - -void -NIImporter_OpenStreetMap::extendRailwayDistances(Edge* e, NBTypeCont& tc) { - const std::string id = toString(e->id); - std::string type = usableType(e->myHighWayType, id, tc); - if (type != "" && isRailway(tc.getPermissions(type))) { - std::vector nodes; - std::vector usablePositions; - std::vector usableIndex; - for (long long int n : e->myCurrentNodes) { - NIOSMNode* node = myOSMNodes[n]; - node->positionMeters = interpretDistance(node); - if (node->positionMeters != std::numeric_limits::max()) { - usablePositions.push_back(node->positionMeters); - usableIndex.push_back((int)nodes.size()); - } - nodes.push_back(node); - } - if (usablePositions.size() == 0) { - return; - } else { - bool forward = true; - if (usablePositions.size() == 1) { - WRITE_WARNINGF("Ambiguous railway kilometrage direction for way '%' (assuming forward)", id); - } else { - forward = usablePositions.front() < usablePositions.back(); - } - // check for consistency - for (int i = 1; i < (int)usablePositions.size(); i++) { - if ((usablePositions[i - 1] < usablePositions[i]) != forward) { - WRITE_WARNINGF("Inconsistent railway kilometrage direction for way '%': %s (skipping)", id, toString(usablePositions)); - return; - } - } - if (nodes.size() > usablePositions.size()) { - // complete missing values - PositionVector shape; - for (NIOSMNode* node : nodes) { - shape.push_back(Position(node->lon, node->lat, 0)); - } - if (!NBNetBuilder::transformCoordinates(shape)) { - return; // error will be given later - } - double sign = forward ? 1 : -1; - // extend backward before first usable value - for (int i = usableIndex.front() - 1; i >= 0; i--) { - nodes[i]->positionMeters = nodes[i + 1]->positionMeters - sign * shape[i].distanceTo2D(shape[i + 1]); - } - // extend forward - for (int i = usableIndex.front() + 1; i < (int)nodes.size(); i++) { - if (nodes[i]->positionMeters == std::numeric_limits::max()) { - nodes[i]->positionMeters = nodes[i - 1]->positionMeters + sign * shape[i].distanceTo2D(shape[i - 1]); - } - } - //std::cout << " way=" << id << " usable=" << toString(usablePositions) << "\n indices=" << toString(usableIndex) - // << " final:\n"; - //for (auto n : nodes) { - // std::cout << " " << n->id << " " << n->positionMeters << " " << n->position<< "\n"; - //} - } - } - } -} - - -double -NIImporter_OpenStreetMap::interpretDistance(NIOSMNode* node) { - if (node->position.size() > 0) { - try { - if (StringUtils::startsWith(node->position, "mi:")) { - return StringUtils::toDouble(node->position.substr(3)) * 1609.344; // meters per mile - } else { - return StringUtils::toDouble(node->position) * 1000; - } - } catch (...) { - WRITE_WARNINGF("Value of railway:position is not numeric ('%') in node '%'.", node->position, toString(node->id)); - } - } - return std::numeric_limits::max(); -} - -SUMOVehicleClass -NIImporter_OpenStreetMap::interpretTransportType(const std::string& type, NIOSMNode* toSet) { - SUMOVehicleClass result = SVC_IGNORING; - if (type == "train") { - result = SVC_RAIL; - } else if (type == "subway" || type == "light_rail") { - result = SVC_RAIL_URBAN; - } else if (SumoVehicleClassStrings.hasString(type)) { - result = SumoVehicleClassStrings.get(type); - } - std::string stop = ""; - if (result == SVC_TRAM) { - stop = ".tram"; - } else if (result == SVC_BUS) { - stop = ".bus"; - } else if (isRailway(result)) { - stop = ".train"; - } - if (toSet != nullptr && result != SVC_IGNORING) { - toSet->permissions |= result; - toSet->ptStopLength = OptionsCont::getOptions().getFloat("osm.stop-output.length" + stop); - } - return result; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/NIImporter_OpenStreetMap.h b/Util/OSM2ODR/src/netimport/NIImporter_OpenStreetMap.h deleted file mode 100644 index eb1b47531..000000000 --- a/Util/OSM2ODR/src/netimport/NIImporter_OpenStreetMap.h +++ /dev/null @@ -1,635 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIImporter_OpenStreetMap.h -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @author Walter Bamberger -/// @author Gregor Laemmel -/// @date Mon, 14.04.2008 -/// -// Importer for networks stored in OpenStreetMap format -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include -#include -#include -#include - - -// =========================================================================== -// class declarations -// =========================================================================== -class NBEdge; -class NBEdgeCont; -class NBNetBuilder; -class NBNode; -class NBNodeCont; -class NBTrafficLightLogicCont; -class NBTypeCont; -class OptionsCont; - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NIImporter_OpenStreetMap - * @brief Importer for networks stored in OpenStreetMap format - * - */ -class NIImporter_OpenStreetMap { -public: - /** @brief Loads content of the optionally given OSM file - * - * If the option "osm-files" is set, the file(s) stored therein is read and - * the network definition stored therein is stored within the given network - * builder. - * - * If the option "osm-files" is not set, this method simply returns. - * - * @param[in] oc The options to use - * @param[in, out] nb The network builder to fill - */ - static void loadNetwork(const OptionsCont& oc, NBNetBuilder& nb); - -protected: - /** @brief An internal representation of an OSM-node - */ - struct NIOSMNode { - NIOSMNode(long long int _id, double _lon, double _lat) - : - id(_id), lon(_lon), lat(_lat), ele(0), - tlsControlled(false), - railwayCrossing(false), - railwaySignal(false), - railwayBufferStop(false), - ptStopPosition(false), ptStopLength(0), name(""), - permissions(SVC_IGNORING), - positionMeters(std::numeric_limits::max()), - node(0) { } - - /// @brief The node's id - const long long int id; - /// @brief The longitude the node is located at - const double lon; - /// @brief The latitude the node is located at - const double lat; - /// @brief The elevation of this node - double ele; - /// @brief Whether this is a tls controlled junction - bool tlsControlled; - /// @brief Whether this is a railway crossing - bool railwayCrossing; - /// @brief Whether this is a railway (main) signal - bool railwaySignal; - /// @brief Whether this is a railway buffer stop - bool railwayBufferStop; - /// @brief Whether this is a public transport stop position - bool ptStopPosition; - /// @brief The length of the pt stop - double ptStopLength; - /// @brief The name of the node - std::string name; - /// @brief type of pt stop - SVCPermissions permissions; - /// @brief kilometrage/mileage - std::string position; - /// @brief position converted to m (using highest precision available) - double positionMeters; - /// @brief the NBNode that was instantiated - NBNode* node; - - private: - /// invalidated assignment operator - NIOSMNode& operator=(const NIOSMNode& s) = delete; - - - }; - -public: - /// @brief translate osm transport designations into sumo vehicle class - static SUMOVehicleClass interpretTransportType(const std::string& type, NIOSMNode* toSet = nullptr); - -protected: - - - /** @enum CycleWayType - * @brief details on the kind of cycleway along this road - */ - enum WayType { - WAY_NONE = 0, - WAY_FORWARD = 1, - WAY_BACKWARD = 2, - WAY_BOTH = WAY_FORWARD | WAY_BACKWARD, - WAY_UNKNOWN = 4 - }; - - enum ParkingType { - PARKING_NONE = 0, - PARKING_LEFT = 1, - PARKING_RIGHT = 2, - PARKING_BOTH = WAY_FORWARD | WAY_BACKWARD, - PARKING_UNKNOWN = 4, - PARKING_FORBIDDEN = 8, - PARKING_PERPENDICULAR = 16, - PARKING_DIAGONAL = 32 - }; - - - /** @brief An internal definition of a loaded edge - */ - struct Edge : public Parameterised { - - explicit Edge(long long int _id) - : - id(_id), myNoLanes(-1), myNoLanesForward(0), - myMaxSpeed(MAXSPEED_UNGIVEN), - myMaxSpeedBackward(MAXSPEED_UNGIVEN), - myCyclewayType(WAY_UNKNOWN), // building of extra lane depends on bikelaneWidth of loaded typemap - myBuswayType(WAY_NONE), // buslanes are always built when declared - mySidewalkType(WAY_UNKNOWN), // building of extra lanes depends on sidewalkWidth of loaded typemap - myRailDirection(WAY_UNKNOWN), // store direction(s) of railway usage - myParkingType(PARKING_NONE), // parking areas exported optionally - myLayer(0), // layer is non-zero only in conflict areas - myCurrentIsRoad(false), - myCurrentIsPlatform(false), - myCurrentIsElectrified(false) - { } - - - /// @brief The edge's id - const long long int id; - /// @brief The edge's street name - std::string streetName; - /// @brief The edge's track name - std::string ref; - /// @brief number of lanes, or -1 if unknown - int myNoLanes; - /// @brief number of lanes in forward direction or 0 if unknown, negative if backwards lanes are meant - int myNoLanesForward; - /// @brief maximum speed in km/h, or MAXSPEED_UNGIVEN - double myMaxSpeed; - /// @brief maximum speed in km/h, or MAXSPEED_UNGIVEN - double myMaxSpeedBackward; - /// @brief The type, stored in "highway" key - std::string myHighWayType; - /// @brief Information whether this is an one-way road - std::string myIsOneWay; - /// @brief Information about the kind of cycleway along this road - WayType myCyclewayType; - /// @brief Information about the kind of busway along this road - WayType myBuswayType; - /// @brief Information about the kind of sidwalk along this road - WayType mySidewalkType; - /// @brief Information about the direction(s) of railway usage - WayType myRailDirection; - /// @brief Information about road-side parking - int myParkingType; - /// @brief Information about the relative z-ordering of ways - int myLayer; - /// @brief The list of nodes this edge is made of - std::vector myCurrentNodes; - /// @brief Information whether this is a road - bool myCurrentIsRoad; - /// @brief Information whether this is a pt platform - bool myCurrentIsPlatform; - /// @brief Information whether this is railway is electrified - bool myCurrentIsElectrified; - - private: - /// invalidated assignment operator - Edge& operator=(const Edge& s) = delete; - - - }; - - - NIImporter_OpenStreetMap(); - - ~NIImporter_OpenStreetMap(); - - void load(const OptionsCont& oc, NBNetBuilder& nb); - -private: - /** @brief Functor which compares two NIOSMNodes according - * to their coordinates - */ - class CompareNodes { - public: - bool operator()(const NIOSMNode* n1, const NIOSMNode* n2) const { - return (n1->lat > n2->lat) || (n1->lat == n2->lat && n1->lon > n2->lon); - } - }; - - - /// @brief The separator within newly created compound type names - static const std::string compoundTypeSeparator; - - class CompareEdges; - - /** @brief the map from OSM node ids to actual nodes - * @note: NIOSMNodes may appear multiple times due to substition - */ - std::map myOSMNodes; - - /// @brief the set of unique nodes used in NodesHandler, used when freeing memory - std::set myUniqueNodes; - - - /** @brief the map from OSM way ids to edge objects */ - std::map myEdges; - - /** @brief the map from OSM way ids to platform shapes */ - std::map myPlatformShapes; - - /** @brief the map from stop_area relations to member node */ - std::map > myStopAreas; - - /// @brief The compounds types that do not contain known types - std::set myUnusableTypes; - - /// @brief The compound types that have already been mapped to other known types - std::map myKnownCompoundTypes; - - /** @brief Builds an NBNode - * - * If a node with the given id is already known, nothing is done. - * Otherwise, the position and other information of the node is retrieved from the - * given node map, the node is built and added to the given node container. - * If the node is controlled by a tls, the according tls is built and added - * to the tls container. - * @param[in] id The id of the node to build - * @param[in] osmNodes Map of node ids to information about these - * @param[in, out] nc The node container to add the built node to - * @param[in, out] tlsc The traffic lights logic container to add the built tls to - * @return The built/found node - * @exception ProcessError If the tls could not be added to the container - */ - NBNode* insertNodeChecking(long long int id, NBNodeCont& nc, NBTrafficLightLogicCont& tlsc); - - - /** @brief Builds an NBEdge - * - * @param[in] e The definition of the edge - * @param[in] index The index of the edge (in the case it is split along her nodes) - * @param[in] from The origin node of the edge - * @param[in] to The destination node of the edge - * @param[in] passed The list of passed nodes (geometry information) - * @param[in] osmNodes Container of node definitions for getting information about nodes from - * @param[in, out] The NetBuilder instance - * @return the new index if the edge is split - * @exception ProcessError If the edge could not be added to the container - */ - int insertEdge(Edge* e, int index, NBNode* from, NBNode* to, - const std::vector& passed, NBNetBuilder& nb); - - /// @brief reconstruct elevation from layer info - void reconstructLayerElevation(double layerElevation, NBNetBuilder& nb); - - /// @brief collect neighboring nodes with their road distance and maximum between-speed. Search does not continue beyond knownElevation-nodes - std::map > - getNeighboringNodes(NBNode* node, double maxDist, const std::set& knownElevation); - - /// @brief check whether the type is known or consists of known type compounds. return empty string otherwise - std::string usableType(const std::string& type, const std::string& id, NBTypeCont& tc); - - /// @brief extend kilometrage data for all nodes along railway - void extendRailwayDistances(Edge* e, NBTypeCont& tc); - - /// @brief read distance value from node and return value in m - static double interpretDistance(NIOSMNode* node); - -protected: - static const double MAXSPEED_UNGIVEN; - static const long long int INVALID_ID; - - /** - * @class NodesHandler - * @brief A class which extracts OSM-nodes from a parsed OSM-file - */ - friend class NodesHandler; - class NodesHandler : public SUMOSAXHandler { - public: - /** @brief Contructor - * @param[in, out] toFill The nodes container to fill - * @param[in, out] uniqueNodes The nodes container for ensuring uniqueness - * @param[in] options The options to use - */ - NodesHandler(std::map& toFill, std::set& uniqueNodes, - const OptionsCont& cont); - - - /// @brief Destructor - ~NodesHandler() override; - - int getDuplicateNodes() const { - return myDuplicateNodes; - } - - protected: - /// @name inherited from GenericSAXHandler - //@{ - - /** @brief Called on the opening of a tag; - * - * @param[in] element ID of the currently opened element - * @param[in] attrs Attributes within the currently opened element - * @exception ProcessError If something fails - * @see GenericSAXHandler::myStartElement - */ - void myStartElement(int element, const SUMOSAXAttributes& attrs) override; - - - /** @brief Called when a closing tag occurs - * - * @param[in] element ID of the currently opened element - * @exception ProcessError If something fails - * @see GenericSAXHandler::myEndElement - */ - void myEndElement(int element) override; - //@} - - - private: - - /// @brief The nodes container to fill - std::map& myToFill; - - /// @brief ID of the currently parsed node, for reporting mainly - long long int myLastNodeID; - - /// @brief Hierarchy helper for parsing a node's tags - bool myIsInValidNodeTag; - - /// @brief The current hierarchy level - int myHierarchyLevel; - - /// @brief the set of unique nodes (used for duplicate detection/substitution) - std::set& myUniqueNodes; - - /// @brief whether elevation data should be imported - const bool myImportElevation; - - /// @brief number of diplic - int myDuplicateNodes; - - /// @brief the options - const OptionsCont& myOptionsCont; - - - private: - /** @brief invalidated copy constructor */ - NodesHandler(const NodesHandler& s); - - /** @brief invalidated assignment operator */ - NodesHandler& operator=(const NodesHandler& s); - - }; - - - /** - * @class EdgesHandler - * @brief A class which extracts OSM-edges from a parsed OSM-file - */ - class EdgesHandler : public SUMOSAXHandler { - public: - /** @brief Constructor - * - * @param[in] osmNodes The previously parsed (osm-)nodes - * @param[in, out] toFill The edges container to fill with read edges - */ - EdgesHandler(const std::map& osmNodes, - std::map& toFill, std::map& platformShapes); - - - /// @brief Destructor - ~EdgesHandler() override; - - - protected: - /// @name inherited from GenericSAXHandler - //@{ - - /** @brief Called on the opening of a tag; - * - * @param[in] element ID of the currently opened element - * @param[in] attrs Attributes within the currently opened element - * @exception ProcessError If something fails - * @see GenericSAXHandler::myStartElement - */ - void myStartElement(int element, const SUMOSAXAttributes& attrs) override; - - - /** @brief Called when a closing tag occurs - * - * @param[in] element ID of the currently opened element - * @exception ProcessError If something fails - * @see GenericSAXHandler::myEndElement - */ - void myEndElement(int element) override; - //@} - - double interpretSpeed(const std::string& key, std::string value); - - private: - /// @brief The previously parsed nodes - const std::map& myOSMNodes; - - /// @brief A map of built edges - std::map& myEdgeMap; - - /// @brief A map of built edges - std::map& myPlatformShapesMap; - - /// @brief The currently built edge - Edge* myCurrentEdge; - - /// @brief The element stack - std::vector myParentElements; - - /// @brief A map of non-numeric speed descriptions to their numeric values - std::map mySpeedMap; - - /// @brief whether additional way attributes shall be added to the edge - bool myAllAttributes; - - private: - /** @brief invalidated copy constructor */ - EdgesHandler(const EdgesHandler& s); - - /** @brief invalidated assignment operator */ - EdgesHandler& operator=(const EdgesHandler& s); - - }; - - /** - * @class RelationHandler - * @brief A class which extracts relevant relation information from a parsed OSM-file - * - turn restrictions - */ - class RelationHandler : public SUMOSAXHandler { - public: - /** @brief Constructor - * - * @param[in] osmNodes The previously parsed OSM-nodes - * @param[in] osmEdges The previously parse OSM-edges - */ - RelationHandler(const std::map& osmNodes, - const std::map& osmEdges, NBPTStopCont* nbptStopCont, - const std::map& platfromShapes, NBPTLineCont* nbptLineCont, - const OptionsCont& oc); - - - /// @brief Destructor - ~RelationHandler() override; - - protected: - /// @name inherited from GenericSAXHandler - //@{ - - /** @brief Called on the opening of a tag; - * - * @param[in] element ID of the currently opened element - * @param[in] attrs Attributes within the currently opened element - * @exception ProcessError If something fails - * @see GenericSAXHandler::myStartElement - */ - void myStartElement(int element, const SUMOSAXAttributes& attrs) override; - - - /** @brief Called when a closing tag occurs - * - * @param[in] element ID of the currently opened element - * @exception ProcessError If something fails - * @see GenericSAXHandler::myEndElement - */ - void myEndElement(int element) override; - //@} - - - private: - /// @brief The previously parsed nodes - const std::map& myOSMNodes; - - /// @brief The previously parsed edges - const std::map& myOSMEdges; - - /// @brief The previously parsed platform shapes - const std::map& myPlatformShapes; - - /// @brief The previously filled pt stop container - NBPTStopCont* myNBPTStopCont; - - /// @brief PT Line container to be filled - NBPTLineCont* myNBPTLineCont; - - /// @brief The currently parsed relation - long long int myCurrentRelation; - - /// @brief The element stack - std::vector myParentElements; - - /// @brief whether the currently parsed relation is a restriction - bool myIsRestriction; - - /// @brief the origination way for the current restriction - long long int myFromWay; - - /// @brief the destination way for the current restriction - long long int myToWay; - - /// @brief the via node/way for the current restriction - long long int myViaNode; - long long int myViaWay; - - - /// @brief the options cont - const OptionsCont& myOptionsCont; - - /** @enum RestrictionType - * @brief whether the only allowed or the only forbidden connection is defined - */ - enum RestrictionType { - /// @brief The only valid connection is declared - RESTRICTION_ONLY, - /// @brief The only invalid connection is declared - RESTRICTION_NO, - /// @brief The relation tag was missing - RESTRICTION_UNKNOWN - }; - RestrictionType myRestrictionType; - - /// @brief reset members to their defaults for parsing a new relation - void resetValues(); - - /// @brief check whether a referenced way has a corresponding edge - bool checkEdgeRef(long long int ref) const; - - /// @brief try to apply the parsed restriction and return whether successful - bool applyRestriction() const; - - /// @brief try to find the way segment among candidates - NBEdge* findEdgeRef(long long int wayRef, const std::vector& candidates) const; - - private: - /** @brief invalidated copy constructor */ - RelationHandler(const RelationHandler& s); - - /** @brief invalidated assignment operator */ - RelationHandler& operator=(const RelationHandler& s); - - /// @brief bus stop references - std::vector myStops; - - - struct NIIPTPlatform { - long long int ref; - bool isWay; - }; - - /// @brief bus stop platforms - std::vector myPlatforms; - - /// @brief ways in pt line references - std::vector myWays; - - /// @brief indicates whether current relation is a pt stop area - bool myIsStopArea; - - /// @brief indicates whether current relation is a route - bool myIsRoute; - - /// @brief indicates whether current relation is a pt route - std::string myPTRouteType; - - /// @brief name of the relation - std::string myName; - - /// @brief ref of the pt line - std::string myRef; - - /// @brief service interval of the pt line in minutes - int myInterval; - - /// @brief night service information of the pt line - std::string myNightService; - }; - -}; diff --git a/Util/OSM2ODR/src/netimport/NIImporter_SUMO.cpp b/Util/OSM2ODR/src/netimport/NIImporter_SUMO.cpp deleted file mode 100644 index 76ac0078d..000000000 --- a/Util/OSM2ODR/src/netimport/NIImporter_SUMO.cpp +++ /dev/null @@ -1,1018 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIImporter_SUMO.cpp -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @author Leonhard Luecken -/// @date Mon, 14.04.2008 -/// -// Importer for networks stored in SUMO format -/****************************************************************************/ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "NILoader.h" -#include "NIXMLTypesHandler.h" -#include "NIImporter_SUMO.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -// --------------------------------------------------------------------------- -// static methods (interface in this case) -// --------------------------------------------------------------------------- -void -NIImporter_SUMO::loadNetwork(OptionsCont& oc, NBNetBuilder& nb) { - NIImporter_SUMO importer(nb); - importer._loadNetwork(oc); -} - - -// --------------------------------------------------------------------------- -// loader methods -// --------------------------------------------------------------------------- -NIImporter_SUMO::NIImporter_SUMO(NBNetBuilder& nb) - : SUMOSAXHandler("sumo-network"), - myNetBuilder(nb), - myNodeCont(nb.getNodeCont()), - myTLLCont(nb.getTLLogicCont()), - myTypesHandler(nb.getTypeCont()), - myCurrentEdge(nullptr), - myCurrentLane(nullptr), - myCurrentTL(nullptr), - myLocation(nullptr), - myNetworkVersion(0), - myHaveSeenInternalEdge(false), - myAmLefthand(false), - myCornerDetail(0), - myLinkDetail(-1), - myRectLaneCut(false), - myWalkingAreas(false), - myLimitTurnSpeed(-1), - myCheckLaneFoesAll(false), - myCheckLaneFoesRoundabout(true), - myTlsIgnoreInternalJunctionJam(false), - myDefaultSpreadType(toString(LaneSpreadFunction::RIGHT)), - myGeomAvoidOverlap(true) -{ -} - - -NIImporter_SUMO::~NIImporter_SUMO() { - for (std::map::const_iterator i = myEdges.begin(); i != myEdges.end(); ++i) { - EdgeAttrs* ed = (*i).second; - for (std::vector::const_iterator j = ed->lanes.begin(); j != ed->lanes.end(); ++j) { - delete *j; - } - delete ed; - } - delete myLocation; - -} - - -void -NIImporter_SUMO::_loadNetwork(OptionsCont& oc) { - // check whether the option is set (properly) - if (!oc.isUsableFileList("sumo-net-file")) { - return; - } - const std::vector discardableParams = oc.getStringVector("discard-params"); - myDiscardableParams.insert(discardableParams.begin(), discardableParams.end()); - // parse file(s) - const std::vector files = oc.getStringVector("sumo-net-file"); - for (std::vector::const_iterator file = files.begin(); file != files.end(); ++file) { - if (!FileHelpers::isReadable(*file)) { - WRITE_ERROR("Could not open sumo-net-file '" + *file + "'."); - return; - } - setFileName(*file); - PROGRESS_BEGIN_MESSAGE("Parsing sumo-net from '" + *file + "'"); - XMLSubSys::runParser(*this, *file, true); - PROGRESS_DONE_MESSAGE(); - } - // build edges - const double maxSegmentLength = oc.getFloat("geometry.max-segment-length"); - for (std::map::const_iterator i = myEdges.begin(); i != myEdges.end(); ++i) { - EdgeAttrs* ed = (*i).second; - // skip internal edges - if (ed->func == SumoXMLEdgeFunc::INTERNAL || ed->func == SumoXMLEdgeFunc::CROSSING || ed->func == SumoXMLEdgeFunc::WALKINGAREA) { - continue; - } - // get and check the nodes - NBNode* from = myNodeCont.retrieve(ed->fromNode); - NBNode* to = myNodeCont.retrieve(ed->toNode); - if (from == nullptr) { - WRITE_ERROR("Edge's '" + ed->id + "' from-node '" + ed->fromNode + "' is not known."); - continue; - } - if (to == nullptr) { - WRITE_ERROR("Edge's '" + ed->id + "' to-node '" + ed->toNode + "' is not known."); - continue; - } - if (from == to) { - WRITE_ERROR("Edge's '" + ed->id + "' from-node and to-node '" + ed->toNode + "' are identical."); - continue; - } - if (ed->shape.size() == 0 && maxSegmentLength > 0) { - ed->shape.push_back(from->getPosition()); - ed->shape.push_back(to->getPosition()); - // shape is already cartesian but we must use a copy because the original will be modified - NBNetBuilder::addGeometrySegments(ed->shape, PositionVector(ed->shape), maxSegmentLength); - } - // build and insert the edge - NBEdge* e = new NBEdge(ed->id, from, to, - ed->type, ed->maxSpeed, - (int) ed->lanes.size(), - ed->priority, NBEdge::UNSPECIFIED_WIDTH, NBEdge::UNSPECIFIED_OFFSET, - ed->shape, ed->streetName, "", ed->lsf, true); // always use tryIgnoreNodePositions to keep original shape - e->setLoadedLength(ed->length); - e->updateParameters(ed->getParametersMap()); - e->setDistance(ed->distance); - if (!myNetBuilder.getEdgeCont().insert(e)) { - WRITE_ERROR("Could not insert edge '" + ed->id + "'."); - delete e; - continue; - } - ed->builtEdge = myNetBuilder.getEdgeCont().retrieve(ed->id); - if (ed->builtEdge != nullptr) { - ed->builtEdge->setStopOffsets(-1, ed->stopOffsets); - } - } - // assign further lane attributes (edges are built) - EdgeVector toRemove; - const bool dismissVclasses = oc.getBool("dismiss-vclasses"); - for (std::map::const_iterator i = myEdges.begin(); i != myEdges.end(); ++i) { - EdgeAttrs* ed = (*i).second; - NBEdge* nbe = ed->builtEdge; - if (nbe == nullptr) { // inner edge or removed by explicit list, vclass, ... - continue; - } - const SumoXMLNodeType toType = nbe->getToNode()->getType(); - for (int fromLaneIndex = 0; fromLaneIndex < (int) ed->lanes.size(); ++fromLaneIndex) { - LaneAttrs* lane = ed->lanes[fromLaneIndex]; - // connections - const std::vector& connections = lane->connections; - for (const Connection& c : connections) { - if (myEdges.count(c.toEdgeID) == 0) { - WRITE_ERROR("Unknown edge '" + c.toEdgeID + "' given in connection."); - continue; - } - NBEdge* toEdge = myEdges[c.toEdgeID]->builtEdge; - if (toEdge == nullptr) { // removed by explicit list, vclass, ... - continue; - } - if (nbe->hasConnectionTo(toEdge, c.toLaneIdx)) { - WRITE_WARNINGF("Target lane '%' has multiple connections from '%'.", toEdge->getLaneID(c.toLaneIdx), nbe->getID()); - } - // patch attribute uncontrolled for legacy networks where it is not set explicitly - bool uncontrolled = c.uncontrolled; - - if ((NBNode::isTrafficLight(toType) || toType == SumoXMLNodeType::RAIL_SIGNAL) - && c.tlLinkIndex == NBConnection::InvalidTlIndex) { - uncontrolled = true; - } - nbe->addLane2LaneConnection( - fromLaneIndex, toEdge, c.toLaneIdx, NBEdge::Lane2LaneInfoType::VALIDATED, - true, c.mayDefinitelyPass, c.keepClear, c.contPos, c.visibility, c.speed, c.customLength, c.customShape, uncontrolled, c.permissions); - if (c.getParametersMap().size() > 0) { - nbe->getConnectionRef(fromLaneIndex, toEdge, c.toLaneIdx).updateParameters(c.getParametersMap()); - } - // maybe we have a tls-controlled connection - if (c.tlID != "" && myRailSignals.count(c.tlID) == 0) { - const std::map& programs = myTLLCont.getPrograms(c.tlID); - if (programs.size() > 0) { - std::map::const_iterator it; - for (it = programs.begin(); it != programs.end(); it++) { - NBLoadedSUMOTLDef* tlDef = dynamic_cast(it->second); - if (tlDef) { - tlDef->addConnection(nbe, toEdge, fromLaneIndex, c.toLaneIdx, c.tlLinkIndex, c.tlLinkIndex2, false); - } else { - throw ProcessError("Corrupt traffic light definition '" + c.tlID + "' (program '" + it->first + "')"); - } - } - } else { - WRITE_ERROR("The traffic light '" + c.tlID + "' is not known."); - } - } - } - // allow/disallow XXX preferred - if (!dismissVclasses) { - nbe->setPermissions(parseVehicleClasses(lane->allow, lane->disallow, myNetworkVersion), fromLaneIndex); - } - // width, offset - nbe->setLaneWidth(fromLaneIndex, lane->width); - nbe->setEndOffset(fromLaneIndex, lane->endOffset); - nbe->setSpeed(fromLaneIndex, lane->maxSpeed); - nbe->setAcceleration(fromLaneIndex, lane->accelRamp); - nbe->getLaneStruct(fromLaneIndex).oppositeID = lane->oppositeID; - nbe->getLaneStruct(fromLaneIndex).type = lane->type; - nbe->getLaneStruct(fromLaneIndex).updateParameters(lane->getParametersMap()); - if (lane->customShape) { - nbe->setLaneShape(fromLaneIndex, lane->shape); - } - // stop offset for lane - bool stopOffsetSet = false; - if (lane->stopOffsets.size() != 0 || nbe->getStopOffsets().size() == 0) { - // apply lane-specific stopOffset (might be none as well) - stopOffsetSet = nbe->setStopOffsets(fromLaneIndex, lane->stopOffsets); - } - if (!stopOffsetSet) { - // apply default stop offset to lane - nbe->setStopOffsets(fromLaneIndex, nbe->getStopOffsets()); - } - } - nbe->declareConnectionsAsLoaded(); - if (!nbe->hasLaneSpecificWidth() && nbe->getLanes()[0].width != NBEdge::UNSPECIFIED_WIDTH) { - nbe->setLaneWidth(-1, nbe->getLaneWidth(0)); - } - if (!nbe->hasLaneSpecificEndOffset() && nbe->getEndOffset(0) != NBEdge::UNSPECIFIED_OFFSET) { - nbe->setEndOffset(-1, nbe->getEndOffset(0)); - } - if (!nbe->hasLaneSpecificStopOffsets() && nbe->getStopOffsets().size() != 0) { - nbe->setStopOffsets(-1, nbe->getStopOffsets()); - } - // check again after permissions are set - if (myNetBuilder.getEdgeCont().ignoreFilterMatch(nbe)) { - myNetBuilder.getEdgeCont().ignore(nbe->getID()); - toRemove.push_back(nbe); - } - } - for (EdgeVector::iterator i = toRemove.begin(); i != toRemove.end(); ++i) { - myNetBuilder.getEdgeCont().erase(myNetBuilder.getDistrictCont(), *i); - } - // insert loaded prohibitions - for (std::vector::const_iterator it = myProhibitions.begin(); it != myProhibitions.end(); it++) { - NBEdge* prohibitedFrom = myEdges[it->prohibitedFrom]->builtEdge; - NBEdge* prohibitedTo = myEdges[it->prohibitedTo]->builtEdge; - NBEdge* prohibitorFrom = myEdges[it->prohibitorFrom]->builtEdge; - NBEdge* prohibitorTo = myEdges[it->prohibitorTo]->builtEdge; - if (prohibitedFrom == nullptr) { - WRITE_WARNINGF("Edge '%' in prohibition was not built.", it->prohibitedFrom); - } else if (prohibitedTo == nullptr) { - WRITE_WARNINGF("Edge '%' in prohibition was not built.", it->prohibitedTo); - } else if (prohibitorFrom == nullptr) { - WRITE_WARNINGF("Edge '%' in prohibition was not built.", it->prohibitorFrom); - } else if (prohibitorTo == nullptr) { - WRITE_WARNINGF("Edge '%' in prohibition was not built.", it->prohibitorTo); - } else { - NBNode* n = prohibitedFrom->getToNode(); - n->addSortedLinkFoes( - NBConnection(prohibitorFrom, prohibitorTo), - NBConnection(prohibitedFrom, prohibitedTo)); - } - } - if (!myHaveSeenInternalEdge && oc.isDefault("no-internal-links")) { - oc.set("no-internal-links", "true"); - } - if (oc.isDefault("lefthand")) { - oc.set("lefthand", toString(myAmLefthand)); - } - if (oc.isDefault("junctions.corner-detail")) { - oc.set("junctions.corner-detail", toString(myCornerDetail)); - } - if (oc.isDefault("junctions.internal-link-detail") && myLinkDetail > 0) { - oc.set("junctions.internal-link-detail", toString(myLinkDetail)); - } - if (oc.isDefault("rectangular-lane-cut")) { - oc.set("rectangular-lane-cut", toString(myRectLaneCut)); - } - if (oc.isDefault("walkingareas")) { - oc.set("walkingareas", toString(myWalkingAreas)); - } - if (oc.isDefault("junctions.limit-turn-speed")) { - oc.set("junctions.limit-turn-speed", toString(myLimitTurnSpeed)); - } - if (oc.isDefault("check-lane-foes.all") && oc.getBool("check-lane-foes.all") != myCheckLaneFoesAll) { - oc.set("check-lane-foes.all", toString(myCheckLaneFoesAll)); - } - if (oc.isDefault("check-lane-foes.roundabout") && oc.getBool("check-lane-foes.roundabout") != myCheckLaneFoesRoundabout) { - oc.set("check-lane-foes.roundabout", toString(myCheckLaneFoesRoundabout)); - } - if (oc.isDefault("tls.ignore-internal-junction-jam") && oc.getBool("tls.ignore-internal-junction-jam") != myTlsIgnoreInternalJunctionJam) { - oc.set("tls.ignore-internal-junction-jam", toString(myTlsIgnoreInternalJunctionJam)); - } - if (oc.isDefault("default.spreadtype") && oc.getString("default.spreadtype") != myDefaultSpreadType) { - oc.set("default.spreadtype", myDefaultSpreadType); - } - if (oc.isDefault("geometry.avoid-overlap") && oc.getBool("geometry.avoid-overlap") != myGeomAvoidOverlap) { - oc.set("geometry.avoid-overlap", toString(myGeomAvoidOverlap)); - } - if (!deprecatedVehicleClassesSeen.empty()) { - WRITE_WARNING("Deprecated vehicle class(es) '" + toString(deprecatedVehicleClassesSeen) + "' in input network."); - deprecatedVehicleClassesSeen.clear(); - } - if (!oc.getBool("no-internal-links")) { - // add loaded crossings - for (std::map >::const_iterator it = myPedestrianCrossings.begin(); it != myPedestrianCrossings.end(); ++it) { - NBNode* node = myNodeCont.retrieve((*it).first); - for (std::vector::const_iterator it_c = (*it).second.begin(); it_c != (*it).second.end(); ++it_c) { - const Crossing& crossing = (*it_c); - EdgeVector edges; - for (std::vector::const_iterator it_e = crossing.crossingEdges.begin(); it_e != crossing.crossingEdges.end(); ++it_e) { - NBEdge* edge = myNetBuilder.getEdgeCont().retrieve(*it_e); - // edge might have been removed due to options - if (edge != nullptr) { - edges.push_back(edge); - } - } - if (edges.size() > 0) { - node->addCrossing(edges, crossing.width, crossing.priority, crossing.customTLIndex, crossing.customTLIndex2, crossing.customShape, true); - } - } - } - // add walking area custom shapes - for (auto item : myWACustomShapes) { - std::string nodeID = SUMOXMLDefinitions::getJunctionIDFromInternalEdge(item.first); - NBNode* node = myNodeCont.retrieve(nodeID); - std::vector edgeIDs; - if (item.second.fromEdges.size() + item.second.toEdges.size() == 0) { - // must be a split crossing - assert(item.second.fromCrossed.size() > 0); - assert(item.second.toCrossed.size() > 0); - edgeIDs = item.second.fromCrossed; - edgeIDs.insert(edgeIDs.end(), item.second.toCrossed.begin(), item.second.toCrossed.end()); - } else if (item.second.fromEdges.size() > 0) { - edgeIDs = item.second.fromEdges; - } else { - edgeIDs = item.second.toEdges; - } - EdgeVector edges; - for (std::string edgeID : edgeIDs) { - NBEdge* edge = myNetBuilder.getEdgeCont().retrieve(edgeID); - // edge might have been removed due to options - if (edge != nullptr) { - edges.push_back(edge); - } - } - if (edges.size() > 0) { - node->addWalkingAreaShape(edges, item.second.shape); - } - } - } - // add roundabouts - for (std::vector >::const_iterator it = myRoundabouts.begin(); it != myRoundabouts.end(); ++it) { - EdgeSet roundabout; - for (std::vector::const_iterator it_r = it->begin(); it_r != it->end(); ++it_r) { - NBEdge* edge = myNetBuilder.getEdgeCont().retrieve(*it_r); - if (edge == nullptr) { - if (!myNetBuilder.getEdgeCont().wasIgnored(*it_r)) { - WRITE_ERROR("Unknown edge '" + (*it_r) + "' in roundabout"); - } - } else { - roundabout.insert(edge); - } - } - myNetBuilder.getEdgeCont().addRoundabout(roundabout); - } -} - - - -void -NIImporter_SUMO::myStartElement(int element, - const SUMOSAXAttributes& attrs) { - /* our goal is to reproduce the input net faithfully - * there are different types of objects in the netfile: - * 1) those which must be loaded into NBNetBuilder-Containers for processing - * 2) those which can be ignored because they are recomputed based on group 1 - * 3) those which are of no concern to NBNetBuilder but should be exposed to - * NETEDIT. We will probably have to patch NBNetBuilder to contain them - * and hand them over to NETEDIT - * alternative idea: those shouldn't really be contained within the - * network but rather in separate files. teach NETEDIT how to open those - * (POI?) - * 4) those which are of concern neither to NBNetBuilder nor NETEDIT and - * must be copied over - need to patch NBNetBuilder for this. - * copy unknown by default - */ - switch (element) { - case SUMO_TAG_NET: { - bool ok; - myNetworkVersion = attrs.getOpt(SUMO_ATTR_VERSION, nullptr, ok, 0); - myAmLefthand = attrs.getOpt(SUMO_ATTR_LEFTHAND, nullptr, ok, false); - myCornerDetail = attrs.getOpt(SUMO_ATTR_CORNERDETAIL, nullptr, ok, 0); - myLinkDetail = attrs.getOpt(SUMO_ATTR_LINKDETAIL, nullptr, ok, -1); - myRectLaneCut = attrs.getOpt(SUMO_ATTR_RECTANGULAR_LANE_CUT, nullptr, ok, false); - myWalkingAreas = attrs.getOpt(SUMO_ATTR_WALKINGAREAS, nullptr, ok, false); - myLimitTurnSpeed = attrs.getOpt(SUMO_ATTR_LIMIT_TURN_SPEED, nullptr, ok, -1); - myWalkingAreas = attrs.getOpt(SUMO_ATTR_WALKINGAREAS, nullptr, ok, false); - myCheckLaneFoesAll = attrs.getOpt(SUMO_ATTR_CHECKLANEFOES_ALL, nullptr, ok, false); - myCheckLaneFoesRoundabout = attrs.getOpt(SUMO_ATTR_CHECKLANEFOES_ROUNDABOUT, nullptr, ok, true); - myTlsIgnoreInternalJunctionJam = attrs.getOpt(SUMO_ATTR_TLS_IGNORE_INTERNAL_JUNCTION_JAM, nullptr, ok, false); - myDefaultSpreadType = attrs.getOpt(SUMO_ATTR_SPREADTYPE, nullptr, ok, myDefaultSpreadType); - myGeomAvoidOverlap = attrs.getOpt(SUMO_ATTR_AVOID_OVERLAP, nullptr, ok, myGeomAvoidOverlap); - - break; - } - case SUMO_TAG_EDGE: - addEdge(attrs); - break; - case SUMO_TAG_LANE: - addLane(attrs); - break; - case SUMO_TAG_STOPOFFSET: { - bool ok = true; - addStopOffsets(attrs, ok); - } - break; - case SUMO_TAG_NEIGH: - myCurrentLane->oppositeID = attrs.getString(SUMO_ATTR_LANE); - break; - case SUMO_TAG_JUNCTION: - addJunction(attrs); - break; - case SUMO_TAG_REQUEST: - addRequest(attrs); - break; - case SUMO_TAG_CONNECTION: - addConnection(attrs); - break; - case SUMO_TAG_TLLOGIC: - myCurrentTL = initTrafficLightLogic(attrs, myCurrentTL); - if (myCurrentTL) { - myLastParameterised.push_back(myCurrentTL); - } - break; - case SUMO_TAG_PHASE: - addPhase(attrs, myCurrentTL); - break; - case SUMO_TAG_LOCATION: - myLocation = loadLocation(attrs); - break; - case SUMO_TAG_PROHIBITION: - addProhibition(attrs); - break; - case SUMO_TAG_ROUNDABOUT: - addRoundabout(attrs); - break; - case SUMO_TAG_PARAM: - if (myLastParameterised.size() != 0) { - bool ok = true; - const std::string key = attrs.get(SUMO_ATTR_KEY, nullptr, ok); - if (myDiscardableParams.count(key) == 0) { - // circumventing empty string test - const std::string val = attrs.hasAttribute(SUMO_ATTR_VALUE) ? attrs.getString(SUMO_ATTR_VALUE) : ""; - myLastParameterised.back()->setParameter(key, val); - } - } - break; - default: - myTypesHandler.myStartElement(element, attrs); - break; - } -} - - -void -NIImporter_SUMO::myEndElement(int element) { - switch (element) { - case SUMO_TAG_EDGE: - if (myCurrentEdge != nullptr) { - if (myEdges.find(myCurrentEdge->id) != myEdges.end()) { - WRITE_ERROR("Edge '" + myCurrentEdge->id + "' occurred at least twice in the input."); - } else { - myEdges[myCurrentEdge->id] = myCurrentEdge; - } - myCurrentEdge = nullptr; - myLastParameterised.pop_back(); - } - break; - case SUMO_TAG_LANE: - if (myCurrentEdge != nullptr && myCurrentLane != nullptr) { - myCurrentEdge->maxSpeed = MAX2(myCurrentEdge->maxSpeed, myCurrentLane->maxSpeed); - myCurrentEdge->lanes.push_back(myCurrentLane); - myLastParameterised.pop_back(); - } - myCurrentLane = nullptr; - break; - case SUMO_TAG_TLLOGIC: - if (!myCurrentTL) { - WRITE_ERROR("Unmatched closing tag for tl-logic."); - } else { - if (!myTLLCont.insert(myCurrentTL)) { - WRITE_WARNING("Could not add program '" + myCurrentTL->getProgramID() + "' for traffic light '" + myCurrentTL->getID() + "'"); - delete myCurrentTL; - } - myCurrentTL = nullptr; - myLastParameterised.pop_back(); - } - break; - case SUMO_TAG_JUNCTION: - if (myCurrentJunction.node != nullptr) { - myLastParameterised.pop_back(); - } - break; - case SUMO_TAG_CONNECTION: - // !!! this just avoids a crash but is not a real check that it was a connection - if (!myLastParameterised.empty()) { - myLastParameterised.pop_back(); - } - break; - default: - break; - } -} - - -void -NIImporter_SUMO::addEdge(const SUMOSAXAttributes& attrs) { - // get the id, report an error if not given or empty... - bool ok = true; - std::string id = attrs.get(SUMO_ATTR_ID, nullptr, ok); - if (!ok) { - return; - } - myCurrentEdge = new EdgeAttrs(); - myLastParameterised.push_back(myCurrentEdge); - myCurrentEdge->builtEdge = nullptr; - myCurrentEdge->id = id; - // get the function - myCurrentEdge->func = attrs.getEdgeFunc(ok); - if (myCurrentEdge->func == SumoXMLEdgeFunc::CROSSING) { - // add the crossing but don't do anything else - Crossing c(id); - c.crossingEdges = attrs.get >(SUMO_ATTR_CROSSING_EDGES, nullptr, ok); - myPedestrianCrossings[SUMOXMLDefinitions::getJunctionIDFromInternalEdge(id)].push_back(c); - return; - } else if (myCurrentEdge->func == SumoXMLEdgeFunc::INTERNAL || myCurrentEdge->func == SumoXMLEdgeFunc::WALKINGAREA) { - myHaveSeenInternalEdge = true; - return; // skip internal edges - } - // get the type - myCurrentEdge->type = attrs.getOpt(SUMO_ATTR_TYPE, id.c_str(), ok, ""); - // get the origin and the destination node - myCurrentEdge->fromNode = attrs.getOpt(SUMO_ATTR_FROM, id.c_str(), ok, ""); - myCurrentEdge->toNode = attrs.getOpt(SUMO_ATTR_TO, id.c_str(), ok, ""); - myCurrentEdge->priority = attrs.getOpt(SUMO_ATTR_PRIORITY, id.c_str(), ok, -1); - myCurrentEdge->type = attrs.getOpt(SUMO_ATTR_TYPE, id.c_str(), ok, ""); - myCurrentEdge->shape = attrs.getOpt(SUMO_ATTR_SHAPE, id.c_str(), ok, PositionVector()); - NBNetBuilder::transformCoordinates(myCurrentEdge->shape, true, myLocation); - myCurrentEdge->length = attrs.getOpt(SUMO_ATTR_LENGTH, id.c_str(), ok, NBEdge::UNSPECIFIED_LOADED_LENGTH); - myCurrentEdge->maxSpeed = 0; - myCurrentEdge->streetName = attrs.getOpt(SUMO_ATTR_NAME, id.c_str(), ok, ""); - myCurrentEdge->distance = attrs.getOpt(SUMO_ATTR_DISTANCE, id.c_str(), ok, 0); - if (myCurrentEdge->streetName != "" && OptionsCont::getOptions().isDefault("output.street-names")) { - OptionsCont::getOptions().set("output.street-names", "true"); - } - - std::string lsfS = attrs.getOpt(SUMO_ATTR_SPREADTYPE, id.c_str(), ok, myDefaultSpreadType); - if (SUMOXMLDefinitions::LaneSpreadFunctions.hasString(lsfS)) { - myCurrentEdge->lsf = SUMOXMLDefinitions::LaneSpreadFunctions.get(lsfS); - } else { - WRITE_ERROR("Unknown spreadType '" + lsfS + "' for edge '" + id + "'."); - } -} - - -void -NIImporter_SUMO::addLane(const SUMOSAXAttributes& attrs) { - bool ok = true; - std::string id = attrs.get(SUMO_ATTR_ID, nullptr, ok); - if (!ok) { - return; - } - if (!myCurrentEdge) { - WRITE_ERROR("Found lane '" + id + "' not within edge element."); - return; - } - const std::string expectedID = myCurrentEdge->id + "_" + toString(myCurrentEdge->lanes.size()); - if (id != expectedID) { - WRITE_WARNING("Renaming lane '" + id + "' to '" + expectedID + "'."); - } - myCurrentLane = new LaneAttrs(); - myLastParameterised.push_back(myCurrentLane); - myCurrentLane->customShape = attrs.getOpt(SUMO_ATTR_CUSTOMSHAPE, nullptr, ok, false); - myCurrentLane->shape = attrs.get(SUMO_ATTR_SHAPE, id.c_str(), ok); - myCurrentLane->type = attrs.getOpt(SUMO_ATTR_TYPE, id.c_str(), ok, ""); - if (myCurrentEdge->func == SumoXMLEdgeFunc::CROSSING) { - // save the width and the lane id of the crossing but don't do anything else - std::vector& crossings = myPedestrianCrossings[SUMOXMLDefinitions::getJunctionIDFromInternalEdge(myCurrentEdge->id)]; - assert(crossings.size() > 0); - crossings.back().width = attrs.get(SUMO_ATTR_WIDTH, id.c_str(), ok); - if (myCurrentLane->customShape) { - crossings.back().customShape = myCurrentLane->shape; - NBNetBuilder::transformCoordinates(crossings.back().customShape, true, myLocation); - } - } else if (myCurrentEdge->func == SumoXMLEdgeFunc::WALKINGAREA) { - // save custom shape if needed but don't do anything else - if (myCurrentLane->customShape) { - WalkingAreaParsedCustomShape wacs; - wacs.shape = myCurrentLane->shape; - NBNetBuilder::transformCoordinates(wacs.shape, true, myLocation); - myWACustomShapes[myCurrentEdge->id] = wacs; - } - return; - } else if (myCurrentEdge->func == SumoXMLEdgeFunc::INTERNAL) { - return; // skip internal edges - } - if (attrs.hasAttribute("maxspeed")) { - // !!! deprecated - myCurrentLane->maxSpeed = attrs.getFloat("maxspeed"); - } else { - myCurrentLane->maxSpeed = attrs.get(SUMO_ATTR_SPEED, id.c_str(), ok); - } - try { - myCurrentLane->allow = attrs.getOpt(SUMO_ATTR_ALLOW, id.c_str(), ok, "", false); - } catch (EmptyData&) { - // !!! deprecated - myCurrentLane->allow = ""; - } - myCurrentLane->disallow = attrs.getOpt(SUMO_ATTR_DISALLOW, id.c_str(), ok, ""); - myCurrentLane->width = attrs.getOpt(SUMO_ATTR_WIDTH, id.c_str(), ok, (double) NBEdge::UNSPECIFIED_WIDTH); - myCurrentLane->endOffset = attrs.getOpt(SUMO_ATTR_ENDOFFSET, id.c_str(), ok, (double) NBEdge::UNSPECIFIED_OFFSET); - myCurrentLane->accelRamp = attrs.getOpt(SUMO_ATTR_ACCELERATION, id.c_str(), ok, false); - // lane coordinates are derived (via lane spread) do not include them in convex boundary - NBNetBuilder::transformCoordinates(myCurrentLane->shape, false, myLocation); -} - - -void -NIImporter_SUMO::addStopOffsets(const SUMOSAXAttributes& attrs, bool& ok) { - std::map offsets = parseStopOffsets(attrs, ok); - if (!ok) { - return; - } - assert(offsets.size() == 1); - // Admissibility of value will be checked in _loadNetwork(), when lengths are known - if (myCurrentLane == nullptr) { - if (myCurrentEdge->stopOffsets.size() != 0) { - std::stringstream ss; - ss << "Duplicate definition of stopOffset for edge " << myCurrentEdge->id << ".\nIgnoring duplicate specification."; - WRITE_WARNING(ss.str()); - return; - } else { - myCurrentEdge->stopOffsets = offsets; - } - } else { - if (myCurrentLane->stopOffsets.size() != 0) { - std::stringstream ss; - ss << "Duplicate definition of lane's stopOffset on edge " << myCurrentEdge->id << ".\nIgnoring duplicate specifications."; - WRITE_WARNING(ss.str()); - return; - } else { - myCurrentLane->stopOffsets = offsets; - } - } -} - - -void -NIImporter_SUMO::addJunction(const SUMOSAXAttributes& attrs) { - // get the id, report an error if not given or empty... - myCurrentJunction.node = nullptr; - myCurrentJunction.intLanes.clear(); - myCurrentJunction.response.clear(); - bool ok = true; - std::string id = attrs.get(SUMO_ATTR_ID, nullptr, ok); - if (!ok) { - return; - } - if (id[0] == ':') { // internal node - return; - } - SumoXMLNodeType type = attrs.getNodeType(ok); - if (ok) { - if (type == SumoXMLNodeType::DEAD_END_DEPRECATED || type == SumoXMLNodeType::DEAD_END) { - // dead end is a computed status. Reset this to unknown so it will - // be corrected if additional connections are loaded - type = SumoXMLNodeType::UNKNOWN; - } - } else { - WRITE_WARNING("Unknown node type for junction '" + id + "'."); - } - Position pos = readPosition(attrs, id, ok); - NBNetBuilder::transformCoordinate(pos, true, myLocation); - NBNode* node = new NBNode(id, pos, type); - myLastParameterised.push_back(node); - if (!myNodeCont.insert(node)) { - WRITE_ERROR("Problems on adding junction '" + id + "'."); - delete node; - return; - } - myCurrentJunction.node = node; - myCurrentJunction.intLanes = attrs.get >(SUMO_ATTR_INTLANES, nullptr, ok, false); - // set optional radius - if (attrs.hasAttribute(SUMO_ATTR_RADIUS)) { - node->setRadius(attrs.get(SUMO_ATTR_RADIUS, id.c_str(), ok)); - } - // handle custom shape - if (attrs.getOpt(SUMO_ATTR_CUSTOMSHAPE, nullptr, ok, false)) { - PositionVector shape = attrs.get(SUMO_ATTR_SHAPE, id.c_str(), ok); - NBNetBuilder::transformCoordinates(shape); - node->setCustomShape(shape); - } - if (type == SumoXMLNodeType::RAIL_SIGNAL || type == SumoXMLNodeType::RAIL_CROSSING) { - // both types of nodes come without a tlLogic - myRailSignals.insert(id); - } - if (attrs.hasAttribute(SUMO_ATTR_RIGHT_OF_WAY)) { - node->setRightOfWay(attrs.getRightOfWay(ok)); - } - if (attrs.hasAttribute(SUMO_ATTR_FRINGE)) { - node->setFringeType(attrs.getFringeType(ok)); - } - if (attrs.hasAttribute(SUMO_ATTR_NAME)) { - node->setName(attrs.get(SUMO_ATTR_NAME, id.c_str(), ok)); - } -} - - -void -NIImporter_SUMO::addRequest(const SUMOSAXAttributes& attrs) { - if (myCurrentJunction.node != nullptr) { - bool ok = true; - myCurrentJunction.response.push_back(attrs.get(SUMO_ATTR_RESPONSE, nullptr, ok)); - } -} - - -void -NIImporter_SUMO::addConnection(const SUMOSAXAttributes& attrs) { - bool ok = true; - std::string fromID = attrs.get(SUMO_ATTR_FROM, nullptr, ok); - if (myEdges.count(fromID) == 0) { - WRITE_ERROR("Unknown edge '" + fromID + "' given in connection."); - return; - } - EdgeAttrs* from = myEdges[fromID]; - Connection conn; - conn.toEdgeID = attrs.get(SUMO_ATTR_TO, nullptr, ok); - int fromLaneIdx = attrs.get(SUMO_ATTR_FROM_LANE, nullptr, ok); - conn.toLaneIdx = attrs.get(SUMO_ATTR_TO_LANE, nullptr, ok); - conn.tlID = attrs.getOpt(SUMO_ATTR_TLID, nullptr, ok, ""); - conn.mayDefinitelyPass = attrs.getOpt(SUMO_ATTR_PASS, nullptr, ok, false); - conn.keepClear = attrs.getOpt(SUMO_ATTR_KEEP_CLEAR, nullptr, ok, true); - conn.contPos = attrs.getOpt(SUMO_ATTR_CONTPOS, nullptr, ok, NBEdge::UNSPECIFIED_CONTPOS); - conn.visibility = attrs.getOpt(SUMO_ATTR_VISIBILITY_DISTANCE, nullptr, ok, NBEdge::UNSPECIFIED_VISIBILITY_DISTANCE); - std::string allow = attrs.getOpt(SUMO_ATTR_ALLOW, nullptr, ok, "", false); - std::string disallow = attrs.getOpt(SUMO_ATTR_DISALLOW, nullptr, ok, "", false); - if (allow == "" && disallow == "") { - conn.permissions = SVC_UNSPECIFIED; - } else { - conn.permissions = parseVehicleClasses(allow, disallow, myNetworkVersion); - } - conn.speed = attrs.getOpt(SUMO_ATTR_SPEED, nullptr, ok, NBEdge::UNSPECIFIED_SPEED); - conn.customLength = attrs.getOpt(SUMO_ATTR_LENGTH, nullptr, ok, NBEdge::UNSPECIFIED_LOADED_LENGTH); - conn.customShape = attrs.getOpt(SUMO_ATTR_SHAPE, nullptr, ok, PositionVector::EMPTY); - NBNetBuilder::transformCoordinates(conn.customShape, false, myLocation); - conn.uncontrolled = attrs.getOpt(SUMO_ATTR_UNCONTROLLED, nullptr, ok, NBEdge::UNSPECIFIED_CONNECTION_UNCONTROLLED, false); - if (conn.tlID != "") { - conn.tlLinkIndex = attrs.get(SUMO_ATTR_TLLINKINDEX, nullptr, ok); - conn.tlLinkIndex2 = attrs.getOpt(SUMO_ATTR_TLLINKINDEX2, nullptr, ok, -1); - } else { - conn.tlLinkIndex = NBConnection::InvalidTlIndex; - } - if ((int)from->lanes.size() <= fromLaneIdx) { - WRITE_ERROR("Invalid lane index '" + toString(fromLaneIdx) + "' for connection from '" + fromID + "'."); - return; - } - from->lanes[fromLaneIdx]->connections.push_back(conn); - myLastParameterised.push_back(&from->lanes[fromLaneIdx]->connections.back()); - - // determine crossing priority and tlIndex - if (myPedestrianCrossings.size() > 0) { - if (from->func == SumoXMLEdgeFunc::WALKINGAREA && myEdges[conn.toEdgeID]->func == SumoXMLEdgeFunc::CROSSING) { - // connection from walkingArea to crossing - std::vector& crossings = myPedestrianCrossings[SUMOXMLDefinitions::getJunctionIDFromInternalEdge(fromID)]; - for (std::vector::iterator it = crossings.begin(); it != crossings.end(); ++it) { - if (conn.toEdgeID == (*it).edgeID) { - if (conn.tlID != "") { - (*it).priority = true; - (*it).customTLIndex = conn.tlLinkIndex; - } else { - LinkState state = SUMOXMLDefinitions::LinkStates.get(attrs.get(SUMO_ATTR_STATE, nullptr, ok)); - (*it).priority = state == LINKSTATE_MAJOR; - } - } - } - } else if (from->func == SumoXMLEdgeFunc::CROSSING && myEdges[conn.toEdgeID]->func == SumoXMLEdgeFunc::WALKINGAREA) { - // connection from crossing to walkingArea (set optional linkIndex2) - for (Crossing& c : myPedestrianCrossings[SUMOXMLDefinitions::getJunctionIDFromInternalEdge(fromID)]) { - if (fromID == c.edgeID) { - c.customTLIndex2 = attrs.getOpt(SUMO_ATTR_TLLINKINDEX, nullptr, ok, -1); - } - } - } - } - // determine walking area reference edges - if (myWACustomShapes.size() > 0) { - EdgeAttrs* to = myEdges[conn.toEdgeID]; - if (from->func == SumoXMLEdgeFunc::WALKINGAREA) { - std::map::iterator it = myWACustomShapes.find(fromID); - if (it != myWACustomShapes.end()) { - if (to->func == SumoXMLEdgeFunc::NORMAL) { - // add target sidewalk as reference - it->second.toEdges.push_back(conn.toEdgeID); - } else if (to->func == SumoXMLEdgeFunc::CROSSING) { - // add target crossing edges as reference - for (Crossing crossing : myPedestrianCrossings[SUMOXMLDefinitions::getJunctionIDFromInternalEdge(fromID)]) { - if (conn.toEdgeID == crossing.edgeID) { - it->second.toCrossed.insert(it->second.toCrossed.end(), crossing.crossingEdges.begin(), crossing.crossingEdges.end()); - } - } - } - } - } else if (to->func == SumoXMLEdgeFunc::WALKINGAREA) { - std::map::iterator it = myWACustomShapes.find(conn.toEdgeID); - if (it != myWACustomShapes.end()) { - if (from->func == SumoXMLEdgeFunc::NORMAL) { - // add origin sidewalk as reference - it->second.fromEdges.push_back(fromID); - } else if (from->func == SumoXMLEdgeFunc::CROSSING) { - // add origin crossing edges as reference - for (Crossing crossing : myPedestrianCrossings[SUMOXMLDefinitions::getJunctionIDFromInternalEdge(fromID)]) { - if (fromID == crossing.edgeID) { - it->second.fromCrossed.insert(it->second.fromCrossed.end(), crossing.crossingEdges.begin(), crossing.crossingEdges.end()); - } - } - } - } - } - } -} - - -void -NIImporter_SUMO::addProhibition(const SUMOSAXAttributes& attrs) { - bool ok = true; - std::string prohibitor = attrs.getOpt(SUMO_ATTR_PROHIBITOR, nullptr, ok, ""); - std::string prohibited = attrs.getOpt(SUMO_ATTR_PROHIBITED, nullptr, ok, ""); - if (!ok) { - return; - } - Prohibition p; - parseProhibitionConnection(prohibitor, p.prohibitorFrom, p.prohibitorTo, ok); - parseProhibitionConnection(prohibited, p.prohibitedFrom, p.prohibitedTo, ok); - if (!ok) { - return; - } - myProhibitions.push_back(p); -} - - -NIImporter_SUMO::LaneAttrs* -NIImporter_SUMO::getLaneAttrsFromID(EdgeAttrs* edge, std::string lane_id) { - std::string edge_id; - int index; - NBHelpers::interpretLaneID(lane_id, edge_id, index); - assert(edge->id == edge_id); - if ((int)edge->lanes.size() <= index) { - WRITE_ERROR("Unknown lane '" + lane_id + "' given in succedge."); - return nullptr; - } else { - return edge->lanes[index]; - } -} - - -NBLoadedSUMOTLDef* -NIImporter_SUMO::initTrafficLightLogic(const SUMOSAXAttributes& attrs, NBLoadedSUMOTLDef* currentTL) { - if (currentTL) { - WRITE_ERROR("Definition of tl-logic '" + currentTL->getID() + "' was not finished."); - return nullptr; - } - bool ok = true; - std::string id = attrs.get(SUMO_ATTR_ID, nullptr, ok); - SUMOTime offset = TIME2STEPS(attrs.get(SUMO_ATTR_OFFSET, id.c_str(), ok)); - std::string programID = attrs.getOpt(SUMO_ATTR_PROGRAMID, id.c_str(), ok, ""); - std::string typeS = attrs.get(SUMO_ATTR_TYPE, nullptr, ok); - TrafficLightType type; - if (SUMOXMLDefinitions::TrafficLightTypes.hasString(typeS)) { - type = SUMOXMLDefinitions::TrafficLightTypes.get(typeS); - } else { - WRITE_ERROR("Unknown traffic light type '" + typeS + "' for tlLogic '" + id + "'."); - return nullptr; - } - if (ok) { - return new NBLoadedSUMOTLDef(id, programID, offset, type); - } else { - return nullptr; - } -} - - -void -NIImporter_SUMO::addPhase(const SUMOSAXAttributes& attrs, NBLoadedSUMOTLDef* currentTL) { - if (!currentTL) { - WRITE_ERROR("found phase without tl-logic"); - return; - } - const std::string& id = currentTL->getID(); - bool ok = true; - std::string state = attrs.get(SUMO_ATTR_STATE, id.c_str(), ok); - SUMOTime duration = TIME2STEPS(attrs.get(SUMO_ATTR_DURATION, id.c_str(), ok)); - if (duration < 0) { - WRITE_ERROR("Phase duration for tl-logic '" + id + "/" + currentTL->getProgramID() + "' must be positive."); - return; - } - // if the traffic light is an actuated traffic light, try to get - // the minimum and maximum durations - SUMOTime minDuration = attrs.getOptSUMOTimeReporting(SUMO_ATTR_MINDURATION, id.c_str(), ok, NBTrafficLightDefinition::UNSPECIFIED_DURATION); - SUMOTime maxDuration = attrs.getOptSUMOTimeReporting(SUMO_ATTR_MAXDURATION, id.c_str(), ok, NBTrafficLightDefinition::UNSPECIFIED_DURATION); - std::vector nextPhases = attrs.getOptIntVector(SUMO_ATTR_NEXT, nullptr, ok); - const std::string name = attrs.getOpt(SUMO_ATTR_NAME, nullptr, ok, ""); - if (ok) { - currentTL->addPhase(duration, state, minDuration, maxDuration, nextPhases, name); - } -} - - -GeoConvHelper* -NIImporter_SUMO::loadLocation(const SUMOSAXAttributes& attrs) { - // @todo refactor parsing of location since its duplicated in NLHandler and PCNetProjectionLoader - bool ok = true; - GeoConvHelper* result = nullptr; - PositionVector s = attrs.get(SUMO_ATTR_NET_OFFSET, nullptr, ok); - Boundary convBoundary = attrs.get(SUMO_ATTR_CONV_BOUNDARY, nullptr, ok); - Boundary origBoundary = attrs.get(SUMO_ATTR_ORIG_BOUNDARY, nullptr, ok); - std::string proj = attrs.get(SUMO_ATTR_ORIG_PROJ, nullptr, ok); - if (ok) { - Position networkOffset = s[0]; - result = new GeoConvHelper(proj, networkOffset, origBoundary, convBoundary); - GeoConvHelper::setLoaded(*result); - } - return result; -} - - -Position -NIImporter_SUMO::readPosition(const SUMOSAXAttributes& attrs, const std::string& id, bool& ok) { - const double x = attrs.get(SUMO_ATTR_X, id.c_str(), ok); - const double y = attrs.get(SUMO_ATTR_Y, id.c_str(), ok); - const double z = attrs.getOpt(SUMO_ATTR_Z, id.c_str(), ok, 0.); - return Position(x, y, z); -} - - -void -NIImporter_SUMO::parseProhibitionConnection(const std::string& attr, std::string& from, std::string& to, bool& ok) { - // split from/to - const std::string::size_type div = attr.find("->"); - if (div == std::string::npos) { - WRITE_ERROR("Missing connection divider in prohibition attribute '" + attr + "'"); - ok = false; - } - from = attr.substr(0, div); - to = attr.substr(div + 2); - // check whether the definition includes a lane information and discard it - if (from.find('_') != std::string::npos) { - from = from.substr(0, from.find('_')); - } - if (to.find('_') != std::string::npos) { - to = to.substr(0, to.find('_')); - } - // check whether the edges are known - if (myEdges.count(from) == 0) { - WRITE_ERROR("Unknown edge prohibition '" + from + "'"); - ok = false; - } - if (myEdges.count(to) == 0) { - WRITE_ERROR("Unknown edge prohibition '" + to + "'"); - ok = false; - } -} - - -void -NIImporter_SUMO::addRoundabout(const SUMOSAXAttributes& attrs) { - if (attrs.hasAttribute(SUMO_ATTR_EDGES)) { - myRoundabouts.push_back(attrs.getStringVector(SUMO_ATTR_EDGES)); - } else { - WRITE_ERROR("Empty edges in roundabout."); - } -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/NIImporter_SUMO.h b/Util/OSM2ODR/src/netimport/NIImporter_SUMO.h deleted file mode 100644 index e0461b943..000000000 --- a/Util/OSM2ODR/src/netimport/NIImporter_SUMO.h +++ /dev/null @@ -1,423 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIImporter_SUMO.h -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date Mon, 14.04.2008 -/// -// Importer for networks stored in SUMO format -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include -#include -#include -#include -#include "NIXMLTypesHandler.h" - - -// =========================================================================== -// class declarations -// =========================================================================== -class NBNetBuilder; -class NBEdge; -class OptionsCont; - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NIImporter_SUMO - * @brief Importer for networks stored in SUMO format - * - */ -class NIImporter_SUMO : public SUMOSAXHandler { -public: - /** @brief Loads content of the optionally given SUMO file - * - * If the option "sumo-net-file" is set, the file stored therein is read and - * the network definition stored therein is stored within the given network - * builder. - * - * If the option "sumo-net-file" is not set, this method simply returns. - * - * The loading is done by parsing the network definition as an XML file - * using the SAXinterface and handling the incoming data via this class' - * methods. - * - * @param[in,out] oc The options to use (option no-internal-links may be modified) - * @param[in] nb The network builder to fill - */ - static void loadNetwork(OptionsCont& oc, NBNetBuilder& nb); - - /// begins the reading of a traffic lights logic - static NBLoadedSUMOTLDef* initTrafficLightLogic(const SUMOSAXAttributes& attrs, NBLoadedSUMOTLDef* currentTL); - - /// adds a phase to the traffic lights logic currently build - static void addPhase(const SUMOSAXAttributes& attrs, NBLoadedSUMOTLDef* currentTL); - - /// Parses network location description and registers it with GeoConveHelper::setLoaded - static GeoConvHelper* loadLocation(const SUMOSAXAttributes& attrs); - -protected: - /** @brief Constructor - * @param[in] nc The network builder to fill - */ - NIImporter_SUMO(NBNetBuilder& nb); - - /// @brief Destructor - ~NIImporter_SUMO(); - - /// @name inherited from GenericSAXHandler - //@{ - - /** @brief Called on the opening of a tag; - * - * In dependence to the obtained type, an appropriate parsing - * method is called ("addEdge" if an edge encounters, f.e.). - * - * @param[in] element ID of the currently opened element - * @param[in] attrs Attributes within the currently opened element - * @exception ProcessError If something fails - * @see GenericSAXHandler::myStartElement - */ - void myStartElement(int element, - const SUMOSAXAttributes& attrs); - - - /** @brief Called when a closing tag occurs - * - * @param[in] element ID of the currently opened element - * @exception ProcessError If something fails - * @see GenericSAXHandler::myEndElement - */ - void myEndElement(int element); - //@} - - -private: - /// @brief load the network - void _loadNetwork(OptionsCont& oc); - - /// @name Object instance parsing methods - //@{ - - /** @brief Parses an edge and stores the values in "myCurrentEdge" - * @param[in] attrs The attributes to get the edge's values from - */ - void addEdge(const SUMOSAXAttributes& attrs); - - - /** @brief Parses a lane and stores the values in "myCurrentLane" - * @param[in] attrs The attributes to get the lane's values from - */ - void addLane(const SUMOSAXAttributes& attrs); - - /** @brief parses stop offsets for the current lane or edge - * @param[in] attrs The attributes to get the stop offset sepcifics from - */ - void addStopOffsets(const SUMOSAXAttributes& attrs, bool& ok); - - /** @brief Parses a junction and saves it in the node control - * @param[in] attrs The attributes to get the junction's values from - */ - void addJunction(const SUMOSAXAttributes& attrs); - - - /** @brief Parses a reques and saves selected attributes in myCurrentJunction - * @param[in] attrs The attributes to get the junction's values from - */ - void addRequest(const SUMOSAXAttributes& attrs); - - - /** @brief Parses a connection and saves it - * into the lane's definition stored in "myCurrentLane" - * @param[in] attrs The attributes to get the connection from - */ - void addConnection(const SUMOSAXAttributes& attrs); - - /** @brief Parses a prohibition and saves it - * @param[in] attrs The attributes to get the connection from - */ - void addProhibition(const SUMOSAXAttributes& attrs); - - /** @brief Parses a roundabout and stores it in myEdgeCont. - * @param[in] attrs The attributes to get the roundabouts values from - */ - void addRoundabout(const SUMOSAXAttributes& attrs); - - //@} - - - -private: - /** - * @struct Connection - * @brief A connection description. - */ - struct Connection : public Parameterised { - /// @brief The id of the target edge - std::string toEdgeID; - /// @brief The index of the target lane - int toLaneIdx; - /// @brief The id of the traffic light that controls this connection - std::string tlID; - /// @brief The index of this connection within the controlling traffic light - int tlLinkIndex; - int tlLinkIndex2; - /// @brief Information about being definitely free to drive (on-ramps) - bool mayDefinitelyPass; - /// @brief Whether the junction must be kept clear coming from this connection - bool keepClear; - /// @brief custom position for internal junction on this connection - double contPos; - /// @brief custom foe visibility for connection - double visibility; - /// @brief custom permissions for connection - SVCPermissions permissions; - /// @brief custom speed for connection - double speed; - /// @brief custom length for connection - double customLength; - /// @brief custom shape connection - PositionVector customShape; - /// @brief if set to true, This connection will not be TLS-controlled despite its node being controlled. - bool uncontrolled; - }; - - - /** @struct LaneAttrs - * @brief Describes the values found in a lane's definition - */ - struct LaneAttrs : public Parameterised { - /// @brief The maximum velocity allowed on this lane - double maxSpeed; - /// @brief This lane's shape (may be custom) - PositionVector shape; - /// @brief This lane's connections - std::vector connections; - /// @brief This lane's allowed vehicle classes - std::string allow; - /// @brief This lane's disallowed vehicle classes - std::string disallow; - /// @brief The width of this lane - double width; - /// @brief This lane's offset from the intersection - double endOffset; - /// @brief This lane's vehicle specific stop offsets - std::map stopOffsets; - /// @brief Whether this lane is an acceleration lane - bool accelRamp; - /// @brief This lane's opposite lane - std::string oppositeID; - /// @brief Whether this lane has a custom shape - bool customShape; - /// @brief the type of this lane - std::string type; - }; - - - /** @struct EdgeAttrs - * @brief Describes the values found in an edge's definition and this edge's lanes - */ - struct EdgeAttrs : public Parameterised { - /// @brief This edge's id - std::string id; - /// @brief This edge's street name - std::string streetName; - /// @brief This edge's type - std::string type; - /// @brief This edge's function - SumoXMLEdgeFunc func; - /// @brief The node this edge starts at - std::string fromNode; - /// @brief The node this edge ends at - std::string toNode; - /// @brief This edges's shape - PositionVector shape; - /// @brief The length of the edge if set explicitly - double length; - /// @brief This edge's priority - int priority; - /// @brief The maximum velocity allowed on this edge (!!!) - double maxSpeed; - /// @brief This edge's lanes - std::vector lanes; - /// @brief The built edge - NBEdge* builtEdge; - /// @brief The lane spread function - LaneSpreadFunction lsf; - /// @brief This edge's vehicle specific stop offsets (used for lanes, that do not have a specified stopOffset) - std::map stopOffsets; - /// @brief The position at the start of this edge (kilometrage/mileage) - double distance; - }; - - - /** @struct Prohibition - * @brief Describes the values found in a prohibition - */ - struct Prohibition { - std::string prohibitorFrom; - std::string prohibitorTo; - std::string prohibitedFrom; - std::string prohibitedTo; - }; - - /** @struct Crossing - * @brief Describes a pedestrian crossing - */ - struct Crossing { - Crossing(const std::string& _edgeID) : - edgeID(_edgeID), customTLIndex(-1), customTLIndex2(-1) {} - - std::string edgeID; - std::vector crossingEdges; - double width; - bool priority; - PositionVector customShape; - int customTLIndex; - int customTLIndex2; - }; - - /** @struct WalkingAreaParsedCustomShape - * @brief Describes custom shape for a walking area during parsing - */ - struct WalkingAreaParsedCustomShape { - PositionVector shape; - std::vector fromEdges; - std::vector toEdges; - std::vector fromCrossed; - std::vector toCrossed; - }; - - /** @struct JunctionAttrs - * @brief Describes the values found in a junction - */ - struct JunctionAttrs { - NBNode* node; - // @the list of internal lanes corresponding to each link - std::vector intLanes; - // @brief the complete response definition for all links - std::vector response; - }; - - /// @brief Loaded edge definitions - std::map myEdges; - - /// @brief Loaded prohibitions - std::vector myProhibitions; - - /// @brief The network builder to fill - NBNetBuilder& myNetBuilder; - - /// @brief The node container to fill - NBNodeCont& myNodeCont; - - /// @brief The node container to fill - NBTrafficLightLogicCont& myTLLCont; - - /// @brief The handler for parsing edge types and restrictions - NIXMLTypesHandler myTypesHandler; - - /// @brief The currently parsed edge's definition (to add loaded lanes to) - EdgeAttrs* myCurrentEdge; - - /// @brief The currently parsed junction definition to help in reconstructing crossings - JunctionAttrs myCurrentJunction; - - /// @brief The currently parsed lanes's definition (to add the shape to) - LaneAttrs* myCurrentLane; - - /// @brief The currently parsed traffic light - NBLoadedSUMOTLDef* myCurrentTL; - - /// @brief The coordinate transformation which was used to build the loaded network. - GeoConvHelper* myLocation; - - /// @brief The pedestrian crossings found in the network - std::map > myPedestrianCrossings; - - /// @brief Map from walkingArea edge IDs to custom shapes - std::map myWACustomShapes; - - /// @brief element to receive parameters - std::vector myLastParameterised; - - /// @brief the loaded network version - double myNetworkVersion; - - /// @brief whether the loaded network contains internal lanes - bool myHaveSeenInternalEdge; - - /// @brief whether the loaded network was built for lefthand traffic - bool myAmLefthand; - - /// @brief the level of corner detail in the loaded network - int myCornerDetail; - - /// @brief the level of geometry detail for internal lanes in the loaded network - int myLinkDetail; - - /// @brief whether all lanes of an edge should have the same stop line - bool myRectLaneCut; - - /// @brief whether walkingareas must be built - bool myWalkingAreas; - - /// @brief whether turning speed was limited in the network - double myLimitTurnSpeed; - - /// @brief whether foe-relationships where checked at lane-level - bool myCheckLaneFoesAll; - bool myCheckLaneFoesRoundabout; - /// @brief whether some right-of-way checks at traffic light junctions should be disabled - bool myTlsIgnoreInternalJunctionJam; - /// @brief default spreadType defined in the network - std::string myDefaultSpreadType; - /// @brief overlap option for loaded network - bool myGeomAvoidOverlap; - - /// @brief loaded roundabout edges - std::vector > myRoundabouts; - - /// @brief list of node id with rail signals (no NBTrafficLightDefinition exists) - std::set myRailSignals; - - /// @brief list of parameter keys to discard - std::set myDiscardableParams; - -private: - /** @brief Parses lane index from lane ID an retrieve lane from EdgeAttrs - * @param[in] edge The EdgeAttrs* which should contain the lane - * @param[in] lane_id The ID of the lane - */ - LaneAttrs* getLaneAttrsFromID(EdgeAttrs* edge, std::string lane_id); - - /// @brief read position from the given attributes, attribute errors to id - static Position readPosition(const SUMOSAXAttributes& attrs, const std::string& id, bool& ok); - - /** @brief parses connection string of a prohibition (very old school) - * @param[in] attr The connection attribute - * @param[out] from ID of the source edge - * @param[out] to ID of the destination edge - * @param[out] ok Whether parsing completed successfully - */ - void parseProhibitionConnection(const std::string& attr, std::string& from, std::string& to, bool& ok); -}; diff --git a/Util/OSM2ODR/src/netimport/NIImporter_VISUM.cpp b/Util/OSM2ODR/src/netimport/NIImporter_VISUM.cpp deleted file mode 100644 index 9b7df06c1..000000000 --- a/Util/OSM2ODR/src/netimport/NIImporter_VISUM.cpp +++ /dev/null @@ -1,1512 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIImporter_VISUM.cpp -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Sascha Krieg -/// @author Michael Behrisch -/// @date Fri, 19 Jul 2002 -/// -// A VISUM network importer -/****************************************************************************/ -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include "NILoader.h" -#include "NIImporter_VISUM.h" - - -StringBijection::Entry NIImporter_VISUM::KEYS_DE[] = { - { "VSYS", VISUM_SYS }, - { "STRECKENTYP", VISUM_LINKTYPE }, - { "KNOTEN", VISUM_NODE }, - { "BEZIRK", VISUM_DISTRICT }, - { "PUNKT", VISUM_POINT }, - { "STRECKE", VISUM_LINK }, - { "V0IV", VISUM_V0 }, - { "VSYSSET", VISUM_TYPES }, - { "RANG", VISUM_RANK }, - { "KAPIV", VISUM_CAPACITY }, - { "XKOORD", VISUM_XCOORD }, - { "YKOORD", VISUM_YCOORD }, - { "ID", VISUM_ID }, - { "CODE", VISUM_CODE }, - { "VONKNOTNR", VISUM_FROMNODE }, - { "NACHKNOTNR", VISUM_TONODE }, - { "TYPNR", VISUM_TYPE }, - { "TYP", VISUM_TYP }, - { "ANBINDUNG", VISUM_DISTRICT_CONNECTION }, - { "BEZNR", VISUM_SOURCE_DISTRICT }, - { "KNOTNR", VISUM_FROMNODENO }, - { "RICHTUNG", VISUM_DIRECTION }, - { "FLAECHEID", VISUM_SURFACEID }, - { "TFLAECHEID", VISUM_FACEID }, - { "VONPUNKTID", VISUM_FROMPOINTID }, - { "NACHPUNKTID", VISUM_TOPOINTID }, - { "KANTE", VISUM_EDGE }, - { "ABBIEGER", VISUM_TURN }, - { "UEBERKNOTNR", VISUM_VIANODENO }, - { "ANZFAHRSTREIFEN", VISUM_NUMLANES }, - { "INDEX", VISUM_INDEX }, - { "STRECKENPOLY", VISUM_LINKPOLY }, - { "FLAECHENELEMENT", VISUM_SURFACEITEM }, - { "TEILFLAECHENELEMENT", VISUM_FACEITEM }, - { "KANTEID", VISUM_EDGEID }, - { "Q", VISUM_ORIGIN }, - { "Z", VISUM_DESTINATION }, - { "NR", VISUM_NO } // must be the last one -}; - - - -StringBijection NIImporter_VISUM::KEYS(NIImporter_VISUM::KEYS_DE, VISUM_NO); - -// =========================================================================== -// method definitions -// =========================================================================== -// --------------------------------------------------------------------------- -// static methods (interface in this case) -// --------------------------------------------------------------------------- -void -NIImporter_VISUM::loadNetwork(const OptionsCont& oc, NBNetBuilder& nb) { - // check whether the option is set (properly) - if (!oc.isSet("visum-file")) { - return; - } - // build the handler - NIImporter_VISUM loader(nb, oc.getString("visum-file"), - NBCapacity2Lanes(oc.getFloat("lanes-from-capacity.norm")), - oc.getBool("visum.use-type-priority"), - oc.getString("visum.language-file")); - loader.load(); -} - - - -// --------------------------------------------------------------------------- -// loader methods -// --------------------------------------------------------------------------- -NIImporter_VISUM::NIImporter_VISUM(NBNetBuilder& nb, - const std::string& file, - NBCapacity2Lanes capacity2Lanes, - bool useVisumPrio, - const std::string& languageFile) : - myNetBuilder(nb), myFileName(file), - myCapacity2Lanes(capacity2Lanes), myUseVisumPrio(useVisumPrio) { - if (languageFile != "") { - loadLanguage(languageFile); - } - - // the order of process is important! - // set1 - addParser(KEYS.getString(VISUM_SYS), &NIImporter_VISUM::parse_VSysTypes); - addParser(KEYS.getString(VISUM_LINKTYPE), &NIImporter_VISUM::parse_Types); - addParser(KEYS.getString(VISUM_NODE), &NIImporter_VISUM::parse_Nodes); - addParser(KEYS.getString(VISUM_DISTRICT), &NIImporter_VISUM::parse_Districts); - addParser(KEYS.getString(VISUM_POINT), &NIImporter_VISUM::parse_Point); - - // set2 - // two types of "strecke" - addParser(KEYS.getString(VISUM_LINK), &NIImporter_VISUM::parse_Edges); - addParser(KEYS.getString(VISUM_EDGE), &NIImporter_VISUM::parse_Kante); - - // set3 - if (OptionsCont::getOptions().getBool("visum.no-connectors")) { - addParser(KEYS.getString(VISUM_DISTRICT_CONNECTION), &NIImporter_VISUM::parse_Connectors); - } else { - addParser(KEYS.getString(VISUM_DISTRICT_CONNECTION), &NIImporter_VISUM::parse_Connectors_legacy); - } - // two types of "abbieger" - addParser("ABBIEGEBEZIEHUNG", &NIImporter_VISUM::parse_Turns); - addParser(KEYS.getString(VISUM_TURN), &NIImporter_VISUM::parse_Turns); - - addParser(KEYS.getString(VISUM_LINKPOLY), &NIImporter_VISUM::parse_EdgePolys); - addParser("FAHRSTREIFEN", &NIImporter_VISUM::parse_Lanes); - addParser(KEYS.getString(VISUM_SURFACEITEM), &NIImporter_VISUM::parse_PartOfArea); - - - // set4 - // two types of lsa - addParser("LSA", &NIImporter_VISUM::parse_TrafficLights); - addParser("SIGNALANLAGE", &NIImporter_VISUM::parse_TrafficLights); - // two types of knotenzulsa - addParser("KNOTENZULSA", &NIImporter_VISUM::parse_NodesToTrafficLights); - addParser("LSAZUKNOTEN", &NIImporter_VISUM::parse_NodesToTrafficLights); - addParser("SIGNALANLAGEZUKNOTEN", &NIImporter_VISUM::parse_NodesToTrafficLights); - // two types of signalgruppe - addParser("LSASIGNALGRUPPE", &NIImporter_VISUM::parse_SignalGroups); - addParser("SIGNALGRUPPE", &NIImporter_VISUM::parse_SignalGroups); - // three types of ABBZULSASIGNALGRUPPE - addParser("ABBZULSASIGNALGRUPPE", &NIImporter_VISUM::parse_TurnsToSignalGroups); - addParser("SIGNALGRUPPEZUABBIEGER", &NIImporter_VISUM::parse_TurnsToSignalGroups); - addParser("SIGNALGRUPPEZUFSABBIEGER", &NIImporter_VISUM::parse_TurnsToSignalGroups); - - addParser(KEYS.getString(VISUM_FACEITEM), &NIImporter_VISUM::parse_AreaSubPartElement); - - // two types of LSAPHASE - addParser("LSAPHASE", &NIImporter_VISUM::parse_Phases); - addParser("PHASE", &NIImporter_VISUM::parse_Phases); - - addParser("LSASIGNALGRUPPEZULSAPHASE", &NIImporter_VISUM::parse_SignalGroupsToPhases); - addParser("FAHRSTREIFENABBIEGER", &NIImporter_VISUM::parse_LanesConnections); -} - - -NIImporter_VISUM::~NIImporter_VISUM() { - for (NIVisumTL_Map::iterator j = myTLS.begin(); j != myTLS.end(); j++) { - delete j->second; - } -} - - -void -NIImporter_VISUM::addParser(const std::string& name, ParsingFunction function) { - TypeParser p; - p.name = name; - p.function = function; - p.position = -1; - mySingleDataParsers.push_back(p); -} - - -void -NIImporter_VISUM::load() { - // open the file - if (!myLineReader.setFile(myFileName)) { - throw ProcessError("Can not open visum-file '" + myFileName + "'."); - } - // scan the file for data positions - while (myLineReader.hasMore()) { - std::string line = myLineReader.readLine(); - if (line.length() > 0 && line[0] == '$') { - ParserVector::iterator i; - for (i = mySingleDataParsers.begin(); i != mySingleDataParsers.end(); i++) { - std::string dataName = "$" + (*i).name + ":"; - if (line.substr(0, dataName.length()) == dataName) { - (*i).position = myLineReader.getPosition(); - (*i).pattern = line.substr(dataName.length()); - WRITE_MESSAGE("Found: " + dataName + " at " + toString(myLineReader.getPosition())); - } - } - } - } - // go through the parsers and process all entries - for (ParserVector::iterator i = mySingleDataParsers.begin(); i != mySingleDataParsers.end(); i++) { - if ((*i).position < 0) { - // do not process using parsers for which no information was found - continue; - } - // ok, the according information is stored in the file - PROGRESS_BEGIN_MESSAGE("Parsing " + (*i).name); - // reset the line reader and let it point to the begin of the according data field - myLineReader.reinit(); - myLineReader.setPos((*i).position); - // prepare the line parser - myLineParser.reinit((*i).pattern); - // read - bool singleDataEndFound = false; - while (myLineReader.hasMore() && !singleDataEndFound) { - std::string line = myLineReader.readLine(); - if (line.length() == 0 || line[0] == '*' || line[0] == '$') { - singleDataEndFound = true; - } else { - myLineParser.parseLine(line); - try { - myCurrentID = ""; - (this->*(*i).function)(); - } catch (OutOfBoundsException&) { - WRITE_ERROR("Too short value line in " + (*i).name + " occurred."); - } catch (NumberFormatException&) { - WRITE_ERROR("A value in " + (*i).name + " should be numeric but is not (id='" + myCurrentID + "')."); - } catch (UnknownElement& e) { - WRITE_ERROR("One of the needed values ('" + std::string(e.what()) + "') is missing in " + (*i).name + "."); - } - } - } - // close single reader processing - PROGRESS_DONE_MESSAGE(); - } - myNetBuilder.getEdgeCont().reduceGeometries(POSITION_EPS); - - // build traffic lights - for (NIVisumTL_Map::iterator j = myTLS.begin(); j != myTLS.end(); j++) { - j->second->build(myNetBuilder.getEdgeCont(), myNetBuilder.getTLLogicCont()); - } - // build district shapes - for (std::map::const_iterator k = myDistrictShapes.begin(); k != myDistrictShapes.end(); ++k) { - (*k).first->addShape((*k).second); - } -} - - - - - -void -NIImporter_VISUM::parse_VSysTypes() { - std::string name = myLineParser.know("VSysCode") ? myLineParser.get("VSysCode").c_str() : myLineParser.get(KEYS.getString(VISUM_CODE)).c_str(); - std::string type = myLineParser.know("VSysMode") ? myLineParser.get("VSysMode").c_str() : myLineParser.get(KEYS.getString(VISUM_TYP)).c_str(); - myVSysTypes[name] = type; -} - - -void -NIImporter_VISUM::parse_Types() { - // get the id - myCurrentID = NBHelpers::normalIDRepresentation(myLineParser.get(KEYS.getString(VISUM_NO))); - // get the maximum speed - double speed = getWeightedFloat2("v0-IV", KEYS.getString(VISUM_V0), "km/h"); - if (speed == 0) { - // unlimited speed - speed = 3600; - } else if (speed < 0) { - WRITE_ERROR("Type '" + myCurrentID + "' has speed " + toString(speed)); - } - // get the permissions - SVCPermissions permissions = getPermissions(KEYS.getString(VISUM_TYPES), true); - // get the priority - const int priority = 1000 - StringUtils::toInt(myLineParser.get(KEYS.getString(VISUM_RANK))); - // try to retrieve the number of lanes - const int numLanes = myCapacity2Lanes.get(getNamedFloat("Kap-IV", KEYS.getString(VISUM_CAPACITY))); - // insert the type - myNetBuilder.getTypeCont().insert(myCurrentID, numLanes, speed / (double) 3.6, priority, permissions, NBEdge::UNSPECIFIED_WIDTH, false, NBEdge::UNSPECIFIED_WIDTH, NBEdge::UNSPECIFIED_WIDTH, 0, 0, 0); - myNetBuilder.getTypeCont().markAsSet(myCurrentID, SUMO_ATTR_NUMLANES); - myNetBuilder.getTypeCont().markAsSet(myCurrentID, SUMO_ATTR_SPEED); - myNetBuilder.getTypeCont().markAsSet(myCurrentID, SUMO_ATTR_PRIORITY); - myNetBuilder.getTypeCont().markAsSet(myCurrentID, SUMO_ATTR_ONEWAY); - myNetBuilder.getTypeCont().markAsSet(myCurrentID, SUMO_ATTR_ALLOW); -} - - -void -NIImporter_VISUM::parse_Nodes() { - // get the id - myCurrentID = NBHelpers::normalIDRepresentation(myLineParser.get(KEYS.getString(VISUM_NO))); - // get the position - double x = getNamedFloat(KEYS.getString(VISUM_XCOORD)); - double y = getNamedFloat(KEYS.getString(VISUM_YCOORD)); - Position pos(x, y); - if (!NBNetBuilder::transformCoordinate(pos)) { - WRITE_ERROR("Unable to project coordinates for node " + myCurrentID + "."); - return; - } - // add to the list - if (!myNetBuilder.getNodeCont().insert(myCurrentID, pos)) { - WRITE_ERROR("Duplicate node occurred ('" + myCurrentID + "')."); - } -} - - -void -NIImporter_VISUM::parse_Districts() { - // get the id - myCurrentID = NBHelpers::normalIDRepresentation(myLineParser.get(KEYS.getString(VISUM_NO))); - // get the information whether the source and the destination - // connections are weighted - //bool sourcesWeighted = getWeightedBool("Proz_Q"); - //bool destWeighted = getWeightedBool("Proz_Z"); - // get the node information - double x = getNamedFloat(KEYS.getString(VISUM_XCOORD)); - double y = getNamedFloat(KEYS.getString(VISUM_YCOORD)); - Position pos(x, y); - if (!NBNetBuilder::transformCoordinate(pos, false)) { - WRITE_ERROR("Unable to project coordinates for district " + myCurrentID + "."); - return; - } - // build the district - NBDistrict* district = new NBDistrict(myCurrentID, pos); - if (!myNetBuilder.getDistrictCont().insert(district)) { - WRITE_ERROR("Duplicate district occurred ('" + myCurrentID + "')."); - delete district; - return; - } - if (myLineParser.know(KEYS.getString(VISUM_SURFACEID))) { - long long int flaecheID = StringUtils::toLong(myLineParser.get(KEYS.getString(VISUM_SURFACEID))); - myShapeDistrictMap[flaecheID] = district; - } -} - - -void -NIImporter_VISUM::parse_Point() { - long long int id = StringUtils::toLong(myLineParser.get(KEYS.getString(VISUM_ID))); - double x = StringUtils::toDouble(myLineParser.get(KEYS.getString(VISUM_XCOORD))); - double y = StringUtils::toDouble(myLineParser.get(KEYS.getString(VISUM_YCOORD))); - Position pos(x, y); - if (!NBNetBuilder::transformCoordinate(pos, false)) { - WRITE_ERROR("Unable to project coordinates for point " + toString(id) + "."); - return; - } - myPoints[id] = pos; -} - - -void -NIImporter_VISUM::parse_Edges() { - if (myLineParser.know(KEYS.getString(VISUM_TYPES)) && myLineParser.get(KEYS.getString(VISUM_TYPES)) == "") { - // no vehicle allowed; don't add - return; - } - // get the id - myCurrentID = NBHelpers::normalIDRepresentation(myLineParser.get(KEYS.getString(VISUM_NO))); - // get the from- & to-node and validate them - NBNode* from = getNamedNode("VonKnot", KEYS.getString(VISUM_FROMNODE)); - NBNode* to = getNamedNode("NachKnot", KEYS.getString(VISUM_TONODE)); - if (!checkNodes(from, to)) { - return; - } - // get the type - std::string type = myLineParser.know(KEYS.getString(VISUM_TYP)) ? myLineParser.get(KEYS.getString(VISUM_TYP)) : myLineParser.get(KEYS.getString(VISUM_TYPE)); - // get the speed - double speed = myNetBuilder.getTypeCont().getSpeed(type); - if (!OptionsCont::getOptions().getBool("visum.use-type-speed")) { - try { - std::string speedS = myLineParser.know("v0-IV") ? myLineParser.get("v0-IV") : myLineParser.get(KEYS.getString(VISUM_V0)); - if (speedS.find("km/h") != std::string::npos) { - speedS = speedS.substr(0, speedS.find("km/h")); - } - speed = StringUtils::toDouble(speedS) / 3.6; - } catch (OutOfBoundsException&) {} - } - if (speed <= 0) { - speed = myNetBuilder.getTypeCont().getSpeed(type); - } - - // get the information whether the edge is a one-way - bool oneway = myLineParser.know("Einbahn") - ? StringUtils::toBool(myLineParser.get("Einbahn")) - : true; - // get the number of lanes - int nolanes = myNetBuilder.getTypeCont().getNumLanes(type); - if (!OptionsCont::getOptions().getBool("visum.recompute-lane-number")) { - if (!OptionsCont::getOptions().getBool("visum.use-type-laneno")) { - if (myLineParser.know("Fahrstreifen")) { - nolanes = StringUtils::toInt(myLineParser.get("Fahrstreifen")); - } else if (myLineParser.know(KEYS.getString(VISUM_NUMLANES))) { - nolanes = StringUtils::toInt(myLineParser.get(KEYS.getString(VISUM_NUMLANES))); - } - } - } else { - if (myLineParser.know(KEYS.getString(VISUM_CAPACITY))) { - nolanes = myCapacity2Lanes.get(StringUtils::toDouble(myLineParser.get(KEYS.getString(VISUM_CAPACITY)))); - } else if (myLineParser.know("KAP-IV")) { - nolanes = myCapacity2Lanes.get(StringUtils::toDouble(myLineParser.get("KAP-IV"))); - } - } - // check whether the id is already used - // (should be the opposite direction) - bool oneway_checked = oneway; - NBEdge* previous = myNetBuilder.getEdgeCont().retrieve(myCurrentID); - if (previous != nullptr) { - myCurrentID = '-' + myCurrentID; - previous->setLaneSpreadFunction(LaneSpreadFunction::RIGHT); - oneway_checked = false; - } - if (find(myTouchedEdges.begin(), myTouchedEdges.end(), myCurrentID) != myTouchedEdges.end()) { - oneway_checked = false; - } - std::string tmpid = '-' + myCurrentID; - if (find(myTouchedEdges.begin(), myTouchedEdges.end(), tmpid) != myTouchedEdges.end()) { - previous = myNetBuilder.getEdgeCont().retrieve(tmpid); - if (previous != nullptr) { - previous->setLaneSpreadFunction(LaneSpreadFunction::RIGHT); - } - oneway_checked = false; - } - // add the edge - const SVCPermissions permissions = getPermissions(KEYS.getString(VISUM_TYPES), false, myNetBuilder.getTypeCont().getPermissions(type)); - int prio = myUseVisumPrio ? myNetBuilder.getTypeCont().getPriority(type) : -1; - if (nolanes != 0 && speed != 0) { - LaneSpreadFunction lsf = oneway_checked ? LaneSpreadFunction::CENTER : LaneSpreadFunction::RIGHT; - // @todo parse name from visum files - NBEdge* e = new NBEdge(myCurrentID, from, to, type, speed, nolanes, prio, - NBEdge::UNSPECIFIED_WIDTH, NBEdge::UNSPECIFIED_OFFSET, "", lsf); - e->setPermissions(permissions); - if (!myNetBuilder.getEdgeCont().insert(e)) { - delete e; - WRITE_ERROR("Duplicate edge occurred ('" + myCurrentID + "')."); - } - } - myTouchedEdges.push_back(myCurrentID); - // nothing more to do, when the edge is a one-way street - if (oneway) { - return; - } - // add the opposite edge - myCurrentID = '-' + myCurrentID; - if (nolanes != 0 && speed != 0) { - LaneSpreadFunction lsf = oneway_checked ? LaneSpreadFunction::CENTER : LaneSpreadFunction::RIGHT; - // @todo parse name from visum files - NBEdge* e = new NBEdge(myCurrentID, from, to, type, speed, nolanes, prio, - NBEdge::UNSPECIFIED_WIDTH, NBEdge::UNSPECIFIED_OFFSET, "", lsf); - e->setPermissions(permissions); - if (!myNetBuilder.getEdgeCont().insert(e)) { - delete e; - WRITE_ERROR("Duplicate edge occurred ('" + myCurrentID + "')."); - } - } - myTouchedEdges.push_back(myCurrentID); -} - - -void -NIImporter_VISUM::parse_Kante() { - long long int id = StringUtils::toLong(myLineParser.get(KEYS.getString(VISUM_ID))); - long long int from = StringUtils::toLong(myLineParser.get(KEYS.getString(VISUM_FROMPOINTID))); - long long int to = StringUtils::toLong(myLineParser.get(KEYS.getString(VISUM_TOPOINTID))); - myEdges[id] = std::make_pair(from, to); -} - - -void -NIImporter_VISUM::parse_PartOfArea() { - long long int flaecheID = StringUtils::toLong(myLineParser.get(KEYS.getString(VISUM_SURFACEID))); - long long int flaechePartID = StringUtils::toLong(myLineParser.get(KEYS.getString(VISUM_FACEID))); - if (mySubPartsAreas.find(flaechePartID) == mySubPartsAreas.end()) { - mySubPartsAreas[flaechePartID] = std::vector(); - } - mySubPartsAreas[flaechePartID].push_back(flaecheID); -} - - -void -NIImporter_VISUM::parse_Connectors() { - // get the source district - std::string bez = NBHelpers::normalIDRepresentation(myLineParser.get(KEYS.getString(VISUM_SOURCE_DISTRICT))); - // get the destination node - NBNode* dest = getNamedNode(KEYS.getString(VISUM_FROMNODENO)); - if (dest == nullptr) { - return; - } - // get the weight of the connection - double proz = 1; - if (myLineParser.know("Proz") || myLineParser.know("Proz(IV)")) { - proz = getNamedFloat("Proz", "Proz(IV)") / 100; - } - // get the information whether this is a sink or a source - std::string dir = myLineParser.get(KEYS.getString(VISUM_DIRECTION)); - if (dir.length() == 0) { - dir = KEYS.getString(VISUM_ORIGIN) + KEYS.getString(VISUM_DESTINATION); - } - // build the source when needed - if (dir.find(KEYS.getString(VISUM_ORIGIN)) != std::string::npos) { - for (NBEdge* edge : dest->getOutgoingEdges()) { - myNetBuilder.getDistrictCont().addSource(bez, edge, proz); - } - } - // build the sink when needed - if (dir.find(KEYS.getString(VISUM_DESTINATION)) != std::string::npos) { - for (NBEdge* edge : dest->getIncomingEdges()) { - myNetBuilder.getDistrictCont().addSink(bez, edge, proz); - } - } -} - - - -void -NIImporter_VISUM::parse_Connectors_legacy() { - // get the source district - std::string bez = NBHelpers::normalIDRepresentation(myLineParser.get(KEYS.getString(VISUM_SOURCE_DISTRICT))); - // get the destination node - NBNode* dest = getNamedNode(KEYS.getString(VISUM_FROMNODENO)); - if (dest == nullptr) { - return; - } - // get the weight of the connection - double proz = 1; - if (myLineParser.know("Proz") || myLineParser.know("Proz(IV)")) { - proz = getNamedFloat("Proz", "Proz(IV)") / 100; - } - // get the duration to wait (unused) -// double retard = -1; -// if (myLineParser.know("t0-IV")) { -// retard = getNamedFloat("t0-IV", -1); -// } - // get the type; - // use a standard type with a large speed when a type is not given - - std::string type = myLineParser.know(KEYS.getString(VISUM_TYP)) - ? NBHelpers::normalIDRepresentation(myLineParser.get(KEYS.getString(VISUM_TYP))) - : ""; - // add the connectors as an edge - std::string id = bez + "-" + dest->getID(); - // get the information whether this is a sink or a source - std::string dir = myLineParser.get(KEYS.getString(VISUM_DIRECTION)); - if (dir.length() == 0) { - dir = KEYS.getString(VISUM_ORIGIN) + KEYS.getString(VISUM_DESTINATION); - } - // build the source when needed - if (dir.find(KEYS.getString(VISUM_ORIGIN)) != std::string::npos) { - const EdgeVector& edges = dest->getOutgoingEdges(); - bool hasContinuation = false; - for (EdgeVector::const_iterator i = edges.begin(); i != edges.end(); ++i) { - if (!(*i)->isMacroscopicConnector()) { - hasContinuation = true; - } - } - if (!hasContinuation) { - // obviously, there is no continuation on the net - WRITE_WARNING("Incoming connector '" + id + "' will not be build - would be not connected to network."); - } else { - NBNode* src = buildDistrictNode(bez, dest, true); - if (src == nullptr) { - WRITE_ERROR("The district '" + bez + "' could not be built."); - return; - } - NBEdge* edge = new NBEdge(id, src, dest, "VisumConnector", - OptionsCont::getOptions().getFloat("visum.connector-speeds"), - OptionsCont::getOptions().getInt("visum.connectors-lane-number"), - -1, NBEdge::UNSPECIFIED_WIDTH, NBEdge::UNSPECIFIED_OFFSET, - "", LaneSpreadFunction::RIGHT); - edge->setAsMacroscopicConnector(); - if (!myNetBuilder.getEdgeCont().insert(edge)) { - WRITE_ERROR("A duplicate edge id occurred (ID='" + id + "')."); - return; - } - edge = myNetBuilder.getEdgeCont().retrieve(id); - if (edge != nullptr) { - myNetBuilder.getDistrictCont().addSource(bez, edge, proz); - } - } - } - // build the sink when needed - if (dir.find(KEYS.getString(VISUM_DESTINATION)) != std::string::npos) { - const EdgeVector& edges = dest->getIncomingEdges(); - bool hasPredeccessor = false; - for (EdgeVector::const_iterator i = edges.begin(); i != edges.end(); ++i) { - if (!(*i)->isMacroscopicConnector()) { - hasPredeccessor = true; - } - } - if (!hasPredeccessor) { - // obviously, the network is not connected to this node - WRITE_WARNING("Outgoing connector '" + id + "' will not be build - would be not connected to network."); - } else { - NBNode* src = buildDistrictNode(bez, dest, false); - if (src == nullptr) { - WRITE_ERROR("The district '" + bez + "' could not be built."); - return; - } - id = "-" + id; - NBEdge* edge = new NBEdge(id, dest, src, "VisumConnector", - OptionsCont::getOptions().getFloat("visum.connector-speeds"), - OptionsCont::getOptions().getInt("visum.connectors-lane-number"), - -1, NBEdge::UNSPECIFIED_WIDTH, NBEdge::UNSPECIFIED_OFFSET, - "", LaneSpreadFunction::RIGHT); - edge->setAsMacroscopicConnector(); - if (!myNetBuilder.getEdgeCont().insert(edge)) { - WRITE_ERROR("A duplicate edge id occurred (ID='" + id + "')."); - return; - } - edge = myNetBuilder.getEdgeCont().retrieve(id); - if (edge != nullptr) { - myNetBuilder.getDistrictCont().addSink(bez, edge, proz); - } - } - } -} - - -void -NIImporter_VISUM::parse_Turns() { - if (myLineParser.know(KEYS.getString(VISUM_TYPES)) && myLineParser.get(KEYS.getString(VISUM_TYPES)) == "") { - // no vehicle allowed; don't add - return; - } - // retrieve the nodes - NBNode* from = getNamedNode("VonKnot", KEYS.getString(VISUM_FROMNODE)); - NBNode* via = getNamedNode("UeberKnot", KEYS.getString(VISUM_VIANODENO)); - NBNode* to = getNamedNode("NachKnot", KEYS.getString(VISUM_TONODE)); - if (from == nullptr || via == nullptr || to == nullptr) { - return; - } - // all nodes are known - std::string type = myLineParser.know("VSysCode") - ? myLineParser.get("VSysCode") - : myLineParser.get(KEYS.getString(VISUM_TYPES)); - if (myVSysTypes.find(type) != myVSysTypes.end() && myVSysTypes.find(type)->second == "IV") { - // try to set the turning definition - NBEdge* src = from->getConnectionTo(via); - NBEdge* dest = via->getConnectionTo(to); - // check both - if (src == nullptr) { - if (OptionsCont::getOptions().getBool("visum.verbose-warnings")) { - WRITE_WARNING("There is no edge from node '" + from->getID() + "' to node '" + via->getID() + "'."); - } - return; - } - if (dest == nullptr) { - if (OptionsCont::getOptions().getBool("visum.verbose-warnings")) { - WRITE_WARNING("There is no edge from node '" + via->getID() + "' to node '" + to->getID() + "'."); - } - return; - } - // both edges found - // set them into the edge - src->addEdge2EdgeConnection(dest); - } -} - - -void -NIImporter_VISUM::parse_EdgePolys() { - // get the from- & to-node and validate them - NBNode* from = getNamedNode("VonKnot", KEYS.getString(VISUM_FROMNODE)); - NBNode* to = getNamedNode("NachKnot", KEYS.getString(VISUM_TONODE)); - if (!checkNodes(from, to)) { - return; - } - bool failed = false; - int index; - double x, y; - try { - index = StringUtils::toInt(myLineParser.get(KEYS.getString(VISUM_INDEX))); - x = getNamedFloat(KEYS.getString(VISUM_XCOORD)); - y = getNamedFloat(KEYS.getString(VISUM_YCOORD)); - } catch (NumberFormatException&) { - WRITE_ERROR("Error in geometry description from node '" + from->getID() + "' to node '" + to->getID() + "'."); - return; - } - Position pos(x, y); - if (!NBNetBuilder::transformCoordinate(pos)) { - WRITE_ERROR("Unable to project coordinates for node '" + from->getID() + "'."); - return; - } - NBEdge* e = from->getConnectionTo(to); - if (e != nullptr) { - e->addGeometryPoint(index, pos); - } else { - failed = true; - } - e = to->getConnectionTo(from); - if (e != nullptr) { - e->addGeometryPoint(-index, pos); - failed = false; - } - // check whether the operation has failed - if (failed) { - if (OptionsCont::getOptions().getBool("visum.verbose-warnings")) { - WRITE_WARNING("There is no edge from node '" + from->getID() + "' to node '" + to->getID() + "'."); - } - } -} - - -void -NIImporter_VISUM::parse_Lanes() { - // The base number of lanes for the edge was already defined in STRECKE - // this refines lane specific attribute (width) and optionally introduces splits for additional lanes - // It is permitted for KNOTNR to be 0 - // - // get the edge - NBEdge* baseEdge = getNamedEdge("STRNR"); - if (baseEdge == nullptr) { - return; - } - NBEdge* edge = baseEdge; - // get the node - NBNode* node = getNamedNodeSecure("KNOTNR"); - if (node == nullptr) { - node = edge->getToNode(); - } else { - edge = getNamedEdgeContinuating("STRNR", node); - } - // check - if (edge == nullptr) { - return; - } - // get the lane - std::string laneS = myLineParser.know("FSNR") - ? NBHelpers::normalIDRepresentation(myLineParser.get("FSNR")) - : NBHelpers::normalIDRepresentation(myLineParser.get("NR")); - int lane = -1; - try { - lane = StringUtils::toInt(laneS); - } catch (NumberFormatException&) { - WRITE_ERROR("A lane number for edge '" + edge->getID() + "' is not numeric (" + laneS + ")."); - return; - } - lane -= 1; - if (lane < 0) { - WRITE_ERROR("A lane number for edge '" + edge->getID() + "' is not positive (" + laneS + ")."); - return; - } - // get the direction - std::string dirS = NBHelpers::normalIDRepresentation(myLineParser.get("RICHTTYP")); - int prevLaneNo = baseEdge->getNumLanes(); - if ((dirS == "1" && !(node->hasIncoming(edge))) || (dirS == "0" && !(node->hasOutgoing(edge)))) { - // get the last part of the turnaround direction - NBEdge* cand = getReversedContinuating(edge, node); - if (cand) { - edge = cand; - } - } - // get the length - std::string lengthS = NBHelpers::normalIDRepresentation(myLineParser.get("LAENGE")); - double length = -1; - try { - length = StringUtils::toDouble(lengthS); - } catch (NumberFormatException&) { - WRITE_ERROR("A lane length for edge '" + edge->getID() + "' is not numeric (" + lengthS + ")."); - return; - } - if (length < 0) { - WRITE_ERROR("A lane length for edge '" + edge->getID() + "' is not positive (" + lengthS + ")."); - return; - } - // - if (dirS == "1") { - lane -= prevLaneNo; - } - // - if (length == 0) { - if ((int) edge->getNumLanes() > lane) { - // ok, we know this already... - return; - } - // increment by one - edge->incLaneNo(1); - } else { - // check whether this edge already has been created - if (isSplitEdge(edge, node)) { - if (edge->getID().substr(edge->getID().find('_')) == "_" + toString(length) + "_" + node->getID()) { - if ((int) edge->getNumLanes() > lane) { - // ok, we know this already... - return; - } - // increment by one - edge->incLaneNo(1); - return; - } - } - // nope, we have to split the edge... - // maybe it is not the proper edge to split - VISUM seems not to sort the splits... - bool mustRecheck = true; - double seenLength = 0; - while (mustRecheck) { - if (isSplitEdge(edge, node)) { - // ok, we have a previously created edge here - std::string sub = edge->getID(); - sub = sub.substr(sub.rfind('_', sub.rfind('_') - 1)); - sub = sub.substr(1, sub.find('_', 1) - 1); - double dist = StringUtils::toDouble(sub); - if (dist < length) { - seenLength += edge->getLength(); - if (dirS == "1") { - // incoming -> move back - edge = edge->getFromNode()->getIncomingEdges()[0]; - } else { - // outgoing -> move forward - edge = edge->getToNode()->getOutgoingEdges()[0]; - } - } else { - mustRecheck = false; - } - } else { - // we have the center edge - do not continue... - mustRecheck = false; - } - } - // compute position - Position p; - double useLength = length - seenLength; - useLength = edge->getLength() - useLength; - if (useLength < 0 || useLength > edge->getLength()) { - WRITE_WARNING("Could not find split position for edge '" + edge->getID() + "'."); - return; - } - std::string edgeID = edge->getID(); - p = edge->getGeometry().positionAtOffset(useLength); - if (isSplitEdge(edge, node)) { - edgeID = edgeID.substr(0, edgeID.find('_')); - } - NBNode* rn = new NBNode(edgeID + "_" + toString((int) length) + "_" + node->getID(), p); - if (!myNetBuilder.getNodeCont().insert(rn)) { - throw ProcessError("Ups - could not insert node!"); - } - std::string nid = edgeID + "_" + toString((int) length) + "_" + node->getID(); - myNetBuilder.getEdgeCont().splitAt(myNetBuilder.getDistrictCont(), edge, useLength, rn, - edge->getID(), nid, edge->getNumLanes() + 0, edge->getNumLanes() + 1); - // old edge is deleted and a new edge with the same name created - edge = myNetBuilder.getEdgeCont().retrieve(edgeID); - NBEdge* nedge = myNetBuilder.getEdgeCont().retrieve(nid); - nedge = nedge->getToNode()->getOutgoingEdges()[0]; - while (isSplitEdge(edge, node)) { - assert(nedge->getToNode()->getOutgoingEdges().size() > 0); - nedge->incLaneNo(1); - nedge = nedge->getToNode()->getOutgoingEdges()[0]; - } - } -} - - -void -NIImporter_VISUM::parse_TrafficLights() { - myCurrentID = NBHelpers::normalIDRepresentation(myLineParser.get(KEYS.getString(VISUM_NO))); - SUMOTime cycleTime = (SUMOTime) getWeightedFloat2("Umlaufzeit", "UMLZEIT", "s"); - SUMOTime intermediateTime = (SUMOTime) getWeightedFloat2("StdZwischenzeit", "STDZWZEIT", "s"); - bool phaseBased = myLineParser.know("PhasenBasiert") - ? StringUtils::toBool(myLineParser.get("PhasenBasiert")) - : false; - SUMOTime offset = myLineParser.know("ZEITVERSATZ") ? TIME2STEPS(getWeightedFloat("ZEITVERSATZ", "s")) : 0; - // add to the list - myTLS[myCurrentID] = new NIVisumTL(myCurrentID, cycleTime, offset, intermediateTime, phaseBased); -} - - -void -NIImporter_VISUM::parse_NodesToTrafficLights() { - std::string node = myLineParser.get("KnotNr").c_str(); - if (node == "0") { - // this is a dummy value which cannot be assigned to - return; - } - std::string trafficLight = myLineParser.get("LsaNr").c_str(); - // add to the list - NBNode* n = myNetBuilder.getNodeCont().retrieve(node); - auto tlIt = myTLS.find(trafficLight); - if (n != nullptr && tlIt != myTLS.end()) { - tlIt->second->addNode(n); - } else { - WRITE_ERROR("Could not assign" + std::string(n == nullptr ? " missing" : "") + " node '" + node - + "' to" + std::string(tlIt == myTLS.end() ? " missing" : "") + " traffic light '" + trafficLight + "'"); - } -} - - -void -NIImporter_VISUM::parse_SignalGroups() { - myCurrentID = NBHelpers::normalIDRepresentation(myLineParser.get(KEYS.getString(VISUM_NO))); - std::string LSAid = NBHelpers::normalIDRepresentation(myLineParser.get("LsaNr")); - double startTime = getNamedFloat("GzStart", "GRUENANF"); - double endTime = getNamedFloat("GzEnd", "GRUENENDE"); - double yellowTime = myLineParser.know("GELB") ? getNamedFloat("GELB") : -1; - // add to the list - if (myTLS.find(LSAid) == myTLS.end()) { - WRITE_ERROR("Could not find TLS '" + LSAid + "' for setting the signal group."); - return; - } - myTLS.find(LSAid)->second->addSignalGroup(myCurrentID, (SUMOTime) startTime, (SUMOTime) endTime, (SUMOTime) yellowTime); -} - - -void -NIImporter_VISUM::parse_TurnsToSignalGroups() { - // get the id - std::string SGid = getNamedString("SGNR", "SIGNALGRUPPENNR"); - if (!myLineParser.know("LsaNr")) { - /// XXX could be retrieved from context - WRITE_WARNING("Ignoring SIGNALGRUPPEZUFSABBIEGER because LsaNr is not known"); - return; - } - std::string LSAid = getNamedString("LsaNr"); - // nodes - NBNode* from = myLineParser.know("VonKnot") ? getNamedNode("VonKnot") : nullptr; - NBNode* via = myLineParser.know("KNOTNR") - ? getNamedNode("KNOTNR") - : getNamedNode("UeberKnot", "UeberKnotNr"); - NBNode* to = myLineParser.know("NachKnot") ? getNamedNode("NachKnot") : nullptr; - // edges - NBEdge* edg1 = nullptr; - NBEdge* edg2 = nullptr; - if (from == nullptr && to == nullptr) { - edg1 = getNamedEdgeContinuating("VONSTRNR", via); - edg2 = getNamedEdgeContinuating("NACHSTRNR", via); - } else { - edg1 = getEdge(from, via); - edg2 = getEdge(via, to); - } - // add to the list - NIVisumTL::SignalGroup& SG = myTLS.find(LSAid)->second->getSignalGroup(SGid); - if (edg1 != nullptr && edg2 != nullptr) { - if (!via->hasIncoming(edg1)) { - std::string sid; - if (edg1->getID()[0] == '-') { - sid = edg1->getID().substr(1); - } else { - sid = "-" + edg1->getID(); - } - if (sid.find('_') != std::string::npos) { - sid = sid.substr(0, sid.find('_')); - } - edg1 = getNamedEdgeContinuating(myNetBuilder.getEdgeCont().retrieve(sid), via); - } - if (!via->hasOutgoing(edg2)) { - std::string sid; - if (edg2->getID()[0] == '-') { - sid = edg2->getID().substr(1); - } else { - sid = "-" + edg2->getID(); - } - if (sid.find('_') != std::string::npos) { - sid = sid.substr(0, sid.find('_')); - } - edg2 = getNamedEdgeContinuating(myNetBuilder.getEdgeCont().retrieve(sid), via); - } - SG.connections().push_back(NBConnection(edg1, edg2)); - } -} - - -void -NIImporter_VISUM::parse_AreaSubPartElement() { - long long int id = StringUtils::toLong(myLineParser.get(KEYS.getString(VISUM_FACEID))); - long long int edgeid = StringUtils::toLong(myLineParser.get(KEYS.getString(VISUM_EDGEID))); - if (myEdges.find(edgeid) == myEdges.end()) { - WRITE_ERROR("Unknown edge in TEILFLAECHENELEMENT"); - return; - } - std::string dir = myLineParser.get(KEYS.getString(VISUM_DIRECTION)); -// get index (unused) -// std::string indexS = NBHelpers::normalIDRepresentation(myLineParser.get("INDEX")); -// int index = -1; -// try { -// index = StringUtils::toInt(indexS) - 1; -// } catch (NumberFormatException&) { -// WRITE_ERROR("An index for a TEILFLAECHENELEMENT is not numeric (id='" + toString(id) + "')."); -// return; -// } - PositionVector shape; - shape.push_back(myPoints[myEdges[edgeid].first]); - shape.push_back(myPoints[myEdges[edgeid].second]); - if (dir.length() > 0 && dir[0] == '1') { - shape = shape.reverse(); - } - if (mySubPartsAreas.find(id) == mySubPartsAreas.end()) { - WRITE_ERROR("Unkown are for area part '" + myCurrentID + "'."); - return; - } - - const std::vector& areas = mySubPartsAreas.find(id)->second; - for (std::vector::const_iterator i = areas.begin(); i != areas.end(); ++i) { - NBDistrict* d = myShapeDistrictMap[*i]; - if (d == nullptr) { - continue; - } - if (myDistrictShapes.find(d) == myDistrictShapes.end()) { - myDistrictShapes[d] = PositionVector(); - } - if (dir.length() > 0 && dir[0] == '1') { - myDistrictShapes[d].push_back(myPoints[myEdges[edgeid].second]); - myDistrictShapes[d].push_back(myPoints[myEdges[edgeid].first]); - } else { - myDistrictShapes[d].push_back(myPoints[myEdges[edgeid].first]); - myDistrictShapes[d].push_back(myPoints[myEdges[edgeid].second]); - } - } -} - - -void -NIImporter_VISUM::parse_Phases() { - // get the id - std::string phaseid = NBHelpers::normalIDRepresentation(myLineParser.get(KEYS.getString(VISUM_NO))); - std::string LSAid = NBHelpers::normalIDRepresentation(myLineParser.get("LsaNr")); - double startTime = getNamedFloat("GzStart", "GRUENANF"); - double endTime = getNamedFloat("GzEnd", "GRUENENDE"); - double yellowTime = myLineParser.know("GELB") ? getNamedFloat("GELB") : -1; - myTLS.find(LSAid)->second->addPhase(phaseid, (SUMOTime) startTime, (SUMOTime) endTime, (SUMOTime) yellowTime); -} - - -void NIImporter_VISUM::parse_SignalGroupsToPhases() { - // get the id - std::string Phaseid = NBHelpers::normalIDRepresentation(myLineParser.get("PsNr")); - std::string LSAid = NBHelpers::normalIDRepresentation(myLineParser.get("LsaNr")); - std::string SGid = NBHelpers::normalIDRepresentation(myLineParser.get("SGNR")); - // insert - NIVisumTL* LSA = myTLS.find(LSAid)->second; - NIVisumTL::SignalGroup& SG = LSA->getSignalGroup(SGid); - NIVisumTL::Phase* PH = LSA->getPhases().find(Phaseid)->second; - SG.phases()[Phaseid] = PH; -} - - -void NIImporter_VISUM::parse_LanesConnections() { - NBNode* node = nullptr; - NBEdge* fromEdge = nullptr; - NBEdge* toEdge = nullptr; - // get the node and edges depending on network format - const std::string nodeID = getNamedString("KNOTNR", "KNOT"); - if (nodeID == "0") { - fromEdge = getNamedEdge("VONSTRNR", "VONSTR"); - toEdge = getNamedEdge("NACHSTRNR", "NACHSTR"); - if (fromEdge == nullptr) { - return; - } - node = fromEdge->getToNode(); - WRITE_WARNING("Ignoring lane-to-lane connection (not yet implemented for this format version)"); - return; - } else { - node = getNamedNode("KNOTNR", "KNOT"); - if (node == nullptr) { - return; - } - fromEdge = getNamedEdgeContinuating("VONSTRNR", "VONSTR", node); - toEdge = getNamedEdgeContinuating("NACHSTRNR", "NACHSTR", node); - } - if (fromEdge == nullptr || toEdge == nullptr) { - return; - } - - int fromLaneOffset = 0; - if (!node->hasIncoming(fromEdge)) { - fromLaneOffset = fromEdge->getNumLanes(); - fromEdge = getReversedContinuating(fromEdge, node); - } else { - fromEdge = getReversedContinuating(fromEdge, node); - NBEdge* tmp = myNetBuilder.getEdgeCont().retrieve(fromEdge->getID().substr(0, fromEdge->getID().find('_'))); - fromLaneOffset = tmp->getNumLanes(); - } - - int toLaneOffset = 0; - if (!node->hasOutgoing(toEdge)) { - toLaneOffset = toEdge->getNumLanes(); - toEdge = getReversedContinuating(toEdge, node); - } else { - NBEdge* tmp = myNetBuilder.getEdgeCont().retrieve(toEdge->getID().substr(0, toEdge->getID().find('_'))); - toLaneOffset = tmp->getNumLanes(); - } - // get the from-lane - std::string fromLaneS = NBHelpers::normalIDRepresentation(myLineParser.get("VONFSNR")); - int fromLane = -1; - try { - fromLane = StringUtils::toInt(fromLaneS); - } catch (NumberFormatException&) { - WRITE_ERROR("A from-lane number for edge '" + fromEdge->getID() + "' is not numeric (" + fromLaneS + ")."); - return; - } - fromLane -= 1; - if (fromLane < 0) { - WRITE_ERROR("A from-lane number for edge '" + fromEdge->getID() + "' is not positive (" + fromLaneS + ")."); - return; - } - // get the from-lane - std::string toLaneS = NBHelpers::normalIDRepresentation(myLineParser.get("NACHFSNR")); - int toLane = -1; - try { - toLane = StringUtils::toInt(toLaneS); - } catch (NumberFormatException&) { - WRITE_ERROR("A to-lane number for edge '" + toEdge->getID() + "' is not numeric (" + toLaneS + ")."); - return; - } - toLane -= 1; - if (toLane < 0) { - WRITE_ERROR("A to-lane number for edge '" + toEdge->getID() + "' is not positive (" + toLaneS + ")."); - return; - } - // !!! the next is probably a hack - if (fromLane - fromLaneOffset < 0) { - //fromLaneOffset = 0; - } else { - fromLane = (int)fromEdge->getNumLanes() - (fromLane - fromLaneOffset) - 1; - } - if (toLane - toLaneOffset < 0) { - //toLaneOffset = 0; - } else { - toLane = (int)toEdge->getNumLanes() - (toLane - toLaneOffset) - 1; - } - // - if ((int) fromEdge->getNumLanes() <= fromLane) { - WRITE_ERROR("A from-lane number for edge '" + fromEdge->getID() + "' is larger than the edge's lane number (" + fromLaneS + ")."); - return; - } - if ((int) toEdge->getNumLanes() <= toLane) { - WRITE_ERROR("A to-lane number for edge '" + toEdge->getID() + "' is larger than the edge's lane number (" + toLaneS + ")."); - return; - } - // - fromEdge->addLane2LaneConnection(fromLane, toEdge, toLane, NBEdge::Lane2LaneInfoType::VALIDATED); -} - - - - - - - - - - - - - -double -NIImporter_VISUM::getWeightedFloat(const std::string& name, const std::string& suffix) { - try { - std::string val = myLineParser.get(name); - if (val.find(suffix) != std::string::npos) { - val = val.substr(0, val.find(suffix)); - } - return StringUtils::toDouble(val); - } catch (...) {} - return -1; -} - - -double -NIImporter_VISUM::getWeightedFloat2(const std::string& name, const std::string& name2, const std::string& suffix) { - double result = getWeightedFloat(name, suffix); - if (result != -1) { - return result; - } else { - return getWeightedFloat(name2, suffix); - } -} - -bool -NIImporter_VISUM::getWeightedBool(const std::string& name) { - try { - return StringUtils::toBool(myLineParser.get(name)); - } catch (...) {} - try { - return StringUtils::toBool(myLineParser.get((name + "(IV)"))); - } catch (...) {} - return false; -} - -SVCPermissions -NIImporter_VISUM::getPermissions(const std::string& name, bool warn, SVCPermissions unknown) { - SVCPermissions result = 0; - for (std::string v : StringTokenizer(myLineParser.get(name), ",").getVector()) { - // common values in english and german - // || v == "funiculaire-telecabine" ---> no matching - std::transform(v.begin(), v.end(), v.begin(), tolower); - if (v == "bus" || v == "tcsp" || v == "acces tc" || v == "Accès tc" || v == "accès tc") { - result |= SVC_BUS; - } else if (v == "walk" || v == "w" || v == "f" || v == "ped" || v == "map") { - result |= SVC_PEDESTRIAN; - } else if (v == "l" || v == "lkw" || v == "h" || v == "hgv" || v == "lw" || v == "truck" || v == "tru" || v == "pl") { - result |= SVC_TRUCK; - } else if (v == "b" || v == "bike" || v == "velo") { - result |= SVC_BICYCLE; - } else if (v == "train" || v == "rail") { - result |= SVC_RAIL; - } else if (v == "tram") { - result |= SVC_TRAM; - } else if (v == "p" || v == "pkw" || v == "car" || v == "c" || v == "vp" || v == "2rm") { - result |= SVC_PASSENGER; - } else { - if (warn) { - WRITE_WARNING("Encountered unknown vehicle category '" + v + "' in type '" + myLineParser.get(KEYS.getString(VISUM_NO)) + "'"); - } - result |= unknown; - } - } - return result; -} - -NBNode* -NIImporter_VISUM::getNamedNode(const std::string& fieldName) { - std::string nodeS = NBHelpers::normalIDRepresentation(myLineParser.get(fieldName)); - NBNode* node = myNetBuilder.getNodeCont().retrieve(nodeS); - if (node == nullptr) { - WRITE_ERROR("The node '" + nodeS + "' is not known."); - } - return node; -} - -NBNode* -NIImporter_VISUM::getNamedNodeSecure(const std::string& fieldName, NBNode* fallback) { - std::string nodeS = NBHelpers::normalIDRepresentation(myLineParser.get(fieldName)); - NBNode* node = myNetBuilder.getNodeCont().retrieve(nodeS); - if (node == nullptr) { - return fallback; - } - return node; -} - - -NBNode* -NIImporter_VISUM::getNamedNode(const std::string& fieldName1, const std::string& fieldName2) { - if (myLineParser.know(fieldName1)) { - return getNamedNode(fieldName1); - } else { - return getNamedNode(fieldName2); - } -} - - -NBEdge* -NIImporter_VISUM::getNamedEdge(const std::string& fieldName) { - std::string edgeS = NBHelpers::normalIDRepresentation(myLineParser.get(fieldName)); - NBEdge* edge = myNetBuilder.getEdgeCont().retrieve(edgeS); - if (edge == nullptr) { - WRITE_ERROR("The edge '" + edgeS + "' is not known."); - } - return edge; -} - - -NBEdge* -NIImporter_VISUM::getNamedEdge(const std::string& fieldName1, const std::string& fieldName2) { - if (myLineParser.know(fieldName1)) { - return getNamedEdge(fieldName1); - } else { - return getNamedEdge(fieldName2); - } -} - - - -NBEdge* -NIImporter_VISUM::getReversedContinuating(NBEdge* edge, NBNode* node) { - std::string sid; - if (edge->getID()[0] == '-') { - sid = edge->getID().substr(1); - } else { - sid = "-" + edge->getID(); - } - if (sid.find('_') != std::string::npos) { - sid = sid.substr(0, sid.find('_')); - } - return getNamedEdgeContinuating(myNetBuilder.getEdgeCont().retrieve(sid), node); -} - - -NBEdge* -NIImporter_VISUM::getNamedEdgeContinuating(NBEdge* begin, NBNode* node) { - if (begin == nullptr) { - return nullptr; - } - NBEdge* ret = begin; - std::string edgeID = ret->getID(); - // hangle forward - while (ret != nullptr) { - // ok, this is the edge we are looking for - if (ret->getToNode() == node) { - return ret; - } - const EdgeVector& nedges = ret->getToNode()->getOutgoingEdges(); - if (nedges.size() != 1) { - // too many edges follow - ret = nullptr; - continue; - } - NBEdge* next = nedges[0]; - if (ret->getID().substr(0, edgeID.length()) != next->getID().substr(0, edgeID.length())) { - // ok, another edge is next... - ret = nullptr; - continue; - } - if (next->getID().substr(next->getID().length() - node->getID().length()) != node->getID()) { - ret = nullptr; - continue; - } - ret = next; - } - - ret = begin; - // hangle backward - while (ret != nullptr) { - // ok, this is the edge we are looking for - if (ret->getFromNode() == node) { - return ret; - } - const EdgeVector& nedges = ret->getFromNode()->getIncomingEdges(); - if (nedges.size() != 1) { - // too many edges follow - ret = nullptr; - continue; - } - NBEdge* next = nedges[0]; - if (ret->getID().substr(0, edgeID.length()) != next->getID().substr(0, edgeID.length())) { - // ok, another edge is next... - ret = nullptr; - continue; - } - if (next->getID().substr(next->getID().length() - node->getID().length()) != node->getID()) { - ret = nullptr; - continue; - } - ret = next; - } - return nullptr; -} - - -NBEdge* -NIImporter_VISUM::getNamedEdgeContinuating(const std::string& fieldName, NBNode* node) { - std::string edgeS = NBHelpers::normalIDRepresentation(myLineParser.get(fieldName)); - NBEdge* edge = myNetBuilder.getEdgeCont().retrieve(edgeS); - if (edge == nullptr) { - WRITE_ERROR("The edge '" + edgeS + "' is not known."); - } - return getNamedEdgeContinuating(edge, node); -} - - -NBEdge* -NIImporter_VISUM::getNamedEdgeContinuating(const std::string& fieldName1, const std::string& fieldName2, - NBNode* node) { - if (myLineParser.know(fieldName1)) { - return getNamedEdgeContinuating(fieldName1, node); - } else { - return getNamedEdgeContinuating(fieldName2, node); - } -} - - -NBEdge* -NIImporter_VISUM::getEdge(NBNode* FromNode, NBNode* ToNode) { - EdgeVector::const_iterator i; - for (i = FromNode->getOutgoingEdges().begin(); i != FromNode->getOutgoingEdges().end(); i++) { - if (ToNode == (*i)->getToNode()) { - return (*i); - } - } - //!!! - return nullptr; -} - - -double -NIImporter_VISUM::getNamedFloat(const std::string& fieldName) { - std::string value = myLineParser.get(fieldName); - if (StringUtils::endsWith(myLineParser.get(fieldName), "km/h")) { - value = value.substr(0, value.length() - 4); - } - return StringUtils::toDouble(value); -} - - -double -NIImporter_VISUM::getNamedFloat(const std::string& fieldName, double defaultValue) { - try { - return StringUtils::toDouble(myLineParser.get(fieldName)); - } catch (...) { - return defaultValue; - } -} - - -double -NIImporter_VISUM::getNamedFloat(const std::string& fieldName1, const std::string& fieldName2) { - if (myLineParser.know(fieldName1)) { - return getNamedFloat(fieldName1); - } else { - return getNamedFloat(fieldName2); - } -} - - -double -NIImporter_VISUM::getNamedFloat(const std::string& fieldName1, const std::string& fieldName2, - double defaultValue) { - if (myLineParser.know(fieldName1)) { - return getNamedFloat(fieldName1, defaultValue); - } else { - return getNamedFloat(fieldName2, defaultValue); - } -} - - -std::string -NIImporter_VISUM::getNamedString(const std::string& fieldName) { - return NBHelpers::normalIDRepresentation(myLineParser.get(fieldName)); -} - - -std::string -NIImporter_VISUM::getNamedString(const std::string& fieldName1, - const std::string& fieldName2) { - if (myLineParser.know(fieldName1)) { - return getNamedString(fieldName1); - } else { - return getNamedString(fieldName2); - } -} - - - - - - -NBNode* -NIImporter_VISUM::buildDistrictNode(const std::string& id, NBNode* dest, - bool isSource) { - // get the district - NBDistrict* dist = myNetBuilder.getDistrictCont().retrieve(id); - if (dist == nullptr) { - return nullptr; - } - // build the id - std::string nid; - nid = id + "-" + dest->getID(); - if (!isSource) { - nid = "-" + nid; - } - // insert the node - if (!myNetBuilder.getNodeCont().insert(nid, dist->getPosition())) { - WRITE_ERROR("Could not build connector node '" + nid + "'."); - } - // return the node - return myNetBuilder.getNodeCont().retrieve(nid); -} - - -bool -NIImporter_VISUM::checkNodes(NBNode* from, NBNode* to) { - if (from == nullptr) { - WRITE_ERROR(" The from-node was not found within the net"); - } - if (to == nullptr) { - WRITE_ERROR(" The to-node was not found within the net"); - } - if (from == to) { - WRITE_ERROR(" Both nodes are the same"); - } - return from != nullptr && to != nullptr && from != to; -} - -bool -NIImporter_VISUM::isSplitEdge(NBEdge* edge, NBNode* node) { - return (edge->getID().length() > node->getID().length() + 1 - && (edge->getID().substr(edge->getID().length() - node->getID().length() - 1) == "_" + node->getID())); -} - -void -NIImporter_VISUM::loadLanguage(const std::string& file) { - std::ifstream strm(file.c_str()); - if (!strm.good()) { - throw ProcessError("Could not load VISUM language map from '" + file + "'."); - } - while (strm.good()) { - std::string keyDE; - std::string keyNew; - strm >> keyDE; - strm >> keyNew; - if (KEYS.hasString(keyDE)) { - VISUM_KEY key = KEYS.get(keyDE); - KEYS.remove(keyDE, key); - KEYS.insert(keyNew, key); - } else if (keyDE != "") { - WRITE_WARNING("Unknown entry '" + keyDE + "' in VISUM language map"); - } - } - -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/NIImporter_VISUM.h b/Util/OSM2ODR/src/netimport/NIImporter_VISUM.h deleted file mode 100644 index 68c4fb4e4..000000000 --- a/Util/OSM2ODR/src/netimport/NIImporter_VISUM.h +++ /dev/null @@ -1,575 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIImporter_VISUM.h -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Fri, 19 Jul 2002 -/// -// A VISUM network importer -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include -#include -#include -#include -#include -#include "NIVisumTL.h" - - -// =========================================================================== -// class declaration -// =========================================================================== -class OptionsCont; -class NBNetBuilder; -class NBNodeCont; -class NBEdgeCont; -class NBNode; -class NBEdge; - - -// =========================================================================== -// class declaration -// =========================================================================== -/** - * @class NIImporter_VISUM - * @brief A VISUM network importer - * - * This class build an internal list of those VISUM-db entries which are - * supported, first. This list is sorted in a way that the parsed dbs can - * build upon each other as their related structures within the XML-input. - * So, nodes are loaded first, then edges, etc. - * - * Because these structures may have a different order within the VISUM-file - * than we need, at first the file is scanned and any occurence of one of the - * searched dbs is saved. That's where the "Found $XXX at YYY" are printed. - * "YYY" is the character position within the file. - * - * In a second step, the dbs are parsed in the order we need. It is asked for - * each subsequently whether it was found and if so, the proper parse_XXX() - * method is called. - */ -class NIImporter_VISUM { -public: - /** @brief Loads network definition from the assigned option and stores it in the given network builder - * - * If the option "visum" is set, the file stored therein is read and - * the network definition stored therein is stored within the given network - * builder. - * - * If the option "visum" is not set, this method simply returns. - * - * @param[in] oc The options to use - * @param[in] nb The network builder to fill - */ - static void loadNetwork(const OptionsCont& oc, NBNetBuilder& nb); - - -protected: - /** @brief constructor - * - * Builds the list of typed db parsers ("TypeParser") and stores them in - * mySingleDataParsers in the order the according db values must be parsed. - * - * @param[in,out] nb the network builder (storage) to fill with parsed values - * @param[in] file The name of the file to parse - * @param[in] capacity2Lanes The converter from flow to lanes - * @param[in] useVisumPrio Information whether the VISUM type's priority shall be used - */ - NIImporter_VISUM(NBNetBuilder& nb, const std::string& file, - NBCapacity2Lanes capacity2Lanes, bool useVisumPrio, - const std::string& languageFile); - - - /// @brief destructor - ~NIImporter_VISUM(); - - - /** @brief Parses the VISUM-network file storing the parsed structures within myNetBuilder - * - * At first, it is checked whether the file can be opened. A ProcessError is thrown - * if not. Otherwise, the file is scanned for occurences of db table begins. For each found - * db, its position within the file, and the column names are stored in the according - * TypeParser. After this, the sorted list of type parsers is one through and each - * found is used to parse the entries at the found positions using the found column names. - * - * @exception ProcessError If the file could not be opened - */ - void load(); - -private: - /** @brief Returns the value from the named column as a float - * - * @param[in] fieldName Name of the column to extract the float from - * @return The parsed real - * @exception OutOfBoundsException If the current data line has less entries than the float's position - * @exception NumberFormatException If the float is not numeric - * @exception UnknownElement If the named data field is not in the line - */ - double getNamedFloat(const std::string& fieldName); - - /** @brief The same, but two different names for the field are allowed - * - * @param[in] fieldName1 Name of the first column to extract the float from - * @param[in] fieldName2 Name of the second column to extract the efloat from - * @return The parsed real - * @exception OutOfBoundsException If the current data line has less entries than the float's position - * @exception NumberFormatException If the float is not numeric - * @exception UnknownElement If the named data field is not in the line - */ - double getNamedFloat(const std::string& fieldName1, const std::string& fieldName2); - - - /** @brief Returns the value from the named column as a float or the default value if an error occurs - * - * @param[in] fieldName Name of the column to extract the float from - * @param[in] defaultValue The default to return in the case of an error - * @return The parsed real or the default value if an error while parsing occurred - */ - double getNamedFloat(const std::string& fieldName, double defaultValue); - - /** @brief The same, but two different names for the field are allowed - * - * @param[in] fieldName1 Name of the first column to extract the float from - * @param[in] fieldName2 Name of the second column to extract the efloat from - * @param[in] defaultValue The default to return in the case of an error - * @return The parsed real or the default value if an error while parsing occurred - */ - double getNamedFloat(const std::string& fieldName1, const std::string& fieldName2, - double defaultValue); - - - /** @brief Returns the value from the named column as a normalised string - * - * "Normalised" means herein that the leading '0' (zeros) are prunned. - * - * @param[in] fieldName Name of the column to extract the string from - * @return The parsed, normalised string - * @exception OutOfBoundsException If the current data line has less entries than the string's position - * @exception NumberFormatException If the string is not numeric - * @exception UnknownElement If the named data field is not in the line - */ - std::string getNamedString(const std::string& fieldName); - - /** @brief The same, but two different names for the field are allowed - * - * @param[in] fieldName1 Name of the first column to extract the string from - * @param[in] fieldName2 Name of the second column to extract the string from - * @return The parsed, normalised string - * @exception OutOfBoundsException If the current data line has less entries than the string's position - * @exception NumberFormatException If the string is not numeric - * @exception UnknownElement If the named data field is not in the line - */ - std::string getNamedString(const std::string& fieldName1, const std::string& fieldName2); - - - /** @brief tries to get a double which is possibly assigned to a certain modality - * - * When the double cannot be extracted using the given name, "(IV)" is - * appended to the begin of the name. Note that this function does not - * yet support public traffic. - * - * @param[in] name Name of the column to extract the real from - * @return The real stored under the named column, or if not found the one from name + suffix, or if not found -1 - */ - double getWeightedFloat(const std::string& name, const std::string& suffix); - - /// @brief as above but with two alternative names - double getWeightedFloat2(const std::string& name, const std::string& name2, const std::string& suffix); - - /// @brief parse permissions - SVCPermissions getPermissions(const std::string& name, bool warn = false, SVCPermissions unknown = SVCAll); - - /** @brief tries to get a bool which is possibly assigned to a certain modality - * - * When the bool cannot be extracted using the given name, "IV" is - * appended to the begin of the name. Note that this function does not - * yet support public traffic. - * - * @param[in] name Name of the column to extract the bool from - * @return The bool stored under the named column, or if not found the one from "(IV)"+name, or if not found false - */ - bool getWeightedBool(const std::string& name); - - - /** @brief Tries to get the node which name is stored in the given field - * - * If the field can not be parsed, an exception is thrown. Prints an error if the - * node could not be found, returning 0. Otherwise, if the field could be parsed - * and the node was found, this node is returned. - * - * @param[in] fieldName Name of the column to extract the node's name from - * @return An already known node with the found name - * @exception OutOfBoundsException If the current data line has less entries than the node id's position - * @exception NumberFormatException If the node id is not numeric - * @exception UnknownElement If the named data field is not in the line - */ - NBNode* getNamedNode(const std::string& fieldName); - NBNode* getNamedNodeSecure(const std::string& fieldName, NBNode* fallback = 0); - - /** @brief The same, but two different names for the field are allowed - * - * @param[in] fieldName1 Name of the first column to extract the node's name from - * @param[in] fieldName2 Name of the second column to extract the node's name from - * @return An already known node with the found name - * @exception OutOfBoundsException If the current data line has less entries than the node id's position - * @exception NumberFormatException If the node id is not numeric - * @exception UnknownElement If the named data field is not in the line - */ - NBNode* getNamedNode(const std::string& fieldName1, const std::string& fieldName2); - - - /** @brief Tries to get the edge which name is stored in the given field - * - * If the field can not be parsed, an exception is thrown. Prints an error if the - * edge could not be found, returning 0. Otherwise, if the field could be parsed - * and the edge was found, this edge is returned. - * - * @param[in] fieldName Name of the column to extract the edge's name from - * @return An already known edge with the found name - * @exception OutOfBoundsException If the current data line has less entries than the edge id's position - * @exception NumberFormatException If the edge id is not numeric - * @exception UnknownElement If the named data field is not in the line - */ - NBEdge* getNamedEdge(const std::string& fieldName); - - /** @brief The same, but two different names for the field are allowed - * - * @param[in] fieldName1 Name of the first column to extract the edge's name from - * @param[in] fieldName2 Name of the second column to extract the edge's name from - * @return An already known edge with the found name - * @exception OutOfBoundsException If the current data line has less entries than the edge id's position - * @exception NumberFormatException If the edge id is not numeric - * @exception UnknownElement If the named data field is not in the line - */ - NBEdge* getNamedEdge(const std::string& fieldName1, const std::string& fieldName2); - - - /** @brief Tries to get the edge which name is stored in the given field - * continuating the search for a subedge that ends at the given node - * - * If the field can not be parsed, an exception is thrown. Prints an error if the - * edge could not be found, returning 0. Otherwise, if the field could be parsed - * and the edge was found, this edge is returned. - * - * @param[in] fieldName Name of the column to extract the edge's name from - * @param[in] node The node the consecutive edge must end at in order to be returned - * @return The edge's continuation up to the given node, 0 if not found - * @exception OutOfBoundsException If the current data line has less entries than the edge id's position - * @exception NumberFormatException If the edge id is not numeric - * @exception UnknownElement If the named data field is not in the line - */ - NBEdge* getNamedEdgeContinuating(const std::string& fieldName, NBNode* node); - - /** @brief The same, but two different names for the field are allowed - * - * @param[in] fieldName1 Name of the first column to extract the edge's name from - * @param[in] fieldName2 Name of the second column to extract the edge's name from - * @param[in] node The node the consecutive edge must end at in order to be returned - * @return The edge's continuation up to the given node, 0 if not found - * @exception OutOfBoundsException If the current data line has less entries than the edge id's position - * @exception NumberFormatException If the edge id is not numeric - * @exception UnknownElement If the named data field is not in the line - */ - NBEdge* getNamedEdgeContinuating(const std::string& fieldName1, const std::string& fieldName2, - NBNode* node); - - /** @brief The same, but for an already given edge - * - * @param[in] begin The edge to get the continuation of - * @param[in] node The node the consecutive edge must end at in order to be returned - * @return The edge's continuation up to the given node, 0 if not found - */ - NBEdge* getNamedEdgeContinuating(NBEdge* begin, NBNode* node); - - - /** @brief Returns the edge that connects both nodes - * - * @param[in] FromNode Name of the node the edge shall start at - * @param[in] ToNode Name of the node the edge shall end at - * @return The edge connecting both nodes, 0 if no such edge exists - */ - NBEdge* getEdge(NBNode* FromNode, NBNode* ToNode); - - - /** @brief Returns the opposite direction of the given edge - * - * Because the opposite direction edge may be split, not the the plain opposite - * edge, the one which name is obtained by adding/removing the leading '-', is returned, - * but its continuation until the named node. - * - * @param[in] edge Name of the edge to find the opposite of - * @param[in] node Name of the node the opposite edge's continuation must end at - * @return The found opposite edge's continuation, 0 if not found - */ - NBEdge* getReversedContinuating(NBEdge* edge, NBNode* node); - - - /** @brief Builds a node for the given district and returns it - * - * If the district does not exist, an error is generated and 0 returned. Otherwise - * a position for the new node is computed and the new node is built using a combination - * of the district name and the node name as id. If Inserting this node into - * the net builder fails, zero is returned. - * - * @param[in] id Name of the district - * @param[in] dest Name of the according network node - * @param[in] isSource Information whether this node will be used as a source - * @return The built node, zero if an error occurred - */ - NBNode* buildDistrictNode(const std::string& id, NBNode* dest, bool isSource); - - - /** @brief Returns whether both nodes are a valid combination of from/to-nodes - * - * They are valid if both are !=0 and differ. - * - * @param[in] from The from-node - * @param[in] from The to-node - * @return Whether the nodes may be used - */ - bool checkNodes(NBNode* from, NBNode* to); - - -private: - /** - * @brief Definition of a function for parsing a single line from a certain db - * - * This function may assume that both the LineParser is initialised - * with the current line. - */ - typedef void (NIImporter_VISUM::*ParsingFunction)(); - - /** - * @struct TypeParser - * @brief A complete call description for parsing a single db. - */ - struct TypeParser { - /** @brief The name of the db - * - * Initialised in the constructor */ - std::string name; - - /** @brief Pointer to the function used for parsing - * - * Initialised in the constructor */ - ParsingFunction function; - - /** @brief Position of the according db within the file - * - * Set to -1 in the constructor, and reset to the position while - * scaning the file if the according db was found */ - long position; - - /** @brief The column names - * - * Set while scaning the file if the according db was found */ - std::string pattern; - - }; - - - - /// @brief Parses VSYS - void parse_VSysTypes(); - - /// @brief Parses STRECKENTYP - void parse_Types(); - - /// @brief Parses KNOTEN - void parse_Nodes(); - - /// @brief Parses BEZIRK - void parse_Districts(); - - /// @brief Parses PUNKT - void parse_Point(); - - - /// @brief Parses STRECKE/STRECKEN - void parse_Edges(); - - /// @brief Parses FLAECHENELEMENT - void parse_PartOfArea(); - - /// @brief Parses FLAECHENELEMENT - void parse_Kante(); - - - /// @brief Parses ANBINDUNG - void parse_Connectors(); - void parse_Connectors_legacy(); - - /// @brief Parses ABBIEGEBEZIEHUNG/ABBIEGER - void parse_Turns(); - - /// @brief Parses STRECKENPOLY - void parse_EdgePolys(); - - /// @brief Parses FAHRSTREIFEN - void parse_Lanes(); - - /// @brief Parses LSA/SIGNALANLAGE - void parse_TrafficLights(); - - /// @brief Parses KNOTENZULSA/SIGNALANLAGEZUKNOTEN - void parse_NodesToTrafficLights(); - - /// @brief Parses LSASIGNALGRUPPE/SIGNALGRUPPE - void parse_SignalGroups(); - - /// @brief Parses ABBZULSASIGNALGRUPPE/SIGNALGRUPPEZUABBIEGER - void parse_TurnsToSignalGroups(); - - /// @brief Parses ABBZULSASIGNALGRUPPE/SIGNALGRUPPEZUABBIEGER - void parse_AreaSubPartElement(); - - /// @brief Parses LSAPHASE/PHASE - void parse_Phases(); - - /// @brief Parses LSASIGNALGRUPPEZULSAPHASE - void parse_SignalGroupsToPhases(); - - /// @brief Parses FAHRSTREIFENABBIEGER - void parse_LanesConnections(); - - - /** @brief Adds a parser into the sorted list of parsers to use - * - * @param[in] name db name to assign the parser to - * @param[in] function The function to use for parsing the named db - */ - void addParser(const std::string& name, ParsingFunction function); - -private: - - /// @brief whether the edge id ends with _nodeID - static bool isSplitEdge(NBEdge* edge, NBNode* node); - - -private: - /// @brief The network builder to fill with loaded values - NBNetBuilder& myNetBuilder; - - /// @brief The name of the parsed file, for error reporting - std::string myFileName; - - /// @brief The line reader to use to read from the file - LineReader myLineReader; - - /** @brief the parser to parse the information from the data lines - * - * the order of columns within the visum format seems to vary, so a named parser is needed */ - NamedColumnsParser myLineParser; - - /// @brief The converter to compute the lane number of edges from their capacity - NBCapacity2Lanes myCapacity2Lanes; - - /// @brief Definition of a storage for vsystypes - typedef std::map VSysTypeNames; - /// @brief The used vsystypes - VSysTypeNames myVSysTypes; - - /// @brief Definition of the list of known parsers - typedef std::vector ParserVector; - /// @brief List of known parsers - ParserVector mySingleDataParsers; - - /// @brief Definition of a map for loaded traffic lights (id->tls) - typedef std::map NIVisumTL_Map; - /// @brief List of visum traffic lights - NIVisumTL_Map myTLS; - - /// @brief Already read edges - std::vector myTouchedEdges; - - /// @brief Information whether VISUM priority information shall be used - bool myUseVisumPrio; - - /// @brief The name of the currently parsed item used for error reporting - std::string myCurrentID; - - - /// @brief A map of point ids to positions - std::map myPoints; - - /// @brief A map of edge (not road, but "edge" in this case) ids to from/to-points - std::map > myEdges; - - /// @brief A map from district shape definition name to the district - std::map myShapeDistrictMap; - - /// @brief A map from area parts to area ids - std::map > mySubPartsAreas; - - /// @brief A temporary storage for district shapes as they are filled incrementally - std::map myDistrictShapes; - -protected: - /** - * @enum VISUM keys - * @brief Numbers representing VISUM keywords - */ - enum VISUM_KEY { - VISUM_SYS, - VISUM_LINKTYPE, - VISUM_NODE, - VISUM_DISTRICT, - VISUM_POINT, - VISUM_LINK, - VISUM_V0, - VISUM_TYPES, - VISUM_RANK, - VISUM_CAPACITY, - VISUM_XCOORD, - VISUM_YCOORD, - VISUM_FROMNODE, - VISUM_TONODE, - VISUM_TYPE, - VISUM_TYP, - VISUM_ID, - VISUM_CODE, - VISUM_DISTRICT_CONNECTION, - VISUM_SOURCE_DISTRICT, - VISUM_FROMNODENO, - VISUM_DIRECTION, - VISUM_SURFACEID, - VISUM_FACEID, - VISUM_FROMPOINTID, - VISUM_TOPOINTID, - VISUM_EDGE, - VISUM_VIANODENO, - VISUM_NUMLANES, - VISUM_TURN, - VISUM_INDEX, - VISUM_LINKPOLY, - VISUM_SURFACEITEM, - VISUM_FACEITEM, - VISUM_EDGEID, - VISUM_ORIGIN, - VISUM_DESTINATION, - VISUM_NO // must be the last one - }; - - /// Strings for the keywords - static StringBijection::Entry KEYS_DE[]; - - /// @brief link directions - static StringBijection KEYS; - - void loadLanguage(const std::string& file); -}; diff --git a/Util/OSM2ODR/src/netimport/NILoader.cpp b/Util/OSM2ODR/src/netimport/NILoader.cpp deleted file mode 100644 index df40c2c32..000000000 --- a/Util/OSM2ODR/src/netimport/NILoader.cpp +++ /dev/null @@ -1,209 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NILoader.cpp -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Sascha Krieg -/// @author Michael Behrisch -/// @author Robert Hilbrich -/// @date Tue, 20 Nov 2001 -/// -// Perfoms network import -/****************************************************************************/ -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "NILoader.h" -#include "NITypeLoader.h" - -// =========================================================================== -// method definitions -// =========================================================================== -NILoader::NILoader(NBNetBuilder& nb) - : myNetBuilder(nb) {} - -NILoader::~NILoader() {} - -void -NILoader::load(OptionsCont& oc) { - // load types first - NIXMLTypesHandler* handler = - new NIXMLTypesHandler(myNetBuilder.getTypeCont()); - if (!oc.isSet("type-files")) { - std::vector files; - if (oc.isSet("osm-files")) { - files.push_back(osmTypemap); - } - if (oc.isSet("opendrive-files")) { - files.push_back(opendriveTypemap); - } - NITypeLoader::load(handler, files, "types", true); - } else { - NITypeLoader::load(handler, oc.getStringVector("type-files"), "types"); - } - // try to load height data so it is ready for use by other importers - NBHeightMapper::loadIfSet(oc); - // try to load using different methods - NIImporter_SUMO::loadNetwork(oc, myNetBuilder); - NIImporter_OpenStreetMap::loadNetwork(oc, myNetBuilder); - NIImporter_VISUM::loadNetwork(oc, myNetBuilder); - NIImporter_ArcView::loadNetwork(oc, myNetBuilder); - NIImporter_Vissim::loadNetwork(oc, myNetBuilder); - NIImporter_DlrNavteq::loadNetwork(oc, myNetBuilder); - NIImporter_OpenDrive::loadNetwork(oc, myNetBuilder); - NIImporter_MATSim::loadNetwork(oc, myNetBuilder); - NIImporter_ITSUMO::loadNetwork(oc, myNetBuilder); - if (oc.getBool("tls.discard-loaded") || oc.getBool("tls.discard-simple")) { - myNetBuilder.getNodeCont().discardTrafficLights(myNetBuilder.getTLLogicCont(), oc.getBool("tls.discard-simple"), - oc.getBool("tls.guess-signals")); - int removed = myNetBuilder.getTLLogicCont().getNumExtracted(); - if (removed > 0) { - WRITE_MESSAGE(" Removed " + toString(removed) + " traffic lights before loading plain-XML"); - } - } - if (oc.getBool("railway.signals.discard")) { - myNetBuilder.getNodeCont().discardRailSignals(); - } - loadXML(oc); - // check the loaded structures - if (myNetBuilder.getNodeCont().size() == 0) { - throw ProcessError("No nodes loaded."); - } - if (myNetBuilder.getEdgeCont().size() == 0) { - throw ProcessError("No edges loaded."); - } - if (!myNetBuilder.getEdgeCont().checkConsistency(myNetBuilder.getNodeCont())) { - throw ProcessError(); - } - // report loaded structures - WRITE_MESSAGE(" Import done:"); - if (myNetBuilder.getDistrictCont().size() > 0) { - WRITE_MESSAGE(" " + toString(myNetBuilder.getDistrictCont().size()) + " districts loaded."); - } - WRITE_MESSAGE(" " + toString(myNetBuilder.getNodeCont().size()) + " nodes loaded."); - if (myNetBuilder.getTypeCont().size() > 0) { - WRITE_MESSAGE(" " + toString(myNetBuilder.getTypeCont().size()) + " types loaded."); - } - WRITE_MESSAGE(" " + toString(myNetBuilder.getEdgeCont().size()) + " edges loaded."); - if (myNetBuilder.getEdgeCont().getNoEdgeSplits() > 0) { - WRITE_MESSAGE( - "The split of edges was performed " + toString(myNetBuilder.getEdgeCont().getNoEdgeSplits()) + " times."); - } - - //TODO: uncomment the following lines + adapt tests! [Gregor March '17] -// if (myNetBuilder.getPTStopCont().size() > 0) { -// WRITE_MESSAGE(" " + toString(myNetBuilder.getPTStopCont().size()) + " pt stops loaded."); -// } - if (GeoConvHelper::getProcessing().usingGeoProjection()) { - WRITE_MESSAGE("Proj projection parameters used: '" + GeoConvHelper::getProcessing().getProjString() + "'."); - } -} - -/* ------------------------------------------------------------------------- - * file loading methods - * ----------------------------------------------------------------------- */ -bool -NILoader::loadXML(OptionsCont& oc) { - // load nodes - bool ok = NITypeLoader::load(new NIXMLNodesHandler(myNetBuilder.getNodeCont(), myNetBuilder.getEdgeCont(), - myNetBuilder.getTLLogicCont(), oc), - oc.getStringVector("node-files"), "nodes"); - // load the edges - if (ok) { - ok = NITypeLoader::load(new NIXMLEdgesHandler(myNetBuilder.getNodeCont(), - myNetBuilder.getEdgeCont(), - myNetBuilder.getTypeCont(), - myNetBuilder.getDistrictCont(), - myNetBuilder.getTLLogicCont(), - oc), - oc.getStringVector("edge-files"), "edges"); - } - if (!deprecatedVehicleClassesSeen.empty()) { - WRITE_WARNING("Deprecated vehicle class(es) '" + toString(deprecatedVehicleClassesSeen) + "' in input edge files."); - } - // load the connections - if (ok) { - ok = NITypeLoader::load(new NIXMLConnectionsHandler(myNetBuilder.getEdgeCont(), - myNetBuilder.getNodeCont(), - myNetBuilder.getTLLogicCont()), - oc.getStringVector("connection-files"), "connections"); - } - // load traffic lights (needs to come last, references loaded edges and connections) - if (ok) { - ok = NITypeLoader::load(new NIXMLTrafficLightsHandler( - myNetBuilder.getTLLogicCont(), myNetBuilder.getEdgeCont()), - oc.getStringVector("tllogic-files"), "traffic lights"); - } - - // load public transport stops (used for restricting edge removal and as input when repairing railroad topology) - if (ok && oc.exists("ptstop-files")) { - ok = NITypeLoader::load(new NIXMLPTHandler( - myNetBuilder.getEdgeCont(), - myNetBuilder.getPTStopCont(), - myNetBuilder.getPTLineCont()), - oc.getStringVector("ptstop-files"), "public transport stops"); - } - - // load public transport lines (used as input when repairing railroad topology) - if (ok && oc.exists("ptline-files")) { - ok = NITypeLoader::load(new NIXMLPTHandler( - myNetBuilder.getEdgeCont(), - myNetBuilder.getPTStopCont(), - myNetBuilder.getPTLineCont()), - oc.getStringVector("ptline-files"), "public transport lines"); - } - - // load shapes for output formats that embed shape data - if (ok && oc.exists("polygon-files")) { - ok = NITypeLoader::load(new NIXMLShapeHandler( - myNetBuilder.getShapeCont(), - myNetBuilder.getEdgeCont()), - oc.getStringVector("polygon-files"), "polygon data"); - } - return ok; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/NILoader.h b/Util/OSM2ODR/src/netimport/NILoader.h deleted file mode 100644 index 0fbe7e161..000000000 --- a/Util/OSM2ODR/src/netimport/NILoader.h +++ /dev/null @@ -1,85 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NILoader.h -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date Tue, 20 Nov 2001 -/// -// Perfoms network import -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include - - -// =========================================================================== -// class declarations -// =========================================================================== -class OptionsCont; -class NBNetBuilder; -class Position; -class PositionVector; - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NILoader - * @brief Perfoms network import - * - * A plain loader which encapsulates calls to the import modules. - */ -class NILoader { -public: - /** @brief Constructor - * @param[in] nb The network builder to fill with loaded data - */ - NILoader(NBNetBuilder& nb); - - - /// @brief Destructor - ~NILoader(); - - - /** loads data from the files specified in the given option container */ - void load(OptionsCont& oc); - - -private: - /** loads data from sumo-files */ - //void loadSUMO(OptionsCont &oc); - - /** loads data from XML-files */ - bool loadXML(OptionsCont& oc); - - -private: - /// @brief The network builder to fill with loaded data - NBNetBuilder& myNetBuilder; - - -private: - /// @brief Invalidated copy constructor. - NILoader(const NILoader&); - - /// @brief Invalidated assignment operator. - NILoader& operator=(const NILoader&); - - -}; diff --git a/Util/OSM2ODR/src/netimport/NINavTeqHelper.cpp b/Util/OSM2ODR/src/netimport/NINavTeqHelper.cpp deleted file mode 100644 index 8cbf087e7..000000000 --- a/Util/OSM2ODR/src/netimport/NINavTeqHelper.cpp +++ /dev/null @@ -1,235 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NINavTeqHelper.cpp -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Sascha Krieg -/// @author Michael Behrisch -/// @date Jul 2006 -/// -// Some parser methods shared around several formats containing NavTeq-Nets -/****************************************************************************/ -#include - -#include "NINavTeqHelper.h" -#include -#include -#include -#include - - -// =========================================================================== -// method definitions -// =========================================================================== -double -NINavTeqHelper::getSpeed(const std::string& id, const std::string& speedClassS) { - try { - int speedClass = StringUtils::toInt(speedClassS); - switch (speedClass) { - case -1: - return (double) 1.0 / (double) 3.6; - case 1: - return (double) 200 / (double) 3.6; //> 130 KPH / > 80 MPH - case 2: - return (double) 120 / (double) 3.6; //101-130 KPH / 65-80 MPH - case 3: - return (double) 100 / (double) 3.6; // 91-100 KPH / 55-64 MPH - case 4: - return (double) 80 / (double) 3.6; // 71-90 KPH / 41-54 MPH - case 5: - return (double) 70 / (double) 3.6; // 51-70 KPH / 31-40 MPH - case 6: - return (double) 50 / (double) 3.6; // 31-50 KPH / 21-30 MPH - case 7: - return (double) 30 / (double) 3.6; // 11-30 KPH / 6-20 MPH - case 8: - return (double) 5 / (double) 3.6; //< 11 KPH / < 6 MPH - default: - throw ProcessError("Invalid speed code (edge '" + id + "')."); - } - } catch (NumberFormatException&) { - throw ProcessError("Non-numerical value for an edge's speed type occurred (edge '" + id + "')."); - } -} - - -int -NINavTeqHelper::getLaneNumber(const std::string& id, const std::string& laneNoS, double speed) { - try { - int nolanes = StringUtils::toInt(laneNoS); - if (nolanes < 0) { - return 1; - } else if (nolanes / 10 > 0) { - return nolanes / 10; - } else { - switch (nolanes % 10) { - case 1: - return 1; - case 2: - nolanes = 2; - if (speed > 78.0 / 3.6) { - nolanes = 3; - } - return nolanes; - case 3: - return 4; - default: - throw ProcessError("Invalid lane number (edge '" + id + "')."); - } - } - } catch (NumberFormatException&) { - throw ProcessError("Non-numerical value for an edge's lane number occurred (edge '" + id + "'."); - } -} - - -bool -NINavTeqHelper::addCommonVehicleClasses(NBEdge& e, const std::string& classS, const int offset) { - bool haveCar = false; - // High Occupancy Vehicle -- becomes SVC_PASSENGER|SVC_HOV - if (classS[offset] == '1') { - e.allowVehicleClass(-1, SVC_HOV); - e.allowVehicleClass(-1, SVC_PASSENGER); - haveCar = true; - } else { - e.disallowVehicleClass(-1, SVC_HOV); - } - // Emergency Vehicle -- becomes SVC_EMERGENCY - if (classS[offset + 1] == '1') { - e.allowVehicleClass(-1, SVC_EMERGENCY); - } else { - e.disallowVehicleClass(-1, SVC_EMERGENCY); - } - // Taxi -- becomes SVC_TAXI - if (classS[offset + 2] == '1') { - e.allowVehicleClass(-1, SVC_TAXI); - haveCar = true; - } else { - e.disallowVehicleClass(-1, SVC_TAXI); - } - // Public Bus -- becomes SVC_BUS|SVC_COACH - if (classS[offset + 3] == '1') { - e.allowVehicleClass(-1, SVC_BUS); - e.allowVehicleClass(-1, SVC_COACH); - haveCar = true; - } else { - e.disallowVehicleClass(-1, SVC_BUS); - e.disallowVehicleClass(-1, SVC_COACH); - } - // Delivery Truck -- becomes SVC_DELIVERY - if (classS[offset + 4] == '1') { - e.allowVehicleClass(-1, SVC_DELIVERY); - haveCar = true; - } else { - e.disallowVehicleClass(-1, SVC_DELIVERY); - } - // Transport Truck -- becomes SVC_TRUCK|SVC_TRAILER - if (classS[offset + 5] == '1') { - e.allowVehicleClass(-1, SVC_TRUCK); - e.allowVehicleClass(-1, SVC_TRAILER); - haveCar = true; - } else { - e.disallowVehicleClass(-1, SVC_TRUCK); - e.disallowVehicleClass(-1, SVC_TRAILER); - } - return haveCar; -} - - -void -NINavTeqHelper::addVehicleClasses(NBEdge& e, const std::string& oclassS, const SVCPermissions allPermissions, const SVCPermissions defaultPermissions) { - std::string classS = "0000000000" + oclassS; - classS = classS.substr(classS.length() - 10); - // 0: allow all vehicle types - if (classS[0] == '1') { - e.setPermissions(allPermissions); - return; - } - bool haveCar = false; - e.setPermissions(defaultPermissions); - // Passenger cars -- becomes SVC_PASSENGER - if (classS[1] == '1') { - e.allowVehicleClass(-1, SVC_PASSENGER); - haveCar = true; - } else { - e.disallowVehicleClass(-1, SVC_PASSENGER); - } - haveCar |= addCommonVehicleClasses(e, classS, 2); - if (!haveCar) { - e.setPermissions(0); - } - // Bicycle -- becomes SVC_BICYCLE - if (classS[8] == '1') { - e.allowVehicleClass(-1, SVC_BICYCLE); - } else { - e.disallowVehicleClass(-1, SVC_BICYCLE); - } - // Pedestrian -- becomes SVC_PEDESTRIAN - if (classS[9] == '1') { - e.allowVehicleClass(-1, SVC_PEDESTRIAN); - } else { - e.disallowVehicleClass(-1, SVC_PEDESTRIAN); - } -} - - -void -NINavTeqHelper::addVehicleClassesV6(NBEdge& e, const std::string& oclassS, const SVCPermissions allPermissions, const SVCPermissions defaultPermissions) { - std::string classS = "0000000000" + oclassS; - classS = classS.substr(classS.length() - 12); - // 0: allow all vehicle types - if (classS[0] == '1') { - e.setPermissions(allPermissions); - return; - } - bool haveCar = false; - e.setPermissions(defaultPermissions); - // Passenger cars -- becomes SVC_PASSENGER - if (classS[1] == '1') { - e.allowVehicleClass(-1, SVC_PASSENGER); - haveCar = true; - } else { - e.disallowVehicleClass(-1, SVC_PASSENGER); - } - // Residential Vehicle -- becomes SVC_PASSENGER - if (classS[2] == '1') { - e.allowVehicleClass(-1, SVC_PASSENGER); - haveCar = true; - } - haveCar |= addCommonVehicleClasses(e, classS, 3); - if (!haveCar) { - e.setPermissions(0); - } - // Motorcycle -- becomes SVC_MOTORCYCLE - if (classS[9] == '1') { - e.allowVehicleClass(-1, SVC_MOTORCYCLE); - } else { - e.disallowVehicleClass(-1, SVC_MOTORCYCLE); - } - // Bicycle -- becomes SVC_BICYCLE - if (classS[10] == '1') { - e.allowVehicleClass(-1, SVC_BICYCLE); - } else { - e.disallowVehicleClass(-1, SVC_BICYCLE); - } - // Pedestrian -- becomes SVC_PEDESTRIAN - if (classS[11] == '1') { - e.allowVehicleClass(-1, SVC_PEDESTRIAN); - } else { - e.disallowVehicleClass(-1, SVC_PEDESTRIAN); - } -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/NINavTeqHelper.h b/Util/OSM2ODR/src/netimport/NINavTeqHelper.h deleted file mode 100644 index eca624274..000000000 --- a/Util/OSM2ODR/src/netimport/NINavTeqHelper.h +++ /dev/null @@ -1,94 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NINavTeqHelper.h -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date Jul 2006 -/// -// Some parser methods shared around several formats containing NavTeq-Nets -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include -#include - - -// =========================================================================== -// class declarations -// =========================================================================== -class NBEdge; - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NINavTeqHelper - * @brief Some parser methods shared around several formats containing NavTeq-Nets - * - * Networks from NavTeq ofte use categories for speed limits and the number of lanes. - * This class parses such categories and converts them into proper values. - */ -class NINavTeqHelper { -public: - /** @brief Returns the speed evaluating the given Navteq-description - * - * This method tries to parse the speed category into its int-representation - * and to determine the speed that is assigned to the category. - * If either of both steps can not be perfored, a ProcessError is - * thrown. - * - * @param[in] id The id of the edge (for debug-output) - * @param[in] speedClassS The string that describes the speed class - * @return The converted speed (in m/s) - * @exception ProcessError If the given speed class definition is not a number or if it is not known - */ - static double getSpeed(const std::string& id, - const std::string& speedClassS); - - - /** @brief Returns the lane number evaluating the given Navteq-description - * - * @param[in] id The id of the edge (for debug-output) - * @param[in] laneNoS The string that describes the number of lanes - * @param[in] speed An additional hint for guessing the proper lane number - * @return The converted lane number - * @exception ProcessError If the given lane number definition is not a number or if it is not known - */ - static int getLaneNumber(const std::string& id, - const std::string& laneNoS, double speed); - - - /** @brief Adds vehicle classes parsing the given list of allowed vehicles - * - * Parses the given class-string and sets all set (allowed) vehicle types - * into the given edge using "addVehicleClass". - * - * @param[in] e The edge to set the parsed vehicle classes into - * @param[in] classS The string that contains the information whether a vehicle class is allowed - * @see addVehicleClass - */ - static void addVehicleClasses(NBEdge& e, const std::string& classS, const SVCPermissions allPermissions, const SVCPermissions defaultPermissions); - - /// @brief same as addVehicleClasses but for version 6+ - static void addVehicleClassesV6(NBEdge& e, const std::string& classS, const SVCPermissions allPermissions, const SVCPermissions defaultPermissions); - -private: - static bool addCommonVehicleClasses(NBEdge& e, const std::string& classS, const int offset); - -}; diff --git a/Util/OSM2ODR/src/netimport/NITypeLoader.cpp b/Util/OSM2ODR/src/netimport/NITypeLoader.cpp deleted file mode 100644 index c3dffb0e0..000000000 --- a/Util/OSM2ODR/src/netimport/NITypeLoader.cpp +++ /dev/null @@ -1,86 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NITypeLoader.cpp -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Sascha Krieg -/// @author Michael Behrisch -/// @author Robert Hilbrich -/// @date Tue, 20 Nov 2001 -/// -// Perfoms network import -/****************************************************************************/ -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "NITypeLoader.h" - - -bool -NITypeLoader::load(SUMOSAXHandler* handler, const std::vector& files, - const std::string& type, const bool stringParse) { - // build parser - std::string exceptMsg = ""; - std::string fileName = ""; - // start the parsing - bool ok = true; - bool raise = false; - try { - for (std::vector::const_iterator file = files.begin(); file != files.end(); ++file) { - fileName = *file; - if (stringParse) { - fileName = "built in type map"; - handler->setFileName(fileName); - SUMOSAXReader* reader = XMLSubSys::getSAXReader(*handler); - reader->parseString(*file); - delete reader; - continue; - } - if (!FileHelpers::isReadable(fileName)) { - WRITE_ERROR("Could not open " + type + "-file '" + fileName + "'."); - return false; - } - PROGRESS_BEGIN_MESSAGE("Parsing " + type + " from '" + fileName + "'"); - ok &= XMLSubSys::runParser(*handler, fileName); - PROGRESS_DONE_MESSAGE(); - } - } catch (const XERCES_CPP_NAMESPACE::XMLException& toCatch) { - exceptMsg = StringUtils::transcode(toCatch.getMessage()) + "\n "; - raise = true; - } catch (const ProcessError& toCatch) { - exceptMsg = std::string(toCatch.what()) + "\n "; - raise = true; - } catch (...) { - raise = true; - } - delete handler; - if (raise) { - throw ProcessError(exceptMsg + "The " + type + " could not be loaded from '" + fileName + "'."); - } - return ok; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/NITypeLoader.h b/Util/OSM2ODR/src/netimport/NITypeLoader.h deleted file mode 100644 index 39f048665..000000000 --- a/Util/OSM2ODR/src/netimport/NITypeLoader.h +++ /dev/null @@ -1,51 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NITypeLoader.h -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date Tue, 20 Nov 2001 -/// -// Perfoms network import -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include - - -// =========================================================================== -// class declarations -// =========================================================================== -class OptionsCont; -class SUMOSAXHandler; -class NBNetBuilder; -class Position; -class PositionVector; - - - -class NITypeLoader { - /** - * @class NITypeLoader - * @brief loads a specificy type of xml file. - * @note Extra class to simplify import * from netgenerate - */ -public: - /** loads data from the list of xml-files of certain type */ - static bool load(SUMOSAXHandler* handler, const std::vector& files, - const std::string& type, const bool stringParse = false); -}; diff --git a/Util/OSM2ODR/src/netimport/NIVisumTL.cpp b/Util/OSM2ODR/src/netimport/NIVisumTL.cpp deleted file mode 100644 index 150a23df8..000000000 --- a/Util/OSM2ODR/src/netimport/NIVisumTL.cpp +++ /dev/null @@ -1,110 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2003-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVisumTL.cpp -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date Thr, 08 May 2003 -/// -// Intermediate class for storing visum traffic lights during their import -/****************************************************************************/ -#include - -#include -#include -#include -#include -#include -#include -#include "NIVisumTL.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -NIVisumTL::NIVisumTL(const std::string& name, SUMOTime cycleTime, SUMOTime offset, - SUMOTime intermediateTime, bool phaseDefined) - : myName(name), myCycleTime(cycleTime), myOffset(offset), - myIntermediateTime(intermediateTime), myPhaseDefined(phaseDefined) { -} - - -NIVisumTL::~NIVisumTL() { - for (std::map::iterator i = myPhases.begin(); i != myPhases.end(); ++i) { - delete i->second; - } - for (std::map::iterator i = mySignalGroups.begin(); i != mySignalGroups.end(); ++i) { - delete i->second; - } -} - - -void -NIVisumTL::addSignalGroup(const std::string& name, SUMOTime startTime, SUMOTime endTime, SUMOTime yellowTime) { - mySignalGroups[name] = new NIVisumTL::SignalGroup(name, startTime, endTime, yellowTime); -} - - -void -NIVisumTL::addPhase(const std::string& name, SUMOTime startTime, SUMOTime endTime, SUMOTime yellowTime) { - myPhases[name] = new NIVisumTL::Phase(startTime, endTime, yellowTime); -} - - -NIVisumTL::SignalGroup& -NIVisumTL::getSignalGroup(const std::string& name) { - return *mySignalGroups.find(name)->second; -} - - -void -NIVisumTL::build(NBEdgeCont& ec, NBTrafficLightLogicCont& tlc) { - for (std::vector::iterator ni = myNodes.begin(); ni != myNodes.end(); ni++) { - NBNode* node = (*ni); - if (node == nullptr) { - WRITE_WARNING("invalid node for traffic light '" + myName + "'"); - continue; - } - TrafficLightType type = SUMOXMLDefinitions::TrafficLightTypes.get(OptionsCont::getOptions().getString("tls.default-type")); - NBLoadedTLDef* def = new NBLoadedTLDef(ec, node->getID(), node, myOffset, type); - tlc.insert(def); - def->setCycleDuration((int) myCycleTime); - // signalgroups - for (std::map::iterator gi = mySignalGroups.begin(); gi != mySignalGroups.end(); gi++) { - std::string groupName = (*gi).first; - NIVisumTL::SignalGroup& SG = *(*gi).second; - def->addSignalGroup(groupName); - def->addToSignalGroup(groupName, SG.connections()); - // phases - SUMOTime yellowTime = -1; - if (myPhaseDefined) { - for (std::map::iterator pi = SG.phases().begin(); pi != SG.phases().end(); pi++) { - NIVisumTL::Phase& PH = *(*pi).second; - def->addSignalGroupPhaseBegin(groupName, PH.getStartTime(), NBTrafficLightDefinition::TLCOLOR_GREEN); - def->addSignalGroupPhaseBegin(groupName, PH.getEndTime(), NBTrafficLightDefinition::TLCOLOR_RED); - yellowTime = MAX2(PH.getYellowTime(), yellowTime); - }; - } else { - def->addSignalGroupPhaseBegin(groupName, SG.getStartTime(), NBTrafficLightDefinition::TLCOLOR_GREEN); - def->addSignalGroupPhaseBegin(groupName, SG.getEndTime(), NBTrafficLightDefinition::TLCOLOR_RED); - yellowTime = MAX2(SG.getYellowTime(), yellowTime); - } - // yellowTime can be -1 if not given in the input; it will be "patched" later - def->setSignalYellowTimes(groupName, myIntermediateTime, yellowTime); - } - } -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/NIVisumTL.h b/Util/OSM2ODR/src/netimport/NIVisumTL.h deleted file mode 100644 index 696d59b7a..000000000 --- a/Util/OSM2ODR/src/netimport/NIVisumTL.h +++ /dev/null @@ -1,191 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVisumTL.h -/// @author Daniel Krajzewicz -/// @date Wed, 07 May 2003 -/// -// Intermediate class for storing visum traffic lights during their import -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include -#include -#include -#include - -class NBTrafficLightLogicCont; -class NBEdgeCont; - - -// =========================================================================== -// class declaration -// =========================================================================== -/** - * @class NIVisumTL - * @brief Intermediate class for storing visum traffic lights during their import - */ -class NIVisumTL { -public: - /** @class TimePeriod - * @brief A time period with a start and an end time - */ - class TimePeriod { - public: - /// @brief Constructor - TimePeriod(SUMOTime startTime, SUMOTime endTime, SUMOTime yellowTime) - : myStartTime(startTime), myEndTime(endTime), myYellowTime(yellowTime) {} - - /// @brief Destructor - ~TimePeriod() {} - - /// @brief Returns the stored start time - SUMOTime getStartTime() { - return myStartTime; - } - - /// @brief Returns the stored end time - SUMOTime getEndTime() { - return myEndTime; - } - - /// @brief Returns the stored yellow time - SUMOTime getYellowTime() { - return myYellowTime; - } - - private: - /// @brief Start time - SUMOTime myStartTime; - /// @brief End time - SUMOTime myEndTime; - /// @brief Yellow time - SUMOTime myYellowTime; - }; - - - - /** @class Phase - * @brief A phase - */ - class Phase : public TimePeriod { - public: - /// @brief Constructor - Phase(SUMOTime startTime, SUMOTime endTime, SUMOTime yellowTime) : NIVisumTL::TimePeriod(startTime, endTime, yellowTime) {} - - /// @brief Destructor - ~Phase() {} - - }; - - - - /** @class SignalGroup - * @brief A signal group can be defined either by a time period or by phases - */ - class SignalGroup : public TimePeriod { - public: - /// @brief constructor - SignalGroup(const std::string& name, SUMOTime startTime, SUMOTime endTime, SUMOTime yellowTime) - : NIVisumTL::TimePeriod(startTime, endTime, yellowTime), myName(name) {} - - /// @brief destructor - ~SignalGroup() {} - - /// @brief Returns the connections vector - NBConnectionVector& connections() { - return myConnections; - } - - /// @brief Returns the phases map - std::map& phases() { - return myPhases; - } - - private: - /// @brief Connections - NBConnectionVector myConnections; - /// @brief phases - std::map myPhases; - /// @brief name - std::string myName; - }; - - - -public: - /** @brief Constructor - * @param[in] name The name of the TLS - * @param[in] cycleTime The cycle time of the TLS - * @param[in] offset Seconds to skip - * @param[in] intermediateTime The name of the TLS - * @param[in] phaseDefined Whether phases are defined - */ - NIVisumTL(const std::string& name, SUMOTime cycleTime, SUMOTime offset, SUMOTime intermediateTime, - bool phaseDefined); - - /// @brief Destructor - ~NIVisumTL(); - - /// @brief Adds a node to control - void addNode(NBNode* n) { - myNodes.push_back(n); - } - - /// @brief Adds a signal group - void addSignalGroup(const std::string& name, SUMOTime startTime, SUMOTime endTime, SUMOTime yellowTime); - - /// @brief Adds a phase - void addPhase(const std::string& name, SUMOTime startTime, SUMOTime endTime, SUMOTime yellowTime); - - /// @brief Returns the map of named phases - std::map& getPhases() { - return myPhases; - } - - /// @brief Returns the named signal group - SignalGroup& getSignalGroup(const std::string& name); - - /// @brief build the traffic light and add it to the given container - void build(NBEdgeCont& ec, NBTrafficLightLogicCont& tlc); - -private: - /// @brief The name of traffic light - std::string myName; - - /// @brief The cycle time of traffic light in seconds - SUMOTime myCycleTime; - - /// @brief The offset in the plan - SUMOTime myOffset; - - /// @brief The all-red time (unused here) - SUMOTime myIntermediateTime; - - /// @brief Toogles the usage either of phases or of time periods in signal groups - bool myPhaseDefined; - - /// @brief Vector of nodes belonging to this traffic light - std::vector myNodes; - - /// @brief Map of used phases if phases defined - std::map myPhases; - - /// @brief Map of used signal groups - std::map mySignalGroups; - - -}; diff --git a/Util/OSM2ODR/src/netimport/NIXMLConnectionsHandler.cpp b/Util/OSM2ODR/src/netimport/NIXMLConnectionsHandler.cpp deleted file mode 100644 index a76556fa6..000000000 --- a/Util/OSM2ODR/src/netimport/NIXMLConnectionsHandler.cpp +++ /dev/null @@ -1,472 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIXMLConnectionsHandler.cpp -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @author Laura Bieker -/// @date Thu, 17 Oct 2002 -/// -// Importer for edge connections stored in XML -/****************************************************************************/ -#include - -#include -#include -#include -#include -#include -#include -#include "NIXMLConnectionsHandler.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - - -// =========================================================================== -// method definitions -// =========================================================================== -NIXMLConnectionsHandler::NIXMLConnectionsHandler(NBEdgeCont& ec, NBNodeCont& nc, NBTrafficLightLogicCont& tlc) : - SUMOSAXHandler("xml-connection-description"), - myEdgeCont(ec), - myNodeCont(nc), - myTLLogicCont(tlc), - myHaveWarnedAboutDeprecatedLanes(false), - myErrorMsgHandler(OptionsCont::getOptions().getBool("ignore-errors.connections") ? - MsgHandler::getWarningInstance() : MsgHandler::getErrorInstance()) {} - - -NIXMLConnectionsHandler::~NIXMLConnectionsHandler() {} - - -void -NIXMLConnectionsHandler::myStartElement(int element, - const SUMOSAXAttributes& attrs) { - if (element == SUMO_TAG_DEL) { - bool ok = true; - std::string from = attrs.get(SUMO_ATTR_FROM, nullptr, ok); - std::string to = attrs.get(SUMO_ATTR_TO, nullptr, ok); - if (!ok) { - return; - } - // these connections were removed when the edge was deleted - if (myEdgeCont.wasRemoved(from) || myEdgeCont.wasRemoved(to)) { - return; - } - NBEdge* fromEdge = myEdgeCont.retrieve(from); - NBEdge* toEdge = myEdgeCont.retrieve(to); - if (fromEdge == nullptr) { - myErrorMsgHandler->informf("The connection-source edge '%' to reset is not known.", from); - return; - } - if (toEdge == nullptr) { - myErrorMsgHandler->informf("The connection-destination edge '%' to reset is not known.", to); - return; - } - if (!fromEdge->isConnectedTo(toEdge) && fromEdge->getStep() >= NBEdge::EdgeBuildingStep::EDGE2EDGES) { - WRITE_WARNINGF("Target edge '%' is not connected with '%'; the connection cannot be reset.", toEdge->getID(), fromEdge->getID()); - return; - } - int fromLane = -1; // Assume all lanes are to be reset. - int toLane = -1; - if (attrs.hasAttribute(SUMO_ATTR_LANE) - || attrs.hasAttribute(SUMO_ATTR_FROM_LANE) - || attrs.hasAttribute(SUMO_ATTR_TO_LANE)) { - if (!parseLaneInfo(attrs, fromEdge, toEdge, &fromLane, &toLane)) { - return; - } - // we could be trying to reset a connection loaded from a sumo net and which has become obsolete. - // In this case it's ok to encounter invalid lance indices - if (!fromEdge->hasConnectionTo(toEdge, toLane) && fromEdge->getStep() >= NBEdge::EdgeBuildingStep::LANES2EDGES) { - WRITE_WARNINGF("Edge '%' has no connection to lane '%'; the connection cannot be reset.", fromEdge->getID(), toEdge->getLaneID(toLane)); - } - } - fromEdge->removeFromConnections(toEdge, fromLane, toLane, true); - } - - if (element == SUMO_TAG_CONNECTION) { - bool ok = true; - std::string from = attrs.get(SUMO_ATTR_FROM, "connection", ok); - std::string to = attrs.getOpt(SUMO_ATTR_TO, "connection", ok, ""); - if (!ok || myEdgeCont.wasIgnored(from) || myEdgeCont.wasIgnored(to)) { - return; - } - // extract edges - NBEdge* fromEdge = myEdgeCont.retrieve(from); - NBEdge* toEdge = to.length() != 0 ? myEdgeCont.retrieve(to) : nullptr; - // check whether they are valid - if (fromEdge == nullptr) { - myErrorMsgHandler->inform("The connection-source edge '" + from + "' is not known."); - return; - } - if (toEdge == nullptr && to.length() != 0) { - myErrorMsgHandler->inform("The connection-destination edge '" + to + "' is not known."); - return; - } - // parse optional lane information - if (attrs.hasAttribute(SUMO_ATTR_LANE) || attrs.hasAttribute(SUMO_ATTR_FROM_LANE) || attrs.hasAttribute(SUMO_ATTR_TO_LANE)) { - parseLaneBound(attrs, fromEdge, toEdge); - } else { - fromEdge->addEdge2EdgeConnection(toEdge); - fromEdge->getToNode()->invalidateTLS(myTLLogicCont, true, false); - if (attrs.hasAttribute(SUMO_ATTR_PASS) - || attrs.hasAttribute(SUMO_ATTR_KEEP_CLEAR) - || attrs.hasAttribute(SUMO_ATTR_CONTPOS) - || attrs.hasAttribute(SUMO_ATTR_VISIBILITY_DISTANCE) - || attrs.hasAttribute(SUMO_ATTR_SPEED) - || attrs.hasAttribute(SUMO_ATTR_LENGTH) - || attrs.hasAttribute(SUMO_ATTR_UNCONTROLLED) - || attrs.hasAttribute(SUMO_ATTR_SHAPE) - || attrs.hasAttribute(SUMO_ATTR_ALLOW) - || attrs.hasAttribute(SUMO_ATTR_DISALLOW)) { - WRITE_ERROR("No additional connection attributes are permitted in connection from edge '" + fromEdge->getID() + "' unless '" - + toString(SUMO_ATTR_FROM_LANE) + "' and '" + toString(SUMO_ATTR_TO_LANE) + "' are set."); - } - } - } - if (element == SUMO_TAG_PROHIBITION) { - bool ok = true; - std::string prohibitor = attrs.getOpt(SUMO_ATTR_PROHIBITOR, nullptr, ok, ""); - std::string prohibited = attrs.getOpt(SUMO_ATTR_PROHIBITED, nullptr, ok, ""); - if (!ok) { - return; - } - NBConnection prohibitorC = parseConnection("prohibitor", prohibitor); - NBConnection prohibitedC = parseConnection("prohibited", prohibited); - if (prohibitorC == NBConnection::InvalidConnection || prohibitedC == NBConnection::InvalidConnection) { - // something failed - return; - } - NBNode* n = prohibitorC.getFrom()->getToNode(); - n->addSortedLinkFoes(prohibitorC, prohibitedC); - } - if (element == SUMO_TAG_CROSSING) { - addCrossing(attrs); - } - if (element == SUMO_TAG_WALKINGAREA) { - addWalkingArea(attrs); - } -} - - -NBConnection -NIXMLConnectionsHandler::parseConnection(const std::string& defRole, const std::string& def) { - // split from/to - const std::string::size_type div = def.find("->"); - if (div == std::string::npos) { - myErrorMsgHandler->inform("Missing connection divider in " + defRole + " '" + def + "'"); - return NBConnection::InvalidConnection; - } - std::string fromDef = def.substr(0, div); - std::string toDef = def.substr(div + 2); - - // retrieve the edges - // check whether the definition includes a lane information (do not process it) - if (fromDef.find('_') != std::string::npos) { - fromDef = fromDef.substr(0, fromDef.find('_')); - } - if (toDef.find('_') != std::string::npos) { - toDef = toDef.substr(0, toDef.find('_')); - } - // retrieve them now - NBEdge* fromE = myEdgeCont.retrieve(fromDef); - NBEdge* toE = myEdgeCont.retrieve(toDef); - // check - if (fromE == nullptr) { - myErrorMsgHandler->inform("Could not find edge '" + fromDef + "' in " + defRole + " '" + def + "'"); - return NBConnection::InvalidConnection; - } - if (toE == nullptr) { - myErrorMsgHandler->inform("Could not find edge '" + toDef + "' in " + defRole + " '" + def + "'"); - return NBConnection::InvalidConnection; - } - return NBConnection(fromE, toE); -} - - -void -NIXMLConnectionsHandler::parseLaneBound(const SUMOSAXAttributes& attrs, NBEdge* from, NBEdge* to) { - if (to == nullptr) { - // do nothing if it's a dead end - return; - } - bool ok = true; - // get the begin and the end lane - int fromLane; - int toLane; - try { - if (!parseLaneInfo(attrs, from, to, &fromLane, &toLane)) { - return; - } - if (fromLane < 0) { - myErrorMsgHandler->informf("Invalid value '%' for " + toString(SUMO_ATTR_FROM_LANE) + - " in connection from '%' to '%'.", fromLane, from->getID(), to->getID()); - return; - } - if (toLane < 0) { - myErrorMsgHandler->informf("Invalid value '%' for " + toString(SUMO_ATTR_TO_LANE) + - " in connection from '%' to '%'.", toLane, from->getID(), to->getID()); - return; - } - if (from->hasConnectionTo(to, toLane) && from->getToNode()->getType() != SumoXMLNodeType::ZIPPER) { - WRITE_WARNINGF("Target lane '%' is already connected from '%'.", to->getLaneID(toLane), from->getID()); - } - - NBEdge::Connection defaultCon(fromLane, to, toLane); - if (from->getStep() == NBEdge::EdgeBuildingStep::LANES2LANES_USER) { - // maybe we are patching an existing connection - std::vector existing = from->getConnectionsFromLane(fromLane, to, toLane); - if (existing.size() > 0) { - assert(existing.size() == 1); - defaultCon = existing.front(); - // remove the original so we can insert the replacement - from->removeFromConnections(defaultCon); - } else { - from->getToNode()->invalidateTLS(myTLLogicCont, true, false); - } - } - const bool mayDefinitelyPass = attrs.getOpt(SUMO_ATTR_PASS, nullptr, ok, defaultCon.mayDefinitelyPass); - const bool keepClear = attrs.getOpt(SUMO_ATTR_KEEP_CLEAR, nullptr, ok, defaultCon.keepClear); - const double contPos = attrs.getOpt(SUMO_ATTR_CONTPOS, nullptr, ok, defaultCon.contPos); - const double visibility = attrs.getOpt(SUMO_ATTR_VISIBILITY_DISTANCE, nullptr, ok, defaultCon.visibility); - const double speed = attrs.getOpt(SUMO_ATTR_SPEED, nullptr, ok, defaultCon.speed); - const double length = attrs.getOpt(SUMO_ATTR_LENGTH, nullptr, ok, defaultCon.customLength); - const bool uncontrolled = attrs.getOpt(SUMO_ATTR_UNCONTROLLED, nullptr, ok, defaultCon.uncontrolled); - PositionVector customShape = attrs.getOpt(SUMO_ATTR_SHAPE, nullptr, ok, defaultCon.customShape); - std::string allow = attrs.getOpt(SUMO_ATTR_ALLOW, nullptr, ok, ""); - std::string disallow = attrs.getOpt(SUMO_ATTR_DISALLOW, nullptr, ok, ""); - SVCPermissions permissions; - if (allow == "" && disallow == "") { - permissions = SVC_UNSPECIFIED; - } else { - permissions = parseVehicleClasses(attrs.getOpt(SUMO_ATTR_ALLOW, nullptr, ok, ""), attrs.getOpt(SUMO_ATTR_DISALLOW, nullptr, ok, "")); - } - - if (attrs.hasAttribute(SUMO_ATTR_SHAPE) && !NBNetBuilder::transformCoordinates(customShape)) { - WRITE_ERROR("Unable to project shape for connection from edge '" + from->getID() + "' to edge '" + to->getID() + "'."); - } - if (!ok) { - return; - } - if (!from->addLane2LaneConnection(fromLane, to, toLane, NBEdge::Lane2LaneInfoType::USER, true, mayDefinitelyPass, - keepClear, contPos, visibility, speed, length, customShape, uncontrolled, permissions)) { - if (OptionsCont::getOptions().getBool("show-errors.connections-first-try")) { - WRITE_WARNINGF("Could not set loaded connection from lane '%' to lane '%'.", from->getLaneID(fromLane), to->getLaneID(toLane)); - } - // set as to be re-applied after network processing - myEdgeCont.addPostProcessConnection(from->getID(), fromLane, to->getID(), toLane, mayDefinitelyPass, keepClear, contPos, visibility, speed, length, customShape, uncontrolled, false, permissions); - } - } catch (NumberFormatException&) { - myErrorMsgHandler->inform("At least one of the defined lanes was not numeric"); - } -} - -bool -NIXMLConnectionsHandler::parseLaneInfo(const SUMOSAXAttributes& attributes, NBEdge* fromEdge, NBEdge* toEdge, - int* fromLane, int* toLane) { - if (attributes.hasAttribute(SUMO_ATTR_LANE)) { - return parseDeprecatedLaneDefinition(attributes, fromEdge, toEdge, fromLane, toLane); - } else { - return parseLaneDefinition(attributes, fromLane, toLane); - } -} - - -inline bool -NIXMLConnectionsHandler::parseDeprecatedLaneDefinition(const SUMOSAXAttributes& attributes, - NBEdge* from, NBEdge* to, - int* fromLane, int* toLane) { - bool ok = true; - if (!myHaveWarnedAboutDeprecatedLanes) { - myHaveWarnedAboutDeprecatedLanes = true; - WRITE_WARNING("'" + toString(SUMO_ATTR_LANE) + "' is deprecated, please use '" + - toString(SUMO_ATTR_FROM_LANE) + "' and '" + toString(SUMO_ATTR_TO_LANE) + - "' instead."); - } - - std::string laneConn = attributes.get(SUMO_ATTR_LANE, nullptr, ok); - StringTokenizer st(laneConn, ':'); - if (!ok || st.size() != 2) { - myErrorMsgHandler->inform("Invalid lane to lane connection from '" + - from->getID() + "' to '" + to->getID() + "'."); - return false; // There was an error. - } - - *fromLane = StringUtils::toIntSecure(st.next(), -1); - *toLane = StringUtils::toIntSecure(st.next(), -1); - - return true; // We succeeded. -} - - -inline bool -NIXMLConnectionsHandler::parseLaneDefinition(const SUMOSAXAttributes& attributes, - int* fromLane, - int* toLane) { - bool ok = true; - *fromLane = attributes.get(SUMO_ATTR_FROM_LANE, nullptr, ok); - *toLane = attributes.get(SUMO_ATTR_TO_LANE, nullptr, ok); - return ok; -} - - -void -NIXMLConnectionsHandler::addCrossing(const SUMOSAXAttributes& attrs) { - bool ok = true; - EdgeVector edges; - const std::string nodeID = attrs.get(SUMO_ATTR_NODE, nullptr, ok); - double width = attrs.getOpt(SUMO_ATTR_WIDTH, nodeID.c_str(), ok, NBEdge::UNSPECIFIED_WIDTH, true); - const bool discard = attrs.getOpt(SUMO_ATTR_DISCARD, nodeID.c_str(), ok, false, true); - int tlIndex = attrs.getOpt(SUMO_ATTR_TLLINKINDEX, nullptr, ok, -1); - int tlIndex2 = attrs.getOpt(SUMO_ATTR_TLLINKINDEX2, nullptr, ok, -1); - NBNode* node = myNodeCont.retrieve(nodeID); - if (node == nullptr) { - if (!discard && myNodeCont.wasRemoved(nodeID)) { - WRITE_ERROR("Node '" + nodeID + "' in crossing is not known."); - } - return; - } - if (!attrs.hasAttribute(SUMO_ATTR_EDGES)) { - if (discard) { - node->discardAllCrossings(true); - return; - } else { - WRITE_ERROR("No edges specified for crossing at node '" + nodeID + "'."); - return; - } - } - for (const std::string& id : attrs.get >(SUMO_ATTR_EDGES, nodeID.c_str(), ok)) { - NBEdge* edge = myEdgeCont.retrieve(id); - if (edge == nullptr) { - if (!(discard && myEdgeCont.wasRemoved(id))) { - WRITE_ERROR("Edge '" + id + "' for crossing at node '" + nodeID + "' is not known."); - return; - } else { - edge = myEdgeCont.retrieve(id, true); - } - } else { - if (edge->getToNode() != node && edge->getFromNode() != node) { - if (!discard) { - WRITE_ERROR("Edge '" + id + "' does not touch node '" + nodeID + "'."); - return; - } - } - } - edges.push_back(edge); - } - if (!ok) { - return; - } - bool priority = attrs.getOpt(SUMO_ATTR_PRIORITY, nodeID.c_str(), ok, node->isTLControlled(), true); - if (node->isTLControlled() && !priority) { - // traffic_light nodes should always have priority crossings - WRITE_WARNING("Crossing at controlled node '" + nodeID + "' must be prioritized"); - priority = true; - } - PositionVector customShape = attrs.getOpt(SUMO_ATTR_SHAPE, nullptr, ok, PositionVector::EMPTY); - if (!NBNetBuilder::transformCoordinates(customShape)) { - WRITE_ERROR("Unable to project shape for crossing at node '" + node->getID() + "'."); - } - if (discard) { - node->removeCrossing(edges); - } else { - if (node->checkCrossingDuplicated(edges)) { - // possibly a diff - NBNode::Crossing* existing = node->getCrossing(edges); - if (!( - (attrs.hasAttribute(SUMO_ATTR_WIDTH) && width != existing->width) - || (attrs.hasAttribute(SUMO_ATTR_TLLINKINDEX) && tlIndex != existing->customTLIndex) - || (attrs.hasAttribute(SUMO_ATTR_TLLINKINDEX2) && tlIndex2 != existing->customTLIndex2) - || (attrs.hasAttribute(SUMO_ATTR_PRIORITY) && priority != existing->priority))) { - WRITE_ERROR("Crossing with edges '" + toString(edges) + "' already exists at node '" + node->getID() + "'."); - return; - } else { - // replace existing, keep old attributes - if (!attrs.hasAttribute(SUMO_ATTR_WIDTH)) { - width = existing->width; - } - if (!attrs.hasAttribute(SUMO_ATTR_TLLINKINDEX)) { - tlIndex = existing->customTLIndex; - } - if (!attrs.hasAttribute(SUMO_ATTR_TLLINKINDEX2)) { - tlIndex2 = existing->customTLIndex2; - } - if (!attrs.hasAttribute(SUMO_ATTR_PRIORITY)) { - priority = existing->priority; - } - node->removeCrossing(edges); - } - } - node->addCrossing(edges, width, priority, tlIndex, tlIndex2, customShape); - } -} - - -void -NIXMLConnectionsHandler::addWalkingArea(const SUMOSAXAttributes& attrs) { - bool ok = true; - NBNode* node = nullptr; - EdgeVector edges; - const std::string nodeID = attrs.get(SUMO_ATTR_NODE, nullptr, ok); - std::vector edgeIDs; - if (!attrs.hasAttribute(SUMO_ATTR_EDGES)) { - WRITE_ERROR("No edges specified for walkingArea at node '" + nodeID + "'."); - return; - } - for (const std::string& id : attrs.get >(SUMO_ATTR_EDGES, nodeID.c_str(), ok)) { - NBEdge* edge = myEdgeCont.retrieve(id); - if (edge == nullptr) { - WRITE_ERROR("Edge '" + id + "' for walkingArea at node '" + nodeID + "' is not known."); - return; - } - if (node == nullptr) { - if (edge->getToNode()->getID() == nodeID) { - node = edge->getToNode(); - } else if (edge->getFromNode()->getID() == nodeID) { - node = edge->getFromNode(); - } else { - WRITE_ERROR("Edge '" + id + "' does not touch node '" + nodeID + "'."); - return; - } - } else { - if (edge->getToNode() != node && edge->getFromNode() != node) { - WRITE_ERROR("Edge '" + id + "' does not touch node '" + nodeID + "'."); - return; - } - } - edges.push_back(edge); - } - if (!ok) { - return; - } - PositionVector customShape = attrs.getOpt(SUMO_ATTR_SHAPE, nullptr, ok, PositionVector::EMPTY); - if (!NBNetBuilder::transformCoordinates(customShape)) { - WRITE_ERROR("Unable to project shape for walkingArea at node '" + node->getID() + "'."); - } - node->addWalkingAreaShape(edges, customShape); -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/NIXMLConnectionsHandler.h b/Util/OSM2ODR/src/netimport/NIXMLConnectionsHandler.h deleted file mode 100644 index 07d125e9f..000000000 --- a/Util/OSM2ODR/src/netimport/NIXMLConnectionsHandler.h +++ /dev/null @@ -1,161 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIXMLConnectionsHandler.h -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date Tue, 20 Nov 2001 -/// -// Importer for edge connections stored in XML -/****************************************************************************/ -#pragma once -#include - -#include -#include - - -// =========================================================================== -// class declarations -// =========================================================================== -class NBEdge; -class NBEdgeCont; -class NBNodeCont; -class NBTrafficLightLogicCont; -class MsgHandler; - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NIXMLConnectionsHandler - * @brief Importer for edge connections stored in XML - * - * This importer parses connections, and prohibitions, and is able - * to reset connections between edges. - */ -class NIXMLConnectionsHandler : public SUMOSAXHandler { -public: - /** @brief Constructor - * @param[in] ec The edge container which includes the edges to change connections of - */ - NIXMLConnectionsHandler(NBEdgeCont& ec, NBNodeCont& nc, NBTrafficLightLogicCont& tlc); - - - /// @brief Destructor - ~NIXMLConnectionsHandler(); - - -protected: - /// @name inherited from GenericSAXHandler - //@{ - - /** @brief Called on the opening of a tag; - * - * @param[in] element ID of the currently opened element - * @param[in] attrs Attributes within the currently opened element - * @exception ProcessError If something fails - * @see GenericSAXHandler::myStartElement - */ - void myStartElement(int element, - const SUMOSAXAttributes& attrs); - //@} - -private: - /** @brief Returns the connection described by def - * - * def should have the following format [_]->[_]. - * - * @param[in] defRole "prohibitor" or "prohibited" - used for error reporting - * @param[in] def The definition of the connection - * @return The parsed connection - */ - NBConnection parseConnection(const std::string& defRole, const std::string& def); - - - /** @brief Parses a connection when it describes a lane-2-lane relationship - * @param[in] attrs The attributes to get further information about the connection from - * @param[in] from The edge at which the connection starts (the on incoming into a node) - * @param[in] to The edge at which the connection ends (the on outgoing from a node) - */ - void parseLaneBound(const SUMOSAXAttributes& attrs, NBEdge* from, NBEdge* to); - - - /** @brief Parses information about lane-2-lane connection when it describes a lane-2-lane relationship - * @param[in] attrs The attributes to get further information about the connection from - * @param[in] fromEdge The edge at which the connection starts (the on incoming into a node) - * @param[in] toEdge The edge at which the connection ends (the on outgoing from a node) - * @param[out] fromLane The lane at which connection starts - * @param[out] toLane The lane at which connection ends - */ - bool parseLaneInfo(const SUMOSAXAttributes& attributes, NBEdge* fromEdge, NBEdge* toEdge, int* fromLane, int* toLane); - - - /** @brief Parses information about lane-2-lane connection in deprecated format. - * @param[in] attrs The attributes to get further information about the connection from - * @param[in] fromEdge The edge at which the connection starts (the on incoming into a node) - * @param[in] toEdge The edge at which the connection ends (the on outgoing from a node) - * @param[out] fromLane The lane at which connection starts - * @param[out] toLane The lane at which connection ends - */ - inline bool parseDeprecatedLaneDefinition(const SUMOSAXAttributes& attributes, - NBEdge* fromEdge, NBEdge* toEdge, - int* fromLane, int* toLane); - - - /** @brief Parses information about lane-2-lane connection. - * @param[in] attrs The attributes to get further information about the connection from - * @param[out] fromLane The lane at which connection starts - * @param[out] toLane The lane at which connection ends - */ - inline bool parseLaneDefinition(const SUMOSAXAttributes& attributes, int* fromLane, int* toLane); - - - /** @brief Parses a crossing and updates the referenced node - * @param[in] attrs The attributes to get the crossings's values from - */ - void addCrossing(const SUMOSAXAttributes& attrs); - - /** @brief Parses a walkingArea and updates the referenced node - * @param[in] attrs The attributes to get the crossings's values from - */ - void addWalkingArea(const SUMOSAXAttributes& attrs); - -private: - /// @brief The edge container to fill - NBEdgeCont& myEdgeCont; - - /// @brief The edge container to fill - NBNodeCont& myNodeCont; - - /** @brief The traffic lights container to add built tls to (when - * invalidating tls) */ - NBTrafficLightLogicCont& myTLLogicCont; - - /// @brief Information whether we have a deprecated attribute - bool myHaveWarnedAboutDeprecatedLanes; - - /// @brief the handler for loading errors - MsgHandler* const myErrorMsgHandler; - -private: - /// @brief invalidated copy constructor - NIXMLConnectionsHandler(const NIXMLConnectionsHandler& s); - - /// @brief invalidated assignment operator - NIXMLConnectionsHandler& operator=(const NIXMLConnectionsHandler& s); - - -}; diff --git a/Util/OSM2ODR/src/netimport/NIXMLEdgesHandler.cpp b/Util/OSM2ODR/src/netimport/NIXMLEdgesHandler.cpp deleted file mode 100644 index 3e2dd9146..000000000 --- a/Util/OSM2ODR/src/netimport/NIXMLEdgesHandler.cpp +++ /dev/null @@ -1,638 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIXMLEdgesHandler.cpp -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @author Walter Bamberger -/// @author Laura Bieker -/// @author Leonhard Luecken -/// @date Tue, 20 Nov 2001 -/// -// Importer for network edges stored in XML -/****************************************************************************/ -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "NIXMLNodesHandler.h" -#include "NIXMLEdgesHandler.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -NIXMLEdgesHandler::NIXMLEdgesHandler(NBNodeCont& nc, - NBEdgeCont& ec, - NBTypeCont& tc, - NBDistrictCont& dc, - NBTrafficLightLogicCont& tlc, - OptionsCont& options) : - SUMOSAXHandler("xml-edges - file"), - myOptions(options), - myNodeCont(nc), - myEdgeCont(ec), - myTypeCont(tc), - myDistrictCont(dc), - myTLLogicCont(tlc), - myCurrentEdge(nullptr), - myCurrentLaneIndex(-1), - myHaveReportedAboutOverwriting(false), - myHaveReportedAboutTypeOverride(false), - myHaveWarnedAboutDeprecatedLaneId(false), - myKeepEdgeShape(!options.getBool("plain.extend-edge-shape")) { -} - - -NIXMLEdgesHandler::~NIXMLEdgesHandler() {} - - -void -NIXMLEdgesHandler::myStartElement(int element, - const SUMOSAXAttributes& attrs) { - switch (element) { - case SUMO_TAG_EDGE: - addEdge(attrs); - break; - case SUMO_TAG_LANE: - addLane(attrs); - break; - case SUMO_TAG_NEIGH: - myCurrentEdge->getLaneStruct((int)myCurrentEdge->getNumLanes() - 1).oppositeID = attrs.getString(SUMO_ATTR_LANE); - break; - case SUMO_TAG_SPLIT: - addSplit(attrs); - break; - case SUMO_TAG_DEL: - deleteEdge(attrs); - break; - case SUMO_TAG_ROUNDABOUT: - addRoundabout(attrs); - break; - case SUMO_TAG_PARAM: - if (myLastParameterised.size() != 0 && myCurrentEdge != nullptr) { - bool ok = true; - const std::string key = attrs.get(SUMO_ATTR_KEY, nullptr, ok); - // circumventing empty string test - const std::string val = attrs.hasAttribute(SUMO_ATTR_VALUE) ? attrs.getString(SUMO_ATTR_VALUE) : ""; - myLastParameterised.back()->setParameter(key, val); - } - break; - case SUMO_TAG_STOPOFFSET: { - bool ok = true; - std::map stopOffsets = parseStopOffsets(attrs, ok); - assert(stopOffsets.size() == 1); - if (!ok) { - std::stringstream ss; - ss << "(Error encountered at lane " << myCurrentLaneIndex << " of edge '" << myCurrentID << "' while parsing stopOffsets.)"; - WRITE_ERROR(ss.str()); - } else { - if (myCurrentEdge->getStopOffsets(myCurrentLaneIndex).size() != 0) { - std::stringstream ss; - ss << "Duplicate definition of stopOffset for "; - if (myCurrentLaneIndex != -1) { - ss << "lane " << myCurrentLaneIndex << " on "; - } - ss << "edge " << myCurrentEdge->getID() << ". Ignoring duplicate specification."; - WRITE_WARNING(ss.str()); - return; - } else if (stopOffsets.begin()->second > myCurrentEdge->getLength() || stopOffsets.begin()->second < 0) { - std::stringstream ss; - ss << "Ignoring invalid stopOffset for "; - if (myCurrentLaneIndex != -1) { - ss << "lane " << myCurrentLaneIndex << " on "; - } - ss << "edge " << myCurrentEdge->getID(); - if (stopOffsets.begin()->second > myCurrentEdge->getLength()) { - ss << " (offset larger than the edge length)."; - } else { - ss << " (negative offset)."; - } - WRITE_WARNING(ss.str()); - } else { - myCurrentEdge->setStopOffsets(myCurrentLaneIndex, stopOffsets); - } - } - } - break; - default: - break; - } -} - - -void -NIXMLEdgesHandler::addEdge(const SUMOSAXAttributes& attrs) { - myIsUpdate = false; - bool ok = true; - // initialise the edge - myCurrentEdge = nullptr; - mySplits.clear(); - // get the id, report an error if not given or empty... - myCurrentID = attrs.get(SUMO_ATTR_ID, nullptr, ok); - if (!ok) { - return; - } - myCurrentEdge = myEdgeCont.retrieve(myCurrentID); - // check deprecated (unused) attributes - // use default values, first - myCurrentType = myOptions.getString("default.type"); - myCurrentPriority = myTypeCont.getPriority(myCurrentType); - myCurrentLaneNo = myTypeCont.getNumLanes(myCurrentType); - myCurrentEndOffset = NBEdge::UNSPECIFIED_OFFSET; - if (myCurrentEdge != nullptr) { - // update existing edge. only update lane-specific settings when explicitly requested - myIsUpdate = true; - myCurrentSpeed = NBEdge::UNSPECIFIED_SPEED; - myPermissions = SVC_UNSPECIFIED; - myCurrentWidth = NBEdge::UNSPECIFIED_WIDTH; - myCurrentType = myCurrentEdge->getTypeID(); - } else { - // this is a completely new edge. get the type specific defaults - myCurrentSpeed = myTypeCont.getSpeed(myCurrentType); - myPermissions = myTypeCont.getPermissions(myCurrentType); - myCurrentWidth = myTypeCont.getWidth(myCurrentType); - } - myShape = PositionVector(); - myLanesSpread = SUMOXMLDefinitions::LaneSpreadFunctions.get(myOptions.getString("default.spreadtype")); - myLength = NBEdge::UNSPECIFIED_LOADED_LENGTH; - myCurrentStreetName = ""; - myReinitKeepEdgeShape = false; - mySidewalkWidth = NBEdge::UNSPECIFIED_WIDTH; - myBikeLaneWidth = NBEdge::UNSPECIFIED_WIDTH; - // check whether a type's values shall be used - if (attrs.hasAttribute(SUMO_ATTR_TYPE)) { - myCurrentType = attrs.get(SUMO_ATTR_TYPE, myCurrentID.c_str(), ok); - if (!ok) { - return; - } - if (!myTypeCont.knows(myCurrentType) && !myOptions.getBool("ignore-errors.edge-type")) { - WRITE_ERRORF("Type '%' used by edge '%' was not defined (ignore with option --ignore-errors.edge-type).", myCurrentType, myCurrentID); - return; - } - myCurrentSpeed = myTypeCont.getSpeed(myCurrentType); - myCurrentPriority = myTypeCont.getPriority(myCurrentType); - myCurrentLaneNo = myTypeCont.getNumLanes(myCurrentType); - myPermissions = myTypeCont.getPermissions(myCurrentType); - myCurrentWidth = myTypeCont.getWidth(myCurrentType); - mySidewalkWidth = myTypeCont.getSidewalkWidth(myCurrentType); - myBikeLaneWidth = myTypeCont.getBikeLaneWidth(myCurrentType); - } - // use values from the edge to overwrite if existing, then - if (myIsUpdate) { - if (!myHaveReportedAboutOverwriting) { - WRITE_MESSAGE("Duplicate edge id occurred ('" + myCurrentID + "'); assuming overwriting is wished."); - myHaveReportedAboutOverwriting = true; - } - if (attrs.hasAttribute(SUMO_ATTR_TYPE) && myCurrentType != myCurrentEdge->getTypeID()) { - if (!myHaveReportedAboutTypeOverride) { - WRITE_MESSAGE("Edge '" + myCurrentID + "' changed it's type; assuming type override is wished."); - myHaveReportedAboutTypeOverride = true; - } - } - if (attrs.getOpt(SUMO_ATTR_REMOVE, myCurrentID.c_str(), ok, false)) { - myEdgeCont.erase(myDistrictCont, myCurrentEdge); - myCurrentEdge = nullptr; - return; - } - myCurrentPriority = myCurrentEdge->getPriority(); - myCurrentLaneNo = myCurrentEdge->getNumLanes(); - if (!myCurrentEdge->hasDefaultGeometry()) { - myShape = myCurrentEdge->getGeometry(); - myReinitKeepEdgeShape = true; - } - myLanesSpread = myCurrentEdge->getLaneSpreadFunction(); - if (myCurrentEdge->hasLoadedLength()) { - myLength = myCurrentEdge->getLoadedLength(); - } - myCurrentStreetName = myCurrentEdge->getStreetName(); - } - // speed, priority and the number of lanes have now default values; - // try to read the real values from the file - if (attrs.hasAttribute(SUMO_ATTR_SPEED)) { - myCurrentSpeed = attrs.get(SUMO_ATTR_SPEED, myCurrentID.c_str(), ok); - } - if (myOptions.getBool("speed-in-kmh") && myCurrentSpeed != NBEdge::UNSPECIFIED_SPEED) { - myCurrentSpeed = myCurrentSpeed / (double) 3.6; - } - // try to get the number of lanes - if (attrs.hasAttribute(SUMO_ATTR_NUMLANES)) { - myCurrentLaneNo = attrs.get(SUMO_ATTR_NUMLANES, myCurrentID.c_str(), ok); - } - // try to get the priority - if (attrs.hasAttribute(SUMO_ATTR_PRIORITY)) { - myCurrentPriority = attrs.get(SUMO_ATTR_PRIORITY, myCurrentID.c_str(), ok); - } - // try to get the width - if (attrs.hasAttribute(SUMO_ATTR_WIDTH)) { - myCurrentWidth = attrs.get(SUMO_ATTR_WIDTH, myCurrentID.c_str(), ok); - } - // try to get the offset of the stop line from the intersection - if (attrs.hasAttribute(SUMO_ATTR_ENDOFFSET)) { - myCurrentEndOffset = attrs.get(SUMO_ATTR_ENDOFFSET, myCurrentID.c_str(), ok); - } - // try to get the street name - if (attrs.hasAttribute(SUMO_ATTR_NAME)) { - myCurrentStreetName = attrs.get(SUMO_ATTR_NAME, myCurrentID.c_str(), ok); - if (myCurrentStreetName != "" && myOptions.isDefault("output.street-names")) { - myOptions.set("output.street-names", "true"); - } - } - - // try to get the allowed/disallowed classes - if (attrs.hasAttribute(SUMO_ATTR_ALLOW) || attrs.hasAttribute(SUMO_ATTR_DISALLOW)) { - std::string allowS = attrs.hasAttribute(SUMO_ATTR_ALLOW) ? attrs.getStringSecure(SUMO_ATTR_ALLOW, "") : ""; - std::string disallowS = attrs.hasAttribute(SUMO_ATTR_DISALLOW) ? attrs.getStringSecure(SUMO_ATTR_DISALLOW, "") : ""; - // XXX matter of interpretation: should updated permissions replace or extend previously set permissions? - myPermissions = parseVehicleClasses(allowS, disallowS); - } - // try to set the nodes - if (!setNodes(attrs)) { - // return if this failed - myCurrentEdge = nullptr; - return; - } - // try to get the shape - myShape = tryGetShape(attrs); - // try to get the spread type - myLanesSpread = tryGetLaneSpread(attrs); - // try to get the length - myLength = attrs.getOpt(SUMO_ATTR_LENGTH, myCurrentID.c_str(), ok, myLength); - // try to get the sidewalkWidth - mySidewalkWidth = attrs.getOpt(SUMO_ATTR_SIDEWALKWIDTH, myCurrentID.c_str(), ok, mySidewalkWidth); - // try to get the bikeLaneWidth - myBikeLaneWidth = attrs.getOpt(SUMO_ATTR_BIKELANEWIDTH, myCurrentID.c_str(), ok, myBikeLaneWidth); - // insert the parsed edge into the edges map - if (!ok) { - myCurrentEdge = nullptr; - return; - } - // check whether a previously defined edge shall be overwritten - if (myCurrentEdge != nullptr) { - myCurrentEdge->reinit(myFromNode, myToNode, myCurrentType, myCurrentSpeed, - myCurrentLaneNo, myCurrentPriority, myShape, - myCurrentWidth, myCurrentEndOffset, - myCurrentStreetName, myLanesSpread, - myReinitKeepEdgeShape); - } else { - // the edge must be allocated in dependence to whether a shape is given - if (myShape.size() == 0) { - myCurrentEdge = new NBEdge(myCurrentID, myFromNode, myToNode, myCurrentType, myCurrentSpeed, - myCurrentLaneNo, myCurrentPriority, myCurrentWidth, myCurrentEndOffset, - myCurrentStreetName, myLanesSpread); - } else { - myCurrentEdge = new NBEdge(myCurrentID, myFromNode, myToNode, myCurrentType, myCurrentSpeed, - myCurrentLaneNo, myCurrentPriority, myCurrentWidth, myCurrentEndOffset, - myShape, myCurrentStreetName, "", myLanesSpread, - myKeepEdgeShape); - } - } - myCurrentEdge->setLoadedLength(myLength); - if (myPermissions != SVC_UNSPECIFIED) { - myCurrentEdge->setPermissions(myPermissions); - } - // try to get the kilometrage/mileage - myCurrentEdge->setDistance(attrs.getOpt(SUMO_ATTR_DISTANCE, myCurrentID.c_str(), ok, myCurrentEdge->getDistance())); - - myLastParameterised.push_back(myCurrentEdge); -} - - -void -NIXMLEdgesHandler::addLane(const SUMOSAXAttributes& attrs) { - if (myCurrentEdge == nullptr) { - if (!OptionsCont::getOptions().isInStringVector("remove-edges.explicit", myCurrentID)) { - WRITE_ERRORF("Additional lane information could not be set - the edge with id '%s' is not known.", myCurrentID); - } - return; - } - bool ok = true; - int lane; - if (attrs.hasAttribute(SUMO_ATTR_ID)) { - lane = attrs.get(SUMO_ATTR_ID, myCurrentID.c_str(), ok); - if (!myHaveWarnedAboutDeprecatedLaneId) { - myHaveWarnedAboutDeprecatedLaneId = true; - WRITE_WARNING("'" + toString(SUMO_ATTR_ID) + "' is deprecated, please use '" + toString(SUMO_ATTR_INDEX) + "' instead."); - } - } else { - lane = attrs.get(SUMO_ATTR_INDEX, myCurrentID.c_str(), ok); - } - if (!ok) { - return; - } - // check whether this lane exists - if (lane >= myCurrentEdge->getNumLanes()) { - WRITE_ERROR("Lane index is larger than number of lanes (edge '" + myCurrentID + "')."); - return; - } - myCurrentLaneIndex = lane; - // set information about allowed / disallowed vehicle classes (if specified) - if (attrs.hasAttribute(SUMO_ATTR_ALLOW) || attrs.hasAttribute(SUMO_ATTR_DISALLOW)) { - const std::string allowed = attrs.getOpt(SUMO_ATTR_ALLOW, nullptr, ok, ""); - const std::string disallowed = attrs.getOpt(SUMO_ATTR_DISALLOW, nullptr, ok, ""); - myCurrentEdge->setPermissions(parseVehicleClasses(allowed, disallowed), lane); - } - if (attrs.hasAttribute(SUMO_ATTR_PREFER)) { - const std::string preferred = attrs.get(SUMO_ATTR_PREFER, nullptr, ok); - myCurrentEdge->setPreferredVehicleClass(parseVehicleClasses(preferred), lane); - } - // try to get the width - if (attrs.hasAttribute(SUMO_ATTR_WIDTH)) { - myCurrentEdge->setLaneWidth(lane, attrs.get(SUMO_ATTR_WIDTH, myCurrentID.c_str(), ok)); - } - // try to get the end-offset (lane shortened due to pedestrian crossing etc..) - if (attrs.hasAttribute(SUMO_ATTR_ENDOFFSET)) { - myCurrentEdge->setEndOffset(lane, attrs.get(SUMO_ATTR_ENDOFFSET, myCurrentID.c_str(), ok)); - } - // try to get lane specific speed (should not occur for german networks) - if (attrs.hasAttribute(SUMO_ATTR_SPEED)) { - myCurrentEdge->setSpeed(lane, attrs.get(SUMO_ATTR_SPEED, myCurrentID.c_str(), ok)); - } - // check whether this is an acceleration lane - if (attrs.hasAttribute(SUMO_ATTR_ACCELERATION)) { - myCurrentEdge->setAcceleration(lane, attrs.get(SUMO_ATTR_ACCELERATION, myCurrentID.c_str(), ok)); - } - // check whether this lane has a custom shape - if (attrs.hasAttribute(SUMO_ATTR_SHAPE)) { - PositionVector shape = attrs.get(SUMO_ATTR_SHAPE, myCurrentID.c_str(), ok); - if (!NBNetBuilder::transformCoordinates(shape)) { - const std::string laneID = myCurrentID + "_" + toString(lane); - WRITE_ERROR("Unable to project coordinates for lane '" + laneID + "'."); - } - if (shape.size() == 1) { - // lane shape of length 1 is not permitted - shape.push_front(myCurrentEdge->getFromNode()->getPosition()); - shape.push_back(myCurrentEdge->getToNode()->getPosition()); - } - shape.removeDoublePoints(); - if (shape.size() < 2) { - // ignore lane shape for very short lanes - shape.clear(); - } - myCurrentEdge->setLaneShape(lane, shape); - } - // set custom lane type - if (attrs.hasAttribute(SUMO_ATTR_TYPE)) { - myCurrentEdge->setLaneType(lane, attrs.get(SUMO_ATTR_TYPE, myCurrentID.c_str(), ok)); - } - myLastParameterised.push_back(&myCurrentEdge->getLaneStruct(lane)); -} - - -void NIXMLEdgesHandler::addSplit(const SUMOSAXAttributes& attrs) { - if (myCurrentEdge == nullptr) { - if (!OptionsCont::getOptions().isInStringVector("remove-edges.explicit", myCurrentID)) { - WRITE_WARNING("Ignoring 'split' because it cannot be assigned to an edge"); - } - return; - } - bool ok = true; - NBEdgeCont::Split e; - e.pos = attrs.get(SUMO_ATTR_POSITION, nullptr, ok); - if (ok) { - if (fabs(e.pos) > myCurrentEdge->getGeometry().length()) { - WRITE_ERROR("Edge '" + myCurrentID + "' has a split at invalid position " + toString(e.pos) + "."); - return; - } - std::vector::iterator i = find_if(mySplits.begin(), mySplits.end(), split_by_pos_finder(e.pos)); - if (i != mySplits.end()) { - WRITE_ERROR("Edge '" + myCurrentID + "' has already a split at position " + toString(e.pos) + "."); - return; - } - // XXX rounding to int may duplicate the id of another split - e.nameID = myCurrentID + "." + toString((int)e.pos); - if (e.pos < 0) { - e.pos += myCurrentEdge->getGeometry().length(); - } - for (const std::string& id : attrs.getOptStringVector(SUMO_ATTR_LANES, myCurrentID.c_str(), ok)) { - try { - int lane = StringUtils::toInt(id); - e.lanes.push_back(lane); - } catch (NumberFormatException&) { - WRITE_ERROR("Error on parsing a split (edge '" + myCurrentID + "')."); - } catch (EmptyData&) { - WRITE_ERROR("Error on parsing a split (edge '" + myCurrentID + "')."); - } - } - if (e.lanes.empty()) { - for (int l = 0; l < myCurrentEdge->getNumLanes(); ++l) { - e.lanes.push_back(l); - } - } - e.speed = attrs.getOpt(SUMO_ATTR_SPEED, nullptr, ok, myCurrentEdge->getSpeed()); - if (attrs.hasAttribute(SUMO_ATTR_SPEED) && myOptions.getBool("speed-in-kmh")) { - e.speed /= 3.6; - } - e.idBefore = attrs.getOpt(SUMO_ATTR_ID_BEFORE, nullptr, ok, std::string("")); - e.idAfter = attrs.getOpt(SUMO_ATTR_ID_AFTER, nullptr, ok, std::string("")); - if (!ok) { - return; - } - const std::string nodeID = attrs.getOpt(SUMO_ATTR_ID, nullptr, ok, e.nameID); - if (nodeID == myCurrentEdge->getFromNode()->getID() || nodeID == myCurrentEdge->getToNode()->getID()) { - WRITE_ERROR("Invalid split node id for edge '" + myCurrentEdge->getID() + "' (from- and to-node are forbidden)"); - return; - } - e.node = myNodeCont.retrieve(nodeID); - e.offsetFactor = OptionsCont::getOptions().getBool("lefthand") ? -1 : 1; - if (e.node == nullptr) { - e.node = new NBNode(nodeID, myCurrentEdge->getGeometry().positionAtOffset(e.pos)); - myNodeCont.insert(e.node); - } - NIXMLNodesHandler::processNodeType(attrs, e.node, e.node->getID(), e.node->getPosition(), false, - myNodeCont, myEdgeCont, myTLLogicCont); - mySplits.push_back(e); - } -} - - -bool -NIXMLEdgesHandler::setNodes(const SUMOSAXAttributes& attrs) { - // the names and the coordinates of the beginning and the end node - // may be found, try - bool ok = true; - if (myIsUpdate) { - myFromNode = myCurrentEdge->getFromNode(); - myToNode = myCurrentEdge->getToNode(); - } - if (attrs.hasAttribute(SUMO_ATTR_FROM)) { - const std::string begNodeID = attrs.get(SUMO_ATTR_FROM, nullptr, ok); - if (begNodeID != "") { - myFromNode = myNodeCont.retrieve(begNodeID); - if (myFromNode == nullptr) { - WRITE_ERROR("Edge's '" + myCurrentID + "' from-node '" + begNodeID + "' is not known."); - } - } - } else if (!myIsUpdate) { - WRITE_ERROR("The from-node is not given for edge '" + myCurrentID + "'."); - ok = false; - } - if (attrs.hasAttribute(SUMO_ATTR_TO)) { - const std::string endNodeID = attrs.get(SUMO_ATTR_TO, nullptr, ok); - if (endNodeID != "") { - myToNode = myNodeCont.retrieve(endNodeID); - if (myToNode == nullptr) { - WRITE_ERROR("Edge's '" + myCurrentID + "' to-node '" + endNodeID + "' is not known."); - } - } - } else if (!myIsUpdate) { - WRITE_ERROR("The to-node is not given for edge '" + myCurrentID + "'."); - ok = false; - } - return ok && myFromNode != nullptr && myToNode != nullptr; -} - - -PositionVector -NIXMLEdgesHandler::tryGetShape(const SUMOSAXAttributes& attrs) { - if (!attrs.hasAttribute(SUMO_ATTR_SHAPE)) { - return myShape; - } - // try to build shape - bool ok = true; - if (!attrs.hasAttribute(SUMO_ATTR_SHAPE)) { - myReinitKeepEdgeShape = false; - return PositionVector(); - } - PositionVector shape = attrs.getOpt(SUMO_ATTR_SHAPE, nullptr, ok, PositionVector()); - if (!NBNetBuilder::transformCoordinates(shape)) { - WRITE_ERROR("Unable to project coordinates for edge '" + myCurrentID + "'."); - } - myReinitKeepEdgeShape = myKeepEdgeShape; - return shape; -} - - -LaneSpreadFunction -NIXMLEdgesHandler::tryGetLaneSpread(const SUMOSAXAttributes& attrs) { - bool ok = true; - LaneSpreadFunction result = myLanesSpread; - std::string lsfS = toString(result); - lsfS = attrs.getOpt(SUMO_ATTR_SPREADTYPE, myCurrentID.c_str(), ok, lsfS); - if (SUMOXMLDefinitions::LaneSpreadFunctions.hasString(lsfS)) { - result = SUMOXMLDefinitions::LaneSpreadFunctions.get(lsfS); - } else { - WRITE_WARNING("Ignoring unknown spreadType '" + lsfS + "' for edge '" + myCurrentID + "'."); - } - return result; -} - - -void -NIXMLEdgesHandler::deleteEdge(const SUMOSAXAttributes& attrs) { - bool ok = true; - myCurrentID = attrs.get(SUMO_ATTR_ID, nullptr, ok); - if (!ok) { - return; - } - NBEdge* edge = myEdgeCont.retrieve(myCurrentID); - if (edge == nullptr) { - WRITE_WARNING("Ignoring tag '" + toString(SUMO_TAG_DEL) + "' for unknown edge '" + - myCurrentID + "'"); - return; - } - const int lane = attrs.getOpt(SUMO_ATTR_INDEX, myCurrentID.c_str(), ok, -1); - if (lane < 0) { - myEdgeCont.extract(myDistrictCont, edge, true); - } else { - edge->deleteLane(lane, false, true); - } -} - - -void -NIXMLEdgesHandler::myEndElement(int element) { - if (myCurrentEdge == nullptr) { - return; - } - if (element == SUMO_TAG_EDGE) { - myLastParameterised.pop_back(); - // add bike lane, wait until lanes are loaded to avoid building if it already exists - if (myBikeLaneWidth != NBEdge::UNSPECIFIED_WIDTH) { - myCurrentEdge->addBikeLane(myBikeLaneWidth); - } - // add sidewalk, wait until lanes are loaded to avoid building if it already exists - if (mySidewalkWidth != NBEdge::UNSPECIFIED_WIDTH) { - myCurrentEdge->addSidewalk(mySidewalkWidth); - } - // apply default stopOffsets of edge to all lanes without specified stopOffset. - std::map stopOffsets = myCurrentEdge->getStopOffsets(-1); - if (stopOffsets.size() != 0) { - for (int i = 0; i < (int)myCurrentEdge->getLanes().size(); i++) { - myCurrentEdge->setStopOffsets(i, stopOffsets, false); - } - } - if (!myIsUpdate) { - try { - if (!myEdgeCont.insert(myCurrentEdge)) { - WRITE_ERROR("Duplicate edge occurred. ID='" + myCurrentID + "'"); - delete myCurrentEdge; - } - } catch (InvalidArgument& e) { - WRITE_ERROR(e.what()); - throw; - } catch (...) { - WRITE_ERROR("An important information is missing in edge '" + myCurrentID + "'."); - } - } - myEdgeCont.processSplits(myCurrentEdge, mySplits, myNodeCont, myDistrictCont, myTLLogicCont); - myCurrentEdge = nullptr; - } else if (element == SUMO_TAG_LANE && myCurrentLaneIndex != -1) { - myLastParameterised.pop_back(); - myCurrentLaneIndex = -1; - } -} - - -void -NIXMLEdgesHandler::addRoundabout(const SUMOSAXAttributes& attrs) { - if (attrs.hasAttribute(SUMO_ATTR_EDGES)) { - std::vector edgeIDs = attrs.getStringVector(SUMO_ATTR_EDGES); - EdgeSet roundabout; - for (std::vector::iterator it = edgeIDs.begin(); it != edgeIDs.end(); ++it) { - NBEdge* edge = myEdgeCont.retrieve(*it); - if (edge == nullptr) { - if (!myEdgeCont.wasIgnored(*it)) { - WRITE_ERROR("Unknown edge '" + (*it) + "' in roundabout"); - } - } else { - roundabout.insert(edge); - } - } - myEdgeCont.addRoundabout(roundabout); - } else { - WRITE_ERROR("Empty edges in roundabout."); - } -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/NIXMLEdgesHandler.h b/Util/OSM2ODR/src/netimport/NIXMLEdgesHandler.h deleted file mode 100644 index 79831ed3c..000000000 --- a/Util/OSM2ODR/src/netimport/NIXMLEdgesHandler.h +++ /dev/null @@ -1,296 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIXMLEdgesHandler.h -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @author Leonhard Luecken -/// @date Tue, 20 Nov 2001 -/// -// Importer for network edges stored in XML -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include -#include -#include - - -// =========================================================================== -// class declarations -// =========================================================================== -class OptionsCont; -class NBNode; -class NBEdge; -class NBNodeCont; -class NBTypeCont; -class NBDistrictCont; -class NBTrafficLightLogicCont; - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NIXMLEdgesHandler - * @brief Importer for network edges stored in XML - * - * This SAX-handler parses edge information and stores it in the given - * container. - * @todo revalidate node retrieval - * @todo One day, one should rethink the order of parsing. Now, the handler - * is able to load edges, using information from the types, first, and extending - * them by given information. In addition, if the read edge is already known, - * it's values are also used. Then, defining vehicles allowed per lane, and - * additional edge split definitions add some further complexity. This all - * works somehow for most of our use cases, but it's definitely not as consistent - * that everything what seems to be possible would also work appropriately. - */ -class NIXMLEdgesHandler : public SUMOSAXHandler { -public: - /** @brief Constructor - * @param[in] nc The nodes container (for retrieval of referenced nodes) - * @param[in] ec The edges container (for insertion of build edges) - * @param[in] tc The types container (for retrieval of type defaults) - * @param[in] dc The districts container (needed if an edge must be split) - * @param[in] options The options to use while building edges - */ - NIXMLEdgesHandler(NBNodeCont& nc, NBEdgeCont& ec, - NBTypeCont& tc, NBDistrictCont& dc, - NBTrafficLightLogicCont& tlc, - OptionsCont& options); - - - /// @brief Destructor - ~NIXMLEdgesHandler(); - -protected: - /// @name inherited from GenericSAXHandler - //@{ - - /** @brief Called on the opening of a tag; - * - * @param[in] element ID of the currently opened element - * @param[in] attrs Attributes within the currently opened element - * @exception ProcessError If something fails - * @see GenericSAXHandler::myStartElement - */ - void myStartElement(int element, - const SUMOSAXAttributes& attrs); - - - /** @brief Called when a closing tag occurs - * - * @param[in] element ID of the currently opened element - * @exception ProcessError If something fails - * @see GenericSAXHandler::myEndElement - */ - void myEndElement(int element); - //@} - - -private: - /** @brief Tries to parse the shape definition - * - * Returns the edge's geometry (may be empty if no one was defined). - * Writes an error message if an error occurred. - * @param[in] attrs The attributes to read the shape from - * @return The edge's shape - */ - PositionVector tryGetShape(const SUMOSAXAttributes& attrs); - - - /** @brief Tries to parse the spread type - */ - LaneSpreadFunction tryGetLaneSpread(const SUMOSAXAttributes& attrs); - - - /** @brief Sets from/to node information of the currently parsed edge - * - * If the nodes could be retrieved/built, they are set in myFromNode/myToNode, - * respectively, and true is returned. If not, false is returned. - * @param[in] attrs The SAX-attributes to parse the nodes from - * @return Whether valid nodes exist - */ - bool setNodes(const SUMOSAXAttributes& attrs); - - -private: - /// @brief A reference to the program's options - OptionsCont& myOptions; - - - /// @name Currently parsed edge's values - /// @{ - - /// @brief The current edge's id - std::string myCurrentID; - - /// @brief The current edge's maximum speed - double myCurrentSpeed; - - /// @brief The current edge's priority - int myCurrentPriority; - - /// @brief The current edge's number of lanes - int myCurrentLaneNo; - - /// @brief The current edge's lane width - double myCurrentWidth; - - /// @brief The current edge's offset till the destination node - double myCurrentEndOffset; - - /// @brief The current edge's street name - std::string myCurrentStreetName; - - /// @brief The current edge's type - std::string myCurrentType; - - /// @brief The nodes the edge starts and ends at - NBNode* myFromNode, *myToNode; - - /// @brief The current edge's length - double myLength; - - /// @brief The shape of the edge - PositionVector myShape; - - /// @brief Information about how to spread the lanes - LaneSpreadFunction myLanesSpread; - - /// @brief Information about lane permissions - SVCPermissions myPermissions; - - /// @brief Whether the edge shape shall be kept at reinitilization - bool myReinitKeepEdgeShape; - - /// @brief The width of the sidewalk that shall be added to the current edge - double mySidewalkWidth; - - /// @brief The width of the bike lane that shall be added to the current edge - double myBikeLaneWidth; - - /// @} - - - /// @brief Whether this edge definition is an update of a previously inserted edge - bool myIsUpdate; - - - /// @name Used instance containers (access to nodes, edges, types, etc.) - /// @{ - - /// @brief The nodes container (for retrieval of referenced nodes) - NBNodeCont& myNodeCont; - - /// @brief The edges container (for insertion of build edges) - NBEdgeCont& myEdgeCont; - - /// @brief The types container (for retrieval of type defaults) - NBTypeCont& myTypeCont; - - /// @brief The districts container (needed if an edge must be split) - NBDistrictCont& myDistrictCont; - - /** @brief The traffic lights container to add built tls to (when - * invalidating tls because of splits) */ - NBTrafficLightLogicCont& myTLLogicCont; - /// @} - - - /// @brief The currently processed edge - NBEdge* myCurrentEdge; - - /// @brief The currently processed lane index - int myCurrentLaneIndex; - - /// @brief The list of this edge's splits - std::vector mySplits; - - /** @class split_by_pos_finder - * @brief Finds a split at the given position - */ - class split_by_pos_finder { - public: - /// @brief Constructor - explicit split_by_pos_finder(double pos) - : myPosition(pos) { } - - /// @brief Comparing operator - bool operator()(const NBEdgeCont::Split& e) { - return e.pos == myPosition; - } - - private: - /// @brief The position to search for - double myPosition; - - }; - - - /// @brief Information whether at least one edge's attributes were overwritten - bool myHaveReportedAboutOverwriting; - - /// @brief Information whether at least one edge's type was changed - bool myHaveReportedAboutTypeOverride; - - bool myHaveWarnedAboutDeprecatedLaneId; - - /// @brief Whether the edge shape shall be kept generally - const bool myKeepEdgeShape; - - /// @brief element to receive parameters - std::vector myLastParameterised; - -private: - - /** @brief Parses an edge and stores the values in "myCurrentEdge" - * @param[in] attrs The attributes to get the edge's values from - */ - void addEdge(const SUMOSAXAttributes& attrs); - - /** @brief parses delete tag and deletes the specified edge or lane - * @param[in] attrs The attributes to get the edge id and the optional lane index from - */ - void deleteEdge(const SUMOSAXAttributes& attrs); - - /** @brief Parses a lane and modifies myCurrentEdge according to the given - * attribures - * @param[in] attrs The attributes to get the lanes's values from - */ - void addLane(const SUMOSAXAttributes& attrs); - - /** @brief Parses a split and stores it in mySplits. Splits are executed Upon reading the end - * tag of an edge - * @param[in] attrs The attributes to get the splits's values from - */ - void addSplit(const SUMOSAXAttributes& attrs); - - /** @brief Parses a roundabout and stores it in myEdgeCont. - * @param[in] attrs The attributes to get the roundabouts values from - */ - void addRoundabout(const SUMOSAXAttributes& attrs); - - -private: - /** @brief invalid copy constructor */ - NIXMLEdgesHandler(const NIXMLEdgesHandler& s); - - /** @brief invalid assignment operator */ - NIXMLEdgesHandler& operator=(const NIXMLEdgesHandler& s); - -}; diff --git a/Util/OSM2ODR/src/netimport/NIXMLNodesHandler.cpp b/Util/OSM2ODR/src/netimport/NIXMLNodesHandler.cpp deleted file mode 100644 index 44b5e3e31..000000000 --- a/Util/OSM2ODR/src/netimport/NIXMLNodesHandler.cpp +++ /dev/null @@ -1,363 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIXMLNodesHandler.cpp -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Sascha Krieg -/// @author Michael Behrisch -/// @date Tue, 20 Nov 2001 -/// -// Importer for network nodes stored in XML -/****************************************************************************/ -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "NIXMLNodesHandler.h" -#include "NIImporter_SUMO.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -NIXMLNodesHandler::NIXMLNodesHandler(NBNodeCont& nc, NBEdgeCont& ec, - NBTrafficLightLogicCont& tlc, - OptionsCont& options) : - SUMOSAXHandler("xml-nodes - file"), - myOptions(options), - myNodeCont(nc), - myEdgeCont(ec), - myTLLogicCont(tlc), - myLocation(nullptr), - myLastParameterised(nullptr) { -} - - -NIXMLNodesHandler::~NIXMLNodesHandler() { - delete myLocation; -} - - -void -NIXMLNodesHandler::myStartElement(int element, - const SUMOSAXAttributes& attrs) { - switch (element) { - case SUMO_TAG_LOCATION: - myLocation = NIImporter_SUMO::loadLocation(attrs); - break; - case SUMO_TAG_NODE: - addNode(attrs); - break; - case SUMO_TAG_JOIN: - addJoinCluster(attrs); - break; - case SUMO_TAG_JOINEXCLUDE: - addJoinExclusion(attrs); - break; - case SUMO_TAG_DEL: - deleteNode(attrs); - break; - case SUMO_TAG_PARAM: - if (myLastParameterised != nullptr) { - bool ok = true; - const std::string key = attrs.get(SUMO_ATTR_KEY, nullptr, ok); - // circumventing empty string test - const std::string val = attrs.hasAttribute(SUMO_ATTR_VALUE) ? attrs.getString(SUMO_ATTR_VALUE) : ""; - myLastParameterised->setParameter(key, val); - } - default: - break; - } -} - - -void -NIXMLNodesHandler::myEndElement(int element) { - switch (element) { - case SUMO_TAG_NODE: - myLastParameterised = nullptr; - break; - default: - break; - } -} - - -void -NIXMLNodesHandler::addNode(const SUMOSAXAttributes& attrs) { - bool ok = true; - // get the id, report a warning if not given or empty... - myID = attrs.get(SUMO_ATTR_ID, nullptr, ok); - if (!ok) { - return; - } - NBNode* node = myNodeCont.retrieve(myID); - // retrieve the position of the node - bool xOk = false; - bool yOk = false; - bool needConversion = true; - if (node != nullptr) { - myPosition = node->getPosition(); - xOk = yOk = true; - needConversion = false; - } else { - myPosition.set(0, 0, 0); // better to reset than to reuse the previous (z)-value - } - if (attrs.hasAttribute(SUMO_ATTR_X)) { - myPosition.set(attrs.get(SUMO_ATTR_X, myID.c_str(), ok), myPosition.y()); - xOk = true; - needConversion = true; - } - if (attrs.hasAttribute(SUMO_ATTR_Y)) { - myPosition.set(myPosition.x(), attrs.get(SUMO_ATTR_Y, myID.c_str(), ok)); - yOk = true; - needConversion = true; - } - if (attrs.hasAttribute(SUMO_ATTR_Z)) { - myPosition.set(myPosition.x(), myPosition.y(), attrs.get(SUMO_ATTR_Z, myID.c_str(), ok)); - } - if (xOk && yOk) { - if (needConversion && !NBNetBuilder::transformCoordinate(myPosition, true, myLocation)) { - WRITE_ERROR("Unable to project coordinates for node '" + myID + "'."); - } - } else { - WRITE_ERROR("Missing position (at node ID='" + myID + "')."); - } - bool updateEdgeGeometries = node != nullptr && myPosition != node->getPosition(); - node = processNodeType(attrs, node, myID, myPosition, updateEdgeGeometries, myNodeCont, myEdgeCont, myTLLogicCont); - myLastParameterised = node; -} - - -NBNode* -NIXMLNodesHandler::processNodeType(const SUMOSAXAttributes& attrs, NBNode* node, const std::string& nodeID, const Position& position, - bool updateEdgeGeometries, - NBNodeCont& nc, NBEdgeCont& ec, NBTrafficLightLogicCont& tlc) { - bool ok = true; - // get the type - SumoXMLNodeType type = SumoXMLNodeType::UNKNOWN; - if (node != nullptr) { - type = node->getType(); - } - std::string typeS = attrs.getOpt(SUMO_ATTR_TYPE, nodeID.c_str(), ok, ""); - if (SUMOXMLDefinitions::NodeTypes.hasString(typeS)) { - type = SUMOXMLDefinitions::NodeTypes.get(typeS); - if (type == SumoXMLNodeType::DEAD_END_DEPRECATED || type == SumoXMLNodeType::DEAD_END) { - // dead end is a computed status. Reset this to unknown so it will - // be corrected if additional connections are loaded - type = SumoXMLNodeType::UNKNOWN; - } - } - std::set oldTLS; - // check whether a prior node shall be modified - if (node == nullptr) { - node = new NBNode(nodeID, position, type); - if (!nc.insert(node)) { - throw ProcessError("Could not insert node though checked this before (id='" + nodeID + "')."); - } - } else { - // patch information - oldTLS = node->getControllingTLS(); - if (node->getType() == SumoXMLNodeType::PRIORITY && type == SumoXMLNodeType::RIGHT_BEFORE_LEFT) { - ec.removeRoundabout(node); - } - node->reinit(position, type, updateEdgeGeometries); - } - // process traffic light definition - if (NBNode::isTrafficLight(type)) { - processTrafficLightDefinitions(attrs, node, tlc); - } - // remove previously set tls if this node is not controlled by them - for (std::set::iterator i = oldTLS.begin(); i != oldTLS.end(); ++i) { - if ((*i)->getNodes().size() == 0) { - tlc.removeFully((*i)->getID()); - } - } - - // set optional shape - PositionVector shape; - if (attrs.hasAttribute(SUMO_ATTR_SHAPE)) { - shape = attrs.getOpt(SUMO_ATTR_SHAPE, nodeID.c_str(), ok, PositionVector()); - if (!NBNetBuilder::transformCoordinates(shape)) { - WRITE_ERROR("Unable to project node shape at node '" + node->getID() + "'."); - } - if (shape.size() > 2) { - shape.closePolygon(); - } - node->setCustomShape(shape); - } - // set optional radius - if (attrs.hasAttribute(SUMO_ATTR_RADIUS)) { - node->setRadius(attrs.get(SUMO_ATTR_RADIUS, nodeID.c_str(), ok)); - } - // set optional keepClear flag - if (attrs.hasAttribute(SUMO_ATTR_KEEP_CLEAR)) { - node->setKeepClear(attrs.get(SUMO_ATTR_KEEP_CLEAR, nodeID.c_str(), ok)); - } - - // set optional right-of-way hint - if (attrs.hasAttribute(SUMO_ATTR_RIGHT_OF_WAY)) { - node->setRightOfWay(attrs.getRightOfWay(ok)); - } - - // set optional fringe type - if (attrs.hasAttribute(SUMO_ATTR_FRINGE)) { - node->setFringeType(attrs.getFringeType(ok)); - } - // set optional name - if (attrs.hasAttribute(SUMO_ATTR_NAME)) { - node->setName(attrs.get(SUMO_ATTR_NAME, nodeID.c_str(), ok)); - } - return node; -} - - -void -NIXMLNodesHandler::deleteNode(const SUMOSAXAttributes& attrs) { - bool ok = true; - // get the id, report a warning if not given or empty... - myID = attrs.get(SUMO_ATTR_ID, nullptr, ok); - if (!ok) { - return; - } - NBNode* node = myNodeCont.retrieve(myID); - if (node == nullptr) { - WRITE_WARNING("Ignoring tag '" + toString(SUMO_TAG_DEL) + "' for unknown node '" + - myID + "'"); - return; - } else { - myNodeCont.extract(node, true); - } -} - - -void -NIXMLNodesHandler::addJoinCluster(const SUMOSAXAttributes& attrs) { - bool ok = true; - const std::string clusterString = attrs.get(SUMO_ATTR_NODES, nullptr, ok); - std::vector ids = StringTokenizer(clusterString).getVector(); - std::sort(ids.begin(), ids.end()); - - myID = attrs.getOpt(SUMO_ATTR_ID, nullptr, ok, "cluster_" + joinToString(ids, "_")); - - Position myPosition = Position::INVALID; - if (attrs.hasAttribute(SUMO_ATTR_X)) { - myPosition.setx(attrs.get(SUMO_ATTR_X, myID.c_str(), ok)); - } - if (attrs.hasAttribute(SUMO_ATTR_Y)) { - myPosition.sety(attrs.get(SUMO_ATTR_Y, myID.c_str(), ok)); - } - if (attrs.hasAttribute(SUMO_ATTR_Z)) { - myPosition.setz(attrs.get(SUMO_ATTR_Z, myID.c_str(), ok)); - } - - NBNode* node = processNodeType(attrs, nullptr, myID, myPosition, false, myNodeCont, myEdgeCont, myTLLogicCont); - if (ok) { - myNodeCont.addCluster2Join(std::set(ids.begin(), ids.end()), node); - } -} - - -void -NIXMLNodesHandler::addJoinExclusion(const SUMOSAXAttributes& attrs) { - bool ok = true; - const std::vector ids = StringTokenizer( - attrs.get(SUMO_ATTR_NODES, nullptr, ok)).getVector(); - if (ok) { - myNodeCont.addJoinExclusion(ids); - } -} - - -void -NIXMLNodesHandler::processTrafficLightDefinitions(const SUMOSAXAttributes& attrs, - NBNode* currentNode, NBTrafficLightLogicCont& tlc) { - // try to get the tl-id - // if a tl-id is given, we will look whether this tl already exists - // if so, we will add the node to it (and to all programs with this id), otherwise allocate a new one with this id - // if no tl-id exists, we will build a tl with the node's id - std::set tlDefs; - bool ok = true; - - std::string oldTlID = ""; - std::string oldTypeS = OptionsCont::getOptions().getString("tls.default-type"); - - if (currentNode->isTLControlled()) { - NBTrafficLightDefinition* oldDef = *(currentNode->getControllingTLS().begin()); - oldTlID = oldDef->getID(); - oldTypeS = toString(oldDef->getType()); - } - std::string tlID = attrs.getOpt(SUMO_ATTR_TLID, nullptr, ok, oldTlID); - std::string typeS = attrs.getOpt(SUMO_ATTR_TLTYPE, nullptr, ok, oldTypeS); - if (tlID != oldTlID || typeS != oldTypeS) { - currentNode->removeTrafficLights(); - } - TrafficLightType type; - if (SUMOXMLDefinitions::TrafficLightTypes.hasString(typeS)) { - type = SUMOXMLDefinitions::TrafficLightTypes.get(typeS); - } else { - WRITE_ERROR("Unknown traffic light type '" + typeS + "' for node '" + currentNode->getID() + "'."); - return; - } - if (tlID != "" && tlc.getPrograms(tlID).size() > 0) { - // we already have definitions for this tlID - const std::map& programs = tlc.getPrograms(tlID); - std::map::const_iterator it; - for (it = programs.begin(); it != programs.end(); it++) { - if (it->second->getType() != type) { - WRITE_ERROR("Mismatched traffic light type '" + typeS + "' for tl '" + tlID + "'."); - ok = false; - } else { - tlDefs.insert(it->second); - it->second->addNode(currentNode); - } - } - } else { - // we need to add a new defition - tlID = (tlID == "" ? currentNode->getID() : tlID); - NBTrafficLightDefinition* tlDef = new NBOwnTLDef(tlID, currentNode, 0, type); - if (!tlc.insert(tlDef)) { - // actually, nothing should fail here - delete tlDef; - throw ProcessError("Could not allocate tls '" + currentNode->getID() + "'."); - } - tlDefs.insert(tlDef); - } - // process inner edges which shall be controlled - const std::vector& controlledInner = attrs.getOptStringVector(SUMO_ATTR_CONTROLLED_INNER, nullptr, ok); - if (controlledInner.size() != 0) { - for (std::set::iterator it = tlDefs.begin(); it != tlDefs.end(); it++) { - (*it)->addControlledInnerEdges(controlledInner); - } - } -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/NIXMLNodesHandler.h b/Util/OSM2ODR/src/netimport/NIXMLNodesHandler.h deleted file mode 100644 index a8c2bb443..000000000 --- a/Util/OSM2ODR/src/netimport/NIXMLNodesHandler.h +++ /dev/null @@ -1,167 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIXMLNodesHandler.h -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date Tue, 20 Nov 2001 -/// -// Importer for network nodes stored in XML -/****************************************************************************/ -#pragma once -#include - -#include -#include - - -// =========================================================================== -// class declarations -// =========================================================================== -class OptionsCont; -class GeoConvHelper; -class NBNode; -class NBNodeCont; -class NBTrafficLightLogicCont; - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NIXMLNodesHandler - * @brief Importer for network nodes stored in XML - * - * This SAX-handler parses node information and stores it in the given node - * container. Additionally, the given tls-container may be filled with - * additional information. - */ -class NIXMLNodesHandler : public SUMOSAXHandler { - -public: - /** @brief Constructor - * - * @param[in, filled] nc The node container to fill - * @param[in, filled] tlc The traffic lights container to fill - * @param[in] options The options to use - * @todo Options are only given to determine whether "flip-y" is set; maybe this should be done by giving a bool - * @todo Why are options not const? - */ - NIXMLNodesHandler(NBNodeCont& nc, NBEdgeCont& ec, NBTrafficLightLogicCont& tlc, - OptionsCont& options); - - - /// @brief Destructor - ~NIXMLNodesHandler(); - - /** @brief parses node attributes (not related to positioning) - */ - static NBNode* processNodeType(const SUMOSAXAttributes& attrs, NBNode* node, const std::string& nodeID, const Position& position, - bool updateEdgeGeometries, - NBNodeCont& nc, NBEdgeCont& ec, - NBTrafficLightLogicCont& tlc); - -protected: - /// @name inherited from GenericSAXHandler - //@{ - - /** @brief Called on the opening of a tag; - * - * In dependence to the obtained type, an appropriate parsing method is called. - * - * @param[in] element ID of the currently opened element - * @param[in] attrs Attributes within the currently opened element - * @exception ProcessError If something fails (not used herein) - * @note policy is to throw no exception in order to allow further processing - * @todo ProcessErrors are thrown when parsing traffic lights!? - */ - void myStartElement(int element, - const SUMOSAXAttributes& attrs); - /** @brief Called when a closing tag occurs - * - * @param[in] element ID of the currently opened element - * @exception ProcessError If something fails - * @see GenericSAXHandler::myEndElement - */ - void myEndElement(int element); - //@} - - -private: - /* - * @brief Parses node information - * Tries to parse a node. If the node can be parsed, it is stored within - * "myNodeCont". Otherwise an error is generated. Then, if given - * the tls information is parsed and inserted into "myTLLogicCont". - */ - void addNode(const SUMOSAXAttributes& attrs); - - /* - * @brief Parses node deletion information - */ - void deleteNode(const SUMOSAXAttributes& attrs); - - /* - * @brief Parses a cluster of nodes to be joined - */ - void addJoinCluster(const SUMOSAXAttributes& attrs); - - /* - * @brief Parses a list of nodes to be excluded from joining - */ - void addJoinExclusion(const SUMOSAXAttributes& attrs); - - - /** @brief Builds the defined traffic light or adds a node to it - * - * @param[in] attrs Attributes within the currently opened node - * @param[in] currentNode The built node to add the tls information to - */ - static void processTrafficLightDefinitions(const SUMOSAXAttributes& attrs, - NBNode* currentNode, NBTrafficLightLogicCont& tlc); - - -private: - /// @brief A reference to the program's options - OptionsCont& myOptions; - - /// @brief The id of the currently parsed node - std::string myID; - - /// @brief The position of the currently parsed node - Position myPosition; - - /// @brief The node container to add built nodes to - NBNodeCont& myNodeCont; - - /// @brief The node container to add built nodes to - NBEdgeCont& myEdgeCont; - - /// @brief The traffic lights container to add built tls to - NBTrafficLightLogicCont& myTLLogicCont; - - /// @brief The coordinate transformation which was used compute the node coordinates - GeoConvHelper* myLocation; - - /// @brief last item the could receive parameters - Parameterised* myLastParameterised; - -private: - /** @brief invalid copy constructor */ - NIXMLNodesHandler(const NIXMLNodesHandler& s); - - /** @brief invalid assignment operator */ - NIXMLNodesHandler& operator=(const NIXMLNodesHandler& s); - -}; diff --git a/Util/OSM2ODR/src/netimport/NIXMLPTHandler.cpp b/Util/OSM2ODR/src/netimport/NIXMLPTHandler.cpp deleted file mode 100644 index 3004b3b80..000000000 --- a/Util/OSM2ODR/src/netimport/NIXMLPTHandler.cpp +++ /dev/null @@ -1,294 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIXMLPTHandler.cpp -/// @author Jakob Erdmann -/// @date Sat, 28 Jul 2018 -/// -// Importer for static public transport information -/****************************************************************************/ -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "NIImporter_OpenStreetMap.h" -#include "NIXMLNodesHandler.h" -#include "NIXMLPTHandler.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -NIXMLPTHandler::NIXMLPTHandler(NBEdgeCont& ec, NBPTStopCont& sc, NBPTLineCont& lc) : - SUMOSAXHandler("public transport - file"), - myEdgeCont(ec), - myStopCont(sc), - myLineCont(lc), - myCurrentLine(nullptr) { -} - - -NIXMLPTHandler::~NIXMLPTHandler() {} - - -void -NIXMLPTHandler::myStartElement(int element, - const SUMOSAXAttributes& attrs) { - switch (element) { - case SUMO_TAG_BUS_STOP: - case SUMO_TAG_TRAIN_STOP: - case SUMO_TAG_STOP: - if (myCurrentRouteID != "") { - addRouteStop(attrs); - } else if (myCurrentLine == nullptr) { - addPTStop(attrs); - } else { - addPTLineStop(attrs); - } - break; - case SUMO_TAG_ACCESS: - addAccess(attrs); - break; - case SUMO_TAG_PT_LINE: - addPTLine(attrs); - break; - case SUMO_TAG_ROUTE: - if (myCurrentLine == nullptr) { - addRoute(attrs); - } else { - addPTLineRoute(attrs); - } - break; - case SUMO_TAG_FLOW: - case SUMO_TAG_TRIP: - addPTLineFromFlow(attrs); - break; - case SUMO_TAG_PARAM: - if (myCurrentLine != nullptr) { - bool ok = true; - const std::string key = attrs.get(SUMO_ATTR_KEY, nullptr, ok); - if (key == "completeness") { - myCurrentCompletion = attrs.get(SUMO_ATTR_VALUE, nullptr, ok); - } else if (key == "name") { - myCurrentLine->setName(attrs.get(SUMO_ATTR_VALUE, nullptr, ok)); - } - } - break; - default: - break; - } -} - -void -NIXMLPTHandler::myEndElement(int element) { - switch (element) { - case SUMO_TAG_BUS_STOP: - case SUMO_TAG_TRAIN_STOP: - myCurrentStop = nullptr; - break; - case SUMO_TAG_PT_LINE: - case SUMO_TAG_FLOW: - case SUMO_TAG_TRIP: - myCurrentLine->setMyNumOfStops((int)(myCurrentLine->getStops().size() / myCurrentCompletion)); - myCurrentLine = nullptr; - break; - case SUMO_TAG_ROUTE: - myCurrentRouteID = ""; - break; - default: - break; - } -} - - -void -NIXMLPTHandler::addPTStop(const SUMOSAXAttributes& attrs) { - bool ok = true; - const std::string id = attrs.get(SUMO_ATTR_ID, "busStop", ok); - const std::string name = attrs.getOpt(SUMO_ATTR_NAME, id.c_str(), ok, ""); - const std::string laneID = attrs.get(SUMO_ATTR_LANE, id.c_str(), ok); - const double startPos = attrs.get(SUMO_ATTR_STARTPOS, id.c_str(), ok); - const double endPos = attrs.get(SUMO_ATTR_ENDPOS, id.c_str(), ok); - const double parkingLength = attrs.getOpt(SUMO_ATTR_PARKING_LENGTH, id.c_str(), ok, 0); - //const std::string lines = attrs.get(SUMO_ATTR_LINES, id.c_str(), ok); - const int laneIndex = NBEdge::getLaneIndexFromLaneID(laneID); - const std::string edgeID = SUMOXMLDefinitions::getEdgeIDFromLane(laneID); - NBEdge* edge = myEdgeCont.retrieve(edgeID); - if (edge == nullptr) { - if (!myEdgeCont.wasIgnored(edgeID)) { - WRITE_ERROR("Edge '" + edgeID + "' for stop '" + id + "' not found"); - } - return; - } - if (edge->getNumLanes() <= laneIndex) { - WRITE_ERROR("Lane '" + laneID + "' for stop '" + id + "' not found"); - return; - } - SVCPermissions permissions = edge->getPermissions(laneIndex); - // possibly the stops were written for a different network. If the lane is not a typical public transport stop lane, assume bus as the default - if (!isRailway(permissions) && permissions != SVC_SHIP && permissions != SVC_TAXI) { - permissions = SVC_BUS; - } - if (ok) { - Position pos = edge->geometryPositionAtOffset((startPos + endPos) / 2); - myCurrentStop = new NBPTStop(id, pos, edgeID, edgeID, endPos - startPos, name, permissions, parkingLength); - if (!myStopCont.insert(myCurrentStop)) { - WRITE_ERROR("Could not add public transport stop '" + id + "' (already exists)"); - } - } -} - -void -NIXMLPTHandler::addAccess(const SUMOSAXAttributes& attrs) { - if (myCurrentStop == nullptr) { - throw InvalidArgument("Could not add access outside a stopping place."); - } - bool ok = true; - const std::string lane = attrs.get(SUMO_ATTR_LANE, "access", ok); - const double pos = attrs.get(SUMO_ATTR_POSITION, "access", ok); - const double length = attrs.getOpt(SUMO_ATTR_LENGTH, "access", ok, -1); - myCurrentStop->addAccess(lane, pos, length); -} - - -void -NIXMLPTHandler::addPTLine(const SUMOSAXAttributes& attrs) { - bool ok = true; - const std::string id = attrs.get(SUMO_ATTR_ID, "ptLine", ok); - const std::string name = attrs.getOpt(SUMO_ATTR_ID, id.c_str(), ok, ""); - const std::string line = attrs.get(SUMO_ATTR_LINE, id.c_str(), ok); - const std::string type = attrs.get(SUMO_ATTR_TYPE, id.c_str(), ok); - SUMOVehicleClass vClass = NIImporter_OpenStreetMap::interpretTransportType(type); - if (attrs.hasAttribute(SUMO_ATTR_VCLASS)) { - vClass = getVehicleClassID(attrs.get(SUMO_ATTR_VCLASS, id.c_str(), ok)); - } - const int intervalS = attrs.getOpt(SUMO_ATTR_PERIOD, id.c_str(), ok, -1); - const std::string nightService = attrs.getStringSecure("nightService", ""); - myCurrentCompletion = StringUtils::toDouble(attrs.getStringSecure("completeness", "1")); - if (ok) { - myCurrentLine = new NBPTLine(id, name, type, line, intervalS / 60, nightService, vClass); - myLineCont.insert(myCurrentLine); - } -} - - -void -NIXMLPTHandler::addPTLineFromFlow(const SUMOSAXAttributes& attrs) { - bool ok = true; - const std::string id = attrs.get(SUMO_ATTR_ID, "flow", ok); - const std::string line = attrs.get(SUMO_ATTR_LINE, id.c_str(), ok); - const std::string type = attrs.get(SUMO_ATTR_TYPE, id.c_str(), ok); - const std::string route = attrs.get(SUMO_ATTR_ROUTE, id.c_str(), ok); - SUMOVehicleClass vClass = NIImporter_OpenStreetMap::interpretTransportType(type); - const int intervalS = attrs.getOpt(SUMO_ATTR_PERIOD, id.c_str(), ok, -1); - if (ok) { - myCurrentLine = new NBPTLine(id, "", type, line, intervalS / 60, "", vClass); - myCurrentLine->setEdges(myRouteEdges[route]); - for (NBPTStop* stop : myRouteStops[route]) { - myCurrentLine->addPTStop(stop); - } - myLineCont.insert(myCurrentLine); - } -} - - -void -NIXMLPTHandler::addPTLineRoute(const SUMOSAXAttributes& attrs) { - if (myCurrentLine == nullptr) { - WRITE_ERROR("Found route outside line definition"); - return; - } - const std::vector& edgeIDs = attrs.getStringVector(SUMO_ATTR_EDGES); - EdgeVector edges; - for (const std::string& edgeID : edgeIDs) { - NBEdge* edge = myEdgeCont.retrieve(edgeID); - if (edge == nullptr) { - if (!myEdgeCont.wasIgnored(edgeID)) { - WRITE_ERROR("Edge '" + edgeID + "' in route of line '" + myCurrentLine->getName() + "' not found"); - } - } else { - edges.push_back(edge); - } - } - myCurrentLine->setEdges(edges); -} - -void -NIXMLPTHandler::addRoute(const SUMOSAXAttributes& attrs) { - bool ok = true; - myCurrentRouteID = attrs.get(SUMO_ATTR_ID, "route", ok); - const std::vector& edgeIDs = attrs.getStringVector(SUMO_ATTR_EDGES); - EdgeVector edges; - for (const std::string& edgeID : edgeIDs) { - NBEdge* edge = myEdgeCont.retrieve(edgeID); - if (edge == nullptr) { - if (!myEdgeCont.wasIgnored(edgeID)) { - WRITE_ERROR("Edge '" + edgeID + "' in route of line '" + myCurrentLine->getName() + "' not found"); - } - } else { - edges.push_back(edge); - } - } - myRouteEdges[myCurrentRouteID] = edges; -} - - -void -NIXMLPTHandler::addPTLineStop(const SUMOSAXAttributes& attrs) { - bool ok = true; - const std::string id = attrs.hasAttribute(SUMO_ATTR_ID) - ? attrs.get(SUMO_ATTR_ID, "ptLine", ok) - : attrs.get(SUMO_ATTR_BUS_STOP, "ptline", ok); - NBPTStop* stop = myStopCont.get(id); - if (stop == nullptr) { - WRITE_ERROR("Stop '" + id + "' within line '" + toString(myCurrentLine->getLineID()) + "' not found"); - return; - } - myCurrentLine->addPTStop(stop); -} - -void -NIXMLPTHandler::addRouteStop(const SUMOSAXAttributes& attrs) { - assert(myCurrentRouteID != ""); - bool ok = true; - const std::string id = attrs.hasAttribute(SUMO_ATTR_ID) - ? attrs.get(SUMO_ATTR_ID, "ptLine", ok) - : attrs.get(SUMO_ATTR_BUS_STOP, "ptline", ok); - NBPTStop* stop = myStopCont.get(id); - if (stop == nullptr) { - WRITE_ERROR("Stop '" + id + "' within route '" + toString(myCurrentRouteID) + "' not found"); - return; - } - myRouteStops[myCurrentRouteID].push_back(stop); -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/NIXMLPTHandler.h b/Util/OSM2ODR/src/netimport/NIXMLPTHandler.h deleted file mode 100644 index 34baee00a..000000000 --- a/Util/OSM2ODR/src/netimport/NIXMLPTHandler.h +++ /dev/null @@ -1,206 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIXMLPTHandler.h -/// @author Jakob Erdmann -/// @date Sat, 28 Jul 2018 -/// -// Importer for static public transport information -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include -#include -#include - - -// =========================================================================== -// class declarations -// =========================================================================== -class OptionsCont; -class NBNode; -class NBEdge; -class NBNodeCont; -class NBTypeCont; -class NBDistrictCont; -class NBTrafficLightLogicCont; - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NIXMLPTHandler - * @brief Importer for network edges stored in XML - * - * This SAX-handler parses edge information and stores it in the given - * container. - * @todo revalidate node retrieval - * @todo One day, one should rethink the order of parsing. Now, the handler - * is able to load edges, using information from the types, first, and extending - * them by given information. In addition, if the read edge is already known, - * it's values are also used. Then, defining vehicles allowed per lane, and - * additional edge split definitions add some further complexity. This all - * works somehow for most of our use cases, but it's definitely not as consistent - * that everything what seems to be possible would also work appropriately. - */ -class NIXMLPTHandler : public SUMOSAXHandler { -public: - /** @brief Constructor - * @param[in] nc The nodes container (for retrieval of referenced nodes) - * @param[in] ec The edges container (for insertion of build edges) - * @param[in] tc The types container (for retrieval of type defaults) - * @param[in] dc The districts container (needed if an edge must be split) - * @param[in] options The options to use while building edges - */ - NIXMLPTHandler(NBEdgeCont& ec, NBPTStopCont& sc, NBPTLineCont& lc); - - - /// @brief Destructor - ~NIXMLPTHandler(); - -protected: - /// @name inherited from GenericSAXHandler - //@{ - - /** @brief Called on the opening of a tag; - * - * @param[in] element ID of the currently opened element - * @param[in] attrs Attributes within the currently opened element - * @exception ProcessError If something fails - * @see GenericSAXHandler::myStartElement - */ - void myStartElement(int element, - const SUMOSAXAttributes& attrs); - - - /** @brief Called when a closing tag occurs - * - * @param[in] element ID of the currently opened element - * @exception ProcessError If something fails - * @see GenericSAXHandler::myEndElement - */ - void myEndElement(int element); - //@} - - -private: - /** @brief Tries to parse the shape definition - * - * Returns the edge's geometry (may be empty if no one was defined). - * Writes an error message if an error occurred. - * @param[in] attrs The attributes to read the shape from - * @return The edge's shape - */ - PositionVector tryGetShape(const SUMOSAXAttributes& attrs); - - - /** @brief Tries to parse the spread type - */ - LaneSpreadFunction tryGetLaneSpread(const SUMOSAXAttributes& attrs); - - - /** @brief Sets from/to node information of the currently parsed edge - * - * If the nodes could be retrieved/built, they are set in myFromNode/myToNode, - * respectively, and true is returned. If not, false is returned. - * @param[in] attrs The SAX-attributes to parse the nodes from - * @return Whether valid nodes exist - */ - bool setNodes(const SUMOSAXAttributes& attrs); - - -private: - - /// @brief The edges container (for retrieving referenced stop edge) - NBEdgeCont& myEdgeCont; - - /// @brief The stop container (for loading of stops) - NBPTStopCont& myStopCont; - - /// @brief The line container (for loading of lines) - NBPTLineCont& myLineCont; - - /// @brief The currently processed stop - NBPTStop* myCurrentStop; - - /// @brief The currently processed line - NBPTLine* myCurrentLine; - - /// @brief The currently processed stand-alone route - std::string myCurrentRouteID; - - /// @brief the completion level of the current line - double myCurrentCompletion; - - /// @brief element to receive parameters - std::vector myLastParameterised; - - /// @brief stand-alone route information - std::map > myRouteStops; - std::map myRouteEdges; - -private: - - /** @brief Parses an public transport stop - * @param[in] attrs The attributes to get the stops's values from - */ - void addPTStop(const SUMOSAXAttributes& attrs); - - /** @brief Parses a route as port of a public transport line - * @param[in] attrs The attributes to get the routes's values from - */ - void addPTLineRoute(const SUMOSAXAttributes& attrs); - - /** @brief Parses a stand-alone route when parsing implicit ptlines from - * routes and flows - * @param[in] attrs The attributes to get the routes's values from - */ - void addRoute(const SUMOSAXAttributes& attrs); - - /** @brief Parses an public transport stop reference within a line element - * @param[in] attrs The attributes to get the stops's values from - */ - void addPTLineStop(const SUMOSAXAttributes& attrs); - - /** @brief Parses an public transport stop reference within a route element - * @param[in] attrs The attributes to get the stops's values from - */ - void addRouteStop(const SUMOSAXAttributes& attrs); - - /** @brief Parses an stop access definition - * @param[in] attrs The attributes to get the access's values from - */ - void addAccess(const SUMOSAXAttributes& attrs); - - /** @brief Parses a public transport line - * @param[in] attrs The attributes to get the lines's values from - */ - void addPTLine(const SUMOSAXAttributes& attrs); - - /** @brief Parses a public transport line - * @param[in] attrs The attributes to get the lines's values from - */ - void addPTLineFromFlow(const SUMOSAXAttributes& attrs); - - -private: - /** @brief invalid copy constructor */ - NIXMLPTHandler(const NIXMLPTHandler& s); - - /** @brief invalid assignment operator */ - NIXMLPTHandler& operator=(const NIXMLPTHandler& s); - -}; diff --git a/Util/OSM2ODR/src/netimport/NIXMLShapeHandler.cpp b/Util/OSM2ODR/src/netimport/NIXMLShapeHandler.cpp deleted file mode 100644 index f63034177..000000000 --- a/Util/OSM2ODR/src/netimport/NIXMLShapeHandler.cpp +++ /dev/null @@ -1,59 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIXMLShapeHandler.cpp -/// @author Jakob Erdmann -/// @date Sat, 28 Jul 2018 -/// -// Importer for static public transport information -/****************************************************************************/ -#include - -#include -#include -#include -#include -#include - -#include "NIXMLShapeHandler.h" - -// =========================================================================== -// method definitions -// =========================================================================== - -NIXMLShapeHandler::NIXMLShapeHandler(ShapeContainer& sc, const NBEdgeCont& ec) : - ShapeHandler("polgyon - file", sc, GeoConvHelper::getNumLoaded() == 0 ? nullptr : & GeoConvHelper::getLoaded()), - myEdgeCont(ec) -{} - -Position -NIXMLShapeHandler::getLanePos(const std::string& poiID, const std::string& laneID, double lanePos, double lanePosLat) { - std::string edgeID; - int laneIndex; - NBHelpers::interpretLaneID(laneID, edgeID, laneIndex); - NBEdge* edge = myEdgeCont.retrieve(edgeID); - if (edge == 0 || laneIndex < 0 || edge->getNumLanes() <= laneIndex) { - WRITE_ERROR("Lane '" + laneID + "' to place poi '" + poiID + "' on is not known."); - return Position::INVALID; - } - if (lanePos < 0) { - lanePos = edge->getLength() + lanePos; - } - if (lanePos < 0 || lanePos > edge->getLength()) { - WRITE_WARNING("lane position " + toString(lanePos) + " for poi '" + poiID + "' is not valid."); - } - return edge->getLanes()[laneIndex].shape.positionAtOffset(lanePos, -lanePosLat); -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/NIXMLShapeHandler.h b/Util/OSM2ODR/src/netimport/NIXMLShapeHandler.h deleted file mode 100644 index 500834e01..000000000 --- a/Util/OSM2ODR/src/netimport/NIXMLShapeHandler.h +++ /dev/null @@ -1,56 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIXMLShapeHandler.h -/// @author Jakob Erdmann -/// @date Sat, 28 Jul 2018 -/// -// Importer for static public transport information -/****************************************************************************/ -#pragma once - -#include - -#include -#include -// =========================================================================== -// class declarations -// =========================================================================== -class NBEdgeCont; -class Position; - -// =========================================================================== -// class definitions -// =========================================================================== - -/** - * @class NBShapeHandler - * @brief The XML-Handler for shapes loading network loading - * - * This subclasses ShapeHandler with MSLane specific function - */ -class NIXMLShapeHandler : public ShapeHandler { -public: - NIXMLShapeHandler(ShapeContainer& sc, const NBEdgeCont& ec); - - /// @brief Destructor - virtual ~NIXMLShapeHandler() {} - - Position getLanePos(const std::string& poiID, const std::string& laneID, double lanePos, double lanePosLat); - - virtual bool addLanePosParams() { - return true; - } - - const NBEdgeCont& myEdgeCont; -}; diff --git a/Util/OSM2ODR/src/netimport/NIXMLTrafficLightsHandler.cpp b/Util/OSM2ODR/src/netimport/NIXMLTrafficLightsHandler.cpp deleted file mode 100644 index 5a76f99cb..000000000 --- a/Util/OSM2ODR/src/netimport/NIXMLTrafficLightsHandler.cpp +++ /dev/null @@ -1,342 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2011-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIXMLTrafficLightsHandler.cpp -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @author Jakob Erdmann -/// @date 2011-10-05 -/// -// Importer for traffic lights stored in XML -/****************************************************************************/ -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "NIImporter_SUMO.h" -#include "NIXMLTrafficLightsHandler.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -NIXMLTrafficLightsHandler::NIXMLTrafficLightsHandler( - NBTrafficLightLogicCont& tlCont, NBEdgeCont& ec, bool ignoreUnknown) : - SUMOSAXHandler("xml-tllogics"), - myTLLCont(tlCont), - myEdgeCont(ec), - myCurrentTL(nullptr), - myResetPhases(false), - myIgnoreUnknown(ignoreUnknown) -{ } - - -NIXMLTrafficLightsHandler::~NIXMLTrafficLightsHandler() {} - - -void -NIXMLTrafficLightsHandler::myStartElement( - int element, const SUMOSAXAttributes& attrs) { - switch (element) { - case SUMO_TAG_TLLOGIC: - myCurrentTL = initTrafficLightLogic(attrs, myCurrentTL); - break; - case SUMO_TAG_PHASE: - if (myCurrentTL != nullptr) { - if (myResetPhases) { - myCurrentTL->getLogic()->resetPhases(); - myResetPhases = false; - } - NIImporter_SUMO::addPhase(attrs, myCurrentTL); - myCurrentTL->phasesLoaded(); - } - break; - case SUMO_TAG_CONNECTION: - addTlConnection(attrs); - break; - case SUMO_TAG_DEL: - removeTlConnection(attrs); - break; - case SUMO_TAG_PARAM: - if (myCurrentTL != nullptr) { - bool ok = true; - const std::string key = attrs.get(SUMO_ATTR_KEY, nullptr, ok); - // circumventing empty string test - const std::string val = attrs.hasAttribute(SUMO_ATTR_VALUE) ? attrs.getString(SUMO_ATTR_VALUE) : ""; - myCurrentTL->setParameter(key, val); - } - default: - break; - } -} - - -void -NIXMLTrafficLightsHandler::myEndElement(int element) { - switch (element) { - case SUMO_TAG_TLLOGIC: - myCurrentTL = nullptr; - break; - default: - break; - } -} - - -NBLoadedSUMOTLDef* -NIXMLTrafficLightsHandler::initTrafficLightLogic(const SUMOSAXAttributes& attrs, NBLoadedSUMOTLDef* currentTL) { - if (currentTL) { - WRITE_ERROR("Definition of tlLogic '" + currentTL->getID() + "' was not finished."); - return nullptr; - } - bool ok = true; - std::string id = attrs.get(SUMO_ATTR_ID, nullptr, ok); - std::string programID = attrs.getOpt(SUMO_ATTR_PROGRAMID, id.c_str(), ok, "UNKNOWN_PROGRAM"); - SUMOTime offset = attrs.hasAttribute(SUMO_ATTR_OFFSET) ? TIME2STEPS(attrs.get(SUMO_ATTR_OFFSET, id.c_str(), ok)) : 0; - std::string typeS = attrs.getOpt(SUMO_ATTR_TYPE, nullptr, ok, - OptionsCont::getOptions().getString("tls.default-type")); - TrafficLightType type; - if (SUMOXMLDefinitions::TrafficLightTypes.hasString(typeS)) { - type = SUMOXMLDefinitions::TrafficLightTypes.get(typeS); - } else { - WRITE_ERROR("Unknown traffic light type '" + typeS + "' for tlLogic '" + id + "'."); - return nullptr; - } - // there are three scenarios to consider - // 1) the tll.xml is loaded to update traffic lights defined in a net.xml: - // simply retrieve the loaded definitions and update them - // 2) the tll.xml is loaded to define new traffic lights - // nod.xml will have triggered building of NBOwnTLDef. Replace it with NBLoadedSUMOTLDef - // 3) the tll.xml is loaded to define new programs for a defined traffic light - // there should be a definition with the same id but different programID - const std::map& programs = myTLLCont.getPrograms(id); - if (programs.size() == 0) { - if (!myIgnoreUnknown) { - WRITE_ERROR("Cannot load traffic light program for unknown id '" + id + "', programID '" + programID + "'."); - } - return nullptr; - } - const std::string existingProgram = programs.begin()->first; // arbitrary for our purpose - NBLoadedSUMOTLDef* loadedDef = dynamic_cast(myTLLCont.getDefinition(id, programID)); - if (loadedDef == nullptr) { - NBLoadedSUMOTLDef* oldDef = dynamic_cast(myTLLCont.getDefinition(id, existingProgram)); - if (oldDef == nullptr) { - // case 2 - NBTrafficLightDefinition* newDef = dynamic_cast(myTLLCont.getDefinition( - id, NBTrafficLightDefinition::DefaultProgramID)); - bool deleteDefault = false; - if (newDef == nullptr) { - // the default program may have already been replaced with a loaded program - newDef = dynamic_cast(myTLLCont.getDefinition( - id, NBTrafficLightDefinition::DefaultProgramID)); - if (newDef == nullptr) { - WRITE_ERROR("Cannot load traffic light program for unknown id '" + id + "', programID '" + programID + "'."); - return nullptr; - } - } else { - deleteDefault = true; - } - assert(newDef != 0); - loadedDef = new NBLoadedSUMOTLDef(id, programID, offset, type); - // copy nodes and controlled inner edges - std::vector nodes = newDef->getNodes(); - for (std::vector::iterator it = nodes.begin(); it != nodes.end(); it++) { - loadedDef->addNode(*it); - } - loadedDef->addControlledInnerEdges(newDef->getControlledInnerEdges()); - if (deleteDefault) { - // make a copy because the vector is modified in the loop - const std::vector nodes = newDef->getNodes(); - // replace default Program - for (NBNode* const n : nodes) { - n->removeTrafficLight(newDef); - } - myTLLCont.removeProgram(id, NBTrafficLightDefinition::DefaultProgramID); - } - myTLLCont.insert(loadedDef); - } else { - // case 3 - NBTrafficLightLogic* oldLogic = oldDef->getLogic(); - NBTrafficLightLogic newLogic(id, programID, oldLogic->getNumLinks(), offset, type); - loadedDef = new NBLoadedSUMOTLDef(*oldDef, newLogic); - // copy nodes - std::vector nodes = oldDef->getNodes(); - for (std::vector::iterator it = nodes.begin(); it != nodes.end(); it++) { - loadedDef->addNode(*it); - } - //std::cout << " case3 oldDef=" << oldDef->getDescription() << " loadedDef=" << loadedDef->getDescription() << "\n"; - myTLLCont.insert(loadedDef); - } - } else { - // case 1 - if (attrs.hasAttribute(SUMO_ATTR_OFFSET)) { - loadedDef->setOffset(offset); - } - if (attrs.hasAttribute(SUMO_ATTR_TYPE)) { - loadedDef->setType(type); - } - } - if (ok) { - myResetPhases = true; - return loadedDef; - } else { - return nullptr; - } -} - - -void -NIXMLTrafficLightsHandler::addTlConnection(const SUMOSAXAttributes& attrs) { - bool ok = true; - // parse identifying attributes - NBEdge* from = retrieveEdge(attrs, SUMO_ATTR_FROM, ok); - NBEdge* to = retrieveEdge(attrs, SUMO_ATTR_TO, ok); - if (!ok) { - return; - } - int fromLane = retrieveLaneIndex(attrs, SUMO_ATTR_FROM_LANE, from, ok); - int toLane = retrieveLaneIndex(attrs, SUMO_ATTR_TO_LANE, to, ok); - if (!ok) { - return; - } - // retrieve connection - const std::vector& connections = from->getConnections(); - std::vector::const_iterator con_it; - con_it = find_if(connections.begin(), connections.end(), - NBEdge::connections_finder(fromLane, to, toLane)); - if (con_it == connections.end()) { - WRITE_ERROR("Connection from=" + from->getID() + " to=" + to->getID() + - " fromLane=" + toString(fromLane) + " toLane=" + toString(toLane) + " not found"); - return; - } - NBEdge::Connection c = *con_it; - // read other attributes - std::string tlID = attrs.getOpt(SUMO_ATTR_TLID, nullptr, ok, ""); - if (tlID == "") { - // we are updating an existing tl-controlled connection - tlID = (*(from->getToNode()->getControllingTLS().begin()))->getID(); - assert(tlID != ""); - } - int tlIndex = attrs.getOpt(SUMO_ATTR_TLLINKINDEX, nullptr, ok, -1); - if (tlIndex == -1) { - // we are updating an existing tl-controlled connection - tlIndex = c.tlLinkIndex; - } - int tlIndex2 = attrs.getOpt(SUMO_ATTR_TLLINKINDEX2, nullptr, ok, -1); - if (tlIndex2 == -1) { - // we are updating an existing tl-controlled connection or index2 is not used - tlIndex2 = c.tlLinkIndex2; - } - - // register the connection with all definitions - const std::map& programs = myTLLCont.getPrograms(tlID); - if (programs.size() > 0) { - std::map::const_iterator it; - for (it = programs.begin(); it != programs.end(); it++) { - NBLoadedSUMOTLDef* tlDef = dynamic_cast(it->second); - if (tlDef) { - tlDef->addConnection(from, c.toEdge, c.fromLane, c.toLane, tlIndex, tlIndex2, false); - } else { - throw ProcessError("Corrupt traffic light definition '" - + tlID + "' (program '" + it->first + "')"); - } - } - } else { - SumoXMLNodeType type = from->getToNode()->getType(); - if (type != SumoXMLNodeType::RAIL_CROSSING && type != SumoXMLNodeType::RAIL_SIGNAL) { - WRITE_ERROR("The traffic light '" + tlID + "' is not known."); - } - } -} - - -void -NIXMLTrafficLightsHandler::removeTlConnection(const SUMOSAXAttributes& attrs) { - bool ok = true; - std::string tlID = attrs.get(SUMO_ATTR_TLID, nullptr, ok); - // does the traffic light still exist? - const std::map& programs = myTLLCont.getPrograms(tlID); - if (programs.size() > 0) { - // parse identifying attributes - NBEdge* from = retrieveEdge(attrs, SUMO_ATTR_FROM, ok); - NBEdge* to = retrieveEdge(attrs, SUMO_ATTR_TO, ok); - int fromLane = -1; - int toLane = -1; - if (ok) { - fromLane = retrieveLaneIndex(attrs, SUMO_ATTR_FROM_LANE, from, ok, true); - toLane = retrieveLaneIndex(attrs, SUMO_ATTR_TO_LANE, to, ok, true); - } - int tlIndex = attrs.get(SUMO_ATTR_TLLINKINDEX, nullptr, ok); - - NBConnection conn(from, fromLane, to, toLane, tlIndex); - // remove the connection from all definitions - std::map::const_iterator it; - for (it = programs.begin(); it != programs.end(); it++) { - NBLoadedSUMOTLDef* tlDef = dynamic_cast(it->second); - if (tlDef) { - tlDef->removeConnection(conn, false); - } else { - throw ProcessError("Corrupt traffic light definition '" - + tlID + "' (program '" + it->first + "')"); - } - } - } -} - - -NBEdge* -NIXMLTrafficLightsHandler::retrieveEdge( - const SUMOSAXAttributes& attrs, SumoXMLAttr attr, bool& ok) { - std::string edgeID = attrs.get(attr, nullptr, ok); - NBEdge* edge = myEdgeCont.retrieve(edgeID, true); - if (edge == nullptr) { - WRITE_ERROR("Unknown edge '" + edgeID + "' given in connection."); - ok = false; - } - return edge; -} - - -int -NIXMLTrafficLightsHandler::retrieveLaneIndex( - const SUMOSAXAttributes& attrs, SumoXMLAttr attr, NBEdge* edge, bool& ok, bool isDelete) { - int laneIndex = attrs.get(attr, nullptr, ok); - if (edge->getNumLanes() <= laneIndex) { - if (!isDelete) { - WRITE_ERROR("Invalid lane index '" + toString(laneIndex) + "' for edge '" + edge->getID() + "'."); - } - ok = false; - } - return laneIndex; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/NIXMLTrafficLightsHandler.h b/Util/OSM2ODR/src/netimport/NIXMLTrafficLightsHandler.h deleted file mode 100644 index 022b1a017..000000000 --- a/Util/OSM2ODR/src/netimport/NIXMLTrafficLightsHandler.h +++ /dev/null @@ -1,127 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIXMLTrafficLightsHandler.h -/// @author Jakob Erdmann -/// @date 2011-10-05 -/// -// Importer for traffic lights stored in XML -/****************************************************************************/ -#pragma once -#include - -#include -#include - - -// =========================================================================== -// class declarations -// =========================================================================== -class NBEdge; -class NBEdgeCont; -class MsgHandler; -class NBLoadedSUMOTLDef; -class NBTrafficLightLogicCont; - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NIXMLTrafficLightsHandler - * @brief Importer for edge connections stored in XML - * - * This importer parses connections, and prohibitions, and is able - * to reset connections between edges. - */ -class NIXMLTrafficLightsHandler : public SUMOSAXHandler { -public: - /** @brief Constructor - * @param[in] ec The traffic light container into which to load logics - */ - NIXMLTrafficLightsHandler(NBTrafficLightLogicCont& tlCont, NBEdgeCont& ec, bool ignoreUnknown = false); - - - /// @brief Destructor - ~NIXMLTrafficLightsHandler(); - - -protected: - /// @name inherited from GenericSAXHandler - //@{ - - /** @brief Called on the opening of a tag; - * - * @param[in] element ID of the currently opened element - * @param[in] attrs Attributes within the currently opened element - * @exception ProcessError If something fails - * @see GenericSAXHandler::myStartElement - */ - void myStartElement(int element, const SUMOSAXAttributes& attrs); - - - /** @brief Called when a closing tag occurs - * - * @param[in] element ID of the currently opened element - * @exception ProcessError If something fails - * @see GenericSAXHandler::myEndElement - */ - void myEndElement(int element); - //@} - - - -private: - /// @brief The traffic light container to fill - NBTrafficLightLogicCont& myTLLCont; - - /// @brief The edge container for retrieving edges - NBEdgeCont& myEdgeCont; - - /// @brief The currently parsed traffic light - NBLoadedSUMOTLDef* myCurrentTL; - - /// @brief whether phases of a previously loaded traffic light must be reset - bool myResetPhases; - - /** begins the reading of a traffic lights logic - * This differs from NIImporter_SUMO::initTrafficLightLogic insofar as - * partial definitions (diffs) are allowed in an xml file - */ - NBLoadedSUMOTLDef* initTrafficLightLogic(const SUMOSAXAttributes& attrs, NBLoadedSUMOTLDef* currentTL); - - /// @brief reads and adds tl-controlled connection - void addTlConnection(const SUMOSAXAttributes& attrs); - - /// @brief reads and removes tl-controlled connection - void removeTlConnection(const SUMOSAXAttributes& attrs); - - /// parses and edge id an returns an existing edge - NBEdge* retrieveEdge(const SUMOSAXAttributes& attrs, SumoXMLAttr attr, bool& ok); - - /// parses a lane index and verifies its correctness - int retrieveLaneIndex(const SUMOSAXAttributes& attrs, SumoXMLAttr attr, NBEdge* edge, bool& ok, bool isDelete = false); - - /// @brief whether definitions for unknown traffic lights shall be silently ignored - bool myIgnoreUnknown; - - -private: - /// @brief invalidated copy constructor - NIXMLTrafficLightsHandler(const NIXMLTrafficLightsHandler& s); - - /// @brief invalidated assignment operator - NIXMLTrafficLightsHandler& operator=(const NIXMLTrafficLightsHandler& s); - - -}; diff --git a/Util/OSM2ODR/src/netimport/NIXMLTypesHandler.cpp b/Util/OSM2ODR/src/netimport/NIXMLTypesHandler.cpp deleted file mode 100644 index 04daf6198..000000000 --- a/Util/OSM2ODR/src/netimport/NIXMLTypesHandler.cpp +++ /dev/null @@ -1,114 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIXMLTypesHandler.cpp -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @author Walter Bamberger -/// @date Tue, 20 Nov 2001 -/// -// Importer for edge type information stored in XML -/****************************************************************************/ -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "NIXMLTypesHandler.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -NIXMLTypesHandler::NIXMLTypesHandler(NBTypeCont& tc) - : SUMOSAXHandler("xml-types - file"), - myTypeCont(tc) {} - - -NIXMLTypesHandler::~NIXMLTypesHandler() {} - - -void -NIXMLTypesHandler::myStartElement(int element, - const SUMOSAXAttributes& attrs) { - switch (element) { - case SUMO_TAG_TYPE: { - bool ok = true; - // get the id, report a warning if not given or empty... - myCurrentTypeID = attrs.get(SUMO_ATTR_ID, nullptr, ok); - const char* const id = myCurrentTypeID.c_str(); - const std::string defType = myTypeCont.knows(myCurrentTypeID) ? myCurrentTypeID : ""; - const int priority = attrs.getOpt(SUMO_ATTR_PRIORITY, id, ok, myTypeCont.getPriority(defType)); - const int numLanes = attrs.getOpt(SUMO_ATTR_NUMLANES, id, ok, myTypeCont.getNumLanes(defType)); - const double speed = attrs.getOpt(SUMO_ATTR_SPEED, id, ok, myTypeCont.getSpeed(defType)); - const std::string allowS = attrs.getOpt(SUMO_ATTR_ALLOW, id, ok, ""); - const std::string disallowS = attrs.getOpt(SUMO_ATTR_DISALLOW, id, ok, ""); - const bool oneway = attrs.getOpt(SUMO_ATTR_ONEWAY, id, ok, myTypeCont.getIsOneWay(defType)); - const bool discard = attrs.getOpt(SUMO_ATTR_DISCARD, id, ok, false); - const double width = attrs.getOpt(SUMO_ATTR_WIDTH, id, ok, myTypeCont.getWidth(defType)); - const double maxWidth = attrs.getOpt(SUMO_ATTR_MAXWIDTH, id, ok, myTypeCont.getMaxWidth(defType)); - const double minWidth = attrs.getOpt(SUMO_ATTR_MINWIDTH, id, ok, myTypeCont.getMinWidth(defType)); - const double widthResolution = attrs.getOpt(SUMO_ATTR_WIDTHRESOLUTION, id, ok, myTypeCont.getWidthResolution(defType)); - const double sidewalkWidth = attrs.getOpt(SUMO_ATTR_SIDEWALKWIDTH, id, ok, myTypeCont.getSidewalkWidth(defType)); - const double bikeLaneWidth = attrs.getOpt(SUMO_ATTR_BIKELANEWIDTH, id, ok, myTypeCont.getBikeLaneWidth(defType)); - if (!ok) { - return; - } - // build the type - SVCPermissions permissions = myTypeCont.getPermissions(defType); - if (allowS != "" || disallowS != "") { - permissions = parseVehicleClasses(allowS, disallowS); - } - myTypeCont.insert(myCurrentTypeID, numLanes, speed, priority, permissions, width, oneway, sidewalkWidth, bikeLaneWidth, widthResolution, maxWidth, minWidth); - if (discard) { - myTypeCont.markAsToDiscard(myCurrentTypeID); - } - SumoXMLAttr myAttrs[] = {SUMO_ATTR_PRIORITY, SUMO_ATTR_NUMLANES, SUMO_ATTR_SPEED, - SUMO_ATTR_ALLOW, SUMO_ATTR_DISALLOW, SUMO_ATTR_ONEWAY, - SUMO_ATTR_DISCARD, SUMO_ATTR_WIDTH, SUMO_ATTR_SIDEWALKWIDTH, SUMO_ATTR_BIKELANEWIDTH - }; - for (int i = 0; i < 10; i++) { - if (attrs.hasAttribute(myAttrs[i])) { - myTypeCont.markAsSet(myCurrentTypeID, myAttrs[i]); - } - } - break; - } - case SUMO_TAG_RESTRICTION: { - bool ok = true; - const SUMOVehicleClass svc = getVehicleClassID(attrs.get(SUMO_ATTR_VCLASS, myCurrentTypeID.c_str(), ok)); - const double speed = attrs.get(SUMO_ATTR_SPEED, myCurrentTypeID.c_str(), ok); - if (ok) { - myTypeCont.addRestriction(myCurrentTypeID, svc, speed); - } - break; - } - default: - break; - } -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/NIXMLTypesHandler.h b/Util/OSM2ODR/src/netimport/NIXMLTypesHandler.h deleted file mode 100644 index 522ca85af..000000000 --- a/Util/OSM2ODR/src/netimport/NIXMLTypesHandler.h +++ /dev/null @@ -1,90 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIXMLTypesHandler.h -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date Tue, 20 Nov 2001 -/// -// Importer for edge type information stored in XML -/****************************************************************************/ -#pragma once -#include - -#include - - -// =========================================================================== -// class declarations -// =========================================================================== -class NBTypeCont; - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NIXMLTypesHandler - * @brief Importer for edge type information stored in XML - * - * This SAX-handler parses edge type information and stores it in the given - * container. - */ -class NIXMLTypesHandler : public SUMOSAXHandler { -public: - /** @brief Constructor - * - * @param[in, filled] tc The type container to fill - */ - NIXMLTypesHandler(NBTypeCont& tc); - - /// @brief Destructor - ~NIXMLTypesHandler(); - - /// @name inherited from GenericSAXHandler - //@{ - - /** @brief Called on the opening of a tag; Parses edge type information - * - * Tries to parse a type. If the type can be parsed, it is stored within - * "myTypeCont". Otherwise an error is generated. No exception is thrown - * so that the parsing continues and further errors can be reported. - * - * @param[in] element ID of the currently opened element - * @param[in] attrs Attributes within the currently opened element - * @exception ProcessError If something fails (not used herein) - * @note policy is to throw no exception in order to allow further processing - */ - void myStartElement(int element, - const SUMOSAXAttributes& attrs); - //@} - - -private: - /// @brief The type container to fill - NBTypeCont& myTypeCont; - - /// @brief The currently parsed type - std::string myCurrentTypeID; - - -private: - /** @brief invalid copy constructor */ - NIXMLTypesHandler(const NIXMLTypesHandler& s); - - /** @brief invalid assignment operator */ - NIXMLTypesHandler& operator=(const NIXMLTypesHandler& s); - - -}; diff --git a/Util/OSM2ODR/src/netimport/README_Contributing.md b/Util/OSM2ODR/src/netimport/README_Contributing.md deleted file mode 100644 index 4c8e4308b..000000000 --- a/Util/OSM2ODR/src/netimport/README_Contributing.md +++ /dev/null @@ -1,43 +0,0 @@ -Please feel free to add and / or modify files here but keep in mind that -EPL requires that "derivative works" be licensed under the terms of the EPL. -If the extension is a separate module and is not published under the EPL -it will not be adopted in the SUMO mainline repository. - -Modifications to the files and directories listed here are considered _derivative work_: - -- NIFrame.cpp -- NIFrame.h -- NIImporter_ArcView.cpp -- NIImporter_ArcView.h -- NIImporter_DlrNavteq.cpp -- NIImporter_DlrNavteq.h -- NIImporter_ITSUMO.cpp -- NIImporter_ITSUMO.h -- NIImporter_MATSim.cpp -- NIImporter_MATSim.h -- NIImporter_OpenDrive.cpp -- NIImporter_OpenDrive.h -- NIImporter_OpenStreetMap.cpp -- NIImporter_OpenStreetMap.h -- NIImporter_RobocupRescue.cpp -- NIImporter_RobocupRescue.h -- NIImporter_SUMO.cpp -- NIImporter_SUMO.h -- NIImporter_VISUM.cpp -- NIImporter_VISUM.h -- NILoader.cpp -- NILoader.h -- NINavTeqHelper.cpp -- NINavTeqHelper.h -- NIVisumTL.cpp -- NIVisumTL.h -- NIXMLConnectionsHandler.cpp -- NIXMLConnectionsHandler.h -- NIXMLEdgesHandler.cpp -- NIXMLEdgesHandler.h -- NIXMLNodesHandler.cpp -- NIXMLNodesHandler.h -- NIXMLTrafficLightsHandler.cpp -- NIXMLTrafficLightsHandler.h -- NIXMLTypesHandler.cpp -- NIXMLTypesHandler.h diff --git a/Util/OSM2ODR/src/netimport/_netimport.dox b/Util/OSM2ODR/src/netimport/_netimport.dox deleted file mode 100644 index 46f41871c..000000000 --- a/Util/OSM2ODR/src/netimport/_netimport.dox +++ /dev/null @@ -1,14 +0,0 @@ -/** - @file _netimport.dox - @defgoup netimport Network Importing Module - @brief reads different network formats and stores them in netbuild-classes - - @addtogroup netimport - @{ - netimport holds classes and methods for reading road networks from different formats. The read data - is stored in according classes from the @ref netbuild module. - - - - @} -*/ \ No newline at end of file diff --git a/Util/OSM2ODR/src/netimport/typemap.h b/Util/OSM2ODR/src/netimport/typemap.h deleted file mode 100644 index 2e78e8593..000000000 --- a/Util/OSM2ODR/src/netimport/typemap.h +++ /dev/null @@ -1,79 +0,0 @@ -const std::string opendriveTypemap = -"\n" -" \n" -" \n" -" \n" -" \n" -" \n" -" \n" -" \n" -" \n" -" \n" -" \n" -" \n" -"\n" -" \n" -" \n" -"\n" -" \n" -" \n" -" \n" -" \n" -" \n" -" \n" -" \n" -" \n" -"\n" -" \n" -" \n" -" \n" -"\n" -" \n" -" \n" -"\n" -; -const std::string osmTypemap = -"\n" -" \n" -" \n" -" \n" -" \n" -" \n" -" \n" -" \n" -" \n" -" \n" -" \n" -" \n" -" \n" -" \n" -" \n" -" \n" -"\n" -" \n" -" \n" -" \n" -" \n" -" \n" -" \n" -" \n" -" \n" -" \n" -" \n" -"\n" -" \n" -" \n" -" \n" -"\n" -" \n" -" \n" -" \n" -" \n" -" \n" -" \n" -"\n" -"\n" -; diff --git a/Util/OSM2ODR/src/netimport/vissim/CMakeLists.txt b/Util/OSM2ODR/src/netimport/vissim/CMakeLists.txt deleted file mode 100644 index c4ec60b0a..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/CMakeLists.txt +++ /dev/null @@ -1,11 +0,0 @@ -add_subdirectory(tempstructs) -add_subdirectory(typeloader) - -set(netimport_vissim_STAT_SRCS - NIImporter_Vissim.cpp - NIImporter_Vissim.h - NIVissimElements.h -) - -add_library(netimport_vissim STATIC ${netimport_vissim_STAT_SRCS}) -set_property(TARGET netimport_vissim PROPERTY PROJECT_LABEL "z_netimport_vissim") diff --git a/Util/OSM2ODR/src/netimport/vissim/NIImporter_Vissim.cpp b/Util/OSM2ODR/src/netimport/vissim/NIImporter_Vissim.cpp deleted file mode 100644 index 12dbc1715..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/NIImporter_Vissim.cpp +++ /dev/null @@ -1,1265 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIImporter_Vissim.cpp -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @author Lukas Grohmann (AIT) -/// @author Gerald Richter (AIT) -/// @date Sept 2002 -/// -// ------------------- -/****************************************************************************/ -#include - - -#include -#include -#include -#include -#include -#include -#include -#include "NIImporter_Vissim.h" -#include "typeloader/NIVissimSingleTypeParser_Simdauer.h" -#include "typeloader/NIVissimSingleTypeParser_Startuhrzeit.h" -#include "typeloader/NIVissimSingleTypeParser_DynUml.h" -#include "typeloader/NIVissimSingleTypeParser_Streckendefinition.h" -#include "typeloader/NIVissimSingleTypeParser_Verbindungsdefinition.h" -#include "typeloader/NIVissimSingleTypeParser_Richtungsentscheidungsdefinition.h" -#include "typeloader/NIVissimSingleTypeParser_Routenentscheidungsdefinition.h" -#include "typeloader/NIVissimSingleTypeParser_VWunschentscheidungsdefinition.h" -#include "typeloader/NIVissimSingleTypeParser_Langsamfahrbereichdefinition.h" -#include "typeloader/NIVissimSingleTypeParser_Zuflussdefinition.h" -#include "typeloader/NIVissimSingleTypeParser_Fahrzeugtypdefinition.h" -#include "typeloader/NIVissimSingleTypeParser_Fahrzeugklassendefinition.h" -#include "typeloader/NIVissimSingleTypeParser_Verkehrszusammensetzungsdefinition.h" -#include "typeloader/NIVissimSingleTypeParser_Geschwindigkeitsverteilungsdefinition.h" -#include "typeloader/NIVissimSingleTypeParser_Laengenverteilungsdefinition.h" -#include "typeloader/NIVissimSingleTypeParser_Zeitenverteilungsdefinition.h" -#include "typeloader/NIVissimSingleTypeParser_Querverkehrsstoerungsdefinition.h" -#include "typeloader/NIVissimSingleTypeParser_Lichtsignalanlagendefinition.h" -#include "typeloader/NIVissimSingleTypeParser_Signalgruppendefinition.h" -#include "typeloader/NIVissimSingleTypeParser_Stopschilddefinition.h" -#include "typeloader/NIVissimSingleTypeParser_Knotendefinition.h" -#include "typeloader/NIVissimSingleTypeParser_Signalgeberdefinition.h" -#include "typeloader/NIVissimSingleTypeParser_Detektordefinition.h" -#include "typeloader/NIVissimSingleTypeParser_Liniendefinition.h" -#include "typeloader/NIVissimSingleTypeParser_Haltestellendefinition.h" -#include "typeloader/NIVissimSingleTypeParser_Reisezeitmessungsdefinition.h" -#include "typeloader/NIVissimSingleTypeParser_Querschnittsmessungsdefinition.h" -#include "typeloader/NIVissimSingleTypeParser_Messungsdefinition.h" -#include "typeloader/NIVissimSingleTypeParser_Verlustzeitmessungsdefinition.h" -#include "typeloader/NIVissimSingleTypeParser_Stauzaehlerdefinition.h" -#include "typeloader/NIVissimSingleTypeParser_Richtungspfeildefinition.h" -#include "typeloader/NIVissimSingleTypeParser_Parkplatzdefinition.h" -#include "typeloader/NIVissimSingleTypeParser_Fahrverhaltendefinition.h" -#include "typeloader/NIVissimSingleTypeParser_Streckentypdefinition.h" -#include "typeloader/NIVissimSingleTypeParser_Kennungszeile.h" -#include "typeloader/NIVissimSingleTypeParser_Fensterdefinition.h" -#include "typeloader/NIVissimSingleTypeParser_Auswertungsdefinition.h" -#include "typeloader/NIVissimSingleTypeParser_Zusammensetzungsdefinition.h" -#include "typeloader/NIVissimSingleTypeParser_Startzufallszahl.h" -#include "typeloader/NIVissimSingleTypeParser_SimRate.h" -#include "typeloader/NIVissimSingleTypeParser_Zeitschrittfaktor.h" -#include "typeloader/NIVissimSingleTypeParser_Linksverkehr.h" -#include "typeloader/NIVissimSingleTypeParser_Stauparameterdefinition.h" -#include "typeloader/NIVissimSingleTypeParser_Gelbverhaltendefinition.h" -#include "typeloader/NIVissimSingleTypeParser_LSAKopplungsdefinition.h" -#include "typeloader/NIVissimSingleTypeParser_Gefahrwarnungsdefinition.h" -#include "typeloader/NIVissimSingleTypeParser_TEAPACDefinition.h" -#include "typeloader/NIVissimSingleTypeParser_Netzobjektdefinition.h" -#include "typeloader/NIVissimSingleTypeParser_Fahrtverlaufdateien.h" -#include "typeloader/NIVissimSingleTypeParser_Emission.h" -#include "typeloader/NIVissimSingleTypeParser_Einheitendefinition.h" -#include "typeloader/NIVissimSingleTypeParser__XVerteilungsdefinition.h" -#include "typeloader/NIVissimSingleTypeParser__XKurvedefinition.h" -#include "typeloader/NIVissimSingleTypeParser_Kantensperrung.h" -#include "typeloader/NIVissimSingleTypeParser_Rautedefinition.h" - - -#include "tempstructs/NIVissimTL.h" -#include "tempstructs/NIVissimClosures.h" -#include "tempstructs/NIVissimSource.h" -#include "tempstructs/NIVissimTrafficDescription.h" -#include "tempstructs/NIVissimVehTypeClass.h" -#include "tempstructs/NIVissimConnection.h" -#include "tempstructs/NIVissimDisturbance.h" -#include "tempstructs/NIVissimConnectionCluster.h" -#include "tempstructs/NIVissimNodeDef.h" -#include "tempstructs/NIVissimEdge.h" -#include "tempstructs/NIVissimConflictArea.h" -#include "tempstructs/NIVissimDistrictConnection.h" -#include "tempstructs/NIVissimVehicleType.h" - -#include -#include -#include -#include -#include -#include - -#include // !!! only for debugging purposes - - -// =========================================================================== -// static variables -// =========================================================================== -StringBijection::Entry NIImporter_Vissim::vissimTags[] = { - { "network", NIImporter_Vissim::VISSIM_TAG_NETWORK }, - { "lanes", NIImporter_Vissim::VISSIM_TAG_LANES }, - { "lane", NIImporter_Vissim::VISSIM_TAG_LANE }, - { "link", NIImporter_Vissim::VISSIM_TAG_LINK }, - { "links", NIImporter_Vissim::VISSIM_TAG_LINKS }, - { "points3D", NIImporter_Vissim::VISSIM_TAG_POINTS3D }, - { "point3D", NIImporter_Vissim::VISSIM_TAG_POINT3D }, - { "linkPolyPoint", NIImporter_Vissim::VISSIM_TAG_LINKPOLYPOINT }, - { "linkPolyPts", NIImporter_Vissim::VISSIM_TAG_LINKPOLYPTS }, - { "fromLinkEndPt", NIImporter_Vissim::VISSIM_TAG_FROM }, - { "toLinkEndPt", NIImporter_Vissim::VISSIM_TAG_TO }, - { "vehicleInput", NIImporter_Vissim::VISSIM_TAG_VEHICLE_INPUT }, - { "parkingLot", NIImporter_Vissim::VISSIM_TAG_PARKINGLOT }, - { "vehicleClass", NIImporter_Vissim::VISSIM_TAG_VEHICLE_CLASS }, - { "intObjectRef", NIImporter_Vissim::VISSIM_TAG_INTOBJECTREF }, - { "desSpeedDecision", NIImporter_Vissim::VISSIM_TAG_SPEED_DECISION }, - { - "desSpeedDistribution", - NIImporter_Vissim::VISSIM_TAG_SPEED_DIST - }, - { - "speedDistributionDataPoint", - NIImporter_Vissim::VISSIM_TAG_DATAPOINT - }, - { - "vehicleRoutingDecisionStatic", - NIImporter_Vissim::VISSIM_TAG_DECISION_STATIC - }, - { - "vehicleRouteStatic", - NIImporter_Vissim::VISSIM_TAG_ROUTE_STATIC - }, - { "conflictArea", NIImporter_Vissim::VISSIM_TAG_CA }, - { "", NIImporter_Vissim::VISSIM_TAG_NOTHING } -}; - - -StringBijection::Entry NIImporter_Vissim::vissimAttrs[] = { - { "no", NIImporter_Vissim::VISSIM_ATTR_NO }, //id - { "name", NIImporter_Vissim::VISSIM_ATTR_NAME }, - { "x", NIImporter_Vissim::VISSIM_ATTR_X }, - { "y", NIImporter_Vissim::VISSIM_ATTR_Y }, - { "zOffset", NIImporter_Vissim::VISSIM_ATTR_ZOFFSET }, - { "surch1", NIImporter_Vissim::VISSIM_ATTR_ZUSCHLAG1 }, - { "surch2", NIImporter_Vissim::VISSIM_ATTR_ZUSCHLAG2 }, - { "width", NIImporter_Vissim::VISSIM_ATTR_WIDTH }, - { "linkBehavType", NIImporter_Vissim::VISSIM_ATTR_LINKBEHAVETYPE}, - { "lane", NIImporter_Vissim::VISSIM_ATTR_LANE }, - { "pos", NIImporter_Vissim::VISSIM_ATTR_POS }, - { "link", NIImporter_Vissim::VISSIM_ATTR_LINK }, - { "intLink", NIImporter_Vissim::VISSIM_ATTR_INTLINK }, //edgeID - { "relFlow", NIImporter_Vissim::VISSIM_ATTR_PERCENTAGE }, - { "zone", NIImporter_Vissim::VISSIM_ATTR_DISTRICT }, - { "color", NIImporter_Vissim::VISSIM_ATTR_COLOR }, - { "key", NIImporter_Vissim::VISSIM_ATTR_KEY }, - { "fx", NIImporter_Vissim::VISSIM_ATTR_FX }, - { "destLink", NIImporter_Vissim::VISSIM_ATTR_DESTLINK }, - { "destPos", NIImporter_Vissim::VISSIM_ATTR_DESTPOS }, - { "link1", NIImporter_Vissim::VISSIM_ATTR_LINK1 }, - { "link2", NIImporter_Vissim::VISSIM_ATTR_LINK2 }, - { "status", NIImporter_Vissim::VISSIM_ATTR_STATUS }, - { "", NIImporter_Vissim::VISSIM_ATTR_NOTHING } -}; - - -// =========================================================================== -// method definitions -// =========================================================================== -// --------------------------------------------------------------------------- -// static methods (interface in this case) -// --------------------------------------------------------------------------- -void -NIImporter_Vissim::loadNetwork(const OptionsCont& oc, NBNetBuilder& nb) { - if (!oc.isSet("vissim-file")) { - return; - } - NIImporter_Vissim(nb).load(oc); -} - - -// --------------------------------------------------------------------------- -// definitions of NIVissimXMLHandler_Streckendefinition-methods -// --------------------------------------------------------------------------- -NIImporter_Vissim::NIVissimXMLHandler_Streckendefinition::NIVissimXMLHandler_Streckendefinition( - //std::map& toFill) - nodeMap& elemData) - : GenericSAXHandler(vissimTags, VISSIM_TAG_NOTHING, - vissimAttrs, VISSIM_ATTR_NOTHING, - "vissim - file"), - myElemData(elemData), - myHierarchyLevel(0), - isConnector(false) { - myElemData.clear(); -} - -NIImporter_Vissim::NIVissimXMLHandler_Streckendefinition::~NIVissimXMLHandler_Streckendefinition() { } - -void -NIImporter_Vissim::NIVissimXMLHandler_Streckendefinition::myStartElement(int element, const SUMOSAXAttributes& attrs) { - myHierarchyLevel++; - - // finding an actual LINK - if (element == VISSIM_TAG_LINK) { - //parse all links - bool ok = true; - int id = attrs.get(VISSIM_ATTR_NO, nullptr, ok); - myLastNodeID = id; - - // !!! assuming empty myElemData - myElemData["id"].push_back(attrs.get(VISSIM_ATTR_NO, nullptr, ok)); - // error ignored if name is empty - myElemData["name"].push_back(attrs.get(VISSIM_ATTR_NAME, nullptr, ok, false)); - myElemData["type"].push_back(attrs.get(VISSIM_ATTR_LINKBEHAVETYPE, nullptr, ok)); - myElemData["zuschlag1"].push_back(attrs.get(VISSIM_ATTR_ZUSCHLAG1, nullptr, ok)); - myElemData["zuschlag2"].push_back(attrs.get(VISSIM_ATTR_ZUSCHLAG2, nullptr, ok)); - } - - if (element == VISSIM_TAG_LANE) { - bool ok = true; - // appends empty element if no width found - // error ignored if name is empty - myElemData["width"].push_back(attrs.get(VISSIM_ATTR_WIDTH, nullptr, ok, false)); - } - - if (element == VISSIM_TAG_FROM) { - if (isConnector != true) { - isConnector = true; - } - bool ok = true; - std::vector from(StringTokenizer(attrs.get( - VISSIM_ATTR_LANE, nullptr, ok), " ").getVector()); - myElemData["from_pos"].push_back(attrs.get(VISSIM_ATTR_POS, nullptr, ok)); - myElemData["from_id"].push_back(from[0]); - myElemData["from_lane"].push_back(from[1]); - } - - if (element == VISSIM_TAG_TO) { - bool ok = true; - std::vector to(StringTokenizer(attrs.get( - VISSIM_ATTR_LANE, nullptr, ok), " ").getVector()); - myElemData["to_pos"].push_back(attrs.get(VISSIM_ATTR_POS, nullptr, ok)); - myElemData["to_id"].push_back(to[0]); - myElemData["to_lane"].push_back(to[1]); - } - - if (element == VISSIM_TAG_POINT3D || element == VISSIM_TAG_LINKPOLYPOINT) { - bool ok = true; - // create a separated string of coordinate data - std::string sep(" "); - - std::string posS(attrs.get(VISSIM_ATTR_X, nullptr, ok)); - posS += sep; - posS.append(attrs.get(VISSIM_ATTR_Y, nullptr, ok)); - // allow for no Z - std::string z(attrs.get(VISSIM_ATTR_ZOFFSET, nullptr, ok, false)); - if (z.length() > 0) { - posS += sep; - posS.append(z); - } - myElemData["pos"].push_back(posS); - } - - -} - -void -NIImporter_Vissim::NIVissimXMLHandler_Streckendefinition::myEndElement(int element) { - if (element == VISSIM_TAG_LINK && myHierarchyLevel == 3) { - //std::cout << "elemData len:" << myElemData.size() << std::endl; - - NIVissimClosedLanesVector clv; //FIXME -> clv einlesen - std::vector assignedVehicles; //FIXME -> assignedVehicles einlesen - int id(StringUtils::toInt(myElemData["id"].front())); - - PositionVector geom; - // convert all position coordinate strings to PositionVectors - while (!myElemData["pos"].empty()) { - std::vector sPos_v(StringTokenizer( - myElemData["pos"].front(), " ").getVector()); - myElemData["pos"].pop_front(); - std::vector pos_v(3); - - // doing a transform with explicit hint on function signature - std::transform(sPos_v.begin(), sPos_v.end(), pos_v.begin(), - StringUtils::toDouble); - geom.push_back_noDoublePos(Position(pos_v[0], pos_v[1], pos_v[2])); - } - // FIXME: a length = 0 PosVec seems fatal -> segfault - double length(geom.length()); - - if (isConnector == false) { - // Add Edge - std::vector laneWidths; - for (std::string& w : myElemData["width"]) { - laneWidths.push_back(StringUtils::toDouble(w)); - } - NIVissimEdge* edge = new NIVissimEdge(id, - myElemData["name"].front(), - myElemData["type"].front(), - laneWidths, - StringUtils::toDouble(myElemData["zuschlag1"].front()), - StringUtils::toDouble(myElemData["zuschlag2"].front()), - length, geom, clv); - NIVissimEdge::dictionary(id, edge); - } else { - int numLanes = (int)myElemData["width"].size(); - std::vector laneVec(numLanes); - // Add Connector - - //NOTE: there should be only 1 lane number in XML - // subtraction of 1 as in readExtEdgePointDef() - laneVec[0] = StringUtils::toInt(myElemData["from_lane"].front()) - 1; - // then count up, building lane number vector - for (std::vector::iterator each = ++laneVec.begin(); each != laneVec.end(); ++each) { - *each = *(each - 1) + 1; - } - - NIVissimExtendedEdgePoint from_def( - StringUtils::toInt(myElemData["from_id"].front()), - laneVec, - StringUtils::toDouble(myElemData["from_pos"].front()), - assignedVehicles); - - //NOTE: there should be only 1 lane number in XML - // subtraction of 1 as in readExtEdgePointDef() - laneVec[0] = StringUtils::toInt(myElemData["to_lane"].front()) - 1; - // then count up, building lane number vector - for (std::vector::iterator each = ++laneVec.begin(); each != laneVec.end(); ++each) { - *each = *(each - 1) + 1; - } - - NIVissimExtendedEdgePoint to_def( - StringUtils::toInt(myElemData["to_id"].front()), - laneVec, - StringUtils::toDouble(myElemData["to_pos"].front()), - assignedVehicles); - - NIVissimConnection* connector = new - NIVissimConnection(id, - myElemData["name"].front(), - from_def, to_def, - geom, assignedVehicles, clv); - - NIVissimConnection::dictionary(id, connector); - } - // clear the element data - myElemData.clear(); - isConnector = false; - //std::cout << "elemData len (clear):" << myElemData.size() << std::endl; - //std::cout.flush(); - - } - --myHierarchyLevel; -} - - -// --------------------------------------------------------------------------- -// definitions of NIVissimXMLHandler_Zuflussdefinition-methods -// --------------------------------------------------------------------------- -NIImporter_Vissim::NIVissimXMLHandler_Zuflussdefinition::NIVissimXMLHandler_Zuflussdefinition() - : GenericSAXHandler(vissimTags, VISSIM_TAG_NOTHING, - vissimAttrs, VISSIM_ATTR_NOTHING, - "vissim - file") { -} - -NIImporter_Vissim::NIVissimXMLHandler_Zuflussdefinition::~NIVissimXMLHandler_Zuflussdefinition() { } - -void -NIImporter_Vissim::NIVissimXMLHandler_Zuflussdefinition::myStartElement(int element, const SUMOSAXAttributes& attrs) { - // finding an actual flow - if (element == VISSIM_TAG_VEHICLE_INPUT) { - //parse all flows - bool ok = true; - std::string id = attrs.get(VISSIM_ATTR_NO, nullptr, ok); - std::string edgeid = attrs.get(VISSIM_ATTR_LINK, nullptr, ok); - std::string name = attrs.get(VISSIM_ATTR_NAME, nullptr, ok, false); - - NIVissimSource::dictionary(id, - name, - edgeid); - } -} - -// --------------------------------------------------------------------------- -// definitions of NIVissimXMLHandler_Parkplatzdefinition-methods -// --------------------------------------------------------------------------- -NIImporter_Vissim::NIVissimXMLHandler_Parkplatzdefinition::NIVissimXMLHandler_Parkplatzdefinition() - : GenericSAXHandler(vissimTags, VISSIM_TAG_NOTHING, - vissimAttrs, VISSIM_ATTR_NOTHING, - "vissim - file") { -} - -NIImporter_Vissim::NIVissimXMLHandler_Parkplatzdefinition::~NIVissimXMLHandler_Parkplatzdefinition() { } - -void -NIImporter_Vissim::NIVissimXMLHandler_Parkplatzdefinition::myStartElement(int element, const SUMOSAXAttributes& attrs) { - // finding an actual parkinglot - if (element == VISSIM_TAG_PARKINGLOT) { - //parse all parkinglots - bool ok = true; - int id = attrs.get(VISSIM_ATTR_NO, nullptr, ok); - int edgeid = attrs.get(VISSIM_ATTR_INTLINK, nullptr, ok); - std::string name = attrs.get(VISSIM_ATTR_NAME, nullptr, ok, false); - double position = attrs.get(VISSIM_ATTR_POS, nullptr, ok); - std::vector > assignedVehicles; // (vclass, vwunsch) - //FIXME: vWunsch + Fahzeugklassen einlesen - // There can be s - std::vector districts; - //FIXME: Parkplatzdefinition für mehrere Zonen implementieren - std::vector percentages; - districts.push_back(attrs.get(VISSIM_ATTR_DISTRICT, nullptr, ok)); - percentages.push_back(attrs.get(VISSIM_ATTR_PERCENTAGE, nullptr, ok)); - - NIVissimDistrictConnection::dictionary(id, - name, - districts, - percentages, - edgeid, - position, - assignedVehicles); - } -} - - -// --------------------------------------------------------------------------- -// definitions of NIVissimXMLHandler_Fahrzeugklassendefinition-methods -// --------------------------------------------------------------------------- -NIImporter_Vissim::NIVissimXMLHandler_Fahrzeugklassendefinition::NIVissimXMLHandler_Fahrzeugklassendefinition(nodeMap& elemData) - : GenericSAXHandler(vissimTags, VISSIM_TAG_NOTHING, - vissimAttrs, VISSIM_ATTR_NOTHING, - "vissim - file"), - myElemData(elemData), - myHierarchyLevel(0) { - myElemData.clear(); -} - -NIImporter_Vissim::NIVissimXMLHandler_Fahrzeugklassendefinition::~NIVissimXMLHandler_Fahrzeugklassendefinition() { } - -void -NIImporter_Vissim::NIVissimXMLHandler_Fahrzeugklassendefinition::myStartElement(int element, const SUMOSAXAttributes& attrs) { - myHierarchyLevel++; - - if (element == VISSIM_TAG_VEHICLE_CLASS) { - bool ok = true; - myElemData["id"].push_back(attrs.get(VISSIM_ATTR_NO, nullptr, ok)); - myElemData["name"].push_back(attrs.get(VISSIM_ATTR_NAME, nullptr, ok, false)); - std::string colorStr(attrs.get(VISSIM_ATTR_COLOR, nullptr, ok)); - for (int pos = (int)colorStr.size() - 2; pos > 0; pos -= 2) { - colorStr.insert(pos, " "); - } - myElemData["color"].push_back(colorStr); - } - if (element == VISSIM_TAG_INTOBJECTREF) { - bool ok = true; - myElemData["types"].push_back(attrs.get(VISSIM_ATTR_KEY, nullptr, ok)); - - - } -} - -void -NIImporter_Vissim::NIVissimXMLHandler_Fahrzeugklassendefinition::myEndElement(int element) { - if (element == VISSIM_TAG_VEHICLE_CLASS && myHierarchyLevel == 3) { - RGBColor color; - std::istringstream iss(myElemData["color"].front()); - std::vector sCol_v(StringTokenizer( - myElemData["color"].front(), " ").getVector()); - std::vector myColorVector(sCol_v.size()); - std::transform(sCol_v.begin(), sCol_v.end(), myColorVector.begin(), StringUtils::hexToInt); - - color = RGBColor((unsigned char)myColorVector[0], - (unsigned char)myColorVector[1], - (unsigned char)myColorVector[2], - (unsigned char)myColorVector[3]); - std::vector types; - while (!myElemData["types"].empty()) { - types.push_back(StringUtils::toInt(myElemData["types"].front())); - myElemData["types"].pop_front(); - } - - NIVissimVehTypeClass::dictionary(StringUtils::toInt(myElemData["id"].front()), - myElemData["name"].front(), - color, - types); - myElemData.clear(); - } - --myHierarchyLevel; -} - -// --------------------------------------------------------------------------- -// definitions of NIVissimXMLHandler_Geschwindigkeitsverteilungsdefinition-methods -// --------------------------------------------------------------------------- -NIImporter_Vissim::NIVissimXMLHandler_Geschwindigkeitsverteilungsdefinition::NIVissimXMLHandler_Geschwindigkeitsverteilungsdefinition(nodeMap& elemData) - : GenericSAXHandler(vissimTags, VISSIM_TAG_NOTHING, - vissimAttrs, VISSIM_ATTR_NOTHING, - "vissim - file"), - myElemData(elemData), - myHierarchyLevel(0) { - myElemData.clear(); -} - -NIImporter_Vissim::NIVissimXMLHandler_Geschwindigkeitsverteilungsdefinition::~NIVissimXMLHandler_Geschwindigkeitsverteilungsdefinition() { } - -void -NIImporter_Vissim::NIVissimXMLHandler_Geschwindigkeitsverteilungsdefinition::myStartElement(int element, const SUMOSAXAttributes& attrs) { - myHierarchyLevel++; - if (element == VISSIM_TAG_SPEED_DIST) { - bool ok = true; - myElemData["id"].push_back(attrs.get(VISSIM_ATTR_NO, nullptr, ok)); - } - - if (element == VISSIM_TAG_DATAPOINT) { - bool ok = true; - std::string sep(" "); - std::string posS(attrs.get(VISSIM_ATTR_X, nullptr, ok)); - posS += sep; - posS.append(attrs.get(VISSIM_ATTR_FX, nullptr, ok)); - myElemData["points"].push_back(posS); - - } - -} - -void -NIImporter_Vissim::NIVissimXMLHandler_Geschwindigkeitsverteilungsdefinition::myEndElement(int element) { - if (element == VISSIM_TAG_SPEED_DIST && myHierarchyLevel == 3) { - Distribution_Points* points = new Distribution_Points(myElemData["id"].front()); - while (!myElemData["points"].empty()) { - std::vector sPos_v(StringTokenizer( - myElemData["points"].front(), " ").getVector()); - myElemData["points"].pop_front(); - points->add(StringUtils::toDouble(sPos_v[0]), StringUtils::toDouble(sPos_v[1])); - } - DistributionCont::dictionary("speed", myElemData["id"].front(), points); - myElemData.clear(); - } - --myHierarchyLevel; -} - -// --------------------------------------------------------------------------- -// definitions of NIVissimXMLHandler_VWunschentscheidungsdefinition-methods -// --------------------------------------------------------------------------- -NIImporter_Vissim::NIVissimXMLHandler_VWunschentscheidungsdefinition::NIVissimXMLHandler_VWunschentscheidungsdefinition(nodeMap& elemData) - : GenericSAXHandler(vissimTags, VISSIM_TAG_NOTHING, - vissimAttrs, VISSIM_ATTR_NOTHING, - "vissim - file"), - myElemData(elemData), - myHierarchyLevel(0) { - myElemData.clear(); -} - -NIImporter_Vissim::NIVissimXMLHandler_VWunschentscheidungsdefinition::~NIVissimXMLHandler_VWunschentscheidungsdefinition() { } - -void -NIImporter_Vissim::NIVissimXMLHandler_VWunschentscheidungsdefinition::myStartElement(int element, const SUMOSAXAttributes& attrs) { - myHierarchyLevel++; - if (element == VISSIM_TAG_SPEED_DECISION) { - bool ok = true; - myElemData["name"].push_back(attrs.get(VISSIM_ATTR_NAME, nullptr, ok, false)); - //FIXME: 2 vWunsch in the xml file, but only 1 of them is set??? - } - -} - -void -NIImporter_Vissim::NIVissimXMLHandler_VWunschentscheidungsdefinition::myEndElement(int /* element */) { - --myHierarchyLevel; -} - - -// --------------------------------------------------------------------------- -// definitions of NIVissimXMLHandler_Routenentscheidungsdefinition-methods -// --------------------------------------------------------------------------- -NIImporter_Vissim::NIVissimXMLHandler_Routenentscheidungsdefinition::NIVissimXMLHandler_Routenentscheidungsdefinition(nodeMap& elemData) - : GenericSAXHandler(vissimTags, VISSIM_TAG_NOTHING, - vissimAttrs, VISSIM_ATTR_NOTHING, - "vissim - file"), - myElemData(elemData), - myHierarchyLevel(0) { - myElemData.clear(); -} - -NIImporter_Vissim::NIVissimXMLHandler_Routenentscheidungsdefinition::~NIVissimXMLHandler_Routenentscheidungsdefinition() { } - -void -NIImporter_Vissim::NIVissimXMLHandler_Routenentscheidungsdefinition::myStartElement(int element, const SUMOSAXAttributes& attrs) { - myHierarchyLevel++; - if (element == VISSIM_TAG_DECISION_STATIC) { - bool ok = true; - myElemData["startLink"].push_back(attrs.get(VISSIM_ATTR_LINK, nullptr, ok)); - myElemData["startPos"].push_back(attrs.get(VISSIM_ATTR_POS, nullptr, ok)); - } - if (element == VISSIM_TAG_ROUTE_STATIC) { - bool ok = true; - myElemData["destLink"].push_back(attrs.get(VISSIM_ATTR_DESTLINK, nullptr, ok)); - myElemData["destPos"].push_back(attrs.get(VISSIM_ATTR_DESTPOS, nullptr, ok)); - myElemData["id"].push_back(attrs.get(VISSIM_ATTR_NO, nullptr, ok)); - } - if (element == VISSIM_TAG_INTOBJECTREF) { - // bool ok = true; - } - -} - -void -NIImporter_Vissim::NIVissimXMLHandler_Routenentscheidungsdefinition::myEndElement(int /* element */) { - --myHierarchyLevel; -} - -// --------------------------------------------------------------------------- -// definitions of NIVissimXMLHandler_ConflictArea-methods -// --------------------------------------------------------------------------- -NIImporter_Vissim::NIVissimXMLHandler_ConflictArea::NIVissimXMLHandler_ConflictArea() - : GenericSAXHandler(vissimTags, VISSIM_TAG_NOTHING, - vissimAttrs, VISSIM_ATTR_NOTHING, - "vissim - file") {} - -NIImporter_Vissim::NIVissimXMLHandler_ConflictArea::~NIVissimXMLHandler_ConflictArea() { } - -void -NIImporter_Vissim::NIVissimXMLHandler_ConflictArea::myStartElement(int element, const SUMOSAXAttributes& attrs) { - // finding an actual flow - if (element == VISSIM_TAG_CA) { - //parse all flows - bool ok = true; - std::string status = attrs.get(VISSIM_ATTR_STATUS, nullptr, ok); - //get only the conflict areas which were set in VISSIM - if (status != "PASSIVE") { - NIVissimConflictArea::dictionary(attrs.get(VISSIM_ATTR_NO, nullptr, ok), - attrs.get(VISSIM_ATTR_LINK1, nullptr, ok), - attrs.get(VISSIM_ATTR_LINK2, nullptr, ok), - status); - } - - } -} - - -/* ------------------------------------------------------------------------- - * NIImporter_Vissim::VissimSingleTypeParser-methods - * ----------------------------------------------------------------------- */ -NIImporter_Vissim::VissimSingleTypeParser::VissimSingleTypeParser(NIImporter_Vissim& parent) - : myVissimParent(parent) {} - - -NIImporter_Vissim::VissimSingleTypeParser::~VissimSingleTypeParser() {} - - -std::string -NIImporter_Vissim::VissimSingleTypeParser::myRead(std::istream& from) { - std::string tmp; - from >> tmp; - return StringUtils::to_lower_case(tmp); -} - - - -std::string -NIImporter_Vissim::VissimSingleTypeParser::readEndSecure(std::istream& from, - const std::string& excl) { - std::string myExcl = StringUtils::to_lower_case(excl); - std::string tmp = myRead(from); - if (tmp == "") { - return "DATAEND"; - } - if (tmp != myExcl - && - (tmp.substr(0, 2) == "--" || !myVissimParent.admitContinue(tmp)) - ) { - return "DATAEND"; - } - return StringUtils::to_lower_case(tmp); -} - - -std::string -NIImporter_Vissim::VissimSingleTypeParser::readEndSecure(std::istream& from, - const std::vector& excl) { - std::vector myExcl; - std::vector::const_iterator i; - for (i = excl.begin(); i != excl.end(); i++) { - std::string mes = StringUtils::to_lower_case(*i); - myExcl.push_back(mes); - } - std::string tmp = myRead(from); - if (tmp == "") { - return "DATAEND"; - } - - bool equals = false; - for (i = myExcl.begin(); i != myExcl.end() && !equals; i++) { - if ((*i) == tmp) { - equals = true; - } - } - if (!equals - && - (tmp.substr(0, 2) == "--" || !myVissimParent.admitContinue(tmp)) - ) { - return "DATAEND"; - } - return StringUtils::to_lower_case(tmp); -} - - -std::string -NIImporter_Vissim::VissimSingleTypeParser::overrideOptionalLabel(std::istream& from, - const std::string& tag) { - std::string tmp; - if (tag == "") { - tmp = myRead(from); - } else { - tmp = tag; - } - if (tmp == "beschriftung") { - tmp = myRead(from); - if (tmp == "keine") { - from >> tmp; - } - tmp = myRead(from); - tmp = myRead(from); - } - return tmp; -} - - -Position -NIImporter_Vissim::VissimSingleTypeParser::getPosition(std::istream& from) { - double x, y; - from >> x; // type-checking is missing! - from >> y; // type-checking is missing! - return Position(x, y); -} - - -std::vector -NIImporter_Vissim::VissimSingleTypeParser::parseAssignedVehicleTypes( - std::istream& from, const std::string& next) { - std::string tmp = readEndSecure(from); - std::vector ret; - if (tmp == "alle") { - ret.push_back(-1); - return ret; - } - while (tmp != "DATAEND" && tmp != next) { - ret.push_back(StringUtils::toInt(tmp)); - tmp = readEndSecure(from); - } - return ret; -} - - -NIVissimExtendedEdgePoint -NIImporter_Vissim::VissimSingleTypeParser::readExtEdgePointDef( - std::istream& from) { - std::string tag; - from >> tag; // "Strecke" - int edgeid; - from >> edgeid; // type-checking is missing! - from >> tag; // "Spuren" - std::vector lanes; - while (tag != "bei") { - tag = readEndSecure(from); - if (tag != "bei") { - int lane = StringUtils::toInt(tag); - lanes.push_back(lane - 1); - } - } - double position; - from >> position; - std::vector dummy; - return NIVissimExtendedEdgePoint(edgeid, lanes, position, dummy); -} - - -std::string -NIImporter_Vissim::VissimSingleTypeParser::readName(std::istream& from) { - std::string name; - from >> name; - if (name[0] == '"') { - while (name[name.length() - 1] != '"') { - std::string tmp; - from >> tmp; - name = name + " " + tmp; - } - name = name.substr(1, name.length() - 2); - } - return StringUtils::convertUmlaute(name); -} - - -void -NIImporter_Vissim::VissimSingleTypeParser::readUntil(std::istream& from, - const std::string& name) { - std::string tag; - while (tag != name) { - tag = myRead(from); - } -} - -bool -NIImporter_Vissim::VissimSingleTypeParser::skipOverreading(std::istream& from, - const std::string& name) { - std::string tag; - while (tag != name) { - tag = myRead(from); - } - while (tag != "DATAEND") { - tag = readEndSecure(from); - } - return true; -} - - - -/* ------------------------------------------------------------------------- - * NIImporter_Vissim-methods - * ----------------------------------------------------------------------- */ -NIImporter_Vissim::NIImporter_Vissim(NBNetBuilder& nb) : myNetBuilder(nb) { - insertKnownElements(); - buildParsers(); - myColorMap["blau"] = RGBColor(77, 77, 255, 255); - myColorMap["gelb"] = RGBColor::YELLOW; - myColorMap["grau"] = RGBColor::GREY; - myColorMap["lila"] = RGBColor::MAGENTA; - myColorMap["gruen"] = RGBColor::GREEN; - myColorMap["rot"] = RGBColor::RED; - myColorMap["schwarz"] = RGBColor::BLACK; - myColorMap["tuerkis"] = RGBColor::CYAN; - myColorMap["weiss"] = RGBColor::WHITE; - myColorMap["keine"] = RGBColor::WHITE; -} - - - - -NIImporter_Vissim::~NIImporter_Vissim() { - NIVissimAbstractEdge::clearDict(); - NIVissimClosures::clearDict(); - NIVissimDistrictConnection::clearDict(); - NIVissimDisturbance::clearDict(); - NIVissimNodeCluster::clearDict(); - NIVissimNodeDef::clearDict(); - NIVissimSource::clearDict(); - NIVissimTL::clearDict(); - NIVissimTL::NIVissimTLSignal::clearDict(); - NIVissimTL::NIVissimTLSignalGroup::clearDict(); - NIVissimTrafficDescription::clearDict(); - NIVissimVehTypeClass::clearDict(); - NIVissimVehicleType::clearDict(); - NIVissimConnectionCluster::clearDict(); - NIVissimEdge::clearDict(); - NIVissimAbstractEdge::clearDict(); - NIVissimConnection::clearDict(); - NIVissimConflictArea::clearDict(); - for (ToParserMap::iterator i = myParsers.begin(); i != myParsers.end(); i++) { - delete (*i).second; - } -} - - -void -NIImporter_Vissim::load(const OptionsCont& options) { - const std::string file = options.getString("vissim-file"); - // try to open the file - std::ifstream strm(file.c_str()); - if (!strm.good()) { - WRITE_ERROR("Could not open vissim-file '" + file + "'."); - return; - } - std::string token; - strm >> token; - if (StringUtils::endsWith(file, ".inpx") || StringUtils::endsWith(token, "> tag; - } - myLastSecure = ""; - bool parsed = false; - while (!parsed && strm.good() && ok) { - ToElemIDMap::iterator i = myKnownElements.find(StringUtils::to_lower_case(tag)); - if (i != myKnownElements.end()) { - ToParserMap::iterator j = myParsers.find((*i).second); - if (j != myParsers.end()) { - VissimSingleTypeParser* parser = (*j).second; - ok = parser->parse(strm); - parsed = true; - } - } - if (!parsed) { - std::string line; - std::streamoff pos; - do { - pos = strm.tellg(); - getline(strm, line); - } while (strm.good() && (line == "" || line[0] == ' ' || line[0] == '-')); - if (!strm.good()) { - return true; - } - strm.seekg(pos); - strm >> tag; - } - } - } - return ok; -} - - -void -NIImporter_Vissim::postLoadBuild(double offset) { - // close the loading process - NIVissimBoundedClusterObject::closeLoading(); - NIVissimConnection::dict_assignToEdges(); - NIVissimDisturbance::dict_SetDisturbances(); - // build district->connections map - NIVissimDistrictConnection::dict_BuildDistrictConnections(); - // build clusters around nodes -// NIVissimNodeDef::buildNodeClusters(); - // build node clusters around traffic lights -// NIVissimTL::buildNodeClusters(); - - // when connections or disturbances are left, build nodes around them - - // try to assign connection clusters to nodes - // only left connections will be processed in - // buildConnectionClusters & join -//30.4. brauchen wir noch! NIVissimNodeDef::dict_assignConnectionsToNodes(); - - // build clusters of connections with the same direction and a similar position along the streets - NIVissimEdge::buildConnectionClusters(); - // check whether further nodes (connection clusters by now) must be added - NIVissimDistrictConnection::dict_CheckEdgeEnds(); - - // join clusters when overlapping (different streets are possible) - NIVissimEdge::dict_checkEdges2Join(); - NIVissimConnectionCluster::joinBySameEdges(offset); -// NIVissimConnectionCluster::joinByDisturbances(offset); - -// NIVissimConnectionCluster::addTLs(offset); - - // build nodes from clusters - NIVissimNodeCluster::setCurrentVirtID(NIVissimNodeDef::getMaxID()); - NIVissimConnectionCluster::buildNodeClusters(); - -// NIVissimNodeCluster::dict_recheckEdgeChanges(); - NIVissimNodeCluster::buildNBNodes(myNetBuilder.getNodeCont()); - NIVissimDistrictConnection::dict_BuildDistrictNodes( - myNetBuilder.getDistrictCont(), myNetBuilder.getNodeCont()); - NIVissimEdge::dict_propagateSpeeds(); - NIVissimEdge::dict_buildNBEdges(myNetBuilder.getDistrictCont(), myNetBuilder.getNodeCont(), myNetBuilder.getEdgeCont(), offset); - if (OptionsCont::getOptions().getBool("vissim.report-unset-speeds")) { - NIVissimEdge::reportUnsetSpeeds(); - } - NIVissimDistrictConnection::dict_BuildDistricts(myNetBuilder.getDistrictCont(), myNetBuilder.getEdgeCont(), myNetBuilder.getNodeCont()); - NIVissimConnection::dict_buildNBEdgeConnections(myNetBuilder.getEdgeCont()); - NIVissimNodeCluster::dict_addDisturbances(myNetBuilder.getDistrictCont(), myNetBuilder.getNodeCont(), myNetBuilder.getEdgeCont()); - NIVissimConflictArea::setPriorityRegulation(myNetBuilder.getEdgeCont()); - NIVissimTL::dict_SetSignals(myNetBuilder.getTLLogicCont(), myNetBuilder.getEdgeCont()); -} - - -void -NIImporter_Vissim::insertKnownElements() { - myKnownElements["kennung"] = VE_Kennungszeile; - myKnownElements["zufallszahl"] = VE_Startzufallszahl; - myKnownElements["simulationsdauer"] = VE_Simdauer; - myKnownElements["startuhrzeit"] = VE_Startuhrzeit; - myKnownElements["simulationsrate"] = VE_SimRate; - myKnownElements["zeitschritt"] = VE_Zeitschrittfaktor; - myKnownElements["linksverkehr"] = VE_Linksverkehr; - myKnownElements["dynuml"] = VE_DynUml; - myKnownElements["stau"] = VE_Stauparameterdefinition; - myKnownElements["gelbverhalten"] = VE_Gelbverhaltendefinition; - myKnownElements["strecke"] = VE_Streckendefinition; - myKnownElements["verbindung"] = VE_Verbindungsdefinition; - myKnownElements["richtungsentscheidung"] = VE_Richtungsentscheidungsdefinition; - myKnownElements["routenentscheidung"] = VE_Routenentscheidungsdefinition; - myKnownElements["vwunschentscheidung"] = VE_VWunschentscheidungsdefinition; - myKnownElements["langsamfahrbereich"] = VE_Langsamfahrbereichdefinition; - myKnownElements["zufluss"] = VE_Zuflussdefinition; - myKnownElements["fahrzeugtyp"] = VE_Fahrzeugtypdefinition; - myKnownElements["fahrzeugklasse"] = VE_Fahrzeugklassendefinition; - myKnownElements["zusammensetzung"] = VE_Verkehrszusammensetzungsdefinition; - myKnownElements["vwunsch"] = VE_Geschwindigkeitsverteilungsdefinition; - myKnownElements["laengen"] = VE_Laengenverteilungsdefinition; - myKnownElements["zeiten"] = VE_Zeitenverteilungsdefinition; - myKnownElements["baujahre"] = VE_Baujahrverteilungsdefinition; - myKnownElements["leistungen"] = VE_Laufleistungsverteilungsdefinition; - myKnownElements["massen"] = VE_Massenverteilungsdefinition; - myKnownElements["leistungen"] = VE_Leistungsverteilungsdefinition; - myKnownElements["maxbeschleunigung"] = VE_Maxbeschleunigungskurvedefinition; - myKnownElements["wunschbeschleunigung"] = VE_Wunschbeschleunigungskurvedefinition; - myKnownElements["maxverzoegerung"] = VE_Maxverzoegerungskurvedefinition; - myKnownElements["wunschverzoegerung"] = VE_Wunschverzoegerungskurvedefinition; - myKnownElements["querverkehrsstoerung"] = VE_Querverkehrsstoerungsdefinition; - myKnownElements["lsa"] = VE_Lichtsignalanlagendefinition; - myKnownElements["signalgruppe"] = VE_Signalgruppendefinition; - myKnownElements["signalgeber"] = VE_Signalgeberdefinition; - myKnownElements["lsakopplung"] = VE_LSAKopplungdefinition; - myKnownElements["detektor"] = VE_Detektorendefinition; - myKnownElements["haltestelle"] = VE_Haltestellendefinition; - myKnownElements["linie"] = VE_Liniendefinition; - myKnownElements["stopschild"] = VE_Stopschilddefinition; - myKnownElements["messung"] = VE_Messungsdefinition; - myKnownElements["reisezeit"] = VE_Reisezeitmessungsdefinition; - myKnownElements["verlustzeit"] = VE_Verlustzeitmessungsdefinition; - myKnownElements["querschnittsmessung"] = VE_Querschnittsmessungsdefinition; - myKnownElements["stauzaehler"] = VE_Stauzaehlerdefinition; - myKnownElements["auswertung"] = VE_Auswertungsdefinition; - myKnownElements["fenster"] = VE_Fensterdefinition; - myKnownElements["motiv"] = VE_Gefahrenwarnsystemdefinition; - myKnownElements["parkplatz"] = VE_Parkplatzdefinition; - myKnownElements["knoten"] = VE_Knotendefinition; - myKnownElements["teapac"] = VE_TEAPACdefinition; - myKnownElements["netzobjekt"] = VE_Netzobjektdefinition; - myKnownElements["richtungspfeil"] = VE_Richtungspfeildefinition; - myKnownElements["raute"] = VE_Rautedefinition; - myKnownElements["fahrverhalten"] = VE_Fahrverhaltendefinition; - myKnownElements["fahrtverlaufdateien"] = VE_Fahrtverlaufdateien; - myKnownElements["emission"] = VE_Emission; - myKnownElements["einheit"] = VE_Einheitendefinition; - myKnownElements["streckentyp"] = VE_Streckentypdefinition; - myKnownElements["kantensperrung"] = VE_Kantensperrung; - myKnownElements["kante"] = VE_Kantensperrung; - - - myKnownElements["advance"] = VE_DUMMY; - myKnownElements["temperatur"] = VE_DUMMY; - -} - - - -void -NIImporter_Vissim::buildParsers() { - myParsers[VE_Simdauer] = - new NIVissimSingleTypeParser_Simdauer(*this); - myParsers[VE_Startuhrzeit] = - new NIVissimSingleTypeParser_Startuhrzeit(*this); - myParsers[VE_DynUml] = - new NIVissimSingleTypeParser_DynUml(*this); - myParsers[VE_Streckendefinition] = - new NIVissimSingleTypeParser_Streckendefinition(*this); - myParsers[VE_Verbindungsdefinition] = - new NIVissimSingleTypeParser_Verbindungsdefinition(*this); - myParsers[VE_Richtungsentscheidungsdefinition] = - new NIVissimSingleTypeParser_Richtungsentscheidungsdefinition(*this); - myParsers[VE_Routenentscheidungsdefinition] = - new NIVissimSingleTypeParser_Routenentscheidungsdefinition(*this); - myParsers[VE_VWunschentscheidungsdefinition] = - new NIVissimSingleTypeParser_VWunschentscheidungsdefinition(*this); - myParsers[VE_Langsamfahrbereichdefinition] = - new NIVissimSingleTypeParser_Langsamfahrbereichdefinition(*this); - myParsers[VE_Zuflussdefinition] = - new NIVissimSingleTypeParser_Zuflussdefinition(*this); - myParsers[VE_Fahrzeugtypdefinition] = - new NIVissimSingleTypeParser_Fahrzeugtypdefinition(*this, myColorMap); - myParsers[VE_Fahrzeugklassendefinition] = - new NIVissimSingleTypeParser_Fahrzeugklassendefinition(*this, myColorMap); - myParsers[VE_Geschwindigkeitsverteilungsdefinition] = - new NIVissimSingleTypeParser_Geschwindigkeitsverteilungsdefinition(*this); - myParsers[VE_Laengenverteilungsdefinition] = - new NIVissimSingleTypeParser_Laengenverteilungsdefinition(*this); - myParsers[VE_Zeitenverteilungsdefinition] = - new NIVissimSingleTypeParser_Zeitenverteilungsdefinition(*this); - myParsers[VE_Querverkehrsstoerungsdefinition] = - new NIVissimSingleTypeParser_Querverkehrsstoerungsdefinition(*this); - myParsers[VE_Lichtsignalanlagendefinition] = - new NIVissimSingleTypeParser_Lichtsignalanlagendefinition(*this); - myParsers[VE_Signalgruppendefinition] = - new NIVissimSingleTypeParser_Signalgruppendefinition(*this); - myParsers[VE_Stopschilddefinition] = - new NIVissimSingleTypeParser_Stopschilddefinition(*this); - myParsers[VE_Knotendefinition] = - new NIVissimSingleTypeParser_Knotendefinition(*this); - myParsers[VE_Signalgeberdefinition] = - new NIVissimSingleTypeParser_Signalgeberdefinition(*this); - myParsers[VE_Detektorendefinition] = - new NIVissimSingleTypeParser_Detektordefinition(*this); - myParsers[VE_Haltestellendefinition] = - new NIVissimSingleTypeParser_Haltestellendefinition(*this); - myParsers[VE_Liniendefinition] = - new NIVissimSingleTypeParser_Liniendefinition(*this); - myParsers[VE_Reisezeitmessungsdefinition] = - new NIVissimSingleTypeParser_Reisezeitmessungsdefinition(*this); - myParsers[VE_Querschnittsmessungsdefinition] = - new NIVissimSingleTypeParser_Querschnittsmessungsdefinition(*this); - myParsers[VE_Messungsdefinition] = - new NIVissimSingleTypeParser_Messungsdefinition(*this); - myParsers[VE_Verlustzeitmessungsdefinition] = - new NIVissimSingleTypeParser_Verlustzeitmessungsdefinition(*this); - myParsers[VE_Stauzaehlerdefinition] = - new NIVissimSingleTypeParser_Stauzaehlerdefinition(*this); - myParsers[VE_Rautedefinition] = - new NIVissimSingleTypeParser_Rautedefinition(*this); - myParsers[VE_Richtungspfeildefinition] = - new NIVissimSingleTypeParser_Richtungspfeildefinition(*this); - myParsers[VE_Parkplatzdefinition] = - new NIVissimSingleTypeParser_Parkplatzdefinition(*this); - myParsers[VE_Fahrverhaltendefinition] = - new NIVissimSingleTypeParser_Fahrverhaltendefinition(*this); - myParsers[VE_Streckentypdefinition] = - new NIVissimSingleTypeParser_Streckentypdefinition(*this); - myParsers[VE_Kennungszeile] = - new NIVissimSingleTypeParser_Kennungszeile(*this); - myParsers[VE_Fensterdefinition] = - new NIVissimSingleTypeParser_Fensterdefinition(*this); - myParsers[VE_Auswertungsdefinition] = - new NIVissimSingleTypeParser_Auswertungsdefinition(*this); - myParsers[VE_Verkehrszusammensetzungsdefinition] = - new NIVissimSingleTypeParser_Zusammensetzungsdefinition(*this); - myParsers[VE_Kantensperrung] = - new NIVissimSingleTypeParser_Kantensperrung(*this); - - myParsers[VE_Startzufallszahl] = - new NIVissimSingleTypeParser_Startzufallszahl(*this); - myParsers[VE_SimRate] = - new NIVissimSingleTypeParser_SimRate(*this); - myParsers[VE_Zeitschrittfaktor] = - new NIVissimSingleTypeParser_Zeitschrittfaktor(*this); - myParsers[VE_Linksverkehr] = - new NIVissimSingleTypeParser_Linksverkehr(*this); - myParsers[VE_Stauparameterdefinition] = - new NIVissimSingleTypeParser_Stauparameterdefinition(*this); - myParsers[VE_Gelbverhaltendefinition] = - new NIVissimSingleTypeParser_Gelbverhaltendefinition(*this); - myParsers[VE_LSAKopplungdefinition] = - new NIVissimSingleTypeParser_LSAKopplungsdefinition(*this); - myParsers[VE_Gefahrenwarnsystemdefinition] = - new NIVissimSingleTypeParser_Gefahrwarnungsdefinition(*this); - myParsers[VE_TEAPACdefinition] = - new NIVissimSingleTypeParser_TEAPACDefinition(*this); - myParsers[VE_Netzobjektdefinition] = - new NIVissimSingleTypeParser_Netzobjektdefinition(*this); - myParsers[VE_Fahrtverlaufdateien] = - new NIVissimSingleTypeParser_Fahrtverlaufdateien(*this); - myParsers[VE_Emission] = - new NIVissimSingleTypeParser_Emission(*this); - myParsers[VE_Einheitendefinition] = - new NIVissimSingleTypeParser_Einheitendefinition(*this); - myParsers[VE_Baujahrverteilungsdefinition] = - new NIVissimSingleTypeParser__XVerteilungsdefinition(*this); - myParsers[VE_Laufleistungsverteilungsdefinition] = - new NIVissimSingleTypeParser__XVerteilungsdefinition(*this); - myParsers[VE_Massenverteilungsdefinition] = - new NIVissimSingleTypeParser__XVerteilungsdefinition(*this); - myParsers[VE_Leistungsverteilungsdefinition] = - new NIVissimSingleTypeParser__XVerteilungsdefinition(*this); - myParsers[VE_Maxbeschleunigungskurvedefinition] = - new NIVissimSingleTypeParser__XKurvedefinition(*this); - myParsers[VE_Wunschbeschleunigungskurvedefinition] = - new NIVissimSingleTypeParser__XKurvedefinition(*this); - myParsers[VE_Maxverzoegerungskurvedefinition] = - new NIVissimSingleTypeParser__XKurvedefinition(*this); - myParsers[VE_Wunschverzoegerungskurvedefinition] = - new NIVissimSingleTypeParser__XKurvedefinition(*this); - -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/vissim/NIImporter_Vissim.h b/Util/OSM2ODR/src/netimport/vissim/NIImporter_Vissim.h deleted file mode 100644 index f9c8b7556..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/NIImporter_Vissim.h +++ /dev/null @@ -1,657 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIImporter_Vissim.h -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @author Lukas Grohmann (AIT) -/// @author Gerald Richter (AIT) -/// @date Sept 2002 -/// -// Importer for networks stored in Vissim format -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include -#include -#include -#include "tempstructs/NIVissimExtendedEdgePoint.h" -#include "NIVissimElements.h" -#include -#include "tempstructs/NIVissimEdge.h" -#include "tempstructs/NIVissimConnection.h" -#include "tempstructs/NIVissimConflictArea.h" - -#include -#include -#include - -// =========================================================================== -// class declarations -// =========================================================================== -class OptionsCont; -class NBNetBuilder; - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NIImporter_Vissim - * @brief Importer for networks stored in Vissim format - */ -class NIImporter_Vissim { -public: - /** @brief Loads network definition from the assigned option and stores it in the given network builder - * - * If the option "vissim-file" is set, the file stored therein is read and - * the network definition stored therein is stored within the given network - * builder. - * - * If the option "vissim-file" is not set, this method simply returns. - * - * @param[in] oc The options to use - * @param[in] nb The network builder to fill - */ - static void loadNetwork(const OptionsCont& oc, NBNetBuilder& nb); - - - -private: - - typedef std::map > nodeMap; - nodeMap elementData; - - /** - * @class NIVissimSingleTypeXMLHandler_Streckendefinition - * @brief A class which extracts VISSIM-Strecken from a parsed VISSIM-file - */ - class NIVissimXMLHandler_Streckendefinition : public GenericSAXHandler { - public: - /** @brief Constructor - * @param[in] strecken_dic The strecken dictionary to fill - */ - //NIVissimXMLHandler_Streckendefinition(std::map& toFill); - NIVissimXMLHandler_Streckendefinition(nodeMap& elemData); - - - /// @brief Destructor - ~NIVissimXMLHandler_Streckendefinition(); - - protected: - /// @name inherited from GenericSAXHandler - //@{ - - /** @brief Called on the opening of a tag; - * - * @param[in] element ID of the currently opened element - * @param[in] attrs Attributes within the currently opened element - * @exception ProcessError If something fails - * @see GenericSAXHandler::myStartElement - */ - void myStartElement(int element, const SUMOSAXAttributes& attrs); - //@} - - void myEndElement(int element); - //@} - - private: - - //std::map myToFill; - nodeMap& myElemData; - - /// @brief The current hierarchy level - int myHierarchyLevel; - - /// @brief check if the link is a connector - bool isConnector; - - /// @brief ID of the currently parsed node, for reporting mainly - int myLastNodeID; - - /** @brief invalidated copy constructor */ - NIVissimXMLHandler_Streckendefinition(const NIVissimXMLHandler_Streckendefinition& s); - - /** @brief invalidated assignment operator */ - NIVissimXMLHandler_Streckendefinition& operator=(const NIVissimXMLHandler_Streckendefinition& s); - }; - - -private: - /** - * @class NIVissimSingleTypeXMLHandler_Zuflussdefinition - * @brief A class which extracts VISSIM-Zuflüsse from a parsed VISSIM-file - */ - class NIVissimXMLHandler_Zuflussdefinition : public GenericSAXHandler { - public: - /** @brief Constructor - */ - NIVissimXMLHandler_Zuflussdefinition(); - - - /// @brief Destructor - ~NIVissimXMLHandler_Zuflussdefinition(); - - protected: - /// @name inherited from GenericSAXHandler - //@{ - - /** @brief Called on the opening of a tag; - * - * @param[in] element ID of the currently opened element - * @param[in] attrs Attributes within the currently opened element - * @exception ProcessError If something fails - * @see GenericSAXHandler::myStartElement - */ - void myStartElement(int element, const SUMOSAXAttributes& attrs); - //@} - - - private: - - - - /** @brief invalidated copy constructor */ - NIVissimXMLHandler_Zuflussdefinition(const NIVissimXMLHandler_Zuflussdefinition& z); - - /** @brief invalidated assignment operator */ - NIVissimXMLHandler_Zuflussdefinition& operator=(const NIVissimXMLHandler_Zuflussdefinition& z); - }; - - -private: - /** - * @class NIVissimSingleTypeXMLHandler_Parkplatzdefinition - * @brief A class which extracts VISSIM-Parkplätze from a parsed VISSIM-file - */ - class NIVissimXMLHandler_Parkplatzdefinition : public GenericSAXHandler { - public: - /** @brief Constructor - */ - NIVissimXMLHandler_Parkplatzdefinition(); - - - /// @brief Destructor - ~NIVissimXMLHandler_Parkplatzdefinition(); - - protected: - /// @name inherited from GenericSAXHandler - //@{ - - /** @brief Called on the opening of a tag; - * - * @param[in] element ID of the currently opened element - * @param[in] attrs Attributes within the currently opened element - * @exception ProcessError If something fails - * @see GenericSAXHandler::myStartElement - */ - void myStartElement(int element, const SUMOSAXAttributes& attrs); - //@} - - - private: - - - - /** @brief invalidated copy constructor */ - NIVissimXMLHandler_Parkplatzdefinition(const NIVissimXMLHandler_Parkplatzdefinition& z); - - /** @brief invalidated assignment operator */ - NIVissimXMLHandler_Parkplatzdefinition& operator=(const NIVissimXMLHandler_Parkplatzdefinition& z); - }; - - -private: - /** - * @class NIVissimSingleTypeXMLHandler_Fahrzeugklassendefinition - * @brief A class which extracts VISSIM-Fahrzeugklassen from a parsed VISSIM-file - */ - class NIVissimXMLHandler_Fahrzeugklassendefinition : public GenericSAXHandler { - public: - /** @brief Constructor - * @param[in] elemData The string container to fill - */ - - NIVissimXMLHandler_Fahrzeugklassendefinition(nodeMap& elemData); - - - /// @brief Destructor - ~NIVissimXMLHandler_Fahrzeugklassendefinition(); - - protected: - /// @name inherited from GenericSAXHandler - //@{ - - /** @brief Called on the opening of a tag; - * - * @param[in] element ID of the currently opened element - * @param[in] attrs Attributes within the currently opened element - * @exception ProcessError If something fails - * @see GenericSAXHandler::myStartElement - */ - void myStartElement(int element, const SUMOSAXAttributes& attrs); - //@} - - void myEndElement(int element); - //@} - - private: - - //std::map myToFill; - nodeMap& myElemData; - - /// @brief The current hierarchy level - int myHierarchyLevel; - - /// @brief ID of the currently parsed node, for reporting mainly - int myLastNodeID; - - /** @brief invalidated copy constructor */ - NIVissimXMLHandler_Fahrzeugklassendefinition(const NIVissimXMLHandler_Fahrzeugklassendefinition& f); - - /** @brief invalidated assignment operator */ - NIVissimXMLHandler_Fahrzeugklassendefinition& operator=(const NIVissimXMLHandler_Fahrzeugklassendefinition& f); - }; - -private: - /** - * @class NIVissimSingleTypeXMLHandler_VWunschentscheidungsdefinition - * @brief A class which extracts VISSIM-VWunschentscheidungen from a parsed VISSIM-file - */ - class NIVissimXMLHandler_VWunschentscheidungsdefinition : public GenericSAXHandler { - public: - /** @brief Constructor - * @param[in] elemData The string container to fill - */ - - NIVissimXMLHandler_VWunschentscheidungsdefinition(nodeMap& elemData); - - - /// @brief Destructor - ~NIVissimXMLHandler_VWunschentscheidungsdefinition(); - - protected: - /// @name inherited from GenericSAXHandler - //@{ - - /** @brief Called on the opening of a tag; - * - * @param[in] element ID of the currently opened element - * @param[in] attrs Attributes within the currently opened element - * @exception ProcessError If something fails - * @see GenericSAXHandler::myStartElement - */ - void myStartElement(int element, const SUMOSAXAttributes& attrs); - //@} - - void myEndElement(int element); - //@} - - private: - - //std::map myToFill; - nodeMap& myElemData; - - /// @brief The current hierarchy level - int myHierarchyLevel; - - /// @brief ID of the currently parsed node, for reporting mainly - int myLastNodeID; - - /** @brief invalidated copy constructor */ - NIVissimXMLHandler_VWunschentscheidungsdefinition(const NIVissimXMLHandler_VWunschentscheidungsdefinition& vW); - - /** @brief invalidated assignment operator */ - NIVissimXMLHandler_VWunschentscheidungsdefinition& operator=(const NIVissimXMLHandler_VWunschentscheidungsdefinition& vW); - }; - - - - -private: - /** - * @class NIVissimSingleTypeXMLHandler_Geschwindigkeitsverteilungsdefinition - * @brief A class which extracts VISSIM-Geschwindigkeitsverteilung from a parsed VISSIM-file - */ - class NIVissimXMLHandler_Geschwindigkeitsverteilungsdefinition : public GenericSAXHandler { - public: - /** @brief Constructor - * @param[in] elemData The string container to fill - */ - - NIVissimXMLHandler_Geschwindigkeitsverteilungsdefinition(nodeMap& elemData); - - - /// @brief Destructor - ~NIVissimXMLHandler_Geschwindigkeitsverteilungsdefinition(); - - protected: - /// @name inherited from GenericSAXHandler - //@{ - - /** @brief Called on the opening of a tag; - * - * @param[in] element ID of the currently opened element - * @param[in] attrs Attributes within the currently opened element - * @exception ProcessError If something fails - * @see GenericSAXHandler::myStartElement - */ - void myStartElement(int element, const SUMOSAXAttributes& attrs); - //@} - - void myEndElement(int element); - //@} - - private: - - //std::map myToFill; - nodeMap& myElemData; - - /// @brief The current hierarchy level - int myHierarchyLevel; - - /// @brief ID of the currently parsed node, for reporting mainly - int myLastNodeID; - - /** @brief invalidated copy constructor */ - NIVissimXMLHandler_Geschwindigkeitsverteilungsdefinition(const NIVissimXMLHandler_Geschwindigkeitsverteilungsdefinition& vW); - - /** @brief invalidated assignment operator */ - NIVissimXMLHandler_Geschwindigkeitsverteilungsdefinition& operator=(const NIVissimXMLHandler_Geschwindigkeitsverteilungsdefinition& vW); - }; - - -private: - /** - * @class NIVissimXMLHandler_Routenentscheidungsdefinition - * @brief A class which extracts VISSIM-Routes from a parsed VISSIM-file - */ - class NIVissimXMLHandler_Routenentscheidungsdefinition : public GenericSAXHandler { - public: - /** @brief Constructor - * @param[in] elemData The string container to fill - */ - - NIVissimXMLHandler_Routenentscheidungsdefinition(nodeMap& elemData); - - - /// @brief Destructor - ~NIVissimXMLHandler_Routenentscheidungsdefinition(); - - protected: - /// @name inherited from GenericSAXHandler - //@{ - - /** @brief Called on the opening of a tag; - * - * @param[in] element ID of the currently opened element - * @param[in] attrs Attributes within the currently opened element - * @exception ProcessError If something fails - * @see GenericSAXHandler::myStartElement - */ - void myStartElement(int element, const SUMOSAXAttributes& attrs); - //@} - - void myEndElement(int element); - //@} - - private: - - //std::map myToFill; - nodeMap& myElemData; - - /// @brief The current hierarchy level - int myHierarchyLevel; - - /// @brief ID of the currently parsed node, for reporting mainly - int myLastNodeID; - - /** @brief invalidated copy constructor */ - NIVissimXMLHandler_Routenentscheidungsdefinition(const NIVissimXMLHandler_Routenentscheidungsdefinition& r); - - /** @brief invalidated assignment operator */ - NIVissimXMLHandler_Routenentscheidungsdefinition& operator=(const NIVissimXMLHandler_Routenentscheidungsdefinition& r); - }; - - -private: - /** - * @class NIVissimSingleTypeXMLHandler_ConflictArea - * @brief A class which extracts VISSIM-ConflictAreas from a parsed VISSIM-file - */ - class NIVissimXMLHandler_ConflictArea : public GenericSAXHandler { - public: - /** @brief Constructor - */ - NIVissimXMLHandler_ConflictArea(); - - - /// @brief Destructor - ~NIVissimXMLHandler_ConflictArea(); - - - protected: - /// @name inherited from GenericSAXHandler - //@{ - - /** @brief Called on the opening of a tag; - * - * @param[in] element ID of the currently opened element - * @param[in] attrs Attributes within the currently opened element - * @exception ProcessError If something fails - * @see GenericSAXHandler::myStartElement - */ - void myStartElement(int element, const SUMOSAXAttributes& attrs); - //@} - - - private: - - - /** @brief invalidated copy constructor */ - NIVissimXMLHandler_ConflictArea(const NIVissimXMLHandler_ConflictArea& c); - - /** @brief invalidated assignment operator */ - NIVissimXMLHandler_ConflictArea& operator=(const NIVissimXMLHandler_ConflictArea& c); - }; - - -protected: - /// constructor - NIImporter_Vissim(NBNetBuilder& nb); - - /// destructor - ~NIImporter_Vissim(); - - /// loads the vissim file - void load(const OptionsCont& options); - - bool admitContinue(const std::string& tag); - -public: - class VissimSingleTypeParser { - public: - /// Constructor - VissimSingleTypeParser(NIImporter_Vissim& parent); - - /// Destructor - virtual ~VissimSingleTypeParser(); - - /** @brief Parses a single data type. - Returns whether no error occurred */ - virtual bool parse(std::istream& from) = 0; - - protected: - /// reads from the stream and returns the lower case version of the read value - std::string myRead(std::istream& from); - - /// as myRead, but returns "DATAEND" when the current field has ended - std::string readEndSecure(std::istream& from, - const std::string& excl = ""); - - std::string readEndSecure(std::istream& from, - const std::vector& excl); - - /// overrides the optional label definition; returns the next tag as done by readEndSecure - std::string overrideOptionalLabel(std::istream& from, - const std::string& tag = ""); - - /// returns the 2d-position saved as next within the stream - Position getPosition(std::istream& from); - - /** @brief parses a listof vehicle types assigned to the current data field - One should remeber, that -1 means "all" vehicle types */ - std::vector parseAssignedVehicleTypes(std::istream& from, - const std::string& next); - - NIVissimExtendedEdgePoint readExtEdgePointDef(std::istream& from); - - /** @brief Reads the structures name - We cannot use the "<<" operator, as names may contain more than one word - which are joined using '"'. */ - std::string readName(std::istream& from); - - /** @brief Overreads the named parameter (if) given and skips the rest until "DATAEND" - */ - bool skipOverreading(std::istream& from, const std::string& name = ""); - - /// Reads from the stream until the keywor occurs - void readUntil(std::istream& from, const std::string& name); - - private: - NIImporter_Vissim& myVissimParent; - - private: - /// @brief Invalidated assignment operator. - VissimSingleTypeParser& operator=(const VissimSingleTypeParser&); - - }; - - - /// definition of a map from color names to color definitions - typedef std::map ColorMap; - -private: - bool readContents(std::istream& strm); - void postLoadBuild(double offset); - - - /// adds name-to-id - relationships of known elements into myKnownElements - void insertKnownElements(); - - /// adds id-to-parser - relationships of elements to parse into myParsers - void buildParsers(); - -private: - /// Definition of a map from element names to their numerical representation - typedef std::map ToElemIDMap; - - /// Map from element names to their numerical representation - ToElemIDMap myKnownElements; - - /// Definition of a map from an element's numerical id to his parser - typedef std::map ToParserMap; - - /// Parsers by element id - ToParserMap myParsers; - - /// a map from color names to color definitions - ColorMap myColorMap; - - std::string myLastSecure; - - NBNetBuilder& myNetBuilder; - -private: - /// @brief Invalidated copy constructor. - NIImporter_Vissim(const NIImporter_Vissim&); - - /// @brief Invalidated assignment operator. - NIImporter_Vissim& operator=(const NIImporter_Vissim&); - - - - /** - * @enum VissimXMLTag - * @brief Numbers representing VISSIM-XML - element names - * @see GenericSAXHandler - */ - enum VissimXMLTag { - VISSIM_TAG_NOTHING = 0, - VISSIM_TAG_NETWORK, - VISSIM_TAG_LANES, - VISSIM_TAG_LANE, - VISSIM_TAG_LINK, - VISSIM_TAG_LINKS, - VISSIM_TAG_POINTS3D, - VISSIM_TAG_POINT3D, - VISSIM_TAG_LINKPOLYPOINT, - VISSIM_TAG_LINKPOLYPTS, - VISSIM_TAG_FROM, - VISSIM_TAG_TO, - VISSIM_TAG_VEHICLE_INPUT, - VISSIM_TAG_PARKINGLOT, - VISSIM_TAG_VEHICLE_CLASS, - VISSIM_TAG_INTOBJECTREF, - VISSIM_TAG_SPEED_DECISION, - VISSIM_TAG_SPEED_DIST, - VISSIM_TAG_DATAPOINT, - VISSIM_TAG_DECISION_STATIC, - VISSIM_TAG_ROUTE_STATIC, - VISSIM_TAG_CA - }; - - - /** - * @enum VissimXMLAttr - * @brief Numbers representing VISSIM-XML - attributes - * @see GenericSAXHandler - */ - enum VissimXMLAttr { - VISSIM_ATTR_NOTHING = 0, - VISSIM_ATTR_NO, - VISSIM_ATTR_NAME, - VISSIM_ATTR_X, - VISSIM_ATTR_Y, - VISSIM_ATTR_ZOFFSET, - VISSIM_ATTR_ZUSCHLAG1, - VISSIM_ATTR_ZUSCHLAG2, - VISSIM_ATTR_WIDTH, - VISSIM_ATTR_LINKBEHAVETYPE, - VISSIM_ATTR_LANE, - VISSIM_ATTR_POS, - VISSIM_ATTR_LINK, - VISSIM_ATTR_INTLINK, - VISSIM_ATTR_PERCENTAGE, - VISSIM_ATTR_DISTRICT, - VISSIM_ATTR_COLOR, - VISSIM_ATTR_KEY, - VISSIM_ATTR_FX, - VISSIM_ATTR_DESTLINK, - VISSIM_ATTR_DESTPOS, - VISSIM_ATTR_LINK1, - VISSIM_ATTR_LINK2, - VISSIM_ATTR_STATUS - }; - - /// The names of VISSIM-XML elements (for passing to GenericSAXHandler) - static StringBijection::Entry vissimTags[]; - - /// The names of VISSIM-XML attributes (for passing to GenericSAXHandler) - static StringBijection::Entry vissimAttrs[]; - - -}; diff --git a/Util/OSM2ODR/src/netimport/vissim/NIVissimElements.h b/Util/OSM2ODR/src/netimport/vissim/NIVissimElements.h deleted file mode 100644 index 11354a83b..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/NIVissimElements.h +++ /dev/null @@ -1,86 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimElements.h -/// @author Daniel Krajzewicz -/// @date Sept 2002 -/// -// ------------------- -/****************************************************************************/ -#pragma once -#include - - -enum NIVissimElement { - VE_Kennungszeile, - VE_Startzufallszahl, - VE_Simdauer, - VE_Startuhrzeit, - VE_SimRate, - VE_Zeitschrittfaktor, - VE_Linksverkehr, - VE_DynUml, - VE_Stauparameterdefinition, - VE_Gelbverhaltendefinition, - VE_Streckendefinition, - VE_Verbindungsdefinition, - VE_Richtungsentscheidungsdefinition, - VE_Routenentscheidungsdefinition, - VE_VWunschentscheidungsdefinition, - VE_Langsamfahrbereichdefinition, - VE_Zuflussdefinition, - VE_Fahrzeugtypdefinition, - VE_Fahrzeugklassendefinition, - VE_Verkehrszusammensetzungsdefinition, - VE_Geschwindigkeitsverteilungsdefinition, - VE_Laengenverteilungsdefinition, - VE_Zeitenverteilungsdefinition, - VE_Baujahrverteilungsdefinition, - VE_Laufleistungsverteilungsdefinition, - VE_Massenverteilungsdefinition, - VE_Leistungsverteilungsdefinition, - VE_Maxbeschleunigungskurvedefinition, - VE_Wunschbeschleunigungskurvedefinition, - VE_Maxverzoegerungskurvedefinition, - VE_Wunschverzoegerungskurvedefinition, - VE_Querverkehrsstoerungsdefinition, - VE_Lichtsignalanlagendefinition, - VE_Signalgruppendefinition, - VE_Signalgeberdefinition, - VE_LSAKopplungdefinition, - VE_Detektorendefinition, - VE_Haltestellendefinition, - VE_Liniendefinition, - VE_Stopschilddefinition, - VE_Messungsdefinition, - VE_Reisezeitmessungsdefinition, - VE_Verlustzeitmessungsdefinition, - VE_Querschnittsmessungsdefinition, - VE_Stauzaehlerdefinition, - VE_Auswertungsdefinition, - VE_Fensterdefinition, - VE_Gefahrenwarnsystemdefinition, - VE_Parkplatzdefinition, - VE_Knotendefinition, - VE_TEAPACdefinition, - VE_Netzobjektdefinition, - VE_Richtungspfeildefinition, - VE_Rautedefinition, - VE_Fahrverhaltendefinition, - VE_Fahrtverlaufdateien, - VE_Emission, - VE_Einheitendefinition, - VE_Streckentypdefinition, - VE_Kantensperrung, - VE_DUMMY -}; diff --git a/Util/OSM2ODR/src/netimport/vissim/tempstructs/CMakeLists.txt b/Util/OSM2ODR/src/netimport/vissim/tempstructs/CMakeLists.txt deleted file mode 100644 index dd1a6a7c8..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/tempstructs/CMakeLists.txt +++ /dev/null @@ -1,55 +0,0 @@ -set(netimport_vissim_tempstructs_STAT_SRCS - NIVissimAbstractEdge.cpp - NIVissimAbstractEdge.h - NIVissimBoundedClusterObject.cpp - NIVissimBoundedClusterObject.h - NIVissimClosedLaneDef.cpp - NIVissimClosedLaneDef.h - NIVissimClosedLanesVector.h - NIVissimClosures.cpp - NIVissimClosures.h - NIVissimConflictArea.cpp - NIVissimConflictArea.h - NIVissimConnection.cpp - NIVissimConnection.h - NIVissimConnectionCluster.cpp - NIVissimConnectionCluster.h - NIVissimDistrictConnection.cpp - NIVissimDistrictConnection.h - NIVissimDisturbance.cpp - NIVissimDisturbance.h - NIVissimEdge.cpp - NIVissimEdge.h - NIVissimEdgePosMap.cpp - NIVissimEdgePosMap.h - NIVissimExtendedEdgePoint.cpp - NIVissimExtendedEdgePoint.h - NIVissimExtendedEdgePointVector.h - NIVissimNodeCluster.cpp - NIVissimNodeCluster.h - NIVissimNodeDef.cpp - NIVissimNodeDef.h - NIVissimNodeDef_Edges.cpp - NIVissimNodeDef_Edges.h - NIVissimNodeDef_Poly.cpp - NIVissimNodeDef_Poly.h - NIVissimNodeParticipatingEdge.cpp - NIVissimNodeParticipatingEdge.h - NIVissimNodeParticipatingEdgeVector.h - NIVissimSource.cpp - NIVissimSource.h - NIVissimTL.cpp - NIVissimTL.h - NIVissimTrafficDescription.cpp - NIVissimTrafficDescription.h - NIVissimVehTypeClass.cpp - NIVissimVehTypeClass.h - NIVissimVehicleClass.cpp - NIVissimVehicleClass.h - NIVissimVehicleClassVector.h - NIVissimVehicleType.cpp - NIVissimVehicleType.h -) - -add_library(netimport_vissim_tempstructs STATIC ${netimport_vissim_tempstructs_STAT_SRCS}) -set_property(TARGET netimport_vissim_tempstructs PROPERTY PROJECT_LABEL "z_netimport_vissim_tempstructs") diff --git a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimAbstractEdge.cpp b/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimAbstractEdge.cpp deleted file mode 100644 index b29acc65e..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimAbstractEdge.cpp +++ /dev/null @@ -1,177 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimAbstractEdge.cpp -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date Sept 2002 -/// -// ------------------- -/****************************************************************************/ -#include - - -#include -#include -#include -#include -#include -#include -#include -#include "NIVissimAbstractEdge.h" - - -NIVissimAbstractEdge::DictType NIVissimAbstractEdge::myDict; - -NIVissimAbstractEdge::NIVissimAbstractEdge(int id, - const PositionVector& geom) - : myID(id), myNode(-1) { - // convert/publicate geometry - for (PositionVector::const_iterator i = geom.begin(); i != geom.end(); ++i) { - Position p = *i; - if (!NBNetBuilder::transformCoordinate(p)) { - WRITE_WARNING("Unable to project coordinates for edge '" + toString(id) + "'."); - } - myGeom.push_back_noDoublePos(p); - } - // - dictionary(id, this); -} - - -NIVissimAbstractEdge::~NIVissimAbstractEdge() {} - - -bool -NIVissimAbstractEdge::dictionary(int id, NIVissimAbstractEdge* e) { - DictType::iterator i = myDict.find(id); - if (i == myDict.end()) { - myDict[id] = e; - return true; - } - return false; -} - - -NIVissimAbstractEdge* -NIVissimAbstractEdge::dictionary(int id) { - DictType::iterator i = myDict.find(id); - if (i == myDict.end()) { - return nullptr; - } - return (*i).second; -} - - - -Position -NIVissimAbstractEdge::getGeomPosition(double pos) const { - if (myGeom.length() > pos) { - return myGeom.positionAtOffset(pos); - } else if (myGeom.length() == pos) { - return myGeom[-1]; - } else { - PositionVector g(myGeom); - const double amount = pos - myGeom.length(); - g.extrapolate(amount * 2); - return g.positionAtOffset(pos + amount * 2); - } -} - - -void -NIVissimAbstractEdge::splitAndAssignToNodes() { - for (DictType::iterator i = myDict.begin(); i != myDict.end(); i++) { - NIVissimAbstractEdge* e = (*i).second; - e->splitAssigning(); - } -} - -void -NIVissimAbstractEdge::splitAssigning() {} - - - - - -bool -NIVissimAbstractEdge::crossesEdge(NIVissimAbstractEdge* c) const { - return myGeom.intersects(c->myGeom); -} - - -Position -NIVissimAbstractEdge::crossesEdgeAtPoint(NIVissimAbstractEdge* c) const { - return myGeom.intersectionPosition2D(c->myGeom); -} - - -std::vector -NIVissimAbstractEdge::getWithin(const AbstractPoly& p, double offset) { - std::vector ret; - for (DictType::iterator i = myDict.begin(); i != myDict.end(); i++) { - NIVissimAbstractEdge* e = (*i).second; - if (e->overlapsWith(p, offset)) { - ret.push_back(e->myID); - } - } - return ret; -} - - -bool -NIVissimAbstractEdge::overlapsWith(const AbstractPoly& p, double offset) const { - return myGeom.overlapsWith(p, offset); -} - - -bool -NIVissimAbstractEdge::hasNodeCluster() const { - return myNode != -1; -} - - -int -NIVissimAbstractEdge::getID() const { - return myID; -} - -void -NIVissimAbstractEdge::clearDict() { - for (DictType::iterator i = myDict.begin(); i != myDict.end(); i++) { - delete (*i).second; - } - myDict.clear(); -} - - -const PositionVector& -NIVissimAbstractEdge::getGeometry() const { - return myGeom; -} - - -void -NIVissimAbstractEdge::addDisturbance(int disturbance) { - myDisturbances.push_back(disturbance); -} - - -const std::vector& -NIVissimAbstractEdge::getDisturbances() const { - return myDisturbances; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimAbstractEdge.h b/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimAbstractEdge.h deleted file mode 100644 index 4e0f4071d..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimAbstractEdge.h +++ /dev/null @@ -1,71 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimAbstractEdge.h -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Sept 2002 -/// -// ------------------- -/****************************************************************************/ -#pragma once -#include - -#include -#include - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * - */ -class NIVissimAbstractEdge { -public: - NIVissimAbstractEdge(int id, const PositionVector& geom); - virtual ~NIVissimAbstractEdge(); - Position getGeomPosition(double pos) const; - void splitAssigning(); - bool crossesEdge(NIVissimAbstractEdge* c) const; - Position crossesEdgeAtPoint(NIVissimAbstractEdge* c) const; - bool overlapsWith(const AbstractPoly& p, double offset = 0.0) const; - virtual void setNodeCluster(int nodeid) = 0; - bool hasNodeCluster() const; - - virtual void buildGeom() = 0; - int getID() const; - const PositionVector& getGeometry() const; - - void addDisturbance(int disturbance); - - const std::vector& getDisturbances() const; - -public: - static bool dictionary(int id, NIVissimAbstractEdge* e); - static NIVissimAbstractEdge* dictionary(int id); - static void splitAndAssignToNodes(); - static std::vector getWithin(const AbstractPoly& p, double offset = 0.0); - static void clearDict(); - - -protected: - int myID; - PositionVector myGeom; - std::vector myDisturbances; - int myNode; - -private: - typedef std::map DictType; - static DictType myDict; -}; diff --git a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimBoundedClusterObject.cpp b/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimBoundedClusterObject.cpp deleted file mode 100644 index cd87ea6b7..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimBoundedClusterObject.cpp +++ /dev/null @@ -1,74 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimBoundedClusterObject.cpp -/// @author Daniel Krajzewicz -/// @date Sept 2002 -/// -// ------------------- -/****************************************************************************/ -#include - - -#include -#include -#include "NIVissimBoundedClusterObject.h" - -NIVissimBoundedClusterObject::ContType NIVissimBoundedClusterObject::myDict; - -NIVissimBoundedClusterObject::NIVissimBoundedClusterObject() - : myBoundary(nullptr), myClusterID(-1) { - myDict.insert(this); -} - - -NIVissimBoundedClusterObject::~NIVissimBoundedClusterObject() { - delete myBoundary; -} - - -bool -NIVissimBoundedClusterObject::crosses(const AbstractPoly& poly, - double offset) const { - assert(myBoundary != 0 && myBoundary->xmax() >= myBoundary->xmin()); - return myBoundary->overlapsWith(poly, offset); -} - - -void -NIVissimBoundedClusterObject::inCluster(int id) { - myClusterID = id; -} - - -bool -NIVissimBoundedClusterObject::clustered() const { - return myClusterID > 0; -} - - -void -NIVissimBoundedClusterObject::closeLoading() { - for (ContType::iterator i = myDict.begin(); i != myDict.end(); i++) { - (*i)->computeBounding(); - } -} - - -const Boundary& -NIVissimBoundedClusterObject::getBoundary() const { - return *myBoundary; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimBoundedClusterObject.h b/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimBoundedClusterObject.h deleted file mode 100644 index 174a44a04..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimBoundedClusterObject.h +++ /dev/null @@ -1,54 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimBoundedClusterObject.h -/// @author Daniel Krajzewicz -/// @date Sept 2002 -/// -// ------------------- -/****************************************************************************/ -#pragma once -#include - -#include -#include - - -// =========================================================================== -// class declarations -// =========================================================================== -class Boundary; - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * - */ -class NIVissimBoundedClusterObject { -public: - NIVissimBoundedClusterObject(); - virtual ~NIVissimBoundedClusterObject(); - virtual void computeBounding() = 0; - bool crosses(const AbstractPoly& poly, double offset = 0) const; - void inCluster(int id); - bool clustered() const; - const Boundary& getBoundary() const; -public: - static void closeLoading(); -protected: - typedef std::set ContType; - static ContType myDict; - Boundary* myBoundary; - int myClusterID; -}; diff --git a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimClosedLaneDef.cpp b/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimClosedLaneDef.cpp deleted file mode 100644 index 55df8fb9f..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimClosedLaneDef.cpp +++ /dev/null @@ -1,34 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2002-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimClosedLaneDef.cpp -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Sept 2002 -/// -// ------------------- -/****************************************************************************/ -#include - -#include -#include "NIVissimClosedLaneDef.h" - - -NIVissimClosedLaneDef::NIVissimClosedLaneDef(const std::vector& assignedVehicles) - : myAssignedVehicles(assignedVehicles) {} - - -NIVissimClosedLaneDef::~NIVissimClosedLaneDef() {} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimClosedLaneDef.h b/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimClosedLaneDef.h deleted file mode 100644 index 9a627981a..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimClosedLaneDef.h +++ /dev/null @@ -1,38 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2002-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimClosedLaneDef.h -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Sept 2002 -/// -// ------------------- -/****************************************************************************/ -#pragma once -#include - - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * - */ -class NIVissimClosedLaneDef { -public: - NIVissimClosedLaneDef(const std::vector& assignedVehicles); - ~NIVissimClosedLaneDef(); -private: - std::vector myAssignedVehicles; -}; diff --git a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimClosedLanesVector.h b/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimClosedLanesVector.h deleted file mode 100644 index 6b246b8df..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimClosedLanesVector.h +++ /dev/null @@ -1,27 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimClosedLanesVector.h -/// @author Daniel Krajzewicz -/// @date Sept 2002 -/// -// ------------------- -/****************************************************************************/ -#pragma once -#include - - -#include -#include "NIVissimClosedLaneDef.h" - -typedef std::vector NIVissimClosedLanesVector; diff --git a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimClosures.cpp b/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimClosures.cpp deleted file mode 100644 index d1f0c99f2..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimClosures.cpp +++ /dev/null @@ -1,85 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2002-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimClosures.cpp -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Sept 2002 -/// -// ------------------- -/****************************************************************************/ -#include - -#include -#include -#include "NIVissimClosures.h" - - -NIVissimClosures::DictType NIVissimClosures::myDict; - -NIVissimClosures::NIVissimClosures(const std::string& id, - int from_node, int to_node, - std::vector& overEdges) - : myID(id), myFromNode(from_node), myToNode(to_node), - myOverEdges(overEdges) {} - - -NIVissimClosures::~NIVissimClosures() {} - - -bool -NIVissimClosures::dictionary(const std::string& id, - int from_node, int to_node, - std::vector& overEdges) { - NIVissimClosures* o = new NIVissimClosures(id, from_node, to_node, - overEdges); - if (!dictionary(id, o)) { - delete o; - return false; - } - return true; -} - - -bool -NIVissimClosures::dictionary(const std::string& name, NIVissimClosures* o) { - DictType::iterator i = myDict.find(name); - if (i == myDict.end()) { - myDict[name] = o; - return true; - } - return false; -} - - -NIVissimClosures* -NIVissimClosures::dictionary(const std::string& name) { - DictType::iterator i = myDict.find(name); - if (i == myDict.end()) { - return nullptr; - } - return (*i).second; -} - - - -void -NIVissimClosures::clearDict() { - for (DictType::iterator i = myDict.begin(); i != myDict.end(); i++) { - delete (*i).second; - } - myDict.clear(); -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimClosures.h b/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimClosures.h deleted file mode 100644 index e741ac187..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimClosures.h +++ /dev/null @@ -1,60 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2002-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimClosures.h -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Sept 2002 -/// -// ------------------- -/****************************************************************************/ -#pragma once -#include - -#include -#include - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * - */ -class NIVissimClosures { -public: - NIVissimClosures(const std::string& id, - int from_node, int to_node, - std::vector& overEdges); - ~NIVissimClosures(); - static bool dictionary(const std::string& id, - int from_node, int to_node, std::vector& overEdges); - static bool dictionary(const std::string& name, NIVissimClosures* o); - static NIVissimClosures* dictionary(const std::string& name); - static void clearDict(); -private: - typedef std::map DictType; - static DictType myDict; - const std::string myID; - int myFromNode, myToNode; - std::vector myOverEdges; - -private: - /// @brief invalidated copy constructor - NIVissimClosures(const NIVissimClosures& s); - - /// @brief invalidated assignment operator - NIVissimClosures& operator=(const NIVissimClosures& s); - - -}; diff --git a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimConflictArea.cpp b/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimConflictArea.cpp deleted file mode 100644 index bf337bc4d..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimConflictArea.cpp +++ /dev/null @@ -1,152 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimConflictArea.cpp -/// @author Lukas Grohmann -/// @date Aug 2015 -/// -// A temporary storage for conflict areas imported from Vissim -/****************************************************************************/ -#include - -#include -#include -#include -#include -#include -#include "NIVissimConflictArea.h" -#include "NIVissimConnection.h" -#include -#include -#include - - -// =========================================================================== -// static members -// =========================================================================== -NIVissimConflictArea::DictType NIVissimConflictArea::myDict; - - -// =========================================================================== -// method definitions -// =========================================================================== -NIVissimConflictArea::NIVissimConflictArea(int id, - const std::string& link1, - const std::string& link2, - const std::string& status) - : myConflictID(id), myFirstLink(link1), mySecondLink(link2), myStatus(status) { -} - - -NIVissimConflictArea::~NIVissimConflictArea() {} - - - - -bool -NIVissimConflictArea::dictionary(int id, const std::string& link1, - const std::string& link2, - const std::string& status) { - NIVissimConflictArea* ca = new NIVissimConflictArea(id, link1, link2, status); - if (!dictionary(id, ca)) { - delete ca; - return false; - } - return true; -} - - - -bool -NIVissimConflictArea::dictionary(int id, NIVissimConflictArea* ca) { - DictType::iterator i = myDict.find(id); - if (i == myDict.end()) { - myDict[id] = ca; - return true; - } - return false; -} - - - -NIVissimConflictArea* -NIVissimConflictArea::dictionary(int id) { - DictType::iterator i = myDict.find(id); - if (i == myDict.end()) { - return nullptr; - } - return (*i).second; -} - - - -NIVissimConflictArea* -NIVissimConflictArea::dict_findByLinks(const std::string& link1, - const std::string& link2) { - for (DictType::iterator i = myDict.begin(); i != myDict.end(); i++) { - if (((*i).second->myFirstLink == link1) && - ((*i).second->mySecondLink == link2)) { - return (*i).second; - } - } - return nullptr; -} - - -void -NIVissimConflictArea::clearDict() { - for (DictType::iterator i = myDict.begin(); i != myDict.end(); i++) { - delete (*i).second; - } - myDict.clear(); -} - - -void -NIVissimConflictArea::setPriorityRegulation(NBEdgeCont& ec) { - std::map::iterator it; - for (it = myDict.begin(); it != myDict.end(); it++) { - NIVissimConflictArea* const conflictArea = it->second; - NIVissimConnection* const firstLink = NIVissimConnection::dictionary(StringUtils::toInt(conflictArea->getFirstLink())); - NIVissimConnection* const secondLink = NIVissimConnection::dictionary(StringUtils::toInt(conflictArea->getSecondLink())); - if (firstLink == nullptr || secondLink == nullptr) { - continue; - } - // status == "TWOYIELDSONE" - NIVissimConnection* priority_conn = firstLink; - NIVissimConnection* subordinate_conn = secondLink; - if (conflictArea->getStatus() == "ONEYIELDSTWO") { - priority_conn = secondLink; - subordinate_conn = firstLink; - } - const std::string mayDriveFrom_id = toString(priority_conn->getFromEdgeID()); - const std::string mayDriveTo_id = toString(priority_conn->getToEdgeID()); - const std::string mustStopFrom_id = toString(subordinate_conn->getFromEdgeID()); - const std::string mustStopTo_id = toString(subordinate_conn->getToEdgeID()); - - NBEdge* const mayDriveFrom = ec.retrievePossiblySplit(mayDriveFrom_id, true); - NBEdge* const mayDriveTo = ec.retrievePossiblySplit(mayDriveTo_id, false); - NBEdge* const mustStopFrom = ec.retrievePossiblySplit(mustStopFrom_id, true); - NBEdge* const mustStopTo = ec.retrievePossiblySplit(mustStopTo_id, false); - - if (mayDriveFrom != nullptr && mayDriveTo != nullptr && mustStopFrom != nullptr && mustStopTo != nullptr) { - NBNode* node = mayDriveFrom->getToNode(); - node->addSortedLinkFoes( - NBConnection(mayDriveFrom, mayDriveTo), - NBConnection(mustStopFrom, mustStopTo)); - } - } -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimConflictArea.h b/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimConflictArea.h deleted file mode 100644 index 30bfede45..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimConflictArea.h +++ /dev/null @@ -1,126 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2002-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimConflictArea.h -/// @author Lukas Grohmann -/// @date Aug 2015 -/// -// ------------------- -/****************************************************************************/ -#pragma once -#include - - -#include -#include -#include -#include "NIVissimConnection.h" -#include -#include -#include - - -// =========================================================================== -// class declarations -// =========================================================================== - - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NIVissimConflictArea - * @brief A temporary storage for conflict areas imported from Vissim - */ -class NIVissimConflictArea { -public: - /// Constructor - NIVissimConflictArea(int id, const std::string& link1, - const std::string& link2, - const std::string& status); - - - /// Destructor - ~NIVissimConflictArea(); - -public: - /** @brief Adds the described item to the dictionary - Builds the conflict area first */ - static bool dictionary(int id, const std::string& link1, - const std::string& link2, const std::string& status); - - /// Adds the conflict area to the dictionary - static bool dictionary(int id, NIVissimConflictArea* ca); - - /// Returns the named dictionary - static NIVissimConflictArea* dictionary(int id); - - /// Returns the conflict area from the dictionary, which defines - /// the priority rule of the two given links - static NIVissimConflictArea* dict_findByLinks(const std::string& link1, - const std::string& link2); - - /// Clears the dictionary - static void clearDict(); - - /// Returns the dictionary including all conflict areas - static std::map getConflictAreas() { - return myDict; - } - - /// Returns the ID of the conflic area - int getID() { - return myConflictID; - } - - /// Returns the first link of the conflic area - std::string getFirstLink() { - return myFirstLink; - } - - /// Returns the second link of the conflic area - std::string getSecondLink() { - return mySecondLink; - } - - /// Returns the priority regulation of the conflic area - std::string getStatus() { - return myStatus; - } - - /// Sets the priority regulation according to the VISSIM conflict area data - static void setPriorityRegulation(NBEdgeCont& ec); - - - -private: - /// The id of the conflict area - int myConflictID; - - /// The first link of the conflict area - std::string myFirstLink; - - /// The second link of the conflict area - std::string mySecondLink; - - /// The priority regulation of the conflict area - std::string myStatus; - -private: - /// @brief Definition of the dictionary type - typedef std::map DictType; - - /// @brief The dictionary - static DictType myDict; -}; diff --git a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimConnection.cpp b/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimConnection.cpp deleted file mode 100644 index 2fd86bae8..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimConnection.cpp +++ /dev/null @@ -1,319 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimConnection.cpp -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Sascha Krieg -/// @author Michael Behrisch -/// @author Laura Bieker -/// @date Sept 2002 -/// -// ------------------- -/****************************************************************************/ -#include - -#include -#include -#include -#include -#include -#include -#include -#include "NIVissimExtendedEdgePoint.h" -#include -#include -#include -#include -#include -#include -#include "NIVissimEdge.h" -#include "NIVissimClosedLanesVector.h" -#include "NIVissimNodeDef.h" -#include "NIVissimConnection.h" -#include - - -// =========================================================================== -// static members -// =========================================================================== -NIVissimConnection::DictType NIVissimConnection::myDict; -int NIVissimConnection::myMaxID; - - -// =========================================================================== -// method definitions -// =========================================================================== -NIVissimConnection::NIVissimConnection(int id, - const std::string& name, const NIVissimExtendedEdgePoint& from_def, - const NIVissimExtendedEdgePoint& to_def, - const PositionVector& geom, - const std::vector& assignedVehicles, const NIVissimClosedLanesVector& clv) - : NIVissimAbstractEdge(id, geom), - myName(name), myFromDef(from_def), myToDef(to_def), - myAssignedVehicles(assignedVehicles), myClosedLanes(clv) {} - - -NIVissimConnection::~NIVissimConnection() { - for (NIVissimClosedLanesVector::iterator i = myClosedLanes.begin(); i != myClosedLanes.end(); i++) { - delete (*i); - } - myClosedLanes.clear(); -} - - -bool -NIVissimConnection::dictionary(int id, NIVissimConnection* o) { - DictType::iterator i = myDict.find(id); - if (i == myDict.end()) { - myDict[id] = o; - return true; - } - return false; -} - - - -NIVissimConnection* -NIVissimConnection::dictionary(int id) { - DictType::iterator i = myDict.find(id); - if (i == myDict.end()) { - return nullptr; - } - return (*i).second; -} - - -void -NIVissimConnection::buildNodeClusters() { - for (DictType::iterator i = myDict.begin(); i != myDict.end(); i++) { - NIVissimConnection* e = (*i).second; - if (!e->clustered()) { - assert(e->myBoundary != 0 && e->myBoundary->xmax() > e->myBoundary->xmin()); - std::vector connections = - NIVissimConnection::getWithin(*(e->myBoundary)); - NIVissimNodeCluster::dictionary(-1, -1, connections, - std::vector(), true); // 19.5.!!! should be on a single edge - } - } -} - - - - - -std::vector -NIVissimConnection::getWithin(const AbstractPoly& poly) { - std::vector ret; - for (DictType::iterator i = myDict.begin(); i != myDict.end(); i++) { - if ((*i).second->crosses(poly)) { - ret.push_back((*i).second->myID); - } - } - return ret; -} - - -void -NIVissimConnection::computeBounding() { - Boundary* bound = new Boundary(); - bound->add(myFromDef.getGeomPosition()); - bound->add(myToDef.getGeomPosition()); - assert(myBoundary == 0); - myBoundary = bound; -} - - -std::vector -NIVissimConnection::getForEdge(int edgeid, bool /*omitNodeAssigned*/) { - std::vector ret; - for (DictType::iterator i = myDict.begin(); i != myDict.end(); i++) { - int connID = (*i).first; - if ((*i).second->myFromDef.getEdgeID() == edgeid - || - (*i).second->myToDef.getEdgeID() == edgeid) { - if (!(*i).second->hasNodeCluster()) { - ret.push_back(connID); - } - } - } - return ret; -} - - -int -NIVissimConnection::getFromEdgeID() const { - return myFromDef.getEdgeID(); -} - - -int -NIVissimConnection::getToEdgeID() const { - return myToDef.getEdgeID(); -} - - -double -NIVissimConnection::getFromPosition() const { - return myFromDef.getPosition(); -} - - -double -NIVissimConnection::getToPosition() const { - return myToDef.getPosition(); -} - - -Position -NIVissimConnection::getFromGeomPosition() const { - return myFromDef.getGeomPosition(); -} - - - -Position -NIVissimConnection::getToGeomPosition() const { - return myToDef.getGeomPosition(); -} - - -void -NIVissimConnection::setNodeCluster(int nodeid) { - assert(myNode == -1); - myNode = nodeid; -} - - -void -NIVissimConnection::buildGeom() { - if (myGeom.size() > 0) { - return; - } - myGeom.push_back(myFromDef.getGeomPosition()); - myGeom.push_back(myToDef.getGeomPosition()); -} - - -int -NIVissimConnection::buildEdgeConnections(NBEdgeCont& ec) { - int unsetConnections = 0; - // try to determine the connected edges - NBEdge* fromEdge = nullptr; - NBEdge* toEdge = nullptr; - NIVissimEdge* vissimFrom = NIVissimEdge::dictionary(getFromEdgeID()); - if (vissimFrom->wasWithinAJunction()) { - // this edge was not built, try to get one that approaches it - vissimFrom = vissimFrom->getBestIncoming(); - if (vissimFrom != nullptr) { - fromEdge = ec.retrievePossiblySplit(toString(vissimFrom->getID()), toString(getFromEdgeID()), true); - } - } else { - // this edge was built, try to get the proper part - fromEdge = ec.retrievePossiblySplit(toString(getFromEdgeID()), toString(getToEdgeID()), true); - } - NIVissimEdge* vissimTo = NIVissimEdge::dictionary(getToEdgeID()); - if (vissimTo->wasWithinAJunction()) { - vissimTo = vissimTo->getBestOutgoing(); - if (vissimTo != nullptr) { - toEdge = ec.retrievePossiblySplit(toString(vissimTo->getID()), toString(getToEdgeID()), true); - } - } else { - toEdge = ec.retrievePossiblySplit(toString(getToEdgeID()), toString(getFromEdgeID()), false); - } - - // try to get the edges the current connection connects - /* - NBEdge *fromEdge = ec.retrievePossiblySplit(toString(getFromEdgeID()), toString(getToEdgeID()), true); - NBEdge *toEdge = ec.retrievePossiblySplit(toString(getToEdgeID()), toString(getFromEdgeID()), false); - */ - if (fromEdge == nullptr || toEdge == nullptr) { - WRITE_WARNING("Could not build connection between '" + toString(getFromEdgeID()) + "' and '" + toString(getToEdgeID()) + "'."); - return 1; // !!! actually not 1 - } - recheckLanes(fromEdge, toEdge); - const std::vector& fromLanes = getFromLanes(); - const std::vector& toLanes = getToLanes(); - if (fromLanes.size() != toLanes.size()) { - WRITE_WARNING("Lane sizes differ for connection '" + toString(getID()) + "'."); - } else { - for (int index = 0; index < (int)fromLanes.size(); ++index) { - if (fromEdge->getNumLanes() <= fromLanes[index]) { - WRITE_WARNING("Could not set connection between '" + fromEdge->getID() + "_" + toString(fromLanes[index]) + "' and '" + toEdge->getID() + "_" + toString(toLanes[index]) + "'."); - ++unsetConnections; - } else if (!fromEdge->addLane2LaneConnection(fromLanes[index], toEdge, toLanes[index], NBEdge::Lane2LaneInfoType::VALIDATED, true)) { - WRITE_WARNING("Could not set connection between '" + fromEdge->getID() + "_" + toString(fromLanes[index]) + "' and '" + toEdge->getID() + "_" + toString(toLanes[index]) + "'."); - ++unsetConnections; - } - } - } - return unsetConnections; -} - - -void -NIVissimConnection::dict_buildNBEdgeConnections(NBEdgeCont& ec) { - int unsetConnections = 0; - // go through connections - for (DictType::iterator i = myDict.begin(); i != myDict.end(); i++) { - unsetConnections += (*i).second->buildEdgeConnections(ec); - } - if (unsetConnections != 0) { - WRITE_WARNING(toString(unsetConnections) + " of " + toString((int)myDict.size()) + " connections could not be assigned."); - } -} - - -const std::vector& -NIVissimConnection::getFromLanes() const { - return myFromDef.getLanes(); -} - - -const std::vector& -NIVissimConnection::getToLanes() const { - return myToDef.getLanes(); -} - - -void -NIVissimConnection::recheckLanes(const NBEdge* const fromEdge, const NBEdge* const toEdge) { - myFromDef.recheckLanes(fromEdge); - myToDef.recheckLanes(toEdge); -} - - -const Boundary& -NIVissimConnection::getBoundingBox() const { - assert(myBoundary != 0 && myBoundary->xmax() >= myBoundary->xmin()); - return *myBoundary; -} - - -void -NIVissimConnection::dict_assignToEdges() { - for (DictType::iterator i = myDict.begin(); i != myDict.end(); i++) { - NIVissimConnection* c = (*i).second; - NIVissimEdge::dictionary(c->getFromEdgeID())->addOutgoingConnection((*i).first); - NIVissimEdge::dictionary(c->getToEdgeID())->addIncomingConnection((*i).first); - } -} - - -int -NIVissimConnection::getMaxID() { - return myMaxID; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimConnection.h b/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimConnection.h deleted file mode 100644 index 36a459e37..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimConnection.h +++ /dev/null @@ -1,109 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimConnection.h -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Sept 2002 -/// -// ------------------- -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include "NIVissimExtendedEdgePoint.h" -#include -#include -#include "NIVissimAbstractEdge.h" -#include "NIVissimClosedLanesVector.h" -#include "NIVissimBoundedClusterObject.h" - - -// =========================================================================== -// class declarations -// =========================================================================== -class NBEdgeCont; - - -// =========================================================================== -// class definitions -// =========================================================================== -class NIVissimConnection - : public NIVissimBoundedClusterObject, - public NIVissimAbstractEdge { -public: - /* enum Direction { - NIVC_DIR_RIGHT, - NIVC_DIR_LEFT, - NIVC_DIR_ALL - }; */ - - NIVissimConnection(int id, const std::string& name, - const NIVissimExtendedEdgePoint& from_def, - const NIVissimExtendedEdgePoint& to_def, - const PositionVector& geom, - const std::vector& assignedVehicles, - const NIVissimClosedLanesVector& clv); - virtual ~NIVissimConnection(); - void computeBounding(); - int getFromEdgeID() const; - int getToEdgeID() const; - double getFromPosition() const; - double getToPosition() const; - Position getFromGeomPosition() const; - Position getToGeomPosition() const; - void setNodeCluster(int nodeid); - const Boundary& getBoundingBox() const; - - int buildEdgeConnections(NBEdgeCont& ec); - - void buildGeom(); - - - /** @brief Resets lane numbers if all lanes shall be used - * - * Calls "NIVissimExtendedEdgePoint::recheckLanes" for both used - * edges. - * - * @param[in] The built from-edge - * @param[in] The built to-edge - */ - void recheckLanes(const NBEdge* const fromEdge, const NBEdge* const toEdge); - -public: - const std::vector& getFromLanes() const; - const std::vector& getToLanes() const; - - - - static bool dictionary(int id, NIVissimConnection* o); - static NIVissimConnection* dictionary(int id); - static std::vector getWithin(const AbstractPoly& poly); - static void buildNodeClusters(); - static std::vector getForEdge(int edgeid, bool omitNodeAssigned = true); - static void dict_buildNBEdgeConnections(NBEdgeCont& ec); - static void dict_assignToEdges(); - static int getMaxID(); - -private: - std::string myName; - NIVissimExtendedEdgePoint myFromDef, myToDef; - std::vector myAssignedVehicles; - NIVissimClosedLanesVector myClosedLanes; -private: - typedef std::map DictType; - static DictType myDict; - static int myMaxID; -}; diff --git a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimConnectionCluster.cpp b/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimConnectionCluster.cpp deleted file mode 100644 index 6e9356150..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimConnectionCluster.cpp +++ /dev/null @@ -1,784 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimConnectionCluster.cpp -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date Sept 2002 -/// -// ------------------- -/****************************************************************************/ -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "NIVissimConnection.h" -#include "NIVissimDisturbance.h" -#include "NIVissimNodeCluster.h" -#include "NIVissimNodeDef.h" -#include "NIVissimEdge.h" -#include "NIVissimTL.h" -#include "NIVissimConnectionCluster.h" - - -// =========================================================================== -// static members -// =========================================================================== -NIVissimConnectionCluster::ContType NIVissimConnectionCluster::myClusters; -int NIVissimConnectionCluster::myFirstFreeID = 100000; -int NIVissimConnectionCluster::myStaticBlaID = 0; - - - -// =========================================================================== -// method definitions -// =========================================================================== -// --------------------------------------------------------------------------- -// NIVissimConnectionCluster::NodeSubCluster - methods -// --------------------------------------------------------------------------- -NIVissimConnectionCluster::NodeSubCluster::NodeSubCluster(NIVissimConnection* c) { - add(c); -} - - -NIVissimConnectionCluster::NodeSubCluster::~NodeSubCluster() {} - - -void -NIVissimConnectionCluster::NodeSubCluster::add(NIVissimConnection* c) { - myBoundary.add(c->getBoundingBox()); - myConnections.push_back(c); -} - - -void -NIVissimConnectionCluster::NodeSubCluster::add(const NIVissimConnectionCluster::NodeSubCluster& c) { - for (ConnectionCont::const_iterator i = c.myConnections.begin(); i != c.myConnections.end(); i++) { - add(*i); - } -} - - -int -NIVissimConnectionCluster::NodeSubCluster::size() const { - return (int)myConnections.size(); -} - - -std::vector -NIVissimConnectionCluster::NodeSubCluster::getConnectionIDs() const { - std::vector ret; - int id = NIVissimConnectionCluster::getNextFreeNodeID(); - for (ConnectionCont::const_iterator i = myConnections.begin(); i != myConnections.end(); i++) { - ret.push_back((*i)->getID()); - (*i)->setNodeCluster(id); - } - return ret; -} - - -bool -NIVissimConnectionCluster::NodeSubCluster::overlapsWith( - const NIVissimConnectionCluster::NodeSubCluster& c, - double offset) { - assert(myBoundary.xmax() >= myBoundary.xmin()); - assert(c.myBoundary.xmax() >= c.myBoundary.xmin()); - return myBoundary.overlapsWith(c.myBoundary, offset); -} - - - -// --------------------------------------------------------------------------- -// NIVissimConnectionCluster - methods -// --------------------------------------------------------------------------- -NIVissimConnectionCluster::NIVissimConnectionCluster( - const std::vector& connections, int nodeCluster, int edgeid) - : myConnections(connections), myNodeCluster(nodeCluster), - myBlaID(myStaticBlaID++) { - recomputeBoundary(); - myClusters.push_back(this); - assert(edgeid > 0); - if (edgeid >= 0) { - myEdges.push_back(edgeid); - } - // add information about incoming and outgoing edges - for (std::vector::const_iterator i = connections.begin(); i != connections.end(); i++) { - NIVissimConnection* c = NIVissimConnection::dictionary(*i); - assert(c != 0); - myOutgoingEdges.push_back(c->getToEdgeID()); - myIncomingEdges.push_back(c->getFromEdgeID()); - assert(c->getFromEdgeID() == edgeid || c->getToEdgeID() == edgeid); - } - VectorHelper::removeDouble(myIncomingEdges); - VectorHelper::removeDouble(myOutgoingEdges); -} - - -NIVissimConnectionCluster::NIVissimConnectionCluster( - const std::vector& connections, const Boundary& boundary, - int nodeCluster, const std::vector& edges) - : myConnections(connections), myBoundary(boundary), - myNodeCluster(nodeCluster), myEdges(edges) { - myClusters.push_back(this); - recomputeBoundary(); - assert(myBoundary.xmax() >= myBoundary.xmin()); - // add information about incoming and outgoing edges - for (std::vector::const_iterator i = connections.begin(); i != connections.end(); i++) { - NIVissimConnection* c = NIVissimConnection::dictionary(*i); - assert(c != 0); - myOutgoingEdges.push_back(c->getToEdgeID()); - myIncomingEdges.push_back(c->getFromEdgeID()); - assert(find(edges.begin(), edges.end(), c->getFromEdgeID()) != edges.end() - || - std::find(edges.begin(), edges.end(), c->getToEdgeID()) != edges.end()); - } - VectorHelper::removeDouble(myIncomingEdges); - VectorHelper::removeDouble(myOutgoingEdges); -} - - -NIVissimConnectionCluster::~NIVissimConnectionCluster() {} - - - -int -NIVissimConnectionCluster::getNextFreeNodeID() { - return myFirstFreeID++; -} - - -bool -NIVissimConnectionCluster::overlapsWith(NIVissimConnectionCluster* c, - double offset) const { - assert(myBoundary.xmax() >= myBoundary.xmin()); - assert(c->myBoundary.xmax() >= c->myBoundary.xmin()); - return c->myBoundary.overlapsWith(myBoundary, offset); -} - - -void -NIVissimConnectionCluster::add(NIVissimConnectionCluster* c) { - assert(myBoundary.xmax() >= myBoundary.xmin()); - assert(c->myBoundary.xmax() >= c->myBoundary.xmin()); - myBoundary.add(c->myBoundary); - for (std::vector::iterator i = c->myConnections.begin(); i != c->myConnections.end(); i++) { - myConnections.push_back(*i); - } - VectorHelper::removeDouble(myConnections); - assert(myNodeCluster == -1 || c->myNodeCluster == -1); - if (myNodeCluster == -1) { - myNodeCluster = c->myNodeCluster; - } - // inform edges about merging - // !!! merge should be done within one method - for (std::vector::iterator j = c->myEdges.begin(); j != c->myEdges.end(); j++) { - NIVissimEdge::dictionary(*j)->mergedInto(c, this); - } - copy(c->myEdges.begin(), c->myEdges.end(), back_inserter(myEdges)); - copy(c->myIncomingEdges.begin(), c->myIncomingEdges.end(), - back_inserter(myIncomingEdges)); - copy(c->myOutgoingEdges.begin(), c->myOutgoingEdges.end(), - back_inserter(myOutgoingEdges)); - VectorHelper::removeDouble(myEdges); - VectorHelper::removeDouble(myIncomingEdges); - VectorHelper::removeDouble(myOutgoingEdges); -} - - - -void -NIVissimConnectionCluster::joinBySameEdges(double offset) { - // !!! ... - // Further, we try to omit joining of overlaping nodes. This is done by holding - // the lists of incoming and outgoing edges and incrementally building the nodes - // regarding this information - std::vector joinAble; - int pos = 0; - ContType::iterator i = myClusters.begin(); - // step1 - faster but no complete - while (i != myClusters.end()) { - joinAble.clear(); - ContType::iterator j = i + 1; - - // check whether every combination has been processed - while (j != myClusters.end()) { - // check whether the current clusters overlap - if ((*i)->joinable(*j, offset)) { - joinAble.push_back(*j); - } - j++; - } - for (std::vector::iterator k = joinAble.begin(); - k != joinAble.end(); k++) { - // add the overlaping cluster - (*i)->add(*k); - // erase the overlaping cluster - delete *k; - myClusters.erase(find(myClusters.begin(), myClusters.end(), *k)); - } - // - if (joinAble.size() > 0) { - i = myClusters.begin() + pos; - // clear temporary storages - joinAble.clear(); - } else { - i++; - pos++; - } - } - // - pos = 0; - i = myClusters.begin(); - while (i != myClusters.end()) { - ContType::iterator j = i + 1; - // check whether every combination has been processed - while (j != myClusters.end()) { - // check whether the current clusters overlap - if ((*i)->joinable(*j, offset)) { - joinAble.push_back(*j); - } - j++; - } - for (std::vector::iterator k = joinAble.begin(); - k != joinAble.end(); k++) { - // add the overlaping cluster - (*i)->add(*k); - // erase the overlaping cluster - delete *k; - myClusters.erase(find(myClusters.begin(), myClusters.end(), *k)); - } - // - if (joinAble.size() > 0) { - i = myClusters.begin(); - // clear temporary storages - joinAble.clear(); - pos = 0; - } else { - i++; - pos++; - } - } - // check for weak district connections - // (junctions made up by district connections, where prohibitions are not - // modelled properly) - pos = 0; - i = myClusters.begin(); - while (i != myClusters.end()) { - ContType::iterator j = i + 1; - // check whether every combination has been processed - while (j != myClusters.end()) { - // check whether the current clusters overlap - if ((*i)->isWeakDistrictConnRealisation(*j)) { - joinAble.push_back(*j); - } - j++; - } - for (std::vector::iterator k = joinAble.begin(); - k != joinAble.end(); k++) { - // add the overlaping cluster - (*i)->add(*k); - // erase the overlaping cluster - delete *k; - myClusters.erase(find(myClusters.begin(), myClusters.end(), *k)); - } - // - if (joinAble.size() > 0) { - i = myClusters.begin(); - // clear temporary storages - joinAble.clear(); - pos = 0; - } else { - i++; - pos++; - } - } -} - - -bool -NIVissimConnectionCluster::joinable(NIVissimConnectionCluster* c2, double offset) { - // join clusters which have at least one connection in common - if (VectorHelper::subSetExists(myConnections, c2->myConnections)) { - return true; - } - - // connections shall overlap otherwise - if (!overlapsWith(c2, offset)) { - return false; - } - - // at least one of the clusters shall not be assigned to a node in previous (!!!??) - if (hasNodeCluster() && c2->hasNodeCluster()) { - return false; - } - - // join clusters which where connections do disturb each other - if (VectorHelper::subSetExists(c2->getDisturbanceParticipators(), myConnections) - || - VectorHelper::subSetExists(getDisturbanceParticipators(), c2->myConnections)) { - - return true; - } - - - // join clusters which do share the same incoming or outgoing edges (not mutually) - std::vector extendedOutgoing1; - std::vector extendedIncoming1; - std::vector extendedOutgoing2; - std::vector extendedIncoming2; - if (myIncomingEdges.size() > 1 || c2->myIncomingEdges.size() > 1) { - extendedOutgoing1 = - extendByToTreatAsSame(myOutgoingEdges, myIncomingEdges); - extendedIncoming1 = - extendByToTreatAsSame(myIncomingEdges, myOutgoingEdges); - extendedOutgoing2 = - extendByToTreatAsSame(c2->myOutgoingEdges, c2->myIncomingEdges); - extendedIncoming2 = - extendByToTreatAsSame(c2->myIncomingEdges, c2->myOutgoingEdges); - } else { - extendedOutgoing1 = myIncomingEdges; - extendedIncoming1 = myOutgoingEdges; - extendedOutgoing2 = c2->myIncomingEdges; - extendedIncoming2 = c2->myOutgoingEdges; - } - - if (VectorHelper::subSetExists(extendedOutgoing1, extendedOutgoing2) - || - VectorHelper::subSetExists(extendedIncoming1, extendedIncoming2) - ) { - return true; - } - return false; -} - - -bool -NIVissimConnectionCluster::isWeakDistrictConnRealisation(NIVissimConnectionCluster* c2) { - if ((myIncomingEdges.size() == 1 && myOutgoingEdges.size() == 1)) { - return false; - } - if ((c2->myIncomingEdges.size() == 1 && c2->myOutgoingEdges.size() == 1)) { - return false; - } - - // ok, may be the other way round - if (myIncomingEdges.size() == 1 && c2->myOutgoingEdges.size() == 1) { - return c2->isWeakDistrictConnRealisation(this); - } - // connections must cross - bool crosses = false; - for (std::vector::const_iterator j1 = myConnections.begin(); j1 != myConnections.end() && !crosses; j1++) { - NIVissimConnection* c1 = NIVissimConnection::dictionary(*j1); - const PositionVector& g1 = c1->getGeometry(); - for (std::vector::const_iterator j2 = c2->myConnections.begin(); j2 != c2->myConnections.end() && !crosses; j2++) { - NIVissimConnection* c2 = NIVissimConnection::dictionary(*j2); - const PositionVector& g2 = c2->getGeometry(); - if (g1.intersects(g2)) { - crosses = true; - } - } - } - if (!crosses) { - return false; - } - // ok, check for connection - if (myOutgoingEdges.size() != 1 || c2->myIncomingEdges.size() != 1) { - return false; - } - // check whether the connection is bidirectional - NIVissimEdge* oe = NIVissimEdge::dictionary(myOutgoingEdges[0]); - NIVissimEdge* ie = NIVissimEdge::dictionary(c2->myIncomingEdges[0]); - if (oe == nullptr || ie == nullptr) { - return false; - } - return fabs(GeomHelper::angleDiff(oe->getGeometry().beginEndAngle(), ie->getGeometry().beginEndAngle())) < DEG2RAD(5); -} - - -bool -NIVissimConnectionCluster::liesOnSameEdgesEnd(NIVissimConnectionCluster* cc2) { - // - for (std::vector::iterator i = myConnections.begin(); i != myConnections.end(); i++) { - NIVissimConnection* c1 = NIVissimConnection::dictionary(*i); - for (std::vector::iterator j = cc2->myConnections.begin(); j != cc2->myConnections.end(); j++) { - NIVissimConnection* c2 = NIVissimConnection::dictionary(*j); - if (c1->getFromEdgeID() == c2->getFromEdgeID()) { - NIVissimEdge* e = NIVissimEdge::dictionary(c1->getFromEdgeID()); - const PositionVector& g = e->getGeometry(); - double pos1 = GeomHelper::nearest_offset_on_line_to_point2D( - g.front(), g.back(), c1->getBoundary().getCenter()); - double pos2 = GeomHelper::nearest_offset_on_line_to_point2D( - g.front(), g.back(), c2->getBoundary().getCenter()); - if (pos1 <= 5.0 && pos2 <= 5.0) { - return true; - } - } - if (c1->getToEdgeID() == c2->getToEdgeID()) { - NIVissimEdge* e = NIVissimEdge::dictionary(c1->getFromEdgeID()); - const PositionVector& g = e->getGeometry(); - double pos1 = GeomHelper::nearest_offset_on_line_to_point2D( - g.front(), g.back(), c1->getBoundary().getCenter()); - double pos2 = GeomHelper::nearest_offset_on_line_to_point2D( - g.front(), g.back(), c2->getBoundary().getCenter()); - if (pos1 >= g.length() - 5.0 && pos2 >= g.length() - 5.0) { - return true; - } - } - } - } - return false; -} - - -std::vector -NIVissimConnectionCluster::extendByToTreatAsSame(const std::vector& iv1, - const std::vector& iv2) const { - std::vector ret(iv1); - for (std::vector::const_iterator i = iv1.begin(); i != iv1.end(); i++) { - NIVissimEdge* e = NIVissimEdge::dictionary(*i); - const std::vector treatAsSame = e->getToTreatAsSame(); - for (std::vector::const_iterator j = treatAsSame.begin(); j != treatAsSame.end(); j++) { - if (find(iv2.begin(), iv2.end(), (*j)->getID()) == iv2.end()) { - ret.push_back((*j)->getID()); - } - } - } - return ret; -} - -std::vector -NIVissimConnectionCluster::getDisturbanceParticipators() { - std::vector ret; - for (std::vector::iterator i = myConnections.begin(); i != myConnections.end(); i++) { - NIVissimConnection* c = NIVissimConnection::dictionary(*i); - const std::vector& disturbances = c->getDisturbances(); - for (std::vector::const_iterator j = disturbances.begin(); j != disturbances.end(); j++) { - NIVissimDisturbance* d = NIVissimDisturbance::dictionary(*j); - ret.push_back(d->getEdgeID()); - ret.push_back(d->getDisturbanceID()); - } - } - return ret; -} - - -void -NIVissimConnectionCluster::buildNodeClusters() { - for (ContType::iterator i = myClusters.begin(); i != myClusters.end(); i++) { - std::vector disturbances; - std::vector tls; - std::vector nodes; - int tlsid = -1; - int nodeid = -1; - if ((*i)->myConnections.size() > 0) { - (*i)->recomputeBoundary(); - disturbances = NIVissimDisturbance::getWithin((*i)->myBoundary); - } - nodes = (*i)->myNodes;//NIVissimTL::getWithin((*i)->myBoundary, 5.0); - if (nodes.size() > 1) { - WRITE_WARNING("NIVissimConnectionCluster:More than a single node"); - // throw 1; // !!! eigentlich sollte hier nur eine Ampelanlage sein - } - if (nodes.size() > 0) { - nodeid = nodes[0]; - } - // - // - int id = NIVissimNodeCluster::dictionary( - nodeid, tlsid, (*i)->myConnections, - disturbances, (*i)->myIncomingEdges.size() < 2); - assert((*i)->myNodeCluster == id || (*i)->myNodeCluster < 0); - (*i)->myNodeCluster = id; - } -} - - -void -NIVissimConnectionCluster::_debugOut(std::ostream& into) { - for (ContType::iterator i = myClusters.begin(); i != myClusters.end(); i++) { - std::vector connections = (*i)->myConnections; - for (std::vector::iterator j = connections.begin(); j != connections.end(); j++) { - if (j != connections.begin()) { - into << ", "; - } - into << *j; - } - into << "(" << (*i)->myBoundary << ")" << std::endl; - } - into << "---------------------------" << std::endl; -} - - - -bool -NIVissimConnectionCluster::hasNodeCluster() const { - return myNodeCluster != -1; -} - - -int -NIVissimConnectionCluster::dictSize() { - return (int)myClusters.size(); -} - - -void -NIVissimConnectionCluster::removeConnections(const NodeSubCluster& c) { - for (NodeSubCluster::ConnectionCont::const_iterator i = c.myConnections.begin(); i != c.myConnections.end(); i++) { - NIVissimConnection* conn = *i; - int connid = conn->getID(); - std::vector::iterator j = std::find(myConnections.begin(), myConnections.end(), connid); - if (j != myConnections.end()) { - myConnections.erase(j); - } - } - recomputeBoundary(); -} - - -void -NIVissimConnectionCluster::recomputeBoundary() { - myBoundary = Boundary(); - for (std::vector::iterator i = myConnections.begin(); i != myConnections.end(); i++) { - NIVissimConnection* c = NIVissimConnection::dictionary(*i); - if (c != nullptr) { - myBoundary.add(c->getFromGeomPosition()); - myBoundary.add(c->getToGeomPosition()); - if (c->getGeometry().size() != 0) { - myBoundary.add(c->getGeometry().getBoxBoundary()); - } - } - } - assert(myBoundary.xmax() >= myBoundary.xmin()); -} - - -NBNode* -NIVissimConnectionCluster::getNBNode() const { - return NIVissimNodeCluster::dictionary(myNodeCluster)->getNBNode(); -} - - -bool -NIVissimConnectionCluster::around(const Position& p, double offset) const { - assert(myBoundary.xmax() >= myBoundary.xmin()); - return myBoundary.around(p, offset); -} - - - -void -NIVissimConnectionCluster::recheckEdges() { - assert(myConnections.size() != 0); - // remove the cluster from all edges at first - std::vector::iterator i; - for (i = myEdges.begin(); i != myEdges.end(); i++) { - NIVissimEdge* edge = NIVissimEdge::dictionary(*i); - edge->removeFromConnectionCluster(this); - } - // clear edge information - myEdges.clear(); - // recheck which edges do still participate and add edges - for (i = myConnections.begin(); i != myConnections.end(); i++) { - NIVissimConnection* c = NIVissimConnection::dictionary(*i); - assert(myBoundary.xmax() >= myBoundary.xmin()); - if (myBoundary.around(c->getFromGeomPosition(), 5)) { - myEdges.push_back(c->getFromEdgeID()); - } - assert(myBoundary.xmax() >= myBoundary.xmin()); - if (myBoundary.around(c->getToGeomPosition(), 5)) { - myEdges.push_back(c->getToEdgeID()); - } - } - // connect edges - for (i = myEdges.begin(); i != myEdges.end(); i++) { - NIVissimEdge* edge = NIVissimEdge::dictionary(*i); - edge->addToConnectionCluster(this); - } -} - - -double -NIVissimConnectionCluster::getPositionForEdge(int edgeid) const { - // return the middle of the connections when there are any - if (myConnections.size() != 0) { - double sum = 0; - int part = 0; - std::vector::const_iterator i; - for (i = myConnections.begin(); i != myConnections.end(); i++) { - NIVissimConnection* c = NIVissimConnection::dictionary(*i); - if (c->getFromEdgeID() == edgeid) { - part++; - sum += c->getFromPosition(); - } - if (c->getToEdgeID() == edgeid) { - part++; - sum += c->getToPosition(); - } - } - if (part > 0) { - return sum / (double) part; - } - } - // use the position of the node if possible - if (myNodeCluster >= 0) { - // try to find the nearest point on the edge - // !!! only the main geometry is regarded - NIVissimNodeDef* node = - NIVissimNodeDef::dictionary(myNodeCluster); - if (node != nullptr) { - double pos = node->getEdgePosition(edgeid); - if (pos >= 0) { - return pos; - } - } - /* - double try1 = GeomHelper::nearest_offset_on_line_to_point( - edge->getBegin2D(), edge->getEnd2D(), node->getPos()); - if(try1>=0) { - return try1; - } - // try to use simple distance - double dist1 = - GeomHelper::distance(node->getPos(), edge->getBegin2D()); - double dist2 = - GeomHelper::distance(node->getPos(), edge->getEnd2D()); - return dist1getLength(); - */ - } - // what else? - WRITE_WARNING("NIVissimConnectionCluster: how to get an edge's position?"); - // !!! - assert(myBoundary.xmin() <= myBoundary.xmax()); - NIVissimEdge* edge = NIVissimEdge::dictionary(edgeid); - std::vector::const_iterator i = std::find(myEdges.begin(), myEdges.end(), edgeid); - if (i == myEdges.end()) { - // edge does not exist!? - throw 1; - } - const PositionVector& edgeGeom = edge->getGeometry(); - Position p = GeomHelper::crossPoint(myBoundary, edgeGeom); - return GeomHelper::nearest_offset_on_line_to_point2D( - edgeGeom.front(), edgeGeom.back(), p); -} - - - -void -NIVissimConnectionCluster::clearDict() { - for (ContType::iterator i = myClusters.begin(); i != myClusters.end(); i++) { - delete (*i); - } - myClusters.clear(); - myFirstFreeID = 100000; -} - - -PositionVector -NIVissimConnectionCluster::getIncomingContinuationGeometry(NIVissimEdge* e) const { - // collect connection where this edge is the incoming one - std::vector edgeIsIncoming; - for (std::vector::const_iterator i = myConnections.begin(); i != myConnections.end(); i++) { - NIVissimConnection* c = NIVissimConnection::dictionary(*i); - if (c->getFromEdgeID() == e->getID()) { - edgeIsIncoming.push_back(c); - } - } - // - if (edgeIsIncoming.size() == 0) { - return PositionVector(); - } - // sort connected edges in same direction - sort(edgeIsIncoming.begin(), edgeIsIncoming.end(), - same_direction_sorter(e->getGeometry().beginEndAngle())); - NIVissimConnection* c = *(edgeIsIncoming.begin()); - return c->getGeometry(); -} - - - -NIVissimConnection* -NIVissimConnectionCluster::getIncomingContinuation(NIVissimEdge* e) const { - // collect connection where this edge is the incoming one - std::vector edgeIsIncoming; - for (std::vector::const_iterator i = myConnections.begin(); i != myConnections.end(); i++) { - NIVissimConnection* c = NIVissimConnection::dictionary(*i); - if (c->getFromEdgeID() == e->getID()) { - edgeIsIncoming.push_back(c); - } - } - // - if (edgeIsIncoming.size() == 0) { - return nullptr; - } - // sort connected edges in same direction - sort(edgeIsIncoming.begin(), edgeIsIncoming.end(), - same_direction_sorter(e->getGeometry().beginEndAngle())); - return *(edgeIsIncoming.begin()); -} - - - -PositionVector -NIVissimConnectionCluster::getOutgoingContinuationGeometry(NIVissimEdge* e) const { - // collect connection where this edge is the outgoing one - std::vector edgeIsOutgoing; - for (std::vector::const_iterator i = myConnections.begin(); i != myConnections.end(); i++) { - NIVissimConnection* c = NIVissimConnection::dictionary(*i); - if (c->getToEdgeID() == e->getID()) { - edgeIsOutgoing.push_back(c); - } - } - // - if (edgeIsOutgoing.size() == 0) { - return PositionVector(); - } - // sort connected edges in same direction - sort(edgeIsOutgoing.begin(), edgeIsOutgoing.end(), - same_direction_sorter(e->getGeometry().beginEndAngle())); - NIVissimConnection* c = *(edgeIsOutgoing.begin()); - return c->getGeometry(); -} - - -NIVissimConnection* -NIVissimConnectionCluster::getOutgoingContinuation(NIVissimEdge* e) const { - // collect connection where this edge is the outgoing one - std::vector edgeIsOutgoing; - for (std::vector::const_iterator i = myConnections.begin(); i != myConnections.end(); i++) { - NIVissimConnection* c = NIVissimConnection::dictionary(*i); - if (c->getToEdgeID() == e->getID()) { - edgeIsOutgoing.push_back(c); - } - } - // - if (edgeIsOutgoing.size() == 0) { - return nullptr; - } - // sort connected edges in same direction - sort(edgeIsOutgoing.begin(), edgeIsOutgoing.end(), - same_direction_sorter(e->getGeometry().beginEndAngle())); - return *(edgeIsOutgoing.begin()); -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimConnectionCluster.h b/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimConnectionCluster.h deleted file mode 100644 index 1ed6aa62d..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimConnectionCluster.h +++ /dev/null @@ -1,190 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimConnectionCluster.h -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Sept 2002 -/// -// ------------------- -/****************************************************************************/ -#pragma once -#include - - -#include -#include -#include -#include -#include "NIVissimConnection.h" - - -// =========================================================================== -// class declarations -// =========================================================================== -class NBNode; -class NIVissimEdge; - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NIVissimConnectionCluster - * This class holds a list of connections either all outgoing or all - * incoming within an edge, which do lies close together. - * This shall be the connections which belong to a single node. - * It still are not all of the node's connections, as other edges - * may participate to this node, too. - */ -class NIVissimConnectionCluster { -public: - /** @brief Constructor - Build the boundary; The boundary includes both incoming and outgoing nodes */ - NIVissimConnectionCluster(const std::vector& connections, int nodeCluster, - int edgeid); - - NIVissimConnectionCluster(const std::vector& connections, - const Boundary& boundary, int nodeCluster, const std::vector& edges); - - /// Destructor - ~NIVissimConnectionCluster(); - - /// Returns the information whether the given cluster overlaps the current - bool overlapsWith(NIVissimConnectionCluster* c, double offset = 0) const; - - bool hasNodeCluster() const; - - NBNode* getNBNode() const; - - bool around(const Position& p, double offset = 0) const; - - double getPositionForEdge(int edgeid) const; - - friend class NIVissimEdge; // !!! debug - - const std::vector& getConnections() const { - return myConnections; - } - - PositionVector getIncomingContinuationGeometry(NIVissimEdge* e) const; - PositionVector getOutgoingContinuationGeometry(NIVissimEdge* e) const; - NIVissimConnection* getIncomingContinuation(NIVissimEdge* e) const; - NIVissimConnection* getOutgoingContinuation(NIVissimEdge* e) const; - - -public: - /** @brief Tries to joind clusters participating within a node - This is done by joining clusters which overlap */ - static void joinBySameEdges(double offset); - - static void joinByDisturbances(double offset); - - static void buildNodeClusters(); - - static void _debugOut(std::ostream& into); - - static int dictSize(); - - - static int getNextFreeNodeID(); - - static void clearDict(); - -private: - class NodeSubCluster { - public: - NodeSubCluster(NIVissimConnection* c); - ~NodeSubCluster(); - void add(NIVissimConnection* c); - void add(const NodeSubCluster& c); - int size() const; - bool overlapsWith(const NodeSubCluster& c, double offset = 0); - std::vector getConnectionIDs() const; - friend class NIVissimConnectionCluster; - public: - Boundary myBoundary; - typedef std::vector ConnectionCont; - ConnectionCont myConnections; - }; - - class same_direction_sorter { - private: - double myAngle; - - public: - /// constructor - explicit same_direction_sorter(double angle) - : myAngle(angle) { } - - public: - /// comparing operation - int operator()(NIVissimConnection* c1, NIVissimConnection* c2) const { - return fabs(GeomHelper::angleDiff(c1->getGeometry().beginEndAngle(), myAngle)) - < - fabs(GeomHelper::angleDiff(c2->getGeometry().beginEndAngle(), myAngle)); - } - }; - - - -private: - /// Adds the second cluster - void add(NIVissimConnectionCluster* c); - - void removeConnections(const NodeSubCluster& c); - - void recomputeBoundary(); - - void recheckEdges(); - - bool joinable(NIVissimConnectionCluster* c2, double offset); - - - std::vector getDisturbanceParticipators(); - - std::vector extendByToTreatAsSame(const std::vector& iv1, - const std::vector& iv2) const; - - bool isWeakDistrictConnRealisation(NIVissimConnectionCluster* c2); - - bool liesOnSameEdgesEnd(NIVissimConnectionCluster* cc2); - - - -private: - /// List of connection-ids which participate within this cluster - std::vector myConnections; - - /// The boundary of the cluster - Boundary myBoundary; - - /// The node the cluster is assigned to - int myNodeCluster; - - // The edge which holds the cluster - std::vector myEdges; - - std::vector myNodes; - - std::vector myTLs; - - std::vector myOutgoingEdges, myIncomingEdges; - -private: - typedef std::vector ContType; - static ContType myClusters; - static int myFirstFreeID; - static int myStaticBlaID; - int myBlaID; -}; diff --git a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimDistrictConnection.cpp b/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimDistrictConnection.cpp deleted file mode 100644 index 17a7a29ce..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimDistrictConnection.cpp +++ /dev/null @@ -1,392 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimDistrictConnection.cpp -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date Sept 2002 -/// -// ------------------- -/****************************************************************************/ -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "NIVissimAbstractEdge.h" -#include "NIVissimEdge.h" -#include -#include -#include -#include -#include -#include -#include "NIVissimDistrictConnection.h" -#include -#include - - -// =========================================================================== -// static member definitions -// =========================================================================== -NIVissimDistrictConnection::DictType NIVissimDistrictConnection::myDict; -std::map > NIVissimDistrictConnection::myDistrictsConnections; - - -// =========================================================================== -// method definitions -// =========================================================================== -NIVissimDistrictConnection::NIVissimDistrictConnection(int id, - const std::string& name, - const std::vector& districts, const std::vector& percentages, - int edgeid, double position, - const std::vector >& assignedVehicles) - : myID(id), myName(name), myDistricts(districts), - myEdgeID(edgeid), myPosition(position), - myAssignedVehicles(assignedVehicles) { - std::vector::iterator i = myDistricts.begin(); - std::vector::const_iterator j = percentages.begin(); - while (i != myDistricts.end()) { - myPercentages[*i] = *j; - i++; - j++; - } -} - - -NIVissimDistrictConnection::~NIVissimDistrictConnection() {} - - - -bool -NIVissimDistrictConnection::dictionary(int id, const std::string& name, - const std::vector& districts, const std::vector& percentages, - int edgeid, double position, - const std::vector >& assignedVehicles) { - NIVissimDistrictConnection* o = - new NIVissimDistrictConnection(id, name, districts, percentages, - edgeid, position, assignedVehicles); - if (!dictionary(id, o)) { - delete o; - return false; - } - return true; -} - - -bool -NIVissimDistrictConnection::dictionary(int id, NIVissimDistrictConnection* o) { - DictType::iterator i = myDict.find(id); - if (i == myDict.end()) { - myDict[id] = o; - return true; - } - return false; -} - - -NIVissimDistrictConnection* -NIVissimDistrictConnection::dictionary(int id) { - DictType::iterator i = myDict.find(id); - if (i == myDict.end()) { - return nullptr; - } - return (*i).second; -} - -void -NIVissimDistrictConnection::dict_BuildDistrictConnections() { - // pre-assign connections to districts - for (DictType::iterator i = myDict.begin(); i != myDict.end(); i++) { - NIVissimDistrictConnection* c = (*i).second; - const std::vector& districts = c->myDistricts; - for (std::vector::const_iterator j = districts.begin(); j != districts.end(); j++) { - // assign connection to district - myDistrictsConnections[*j].push_back((*i).first); - } - } -} - - -void -NIVissimDistrictConnection::dict_CheckEdgeEnds() { - for (std::map >::iterator k = myDistrictsConnections.begin(); k != myDistrictsConnections.end(); k++) { - const std::vector& connections = (*k).second; - for (std::vector::const_iterator j = connections.begin(); j != connections.end(); j++) { - NIVissimDistrictConnection* c = dictionary(*j); - c->checkEdgeEnd(); - } - } -} - - -void -NIVissimDistrictConnection::checkEdgeEnd() { - NIVissimEdge* edge = NIVissimEdge::dictionary(myEdgeID); - assert(edge != 0); - edge->checkDistrictConnectionExistanceAt(myPosition); -} - - -void -NIVissimDistrictConnection::dict_BuildDistrictNodes(NBDistrictCont& dc, - NBNodeCont& nc) { - for (std::map >::iterator k = myDistrictsConnections.begin(); k != myDistrictsConnections.end(); k++) { - // get the connections - const std::vector& connections = (*k).second; - // retrieve the current district - std::string dsid = toString((*k).first); - NBDistrict* district = new NBDistrict(dsid); - dc.insert(district); - // compute the middle of the district - PositionVector pos; - for (std::vector::const_iterator j = connections.begin(); j != connections.end(); j++) { - NIVissimDistrictConnection* c = dictionary(*j); - pos.push_back(c->geomPosition()); - } - Position distCenter = pos.getPolygonCenter(); - if (connections.size() == 1) { // !!! ok, ok, maybe not the best way just to add an offset - distCenter.add(10, 10); - } - district->setCenter(distCenter); - // build the node - std::string id = "District" + district->getID(); - NBNode* districtNode = - new NBNode(id, district->getPosition(), district); - if (!nc.insert(districtNode)) { - throw 1; - } - } -} - -void -NIVissimDistrictConnection::dict_BuildDistricts(NBDistrictCont& dc, - NBEdgeCont& ec, - NBNodeCont& nc) { - // add the sources and sinks - // their normalised probability is computed within NBDistrict - // to avoid double code writing and more securty within the converter - // go through the district table - for (std::map >::iterator k = myDistrictsConnections.begin(); k != myDistrictsConnections.end(); k++) { - // get the connections - const std::vector& connections = (*k).second; - // retrieve the current district - NBDistrict* district = - dc.retrieve(toString((*k).first)); - NBNode* districtNode = nc.retrieve("District" + district->getID()); - assert(district != 0 && districtNode != 0); - - for (std::vector::const_iterator l = connections.begin(); l != connections.end(); l++) { - NIVissimDistrictConnection* c = dictionary(*l); - // get the edge to connect the parking place to - NBEdge* e = ec.retrieve(toString(c->myEdgeID)); - if (e == nullptr) { - e = ec.retrievePossiblySplit(toString(c->myEdgeID), c->myPosition); - } - if (e == nullptr) { - WRITE_WARNING("Could not build district '" + toString((*k).first) + "' - edge '" + toString(c->myEdgeID) + "' is missing."); - continue; - } - std::string id = "ParkingPlace" + toString(*l); - NBNode* parkingPlace = nc.retrieve(id); - if (parkingPlace == nullptr) { - double pos = c->getPosition(); - if (pos < e->getLength() - pos) { - parkingPlace = e->getFromNode(); - parkingPlace->invalidateIncomingConnections(); - } else { - parkingPlace = e->getToNode(); - parkingPlace->invalidateOutgoingConnections(); - } - } - assert( - e->getToNode() == parkingPlace - || - e->getFromNode() == parkingPlace); - - // build the connection to the source - if (e->getFromNode() == parkingPlace) { - id = "VissimFromParkingplace" + toString((*k).first) + "-" + toString(c->myID); - NBEdge* source = - new NBEdge(id, districtNode, parkingPlace, - "Connection", c->getMeanSpeed(/*distc*/) / (double) 3.6, 3, -1, - NBEdge::UNSPECIFIED_WIDTH, NBEdge::UNSPECIFIED_OFFSET); - if (!ec.insert(source)) { // !!! in den Konstruktor - throw 1; // !!! - } - double percNormed = - c->myPercentages[(*k).first]; - if (!district->addSource(source, percNormed)) { - throw 1; - } - } - - // build the connection to the destination - if (e->getToNode() == parkingPlace) { - id = "VissimToParkingplace" + toString((*k).first) + "-" + toString(c->myID); - NBEdge* destination = - new NBEdge(id, parkingPlace, districtNode, - "Connection", (double) 100 / (double) 3.6, 2, -1, - NBEdge::UNSPECIFIED_WIDTH, NBEdge::UNSPECIFIED_OFFSET); - if (!ec.insert(destination)) { // !!! (in den Konstruktor) - throw 1; // !!! - } - double percNormed2 = - c->myPercentages[(*k).first]; - if (!district->addSink(destination, percNormed2)) { - throw 1; // !!! - } - } - - /* - if(e->getToNode()==districtNode) { - double percNormed = - c->myPercentages[(*k).first]; - district->addSink(e, percNormed); - } - if(e->getFromNode()==districtNode) { - double percNormed = - c->myPercentages[(*k).first]; - district->addSource(e, percNormed); - } - */ - } - - /* - // add them as sources and sinks to the current district - for(std::vector::const_iterator l=connections.begin(); l!=connections.end(); l++) { - // get the current connections - NIVissimDistrictConnection *c = dictionary(*l); - // get the edge to connect the parking place to - NBEdge *e = NBEdgeCont::retrieve(toString(c->myEdgeID)); - Position edgepos = c->geomPosition(); - NBNode *edgeend = e->tryGetNodeAtPosition(c->myPosition, - e->getLength()/4.0); - if(edgeend==0) { - // Edge splitting omitted on build district connections by now - assert(false); - } - - // build the district-node if not yet existing - std::string id = "VissimParkingplace" + district->getID(); - NBNode *districtNode = nc.retrieve(id); - assert(districtNode!=0); - - if(e->getToNode()==edgeend) { - // build the connection to the source - id = std::string("VissimFromParkingplace") - + toString((*k).first) + "-" - + toString(c->myID); - NBEdge *source = - new NBEdge(id, id, districtNode, edgeend, - "Connection", 100/3.6, 2, 100, 0, - NBEdge::EDGEFUNCTION_SOURCE); - NBEdgeCont::insert(source); // !!! (in den Konstruktor) - double percNormed = - c->myPercentages[(*k).first]; - district->addSource(source, percNormed); - } else { - // build the connection to the destination - id = std::string("VissimToParkingplace") - + toString((*k).first) + "-" - + toString(c->myID); - NBEdge *destination = - new NBEdge(id, id, edgeend, districtNode, - "Connection", 100/3.6, 2, 100, 0, - NBEdge::EDGEFUNCTION_SINK); - NBEdgeCont::insert(destination); // !!! (in den Konstruktor) - - // add both the source and the sink to the district - double percNormed = - c->myPercentages[(*k).first]; - district->addSink(destination, percNormed); - } - } - */ - } -} - - - -Position -NIVissimDistrictConnection::geomPosition() const { - NIVissimAbstractEdge* e = NIVissimEdge::dictionary(myEdgeID); - return e->getGeomPosition(myPosition); -} - - -NIVissimDistrictConnection* -NIVissimDistrictConnection::dict_findForEdge(int edgeid) { - for (DictType::iterator i = myDict.begin(); i != myDict.end(); i++) { - if ((*i).second->myEdgeID == edgeid) { - return (*i).second; - } - } - return nullptr; -} - - -void -NIVissimDistrictConnection::clearDict() { - for (DictType::iterator i = myDict.begin(); i != myDict.end(); i++) { - delete (*i).second; - } - myDict.clear(); -} - - -double -NIVissimDistrictConnection::getMeanSpeed() const { - //assert(myAssignedVehicles.size()!=0); - if (myAssignedVehicles.size() == 0) { - WRITE_WARNING("No streams assigned at district'" + toString(myID) + "'.\n Using default speed 200km/h"); - return (double) 200 / (double) 3.6; - } - double speed = 0; - std::vector >::const_iterator i; - for (i = myAssignedVehicles.begin(); i != myAssignedVehicles.end(); i++) { - speed += getRealSpeed((*i).second); - } - return speed / (double) myAssignedVehicles.size(); -} - - -double -NIVissimDistrictConnection::getRealSpeed(int distNo) const { - std::string id = toString(distNo); - Distribution* dist = DistributionCont::dictionary("speed", id); - if (dist == nullptr) { - WRITE_WARNING("The referenced speed distribution '" + id + "' is not known."); - WRITE_WARNING(". Using default."); - return OptionsCont::getOptions().getFloat("vissim.default-speed"); - } - assert(dist != 0); - double speed = dist->getMax(); - if (speed < 0 || speed > 1000) { - WRITE_WARNING(" False speed at district '" + id); - WRITE_WARNING(". Using default."); - speed = OptionsCont::getOptions().getFloat("vissim.default-speed"); - } - return speed; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimDistrictConnection.h b/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimDistrictConnection.h deleted file mode 100644 index 77801ec80..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimDistrictConnection.h +++ /dev/null @@ -1,135 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimDistrictConnection.h -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date End of 2002 -/// -// An edge imported from Vissim together for a container for -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include - - -class NBDistrictCont; -class NBEdgeCont; - - -// =========================================================================== -// class definitions -// =========================================================================== -class NIVissimDistrictConnection { -public: - /// Contructor - NIVissimDistrictConnection(int id, const std::string& name, - const std::vector& districts, const std::vector& percentages, - int edgeid, double position, - const std::vector >& assignedVehicles); - - // Destructor - ~NIVissimDistrictConnection(); - - /** @brief Returns the position - The position yields from the edge geometry and the place the connection is plaed at */ - Position geomPosition() const; - - /// Returns the id of the connection - int getID() const { - return myID; - } - - /// Returns the position of the connection at the edge - double getPosition() const { - return myPosition; - } - - double getMeanSpeed() const; - -public: - /// Inserts the connection into the dictionary after building it - static bool dictionary(int id, const std::string& name, - const std::vector& districts, const std::vector& percentages, - int edgeid, double position, - const std::vector >& assignedVehicles); - - /// Inserts the build connection to the dictionary - static bool dictionary(int id, NIVissimDistrictConnection* o); - - /// Returns the named dictionary - static NIVissimDistrictConnection* dictionary(int id); - - /// Builds the nodes that belong to a district - static void dict_BuildDistrictNodes(NBDistrictCont& dc, - NBNodeCont& nc); - - /// Builds the districts - static void dict_BuildDistricts(NBDistrictCont& dc, - NBEdgeCont& ec, NBNodeCont& nc); - - /** @brief Returns the connection to a district placed at the given node - Yep, there onyl should be one, there is no need to build a single edge as connection between two parking places */ - static NIVissimDistrictConnection* dict_findForEdge(int edgeid); - - /// Clears the dictionary - static void clearDict(); - - static void dict_BuildDistrictConnections(); - - static void dict_CheckEdgeEnds(); - - -private: - void checkEdgeEnd(); - double getRealSpeed(int distNo) const; - -private: - /// The id of the connections - int myID; - - /// The name of the connections - std::string myName; - - /// The connected districts - std::vector myDistricts; - - /// Definition of a map of how many vehicles should leave to a certain district - typedef std::map DistrictPercentages; - - /// A map how many vehicles (key, amount) should leave to a district (key) - DistrictPercentages myPercentages; - - /// The id of the connected edge - int myEdgeID; - - /// The position on the edge - double myPosition; - - /// The vehicles using this connection - std::vector > myAssignedVehicles; - -private: - /// Definition of a dictionary of district connections - typedef std::map DictType; - - /// District connection dictionary - static DictType myDict; - - /// Map from ditricts to connections - static std::map > myDistrictsConnections; - -}; diff --git a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimDisturbance.cpp b/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimDisturbance.cpp deleted file mode 100644 index eff3debce..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimDisturbance.cpp +++ /dev/null @@ -1,353 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimDisturbance.cpp -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Sept 2002 -/// -// ------------------- -/****************************************************************************/ -#include - - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "NIVissimEdge.h" -#include "NIVissimConnection.h" -#include "NIVissimNodeDef.h" -#include "NIVissimDisturbance.h" -#include "NIVissimNodeParticipatingEdgeVector.h" - - -// =========================================================================== -// static member variables -// =========================================================================== -NIVissimDisturbance::DictType NIVissimDisturbance::myDict; -int NIVissimDisturbance::myRunningID = 100000000; - -int NIVissimDisturbance::refusedProhibits = 0; - - -// =========================================================================== -// method definitions -// =========================================================================== -NIVissimDisturbance::NIVissimDisturbance(int id, - const std::string& name, - const NIVissimExtendedEdgePoint& edge, - const NIVissimExtendedEdgePoint& by) - : myID(id), myNode(-1), myName(name), myEdge(edge), myDisturbance(by) {} - - -NIVissimDisturbance::~NIVissimDisturbance() {} - - - -bool -NIVissimDisturbance::dictionary(const std::string& name, - const NIVissimExtendedEdgePoint& edge, - const NIVissimExtendedEdgePoint& by) { - int nid = myRunningID++; - NIVissimDisturbance* o = - new NIVissimDisturbance(nid, name, edge, by); - if (!dictionary(nid, o)) { - delete o; - } - return true; -} - - -bool -NIVissimDisturbance::dictionary(int id, NIVissimDisturbance* o) { - DictType::iterator i = myDict.find(id); - if (i == myDict.end()) { - myDict[id] = o; - return true; - } - return false; -} - - -NIVissimDisturbance* -NIVissimDisturbance::dictionary(int id) { - DictType::iterator i = myDict.find(id); - if (i == myDict.end()) { - return nullptr; - } - return (*i).second; -} - -std::vector -NIVissimDisturbance::getWithin(const AbstractPoly& poly) { - std::vector ret; - for (DictType::iterator i = myDict.begin(); i != myDict.end(); i++) { - if ((*i).second->crosses(poly)) { - ret.push_back((*i).second->myID); - } - } - return ret; -} - - -void -NIVissimDisturbance::computeBounding() { - assert(myBoundary == 0); - Boundary* bound = new Boundary(); - if (NIVissimAbstractEdge::dictionary(myEdge.getEdgeID()) != nullptr) { - bound->add(myEdge.getGeomPosition()); - } - if (NIVissimAbstractEdge::dictionary(myDisturbance.getEdgeID()) != nullptr) { - bound->add(myDisturbance.getGeomPosition()); - } - myBoundary = bound; - assert(myBoundary != 0 && myBoundary->xmax() >= myBoundary->xmin()); -} - - - -bool -NIVissimDisturbance::addToNode(NBNode* node, NBDistrictCont& dc, - NBNodeCont& nc, NBEdgeCont& ec) { - myNode = 0; - NIVissimConnection* pc = - NIVissimConnection::dictionary(myEdge.getEdgeID()); - NIVissimConnection* bc = - NIVissimConnection::dictionary(myDisturbance.getEdgeID()); - if (pc == nullptr && bc == nullptr) { - // This has not been tested completely, yet - // Both competing abstract edges are normal edges - // We have to find a crossing point, build a node here, - // split both edges and add the connections - NIVissimEdge* e1 = NIVissimEdge::dictionary(myEdge.getEdgeID()); - NIVissimEdge* e2 = NIVissimEdge::dictionary(myDisturbance.getEdgeID()); - WRITE_WARNING("Ugly split to prohibit '" + toString(e1->getID()) + "' by '" + toString(e2->getID()) + "'."); - Position pos = e1->crossesEdgeAtPoint(e2); - std::string id1 = toString(e1->getID()) + "x" + toString(e2->getID()); - std::string id2 = toString(e2->getID()) + "x" + toString(e1->getID()); - NBNode* node1 = nc.retrieve(id1); - NBNode* node2 = nc.retrieve(id2); - NBNode* node = nullptr; - assert(node1 == 0 || node2 == 0); - if (node1 == nullptr && node2 == nullptr) { - refusedProhibits++; - return false; - /* node = new NBNode(id1, pos.x(), pos.y(), "priority"); - if(!myNodeCont.insert(node)) { - "nope, NIVissimDisturbance" << endl; - throw 1; - }*/ - } else { - node = node1 == nullptr ? node2 : node1; - } - ec.splitAt(dc, ec.retrievePossiblySplit(toString(e1->getID()), myEdge.getPosition()), node); - ec.splitAt(dc, ec.retrievePossiblySplit(toString(e2->getID()), myDisturbance.getPosition()), node); - // !!! in some cases, one of the edges is not being build because it's too short - // !!! what to do in these cases? - NBEdge* mayDriveFrom = ec.retrieve(toString(e1->getID()) + "[0]"); - NBEdge* mayDriveTo = ec.retrieve(toString(e1->getID()) + "[1]"); - NBEdge* mustStopFrom = ec.retrieve(toString(e2->getID()) + "[0]"); - NBEdge* mustStopTo = ec.retrieve(toString(e2->getID()) + "[1]"); - if (mayDriveFrom != nullptr && mayDriveTo != nullptr && mustStopFrom != nullptr && mustStopTo != nullptr) { - node->addSortedLinkFoes( - NBConnection(mayDriveFrom, mayDriveTo), - NBConnection(mayDriveFrom, mayDriveTo)); - } else { - refusedProhibits++; - return false; - // !!! warning - } -// } - } else if (pc != nullptr && bc == nullptr) { - // The prohibited abstract edge is a connection, the other - // is not; - // The connection will be prohibitesd by all connections - // outgoing from the "real" edge - - NBEdge* e = ec.retrievePossiblySplit(toString(myDisturbance.getEdgeID()), myDisturbance.getPosition()); - if (e == nullptr) { - WRITE_WARNING("Could not prohibit '" + toString(myEdge.getEdgeID()) + "' by '" + toString(myDisturbance.getEdgeID()) + "'. Have not found disturbance."); - refusedProhibits++; - return false; - } - if (e->getFromNode() == e->getToNode()) { - WRITE_WARNING("Could not prohibit '" + toString(myEdge.getEdgeID()) + "' by '" + toString(myDisturbance.getEdgeID()) + "'. Disturbance connects same node."); - refusedProhibits++; - // What to do with self-looping edges? - return false; - } - // get the begin of the prohibited connection - std::string id_pcoe = toString(pc->getFromEdgeID()); - std::string id_pcie = toString(pc->getToEdgeID()); - NBEdge* pcoe = ec.retrievePossiblySplit(id_pcoe, id_pcie, true); - NBEdge* pcie = ec.retrievePossiblySplit(id_pcie, id_pcoe, false); - // check whether it's ending node is the node the prohibited - // edge end at - if (pcoe != nullptr && pcie != nullptr && pcoe->getToNode() == e->getToNode()) { - // if so, simply prohibit the connections - NBNode* node = e->getToNode(); - const EdgeVector& connected = e->getConnectedEdges(); - for (EdgeVector::const_iterator i = connected.begin(); i != connected.end(); i++) { - node->addSortedLinkFoes( - NBConnection(e, *i), - NBConnection(pcoe, pcie)); - } - } else { - WRITE_WARNING("Would have to split edge '" + e->getID() + "' to build a prohibition"); - refusedProhibits++; - // quite ugly - why was it not build? - return false; - /* - std::string nid1 = e->getID() + "[0]"; - std::string nid2 = e->getID() + "[1]"; - - if(ec.splitAt(e, node)) { - node->addSortedLinkFoes( - NBConnection( - ec.retrieve(nid1), - ec.retrieve(nid2) - ), - getConnection(node, myEdge.getEdgeID()) - ); - } - */ - } - } else if (bc != nullptr && pc == nullptr) { - // The prohibiting abstract edge is a connection, the other - // is not; - // We have to split the other one and add the prohibition - // description - - NBEdge* e = ec.retrievePossiblySplit(toString(myEdge.getEdgeID()), myEdge.getPosition()); - if (e == nullptr) { - WRITE_WARNING("Could not prohibit '" + toString(myEdge.getEdgeID()) + "' - it was not built."); - return false; - } - std::string nid1 = e->getID() + "[0]"; - std::string nid2 = e->getID() + "[1]"; - if (e->getFromNode() == e->getToNode()) { - WRITE_WARNING("Could not prohibit '" + toString(myEdge.getEdgeID()) + "' by '" + toString(myDisturbance.getEdgeID()) + "'."); - refusedProhibits++; - // What to do with self-looping edges? - return false; - } - // get the begin of the prohibiting connection - std::string id_bcoe = toString(bc->getFromEdgeID()); - std::string id_bcie = toString(bc->getToEdgeID()); - NBEdge* bcoe = ec.retrievePossiblySplit(id_bcoe, id_bcie, true); - NBEdge* bcie = ec.retrievePossiblySplit(id_bcie, id_bcoe, false); - // check whether it's ending node is the node the prohibited - // edge end at - if (bcoe != nullptr && bcie != nullptr && bcoe->getToNode() == e->getToNode()) { - // if so, simply prohibit the connections - NBNode* node = e->getToNode(); - const EdgeVector& connected = e->getConnectedEdges(); - for (EdgeVector::const_iterator i = connected.begin(); i != connected.end(); i++) { - node->addSortedLinkFoes( - NBConnection(bcoe, bcie), - NBConnection(e, *i)); - } - } else { - WRITE_WARNING("Would have to split edge '" + e->getID() + "' to build a prohibition"); - refusedProhibits++; - return false; - /* - // quite ugly - why was it not build? - if(ec.splitAt(e, node)) { - node->addSortedLinkFoes( - getConnection(node, myDisturbance.getEdgeID()), - NBConnection( - ec.retrieve(nid1), - ec.retrieve(nid2) - ) - ); - } - */ - } - } else { - // both the prohibiting and the prohibited abstract edges - // are connections - // We can retrieve the conected edges and add the desription - NBConnection conn1 = getConnection(node, myDisturbance.getEdgeID()); - NBConnection conn2 = getConnection(node, myEdge.getEdgeID()); - if (!conn1.check(ec) || !conn2.check(ec)) { - refusedProhibits++; - return false; - } - node->addSortedLinkFoes(conn1, conn2); - } - return true; -} - - -NBConnection -NIVissimDisturbance::getConnection(NBNode* node, int aedgeid) { - if (NIVissimEdge::dictionary(myEdge.getEdgeID()) == nullptr) { - NIVissimConnection* c = NIVissimConnection::dictionary(aedgeid); - NBEdge* from = - node->getPossiblySplittedIncoming(toString(c->getFromEdgeID())); - NBEdge* to = - node->getPossiblySplittedOutgoing(toString(c->getToEdgeID())); - - // source is a connection - return NBConnection(toString(c->getFromEdgeID()), from, - toString(c->getToEdgeID()), to); - } else { - WRITE_WARNING("NIVissimDisturbance: no connection"); - return NBConnection::InvalidConnection; -// throw 1; // !!! what to do? - } - -} - -void -NIVissimDisturbance::clearDict() { - for (DictType::iterator i = myDict.begin(); i != myDict.end(); i++) { - delete (*i).second; - } - myDict.clear(); -} - - -void -NIVissimDisturbance::dict_SetDisturbances() { - for (DictType::iterator i = myDict.begin(); i != myDict.end(); i++) { - NIVissimDisturbance* d = (*i).second; - NIVissimAbstractEdge::dictionary(d->myEdge.getEdgeID())->addDisturbance((*i).first); - NIVissimAbstractEdge::dictionary(d->myDisturbance.getEdgeID())->addDisturbance((*i).first); - } - /* for(DictType::iterator i=myDict.begin(); i!=myDict.end(); i++) { - delete (*i).second; - } - */ -} - - -void -NIVissimDisturbance::reportRefused() { - if (refusedProhibits > 0) { - WRITE_WARNING("Could not build " + toString(refusedProhibits) + " of " + toString((int)myDict.size()) + " disturbances."); - } -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimDisturbance.h b/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimDisturbance.h deleted file mode 100644 index b8309743e..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimDisturbance.h +++ /dev/null @@ -1,80 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2002-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimDisturbance.h -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Sept 2002 -/// -// ------------------- -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include -#include -#include "NIVissimExtendedEdgePoint.h" -#include "NIVissimBoundedClusterObject.h" -#include "NIVissimNodeParticipatingEdgeVector.h" - - -// =========================================================================== -// class declarations -// =========================================================================== -class NBNode; -class NBEdge; -class NBDistrictCont; - -class NIVissimDisturbance - : public NIVissimBoundedClusterObject { -public: - NIVissimDisturbance(int id, const std::string& name, - const NIVissimExtendedEdgePoint& edge, - const NIVissimExtendedEdgePoint& by); - virtual ~NIVissimDisturbance(); - void computeBounding(); - bool addToNode(NBNode* node, NBDistrictCont& dc, - NBNodeCont& nc, NBEdgeCont& ec); - int getEdgeID() const { - return myEdge.getEdgeID(); - } - int getDisturbanceID() const { - return myDisturbance.getEdgeID(); - } - NBConnection getConnection(NBNode* node, int aedgeid); - -public: - static bool dictionary(const std::string& name, - const NIVissimExtendedEdgePoint& edge, - const NIVissimExtendedEdgePoint& by); - static bool dictionary(int id, NIVissimDisturbance* o); - static NIVissimDisturbance* dictionary(int id); - static std::vector getWithin(const AbstractPoly& poly); - static void clearDict(); - static void dict_SetDisturbances(); - static void reportRefused(); - -private: - int myID; - int myNode; - std::string myName; - NIVissimExtendedEdgePoint myEdge; - NIVissimExtendedEdgePoint myDisturbance; - - typedef std::map DictType; - static DictType myDict; - static int myRunningID; - static int refusedProhibits; -}; diff --git a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimEdge.cpp b/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimEdge.cpp deleted file mode 100644 index f8f91261e..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimEdge.cpp +++ /dev/null @@ -1,1023 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimEdge.cpp -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date Sept 2002 -/// -// A temporary storage for edges imported from Vissim -/****************************************************************************/ -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "NIVissimNodeCluster.h" -#include "NIVissimDistrictConnection.h" -#include "NIVissimClosedLanesVector.h" -#include "NIVissimConnection.h" -#include "NIVissimDisturbance.h" -#include "NIVissimEdge.h" -#include - - -// =========================================================================== -// static members -// =========================================================================== -NIVissimEdge::DictType NIVissimEdge::myDict; -int NIVissimEdge::myMaxID = 0; -std::vector NIVissimEdge::myLanesWithMissingSpeeds; - - -// =========================================================================== -// method definitions -// =========================================================================== -NIVissimEdge::connection_position_sorter::connection_position_sorter(int edgeid) - : myEdgeID(edgeid) {} - - -int -NIVissimEdge::connection_position_sorter::operator()(int c1id, - int c2id) const { - NIVissimConnection* c1 = NIVissimConnection::dictionary(c1id); - NIVissimConnection* c2 = NIVissimConnection::dictionary(c2id); - double pos1 = - c1->getFromEdgeID() == myEdgeID - ? c1->getFromPosition() : c1->getToPosition(); - double pos2 = - c2->getFromEdgeID() == myEdgeID - ? c2->getFromPosition() : c2->getToPosition(); - return pos1 < pos2; -} - - - - - - - - -NIVissimEdge::connection_cluster_position_sorter::connection_cluster_position_sorter(int edgeid) - : myEdgeID(edgeid) {} - - -int -NIVissimEdge::connection_cluster_position_sorter::operator()( - NIVissimConnectionCluster* cc1, - NIVissimConnectionCluster* cc2) const { - double pos1 = cc1->getPositionForEdge(myEdgeID); - double pos2 = cc2->getPositionForEdge(myEdgeID); - if (pos2 < 0 || pos1 < 0) { - cc1->getPositionForEdge(myEdgeID); - cc2->getPositionForEdge(myEdgeID); - } - assert(pos1 >= 0 && pos2 >= 0); - return pos1 < pos2; -} - - - - -NIVissimEdge::NIVissimEdge(int id, const std::string& name, - const std::string& type, - std::vector laneWidths, - double zuschlag1, double zuschlag2, - double /*length*/, const PositionVector& geom, - const NIVissimClosedLanesVector& clv) : - NIVissimAbstractEdge(id, geom), - myName(name), myType(type), myNoLanes((int)laneWidths.size()), - myLaneWidths(laneWidths), - myZuschlag1(zuschlag1), myZuschlag2(zuschlag2), - myClosedLanes(clv), - myLaneSpeeds(myNoLanes, -1), - myAmWithinJunction(false) - //, mySpeed(-1) -{ - assert(myNoLanes >= 0); - if (myMaxID < myID) { - myMaxID = myID; - } -} - - -NIVissimEdge::~NIVissimEdge() { - for (NIVissimClosedLanesVector::iterator i = myClosedLanes.begin(); i != myClosedLanes.end(); i++) { - delete (*i); - } - myClosedLanes.clear(); -} - - -bool -NIVissimEdge::dictionary(int id, const std::string& name, - const std::string& type, int noLanes, - double zuschlag1, double zuschlag2, double length, - const PositionVector& geom, - const NIVissimClosedLanesVector& clv) { - NIVissimEdge* o = new NIVissimEdge(id, name, type, std::vector(noLanes, NBEdge::UNSPECIFIED_WIDTH), - zuschlag1, zuschlag2, length, geom, clv); - if (!dictionary(id, o)) { - delete o; - return false; - } - return true; -} - - - -bool -NIVissimEdge::dictionary(int id, NIVissimEdge* o) { - DictType::iterator i = myDict.find(id); - if (i == myDict.end()) { - myDict[id] = o; - return true; - } - return false; -} - - - -NIVissimEdge* -NIVissimEdge::dictionary(int id) { - DictType::iterator i = myDict.find(id); - if (i == myDict.end()) { - return nullptr; - } - return (*i).second; -} - - -void -NIVissimEdge::buildConnectionClusters() { - const double MAX_CLUSTER_DISTANCE = 10; - // build clusters for all edges made up from not previously assigne - // connections - for (DictType::iterator i = myDict.begin(); i != myDict.end(); i++) { - int edgeid = (*i).first; - NIVissimEdge* edge = (*i).second; - // get all connectors using this edge - std::vector connectors = edge->myIncomingConnections; - copy(edge->myOutgoingConnections.begin(), edge->myOutgoingConnections.end(), back_inserter(connectors)); - if (connectors.size() == 0) { - continue; - } - // sort the connectors by the place on the edge - sort(connectors.begin(), connectors.end(), connection_position_sorter(edgeid)); - // try to cluster the connections participating within the current edge - std::vector currentCluster; - std::vector::iterator j = connectors.begin(); - bool outgoing = NIVissimConnection::dictionary(*j)->getFromEdgeID() == (*i).first; - double position = outgoing - ? NIVissimConnection::dictionary(*j)->getFromPosition() - : NIVissimConnection::dictionary(*j)->getToPosition(); - - // skip connections already in a cluster - // !!! (?) - while (j != connectors.end() && NIVissimConnection::dictionary(*j)->hasNodeCluster()) { - ++j; - } - if (j == connectors.end()) { - continue; - } - currentCluster.push_back(*j); - do { - if (j + 1 != connectors.end() && !NIVissimConnection::dictionary(*j)->hasNodeCluster()) { - bool n_outgoing = NIVissimConnection::dictionary(*(j + 1))->getFromEdgeID() == edgeid; - double n_position = n_outgoing - ? NIVissimConnection::dictionary(*(j + 1))->getFromPosition() - : NIVissimConnection::dictionary(*(j + 1))->getToPosition(); - if (n_outgoing == outgoing && fabs(n_position - position) < MAX_CLUSTER_DISTANCE) { - // ok, in same cluster as prior - currentCluster.push_back(*(j + 1)); - } else { - // start new cluster - VectorHelper::removeDouble(currentCluster); - edge->myConnectionClusters.push_back(new NIVissimConnectionCluster(currentCluster, -1, edgeid)); - currentCluster.clear(); - currentCluster.push_back(*(j + 1)); - } - outgoing = n_outgoing; - position = n_position; - } - j++; - } while (j != connectors.end()); - // add last connection - if (currentCluster.size() > 0) { - VectorHelper::removeDouble(currentCluster); - edge->myConnectionClusters.push_back(new NIVissimConnectionCluster(currentCluster, -1, edgeid)); - } - } -} - - -void -NIVissimEdge::dict_buildNBEdges(NBDistrictCont& dc, NBNodeCont& nc, - NBEdgeCont& ec, double offset) { - for (DictType::iterator i = myDict.begin(); i != myDict.end(); i++) { - NIVissimEdge* edge = (*i).second; - edge->buildNBEdge(dc, nc, ec, offset); - } -} - - -void -NIVissimEdge::dict_propagateSpeeds() { - DictType::iterator i; - for (i = myDict.begin(); i != myDict.end(); i++) { - NIVissimEdge* edge = (*i).second; - edge->setDistrictSpeed(); - } - for (i = myDict.begin(); i != myDict.end(); i++) { - NIVissimEdge* edge = (*i).second; - edge->propagateSpeed(-1, std::vector()); - } - for (int j = 0; j < 3; j++) { - for (i = myDict.begin(); i != myDict.end(); i++) { - NIVissimEdge* edge = (*i).second; - edge->propagateOwn(); - } - for (i = myDict.begin(); i != myDict.end(); i++) { - NIVissimEdge* edge = (*i).second; - edge->checkUnconnectedLaneSpeeds(); - } - } -} - - -void -NIVissimEdge::checkUnconnectedLaneSpeeds() { - for (int i = 0; i < (int) myLaneSpeeds.size(); i++) { - if (myLaneSpeeds[i] == -1) { - double speed = -1; - int j1 = i - 1; // !!! recheck - j1 may become negative? - int j2 = i; - while (j2 != (int) myLaneSpeeds.size() && myLaneSpeeds[j2] == -1) { - j2++; - } - if (j1 < 0) { - if (j2 < (int) myLaneSpeeds.size()) { - speed = myLaneSpeeds[j2]; - } - } else { - if (j2 >= (int) myLaneSpeeds.size()) { - speed = myLaneSpeeds[j1]; - } else { - speed = (myLaneSpeeds[j1] + myLaneSpeeds[j2]) / (double) 2.0; - } - } - if (speed == -1) { - continue; - } - myLaneSpeeds[i] = speed; - std::vector connected = getOutgoingConnected(i); - for (std::vector::iterator j = connected.begin(); j != connected.end(); j++) { - NIVissimConnection* c = *j; - NIVissimEdge* e = NIVissimEdge::dictionary(c->getToEdgeID()); - // propagate - e->propagateSpeed(/*dc, */speed, c->getToLanes()); - } - } - } -} - - -void -NIVissimEdge::propagateOwn() { - for (int i = 0; i < (int) myLaneSpeeds.size(); i++) { - if (myLaneSpeeds[i] == -1) { - continue; - } - std::vector connected = getOutgoingConnected(i); - for (std::vector::iterator j = connected.begin(); j != connected.end(); j++) { - NIVissimConnection* c = *j; - NIVissimEdge* e = NIVissimEdge::dictionary(c->getToEdgeID()); - // propagate - e->propagateSpeed(/*dc, */myLaneSpeeds[i], c->getToLanes()); - } - } -} - - -void -NIVissimEdge::propagateSpeed(double speed, std::vector forLanes) { - // if no lane is given, all set be set - if (forLanes.size() == 0) { - for (int i = 0; i < myNoLanes; i++) { - forLanes.push_back((int) i); - } - } - // for the case of a first call - // go through the lanes - for (std::vector::const_iterator i = forLanes.begin(); i < forLanes.end(); i++) { - // check whether a speed was set before - if (myLaneSpeeds[*i] != -1) { - // do not reset it from incoming - continue; - } - // check whether the lane has a new speed to set - if ((int) myPatchedSpeeds.size() > *i && myPatchedSpeeds[*i] != -1) { - // use it - speed = getRealSpeed(/*dc, */myPatchedSpeeds[*i]); - } - // check whether a speed is given - if (speed == -1) { - // do nothing if not - continue; - } - // set the lane's speed to the given - myLaneSpeeds[*i] = speed; - // propagate the speed further - // get the list of connected edges - std::vector connected = getOutgoingConnected(*i); - // go throught the list - for (std::vector::iterator j = connected.begin(); j != connected.end(); j++) { - NIVissimConnection* c = *j; - NIVissimEdge* e = NIVissimEdge::dictionary(c->getToEdgeID()); - // propagate - e->propagateSpeed(/*dc, */speed, c->getToLanes()); - } - } -} - - - -void -NIVissimEdge::setDistrictSpeed() { - if (myDistrictConnections.size() > 0) { - double pos = *(myDistrictConnections.begin()); - if (pos < getLength() - pos) { - NIVissimDistrictConnection* d = - NIVissimDistrictConnection::dict_findForEdge(myID); - if (d != nullptr) { - double speed = d->getMeanSpeed(/*dc*/); - if (speed == -1) { - return; - } - for (int i = 0; i < myNoLanes; i++) { - myLaneSpeeds[i] = speed; - // propagate the speed further - // get the list of connected edges - std::vector connected = getOutgoingConnected(i); - // go throught the list - for (std::vector::iterator j = connected.begin(); j != connected.end(); j++) { - NIVissimConnection* c = *j; - NIVissimEdge* e = NIVissimEdge::dictionary(c->getToEdgeID()); - // propagate - e->propagateSpeed(/*dc, */speed, c->getToLanes()); - } - } - } - } - } -} - - -std::vector -NIVissimEdge::getOutgoingConnected(int lane) const { - std::vector ret; - for (std::vector::const_iterator i = myOutgoingConnections.begin(); i != myOutgoingConnections.end(); i++) { - NIVissimConnection* c = NIVissimConnection::dictionary(*i); - const std::vector& lanes = c->getFromLanes(); - if (find(lanes.begin(), lanes.end(), lane) != lanes.end()) { - NIVissimEdge* e = NIVissimEdge::dictionary(c->getToEdgeID()); - if (e != nullptr) { - ret.push_back(c); - } - } - } - return ret; -} - - -void -NIVissimEdge::buildNBEdge(NBDistrictCont& dc, NBNodeCont& nc, NBEdgeCont& ec, - double sameNodesOffset) { - // build the edge - std::pair fromInf, toInf; - NBNode* fromNode, *toNode; - fromNode = toNode = nullptr; - sort(myConnectionClusters.begin(), myConnectionClusters.end(), connection_cluster_position_sorter(myID)); - sort(myDistrictConnections.begin(), myDistrictConnections.end()); - ConnectionClusters tmpClusters = myConnectionClusters; - if (tmpClusters.size() != 0) { - sort(tmpClusters.begin(), tmpClusters.end(), connection_cluster_position_sorter(myID)); - // get or build the from-node - // A node may have to be build when the edge starts or ends at - // a parking place or something like this - fromInf = getFromNode(nc, tmpClusters); - fromNode = fromInf.second; - // get or build the to-node - //if(tmpClusters.size()>0) { - toInf = getToNode(nc, tmpClusters); - toNode = toInf.second; - if (fromInf.first != 0 && toNode != nullptr && fromInf.first->around(toNode->getPosition())) { - WRITE_WARNING("Will not build edge '" + toString(myID) + "'."); - myAmWithinJunction = true; - return; - } - //} - // if both nodes are the same, resolve the problem otherwise - if (fromNode == toNode) { - std::pair tmp = resolveSameNode(nc, sameNodesOffset, fromNode, toNode); - if (fromNode != tmp.first) { - fromInf.first = 0; - } - if (toNode != tmp.second) { - toInf.first = 0; - } - fromNode = tmp.first; - toNode = tmp.second; - } - } - - // - if (fromNode == nullptr) { - fromInf.first = 0; - Position pos = myGeom[0]; - fromNode = new NBNode(toString(myID) + "-SourceNode", pos, SumoXMLNodeType::NOJUNCTION); - if (!nc.insert(fromNode)) { - throw ProcessError("Could not insert node '" + fromNode->getID() + "' to nodes container."); - } - } - if (toNode == nullptr) { - toInf.first = 0; - Position pos = myGeom[-1]; - toNode = new NBNode(toString(myID) + "-DestinationNode", pos, SumoXMLNodeType::NOJUNCTION); - if (!nc.insert(toNode)) { - throw ProcessError("Could not insert node '" + toNode->getID() + "' to nodes container."); - } - } - - // build the edge - double avgSpeed = 0; - for (int i = 0; i < myNoLanes; i++) { - if ((int)myLaneSpeeds.size() <= i || myLaneSpeeds[i] == -1) { - myLanesWithMissingSpeeds.push_back(toString(myID) + "_" + toString(i)); - avgSpeed += OptionsCont::getOptions().getFloat("vissim.default-speed"); - } else { - avgSpeed += myLaneSpeeds[i]; - } - } - avgSpeed /= (double) myLaneSpeeds.size(); - avgSpeed *= OptionsCont::getOptions().getFloat("vissim.speed-norm"); - - if (fromNode == toNode) { - WRITE_WARNING("Could not build edge '" + toString(myID) + "'; would connect same node."); - return; - } - - NBEdge* buildEdge = new NBEdge(toString(myID), fromNode, toNode, myType, - avgSpeed / (double) 3.6, myNoLanes, -1, - NBEdge::UNSPECIFIED_WIDTH, NBEdge::UNSPECIFIED_OFFSET, - myGeom, myName, "", LaneSpreadFunction::CENTER, true); - for (int i = 0; i < myNoLanes; i++) { - buildEdge->setLaneWidth(i, myLaneWidths[i]); - if ((int) myLaneSpeeds.size() <= i || myLaneSpeeds[i] == -1) { - buildEdge->setSpeed(i, OptionsCont::getOptions().getFloat("vissim.default-speed") / (double) 3.6); - } else { - buildEdge->setSpeed(i, myLaneSpeeds[i] / (double) 3.6); - } - } - ec.insert(buildEdge); - // check whether the edge contains any other clusters - if (tmpClusters.size() > 0) { - bool cont = true; - for (ConnectionClusters::iterator j = tmpClusters.begin(); cont && j != tmpClusters.end(); ++j) { - // split the edge at the previously build node - std::string nextID = buildEdge->getID() + "[1]"; - cont = ec.splitAt(dc, buildEdge, (*j)->getNBNode()); - // !!! what to do if the edge could not be split? - buildEdge = ec.retrieve(nextID); - } - } -} - - -double -NIVissimEdge::getRealSpeed(int distNo) { - std::string id = toString(distNo); - Distribution* dist = DistributionCont::dictionary("speed", id); - if (dist == nullptr) { - WRITE_WARNING("The referenced speed distribution '" + id + "' is not known."); - return -1; - } - assert(dist != 0); - double speed = dist->getMax(); - if (speed < 0 || speed > 1000) { - WRITE_WARNING("What about distribution '" + toString(distNo) + "' "); - } - return speed; -} - -/* -bool -NIVissimEdge::recheckSpeedPatches() -{ -// int speed_idx = -1; - // check set speeds - if(myPatchedSpeeds.size()!=0) { - std::vector::iterator i = - std::find(myPatchedSpeeds.begin(), myPatchedSpeeds.end(), -1); - if(myPatchedSpeeds.size()!=myNoLanes||i!=myPatchedSpeeds.end()) { - cot << "Warning! Not all lanes are patched! (edge:" << myID << ")." << endl; - } - // - if(std::vectorHelper::maxValue(myPatchedSpeeds)!=std::vectorHelper::minValue(myPatchedSpeeds)) { - cot << "Warning! Not all lanes have the same speed!! (edge:" << myID << ")." << endl; - } - // -/ // !!! ist natuerlich Quatsch - erst recht, wenn Edges zusammengefasst werden - speed = std::vectorHelper::sum(myPatchedSpeeds); - speed /= (double) myPatchedSpeeds.size();*/ -/* return true; - } - if(myDistrictConnections.size()>0) { - double pos = *(myDistrictConnections.begin()); -// if(pos<10) { - NIVissimDistrictConnection *d = - NIVissimDistrictConnection::dict_findForEdge(myID); - if(d!=0) { - return true; -// speed = d->getMeanSpeed(); - } -// } -// return true; - } - return false; -} -*/ - -std::pair -NIVissimEdge::getFromNode(NBNodeCont& nc, ConnectionClusters& clusters) { - // changed MAX_DISTANCE from 10 to 3.5, because 3.5 is the default lane width in VISSIM - const double MAX_DISTANCE = 3.5; - assert(clusters.size() >= 1); - const Position& beg = myGeom.front(); - NIVissimConnectionCluster* c = *(clusters.begin()); - // check whether the edge starts within a already build node - if (c->around(beg, MAX_DISTANCE)) { - clusters.erase(clusters.begin()); - return std::pair - (c, c->getNBNode()); - } - // check for a parking place at the begin - if (myDistrictConnections.size() > 0) { - double pos = *(myDistrictConnections.begin()); - if (pos < 10) { - NBNode* node = new NBNode(toString(myID) + "-begin", beg, SumoXMLNodeType::NOJUNCTION); - if (!nc.insert(node)) { - throw 1; - } - while (myDistrictConnections.size() > 0 && *(myDistrictConnections.begin()) < 10) { - myDistrictConnections.erase(myDistrictConnections.begin()); - } - return std::pair(static_cast(nullptr), node); - } - } - // build a new node for the edge's begin otherwise - NBNode* node = new NBNode(toString(myID) + "-begin", beg, SumoXMLNodeType::NOJUNCTION); - if (!nc.insert(node)) { - throw 1; - } - return std::pair(static_cast(nullptr), node); -} - - -std::pair -NIVissimEdge::getToNode(NBNodeCont& nc, ConnectionClusters& clusters) { - const Position& end = myGeom.back(); - if (clusters.size() > 0) { - const double MAX_DISTANCE = 10.; - assert(clusters.size() >= 1); - NIVissimConnectionCluster* c = *(clusters.end() - 1); - // check whether the edge ends within a already build node - if (c->around(end, MAX_DISTANCE)) { - clusters.erase(clusters.end() - 1); - return std::pair(c, c->getNBNode()); - } - } - // check for a parking place at the end - if (myDistrictConnections.size() > 0) { - double pos = *(myDistrictConnections.end() - 1); - if (pos > myGeom.length() - 10) { - NBNode* node = new NBNode(toString(myID) + "-end", end, SumoXMLNodeType::NOJUNCTION); - if (!nc.insert(node)) { - throw 1; - } - while (myDistrictConnections.size() > 0 && *(myDistrictConnections.end() - 1) < myGeom.length() - 10) { - myDistrictConnections.erase(myDistrictConnections.end() - 1); - } - return std::pair(static_cast(nullptr), node); - } - } - - // build a new node for the edge's end otherwise - NBNode* node = new NBNode(toString(myID) + "-end", end, SumoXMLNodeType::NOJUNCTION); - if (!nc.insert(node)) { - throw 1; - } - return std::pair(static_cast(nullptr), node); - /* - if (clusters.size()>0) { - NIVissimConnectionCluster *c = *(clusters.end()-1); - clusters.erase(clusters.end()-1); - return std::pair(c, c->getNBNode()); - } else { - // !!! self-loop edge?! - return std::pair(static_cast(0), (*(myConnectionClusters.begin()))->getNBNode()); - } - */ -} - - -std::pair -NIVissimEdge::remapOneOfNodes(NBNodeCont& nc, - NIVissimDistrictConnection* d, - NBNode* fromNode, NBNode* toNode) { - std::string nid = "ParkingPlace" + toString(d->getID()); - if (d->geomPosition().distanceTo(fromNode->getPosition()) - < - d->geomPosition().distanceTo(toNode->getPosition())) { - - NBNode* newNode = new NBNode(nid, - fromNode->getPosition(), - SumoXMLNodeType::NOJUNCTION); - nc.erase(fromNode); - nc.insert(newNode); - return std::pair(newNode, toNode); - } else { - NBNode* newNode = new NBNode(nid, - toNode->getPosition(), - SumoXMLNodeType::NOJUNCTION); - nc.erase(toNode); - nc.insert(newNode); - return std::pair(fromNode, newNode); - } -} - - - -std::pair -NIVissimEdge::resolveSameNode(NBNodeCont& nc, double offset, - NBNode* prevFrom, NBNode* prevTo) { - // check whether the edge is connected to a district - // use it if so - NIVissimDistrictConnection* d = - NIVissimDistrictConnection::dict_findForEdge(myID); - if (d != nullptr) { - Position pos = d->geomPosition(); - double position = d->getPosition(); - // the district is at the begin of the edge - if (myGeom.length() - position > position) { - std::string nid = "ParkingPlace" + toString(d->getID()); - NBNode* node = nc.retrieve(nid); - if (node == nullptr) { - node = new NBNode(nid, - pos, SumoXMLNodeType::NOJUNCTION); - if (!nc.insert(node)) { - throw 1; - } - } - return std::pair(node, prevTo); - } - // the district is at the end of the edge - else { - std::string nid = "ParkingPlace" + toString(d->getID()); - NBNode* node = nc.retrieve(nid); - if (node == nullptr) { - node = new NBNode(nid, pos, SumoXMLNodeType::NOJUNCTION); - if (!nc.insert(node)) { - throw 1; - } - } - assert(node != 0); - return std::pair(prevFrom, node); - } - } - // otherwise, check whether the edge is some kind of - // a dead end... - // check which end is nearer to the node centre - if (myConnectionClusters.size() == 1) { - NBNode* node = prevFrom; // it is the same as getToNode() - - NIVissimConnectionCluster* c = *(myConnectionClusters.begin()); - // no end node given - if (c->around(myGeom.front(), offset) && !c->around(myGeom.back(), offset)) { - NBNode* end = new NBNode( - toString(myID) + "-End", - myGeom.back(), - SumoXMLNodeType::NOJUNCTION); - if (!nc.insert(end)) { - throw 1; - } - return std::pair(node, end); - } - - // no begin node given - if (!c->around(myGeom.front(), offset) && c->around(myGeom.back(), offset)) { - NBNode* beg = new NBNode( - toString(myID) + "-Begin", - myGeom.front(), - SumoXMLNodeType::NOJUNCTION); - if (!nc.insert(beg)) { - std::cout << "nope, NIVissimDisturbance" << std::endl; - throw 1; - } - return std::pair(beg, node); - } - - // self-loop edge - both points lie within the same cluster - if (c->around(myGeom.front()) && c->around(myGeom.back())) { - return std::pair(node, node); - } - } - // what to do in other cases? - // It simply is a self-looping edge.... - return std::pair(prevFrom, prevTo); -} - - - - -void -NIVissimEdge::setNodeCluster(int nodeid) { - myNode = nodeid; -} - - -void -NIVissimEdge::buildGeom() {} - - -void -NIVissimEdge::addIncomingConnection(int id) { - myIncomingConnections.push_back(id); -} - - -void -NIVissimEdge::addOutgoingConnection(int id) { - myOutgoingConnections.push_back(id); -} - - - -void -NIVissimEdge::mergedInto(NIVissimConnectionCluster* old, - NIVissimConnectionCluster* act) { - ConnectionClusters::iterator i = - std::find(myConnectionClusters.begin(), myConnectionClusters.end(), old); - if (i != myConnectionClusters.end()) { - myConnectionClusters.erase(i); - } - i = std::find(myConnectionClusters.begin(), myConnectionClusters.end(), act); - if (i == myConnectionClusters.end()) { - myConnectionClusters.push_back(act); - } -} - - - -void -NIVissimEdge::removeFromConnectionCluster(NIVissimConnectionCluster* c) { - ConnectionClusters::iterator i = - std::find(myConnectionClusters.begin(), myConnectionClusters.end(), c); - assert(i != myConnectionClusters.end()); - myConnectionClusters.erase(i); -} - - -void -NIVissimEdge::addToConnectionCluster(NIVissimConnectionCluster* c) { - ConnectionClusters::iterator i = - std::find(myConnectionClusters.begin(), myConnectionClusters.end(), c); - if (i == myConnectionClusters.end()) { - myConnectionClusters.push_back(c); - } -} - - -Position // !!! reference? -NIVissimEdge::getBegin2D() const { - return myGeom[0]; -} - - -Position // !!! reference? -NIVissimEdge::getEnd2D() const { - return myGeom[-1]; -} - - -double -NIVissimEdge::getLength() const { - return myGeom.length(); -} - - -void -NIVissimEdge::checkDistrictConnectionExistanceAt(double pos) { - if (find(myDistrictConnections.begin(), myDistrictConnections.end(), pos) == myDistrictConnections.end()) { - myDistrictConnections.push_back(pos); - /* int id = NIVissimConnection::getMaxID() + 1; - std::vector currentCluster; - currentCluster.push_back(id); - myConnectionClusters.push_back( - new NIVissimConnectionCluster(currentCluster, -1, myID));*/ - } -} - - -void -NIVissimEdge::setSpeed(int lane, int speedDist) { - while ((int)myPatchedSpeeds.size() <= lane) { - myPatchedSpeeds.push_back(-1); - } - myPatchedSpeeds[lane] = speedDist; -} - - -void -NIVissimEdge::dict_checkEdges2Join() { - // go through the edges - for (DictType::iterator i1 = myDict.begin(); i1 != myDict.end(); i1++) { - // retrieve needed values from the first edge - NIVissimEdge* e1 = (*i1).second; - const PositionVector& g1 = e1->getGeometry(); - // check all other edges - DictType::iterator i2 = i1; - i2++; - for (; i2 != myDict.end(); i2++) { - // retrieve needed values from the second edge - NIVissimEdge* e2 = (*i2).second; - const PositionVector& g2 = e2->getGeometry(); - // get the connection description - NIVissimConnection* c = e1->getConnectionTo(e2); - if (c == nullptr) { - c = e2->getConnectionTo(e1); - } - // the edge must not be a direct contiuation of the other - if (c != nullptr) { - if ((c->getFromEdgeID() == e1->getID() && fabs(c->getFromPosition() - e1->getGeometry().length()) < 5) - || - (c->getFromEdgeID() == e2->getID() && fabs(c->getFromPosition() - e2->getGeometry().length()) < 5)) { - - continue; - } - } - // only parallel edges which do end at the same node - // should be joined - // check for parallelity - // !!! the usage of an explicit value is not very fine - if (fabs(GeomHelper::angleDiff(g1.beginEndAngle(), g2.beginEndAngle())) > DEG2RAD(2.0)) { - // continue if the lines are not parallel - continue; - } - - // check whether the same node is approached - // (the distance between the ends should not be too large) - // !!! the usage of an explicit value is not very fine - if (g1.back().distanceTo(g2.back()) > 10) { - // continue if the lines do not end at the same length - continue; - } - // ok, seem to be different lanes for the same edge - // mark as possibly joined later - e1->addToTreatAsSame(e2); - e2->addToTreatAsSame(e1); - } - } -} - - -bool -NIVissimEdge::addToTreatAsSame(NIVissimEdge* e) { - if (e == this) { - return false; - } - // check whether this edge already knows about the other - if (find(myToTreatAsSame.begin(), myToTreatAsSame.end(), e) == myToTreatAsSame.end()) { - myToTreatAsSame.push_back(e); - return true; - } else { - return false; // !!! check this - } - /* - // - std::vector::iterator i; - // add to all other that shall be treated as same - bool changed = true; - while (changed) { - changed = false; - for (i = myToTreatAsSame.begin(); !changed && i != myToTreatAsSame.end(); i++) { - changed |= (*i)->addToTreatAsSame(e); - } - for (i = myToTreatAsSame.begin(); !changed && i != myToTreatAsSame.end(); i++) { - changed |= e->addToTreatAsSame(*i); - } - } - */ -} - -NIVissimConnection* -NIVissimEdge::getConnectionTo(NIVissimEdge* e) { - std::vector::iterator i; - for (i = myIncomingConnections.begin(); i != myIncomingConnections.end(); i++) { - NIVissimConnection* c = NIVissimConnection::dictionary(*i); - if (c->getFromEdgeID() == e->getID()) { - return c; - } - } - for (i = myOutgoingConnections.begin(); i != myOutgoingConnections.end(); i++) { - NIVissimConnection* c = NIVissimConnection::dictionary(*i); - if (c->getToEdgeID() == e->getID()) { - return c; - } - } - return nullptr; -} - - -const std::vector& -NIVissimEdge::getToTreatAsSame() const { - return myToTreatAsSame; -} - - -void -NIVissimEdge::reportUnsetSpeeds() { - if (myLanesWithMissingSpeeds.size() == 0) { - return; - } - std::ostringstream str; - str << "The following lanes have no explicit speed information:\n "; - for (std::vector::iterator i = myLanesWithMissingSpeeds.begin(); i != myLanesWithMissingSpeeds.end(); ++i) { - if (i != myLanesWithMissingSpeeds.begin()) { - str << ", "; - } - str << *i; - } - WRITE_WARNING(str.str()); -} - - -NIVissimEdge* -NIVissimEdge::getBestIncoming() const { - // @todo seems as this would have been a hard hack! - /* - for (std::vector::const_iterator i = myIncomingConnections.begin(); i != myIncomingConnections.end(); ++i) { - NIVissimConnection* c = NIVissimConnection::dictionary(*i); - return NIVissimEdge::dictionary(c->getFromEdgeID()); - } - return 0; - */ - if (myIncomingConnections.size() != 0) { - return NIVissimEdge::dictionary(NIVissimConnection::dictionary(myIncomingConnections.front())->getFromEdgeID()); - } - return nullptr; -} - - -NIVissimEdge* -NIVissimEdge::getBestOutgoing() const { - // @todo seems as this would have been a hard hack! - /* - for (std::vector::const_iterator i = myOutgoingConnections.begin(); i != myOutgoingConnections.end(); ++i) { - NIVissimConnection* c = NIVissimConnection::dictionary(*i); - return NIVissimEdge::dictionary(c->getToEdgeID()); - } - return 0; - */ - if (myOutgoingConnections.size() != 0) { - return NIVissimEdge::dictionary(NIVissimConnection::dictionary(myOutgoingConnections.front())->getToEdgeID()); - } - return nullptr; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimEdge.h b/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimEdge.h deleted file mode 100644 index d456b1a41..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimEdge.h +++ /dev/null @@ -1,298 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimEdge.h -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date End of 2002 -/// -// A temporary storage for edges imported from Vissim -/****************************************************************************/ -#pragma once -#include - -#include "NIVissimConnectionCluster.h" -#include -#include -#include -#include -#include -#include -#include "NIVissimAbstractEdge.h" -#include "NIVissimClosedLanesVector.h" - - -// =========================================================================== -// class declarations -// =========================================================================== -class NBNode; -class NBDistrictCont; -class NIVissimDistrictConnection; - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NIVissimEdge - * @brief A temporary storage for edges imported from Vissim - */ -class NIVissimEdge - : public NIVissimAbstractEdge { -public: - /// Constructor - NIVissimEdge(int id, const std::string& name, - const std::string& type, - std::vector laneWidths, - double zuschlag1, - double zuschlag2, double length, - const PositionVector& geom, - const NIVissimClosedLanesVector& clv); - - /// Destructor - ~NIVissimEdge(); - - void setNodeCluster(int nodeid); - void buildGeom(); - - /// Adds a connection where this edge is the destination - void addIncomingConnection(int id); - - /// Adds a connection where this edge is the source - void addOutgoingConnection(int id); - - /** @brief Returns the node at the given position - As this may be ambigous, a second node not to return may be supplied */ - NBNode* getNodeAt(const Position& p, NBNode* other = 0); - - /** Returns the begin position of the edge */ - Position getBegin2D() const; - - /// Returns the end position of the edge - Position getEnd2D() const; - - /// Returns the length of the node - double getLength() const; - - void checkDistrictConnectionExistanceAt(double pos); - - void mergedInto(NIVissimConnectionCluster* old, - NIVissimConnectionCluster* act); - - void removeFromConnectionCluster(NIVissimConnectionCluster* c); - void addToConnectionCluster(NIVissimConnectionCluster* c); - void setSpeed(int lane, int speedDist); - bool addToTreatAsSame(NIVissimEdge* e); - - NIVissimConnection* getConnectionTo(NIVissimEdge* e); - const std::vector& getToTreatAsSame() const; - - - /** @brief Returns whether this edge was found to be within a junction - * @return Whether this node is assumed to be within a junction - */ - bool wasWithinAJunction() const { - return myAmWithinJunction; - } - - NIVissimEdge* getBestIncoming() const; - NIVissimEdge* getBestOutgoing() const; - - friend class NIVissimNodeDef_Edges; - friend class NIVissimNodeDef_Poly; - -public: - /** @brief Adds the described item to the dictionary - Builds the edge first */ - static bool dictionary(int id, const std::string& name, - const std::string& type, int noLanes, double zuschlag1, - double zuschlag2, double length, - const PositionVector& geom, - const NIVissimClosedLanesVector& clv); - - /// Adds the edge to the dictionary - static bool dictionary(int id, NIVissimEdge* o); - - /// Returns the named edge from the dictionary - static NIVissimEdge* dictionary(int id); - - /** @brief Clusters connections of each edge - * - * For every edge stored in this container, its connections are collected and - * joined into "clusters" if they have the same "direction" (incoming/outgoing) - * and are not further than 10m away from each other. - * - * @todo Probably the distance (MAX_CLUSTER_DISTANCE=10m) should be made variable - */ - static void buildConnectionClusters(); - - /// Builds NBEdges from the VissimEdges within the dictionary - static void dict_buildNBEdges(NBDistrictCont& dc, NBNodeCont& nc, - NBEdgeCont& ec, double offset); - - static void dict_propagateSpeeds(); - - static void dict_checkEdges2Join(); - - - /** @brief Writes edges with unset speeds to the warnings message log instance - * - * Vissim has no direct speed definition of edges; still, we try to propagate - * speed changes along the streets. If a lane is not covered by such, its id - * is put into the static container "myLanesWithMissingSpeeds". - * If the option "vissim.report-unset-speeds" is set, all lane ids stored within - * this container are written. - */ - static void reportUnsetSpeeds(); - - -private: - /// The definition for a container for connection clusters - typedef std::vector ConnectionClusters; - -private: - /** @brief Builds the NBEdge from this VissimEdge - * - * @param[in] dc The district container used if this edge must be split - * @param[in] nc The node container used for (optionally) building this edge's nodes - * @param[in] ec The edge control to add this edge to - * @param[in] sameNodesOffset Offset used to discriminate nodes - * @exception ProcessError If one of the built nodes or edges could not be added to the according container - */ - void buildNBEdge(NBDistrictCont& dc, NBNodeCont& nc, - NBEdgeCont& ec, double sameNodesOffset); - - /// Returns the origin node - std::pair - getFromNode(NBNodeCont& nc, ConnectionClusters& clusters); - - /// Returns the destination node - std::pair - getToNode(NBNodeCont& nc, ConnectionClusters& clusters); - - /// Tries to resolve the problem that the same node has been returned as origin and destination node - std::pair resolveSameNode(NBNodeCont& nc, - double offset, NBNode* prevFrom, NBNode* prevTo); - -// double recheckSpeedPatches(); - - std::vector getOutgoingConnected(int lane) const; - - void propagateSpeed(double speed, std::vector forLanes); - - - void setDistrictSpeed(); - double getRealSpeed(int distNo); - void checkUnconnectedLaneSpeeds(); - void propagateOwn(); - - - -private: - static NBNode* getNodeSecure(int nodeid, const Position& pos, - const std::string& possibleName); - - std::pair - remapOneOfNodes(NBNodeCont& nc, - NIVissimDistrictConnection* d, - NBNode* fromNode, NBNode* toNode); - -private: - /** - * Sorts connections the edge participates in by their position along - * the given edge - */ - class connection_position_sorter { - public: - /// constructor - explicit connection_position_sorter(int edgeid); - - /// comparing operation - int operator()(int c1id, int c2id) const; - - private: - /// The id of the edge - int myEdgeID; - - }; - - - /** - * Sorts connection clusters the edge participates in by their - * position along the given edge - */ - class connection_cluster_position_sorter { - public: - /// constructor - explicit connection_cluster_position_sorter(int edgeid); - - /// comparing operation - int operator()(NIVissimConnectionCluster* cc1, - NIVissimConnectionCluster* cc2) const; - - private: - /// The id of the edge - int myEdgeID; - - }; - -private: - /// The name of the edge - std::string myName; - - /// The type of the edge - std::string myType; - - /// The number of lanes the edge has - int myNoLanes; - std::vector myLaneWidths; - - /// Additional load values for this edge - double myZuschlag1, myZuschlag2; - - /// List of lanes closed on this edge - NIVissimClosedLanesVector myClosedLanes; - - /// List of connection clusters along this edge - ConnectionClusters myConnectionClusters; - - /// List of connections incoming to this edge - std::vector myIncomingConnections; - - /// List of connections outgoing from this edge - std::vector myOutgoingConnections; - - std::vector myDistrictConnections; - - std::vector myPatchedSpeeds; - - std::vector myLaneSpeeds; - - std::vector myToTreatAsSame; - - /// @brief Information whether this edge was not build due to being within a junction - bool myAmWithinJunction; - -private: - /// @brief Definition of the dictionary type - typedef std::map DictType; - - /// @brief The dictionary - static DictType myDict; - - /// @brief The current maximum id; needed for further id assignment - static int myMaxID; - - static std::vector myLanesWithMissingSpeeds; - -}; diff --git a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimEdgePosMap.cpp b/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimEdgePosMap.cpp deleted file mode 100644 index aa6ce392c..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimEdgePosMap.cpp +++ /dev/null @@ -1,71 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimEdgePosMap.cpp -/// @author Daniel Krajzewicz -/// @date Sept 2002 -/// -// ------------------- -/****************************************************************************/ -#include - - -#include -#include "NIVissimEdgePosMap.h" - - -NIVissimEdgePosMap::NIVissimEdgePosMap() {} - - -NIVissimEdgePosMap::~NIVissimEdgePosMap() {} - - -void -NIVissimEdgePosMap::add(int edgeid, double pos) { - add(edgeid, pos, pos); -} - - -void -NIVissimEdgePosMap::add(int edgeid, double from, double to) { - if (from > to) { - double tmp = from; - from = to; - to = tmp; - } - ContType::iterator i = myCont.find(edgeid); - if (i == myCont.end()) { - myCont[edgeid] = Range(from, to); - } else { - double pfrom = (*i).second.first; - double pto = (*i).second.second; - if (pfrom < from) { - from = pfrom; - } - if (pto > to) { - to = pto; - } - myCont[edgeid] = Range(from, to); - } -} - - -void -NIVissimEdgePosMap::join(NIVissimEdgePosMap& with) { - for (ContType::iterator i = with.myCont.begin(); i != with.myCont.end(); i++) { - add((*i).first, (*i).second.first, (*i).second.second); - } -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimEdgePosMap.h b/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimEdgePosMap.h deleted file mode 100644 index c66a6dffe..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimEdgePosMap.h +++ /dev/null @@ -1,43 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimEdgePosMap.h -/// @author Daniel Krajzewicz -/// @date Sept 2002 -/// -// ------------------- -/****************************************************************************/ -#pragma once -#include - - -#include - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * - */ -class NIVissimEdgePosMap { -public: - NIVissimEdgePosMap(); - ~NIVissimEdgePosMap(); - void add(int edgeid, double pos); - void add(int edgeid, double from, double to); - void join(NIVissimEdgePosMap& with); -private: - typedef std::pair Range; - typedef std::map ContType; - ContType myCont; -}; diff --git a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimExtendedEdgePoint.cpp b/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimExtendedEdgePoint.cpp deleted file mode 100644 index 82468205c..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimExtendedEdgePoint.cpp +++ /dev/null @@ -1,88 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimExtendedEdgePoint.cpp -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Sept 2002 -/// -// ------------------- -/****************************************************************************/ -#include - -#include -#include -#include "NIVissimExtendedEdgePoint.h" -#include "NIVissimEdge.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -NIVissimExtendedEdgePoint::NIVissimExtendedEdgePoint( - int edgeid, const std::vector& lanes, double position, - const std::vector& assignedVehicles) - : myEdgeID(edgeid), myLanes(lanes), myPosition(position), - myAssignedVehicles(assignedVehicles) {} - - -NIVissimExtendedEdgePoint::~NIVissimExtendedEdgePoint() {} - - -int -NIVissimExtendedEdgePoint::getEdgeID() const { - return myEdgeID; -} - - -double -NIVissimExtendedEdgePoint::getPosition() const { - return myPosition; -} - - -Position -NIVissimExtendedEdgePoint::getGeomPosition() const { - return - NIVissimAbstractEdge::dictionary(myEdgeID)->getGeomPosition(myPosition); -} - - -const std::vector& -NIVissimExtendedEdgePoint::getLanes() const { - return myLanes; -} - - -void -NIVissimExtendedEdgePoint::recheckLanes(const NBEdge* const edge) { - // check whether an "all" indicator is there - bool hadAll = false; - for (std::vector::const_iterator i = myLanes.begin(); !hadAll && i != myLanes.end(); ++i) { - if ((*i) == -1) { - hadAll = true; - } - } - // no -> return - if (!hadAll) { - return; - } - // patch lane indices - myLanes.clear(); - for (int i = 0; i < (int) edge->getNumLanes(); ++i) { - myLanes.push_back(i); - } -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimExtendedEdgePoint.h b/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimExtendedEdgePoint.h deleted file mode 100644 index 6aefca3e0..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimExtendedEdgePoint.h +++ /dev/null @@ -1,71 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimExtendedEdgePoint.h -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Sept 2002 -/// -// ------------------- -/****************************************************************************/ -#pragma once -#include - -#include - - -// =========================================================================== -// class declarations -// =========================================================================== -class NBEdge; -class Position; - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * - */ -class NIVissimExtendedEdgePoint { -public: - /** @brief Constructor - * @param[in] edgeid The id of the Vissim-edge - * @param[in] lanes Lanes on which this point lies - * @param[in] position The position of this point at the edge - * @param[in] assignedVehicles Vehicle (type) indices which should be regarded by this point - */ - NIVissimExtendedEdgePoint(int edgeid, const std::vector& lanes, - double position, const std::vector& assignedVehicles); - ~NIVissimExtendedEdgePoint(); - int getEdgeID() const; - double getPosition() const; - Position getGeomPosition() const; - const std::vector& getLanes() const; - - - /** @brief Resets lane numbers if all lanes shall be used - * - * If myLanes contains a -1, the content of myLanes is replaced - * by indices of all lanes of the given edge. - * - * @param[in] The built edge - */ - void recheckLanes(const NBEdge* const edge); - -private: - int myEdgeID; - std::vector myLanes; - double myPosition; - std::vector myAssignedVehicles; -}; diff --git a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimExtendedEdgePointVector.h b/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimExtendedEdgePointVector.h deleted file mode 100644 index 3bff35089..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimExtendedEdgePointVector.h +++ /dev/null @@ -1,27 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimExtendedEdgePointVector.h -/// @author Daniel Krajzewicz -/// @date Sept 2002 -/// -// ------------------- -/****************************************************************************/ -#pragma once -#include - - -#include -#include "NIVissimExtendedEdgePoint.h" - -typedef std::vector NIVissimtendedEdgePointVector; diff --git a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimNodeCluster.cpp b/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimNodeCluster.cpp deleted file mode 100644 index 54f6d05e2..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimNodeCluster.cpp +++ /dev/null @@ -1,298 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimNodeCluster.cpp -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date Sept 2002 -/// -// ------------------- -/****************************************************************************/ -#include - - -#include -#include -#include -#include -#include -#include -#include -#include -#include "NIVissimTL.h" -#include "NIVissimDisturbance.h" -#include "NIVissimConnection.h" -#include "NIVissimNodeCluster.h" - - -// =========================================================================== -// static member variables -// =========================================================================== -NIVissimNodeCluster::DictType NIVissimNodeCluster::myDict; -int NIVissimNodeCluster::myCurrentID = 1; - - -// =========================================================================== -// method definitions -// =========================================================================== -NIVissimNodeCluster::NIVissimNodeCluster(int id, int nodeid, int tlid, - const std::vector& connectors, - const std::vector& disturbances, - bool amEdgeSplitOnly) - : myID(id), myNodeID(nodeid), myTLID(tlid), - myConnectors(connectors), myDisturbances(disturbances), - myNBNode(nullptr), myAmEdgeSplit(amEdgeSplitOnly) {} - - -NIVissimNodeCluster::~NIVissimNodeCluster() {} - - - - -bool -NIVissimNodeCluster::dictionary(int id, NIVissimNodeCluster* o) { - DictType::iterator i = myDict.find(id); - if (i == myDict.end()) { - myDict[id] = o; - return true; - } - assert(false); - return false; -} - - -int -NIVissimNodeCluster::dictionary(int nodeid, int tlid, - const std::vector& connectors, - const std::vector& disturbances, - bool amEdgeSplitOnly) { - int id = nodeid; - if (nodeid < 0) { - id = myCurrentID++; - } - NIVissimNodeCluster* o = new NIVissimNodeCluster(id, - nodeid, tlid, connectors, disturbances, amEdgeSplitOnly); - dictionary(id, o); - return id; -} - - -NIVissimNodeCluster* -NIVissimNodeCluster::dictionary(int id) { - DictType::iterator i = myDict.find(id); - if (i == myDict.end()) { - return nullptr; - } - return (*i).second; -} - - - -int -NIVissimNodeCluster::contSize() { - return (int)myDict.size(); -} - - - -std::string -NIVissimNodeCluster::getNodeName() const { - if (myTLID == -1) { - return toString(myID); - } else { - return toString(myID) + "LSA " + toString(myTLID); - } -} - - -void -NIVissimNodeCluster::buildNBNode(NBNodeCont& nc) { - if (myConnectors.size() == 0) { - return; // !!! Check, whether this can happen - } - - // compute the position - PositionVector crossings; - std::vector::iterator i, j; - // check whether this is a split of an edge only - if (myAmEdgeSplit) { -// !!! should be assert(myTLID==-1); - for (i = myConnectors.begin(); i != myConnectors.end(); i++) { - NIVissimConnection* c1 = NIVissimConnection::dictionary(*i); - crossings.push_back_noDoublePos(c1->getFromGeomPosition()); - } - } else { - // compute the places the connections cross - for (i = myConnectors.begin(); i != myConnectors.end(); i++) { - NIVissimAbstractEdge* c1 = NIVissimAbstractEdge::dictionary(*i); - c1->buildGeom(); - for (j = i + 1; j != myConnectors.end(); j++) { - NIVissimAbstractEdge* c2 = NIVissimAbstractEdge::dictionary(*j); - c2->buildGeom(); - if (c1->crossesEdge(c2)) { - crossings.push_back_noDoublePos(c1->crossesEdgeAtPoint(c2)); - } - } - } - // alternative way: compute via positions of crossings - if (crossings.size() == 0) { - for (i = myConnectors.begin(); i != myConnectors.end(); i++) { - NIVissimConnection* c1 = NIVissimConnection::dictionary(*i); - crossings.push_back_noDoublePos(c1->getFromGeomPosition()); - crossings.push_back_noDoublePos(c1->getToGeomPosition()); - } - } - } - // get the position (center) - Position pos = crossings.getPolygonCenter(); - // build the node - /* if(myTLID!=-1) { - !!! NIVissimTL *tl = NIVissimTL::dictionary(myTLID); - if(tl->getType()=="festzeit") { - node = new NBNode(getNodeName(), pos.x(), pos.y(), - "traffic_light"); - } else { - node = new NBNode(getNodeName(), pos.x(), pos.y(), - "actuated_traffic_light"); - } - }*/ - NBNode* node = new NBNode(getNodeName(), pos, SumoXMLNodeType::PRIORITY); - if (!nc.insert(node)) { - delete node; - throw 1; - } - myNBNode = node; -} - - -void -NIVissimNodeCluster::buildNBNodes(NBNodeCont& nc) { - for (DictType::iterator i = myDict.begin(); i != myDict.end(); i++) { - (*i).second->buildNBNode(nc); - } -} - - - -void -NIVissimNodeCluster::dict_recheckEdgeChanges() { - return; -} - - -int -NIVissimNodeCluster::getFromNode(int edgeid) { - int ret = -1; - for (DictType::iterator i = myDict.begin(); i != myDict.end(); i++) { - NIVissimNodeCluster* c = (*i).second; - for (std::vector::iterator j = c->myConnectors.begin(); j != c->myConnectors.end(); j++) { - NIVissimConnection* conn = NIVissimConnection::dictionary(*j); - if (conn != nullptr && conn->getToEdgeID() == edgeid) { -// return (*i).first; - if (ret != -1 && (*i).first != ret) { -// "NIVissimNodeCluster:DoubleNode:" << ret << endl; - throw 1; // an edge should not outgo from two different nodes -// but actually, a joined cluster may posess a connections more than once - } - ret = (*i).first; - } - } - } - return ret; -} - - -int -NIVissimNodeCluster::getToNode(int edgeid) { - int ret = -1; - for (DictType::iterator i = myDict.begin(); i != myDict.end(); i++) { - NIVissimNodeCluster* c = (*i).second; - for (std::vector::iterator j = c->myConnectors.begin(); j != c->myConnectors.end(); j++) { - NIVissimConnection* conn = NIVissimConnection::dictionary(*j); - if (conn != nullptr && conn->getFromEdgeID() == edgeid) { -// return (*i).first; - if (ret != -1 && ret != (*i).first) { -// << "NIVissimNodeCluster: multiple to-nodes" << endl; - throw 1; // an edge should not outgo from two different nodes -// but actually, a joined cluster may posess a connections more than once - - } - ret = (*i).first; - } - } - } - return ret; -} - - -void -NIVissimNodeCluster::_debugOut(std::ostream& into) { - for (DictType::iterator i = myDict.begin(); i != myDict.end(); i++) { - NIVissimNodeCluster* c = (*i).second; - into << std::endl << c->myID << ":"; - for (std::vector::iterator j = c->myConnectors.begin(); j != c->myConnectors.end(); j++) { - if (j != c->myConnectors.begin()) { - into << ", "; - } - into << (*j); - } - } - into << "=======================" << std::endl; -} - - - -NBNode* -NIVissimNodeCluster::getNBNode() const { - return myNBNode; -} - - -Position -NIVissimNodeCluster::getPos() const { - return myPosition; -} - - -void -NIVissimNodeCluster::dict_addDisturbances(NBDistrictCont& dc, - NBNodeCont& nc, NBEdgeCont& ec) { - for (DictType::iterator i = myDict.begin(); i != myDict.end(); i++) { - const std::vector& disturbances = (*i).second->myDisturbances; - NBNode* node = nc.retrieve((*i).second->getNodeName()); - for (std::vector::const_iterator j = disturbances.begin(); j != disturbances.end(); j++) { - NIVissimDisturbance* disturbance = NIVissimDisturbance::dictionary(*j); - disturbance->addToNode(node, dc, nc, ec); - } - } - NIVissimDisturbance::reportRefused(); -} - - -void -NIVissimNodeCluster::clearDict() { - for (DictType::iterator i = myDict.begin(); i != myDict.end(); i++) { - delete (*i).second; - } - myDict.clear(); -} - - -void -NIVissimNodeCluster::setCurrentVirtID(int id) { - myCurrentID = id; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimNodeCluster.h b/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimNodeCluster.h deleted file mode 100644 index fc526401a..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimNodeCluster.h +++ /dev/null @@ -1,92 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimNodeCluster.h -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Sept 2002 -/// -// ------------------- -/****************************************************************************/ -#pragma once -#include - -#include -#include - - -// =========================================================================== -// class declarations -// =========================================================================== -class NBNode; -class NBNodeCont; -class NBEdgeCont; -class NBDistrictCont; - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * - */ -class NIVissimNodeCluster { -public: - NIVissimNodeCluster(int id, int nodeid, int tlid, - const std::vector& connectors, - const std::vector& disturbances, - bool amEdgeSplitOnly); - ~NIVissimNodeCluster(); - int getID() const { - return myID; - } - void buildNBNode(NBNodeCont& nc); - bool recheckEdgeChanges(); - NBNode* getNBNode() const; - Position getPos() const; - std::string getNodeName() const; - - -public: - static bool dictionary(int id, NIVissimNodeCluster* o); - static int dictionary(int nodeid, int tlid, const std::vector& connectors, - const std::vector& disturbances, bool amEdgeSplitOnly); - static NIVissimNodeCluster* dictionary(int id); - static int contSize(); - static void assignToEdges(); - static void buildNBNodes(NBNodeCont& nc); - static void dict_recheckEdgeChanges(); - static int getFromNode(int edgeid); - static int getToNode(int edgeid); - static void _debugOut(std::ostream& into); - static void dict_addDisturbances(NBDistrictCont& dc, - NBNodeCont& nc, NBEdgeCont& ec); - static void clearDict(); - static void setCurrentVirtID(int id); - - -private: - - int myID; - int myNodeID; - int myTLID; - std::vector myConnectors; - std::vector myDisturbances; - Position myPosition; - typedef std::map DictType; - static DictType myDict; - static int myCurrentID; - NBNode* myNBNode; - bool myAmEdgeSplit; - -}; diff --git a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimNodeDef.cpp b/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimNodeDef.cpp deleted file mode 100644 index 06e08e86b..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimNodeDef.cpp +++ /dev/null @@ -1,138 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2002-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimNodeDef.cpp -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Sept 2002 -/// -// ------------------- -/****************************************************************************/ -#include - - -#include // !!! debug -#include -#include "NIVissimNodeDef.h" -#include "NIVissimConnection.h" -#include "NIVissimDisturbance.h" -#include "NIVissimTL.h" - - -// =========================================================================== -// static member variables -// =========================================================================== -NIVissimNodeDef::DictType NIVissimNodeDef::myDict; -int NIVissimNodeDef::myMaxID = 0; - - -// =========================================================================== -// method definitions -// =========================================================================== -NIVissimNodeDef::NIVissimNodeDef(int id, const std::string& name) - : myID(id), myName(name) {} - - -NIVissimNodeDef::~NIVissimNodeDef() {} - - -bool -NIVissimNodeDef::dictionary(int id, NIVissimNodeDef* o) { - DictType::iterator i = myDict.find(id); - if (i == myDict.end()) { - myDict[id] = o; - myMaxID = myMaxID > id - ? myMaxID - : id; -// o->computeBounding(); - return true; - } - return false; -} - - -NIVissimNodeDef* -NIVissimNodeDef::dictionary(int id) { - DictType::iterator i = myDict.find(id); - if (i == myDict.end()) { - return nullptr; - } - return (*i).second; -} - -/* -void -NIVissimNodeDef::buildNodeClusters() -{ - for(DictType::iterator i=myDict.begin(); i!=myDict.end(); i++) { - int cluster = (*i).second->buildNodeCluster(); - } -} -*/ - - -/* - -std::vector -NIVissimNodeDef::getWithin(const AbstractPoly &p, double off) -{ - std::vector ret; - for(DictType::iterator i=myDict.begin(); i!=myDict.end(); i++) { - NIVissimNodeDef *d = (*i).second; - if(d->partialWithin(p, off)) { - ret.push_back((*i).first); - } - } - return ret; -} - -bool -NIVissimNodeDef::partialWithin(const AbstractPoly &p, double off) const -{ - assert(myBoundary!=0&&myBoundary->xmax()>=myBoundary->xmin()); - return myBoundary->partialWithin(p, off); -} - - -void -NIVissimNodeDef::dict_assignConnectionsToNodes() { - for (DictType::iterator i = myDict.begin(); i != myDict.end(); i++) { - (*i).second->searchAndSetConnections(); - } -} -*/ - - -int -NIVissimNodeDef::dictSize() { - return (int)myDict.size(); -} - - - -void -NIVissimNodeDef::clearDict() { - for (DictType::iterator i = myDict.begin(); i != myDict.end(); i++) { - delete (*i).second; - } - myDict.clear(); -} - - -int -NIVissimNodeDef::getMaxID() { - return myMaxID; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimNodeDef.h b/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimNodeDef.h deleted file mode 100644 index 878ca442f..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimNodeDef.h +++ /dev/null @@ -1,58 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2002-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimNodeDef.h -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Sept 2002 -/// -// ------------------- -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include -#include "NIVissimExtendedEdgePointVector.h" -#include "NIVissimNodeCluster.h" - - -class NIVissimNodeDef { -public: - NIVissimNodeDef(int id, const std::string& name); - virtual ~NIVissimNodeDef(); - int buildNodeCluster(); -// virtual void computeBounding() = 0; -// bool partialWithin(const AbstractPoly &p, double off=0.0) const; -// virtual void searchAndSetConnections() = 0; - virtual double getEdgePosition(int edgeid) const = 0; - -public: - static bool dictionary(int id, NIVissimNodeDef* o); - static NIVissimNodeDef* dictionary(int id); -// static std::vector getWithin(const AbstractPoly &p, double off=0.0); -// static void buildNodeClusters(); -// static void dict_assignConnectionsToNodes(); - static int dictSize(); - static void clearDict(); - static int getMaxID(); -protected: - int myID; - std::string myName; - -private: - typedef std::map DictType; - static DictType myDict; - static int myMaxID; -}; diff --git a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimNodeDef_Edges.cpp b/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimNodeDef_Edges.cpp deleted file mode 100644 index 90b7e74b0..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimNodeDef_Edges.cpp +++ /dev/null @@ -1,112 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimNodeDef_Edges.cpp -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Sept 2002 -/// -// ------------------- -/****************************************************************************/ -#include - - - -#include -#include -#include -#include -#include -#include "NIVissimNodeParticipatingEdgeVector.h" -#include "NIVissimNodeDef.h" -#include "NIVissimEdge.h" -#include "NIVissimNodeDef_Edges.h" -#include "NIVissimDisturbance.h" -#include "NIVissimConnection.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -NIVissimNodeDef_Edges::NIVissimNodeDef_Edges(int id, - const std::string& name, const NIVissimNodeParticipatingEdgeVector& edges) - : NIVissimNodeDef(id, name), myEdges(edges) {} - - -NIVissimNodeDef_Edges::~NIVissimNodeDef_Edges() { - for (NIVissimNodeParticipatingEdgeVector::iterator i = myEdges.begin(); i != myEdges.end(); i++) { - delete (*i); - } - myEdges.clear(); -} - - -bool -NIVissimNodeDef_Edges::dictionary(int id, const std::string& name, - const NIVissimNodeParticipatingEdgeVector& edges) { - NIVissimNodeDef_Edges* o = new NIVissimNodeDef_Edges(id, name, edges); - if (!NIVissimNodeDef::dictionary(id, o)) { - delete o; - return false; - } - return true; -} - - -/* -void -NIVissimNodeDef_Edges::searchAndSetConnections() { - std::vector connections; - std::vector edges; - Boundary boundary; - for (NIVissimNodeParticipatingEdgeVector::const_iterator i = myEdges.begin(); i != myEdges.end(); i++) { - NIVissimNodeParticipatingEdge* edge = *i; - NIVissimConnection* c = - NIVissimConnection::dictionary(edge->getID()); - NIVissimEdge* e = - NIVissimEdge::dictionary(edge->getID()); - if (c != 0) { - connections.push_back(edge->getID()); - boundary.add(c->getFromGeomPosition()); - boundary.add(c->getToGeomPosition()); - c->setNodeCluster(myID); - } - if (e != 0) { - edges.push_back(edge->getID()); - boundary.add(e->getGeomPosition(edge->getFromPos())); - boundary.add(e->getGeomPosition(edge->getToPos())); - } - } - NIVissimConnectionCluster* c = - new NIVissimConnectionCluster(connections, boundary, myID, edges); - for (std::vector::iterator j = edges.begin(); j != edges.end(); j++) { - NIVissimEdge* edge = NIVissimEdge::dictionary(*j); - edge->myConnectionClusters.push_back(c); - } -} -*/ - - -double -NIVissimNodeDef_Edges::getEdgePosition(int edgeid) const { - for (NIVissimNodeParticipatingEdgeVector::const_iterator i = myEdges.begin(); i != myEdges.end(); i++) { - NIVissimNodeParticipatingEdge* edge = *i; - if (edge->getID() == edgeid) { - return (edge->getFromPos() + edge->getToPos()) / (double) 2.0; - } - } - return -1; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimNodeDef_Edges.h b/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimNodeDef_Edges.h deleted file mode 100644 index 180c40005..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimNodeDef_Edges.h +++ /dev/null @@ -1,68 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimNodeDef_Edges.h -/// @author Daniel Krajzewicz -/// @date Sept 2002 -/// -// ------------------- -/****************************************************************************/ -#pragma once -#include - - -#include -#include -#include "NIVissimNodeParticipatingEdgeVector.h" -#include "NIVissimExtendedEdgePoint.h" -#include "NIVissimNodeDef.h" - -class NIVissimNodeDef_Edges : - public NIVissimNodeDef { -public: - NIVissimNodeDef_Edges(int id, const std::string& name, - const NIVissimNodeParticipatingEdgeVector& edges); - virtual ~NIVissimNodeDef_Edges(); - static bool dictionary(int id, const std::string& name, - const NIVissimNodeParticipatingEdgeVector& edges); -// virtual void computeBounding(); -// virtual void searchAndSetConnections(); - virtual double getEdgePosition(int edgeid) const; - - /** - * - */ - class id_matches { - public: - explicit id_matches(int id) : myEdgeID(id) { } - bool operator()(NIVissimNodeParticipatingEdge* e) { - return e->getID() == myEdgeID; - } - private: - int myEdgeID; - }; - - class lying_within_match { - public: - explicit lying_within_match(NIVissimNodeParticipatingEdge* e) : myEdge(e) { } - bool operator()(NIVissimExtendedEdgePoint* e) { - return e->getEdgeID() == myEdge->getID() && - myEdge->positionLiesWithin(e->getPosition()); - } - private: - NIVissimNodeParticipatingEdge* myEdge; - }; - -protected: - NIVissimNodeParticipatingEdgeVector myEdges; -}; diff --git a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimNodeDef_Poly.cpp b/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimNodeDef_Poly.cpp deleted file mode 100644 index e0c219338..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimNodeDef_Poly.cpp +++ /dev/null @@ -1,62 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimNodeDef_Poly.cpp -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Sept 2002 -/// -// ------------------- -/****************************************************************************/ -#include - - -#include -#include -#include -#include -#include -#include "NIVissimEdge.h" -#include "NIVissimNodeDef.h" -#include "NIVissimNodeDef_Poly.h" -#include "NIVissimConnection.h" -#include "NIVissimAbstractEdge.h" -#include - - -// =========================================================================== -// method definitions -// =========================================================================== -NIVissimNodeDef_Poly::NIVissimNodeDef_Poly(int id, const std::string& name, - const PositionVector& poly) - : NIVissimNodeDef_Edges(id, name, NIVissimNodeParticipatingEdgeVector()), - myPoly(poly) {} - - -NIVissimNodeDef_Poly::~NIVissimNodeDef_Poly() {} - - -bool -NIVissimNodeDef_Poly::dictionary(int id, const std::string& name, - const PositionVector& poly) { - NIVissimNodeDef_Poly* o = new NIVissimNodeDef_Poly(id, name, poly); - if (!NIVissimNodeDef::dictionary(id, o)) { - delete o; - assert(false); - return false; - } - return true; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimNodeDef_Poly.h b/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimNodeDef_Poly.h deleted file mode 100644 index 2e675c7e1..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimNodeDef_Poly.h +++ /dev/null @@ -1,44 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimNodeDef_Poly.h -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Sept 2002 -/// -// ------------------- -/****************************************************************************/ -#pragma once -#include - - -#include -#include -#include -#include "NIVissimNodeDef_Edges.h" - -class NIVissimNodeDef_Poly : - public NIVissimNodeDef_Edges { -public: - NIVissimNodeDef_Poly(int id, const std::string& name, - const PositionVector& poly); - virtual ~NIVissimNodeDef_Poly(); - static bool dictionary(int id, const std::string& name, - const PositionVector& poly); -// virtual void computeBounding(); -// double getEdgePosition(int edgeid) const; -// void searchAndSetConnections(double offset); -private: - PositionVector myPoly; - -}; diff --git a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimNodeParticipatingEdge.cpp b/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimNodeParticipatingEdge.cpp deleted file mode 100644 index 3c6ad8887..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimNodeParticipatingEdge.cpp +++ /dev/null @@ -1,62 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimNodeParticipatingEdge.cpp -/// @author Daniel Krajzewicz -/// @date Sept 2002 -/// -// ------------------- -/****************************************************************************/ -#include - - -#include "NIVissimEdge.h" -#include "NIVissimConnection.h" -#include "NIVissimNodeParticipatingEdge.h" - - - -NIVissimNodeParticipatingEdge::NIVissimNodeParticipatingEdge( - int edgeid, double frompos, double topos) - : myEdgeID(edgeid), myFromPos(frompos), myToPos(topos) {} - -NIVissimNodeParticipatingEdge::~NIVissimNodeParticipatingEdge() {} - - -int -NIVissimNodeParticipatingEdge::getID() const { - return myEdgeID; -} - - -bool -NIVissimNodeParticipatingEdge::positionLiesWithin(double pos) const { - return - (myFromPos < myToPos && myFromPos >= pos && myToPos <= pos) - || - (myFromPos > myToPos && myFromPos <= pos && myToPos >= pos); -} - -double -NIVissimNodeParticipatingEdge::getFromPos() const { - return myFromPos; -} - - -double -NIVissimNodeParticipatingEdge::getToPos() const { - return myToPos; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimNodeParticipatingEdge.h b/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimNodeParticipatingEdge.h deleted file mode 100644 index 3b63e8d27..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimNodeParticipatingEdge.h +++ /dev/null @@ -1,46 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimNodeParticipatingEdge.h -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Sept 2002 -/// -// ------------------- -/****************************************************************************/ -#pragma once -#include - - -#include -#include - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * - */ -class NIVissimNodeParticipatingEdge { -public: - NIVissimNodeParticipatingEdge(int edgeid, - double frompos, double topos); - ~NIVissimNodeParticipatingEdge(); - int getID() const; - bool positionLiesWithin(double pos) const; - double getFromPos() const; - double getToPos() const; -private: - int myEdgeID; - double myFromPos, myToPos; -}; diff --git a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimNodeParticipatingEdgeVector.h b/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimNodeParticipatingEdgeVector.h deleted file mode 100644 index 6e7974b1c..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimNodeParticipatingEdgeVector.h +++ /dev/null @@ -1,27 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimNodeParticipatingEdgeVector.h -/// @author Daniel Krajzewicz -/// @date Sept 2002 -/// -// ------------------- -/****************************************************************************/ -#pragma once -#include - - -#include -#include "NIVissimNodeParticipatingEdge.h" - -typedef std::vector NIVissimNodeParticipatingEdgeVector; diff --git a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimSource.cpp b/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimSource.cpp deleted file mode 100644 index 5eedecc9a..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimSource.cpp +++ /dev/null @@ -1,79 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSource.cpp -/// @author Daniel Krajzewicz -/// @date Sept 2002 -/// -// ------------------- -/****************************************************************************/ -#include - - -#include -#include -#include "NIVissimSource.h" - -NIVissimSource::DictType NIVissimSource::myDict; - -NIVissimSource::NIVissimSource(const std::string& id, const std::string& name, - const std::string& edgeid) - : myID(id), myName(name), myEdgeID(edgeid) {} - - -NIVissimSource::~NIVissimSource() {} - - -bool -NIVissimSource::dictionary(const std::string& id, const std::string& name, - const std::string& edgeid) { - NIVissimSource* o = new NIVissimSource(id, name, edgeid); - if (!dictionary(id, o)) { - delete o; - return false; - } - return true; -} - - -bool -NIVissimSource::dictionary(const std::string& id, NIVissimSource* o) { - DictType::iterator i = myDict.find(id); - if (i == myDict.end()) { - myDict[id] = o; - return true; - } - return false; -} - - -NIVissimSource* -NIVissimSource::dictionary(const std::string& id) { - DictType::iterator i = myDict.find(id); - if (i == myDict.end()) { - return nullptr; - } - return (*i).second; -} - - -void -NIVissimSource::clearDict() { - for (DictType::iterator i = myDict.begin(); i != myDict.end(); i++) { - delete (*i).second; - } - myDict.clear(); -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimSource.h b/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimSource.h deleted file mode 100644 index e19b1ddc6..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimSource.h +++ /dev/null @@ -1,51 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSource.h -/// @author Daniel Krajzewicz -/// @date Sept 2002 -/// -// ------------------- -/****************************************************************************/ -#pragma once -#include - - -#include -#include - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * - */ -class NIVissimSource { -public: - NIVissimSource(const std::string& id, const std::string& name, - const std::string& edgeid); - ~NIVissimSource(); - static bool dictionary(const std::string& id, const std::string& name, - const std::string& edgeid); - static bool dictionary(const std::string& id, NIVissimSource* o); - static NIVissimSource* dictionary(const std::string& id); - static void clearDict(); -private: - std::string myID; - std::string myName; - std::string myEdgeID; - -private: - typedef std::map DictType; - static DictType myDict; -}; diff --git a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimTL.cpp b/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimTL.cpp deleted file mode 100644 index 5f670e694..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimTL.cpp +++ /dev/null @@ -1,433 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimTL.cpp -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date Sept 2002 -/// -// ------------------- -/****************************************************************************/ -#include - - -#include -#include -#include -#include -#include -#include -#include -#include "NIVissimConnection.h" -#include -#include -#include -#include -#include "NIVissimDisturbance.h" -#include "NIVissimNodeDef.h" -#include "NIVissimEdge.h" -#include "NIVissimTL.h" - - -// =========================================================================== -// static member variables -// =========================================================================== -NIVissimTL::SignalDictType NIVissimTL::NIVissimTLSignal::myDict; - - -// =========================================================================== -// method definitions -// =========================================================================== -NIVissimTL::NIVissimTLSignal::NIVissimTLSignal(int id, - const std::string& name, - const std::vector& groupids, - int edgeid, - int laneno, - double position, - const std::vector& vehicleTypes) - : myID(id), myName(name), myGroupIDs(groupids), - myEdgeID(edgeid), myLane(laneno), myPosition(position), - myVehicleTypes(vehicleTypes) {} - - -NIVissimTL::NIVissimTLSignal::~NIVissimTLSignal() {} - -bool -NIVissimTL::NIVissimTLSignal::isWithin(const PositionVector& poly) const { - return poly.around(getPosition()); -} - - -Position -NIVissimTL::NIVissimTLSignal::getPosition() const { - return NIVissimAbstractEdge::dictionary(myEdgeID)->getGeomPosition(myPosition); -} - - -bool -NIVissimTL::NIVissimTLSignal::dictionary(int lsaid, int id, - NIVissimTL::NIVissimTLSignal* o) { - SignalDictType::iterator i = myDict.find(lsaid); - if (i == myDict.end()) { - myDict[lsaid] = SSignalDictType(); - i = myDict.find(lsaid); - } - SSignalDictType::iterator j = (*i).second.find(id); - if (j == (*i).second.end()) { - myDict[lsaid][id] = o; - return true; - } - return false; -} - - -NIVissimTL::NIVissimTLSignal* -NIVissimTL::NIVissimTLSignal::dictionary(int lsaid, int id) { - SignalDictType::iterator i = myDict.find(lsaid); - if (i == myDict.end()) { - return nullptr; - } - SSignalDictType::iterator j = (*i).second.find(id); - if (j == (*i).second.end()) { - return nullptr; - } - return (*j).second; -} - - -void -NIVissimTL::NIVissimTLSignal::clearDict() { - for (SignalDictType::iterator i = myDict.begin(); i != myDict.end(); i++) { - for (SSignalDictType::iterator j = (*i).second.begin(); j != (*i).second.end(); j++) { - delete (*j).second; - } - } - myDict.clear(); -} - - -NIVissimTL::SSignalDictType -NIVissimTL::NIVissimTLSignal::getSignalsFor(int tlid) { - SignalDictType::iterator i = myDict.find(tlid); - if (i == myDict.end()) { - return SSignalDictType(); - } - return (*i).second; -} - - -bool -NIVissimTL::NIVissimTLSignal::addTo(NBEdgeCont& ec, NBLoadedTLDef* tl) const { - NIVissimConnection* c = NIVissimConnection::dictionary(myEdgeID); - NBConnectionVector assignedConnections; - if (c == nullptr) { - // What to do if on an edge? -> close all outgoing connections - NBEdge* edge = ec.retrievePossiblySplit(toString(myEdgeID), myPosition); - if (edge == nullptr) { - WRITE_WARNING("Could not set tls signal at edge '" + toString(myEdgeID) + "' - the edge was not built."); - return false; - } - // Check whether it is already known, which edges are approached - // by which lanes - // check whether to use the original lanes only - if (edge->lanesWereAssigned()) { - std::vector connections = edge->getConnectionsFromLane(myLane - 1); - for (std::vector::iterator i = connections.begin(); i != connections.end(); i++) { - const NBEdge::Connection& conn = *i; - assert(myLane - 1 < (int)edge->getNumLanes()); - assignedConnections.push_back(NBConnection(edge, myLane - 1, conn.toEdge, conn.toLane)); - } - } else { - WRITE_WARNING("Edge : Lanes were not assigned(!)"); - for (int j = 0; j < edge->getNumLanes(); j++) { - std::vector connections = edge->getConnectionsFromLane(j); - for (std::vector::iterator i = connections.begin(); i != connections.end(); i++) { - const NBEdge::Connection& conn = *i; - assignedConnections.push_back(NBConnection(edge, j, conn.toEdge, conn.toLane)); - } - } - } - } else { - // get the edges - NBEdge* tmpFrom = ec.retrievePossiblySplit(toString(c->getFromEdgeID()), toString(c->getToEdgeID()), true); - NBEdge* tmpTo = ec.retrievePossiblySplit(toString(c->getToEdgeID()), toString(c->getFromEdgeID()), false); - // check whether the edges are known - if (tmpFrom != nullptr && tmpTo != nullptr) { - // add connections this signal is responsible for - assignedConnections.push_back(NBConnection(tmpFrom, -1, tmpTo, -1)); - } else { - return false; - // !!! one of the edges could not be build - } - } - // add to the group - assert(myGroupIDs.size() != 0); - // @todo just another hack?! - /* - if (myGroupIDs.size() == 1) { - return tl->addToSignalGroup(toString(*(myGroupIDs.begin())), - assignedConnections); - } else { - // !!! - return tl->addToSignalGroup(toString(*(myGroupIDs.begin())), - assignedConnections); - } - */ - return tl->addToSignalGroup(toString(myGroupIDs.front()), assignedConnections); -} - - - - - - - - -NIVissimTL::GroupDictType NIVissimTL::NIVissimTLSignalGroup::myDict; - -NIVissimTL::NIVissimTLSignalGroup::NIVissimTLSignalGroup( - int id, - const std::string& name, - bool isGreenBegin, const std::vector& times, - SUMOTime tredyellow, SUMOTime tyellow) - : myID(id), myName(name), myTimes(times), - myFirstIsRed(!isGreenBegin), myTRedYellow(tredyellow), - myTYellow(tyellow) {} - - -NIVissimTL::NIVissimTLSignalGroup::~NIVissimTLSignalGroup() {} - - -bool -NIVissimTL::NIVissimTLSignalGroup::dictionary(int lsaid, int id, - NIVissimTL::NIVissimTLSignalGroup* o) { - GroupDictType::iterator i = myDict.find(lsaid); - if (i == myDict.end()) { - myDict[lsaid] = SGroupDictType(); - i = myDict.find(lsaid); - } - SGroupDictType::iterator j = (*i).second.find(id); - if (j == (*i).second.end()) { - myDict[lsaid][id] = o; - return true; - } - return false; - /* - GroupDictType::iterator i=myDict.find(id); - if(i==myDict.end()) { - myDict[id] = o; - return true; - } - return false; - */ -} - - -NIVissimTL::NIVissimTLSignalGroup* -NIVissimTL::NIVissimTLSignalGroup::dictionary(int lsaid, int id) { - GroupDictType::iterator i = myDict.find(lsaid); - if (i == myDict.end()) { - return nullptr; - } - SGroupDictType::iterator j = (*i).second.find(id); - if (j == (*i).second.end()) { - return nullptr; - } - return (*j).second; -} - -void -NIVissimTL::NIVissimTLSignalGroup::clearDict() { - for (GroupDictType::iterator i = myDict.begin(); i != myDict.end(); i++) { - for (SGroupDictType::iterator j = (*i).second.begin(); j != (*i).second.end(); j++) { - delete (*j).second; - } - } - myDict.clear(); -} - - -NIVissimTL::SGroupDictType -NIVissimTL::NIVissimTLSignalGroup::getGroupsFor(int tlid) { - GroupDictType::iterator i = myDict.find(tlid); - if (i == myDict.end()) { - return SGroupDictType(); - } - return (*i).second; -} - - -bool -NIVissimTL::NIVissimTLSignalGroup::addTo(NBLoadedTLDef* tl) const { - // get the color at the begin - NBTrafficLightDefinition::TLColor color = myFirstIsRed - ? NBTrafficLightDefinition::TLCOLOR_RED : NBTrafficLightDefinition::TLCOLOR_GREEN; - std::string id = toString(myID); - tl->addSignalGroup(id); // !!! myTimes als SUMOTime - for (std::vector::const_iterator i = myTimes.begin(); i != myTimes.end(); i++) { - tl->addSignalGroupPhaseBegin(id, (SUMOTime) *i, color); - color = color == NBTrafficLightDefinition::TLCOLOR_RED - ? NBTrafficLightDefinition::TLCOLOR_GREEN : NBTrafficLightDefinition::TLCOLOR_RED; - } - if (myTimes.size() == 0) { - if (myFirstIsRed) { - tl->addSignalGroupPhaseBegin(id, 0, NBTrafficLightDefinition::TLCOLOR_RED); - } else { - tl->addSignalGroupPhaseBegin(id, 0, NBTrafficLightDefinition::TLCOLOR_GREEN); - } - } - tl->setSignalYellowTimes(id, myTRedYellow, myTYellow); - return true; -} - - - - - - - - -NIVissimTL::DictType NIVissimTL::myDict; - -NIVissimTL::NIVissimTL(int id, const std::string& type, - const std::string& name, SUMOTime absdur, - SUMOTime offset) - : myID(id), myName(name), myAbsDuration(absdur), myOffset(offset), - myCurrentGroup(nullptr), myType(type) - -{} - - -NIVissimTL::~NIVissimTL() {} - - - - - -bool -NIVissimTL::dictionary(int id, const std::string& type, - const std::string& name, SUMOTime absdur, - SUMOTime offset) { - NIVissimTL* o = new NIVissimTL(id, type, name, absdur, offset); - if (!dictionary(id, o)) { - delete o; - return false; - } - return true; -} - -bool -NIVissimTL::dictionary(int id, NIVissimTL* o) { - DictType::iterator i = myDict.find(id); - if (i == myDict.end()) { - myDict[id] = o; - return true; - } - return false; -} - - -NIVissimTL* -NIVissimTL::dictionary(int id) { - DictType::iterator i = myDict.find(id); - if (i == myDict.end()) { - return nullptr; - } - return (*i).second; -} - - -void -NIVissimTL::clearDict() { - for (DictType::iterator i = myDict.begin(); i != myDict.end(); i++) { - delete (*i).second; - } - myDict.clear(); -} - - - - - -bool -NIVissimTL::dict_SetSignals(NBTrafficLightLogicCont& tlc, - NBEdgeCont& ec) { - int ref = 0; - int ref_groups = 0; - int ref_signals = 0; - int no_signals = 0; - int no_groups = 0; - for (DictType::iterator i = myDict.begin(); i != myDict.end(); i++) { - NIVissimTL* tl = (*i).second; - /* if(tl->myType!="festzeit") { - cout << " Warning: The traffic light '" << tl->myID - << "' could not be assigned to a node." << endl; - ref++; - continue; - }*/ - std::string id = toString(tl->myID); - TrafficLightType type = ((tl->getType() == "festzeit" || tl->getType() == "festzeit_fake") ? - TrafficLightType::STATIC : TrafficLightType::ACTUATED); - NBLoadedTLDef* def = new NBLoadedTLDef(ec, id, 0, type); - if (!tlc.insert(def)) { - WRITE_ERROR("Error on adding a traffic light\n Must be a multiple id ('" + id + "')"); - continue; - } - def->setCycleDuration((int) tl->myAbsDuration); - // add each group to the node's container - SGroupDictType sgs = NIVissimTLSignalGroup::getGroupsFor(tl->getID()); - for (SGroupDictType::const_iterator j = sgs.begin(); j != sgs.end(); j++) { - if (!(*j).second->addTo(def)) { - WRITE_WARNING("The signal group '" + toString((*j).first) + "' could not be assigned to tl '" + toString(tl->myID) + "'."); - ref_groups++; - } - no_groups++; - } - // add the signal group signals to the node - SSignalDictType signals = NIVissimTLSignal::getSignalsFor(tl->getID()); - for (SSignalDictType::const_iterator k = signals.begin(); k != signals.end(); k++) { - if (!(*k).second->addTo(ec, def)) { - WRITE_WARNING("The signal '" + toString((*k).first) + "' could not be assigned to tl '" + toString(tl->myID) + "'."); - ref_signals++; - } - no_signals++; - } - } - if (ref != 0) { - WRITE_WARNING("Could not set " + toString(ref) + " of " + toString((int)myDict.size()) + " traffic lights."); - } - if (ref_groups != 0) { - WRITE_WARNING("Could not set " + toString(ref_groups) + " of " + toString(no_groups) + " groups."); - } - if (ref_signals != 0) { - WRITE_WARNING("Could not set " + toString(ref_signals) + " of " + toString(no_signals) + " signals."); - } - return true; - -} - - -std::string -NIVissimTL::getType() const { - return myType; -} - - -int -NIVissimTL::getID() const { - return myID; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimTL.h b/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimTL.h deleted file mode 100644 index f8129444d..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimTL.h +++ /dev/null @@ -1,136 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimTL.h -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Sept 2002 -/// -// ------------------- -/****************************************************************************/ -#pragma once -#include - - -#include -#include -#include -#include -#include -#include - - -// =========================================================================== -// class declarations -// =========================================================================== -class NBTrafficLightLogicCont; -class NBLoadedTLDef; -class NBEdgeCont; - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NIVissimTL - */ -class NIVissimTL { -public: - NIVissimTL(int id, const std::string& type, const std::string& name, - SUMOTime absdur, SUMOTime offset); - ~NIVissimTL(); -// void computeBounding(); - std::string getType() const; - int getID() const; - -public: - static bool dictionary(int id, const std::string& type, - const std::string& name, SUMOTime absdur, SUMOTime offset); - static bool dictionary(int id, NIVissimTL* o); - static NIVissimTL* dictionary(int id); -// static std::vector getWithin(const AbstractPoly &poly, double offset); - static void clearDict(); - static bool dict_SetSignals(NBTrafficLightLogicCont& tlc, - NBEdgeCont& ec); - -public: - class NIVissimTLSignal; - class NIVissimTLSignalGroup; - typedef std::map SSignalDictType; - typedef std::map SGroupDictType; - typedef std::map SignalDictType; - typedef std::map GroupDictType; - - /** - * - */ - class NIVissimTLSignal { - public: - NIVissimTLSignal(int id, const std::string& name, - const std::vector& groupids, int edgeid, int laneno, - double position, const std::vector& assignedVehicleTypes); - ~NIVissimTLSignal(); - bool isWithin(const PositionVector& poly) const; - Position getPosition() const; - bool addTo(NBEdgeCont& ec, NBLoadedTLDef* node) const; - - public: - static bool dictionary(int lsaid, int id, NIVissimTLSignal* o); - static NIVissimTLSignal* dictionary(int lsaid, int id); - static void clearDict(); - static SSignalDictType getSignalsFor(int tlid); - - protected: - int myID; - std::string myName; - std::vector myGroupIDs; - int myEdgeID; - int myLane; - double myPosition; - std::vector myVehicleTypes; - static SignalDictType myDict; - }; - - class NIVissimTLSignalGroup { - public: - NIVissimTLSignalGroup(int id, const std::string& name, - bool isGreenBegin, const std::vector& times, - SUMOTime tredyellow, SUMOTime tyellow); - ~NIVissimTLSignalGroup(); - bool addTo(NBLoadedTLDef* node) const; - public: - static bool dictionary(int lsaid, int id, NIVissimTLSignalGroup* o); - static NIVissimTLSignalGroup* dictionary(int lsaid, int id); - static void clearDict(); - static SGroupDictType getGroupsFor(int tlid); - - private: - int myID; - std::string myName; - std::vector myTimes; - bool myFirstIsRed; - SUMOTime myTRedYellow, myTYellow; - static GroupDictType myDict; - }; - -protected: - int myID; - std::string myName; - SUMOTime myAbsDuration; - SUMOTime myOffset; - NIVissimTLSignalGroup* myCurrentGroup; - std::string myType; -private: - typedef std::map DictType; - static DictType myDict; -}; diff --git a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimTrafficDescription.cpp b/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimTrafficDescription.cpp deleted file mode 100644 index bbe1f26aa..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimTrafficDescription.cpp +++ /dev/null @@ -1,115 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimTrafficDescription.cpp -/// @author Daniel Krajzewicz -/// @date Sept 2002 -/// -// ------------------- -/****************************************************************************/ -#include - -#include -#include -#include -#include "NIVissimVehicleClassVector.h" -#include "NIVissimTrafficDescription.h" - - -// =========================================================================== -// member function definitions -// =========================================================================== -NIVissimTrafficDescription::DictType NIVissimTrafficDescription::myDict; - - -// =========================================================================== -// member method definitions -// =========================================================================== -NIVissimTrafficDescription::NIVissimTrafficDescription( - const std::string& name, - const NIVissimVehicleClassVector& vehicleTypes) - : myName(name), myVehicleTypes(vehicleTypes) {} - - -NIVissimTrafficDescription::~NIVissimTrafficDescription() { - for (NIVissimVehicleClassVector::iterator i = myVehicleTypes.begin(); i != myVehicleTypes.end(); i++) { - delete *i; - } - myVehicleTypes.clear(); -} - - -bool -NIVissimTrafficDescription::dictionary(int id, - const std::string& name, - const NIVissimVehicleClassVector& vehicleTypes) { - NIVissimTrafficDescription* o = new NIVissimTrafficDescription(name, vehicleTypes); - if (!dictionary(id, o)) { - delete o; - return false; - } - return true; -} - - -bool -NIVissimTrafficDescription::dictionary(int id, NIVissimTrafficDescription* o) { - DictType::iterator i = myDict.find(id); - if (i == myDict.end()) { - myDict[id] = o; - return true; - } - return false; -} - - -NIVissimTrafficDescription* -NIVissimTrafficDescription::dictionary(int id) { - DictType::iterator i = myDict.find(id); - if (i == myDict.end()) { - return nullptr; - } - return (*i).second; -} - - -void -NIVissimTrafficDescription::clearDict() { - for (DictType::iterator i = myDict.begin(); i != myDict.end(); i++) { - delete (*i).second; - } - myDict.clear(); -} - - - - -double -NIVissimTrafficDescription::meanSpeed(int id) { - NIVissimTrafficDescription* i = dictionary(id); - assert(i != 0); - return i->meanSpeed(); -} - - -double -NIVissimTrafficDescription::meanSpeed() const { - double speed = 0; - for (NIVissimVehicleClassVector::const_iterator i = myVehicleTypes.begin(); i != myVehicleTypes.end(); i++) { - speed += (*i)->getSpeed(); - } - return speed / (double) myVehicleTypes.size(); -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimTrafficDescription.h b/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimTrafficDescription.h deleted file mode 100644 index cad045e23..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimTrafficDescription.h +++ /dev/null @@ -1,52 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimTrafficDescription.h -/// @author Daniel Krajzewicz -/// @date Sept 2002 -/// -// ------------------- -/****************************************************************************/ -#pragma once -#include - - -#include -#include -#include "NIVissimVehicleClassVector.h" - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * - */ -class NIVissimTrafficDescription { -public: - NIVissimTrafficDescription(const std::string& name, - const NIVissimVehicleClassVector& vehicleTypes); - ~NIVissimTrafficDescription(); - static bool dictionary(int id, const std::string& name, - const NIVissimVehicleClassVector& vehicleTypes); - static bool dictionary(int id, NIVissimTrafficDescription* o); - static NIVissimTrafficDescription* dictionary(int id); - static void clearDict(); - static double meanSpeed(int id); - double meanSpeed() const; -private: - std::string myName; - NIVissimVehicleClassVector myVehicleTypes; -private: - typedef std::map DictType; - static DictType myDict; -}; diff --git a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimVehTypeClass.cpp b/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimVehTypeClass.cpp deleted file mode 100644 index cd4a697dc..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimVehTypeClass.cpp +++ /dev/null @@ -1,85 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2002-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimVehTypeClass.cpp -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Sept 2002 -/// -// ------------------- -/****************************************************************************/ -#include - -#include -#include -#include -#include "NIVissimVehTypeClass.h" - - -NIVissimVehTypeClass::DictType NIVissimVehTypeClass::myDict; - -NIVissimVehTypeClass::NIVissimVehTypeClass(int id, - const std::string& name, - const RGBColor& color, - std::vector& types) - : myID(id), myName(name), myColor(color), myTypes(types) {} - -NIVissimVehTypeClass::~NIVissimVehTypeClass() {} - - -bool -NIVissimVehTypeClass::dictionary(int id, const std::string& name, - const RGBColor& color, - std::vector& types) { - NIVissimVehTypeClass* o = new NIVissimVehTypeClass(id, name, color, types); - if (!dictionary(id, o)) { - delete o; - return false; - } - return true; -} - - - - -bool -NIVissimVehTypeClass::dictionary(int name, NIVissimVehTypeClass* o) { - DictType::iterator i = myDict.find(name); - if (i == myDict.end()) { - myDict[name] = o; - return true; - } - return false; -} - - -NIVissimVehTypeClass* -NIVissimVehTypeClass::dictionary(int name) { - DictType::iterator i = myDict.find(name); - if (i == myDict.end()) { - return nullptr; - } - return (*i).second; -} - - -void -NIVissimVehTypeClass::clearDict() { - for (DictType::iterator i = myDict.begin(); i != myDict.end(); i++) { - delete (*i).second; - } - myDict.clear(); -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimVehTypeClass.h b/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimVehTypeClass.h deleted file mode 100644 index ca9d2c1cd..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimVehTypeClass.h +++ /dev/null @@ -1,54 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2002-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimVehTypeClass.h -/// @author Michael Behrisch -/// @author Daniel Krajzewicz -/// @date Sept 2002 -/// -// ------------------- -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * - */ -class NIVissimVehTypeClass { -public: - NIVissimVehTypeClass(int id, const std::string& name, - const RGBColor& color, std::vector& types); - ~NIVissimVehTypeClass(); - static bool dictionary(int id, const std::string& name, - const RGBColor& color, std::vector& types); - static bool dictionary(int id, NIVissimVehTypeClass* o); - static NIVissimVehTypeClass* dictionary(int name); - static void clearDict(); - double meanSpeed() const; -private: - int myID; - std::string myName; - RGBColor myColor; - std::vector myTypes; -private: - typedef std::map DictType; - static DictType myDict; -}; diff --git a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimVehicleClass.cpp b/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimVehicleClass.cpp deleted file mode 100644 index 79440b13d..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimVehicleClass.cpp +++ /dev/null @@ -1,38 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimVehicleClass.cpp -/// @author Daniel Krajzewicz -/// @date Sept 2002 -/// -// ------------------- -/****************************************************************************/ -#include - - -#include "NIVissimVehicleClass.h" - -NIVissimVehicleClass::NIVissimVehicleClass(int vwish) - : myVWish(vwish) {} - - -NIVissimVehicleClass::~NIVissimVehicleClass() {} - - -int -NIVissimVehicleClass::getSpeed() const { - return myVWish; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimVehicleClass.h b/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimVehicleClass.h deleted file mode 100644 index 016630206..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimVehicleClass.h +++ /dev/null @@ -1,37 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimVehicleClass.h -/// @author Daniel Krajzewicz -/// @date Sept 2002 -/// -// ------------------- -/****************************************************************************/ -#pragma once -#include - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * - */ -class NIVissimVehicleClass { -public: - NIVissimVehicleClass(int vwish); - ~NIVissimVehicleClass(); - int getSpeed() const; -private: - int myVWish; -}; diff --git a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimVehicleClassVector.h b/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimVehicleClassVector.h deleted file mode 100644 index 97b9982c1..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimVehicleClassVector.h +++ /dev/null @@ -1,27 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimVehicleClassVector.h -/// @author Daniel Krajzewicz -/// @date Sept 2002 -/// -// ------------------- -/****************************************************************************/ -#pragma once -#include - - -#include -#include "NIVissimVehicleClass.h" - -typedef std::vector NIVissimVehicleClassVector; diff --git a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimVehicleType.cpp b/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimVehicleType.cpp deleted file mode 100644 index 10cf336ed..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimVehicleType.cpp +++ /dev/null @@ -1,78 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimVehicleType.cpp -/// @author Daniel Krajzewicz -/// @date Sept 2002 -/// -// ------------------- -/****************************************************************************/ -#include - - -#include "NIVissimVehicleType.h" - -NIVissimVehicleType::DictType NIVissimVehicleType::myDict; - -NIVissimVehicleType::NIVissimVehicleType(const std::string& name, - const std::string& category, const RGBColor& color) - : myName(name), myCategory(category), - myColor(color) {} - - -NIVissimVehicleType::~NIVissimVehicleType() {} - - - -bool -NIVissimVehicleType::dictionary(int id, const std::string& name, const std::string& category, - const RGBColor& color) { - NIVissimVehicleType* o = new NIVissimVehicleType(name, category, color); - if (!dictionary(id, o)) { - delete o; - return false; - } - return true; -} - - -bool -NIVissimVehicleType::dictionary(int id, NIVissimVehicleType* o) { - DictType::iterator i = myDict.find(id); - if (i == myDict.end()) { - myDict[id] = o; - return true; - } - return false; -} - - -NIVissimVehicleType* -NIVissimVehicleType::dictionary(int id) { - DictType::iterator i = myDict.find(id); - if (i == myDict.end()) { - return nullptr; - } - return (*i).second; -} - -void -NIVissimVehicleType::clearDict() { - for (DictType::iterator i = myDict.begin(); i != myDict.end(); i++) { - delete (*i).second; - } - myDict.clear(); -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimVehicleType.h b/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimVehicleType.h deleted file mode 100644 index a855bcd89..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/tempstructs/NIVissimVehicleType.h +++ /dev/null @@ -1,52 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimVehicleType.h -/// @author Daniel Krajzewicz -/// @date Sept 2002 -/// -// ------------------- -/****************************************************************************/ -#pragma once -#include - - -#include -#include -#include - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * - */ -class NIVissimVehicleType { -public: - NIVissimVehicleType(const std::string& name, - const std::string& category, const RGBColor& color); - ~NIVissimVehicleType(); - static bool dictionary(int id, const std::string& name, - const std::string& category, const RGBColor& color); - static bool dictionary(int id, NIVissimVehicleType* o); - static NIVissimVehicleType* dictionary(int id); - static void clearDict(); - -private: - std::string myName; - std::string myCategory; - RGBColor myColor; -private: - typedef std::map DictType; - static DictType myDict; -}; diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/CMakeLists.txt b/Util/OSM2ODR/src/netimport/vissim/typeloader/CMakeLists.txt deleted file mode 100644 index f0b363b5e..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/CMakeLists.txt +++ /dev/null @@ -1,115 +0,0 @@ -set(netimport_vissim_typeloader_STAT_SRCS - NIVissimSingleTypeParser_Auswertungsdefinition.cpp - NIVissimSingleTypeParser_Auswertungsdefinition.h - NIVissimSingleTypeParser_Detektordefinition.cpp - NIVissimSingleTypeParser_Detektordefinition.h - NIVissimSingleTypeParser_DynUml.cpp - NIVissimSingleTypeParser_DynUml.h - NIVissimSingleTypeParser_Einheitendefinition.cpp - NIVissimSingleTypeParser_Einheitendefinition.h - NIVissimSingleTypeParser_Emission.cpp - NIVissimSingleTypeParser_Emission.h - NIVissimSingleTypeParser_Fahrtverlaufdateien.cpp - NIVissimSingleTypeParser_Fahrtverlaufdateien.h - NIVissimSingleTypeParser_Fahrverhaltendefinition.cpp - NIVissimSingleTypeParser_Fahrverhaltendefinition.h - NIVissimSingleTypeParser_Fahrzeugklassendefinition.cpp - NIVissimSingleTypeParser_Fahrzeugklassendefinition.h - NIVissimSingleTypeParser_Fahrzeugtypdefinition.cpp - NIVissimSingleTypeParser_Fahrzeugtypdefinition.h - NIVissimSingleTypeParser_Fensterdefinition.cpp - NIVissimSingleTypeParser_Fensterdefinition.h - NIVissimSingleTypeParser_Gefahrwarnungsdefinition.cpp - NIVissimSingleTypeParser_Gefahrwarnungsdefinition.h - NIVissimSingleTypeParser_Gelbverhaltendefinition.cpp - NIVissimSingleTypeParser_Gelbverhaltendefinition.h - NIVissimSingleTypeParser_Geschwindigkeitsverteilungsdefinition.cpp - NIVissimSingleTypeParser_Geschwindigkeitsverteilungsdefinition.h - NIVissimSingleTypeParser_Haltestellendefinition.cpp - NIVissimSingleTypeParser_Haltestellendefinition.h - NIVissimSingleTypeParser_Kantensperrung.cpp - NIVissimSingleTypeParser_Kantensperrung.h - NIVissimSingleTypeParser_Kennungszeile.cpp - NIVissimSingleTypeParser_Kennungszeile.h - NIVissimSingleTypeParser_Knotendefinition.cpp - NIVissimSingleTypeParser_Knotendefinition.h - NIVissimSingleTypeParser_LSAKopplungsdefinition.cpp - NIVissimSingleTypeParser_LSAKopplungsdefinition.h - NIVissimSingleTypeParser_Laengenverteilungsdefinition.cpp - NIVissimSingleTypeParser_Laengenverteilungsdefinition.h - NIVissimSingleTypeParser_Langsamfahrbereichdefinition.cpp - NIVissimSingleTypeParser_Langsamfahrbereichdefinition.h - NIVissimSingleTypeParser_Lichtsignalanlagendefinition.cpp - NIVissimSingleTypeParser_Lichtsignalanlagendefinition.h - NIVissimSingleTypeParser_Liniendefinition.cpp - NIVissimSingleTypeParser_Liniendefinition.h - NIVissimSingleTypeParser_Linksverkehr.cpp - NIVissimSingleTypeParser_Linksverkehr.h - NIVissimSingleTypeParser_Messungsdefinition.cpp - NIVissimSingleTypeParser_Messungsdefinition.h - NIVissimSingleTypeParser_Netzobjektdefinition.cpp - NIVissimSingleTypeParser_Netzobjektdefinition.h - NIVissimSingleTypeParser_Parkplatzdefinition.cpp - NIVissimSingleTypeParser_Parkplatzdefinition.h - NIVissimSingleTypeParser_Querschnittsmessungsdefinition.cpp - NIVissimSingleTypeParser_Querschnittsmessungsdefinition.h - NIVissimSingleTypeParser_Querverkehrsstoerungsdefinition.cpp - NIVissimSingleTypeParser_Querverkehrsstoerungsdefinition.h - NIVissimSingleTypeParser_Rautedefinition.cpp - NIVissimSingleTypeParser_Rautedefinition.h - NIVissimSingleTypeParser_Reisezeitmessungsdefinition.cpp - NIVissimSingleTypeParser_Reisezeitmessungsdefinition.h - NIVissimSingleTypeParser_Richtungsentscheidungsdefinition.cpp - NIVissimSingleTypeParser_Richtungsentscheidungsdefinition.h - NIVissimSingleTypeParser_Richtungspfeildefinition.cpp - NIVissimSingleTypeParser_Richtungspfeildefinition.h - NIVissimSingleTypeParser_Routenentscheidungsdefinition.cpp - NIVissimSingleTypeParser_Routenentscheidungsdefinition.h - NIVissimSingleTypeParser_Signalgeberdefinition.cpp - NIVissimSingleTypeParser_Signalgeberdefinition.h - NIVissimSingleTypeParser_Signalgruppendefinition.cpp - NIVissimSingleTypeParser_Signalgruppendefinition.h - NIVissimSingleTypeParser_SimRate.cpp - NIVissimSingleTypeParser_SimRate.h - NIVissimSingleTypeParser_Simdauer.cpp - NIVissimSingleTypeParser_Simdauer.h - NIVissimSingleTypeParser_Startuhrzeit.cpp - NIVissimSingleTypeParser_Startuhrzeit.h - NIVissimSingleTypeParser_Startzufallszahl.cpp - NIVissimSingleTypeParser_Startzufallszahl.h - NIVissimSingleTypeParser_Stauparameterdefinition.cpp - NIVissimSingleTypeParser_Stauparameterdefinition.h - NIVissimSingleTypeParser_Stauzaehlerdefinition.cpp - NIVissimSingleTypeParser_Stauzaehlerdefinition.h - NIVissimSingleTypeParser_Stopschilddefinition.cpp - NIVissimSingleTypeParser_Stopschilddefinition.h - NIVissimSingleTypeParser_Streckendefinition.cpp - NIVissimSingleTypeParser_Streckendefinition.h - NIVissimSingleTypeParser_Streckentypdefinition.cpp - NIVissimSingleTypeParser_Streckentypdefinition.h - NIVissimSingleTypeParser_TEAPACDefinition.cpp - NIVissimSingleTypeParser_TEAPACDefinition.h - NIVissimSingleTypeParser_VWunschentscheidungsdefinition.cpp - NIVissimSingleTypeParser_VWunschentscheidungsdefinition.h - NIVissimSingleTypeParser_Verbindungsdefinition.cpp - NIVissimSingleTypeParser_Verbindungsdefinition.h - NIVissimSingleTypeParser_Verkehrszusammensetzungsdefinition.cpp - NIVissimSingleTypeParser_Verkehrszusammensetzungsdefinition.h - NIVissimSingleTypeParser_Verlustzeitmessungsdefinition.cpp - NIVissimSingleTypeParser_Verlustzeitmessungsdefinition.h - NIVissimSingleTypeParser_Zeitenverteilungsdefinition.cpp - NIVissimSingleTypeParser_Zeitenverteilungsdefinition.h - NIVissimSingleTypeParser_Zeitschrittfaktor.cpp - NIVissimSingleTypeParser_Zeitschrittfaktor.h - NIVissimSingleTypeParser_Zuflussdefinition.cpp - NIVissimSingleTypeParser_Zuflussdefinition.h - NIVissimSingleTypeParser_Zusammensetzungsdefinition.cpp - NIVissimSingleTypeParser_Zusammensetzungsdefinition.h - NIVissimSingleTypeParser__XKurvedefinition.cpp - NIVissimSingleTypeParser__XKurvedefinition.h - NIVissimSingleTypeParser__XVerteilungsdefinition.cpp - NIVissimSingleTypeParser__XVerteilungsdefinition.h -) - -add_library(netimport_vissim_typeloader STATIC ${netimport_vissim_typeloader_STAT_SRCS}) -set_property(TARGET netimport_vissim_typeloader PROPERTY PROJECT_LABEL "z_netimport_vissim_typeloader") diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Auswertungsdefinition.cpp b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Auswertungsdefinition.cpp deleted file mode 100644 index ab4973059..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Auswertungsdefinition.cpp +++ /dev/null @@ -1,70 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Auswertungsdefinition.cpp -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Fri, 21 Mar 2003 -/// -// -/****************************************************************************/ -#include - -#include -#include -#include "../NIImporter_Vissim.h" -#include "../tempstructs/NIVissimSource.h" -#include "NIVissimSingleTypeParser_Auswertungsdefinition.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -NIVissimSingleTypeParser_Auswertungsdefinition::NIVissimSingleTypeParser_Auswertungsdefinition(NIImporter_Vissim& parent) - : NIImporter_Vissim::VissimSingleTypeParser(parent) {} - - -NIVissimSingleTypeParser_Auswertungsdefinition::~NIVissimSingleTypeParser_Auswertungsdefinition() {} - - -bool -NIVissimSingleTypeParser_Auswertungsdefinition::parse(std::istream& from) { - std::string id; - from >> id; // "typ" - - if (id == "DATENBANK") { // !!! unverified - return true; - } - - std::string type = myRead(from); - if (type == "abfluss") { - while (type != "signalgruppe") { - type = myRead(from); - } - while (type != "DATAEND") { - type = readEndSecure(from, "messung"); - } - } else if (type == "vbv") {} else if (type == "dichte") {} else if (type == "emissionen") {} else if (type == "fzprot") {} else if (type == "spwprot") {} else if (type == "segment") { - while (type != "konfdatei") { - type = myRead(from); - } - } else if (type == "wegeausw") {} else if (type == "knoten") {} else if (type == "konvergenz") { - while (type != "zeit") { - type = myRead(from); - } - } - return true; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Auswertungsdefinition.h b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Auswertungsdefinition.h deleted file mode 100644 index 0610a386f..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Auswertungsdefinition.h +++ /dev/null @@ -1,46 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Auswertungsdefinition.h -/// @author Daniel Krajzewicz -/// @date Fri, 21 Mar 2003 -/// -// -/****************************************************************************/ -#pragma once -#include - -#include -#include "../NIImporter_Vissim.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NIVissimSingleTypeParser_Auswertungsdefinition - * - */ -class NIVissimSingleTypeParser_Auswertungsdefinition : - public NIImporter_Vissim::VissimSingleTypeParser { -public: - /// Constructor - NIVissimSingleTypeParser_Auswertungsdefinition(NIImporter_Vissim& parent); - - /// Destructor - ~NIVissimSingleTypeParser_Auswertungsdefinition(); - - /// Parses the data type from the given stream - bool parse(std::istream& from); - -}; diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Detektordefinition.cpp b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Detektordefinition.cpp deleted file mode 100644 index 5082b36be..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Detektordefinition.cpp +++ /dev/null @@ -1,53 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Detektordefinition.cpp -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Wed, 18 Dec 2002 -/// -// -/****************************************************************************/ -#include - -#include -#include -#include "../NIImporter_Vissim.h" -#include "../tempstructs/NIVissimClosures.h" -#include "NIVissimSingleTypeParser_Detektordefinition.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -NIVissimSingleTypeParser_Detektordefinition::NIVissimSingleTypeParser_Detektordefinition(NIImporter_Vissim& parent) - : NIImporter_Vissim::VissimSingleTypeParser(parent) {} - - -NIVissimSingleTypeParser_Detektordefinition::~NIVissimSingleTypeParser_Detektordefinition() {} - - -bool -NIVissimSingleTypeParser_Detektordefinition::parse(std::istream& from) { - std::string tag; - while (tag != "strecke") { - tag = myRead(from); - } - while (tag != "DATAEND") { - tag = readEndSecure(from); - } - return true; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Detektordefinition.h b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Detektordefinition.h deleted file mode 100644 index 84c87e84d..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Detektordefinition.h +++ /dev/null @@ -1,46 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Detektordefinition.h -/// @author Daniel Krajzewicz -/// @date Wed, 18 Dec 2002 -/// -// -/****************************************************************************/ -#pragma once -#include - -#include -#include "../NIImporter_Vissim.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NIVissimSingleTypeParser_Detektordefinition - * - */ -class NIVissimSingleTypeParser_Detektordefinition : - public NIImporter_Vissim::VissimSingleTypeParser { -public: - /// Constructor - NIVissimSingleTypeParser_Detektordefinition(NIImporter_Vissim& parent); - - /// Destructor - ~NIVissimSingleTypeParser_Detektordefinition(); - - /// Parses the data type from the given stream - bool parse(std::istream& from); - -}; diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_DynUml.cpp b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_DynUml.cpp deleted file mode 100644 index f1c869d5d..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_DynUml.cpp +++ /dev/null @@ -1,54 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_DynUml.cpp -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Wed, 18 Dec 2002 -/// -// -/****************************************************************************/ -#include - -#include -#include -#include -#include "../NIImporter_Vissim.h" -#include "NIVissimSingleTypeParser_DynUml.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -NIVissimSingleTypeParser_DynUml::NIVissimSingleTypeParser_DynUml(NIImporter_Vissim& parent) - : NIImporter_Vissim::VissimSingleTypeParser(parent) {} - - -NIVissimSingleTypeParser_DynUml::~NIVissimSingleTypeParser_DynUml() {} - - -bool -NIVissimSingleTypeParser_DynUml::parse(std::istream& from) { - std::vector tmp; - tmp.push_back("reisezeit"); - tmp.push_back("kante"); - readUntil(from, "kirchhoffexponent"); - std::string tag = readEndSecure(from, tmp); - while (tag != "DATAEND") { - tag = readEndSecure(from, tmp); - } - return true; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_DynUml.h b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_DynUml.h deleted file mode 100644 index 15597296b..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_DynUml.h +++ /dev/null @@ -1,46 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_DynUml.h -/// @author Daniel Krajzewicz -/// @date Wed, 18 Dec 2002 -/// -// -/****************************************************************************/ -#pragma once -#include - -#include -#include "../NIImporter_Vissim.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NIVissimSingleTypeParser_DynUml - * - */ -class NIVissimSingleTypeParser_DynUml : - public NIImporter_Vissim::VissimSingleTypeParser { -public: - /// Constructor - NIVissimSingleTypeParser_DynUml(NIImporter_Vissim& parent); - - /// Destructor - ~NIVissimSingleTypeParser_DynUml(); - - /// Parses the data type from the given stream - bool parse(std::istream& from); - -}; diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Einheitendefinition.cpp b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Einheitendefinition.cpp deleted file mode 100644 index 8e9837788..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Einheitendefinition.cpp +++ /dev/null @@ -1,46 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Einheitendefinition.cpp -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Wed, 30 Apr 2003 -/// -// -/****************************************************************************/ -#include - -#include -#include -#include "../NIImporter_Vissim.h" -#include "../tempstructs/NIVissimSource.h" -#include "NIVissimSingleTypeParser_Einheitendefinition.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -NIVissimSingleTypeParser_Einheitendefinition::NIVissimSingleTypeParser_Einheitendefinition(NIImporter_Vissim& parent) - : NIImporter_Vissim::VissimSingleTypeParser(parent) {} - - -NIVissimSingleTypeParser_Einheitendefinition::~NIVissimSingleTypeParser_Einheitendefinition() {} - - -bool -NIVissimSingleTypeParser_Einheitendefinition::parse(std::istream&) { - return true; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Einheitendefinition.h b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Einheitendefinition.h deleted file mode 100644 index 0da4b3ab9..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Einheitendefinition.h +++ /dev/null @@ -1,46 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Einheitendefinition.h -/// @author Daniel Krajzewicz -/// @date Wed, 30 Apr 2003 -/// -// -/****************************************************************************/ -#pragma once -#include - -#include -#include "../NIImporter_Vissim.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NIVissimSingleTypeParser_Einheitendefinition - * - */ -class NIVissimSingleTypeParser_Einheitendefinition : - public NIImporter_Vissim::VissimSingleTypeParser { -public: - /// Constructor - NIVissimSingleTypeParser_Einheitendefinition(NIImporter_Vissim& parent); - - /// Destructor - ~NIVissimSingleTypeParser_Einheitendefinition(); - - /// Parses the data type from the given stream - bool parse(std::istream& from); - -}; diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Emission.cpp b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Emission.cpp deleted file mode 100644 index b961f230d..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Emission.cpp +++ /dev/null @@ -1,46 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Emission.cpp -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Wed, 30 Apr 2003 -/// -// -/****************************************************************************/ -#include - -#include -#include -#include "../NIImporter_Vissim.h" -#include "../tempstructs/NIVissimSource.h" -#include "NIVissimSingleTypeParser_Emission.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -NIVissimSingleTypeParser_Emission::NIVissimSingleTypeParser_Emission(NIImporter_Vissim& parent) - : NIImporter_Vissim::VissimSingleTypeParser(parent) {} - - -NIVissimSingleTypeParser_Emission::~NIVissimSingleTypeParser_Emission() {} - - -bool -NIVissimSingleTypeParser_Emission::parse(std::istream&) { - return true; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Emission.h b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Emission.h deleted file mode 100644 index b8921bdf3..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Emission.h +++ /dev/null @@ -1,46 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Emission.h -/// @author Daniel Krajzewicz -/// @date Wed, 30 Apr 2003 -/// -// -/****************************************************************************/ -#pragma once -#include - -#include -#include "../NIImporter_Vissim.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NIVissimSingleTypeParser_Emission - * - */ -class NIVissimSingleTypeParser_Emission : - public NIImporter_Vissim::VissimSingleTypeParser { -public: - /// Constructor - NIVissimSingleTypeParser_Emission(NIImporter_Vissim& parent); - - /// Destructor - ~NIVissimSingleTypeParser_Emission(); - - /// Parses the data type from the given stream - bool parse(std::istream& from); - -}; diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Fahrtverlaufdateien.cpp b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Fahrtverlaufdateien.cpp deleted file mode 100644 index eac0fdf9d..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Fahrtverlaufdateien.cpp +++ /dev/null @@ -1,46 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Fahrtverlaufdateien.cpp -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Wed, 30 Apr 2003 -/// -// -/****************************************************************************/ -#include - -#include -#include -#include "../NIImporter_Vissim.h" -#include "../tempstructs/NIVissimSource.h" -#include "NIVissimSingleTypeParser_Fahrtverlaufdateien.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -NIVissimSingleTypeParser_Fahrtverlaufdateien::NIVissimSingleTypeParser_Fahrtverlaufdateien(NIImporter_Vissim& parent) - : NIImporter_Vissim::VissimSingleTypeParser(parent) {} - - -NIVissimSingleTypeParser_Fahrtverlaufdateien::~NIVissimSingleTypeParser_Fahrtverlaufdateien() {} - - -bool -NIVissimSingleTypeParser_Fahrtverlaufdateien::parse(std::istream&) { - return true; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Fahrtverlaufdateien.h b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Fahrtverlaufdateien.h deleted file mode 100644 index 82efdecfd..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Fahrtverlaufdateien.h +++ /dev/null @@ -1,46 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Fahrtverlaufdateien.h -/// @author Daniel Krajzewicz -/// @date Wed, 30 Apr 2003 -/// -// -/****************************************************************************/ -#pragma once -#include - -#include -#include "../NIImporter_Vissim.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NIVissimSingleTypeParser_Fahrtverlaufdateien - * - */ -class NIVissimSingleTypeParser_Fahrtverlaufdateien : - public NIImporter_Vissim::VissimSingleTypeParser { -public: - /// Constructor - NIVissimSingleTypeParser_Fahrtverlaufdateien(NIImporter_Vissim& parent); - - /// Destructor - ~NIVissimSingleTypeParser_Fahrtverlaufdateien(); - - /// Parses the data type from the given stream - bool parse(std::istream& from); - -}; diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Fahrverhaltendefinition.cpp b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Fahrverhaltendefinition.cpp deleted file mode 100644 index 095b55451..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Fahrverhaltendefinition.cpp +++ /dev/null @@ -1,55 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Fahrverhaltendefinition.cpp -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Wed, 18 Dec 2002 -/// -// -/****************************************************************************/ -#include - -#include -#include "../NIImporter_Vissim.h" -#include "NIVissimSingleTypeParser_Fahrverhaltendefinition.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -NIVissimSingleTypeParser_Fahrverhaltendefinition::NIVissimSingleTypeParser_Fahrverhaltendefinition(NIImporter_Vissim& parent) - : NIImporter_Vissim::VissimSingleTypeParser(parent) {} - - -NIVissimSingleTypeParser_Fahrverhaltendefinition::~NIVissimSingleTypeParser_Fahrverhaltendefinition() {} - - -bool -NIVissimSingleTypeParser_Fahrverhaltendefinition::parse(std::istream& from) { - std::string tmp; - from >> tmp; - // in the both next cases, we do not have to overread anything - if (tmp == "BEHALT_ALTE_PARA" || tmp == "ANZ_VM") { - return true; - } - // - from >> tmp; - if (tmp == "NAME") { - readUntil(from, "gelbverhalten"); - } - return true; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Fahrverhaltendefinition.h b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Fahrverhaltendefinition.h deleted file mode 100644 index cc710ba59..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Fahrverhaltendefinition.h +++ /dev/null @@ -1,46 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Fahrverhaltendefinition.h -/// @author Daniel Krajzewicz -/// @date Wed, 18 Dec 2002 -/// -// -/****************************************************************************/ -#pragma once -#include - -#include -#include "../NIImporter_Vissim.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NIVissimSingleTypeParser_Fahrverhaltendefinition - * - */ -class NIVissimSingleTypeParser_Fahrverhaltendefinition : - public NIImporter_Vissim::VissimSingleTypeParser { -public: - /// Constructor - NIVissimSingleTypeParser_Fahrverhaltendefinition(NIImporter_Vissim& parent); - - /// Destructor - ~NIVissimSingleTypeParser_Fahrverhaltendefinition(); - - /// Parses the data type from the given stream - bool parse(std::istream& from); - -}; diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Fahrzeugklassendefinition.cpp b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Fahrzeugklassendefinition.cpp deleted file mode 100644 index 8e2637ae7..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Fahrzeugklassendefinition.cpp +++ /dev/null @@ -1,90 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Fahrzeugklassendefinition.cpp -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Wed, 18 Dec 2002 -/// -// -/****************************************************************************/ -#include - -#include -#include -#include -#include -#include "../NIImporter_Vissim.h" -#include "../tempstructs/NIVissimVehTypeClass.h" -#include "NIVissimSingleTypeParser_Fahrzeugklassendefinition.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -NIVissimSingleTypeParser_Fahrzeugklassendefinition::NIVissimSingleTypeParser_Fahrzeugklassendefinition( - NIImporter_Vissim& parent, NIImporter_Vissim::ColorMap& colorMap) - : NIImporter_Vissim::VissimSingleTypeParser(parent), - myColorMap(colorMap) {} - - -NIVissimSingleTypeParser_Fahrzeugklassendefinition::~NIVissimSingleTypeParser_Fahrzeugklassendefinition() {} - - -bool -NIVissimSingleTypeParser_Fahrzeugklassendefinition::parse(std::istream& from) { - // id - int id; - from >> id; // type-checking is missing! - // name - std::string tag; - from >> tag; - std::string name = readName(from); - // color - from >> tag; - std::string colorName = myRead(from); - RGBColor color; - NIImporter_Vissim::ColorMap::iterator i = myColorMap.find(colorName); - if (i != myColorMap.end()) { - color = (*i).second; - } else { - int r, g, b; - r = StringUtils::toInt(colorName); - if (!(from >> g)) { - throw NumberFormatException(""); - } - if (!(from >> b)) { - throw NumberFormatException(""); - } - if (r < 0 || r > 255 || g < 0 || g > 255 || b < 0 || b > 255) { - throw NumberFormatException(""); - } - color = RGBColor((unsigned char)r, (unsigned char)g, (unsigned char)b, 255); - } - // types - from >> tag; - if (tag == "ANM_ID") { - readName(from); - from >> tag; - } - std::vector types; - from >> tag; - do { - types.push_back(StringUtils::toInt(tag)); - tag = readEndSecure(from); - } while (tag != "DATAEND"); - return NIVissimVehTypeClass::dictionary(id, name, color, types); -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Fahrzeugklassendefinition.h b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Fahrzeugklassendefinition.h deleted file mode 100644 index 46fbfb105..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Fahrzeugklassendefinition.h +++ /dev/null @@ -1,51 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Fahrzeugklassendefinition.h -/// @author Daniel Krajzewicz -/// @date Wed, 18 Dec 2002 -/// -// -/****************************************************************************/ -#pragma once -#include - -#include -#include "../NIImporter_Vissim.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NIVissimSingleTypeParser_Fahrzeugklassendefinition - * - */ -class NIVissimSingleTypeParser_Fahrzeugklassendefinition : - public NIImporter_Vissim::VissimSingleTypeParser { -public: - /// Constructor - NIVissimSingleTypeParser_Fahrzeugklassendefinition(NIImporter_Vissim& parent, - NIImporter_Vissim::ColorMap& colorMap); - - /// Destructor - ~NIVissimSingleTypeParser_Fahrzeugklassendefinition(); - - /// Parses the data type from the given stream - bool parse(std::istream& from); - -private: - /// color definitions - NIImporter_Vissim::ColorMap& myColorMap; - -}; diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Fahrzeugtypdefinition.cpp b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Fahrzeugtypdefinition.cpp deleted file mode 100644 index f54a1ee41..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Fahrzeugtypdefinition.cpp +++ /dev/null @@ -1,106 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Fahrzeugtypdefinition.cpp -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Wed, 18 Dec 2002 -/// -// -/****************************************************************************/ -#include - -#include -#include -#include -#include "../NIImporter_Vissim.h" -#include "../tempstructs/NIVissimVehicleType.h" -#include "NIVissimSingleTypeParser_Fahrzeugtypdefinition.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -NIVissimSingleTypeParser_Fahrzeugtypdefinition::NIVissimSingleTypeParser_Fahrzeugtypdefinition( - NIImporter_Vissim& parent, NIImporter_Vissim::ColorMap& colorMap) - : NIImporter_Vissim::VissimSingleTypeParser(parent), - myColorMap(colorMap) {} - - -NIVissimSingleTypeParser_Fahrzeugtypdefinition::~NIVissimSingleTypeParser_Fahrzeugtypdefinition() {} - - -bool -NIVissimSingleTypeParser_Fahrzeugtypdefinition::parse(std::istream& from) { - // id - int id; - from >> id; // type-checking is missing! - // name - std::string tag; - from >> tag; - std::string name = readName(from); - // category - std::string category; - from >> tag; - from >> category; - // color (optional) and length - RGBColor color; - tag = myRead(from); - while (tag != "laenge") { - if (tag == "farbe") { - std::string colorName = myRead(from); - NIImporter_Vissim::ColorMap::iterator i = myColorMap.find(colorName); - if (i != myColorMap.end()) { - color = (*i).second; - } else { - int r, g, b; - r = StringUtils::toInt(colorName); - if (!(from >> g)) { - throw NumberFormatException(""); - } - if (!(from >> b)) { - throw NumberFormatException(""); - } - if (r < 0 || r > 255 || g < 0 || g > 255 || b < 0 || b > 255) { - throw NumberFormatException(""); - } - color = RGBColor((unsigned char)r, (unsigned char)g, (unsigned char)b, 255); - } - } - tag = myRead(from); - } - double length; - from >> length; - // overread until "Maxbeschleunigung" - while (tag != "maxbeschleunigung") { - tag = myRead(from); - } - double amax; - from >> amax; // type-checking is missing! - // overread until "Maxverzoegerung" - while (tag != "maxverzoegerung") { - tag = myRead(from); - } - double dmax; - from >> dmax; // type-checking is missing! - while (tag != "besetzungsgrad") { - tag = myRead(from); - } - while (tag != "DATAEND") { - tag = readEndSecure(from, "verlustzeit"); - } - return NIVissimVehicleType::dictionary(id, name, category, color); -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Fahrzeugtypdefinition.h b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Fahrzeugtypdefinition.h deleted file mode 100644 index 99ba7c7bb..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Fahrzeugtypdefinition.h +++ /dev/null @@ -1,50 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Fahrzeugtypdefinition.h -/// @author Daniel Krajzewicz -/// @date Wed, 18 Dec 2002 -/// -// -/****************************************************************************/ -#pragma once -#include - -#include -#include "../NIImporter_Vissim.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NIVissimSingleTypeParser_Fahrzeugtypdefinition - * - */ -class NIVissimSingleTypeParser_Fahrzeugtypdefinition : - public NIImporter_Vissim::VissimSingleTypeParser { -public: - /// Constructor - NIVissimSingleTypeParser_Fahrzeugtypdefinition(NIImporter_Vissim& parent, - NIImporter_Vissim::ColorMap& colorMap); - - /// Destructor - ~NIVissimSingleTypeParser_Fahrzeugtypdefinition(); - - /// Parses the data type from the given stream - bool parse(std::istream& from); - -private: - /// The color map to use - NIImporter_Vissim::ColorMap& myColorMap; -}; diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Fensterdefinition.cpp b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Fensterdefinition.cpp deleted file mode 100644 index 61e7f1cad..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Fensterdefinition.cpp +++ /dev/null @@ -1,57 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Fensterdefinition.cpp -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Fri, 21 Mar 2003 -/// -// -/****************************************************************************/ -#include - -#include -#include -#include "../NIImporter_Vissim.h" -#include "../tempstructs/NIVissimSource.h" -#include "NIVissimSingleTypeParser_Fensterdefinition.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -NIVissimSingleTypeParser_Fensterdefinition::NIVissimSingleTypeParser_Fensterdefinition(NIImporter_Vissim& parent) - : NIImporter_Vissim::VissimSingleTypeParser(parent) {} - - -NIVissimSingleTypeParser_Fensterdefinition::~NIVissimSingleTypeParser_Fensterdefinition() {} - - -bool -NIVissimSingleTypeParser_Fensterdefinition::parse(std::istream& from) { - std::string id; - from >> id; // "typ" - std::string type = myRead(from); - if (type == "fzinfo") { - std::string tmp; - from >> tmp; - from >> tmp; - } else if (type == "ldp" || type == "szp") { - std::string tmp; - readUntil(from, "lsa"); - } - return true; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Fensterdefinition.h b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Fensterdefinition.h deleted file mode 100644 index b90e69fe5..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Fensterdefinition.h +++ /dev/null @@ -1,46 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Fensterdefinition.h -/// @author Daniel Krajzewicz -/// @date Fri, 21 Mar 2003 -/// -// -/****************************************************************************/ -#pragma once -#include - -#include -#include "../NIImporter_Vissim.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NIVissimSingleTypeParser_Fensterdefinition - * - */ -class NIVissimSingleTypeParser_Fensterdefinition : - public NIImporter_Vissim::VissimSingleTypeParser { -public: - /// Constructor - NIVissimSingleTypeParser_Fensterdefinition(NIImporter_Vissim& parent); - - /// Destructor - ~NIVissimSingleTypeParser_Fensterdefinition(); - - /// Parses the data type from the given stream - bool parse(std::istream& from); - -}; diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Gefahrwarnungsdefinition.cpp b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Gefahrwarnungsdefinition.cpp deleted file mode 100644 index c3ae98631..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Gefahrwarnungsdefinition.cpp +++ /dev/null @@ -1,46 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Gefahrwarnungsdefinition.cpp -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Wed, 30 Apr 2003 -/// -// -/****************************************************************************/ -#include - -#include -#include -#include "../NIImporter_Vissim.h" -#include "../tempstructs/NIVissimSource.h" -#include "NIVissimSingleTypeParser_Gefahrwarnungsdefinition.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -NIVissimSingleTypeParser_Gefahrwarnungsdefinition::NIVissimSingleTypeParser_Gefahrwarnungsdefinition(NIImporter_Vissim& parent) - : NIImporter_Vissim::VissimSingleTypeParser(parent) {} - - -NIVissimSingleTypeParser_Gefahrwarnungsdefinition::~NIVissimSingleTypeParser_Gefahrwarnungsdefinition() {} - - -bool -NIVissimSingleTypeParser_Gefahrwarnungsdefinition::parse(std::istream&) { - return true; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Gefahrwarnungsdefinition.h b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Gefahrwarnungsdefinition.h deleted file mode 100644 index 052c93a54..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Gefahrwarnungsdefinition.h +++ /dev/null @@ -1,46 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Gefahrwarnungsdefinition.h -/// @author Daniel Krajzewicz -/// @date Wed, 30 Apr 2003 -/// -// -/****************************************************************************/ -#pragma once -#include - -#include -#include "../NIImporter_Vissim.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NIVissimSingleTypeParser_Gefahrwarnungsdefinition - * - */ -class NIVissimSingleTypeParser_Gefahrwarnungsdefinition : - public NIImporter_Vissim::VissimSingleTypeParser { -public: - /// Constructor - NIVissimSingleTypeParser_Gefahrwarnungsdefinition(NIImporter_Vissim& parent); - - /// Destructor - ~NIVissimSingleTypeParser_Gefahrwarnungsdefinition(); - - /// Parses the data type from the given stream - bool parse(std::istream& from); - -}; diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Gelbverhaltendefinition.cpp b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Gelbverhaltendefinition.cpp deleted file mode 100644 index 84ac1d037..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Gelbverhaltendefinition.cpp +++ /dev/null @@ -1,46 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Gelbverhaltendefinition.cpp -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Wed, 30 Apr 2003 -/// -// -/****************************************************************************/ -#include - -#include -#include -#include "../NIImporter_Vissim.h" -#include "../tempstructs/NIVissimSource.h" -#include "NIVissimSingleTypeParser_Gelbverhaltendefinition.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -NIVissimSingleTypeParser_Gelbverhaltendefinition::NIVissimSingleTypeParser_Gelbverhaltendefinition(NIImporter_Vissim& parent) - : NIImporter_Vissim::VissimSingleTypeParser(parent) {} - - -NIVissimSingleTypeParser_Gelbverhaltendefinition::~NIVissimSingleTypeParser_Gelbverhaltendefinition() {} - - -bool -NIVissimSingleTypeParser_Gelbverhaltendefinition::parse(std::istream&) { - return true; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Gelbverhaltendefinition.h b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Gelbverhaltendefinition.h deleted file mode 100644 index 01cf1d7d3..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Gelbverhaltendefinition.h +++ /dev/null @@ -1,46 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Gelbverhaltendefinition.h -/// @author Daniel Krajzewicz -/// @date Wed, 30 Apr 2003 -/// -// -/****************************************************************************/ -#pragma once -#include - -#include -#include "../NIImporter_Vissim.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NIVissimSingleTypeParser_Gelbverhaltendefinition - * - */ -class NIVissimSingleTypeParser_Gelbverhaltendefinition : - public NIImporter_Vissim::VissimSingleTypeParser { -public: - /// Constructor - NIVissimSingleTypeParser_Gelbverhaltendefinition(NIImporter_Vissim& parent); - - /// Destructor - ~NIVissimSingleTypeParser_Gelbverhaltendefinition(); - - /// Parses the data type from the given stream - bool parse(std::istream& from); - -}; diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Geschwindigkeitsverteilungsdefinition.cpp b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Geschwindigkeitsverteilungsdefinition.cpp deleted file mode 100644 index f9774a39d..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Geschwindigkeitsverteilungsdefinition.cpp +++ /dev/null @@ -1,70 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Geschwindigkeitsverteilungsdefinition.cpp -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Wed, 18 Dec 2002 -/// -// -/****************************************************************************/ -#include - -#include -#include -#include -#include -#include -#include -#include -#include "../NIImporter_Vissim.h" -#include "NIVissimSingleTypeParser_Geschwindigkeitsverteilungsdefinition.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -NIVissimSingleTypeParser_Geschwindigkeitsverteilungsdefinition::NIVissimSingleTypeParser_Geschwindigkeitsverteilungsdefinition(NIImporter_Vissim& parent) - : NIImporter_Vissim::VissimSingleTypeParser(parent) {} - - -NIVissimSingleTypeParser_Geschwindigkeitsverteilungsdefinition::~NIVissimSingleTypeParser_Geschwindigkeitsverteilungsdefinition() {} - - -bool -NIVissimSingleTypeParser_Geschwindigkeitsverteilungsdefinition::parse(std::istream& from) { - // id - std::string id; - from >> id; - // list of points - Distribution_Points* points = new Distribution_Points(id); - std::string tag; - do { - tag = readEndSecure(from); - if (tag == "name") { - readName(from); - tag = readEndSecure(from); - } - if (tag != "DATAEND") { - const double p1 = StringUtils::toDouble(tag); - from >> tag; - const double p2 = StringUtils::toDouble(tag); - points->add(p1, p2); - } - } while (tag != "DATAEND"); - DistributionCont::dictionary("speed", id, points); - return true; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Geschwindigkeitsverteilungsdefinition.h b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Geschwindigkeitsverteilungsdefinition.h deleted file mode 100644 index 7cd9d8514..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Geschwindigkeitsverteilungsdefinition.h +++ /dev/null @@ -1,46 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Geschwindigkeitsverteilungsdefinition.h -/// @author Daniel Krajzewicz -/// @date Wed, 18 Dec 2002 -/// -// -/****************************************************************************/ -#pragma once -#include - -#include -#include "../NIImporter_Vissim.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NIVissimSingleTypeParser_Geschwindigkeitsverteilungsdefinition - * - */ -class NIVissimSingleTypeParser_Geschwindigkeitsverteilungsdefinition : - public NIImporter_Vissim::VissimSingleTypeParser { -public: - /// Constructor - NIVissimSingleTypeParser_Geschwindigkeitsverteilungsdefinition(NIImporter_Vissim& parent); - - /// Destructor - ~NIVissimSingleTypeParser_Geschwindigkeitsverteilungsdefinition(); - - /// Parses the data type from the given stream - bool parse(std::istream& from); - -}; diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Haltestellendefinition.cpp b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Haltestellendefinition.cpp deleted file mode 100644 index fa7af05c1..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Haltestellendefinition.cpp +++ /dev/null @@ -1,63 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Haltestellendefinition.cpp -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Wed, 18 Dec 2002 -/// -// -/****************************************************************************/ -#include - -#include -#include -#include "../NIImporter_Vissim.h" -#include "../tempstructs/NIVissimClosures.h" -#include "NIVissimSingleTypeParser_Haltestellendefinition.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -NIVissimSingleTypeParser_Haltestellendefinition::NIVissimSingleTypeParser_Haltestellendefinition(NIImporter_Vissim& parent) - : NIImporter_Vissim::VissimSingleTypeParser(parent) {} - - -NIVissimSingleTypeParser_Haltestellendefinition::~NIVissimSingleTypeParser_Haltestellendefinition() {} - - -bool -NIVissimSingleTypeParser_Haltestellendefinition::parse(std::istream& from) { - std::string tag; - while (tag != "strecke") { - tag = myRead(from); - } - while (tag != "laenge") { - tag = myRead(from); - } - from >> tag; - tag = readEndSecure(from); - while (tag == "einsteiger" && tag != "DATAEND") { - while (tag != "linie") { - tag = myRead(from); - } - while (tag != "einsteiger" && tag != "DATAEND") { - tag = readEndSecure(from); - } - } - return true; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Haltestellendefinition.h b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Haltestellendefinition.h deleted file mode 100644 index ce36a7709..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Haltestellendefinition.h +++ /dev/null @@ -1,46 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Haltestellendefinition.h -/// @author Daniel Krajzewicz -/// @date Wed, 18 Dec 2002 -/// -// -/****************************************************************************/ -#pragma once -#include - -#include -#include "../NIImporter_Vissim.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NIVissimSingleTypeParser_Haltestellendefinition - * - */ -class NIVissimSingleTypeParser_Haltestellendefinition : - public NIImporter_Vissim::VissimSingleTypeParser { -public: - /// Constructor - NIVissimSingleTypeParser_Haltestellendefinition(NIImporter_Vissim& parent); - - /// Destructor - ~NIVissimSingleTypeParser_Haltestellendefinition(); - - /// Parses the data type from the given stream - bool parse(std::istream& from); - -}; diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Kantensperrung.cpp b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Kantensperrung.cpp deleted file mode 100644 index a5a7b4c17..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Kantensperrung.cpp +++ /dev/null @@ -1,72 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Kantensperrung.cpp -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Wed, 18 Dec 2002 -/// -// -/****************************************************************************/ -#include - -#include -#include -#include "../NIImporter_Vissim.h" -#include "../tempstructs/NIVissimClosures.h" -#include "NIVissimSingleTypeParser_Kantensperrung.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -NIVissimSingleTypeParser_Kantensperrung::NIVissimSingleTypeParser_Kantensperrung(NIImporter_Vissim& parent) - : NIImporter_Vissim::VissimSingleTypeParser(parent) {} - - -NIVissimSingleTypeParser_Kantensperrung::~NIVissimSingleTypeParser_Kantensperrung() {} - - -bool -NIVissimSingleTypeParser_Kantensperrung::parse(std::istream& from) { - std::string tag; - from >> tag; - // - std::string id; - from >> id; - // - from >> tag; - from >> tag; - int from_node; - from >> from_node; - // - from >> tag; - from >> tag; - int to_node; - from >> to_node; - // - from >> tag; - from >> tag; - std::vector edges; - while (tag != "DATAEND") { - tag = readEndSecure(from); - if (tag != "DATAEND") { - edges.push_back(StringUtils::toInt(tag)); - } - } - NIVissimClosures::dictionary(id, from_node, to_node, edges); - return true; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Kantensperrung.h b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Kantensperrung.h deleted file mode 100644 index a4c98cd84..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Kantensperrung.h +++ /dev/null @@ -1,46 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Kantensperrung.h -/// @author Daniel Krajzewicz -/// @date Wed, 18 Dec 2002 -/// -// -/****************************************************************************/ -#pragma once -#include - -#include -#include "../NIImporter_Vissim.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NIVissimSingleTypeParser_Kantensperrung - * - */ -class NIVissimSingleTypeParser_Kantensperrung : - public NIImporter_Vissim::VissimSingleTypeParser { -public: - /// Constructor - NIVissimSingleTypeParser_Kantensperrung(NIImporter_Vissim& parent); - - /// Destructor - ~NIVissimSingleTypeParser_Kantensperrung(); - - /// Parses the data type from the given stream - bool parse(std::istream& from); - -}; diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Kennungszeile.cpp b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Kennungszeile.cpp deleted file mode 100644 index 432711e41..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Kennungszeile.cpp +++ /dev/null @@ -1,46 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Kennungszeile.cpp -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Thu, 6 Mar 2003 -/// -// -/****************************************************************************/ -#include - -#include -#include -#include "../NIImporter_Vissim.h" -#include "NIVissimSingleTypeParser_Kennungszeile.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -NIVissimSingleTypeParser_Kennungszeile::NIVissimSingleTypeParser_Kennungszeile(NIImporter_Vissim& parent) - : NIImporter_Vissim::VissimSingleTypeParser(parent) {} - - -NIVissimSingleTypeParser_Kennungszeile::~NIVissimSingleTypeParser_Kennungszeile() {} - - -bool -NIVissimSingleTypeParser_Kennungszeile::parse(std::istream& from) { - readName(from); - return true; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Kennungszeile.h b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Kennungszeile.h deleted file mode 100644 index b261f4f0c..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Kennungszeile.h +++ /dev/null @@ -1,46 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Kennungszeile.h -/// @author Daniel Krajzewicz -/// @date Thu, 6 Mar 2003 -/// -// -/****************************************************************************/ -#pragma once -#include - -#include -#include "../NIImporter_Vissim.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NIVissimSingleTypeParser_Kennungszeile - * - */ -class NIVissimSingleTypeParser_Kennungszeile : - public NIImporter_Vissim::VissimSingleTypeParser { -public: - /// Constructor - NIVissimSingleTypeParser_Kennungszeile(NIImporter_Vissim& parent); - - /// Destructor - ~NIVissimSingleTypeParser_Kennungszeile(); - - /// Parses the data type from the given stream - bool parse(std::istream& from); - -}; diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Knotendefinition.cpp b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Knotendefinition.cpp deleted file mode 100644 index 71835f701..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Knotendefinition.cpp +++ /dev/null @@ -1,93 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Knotendefinition.cpp -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Wed, 18 Dec 2002 -/// -// -/****************************************************************************/ -#include - -#include -#include -#include -#include -#include "../NIImporter_Vissim.h" -#include "../tempstructs/NIVissimNodeParticipatingEdge.h" -#include "../tempstructs/NIVissimNodeParticipatingEdgeVector.h" -#include "../tempstructs/NIVissimNodeDef_Edges.h" -#include "../tempstructs/NIVissimNodeDef_Poly.h" -#include "../tempstructs/NIVissimNodeDef.h" -#include "NIVissimSingleTypeParser_Knotendefinition.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -NIVissimSingleTypeParser_Knotendefinition::NIVissimSingleTypeParser_Knotendefinition(NIImporter_Vissim& parent) - : NIImporter_Vissim::VissimSingleTypeParser(parent) {} - - -NIVissimSingleTypeParser_Knotendefinition::~NIVissimSingleTypeParser_Knotendefinition() {} - - -bool -NIVissimSingleTypeParser_Knotendefinition::parse(std::istream& from) { - // - int id; - from >> id; - // - std::string tag; - from >> tag; - std::string name = readName(from); - // - tag = overrideOptionalLabel(from); - // - while (tag != "netzausschnitt") { - tag = myRead(from); - } - // - tag = myRead(from); - if (tag == "strecke") { - NIVissimNodeParticipatingEdgeVector edges; - while (tag == "strecke") { - int edgeid; - double from_pos, to_pos; - from_pos = to_pos = -1.0; - from >> edgeid; - tag = readEndSecure(from, "strecke"); - if (tag == "von") { - from >> from_pos; // type-checking is missing! - from >> tag; - from >> to_pos; // type-checking is missing! - tag = readEndSecure(from, "strecke"); - } - edges.push_back(new NIVissimNodeParticipatingEdge(edgeid, from_pos, to_pos)); - } - NIVissimNodeDef_Edges::dictionary(id, name, edges); - } else { - int no = StringUtils::toInt(tag); - PositionVector poly; - for (int i = 0; i < no; i++) { - poly.push_back(getPosition(from)); - } - poly.closePolygon(); - NIVissimNodeDef_Poly::dictionary(id, name, poly); - } - return true; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Knotendefinition.h b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Knotendefinition.h deleted file mode 100644 index f228c5709..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Knotendefinition.h +++ /dev/null @@ -1,46 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Knotendefinition.h -/// @author Daniel Krajzewicz -/// @date Wed, 18 Dec 2002 -/// -// -/****************************************************************************/ -#pragma once -#include - -#include -#include "../NIImporter_Vissim.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NIVissimSingleTypeParser_Knotendefinition - * - */ -class NIVissimSingleTypeParser_Knotendefinition : - public NIImporter_Vissim::VissimSingleTypeParser { -public: - /// Constructor - NIVissimSingleTypeParser_Knotendefinition(NIImporter_Vissim& parent); - - /// Destructor - ~NIVissimSingleTypeParser_Knotendefinition(); - - /// Parses the data type from the given stream - bool parse(std::istream& from); - -}; diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_LSAKopplungsdefinition.cpp b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_LSAKopplungsdefinition.cpp deleted file mode 100644 index 7e436fe37..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_LSAKopplungsdefinition.cpp +++ /dev/null @@ -1,46 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_LSAKopplungsdefinition.cpp -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Wed, 30 Apr 2003 -/// -// -/****************************************************************************/ -#include - -#include -#include -#include "../NIImporter_Vissim.h" -#include "../tempstructs/NIVissimSource.h" -#include "NIVissimSingleTypeParser_LSAKopplungsdefinition.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -NIVissimSingleTypeParser_LSAKopplungsdefinition::NIVissimSingleTypeParser_LSAKopplungsdefinition(NIImporter_Vissim& parent) - : NIImporter_Vissim::VissimSingleTypeParser(parent) {} - - -NIVissimSingleTypeParser_LSAKopplungsdefinition::~NIVissimSingleTypeParser_LSAKopplungsdefinition() {} - - -bool -NIVissimSingleTypeParser_LSAKopplungsdefinition::parse(std::istream&) { - return true; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_LSAKopplungsdefinition.h b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_LSAKopplungsdefinition.h deleted file mode 100644 index be905d031..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_LSAKopplungsdefinition.h +++ /dev/null @@ -1,46 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_LSAKopplungsdefinition.h -/// @author Daniel Krajzewicz -/// @date Wed, 30 Apr 2003 -/// -// -/****************************************************************************/ -#pragma once -#include - -#include -#include "../NIImporter_Vissim.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NIVissimSingleTypeParser_LSAKopplungsdefinition - * - */ -class NIVissimSingleTypeParser_LSAKopplungsdefinition : - public NIImporter_Vissim::VissimSingleTypeParser { -public: - /// Constructor - NIVissimSingleTypeParser_LSAKopplungsdefinition(NIImporter_Vissim& parent); - - /// Destructor - ~NIVissimSingleTypeParser_LSAKopplungsdefinition(); - - /// Parses the data type from the given stream - bool parse(std::istream& from); - -}; diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Laengenverteilungsdefinition.cpp b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Laengenverteilungsdefinition.cpp deleted file mode 100644 index c9e8c9c1b..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Laengenverteilungsdefinition.cpp +++ /dev/null @@ -1,64 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Laengenverteilungsdefinition.cpp -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Wed, 18 Dec 2002 -/// -// -/****************************************************************************/ -#include - -#include -#include -#include -#include "../NIImporter_Vissim.h" -#include -#include -#include "NIVissimSingleTypeParser_Laengenverteilungsdefinition.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -NIVissimSingleTypeParser_Laengenverteilungsdefinition::NIVissimSingleTypeParser_Laengenverteilungsdefinition(NIImporter_Vissim& parent) - : NIImporter_Vissim::VissimSingleTypeParser(parent) {} - - -NIVissimSingleTypeParser_Laengenverteilungsdefinition::~NIVissimSingleTypeParser_Laengenverteilungsdefinition() {} - - -bool -NIVissimSingleTypeParser_Laengenverteilungsdefinition::parse(std::istream& from) { - // id - std::string id; - from >> id; - // list of points - Distribution_Points* points = new Distribution_Points(id); - std::string tag; - do { - tag = readEndSecure(from); - if (tag != "DATAEND") { - double p1 = StringUtils::toDouble(tag); - from >> tag; - double p2 = StringUtils::toDouble(tag); - points->add(p1, p2); - } - } while (tag != "DATAEND"); - DistributionCont::dictionary("length", id, points); - return true; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Laengenverteilungsdefinition.h b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Laengenverteilungsdefinition.h deleted file mode 100644 index b235a6a94..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Laengenverteilungsdefinition.h +++ /dev/null @@ -1,46 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Laengenverteilungsdefinition.h -/// @author Daniel Krajzewicz -/// @date Wed, 18 Dec 2002 -/// -// -/****************************************************************************/ -#pragma once -#include - -#include -#include "../NIImporter_Vissim.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NIVissimSingleTypeParser_Laengenverteilungsdefinition - * - */ -class NIVissimSingleTypeParser_Laengenverteilungsdefinition : - public NIImporter_Vissim::VissimSingleTypeParser { -public: - /// Constructor - NIVissimSingleTypeParser_Laengenverteilungsdefinition(NIImporter_Vissim& parent); - - /// Destructor - ~NIVissimSingleTypeParser_Laengenverteilungsdefinition(); - - /// Parses the data type from the given stream - bool parse(std::istream& from); - -}; diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Langsamfahrbereichdefinition.cpp b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Langsamfahrbereichdefinition.cpp deleted file mode 100644 index 13a2aca51..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Langsamfahrbereichdefinition.cpp +++ /dev/null @@ -1,54 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Langsamfahrbereichdefinition.cpp -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Wed, 18 Dec 2002 -/// -// -/****************************************************************************/ -#include - -#include -#include -#include "../NIImporter_Vissim.h" -#include "NIVissimSingleTypeParser_Langsamfahrbereichdefinition.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -NIVissimSingleTypeParser_Langsamfahrbereichdefinition::NIVissimSingleTypeParser_Langsamfahrbereichdefinition(NIImporter_Vissim& parent) - : NIImporter_Vissim::VissimSingleTypeParser(parent) {} - - -NIVissimSingleTypeParser_Langsamfahrbereichdefinition::~NIVissimSingleTypeParser_Langsamfahrbereichdefinition() {} - - -bool -NIVissimSingleTypeParser_Langsamfahrbereichdefinition::parse(std::istream& from) { - std::string id; - from >> id; - readUntil(from, "fahrzeugklasse"); - std::string tag = "fahrzeugklasse"; - while (tag == "fahrzeugklasse") { - readUntil(from, "maxverzoegerung"); - tag = myRead(from); - tag = myRead(from); - } - return true; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Langsamfahrbereichdefinition.h b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Langsamfahrbereichdefinition.h deleted file mode 100644 index f5b5d5346..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Langsamfahrbereichdefinition.h +++ /dev/null @@ -1,46 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Langsamfahrbereichdefinition.h -/// @author Daniel Krajzewicz -/// @date Wed, 18 Dec 2002 -/// -// -/****************************************************************************/ -#pragma once -#include - -#include -#include "../NIImporter_Vissim.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NIVissimSingleTypeParser_Langsamfahrbereichdefinition - * - */ -class NIVissimSingleTypeParser_Langsamfahrbereichdefinition : - public NIImporter_Vissim::VissimSingleTypeParser { -public: - /// Constructor - NIVissimSingleTypeParser_Langsamfahrbereichdefinition(NIImporter_Vissim& parent); - - /// Destructor - ~NIVissimSingleTypeParser_Langsamfahrbereichdefinition(); - - /// Parses the data type from the given stream - bool parse(std::istream& from); - -}; diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Lichtsignalanlagendefinition.cpp b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Lichtsignalanlagendefinition.cpp deleted file mode 100644 index 2696c7dc5..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Lichtsignalanlagendefinition.cpp +++ /dev/null @@ -1,153 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Lichtsignalanlagendefinition.cpp -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date Wed, 18 Dec 2002 -/// -// -/****************************************************************************/ -#include - -#include -#include -#include -#include "../NIImporter_Vissim.h" -#include "../tempstructs/NIVissimTL.h" -#include "NIVissimSingleTypeParser_Lichtsignalanlagendefinition.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -NIVissimSingleTypeParser_Lichtsignalanlagendefinition::NIVissimSingleTypeParser_Lichtsignalanlagendefinition(NIImporter_Vissim& parent) - : NIImporter_Vissim::VissimSingleTypeParser(parent) {} - - -NIVissimSingleTypeParser_Lichtsignalanlagendefinition::~NIVissimSingleTypeParser_Lichtsignalanlagendefinition() {} - - -bool -NIVissimSingleTypeParser_Lichtsignalanlagendefinition::parse(std::istream& from) { - // - int id; - from >> id; - // - std::string tag, name; - tag = myRead(from); - if (tag == "name") { - name = readName(from); - tag = myRead(from); - } - // type - std::string type; - type = myRead(from); - if (type == "festzeit") { - return parseFixedTime(id, name, from); - } - if (type == "vas") { - return parseVAS(id, name, from); - } - if (type == "vsplus") { - return parseRestActuated(id, name, from, type); - } - if (type == "trends") { - return parseRestActuated(id, name, from, type); - } - if (type == "vap") { - return parseRestActuated(id, name, from, type); - } - if (type == "tl") { - return parseRestActuated(id, name, from, type); - } - if (type == "pos") { - return parseRestActuated(id, name, from, type); - } - if (type == "nema") { - return parseRestActuated(id, name, from, type); - } - if (type == "extern") { - return parseRestActuated(id, name, from, type); - } - WRITE_ERROR("Unsupported LSA-Type '" + type + "' occurred."); - return false; -} - - -bool -NIVissimSingleTypeParser_Lichtsignalanlagendefinition::parseFixedTime( - int id, std::string name, std::istream& from) { - std::string type = "festzeit"; - std::string tag; - from >> tag; - // - double absdur; - from >> absdur; // type-checking is missing! - // - tag = readEndSecure(from); - double offset = 0; - if (tag == "versatz") { - from >> offset; // type-checking is missing! - } - if (tag != "szpkonfdatei" && tag != "DATAEND" && tag != "progdatei") { - tag = readEndSecure(from); - if (tag == "szpkonfdatei" || tag == "progdatei") { - type = "festzeit_fake"; - } - } - return NIVissimTL::dictionary(id, type, name, (SUMOTime) absdur, (SUMOTime) offset); -} - - -bool -NIVissimSingleTypeParser_Lichtsignalanlagendefinition::parseVAS( - int id, std::string name, std::istream& from) { - std::string tag; - from >> tag; - // - double absdur; - from >> absdur; // type-checking is missing! - // - tag = readEndSecure(from); - double offset = 0; - if (tag == "versatz") { - from >> offset; // type-checking is missing! - } - return NIVissimTL::dictionary(id, "vas", name, (SUMOTime) absdur, (SUMOTime) offset); -} - - -bool -NIVissimSingleTypeParser_Lichtsignalanlagendefinition::parseRestActuated( - int id, std::string name, std::istream& from, const std::string& type) { - std::string tag; - from >> tag; - // - double absdur; - from >> absdur; // type-checking is missing! - // - tag = readEndSecure(from); - double offset = 0; - if (tag == "versatz") { - from >> offset; // type-checking is missing! - } - while (tag != "datei") { - tag = myRead(from); - } - return NIVissimTL::dictionary(id, type, name, (SUMOTime) absdur, (SUMOTime) offset); -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Lichtsignalanlagendefinition.h b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Lichtsignalanlagendefinition.h deleted file mode 100644 index 13c9a6ba5..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Lichtsignalanlagendefinition.h +++ /dev/null @@ -1,60 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Lichtsignalanlagendefinition.h -/// @author Daniel Krajzewicz -/// @date Wed, 18 Dec 2002 -/// -// -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include "../NIImporter_Vissim.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NIVissimSingleTypeParser_Lichtsignalanlagendefinition - * - */ -class NIVissimSingleTypeParser_Lichtsignalanlagendefinition : - public NIImporter_Vissim::VissimSingleTypeParser { -public: - /// Constructor - NIVissimSingleTypeParser_Lichtsignalanlagendefinition(NIImporter_Vissim& parent); - - /// Destructor - ~NIVissimSingleTypeParser_Lichtsignalanlagendefinition(); - - /// Parses the data type from the given stream - bool parse(std::istream& from); - -private: - /// parses a traffic light with fixed times (no other types are supported by now) - bool parseFixedTime(int id, std::string name, std::istream& from); - - /** @brief Parses a vas-traffic light; - All other actuated traffic lights are parsed using "parseRestActuated" - as they have a different format */ - bool parseVAS(int id, std::string name, std::istream& from); - - /// Parses actuated traffic lights (beside VAS) - bool parseRestActuated(int id, std::string name, std::istream& from, - const std::string& type); - -}; diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Liniendefinition.cpp b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Liniendefinition.cpp deleted file mode 100644 index 39adf2975..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Liniendefinition.cpp +++ /dev/null @@ -1,52 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Liniendefinition.cpp -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Wed, 18 Dec 2002 -/// -// -/****************************************************************************/ -#include - -#include -#include -#include "../NIImporter_Vissim.h" -#include "../tempstructs/NIVissimClosures.h" -#include "NIVissimSingleTypeParser_Liniendefinition.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -NIVissimSingleTypeParser_Liniendefinition::NIVissimSingleTypeParser_Liniendefinition(NIImporter_Vissim& parent) - : NIImporter_Vissim::VissimSingleTypeParser(parent) {} - - -NIVissimSingleTypeParser_Liniendefinition::~NIVissimSingleTypeParser_Liniendefinition() {} - - -bool -NIVissimSingleTypeParser_Liniendefinition::parse(std::istream& from) { - std::string tag; - from >> tag; - //cout << tag << endl; - do { - getline(from, tag); - } while (tag.length() > 0 && tag[0] == ' '); - return true; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Liniendefinition.h b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Liniendefinition.h deleted file mode 100644 index 9821443bc..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Liniendefinition.h +++ /dev/null @@ -1,46 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Liniendefinition.h -/// @author Daniel Krajzewicz -/// @date Wed, 18 Dec 2002 -/// -// -/****************************************************************************/ -#pragma once -#include - -#include -#include "../NIImporter_Vissim.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NIVissimSingleTypeParser_Liniendefinition - * - */ -class NIVissimSingleTypeParser_Liniendefinition : - public NIImporter_Vissim::VissimSingleTypeParser { -public: - /// Constructor - NIVissimSingleTypeParser_Liniendefinition(NIImporter_Vissim& parent); - - /// Destructor - ~NIVissimSingleTypeParser_Liniendefinition(); - - /// Parses the data type from the given stream - bool parse(std::istream& from); - -}; diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Linksverkehr.cpp b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Linksverkehr.cpp deleted file mode 100644 index 308594e57..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Linksverkehr.cpp +++ /dev/null @@ -1,46 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Linksverkehr.cpp -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Wed, 30 Apr 2003 -/// -// -/****************************************************************************/ -#include - -#include -#include -#include "../NIImporter_Vissim.h" -#include "../tempstructs/NIVissimSource.h" -#include "NIVissimSingleTypeParser_Linksverkehr.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -NIVissimSingleTypeParser_Linksverkehr::NIVissimSingleTypeParser_Linksverkehr(NIImporter_Vissim& parent) - : NIImporter_Vissim::VissimSingleTypeParser(parent) {} - - -NIVissimSingleTypeParser_Linksverkehr::~NIVissimSingleTypeParser_Linksverkehr() {} - - -bool -NIVissimSingleTypeParser_Linksverkehr::parse(std::istream&) { - return true; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Linksverkehr.h b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Linksverkehr.h deleted file mode 100644 index 6752770c9..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Linksverkehr.h +++ /dev/null @@ -1,46 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Linksverkehr.h -/// @author Daniel Krajzewicz -/// @date Wed, 30 Apr 2003 -/// -// -/****************************************************************************/ -#pragma once -#include - -#include -#include "../NIImporter_Vissim.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NIVissimSingleTypeParser_Linksverkehr - * - */ -class NIVissimSingleTypeParser_Linksverkehr : - public NIImporter_Vissim::VissimSingleTypeParser { -public: - /// Constructor - NIVissimSingleTypeParser_Linksverkehr(NIImporter_Vissim& parent); - - /// Destructor - ~NIVissimSingleTypeParser_Linksverkehr(); - - /// Parses the data type from the given stream - bool parse(std::istream& from); - -}; diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Messungsdefinition.cpp b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Messungsdefinition.cpp deleted file mode 100644 index 8c77bc200..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Messungsdefinition.cpp +++ /dev/null @@ -1,46 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Messungsdefinition.cpp -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Wed, 18 Dec 2002 -/// -// -/****************************************************************************/ -#include - -#include -#include -#include "../NIImporter_Vissim.h" -#include "../tempstructs/NIVissimClosures.h" -#include "NIVissimSingleTypeParser_Messungsdefinition.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -NIVissimSingleTypeParser_Messungsdefinition::NIVissimSingleTypeParser_Messungsdefinition(NIImporter_Vissim& parent) - : NIImporter_Vissim::VissimSingleTypeParser(parent) {} - - -NIVissimSingleTypeParser_Messungsdefinition::~NIVissimSingleTypeParser_Messungsdefinition() {} - - -bool -NIVissimSingleTypeParser_Messungsdefinition::parse(std::istream& from) { - return skipOverreading(from, "strecke"); -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Messungsdefinition.h b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Messungsdefinition.h deleted file mode 100644 index 6c27d657f..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Messungsdefinition.h +++ /dev/null @@ -1,46 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Messungsdefinition.h -/// @author Daniel Krajzewicz -/// @date Wed, 18 Dec 2002 -/// -// -/****************************************************************************/ -#pragma once -#include - -#include -#include "../NIImporter_Vissim.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NIVissimSingleTypeParser_Messungsdefinition - * - */ -class NIVissimSingleTypeParser_Messungsdefinition : - public NIImporter_Vissim::VissimSingleTypeParser { -public: - /// Constructor - NIVissimSingleTypeParser_Messungsdefinition(NIImporter_Vissim& parent); - - /// Destructor - ~NIVissimSingleTypeParser_Messungsdefinition(); - - /// Parses the data type from the given stream - bool parse(std::istream& from); - -}; diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Netzobjektdefinition.cpp b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Netzobjektdefinition.cpp deleted file mode 100644 index 1097a4259..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Netzobjektdefinition.cpp +++ /dev/null @@ -1,46 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Netzobjektdefinition.cpp -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Wed, 30 Apr 2003 -/// -// -/****************************************************************************/ -#include - -#include -#include -#include "../NIImporter_Vissim.h" -#include "../tempstructs/NIVissimSource.h" -#include "NIVissimSingleTypeParser_Netzobjektdefinition.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -NIVissimSingleTypeParser_Netzobjektdefinition::NIVissimSingleTypeParser_Netzobjektdefinition(NIImporter_Vissim& parent) - : NIImporter_Vissim::VissimSingleTypeParser(parent) {} - - -NIVissimSingleTypeParser_Netzobjektdefinition::~NIVissimSingleTypeParser_Netzobjektdefinition() {} - - -bool -NIVissimSingleTypeParser_Netzobjektdefinition::parse(std::istream&) { - return true; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Netzobjektdefinition.h b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Netzobjektdefinition.h deleted file mode 100644 index 93a8df955..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Netzobjektdefinition.h +++ /dev/null @@ -1,46 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Netzobjektdefinition.h -/// @author Daniel Krajzewicz -/// @date Wed, 30 Apr 2003 -/// -// -/****************************************************************************/ -#pragma once -#include - -#include -#include "../NIImporter_Vissim.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NIVissimSingleTypeParser_Netzobjektdefinition - * - */ -class NIVissimSingleTypeParser_Netzobjektdefinition : - public NIImporter_Vissim::VissimSingleTypeParser { -public: - /// Constructor - NIVissimSingleTypeParser_Netzobjektdefinition(NIImporter_Vissim& parent); - - /// Destructor - ~NIVissimSingleTypeParser_Netzobjektdefinition(); - - /// Parses the data type from the given stream - bool parse(std::istream& from); - -}; diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Parkplatzdefinition.cpp b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Parkplatzdefinition.cpp deleted file mode 100644 index 9a4caa934..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Parkplatzdefinition.cpp +++ /dev/null @@ -1,120 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Parkplatzdefinition.cpp -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Wed, 18 Dec 2002 -/// -// -/****************************************************************************/ -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "../NIImporter_Vissim.h" -#include "../tempstructs/NIVissimDistrictConnection.h" -#include "NIVissimSingleTypeParser_Parkplatzdefinition.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -NIVissimSingleTypeParser_Parkplatzdefinition::NIVissimSingleTypeParser_Parkplatzdefinition(NIImporter_Vissim& parent) - : NIImporter_Vissim::VissimSingleTypeParser(parent) {} - - -NIVissimSingleTypeParser_Parkplatzdefinition::~NIVissimSingleTypeParser_Parkplatzdefinition() {} - - -bool -NIVissimSingleTypeParser_Parkplatzdefinition::parse(std::istream& from) { - int id; - from >> id; - - std::string tag; - from >> tag; - std::string name = readName(from); - - // parse the districts - // and allocate them if not done before - // A district may be already saved when another parking place with - // the same district was already build. - std::vector districts; - std::vector percentages; - readUntil(from, "bezirke"); // "Bezirke" - while (tag != "ort") { - double perc = -1; - int districtid; - from >> districtid; - tag = myRead(from); - if (tag == "anteil") { - from >> perc; - } - districts.push_back(districtid); - percentages.push_back(perc); - tag = myRead(from); - } - - from >> tag; // "Strecke" - int edgeid; - from >> edgeid; - - double position; - from >> tag; // "bei" - from >> position; - - double length; - from >> tag; - from >> length; - - from >> tag; // "Kapazitaet" - from >> tag; // "Kapazitaet"-value - - tag = myRead(from); - if (tag == "belegung") { - from >> tag; - tag = myRead(from); // "fahrzeugklasse" - } - - std::vector > assignedVehicles; - while (tag != "default") { - int vclass; - from >> vclass; - from >> tag; // "vwunsch" - int vwunsch; - from >> vwunsch; // "vwunsch"-value - assignedVehicles.push_back(std::pair(vclass, vwunsch)); - tag = myRead(from); - } - - from >> tag; - from >> tag; -// NIVissimEdge *e = NIVissimEdge::dictionary(edgeid); -// e->addReferencedDistrict(id); - - // build the district connection - return NIVissimDistrictConnection::dictionary(id, name, - districts, percentages, edgeid, position, assignedVehicles); -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Parkplatzdefinition.h b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Parkplatzdefinition.h deleted file mode 100644 index 8f6091801..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Parkplatzdefinition.h +++ /dev/null @@ -1,46 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Parkplatzdefinition.h -/// @author Daniel Krajzewicz -/// @date Wed, 18 Dec 2002 -/// -// -/****************************************************************************/ -#pragma once -#include - -#include -#include "../NIImporter_Vissim.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NIVissimSingleTypeParser_Parkplatzdefinition - * - */ -class NIVissimSingleTypeParser_Parkplatzdefinition : - public NIImporter_Vissim::VissimSingleTypeParser { -public: - /// Constructor - NIVissimSingleTypeParser_Parkplatzdefinition(NIImporter_Vissim& parent); - - /// Destructor - ~NIVissimSingleTypeParser_Parkplatzdefinition(); - - /// Parses the data type from the given stream - bool parse(std::istream& from); - -}; diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Querschnittsmessungsdefinition.cpp b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Querschnittsmessungsdefinition.cpp deleted file mode 100644 index 7c91e8155..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Querschnittsmessungsdefinition.cpp +++ /dev/null @@ -1,62 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Querschnittsmessungsdefinition.cpp -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Wed, 18 Dec 2002 -/// -// -/****************************************************************************/ -#include - -#include -#include -#include "../NIImporter_Vissim.h" -#include "../tempstructs/NIVissimClosures.h" -#include "NIVissimSingleTypeParser_Querschnittsmessungsdefinition.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -NIVissimSingleTypeParser_Querschnittsmessungsdefinition::NIVissimSingleTypeParser_Querschnittsmessungsdefinition(NIImporter_Vissim& parent) - : NIImporter_Vissim::VissimSingleTypeParser(parent) {} - - -NIVissimSingleTypeParser_Querschnittsmessungsdefinition::~NIVissimSingleTypeParser_Querschnittsmessungsdefinition() {} - - -bool -NIVissimSingleTypeParser_Querschnittsmessungsdefinition::parse(std::istream& from) { - std::string tag = myRead(from); - if (tag == "von") { - while (tag != "fahrzeugklassen" && tag != "konfdatei") { - tag = myRead(from); - } - tag = myRead(from); - while (tag != "DATAEND") { - tag = readEndSecure(from); - } - return true; - } - tag = myRead(from); - tag = myRead(from); - while (tag != "DATAEND") { - tag = readEndSecure(from); - } - return true; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Querschnittsmessungsdefinition.h b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Querschnittsmessungsdefinition.h deleted file mode 100644 index da55eb013..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Querschnittsmessungsdefinition.h +++ /dev/null @@ -1,46 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Querschnittsmessungsdefinition.h -/// @author Daniel Krajzewicz -/// @date Wed, 18 Dec 2002 -/// -// -/****************************************************************************/ -#pragma once -#include - -#include -#include "../NIImporter_Vissim.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NIVissimSingleTypeParser_Querschnittsmessungsdefinition - * - */ -class NIVissimSingleTypeParser_Querschnittsmessungsdefinition : - public NIImporter_Vissim::VissimSingleTypeParser { -public: - /// Constructor - NIVissimSingleTypeParser_Querschnittsmessungsdefinition(NIImporter_Vissim& parent); - - /// Destructor - ~NIVissimSingleTypeParser_Querschnittsmessungsdefinition(); - - /// Parses the data type from the given stream - bool parse(std::istream& from); - -}; diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Querverkehrsstoerungsdefinition.cpp b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Querverkehrsstoerungsdefinition.cpp deleted file mode 100644 index 207b8d25b..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Querverkehrsstoerungsdefinition.cpp +++ /dev/null @@ -1,182 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Querverkehrsstoerungsdefinition.cpp -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date Wed, 18 Dec 2002 -/// -// -/****************************************************************************/ -#include - -#include -#include -#include -#include "../NIImporter_Vissim.h" -#include "../tempstructs/NIVissimExtendedEdgePoint.h" -#include "../tempstructs/NIVissimDisturbance.h" -#include "NIVissimSingleTypeParser_Querverkehrsstoerungsdefinition.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -NIVissimSingleTypeParser_Querverkehrsstoerungsdefinition::NIVissimSingleTypeParser_Querverkehrsstoerungsdefinition(NIImporter_Vissim& parent) - : NIImporter_Vissim::VissimSingleTypeParser(parent) {} - - -NIVissimSingleTypeParser_Querverkehrsstoerungsdefinition::~NIVissimSingleTypeParser_Querverkehrsstoerungsdefinition() {} - - -bool -NIVissimSingleTypeParser_Querverkehrsstoerungsdefinition::parse(std::istream& from) { - std::string tag; - tag = myRead(from); - if (tag == "nureigenestrecke") { - return parseOnlyMe(from); - } else if (tag == "ort") { - return parsePositionDescribed(from); - } else if (tag == "nummer") { - return parseNumbered(from); - } - WRITE_ERROR( - "NIVissimSingleTypeParser_Querverkehrsstoerungsdefinition: format problem"); - throw 1; -} - -bool -NIVissimSingleTypeParser_Querverkehrsstoerungsdefinition::parseOnlyMe(std::istream& from) { - std::string tag; - from >> tag; - return true; -} - - -bool -NIVissimSingleTypeParser_Querverkehrsstoerungsdefinition::parsePositionDescribed(std::istream& from) { - std::string tag = myRead(from); - NIVissimExtendedEdgePoint edge = parsePos(from); -// from >> tag; // "Durch" - bool ok = true; - do { - from >> tag; // "Strecke" - NIVissimExtendedEdgePoint by = parsePos(from); - // - double timegap; - from >> timegap; - - from >> tag; - double waygap; - from >> waygap; - - double vmax = -1; - tag = readEndSecure(from); - if (tag == "vmax") { - from >> vmax; - } - ok = NIVissimDisturbance::dictionary("", edge, by); - if (tag != "DATAEND") { - tag = readEndSecure(from); - } - } while (tag != "DATAEND" && ok); - return ok; -} - - - -bool -NIVissimSingleTypeParser_Querverkehrsstoerungsdefinition::parseNumbered(std::istream& from) { - // - int id; - from >> id; - // - std::string tag; - from >> tag; - std::string name = readName(from); - // skip optional "Beschriftung" - while (tag != "ort") { - tag = myRead(from); - } - // - from >> tag; // "Strecke" - NIVissimExtendedEdgePoint edge = parsePos(from); - bool ok = true; - do { - from >> tag; // "Ort" - from >> tag; // "Strecke" - NIVissimExtendedEdgePoint by = parsePos(from); - // - double timegap; - from >> timegap; - - double waygap; - from >> tag; - from >> waygap; - - double vmax = -1; - tag = readEndSecure(from); - if (tag == "vmax") { - from >> vmax; - } - - ok = NIVissimDisturbance::dictionary(name, edge, by); - if (tag != "DATAEND") { - tag = readEndSecure(from); - } - } while (tag != "DATAEND" && ok); - return ok; -} - - - -NIVissimExtendedEdgePoint -NIVissimSingleTypeParser_Querverkehrsstoerungsdefinition::parsePos(std::istream& from) { - int edgeid; - from >> edgeid; // type-checking is missing! - // - std::string tag; - from >> tag; - from >> tag; - std::vector lanes; - if (tag == "ALLE") { - //lanes.push_back(1); // !!! - } else { - lanes.push_back(StringUtils::toInt(tag)); - } - // - double position; - from >> tag; - from >> position; - // assigned vehicle types - std::vector types; - from >> tag; - while (tag != "zeitluecke" && tag != "durch" && tag != "DATAEND" && tag != "alle") { - tag = readEndSecure(from); - if (tag != "DATAEND") { - if (tag == "alle") { - types.push_back(-1); - from >> tag; - tag = "alle"; - } else if (tag != "zeitluecke" && tag != "durch" && tag != "DATAEND") { - int tmp = StringUtils::toInt(tag); - types.push_back(tmp); - } - } - } - return NIVissimExtendedEdgePoint(edgeid, lanes, position, types); -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Querverkehrsstoerungsdefinition.h b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Querverkehrsstoerungsdefinition.h deleted file mode 100644 index c03e5f38c..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Querverkehrsstoerungsdefinition.h +++ /dev/null @@ -1,58 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Querverkehrsstoerungsdefinition.h -/// @author Daniel Krajzewicz -/// @date Wed, 18 Dec 2002 -/// -// -/****************************************************************************/ -#pragma once -#include - -#include -#include "../NIImporter_Vissim.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NIVissimSingleTypeParser_Querverkehrsstoerungsdefinition - * - */ -class NIVissimSingleTypeParser_Querverkehrsstoerungsdefinition : - public NIImporter_Vissim::VissimSingleTypeParser { -public: - /// Constructor - NIVissimSingleTypeParser_Querverkehrsstoerungsdefinition(NIImporter_Vissim& parent); - - /// Destructor - ~NIVissimSingleTypeParser_Querverkehrsstoerungsdefinition(); - - /// Parses the data type from the given stream - bool parse(std::istream& from); - -private: - /// ?? (unknown vissim-description) - bool parseOnlyMe(std::istream& from); - - /// parses a disturbance described by its position - bool parsePositionDescribed(std::istream& from); - - /// parses a full description of a disturbance - bool parseNumbered(std::istream& from); - - NIVissimExtendedEdgePoint parsePos(std::istream& from); - -}; diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Rautedefinition.cpp b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Rautedefinition.cpp deleted file mode 100644 index 72e4b5700..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Rautedefinition.cpp +++ /dev/null @@ -1,48 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Rautedefinition.cpp -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Wed, 18 Dec 2002 -/// -// -/****************************************************************************/ -#include - -#include -#include -#include "../NIImporter_Vissim.h" -#include "../tempstructs/NIVissimSource.h" -#include "NIVissimSingleTypeParser_Rautedefinition.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -NIVissimSingleTypeParser_Rautedefinition::NIVissimSingleTypeParser_Rautedefinition(NIImporter_Vissim& parent) - : NIImporter_Vissim::VissimSingleTypeParser(parent) {} - - -NIVissimSingleTypeParser_Rautedefinition::~NIVissimSingleTypeParser_Rautedefinition() {} - - -bool -NIVissimSingleTypeParser_Rautedefinition::parse(std::istream& from) { - std::string t; - getline(from, t); - return true; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Rautedefinition.h b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Rautedefinition.h deleted file mode 100644 index fd826b93d..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Rautedefinition.h +++ /dev/null @@ -1,47 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Rautedefinition.h -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Wed, 18 Dec 2002 -/// -// -/****************************************************************************/ -#pragma once -#include - -#include -#include "../NIImporter_Vissim.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NIVissimSingleTypeParser_Rautedefinition - * - */ -class NIVissimSingleTypeParser_Rautedefinition : - public NIImporter_Vissim::VissimSingleTypeParser { -public: - /// Constructor - NIVissimSingleTypeParser_Rautedefinition(NIImporter_Vissim& parent); - - /// Destructor - ~NIVissimSingleTypeParser_Rautedefinition(); - - /// Parses the data type from the given stream - bool parse(std::istream& from); - -}; diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Reisezeitmessungsdefinition.cpp b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Reisezeitmessungsdefinition.cpp deleted file mode 100644 index 39b9ac951..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Reisezeitmessungsdefinition.cpp +++ /dev/null @@ -1,64 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Reisezeitmessungsdefinition.cpp -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Wed, 18 Dec 2002 -/// -// -/****************************************************************************/ -#include - -#include -#include -#include "../NIImporter_Vissim.h" -#include "../tempstructs/NIVissimClosures.h" -#include "NIVissimSingleTypeParser_Reisezeitmessungsdefinition.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -NIVissimSingleTypeParser_Reisezeitmessungsdefinition::NIVissimSingleTypeParser_Reisezeitmessungsdefinition(NIImporter_Vissim& parent) - : NIImporter_Vissim::VissimSingleTypeParser(parent) {} - - -NIVissimSingleTypeParser_Reisezeitmessungsdefinition::~NIVissimSingleTypeParser_Reisezeitmessungsdefinition() {} - - -bool -NIVissimSingleTypeParser_Reisezeitmessungsdefinition::parse(std::istream& from) { - std::string tag = myRead(from); - if (tag == "aggregationsintervall") { - while (tag != "DATAEND") { - tag = readEndSecure(from); - } - return true; - } - - while (tag != "strecke") { - tag = myRead(from); - } - tag = myRead(from); - while (tag != "strecke") { - tag = myRead(from); - } - while (tag != "DATAEND") { - tag = readEndSecure(from); - } - return true; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Reisezeitmessungsdefinition.h b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Reisezeitmessungsdefinition.h deleted file mode 100644 index 09d282af1..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Reisezeitmessungsdefinition.h +++ /dev/null @@ -1,46 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Reisezeitmessungsdefinition.h -/// @author Daniel Krajzewicz -/// @date Wed, 18 Dec 2002 -/// -// -/****************************************************************************/ -#pragma once -#include - -#include -#include "../NIImporter_Vissim.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NIVissimSingleTypeParser_Reisezeitmessungsdefinition - * - */ -class NIVissimSingleTypeParser_Reisezeitmessungsdefinition : - public NIImporter_Vissim::VissimSingleTypeParser { -public: - /// Constructor - NIVissimSingleTypeParser_Reisezeitmessungsdefinition(NIImporter_Vissim& parent); - - /// Destructor - ~NIVissimSingleTypeParser_Reisezeitmessungsdefinition(); - - /// Parses the data type from the given stream - bool parse(std::istream& from); - -}; diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Richtungsentscheidungsdefinition.cpp b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Richtungsentscheidungsdefinition.cpp deleted file mode 100644 index 5a9e7c3fd..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Richtungsentscheidungsdefinition.cpp +++ /dev/null @@ -1,45 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Richtungsentscheidungsdefinition.cpp -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Wed, 18 Dec 2002 -/// -// -/****************************************************************************/ -#include - -#include -#include -#include "../NIImporter_Vissim.h" -#include "NIVissimSingleTypeParser_Richtungsentscheidungsdefinition.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -NIVissimSingleTypeParser_Richtungsentscheidungsdefinition::NIVissimSingleTypeParser_Richtungsentscheidungsdefinition(NIImporter_Vissim& parent) - : NIImporter_Vissim::VissimSingleTypeParser(parent) {} - - -NIVissimSingleTypeParser_Richtungsentscheidungsdefinition::~NIVissimSingleTypeParser_Richtungsentscheidungsdefinition() {} - - -bool -NIVissimSingleTypeParser_Richtungsentscheidungsdefinition::parse(std::istream& from) { - return skipOverreading(from, "fahrzeugklassen"); -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Richtungsentscheidungsdefinition.h b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Richtungsentscheidungsdefinition.h deleted file mode 100644 index 9f8fcba83..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Richtungsentscheidungsdefinition.h +++ /dev/null @@ -1,46 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Richtungsentscheidungsdefinition.h -/// @author Daniel Krajzewicz -/// @date Wed, 18 Dec 2002 -/// -// -/****************************************************************************/ -#pragma once -#include - -#include -#include "../NIImporter_Vissim.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NIVissimSingleTypeParser_Richtungsentscheidungsdefinition - * - */ -class NIVissimSingleTypeParser_Richtungsentscheidungsdefinition : - public NIImporter_Vissim::VissimSingleTypeParser { -public: - /// Constructor - NIVissimSingleTypeParser_Richtungsentscheidungsdefinition(NIImporter_Vissim& parent); - - /// Destructor - ~NIVissimSingleTypeParser_Richtungsentscheidungsdefinition(); - - /// Parses the data type from the given stream - bool parse(std::istream& from); - -}; diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Richtungspfeildefinition.cpp b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Richtungspfeildefinition.cpp deleted file mode 100644 index 88fbe841f..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Richtungspfeildefinition.cpp +++ /dev/null @@ -1,48 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Richtungspfeildefinition.cpp -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Wed, 18 Dec 2002 -/// -// -/****************************************************************************/ -#include - -#include -#include -#include "../NIImporter_Vissim.h" -#include "../tempstructs/NIVissimSource.h" -#include "NIVissimSingleTypeParser_Richtungspfeildefinition.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -NIVissimSingleTypeParser_Richtungspfeildefinition::NIVissimSingleTypeParser_Richtungspfeildefinition(NIImporter_Vissim& parent) - : NIImporter_Vissim::VissimSingleTypeParser(parent) {} - - -NIVissimSingleTypeParser_Richtungspfeildefinition::~NIVissimSingleTypeParser_Richtungspfeildefinition() {} - - -bool -NIVissimSingleTypeParser_Richtungspfeildefinition::parse(std::istream& from) { - std::string t; - getline(from, t); - return true; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Richtungspfeildefinition.h b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Richtungspfeildefinition.h deleted file mode 100644 index b123a8fec..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Richtungspfeildefinition.h +++ /dev/null @@ -1,46 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Richtungspfeildefinition.h -/// @author Daniel Krajzewicz -/// @date Wed, 18 Dec 2002 -/// -// -/****************************************************************************/ -#pragma once -#include - -#include -#include "../NIImporter_Vissim.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NIVissimSingleTypeParser_Richtungspfeildefinition - * - */ -class NIVissimSingleTypeParser_Richtungspfeildefinition : - public NIImporter_Vissim::VissimSingleTypeParser { -public: - /// Constructor - NIVissimSingleTypeParser_Richtungspfeildefinition(NIImporter_Vissim& parent); - - /// Destructor - ~NIVissimSingleTypeParser_Richtungspfeildefinition(); - - /// Parses the data type from the given stream - bool parse(std::istream& from); - -}; diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Routenentscheidungsdefinition.cpp b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Routenentscheidungsdefinition.cpp deleted file mode 100644 index 8de21fcae..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Routenentscheidungsdefinition.cpp +++ /dev/null @@ -1,64 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Routenentscheidungsdefinition.cpp -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Wed, 18 Dec 2002 -/// -// -/****************************************************************************/ -#include - -#include -#include -#include "../NIImporter_Vissim.h" -#include "NIVissimSingleTypeParser_Routenentscheidungsdefinition.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -NIVissimSingleTypeParser_Routenentscheidungsdefinition::NIVissimSingleTypeParser_Routenentscheidungsdefinition(NIImporter_Vissim& parent) - : NIImporter_Vissim::VissimSingleTypeParser(parent) {} - - -NIVissimSingleTypeParser_Routenentscheidungsdefinition::~NIVissimSingleTypeParser_Routenentscheidungsdefinition() {} - - -bool -NIVissimSingleTypeParser_Routenentscheidungsdefinition::parse(std::istream& from) { - std::string tag; - while (tag != "fahrzeugklassen") { - tag = myRead(from); - } - do { - while (tag != "DATAEND" || tag == "route") { - if (tag == "route") { - while (tag != "strecke") { - tag = myRead(from); - } - tag = readEndSecure(from); - } else { - tag = readEndSecure(from); - } - } - if (tag != "DATAEND") { - tag = readEndSecure(from); - } - } while (tag != "DATAEND"); - return true; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Routenentscheidungsdefinition.h b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Routenentscheidungsdefinition.h deleted file mode 100644 index 78be6df3b..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Routenentscheidungsdefinition.h +++ /dev/null @@ -1,46 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Routenentscheidungsdefinition.h -/// @author Daniel Krajzewicz -/// @date Wed, 18 Dec 2002 -/// -// -/****************************************************************************/ -#pragma once -#include - -#include -#include "../NIImporter_Vissim.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NIVissimSingleTypeParser_Routenentscheidungsdefinition - * - */ -class NIVissimSingleTypeParser_Routenentscheidungsdefinition : - public NIImporter_Vissim::VissimSingleTypeParser { -public: - /// Constructor - NIVissimSingleTypeParser_Routenentscheidungsdefinition(NIImporter_Vissim& parent); - - /// Destructor - ~NIVissimSingleTypeParser_Routenentscheidungsdefinition(); - - /// Parses the data type from the given stream - bool parse(std::istream& from); - -}; diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Signalgeberdefinition.cpp b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Signalgeberdefinition.cpp deleted file mode 100644 index 6dfb40cf5..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Signalgeberdefinition.cpp +++ /dev/null @@ -1,110 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Signalgeberdefinition.cpp -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Wed, 18 Dec 2002 -/// -// -/****************************************************************************/ -#include - -#include -#include -#include -#include -#include -#include -#include "../NIImporter_Vissim.h" -#include "../tempstructs/NIVissimTL.h" -#include "NIVissimSingleTypeParser_Signalgeberdefinition.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -NIVissimSingleTypeParser_Signalgeberdefinition::NIVissimSingleTypeParser_Signalgeberdefinition(NIImporter_Vissim& parent) - : NIImporter_Vissim::VissimSingleTypeParser(parent) {} - - -NIVissimSingleTypeParser_Signalgeberdefinition::~NIVissimSingleTypeParser_Signalgeberdefinition() {} - - -bool -NIVissimSingleTypeParser_Signalgeberdefinition::parse(std::istream& from) { - // - int id; - from >> id; - // - std::string tag, name; - tag = myRead(from); - if (tag == "name") { - name = readName(from); - tag = myRead(from); - } - // skip optional "Beschriftung" - tag = overrideOptionalLabel(from, tag); - // - int lsaid; - std::vector groupids; - if (tag == "lsa") { - int groupid; - from >> lsaid; // type-checking is missing! - from >> tag; // "Gruppe" - do { - from >> groupid; - groupids.push_back(groupid); - tag = myRead(from); - } while (tag == "oder"); - // - } else { - from >> tag; // strecke - WRITE_WARNING("Omitting unknown traffic light."); - return true; - } - if (tag == "typ") { - from >> tag; // typ-value - from >> tag; // "ort" - } - - // - from >> tag; - int edgeid; - from >> edgeid; - - from >> tag; - int laneno; - from >> laneno; - - from >> tag; - double position; - from >> position; - // - while (tag != "fahrzeugklassen") { - tag = myRead(from); - } - std::vector assignedVehicleTypes = parseAssignedVehicleTypes(from, "N/A"); - // - NIVissimTL::dictionary(lsaid); // !!! check whether someting is really done here - NIVissimTL::NIVissimTLSignal* signal = - new NIVissimTL::NIVissimTLSignal(id, name, groupids, edgeid, - laneno, position, assignedVehicleTypes); - if (!NIVissimTL::NIVissimTLSignal::dictionary(lsaid, id, signal)) { - throw 1; // !!! - } - return true; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Signalgeberdefinition.h b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Signalgeberdefinition.h deleted file mode 100644 index 31d86a2e8..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Signalgeberdefinition.h +++ /dev/null @@ -1,46 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Signalgeberdefinition.h -/// @author Daniel Krajzewicz -/// @date Wed, 18 Dec 2002 -/// -// -/****************************************************************************/ -#pragma once -#include - -#include -#include "../NIImporter_Vissim.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NIVissimSingleTypeParser_Signalgeberdefinition - * - */ -class NIVissimSingleTypeParser_Signalgeberdefinition : - public NIImporter_Vissim::VissimSingleTypeParser { -public: - /// Constructor - NIVissimSingleTypeParser_Signalgeberdefinition(NIImporter_Vissim& parent); - - /// Destructor - ~NIVissimSingleTypeParser_Signalgeberdefinition(); - - /// Parses the data type from the given stream - bool parse(std::istream& from); - -}; diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Signalgruppendefinition.cpp b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Signalgruppendefinition.cpp deleted file mode 100644 index 53b3e9ff9..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Signalgruppendefinition.cpp +++ /dev/null @@ -1,199 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Signalgruppendefinition.cpp -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date Wed, 18 Dec 2002 -/// -// -/****************************************************************************/ -#include - -#include -#include -#include -#include -#include -#include -#include "../NIImporter_Vissim.h" -#include "../tempstructs/NIVissimTL.h" -#include "NIVissimSingleTypeParser_Signalgruppendefinition.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -NIVissimSingleTypeParser_Signalgruppendefinition::NIVissimSingleTypeParser_Signalgruppendefinition(NIImporter_Vissim& parent) - : NIImporter_Vissim::VissimSingleTypeParser(parent) {} - - -NIVissimSingleTypeParser_Signalgruppendefinition::~NIVissimSingleTypeParser_Signalgruppendefinition() {} - - -bool -NIVissimSingleTypeParser_Signalgruppendefinition::parse(std::istream& from) { - // - int id; - from >> id; // type-checking is missing! - // - std::string tag; - tag = myRead(from); - std::string name; - if (tag == "name") { - name = readName(from); - tag = myRead(from); - } - // - int lsaid; - from >> lsaid; - NIVissimTL* tl = NIVissimTL::dictionary(lsaid); - if (tl == nullptr) { - WRITE_ERROR("A traffic light group with an unknown traffic light occurred.\n Group-ID: " + toString(id) - + "\n TrafficLight-ID: " + toString(lsaid)); - return false; - } - std::string type = tl->getType(); - if (type == "festzeit") { - return parseFixedTime(id, name, lsaid, from); - } - if (type == "festzeit_fake") { - return parseFixedTime(id, name, lsaid, from); -// return parseExternFixedTime(id, name, lsaid, from); - } - if (type == "vas") { - return parseVAS(id, name, lsaid, from); - } - if (type == "vsplus") { - return parseVSPLUS(id, name, lsaid, from); - } - if (type == "trends") { - return parseTRENDS(id, name, lsaid, from); - } - if (type == "vap") { - return parseVAP(id, name, lsaid, from); - } - if (type == "tl") { - return parseTL(id, name, lsaid, from); - } - if (type == "pos") { - return parsePOS(id, name, lsaid, from); - } - WRITE_WARNING("Unsupported LSA-Type '" + type + "' occurred."); - return true; -} - - -bool -NIVissimSingleTypeParser_Signalgruppendefinition::parseFixedTime( - int id, const std::string& name, int lsaid, std::istream& from) { - // - bool isGreenBegin; - std::vector times; - std::string tag = myRead(from); - if (tag == "dauergruen") { - isGreenBegin = true; - from >> tag; - } else if (tag == "dauerrot") { - isGreenBegin = false; - from >> tag; - } else { - // the first phase will be green - isGreenBegin = true; - while (tag == "rotende" || tag == "gruenanfang") { - double point; - from >> point; // type-checking is missing! - times.push_back(point); - from >> tag; - from >> point; // type-checking is missing! - times.push_back(point); - tag = myRead(from); - } - } - // - double tredyellow, tyellow; - from >> tredyellow; - from >> tag; - from >> tyellow; - NIVissimTL::NIVissimTLSignalGroup* group = - new NIVissimTL::NIVissimTLSignalGroup( - id, name, isGreenBegin, times, (SUMOTime) tredyellow, (SUMOTime) tyellow); - if (!NIVissimTL::NIVissimTLSignalGroup::dictionary(lsaid, id, group)) { - throw 1; // !!! - } - return true; -} - - -bool -NIVissimSingleTypeParser_Signalgruppendefinition::parseVAS( - int /*id*/, const std::string& /*name*/, int lsaid, std::istream& from) { - WRITE_WARNING("VAS traffic lights are not supported (lsa=" + toString(lsaid) + ")"); - std::string tag; - while (tag != "detektoren") { - tag = myRead(from); - } - return true; -} - - -bool -NIVissimSingleTypeParser_Signalgruppendefinition::parseVSPLUS( - int /*id*/, const std::string&, int lsaid, std::istream&) { - WRITE_WARNING("VSPLUS traffic lights are not supported (lsa=" + toString(lsaid) + ")"); - return true; -} - - -bool -NIVissimSingleTypeParser_Signalgruppendefinition::parseTRENDS( - int /*id*/, const std::string&, int lsaid, std::istream&) { - WRITE_WARNING("TRENDS traffic lights are not supported (lsa=" + toString(lsaid) + ")"); - return true; -} - - -bool -NIVissimSingleTypeParser_Signalgruppendefinition::parseVAP( - int /*id*/, const std::string&, int lsaid, std::istream&) { - WRITE_WARNING("VAS traffic lights are not supported (lsa=" + toString(lsaid) + ")"); - return true; -} - - -bool -NIVissimSingleTypeParser_Signalgruppendefinition::parseTL( - int /*id*/, const std::string&, int lsaid, std::istream&) { - WRITE_WARNING("TL traffic lights are not supported (lsa=" + toString(lsaid) + ")"); - return true; -} - - -bool -NIVissimSingleTypeParser_Signalgruppendefinition::parsePOS( - int /*id*/, const std::string&, int lsaid, std::istream&) { - WRITE_WARNING("POS traffic lights are not supported (lsa=" + toString(lsaid) + ")"); - return true; -} - - -bool -NIVissimSingleTypeParser_Signalgruppendefinition::parseExternFixedTime( - int /*id*/, const std::string&, int lsaid, std::istream&) { - WRITE_WARNING("externally defined traffic lights are not supported (lsa=" + toString(lsaid) + ")"); - return true; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Signalgruppendefinition.h b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Signalgruppendefinition.h deleted file mode 100644 index 4efb3a99f..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Signalgruppendefinition.h +++ /dev/null @@ -1,79 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Signalgruppendefinition.h -/// @author Daniel Krajzewicz -/// @date Wed, 18 Dec 2002 -/// -// -/****************************************************************************/ -#pragma once -#include - -#include -#include "../NIImporter_Vissim.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NIVissimSingleTypeParser_Signalgruppendefinition - * - */ -class NIVissimSingleTypeParser_Signalgruppendefinition : - public NIImporter_Vissim::VissimSingleTypeParser { -public: - /// Constructor - NIVissimSingleTypeParser_Signalgruppendefinition(NIImporter_Vissim& parent); - - /// Destructor - ~NIVissimSingleTypeParser_Signalgruppendefinition(); - - /// Parses the data type from the given stream - bool parse(std::istream& from); - -private: - /// Parses a traffic light group which belongs to a fixed time traffic light - bool parseFixedTime(int id, const std::string& name, int lsaid, - std::istream& from); - - /// Parses a traffic light group which belongs to a VAS traffic light - bool parseVAS(int id, const std::string& name, int lsaid, - std::istream& from); - - /// Parses a traffic light group which belongs to a VSPLUS traffic light - bool parseVSPLUS(int id, const std::string& name, int lsaid, - std::istream& from); - - /// Parses a traffic light group which belongs to a TRENDS traffic light - bool parseTRENDS(int id, const std::string& name, int lsaid, - std::istream& from); - - /// Parses a traffic light group which belongs to a VAStraffic light - bool parseVAP(int id, const std::string& name, int lsaid, - std::istream& from); - - /// Parses a traffic light group which belongs to a TL traffic light - bool parseTL(int id, const std::string& name, int lsaid, - std::istream& from); - - /// Parses a traffic light group which belongs to a POS traffic light - bool parsePOS(int id, const std::string& name, int lsaid, - std::istream& from); - - /// Parses a traffic light group which belongs fixed time traffic light with an extern definition - bool parseExternFixedTime(int id, const std::string& name, int lsaid, - std::istream& from); - -}; diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_SimRate.cpp b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_SimRate.cpp deleted file mode 100644 index 3fa5ab328..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_SimRate.cpp +++ /dev/null @@ -1,46 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_SimRate.cpp -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Wed, 30 Apr 2003 -/// -// -/****************************************************************************/ -#include - -#include -#include -#include "../NIImporter_Vissim.h" -#include "../tempstructs/NIVissimSource.h" -#include "NIVissimSingleTypeParser_SimRate.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -NIVissimSingleTypeParser_SimRate::NIVissimSingleTypeParser_SimRate(NIImporter_Vissim& parent) - : NIImporter_Vissim::VissimSingleTypeParser(parent) {} - - -NIVissimSingleTypeParser_SimRate::~NIVissimSingleTypeParser_SimRate() {} - - -bool -NIVissimSingleTypeParser_SimRate::parse(std::istream&) { - return true; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_SimRate.h b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_SimRate.h deleted file mode 100644 index f6548ba37..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_SimRate.h +++ /dev/null @@ -1,46 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_SimRate.h -/// @author Daniel Krajzewicz -/// @date Wed, 30 Apr 2003 -/// -// -/****************************************************************************/ -#pragma once -#include - -#include -#include "../NIImporter_Vissim.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NIVissimSingleTypeParser_SimRate - * - */ -class NIVissimSingleTypeParser_SimRate : - public NIImporter_Vissim::VissimSingleTypeParser { -public: - /// Constructor - NIVissimSingleTypeParser_SimRate(NIImporter_Vissim& parent); - - /// Destructor - ~NIVissimSingleTypeParser_SimRate(); - - /// Parses the data type from the given stream - bool parse(std::istream& from); - -}; diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Simdauer.cpp b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Simdauer.cpp deleted file mode 100644 index 3fc5661f6..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Simdauer.cpp +++ /dev/null @@ -1,56 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Simdauer.cpp -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date Wed, 18 Dec 2002 -/// -// -/****************************************************************************/ -#include - -#include -#include -#include -#include "../NIImporter_Vissim.h" -#include "NIVissimSingleTypeParser_Simdauer.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -NIVissimSingleTypeParser_Simdauer::NIVissimSingleTypeParser_Simdauer(NIImporter_Vissim& parent) - : NIImporter_Vissim::VissimSingleTypeParser(parent) {} - - -NIVissimSingleTypeParser_Simdauer::~NIVissimSingleTypeParser_Simdauer() {} - - -bool -NIVissimSingleTypeParser_Simdauer::parse(std::istream& from) { - std::string duration; - from >> duration; - // !!! - try { - StringUtils::toDouble(duration); - } catch (...) { - WRITE_ERROR("Simulation duration could not be parsed"); - return false; - } - return true; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Simdauer.h b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Simdauer.h deleted file mode 100644 index b579b51ab..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Simdauer.h +++ /dev/null @@ -1,46 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Simdauer.h -/// @author Daniel Krajzewicz -/// @date Wed, 18 Dec 2002 -/// -// -/****************************************************************************/ -#pragma once -#include - -#include -#include "../NIImporter_Vissim.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NIVissimSingleTypeParser_Simdauer - * - */ -class NIVissimSingleTypeParser_Simdauer : - public NIImporter_Vissim::VissimSingleTypeParser { -public: - /// Constructor - NIVissimSingleTypeParser_Simdauer(NIImporter_Vissim& parent); - - /// Destructor - ~NIVissimSingleTypeParser_Simdauer(); - - /// Parses the data type from the given stream - bool parse(std::istream& from); - -}; diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Startuhrzeit.cpp b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Startuhrzeit.cpp deleted file mode 100644 index e427a949a..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Startuhrzeit.cpp +++ /dev/null @@ -1,45 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Startuhrzeit.cpp -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Wed, 18 Dec 2002 -/// -// -/****************************************************************************/ -#include - -#include -#include -#include "../NIImporter_Vissim.h" -#include "NIVissimSingleTypeParser_Startuhrzeit.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -NIVissimSingleTypeParser_Startuhrzeit::NIVissimSingleTypeParser_Startuhrzeit(NIImporter_Vissim& parent) - : NIImporter_Vissim::VissimSingleTypeParser(parent) {} - - -NIVissimSingleTypeParser_Startuhrzeit::~NIVissimSingleTypeParser_Startuhrzeit() {} - - -bool -NIVissimSingleTypeParser_Startuhrzeit::parse(std::istream&) { - return true; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Startuhrzeit.h b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Startuhrzeit.h deleted file mode 100644 index 2e87c118d..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Startuhrzeit.h +++ /dev/null @@ -1,46 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Startuhrzeit.h -/// @author Daniel Krajzewicz -/// @date Wed, 18 Dec 2002 -/// -// -/****************************************************************************/ -#pragma once -#include - -#include -#include "../NIImporter_Vissim.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NIVissimSingleTypeParser_Startuhrzeit - * - */ -class NIVissimSingleTypeParser_Startuhrzeit : - public NIImporter_Vissim::VissimSingleTypeParser { -public: - /// Constructor - NIVissimSingleTypeParser_Startuhrzeit(NIImporter_Vissim& parent); - - /// Destructor - ~NIVissimSingleTypeParser_Startuhrzeit(); - - /// Parses the data type from the given stream - bool parse(std::istream& from); - -}; diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Startzufallszahl.cpp b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Startzufallszahl.cpp deleted file mode 100644 index 9bd141213..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Startzufallszahl.cpp +++ /dev/null @@ -1,46 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Startzufallszahl.cpp -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Wed, 30 Apr 2003 -/// -// -/****************************************************************************/ -#include - -#include -#include -#include "../NIImporter_Vissim.h" -#include "../tempstructs/NIVissimSource.h" -#include "NIVissimSingleTypeParser_Startzufallszahl.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -NIVissimSingleTypeParser_Startzufallszahl::NIVissimSingleTypeParser_Startzufallszahl(NIImporter_Vissim& parent) - : NIImporter_Vissim::VissimSingleTypeParser(parent) {} - - -NIVissimSingleTypeParser_Startzufallszahl::~NIVissimSingleTypeParser_Startzufallszahl() {} - - -bool -NIVissimSingleTypeParser_Startzufallszahl::parse(std::istream&) { - return true; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Startzufallszahl.h b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Startzufallszahl.h deleted file mode 100644 index 7eea6f6e0..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Startzufallszahl.h +++ /dev/null @@ -1,46 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Startzufallszahl.h -/// @author Daniel Krajzewicz -/// @date Wed, 30 Apr 2003 -/// -// -/****************************************************************************/ -#pragma once -#include - -#include -#include "../NIImporter_Vissim.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NIVissimSingleTypeParser_Startzufallszahl - * - */ -class NIVissimSingleTypeParser_Startzufallszahl : - public NIImporter_Vissim::VissimSingleTypeParser { -public: - /// Constructor - NIVissimSingleTypeParser_Startzufallszahl(NIImporter_Vissim& parent); - - /// Destructor - ~NIVissimSingleTypeParser_Startzufallszahl(); - - /// Parses the data type from the given stream - bool parse(std::istream& from); - -}; diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Stauparameterdefinition.cpp b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Stauparameterdefinition.cpp deleted file mode 100644 index 5368079f0..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Stauparameterdefinition.cpp +++ /dev/null @@ -1,46 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Stauparameterdefinition.cpp -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Wed, 30 Apr 2003 -/// -// -/****************************************************************************/ -#include - -#include -#include -#include "../NIImporter_Vissim.h" -#include "../tempstructs/NIVissimSource.h" -#include "NIVissimSingleTypeParser_Stauparameterdefinition.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -NIVissimSingleTypeParser_Stauparameterdefinition::NIVissimSingleTypeParser_Stauparameterdefinition(NIImporter_Vissim& parent) - : NIImporter_Vissim::VissimSingleTypeParser(parent) {} - - -NIVissimSingleTypeParser_Stauparameterdefinition::~NIVissimSingleTypeParser_Stauparameterdefinition() {} - - -bool -NIVissimSingleTypeParser_Stauparameterdefinition::parse(std::istream&) { - return true; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Stauparameterdefinition.h b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Stauparameterdefinition.h deleted file mode 100644 index fb3a947c9..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Stauparameterdefinition.h +++ /dev/null @@ -1,46 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Stauparameterdefinition.h -/// @author Daniel Krajzewicz -/// @date Wed, 30 Apr 2003 -/// -// -/****************************************************************************/ -#pragma once -#include - -#include -#include "../NIImporter_Vissim.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NIVissimSingleTypeParser_Stauparameterdefinition - * - */ -class NIVissimSingleTypeParser_Stauparameterdefinition : - public NIImporter_Vissim::VissimSingleTypeParser { -public: - /// Constructor - NIVissimSingleTypeParser_Stauparameterdefinition(NIImporter_Vissim& parent); - - /// Destructor - ~NIVissimSingleTypeParser_Stauparameterdefinition(); - - /// Parses the data type from the given stream - bool parse(std::istream& from); - -}; diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Stauzaehlerdefinition.cpp b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Stauzaehlerdefinition.cpp deleted file mode 100644 index b840dde72..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Stauzaehlerdefinition.cpp +++ /dev/null @@ -1,46 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Stauzaehlerdefinition.cpp -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Wed, 18 Dec 2002 -/// -// -/****************************************************************************/ -#include - -#include -#include -#include "../NIImporter_Vissim.h" -#include "../tempstructs/NIVissimClosures.h" -#include "NIVissimSingleTypeParser_Stauzaehlerdefinition.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -NIVissimSingleTypeParser_Stauzaehlerdefinition::NIVissimSingleTypeParser_Stauzaehlerdefinition(NIImporter_Vissim& parent) - : NIImporter_Vissim::VissimSingleTypeParser(parent) {} - - -NIVissimSingleTypeParser_Stauzaehlerdefinition::~NIVissimSingleTypeParser_Stauzaehlerdefinition() {} - - -bool -NIVissimSingleTypeParser_Stauzaehlerdefinition::parse(std::istream& from) { - return skipOverreading(from, "strecke"); -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Stauzaehlerdefinition.h b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Stauzaehlerdefinition.h deleted file mode 100644 index fc1d42a00..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Stauzaehlerdefinition.h +++ /dev/null @@ -1,46 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Stauzaehlerdefinition.h -/// @author Daniel Krajzewicz -/// @date Wed, 18 Dec 2002 -/// -// -/****************************************************************************/ -#pragma once -#include - -#include -#include "../NIImporter_Vissim.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NIVissimSingleTypeParser_Stauzaehlerdefinition - * - */ -class NIVissimSingleTypeParser_Stauzaehlerdefinition : - public NIImporter_Vissim::VissimSingleTypeParser { -public: - /// Constructor - NIVissimSingleTypeParser_Stauzaehlerdefinition(NIImporter_Vissim& parent); - - /// Destructor - ~NIVissimSingleTypeParser_Stauzaehlerdefinition(); - - /// Parses the data type from the given stream - bool parse(std::istream& from); - -}; diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Stopschilddefinition.cpp b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Stopschilddefinition.cpp deleted file mode 100644 index 5d1abe8ae..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Stopschilddefinition.cpp +++ /dev/null @@ -1,66 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Stopschilddefinition.cpp -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Wed, 18 Dec 2002 -/// -// -/****************************************************************************/ -#include - -#include -#include -#include "../NIImporter_Vissim.h" -#include "NIVissimSingleTypeParser_Stopschilddefinition.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -NIVissimSingleTypeParser_Stopschilddefinition::NIVissimSingleTypeParser_Stopschilddefinition(NIImporter_Vissim& parent) - : NIImporter_Vissim::VissimSingleTypeParser(parent) {} - - -NIVissimSingleTypeParser_Stopschilddefinition::~NIVissimSingleTypeParser_Stopschilddefinition() {} - - -bool -NIVissimSingleTypeParser_Stopschilddefinition::parse(std::istream& from) { - readUntil(from, "strecke"); - std::string tag; - from >> tag; // edge name - from >> tag; // "spur" - from >> tag; // lane no - from >> tag; // "bei" - from >> tag; // pos - from >> tag; - if (tag == "RTOR") { - from >> tag; // "lsa" - from >> tag; // lsa id - from >> tag; // "gruppe" - from >> tag; // gruppe id - } else { - while (tag == "fahrzeugklasse") { - from >> tag; // class no - from >> tag; // "zeiten" - from >> tag; // times no - tag = readEndSecure(from, "fahrzeugklasse"); - } - } - return true; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Stopschilddefinition.h b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Stopschilddefinition.h deleted file mode 100644 index f7b2ea63b..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Stopschilddefinition.h +++ /dev/null @@ -1,46 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Stopschilddefinition.h -/// @author Daniel Krajzewicz -/// @date Wed, 18 Dec 2002 -/// -// -/****************************************************************************/ -#pragma once -#include - -#include -#include "../NIImporter_Vissim.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NIVissimSingleTypeParser_Stopschilddefinition - * - */ -class NIVissimSingleTypeParser_Stopschilddefinition : - public NIImporter_Vissim::VissimSingleTypeParser { -public: - /// Constructor - NIVissimSingleTypeParser_Stopschilddefinition(NIImporter_Vissim& parent); - - /// Destructor - ~NIVissimSingleTypeParser_Stopschilddefinition(); - - /// Parses the data type from the given stream - bool parse(std::istream& from); - -}; diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Streckendefinition.cpp b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Streckendefinition.cpp deleted file mode 100644 index 09254a41c..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Streckendefinition.cpp +++ /dev/null @@ -1,133 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Streckendefinition.cpp -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Wed, 18 Dec 2002 -/// -// -/****************************************************************************/ -#include - -#include -#include -#include -#include -#include "../NIImporter_Vissim.h" -#include "../tempstructs/NIVissimEdge.h" -#include "../tempstructs/NIVissimClosedLaneDef.h" -#include "../tempstructs/NIVissimClosedLanesVector.h" -#include "NIVissimSingleTypeParser_Streckendefinition.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -NIVissimSingleTypeParser_Streckendefinition::NIVissimSingleTypeParser_Streckendefinition(NIImporter_Vissim& parent) - : NIImporter_Vissim::VissimSingleTypeParser(parent) {} - - -NIVissimSingleTypeParser_Streckendefinition::~NIVissimSingleTypeParser_Streckendefinition() {} - - -bool -NIVissimSingleTypeParser_Streckendefinition::parse(std::istream& from) { - // read in the id - int id; - from >> id; - // - std::string tag; - // the following elements may occure: "Name", "Beschriftung", "Typ", - // followed by the mandatory "Laenge" - std::string name, label, type; - double length = -1; - while (length < 0) { - tag = overrideOptionalLabel(from); - if (tag == "name") { - name = readName(from); - } else if (tag == "typ") { - type = myRead(from); - } else if (tag == "laenge") { - from >> length; // type-checking is missing! - } - } - // read in the number of lanes - int noLanes; - tag = myRead(from); - from >> noLanes; - // skip some parameter, except optional "Zuschlag" until "Von" (mandatory) - // occurs - double zuschlag1, zuschlag2; - zuschlag1 = zuschlag2 = 0; - while (tag != "von") { - tag = myRead(from); - if (tag == "zuschlag") { - from >> zuschlag1; // type-checking is missing! - tag = myRead(from); - if (tag == "zuschlag") { - from >> zuschlag2; // type-checking is missing! - } - } - } - // Read the geometry information - PositionVector geom; - while (tag != "nach") { - geom.push_back_noDoublePos(getPosition(from)); - tag = myRead(from); - try { - StringUtils::toDouble(tag); - tag = myRead(from); - } catch (NumberFormatException&) {} - } - geom.push_back_noDoublePos(getPosition(from)); - // Read definitions of closed lanes - NIVissimClosedLanesVector clv; - // check whether a next close lane definition can be found - tag = readEndSecure(from); - while (tag != "DATAEND") { - if (tag == "keinspurwechsel") { - while (tag != "DATAEND") { - tag = readEndSecure(from); - } - } else if (tag == "spur") { - // get the lane number - int laneNo; - from >> laneNo; // unused and type-checking is missing! - // get the list of assigned car classes - std::vector assignedVehicles; - tag = myRead(from); - tag = myRead(from); - while (tag != "DATAEND" && tag != "spur" && tag != "keinspurwechsel") { - int classes = StringUtils::toInt(tag); - assignedVehicles.push_back(classes); - tag = readEndSecure(from); - } - // build and add the definition - NIVissimClosedLaneDef* cld = new NIVissimClosedLaneDef(assignedVehicles); - clv.push_back(cld); - } else { - tag = readEndSecure(from); - } - } - NIVissimEdge* e = new NIVissimEdge(id, name, type, std::vector(noLanes, NBEdge::UNSPECIFIED_WIDTH), - zuschlag1, zuschlag2, length, geom, clv); - if (!NIVissimEdge::dictionary(id, e)) { - return false; - } - return true; - //return NIVissimAbstractEdge::dictionary(id, e); -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Streckendefinition.h b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Streckendefinition.h deleted file mode 100644 index 21b86217a..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Streckendefinition.h +++ /dev/null @@ -1,46 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Streckendefinition.h -/// @author Daniel Krajzewicz -/// @date Wed, 18 Dec 2002 -/// -// -/****************************************************************************/ -#pragma once -#include - -#include -#include "../NIImporter_Vissim.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NIVissimSingleTypeParser_Streckendefinition - * - */ -class NIVissimSingleTypeParser_Streckendefinition : - public NIImporter_Vissim::VissimSingleTypeParser { -public: - /// Constructor - NIVissimSingleTypeParser_Streckendefinition(NIImporter_Vissim& parent); - - /// Destructor - ~NIVissimSingleTypeParser_Streckendefinition(); - - /// Parses the data type from the given stream - bool parse(std::istream& from); - -}; diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Streckentypdefinition.cpp b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Streckentypdefinition.cpp deleted file mode 100644 index a047cc47b..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Streckentypdefinition.cpp +++ /dev/null @@ -1,48 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Streckentypdefinition.cpp -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Thu, 6 Mar 2003 -/// -// -/****************************************************************************/ -#include - -#include -#include -#include "../NIImporter_Vissim.h" -#include "NIVissimSingleTypeParser_Streckentypdefinition.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -NIVissimSingleTypeParser_Streckentypdefinition::NIVissimSingleTypeParser_Streckentypdefinition(NIImporter_Vissim& parent) - : NIImporter_Vissim::VissimSingleTypeParser(parent) {} - - -NIVissimSingleTypeParser_Streckentypdefinition::~NIVissimSingleTypeParser_Streckentypdefinition() {} - - -bool -NIVissimSingleTypeParser_Streckentypdefinition::parse(std::istream& from) { - readUntil(from, "default"); - std::string tag; - from >> tag; - return true; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Streckentypdefinition.h b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Streckentypdefinition.h deleted file mode 100644 index 57ebd7637..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Streckentypdefinition.h +++ /dev/null @@ -1,46 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Streckentypdefinition.h -/// @author Daniel Krajzewicz -/// @date Thu, 6 Mar 2003 -/// -// -/****************************************************************************/ -#pragma once -#include - -#include -#include "../NIImporter_Vissim.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NIVissimSingleTypeParser_Streckentypdefinition - * - */ -class NIVissimSingleTypeParser_Streckentypdefinition : - public NIImporter_Vissim::VissimSingleTypeParser { -public: - /// Constructor - NIVissimSingleTypeParser_Streckentypdefinition(NIImporter_Vissim& parent); - - /// Destructor - ~NIVissimSingleTypeParser_Streckentypdefinition(); - - /// Parses the data type from the given stream - bool parse(std::istream& from); - -}; diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_TEAPACDefinition.cpp b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_TEAPACDefinition.cpp deleted file mode 100644 index 4e70b3911..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_TEAPACDefinition.cpp +++ /dev/null @@ -1,46 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_TEAPACDefinition.cpp -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Wed, 30 Apr 2003 -/// -// -/****************************************************************************/ -#include - -#include -#include -#include "../NIImporter_Vissim.h" -#include "../tempstructs/NIVissimSource.h" -#include "NIVissimSingleTypeParser_TEAPACDefinition.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -NIVissimSingleTypeParser_TEAPACDefinition::NIVissimSingleTypeParser_TEAPACDefinition(NIImporter_Vissim& parent) - : NIImporter_Vissim::VissimSingleTypeParser(parent) {} - - -NIVissimSingleTypeParser_TEAPACDefinition::~NIVissimSingleTypeParser_TEAPACDefinition() {} - - -bool -NIVissimSingleTypeParser_TEAPACDefinition::parse(std::istream&) { - return true; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_TEAPACDefinition.h b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_TEAPACDefinition.h deleted file mode 100644 index 500ab2e46..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_TEAPACDefinition.h +++ /dev/null @@ -1,46 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_TEAPACDefinition.h -/// @author Daniel Krajzewicz -/// @date Wed, 30 Apr 2003 -/// -// -/****************************************************************************/ -#pragma once -#include - -#include -#include "../NIImporter_Vissim.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NIVissimSingleTypeParser_TEAPACDefinition - * - */ -class NIVissimSingleTypeParser_TEAPACDefinition : - public NIImporter_Vissim::VissimSingleTypeParser { -public: - /// Constructor - NIVissimSingleTypeParser_TEAPACDefinition(NIImporter_Vissim& parent); - - /// Destructor - ~NIVissimSingleTypeParser_TEAPACDefinition(); - - /// Parses the data type from the given stream - bool parse(std::istream& from); - -}; diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_VWunschentscheidungsdefinition.cpp b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_VWunschentscheidungsdefinition.cpp deleted file mode 100644 index 67ee63024..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_VWunschentscheidungsdefinition.cpp +++ /dev/null @@ -1,99 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_VWunschentscheidungsdefinition.cpp -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Wed, 18 Dec 2002 -/// -// -/****************************************************************************/ -#include - -#include -#include -#include -#include -#include "../NIImporter_Vissim.h" -#include "../tempstructs/NIVissimEdge.h" -#include "../tempstructs/NIVissimConnection.h" -#include "NIVissimSingleTypeParser_VWunschentscheidungsdefinition.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -NIVissimSingleTypeParser_VWunschentscheidungsdefinition::NIVissimSingleTypeParser_VWunschentscheidungsdefinition(NIImporter_Vissim& parent) - : NIImporter_Vissim::VissimSingleTypeParser(parent) {} - - -NIVissimSingleTypeParser_VWunschentscheidungsdefinition::~NIVissimSingleTypeParser_VWunschentscheidungsdefinition() {} - - -bool -NIVissimSingleTypeParser_VWunschentscheidungsdefinition::parse(std::istream& from) { - std::string tag; - from >> tag; // id - from >> tag; // name - tag = readName(from); - tag = overrideOptionalLabel(from); - from >> tag; // strecke - std::string edgeid; - from >> edgeid; - from >> tag; // spur - std::string lane; - from >> lane; - from >> tag; // bei - std::string pos; - from >> pos; - from >> tag; // fahrzeugklasse - from >> tag; // - from >> tag; // vwunsch - std::string vwunsch; - from >> vwunsch; // vwunsch - std::vector tmp; - tmp.push_back("zeit"); - tmp.push_back("fahrzeugklasse"); - tag = readEndSecure(from, tmp); - while (tag != "DATAEND" && tag != "zeit") { - from >> tag; - from >> tag; - from >> tag; - tag = myRead(from); - } - if (tag == "zeit") { - from >> tag; - from >> tag; - from >> tag; - from >> tag; - } - int numid = StringUtils::toInt(edgeid); - int numlane = StringUtils::toInt(lane) - 1; - int numv = StringUtils::toInt(vwunsch); - NIVissimEdge* e = NIVissimEdge::dictionary(numid); - if (e == nullptr) { - NIVissimConnection* c = NIVissimConnection::dictionary(numid); - const std::vector& lanes = c->getToLanes(); - e = NIVissimEdge::dictionary(c->getToEdgeID()); - for (std::vector::const_iterator j = lanes.begin(); j != lanes.end(); j++) { - e->setSpeed((*j), numv); - } - assert(e != 0); - } else { - e->setSpeed(numlane, numv); - } - return true; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_VWunschentscheidungsdefinition.h b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_VWunschentscheidungsdefinition.h deleted file mode 100644 index 5c666e67a..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_VWunschentscheidungsdefinition.h +++ /dev/null @@ -1,46 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_VWunschentscheidungsdefinition.h -/// @author Daniel Krajzewicz -/// @date Wed, 18 Dec 2002 -/// -// -/****************************************************************************/ -#pragma once -#include - -#include -#include "../NIImporter_Vissim.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NIVissimSingleTypeParser_VWunschentscheidungsdefinition - * - */ -class NIVissimSingleTypeParser_VWunschentscheidungsdefinition : - public NIImporter_Vissim::VissimSingleTypeParser { -public: - /// Constructor - NIVissimSingleTypeParser_VWunschentscheidungsdefinition(NIImporter_Vissim& parent); - - /// Destructor - ~NIVissimSingleTypeParser_VWunschentscheidungsdefinition(); - - /// Parses the data type from the given stream - bool parse(std::istream& from); - -}; diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Verbindungsdefinition.cpp b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Verbindungsdefinition.cpp deleted file mode 100644 index a5e149038..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Verbindungsdefinition.cpp +++ /dev/null @@ -1,164 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Verbindungsdefinition.cpp -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Wed, 18 Dec 2002 -/// -// -/****************************************************************************/ -#include - -#include -#include -#include -#include "../NIImporter_Vissim.h" -#include "../tempstructs/NIVissimConnection.h" -#include "NIVissimSingleTypeParser_Verbindungsdefinition.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -NIVissimSingleTypeParser_Verbindungsdefinition::NIVissimSingleTypeParser_Verbindungsdefinition(NIImporter_Vissim& parent) - : NIImporter_Vissim::VissimSingleTypeParser(parent) {} - - -NIVissimSingleTypeParser_Verbindungsdefinition::~NIVissimSingleTypeParser_Verbindungsdefinition() {} - - -bool -NIVissimSingleTypeParser_Verbindungsdefinition::parse(std::istream& from) { - int id; - from >> id; // type-checking is missing! - std::string tag; - // Read optional value "Name", skip optional value "Beschriftung" - std::string name; - while (tag != "von") { - tag = overrideOptionalLabel(from); - if (tag == "name") { - name = readName(from); - } - } - // Read the geometry information - NIVissimExtendedEdgePoint from_def = readExtEdgePointDef(from); - PositionVector geom; - tag = myRead(from); // "ueber" - while (tag != "nach") { - std::string x = myRead(from); - std::string y = myRead(from); - if (y != "nach") { - geom.push_back_noDoublePos( - Position( - StringUtils::toDouble(x), - StringUtils::toDouble(y) - )); - tag = myRead(from); - try { - StringUtils::toDouble(tag); - tag = myRead(from); - } catch (NumberFormatException&) {} - } else { - tag = y; - } - } - NIVissimExtendedEdgePoint to_def = readExtEdgePointDef(from); - // read some optional values until mandatory "Fahrzeugklassen" occurs - double dxnothalt = 0; - double dxeinordnen = 0; - double zuschlag1, zuschlag2; - zuschlag1 = zuschlag2 = 0; - double seglength = 0; - tag = myRead(from); -// NIVissimConnection::Direction direction = NIVissimConnection::NIVC_DIR_ALL; - while (tag != "fahrzeugklassen" && tag != "sperrung" && tag != "auswertung" && tag != "DATAEND") { - if (tag == "rechts") { -// direction = NIVissimConnection::NIVC_DIR_RIGHT; - } else if (tag == "links") { -// direction = NIVissimConnection::NIVC_DIR_LEFT; - } else if (tag == "alle") { -// direction = NIVissimConnection::NIVC_DIR_ALL; - } else if (tag == "dxnothalt") { - from >> dxnothalt; // type-checking is missing! - } else if (tag == "dxeinordnen") { - from >> dxeinordnen; // type-checking is missing! - } else if (tag == "segment") { - from >> tag; - from >> seglength; - } - if (tag == "zuschlag") { - from >> zuschlag1; // type-checking is missing! - tag = readEndSecure(from); - if (tag == "zuschlag") { - from >> zuschlag2; // type-checking is missing! - tag = readEndSecure(from, "auswertung"); - } - } else { - tag = readEndSecure(from, "auswertung"); - } - } - // read in allowed vehicle classes - std::vector assignedVehicles; - if (tag == "fahrzeugklassen") { - tag = readEndSecure(from); - while (tag != "DATAEND" && tag != "sperrung" && tag != "auswertung") { - int classes = StringUtils::toInt(tag); - assignedVehicles.push_back(classes); - tag = readEndSecure(from, "auswertung"); - } - } - // Read definitions of closed lanes - NIVissimClosedLanesVector clv; - if (tag != "DATAEND") { - do { - // check whether a next close lane definition can be found - tag = readEndSecure(from); - if (tag == "keinspurwechsel") { - while (tag != "DATAEND") { - tag = readEndSecure(from); - } - } else if (tag == "spur") { - // get the lane number -// from >> tag; - int laneNo; - from >> laneNo; // unused and type-checking is missing! - // get the list of assigned car classes - std::vector assignedVehicles; - tag = myRead(from); - if (tag == "fahrzeugklassen") { - tag = myRead(from); - } - while (tag != "DATAEND" && tag != "spur" && tag != "keinspurwechsel") { - int classes = StringUtils::toInt(tag); - assignedVehicles.push_back(classes); - tag = readEndSecure(from); - } - // build and add the definition - NIVissimClosedLaneDef* cld = new NIVissimClosedLaneDef(assignedVehicles); - clv.push_back(cld); - } - } while (tag != "DATAEND"); - } - NIVissimConnection* c = new NIVissimConnection(id, name, from_def, to_def, geom, - assignedVehicles, clv); - - if (!NIVissimConnection::dictionary(id, c)) { - return false; - } - return true; - //return NIVissimAbstractEdge::dictionary(id, c); -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Verbindungsdefinition.h b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Verbindungsdefinition.h deleted file mode 100644 index 3e2a3f789..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Verbindungsdefinition.h +++ /dev/null @@ -1,47 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Verbindungsdefinition.h -/// @author Daniel Krajzewicz -/// @date Wed, 18 Dec 2002 -/// -// -/****************************************************************************/ -#pragma once -#include - -#include -#include "../NIImporter_Vissim.h" -#include "../tempstructs/NIVissimExtendedEdgePoint.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NIVissimSingleTypeParser_Verbindungsdefinition - * - */ -class NIVissimSingleTypeParser_Verbindungsdefinition : - public NIImporter_Vissim::VissimSingleTypeParser { -public: - /// Constructor - NIVissimSingleTypeParser_Verbindungsdefinition(NIImporter_Vissim& parent); - - /// Destructor - ~NIVissimSingleTypeParser_Verbindungsdefinition(); - - /// Parses the data type from the given stream - bool parse(std::istream& from); - -}; diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Verkehrszusammensetzungsdefinition.cpp b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Verkehrszusammensetzungsdefinition.cpp deleted file mode 100644 index 722f81f81..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Verkehrszusammensetzungsdefinition.cpp +++ /dev/null @@ -1,75 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Verkehrszusammensetzungsdefinition.cpp -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Wed, 18 Dec 2002 -/// -// -/****************************************************************************/ -#include - -#include -#include -#include "../NIImporter_Vissim.h" -#include "../tempstructs/NIVissimVehicleClass.h" -#include "../tempstructs/NIVissimVehicleClassVector.h" -#include "../tempstructs/NIVissimTrafficDescription.h" -#include "NIVissimSingleTypeParser_Verkehrszusammensetzungsdefinition.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -NIVissimSingleTypeParser_Verkehrszusammensetzungsdefinition::NIVissimSingleTypeParser_Verkehrszusammensetzungsdefinition(NIImporter_Vissim& parent) - : NIImporter_Vissim::VissimSingleTypeParser(parent) {} - - -NIVissimSingleTypeParser_Verkehrszusammensetzungsdefinition::~NIVissimSingleTypeParser_Verkehrszusammensetzungsdefinition() {} - - -bool -NIVissimSingleTypeParser_Verkehrszusammensetzungsdefinition::parse(std::istream& from) { - // id - int id; - from >> id; // type-checking is missing! - // name - std::string tag; - from >> tag; - std::string name = readName(from); - // assigned vehicle classes - tag = myRead(from); - if (tag == "temperatur") { - tag = myRead(from); - tag = myRead(from); - } - NIVissimVehicleClassVector assignedTypes; - while (tag != "DATAEND") { - int type; - from >> type; - double percentage; - from >> tag; - from >> percentage; - int vwish; - from >> tag; - from >> vwish; - assignedTypes.push_back(new NIVissimVehicleClass(vwish)); - tag = readEndSecure(from, "Fahrzeugtyp"); - } - // - return NIVissimTrafficDescription::dictionary(id, name, assignedTypes); -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Verkehrszusammensetzungsdefinition.h b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Verkehrszusammensetzungsdefinition.h deleted file mode 100644 index 41c6d827a..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Verkehrszusammensetzungsdefinition.h +++ /dev/null @@ -1,46 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Verkehrszusammensetzungsdefinition.h -/// @author Daniel Krajzewicz -/// @date Wed, 18 Dec 2002 -/// -// -/****************************************************************************/ -#pragma once -#include - -#include -#include "../NIImporter_Vissim.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NIVissimSingleTypeParser_Verkehrszusammensetzungsdefinition - * - */ -class NIVissimSingleTypeParser_Verkehrszusammensetzungsdefinition : - public NIImporter_Vissim::VissimSingleTypeParser { -public: - /// Constructor - NIVissimSingleTypeParser_Verkehrszusammensetzungsdefinition(NIImporter_Vissim& parent); - - /// Destructor - ~NIVissimSingleTypeParser_Verkehrszusammensetzungsdefinition(); - - /// Parses the data type from the given stream - bool parse(std::istream& from); - -}; diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Verlustzeitmessungsdefinition.cpp b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Verlustzeitmessungsdefinition.cpp deleted file mode 100644 index b09d8c7e0..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Verlustzeitmessungsdefinition.cpp +++ /dev/null @@ -1,60 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Verlustzeitmessungsdefinition.cpp -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Wed, 18 Dec 2002 -/// -// -/****************************************************************************/ -#include - -#include -#include -#include "../NIImporter_Vissim.h" -#include "../tempstructs/NIVissimClosures.h" -#include "NIVissimSingleTypeParser_Verlustzeitmessungsdefinition.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -NIVissimSingleTypeParser_Verlustzeitmessungsdefinition::NIVissimSingleTypeParser_Verlustzeitmessungsdefinition(NIImporter_Vissim& parent) - : NIImporter_Vissim::VissimSingleTypeParser(parent) {} - - -NIVissimSingleTypeParser_Verlustzeitmessungsdefinition::~NIVissimSingleTypeParser_Verlustzeitmessungsdefinition() {} - - -bool -NIVissimSingleTypeParser_Verlustzeitmessungsdefinition::parse(std::istream& from) { - std::string tag = myRead(from); - if (tag == "von") { - while (tag != "DATAEND") { - tag = readEndSecure(from); - } - return true; - } - - while (tag != "fahrzeugklassen") { - tag = myRead(from); - } - while (tag != "DATAEND") { - tag = readEndSecure(from); - } - return true; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Verlustzeitmessungsdefinition.h b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Verlustzeitmessungsdefinition.h deleted file mode 100644 index e40bdce4a..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Verlustzeitmessungsdefinition.h +++ /dev/null @@ -1,46 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Verlustzeitmessungsdefinition.h -/// @author Daniel Krajzewicz -/// @date Wed, 18 Dec 2002 -/// -// -/****************************************************************************/ -#pragma once -#include - -#include -#include "../NIImporter_Vissim.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NIVissimSingleTypeParser_Verlustzeitmessungsdefinition - * - */ -class NIVissimSingleTypeParser_Verlustzeitmessungsdefinition : - public NIImporter_Vissim::VissimSingleTypeParser { -public: - /// Constructor - NIVissimSingleTypeParser_Verlustzeitmessungsdefinition(NIImporter_Vissim& parent); - - /// Destructor - ~NIVissimSingleTypeParser_Verlustzeitmessungsdefinition(); - - /// Parses the data type from the given stream - bool parse(std::istream& from); - -}; diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Zeitenverteilungsdefinition.cpp b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Zeitenverteilungsdefinition.cpp deleted file mode 100644 index 7e735989a..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Zeitenverteilungsdefinition.cpp +++ /dev/null @@ -1,74 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Zeitenverteilungsdefinition.cpp -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Wed, 18 Dec 2002 -/// -// -/****************************************************************************/ -#include - -#include -#include -#include -#include -#include "../NIImporter_Vissim.h" -#include -#include -#include -#include "NIVissimSingleTypeParser_Zeitenverteilungsdefinition.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -NIVissimSingleTypeParser_Zeitenverteilungsdefinition::NIVissimSingleTypeParser_Zeitenverteilungsdefinition(NIImporter_Vissim& parent) - : NIImporter_Vissim::VissimSingleTypeParser(parent) {} - - -NIVissimSingleTypeParser_Zeitenverteilungsdefinition::~NIVissimSingleTypeParser_Zeitenverteilungsdefinition() {} - - -bool -NIVissimSingleTypeParser_Zeitenverteilungsdefinition::parse(std::istream& from) { - // id - std::string id; - from >> id; - // list of points - Distribution_Points* points = new Distribution_Points(id); - std::string tag; - do { - tag = readEndSecure(from); - if (tag == "mittelwert") { - double mean, deviation; - from >> mean; - from >> tag; - from >> deviation; - delete points; - return DistributionCont::dictionary("times", id, - new Distribution_Parameterized(id, mean, deviation)); - } - if (tag != "DATAEND") { - double p1 = StringUtils::toDouble(tag); - from >> tag; - double p2 = StringUtils::toDouble(tag); - points->add(p1, p2); - } - } while (tag != "DATAEND"); - return DistributionCont::dictionary("times", id, points); -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Zeitenverteilungsdefinition.h b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Zeitenverteilungsdefinition.h deleted file mode 100644 index f2598c9bd..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Zeitenverteilungsdefinition.h +++ /dev/null @@ -1,46 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Zeitenverteilungsdefinition.h -/// @author Daniel Krajzewicz -/// @date Wed, 18 Dec 2002 -/// -// -/****************************************************************************/ -#pragma once -#include - -#include -#include "../NIImporter_Vissim.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NIVissimSingleTypeParser_Zeitenverteilungsdefinition - * - */ -class NIVissimSingleTypeParser_Zeitenverteilungsdefinition : - public NIImporter_Vissim::VissimSingleTypeParser { -public: - /// Constructor - NIVissimSingleTypeParser_Zeitenverteilungsdefinition(NIImporter_Vissim& parent); - - /// Destructor - ~NIVissimSingleTypeParser_Zeitenverteilungsdefinition(); - - /// Parses the data type from the given stream - bool parse(std::istream& from); - -}; diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Zeitschrittfaktor.cpp b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Zeitschrittfaktor.cpp deleted file mode 100644 index 21f79bf00..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Zeitschrittfaktor.cpp +++ /dev/null @@ -1,46 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Zeitschrittfaktor.cpp -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Wed, 30 Apr 2003 -/// -// -/****************************************************************************/ -#include - -#include -#include -#include "../NIImporter_Vissim.h" -#include "../tempstructs/NIVissimSource.h" -#include "NIVissimSingleTypeParser_Zeitschrittfaktor.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -NIVissimSingleTypeParser_Zeitschrittfaktor::NIVissimSingleTypeParser_Zeitschrittfaktor(NIImporter_Vissim& parent) - : NIImporter_Vissim::VissimSingleTypeParser(parent) {} - - -NIVissimSingleTypeParser_Zeitschrittfaktor::~NIVissimSingleTypeParser_Zeitschrittfaktor() {} - - -bool -NIVissimSingleTypeParser_Zeitschrittfaktor::parse(std::istream&) { - return true; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Zeitschrittfaktor.h b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Zeitschrittfaktor.h deleted file mode 100644 index 74255a327..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Zeitschrittfaktor.h +++ /dev/null @@ -1,46 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Zeitschrittfaktor.h -/// @author Daniel Krajzewicz -/// @date Wed, 30 Apr 2003 -/// -// -/****************************************************************************/ -#pragma once -#include - -#include -#include "../NIImporter_Vissim.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NIVissimSingleTypeParser_Zeitschrittfaktor - * - */ -class NIVissimSingleTypeParser_Zeitschrittfaktor : - public NIImporter_Vissim::VissimSingleTypeParser { -public: - /// Constructor - NIVissimSingleTypeParser_Zeitschrittfaktor(NIImporter_Vissim& parent); - - /// Destructor - ~NIVissimSingleTypeParser_Zeitschrittfaktor(); - - /// Parses the data type from the given stream - bool parse(std::istream& from); - -}; diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Zuflussdefinition.cpp b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Zuflussdefinition.cpp deleted file mode 100644 index 8321ba4c4..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Zuflussdefinition.cpp +++ /dev/null @@ -1,81 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Zuflussdefinition.cpp -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Wed, 18 Dec 2002 -/// -// -/****************************************************************************/ -#include - -#include -#include -#include "../NIImporter_Vissim.h" -#include "../tempstructs/NIVissimSource.h" -#include "NIVissimSingleTypeParser_Zuflussdefinition.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -NIVissimSingleTypeParser_Zuflussdefinition::NIVissimSingleTypeParser_Zuflussdefinition(NIImporter_Vissim& parent) - : NIImporter_Vissim::VissimSingleTypeParser(parent) {} - - -NIVissimSingleTypeParser_Zuflussdefinition::~NIVissimSingleTypeParser_Zuflussdefinition() {} - - -bool -NIVissimSingleTypeParser_Zuflussdefinition::parse(std::istream& from) { - std::string id, edgeid; - from >> id; // type-checking is missing! - std::string tag, name; - // override some optional values till q - while (tag != "q") { - tag = overrideOptionalLabel(from); - if (tag == "name") { - name = readName(from); - } else if (tag == "strecke") { - from >> edgeid; // type-checking is missing! - } - } - // read q - // bool exact = false; - tag = myRead(from); - if (tag == "exakt") { - // exact = true; - tag = myRead(from); - } - // double q = StringUtils::toDouble(tag); - // read the vehicle types - from >> tag; - int vehicle_combination; - from >> vehicle_combination; - // check whether optional time information is available - tag = readEndSecure(from); - double beg, end; - beg = -1; - end = -1; - if (tag == "zeit") { - from >> tag; - from >> beg; - from >> tag; - from >> end; - } - return NIVissimSource::dictionary(id, name, edgeid); -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Zuflussdefinition.h b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Zuflussdefinition.h deleted file mode 100644 index 79500a074..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Zuflussdefinition.h +++ /dev/null @@ -1,46 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Zuflussdefinition.h -/// @author Daniel Krajzewicz -/// @date Wed, 18 Dec 2002 -/// -// -/****************************************************************************/ -#pragma once -#include - -#include -#include "../NIImporter_Vissim.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NIVissimSingleTypeParser_Zuflussdefinition - * - */ -class NIVissimSingleTypeParser_Zuflussdefinition : - public NIImporter_Vissim::VissimSingleTypeParser { -public: - /// Constructor - NIVissimSingleTypeParser_Zuflussdefinition(NIImporter_Vissim& parent); - - /// Destructor - ~NIVissimSingleTypeParser_Zuflussdefinition(); - - /// Parses the data type from the given stream - bool parse(std::istream& from); - -}; diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Zusammensetzungsdefinition.cpp b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Zusammensetzungsdefinition.cpp deleted file mode 100644 index d2fc57faa..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Zusammensetzungsdefinition.cpp +++ /dev/null @@ -1,58 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Zusammensetzungsdefinition.cpp -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Wed, 18 Dec 2002 -/// -// -/****************************************************************************/ -#include - -#include -#include -#include "../NIImporter_Vissim.h" -#include "../tempstructs/NIVissimSource.h" -#include "NIVissimSingleTypeParser_Zusammensetzungsdefinition.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -NIVissimSingleTypeParser_Zusammensetzungsdefinition::NIVissimSingleTypeParser_Zusammensetzungsdefinition(NIImporter_Vissim& parent) - : NIImporter_Vissim::VissimSingleTypeParser(parent) {} - - -NIVissimSingleTypeParser_Zusammensetzungsdefinition::~NIVissimSingleTypeParser_Zusammensetzungsdefinition() {} - - -bool -NIVissimSingleTypeParser_Zusammensetzungsdefinition::parse(std::istream& from) { - std::string tag = myRead(from); - while (tag != "fahrzeugtyp") { - tag = readEndSecure(from, "fahrzeugtyp"); - } - do { - tag = myRead(from); // id - tag = myRead(from); // "anteil" - tag = myRead(from); // value - tag = myRead(from); // "VWunsch" - tag = myRead(from); // value - tag = readEndSecure(from, "fahrzeugtyp"); // "fahrzeugtyp"? - } while (tag == "fahrzeugtyp"); - return true; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Zusammensetzungsdefinition.h b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Zusammensetzungsdefinition.h deleted file mode 100644 index 2c917798e..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Zusammensetzungsdefinition.h +++ /dev/null @@ -1,46 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser_Zusammensetzungsdefinition.h -/// @author Daniel Krajzewicz -/// @date Wed, 18 Dec 2002 -/// -// -/****************************************************************************/ -#pragma once -#include - -#include -#include "../NIImporter_Vissim.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NIVissimSingleTypeParser_Zusammensetzungsdefinition - * - */ -class NIVissimSingleTypeParser_Zusammensetzungsdefinition : - public NIImporter_Vissim::VissimSingleTypeParser { -public: - /// Constructor - NIVissimSingleTypeParser_Zusammensetzungsdefinition(NIImporter_Vissim& parent); - - /// Destructor - ~NIVissimSingleTypeParser_Zusammensetzungsdefinition(); - - /// Parses the data type from the given stream - bool parse(std::istream& from); - -}; diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser__XKurvedefinition.cpp b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser__XKurvedefinition.cpp deleted file mode 100644 index 25f85f886..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser__XKurvedefinition.cpp +++ /dev/null @@ -1,46 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser__XKurvedefinition.cpp -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Wed, 30 Apr 2003 -/// -// -/****************************************************************************/ -#include - -#include -#include -#include "../NIImporter_Vissim.h" -#include "../tempstructs/NIVissimSource.h" -#include "NIVissimSingleTypeParser__XKurvedefinition.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -NIVissimSingleTypeParser__XKurvedefinition::NIVissimSingleTypeParser__XKurvedefinition(NIImporter_Vissim& parent) - : NIImporter_Vissim::VissimSingleTypeParser(parent) {} - - -NIVissimSingleTypeParser__XKurvedefinition::~NIVissimSingleTypeParser__XKurvedefinition() {} - - -bool -NIVissimSingleTypeParser__XKurvedefinition::parse(std::istream&) { - return true; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser__XKurvedefinition.h b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser__XKurvedefinition.h deleted file mode 100644 index b0e070407..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser__XKurvedefinition.h +++ /dev/null @@ -1,46 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser__XKurvedefinition.h -/// @author Daniel Krajzewicz -/// @date Wed, 30 Apr 2003 -/// -// -/****************************************************************************/ -#pragma once -#include - -#include -#include "../NIImporter_Vissim.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NIVissimSingleTypeParser__XKurvedefinition - * - */ -class NIVissimSingleTypeParser__XKurvedefinition : - public NIImporter_Vissim::VissimSingleTypeParser { -public: - /// Constructor - NIVissimSingleTypeParser__XKurvedefinition(NIImporter_Vissim& parent); - - /// Destructor - ~NIVissimSingleTypeParser__XKurvedefinition(); - - /// Parses the data type from the given stream - bool parse(std::istream& from); - -}; diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser__XVerteilungsdefinition.cpp b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser__XVerteilungsdefinition.cpp deleted file mode 100644 index a6e8e18ba..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser__XVerteilungsdefinition.cpp +++ /dev/null @@ -1,46 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser__XVerteilungsdefinition.cpp -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Wed, 30 Apr 2003 -/// -// -/****************************************************************************/ -#include - -#include -#include -#include "../NIImporter_Vissim.h" -#include "../tempstructs/NIVissimSource.h" -#include "NIVissimSingleTypeParser__XVerteilungsdefinition.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -NIVissimSingleTypeParser__XVerteilungsdefinition::NIVissimSingleTypeParser__XVerteilungsdefinition(NIImporter_Vissim& parent) - : NIImporter_Vissim::VissimSingleTypeParser(parent) {} - - -NIVissimSingleTypeParser__XVerteilungsdefinition::~NIVissimSingleTypeParser__XVerteilungsdefinition() {} - - -bool -NIVissimSingleTypeParser__XVerteilungsdefinition::parse(std::istream&) { - return true; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser__XVerteilungsdefinition.h b/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser__XVerteilungsdefinition.h deleted file mode 100644 index afc3d0362..000000000 --- a/Util/OSM2ODR/src/netimport/vissim/typeloader/NIVissimSingleTypeParser__XVerteilungsdefinition.h +++ /dev/null @@ -1,46 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NIVissimSingleTypeParser__XVerteilungsdefinition.h -/// @author Daniel Krajzewicz -/// @date Wed, 30 Apr 2003 -/// -// -/****************************************************************************/ -#pragma once -#include - -#include -#include "../NIImporter_Vissim.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NIVissimSingleTypeParser__XVerteilungsdefinition - * - */ -class NIVissimSingleTypeParser__XVerteilungsdefinition : - public NIImporter_Vissim::VissimSingleTypeParser { -public: - /// Constructor - NIVissimSingleTypeParser__XVerteilungsdefinition(NIImporter_Vissim& parent); - - /// Destructor - ~NIVissimSingleTypeParser__XVerteilungsdefinition(); - - /// Parses the data type from the given stream - bool parse(std::istream& from); - -}; diff --git a/Util/OSM2ODR/src/netload/NLBuilder.h b/Util/OSM2ODR/src/netload/NLBuilder.h deleted file mode 100644 index aafa4701c..000000000 --- a/Util/OSM2ODR/src/netload/NLBuilder.h +++ /dev/null @@ -1,227 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NLBuilder.h -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Mon, 9 Jul 2001 -/// -// The main interface for loading a microsim -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include -#include - - -// =========================================================================== -// class declarations -// =========================================================================== -class MSNet; -class NLContainer; -class MSJunctionLogic; -class MSDetectorControl; -class OptionsCont; -class NLHandler; -class NLEdgeControlBuilder; -class NLJunctionControlBuilder; -class NLDetectorBuilder; -class NLTriggerBuilder; -class SUMORouteLoader; -class SUMORouteLoaderControl; - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NLBuilder - * @brief The main interface for loading a microsim - * - * It is a black-box where only the options and factories must be supplied - * on the constructor call. An (empty) instance of the network must be - * supplied, too, and is filled during loading. - */ -class NLBuilder { -public: - /** @brief Constructor - * - * @param[in] oc The options to use - * @param[in, out] net The network to fill - * @param[in] eb The builder of edges to use - * @param[in] jb The builder of junctions to use - * @param[in] db The detector builder to use - * @param[in] tb The trigger builder to use - * @param[in] xmlHandler The xml handler to use - */ - NLBuilder(OptionsCont& oc, MSNet& net, - NLEdgeControlBuilder& eb, NLJunctionControlBuilder& jb, - NLDetectorBuilder& db, - NLHandler& xmlHandler); - - - /// @brief Destructor - virtual ~NLBuilder(); - - - /** @brief Builds and initialises the simulation - * - * At first, the network is loaded and the built using "buildNet". - * If this could be done, additional information is loaded (state dump, - * weight files, route files, and additional files). - * If everything could be done, true is returned, otherwise false. - * - * @see buildNet - * @exception ProcessError If something fails on network building - * @todo Again, both returning a bool and throwing an exception; quite inconsistent - */ - virtual bool build(); - - /** - * loads the net, additional routes and the detectors - */ - static MSNet* init(const bool isLibsumo = false); - - /// @brief initializes all RNGs - static void initRandomness(); - - -protected: - /** @brief Loads a described subpart form the given list of files - * - * Assuming the given string to be an option name behind which a list of files - * is stored, this method invokes an XML reader on all the files set for this option. - * @param[in] mmlWhat The option to get the file list from - * @param[in] isNet whether a network gets loaded - * @return Whether loading of all files was successfull - */ - bool load(const std::string& mmlWhat, const bool isNet = false); - - - /** @brief Closes the net building process - * - * Builds the microsim-structures which belong to a MSNet using the factories - * filled while loading. Initialises the network using these structures by calling - * MSNet::closeBuilding. - * If an error occurs, all built structures are deleted and a ProcessError is thrown. - * @exception ProcessError If the loaded structures could not be built - */ - void buildNet(); - - - /** @brief Builds the route loader control - * - * Goes through the list of route files to open defined in the option - * "route-files" and builds loaders reading these files - * @param[in] oc The options to read the list of route files to open from - * @return The built route loader control - * @exception ProcessError If an error occurred - */ - SUMORouteLoaderControl* buildRouteLoaderControl(const OptionsCont& oc); - - - - - /** - * @class EdgeFloatTimeLineRetriever_EdgeTravelTime - * @brief Obtains edge efforts from a weights handler and stores them within the edges - * @see SAXWeightsHandler::EdgeFloatTimeLineRetriever - */ - class EdgeFloatTimeLineRetriever_EdgeEffort : public SAXWeightsHandler::EdgeFloatTimeLineRetriever { - public: - /// @brief Constructor - EdgeFloatTimeLineRetriever_EdgeEffort(MSNet& net) : myNet(net) {} - - /// @brief Destructor - ~EdgeFloatTimeLineRetriever_EdgeEffort() { } - - /** @brief Adds an effort for a given edge and time period - * - * @param[in] id The id of the object to add a weight for - * @param[in] val The effort - * @param[in] beg The begin of the interval the weight is valid for - * @param[in] end The end of the interval the weight is valid for - * @see SAXWeightsHandler::EdgeFloatTimeLineRetriever::addEdgeWeight - */ - void addEdgeWeight(const std::string& id, - double val, double beg, double end) const; - - private: - /// @brief The network edges shall be obtained from - MSNet& myNet; - - }; - - - /** - * @class EdgeFloatTimeLineRetriever_EdgeTravelTime - * @brief Obtains edge travel times from a weights handler and stores them within the edges - * @see SAXWeightsHandler::EdgeFloatTimeLineRetriever - */ - class EdgeFloatTimeLineRetriever_EdgeTravelTime : public SAXWeightsHandler::EdgeFloatTimeLineRetriever { - public: - /// @brief Constructor - EdgeFloatTimeLineRetriever_EdgeTravelTime(MSNet& net) : myNet(net) {} - - /// @brief Destructor - ~EdgeFloatTimeLineRetriever_EdgeTravelTime() { } - - /** @brief Adds a travel time for a given edge and time period - * - * @param[in] id The id of the object to add a weight for - * @param[in] val The travel time - * @param[in] beg The begin of the interval the weight is valid for - * @param[in] end The end of the interval the weight is valid for - * @see SAXWeightsHandler::EdgeFloatTimeLineRetriever::addEdgeWeight - */ - void addEdgeWeight(const std::string& id, - double val, double beg, double end) const; - - private: - /// @brief The network edges shall be obtained from - MSNet& myNet; - - }; - - -protected: - /// @brief The options to get the names of the files to load and further information from - OptionsCont& myOptions; - - /// @brief The edge control builder to use - NLEdgeControlBuilder& myEdgeBuilder; - - /// @brief The junction control builder to use - NLJunctionControlBuilder& myJunctionBuilder; - - /// @brief The detector control builder to use - NLDetectorBuilder& myDetectorBuilder; - - /// @brief The net to fill - MSNet& myNet; - - /// @brief The handler used to parse the net - NLHandler& myXMLHandler; - - -private: - /// @brief invalidated copy operator - NLBuilder(const NLBuilder& s); - - /// @brief invalidated assignment operator - NLBuilder& operator=(const NLBuilder& s); - -}; diff --git a/Util/OSM2ODR/src/netload/NLDetectorBuilder.h b/Util/OSM2ODR/src/netload/NLDetectorBuilder.h deleted file mode 100644 index 541323dae..000000000 --- a/Util/OSM2ODR/src/netload/NLDetectorBuilder.h +++ /dev/null @@ -1,491 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NLDetectorBuilder.h -/// @author Daniel Krajzewicz -/// @author Clemens Honomichl -/// @author Christian Roessel -/// @author Michael Behrisch -/// @date Mon, 15 Apr 2002 -/// -// Builds detectors for microsim -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include -#include -// #include - -// =========================================================================== -// class declarations -// =========================================================================== -class MSDetectorFileOutput; -class MSLane; -class MSEdge; - -class MEInductLoop; -class MESegment; - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NLDetectorBuilder - * @brief Builds detectors for microsim - * - * The building methods may be overridden, to build guisim-instances of the triggers, - * for example. - */ -class NLDetectorBuilder { -public: - /** @brief Constructor - * - * @param[in] net The network to which's detector control built detector shall be added - */ - NLDetectorBuilder(MSNet& net); - - - /// @brief Destructor - virtual ~NLDetectorBuilder(); - - - /// @name Value parsing and detector building methods - /// @{ - - /** @brief Builds an e1 detector and adds it to the net - * - * Checks the given values, first. If one of the values is invalid - * (lane is not known, sampling frequency<=0, position is larger - * than lane's length, the id is already in use), an InvalidArgument is thrown. - * - * Otherwise the e1 detector is built by calling "createInductLoop". - * - * Internally, there is also a distinction whether a mesosim e1 detector - * shall be built. - * - * @param[in] id The id the detector shall have - * @param[in] lane The name of the lane the detector is placed at - * @param[in] pos The definition of the position on the lane the detector shall be placed at - * @param[in] splInterval The aggregation time span the detector shall use - * @param[in] device The output device the detector shall write into - * @param[in] friendlyPos Whether the position information shall be used "friendly" (see user docs) - * @param[in] vTypes which vehicle types are considered - * @exception InvalidArgument If one of the values is invalid - */ - void buildInductLoop(const std::string& id, - const std::string& lane, double pos, SUMOTime splInterval, - const std::string& device, bool friendlyPos, - const std::string& vTypes); - - - /** @brief Builds an instantenous induction and adds it to the net - * - * Checks the given values, first. If one of the values is invalid - * (lane is not known, sampling frequency<=0, position is larger - * than lane's length, the id is already in use), an InvalidArgument is thrown. - * - * Otherwise the e1 detector is built by calling "createInductLoop". - * - * @param[in] id The id the detector shall have - * @param[in] lane The name of the lane the detector is placed at - * @param[in] pos The definition of the position on the lane the detector shall be placed at - * @param[in] device The output device the detector shall write into - * @param[in] friendlyPos Whether the position information shall be used "friendly" (see user docs) - * @exception InvalidArgument If one of the values is invalid - */ - void buildInstantInductLoop(const std::string& id, - const std::string& lane, double pos, - const std::string& device, bool friendlyPos, - const std::string& vTypes); - - - - - /** @brief Builds a new E2 detector and adds it to the net's detector control. Also performs some - * consistency checks for the detector positioning and applies "friendly positioning" - * - * @param[in] tlls Traffic light logic associated to the detector - * @param[in] toLane Lane associated to the detector (only for tlls != 0) - * @param[in] friendlyPos Whether automatic adjustments of the detector position shall be applied in case of erroneous specification - * @see For the other parameters see the MSE2Collector constructors - * - * @todo Add parameter showDetector to indicate whether the detector should be visible in the GUI - * - */ - void buildE2Detector(const std::string& id, MSLane* lane, double pos, double endPos, double length, - const std::string& device, SUMOTime frequency, - SUMOTime haltingTimeThreshold, double haltingSpeedThreshold, double jamDistThreshold, - const std::string& vTypes, bool friendlyPos, bool showDetector, - MSTLLogicControl::TLSLogicVariants* tlls = 0, MSLane* toLane = 0); - - void buildE2Detector(const std::string& id, std::vector lanes, double pos, double endPos, - const std::string& device, SUMOTime frequency, - SUMOTime haltingTimeThreshold, double haltingSpeedThreshold, double jamDistThreshold, - const std::string& vTypes, bool friendlyPos, bool showDetector, - MSTLLogicControl::TLSLogicVariants* tlls = 0, MSLane* toLane = 0); - - - /** @brief Stores temporary the initial information about an e3 detector to build - * - * If the given sample interval is < 0, an InvalidArgument is thrown. Otherwise, - * the values are stored in a new instance of E3DetectorDefinition within - * "myE3Definition". - * - * @param[in] id The id the detector shall have - * @param[in] device The output device the detector shall write into - * @param[in] splInterval The aggregation time span the detector shall use - * @param[in] haltingTimeThreshold Detector parameter: the time a vehicle's speed must be below haltingSpeedThreshold to be assigned as jammed - * @param[in] haltingSpeedThreshold Detector parameter: the speed a vehicle's speed must be below to be assigned as jammed - * @exception InvalidArgument If one of the values is invalid - */ - void beginE3Detector(const std::string& id, const std::string& device, SUMOTime splInterval, - double haltingSpeedThreshold, SUMOTime haltingTimeThreshold, - const std::string& vTypes, bool openEntry); - - - /** @brief Builds an entry point of an e3 detector - * - * If the lane is not known or the position information is not within the lane, - * an InvalidArgument is thrown. Otherwise a MSCrossSection is built - * using the obtained values and added to the list of entries of the e3 definition - * stored in "myE3Definition". - * - * @param[in] lane The id of the lane the entry shall be placed at - * @param[in] pos The position on the lane the entry shall be placed at - * @param[in] friendlyPos Whether the position information shall be used "friendly" (see user docs) - * @exception InvalidArgument If one of the values is invalid - */ - void addE3Entry(const std::string& lane, double pos, bool friendlyPos); - - - /** @brief Builds an exit point of an e3 detector - * - * If the lane is not known or the position information is not within the lane, - * an InvalidArgument is thrown. Otherwise a MSCrossSection is built - * using the obtained values and added to the list of exits of the e3 definition - * stored in "myE3Definition". - * - * @param[in] lane The id of the lane the exit shall be placed at - * @param[in] pos The position on the lane the exit shall be placed at - * @param[in] friendlyPos Whether the position information shall be used "friendly" (see user docs) - * @exception InvalidArgument If one of the values is invalid - */ - void addE3Exit(const std::string& lane, double pos, bool friendlyPos); - - - /** @brief Builds of an e3 detector using collected values - * - * The parameter collected are used to build an e3 detector using - * "createE3Detector". The resulting detector is added to the net. - * - * @param[in] lane The id of the lane the exit shall be placed at - * @param[in] pos The position on the lane the exit shall be placed at - * @exception InvalidArgument If one of the values is invalid - */ - void endE3Detector(); - - - /** @brief Returns the id of the currently built e3 detector - * - * This is used for error-message generation only. If no id is known, - * "" is returned. - * - * @return The id of the currently processed e3 detector - */ - std::string getCurrentE3ID() const; - - - /** @brief Builds a vTypeProbe and adds it to the net - * - * Checks the given values, first. If one of the values is invalid - * (sampling frequency<=0), an InvalidArgument is thrown. - * - * Otherwise the vTypeProbe is built (directly). - * - * @param[in] id The id the detector shall have - * @param[in] vtype The name of the vehicle type the detector shall observe - * @param[in] frequency The reporting frequency - * @param[in] device The output device the detector shall write into - * @exception InvalidArgument If one of the values is invalid - */ - void buildVTypeProbe(const std::string& id, - const std::string& vtype, SUMOTime frequency, - const std::string& device); - - - /** @brief Builds a routeProbe and adds it to the net - * - * Checks the given values, first. If one of the values is invalid - * (sampling frequency<=0), an InvalidArgument is thrown. - * - * Otherwise the routeProbe is built (directly). - * - * @param[in] id The id the detector shall have - * @param[in] edge The name of the edge the detector shall observe - * @param[in] frequency The reporting frequency - * @param[in] begin The start of the first reporting interval - * @param[in] device The output device the detector shall write into - * @exception InvalidArgument If one of the values is invalid - */ - void buildRouteProbe(const std::string& id, const std::string& edge, - SUMOTime frequency, SUMOTime begin, - const std::string& device, - const std::string& vTypes); - /// @} - - - - /// @name Detector creating methods - /// - /// Virtual, so they may be overwritten, for generating gui-versions of the detectors, for example. - /// @{ - - /** @brief Creates an instance of an e1 detector using the given values - * - * Simply calls the MSInductLoop constructor - * - * @param[in] id The id the detector shall have - * @param[in] lane The lane the detector is placed at - * @param[in] pos The position on the lane the detector is placed at - * @param[in] vTypes which vehicle types are considered - * @param[in] show Whether to show the detector in the gui if available - */ - virtual MSDetectorFileOutput* createInductLoop(const std::string& id, - MSLane* lane, double pos, - const std::string& vTypes, bool show = true); - - - /** @brief Creates an instance of an e1 detector using the given values - * - * Simply calls the MSInductLoop constructor - * - * @param[in] id The id the detector shall have - * @param[in] lane The lane the detector is placed at - * @param[in] pos The position on the lane the detector is placed at - * @param[in] od The output device the loop shall use - */ - virtual MSDetectorFileOutput* createInstantInductLoop(const std::string& id, - MSLane* lane, double pos, const std::string& od, - const std::string& vTypes); - - - /** @brief Creates a MSE2Collector instance, overridden by GUIE2Collector::createE2Detector() - * - * Simply calls the MSE2Collector constructor - * - * @see MSE2Collector Constructor documentation - */ - virtual MSE2Collector* createE2Detector(const std::string& id, - DetectorUsage usage, MSLane* lane, double pos, double endPos, double length, - SUMOTime haltingTimeThreshold, double haltingSpeedThreshold, double jamDistThreshold, - const std::string& vTypes, bool showDetector = true); - - virtual MSE2Collector* createE2Detector(const std::string& id, - DetectorUsage usage, std::vector lanes, double pos, double endPos, - SUMOTime haltingTimeThreshold, double haltingSpeedThreshold, double jamDistThreshold, - const std::string& vTypes, bool showDetector = true); - - /** @brief Creates an instance of an e3 detector using the given values - * - * Simply calls the MSE3Collector constructor. - * - * @param[in] id The id the detector shall have - * @param[in] entries The list of this detector's entries - * @param[in] exits The list of this detector's exits - * @param[in] haltingSpeedThreshold Detector parameter: the speed a vehicle's speed must be below to be assigned as jammed - * @param[in] haltingTimeThreshold Detector parameter: the time a vehicle's speed must be below haltingSpeedThreshold to be assigned as jammed - */ - virtual MSDetectorFileOutput* createE3Detector(const std::string& id, - const CrossSectionVector& entries, const CrossSectionVector& exits, - double haltingSpeedThreshold, SUMOTime haltingTimeThreshold, - const std::string& vTypes, bool openEntry); - - - /** @brief Creates edge based mean data collector using the given specification - * - * @param[in] id The id the detector shall have - * @param[in] frequency The aggregation interval the detector shall use - * @param[in] begin dump begin time - * @param[in] end dump end time - * @param[in] type The type of values to be generated - * @param[in] useLanes Information whether lane-based or edge-based dump shall be generated - * @param[in] withEmpty Information whether empty lanes/edges shall be written - * @param[in] withInternal Information whether internal lanes/edges shall be written - * @param[in] trackVehicles Information whether information shall be collected per vehicle - * @param[in] detectPersons Whether pedestrians shall be detected instead of vehicles - * @param[in] maxTravelTime the maximum travel time to output - * @param[in] minSamples the minimum number of sample seconds before the values are valid - * @param[in] haltSpeed the maximum speed to consider a vehicle waiting - * @param[in] vTypes the set of vehicle types to consider - * @exception InvalidArgument If one of the values is invalid - */ - void createEdgeLaneMeanData(const std::string& id, SUMOTime frequency, - SUMOTime begin, SUMOTime end, const std::string& type, - const bool useLanes, const bool withEmpty, const bool printDefaults, - const bool withInternal, const bool trackVehicles, const int detectPersons, - const double maxTravelTime, const double minSamples, - const double haltSpeed, const std::string& vTypes, - const std::string& writeAttributes, - const std::string& device); - /// @} - - - - /** @brief Builds an e2 detector that lies on only one lane - * - * @param[in] id The id the detector shall have - * @param[in] usage Information how the detector is used within the simulation - * @param[in] lane The lane the detector is placed at - * @param[in] pos The position on the lane the detector is placed at - * @param[in] length The length the detector has - * @param[in] haltingTimeThreshold Detector parameter: the time a vehicle's speed must be below haltingSpeedThreshold to be assigned as jammed - * @param[in] haltingSpeedThreshold Detector parameter: the speed a vehicle's speed must be below to be assigned as jammed - * @param[in] jamDistThreshold Detector parameter: the distance between two vehicles in order to not count them to one jam - * @todo Check whether this method is really needful - */ - MSE2Collector* buildSingleLaneE2Det(const std::string& id, - DetectorUsage usage, MSLane* lane, double pos, double length, - SUMOTime haltingTimeThreshold, double haltingSpeedThreshold, - double jamDistThreshold, - const std::string& vTypes); - - -protected: - /** - * @class E3DetectorDefinition - * @brief Holds the incoming definitions of an e3 detector unless the detector is build. - */ - class E3DetectorDefinition { - public: - /** @brief Constructor - * @param[in] id The id the detector shall have - * @param[in] device The output device the detector shall write into - * @param[in] haltingSpeedThreshold Detector parameter: the speed a vehicle's speed must be below to be assigned as jammed - * @param[in] haltingTimeThreshold Detector parameter: the time a vehicle's speed must be below haltingSpeedThreshold to be assigned as jammed - * @param[in] splInterval The aggregation time span the detector shall use - */ - E3DetectorDefinition(const std::string& id, - const std::string& device, double haltingSpeedThreshold, - SUMOTime haltingTimeThreshold, SUMOTime splInterval, - const std::string& vTypes, bool openEntry); - - /// @brief Destructor - ~E3DetectorDefinition(); - - /// @brief The id of the detector - const std::string myID; - /// @brief The device the detector shall use - const std::string myDevice; - /// @brief The speed a vehicle's speed must be below to be assigned as jammed - double myHaltingSpeedThreshold; - /// @brief The time a vehicle's speed must be below haltingSpeedThreshold to be assigned as jammed - SUMOTime myHaltingTimeThreshold; - /// @brief List of detector's entries - CrossSectionVector myEntries; - /// @brief List of detector's exits - CrossSectionVector myExits; - /// @brief The aggregation interval - SUMOTime mySampleInterval; - /// @brief The device the detector shall use - const std::string myVehicleTypes; - /// @brief Whether the detector is declared as having incomplete entry detectors - bool myOpenEntry; - //@} - - private: - /// @brief Invalidated copy constructor. - E3DetectorDefinition(const E3DetectorDefinition&); - - /// @brief Invalidated assignment operator. - E3DetectorDefinition& operator=(const E3DetectorDefinition&); - - }; - - -protected: - /** @brief Computes the position to use - * - * At first, it is checked whether the given position is negative. If so, the - * position is added to the lane's length to obtain the position counted - * backwards. - * - * If the resulting position is beyond or in front (<0) of the lane, it is either - * set to the according lane's boundary (.1 or length-.1) if friendlyPos - * is set, or, if friendlyPos is not set, an InvalidArgument is thrown. - * - * @param[in] pos Definition of the position on the lane - * @param[in] lane The lane the position must be valid for - * @param[in] friendlyPos Whether false positions shall be made acceptable - * @param[in] detid The id of the currently built detector (for error message generation) - * @exception InvalidArgument If the defined position is invalid - */ - double getPositionChecking(double pos, MSLane* lane, bool friendlyPos, - const std::string& detid); - - - /// @name Value checking/adapting methods - /// @{ - - /** @brief Returns the named edge - * @param[in] edgeID The id of the lane - * @param[in] type The type of the detector (for error message generation) - * @param[in] detid The id of the currently built detector (for error message generation) - * @exception InvalidArgument If the named edge is not known - */ - MSEdge* getEdgeChecking(const std::string& edgeID, SumoXMLTag type, - const std::string& detid); - -public: - /** @brief Returns the named lane - * @param[in] laneID The id of the lane - * @param[in] type The type of the detector (for error message generation) - * @param[in] detid The id of the currently built detector (for error message generation) - * @exception InvalidArgument If the named lane is not known - */ - MSLane* getLaneChecking(const std::string& laneID, SumoXMLTag type, - const std::string& detid); - -protected: - /** @brief Checks whether the given frequency (sample interval) is valid - * @param[in] splInterval The sample interval - * @param[in] type The type of the detector (for error message generation) - * @param[in] id The id of the detector (for error message generation) - * @exception InvalidArgument If the given sample interval is invalid (<=0) - * @todo Why is splInterval an int??? - */ - void checkSampleInterval(SUMOTime splInterval, SumoXMLTag type, const std::string& id); - /// @} - - -protected: - /// @brief The net to fill - MSNet& myNet; - - -private: - /// @brief definition of the currently parsed e3 detector - E3DetectorDefinition* myE3Definition; - - -private: - /// @brief Invalidated copy constructor. - NLDetectorBuilder(const NLDetectorBuilder&); - - /// @brief Invalidated assignment operator. - NLDetectorBuilder& operator=(const NLDetectorBuilder&); - -}; diff --git a/Util/OSM2ODR/src/netload/NLDiscreteEventBuilder.h b/Util/OSM2ODR/src/netload/NLDiscreteEventBuilder.h deleted file mode 100644 index f15db356e..000000000 --- a/Util/OSM2ODR/src/netload/NLDiscreteEventBuilder.h +++ /dev/null @@ -1,91 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NLDiscreteEventBuilder.h -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Sep, 2003 -/// -// missing_desc -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include - - -// =========================================================================== -// class declarations -// =========================================================================== -class MSNet; - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NLDiscreteEventBuilder - * This class is responsible for building event-handling actions which - * the simulation shall execute. - */ -class NLDiscreteEventBuilder { -public: - /// Known action types - enum ActionType { - /// "SaveTLSStates" - EV_SAVETLSTATE, - /// "SaveTLSSwitchTimes" - EV_SAVETLSWITCHES, - /// "SaveTLSSwitchStates" - EV_SAVETLSWITCHSTATES, - /// "SaveTLSProgram" - EV_SAVETLSPROGRAM - }; - - /// Constructor - NLDiscreteEventBuilder(MSNet& net); - - /// Destructor - ~NLDiscreteEventBuilder(); - - /// Builds an action and saves it for further use - void addAction(const SUMOSAXAttributes& attrs, const std::string& basePath); - -private: - /// Builds an action which saves the state of a certain tls into a file - void buildSaveTLStateCommand(const SUMOSAXAttributes& attrs, const std::string& basePath); - - /// Builds an action which saves the switch times of links into a file - void buildSaveTLSwitchesCommand(const SUMOSAXAttributes& attrs, const std::string& basePath); - - /// Builds an action which saves the switch times and states of tls into a file - void buildSaveTLSwitchStatesCommand(const SUMOSAXAttributes& attrs, const std::string& basePath); - - /// Builds an action which saves the tls states as a loadable program into a file - void buildSaveTLSProgramCommand(const SUMOSAXAttributes& attrs, const std::string& basePath); - -private: - NLDiscreteEventBuilder& operator=(const NLDiscreteEventBuilder&); // just to avoid a compiler warning - -protected: - /// Definitions of a storage for build actions - typedef std::map KnownActions; - - /// Build actions that shall be executed during the simulation - KnownActions myActions; - - MSNet& myNet; - -}; diff --git a/Util/OSM2ODR/src/netload/NLEdgeControlBuilder.h b/Util/OSM2ODR/src/netload/NLEdgeControlBuilder.h deleted file mode 100644 index 0aa9eeb94..000000000 --- a/Util/OSM2ODR/src/netload/NLEdgeControlBuilder.h +++ /dev/null @@ -1,197 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NLEdgeControlBuilder.h -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @author Leonhard Luecken -/// @date Mon, 9 Jul 2001 -/// -// Interface for building edges -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include -#include - - -// =========================================================================== -// class declarations -// =========================================================================== -class MSEdgeControl; -class MSLane; -class MSNet; -class OutputDevice; - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NLEdgeControlBuilder - * @brief Interface for building edges - * - * This class is the container for MSEdge-instances while they are build. - * - * While building instances of MSEdge, these are stored in a list. The list of - * edges is later split into two lists, one containing single-lane-edges and - * one containing multi-lane-edges. - * @todo Assignment of lanes is not really well. Should be reworked after shapes are given as params. - */ -class NLEdgeControlBuilder { - -public: - /// @brief Constructor - NLEdgeControlBuilder(); - - - /// @brief Destructor - virtual ~NLEdgeControlBuilder(); - - - /** @brief Begins building of an MSEdge - * - * Builds an instance of MSEdge using "buildEdge". Stores it - * as the current edge in "myActiveEdge" and appends it to the list - * of built edges ("myEdges"). - * - * The given information is used to build the edge. - * @param[in] id The id of the edge - * @param[in] function The function of the edge - * @param[in] streetName The street name of the edge - * @exception InvalidArgument If an edge with the same name was already built - */ - void beginEdgeParsing(const std::string& id, const SumoXMLEdgeFunc function, - const std::string& streetName, const std::string& edgeType, - int priority, - const std::string& bidi, - double distance); - - - /** @brief Adds a lane to the current edge - * - * @param[in] id The lane's id - * @param[in] maxSpeed The speed allowed on this lane - * @param[in] length The lane's length - * @param[in] shape The shape of the lane - * @param[in] width The width of the lane - * @param[in] permissions Encoding of vehicle classes that may drive on this lane - * @param[in] index The index of this lane within its parent edge - * @see SUMOVehicleClass - * @see MSLane - * @todo Definitely not a good way - */ - virtual MSLane* addLane(const std::string& id, double maxSpeed, - double length, const PositionVector& shape, - double width, - SVCPermissions permissions, int index, bool isRampAccel, - const std::string& type); - - /** @brief process a stopOffset element (originates either from the active edge or lane). - */ - void addStopOffsets(const std::map& stopOffsets); - - - /** @brief Return info about currently processed edge or lane - */ - std::string reportCurrentEdgeOrLane() const; - - - /** @brief Adds a neighbor to the current lane - * - * @param[in] id The lane's id - * @see MSLane - */ - virtual void addNeigh(const std::string id); - - - /** @brief Closes the building of an edge; - The edge is completely described by now and may not be opened again */ - virtual MSEdge* closeEdge(); - - /** @brief Closes the building of a lane; - The edge is completely described by now and may not be opened again */ - void closeLane(); - - /// builds the MSEdgeControl-class which holds all edges - MSEdgeControl* build(double networkVersion); - - - /** @brief Builds an edge instance (MSEdge in this case) - * - * Builds an MSEdge-instance using the given name and the current index - * "myCurrentNumericalEdgeID". Post-increments the index, returns - * the built edge. - * - * @param[in] id The id of the edge to build - * @param[in] streetName The street name of the edge to build - */ - virtual MSEdge* buildEdge(const std::string& id, const SumoXMLEdgeFunc function, - const std::string& streetName, const std::string& edgeType, const int priority, const double distance); - - /** @brief add the crossingEdges in a crossing edge if present - * - * @param[in] the vector of crossed edges id - */ - virtual void addCrossingEdges(const std::vector&); - -protected: - /// @brief A running number for lane numbering - int myCurrentNumericalLaneID; - - /// @brief A running number for edge numbering - int myCurrentNumericalEdgeID; - - /// @brief Temporary, internal storage for built edges - MSEdgeVector myEdges; - - /// @brief pointer to the currently chosen edge - MSEdge* myActiveEdge; - - /// @brief The default stop offset for all lanes belonging to the active edge (this is set if the edge was given a stopOffset child) - std::map myCurrentDefaultStopOffsets; - - /// @brief The index of the currently active lane (-1 if none is active) - int myCurrentLaneIndex; - - /// @brief pointer to a temporary lane storage - std::vector* myLaneStorage; - - /// @brief temporary storage for bidi attributes (to be resolved after loading all edges) - std::map myBidiEdges; - - - /** @brief set the stopOffset for the last added lane. - */ - void updateCurrentLaneStopOffsets(const std::map& stopOffsets); - - /** @brief set the stopOffset for the last added lane. - */ - void setDefaultStopOffsets(std::map stopOffsets); - - /** @brief - */ - void applyDefaultStopOffsetsToLanes(); - -private: - /// @brief invalidated copy constructor - NLEdgeControlBuilder(const NLEdgeControlBuilder& s); - - /// @brief invalidated assignment operator - NLEdgeControlBuilder& operator=(const NLEdgeControlBuilder& s); - -}; diff --git a/Util/OSM2ODR/src/netload/NLHandler.h b/Util/OSM2ODR/src/netload/NLHandler.h deleted file mode 100644 index 1212dadf9..000000000 --- a/Util/OSM2ODR/src/netload/NLHandler.h +++ /dev/null @@ -1,357 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NLHandler.h -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Clemens Honomichl -/// @author Michael Behrisch -/// @date Sept 2002 -/// -// The XML-Handler for network loading -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include -#include "NLDiscreteEventBuilder.h" - - -// =========================================================================== -// class declarations -// =========================================================================== -class NLContainer; -class NLDetectorBuilder; -class NLEdgeControlBuilder; -class NLJunctionControlBuilder; -class NLTriggerBuilder; -class MSTrafficLightLogic; - - -// =========================================================================== -// class definitions -// =========================================================================== - - -/** - * @class NLShapeHandler - * @brief The XML-Handler for shapes loading network loading - * - * This subclasses ShapeHandler with MSLane specific function - */ -class NLShapeHandler : public ShapeHandler { -public: - NLShapeHandler(const std::string& file, ShapeContainer& sc) : - ShapeHandler(file, sc) {} - - /// @brief Destructor - virtual ~NLShapeHandler() {} - - Position getLanePos(const std::string& poiID, const std::string& laneID, double lanePos, double lanePosLat); - - virtual bool addLanePosParams() { - return true; - } -}; - - -/** - * @class NLHandler - * @brief The XML-Handler for network loading - * - * The SAX2-handler responsible for parsing networks and routes to load. - * This is an extension of the MSRouteHandler as routes and vehicles may also - * be loaded from network descriptions. - */ -class NLHandler : public MSRouteHandler { -public: - /// @brief Definition of a lane vector - typedef std::vector LaneVector; - -public: - /** @brief Constructor - * - * @param[in] file Name of the parsed file - * @param[in, out] net The network to fill - * @param[in] detBuilder The detector builder to use - * @param[in] triggerBuilder The trigger builder to use - * @param[in] edgeBuilder The builder of edges to use - * @param[in] junctionBuilder The builder of junctions to use - */ - NLHandler(const std::string& file, MSNet& net, - NLDetectorBuilder& detBuilder, NLTriggerBuilder& triggerBuilder, - NLEdgeControlBuilder& edgeBuilder, - NLJunctionControlBuilder& junctionBuilder); - - - /// @brief Destructor - virtual ~NLHandler(); - - bool haveSeenInternalEdge() const { - return myHaveSeenInternalEdge; - } - - bool haveSeenDefaultLength() const { - return myHaveSeenDefaultLength; - } - - bool haveSeenNeighs() const { - return myHaveSeenNeighs; - } - - bool haveSeenAdditionalSpeedRestrictions() const { - return myHaveSeenAdditionalSpeedRestrictions; - } - - double networkVersion() const { - return myNetworkVersion; - } - -protected: - /// @name inherited from GenericSAXHandler - //@{ - - /** @brief Called on the opening of a tag; - * - * @param[in] element ID of the currently opened element - * @param[in] attrs Attributes within the currently opened element - * @exception ProcessError If something fails - * @see GenericSAXHandler::myStartElement - * @todo Refactor/describe - */ - virtual void myStartElement(int element, - const SUMOSAXAttributes& attrs); - - - /** @brief Called when a closing tag occurs - * - * @param[in] element ID of the currently opened element - * @exception ProcessError If something fails - * @see GenericSAXHandler::myEndElement - * @todo Refactor/describe - */ - virtual void myEndElement(int element); - //@} - - -protected: - void addParam(const SUMOSAXAttributes& attrs); - - /** @brief Builds an e1 detector using the given specification - * @param[in] attrs The attributes that define the detector - */ - virtual void addE1Detector(const SUMOSAXAttributes& attrs); - - /** @brief Builds an e1 detector using the given specification - * @param[in] attrs The attributes that define the detector - */ - virtual void addInstantE1Detector(const SUMOSAXAttributes& attrs); - - /** @brief Builds an e2 detector using the given specification - * @param[in] attrs The attributes that define the detector - */ - virtual void addE2Detector(const SUMOSAXAttributes& attrs); - - /** @brief Starts building of an e3 detector using the given specification - * @param[in] attrs The attributes that define the detector - */ - void beginE3Detector(const SUMOSAXAttributes& attrs); - - /** @brief Adds an entry to the currently processed e3 detector - * @param[in] attrs The attributes that define the entry - */ - void addE3Entry(const SUMOSAXAttributes& attrs); - - /** @brief Adds an exit to the currently processed e3 detector - * @param[in] attrs The attributes that define the exit - */ - void addE3Exit(const SUMOSAXAttributes& attrs); - - /// Builds of an e3 detector using collected values - virtual void endE3Detector(); - - /** @brief Builds a vtype-detector using the given specification - * @param[in] attrs The attributes that define the detector - */ - virtual void addVTypeProbeDetector(const SUMOSAXAttributes& attrs); - - /** @brief Builds a routeProbe-detector using the given specification - * @param[in] attrs The attributes that define the detector - */ - virtual void addRouteProbeDetector(const SUMOSAXAttributes& attrs); - - /** @brief Builds edge or lane base mean data collector using the given specification - * @param[in] attrs The attributes that define the detector - * @param[in] objecttype The type (lane/edge) of the parsed mean data definition - */ - virtual void addEdgeLaneMeanData(const SUMOSAXAttributes& attrs, int objecttype); - - /// Closes the process of building an edge - virtual void closeEdge(); - - -protected: - /// The net to fill (preinitialised) - MSNet& myNet; - - -private: - /// begins the processing of an edge - void beginEdgeParsing(const SUMOSAXAttributes& attrs); - - /// adds a lane to the previously opened edge - void addLane(const SUMOSAXAttributes& attrs); - - /// adds a request item to the current junction logic - void addRequest(const SUMOSAXAttributes& attrs); - - /// begins the reading of a junction row logic - void initJunctionLogic(const SUMOSAXAttributes& attrs); - - /// begins the reading of a traffic lights logic - void initTrafficLightLogic(const SUMOSAXAttributes& attrs); - - /// adds a phase to the traffic lights logic currently build - void addPhase(const SUMOSAXAttributes& attrs); - - - /// opens a junction for processing - virtual void openJunction(const SUMOSAXAttributes& attrs); - - void parseLanes(const std::string& junctionID, const std::string& def, std::vector& into, bool& ok); - - /// adds a connection - void addConnection(const SUMOSAXAttributes& attrs); - - virtual void openWAUT(const SUMOSAXAttributes& attrs); - void addWAUTSwitch(const SUMOSAXAttributes& attrs); - void addWAUTJunction(const SUMOSAXAttributes& attrs); - - /// Parses network location description - void setLocation(const SUMOSAXAttributes& attrs); - - /** @begin Parses a district and creates a pseudo edge for it - * - * Called on the occurence of a "district" element, this method - * retrieves the id of the district and creates a district type - * edge with this id. - * - * @param[in] attrs The attributes (of the "district"-element) to parse - * @exception ProcessError If an edge given in district@edges is not known - */ - void addDistrict(const SUMOSAXAttributes& attrs); - - - /** @begin Parses a district edge and connects it to the district - * - * Called on the occurence of a "dsource" or "dsink" element, this method - * retrieves the id of the approachable edge. If this edge is known - * and valid, the approaching edge is informed about it. - * - * @param[in] attrs The attributes to parse - * @param[in] isSource whether a "dsource or a "dsink" was given - * @todo No exception? - */ - void addDistrictEdge(const SUMOSAXAttributes& attrs, bool isSource); - - /** @begin Parses a roundabout and sets flags for the edges - * @param[in] attrs The attributes to parse - */ - void addRoundabout(const SUMOSAXAttributes& attrs); - - - void closeWAUT(); - - /// @brief Parses the given character into an enumeration typed link direction - LinkDirection parseLinkDir(const std::string& dir); - - /// @brief Parses the given character into an enumeration typed link state - LinkState parseLinkState(const std::string& state); - -protected: - /// @brief A builder for object actions - NLDiscreteEventBuilder myActionBuilder; - - /// @brief Information whether the currently parsed edge is internal and not wished, here - bool myCurrentIsInternalToSkip; - - - /// @brief The detector builder to use - NLDetectorBuilder& myDetectorBuilder; - - /// @brief The trigger builder to use - NLTriggerBuilder& myTriggerBuilder; - - /// @brief The edge builder to use - NLEdgeControlBuilder& myEdgeControlBuilder; - - /// @brief The junction builder to use - NLJunctionControlBuilder& myJunctionControlBuilder; - - /// The id of the current district - std::string myCurrentDistrictID; - - /// internal information whether a tls-logic is currently read - bool myAmParsingTLLogicOrJunction; - - /// The id of the currently processed WAUT - std::string myCurrentWAUTID; - - /// The id of the currently processed edge type - std::string myCurrentTypeID; - - /// The network offset - Position myNetworkOffset; - - /// The network's boundaries - Boundary myOrigBoundary, myConvBoundary; - - bool myCurrentIsBroken; - - bool myHaveWarnedAboutInvalidTLType; - - Parameterised myLastEdgeParameters; - std::vector myLastParameterised; - - /// @brief whether the loaded network contains internal lanes - bool myHaveSeenInternalEdge; - - /// @brief whether the loaded network contains edges with default lengths - bool myHaveSeenDefaultLength; - - /// @brief whether the loaded network contains explicit neighbor lanes - bool myHaveSeenNeighs; - - /// @brief whether additional files contained type-specific speed limits - bool myHaveSeenAdditionalSpeedRestrictions; - - /// @brief the loaded network version - double myNetworkVersion; - - /// @brief whether the location element was already loadee - bool myNetIsLoaded; - - /// @brief temporary data for building the junction graph after network parsing is finished - typedef std::map > JunctionGraph; - JunctionGraph myJunctionGraph; - -private: - /** invalid copy constructor */ - NLHandler(const NLHandler& s); - - /** invalid assignment operator */ - NLHandler& operator=(const NLHandler& s); - -}; diff --git a/Util/OSM2ODR/src/netload/NLJunctionControlBuilder.h b/Util/OSM2ODR/src/netload/NLJunctionControlBuilder.h deleted file mode 100644 index 832573955..000000000 --- a/Util/OSM2ODR/src/netload/NLJunctionControlBuilder.h +++ /dev/null @@ -1,421 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NLJunctionControlBuilder.h -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date Mon, 9 Jul 2001 -/// -// Builder of microsim-junctions and tls -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - - -// =========================================================================== -// class declarations -// =========================================================================== -class OptionsCont; -class NLDetectorBuilder; - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NLJunctionControlBuilder - * @brief Builder of microsim-junctions and tls - * - * NLJunctionControlBuilder is a factory for MSJunction, MSJunctionLogic, WAUT, - * and MSTRafficLightLogic-instances. - * - * @todo Refactor this class - it's too large - * @todo Resort method by one of the topics. - */ -class NLJunctionControlBuilder { -private: - /// @brief Definition of a lane vector - typedef std::vector LaneVector; - -public: - /** @brief Constructor - * - * Stores default values for extended tls reading them from the given - * options. Builds a MSTLLogicControl instance for myLogicControl. - * @param[in] net The network to fill - * @param[in] db The detector builder to use - */ - NLJunctionControlBuilder(MSNet& net, NLDetectorBuilder& db); - - - /** @brief Destructor - * - * Deletes previously allocated "myLogicControl" and "myJunctions" if - * they were not previously returned (this may happen if an error occurred). - */ - virtual ~NLJunctionControlBuilder(); - - - /** @brief Begins the processing of the named junction - * - * @param[in] id The ID of the junction - * @param[in] key unused?! - * @param[in] type The type of the junction - * @param[in] x x-position of the junction - * @param[in] y y-position of the junction - * @param[in] shape The shape of the junction - * @param[in] incomingLanes List of lanes which end at this intersection - * @param[in] internalLanes List of internal lanes across this intersection - * @exception InvalidArgument If the junction type is not known - * @todo Check why "key" is given - */ - void openJunction(const std::string& id, const std::string& key, - const SumoXMLNodeType type, - const Position pos, - const PositionVector& shape, - const std::vector& incomingLanes, - const std::vector& internalLanes, - const std::string& name); - - - /** @brief Closes (ends) the processing of the current junction - * - * This method throws an InvalidArgument when a junction with the same id - * as the current was already added or if the junction type stored in "myType" - * is invalid. It throws a ProcessError if the container to store the - * junction in was not built before. - * - * @exception InvalidArgument If the current id is already used or the junction type was invalid - * @exception ProcessError If the container to store the junction in was not built before - * @todo Throwing ProcessError would get unneeded if the container would be built by default (see prepare) - * @todo The type of the junctions shoould probably be checked when supprted (in openJunction) - */ - void closeJunction(const std::string& basePath); - - - /** @brief Builds the MSJunctionControl which holds all of the simulations junctions - * - * Returns the previously built junction control ("myJunctions"). "myJunctions" is - * set to 0, so that it will not be destroyed by the destructor. - * - * @return The built junction control - */ - MSJunctionControl* build() const; - - - /** @brief Initialises a junction logic - * @param[in] id The id of the row-logic - */ - void initJunctionLogic(const std::string& id); - - - /** @brief Adds a logic item - * - * Adds a logic item to the current processed logic. Throws an InvalidArgument - * if the current request size (myRequestSize) is 0 or lower. - * - * @param[in] request The request (~link) index - * @param[in] response The response (list of higher priorised links) - * @param[in] foes List of foes to the request - * @param[in] cont Whether the request is followed by an internal end - * @todo Recheck "cont"; is the description correct? - */ - void addLogicItem(int request, const std::string& response, - const std::string& foes, bool cont); - - - /** @brief Begins the reading of a traffic lights logic - * - * @param[in] id The id of the tls - * @param[in] programID The id of the currently loaded program - * @param[in] type The type of the tls - * @param[in] offset The offset to start with - * @todo Why is the type not verified? - * @todo Recheck, describe usage of detectorOffset (where does the information come from?) - */ - void initTrafficLightLogic(const std::string& id, const std::string& programID, - TrafficLightType type, SUMOTime offset); - - - /** @brief Adds a phase to the currently built traffic lights logic - * - * @param[in] duration The duration of the phase - * @param[in] state The state of the tls - * @param[in] min The minimum duration of the phase - * @param[in] max The maximum duration of the phase - * @todo min/max is used only by one junction type. Recheck - * @todo min/max: maybe only one type of a phase definition should be built - */ - void addPhase(SUMOTime duration, const std::string& state, const std::vector& nextPhases, - SUMOTime min, SUMOTime max, const std::string& name); - - /** @brief Adds a phase to the currently built traffic lights logic - * - * @param[in] duration The duration of the phase - * @param[in] state The state of the tls - * @param[in] minDuration The minimum duration of the phase - * @param[in] maxDuration The maximum duration of the phase - * @param[in] transient_notdecisional Specifies if this is a transient phase (true) or a decisional one (false) - * @param[in] commit Specifies if this is a commit phase - * @param[in] targetLanes A reference to the vector containing targeted sensor lanes for this phase, given by lane id - */ - void addPhase(SUMOTime duration, const std::string& state, const std::vector& nextPhases, SUMOTime minDuration, SUMOTime maxDuration, const std::string& name, bool transient_notdecisional, bool commit, MSPhaseDefinition::LaneIdVector* targetLanes = nullptr); - - - /** @brief Returns a previously build tls logic - * - * @param[in] id The ID of the tls logic to return - * @return The named logic - * @exception InvalidArgument If the named tls logic was not built before - */ - MSTLLogicControl::TLSLogicVariants& getTLLogic(const std::string& id) - const; - - - /** @brief Returns the built tls-logic control - * - * Returns the junction control ("myLogicControl") built using MSTLLogicControl::closeNetworkReading. - * "myLogicControl" is set to 0, so that it will not be destroyed by the destructor. - * - * @return The built tls-logic control - * @exception ProcessError If the traffic lights were not correct - * @see MSTLLogicControl::closeNetworkReading - */ - MSTLLogicControl* buildTLLogics(); - - - /** @brief Ends the building of a traffic lights logic - * - * Builds the correct type of a MSTrafficLightLogic using the stored information. - * Tries to add it to the used tls control. Throws an InvalidArgument if - * this is not possible (another tls logic with the same name exists). - * - * @exception InvalidArgument If another tls logic with the same name as the currently built was loaded before - */ - virtual void closeTrafficLightLogic(const std::string& basePath); - - - /** @brief Ends the building of a junction logic (row-logic) - * - * Rechecks values for the request and builds a MSJunctionLogic using these values. - * Throws and InvalidArgument if the values are invalid (error message is - * included). - * Tries to add the built logic to the internal container "myLogics". If another - * logic with the same id exists, an InvalidArgument is thrown. - * - * @exception InvalidArgument If the logic's values are false or another logic with the same id was built before - */ - void closeJunctionLogic(); - - - /** @brief Adds a parameter - * - * @param[in] key The key of the parameter - * @param[in] value The value of the parameter - * @todo Where are these parameter used? Describe! - * @todo Can a parameter be overwritten? - */ - void addParam(const std::string& key, const std::string& value); - - - /** @brief Returns the active key - * @return The active key - */ - const std::string& getActiveKey() const; - - - /** @brief Returns the active sub key - * @return The active sub key - */ - const std::string& getActiveSubKey() const; - - - /** @brief Returns the used tls control - * - * This may be either the internal one ("myLogicControl"), or, if the network has - * been already loaded and we are loading additional tls programs, the net's logic control. - * - * @return The tls control to use - */ - MSTLLogicControl& getTLLogicControlToUse() const; - - /// @brief initialize junctions after all connections have been loaded - void postLoadInitialization(); - - /// @brief try to retrieve junction by id - MSJunction* retrieve(const std::string id); - - /// @brief return the number of phases loaded so far (for error reporting) - int getNumberOfLoadedPhases() const { - return (int)myActivePhases.size(); - } - - -protected: - /** @brief Returns the current junction logic - * - * "Current" means the one with "myActiveID". If it is not built yet - * (not within "myLogics") an InvalidArgument is thrown. - * - * @return The current tls logic - * @exception InvalidArgument If the logic was not built before - * @todo Where is this used? - */ - MSJunctionLogic* getJunctionLogicSecure(); - - -protected: - /// @name Factory methods, virtual so that other versions of the structures can be built - /// @{ - - /** @brief Builds a junction that does not use a logic - * - * Builds a MSNoLogicJunction - * - * @return The built junction - */ - virtual MSJunction* buildNoLogicJunction(); - - - /** @brief Builds a junction with a logic - * - * Builds a MSRightOfWayJunction. Throws an exception if the logic was not built - * (see getJunctionLogicSecure). - * - * @return The built junction - * @exception InvalidArgument If the logic of the junction was not built before - */ - virtual MSJunction* buildLogicJunction(); - - - /** @brief Builds an internal junction - * - * Builds a MSInternalJunction - * - * @return The built junction - */ - virtual MSJunction* buildInternalJunction(); - /// @} - - -protected: - /// @brief The net to use - MSNet& myNet; - - /// @brief The detector builder to use - NLDetectorBuilder& myDetectorBuilder; - - /// @brief The switch offset within the tls - SUMOTime myOffset; - - /// @brief The current logic type - TrafficLightType myLogicType; - - /// @brief The right-of-way-logic of the currently chosen bitset-logic - MSBitsetLogic::Logic myActiveLogic; - - /// @brief The description about which lanes disallow other passing the junction simultaneously - MSBitsetLogic::Foes myActiveFoes; - - /// @brief The description about which lanes have an internal follower - std::bitset myActiveConts; - - /// @brief The current phase definitions for a simple traffic light - MSSimpleTrafficLightLogic::Phases myActivePhases; - - /// @brief The size of the request - int myRequestSize; - - /// @brief Counter for the inserted items - int myRequestItemNumber; - - /// @brief The junctions controls - mutable MSJunctionControl* myJunctions; - - /// @brief The list of the incoming lanes of the currently chosen junction - LaneVector myActiveIncomingLanes; - - /// @brief The list of the internal lanes of the currently chosen junction - LaneVector myActiveInternalLanes; - - /// @brief The id of the currently chosen junction - std::string myActiveID; - - /// @brief The key of the currently chosen junction - std::string myActiveKey, myActiveProgram; - - /// @brief The type of the currently chosen junction - SumoXMLNodeType myType; - - /// @brief The position of the junction - Position myPosition; - - /// @brief The absolute duration of a tls-control loop - SUMOTime myAbsDuration; - - /// @brief The shape of the current junction - PositionVector myShape; - - /// @brief the name of the current junction - std::string myActiveName; - - /// @brief The container for information which junctions shall be initialised using which values - std::vector myLogics2PostLoadInit; - - - /// @brief The tls control to use (0 if net's tls control shall be used) - mutable MSTLLogicControl* myLogicControl; - - - /// @brief Definition of a parameter map (key->value) - typedef std::map StringParameterMap; - - /// @brief Parameter map (key->value) - StringParameterMap myAdditionalParameter; - - - /// @brief Map of loaded junction logics - std::map myLogics; - - /// @brief Information whether the current logic had an error - bool myCurrentHasError; - - -private: - /** @brief invalidated copy operator */ - NLJunctionControlBuilder(const NLJunctionControlBuilder& s); - - /** @brief invalidated assignment operator */ - NLJunctionControlBuilder& operator=(const NLJunctionControlBuilder& s); - - static const int NO_REQUEST_SIZE; - - /// @brief whether the network has been loaded - bool myNetIsLoaded; - -}; diff --git a/Util/OSM2ODR/src/netload/NLTriggerBuilder.h b/Util/OSM2ODR/src/netload/NLTriggerBuilder.h deleted file mode 100644 index d8c7d0ace..000000000 --- a/Util/OSM2ODR/src/netload/NLTriggerBuilder.h +++ /dev/null @@ -1,488 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2002-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NLTriggerBuilder.h -/// @author Daniel Krajzewicz -/// @author Tino Morenz -/// @author Eric Nicolay -/// @author Michael Behrisch -/// @author Jakob Erdmann -/// @date Thu, 17 Oct 2002 -/// -// Builds trigger objects for microsim -/****************************************************************************/ -#pragma once -#include - -#include -#include - - -// =========================================================================== -// class declarations -// =========================================================================== -class MSTrigger; -class MSNet; -class MSLaneSpeedTrigger; -class NLHandler; -class MSTriggeredRerouter; -class MSLane; -class MSEdge; -class MSStoppingPlace; -class MSCalibrator; -class MSRouteProbe; - -class METriggeredCalibrator; - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NLTriggerBuilder - * @brief Builds trigger objects for microsim - * - * The building methods may be overridden, to build guisim-instances of the triggers, - * for example. - * - */ -class NLTriggerBuilder { -public: - /// @brief Constructor - NLTriggerBuilder(); - - - /// @brief Destructor - virtual ~NLTriggerBuilder(); - - - /** @brief Sets the parent handler to use for nested parsing - * - * @param[in] handler The netload handler to set - */ - void setHandler(NLHandler* handler); - - - /** @brief Builds a vaporization - * - * Parses the attributes, reporting errors if the time values are false - * or the edge is not known. - * Instatiates events for enabling and disabling the vaporization otherwise. - * - * @param[in] attrs SAX-attributes which define the vaporizer - * @note recheck throwing the exception - */ - void buildVaporizer(const SUMOSAXAttributes& attrs); - - - /// @name parsing methods - /// - /// These methods parse the attributes for each of the described trigger - /// and call the according methods to build the trigger - //@{ - /** @brief Parses his values and builds a lane speed trigger - * - * If one of the declaration values is errornous, an InvalidArgument is thrown. - * - * If the XML-file parsed during initialisation is errornous, and the - * MSLaneSpeedTrigger-constructor throws a ProcessError due to this, this - * exception is catched and an InvalidArgument with the message given in the - * ProcessError is thrown. - * - * @param[in] net The network the lane speed trigger belongs to - * @param[in] attrs SAX-attributes which define the trigger - * @param[in] base The base path - * @exception InvalidArgument If a parameter (lane/position) is not valid or the read definition is errornous - * @see buildLaneSpeedTrigger - */ - void parseAndBuildLaneSpeedTrigger(MSNet& net, const SUMOSAXAttributes& attrs, - const std::string& base); - - - /** @brief Parses his values and builds a rerouter - * - * @param[in] net The network the rerouter belongs to - * @param[in] attrs SAX-attributes which define the trigger - * @param[in] base The base path - * @exception InvalidArgument If a parameter (edge) is not valid - */ - void parseAndBuildRerouter(MSNet& net, const SUMOSAXAttributes& attrs, - const std::string& base); - - - /** @brief Parses the values and builds a stopping places for busses, trains or container vehicles - * - * @param[in] net The network the stop belongs to - * @param[in] attrs SAX-attributes which define the stop - * @param[in] element which kind of stop is to be built - * @exception InvalidArgument If a parameter (lane/position) is not valid - */ - void parseAndBuildStoppingPlace(MSNet& net, const SUMOSAXAttributes& attrs, const SumoXMLTag element); - - - /** @brief Begin a parking area - * - * Simply calls the MSParkingArea constructor. - * - * @param[in] net The net the parking area belongs to - * @param[in] id The id of the parking area - * @param[in] lines Names of the lines that halt on this parking area - * @param[in] lane The lane the parking area is placed on - * @param[in] frompos Begin position of the parking area on the lane - * @param[in] topos End position of the parking area on the lane - * @param[in] capacity Capacity of the parking area - * @param[in] width Width of the default lot rectangle - * @param[in] length Length of the default lot rectangle - * @param[in] angle Angle of the default lot rectangle - * @exception InvalidArgument If the parking area can not be added to the net (is duplicate) - */ - virtual void beginParkingArea(MSNet& net, - const std::string& id, const std::vector& lines, - MSLane* lane, double frompos, double topos, - unsigned int capacity, - double width, double length, double angle, const std::string& name, - bool onRoad); - - - /** @brief Add a lot entry to current parking area - * - * Simply calls the addLotEntry method for current parking area. - * - * @param[in] x X position of the lot center - * @param[in] y Y position of the lot center - * @param[in] z Z position of the lot center - * @param[in] width Width of the lot rectangle - * @param[in] length Length of the lot rectangle - * @param[in] angle Angle of the lot rectangle - * @exception InvalidArgument If the current parking area is 0 - */ - void addLotEntry(double x, double y, double z, - double width, double length, double angle); - - - - /** @brief Parses the values and adds an access point to the currently parsed stopping place - * - * @param[in] net The network the stop belongs to - * @param[in] attrs SAX-attributes which define the access - * @exception InvalidArgument If a parameter (lane/position) is not valid - */ - void addAccess(MSNet& net, const SUMOSAXAttributes& attrs); - - - /** @brief Parses his values and builds a parking area - * - * @param[in] net The network the parking area belongs to - * @param[in] attrs SAX-attributes which define the trigger - * @exception InvalidArgument If a parameter (lane/position) is not valid - */ - void parseAndBeginParkingArea(MSNet& net, const SUMOSAXAttributes& attrs); - - - /** @brief Parses his values and adds a lot entry to current parking area - * - * @param[in] attrs SAX-attributes which define the lot entry - */ - void parseAndAddLotEntry(const SUMOSAXAttributes& attrs); - - - /** @brief End a parking area - * - * @exception InvalidArgument If the current parking area is 0 - */ - virtual void endParkingArea(); - - /** @brief End a stopping place - * - * @exception InvalidArgument If the current stopping place is 0 - */ - virtual void endStoppingPlace(); - - - /** @brief Parses his values and builds a charging station - * - * @param[in] net The network the charging station belongs to - * @param[in] attrs SAXattributes which define the trigger - * @exception InvalidArgument If a parameter (lane/position) is not valid - */ - void parseAndBuildChargingStation(MSNet& net, const SUMOSAXAttributes& attrs); - - /** @brief Parses its values and builds an overhead wire segment - * - * @param[in] net The network the overhead wire segment belongs to - * @param[in] attrs SAXattributes which define the trigger - * @exception InvalidArgument If a parameter (lane/position) is not valid - */ - void parseAndBuildOverheadWireSegment(MSNet& net, const SUMOSAXAttributes& attrs); - - /** @brief Parses its values and builds an overhead wire section - * - * @param[in] net The network the overhead wire segment belongs to - * @param[in] attrs SAXattributes which define the trigger - * @exception InvalidArgument If a substationId is not known, a segment is not known or is assigned to another overheadWireSection - */ - void parseAndBuildOverheadWireSection(MSNet& net, const SUMOSAXAttributes& attrs); - - /** @brief Parses its values and builds a traction substation - * - * @param[in] net The network the overhead wire segment belongs to - * @param[in] attrs SAXattributes which define the trigger - * @exception InvalidArgument If the id is not given or is empty... - */ - void parseAndBuildTractionSubstation(MSNet& net, const SUMOSAXAttributes& attrs); - - /** @brief Parses its values and builds an overhead wire clamp - * - * An overhead wire clamp is a conductive connection of wires in the opposite direction over the road - * - * @param[in] net The network the overhead wire clamp belongs to - * @param[in] attrs SAXattributes which define the trigger - * @exception InvalidArgument If the traction substation is not found in the net or if the start or end segment belongs to a different traction substation - */ - void parseAndBuildOverheadWireClamp(MSNet& net, const SUMOSAXAttributes& attrs); - - /** @brief Parses his values and builds a mesoscopic or microscopic calibrator - * - * @param[in] net The network the calibrator belongs to - * @param[in] attrs SAX-attributes which define the trigger - * @param[in] base The base path - * @exception InvalidArgument If a parameter (edge/position) is not valid - */ - void parseAndBuildCalibrator(MSNet& net, const SUMOSAXAttributes& attrs, - const std::string& base); - //@} - - - MSStoppingPlace* getCurrentStop(); - - -protected: - /// @name building methods - /// - /// Called with parsed values, these methods build the trigger. - /// - /// These methods should be overriden for the gui loader in order - /// to build visualizable versions of the triggers. - /// - /// In most cases, these methods only call the constructor. - //@{ - - /** @brief Builds a lane speed trigger - * - * Simply calls the MSLaneSpeedTrigger constructor. - * - * @param[in] net The net the lane speed trigger belongs to - * @param[in] id The id of the lane speed trigger - * @param[in] destLanes List of lanes affected by this speed trigger - * @param[in] file Name of the file to read the speeds to set from - * @see MSLaneSpeedTrigger - * @exception ProcessError If the XML definition file is errornous - */ - virtual MSLaneSpeedTrigger* buildLaneSpeedTrigger(MSNet& net, - const std::string& id, const std::vector& destLanes, - const std::string& file); - - - /** @brief Builds a stopping place - * - * Simply calls the MSStoppingPlace constructor. - * - * @param[in] net The net the stop belongs to - * @param[in] id The id of the stop - * @param[in] lines Names of the lines that halt on this bus stop - * @param[in] lane The lane the stop is placed on - * @param[in] frompos Begin position of the stop on the lane - * @param[in] topos End position of the stop on the lane - * @param[in] element which kind of stop is to be built - * @exception InvalidArgument If the stop can not be added to the net (is duplicate) - */ - virtual void buildStoppingPlace(MSNet& net, std::string id, std::vector lines, MSLane* lane, - double frompos, double topos, const SumoXMLTag element, std::string string, - int personCapacity, double parkingLength); - - /** @brief Builds a charging station - * - * Simply calls the MSChargingStation constructor and adds the result to the network. - * - * @param[in] net The net the charging station belongs to - * @param[in] id The id of the charging station - * @param[in] lane The lane the charging station is placed on - * @param[in] frompos Begin position of the charging station on the lane - * @param[in] topos End position of the charging station on the lane - * @param[in] chargingPower energy charged in every timeStep - * @param[in] efficiency efficiency of the charge - * @param[in] chargeInTransit enable or disable charge in transit - * @param[in] chargeDelay delay in the charge - * @exception InvalidArgument If the charging station can not be added to the net (is duplicate) - */ - virtual void buildChargingStation(MSNet& net, const std::string& id, MSLane* lane, double frompos, double topos, const std::string& name, - double chargingPower, double efficiency, bool chargeInTransit, double chargeDelay); - - /** @brief Builds an overhead wire segment - * - * Simply calls the MSOverheadWire constructor and adds the result to the network. - * - * @param[in] net The net the overhead wire segment belongs to - * @param[in] id The id of the overhead wire segment - * @param[in] lane The lane the overhead wire segment is placed on - * @param[in] frompos Begin position of the overhead wire segment on the lane - * @param[in] topos End position of the overhead wire segment on the lane - * @param[in] voltageSource default voltage of overhead wire segment (unused) TODORICE - * @exception InvalidArgument If the overhead wire segment can not be added to the net (is duplicate according to the id) - */ - virtual void buildOverheadWireSegment(MSNet& net, const std::string& id, MSLane* lane, double frompos, double topos, bool voltageSource); - - /** @brief Builds an overhead wire inner segments - * - * Simply calls the buildOverheadWireSegment for inner edges connection, frontConnection and behindConnection if exists. - * - * @param[in] net The net the overhead wire inner segments belongs to - * @param[in] connection The inner lane that connects two regular lanes, or a regular lane with the inner "behindConnection" lane, - or the inner "frontConnection" lane with a regular lane, or the inner "frontConnection" lane with the inner "behindConnection" lane - * @param[in] frontConnection The inner lane that connects a regular lane with the inner "connection" lane - * @param[in] behindConnection The inner lane that connects the inner "connection" lane with a regular lane - * @exception InvalidArgument If the over can not be added to the net (is duplicate according to the id) - */ - void buildInnerOverheadWireSegments(MSNet& net, const MSLane* connection, const MSLane* frontConnection, const MSLane* behindConnection); - - /** @brief Builds a traction substation - * - * Simply calls the MSTractionSubstaion cosnstructor and adds the substation to the list of substations in the net. - * - * @param[in] net The net the traction substation belongs to - * @param[in] id The id of the traction substation - * @param[in] voltage The voltage level of the voltage source representing the traction substation - * @exception InvalidArgument If the over can not be added to the net (is duplicate according to the id) - */ - void buildTractionSubstation(MSNet& net, std::string id, double voltage); - - virtual void buildOverheadWireClamp(MSNet& net, const std::string& id, MSLane* lane_start, MSLane* lane_end); - - /** @brief builds a microscopic calibrator - * - * Simply calls the MSCalibrator constructor. - * - * @param[in] net The net the calibrator belongs to - * @param[in] id The id of the calibrator - * @param[in] edge The edge the calibrator is placed at - * @param[in] pos The position on the edge the calibrator lies at - * @param[in] file The file to read the flows from - * @todo Is the position correct/needed - */ - virtual MSCalibrator* buildCalibrator(MSNet& net, - const std::string& id, MSEdge* edge, MSLane* lane, double pos, - const std::string& file, const std::string& outfile, - const SUMOTime freq, - const MSRouteProbe* probe, - const std::string& vTypes); - - /** @brief builds a mesoscopic calibrator - * - * Simply calls the METriggeredCalibrator constructor. - * - * @param[in] net The net the calibrator belongs to - * @param[in] id The id of the calibrator - * @param[in] edge The edge the calibrator is placed at - * @param[in] pos The position on the edge the calibrator lies at - * @param[in] file The file to read the flows from - * @todo Is the position correct/needed - */ - virtual METriggeredCalibrator* buildMECalibrator(MSNet& net, - const std::string& id, const MSEdge* edge, double pos, - const std::string& file, const std::string& outfile, - const SUMOTime freq, - MSRouteProbe* probe, - const std::string& vTypes); - - - /** @brief builds an rerouter - * - * Simply calls the MSTriggeredRerouter constructor. - * - * @param[in] net The net the rerouter belongs to - * @param[in] id The id of the rerouter - * @param[in] edges The edges the rerouter is placed at - * @param[in] prob The probability the rerouter reoutes vehicles with - * @param[in] file The file to read the reroute definitions from - */ - virtual MSTriggeredRerouter* buildRerouter(MSNet& net, - const std::string& id, MSEdgeVector& edges, - double prob, const std::string& file, bool off, - SUMOTime timeThreshold, - const std::string& vTypes); - //@} - - -protected: - /// @name helper method for obtaining and checking values - /// @{ - - /** @brief Helper method to obtain the filename - * - * Retrieves "file" from attributes, checks whether it is absolute - * and extends it by the given base path if not. Returns this - * information. - * - * @param[in] attrs The attributes to obtain the file name from - * @param[in] base The base path (the path the loaded additional file lies in) - * @return The (expanded) path to the named file - * @todo Recheck usage of the helper class - */ - std::string getFileName(const SUMOSAXAttributes& attrs, - const std::string& base, - const bool allowEmpty = false); - - - /** @brief Returns the lane defined by attribute "lane" - * - * Retrieves the lane id from the given attrs. Tries to retrieve the lane, - * throws an InvalidArgument if it does not exist. - * - * @param[in] attrs The attributes to obtain the lane id from - * @param[in] tt The trigger type (for user output) - * @param[in] tid The trigger id (for user output) - * @return The named lane if it is known - * @exception InvalidArgument If the named lane does not exist or a lane is not named - */ - MSLane* getLane(const SUMOSAXAttributes& attrs, - const std::string& tt, const std::string& tid); - - - /** @brief returns the position on the lane checking it - * - * This method extracts the position, checks whether it shall be mirrored - * and checks whether it is within the lane. If not, an error is reported - * and a InvalidArgument is thrown. - * - * @param[in] attrs The attributes to obtain the position from - * @param[in] lane The lane the position shall be valid for - * @param[in] tt The trigger type (for user output) - * @param[in] tid The trigger id (for user output) - * @return The position on the lane - * @exception InvalidArgument If the position is beyond the lane - */ - double getPosition(const SUMOSAXAttributes& attrs, - MSLane* lane, const std::string& tt, const std::string& tid, MSEdge* edge = 0); - /// @} - - -protected: - /// @brief The parent handler to set for subhandlers - NLHandler* myHandler; - /// @brief definition of the currently parsed parking area - MSParkingArea* myParkingArea; - /// @brief The currently parsed stop to add access points to - MSStoppingPlace* myCurrentStop; - - bool myHaveWarnedAboutEigen = false; -}; diff --git a/Util/OSM2ODR/src/netwrite/CMakeLists.txt b/Util/OSM2ODR/src/netwrite/CMakeLists.txt deleted file mode 100644 index 871664844..000000000 --- a/Util/OSM2ODR/src/netwrite/CMakeLists.txt +++ /dev/null @@ -1,19 +0,0 @@ -set(netwrite_STAT_SRCS - NWFrame.cpp - NWFrame.h - NWWriter_Amitran.cpp - NWWriter_Amitran.h - NWWriter_MATSim.cpp - NWWriter_MATSim.h - NWWriter_OpenDrive.cpp - NWWriter_OpenDrive.h - NWWriter_DlrNavteq.cpp - NWWriter_DlrNavteq.h - NWWriter_SUMO.cpp - NWWriter_SUMO.h - NWWriter_XML.cpp - NWWriter_XML.h -) - -add_library(netwrite STATIC ${netwrite_STAT_SRCS}) -set_property(TARGET netwrite PROPERTY PROJECT_LABEL "z_netwrite") diff --git a/Util/OSM2ODR/src/netwrite/NWFrame.cpp b/Util/OSM2ODR/src/netwrite/NWFrame.cpp deleted file mode 100644 index cf1c627e6..000000000 --- a/Util/OSM2ODR/src/netwrite/NWFrame.cpp +++ /dev/null @@ -1,196 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NWFrame.cpp -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date Tue, 20 Nov 2001 -/// -// Sets and checks options for netwrite -/****************************************************************************/ -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include "NWFrame.h" -#include "NWWriter_SUMO.h" -#include "NWWriter_Amitran.h" -#include "NWWriter_MATSim.h" -#include "NWWriter_XML.h" -#include "NWWriter_OpenDrive.h" -#include "NWWriter_DlrNavteq.h" - -// =========================================================================== -// static members -// =========================================================================== - -// =========================================================================== -// method definitions -// =========================================================================== -void -NWFrame::fillOptions(bool forNetgen) { - OptionsCont& oc = OptionsCont::getOptions(); - // register options - oc.doRegister("output-file", 'o', new Option_FileName()); - oc.addSynonyme("output-file", "sumo-output"); - oc.addSynonyme("output-file", "output"); - oc.addDescription("output-file", "Output", "The generated net will be written to FILE"); - - oc.doRegister("plain-output-prefix", new Option_FileName()); - oc.addSynonyme("plain-output-prefix", "plain-output"); - oc.addSynonyme("plain-output-prefix", "plain"); - oc.addDescription("plain-output-prefix", "Output", "Prefix of files to write plain xml nodes, edges and connections to"); - - oc.doRegister("junctions.join-output", new Option_FileName()); - oc.addDescription("junctions.join-output", "Output", - "Writes information about joined junctions to FILE (can be loaded as additional node-file to reproduce joins"); - - oc.doRegister("prefix", new Option_String("")); - oc.addDescription("prefix", "Output", "Defines a prefix for edge and junction names"); - -#ifdef PROJ_API_FILE - if (!forNetgen) { - oc.doRegister("proj.plain-geo", new Option_Bool(false)); - oc.addDescription("proj.plain-geo", "Projection", "Write geo coordinates in plain-xml"); - } -#endif // PROJ_API_FILE - - oc.doRegister("amitran-output", new Option_FileName()); - oc.addDescription("amitran-output", "Output", "The generated net will be written to FILE using Amitran format"); - - oc.doRegister("matsim-output", new Option_FileName()); - oc.addDescription("matsim-output", "Output", "The generated net will be written to FILE using MATsim format"); - - oc.doRegister("opendrive-output", new Option_FileName()); - oc.addDescription("opendrive-output", "Output", "The generated net will be written to FILE using OpenDRIVE format"); - - oc.doRegister("dlr-navteq-output", new Option_FileName()); - oc.addDescription("dlr-navteq-output", "Output", "The generated net will be written to dlr-navteq files with the given PREFIX"); - - oc.doRegister("dlr-navteq.precision", new Option_Integer(2)); - oc.addDescription("dlr-navteq.precision", "Output", "The network coordinates are written with the specified level of output precision"); - - oc.doRegister("output.street-names", new Option_Bool(false)); - oc.addDescription("output.street-names", "Output", "Street names will be included in the output (if available)"); - - oc.doRegister("output.original-names", new Option_Bool(false)); - oc.addDescription("output.original-names", "Output", "Writes original names, if given, as parameter"); - - oc.doRegister("street-sign-output", new Option_FileName()); - oc.addDescription("street-sign-output", "Output", "Writes street signs as POIs to FILE"); - - if (!forNetgen) { - oc.doRegister("ptstop-output", new Option_FileName()); - oc.addDescription("ptstop-output", "Output", "Writes public transport stops to FILE"); - oc.doRegister("ptline-output", new Option_FileName()); - oc.addDescription("ptline-output", "Output", "Writes public transport lines to FILE"); - oc.doRegister("ptline-clean-up", new Option_Bool(false)); - oc.addDescription("ptline-clean-up", "Output", "Clean-up pt stops that are not served by any line"); - - oc.doRegister("parking-output", new Option_FileName()); - oc.addDescription("parking-output", "Output", "Writes parking areas to FILE"); - - oc.doRegister("railway.topology.output", new Option_FileName()); - oc.addDescription("railway.topology.output", "Output", "Analyse topology of the railway network"); - - oc.doRegister("polygon-output", new Option_FileName()); - oc.addSynonyme("polygon-output", "taz-output"); - oc.addDescription("polygon-output", "Output", "Write shapes that are embedded in the network input and that are not supported by polyconvert (OpenDRIVE)"); - } - - // register opendrive options - oc.doRegister("opendrive-output.straight-threshold", new Option_Float(0.00000001)); // matching the angular output precision in NWWriter_OpenDrive - oc.addDescription("opendrive-output.straight-threshold", "Output", "Builds parameterized curves whenever the angular change between straight segments exceeds FLOAT degrees"); -} - - -bool -NWFrame::checkOptions() { - OptionsCont& oc = OptionsCont::getOptions(); - bool ok = true; - // check whether the output is valid and can be build - if (!oc.isSet("output-file") - && !oc.isSet("plain-output-prefix") - && !oc.isSet("amitran-output") - && !oc.isSet("matsim-output") - && !oc.isSet("opendrive-output") - && !oc.isSet("dlr-navteq-output")) { - std::string net = "net.net.xml"; - if (oc.isSet("configuration-file")) { - net = FileHelpers::getConfigurationRelative(oc.getString("configuration-file"), net); - } - oc.setDefault("output-file", net); - } - // some outputs need internal lanes - if (oc.isSet("opendrive-output") && oc.getBool("no-internal-links")) { - WRITE_ERROR("OpenDRIVE export needs internal links computation."); - ok = false; - } - if (oc.isSet("opendrive-output") && oc.isDefault("no-internal-links")) { - oc.set("no-internal-links", "false"); - } - if (oc.isSet("opendrive-output") && oc.isDefault("rectangular-lane-cut")) { - oc.set("rectangular-lane-cut", "true"); - } - if (oc.isSet("opendrive-output") && !oc.getBool("rectangular-lane-cut")) { - WRITE_WARNING("OpenDRIVE cannot represent oblique lane cuts and should use option 'rectangular-lane-cut'."); - } - if (oc.isSet("dlr-navteq-output") && oc.isDefault("numerical-ids")) { - oc.set("numerical-ids", "true"); - } - if (oc.isSet("dlr-navteq-output") && oc.isDefault("osm.all-attributes")) { - oc.set("osm.all-attributes", "true"); - } - if (oc.exists("ptline-output") && oc.isSet("ptline-output") && !oc.isSet("ptstop-output")) { - WRITE_ERROR("public transport lines output requires 'ptstop-output' to be set"); - ok = false; - } - if (oc.exists("ptline-clean-up") && oc.getBool("ptline-clean-up") && !oc.isSet("ptline-output")) { - WRITE_WARNING("'ptline-clean-up' only works in conjunction with 'ptline-output'. Ignoring invalid option."); - } - - return ok; -} - - -void -NWFrame::writeNetwork(const OptionsCont& oc, NBNetBuilder& nb) { - const long before = PROGRESS_BEGIN_TIME_MESSAGE("Writing network"); - NWWriter_SUMO::writeNetwork(oc, nb); - NWWriter_Amitran::writeNetwork(oc, nb); - NWWriter_MATSim::writeNetwork(oc, nb); - NWWriter_OpenDrive::writeNetwork(oc, nb); - NWWriter_DlrNavteq::writeNetwork(oc, nb); - NWWriter_XML::writeNetwork(oc, nb); - PROGRESS_TIME_MESSAGE(before); -} - - -void -NWFrame::writePositionLong(const Position& pos, OutputDevice& dev) { - dev.writeAttr(SUMO_ATTR_X, pos.x()); - dev.writeAttr(SUMO_ATTR_Y, pos.y()); - if (pos.z() != 0) { - dev.writeAttr(SUMO_ATTR_Z, pos.z()); - } -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netwrite/NWFrame.h b/Util/OSM2ODR/src/netwrite/NWFrame.h deleted file mode 100644 index 0e4b67015..000000000 --- a/Util/OSM2ODR/src/netwrite/NWFrame.h +++ /dev/null @@ -1,58 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NWFrame.h -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date Tue, 20 Nov 2001 -/// -// Sets and checks options for netwrite -/****************************************************************************/ -#pragma once -#include - - -// =========================================================================== -// class declarations -// =========================================================================== -class OptionsCont; -class NBNetBuilder; -class Position; -class OutputDevice; - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NWFrame - * @brief Sets and checks options for netwrite; saves the network - */ -class NWFrame { -public: - /// @brief Inserts options used by the network writer - static void fillOptions(bool forNetgen); - - /** @brief Checks set options from the OptionsCont-singleton for being valid - * @return Whether needed options are set and have proper values - */ - static bool checkOptions(); - - /// @brief Writes the network stored in the given net builder - static void writeNetwork(const OptionsCont& oc, NBNetBuilder& nb); - - /// @brief Writes the given position to device in long format (one attribute per dimension) - static void writePositionLong(const Position& pos, OutputDevice& dev); - -}; diff --git a/Util/OSM2ODR/src/netwrite/NWWriter_Amitran.cpp b/Util/OSM2ODR/src/netwrite/NWWriter_Amitran.cpp deleted file mode 100644 index 9eb7ac91c..000000000 --- a/Util/OSM2ODR/src/netwrite/NWWriter_Amitran.cpp +++ /dev/null @@ -1,134 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2014-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NWWriter_Amitran.cpp -/// @author Michael Behrisch -/// @date 13.03.2014 -/// -// Exporter writing networks using the Amitran format -/****************************************************************************/ -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include "NWWriter_DlrNavteq.h" -#include "NWWriter_Amitran.h" - - - -// =========================================================================== -// method definitions -// =========================================================================== -// --------------------------------------------------------------------------- -// static methods -// --------------------------------------------------------------------------- -void -NWWriter_Amitran::writeNetwork(const OptionsCont& oc, NBNetBuilder& nb) { - // check whether an amitran-file shall be generated - if (!oc.isSet("amitran-output")) { - return; - } - NBEdgeCont& ec = nb.getEdgeCont(); - OutputDevice& device = OutputDevice::getDevice(oc.getString("amitran-output")); - device << "\n"; - device << "\n"; - // write nodes - int index = 0; - NBNodeCont& nc = nb.getNodeCont(); - std::set singleRoundaboutNodes; - std::set multiRoundaboutNodes; - const std::set& roundabouts = ec.getRoundabouts(); - for (std::set::const_iterator i = roundabouts.begin(); i != roundabouts.end(); ++i) { - for (EdgeSet::const_iterator j = (*i).begin(); j != (*i).end(); ++j) { - if ((*j)->getNumLanes() > 1) { - multiRoundaboutNodes.insert((*j)->getFromNode()); - } else { - singleRoundaboutNodes.insert((*j)->getFromNode()); - } - } - } - std::map nodeIds; - for (std::map::const_iterator i = nc.begin(); i != nc.end(); ++i) { - device << " second] = index++; - if (singleRoundaboutNodes.count(i->second) > 0) { - device << "\" type=\"roundaboutSingle\"/>\n"; - continue; - } - if (multiRoundaboutNodes.count(i->second) > 0) { - device << "\" type=\"roundaboutMulti\"/>\n"; - continue; - } - switch (i->second->getType()) { - case SumoXMLNodeType::TRAFFIC_LIGHT: - case SumoXMLNodeType::TRAFFIC_LIGHT_NOJUNCTION: - case SumoXMLNodeType::TRAFFIC_LIGHT_RIGHT_ON_RED: - device << "\" type=\"trafficLight"; - break; - case SumoXMLNodeType::PRIORITY: - device << "\" type=\"priority"; - break; - case SumoXMLNodeType::PRIORITY_STOP: - device << "\" type=\"priorityStop"; - break; - case SumoXMLNodeType::RIGHT_BEFORE_LEFT: - device << "\" type=\"rightBeforeLeft"; - break; - case SumoXMLNodeType::ALLWAY_STOP: - device << "\" type=\"allwayStop"; - break; - case SumoXMLNodeType::ZIPPER: - device << "\" type=\"zipper"; - break; - case SumoXMLNodeType::RAIL_SIGNAL: - device << "\" type=\"railSignal"; - break; - case SumoXMLNodeType::RAIL_CROSSING: - device << "\" type=\"railCrossing"; - break; - case SumoXMLNodeType::DEAD_END: - case SumoXMLNodeType::DEAD_END_DEPRECATED: - device << "\" type=\"deadEnd"; - break; - case SumoXMLNodeType::DISTRICT: - case SumoXMLNodeType::NOJUNCTION: - case SumoXMLNodeType::INTERNAL: - case SumoXMLNodeType::UNKNOWN: - break; - } - device << "\"/>\n"; - } - // write edges - index = 0; - for (std::map::const_iterator i = ec.begin(); i != ec.end(); ++i) { - device << " second->getFromNode()] - << "\" to=\"" << nodeIds[i->second->getToNode()] - << "\" roadClass=\"" << NWWriter_DlrNavteq::getRoadClass((*i).second) - << "\" length=\"" << int(1000 * i->second->getLoadedLength()) - << "\" speedLimitKmh=\"" << int(3.6 * (*i).second->getSpeed() + 0.5) - << "\" laneNr=\"" << (*i).second->getNumLanes() - << "\"/>\n"; - } - device << "\n"; - device.close(); -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netwrite/NWWriter_Amitran.h b/Util/OSM2ODR/src/netwrite/NWWriter_Amitran.h deleted file mode 100644 index f6e4ff9b5..000000000 --- a/Util/OSM2ODR/src/netwrite/NWWriter_Amitran.h +++ /dev/null @@ -1,48 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2014-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NWWriter_Amitran.h -/// @author Michael Behrisch -/// @date 13.03.2014 -/// -// Exporter writing networks using the Amitran format -/****************************************************************************/ -#pragma once -#include - - -// =========================================================================== -// class declarations -// =========================================================================== -class NBNetBuilder; -class OptionsCont; - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NWWriter_Amitran - * @brief Exporter writing networks using the Amitran format - * - */ -class NWWriter_Amitran { -public: - /** @brief Writes the network into a Amitran-file - * - * @param[in] oc The options to use - * @param[in] nb The network builder to fill - */ - static void writeNetwork(const OptionsCont& oc, NBNetBuilder& nb); - -}; diff --git a/Util/OSM2ODR/src/netwrite/NWWriter_DlrNavteq.cpp b/Util/OSM2ODR/src/netwrite/NWWriter_DlrNavteq.cpp deleted file mode 100644 index 0139935d4..000000000 --- a/Util/OSM2ODR/src/netwrite/NWWriter_DlrNavteq.cpp +++ /dev/null @@ -1,557 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2012-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NWWriter_DlrNavteq.cpp -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date 26.10.2012 -/// -// Exporter writing networks using DlrNavteq (Elmar) format -/****************************************************************************/ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "NWFrame.h" -#include "NWWriter_DlrNavteq.h" - - -// --------------------------------------------------------------------------- -// static members -// --------------------------------------------------------------------------- -const std::string NWWriter_DlrNavteq::UNDEFINED("-1"); - -// --------------------------------------------------------------------------- -// static methods -// --------------------------------------------------------------------------- -void -NWWriter_DlrNavteq::writeNetwork(const OptionsCont& oc, NBNetBuilder& nb) { - // check whether a matsim-file shall be generated - if (!oc.isSet("dlr-navteq-output")) { - return; - } - std::map internalNodes; - writeNodesUnsplitted(oc, nb.getNodeCont(), nb.getEdgeCont(), internalNodes); - writeLinksUnsplitted(oc, nb.getEdgeCont(), internalNodes); - writeTrafficSignals(oc, nb.getNodeCont()); - writeProhibitedManoeuvres(oc, nb.getNodeCont(), nb.getEdgeCont()); - writeConnectedLanes(oc, nb.getNodeCont()); -} - - -void NWWriter_DlrNavteq::writeHeader(OutputDevice& device, const OptionsCont& oc) { - device << "# Format matches Extraction version: V6.5 \n"; - std::stringstream tmp; - oc.writeConfiguration(tmp, true, false, false); - tmp.seekg(std::ios_base::beg); - std::string line; - while (!tmp.eof()) { - std::getline(tmp, line); - device << "# " << line << "\n"; - } - device << "#\n"; -} - -void -NWWriter_DlrNavteq::writeNodesUnsplitted(const OptionsCont& oc, NBNodeCont& nc, NBEdgeCont& ec, std::map& internalNodes) { - // For "real" nodes we simply use the node id. - // For internal nodes (geometry vectors describing edge geometry in the parlance of this format) - // we use the id of the edge and do not bother with - // compression (each direction gets its own internal node). - OutputDevice& device = OutputDevice::getDevice(oc.getString("dlr-navteq-output") + "_nodes_unsplitted.txt"); - writeHeader(device, oc); - const GeoConvHelper& gch = GeoConvHelper::getFinal(); - const bool haveGeo = gch.usingGeoProjection(); - const double geoScale = pow(10.0f, haveGeo ? 5 : 2); // see NIImporter_DlrNavteq::GEO_SCALE - device.setPrecision(oc.getInt("dlr-navteq.precision")); - if (!haveGeo) { - WRITE_WARNING("DlrNavteq node data will be written in (floating point) cartesian coordinates"); - } - // write format specifier - device << "# NODE_ID\tIS_BETWEEN_NODE\tamount_of_geocoordinates\tx1\ty1\t[x2 y2 ... xn yn]\n"; - // write header - Boundary boundary = gch.getConvBoundary(); - Position min(boundary.xmin(), boundary.ymin()); - Position max(boundary.xmax(), boundary.ymax()); - gch.cartesian2geo(min); - min.mul(geoScale); - gch.cartesian2geo(max); - max.mul(geoScale); - int multinodes = 0; - for (std::map::const_iterator i = ec.begin(); i != ec.end(); ++i) { - if ((*i).second->getGeometry().size() > 2) { - multinodes++; - } - } - device << "# [xmin_region] " << min.x() << "\n"; - device << "# [xmax_region] " << max.x() << "\n"; - device << "# [ymin_region] " << min.y() << "\n"; - device << "# [ymax_region] " << max.y() << "\n"; - device << "# [elements_multinode] " << multinodes << "\n"; - device << "# [elements_normalnode] " << nc.size() << "\n"; - device << "# [xmin] " << min.x() << "\n"; - device << "# [xmax] " << max.x() << "\n"; - device << "# [ymin] " << min.y() << "\n"; - device << "# [ymax] " << max.y() << "\n"; - // write normal nodes - for (std::map::const_iterator i = nc.begin(); i != nc.end(); ++i) { - NBNode* n = (*i).second; - Position pos = n->getPosition(); - gch.cartesian2geo(pos); - pos.mul(geoScale); - device << n->getID() << "\t0\t1\t" << pos.x() << "\t" << pos.y() << "\n"; - } - // write "internal" nodes - std::vector avoid; - std::set reservedNodeIDs; - const bool numericalIDs = oc.getBool("numerical-ids"); - if (oc.isSet("reserved-ids")) { - NBHelpers::loadPrefixedIDsFomFile(oc.getString("reserved-ids"), "node:", reservedNodeIDs); // backward compatibility - NBHelpers::loadPrefixedIDsFomFile(oc.getString("reserved-ids"), "junction:", reservedNodeIDs); // selection format - } - if (numericalIDs) { - avoid = nc.getAllNames(); - std::vector avoid2 = ec.getAllNames(); - avoid.insert(avoid.end(), avoid2.begin(), avoid2.end()); - avoid.insert(avoid.end(), reservedNodeIDs.begin(), reservedNodeIDs.end()); - } - IDSupplier idSupplier("", avoid); - for (std::map::const_iterator i = ec.begin(); i != ec.end(); ++i) { - NBEdge* e = (*i).second; - PositionVector geom = e->getGeometry(); - if (geom.size() > 2) { - // the import NIImporter_DlrNavteq checks for the presence of a - // negated edge id to determine spread type. We may need to do some - // shifting to make this consistent - const bool hasOppositeID = ec.getOppositeByID(e->getID()) != nullptr; - if (e->getLaneSpreadFunction() == LaneSpreadFunction::RIGHT && !hasOppositeID) { - // need to write center-line geometry instead - try { - geom.move2side(e->getTotalWidth() / 2); - } catch (InvalidArgument& exception) { - WRITE_WARNING("Could not reconstruct shape for edge:'" + e->getID() + "' (" + exception.what() + ")."); - } - } else if (e->getLaneSpreadFunction() == LaneSpreadFunction::CENTER && hasOppositeID) { - // need to write left-border geometry instead - try { - geom.move2side(-e->getTotalWidth() / 2); - } catch (InvalidArgument& exception) { - WRITE_WARNING("Could not reconstruct shape for edge:'" + e->getID() + "' (" + exception.what() + ")."); - } - } - - std::string internalNodeID = e->getID(); - if (internalNodeID == UNDEFINED - || (nc.retrieve(internalNodeID) != nullptr) - || reservedNodeIDs.count(internalNodeID) > 0 - ) { - // need to invent a new name to avoid clashing with the id of a 'real' node or a reserved name - if (numericalIDs) { - internalNodeID = idSupplier.getNext(); - } else { - internalNodeID += "_geometry"; - } - } - internalNodes[e] = internalNodeID; - device << internalNodeID << "\t1\t" << geom.size() - 2; - for (int ii = 1; ii < (int)geom.size() - 1; ++ii) { - Position pos = geom[(int)ii]; - gch.cartesian2geo(pos); - pos.mul(geoScale); - device << "\t" << pos.x() << "\t" << pos.y(); - } - device << "\n"; - } - } - device.close(); -} - - -void -NWWriter_DlrNavteq::writeLinksUnsplitted(const OptionsCont& oc, NBEdgeCont& ec, std::map& internalNodes) { - std::map nameIDs; - OutputDevice& device = OutputDevice::getDevice(oc.getString("dlr-navteq-output") + "_links_unsplitted.txt"); - writeHeader(device, oc); - // write format specifier - device << "# LINK_ID\tNODE_ID_FROM\tNODE_ID_TO\tBETWEEN_NODE_ID\tLENGTH\tVEHICLE_TYPE\tFORM_OF_WAY\tBRUNNEL_TYPE\tFUNCTIONAL_ROAD_CLASS\tSPEED_CATEGORY\tNUMBER_OF_LANES\tSPEED_LIMIT\tSPEED_RESTRICTION\tNAME_ID1_REGIONAL\tNAME_ID2_LOCAL\tHOUSENUMBERS_RIGHT\tHOUSENUMBERS_LEFT\tZIP_CODE\tAREA_ID\tSUBAREA_ID\tTHROUGH_TRAFFIC\tSPECIAL_RESTRICTIONS\tEXTENDED_NUMBER_OF_LANES\tISRAMP\tCONNECTION\n"; - // write edges - for (std::map::const_iterator i = ec.begin(); i != ec.end(); ++i) { - NBEdge* e = (*i).second; - const int kph = speedInKph(e->getSpeed()); - const std::string& betweenNodeID = (e->getGeometry().size() > 2) ? internalNodes[e] : UNDEFINED; - std::string nameID = UNDEFINED; - std::string nameIDRegional = UNDEFINED; - if (oc.getBool("output.street-names")) { - const std::string& name = e->getStreetName(); - if (name != "") { - if (nameIDs.count(name) == 0) { - nameIDs[name] = toString(nameIDs.size()); - } - nameID = nameIDs[name]; - } - const std::string& name2 = e->getParameter("ref", ""); - if (name2 != "") { - if (nameIDs.count(name2) == 0) { - nameIDs[name2] = toString(nameIDs.size()); - } - nameIDRegional = nameIDs[name2]; - } - } - device << e->getID() << "\t" - << e->getFromNode()->getID() << "\t" - << e->getToNode()->getID() << "\t" - << betweenNodeID << "\t" - << getGraphLength(e) << "\t" - << getAllowedTypes(e->getPermissions()) << "\t" - << getFormOfWay(e) << "\t" - << getBrunnelType(e) << "\t" - << getRoadClass(e) << "\t" - << getSpeedCategory(kph) << "\t" - << getNavteqLaneCode(e->getNumLanes()) << "\t" - << getSpeedCategoryUpperBound(kph) << "\t" - << kph << "\t" - << nameIDRegional << "\t" - << nameID << "\t" // NAME_ID2_LOCAL - << UNDEFINED << "\t" // housenumbers_right - << UNDEFINED << "\t" // housenumbers_left - << getSinglePostalCode(e->getParameter("postal_code", UNDEFINED), e->getID()) << "\t" // ZIP_CODE - << UNDEFINED << "\t" // AREA_ID - << UNDEFINED << "\t" // SUBAREA_ID - << "1\t" // through_traffic (allowed) - << UNDEFINED << "\t" // special_restrictions - << UNDEFINED << "\t" // extended_number_of_lanes - << UNDEFINED << "\t" // isRamp - << "0\t" // connection (between nodes always in order) - << "\n"; - } - if (oc.getBool("output.street-names")) { - OutputDevice& namesDevice = OutputDevice::getDevice(oc.getString("dlr-navteq-output") + "_names.txt"); - writeHeader(namesDevice, oc); - // write format specifier - namesDevice << "# NAME_ID\tPERMANENT_ID_INFO\tName\n"; - namesDevice << "# [elements] " << nameIDs.size() << "\n"; - for (std::map::const_iterator i = nameIDs.begin(); i != nameIDs.end(); ++i) { - namesDevice - << i->second << "\t" - << 0 << "\t" - << i->first << "\n"; - } - namesDevice.close(); - } - device.close(); -} - - -std::string -NWWriter_DlrNavteq::getAllowedTypes(SVCPermissions permissions) { - if (permissions == SVCAll) { - return "100000000000"; - } - std::ostringstream oss; - oss << "0"; - oss << ((permissions & SVC_PASSENGER) > 0 ? 1 : 0); - oss << ((permissions & SVC_PASSENGER) > 0 ? 1 : 0); // residential - oss << ((permissions & SVC_HOV) > 0 ? 1 : 0); - oss << ((permissions & SVC_EMERGENCY) > 0 ? 1 : 0); - oss << ((permissions & SVC_TAXI) > 0 ? 1 : 0); - oss << ((permissions & (SVC_BUS | SVC_COACH)) > 0 ? 1 : 0); - oss << ((permissions & SVC_DELIVERY) > 0 ? 1 : 0); - oss << ((permissions & (SVC_TRUCK | SVC_TRAILER)) > 0 ? 1 : 0); - oss << ((permissions & SVC_MOTORCYCLE) > 0 ? 1 : 0); - oss << ((permissions & SVC_BICYCLE) > 0 ? 1 : 0); - oss << ((permissions & SVC_PEDESTRIAN) > 0 ? 1 : 0); - return oss.str(); -} - - -int -NWWriter_DlrNavteq::getRoadClass(NBEdge* edge) { - // quoting the navteq manual: - // As a general rule, Functional Road Class assignments have no direct - // correlation with other road attributes like speed, controlled access, route type, etc. - // if the network is based on OSM, we can use the highway types for determining FRC - std::string type = edge->getTypeID(); - if (StringUtils::startsWith(type, "highway.")) { - type = type.substr(8); - } - if (StringUtils::startsWith(type, "motorway")) { - return 0; - } else if (StringUtils::startsWith(type, "trunk")) { - return 1; - } else if (StringUtils::startsWith(type, "primary")) { - return 1; - } else if (StringUtils::startsWith(type, "secondary")) { - return 2; - } else if (StringUtils::startsWith(type, "tertiary")) { - return 3; - } else if (type == "unclassified") { - return 3; - } else if (type == "living_street" || type == "residential" || type == "road" || type == "service" || type == "track" || type == "cycleway" || type == "path" || type == "footway") { - return 4; - } - // as a fallback we do a simple speed / lane-count mapping anyway - // the resulting functional road class layers probably won't be connected as required - const int kph = speedInKph(edge->getSpeed()); - if ((kph) > 100) { - return 0; - } - if ((kph) > 70) { - return 1; - } - if ((kph) > 50) { - return (edge->getNumLanes() > 1 ? 2 : 3); - } - if ((kph) > 30) { - return 3; - } - return 4; -} - - -int -NWWriter_DlrNavteq::getSpeedCategory(int kph) { - if ((kph) > 130) { - return 1; - } - if ((kph) > 100) { - return 2; - } - if ((kph) > 90) { - return 3; - } - if ((kph) > 70) { - return 4; - } - if ((kph) > 50) { - return 5; - } - if ((kph) > 30) { - return 6; - } - if ((kph) > 10) { - return 7; - } - return 8; -} - - -int -NWWriter_DlrNavteq::getSpeedCategoryUpperBound(int kph) { - if ((kph) > 130) { - return 131; - } - if ((kph) > 100) { - return 130; - } - if ((kph) > 90) { - return 100; - } - if ((kph) > 70) { - return 90; - } - if ((kph) > 50) { - return 70; - } - if ((kph) > 30) { - return 50; - } - if ((kph) > 10) { - return 30; - } - return 10; -} - - -int -NWWriter_DlrNavteq::getNavteqLaneCode(const int numLanes) { - const int code = (numLanes == 1 ? 1 : - (numLanes < 4 ? 2 : 3)); - return numLanes * 10 + code; -} - - -int -NWWriter_DlrNavteq::getBrunnelType(NBEdge* edge) { - if (edge->knowsParameter("bridge")) { - return 1; - } else if (edge->knowsParameter("tunnel")) { - return 4; - } else if (edge->getTypeID() == "route.ferry") { - return 10; - } - return -1; // UNDEFINED -} - - -int -NWWriter_DlrNavteq::getFormOfWay(NBEdge* edge) { - if (edge->getPermissions() == SVC_PEDESTRIAN) { - return 15; - } else if (edge->getJunctionPriority(edge->getToNode()) == NBEdge::JunctionPriority::ROUNDABOUT) { - return 4; - } else if (edge->getTypeID() == "highway.service") { - return 14; - } else if (edge->getTypeID().find("_link") != std::string::npos) { - return 10; - } - return 3; // speed category 1-8; -} - - -double -NWWriter_DlrNavteq::getGraphLength(NBEdge* edge) { - PositionVector geom = edge->getGeometry(); - geom.push_back_noDoublePos(edge->getToNode()->getPosition()); - geom.push_front_noDoublePos(edge->getFromNode()->getPosition()); - return geom.length(); -} - - -std::string -NWWriter_DlrNavteq::getSinglePostalCode(const std::string& zipCode, const std::string edgeID) { - // might be multiple codes - if (zipCode.find_first_of(" ,;") != std::string::npos) { - WRITE_WARNING("ambiguous zip code '" + zipCode + "' for edge '" + edgeID + "'. (using first value)"); - StringTokenizer st(zipCode, " ,;", true); - std::vector ret = st.getVector(); - return ret[0]; - } else if (zipCode.size() > 16) { - WRITE_WARNING("long zip code '" + zipCode + "' for edge '" + edgeID + "'"); - } - return zipCode; -} - -void -NWWriter_DlrNavteq::writeTrafficSignals(const OptionsCont& oc, NBNodeCont& nc) { - OutputDevice& device = OutputDevice::getDevice(oc.getString("dlr-navteq-output") + "_traffic_signals.txt"); - writeHeader(device, oc); - const GeoConvHelper& gch = GeoConvHelper::getFinal(); - const bool haveGeo = gch.usingGeoProjection(); - const double geoScale = pow(10.0f, haveGeo ? 5 : 2); // see NIImporter_DlrNavteq::GEO_SCALE - device.setPrecision(oc.getInt("dlr-navteq.precision")); - // write format specifier - device << "#Traffic signal related to LINK_ID and NODE_ID with location relative to driving direction.\n#column format like pointcollection.\n#DESCRIPTION->LOCATION: 1-rechts von LINK; 2-links von LINK; 3-oberhalb LINK -1-keineAngabe\n#RELATREC_ID\tPOICOL_TYPE\tDESCRIPTION\tLONGITUDE\tLATITUDE\tLINK_ID\n"; - // write record for every edge incoming to a tls controlled node - for (std::map::const_iterator i = nc.begin(); i != nc.end(); ++i) { - NBNode* n = (*i).second; - if (n->isTLControlled()) { - Position pos = n->getPosition(); - gch.cartesian2geo(pos); - pos.mul(geoScale); - const EdgeVector& incoming = n->getIncomingEdges(); - for (EdgeVector::const_iterator it = incoming.begin(); it != incoming.end(); ++it) { - NBEdge* e = *it; - device << e->getID() << "\t" - << "12\t" // POICOL_TYPE - << "LSA;NODEIDS#" << n->getID() << "#;LOCATION#-1#;\t" - << pos.x() << "\t" - << pos.y() << "\t" - << e->getID() << "\n"; - } - } - } - device.close(); -} - - -void -NWWriter_DlrNavteq::writeProhibitedManoeuvres(const OptionsCont& oc, const NBNodeCont& nc, const NBEdgeCont& ec) { - OutputDevice& device = OutputDevice::getDevice(oc.getString("dlr-navteq-output") + "_prohibited_manoeuvres.txt"); - writeHeader(device, oc); - // need to invent id for relation - std::set reservedRelIDs; - if (oc.isSet("reserved-ids")) { - NBHelpers::loadPrefixedIDsFomFile(oc.getString("reserved-ids"), "rel:", reservedRelIDs); - } - std::vector avoid = ec.getAllNames(); // already used for tls RELATREC_ID - avoid.insert(avoid.end(), reservedRelIDs.begin(), reservedRelIDs.end()); - IDSupplier idSupplier("", avoid); // @note: use a global relRecIDsupplier if this is used more often - // write format specifier - device << "#No driving allowed from ID1 to ID2 or the complete chain from ID1 to IDn\n"; - device << "#RELATREC_ID\tPERMANENT_ID_INFO\tVALIDITY_PERIOD\tTHROUGH_TRAFFIC\tVEHICLE_TYPE\tNAVTEQ_LINK_ID1\t[NAVTEQ_LINK_ID2 ...]\n"; - // write record for every pair of incoming/outgoing edge that are not connected despite having common permissions - for (std::map::const_iterator i = nc.begin(); i != nc.end(); ++i) { - NBNode* n = (*i).second; - const EdgeVector& incoming = n->getIncomingEdges(); - const EdgeVector& outgoing = n->getOutgoingEdges(); - for (EdgeVector::const_iterator j = incoming.begin(); j != incoming.end(); ++j) { - NBEdge* inEdge = *j; - const SVCPermissions inPerm = inEdge->getPermissions(); - for (EdgeVector::const_iterator k = outgoing.begin(); k != outgoing.end(); ++k) { - NBEdge* outEdge = *k; - const SVCPermissions outPerm = outEdge->getPermissions(); - const SVCPermissions commonPerm = inPerm & outPerm; - if (commonPerm != 0 && commonPerm != SVC_PEDESTRIAN && !inEdge->isConnectedTo(outEdge)) { - device - << idSupplier.getNext() << "\t" - << 1 << "\t" // permanent id - << UNDEFINED << "\t" - << 1 << "\t" - << getAllowedTypes(SVCAll) << "\t" - << inEdge->getID() << "\t" << outEdge->getID() << "\n"; - } - } - } - } - device.close(); -} - - -void -NWWriter_DlrNavteq::writeConnectedLanes(const OptionsCont& oc, NBNodeCont& nc) { - OutputDevice& device = OutputDevice::getDevice(oc.getString("dlr-navteq-output") + "_connected_lanes.txt"); - writeHeader(device, oc); - // write format specifier - device << "#Lane connections related to LINK-IDs and NODE-ID.\n"; - device << "#column format like pointcollection.\n"; - device << "#NODE-ID\tVEHICLE-TYPE\tFROM_LANE\tTO_LANE\tTHROUGH_TRAFFIC\tLINK_IDs[2..*]\n"; - // write record for every connection - for (std::map::const_iterator i = nc.begin(); i != nc.end(); ++i) { - NBNode* n = (*i).second; - const EdgeVector& incoming = n->getIncomingEdges(); - for (EdgeVector::const_iterator j = incoming.begin(); j != incoming.end(); ++j) { - NBEdge* from = *j; - const SVCPermissions fromPerm = from->getPermissions(); - const std::vector& connections = from->getConnections(); - for (std::vector::const_iterator it_c = connections.begin(); it_c != connections.end(); it_c++) { - const NBEdge::Connection& c = *it_c; - device - << n->getID() << "\t" - << getAllowedTypes(fromPerm & c.toEdge->getPermissions()) << "\t" - << c.fromLane + 1 << "\t" // one-based - << c.toLane + 1 << "\t" // one-based - << 1 << "\t" // no information regarding permissibility of through traffic - << from->getID() << "\t" - << c.toEdge->getID() << "\t" - << "\n"; - } - } - } - device.close(); -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netwrite/NWWriter_DlrNavteq.h b/Util/OSM2ODR/src/netwrite/NWWriter_DlrNavteq.h deleted file mode 100644 index 656fa30e9..000000000 --- a/Util/OSM2ODR/src/netwrite/NWWriter_DlrNavteq.h +++ /dev/null @@ -1,131 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2012-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NWWriter_DlrNavteq.h -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date 26.10.2012 -/// -// Exporter writing networks using DlrNavteq (Elmar) format -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include -#include - - -// =========================================================================== -// class declarations -// =========================================================================== -class NBEdge; -class NBEdgeCont; -class NBNetBuilder; -class NBNode; -class NBNodeCont; -class NBTrafficLightLogicCont; -class NBTypeCont; -class OptionsCont; - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NWWriter_DlrNavteq - * @brief Exporter writing networks using XML (native input) format - * - */ -class NWWriter_DlrNavteq { -public: - /** @brief Writes the network into XML-files (nodes, edges, connections, - * traffic lights) - * @param[in] oc The options to use - * @param[in] nb The network builder from which to read data - */ - static void writeNetwork(const OptionsCont& oc, NBNetBuilder& nb); - - /// @brief get the navteq road class - static int getRoadClass(NBEdge* edge); - - /// @brief get the navteq brunnel type - static int getBrunnelType(NBEdge* edge); - - /// @brief get the form of way - static int getFormOfWay(NBEdge* edge); - -private: - /** @brief Writes the nodes_unsplitted file - * @param[in] oc The options to use - * @param[in] nc The node-container from which to read data - * @param[in] ec The edge-container from which to read data - * @param[out] internalNodes The internal node ids, generated for edges with complex geometry - */ - static void writeNodesUnsplitted(const OptionsCont& oc, NBNodeCont& nc, NBEdgeCont& ec, std::map& internalNodes); - - /** @brief Writes the links_unsplitted file - * @param[in] oc The options to use - * @param[in] ec The edge-container from which to read data - * @param[int] internalNodes The internal node ids, generated for edges with complex geometry - */ - static void writeLinksUnsplitted(const OptionsCont& oc, NBEdgeCont& ec, std::map& internalNodes); - - /** @brief Writes the traffic_signals file - * @param[in] oc The options to use - * @param[in] nc The node-container from which to read data - */ - static void writeTrafficSignals(const OptionsCont& oc, NBNodeCont& nc); - - - /** @brief Writes the prohibited_manoeuvres file - * @param[in] oc The options to use - * @param[in] nc The node-container from which to read data - */ - static void writeProhibitedManoeuvres(const OptionsCont& oc, const NBNodeCont& nc, const NBEdgeCont& ec); - - /** @brief Writes the connected_lanes file - * @param[in] oc The options to use - * @param[in] nc The node-container from which to read data - */ - static void writeConnectedLanes(const OptionsCont& oc, NBNodeCont& nc); - - /// @brief write header comments (input paramters, date, etc...) - static void writeHeader(OutputDevice& device, const OptionsCont& oc); - - /// @brief build the ascii-bit-vector for column vehicle_type - static std::string getAllowedTypes(SVCPermissions permissions); - - /// @brief get the navteq speed class based on the speed in km/h - static int getSpeedCategory(int kph); - - /// @brief get the SPEED_LIMIT as defined by elmar (upper bound of speed category) - static int getSpeedCategoryUpperBound(int kph); - - /// @brief get the lane number encoding - static int getNavteqLaneCode(const int numLanes); - - /// @brief get the length of the edge when measured up to the junction center - static double getGraphLength(NBEdge* edge); - - static std::string getSinglePostalCode(const std::string& zipCode, const std::string edgeID); - - /// @brief magic value for undefined stuff - static const std::string UNDEFINED; - - /// @brief get edge speed rounded to kmh - static inline int speedInKph(double metersPerSecond) { - return (int)std::floor(metersPerSecond * 3.6 + 0.5); - } -}; diff --git a/Util/OSM2ODR/src/netwrite/NWWriter_MATSim.cpp b/Util/OSM2ODR/src/netwrite/NWWriter_MATSim.cpp deleted file mode 100644 index f361d2b91..000000000 --- a/Util/OSM2ODR/src/netwrite/NWWriter_MATSim.cpp +++ /dev/null @@ -1,80 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NWWriter_MATSim.cpp -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Tue, 04.05.2011 -/// -// Exporter writing networks using the MATSim format -/****************************************************************************/ -#include -#include "NWWriter_MATSim.h" -#include -#include -#include -#include -#include -#include -#include -#include - - - -// =========================================================================== -// method definitions -// =========================================================================== -// --------------------------------------------------------------------------- -// static methods -// --------------------------------------------------------------------------- -void -NWWriter_MATSim::writeNetwork(const OptionsCont& oc, NBNetBuilder& nb) { - // check whether a matsim-file shall be generated - if (!oc.isSet("matsim-output")) { - return; - } - OutputDevice& device = OutputDevice::getDevice(oc.getString("matsim-output")); - device << "\n"; - device << "\n\n"; - device << "\n"; // !!! name - // write nodes - device << " \n"; - NBNodeCont& nc = nb.getNodeCont(); - for (std::map::const_iterator i = nc.begin(); i != nc.end(); ++i) { - device << " getPosition().x() - << "\" y=\"" << (*i).second->getPosition().y() - << "\"/>\n"; - } - device << " \n"; - // write edges - device << " \n"; - NBEdgeCont& ec = nb.getEdgeCont(); - for (std::map::const_iterator i = ec.begin(); i != ec.end(); ++i) { - device << " getFromNode()->getID() - << "\" to=\"" << (*i).second->getToNode()->getID() - << "\" length=\"" << (*i).second->getLoadedLength() - << "\" capacity=\"" << (oc.getFloat("lanes-from-capacity.norm") * (*i).second->getNumLanes()) - << "\" freespeed=\"" << (*i).second->getSpeed() - << "\" permlanes=\"" << (*i).second->getNumLanes() - << "\"/>\n"; - } - device << " \n"; - // - device << "\n"; // !!! name - device.close(); -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netwrite/NWWriter_MATSim.h b/Util/OSM2ODR/src/netwrite/NWWriter_MATSim.h deleted file mode 100644 index c9ba45695..000000000 --- a/Util/OSM2ODR/src/netwrite/NWWriter_MATSim.h +++ /dev/null @@ -1,60 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NWWriter_MATSim.h -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Tue, 04.05.2011 -/// -// Exporter writing networks using the MATSim format -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include -#include - - -// =========================================================================== -// class declarations -// =========================================================================== -class NBEdge; -class NBEdgeCont; -class NBNetBuilder; -class NBNode; -class NBNodeCont; -class NBTrafficLightLogicCont; -class NBTypeCont; -class OptionsCont; - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NWWriter_MATSim - * @brief Exporter writing networks using the MATSim format - * - */ -class NWWriter_MATSim { -public: - /** @brief Writes the network into a MATSim-file - * - * @param[in] oc The options to use - * @param[in] nb The network builder to fill - */ - static void writeNetwork(const OptionsCont& oc, NBNetBuilder& nb); - -}; diff --git a/Util/OSM2ODR/src/netwrite/NWWriter_OpenDrive.cpp b/Util/OSM2ODR/src/netwrite/NWWriter_OpenDrive.cpp deleted file mode 100644 index f0bf7a5c4..000000000 --- a/Util/OSM2ODR/src/netwrite/NWWriter_OpenDrive.cpp +++ /dev/null @@ -1,946 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2011-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NWWriter_OpenDrive.cpp -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @date Tue, 04.05.2011 -/// -// Exporter writing networks using the openDRIVE format -/****************************************************************************/ -#include - -#include -#include "NWWriter_OpenDrive.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#define INVALID_ID -1 - -//#define DEBUG_SMOOTH_GEOM -#define DEBUGCOND true - -#define MIN_TURN_DIAMETER 2.0 - - -// =========================================================================== -// method definitions -// =========================================================================== -// --------------------------------------------------------------------------- -// static methods -// --------------------------------------------------------------------------- -void -NWWriter_OpenDrive::writeNetwork(const OptionsCont& oc, NBNetBuilder& nb) { - // check whether an opendrive-file shall be generated - if (!oc.isSet("opendrive-output")) { - return; - } - const NBNodeCont& nc = nb.getNodeCont(); - const NBEdgeCont& ec = nb.getEdgeCont(); - const bool origNames = oc.getBool("output.original-names"); - const bool lefthand = oc.getBool("lefthand"); - const double straightThresh = DEG2RAD(oc.getFloat("opendrive-output.straight-threshold")); - // some internal mapping containers - int nodeID = 1; - int edgeID = nc.size() * 10; // distinct from node ids - StringBijection edgeMap; - StringBijection nodeMap; - // - OutputDevice_String device; - device << "\n"; - device.openTag("OpenDRIVE"); - time_t now = time(nullptr); - std::string dstr(ctime(&now)); - const Boundary& b = GeoConvHelper::getFinal().getConvBoundary(); - // write header - device.openTag("header"); - device.writeAttr("revMajor", "1"); - device.writeAttr("revMinor", "4"); - device.writeAttr("name", ""); - device.writeAttr("version", "1.00"); - device.writeAttr("date", dstr.substr(0, dstr.length() - 1)); - device.writeAttr("north", b.ymax()); - device.writeAttr("south", b.ymin()); - device.writeAttr("east", b.xmax()); - device.writeAttr("west", b.xmin()); - /* @note obsolete in 1.4 - device.writeAttr("maxRoad", ec.size()); - device.writeAttr("maxJunc", nc.size()); - device.writeAttr("maxPrg", 0); - */ - // write optional geo reference - const GeoConvHelper& gch = GeoConvHelper::getFinal(); - if (gch.usingGeoProjection()) { - if (gch.getOffsetBase() == Position(0, 0)) { - device.openTag("geoReference"); - device.writePreformattedTag(" \n"); - device.closeTag(); - } else { - WRITE_WARNING("Could not write OpenDRIVE geoReference. Only unshifted Coordinate systems are supported (center_map and use_offsets need to be set to False)"); - } - } - device.closeTag(); - - // write normal edges (road) - for (std::map::const_iterator i = ec.begin(); i != ec.end(); ++i) { - const NBEdge* e = (*i).second; - const int fromNodeID = e->getIncomingEdges().size() > 0 ? getID(e->getFromNode()->getID(), nodeMap, nodeID) : INVALID_ID; - const int toNodeID = e->getConnections().size() > 0 ? getID(e->getToNode()->getID(), nodeMap, nodeID) : INVALID_ID; - writeNormalEdge(device, e, - getID(e->getID(), edgeMap, edgeID), - fromNodeID, toNodeID, - origNames, straightThresh, - nb.getShapeCont()); - } - device.lf(); - - // write junction-internal edges (road). In OpenDRIVE these are called 'paths' or 'connecting roads' - OutputDevice_String junctionOSS(3); - for (std::map::const_iterator i = nc.begin(); i != nc.end(); ++i) { - NBNode* n = (*i).second; - int connectionID = 0; // unique within a junction - const int nID = getID(n->getID(), nodeMap, nodeID); - if (n->numNormalConnections() > 0) { - junctionOSS << " getID() << "\" id=\"" << nID << "\">\n"; - } - std::vector incoming = (*i).second->getIncomingEdges(); - if (lefthand) { - std::reverse(incoming.begin(), incoming.end()); - } - for (NBEdge* inEdge : incoming) { - std::string centerMark = "none"; - const int inEdgeID = getID(inEdge->getID(), edgeMap, edgeID); - // group parallel edges - const NBEdge* outEdge = nullptr; - bool isOuterEdge = true; // determine where a solid outer border should be drawn - int lastFromLane = -1; - std::vector parallel; - std::vector connections = inEdge->getConnections(); - if (lefthand) { - std::reverse(connections.begin(), connections.end()); - } - for (const NBEdge::Connection& c : connections) { - assert(c.toEdge != 0); - if (outEdge != c.toEdge || c.fromLane == lastFromLane) { - if (outEdge != nullptr) { - if (isOuterEdge) { - addPedestrianConnection(inEdge, outEdge, parallel); - } - connectionID = writeInternalEdge(device, junctionOSS, inEdge, nID, - getID(parallel.back().getInternalLaneID(), edgeMap, edgeID), - inEdgeID, - getID(outEdge->getID(), edgeMap, edgeID), - connectionID, - parallel, isOuterEdge, straightThresh, centerMark); - parallel.clear(); - isOuterEdge = false; - } - outEdge = c.toEdge; - } - lastFromLane = c.fromLane; - parallel.push_back(c); - } - if (isOuterEdge) { - addPedestrianConnection(inEdge, outEdge, parallel); - } - if (!parallel.empty()) { - if (!lefthand && (n->geometryLike() || inEdge->isTurningDirectionAt(outEdge))) { - centerMark = "solid"; - } - connectionID = writeInternalEdge(device, junctionOSS, inEdge, nID, - getID(parallel.back().getInternalLaneID(), edgeMap, edgeID), - inEdgeID, - getID(outEdge->getID(), edgeMap, edgeID), - connectionID, - parallel, isOuterEdge, straightThresh, centerMark); - parallel.clear(); - } - } - if (n->numNormalConnections() > 0) { - junctionOSS << " \n"; - } - } - device.lf(); - // write junctions (junction) - device << junctionOSS.getString(); - - for (std::map::const_iterator i = nc.begin(); i != nc.end(); ++i) { - NBNode* n = (*i).second; - const std::vector& incoming = n->getIncomingEdges(); - // check if any connections must be written - int numConnections = 0; - for (std::vector::const_iterator j = incoming.begin(); j != incoming.end(); ++j) { - numConnections += (int)((*j)->getConnections().size()); - } - if (numConnections == 0) { - continue; - } - for (std::vector::const_iterator j = incoming.begin(); j != incoming.end(); ++j) { - const NBEdge* inEdge = *j; - const std::vector& elv = inEdge->getConnections(); - for (std::vector::const_iterator k = elv.begin(); k != elv.end(); ++k) { - const NBEdge::Connection& c = *k; - const NBEdge* outEdge = c.toEdge; - if (outEdge == nullptr) { - continue; - } - } - } - } - - device.closeTag(); - - OptionsCont::getOptions().output_xodr_file = device.getString(); - - // device.close(); -} - - -void -NWWriter_OpenDrive::writeNormalEdge(OutputDevice& device, const NBEdge* e, - int edgeID, int fromNodeID, int toNodeID, - const bool origNames, - const double straightThresh, - const ShapeContainer& shc) { - // buffer output because some fields are computed out of order - OutputDevice_String elevationOSS(3); - elevationOSS.setPrecision(8); - OutputDevice_String planViewOSS(2); - planViewOSS.setPrecision(8); - double length = 0; - - planViewOSS.openTag("planView"); - // for the shape we need to use the leftmost border of the leftmost lane - const std::vector& lanes = e->getLanes(); - PositionVector ls = getLeftLaneBorder(e); -#ifdef DEBUG_SMOOTH_GEOM - if (DEBUGCOND) { - std::cout << "write planview for edge " << e->getID() << "\n"; - } -#endif - - if (ls.size() == 2 || e->getPermissions() == SVC_PEDESTRIAN) { - // foot paths may contain sharp angles - length = writeGeomLines(ls, planViewOSS, elevationOSS); - } else { - bool ok = writeGeomSmooth(ls, e->getSpeed(), planViewOSS, elevationOSS, straightThresh, length); - if (!ok) { - WRITE_WARNING("Could not compute smooth shape for edge '" + e->getID() + "'."); - } - } - planViewOSS.closeTag(); - - device.openTag("road"); - device.writeAttr("name", StringUtils::escapeXML(e->getStreetName())); - device.setPrecision(8); // length requires higher precision - device.writeAttr("length", MAX2(POSITION_EPS, length)); - device.setPrecision(gPrecision); - device.writeAttr("id", edgeID); - device.writeAttr("junction", -1); - if (fromNodeID != INVALID_ID || toNodeID != INVALID_ID) { - device.openTag("link"); - if (fromNodeID != INVALID_ID) { - device.openTag("predecessor"); - device.writeAttr("elementType", "junction"); - device.writeAttr("elementId", fromNodeID); - device.closeTag(); - } - if (toNodeID != INVALID_ID) { - device.openTag("successor"); - device.writeAttr("elementType", "junction"); - device.writeAttr("elementId", toNodeID); - device.closeTag(); - } - device.closeTag(); - } - device.openTag("type").writeAttr("s", 0).writeAttr("type", "town").closeTag(); - device << planViewOSS.getString(); - writeElevationProfile(ls, device, elevationOSS); - device << " \n"; - device << " \n"; - device << " \n"; - const std::string centerMark = e->getPermissions(e->getNumLanes() - 1) == 0 ? "none" : "solid"; - writeEmptyCenterLane(device, centerMark, 0.13); - device << " \n"; - for (int j = e->getNumLanes(); --j >= 0;) { - std::string laneType = getLaneType(e->getPermissions(j)); - device << " getNumLanes() - j << "\" type=\"" << laneType << "\" level=\"true\">\n"; - device << " \n"; - // this could be used for geometry-link junctions without u-turn, - // predecessor and sucessors would be lane indices, - // road predecessor / succesfors would be of type 'road' rather than - // 'junction' - //device << " \n"; - //device << " \n"; - //device << " \n"; - device << " getLaneWidth(j) << "\" b=\"0\" c=\"0\" d=\"0\"/>\n"; - std::string markType = "broken"; - if (j == 0) { - markType = "solid"; - } else if (j > 0 - && (e->getPermissions(j - 1) & ~(SVC_PEDESTRIAN | SVC_BICYCLE)) == 0) { - // solid road mark to the left of sidewalk or bicycle lane - markType = "solid"; - } else if (e->getPermissions(j) == 0) { - // solid road mark to the right of a forbidden lane - markType = "solid"; - } - std::string laneChange = "both"; - if (j == 0) { - laneChange = "none"; - } else if (getLaneType(e->getPermissions(j - 1)) == laneType) { - laneChange = "both"; - } else { - laneChange = "none"; - } - device << " \n"; - device << " \n"; - device << " \n"; - } - device << " \n"; - device << " \n"; - device << " \n"; - writeRoadObjects(device, e, shc); - device << " \n"; - if (origNames) { - device << " getID() << "\"/>\n"; - } - device.closeTag(); - checkLaneGeometries(e); -} - -void -NWWriter_OpenDrive::addPedestrianConnection(const NBEdge* inEdge, const NBEdge* outEdge, std::vector& parallel) { - // by default there are no internal lanes for pedestrians. Determine if - // one is feasible and does not exist yet. - if (outEdge != nullptr - && inEdge->getPermissions(0) == SVC_PEDESTRIAN - && outEdge->getPermissions(0) == SVC_PEDESTRIAN - && (parallel.empty() - || parallel.front().fromLane != 0 - || parallel.front().toLane != 0)) { - parallel.insert(parallel.begin(), NBEdge::Connection(0, const_cast(outEdge), 0, false)); - parallel.front().vmax = (inEdge->getLanes()[0].speed + outEdge->getLanes()[0].speed) / (double) 2.0; - } -} - - -int -NWWriter_OpenDrive::writeInternalEdge(OutputDevice& device, OutputDevice& junctionDevice, const NBEdge* inEdge, int nodeID, - int edgeID, int inEdgeID, int outEdgeID, - int connectionID, - const std::vector& parallel, - const bool isOuterEdge, - const double straightThresh, - const std::string& centerMark) { - assert(parallel.size() != 0); - const NBEdge::Connection& cLeft = parallel.back(); - const NBEdge* outEdge = cLeft.toEdge; - PositionVector begShape = getLeftLaneBorder(inEdge, cLeft.fromLane); - PositionVector endShape = getLeftLaneBorder(outEdge, cLeft.toLane); - //std::cout << "computing reference line for internal lane " << cLeft.getInternalLaneID() << " begLane=" << inEdge->getLaneShape(cLeft.fromLane) << " endLane=" << outEdge->getLaneShape(cLeft.toLane) << "\n"; - - double length; - double laneOffset = 0; - PositionVector fallBackShape; - fallBackShape.push_back(begShape.back()); - fallBackShape.push_back(endShape.front()); - const bool turnaround = inEdge->isTurningDirectionAt(outEdge); - bool ok = true; - PositionVector init = NBNode::bezierControlPoints(begShape, endShape, turnaround, 25, 25, ok, nullptr, straightThresh); - if (init.size() == 0) { - length = fallBackShape.length2D(); - // problem with turnarounds is known, method currently returns 'ok' (#2539) - if (!ok) { - WRITE_WARNING("Could not compute smooth shape from lane '" + inEdge->getLaneID(cLeft.fromLane) + "' to lane '" + outEdge->getLaneID(cLeft.toLane) + "'. Use option 'junctions.scurve-stretch' or increase radius of junction '" + inEdge->getToNode()->getID() + "' to fix this."); - } else if (length <= NUMERICAL_EPS) { - // left-curving geometry-like edges must use the right - // side as reference line and shift - begShape = getRightLaneBorder(inEdge, cLeft.fromLane); - endShape = getRightLaneBorder(outEdge, cLeft.toLane); - init = NBNode::bezierControlPoints(begShape, endShape, turnaround, 25, 25, ok, nullptr, straightThresh); - if (init.size() != 0) { - length = init.bezier(12).length2D(); - laneOffset = outEdge->getLaneWidth(cLeft.toLane); - //std::cout << " internalLane=" << cLeft.getInternalLaneID() << " length=" << length << "\n"; - } - } - } else { - length = init.bezier(12).length2D(); - } - - junctionDevice << " \n"; - device.openTag("road"); - device.writeAttr("name", cLeft.id); - device.setPrecision(8); // length requires higher precision - device.writeAttr("length", MAX2(POSITION_EPS, length)); - device.setPrecision(gPrecision); - device.writeAttr("id", edgeID); - device.writeAttr("junction", nodeID); - device.openTag("link"); - device.openTag("predecessor"); - device.writeAttr("elementType", "road"); - device.writeAttr("elementId", inEdgeID); - device.writeAttr("contactPoint", "end"); - device.closeTag(); - device.openTag("successor"); - device.writeAttr("elementType", "road"); - device.writeAttr("elementId", outEdgeID); - device.writeAttr("contactPoint", "start"); - device.closeTag(); - device.closeTag(); - device.openTag("type").writeAttr("s", 0).writeAttr("type", "town").closeTag(); - device.openTag("planView"); - device.setPrecision(8); // geometry hdg requires higher precision - OutputDevice_String elevationOSS(3); - elevationOSS.setPrecision(8); -#ifdef DEBUG_SMOOTH_GEOM - if (DEBUGCOND) { - std::cout << "write planview for internal edge " << cLeft.id << " init=" << init << " fallback=" << fallBackShape - << " begShape=" << begShape << " endShape=" << endShape - << "\n"; - } -#endif - if (init.size() == 0) { - writeGeomLines(fallBackShape, device, elevationOSS); - } else { - writeGeomPP3(device, elevationOSS, init, length); - } - device.setPrecision(gPrecision); - device.closeTag(); - writeElevationProfile(fallBackShape, device, elevationOSS); - device << " \n"; - device << " \n"; - if (laneOffset != 0) { - device << " \n"; - } - device << " \n"; - writeEmptyCenterLane(device, centerMark, 0); - device << " \n"; - for (int j = (int)parallel.size(); --j >= 0;) { - const NBEdge::Connection& c = parallel[j]; - const int fromIndex = c.fromLane - inEdge->getNumLanes(); - const int toIndex = c.toLane - outEdge->getNumLanes(); - device << " getPermissions(c.toLane)) << "\" level=\"true\">\n"; - device << " \n"; - device << " \n"; - device << " \n"; - device << " \n"; - device << " getLaneWidth(c.toLane) << "\" b=\"0\" c=\"0\" d=\"0\"/>\n"; - std::string markType = "broken"; - if (inEdge->isTurningDirectionAt(outEdge)) { - markType = "none"; - } else if (c.fromLane == 0 && c.toLane == 0 && isOuterEdge) { - // solid road mark at the outer border - markType = "solid"; - } else if (isOuterEdge && j > 0 - && (outEdge->getPermissions(parallel[j - 1].toLane) & ~(SVC_PEDESTRIAN | SVC_BICYCLE)) == 0) { - // solid road mark to the left of sidewalk or bicycle lane - markType = "solid"; - } else if (!inEdge->getToNode()->geometryLike()) { - // draw shorter road marks to indicate turning paths - LinkDirection dir = inEdge->getToNode()->getDirection(inEdge, outEdge, OptionsCont::getOptions().getBool("lefthand")); - if (dir == LinkDirection::LEFT || dir == LinkDirection::RIGHT || dir == LinkDirection::PARTLEFT || dir == LinkDirection::PARTRIGHT) { - // XXX is not rendered by odrViewer so cannot be validated - // device << " \n"; - // device << " \n"; - // device << " \n"; - markType = "none"; - } - } - device << " \n"; - device << " \n"; - device << " \n"; - - const int toLane = -(parallel.size() - j); - junctionDevice << " \n"; - connectionID++; - } - device << " \n"; - device << " \n"; - device << " \n"; - device << " \n"; - device << " \n"; - device.closeTag(); - junctionDevice << " \n"; - - return connectionID; -} - - -double -NWWriter_OpenDrive::writeGeomLines(const PositionVector& shape, OutputDevice& device, OutputDevice& elevationDevice, double offset) { - for (int j = 0; j < (int)shape.size() - 1; ++j) { - const Position& p = shape[j]; - const Position& p2 = shape[j + 1]; - const double hdg = shape.angleAt2D(j); - const double length = p.distanceTo2D(p2); - device.openTag("geometry"); - device.writeAttr("s", offset); - device.writeAttr("x", p.x()); - device.writeAttr("y", p.y()); - device.writeAttr("hdg", hdg); - device.writeAttr("length", length); - device.openTag("line").closeTag(); - device.closeTag(); - elevationDevice << " \n"; - offset += length; - } - return offset; -} - - -void -NWWriter_OpenDrive::writeEmptyCenterLane(OutputDevice& device, const std::string& mark, double markWidth) { - device << "
\n"; - device << " \n"; - device << " \n"; - // laneChange = none as roads contain lanes in one direction only - device << " \n"; - device << " \n"; - device << "
\n"; -} - - -int -NWWriter_OpenDrive::getID(const std::string& origID, StringBijection& map, int& lastID) { - if (map.hasString(origID)) { - return map.get(origID); - } - map.insert(origID, lastID++); - return lastID - 1; -} - - -std::string -NWWriter_OpenDrive::getLaneType(SVCPermissions permissions) { - switch (permissions) { - case SVC_PEDESTRIAN: - return "sidewalk"; - //case (SVC_BICYCLE | SVC_PEDESTRIAN): - // WRITE_WARNING("Ambiguous lane type (biking+driving) for road '" + roadID + "'"); - // return "sidewalk"; - case SVC_BICYCLE: - return "biking"; - case 0: - // ambiguous - return "none"; - case SVC_RAIL: - case SVC_RAIL_URBAN: - case SVC_RAIL_ELECTRIC: - case SVC_RAIL_FAST: - return "rail"; - case SVC_TRAM: - return "tram"; - default: { - // complex permissions - if (permissions == SVCAll) { - return "driving"; - } else if (isRailway(permissions)) { - return "rail"; - } else if ((permissions & SVC_PASSENGER) != 0) { - return "driving"; - } else { - return "restricted"; - } - } - } -} - - -PositionVector -NWWriter_OpenDrive::getLeftLaneBorder(const NBEdge* edge, int laneIndex, double widthOffset) { - const bool lefthand = OptionsCont::getOptions().getBool("lefthand"); - if (laneIndex == -1) { - // leftmost lane - laneIndex = lefthand ? 0 : (int)edge->getNumLanes() - 1; - } - /// it would be tempting to use - // PositionVector result = edge->getLaneShape(laneIndex); - // (and the moveo2side) - // However, the lanes in SUMO have a small lateral gap (SUMO_const_laneOffset) to account for markings - // In OpenDRIVE this gap does not exists so we have to do all lateral - // computations based on the reference line - // This assumes that the 'stop line' for all lanes is colinear! - const int leftmost = lefthand ? 0 : (int)edge->getNumLanes() - 1; - widthOffset -= (edge->getLaneWidth(leftmost) / 2); - // collect lane widths from left border of edge to left border of lane to connect to - if (lefthand) { - for (int i = leftmost; i < laneIndex; i++) { - widthOffset += edge->getLaneWidth(i); - } - } else { - for (int i = leftmost; i > laneIndex; i--) { - widthOffset += edge->getLaneWidth(i); - } - } - PositionVector result = edge->getLaneShape(leftmost); - try { - result.move2side(widthOffset); - } catch (InvalidArgument&) { } - return result; -} - -PositionVector -NWWriter_OpenDrive::getRightLaneBorder(const NBEdge* edge, int laneIndex) { - return getLeftLaneBorder(edge, laneIndex, edge->getLaneWidth(laneIndex)); -} - - -double -NWWriter_OpenDrive::writeGeomPP3( - OutputDevice& device, - OutputDevice& elevationDevice, - PositionVector init, - double length, - double offset) { - assert(init.size() == 3 || init.size() == 4); - - // avoid division by 0 - length = MAX2(POSITION_EPS, length); - - const Position p = init.front(); - const double hdg = init.angleAt2D(0); - - // backup elevation values - const PositionVector initZ = init; - // translate to u,v coordinates - init.add(-p.x(), -p.y(), -p.z()); - init.rotate2D(-hdg); - - // parametric coefficients - double aU, bU, cU, dU; - double aV, bV, cV, dV; - double aZ, bZ, cZ, dZ; - - // unfactor the Bernstein polynomials of degree 2 (or 3) and collect the coefficients - if (init.size() == 3) { - //f(x, a, b ,c) = a + (2*b - 2*a)*x + (a - 2*b + c)*x*x - aU = init[0].x(); - bU = 2 * init[1].x() - 2 * init[0].x(); - cU = init[0].x() - 2 * init[1].x() + init[2].x(); - dU = 0; - - aV = init[0].y(); - bV = 2 * init[1].y() - 2 * init[0].y(); - cV = init[0].y() - 2 * init[1].y() + init[2].y(); - dV = 0; - - // elevation is not parameteric on [0:1] but on [0:length] - aZ = initZ[0].z(); - bZ = (2 * initZ[1].z() - 2 * initZ[0].z()) / length; - cZ = (initZ[0].z() - 2 * initZ[1].z() + initZ[2].z()) / (length * length); - dZ = 0; - - } else { - // f(x, a, b, c, d) = a + (x*((3*b) - (3*a))) + ((x*x)*((3*a) + (3*c) - (6*b))) + ((x*x*x)*((3*b) - (3*c) - a + d)) - aU = init[0].x(); - bU = 3 * init[1].x() - 3 * init[0].x(); - cU = 3 * init[0].x() - 6 * init[1].x() + 3 * init[2].x(); - dU = -init[0].x() + 3 * init[1].x() - 3 * init[2].x() + init[3].x(); - - aV = init[0].y(); - bV = 3 * init[1].y() - 3 * init[0].y(); - cV = 3 * init[0].y() - 6 * init[1].y() + 3 * init[2].y(); - dV = -init[0].y() + 3 * init[1].y() - 3 * init[2].y() + init[3].y(); - - // elevation is not parameteric on [0:1] but on [0:length] - aZ = initZ[0].z(); - bZ = (3 * initZ[1].z() - 3 * initZ[0].z()) / length; - cZ = (3 * initZ[0].z() - 6 * initZ[1].z() + 3 * initZ[2].z()) / (length * length); - dZ = (-initZ[0].z() + 3 * initZ[1].z() - 3 * initZ[2].z() + initZ[3].z()) / (length * length * length); - } - - device.openTag("geometry"); - device.writeAttr("s", offset); - device.writeAttr("x", p.x()); - device.writeAttr("y", p.y()); - device.writeAttr("hdg", hdg); - device.writeAttr("length", length); - - device.openTag("paramPoly3"); - device.writeAttr("aU", aU); - device.writeAttr("bU", bU); - device.writeAttr("cU", cU); - device.writeAttr("dU", dU); - device.writeAttr("aV", aV); - device.writeAttr("bV", bV); - device.writeAttr("cV", cV); - device.writeAttr("dV", dV); - device.closeTag(); - device.closeTag(); - - // write elevation - elevationDevice.openTag("elevation"); - elevationDevice.writeAttr("s", offset); - elevationDevice.writeAttr("a", aZ); - elevationDevice.writeAttr("b", bZ); - elevationDevice.writeAttr("c", cZ); - elevationDevice.writeAttr("d", dZ); - elevationDevice.closeTag(); - - return offset + length; -} - - -bool -NWWriter_OpenDrive::writeGeomSmooth(const PositionVector& shape, double speed, OutputDevice& device, OutputDevice& elevationDevice, double straightThresh, double& length) { -#ifdef DEBUG_SMOOTH_GEOM - if (DEBUGCOND) { - std::cout << "writeGeomSmooth\n n=" << shape.size() << " shape=" << toString(shape) << "\n"; - } -#endif - bool ok = true; - const double longThresh = speed; // 16.0; // make user-configurable (should match the sampling rate of the source data) - const double curveCutout = longThresh / 2; // 8.0; // make user-configurable (related to the maximum turning rate) - // the length of the segment that is added for cutting a corner can be bounded by 2*curveCutout (prevent the segment to be classified as 'long') - assert(longThresh >= 2 * curveCutout); - assert(shape.size() > 2); - // add intermediate points wherever there is a strong angular change between long segments - // assume the geometry is simplified so as not to contain consecutive colinear points - PositionVector shape2 = shape; - double maxAngleDiff = 0; - double offset = 0; - for (int j = 1; j < (int)shape.size() - 1; ++j) { - //const double hdg = shape.angleAt2D(j); - const Position& p0 = shape[j - 1]; - const Position& p1 = shape[j]; - const Position& p2 = shape[j + 1]; - const double dAngle = fabs(GeomHelper::angleDiff(p0.angleTo2D(p1), p1.angleTo2D(p2))); - const double length1 = p0.distanceTo2D(p1); - const double length2 = p1.distanceTo2D(p2); - maxAngleDiff = MAX2(maxAngleDiff, dAngle); -#ifdef DEBUG_SMOOTH_GEOM - if (DEBUGCOND) { - std::cout << " j=" << j << " dAngle=" << RAD2DEG(dAngle) << " length1=" << length1 << " length2=" << length2 << "\n"; - } -#endif - if (dAngle > straightThresh - && (length1 > longThresh || j == 1) - && (length2 > longThresh || j == (int)shape.size() - 2)) { - shape2.insertAtClosest(shape.positionAtOffset2D(offset + length1 - MIN2(length1 - POSITION_EPS, curveCutout)), false); - shape2.insertAtClosest(shape.positionAtOffset2D(offset + length1 + MIN2(length2 - POSITION_EPS, curveCutout)), false); - shape2.removeClosest(p1); - } - offset += length1; - } - const int numPoints = (int)shape2.size(); -#ifdef DEBUG_SMOOTH_GEOM - if (DEBUGCOND) { - std::cout << " n=" << numPoints << " shape2=" << toString(shape2) << "\n"; - } -#endif - - if (maxAngleDiff < straightThresh) { - length = writeGeomLines(shape2, device, elevationDevice, 0); -#ifdef DEBUG_SMOOTH_GEOM - if (DEBUGCOND) { - std::cout << " special case: all lines. maxAngleDiff=" << maxAngleDiff << "\n"; - } -#endif - return ok; - } - - // write the long segments as lines, short segments as curves - offset = 0; - for (int j = 0; j < numPoints - 1; ++j) { - const Position& p0 = shape2[j]; - const Position& p1 = shape2[j + 1]; - PositionVector line; - line.push_back(p0); - line.push_back(p1); - const double lineLength = line.length2D(); - if (lineLength >= longThresh) { - offset = writeGeomLines(line, device, elevationDevice, offset); -#ifdef DEBUG_SMOOTH_GEOM - if (DEBUGCOND) { - std::cout << " writeLine=" << toString(line) << "\n"; - } -#endif - } else { - // find control points - PositionVector begShape; - PositionVector endShape; - if (j == 0 || j == numPoints - 2) { - // keep the angle of the first/last segment but end at the front of the shape - begShape = line; - begShape.add(p0 - begShape.back()); - } else if (j == 1 || p0.distanceTo2D(shape2[j - 1]) > longThresh) { - // use the previous segment if it is long or the first one - begShape.push_back(shape2[j - 1]); - begShape.push_back(p0); - } else { - // end at p0 with mean angle of the previous and current segment - begShape.push_back(shape2[j - 1]); - begShape.push_back(p1); - begShape.add(p0 - begShape.back()); - } - - if (j == 0 || j == numPoints - 2) { - // keep the angle of the first/last segment but start at the end of the shape - endShape = line; - endShape.add(p1 - endShape.front()); - } else if (j == numPoints - 3 || p1.distanceTo2D(shape2[j + 2]) > longThresh) { - // use the next segment if it is long or the final one - endShape.push_back(p1); - endShape.push_back(shape2[j + 2]); - } else { - // start at p1 with mean angle of the current and next segment - endShape.push_back(p0); - endShape.push_back(shape2[j + 2]); - endShape.add(p1 - endShape.front()); - } - const double extrapolateLength = MIN2((double)25, lineLength / 4); - PositionVector init = NBNode::bezierControlPoints(begShape, endShape, false, extrapolateLength, extrapolateLength, ok, nullptr, straightThresh); - if (init.size() == 0) { - // could not compute control points, write line - offset = writeGeomLines(line, device, elevationDevice, offset); -#ifdef DEBUG_SMOOTH_GEOM - if (DEBUGCOND) { - std::cout << " writeLine lineLength=" << lineLength << " begShape" << j << "=" << toString(begShape) << " endShape" << j << "=" << toString(endShape) << " init" << j << "=" << toString(init) << "\n"; - } -#endif - } else { - // write bezier - const double curveLength = init.bezier(12).length2D(); - offset = writeGeomPP3(device, elevationDevice, init, curveLength, offset); -#ifdef DEBUG_SMOOTH_GEOM - if (DEBUGCOND) { - std::cout << " writeCurve lineLength=" << lineLength << " curveLength=" << curveLength << " begShape" << j << "=" << toString(begShape) << " endShape" << j << "=" << toString(endShape) << " init" << j << "=" << toString(init) << "\n"; - } -#endif - } - } - } - length = offset; - return ok; -} - - -void -NWWriter_OpenDrive::writeElevationProfile(const PositionVector& shape, OutputDevice& device, const OutputDevice_String& elevationDevice) { - // check if the shape is flat - bool flat = true; - double z = shape.size() == 0 ? 0 : shape[0].z(); - for (int i = 1; i < (int)shape.size(); ++i) { - if (fabs(shape[i].z() - z) > NUMERICAL_EPS) { - flat = false; - break; - } - } - device << " \n"; - if (flat) { - device << " \n"; - } else { - device << elevationDevice.getString(); - } - device << " \n"; - -} - - -void -NWWriter_OpenDrive::checkLaneGeometries(const NBEdge* e) { - if (e->getNumLanes() > 1) { - // compute 'stop line' of rightmost lane - const PositionVector shape0 = e->getLaneShape(0); - assert(shape0.size() >= 2); - const Position& from = shape0[-2]; - const Position& to = shape0[-1]; - PositionVector stopLine; - stopLine.push_back(to); - stopLine.push_back(to - PositionVector::sideOffset(from, to, -1000.0)); - // endpoints of all other lanes should be on the stop line - for (int lane = 1; lane < e->getNumLanes(); ++lane) { - const double dist = stopLine.distance2D(e->getLaneShape(lane)[-1]); - if (dist > NUMERICAL_EPS) { - WRITE_WARNING("Uneven stop line at lane '" + e->getLaneID(lane) + "' (dist=" + toString(dist) + ") cannot be represented in OpenDRIVE."); - } - } - } -} - -void -NWWriter_OpenDrive::writeRoadObjects(OutputDevice& device, const NBEdge* e, const ShapeContainer& shc) { - if (e->knowsParameter("roadObjects")) { - device.openTag("objects"); - device.setPrecision(8); // geometry hdg requires higher precision - PositionVector road = getLeftLaneBorder(e); - for (std::string id : StringTokenizer(e->getParameter("roadObjects", "")).getVector()) { - SUMOPolygon* p = shc.getPolygons().get(id); - if (p == nullptr) { - WRITE_WARNING("Road object polygon '" + id + "' not found for edge '" + e->getID() + "'"); - } else if (p->getShape().size() != 4) { - WRITE_WARNING("Cannot convert road object polygon '" + id + "' with " + toString(p->getShape().size()) + " points for edge '" + e->getID() + "'"); - } else { - const PositionVector& shape = p->getShape(); - device.openTag("object"); - Position center = shape.getPolygonCenter(); - PositionVector sideline = shape.getSubpartByIndex(0, 2); - PositionVector ortholine = shape.getSubpartByIndex(1, 2); - const double absAngle = sideline.angleAt2D(0); - const double length = sideline.length2D(); - const double width = ortholine.length2D(); - const double edgeOffset = road.nearest_offset_to_point2D(center); - if (edgeOffset == GeomHelper::INVALID_OFFSET) { - WRITE_WARNING("Cannot map road object polygon '" + id + "' with center " + toString(center) + " onto edge '" + e->getID() + "'"); - continue; - } - Position edgePos = road.positionAtOffset2D(edgeOffset); - const double edgeAngle = road.rotationAtOffset(edgeOffset); - const double relAngle = absAngle - edgeAngle; - double sideOffset = center.distanceTo2D(edgePos); - // determine sign of sideOffset - PositionVector tmp = road.getSubpart2D(MAX2(0.0, edgeOffset - 1), MIN2(road.length2D(), edgeOffset + 1)); - tmp.move2side(sideOffset); - if (tmp.distance2D(center) < sideOffset) { - sideOffset *= -1; - } - //std::cout << " id=" << id - // << " shape=" << shape - // << " center=" << center - // << " edgeOffset=" << edgeOffset - // << "\n"; - device.writeAttr("id", id); - device.writeAttr("type", p->getShapeType()); - device.writeAttr("name", p->getParameter("name", "")); - device.writeAttr("s", edgeOffset); - device.writeAttr("t", sideOffset); - device.writeAttr("width", width); - device.writeAttr("length", length); - device.writeAttr("hdg", relAngle); - device.closeTag(); - } - } - device.setPrecision(gPrecision); - device.closeTag(); - } else { - device << " \n"; - } -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netwrite/NWWriter_OpenDrive.h b/Util/OSM2ODR/src/netwrite/NWWriter_OpenDrive.h deleted file mode 100644 index 955fceb7c..000000000 --- a/Util/OSM2ODR/src/netwrite/NWWriter_OpenDrive.h +++ /dev/null @@ -1,110 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NWWriter_OpenDrive.h -/// @author Daniel Krajzewicz -/// @date Tue, 04.05.2011 -/// -// Exporter writing networks using the openDRIVE format -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include - - -// =========================================================================== -// class declarations -// =========================================================================== -class NBNetBuilder; -class NBEdge; -class OptionsCont; -class PositionVector; -class OutputDevice; -class OutputDevice_String; -class ShapeContainer; - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NWWriter_OpenDrive - * @brief Exporter writing networks using the openDRIVE format - * - */ -class NWWriter_OpenDrive { -public: - /** @brief Writes the network into a openDRIVE-file - * - * @param[in] oc The options to use - * @param[in] nb The network builder to fill - */ - static void writeNetwork(const OptionsCont& oc, NBNetBuilder& nb); - -protected: - /// @brief write normal edge to device - static void writeNormalEdge(OutputDevice& device, const NBEdge* e, - int edgeID, int fromNodeID, int toNodeID, - const bool origNames, - const double straightThresh, - const ShapeContainer& shc); - - /// @brief write internal edge to device, return next connectionID - static int writeInternalEdge(OutputDevice& device, OutputDevice& junctionDevice, - const NBEdge* inEdge, int nodeID, - int edgeID, int inEdgeID, int outEdgeID, - int connectionID, - const std::vector& parallel, - const bool isOuterEdge, - const double straightThresh, - const std::string& centerMark); - - static void addPedestrianConnection(const NBEdge* inEdge, const NBEdge* outEdge, std::vector& parallel); - - /// @brief write geometry as sequence of lines (sumo style) - static double writeGeomLines(const PositionVector& shape, OutputDevice& device, OutputDevice& elevationDevice, double offset = 0); - - /* @brief write geometry as sequence of lines and bezier curves - * - * @param[in] straightThresh angular changes below threshold are considered to be straight and no curve will be fitted between the segments - * @param[out] length Return the total length of the reference line - */ - static bool writeGeomSmooth(const PositionVector& shape, double speed, OutputDevice& device, OutputDevice& elevationDevice, double straightThresh, double& length); - - /// @brief write geometry as a single bezier curve (paramPoly3) - static double writeGeomPP3(OutputDevice& device, - OutputDevice& elevationDevice, - PositionVector init, - double length, - double offset = 0); - - static void writeElevationProfile(const PositionVector& shape, OutputDevice& device, const OutputDevice_String& elevationDevice); - - static void writeEmptyCenterLane(OutputDevice& device, const std::string& mark, double markWidth); - static int getID(const std::string& origID, StringBijection& map, int& lastID); - - static std::string getLaneType(SVCPermissions permissions); - - /// @brief get the left border of the given lane (the leftmost one by default) - static PositionVector getLeftLaneBorder(const NBEdge* edge, int laneIndex = -1, double widthOffset = 0); - static PositionVector getRightLaneBorder(const NBEdge* edge, int laneIndex = -1); - - /// @brief check if the lane geometries are compatible with OpenDRIVE assumptions (colinear stop line) - static void checkLaneGeometries(const NBEdge* e); - - /// @brief write road objects referenced as edge parameters - static void writeRoadObjects(OutputDevice& device, const NBEdge* e, const ShapeContainer& shc); -}; diff --git a/Util/OSM2ODR/src/netwrite/NWWriter_SUMO.cpp b/Util/OSM2ODR/src/netwrite/NWWriter_SUMO.cpp deleted file mode 100644 index 897c52692..000000000 --- a/Util/OSM2ODR/src/netwrite/NWWriter_SUMO.cpp +++ /dev/null @@ -1,999 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NWWriter_SUMO.cpp -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @author Leonhard Luecken -/// @date Tue, 04.05.2011 -/// -// Exporter writing networks using the SUMO format -/****************************************************************************/ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "NWFrame.h" -#include "NWWriter_SUMO.h" - - -//#define DEBUG_OPPOSITE_INTERNAL - -// =========================================================================== -// method definitions -// =========================================================================== -// --------------------------------------------------------------------------- -// static methods -// --------------------------------------------------------------------------- -void -NWWriter_SUMO::writeNetwork(const OptionsCont& oc, NBNetBuilder& nb) { - // check whether a sumo net-file shall be generated - if (!oc.isSet("output-file")) { - return; - } - OutputDevice& device = OutputDevice::getDevice(oc.getString("output-file")); - std::map attrs; - attrs[SUMO_ATTR_VERSION] = toString(NETWORK_VERSION, 1); - if (oc.getBool("lefthand") != oc.getBool("flip-y-axis")) { - attrs[SUMO_ATTR_LEFTHAND] = "true"; - } else if (oc.getBool("lefthand")) { - // network was flipped, correct written link directions - OptionsCont::getOptions().resetWritable(); - OptionsCont::getOptions().set("lefthand", "false"); - } - const int cornerDetail = oc.getInt("junctions.corner-detail"); - if (cornerDetail > 0) { - attrs[SUMO_ATTR_CORNERDETAIL] = toString(cornerDetail); - } - if (!oc.isDefault("junctions.internal-link-detail")) { - attrs[SUMO_ATTR_LINKDETAIL] = toString(oc.getInt("junctions.internal-link-detail")); - } - if (oc.getBool("rectangular-lane-cut")) { - attrs[SUMO_ATTR_RECTANGULAR_LANE_CUT] = "true"; - } - if (oc.getBool("crossings.guess") || oc.getBool("walkingareas")) { - attrs[SUMO_ATTR_WALKINGAREAS] = "true"; - } - if (oc.getFloat("junctions.limit-turn-speed") > 0) { - attrs[SUMO_ATTR_LIMIT_TURN_SPEED] = toString(oc.getFloat("junctions.limit-turn-speed")); - } - if (!oc.isDefault("check-lane-foes.all")) { - attrs[SUMO_ATTR_CHECKLANEFOES_ALL] = toString(oc.getBool("check-lane-foes.all")); - } - if (!oc.isDefault("check-lane-foes.roundabout")) { - attrs[SUMO_ATTR_CHECKLANEFOES_ROUNDABOUT] = toString(oc.getBool("check-lane-foes.roundabout")); - } - if (!oc.isDefault("tls.ignore-internal-junction-jam")) { - attrs[SUMO_ATTR_TLS_IGNORE_INTERNAL_JUNCTION_JAM] = toString(oc.getBool("tls.ignore-internal-junction-jam")); - } - if (oc.getString("default.spreadtype") != "right") { - attrs[SUMO_ATTR_SPREADTYPE] = oc.getString("default.spreadtype"); - } - if (oc.exists("geometry.avoid-overlap") && !oc.getBool("geometry.avoid-overlap")) { - attrs[SUMO_ATTR_AVOID_OVERLAP] = toString(oc.getBool("geometry.avoid-overlap")); - } - device.writeXMLHeader("net", "net_file.xsd", attrs); // street names may contain non-ascii chars - device.lf(); - // get involved container - const NBNodeCont& nc = nb.getNodeCont(); - const NBEdgeCont& ec = nb.getEdgeCont(); - const NBDistrictCont& dc = nb.getDistrictCont(); - - // write network offsets and projection - GeoConvHelper::writeLocation(device); - - // write edge types and restrictions - nb.getTypeCont().writeTypes(device); - - // write inner lanes - if (!oc.getBool("no-internal-links")) { - bool hadAny = false; - for (std::map::const_iterator i = nc.begin(); i != nc.end(); ++i) { - hadAny |= writeInternalEdges(device, ec, *(*i).second); - } - if (hadAny) { - device.lf(); - } - } - - // write edges with lanes and connected edges - bool noNames = !oc.getBool("output.street-names"); - for (std::map::const_iterator i = ec.begin(); i != ec.end(); ++i) { - writeEdge(device, *(*i).second, noNames); - } - device.lf(); - - // write tls logics - writeTrafficLights(device, nb.getTLLogicCont()); - - // write the nodes (junctions) - for (std::map::const_iterator i = nc.begin(); i != nc.end(); ++i) { - writeJunction(device, *(*i).second); - } - device.lf(); - const bool includeInternal = !oc.getBool("no-internal-links"); - if (includeInternal) { - // ... internal nodes if not unwanted - bool hadAny = false; - for (std::map::const_iterator i = nc.begin(); i != nc.end(); ++i) { - hadAny |= writeInternalNodes(device, *(*i).second); - } - if (hadAny) { - device.lf(); - } - } - - // write the successors of lanes - int numConnections = 0; - for (std::map::const_iterator it_edge = ec.begin(); it_edge != ec.end(); it_edge++) { - NBEdge* from = it_edge->second; - const std::vector connections = from->getConnections(); - numConnections += (int)connections.size(); - for (std::vector::const_iterator it_c = connections.begin(); it_c != connections.end(); it_c++) { - writeConnection(device, *from, *it_c, includeInternal); - } - } - if (numConnections > 0) { - device.lf(); - } - if (includeInternal) { - // ... internal successors if not unwanted - bool hadAny = false; - for (std::map::const_iterator i = nc.begin(); i != nc.end(); ++i) { - hadAny |= writeInternalConnections(device, *(*i).second); - } - if (hadAny) { - device.lf(); - } - } - for (std::map::const_iterator i = nc.begin(); i != nc.end(); ++i) { - NBNode* node = (*i).second; - // write connections from pedestrian crossings - std::vector crossings = node->getCrossings(); - for (auto c : crossings) { - NWWriter_SUMO::writeInternalConnection(device, c->id, c->nextWalkingArea, 0, 0, "", LinkDirection::STRAIGHT, c->tlID, c->tlLinkIndex2); - } - // write connections from pedestrian walking areas - for (const NBNode::WalkingArea& wa : node->getWalkingAreas()) { - for (const std::string& cID : wa.nextCrossings) { - const NBNode::Crossing& nextCrossing = *node->getCrossing(cID); - // connection to next crossing (may be tls-controlled) - device.openTag(SUMO_TAG_CONNECTION); - device.writeAttr(SUMO_ATTR_FROM, wa.id); - device.writeAttr(SUMO_ATTR_TO, cID); - device.writeAttr(SUMO_ATTR_FROM_LANE, 0); - device.writeAttr(SUMO_ATTR_TO_LANE, 0); - if (nextCrossing.tlID != "") { - device.writeAttr(SUMO_ATTR_TLID, nextCrossing.tlID); - assert(nextCrossing.tlLinkIndex >= 0); - device.writeAttr(SUMO_ATTR_TLLINKINDEX, nextCrossing.tlLinkIndex); - } - device.writeAttr(SUMO_ATTR_DIR, LinkDirection::STRAIGHT); - device.writeAttr(SUMO_ATTR_STATE, nextCrossing.priority ? LINKSTATE_MAJOR : LINKSTATE_MINOR); - device.closeTag(); - } - // optional connections from/to sidewalk - std::string edgeID; - int laneIndex; - for (const std::string& sw : wa.nextSidewalks) { - NBHelpers::interpretLaneID(sw, edgeID, laneIndex); - NWWriter_SUMO::writeInternalConnection(device, wa.id, edgeID, 0, laneIndex, ""); - } - for (const std::string& sw : wa.prevSidewalks) { - NBHelpers::interpretLaneID(sw, edgeID, laneIndex); - NWWriter_SUMO::writeInternalConnection(device, edgeID, wa.id, laneIndex, 0, ""); - } - } - } - - // write loaded prohibitions - for (std::map::const_iterator i = nc.begin(); i != nc.end(); ++i) { - writeProhibitions(device, i->second->getProhibitions()); - } - - // write roundabout information - writeRoundabouts(device, ec.getRoundabouts(), ec); - - // write the districts - if (dc.size() != 0 && oc.isDefault("taz-output")) { - WRITE_WARNING("Embedding TAZ-data inside the network is deprecated. Use option --taz-output instead"); - for (std::map::const_iterator i = dc.begin(); i != dc.end(); i++) { - writeDistrict(device, *(*i).second); - } - device.lf(); - } - device.close(); -} - - -std::string -NWWriter_SUMO::getOppositeInternalID(const NBEdgeCont& ec, const NBEdge* from, const NBEdge::Connection& con, double& oppositeLength) { - const NBEdge::Lane& succ = con.toEdge->getLanes()[con.toLane]; - const NBEdge::Lane& pred = from->getLanes()[con.fromLane]; - const bool lefthand = OptionsCont::getOptions().getBool("lefthand"); - if (succ.oppositeID != "" && succ.oppositeID != "-" && pred.oppositeID != "" && pred.oppositeID != "-") { -#ifdef DEBUG_OPPOSITE_INTERNAL - std::cout << "getOppositeInternalID con=" << con.getDescription(from) << " (" << con.getInternalLaneID() << ")\n"; -#endif - // find the connection that connects succ.oppositeID to pred.oppositeID - const NBEdge* succOpp = ec.retrieve(succ.oppositeID.substr(0, succ.oppositeID.rfind("_"))); - const NBEdge* predOpp = ec.retrieve(pred.oppositeID.substr(0, pred.oppositeID.rfind("_"))); - assert(succOpp != 0); - assert(predOpp != 0); - const std::vector& connections = succOpp->getConnections(); - for (std::vector::const_iterator it_c = connections.begin(); it_c != connections.end(); it_c++) { - const NBEdge::Connection& conOpp = *it_c; - if (succOpp != from // turnaround - && predOpp == conOpp.toEdge - && succOpp->getLaneID(conOpp.fromLane) == succ.oppositeID - && predOpp->getLaneID(conOpp.toLane) == pred.oppositeID - && from->getToNode()->getDirection(from, con.toEdge, lefthand) == LinkDirection::STRAIGHT - && from->getToNode()->getDirection(succOpp, predOpp, lefthand) == LinkDirection::STRAIGHT - ) { -#ifdef DEBUG_OPPOSITE_INTERNAL - std::cout << " found " << conOpp.getInternalLaneID() << "\n"; -#endif - oppositeLength = conOpp.length; - return conOpp.getInternalLaneID(); - } else { - /* - #ifdef DEBUG_OPPOSITE_INTERNAL - std::cout << " rejected " << conOpp.getInternalLaneID() - << "\n succ.oppositeID=" << succ.oppositeID - << "\n succOppLane=" << succOpp->getLaneID(conOpp.fromLane) - << "\n pred.oppositeID=" << pred.oppositeID - << "\n predOppLane=" << predOpp->getLaneID(conOpp.toLane) - << "\n predOpp=" << predOpp->getID() - << "\n conOppTo=" << conOpp.toEdge->getID() - << "\n len1=" << con.shape.length() - << "\n len2=" << conOpp.shape.length() - << "\n"; - #endif - */ - } - } - return ""; - } else { - return ""; - } -} - - -bool -NWWriter_SUMO::writeInternalEdges(OutputDevice& into, const NBEdgeCont& ec, const NBNode& n) { - bool ret = false; - const EdgeVector& incoming = n.getIncomingEdges(); - // first pass: determine opposite internal edges and average their length - std::map oppositeLaneID; - std::map oppositeLengths; - for (NBEdge* e : incoming) { - for (const NBEdge::Connection& c : e->getConnections()) { - double oppositeLength = 0; - const std::string op = getOppositeInternalID(ec, e, c, oppositeLength); - oppositeLaneID[c.getInternalLaneID()] = op; - if (op != "") { - oppositeLengths[c.id] = oppositeLength; - } - } - } - if (oppositeLengths.size() > 0) { - for (NBEdge* e : incoming) { - for (NBEdge::Connection& c : e->getConnections()) { - if (oppositeLengths.count(c.id) > 0) { - c.length = (c.length + oppositeLengths[c.id]) / 2; - } - } - } - } - - for (NBEdge* e : incoming) { - const std::vector& elv = e->getConnections(); - if (elv.size() > 0) { - bool haveVia = false; - std::string edgeID = ""; - // second pass: write non-via edges - for (const NBEdge::Connection& k : elv) { - if (k.toEdge == nullptr) { - assert(false); // should never happen. tell me when it does - continue; - } - if (edgeID != k.id) { - if (edgeID != "") { - // close the previous edge - into.closeTag(); - } - edgeID = k.id; - into.openTag(SUMO_TAG_EDGE); - into.writeAttr(SUMO_ATTR_ID, edgeID); - into.writeAttr(SUMO_ATTR_FUNCTION, SumoXMLEdgeFunc::INTERNAL); - if (e->isBidiRail() && k.toEdge->isBidiRail() && - e != k.toEdge->getTurnDestination(true)) { - try { - NBEdge::Connection bidiCon = k.toEdge->getTurnDestination(true)->getConnection( - 0, e->getTurnDestination(true), 0); - into.writeAttr(SUMO_ATTR_BIDI, bidiCon.id); - } catch (ProcessError&) { - WRITE_WARNINGF("Could not find bidi-connection for edge '%'", edgeID) - } - } - // open a new edge - } - // to avoid changing to an internal lane which has a successor - // with the wrong permissions we need to inherit them from the successor - const NBEdge::Lane& successor = k.toEdge->getLanes()[k.toLane]; - SVCPermissions permissions = (k.permissions != SVC_UNSPECIFIED) ? k.permissions : ( - successor.permissions & e->getPermissions(k.fromLane)); - const double width = n.isConstantWidthTransition() && e->getNumLanes() > k.toEdge->getNumLanes() ? e->getLaneWidth(k.fromLane) : successor.width; - writeLane(into, k.getInternalLaneID(), k.vmax, - permissions, successor.preferred, - NBEdge::UNSPECIFIED_OFFSET, NBEdge::UNSPECIFIED_OFFSET, - std::map(), width, k.shape, &k, - k.length, k.internalLaneIndex, oppositeLaneID[k.getInternalLaneID()], ""); - haveVia = haveVia || k.haveVia; - } - ret = true; - into.closeTag(); // close the last edge - // third pass: write via edges - if (haveVia) { - for (const NBEdge::Connection& k : elv) { - if (!k.haveVia) { - continue; - } - if (k.toEdge == nullptr) { - assert(false); // should never happen. tell me when it does - continue; - } - const NBEdge::Lane& successor = k.toEdge->getLanes()[k.toLane]; - into.openTag(SUMO_TAG_EDGE); - into.writeAttr(SUMO_ATTR_ID, k.viaID); - into.writeAttr(SUMO_ATTR_FUNCTION, SumoXMLEdgeFunc::INTERNAL); - SVCPermissions permissions = (k.permissions != SVC_UNSPECIFIED) ? k.permissions : ( - successor.permissions & e->getPermissions(k.fromLane)); - writeLane(into, k.viaID + "_0", k.vmax, permissions, successor.preferred, - NBEdge::UNSPECIFIED_OFFSET, NBEdge::UNSPECIFIED_OFFSET, - std::map(), successor.width, k.viaShape, &k, - MAX2(k.viaLength, POSITION_EPS), // microsim needs positive length - 0, "", ""); - into.closeTag(); - } - } - } - } - // write pedestrian crossings - for (auto c : n.getCrossings()) { - into.openTag(SUMO_TAG_EDGE); - into.writeAttr(SUMO_ATTR_ID, c->id); - into.writeAttr(SUMO_ATTR_FUNCTION, SumoXMLEdgeFunc::CROSSING); - into.writeAttr(SUMO_ATTR_CROSSING_EDGES, c->edges); - writeLane(into, c->id + "_0", 1, SVC_PEDESTRIAN, 0, - NBEdge::UNSPECIFIED_OFFSET, NBEdge::UNSPECIFIED_OFFSET, - std::map(), c->width, c->shape, nullptr, - MAX2(c->shape.length(), POSITION_EPS), 0, "", "", false, c->customShape.size() != 0); - into.closeTag(); - } - // write pedestrian walking areas - const std::vector& WalkingAreas = n.getWalkingAreas(); - for (std::vector::const_iterator it = WalkingAreas.begin(); it != WalkingAreas.end(); it++) { - const NBNode::WalkingArea& wa = *it; - into.openTag(SUMO_TAG_EDGE); - into.writeAttr(SUMO_ATTR_ID, wa.id); - into.writeAttr(SUMO_ATTR_FUNCTION, SumoXMLEdgeFunc::WALKINGAREA); - writeLane(into, wa.id + "_0", 1, SVC_PEDESTRIAN, 0, - NBEdge::UNSPECIFIED_OFFSET, NBEdge::UNSPECIFIED_OFFSET, - std::map(), wa.width, wa.shape, nullptr, wa.length, 0, "", "", false, wa.hasCustomShape); - into.closeTag(); - } - return ret; -} - - -void -NWWriter_SUMO::writeEdge(OutputDevice& into, const NBEdge& e, bool noNames) { - // write the edge's begin - into.openTag(SUMO_TAG_EDGE).writeAttr(SUMO_ATTR_ID, e.getID()); - into.writeAttr(SUMO_ATTR_FROM, e.getFromNode()->getID()); - into.writeAttr(SUMO_ATTR_TO, e.getToNode()->getID()); - if (!noNames && e.getStreetName() != "") { - into.writeAttr(SUMO_ATTR_NAME, StringUtils::escapeXML(e.getStreetName())); - } - into.writeAttr(SUMO_ATTR_PRIORITY, e.getPriority()); - if (e.getTypeID() != "") { - into.writeAttr(SUMO_ATTR_TYPE, e.getTypeID()); - } - if (e.isMacroscopicConnector()) { - into.writeAttr(SUMO_ATTR_FUNCTION, SumoXMLEdgeFunc::CONNECTOR); - } - // write the spread type if not default ("right") - if (e.getLaneSpreadFunction() != LaneSpreadFunction::RIGHT) { - into.writeAttr(SUMO_ATTR_SPREADTYPE, e.getLaneSpreadFunction()); - } - if (e.hasLoadedLength()) { - into.writeAttr(SUMO_ATTR_LENGTH, e.getLoadedLength()); - } - if (!e.hasDefaultGeometry()) { - into.writeAttr(SUMO_ATTR_SHAPE, e.getGeometry()); - } - if (e.getStopOffsets().size() != 0) { - writeStopOffsets(into, e.getStopOffsets()); - } - if (e.isBidiRail()) { - into.writeAttr(SUMO_ATTR_BIDI, e.getTurnDestination(true)->getID()); - } - if (e.getDistance() != 0) { - into.writeAttr(SUMO_ATTR_DISTANCE, e.getDistance()); - } - - // write the lanes - const std::vector& lanes = e.getLanes(); - - const double length = e.getFinalLength(); - double startOffset = e.isBidiRail() ? e.getTurnDestination(true)->getEndOffset() : 0; - for (int i = 0; i < (int) lanes.size(); i++) { - const NBEdge::Lane& l = lanes[i]; - std::map stopOffsets; - if (l.stopOffsets != e.getStopOffsets()) { - stopOffsets = l.stopOffsets; - } - writeLane(into, e.getLaneID(i), l.speed, - l.permissions, l.preferred, - startOffset, l.endOffset, - stopOffsets, l.width, l.shape, &l, - length, i, l.oppositeID, l.type, l.accelRamp, l.customShape.size() > 0); - } - // close the edge - e.writeParams(into); - into.closeTag(); -} - - -void -NWWriter_SUMO::writeLane(OutputDevice& into, const std::string& lID, - double speed, SVCPermissions permissions, SVCPermissions preferred, - double startOffset, double endOffset, - std::map stopOffsets, double width, PositionVector shape, - const Parameterised* params, double length, int index, - const std::string& oppositeID, - const std::string& type, - bool accelRamp, bool customShape) { - // output the lane's attributes - into.openTag(SUMO_TAG_LANE).writeAttr(SUMO_ATTR_ID, lID); - // the first lane of an edge will be the depart lane - into.writeAttr(SUMO_ATTR_INDEX, index); - // write the list of allowed/disallowed vehicle classes - if (permissions != SVC_UNSPECIFIED) { - writePermissions(into, permissions); - } - writePreferences(into, preferred); - // some further information - if (speed == 0) { - WRITE_WARNINGF("Lane '%' has a maximum allowed speed of 0.", lID); - } else if (speed < 0) { - throw ProcessError("Negative allowed speed (" + toString(speed) + ") on lane '" + lID + "', use --speed.minimum to prevent this."); - } - into.writeAttr(SUMO_ATTR_SPEED, speed); - into.writeAttr(SUMO_ATTR_LENGTH, length); - if (endOffset != NBEdge::UNSPECIFIED_OFFSET) { - into.writeAttr(SUMO_ATTR_ENDOFFSET, endOffset); - } - if (width != NBEdge::UNSPECIFIED_WIDTH) { - into.writeAttr(SUMO_ATTR_WIDTH, width); - } - if (accelRamp) { - into.writeAttr(SUMO_ATTR_ACCELERATION, accelRamp); - } - if (customShape) { - into.writeAttr(SUMO_ATTR_CUSTOMSHAPE, true); - } - if (endOffset > 0 || startOffset > 0) { - if (startOffset + endOffset < shape.length()) { - shape = shape.getSubpart(startOffset, shape.length() - endOffset); - } else { - WRITE_ERROR("Invalid endOffset " + toString(endOffset) + " at lane '" + lID - + "' with length " + toString(shape.length()) + " (startOffset " + toString(startOffset) + ")"); - if (!OptionsCont::getOptions().getBool("ignore-errors")) { - throw ProcessError(); - } - } - } - into.writeAttr(SUMO_ATTR_SHAPE, shape); - if (type != "") { - into.writeAttr(SUMO_ATTR_TYPE, type); - } - - if (stopOffsets.size() != 0) { - writeStopOffsets(into, stopOffsets); - } - - if (oppositeID != "" && oppositeID != "-") { - into.openTag(SUMO_TAG_NEIGH); - into.writeAttr(SUMO_ATTR_LANE, oppositeID); - into.closeTag(); - } - - if (params != nullptr) { - params->writeParams(into); - } - - into.closeTag(); -} - - -void -NWWriter_SUMO::writeJunction(OutputDevice& into, const NBNode& n) { - // write the attributes - into.openTag(SUMO_TAG_JUNCTION).writeAttr(SUMO_ATTR_ID, n.getID()); - into.writeAttr(SUMO_ATTR_TYPE, n.getType()); - NWFrame::writePositionLong(n.getPosition(), into); - // write the incoming lanes - std::vector incLanes; - const std::vector& incoming = n.getIncomingEdges(); - for (std::vector::const_iterator i = incoming.begin(); i != incoming.end(); ++i) { - int noLanes = (*i)->getNumLanes(); - for (int j = 0; j < noLanes; j++) { - incLanes.push_back((*i)->getLaneID(j)); - } - } - std::vector crossings = n.getCrossings(); - std::set prevWAs; - // avoid duplicates - for (auto c : crossings) { - if (prevWAs.count(c->prevWalkingArea) == 0) { - incLanes.push_back(c->prevWalkingArea + "_0"); - prevWAs.insert(c->prevWalkingArea); - } - } - into.writeAttr(SUMO_ATTR_INCLANES, incLanes); - // write the internal lanes - std::vector intLanes; - if (!OptionsCont::getOptions().getBool("no-internal-links")) { - for (EdgeVector::const_iterator i = incoming.begin(); i != incoming.end(); i++) { - const std::vector& elv = (*i)->getConnections(); - for (std::vector::const_iterator k = elv.begin(); k != elv.end(); ++k) { - if ((*k).toEdge == nullptr) { - continue; - } - if (!(*k).haveVia) { - intLanes.push_back((*k).getInternalLaneID()); - } else { - intLanes.push_back((*k).viaID + "_0"); - } - } - } - } - if (n.getType() != SumoXMLNodeType::DEAD_END && n.getType() != SumoXMLNodeType::NOJUNCTION) { - for (auto c : crossings) { - intLanes.push_back(c->id + "_0"); - } - } - into.writeAttr(SUMO_ATTR_INTLANES, intLanes); - // close writing - into.writeAttr(SUMO_ATTR_SHAPE, n.getShape().simplified()); - // write optional radius - if (n.getRadius() != NBNode::UNSPECIFIED_RADIUS) { - into.writeAttr(SUMO_ATTR_RADIUS, n.getRadius()); - } - // specify whether a custom shape was used - if (n.hasCustomShape()) { - into.writeAttr(SUMO_ATTR_CUSTOMSHAPE, true); - } - if (n.getRightOfWay() != RightOfWay::DEFAULT) { - into.writeAttr(SUMO_ATTR_RIGHT_OF_WAY, toString(n.getRightOfWay())); - } - if (n.getFringeType() != FringeType::DEFAULT) { - into.writeAttr(SUMO_ATTR_FRINGE, toString(n.getFringeType())); - } - if (n.getName() != "") { - into.writeAttr(SUMO_ATTR_NAME, n.getName()); - } - if (n.getType() != SumoXMLNodeType::DEAD_END) { - // write right-of-way logics - n.writeLogic(into); - } - n.writeParams(into); - into.closeTag(); -} - - -bool -NWWriter_SUMO::writeInternalNodes(OutputDevice& into, const NBNode& n) { - bool ret = false; - const std::vector& incoming = n.getIncomingEdges(); - // build the list of internal lane ids - std::vector internalLaneIDs; - std::map viaIDs; - for (EdgeVector::const_iterator i = incoming.begin(); i != incoming.end(); i++) { - const std::vector& elv = (*i)->getConnections(); - for (std::vector::const_iterator k = elv.begin(); k != elv.end(); ++k) { - if ((*k).toEdge != nullptr) { - internalLaneIDs.push_back((*k).getInternalLaneID()); - viaIDs[(*k).getInternalLaneID()] = ((*k).viaID); - } - } - } - for (auto c : n.getCrossings()) { - internalLaneIDs.push_back(c->id + "_0"); - } - // write the internal nodes - for (std::vector::const_iterator i = incoming.begin(); i != incoming.end(); i++) { - const std::vector& elv = (*i)->getConnections(); - for (std::vector::const_iterator k = elv.begin(); k != elv.end(); ++k) { - if ((*k).toEdge == nullptr || !(*k).haveVia) { - continue; - } - Position pos = (*k).shape[-1]; - into.openTag(SUMO_TAG_JUNCTION).writeAttr(SUMO_ATTR_ID, (*k).viaID + "_0"); - into.writeAttr(SUMO_ATTR_TYPE, SumoXMLNodeType::INTERNAL); - NWFrame::writePositionLong(pos, into); - std::string incLanes = (*k).getInternalLaneID(); - std::vector foeIDs; - for (std::string incLane : (*k).foeIncomingLanes) { - incLanes += " " + incLane; - if (incLane[0] == ':' && viaIDs[incLane] != "") { - // intersecting left turns - foeIDs.push_back(viaIDs[incLane] + "_0"); - } - } - into.writeAttr(SUMO_ATTR_INCLANES, incLanes); - const std::vector& foes = (*k).foeInternalLinks; - for (std::vector::const_iterator it = foes.begin(); it != foes.end(); ++it) { - foeIDs.push_back(internalLaneIDs[*it]); - } - into.writeAttr(SUMO_ATTR_INTLANES, joinToString(foeIDs, " ")); - into.closeTag(); - ret = true; - } - } - return ret; -} - - -void -NWWriter_SUMO::writeConnection(OutputDevice& into, const NBEdge& from, const NBEdge::Connection& c, - bool includeInternal, ConnectionStyle style, bool geoAccuracy) { - assert(c.toEdge != 0); - into.openTag(SUMO_TAG_CONNECTION); - into.writeAttr(SUMO_ATTR_FROM, from.getID()); - into.writeAttr(SUMO_ATTR_TO, c.toEdge->getID()); - into.writeAttr(SUMO_ATTR_FROM_LANE, c.fromLane); - into.writeAttr(SUMO_ATTR_TO_LANE, c.toLane); - if (c.mayDefinitelyPass && style != TLL) { - into.writeAttr(SUMO_ATTR_PASS, c.mayDefinitelyPass); - } - if ((from.getToNode()->getKeepClear() == false || c.keepClear == false) && style != TLL) { - into.writeAttr(SUMO_ATTR_KEEP_CLEAR, false); - } - if (c.contPos != NBEdge::UNSPECIFIED_CONTPOS && style != TLL) { - into.writeAttr(SUMO_ATTR_CONTPOS, c.contPos); - } - if (c.visibility != NBEdge::UNSPECIFIED_VISIBILITY_DISTANCE && style != TLL) { - into.writeAttr(SUMO_ATTR_VISIBILITY_DISTANCE, c.visibility); - } - if (c.permissions != SVC_UNSPECIFIED && style != TLL) { - writePermissions(into, c.permissions); - } - if (c.speed != NBEdge::UNSPECIFIED_SPEED && style != TLL) { - into.writeAttr(SUMO_ATTR_SPEED, c.speed); - } - if (c.customLength != NBEdge::UNSPECIFIED_LOADED_LENGTH && style != TLL) { - into.writeAttr(SUMO_ATTR_LENGTH, c.customLength); - } - if (c.customShape.size() != 0 && style != TLL) { - if (geoAccuracy) { - into.setPrecision(gPrecisionGeo); - } - into.writeAttr(SUMO_ATTR_SHAPE, c.customShape); - if (geoAccuracy) { - into.setPrecision(); - } - } - if (c.uncontrolled != false && style != TLL) { - into.writeAttr(SUMO_ATTR_UNCONTROLLED, c.uncontrolled); - } - if (style != PLAIN) { - if (includeInternal) { - into.writeAttr(SUMO_ATTR_VIA, c.getInternalLaneID()); - } - // set information about the controlling tl if any - if (c.tlID != "") { - into.writeAttr(SUMO_ATTR_TLID, c.tlID); - into.writeAttr(SUMO_ATTR_TLLINKINDEX, c.tlLinkIndex); - if (c.tlLinkIndex2 >= 0) { - into.writeAttr(SUMO_ATTR_TLLINKINDEX2, c.tlLinkIndex2); - } - } - if (style == SUMONET) { - // write the direction information - LinkDirection dir = from.getToNode()->getDirection(&from, c.toEdge, OptionsCont::getOptions().getBool("lefthand")); - assert(dir != LinkDirection::NODIR); - into.writeAttr(SUMO_ATTR_DIR, toString(dir)); - // write the state information - const LinkState linkState = from.getToNode()->getLinkState( - &from, c.toEdge, c.fromLane, c.toLane, c.mayDefinitelyPass, c.tlID); - into.writeAttr(SUMO_ATTR_STATE, linkState); - } - } - c.writeParams(into); - into.closeTag(); -} - - -bool -NWWriter_SUMO::writeInternalConnections(OutputDevice& into, const NBNode& n) { - bool ret = false; - const bool lefthand = OptionsCont::getOptions().getBool("lefthand"); - const std::vector& incoming = n.getIncomingEdges(); - for (std::vector::const_iterator i = incoming.begin(); i != incoming.end(); ++i) { - NBEdge* from = *i; - const std::vector& connections = from->getConnections(); - for (std::vector::const_iterator j = connections.begin(); j != connections.end(); ++j) { - const NBEdge::Connection& c = *j; - LinkDirection dir = n.getDirection(from, c.toEdge, lefthand); - assert(c.toEdge != 0); - if (c.haveVia) { - // internal split with optional signal - std::string tlID = ""; - int linkIndex2 = NBConnection::InvalidTlIndex; - if (c.tlLinkIndex2 != NBConnection::InvalidTlIndex) { - linkIndex2 = c.tlLinkIndex2; - tlID = c.tlID; - } - writeInternalConnection(into, c.id, c.toEdge->getID(), c.internalLaneIndex, c.toLane, c.viaID + "_0", dir, tlID, linkIndex2); - writeInternalConnection(into, c.viaID, c.toEdge->getID(), 0, c.toLane, "", dir); - } else { - // no internal split - writeInternalConnection(into, c.id, c.toEdge->getID(), c.internalLaneIndex, c.toLane, "", dir); - } - ret = true; - } - } - return ret; -} - - -void -NWWriter_SUMO::writeInternalConnection(OutputDevice& into, - const std::string& from, const std::string& to, - int fromLane, int toLane, const std::string& via, - LinkDirection dir, const std::string& tlID, int linkIndex) { - into.openTag(SUMO_TAG_CONNECTION); - into.writeAttr(SUMO_ATTR_FROM, from); - into.writeAttr(SUMO_ATTR_TO, to); - into.writeAttr(SUMO_ATTR_FROM_LANE, fromLane); - into.writeAttr(SUMO_ATTR_TO_LANE, toLane); - if (via != "") { - into.writeAttr(SUMO_ATTR_VIA, via); - } - if (tlID != "" && linkIndex != NBConnection::InvalidTlIndex) { - // used for the reverse direction of pedestrian crossings - into.writeAttr(SUMO_ATTR_TLID, tlID); - into.writeAttr(SUMO_ATTR_TLLINKINDEX, linkIndex); - } - into.writeAttr(SUMO_ATTR_DIR, dir); - into.writeAttr(SUMO_ATTR_STATE, (via != "" ? "m" : "M")); - into.closeTag(); -} - - -void -NWWriter_SUMO::writeRoundabouts(OutputDevice& into, const std::set& roundabouts, - const NBEdgeCont& ec) { - // make output deterministic - std::vector > edgeIDs; - for (std::set::const_iterator i = roundabouts.begin(); i != roundabouts.end(); ++i) { - std::vector tEdgeIDs; - for (EdgeSet::const_iterator j = (*i).begin(); j != (*i).end(); ++j) { - // the edges may have been erased from NBEdgeCont but their pointers are still valid - // we verify their existance in writeRoundabout() - tEdgeIDs.push_back((*j)->getID()); - } - std::sort(tEdgeIDs.begin(), tEdgeIDs.end()); - edgeIDs.push_back(tEdgeIDs); - } - std::sort(edgeIDs.begin(), edgeIDs.end()); - // write - for (std::vector >::const_iterator i = edgeIDs.begin(); i != edgeIDs.end(); ++i) { - writeRoundabout(into, *i, ec); - } - if (roundabouts.size() != 0) { - into.lf(); - } -} - - -void -NWWriter_SUMO::writeRoundabout(OutputDevice& into, const std::vector& edgeIDs, - const NBEdgeCont& ec) { - std::vector validEdgeIDs; - std::vector invalidEdgeIDs; - std::vector nodeIDs; - for (std::vector::const_iterator i = edgeIDs.begin(); i != edgeIDs.end(); ++i) { - const NBEdge* edge = ec.retrieve(*i); - if (edge != nullptr) { - nodeIDs.push_back(edge->getToNode()->getID()); - validEdgeIDs.push_back(edge->getID()); - } else { - invalidEdgeIDs.push_back(*i); - } - } - std::sort(nodeIDs.begin(), nodeIDs.end()); - if (validEdgeIDs.size() > 0) { - into.openTag(SUMO_TAG_ROUNDABOUT); - into.writeAttr(SUMO_ATTR_NODES, joinToString(nodeIDs, " ")); - into.writeAttr(SUMO_ATTR_EDGES, joinToString(validEdgeIDs, " ")); - into.closeTag(); - if (invalidEdgeIDs.size() > 0) { - WRITE_WARNING("Writing incomplete roundabout. Edges: '" - + joinToString(invalidEdgeIDs, " ") + "' no longer exist'"); - } - } -} - - -void -NWWriter_SUMO::writeDistrict(OutputDevice& into, const NBDistrict& d) { - std::vector sourceW = d.getSourceWeights(); - VectorHelper::normaliseSum(sourceW, 1.0); - std::vector sinkW = d.getSinkWeights(); - VectorHelper::normaliseSum(sinkW, 1.0); - // write the head and the id of the district - into.openTag(SUMO_TAG_TAZ).writeAttr(SUMO_ATTR_ID, d.getID()); - if (d.getShape().size() > 0) { - into.writeAttr(SUMO_ATTR_SHAPE, d.getShape()); - } - // write all sources - const std::vector& sources = d.getSourceEdges(); - for (int i = 0; i < (int)sources.size(); i++) { - // write the head and the id of the source - into.openTag(SUMO_TAG_TAZSOURCE).writeAttr(SUMO_ATTR_ID, sources[i]->getID()).writeAttr(SUMO_ATTR_WEIGHT, sourceW[i]); - into.closeTag(); - } - // write all sinks - const std::vector& sinks = d.getSinkEdges(); - for (int i = 0; i < (int)sinks.size(); i++) { - // write the head and the id of the sink - into.openTag(SUMO_TAG_TAZSINK).writeAttr(SUMO_ATTR_ID, sinks[i]->getID()).writeAttr(SUMO_ATTR_WEIGHT, sinkW[i]); - into.closeTag(); - } - // write the tail - into.closeTag(); -} - - -std::string -NWWriter_SUMO::writeSUMOTime(SUMOTime steps) { - double time = STEPS2TIME(steps); - if (time == std::floor(time)) { - return toString(int(time)); - } else { - return toString(time); - } -} - - -void -NWWriter_SUMO::writeProhibitions(OutputDevice& into, const NBConnectionProhibits& prohibitions) { - for (NBConnectionProhibits::const_iterator j = prohibitions.begin(); j != prohibitions.end(); j++) { - NBConnection prohibited = (*j).first; - const NBConnectionVector& prohibiting = (*j).second; - for (NBConnectionVector::const_iterator k = prohibiting.begin(); k != prohibiting.end(); k++) { - NBConnection prohibitor = *k; - into.openTag(SUMO_TAG_PROHIBITION); - into.writeAttr(SUMO_ATTR_PROHIBITOR, prohibitionConnection(prohibitor)); - into.writeAttr(SUMO_ATTR_PROHIBITED, prohibitionConnection(prohibited)); - into.closeTag(); - } - } -} - - -std::string -NWWriter_SUMO::prohibitionConnection(const NBConnection& c) { - return c.getFrom()->getID() + "->" + c.getTo()->getID(); -} - - -void -NWWriter_SUMO::writeTrafficLights(OutputDevice& into, const NBTrafficLightLogicCont& tllCont) { - std::vector logics = tllCont.getComputed(); - for (NBTrafficLightLogic* logic : logics) { - writeTrafficLight(into, logic); - } - if (logics.size() > 0) { - into.lf(); - } -} - - -void -NWWriter_SUMO::writeTrafficLight(OutputDevice& into, const NBTrafficLightLogic* logic) { - into.openTag(SUMO_TAG_TLLOGIC); - into.writeAttr(SUMO_ATTR_ID, logic->getID()); - into.writeAttr(SUMO_ATTR_TYPE, logic->getType()); - into.writeAttr(SUMO_ATTR_PROGRAMID, logic->getProgramID()); - into.writeAttr(SUMO_ATTR_OFFSET, writeSUMOTime(logic->getOffset())); - // write the phases - const bool varPhaseLength = logic->getType() != TrafficLightType::STATIC; - for (const NBTrafficLightLogic::PhaseDefinition& phase : logic->getPhases()) { - into.openTag(SUMO_TAG_PHASE); - into.writeAttr(SUMO_ATTR_DURATION, writeSUMOTime(phase.duration)); - if (phase.duration < TIME2STEPS(10)) { - into.writePadding(" "); - } - into.writeAttr(SUMO_ATTR_STATE, phase.state); - if (varPhaseLength) { - if (phase.minDur != NBTrafficLightDefinition::UNSPECIFIED_DURATION) { - into.writeAttr(SUMO_ATTR_MINDURATION, writeSUMOTime(phase.minDur)); - } - if (phase.maxDur != NBTrafficLightDefinition::UNSPECIFIED_DURATION) { - into.writeAttr(SUMO_ATTR_MAXDURATION, writeSUMOTime(phase.maxDur)); - } - } - if (phase.name != "") { - into.writeAttr(SUMO_ATTR_NAME, phase.name); - } - if (phase.next.size() > 0) { - into.writeAttr(SUMO_ATTR_NEXT, phase.next); - } - into.closeTag(); - } - // write params - logic->writeParams(into); - into.closeTag(); -} - - -void -NWWriter_SUMO::writeStopOffsets(OutputDevice& into, const std::map& stopOffsets) { - if (stopOffsets.size() == 0) { - return; - } - assert(stopOffsets.size() == 1); - std::pair offset = *stopOffsets.begin(); - std::string ss_vclasses = getVehicleClassNames(offset.first); - if (ss_vclasses.length() == 0) { - // This stopOffset would have no effect... - return; - } - into.openTag(SUMO_TAG_STOPOFFSET); - std::string ss_exceptions = getVehicleClassNames(~offset.first); - if (ss_vclasses.length() <= ss_exceptions.length()) { - into.writeAttr(SUMO_ATTR_VCLASSES, ss_vclasses); - } else { - if (ss_exceptions.length() == 0) { - into.writeAttr(SUMO_ATTR_VCLASSES, "all"); - } else { - into.writeAttr(SUMO_ATTR_EXCEPTIONS, ss_exceptions); - } - } - into.writeAttr(SUMO_ATTR_VALUE, offset.second); - into.closeTag(); -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netwrite/NWWriter_SUMO.h b/Util/OSM2ODR/src/netwrite/NWWriter_SUMO.h deleted file mode 100644 index 017221887..000000000 --- a/Util/OSM2ODR/src/netwrite/NWWriter_SUMO.h +++ /dev/null @@ -1,204 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NWWriter_SUMO.h -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @author Leonhard Luecken -/// @date Tue, 04.05.2011 -/// -// Exporter writing networks using the SUMO format -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include -#include -#include -#include - - -// =========================================================================== -// class declarations -// =========================================================================== -class OutputDevice; -class OptionsCont; -class NBNetBuilder; -class NBTrafficLightLogic; -class NBTrafficLightLogicCont; -class NBNode; -class NBDistrict; -class NBEdgeControl; - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NWWriter_SUMO - * @brief Exporter writing networks using the SUMO format - * - */ -class NWWriter_SUMO { -public: - - enum ConnectionStyle { - SUMONET, // all connection information - PLAIN, // only edges and link indices - TLL // like plain but include tl information - }; - - /** @brief Writes the network into a SUMO-file - * - * @param[in] oc The options to use - * @param[in] nb The network builder to fill - */ - static void writeNetwork(const OptionsCont& oc, NBNetBuilder& nb); - - - /** @brief Writes connections outgoing from the given edge (also used in NWWriter_XML) - * @param[in] into The device to write the edge into - * @param[in] from The edge to write connections for - * @param[in] c The connection to write - * @param[in] includeInternal Whether information about inner-lanes used to cross the intersection shall be written - * @param[in] plain Whether only plain-xml output should be written (omit some attributes) - */ - static void writeConnection(OutputDevice& into, const NBEdge& from, const NBEdge::Connection& c, - bool includeInternal, ConnectionStyle style = SUMONET, bool geoAccuracy = false); - - /// @brief writes the given prohibitions - static void writeProhibitions(OutputDevice& into, const NBConnectionProhibits& prohibitions); - - /// @brief writes the traffic light logics to the given device - static void writeTrafficLights(OutputDevice& into, const NBTrafficLightLogicCont& tllCont); - - /// @brief writes a single traffic light logic to the given device - static void writeTrafficLight(OutputDevice& into, const NBTrafficLightLogic* logic); - - /** @brief Writes roundabouts - * @param[in] into The device to write the edge into - * @param[in] roundaboutes The roundabouts to write - * @param[in] ec The edge control to retrieve named edges from - */ - static void writeRoundabouts(OutputDevice& into, const std::set& roundabouts, - const NBEdgeCont& ec); - - - /** @brief Write a stopOffset element into output device - */ - static void writeStopOffsets(OutputDevice& into, const std::map& stopOffsets); - - /** @brief Writes a district - * @param[in] into The device to write the edge into - * @param[in] d The district - */ - static void writeDistrict(OutputDevice& into, const NBDistrict& d); - - -private: - /// @name Methods for writing network parts - /// @{ - - /** @brief Writes internal edges ( stopOffsets, double width, PositionVector shape, - const Parameterised* params, double length, int index, - const std::string& oppositeID, const std::string& type, - bool accelRamp = false, - bool customShape = false); - - - /** @brief Writes a junction (& r, - const NBEdgeCont& ec); - - /// @brief retrieve the id of the opposite direction internal lane if it exists - static std::string getOppositeInternalID(const NBEdgeCont& ec, const NBEdge* from, const NBEdge::Connection& con, double& oppositeLength); - -}; diff --git a/Util/OSM2ODR/src/netwrite/NWWriter_XML.cpp b/Util/OSM2ODR/src/netwrite/NWWriter_XML.cpp deleted file mode 100644 index 800c5dc61..000000000 --- a/Util/OSM2ODR/src/netwrite/NWWriter_XML.cpp +++ /dev/null @@ -1,474 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NWWriter_XML.cpp -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @author Leonhard Luecken -/// @date Tue, 11.05.2011 -/// -// Exporter writing networks using XML (native input) format -/****************************************************************************/ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "NWFrame.h" -#include "NWWriter_SUMO.h" -#include "NWWriter_XML.h" - - - -// =========================================================================== -// method definitions -// =========================================================================== -// --------------------------------------------------------------------------- -// static methods -// --------------------------------------------------------------------------- -void -NWWriter_XML::writeNetwork(const OptionsCont& oc, NBNetBuilder& nb) { - // check whether plain-output files shall be generated - if (oc.isSet("plain-output-prefix")) { - writeNodes(oc, nb.getNodeCont()); - if (nb.getTypeCont().size() > 0) { - writeTypes(oc, nb.getTypeCont()); - } - writeEdgesAndConnections(oc, nb.getNodeCont(), nb.getEdgeCont()); - writeTrafficLights(oc, nb.getTLLogicCont(), nb.getEdgeCont()); - } - if (oc.isSet("junctions.join-output")) { - writeJoinedJunctions(oc, nb.getNodeCont()); - } - if (oc.isSet("street-sign-output")) { - writeStreetSigns(oc, nb.getEdgeCont()); - } - if (oc.exists("ptstop-output") && oc.isSet("ptstop-output")) { - writePTStops(oc, nb.getPTStopCont()); - } - if (oc.exists("ptline-output") && oc.isSet("ptline-output")) { - writePTLines(oc, nb.getPTLineCont(), nb.getEdgeCont()); - } - - if (oc.exists("parking-output") && oc.isSet("parking-output")) { - writeParkingAreas(oc, nb.getParkingCont(), nb.getEdgeCont()); - } - if (oc.exists("taz-output") && oc.isSet("taz-output")) { - writeDistricts(oc, nb.getDistrictCont()); - } -} - - -void -NWWriter_XML::writeNodes(const OptionsCont& oc, NBNodeCont& nc) { - const GeoConvHelper& gch = GeoConvHelper::getFinal(); - bool useGeo = oc.exists("proj.plain-geo") && oc.getBool("proj.plain-geo"); - if (useGeo && !gch.usingGeoProjection()) { - WRITE_WARNING("Ignoring option \"proj.plain-geo\" because no geo-conversion has been defined"); - useGeo = false; - } - const bool geoAccuracy = useGeo || gch.usingInverseGeoProjection(); - - OutputDevice& device = OutputDevice::getDevice(oc.getString("plain-output-prefix") + ".nod.xml"); - std::map attrs; - attrs[SUMO_ATTR_VERSION] = toString(NETWORK_VERSION, 1); - device.writeXMLHeader("nodes", "nodes_file.xsd", attrs); - - // write network offsets and projection to allow reconstruction of original coordinates - if (!useGeo) { - GeoConvHelper::writeLocation(device); - } - - // write nodes - for (std::map::const_iterator i = nc.begin(); i != nc.end(); ++i) { - NBNode* n = (*i).second; - device.openTag(SUMO_TAG_NODE); - device.writeAttr(SUMO_ATTR_ID, n->getID()); - // write position - Position pos = n->getPosition(); - if (useGeo) { - gch.cartesian2geo(pos); - } - if (geoAccuracy) { - device.setPrecision(gPrecisionGeo); - } - NWFrame::writePositionLong(pos, device); - if (geoAccuracy) { - device.setPrecision(); - } - - device.writeAttr(SUMO_ATTR_TYPE, toString(n->getType())); - if (n->isTLControlled()) { - const std::set& tlss = n->getControllingTLS(); - // set may contain multiple programs for the same id. - // make sure ids are unique and sorted - std::set tlsIDs; - std::set controlledInnerEdges; - for (std::set::const_iterator it_tl = tlss.begin(); it_tl != tlss.end(); it_tl++) { - tlsIDs.insert((*it_tl)->getID()); - std::vector cie = (*it_tl)->getControlledInnerEdges(); - controlledInnerEdges.insert(cie.begin(), cie.end()); - } - std::vector sortedIDs(tlsIDs.begin(), tlsIDs.end()); - sort(sortedIDs.begin(), sortedIDs.end()); - device.writeAttr(SUMO_ATTR_TLID, sortedIDs); - if (controlledInnerEdges.size() > 0) { - std::vector sortedCIEs(controlledInnerEdges.begin(), controlledInnerEdges.end()); - sort(sortedCIEs.begin(), sortedCIEs.end()); - device.writeAttr(SUMO_ATTR_CONTROLLED_INNER, joinToString(sortedCIEs, " ")); - } - } - if (n->hasCustomShape()) { - writeShape(device, gch, n->getShape(), SUMO_ATTR_SHAPE, useGeo, geoAccuracy); - } - if (n->getRadius() != NBNode::UNSPECIFIED_RADIUS) { - device.writeAttr(SUMO_ATTR_RADIUS, n->getRadius()); - } - if (n->getKeepClear() == false) { - device.writeAttr(SUMO_ATTR_KEEP_CLEAR, n->getKeepClear()); - } - if (n->getRightOfWay() != RightOfWay::DEFAULT) { - device.writeAttr(SUMO_ATTR_RIGHT_OF_WAY, toString(n->getRightOfWay())); - } - if (n->getFringeType() != FringeType::DEFAULT) { - device.writeAttr(SUMO_ATTR_FRINGE, toString(n->getFringeType())); - } - if (n->getName() != "") { - device.writeAttr(SUMO_ATTR_NAME, n->getName()); - } - n->writeParams(device); - device.closeTag(); - } - device.close(); -} - - -void -NWWriter_XML::writeTypes(const OptionsCont& oc, NBTypeCont& tc) { - OutputDevice& device = OutputDevice::getDevice(oc.getString("plain-output-prefix") + ".typ.xml"); - std::map attrs; - attrs[SUMO_ATTR_VERSION] = toString(NETWORK_VERSION, 1); - device.writeXMLHeader("types", "types_file.xsd", attrs); - tc.writeTypes(device); - device.close(); -} - - -void -NWWriter_XML::writeEdgesAndConnections(const OptionsCont& oc, NBNodeCont& nc, NBEdgeCont& ec) { - const GeoConvHelper& gch = GeoConvHelper::getFinal(); - bool useGeo = oc.exists("proj.plain-geo") && oc.getBool("proj.plain-geo"); - const bool geoAccuracy = useGeo || gch.usingInverseGeoProjection(); - - std::map attrs; - attrs[SUMO_ATTR_VERSION] = toString(NETWORK_VERSION, 1); - OutputDevice& edevice = OutputDevice::getDevice(oc.getString("plain-output-prefix") + ".edg.xml"); - edevice.writeXMLHeader("edges", "edges_file.xsd", attrs); - OutputDevice& cdevice = OutputDevice::getDevice(oc.getString("plain-output-prefix") + ".con.xml"); - cdevice.writeXMLHeader("connections", "connections_file.xsd", attrs); - const bool writeNames = oc.getBool("output.street-names"); - LaneSpreadFunction defaultSpread = SUMOXMLDefinitions::LaneSpreadFunctions.get(oc.getString("default.spreadtype")); - for (std::map::const_iterator i = ec.begin(); i != ec.end(); ++i) { - // write the edge itself to the edges-files - NBEdge* e = (*i).second; - edevice.openTag(SUMO_TAG_EDGE); - edevice.writeAttr(SUMO_ATTR_ID, e->getID()); - edevice.writeAttr(SUMO_ATTR_FROM, e->getFromNode()->getID()); - edevice.writeAttr(SUMO_ATTR_TO, e->getToNode()->getID()); - if (writeNames && e->getStreetName() != "") { - edevice.writeAttr(SUMO_ATTR_NAME, StringUtils::escapeXML(e->getStreetName())); - } - edevice.writeAttr(SUMO_ATTR_PRIORITY, e->getPriority()); - // write the type if given - if (e->getTypeID() != "") { - edevice.writeAttr(SUMO_ATTR_TYPE, e->getTypeID()); - } - edevice.writeAttr(SUMO_ATTR_NUMLANES, e->getNumLanes()); - if (!e->hasLaneSpecificSpeed()) { - edevice.writeAttr(SUMO_ATTR_SPEED, e->getSpeed()); - } - // write non-default geometry - if (!e->hasDefaultGeometry()) { - writeShape(edevice, gch, e->getGeometry(), SUMO_ATTR_SHAPE, useGeo, geoAccuracy); - } - // write the spread type if not default ("right") - if (e->getLaneSpreadFunction() != defaultSpread) { - edevice.writeAttr(SUMO_ATTR_SPREADTYPE, toString(e->getLaneSpreadFunction())); - } - // write the length if it was specified - if (e->hasLoadedLength()) { - edevice.writeAttr(SUMO_ATTR_LENGTH, e->getLoadedLength()); - } - // some attributes can be set by edge default or per lane. Write as default if possible (efficiency) - if (e->getLaneWidth() != NBEdge::UNSPECIFIED_WIDTH && !e->hasLaneSpecificWidth()) { - edevice.writeAttr(SUMO_ATTR_WIDTH, e->getLaneWidth()); - } - if (e->getEndOffset() != NBEdge::UNSPECIFIED_OFFSET && !e->hasLaneSpecificEndOffset()) { - edevice.writeAttr(SUMO_ATTR_ENDOFFSET, e->getEndOffset()); - } - if (!e->hasLaneSpecificPermissions()) { - writePermissions(edevice, e->getPermissions(0)); - } - if (!e->hasLaneSpecificStopOffsets() && e->getStopOffsets().size() != 0) { - NWWriter_SUMO::writeStopOffsets(edevice, e->getStopOffsets()); - } - if (e->getDistance() != 0) { - edevice.writeAttr(SUMO_ATTR_DISTANCE, e->getDistance()); - } - if (e->needsLaneSpecificOutput()) { - for (int i = 0; i < (int)e->getLanes().size(); ++i) { - const NBEdge::Lane& lane = e->getLanes()[i]; - edevice.openTag(SUMO_TAG_LANE); - edevice.writeAttr(SUMO_ATTR_INDEX, i); - // write allowed lanes - if (e->hasLaneSpecificPermissions()) { - writePermissions(edevice, lane.permissions); - } - writePreferences(edevice, lane.preferred); - // write other attributes - if (lane.width != NBEdge::UNSPECIFIED_WIDTH && e->hasLaneSpecificWidth()) { - edevice.writeAttr(SUMO_ATTR_WIDTH, lane.width); - } - if (lane.endOffset != NBEdge::UNSPECIFIED_OFFSET && e->hasLaneSpecificEndOffset()) { - edevice.writeAttr(SUMO_ATTR_ENDOFFSET, lane.endOffset); - } - if (e->hasLaneSpecificSpeed()) { - edevice.writeAttr(SUMO_ATTR_SPEED, lane.speed); - } - if (lane.accelRamp) { - edevice.writeAttr(SUMO_ATTR_ACCELERATION, lane.accelRamp); - } - if (lane.customShape.size() > 0) { - writeShape(edevice, gch, lane.customShape, SUMO_ATTR_SHAPE, useGeo, geoAccuracy); - } - if (lane.type != "") { - edevice.writeAttr(SUMO_ATTR_TYPE, lane.type); - } - if (lane.oppositeID != "") { - edevice.openTag(SUMO_TAG_NEIGH); - edevice.writeAttr(SUMO_ATTR_LANE, lane.oppositeID); - edevice.closeTag(); - } - lane.writeParams(edevice); - NWWriter_SUMO::writeStopOffsets(edevice, lane.stopOffsets); - edevice.closeTag(); - } - } - e->writeParams(edevice); - edevice.closeTag(); - // write this edge's connections to the connections-files - const std::vector connections = e->getConnections(); - if (connections.empty()) { - // if there are no connections and this appears to be customized, preserve the information - const int numOutgoing = (int)e->getToNode()->getOutgoingEdges().size(); - if (numOutgoing > 0) { - const SVCPermissions inPerm = e->getPermissions(); - SVCPermissions outPerm = 0; - for (auto out : e->getToNode()->getOutgoingEdges()) { - outPerm |= out->getPermissions(); - } - if ((inPerm & outPerm) != 0 && (inPerm & outPerm) != SVC_PEDESTRIAN) { - cdevice.openTag(SUMO_TAG_CONNECTION); - cdevice.writeAttr(SUMO_ATTR_FROM, e->getID()); - cdevice.closeTag(); - cdevice << "\n"; - } - } - } else { - for (NBEdge::Connection c : connections) { - if (useGeo) { - for (int i = 0; i < (int) c.customShape.size(); i++) { - gch.cartesian2geo(c.customShape[i]); - } - } - NWWriter_SUMO::writeConnection(cdevice, *e, c, false, NWWriter_SUMO::PLAIN, geoAccuracy); - } - cdevice << "\n"; - } - } - // write roundabout information to the edges-files - if (ec.getRoundabouts().size() > 0) { - edevice.lf(); - NWWriter_SUMO::writeRoundabouts(edevice, ec.getRoundabouts(), ec); - } - - // write loaded prohibitions to the connections-file - for (std::map::const_iterator i = nc.begin(); i != nc.end(); ++i) { - NWWriter_SUMO::writeProhibitions(cdevice, i->second->getProhibitions()); - } - // write pedestrian crossings to the connections-file - for (std::map::const_iterator it_node = nc.begin(); it_node != nc.end(); ++it_node) { - const std::vector& crossings = (*it_node).second->getCrossings(); - for (auto c : crossings) { - cdevice.openTag(SUMO_TAG_CROSSING); - cdevice.writeAttr(SUMO_ATTR_NODE, (*it_node).second->getID()); - cdevice.writeAttr(SUMO_ATTR_EDGES, c->edges); - cdevice.writeAttr(SUMO_ATTR_PRIORITY, c->priority); - if (c->customWidth != NBEdge::UNSPECIFIED_WIDTH) { - cdevice.writeAttr(SUMO_ATTR_WIDTH, c->customWidth); - } - if (c->customTLIndex != -1) { - cdevice.writeAttr(SUMO_ATTR_TLLINKINDEX, c->customTLIndex); - } - if (c->customTLIndex2 != -1) { - cdevice.writeAttr(SUMO_ATTR_TLLINKINDEX2, c->customTLIndex2); - } - if (c->customShape.size() != 0) { - writeShape(cdevice, gch, c->customShape, SUMO_ATTR_SHAPE, useGeo, geoAccuracy); - } - cdevice.closeTag(); - } - } - // write custom walkingarea shapes to the connections file - for (std::map::const_iterator it_node = nc.begin(); it_node != nc.end(); ++it_node) { - for (const auto& wacs : it_node->second->getWalkingAreaCustomShapes()) { - cdevice.openTag(SUMO_TAG_WALKINGAREA); - cdevice.writeAttr(SUMO_ATTR_NODE, it_node->first); - cdevice.writeAttr(SUMO_ATTR_EDGES, joinNamedToString(wacs.edges, " ")); - writeShape(cdevice, gch, wacs.shape, SUMO_ATTR_SHAPE, useGeo, geoAccuracy); - cdevice.closeTag(); - } - } - - edevice.close(); - cdevice.close(); -} - - -void -NWWriter_XML::writeTrafficLights(const OptionsCont& oc, NBTrafficLightLogicCont& tc, NBEdgeCont& ec) { - std::map attrs; - attrs[SUMO_ATTR_VERSION] = toString(NETWORK_VERSION, 1); - OutputDevice& device = OutputDevice::getDevice(oc.getString("plain-output-prefix") + ".tll.xml"); - device.writeXMLHeader("tlLogics", "tllogic_file.xsd", attrs); - NWWriter_SUMO::writeTrafficLights(device, tc); - // we also need to remember the associations between tlLogics and connections - // since the information in con.xml is insufficient - for (std::map::const_iterator i = ec.begin(); i != ec.end(); ++i) { - NBEdge* e = (*i).second; - // write this edge's tl-controlled connections - const std::vector connections = e->getConnections(); - for (std::vector::const_iterator c = connections.begin(); c != connections.end(); ++c) { - if (c->tlID != "") { - NWWriter_SUMO::writeConnection(device, *e, *c, false, NWWriter_SUMO::TLL); - } - } - } - device.close(); -} - - -void -NWWriter_XML::writeJoinedJunctions(const OptionsCont& oc, NBNodeCont& nc) { - std::map attrs; - attrs[SUMO_ATTR_VERSION] = toString(NETWORK_VERSION, 1); - OutputDevice& device = OutputDevice::getDevice(oc.getString("junctions.join-output")); - device.writeXMLHeader("nodes", "nodes_file.xsd", attrs); - const std::vector >& clusters = nc.getJoinedClusters(); - for (std::vector >::const_iterator it = clusters.begin(); it != clusters.end(); it++) { - assert((*it).size() > 0); - device.openTag(SUMO_TAG_JOIN); - // prepare string - std::ostringstream oss; - for (std::set::const_iterator it_id = it->begin(); it_id != it->end(); it_id++) { - oss << *it_id << " "; - } - // remove final space - std::string ids = oss.str(); - device.writeAttr(SUMO_ATTR_NODES, ids.substr(0, ids.size() - 1)); - device.closeTag(); - } - device.close(); -} - - -void -NWWriter_XML::writeStreetSigns(const OptionsCont& oc, NBEdgeCont& ec) { - OutputDevice& device = OutputDevice::getDevice(oc.getString("street-sign-output")); - device.writeXMLHeader("additional", "additional_file.xsd"); - for (std::map::const_iterator i = ec.begin(); i != ec.end(); ++i) { - NBEdge* e = (*i).second; - const std::vector& signs = e->getSigns(); - for (std::vector::const_iterator it = signs.begin(); it != signs.end(); ++it) { - it->writeAsPOI(device, e); - } - } - device.close(); -} -void -NWWriter_XML::writePTStops(const OptionsCont& oc, NBPTStopCont& sc) { - OutputDevice& device = OutputDevice::getDevice(oc.getString("ptstop-output")); - device.writeXMLHeader("additional", "additional_file.xsd"); - for (std::map::const_iterator i = sc.begin(); i != sc.end(); ++i) { - i->second->write(device); - } - device.close(); -} -void NWWriter_XML::writePTLines(const OptionsCont& oc, NBPTLineCont& lc, NBEdgeCont& ec) { - OutputDevice& device = OutputDevice::getDevice(oc.getString("ptline-output")); - device.writeXMLHeader("ptLines", "ptlines_file.xsd"); - for (const auto& item : lc.getLines()) { - item.second->write(device, ec); - } - device.close(); -} - -void NWWriter_XML::writeParkingAreas(const OptionsCont& oc, NBParkingCont& pc, NBEdgeCont& ec) { - OutputDevice& device = OutputDevice::getDevice(oc.getString("parking-output")); - device.writeXMLHeader("additional", "additional_file.xsd"); - for (NBParking& p : pc) { - p.write(device, ec); - } - device.close(); -} - -void -NWWriter_XML::writeDistricts(const OptionsCont& oc, NBDistrictCont& dc) { - OutputDevice& device = OutputDevice::getDevice(oc.getString("taz-output")); - device.writeXMLHeader("additional", "additional_file.xsd"); - for (std::map::const_iterator i = dc.begin(); i != dc.end(); i++) { - NWWriter_SUMO::writeDistrict(device, *(*i).second); - } -} - -void -NWWriter_XML::writeShape(OutputDevice& out, const GeoConvHelper& gch, PositionVector shape, SumoXMLAttr attr, bool useGeo, bool geoAccuracy) { - if (useGeo) { - for (int i = 0; i < (int) shape.size(); i++) { - gch.cartesian2geo(shape[i]); - } - } - if (geoAccuracy) { - out.setPrecision(gPrecisionGeo); - } - out.writeAttr(attr, shape); - if (geoAccuracy) { - out.setPrecision(); - } -} - -/****************************************************************************/ - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/netwrite/NWWriter_XML.h b/Util/OSM2ODR/src/netwrite/NWWriter_XML.h deleted file mode 100644 index f6c2199a7..000000000 --- a/Util/OSM2ODR/src/netwrite/NWWriter_XML.h +++ /dev/null @@ -1,117 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NWWriter_XML.h -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date Tue, 11.05.2011 -/// -// Exporter writing networks using XML (native input) format -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include -#include - - -// =========================================================================== -// class declarations -// =========================================================================== -class NBEdge; -class NBEdgeCont; -class NBNetBuilder; -class NBNode; -class NBNodeCont; -class NBParkingCont; -class NBPTStopCont; -class NBPTLineCont; -class NBTrafficLightLogicCont; -class NBTypeCont; -class OptionsCont; - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NWWriter_XML - * @brief Exporter writing networks using XML (native input) format - * - */ -class NWWriter_XML { -public: - /** @brief Writes the network into XML-files (nodes, edges, connections, - * traffic lights) - * @param[in] oc The options to use - * @param[in] nb The network builder from which to read data - */ - static void writeNetwork(const OptionsCont& oc, NBNetBuilder& nb); - - /** @brief Writes the joined-juncionts to file - * @param[in] oc The options to use - * @param[in] nc The node-container from which to read data - */ - static void writeJoinedJunctions(const OptionsCont& oc, NBNodeCont& nc); - - /** @brief Writes street signs as POIs to file - * @param[in] oc The options to use - * @param[in] ec The edge-container from which to read data - */ - static void writeStreetSigns(const OptionsCont& oc, NBEdgeCont& ec); - -private: - /** @brief Writes the nodes file - * @param[in] oc The options to use - * @param[in] nc The node-container from which to read data - */ - static void writeNodes(const OptionsCont& oc, NBNodeCont& nc); - - /** @brief Writes the types file - * @param[in] oc The options to use - * @param[in] nc The type-container from which to read data - */ - static void writeTypes(const OptionsCont& oc, NBTypeCont& tc); - - /** @brief Writes the edges and connections files - * @param[in] oc The options to use - * @param[in] nb The network build from which to read data - */ - static void writeEdgesAndConnections(const OptionsCont& oc, NBNodeCont& nc, NBEdgeCont& ec); - - - /** @brief Writes the traffic lights file - * @param[in] oc The options to use - * @param[in] tc The tll-container from which to read data - * @param[in] ec The edge-container from which to read data - */ - static void writeTrafficLights(const OptionsCont& oc, NBTrafficLightLogicCont& tc, NBEdgeCont& ec); - - /** @brief Writes the pt stops file - * @param[in] oc The options to use - * @param[in] nc The pt stop container from which to read data - */ - static void writePTStops(const OptionsCont& oc, NBPTStopCont& ec); - static void writePTLines(const OptionsCont& cont, NBPTLineCont& lc, NBEdgeCont& ec); - - /// @brief writes imported parking areas to file - static void writeParkingAreas(const OptionsCont& cont, NBParkingCont& pc, NBEdgeCont& ec); - - /// @brief writes imported districts (TAZ) to file - static void writeDistricts(const OptionsCont& oc, NBDistrictCont& dc); - - static void writeShape(OutputDevice& out, const GeoConvHelper& gch, PositionVector shape, SumoXMLAttr attr, bool useGeo, bool geoAccuracy); -}; diff --git a/Util/OSM2ODR/src/netwrite/README_Contributing.md b/Util/OSM2ODR/src/netwrite/README_Contributing.md deleted file mode 100644 index 5522c1c0d..000000000 --- a/Util/OSM2ODR/src/netwrite/README_Contributing.md +++ /dev/null @@ -1,21 +0,0 @@ -Please feel free to add and / or modify files here but keep in mind that -EPL requires that "derivative works" be licensed under the terms of the EPL. -If the extension is a separate module and is not published under the EPL -it will not be adopted in the SUMO mainline repository. - -Modifications to the files and directories listed here are considered _derivative work_: - -- NWFrame.cpp -- NWFrame.h -- NWWriter_Amitran.cpp -- NWWriter_Amitran.h -- NWWriter_DlrNavteq.cpp -- NWWriter_DlrNavteq.h -- NWWriter_MATSim.cpp -- NWWriter_MATSim.h -- NWWriter_OpenDrive.cpp -- NWWriter_OpenDrive.h -- NWWriter_SUMO.cpp -- NWWriter_SUMO.h -- NWWriter_XML.cpp -- NWWriter_XML.h diff --git a/Util/OSM2ODR/src/notes b/Util/OSM2ODR/src/notes deleted file mode 100644 index 34d60af90..000000000 --- a/Util/OSM2ODR/src/notes +++ /dev/null @@ -1 +0,0 @@ -webwizard: cluster_25664673_4590472030_4590472039_4590472040 1085513888 diff --git a/Util/OSM2ODR/src/polyconvert/PCLoaderArcView.h b/Util/OSM2ODR/src/polyconvert/PCLoaderArcView.h deleted file mode 100644 index 4c80ebc34..000000000 --- a/Util/OSM2ODR/src/polyconvert/PCLoaderArcView.h +++ /dev/null @@ -1,84 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file PCLoaderArcView.h -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Sept 2002 -/// -// A reader of pois and polygons from shape files -/****************************************************************************/ -#pragma once -#include - -#include -#include - - -// =========================================================================== -// class declarations -// =========================================================================== -class OptionsCont; -class PCPolyContainer; -class PCTypeMap; - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class PCLoaderArcView - * @brief A reader of pois and polygons from shape files - * - * The current importer works only if SUMO was compiled with GDAL-support. - * If not, an error message is generated. - * - * @todo reinsert import via shapelib - */ -class PCLoaderArcView { -public: - /** @brief Loads pois/polygons assumed to be stored as shape files-files - * - * If the option "shape-files" is set within the given options container, - * the files stored herein are parsed using "load", assuming this - * option contains file paths to files containing pois and polygons stored - * as shape-files. - * - * @param[in] oc The options container to get further options from - * @param[in] toFill The poly/pois container to add loaded polys/pois to - * @param[in] tm The type map to use for setting values of loaded polys/pois - * @exception ProcessError if something fails - */ - static void loadIfSet(OptionsCont& oc, PCPolyContainer& toFill, - PCTypeMap& tm); - - -protected: - /** @brief Parses pois/polys stored within the given file - * @param[in] oc The options container to get further options from - * @param[in] toFill The poly/pois container to add loaded polys/pois to - * @param[in] tm The type map to use for setting values of loaded polys/pois - * @exception ProcessError if something fails - */ - static void load(const std::string& file, OptionsCont& oc, PCPolyContainer& toFill, - PCTypeMap& tm); - - -private: - /// @brief Invalidated copy constructor. - PCLoaderArcView(const PCLoaderArcView&); - - /// @brief Invalidated assignment operator. - PCLoaderArcView& operator=(const PCLoaderArcView&); - -}; diff --git a/Util/OSM2ODR/src/polyconvert/PCLoaderDlrNavteq.h b/Util/OSM2ODR/src/polyconvert/PCLoaderDlrNavteq.h deleted file mode 100644 index 0c9c852a5..000000000 --- a/Util/OSM2ODR/src/polyconvert/PCLoaderDlrNavteq.h +++ /dev/null @@ -1,123 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file PCLoaderDlrNavteq.h -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Thu, 02.11.2006 -/// -// A reader of pois and polygons stored in DLR-Navteq (Elmar)-format -/****************************************************************************/ -#pragma once -#include - -#include -#include "PCPolyContainer.h" -#include "PCTypeMap.h" -#include - - -// =========================================================================== -// class definitions -// =========================================================================== -class OptionsCont; - - -// =========================================================================== -// class declarations -// =========================================================================== -/** - * @class PCLoaderDlrNavteq - * @brief A reader of pois and polygons stored in DLR-Navteq (Elmar)-format - * - * Reads pois stored in "pointcollection.txt" and polygons stored in - * "...polygons.txt"/"...water_polygons.txt", applies the given projection - * and network offset and stores the so build pois/polys into the given map. - */ -class PCLoaderDlrNavteq { -public: - /** @brief Loads pois/polygons assumed to be stored as according DLR-Navteq (Elmar)-files - * - * If the option "elmar-poi-files" is set within the given options container, - * the files stored herein are parsed using "loadPOIFiles", assuming this - * option contains file paths to files containing pois stored in DLR-Navteq - * "pointcollection.txt"-format. - * - * If the option "elmar-poly-files" is set within the given options container, - * the files stored herein are parsed using "loadPolyFiles", assuming this - * option contains file paths to files containing polygons stored in DLR-Navteq - * "...polygons.txt"/"...water_polygons.txt"-format. - * - * @param[in] oc The options container to get further options from - * @param[in] toFill The poly/pois container to add loaded polys/pois to - * @param[in] tm The type map to use for setting values of loaded polys/pois - * @exception ProcessError if something fails - */ - static void loadIfSet(OptionsCont& oc, PCPolyContainer& toFill, - PCTypeMap& tm); - - -protected: - /** @brief Loads pois assumed to be stored as according DLR-Navteq (Elmar)-files - * - * Goes through the list of files given in "elmar-poi-files". Calls - * "loadPOIFile" using each of these as the first parameter. - * - * @param[in] oc The options container to get further options from - * @param[in] toFill The poly/pois container to add loaded pois to - * @param[in] tm The type map to use for setting values of loaded pois - * @exception ProcessError if something fails - */ - static void loadPOIFiles(OptionsCont& oc, PCPolyContainer& toFill, - PCTypeMap& tm); - - - /** @brief Loads polygons assumed to be stored as according DLR-Navteq (Elmar)-files - * - * Goes through the list of files given in "elmar-poly-files". Calls - * "loadPolyFile" using each of these as the first parameter. - * - * @param[in] oc The options container to get further options from - * @param[in] toFill The poly/pois container to add loaded polys to - * @param[in] tm The type map to use for setting values of loaded polys - * @exception ProcessError if something fails - */ - static void loadPolyFiles(OptionsCont& oc, PCPolyContainer& toFill, - PCTypeMap& tm); - - - /** @brief Loads DLR-Navteq (Elmar)-pois from the given file - * @param[in] file The name of the file to parse - * @param[in] oc The options container to get further options from - * @param[in] toFill The poly/pois container to add loaded polys to - * @param[in] tm The type map to use for setting values of loaded polys - * @exception ProcessError if something fails - */ - static void loadPOIFile(const std::string& file, - OptionsCont& oc, PCPolyContainer& toFill, - PCTypeMap& tm); - - - /** @brief Loads DLR-Navteq (Elmar)-polygons from the given file - * @param[in] file The name of the file to parse - * @param[in] oc The options container to get further options from - * @param[in] toFill The poly/pois container to add loaded polys to - * @param[in] tm The type map to use for setting values of loaded polys - * @exception ProcessError if something fails - */ - static void loadPolyFile(const std::string& file, - OptionsCont& oc, PCPolyContainer& toFill, - PCTypeMap& tm); - - -}; diff --git a/Util/OSM2ODR/src/polyconvert/PCLoaderOSM.h b/Util/OSM2ODR/src/polyconvert/PCLoaderOSM.h deleted file mode 100644 index 82e8c6efc..000000000 --- a/Util/OSM2ODR/src/polyconvert/PCLoaderOSM.h +++ /dev/null @@ -1,372 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2008-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file PCLoaderOSM.h -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @author Melanie Knocke -/// @date Wed, 19.11.2008 -/// -// A reader of pois and polygons stored in OSM-format -/****************************************************************************/ -#pragma once -#include - -#include -#include "PCPolyContainer.h" -#include "PCTypeMap.h" -#include - - -// =========================================================================== -// class definitions -// =========================================================================== -class OptionsCont; - - -// =========================================================================== -// class declarations -// =========================================================================== -/** - * @class PCLoaderOSM - * @brief A reader of pois and polygons stored in OSM-format - * - * Reads pois stored as XML definition as given by the OpenStreetMap-API. - */ -class PCLoaderOSM : public SUMOSAXHandler { -public: - /** @brief Loads pois/polygons assumed to be stored as OSM-XML - * - * If the option "osm-files" is set within the given options container, - * an instance of PCLoaderOSM is built and used as a handler for the - * files given in this option. - * - * @param[in] oc The options container to get further options from - * @param[in] toFill The poly/pois container to add loaded polys/pois to - * @param[in] tm The type map to use for setting values of loaded polys/pois - * @exception ProcessError if something fails - */ - static void loadIfSet(OptionsCont& oc, PCPolyContainer& toFill, - PCTypeMap& tm); - - -protected: - - /** @brief An internal representation of an OSM-node - */ - struct PCOSMNode { - /// @brief The node's id - long long int id; - /// @brief The longitude the node is located at - double lon; - /// @brief The latitude the node is located at - double lat; - /// @brief The nodes name (if any) - std::string name; - /// @brief Additional attributes - std::map myAttributes; - }; - - - /** @brief An internal definition of a loaded relation - */ - struct PCOSMRelation { - /// @brief The relation's id - long long int id; - /// @brief The relation's name (if any) - std::string name; - /// @brief The list of ways this relation is made of - std::vector myWays; - /// @brief Additional attributes - std::map myAttributes; - /// @brief whether this relation is a valid polygon - bool keep; - }; - - - /** @brief An internal definition of a loaded edge - */ - struct PCOSMEdge { - /// @brief The edge's id - long long int id; - /// @brief The edge's name (if any) - std::string name; - /// @brief Information whether this area is closed - bool myIsClosed; - /// @brief The list of nodes this edge is made of - std::vector myCurrentNodes; - /// @brief Additional attributes - std::map myAttributes; - // @brief Wether this way constitutes a complete polygon object - bool standalone; - }; - - typedef std::vector Relations; - typedef std::map RelationsMap; - typedef std::map EdgeMap; - -protected: - /// @brief try add the polygon and return the next index on success - static int addPolygon(const PCOSMEdge* edge, const PositionVector& vec, const PCTypeMap::TypeDef& def, - const std::string& fullType, int index, bool useName, PCPolyContainer& toFill, bool ignorePruning, bool withAttributes); - - /// @brief try add the POI and return the next index on success - static int addPOI(const PCOSMNode* node, const Position& pos, const PCTypeMap::TypeDef& def, - const std::string& fullType, int index, bool useName, PCPolyContainer& toFill, bool ignorePruning, bool withAttributes); - - -protected: - static const std::set MyKeysToInclude; - -private: - static std::set initMyKeysToInclude(); - - /// @brief retrieve cartesian coordinate for given node - static Position convertNodePosition(PCOSMNode* n); - -protected: - /** - * @class NodesHandler - * @brief A class which extracts OSM-nodes from a parsed OSM-file - */ - class NodesHandler : public SUMOSAXHandler { - public: - /** @brief Contructor - * @param[in] toFill The nodes container to fill - * @param[in] withAttributes Whether all attributes shall be stored - * @param[in] errorHandler The handler to report errors to (WarningHandler for ignoring errors) - */ - NodesHandler(std::map& toFill, bool withAttributes, - MsgHandler& errorHandler); - - - /// @brief Destructor - ~NodesHandler(); - - - protected: - /// @name inherited from GenericSAXHandler - //@{ - - /** @brief Called on the opening of a tag; - * - * @param[in] element ID of the currently opened element - * @param[in] attrs Attributes within the currently opened element - * @exception ProcessError If something fails - * @see GenericSAXHandler::myStartElement - */ - void myStartElement(int element, const SUMOSAXAttributes& attrs); - - - /** @brief Called when a closing tag occurs - * - * @param[in] element ID of the currently opened element - * @exception ProcessError If something fails - * @see GenericSAXHandler::myEndElement - */ - void myEndElement(int element); - //@} - - - private: - /// @brief Whether all attributes shall be stored - bool myWithAttributes; - - /// @brief The handler to report errors to (will be the WarningsHandler if --ignore-errors was set) - MsgHandler& myErrorHandler; - - /// @brief The nodes container to fill - std::map& myToFill; - - /// @brief Current path in order to know to what occuring values belong - std::vector myParentElements; - - /// @brief The id of the last parsed node - long long int myLastNodeID; - - private: - /// @brief Invalidated copy constructor - NodesHandler(const NodesHandler& s); - - /// @brief Invalidated assignment operator - NodesHandler& operator=(const NodesHandler& s); - - }; - - /** - * @class RelationsHandler - * @brief A class which extracts relevant way-ids from relations in a parsed OSM-file - */ - class RelationsHandler : public SUMOSAXHandler { - public: - /** @brief Constructor - * - * @param[in] osmNodes The previously parsed (osm-)nodes - * @param[in] toFill The edges container to fill with read edges - * @param[in] withAttributes Whether all attributes shall be stored - * @param[in] errorHandler The handler to report errors to (WarningHandler for ignoring errors) - */ - RelationsHandler(RelationsMap& additionalWays, - Relations& relations, - bool withAttributes, - MsgHandler& errorHandler); - - - /// @brief Destructor - ~RelationsHandler(); - - - protected: - /// @name inherited from GenericSAXHandler - //@{ - - /** @brief Called on the opening of a tag; - * - * @param[in] element ID of the currently opened element - * @param[in] attrs Attributes within the currently opened element - * @exception ProcessError If something fails - * @see GenericSAXHandler::myStartElement - */ - void myStartElement(int element, const SUMOSAXAttributes& attrs); - - - /** @brief Called when a closing tag occurs - * - * @param[in] element ID of the currently opened element - * @exception ProcessError If something fails - * @see GenericSAXHandler::myEndElement - */ - void myEndElement(int element); - //@} - - - private: - /// @brief additional ways which are reference by relations - RelationsMap& myAdditionalWays; - - /// @brief the loaded relations - Relations& myRelations; - - /// @brief Whether all attributes shall be stored - bool myWithAttributes; - - /// @brief The handler to report errors to (will be the WarningsHandler if --ignore-errors was set) - MsgHandler& myErrorHandler; - - /// @brief The currently parsed relation - PCOSMRelation* myCurrentRelation; - - /// @brief the ways within the current relation - std::vector myCurrentWays; - - /// @brief Current path in order to know to what occuring values belong - std::vector myParentElements; - - /// @brief whether the last edge (way) should be kept because it had a key from the inclusion list - bool myKeep; - - private: - /// @brief Invalidated copy constructor - RelationsHandler(const RelationsHandler& s); - - /// @brief Invalidated assignment operator - RelationsHandler& operator=(const RelationsHandler& s); - - }; - - - /** - * @class EdgesHandler - * @brief A class which extracts OSM-edges from a parsed OSM-file - */ - class EdgesHandler : public SUMOSAXHandler { - public: - /** @brief Constructor - * - * @param[in] osmNodes The previously parsed (osm-)nodes - * @param[in] toFill The edges container to fill with read edges - * @param[in] withAttributes Whether all attributes shall be stored - * @param[in] additionalWays Additional ways which were identified as polygons to import - * @param[in] errorHandler The handler to report errors to (WarningHandler for ignoring errors) - */ - EdgesHandler(const std::map& osmNodes, - EdgeMap& toFill, - const RelationsMap& additionalWays, - bool withAttributes, - MsgHandler& errorHandler); - - - /// @brief Destructor - ~EdgesHandler(); - - - protected: - /// @name inherited from GenericSAXHandler - //@{ - - /** @brief Called on the opening of a tag; - * - * @param[in] element ID of the currently opened element - * @param[in] attrs Attributes within the currently opened element - * @exception ProcessError If something fails - * @see GenericSAXHandler::myStartElement - */ - void myStartElement(int element, const SUMOSAXAttributes& attrs); - - - /** @brief Called when a closing tag occurs - * - * @param[in] element ID of the currently opened element - * @exception ProcessError If something fails - * @see GenericSAXHandler::myEndElement - */ - void myEndElement(int element); - //@} - - - private: - /// @brief Whether all attributes shall be stored - bool myWithAttributes; - - /// @brief The handler to report errors to (will be the WarningsHandler if --ignore-errors was set) - MsgHandler& myErrorHandler; - - /// @brief The previously parsed nodes - const std::map& myOSMNodes; - - /// @brief A map of built edges - EdgeMap& myEdgeMap; - - /// @brief additional ways which are reference by relations - const RelationsMap& myAdditionalWays; - - /// @brief The currently built edge - PCOSMEdge* myCurrentEdge; - - /// @brief Current path in order to know to what occuring values belong - std::vector myParentElements; - - /// @brief whether the last edge (way) should be kept because it had a key from the inclusion list - bool myKeep; - - private: - /// @brief Invalidated copy constructor - EdgesHandler(const EdgesHandler& s); - - /// @brief Invalidated assignment operator - EdgesHandler& operator=(const EdgesHandler& s); - - }; - -}; diff --git a/Util/OSM2ODR/src/polyconvert/PCLoaderVisum.h b/Util/OSM2ODR/src/polyconvert/PCLoaderVisum.h deleted file mode 100644 index 6343001cf..000000000 --- a/Util/OSM2ODR/src/polyconvert/PCLoaderVisum.h +++ /dev/null @@ -1,71 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file PCLoaderVisum.h -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Thu, 02.11.2006 -/// -// A reader of pois and polygons stored in VISUM-format -/****************************************************************************/ -#pragma once -#include - -#include -#include "PCPolyContainer.h" -#include "PCTypeMap.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -class OptionsCont; - - -// =========================================================================== -// class declarations -// =========================================================================== -/** - * @class PCLoaderVisum - * @brief A reader of pois and polygons stored in VISUM-format - */ -class PCLoaderVisum { -public: - /** @brief Loads pois/polygons assumed to be stored using VISUM-format - * - * If the option "visum-files" is set within the given options container, - * the files stored herein are parsed using "load", assuming this - * option contains file paths to files containing pois and polygons stored - * in VISUM ".net"-format. - * - * @param[in] oc The options container to get further options from - * @param[in] toFill The poly/pois container to add loaded polys/pois to - * @param[in] tm The type map to use for setting values of loaded polys/pois - * @exception ProcessError if something fails - */ - static void loadIfSet(OptionsCont& oc, PCPolyContainer& toFill, - PCTypeMap& tm); - - -protected: - /** @brief Parses pois/polys stored within the given file - * @param[in] oc The options container to get further options from - * @param[in] toFill The poly/pois container to add loaded polys/pois to - * @param[in] tm The type map to use for setting values of loaded polys/pois - * @exception ProcessError if something fails - */ - static void load(const std::string& file, OptionsCont& oc, PCPolyContainer& toFill, - PCTypeMap& tm); - - -}; diff --git a/Util/OSM2ODR/src/polyconvert/PCLoaderXML.h b/Util/OSM2ODR/src/polyconvert/PCLoaderXML.h deleted file mode 100644 index 1450a03f9..000000000 --- a/Util/OSM2ODR/src/polyconvert/PCLoaderXML.h +++ /dev/null @@ -1,103 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file PCLoaderXML.h -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date Thu, 02.11.2006 -/// -// A reader for polygons and pois stored in XML-format -/****************************************************************************/ -#pragma once -#include - -#include -#include "PCPolyContainer.h" -#include "PCTypeMap.h" -#include -#include - - -// =========================================================================== -// class definitions -// =========================================================================== -class OptionsCont; - - -// =========================================================================== -// class declarations -// =========================================================================== -/** - * @class PCLoaderXML - * @brief A reader for polygons and pois stored in XML-format - * - * Reads pois stored as XML definition. The definitions must match - * the format POLYCONVERT generates. - */ -class PCLoaderXML : public ShapeHandler { -public: - /** @brief Loads pois/polygons assumed to be stored as XML - * - * If the option "xml" is set within the given options container, - * an instance of PCLoaderXML is built and used as a handler for the - * files given in this option. - * - * @param[in] oc The options container to get further options from - * @param[in] toFill The poly/pois container to add loaded polys/pois to - * @param[in] tm The type map to use for setting values of loaded polys/pois - * @exception ProcessError if something fails - */ - static void loadIfSet(OptionsCont& oc, PCPolyContainer& toFill, - PCTypeMap& tm); - - - Position getLanePos(const std::string& poiID, const std::string& laneID, double lanePos, double lanePosLat); - -protected: - /** @brief Constructor - * @param[in] toFill The poly/pois container to add loaded polys/pois to - * @param[in] tm The type map to use for setting values of loaded polys/pois - * @param[in] oc The options container to get further options from - */ - PCLoaderXML(PCPolyContainer& toFill, - PCTypeMap& tm, OptionsCont& oc); - - - /// @brief Destructor - ~PCLoaderXML(); - - -protected: - /// @name inherited from GenericSAXHandler - //@{ - - /** @brief Called on the opening of a tag; - * - * @param[in] element ID of the currently opened element - * @param[in] attrs Attributes within the currently opened element - * @exception ProcessError If something fails - * @see GenericSAXHandler::myStartElement - */ - virtual void myStartElement(int element, const SUMOSAXAttributes& attrs); - //@} - - -private: - /// @brief The type map to use - PCTypeMap& myTypeMap; - - /// @brief Settings to use - OptionsCont& myOptions; - -}; diff --git a/Util/OSM2ODR/src/polyconvert/PCNetProjectionLoader.h b/Util/OSM2ODR/src/polyconvert/PCNetProjectionLoader.h deleted file mode 100644 index a9a70f046..000000000 --- a/Util/OSM2ODR/src/polyconvert/PCNetProjectionLoader.h +++ /dev/null @@ -1,94 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file PCNetProjectionLoader.h -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date Thu, 02.11.2006 -/// -// A reader for a SUMO network's projection description -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include -#include - - -// =========================================================================== -// class definitions -// =========================================================================== -class OptionsCont; - - -// =========================================================================== -// class declarations -// =========================================================================== -/** - * @class PCNetProjectionLoader - * @brief A reader for a SUMO network's projection description - */ -class PCNetProjectionLoader : public SUMOSAXHandler { -public: - /** @brief Loads network projection if wished - * - * @param[in] file The network file from which to parse the location element - * @param[in] shift The shift of the decimal point when interpreting loaded coordinates - */ - static void load(const std::string& file, double scale); - - -protected: - /** @brief Constructor - */ - PCNetProjectionLoader(double scale); - - - /// @brief Destructor - ~PCNetProjectionLoader(); - - - /** @brief Returns whether all needed values were read - * @return Whether all needed values were read - */ - bool hasReadAll() const; - - -protected: - /// @name inherited from GenericSAXHandler - //@{ - - /** @brief Called on the opening of a tag; - * - * @param[in] element ID of the currently opened element - * @param[in] attrs Attributes within the currently opened element - * @exception ProcessError If something fails - * @see GenericSAXHandler::myStartElement - */ - virtual void myStartElement(int element, - const SUMOSAXAttributes& attrs); - //@} - - -private: - /// @brief Information whether the parameter was read - bool myFoundLocation; - - /// @brief scaling of input coordinates (not given in the location element) - double myScale; - - -}; diff --git a/Util/OSM2ODR/src/polyconvert/PCPolyContainer.h b/Util/OSM2ODR/src/polyconvert/PCPolyContainer.h deleted file mode 100644 index 394033c9b..000000000 --- a/Util/OSM2ODR/src/polyconvert/PCPolyContainer.h +++ /dev/null @@ -1,157 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2005-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file PCPolyContainer.h -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @author Jakob Erdmann -/// @date Mon, 05 Dec 2005 -/// -// A storage for loaded polygons and pois -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include -#include - - -// =========================================================================== -// class declarations -// =========================================================================== -class Boundary; -class SUMOPolygon; -class PointOfInterest; -class OptionsCont; -class OutputDevice; - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class PCPolyContainer - * @brief A storage for loaded polygons and pois - */ -class PCPolyContainer : public ShapeContainer { -public: - /** @brief Constructor - * @param[in] prune Whether added polygons/pois shall be pruned - * @param[in] pruningBoundary The pruning boundary (only valid if prune==true) - * @param[in] removeByNames Names of objects that shall not be added - */ - PCPolyContainer(bool prune, const Boundary& pruningBoundary, - const std::vector& removeByNames); - - - /// @brief Destructor - ~PCPolyContainer(); - - - /** @brief Adds a polygon to the storage - * - * If pruning is enabled, "ignorePruning" is false and the polygon lies outside - * the pruning boundary, or if the polygon's name is within the names of - * objects to discard, the polygon is deleted and false is returned. - * - * Afterwards it is tested whether a polygon with the same name is already stored. - * If so, an error message is printed, the polygon is deleted and false is returned, otherwise true. - * - * @param[in] poly The polygon to add - * @param[in] ignorePruning Whether the polygon shall be kept, even though it would be pruned - * @return Whether the polygon could be added - */ - bool add(SUMOPolygon* poly, bool ignorePruning = false); - - - /** @brief Adds a poi to the storage - * - * If pruning is enabled, "ignorePruning" is false and the poi lies outside - * the pruning boundary, or if the poi's name is within the names of - * objects to discard, the poi is deleted and false is returned. - * - * Afterwards it is tested whether a poi with the same name is already stored. - * If so, an error message is printed, the poi is deleted and false is returned, otherwise true. - * - * @param[in] poly The poi to add - * @param[in] ignorePruning Whether the poi shall be kept, even though it would be pruned - * @return Whether the poi could be added - */ - bool add(PointOfInterest* poi, bool ignorePruning = false); - - - void addLanePos(const std::string& poiID, const std::string& laneID, double lanePos, double lanePosLat); - - /** @brief Saves the stored polygons and pois into the given file - * @param[in] file The name of the file to write stored objects' definitions into - * @param[in] useGeo Whether to write output in geo-coordinates - * @exception IOError If the file could not be opened - */ - void save(const std::string& file, bool useGeo); - - /** @brief Saves the stored polygons and pois into the given file in dlrTDP format - * @param[in] prefix The prefix of the file to write stored objects' definitions into - */ - void saveDlrTDP(const std::string& prefix); - - - /** @brief Retuns a unique id for a given name - * - * The unique id is generated by having an internal map of ids to running numbers. - * The first call to this method will return 0, all subsequent with the same - * key will return numbers increased by one at each call. - * @param[in] key The key to get a running number for - * @return Unique id (running number of calls that used this key) - */ - int getEnumIDFor(const std::string& key); - - -private: - - struct LanePos { - LanePos() {} - LanePos(const std::string& _laneID, double _pos, double _posLat) : - laneID(_laneID), pos(_pos), posLat(_posLat) {} - std::string laneID; - double pos; - double posLat; - }; - - /// @brief An id to pos map for lane pos specs - std::map myLanePosPois; - - /// @brief An id to int map for proper enumeration - std::map myIDEnums; - - /// @brief The boundary that described the rectangle within which an object must be in order to be kept - Boundary myPruningBoundary; - - /// @brief Information whether the pruning boundary shall be used - bool myDoPrune; - - /// @brief List of names of polygons/pois that shall be removed - std::vector myRemoveByNames; - - static void writeDlrTDPHeader(OutputDevice& device, const OptionsCont& oc); - -private: - /// @brief Invalidated copy constructor - PCPolyContainer(const PCPolyContainer& s); - - /// @brief Invalidated assignment operator - PCPolyContainer& operator=(const PCPolyContainer& s); - - -}; diff --git a/Util/OSM2ODR/src/polyconvert/PCTypeDefHandler.h b/Util/OSM2ODR/src/polyconvert/PCTypeDefHandler.h deleted file mode 100644 index 31b047fb1..000000000 --- a/Util/OSM2ODR/src/polyconvert/PCTypeDefHandler.h +++ /dev/null @@ -1,89 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file PCTypeDefHandler.h -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date Thu, 16.03.2006 -/// -// A handler for loading polygon type maps -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include -#include "PCTypeDefHandler.h" - - -// =========================================================================== -// class declarations -// =========================================================================== -class PCTypeToDef; - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class PCTypeDefHandler - * @brief A handler for loading polygon type maps - */ -class PCTypeDefHandler : public SUMOSAXHandler { -public: - /** @brief Constructor - * @param[in] oc The options used while loading the type map - * @param[out] con The container to fill - */ - PCTypeDefHandler(OptionsCont& oc, PCTypeMap& con); - - - /// @brief Destructor - virtual ~PCTypeDefHandler(); - - -protected: - /// @name inherited from GenericSAXHandler - //@{ - - /** @brief Called on the opening of a tag; - * - * @param[in] element ID of the currently opened element - * @param[in] attrs Attributes within the currently opened element - * @exception ProcessError If something fails - * @see GenericSAXHandler::myStartElement - * @todo Completely unsecure currently (invalid values may force abortion with no error message) - */ - void myStartElement(int element, - const SUMOSAXAttributes& attrs); - //@} - - -protected: - /// @brief The options (program settings) - OptionsCont& myOptions; - - /// @brief The type map to fill - PCTypeMap& myContainer; - - -private: - /// @brief Invalidated copy constructor - PCTypeDefHandler(const PCTypeDefHandler& src); - - /// @brief Invalidated assignment operator - PCTypeDefHandler& operator=(const PCTypeDefHandler& src); - -}; diff --git a/Util/OSM2ODR/src/polyconvert/PCTypeMap.h b/Util/OSM2ODR/src/polyconvert/PCTypeMap.h deleted file mode 100644 index 8eaf8f9e5..000000000 --- a/Util/OSM2ODR/src/polyconvert/PCTypeMap.h +++ /dev/null @@ -1,122 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2005-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file PCTypeMap.h -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @author Jakob Erdmann -/// @date Mon, 05 Dec 2005 -/// -// A storage for type mappings -/****************************************************************************/ -#pragma once -#include - -#include "utils/common/RGBColor.h" -#include -#include - - -// =========================================================================== -// class declarations -// =========================================================================== -class OptionsCont; - -/** - * @class PCTypeMap - * @brief A storage for type mappings - * - * This class holds the mappings between names of read polygon/poi types and the - * values (color, new type name etc.) that shall be assigned to them. - */ -class PCTypeMap { -public: - /// @brief Constructor. The default type is constructed based on the given options - PCTypeMap(const OptionsCont& oc); - - - /// @brief Destructor - ~PCTypeMap(); - - - /** - * @struct TypeDef - * @brief A single definition of values that shall be used for a given type - */ - struct TypeDef { - /// @brief The new type id to use - std::string id; - /// @brief The color to use - RGBColor color; - /// @brief The prefix to use - std::string prefix; - /// @brief The layer to use - double layer; - /// @brief The angle to use - double angle; - /// @brief The image file to use - std::string imgFile; - /// @brief Information whether polygons of this type shall be discarded - bool discard; - /// @brief Information whether polygons of this type can be filled - bool allowFill; - - }; - - - /** @brief Adds a type definition - * - * @param[in] id The original id of the type - * @param[in] newid The new id (name) of the type - * @param[in] color The color to set for imported objects of this type - * @param[in] prefix The prefix to prepend to the read names of this type's objects - * @param[in] layer The layer number to set for this type's objects - * @param[in] angle The angle to rotate this type's objects - * @param[in] imgFile The image file used as texture for objects of this type - * @param[in] discard Whether objects of this type shall be discarded - * @param[in] allowFill Whether objects of this type may be filled - * @return Whether the type could been added (was not known before) - */ - bool add(const std::string& id, const std::string& newid, const std::string& color, - const std::string& prefix, double layer, double angle, const std::string& imgFile, - bool discard, bool allowFill); - - - /** @brief Returns a type definition - * - * This type definition MUST have been added otherwise the further process - * is undefined. - * @param[in] id The id of the type to get the definitions of - * @return Definition of the named type - */ - const TypeDef& get(const std::string& id); - - - /** @brief Returns the information whether the named type is known - * @param[in] id The id of the type - * @return Whether a definition of the named type was added before - */ - bool has(const std::string& id); - - /// @brief get the default type according to the given options - const TypeDef& getDefault() { - return myDefaultType; - } - -protected: - /// @brief A map of type names to type definitions - std::map myTypes; - - TypeDef myDefaultType; - -}; diff --git a/Util/OSM2ODR/src/utils/CMakeLists.txt b/Util/OSM2ODR/src/utils/CMakeLists.txt deleted file mode 100644 index 7976dfe5d..000000000 --- a/Util/OSM2ODR/src/utils/CMakeLists.txt +++ /dev/null @@ -1,10 +0,0 @@ -add_subdirectory(common) -add_subdirectory(distribution) -add_subdirectory(geom) -add_subdirectory(importio) -add_subdirectory(iodevices) -add_subdirectory(options) -add_subdirectory(shapes) -add_subdirectory(traction_wire) -add_subdirectory(xml) - diff --git a/Util/OSM2ODR/src/utils/common/CMakeLists.txt b/Util/OSM2ODR/src/utils/common/CMakeLists.txt deleted file mode 100644 index 6c36f2501..000000000 --- a/Util/OSM2ODR/src/utils/common/CMakeLists.txt +++ /dev/null @@ -1,48 +0,0 @@ -set(utils_common_STAT_SRCS - Command.h - FileHelpers.cpp - FileHelpers.h - IDSupplier.h - IDSupplier.cpp - MsgHandler.h - MsgHandler.cpp - MsgRetrievingFunction.h - Named.h - NamedObjectCont.h - NamedRTree.h - Parameterised.cpp - Parameterised.h - PolySolver.h - PolySolver.cpp - RandHelper.h - RandHelper.cpp - RGBColor.cpp - RGBColor.h - StaticCommand.h - StdDefs.h - StdDefs.cpp - StringBijection.h - StringTokenizer.cpp - StringTokenizer.h - StringUtils.cpp - StringUtils.h - SUMOTime.cpp - SUMOTime.h - SUMOVehicleClass.cpp - SUMOVehicleClass.h - SystemFrame.cpp - SystemFrame.h - SysUtils.h - SysUtils.cpp - ToString.h - UtilExceptions.h - ValueRetriever.h - ValueSource.h - ValueTimeLine.h - VectorHelper.h - WrappingCommand.h - SwarmDebug.h -) - -add_library(utils_common STATIC ${utils_common_STAT_SRCS}) -set_property(TARGET utils_common PROPERTY PROJECT_LABEL "z_utils_common") diff --git a/Util/OSM2ODR/src/utils/common/Command.h b/Util/OSM2ODR/src/utils/common/Command.h deleted file mode 100644 index e46cb8aed..000000000 --- a/Util/OSM2ODR/src/utils/common/Command.h +++ /dev/null @@ -1,86 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file Command.h -/// @author Christian Roessel -/// @author Daniel Krajzewicz -/// @date Thu, 20 Dec 2001 -/// -// Base (microsim) event class -/****************************************************************************/ -#pragma once -#include -#include - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class Command - * @brief Base (microsim) event class - * - * Classes derived from Command may be added to MSEventControl instances in - * order to be executed at a certain time step. - * - * As soon as the simulation reaches the desired time step, the command (event) - * is executed by calling "execute" with the current time step. The method must - * return either 0, if the event shall not be executed again or a positive value - * (in simulation seconds) that described when it shall be executed again. The method - * must not return a value below zero, the behaviour is undefined in this case. - * - * @warning The EventControl the Command is added to gets responsible for - * this command's deletion. - * - * @see Design Patterns, Gamma et al. - * @see WrappingCommand - * @see MSEventControl - */ -class Command { -public: - /// @brief Constructor - Command() { } - - - /// @brief Destructor. - virtual ~Command() { } - - - /** @brief Executes the command. - * - * The implementations should return 0 if the command shall not be repeated, - * or a value larger than 0 that describe the time after which the command - * shall be executed again. Values below 0 must not be returned. - * - * @param[in] currentTime The current simulation time - * @return The time after which the command shall be executed again, 0 if this command shall be descheduled. - * @exception ProcessError Derived actions may throw this exception - */ - virtual SUMOTime execute(SUMOTime currentTime) = 0; - - /** @brief Reschedule or deschedule the command when quick-loading state - * - * The implementations should return -1 if the command shall not be re-scheduled, - * or a value >= 0 that describe the new time at which the command - * shall be executed again. - * - * @param[in] currentTime The current simulation time - * @param[in] execTime The time at which the command would have been executed - * @param[in] newTime The simulation time at which the simulation is restarted - * @return The time at which the command shall be executed again - */ - virtual SUMOTime shiftTime(SUMOTime /*currentTime*/, SUMOTime /*execTime*/, SUMOTime /*newTime*/) { - return -1; - } - -}; diff --git a/Util/OSM2ODR/src/utils/common/FileHelpers.cpp b/Util/OSM2ODR/src/utils/common/FileHelpers.cpp deleted file mode 100644 index 3271f6375..000000000 --- a/Util/OSM2ODR/src/utils/common/FileHelpers.cpp +++ /dev/null @@ -1,220 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file FileHelpers.cpp -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Mon, 17 Dec 2001 -/// -// Functions for an easier usage of files -/****************************************************************************/ -#include - -#include -#ifdef WIN32 -// this is how fox does it in xincs.h -#include -#define access _access -#define R_OK 4 /* Test for read permission. */ -#else -#include -#endif -#include -#include -#include "FileHelpers.h" -#include "StringTokenizer.h" -#include "MsgHandler.h" - - -// =========================================================================== -// method definitions -// =========================================================================== - -// --------------------------------------------------------------------------- -// file access functions -// --------------------------------------------------------------------------- - -bool -FileHelpers::isReadable(std::string path) { - if (path.length() == 0) { - return false; - } - while (path[path.length() - 1] == '/' || path[path.length() - 1] == '\\') { - path.erase(path.end() - 1); - } - if (path.length() == 0) { - return false; - } - return access(path.c_str(), R_OK) == 0; -} - -bool -FileHelpers::isDirectory(std::string path) { - struct stat fileInfo; - if (stat(path.c_str(), &fileInfo) != 0) { - throw ProcessError("Cannot get file attributes for file '" + path + "'!"); - } - return (fileInfo.st_mode & S_IFMT) == S_IFDIR; -} - -// --------------------------------------------------------------------------- -// file path evaluating functions -// --------------------------------------------------------------------------- - -std::string -FileHelpers::getFilePath(const std::string& path) { - const std::string::size_type beg = path.find_last_of("\\/"); - if (beg == std::string::npos) { - return ""; - } - return path.substr(0, beg + 1); -} - - -std::string -FileHelpers::addExtension(const std::string& path, const std::string& extension) { - if (path.empty()) { - return ""; - } else if (extension.empty()) { - return path; - } else if (path == extension) { - return ""; - } else if (path.size() < extension.size()) { - return path + extension; - } else { - // declare two reverse iterator for every string - std::string::const_reverse_iterator it_path = path.rbegin(); - std::string::const_reverse_iterator it_extension = extension.rbegin(); - // iterate over extension and compare both characters - while (it_extension != extension.rend()) { - // if both characters are different, then return path + extension - if (*it_path != *it_extension) { - return path + extension; - } - it_path++; - it_extension++; - } - // if comparison was successful, then the path has already the extension - return path; - } -} - - -std::string -FileHelpers::getConfigurationRelative(const std::string& configPath, const std::string& path) { - std::string retPath = getFilePath(configPath); - return retPath + path; -} - - -bool -FileHelpers::isSocket(const std::string& name) { - const std::string::size_type colonPos = name.find(":"); - return (colonPos != std::string::npos) && (colonPos > 1); -} - - -bool -FileHelpers::isAbsolute(const std::string& path) { - if (isSocket(path)) { - return true; - } - // check UNIX - absolute paths - if (path.length() > 0 && path[0] == '/') { - return true; - } - // check Windows - absolute paths - if (path.length() > 0 && path[0] == '\\') { - return true; - } - if (path.length() > 1 && path[1] == ':') { - return true; - } - if (path == "nul" || path == "NUL") { - return true; - } - return false; -} - - -std::string -FileHelpers::checkForRelativity(const std::string& filename, const std::string& basePath) { - if (filename == "stdout" || filename == "STDOUT" || filename == "-") { - return "stdout"; - } - if (filename == "stderr" || filename == "STDERR") { - return "stderr"; - } - if (filename == "nul" || filename == "NUL") { - return "/dev/null"; - } - if (!isSocket(filename) && !isAbsolute(filename)) { - return getConfigurationRelative(basePath, filename); - } - return filename; -} - - -std::string -FileHelpers::prependToLastPathComponent(const std::string& prefix, const std::string& path) { - const std::string::size_type sep_index = path.find_last_of("\\/"); - if (sep_index == std::string::npos) { - return prefix + path; - } else { - return path.substr(0, sep_index + 1) + prefix + path.substr(sep_index + 1); - } -} - -// --------------------------------------------------------------------------- -// binary reading/writing functions -// --------------------------------------------------------------------------- - -std::ostream& -FileHelpers::writeInt(std::ostream& strm, int value) { - strm.write((char*) &value, sizeof(int)); - return strm; -} - - -std::ostream& -FileHelpers::writeFloat(std::ostream& strm, double value) { - strm.write((char*) &value, sizeof(double)); - return strm; -} - - -std::ostream& -FileHelpers::writeByte(std::ostream& strm, unsigned char value) { - strm.write((char*) &value, sizeof(char)); - return strm; -} - - -std::ostream& -FileHelpers::writeString(std::ostream& strm, const std::string& value) { - int size = (int)value.length(); - const char* cstr = value.c_str(); - writeInt(strm, size); - strm.write((char*) cstr, (std::streamsize)(sizeof(char)*size)); - return strm; -} - - -std::ostream& -FileHelpers::writeTime(std::ostream& strm, SUMOTime value) { - strm.write((char*) &value, sizeof(SUMOTime)); - return strm; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/utils/common/FileHelpers.h b/Util/OSM2ODR/src/utils/common/FileHelpers.h deleted file mode 100644 index 110bdd657..000000000 --- a/Util/OSM2ODR/src/utils/common/FileHelpers.h +++ /dev/null @@ -1,303 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file FileHelpers.h -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @author Jakob Erdmann -/// @date Mon, 17 Dec 2001 -/// -// Functions for an easier usage of files -/****************************************************************************/ -#pragma once -#include -#include -#include -#include -#include "SUMOTime.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class FileHelpers - * @brief Functions for an easier usage of files and paths - */ -class FileHelpers { -public: - /// @name file access functions - /// @{ - - /** @brief Checks whether the given file is readable - * - * @param[in] path The path to the file that shall be examined - * @return Whether the named file is readable - */ - static bool isReadable(std::string path); - - /** @brief Checks whether the given file is a directory - * - * @param[in] path The path to the file that shall be examined - * @return Whether the named file is a directory. - */ - static bool isDirectory(std::string path); - /// @} - - /// @name file path evaluating functions - /// @{ - - /** @brief Removes the file information from the given path - * - * @param[in] path The path to the file to return the folder it is located in - * @return The directory of the named file - */ - static std::string getFilePath(const std::string& path); - - /** @brief Add an extension to the given file path - * - * @param[in] path The path to the file - * @param[in] extension new extension (with dot, example: '.xml') - * @return the new path with extension, the same path if it already has the extension, or a empty string if path is invalid - */ - static std::string addExtension(const std::string& path, const std::string& extension); - - /** @brief Returns the second path as a relative path to the first file - * - * Given the position of the configuration file, and the information where a second - * file is relative to the configuration file's position, we want to known where - * this second file can be found. This method gets the path to the configuration file - * (including the configuration file name) and the path to get the relative position - * of and returns this relative position. - * - * @param[in] configPath The path the configuration file (including the config's file name) - * @param[in] path The path to the references file (relativ to configuration path) - * @return The file's position (relative to curent working directory) - */ - static std::string getConfigurationRelative(const std::string& configPath, const std::string& path); - - /** @brief Returns the information whether the given name represents a socket - * - * A file name is meant to describe a socket address if a colon is found at a position - * larger than one. - * - * @param[in] name The name of a file - * @return Whether the name names a socket - */ - static bool isSocket(const std::string& name); - - /** @brief Returns the information whether the given path is absolute - * - * A path is meant to be absolute, if - * @arg it is a socket - * @arg it starts with a "/" (Linux) - * @arg it has a ':' at the second position (Windows) - * - * @param[in] path The path to examine - * @return Whether the path is absolute - */ - static bool isAbsolute(const std::string& path); - - /** @brief Returns the path from a configuration so that it is accessable from the current working directory - * - * If the path is absolute, it is returned. Otherwise, the file's position - * is computed regarding the configuration path (see getConfigurationRelative). - * - * @see isAbsolute - * @see getConfigurationRelative - * @param[in] filename The path to the file to be examined - * @param[in] basePath The path the configuration file (including the config's file name) - * @return The file's position - */ - static std::string checkForRelativity(const std::string& filename, const std::string& basePath); - - /// @brief prepend the given prefix to the last path component of the given file path - static std::string prependToLastPathComponent(const std::string& prefix, const std::string& path); - - /// @} - - /// @name binary writing functions - /// @{ - - /** @brief Writes an integer binary - * - * @param[in, out] strm The stream to write into - * @param[in] value The integer to write - * @return Reference to the stream - */ - static std::ostream& writeInt(std::ostream& strm, int value); - - /** @brief Writes a float binary - * - * This method behaves differently depending on the definition of double at compile time. - * - * @param[in, out] strm The stream to write into - * @param[in] value The float to write - * @return Reference to the stream - */ - static std::ostream& writeFloat(std::ostream& strm, double value); - - /** @brief Writes a byte binary - * - * @param[in, out] strm The stream to write into - * @param[in] value The byte to write - * @return Reference to the stream - */ - static std::ostream& writeByte(std::ostream& strm, unsigned char value); - - /** @brief Writes a string binary - * - * Writes the length of the string, first, using writeInt. Writes then the string's - * characters. - * - * @see writeInt - * @param[in, out] strm The stream to write into - * @param[in] value The string to write - * @return Reference to the stream - */ - static std::ostream& writeString(std::ostream& strm, const std::string& value); - - /** @brief Writes a time description binary - * - * This method behaves differently depending on the definition of SUMOTime at compile time, - * which in turn depends on the enabling of subsecond timesteps. - * - * @param[in, out] strm The stream to write into - * @param[in] value The time to write - * @return Reference to the stream - */ - static std::ostream& writeTime(std::ostream& strm, SUMOTime value); - - /** @brief Writes an edge vector binary - * - * @param[in, out] os The stream to write into - * @param[in] edges The edges to write - * @return Reference to the stream - */ - template - static std::ostream& writeEdgeVector(std::ostream& os, const std::vector& edges); - - /** @brief Reads an edge vector binary - * - * @param[in] is The stream to read from - * @param[out] edges The edge vector to write into - * @return Reference to the stream - */ - template - static void readEdgeVector(std::istream& in, std::vector& edges, const std::string& rid); - /// @} -}; - - -template -std::ostream& FileHelpers::writeEdgeVector(std::ostream& os, const std::vector& edges) { - FileHelpers::writeInt(os, (int)edges.size()); - std::vector follow; - int maxFollow = 0; - E prev = edges.front(); - for (typename std::vector::const_iterator i = edges.begin() + 1; i != edges.end(); ++i) { - int idx = 0; - for (; idx < prev->getNumSuccessors(); ++idx) { - if (idx > 15) { - break; - } - if (prev->getSuccessors()[idx] == (*i)) { - follow.push_back(idx); - if (idx > maxFollow) { - maxFollow = idx; - } - break; - } - } - if (idx > 15 || idx == prev->getNumSuccessors()) { - follow.clear(); - break; - } - prev = *i; - } - if (follow.empty()) { - for (typename std::vector::const_iterator i = edges.begin(); i != edges.end(); ++i) { - FileHelpers::writeInt(os, (*i)->getNumericalID()); - } - } else { - const int bits = maxFollow > 3 ? 4 : 2; - const int numFields = 8 * sizeof(int) / bits; - FileHelpers::writeInt(os, -bits); - FileHelpers::writeInt(os, edges.front()->getNumericalID()); - int data = 0; - int field = 0; - for (std::vector::const_iterator i = follow.begin(); i != follow.end(); ++i) { - data |= *i; - field++; - if (field == numFields) { - FileHelpers::writeInt(os, data); - data = 0; - field = 0; - } else { - data <<= bits; - } - } - if (field > 0) { - FileHelpers::writeInt(os, data << ((numFields - field - 1) * bits)); - } - } - return os; -} - - -template -void FileHelpers::readEdgeVector(std::istream& in, std::vector& edges, const std::string& rid) { - int size; - in.read((char*) &size, sizeof(int)); - edges.reserve(size); - int bitsOrEntry; - in.read((char*) &bitsOrEntry, sizeof(int)); - if (bitsOrEntry < 0) { - const int bits = -bitsOrEntry; - const int numFields = 8 * sizeof(int) / bits; - const int mask = (1 << bits) - 1; - int edgeID; - in.read((char*) &edgeID, sizeof(int)); - const E* prev = E::getAllEdges()[edgeID]; - assert(prev != 0); - edges.push_back(prev); - size--; - int data = 0; - int field = numFields; - for (; size > 0; size--) { - if (field == numFields) { - in.read((char*) &data, sizeof(int)); - field = 0; - } - int followIndex = (data >> ((numFields - field - 1) * bits)) & mask; - if (followIndex >= prev->getNumSuccessors()) { - throw ProcessError("Invalid follower index in route '" + rid + "'!"); - } - prev = prev->getSuccessors()[followIndex]; - edges.push_back(prev); - field++; - } - } else { - while (size > 0) { - const E* edge = E::getAllEdges()[bitsOrEntry]; - if (edge == 0) { - throw ProcessError("An edge within the route '" + rid + "' is not known!"); - } - edges.push_back(edge); - size--; - if (size > 0) { - in.read((char*) &bitsOrEntry, sizeof(int)); - } - } - } -} diff --git a/Util/OSM2ODR/src/utils/common/IDSupplier.cpp b/Util/OSM2ODR/src/utils/common/IDSupplier.cpp deleted file mode 100644 index 33d3a8d6d..000000000 --- a/Util/OSM2ODR/src/utils/common/IDSupplier.cpp +++ /dev/null @@ -1,73 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file IDSupplier.cpp -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date Sept 2002 -/// -// A class that generates enumerated and prefixed string-ids -/****************************************************************************/ -#include - -#include -#include -#include -#include "StdDefs.h" -#include "IDSupplier.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -IDSupplier::IDSupplier(const std::string& prefix, long long int begin) - : myCurrent(begin), myPrefix(prefix) {} - - - -IDSupplier::IDSupplier(const std::string& prefix, const std::vector& knownIDs) - : myCurrent(0), myPrefix(prefix) { - for (std::vector::const_iterator id_it = knownIDs.begin(); id_it != knownIDs.end(); ++id_it) { - avoid(*id_it); - } -} - - -IDSupplier::~IDSupplier() {} - - -std::string -IDSupplier::getNext() { - std::ostringstream strm; - strm << myPrefix << myCurrent++; - return strm.str(); -} - - -void -IDSupplier::avoid(const std::string& id) { - // does it start with prefix? - if (id.find(myPrefix) == 0) { - long long int number; - std::istringstream buf(id.substr(myPrefix.size())); - buf >> number; - // does it continue with a number? - if (!buf.fail()) { - myCurrent = MAX2(myCurrent, number + 1); - } - } -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/utils/common/IDSupplier.h b/Util/OSM2ODR/src/utils/common/IDSupplier.h deleted file mode 100644 index 815356164..000000000 --- a/Util/OSM2ODR/src/utils/common/IDSupplier.h +++ /dev/null @@ -1,62 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file IDSupplier.h -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @date Sept 2002 -/// -// A class that generates enumerated and prefixed string-ids -/****************************************************************************/ -#pragma once -#include -#include - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class IDSupplier - * This class builds string ids by adding an increasing numerical value to a - * previously given string - */ -class IDSupplier { -public: - /// Constructor - IDSupplier(const std::string& prefix = "", long long int begin = 0); - - /** @brief Constructor - * @param[in] prefix The string to use as ID prefix - * @param[in] knownIDs List of IDs that should never be returned by this - * IDSupplier - **/ - IDSupplier(const std::string& prefix, const std::vector& knownIDs); - - /// Destructor - ~IDSupplier(); - - /// Returns the next id - std::string getNext(); - - /// make sure that the given id is never supplied - void avoid(const std::string& id); - -private: - /// The current index - long long int myCurrent; - - /// The prefix to use - std::string myPrefix; - -}; diff --git a/Util/OSM2ODR/src/utils/common/InstancePool.h b/Util/OSM2ODR/src/utils/common/InstancePool.h deleted file mode 100644 index 80fcbbfee..000000000 --- a/Util/OSM2ODR/src/utils/common/InstancePool.h +++ /dev/null @@ -1,98 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file InstancePool.h -/// @author Daniel Krajzewicz -/// @date Fri, 29.04.2005 -/// -// A pool of resuable instances -/****************************************************************************/ -#pragma once -#include -#include - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class InstancePool - * @brief A pool of resuable instances - */ -template -class InstancePool { -public: - /** @brief Constructor - * - * @param[in] deleteOnQuit Information whether stored instances shall be deleted when this container is deleted - */ - InstancePool(bool deleteOnQuit) : myDeleteOnQuit(deleteOnQuit) { } - - - /// @brief Destructor - ~InstancePool() { - typedef typename std::vector::iterator It; - if (myDeleteOnQuit) { - for (It i = myFreeInstances.begin(); i != myFreeInstances.end(); i++) { - delete *i; - } - } - } - - - /** @brief Returns a free instance or 0 if no such exists - * - * If any free instance is stored, it is returned and removed from - * the storage. If no one is stored, 0 is returned. - * - * @return A free instance or 0 if no such exists - */ - T* getFreeInstance() { - if (myFreeInstances.size() == 0) { - return 0; - } else { - T* instance = myFreeInstances.back(); - myFreeInstances.pop_back(); - return instance; - } - } - - - /** @brief Adds a free, reusable instance - * - * @param[in] instance An instance to add - */ - void addFreeInstance(T* instance) { - myFreeInstances.push_back(instance); - } - - - /** @brief Adds some free, reusable instances - * - * @param[in] instances A vector of instances to add - */ - void addFreeInstances(const std::vector instances) { - std::copy(instances.begin(), instances.end(), - std::back_inserter(myFreeInstances)); - } - - -private: - /// @brief List of reusable instances - std::vector myFreeInstances; - - /// @brief Information whether the stored instances shall be deleted - bool myDeleteOnQuit; - - -}; diff --git a/Util/OSM2ODR/src/utils/common/MsgHandler.cpp b/Util/OSM2ODR/src/utils/common/MsgHandler.cpp deleted file mode 100644 index 8197c5251..000000000 --- a/Util/OSM2ODR/src/utils/common/MsgHandler.cpp +++ /dev/null @@ -1,286 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file MsgHandler.cpp -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Tue, 17 Jun 2003 -/// -// Retrieves messages about the process and gives them further to output -/****************************************************************************/ -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include "MsgHandler.h" - - -// =========================================================================== -// static member variables -// =========================================================================== - -MsgHandler::Factory MsgHandler::myFactory = nullptr; -MsgHandler* MsgHandler::myDebugInstance = nullptr; -MsgHandler* MsgHandler::myGLDebugInstance = nullptr; -MsgHandler* MsgHandler::myErrorInstance = nullptr; -MsgHandler* MsgHandler::myWarningInstance = nullptr; -MsgHandler* MsgHandler::myMessageInstance = nullptr; -bool MsgHandler::myAmProcessingProcess = false; -bool MsgHandler::myWriteDebugMessages(false); -bool MsgHandler::myWriteDebugGLMessages(false); - - -// =========================================================================== -// method definitions -// =========================================================================== - -MsgHandler* -MsgHandler::getMessageInstance() { - if (myMessageInstance == nullptr) { - if (myFactory == nullptr) { - myMessageInstance = new MsgHandler(MT_MESSAGE); - } else { - myMessageInstance = myFactory(MT_MESSAGE); - } - } - return myMessageInstance; -} - - -MsgHandler* -MsgHandler::getWarningInstance() { - if (myWarningInstance == nullptr) { - if (myFactory == nullptr) { - myWarningInstance = new MsgHandler(MT_WARNING); - } else { - myWarningInstance = myFactory(MT_WARNING); - } - } - return myWarningInstance; -} - - -MsgHandler* -MsgHandler::getErrorInstance() { - if (myErrorInstance == nullptr) { - myErrorInstance = new MsgHandler(MT_ERROR); - } - return myErrorInstance; -} - - -MsgHandler* -MsgHandler::getDebugInstance() { - if (myDebugInstance == nullptr) { - myDebugInstance = new MsgHandler(MT_DEBUG); - } - return myDebugInstance; -} - - -MsgHandler* -MsgHandler::getGLDebugInstance() { - if (myGLDebugInstance == nullptr) { - myGLDebugInstance = new MsgHandler(MT_GLDEBUG); - } - return myGLDebugInstance; -} - - -void -MsgHandler::enableDebugMessages(bool enable) { - myWriteDebugMessages = enable; -} - -void -MsgHandler::enableDebugGLMessages(bool enable) { - myWriteDebugGLMessages = enable; -} - -void -MsgHandler::inform(std::string msg, bool addType) { - // beautify progress output - if (myAmProcessingProcess) { - myAmProcessingProcess = false; - MsgHandler::getMessageInstance()->inform(""); - } - msg = build(msg, addType); - // inform all receivers - for (auto i : myRetrievers) { - i->inform(msg); - } - // set the information that something occurred - myWasInformed = true; -} - - -void -MsgHandler::beginProcessMsg(std::string msg, bool addType) { - msg = build(msg, addType); - // inform all other receivers - for (auto i : myRetrievers) { - i->inform(msg, ' '); - myAmProcessingProcess = true; - } - // set the information that something occurred - myWasInformed = true; -} - - -void -MsgHandler::endProcessMsg(std::string msg) { - // inform all other receivers - for (auto i : myRetrievers) { - i->inform(msg); - } - // set the information that something occurred - myWasInformed = true; - myAmProcessingProcess = false; -} - - -void -MsgHandler::clear(bool resetInformed) { - if (resetInformed) { - myWasInformed = false; - } - if (myAggregationThreshold >= 0) { - for (const auto& i : myAggregationCount) { - if (i.second > myAggregationThreshold) { - inform(toString(i.second) + " total messages of type: " + i.first); - } - } - } - myAggregationCount.clear(); -} - - -void -MsgHandler::addRetriever(OutputDevice* retriever) { - if (!isRetriever(retriever)) { - myRetrievers.push_back(retriever); - } -} - - -void -MsgHandler::removeRetriever(OutputDevice* retriever) { - std::vector::iterator i = find(myRetrievers.begin(), myRetrievers.end(), retriever); - if (i != myRetrievers.end()) { - myRetrievers.erase(i); - } -} - - -bool -MsgHandler::isRetriever(OutputDevice* retriever) const { - return std::find(myRetrievers.begin(), myRetrievers.end(), retriever) != myRetrievers.end(); -} - - -void -MsgHandler::removeRetrieverFromAllInstances(OutputDevice* out) { - if (myDebugInstance != nullptr) { - myDebugInstance->removeRetriever(out); - } - if (myGLDebugInstance != nullptr) { - myGLDebugInstance->removeRetriever(out); - } - if (myErrorInstance != nullptr) { - myErrorInstance->removeRetriever(out); - } - if (myWarningInstance != nullptr) { - myWarningInstance->removeRetriever(out); - } - if (myMessageInstance != nullptr) { - myMessageInstance->removeRetriever(out); - } -} - -void -MsgHandler::initOutputOptions() { - // initialize console properly - OutputDevice::getDevice("stdout"); - OutputDevice::getDevice("stderr"); - OptionsCont& oc = OptionsCont::getOptions(); - getWarningInstance()->setAggregationThreshold(oc.getInt("aggregate-warnings")); - getErrorInstance()->setAggregationThreshold(oc.getInt("aggregate-warnings")); - if (oc.getBool("no-warnings")) { - getWarningInstance()->removeRetriever(&OutputDevice::getDevice("stderr")); - } - // build the logger if possible - if (oc.isSet("log", false)) { - OutputDevice* logFile = &OutputDevice::getDevice(oc.getString("log")); - getErrorInstance()->addRetriever(logFile); - if (!oc.getBool("no-warnings")) { - getWarningInstance()->addRetriever(logFile); - } - getMessageInstance()->addRetriever(logFile); - } - if (oc.isSet("message-log", false)) { - OutputDevice* logFile = &OutputDevice::getDevice(oc.getString("message-log")); - getMessageInstance()->addRetriever(logFile); - } - if (oc.isSet("error-log", false)) { - OutputDevice* logFile = &OutputDevice::getDevice(oc.getString("error-log")); - getErrorInstance()->addRetriever(logFile); - getWarningInstance()->addRetriever(logFile); - } - if (!oc.getBool("verbose")) { - getMessageInstance()->removeRetriever(&OutputDevice::getDevice("stdout")); - } -} - - -void -MsgHandler::cleanupOnEnd() { - delete myMessageInstance; - myMessageInstance = nullptr; - delete myWarningInstance; - myWarningInstance = nullptr; - delete myErrorInstance; - myErrorInstance = nullptr; - delete myDebugInstance; - myDebugInstance = nullptr; - delete myGLDebugInstance; - myGLDebugInstance = nullptr; -} - - -MsgHandler::MsgHandler(MsgType type) : - myType(type), myWasInformed(false), myAggregationThreshold(-1) { - if (type == MT_MESSAGE) { - addRetriever(&OutputDevice::getDevice("stdout")); - } else { - addRetriever(&OutputDevice::getDevice("stderr")); - } -} - - -MsgHandler::~MsgHandler() { -} - - -bool -MsgHandler::wasInformed() const { - return myWasInformed; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/utils/common/MsgHandler.h b/Util/OSM2ODR/src/utils/common/MsgHandler.h deleted file mode 100644 index a9c7e8fd9..000000000 --- a/Util/OSM2ODR/src/utils/common/MsgHandler.h +++ /dev/null @@ -1,287 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2003-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file MsgHandler.h -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @author Jakob Erdmann -/// @date Tue, 17 Jun 2003 -/// -// Retrieves messages about the process and gives them further to output -/****************************************************************************/ -#pragma once -#include -#include -#include -#include -#include - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * MsgHandler - */ -class MsgHandler { -public: - /** - * @enum MsgType - * An enumeration to differ between different types of messages - * (errors, warning and information) - */ - enum MsgType { - /// The message is only something to show - MT_MESSAGE, - /// The message is a warning - MT_WARNING, - /// The message is an error - MT_ERROR, - /// The message is an debug - MT_DEBUG, - /// The message is an debug - MT_GLDEBUG - }; - -private: - typedef MsgHandler* (*Factory)(MsgType); - -public: - /// @brief Sets the factory function to use for new MsgHandlers - static void setFactory(Factory func) { - // clean old instances - cleanupOnEnd(); - myFactory = func; - } - - /// @brief Returns the instance to add normal messages to - static MsgHandler* getMessageInstance(); - - /// @brief Returns the instance to add warnings to - static MsgHandler* getWarningInstance(); - - /// @brief Returns the instance to add errors to - static MsgHandler* getErrorInstance(); - - /// @brief Returns the instance to add debug to - static MsgHandler* getDebugInstance(); - - /// @brief Returns the instance to add GLdebug to - static MsgHandler* getGLDebugInstance(); - - /// @brief enable/disable debug messages - static void enableDebugMessages(bool enable); - - /// @brief enable/disable gl-debug messages - static void enableDebugGLMessages(bool enable); - - /// @brief check whether to enable/disable debug messages - static inline bool writeDebugMessages() { - return myWriteDebugMessages; - } - - /// @brief check whether to enable/disable gl-debug messages - static inline bool writeDebugGLMessages() { - return myWriteDebugGLMessages; - } - - /// @brief ensure that that given output device is no longer used as retriever by any instance - static void removeRetrieverFromAllInstances(OutputDevice* out); - - ///@brief init output options - static void initOutputOptions(); - - /// @brief Removes pending handler - static void cleanupOnEnd(); - - /// @brief adds a new error to the list - virtual void inform(std::string msg, bool addType = true); - - /// @brief adds a new formatted message - // variadic function - template - void informf(const std::string& format, T value, Targs... Fargs) { - if (!aggregationThresholdReached(format)) { - std::ostringstream os; - os << std::fixed << std::setprecision(gPrecision); - _informf(format.c_str(), os, value, Fargs...); - inform(os.str(), true); - } - } - - /** @brief Begins a process information - * - * When a longer action is started, this method should be used to inform the user about it. - * There will be no newline printed, but the message handler will be informed that - * a process message has been begun. If an error occurs, a newline will be printed. - * After the action has been performed, use endProcessMsg to inform the user about it. - */ - virtual void beginProcessMsg(std::string msg, bool addType = true); - - /// @brief Ends a process information - virtual void endProcessMsg(std::string msg); - - /// @brief Clears information whether an error occurred previously and print aggregated message summary - virtual void clear(bool resetInformed = true); - - /// @brief Adds a further retriever to the instance responsible for a certain msg type - virtual void addRetriever(OutputDevice* retriever); - - /// @brief Removes the retriever from the handler - virtual void removeRetriever(OutputDevice* retriever); - - /// @brief Returns whether the given output device retrieves messages from the handler - bool isRetriever(OutputDevice* retriever) const; - - /// @brief Returns the information whether any messages were added - bool wasInformed() const; - - /** @brief Generic output operator - * @return The MsgHandler for further processing - */ - template - MsgHandler& operator<<(const T& t) { - // inform all other receivers - for (OutputDevice* o : myRetrievers) { - (*o) << t; - } - return *this; - } - -protected: - /// @brief Builds the string which includes the mml-message type - inline std::string build(const std::string& msg, bool addType) { - if (addType) { - switch (myType) { - case MT_MESSAGE: - break; - case MT_WARNING: - return "Warning: " + msg; - break; - case MT_ERROR: - return "Error: " + msg; - break; - case MT_DEBUG: - return "Debug: " + msg; - break; - case MT_GLDEBUG: - return "GLDebug: " + msg; - break; - default: - break; - } - } - return msg; - } - - virtual bool aggregationThresholdReached(const std::string& format) { - return myAggregationThreshold >= 0 && myAggregationCount[format]++ >= myAggregationThreshold; - } - - void _informf(const char* format, std::ostringstream& os) { - os << format; - } - - /// @brief adds a new formatted message - // variadic function - template - void _informf(const char* format, std::ostringstream& os, T value, Targs... Fargs) { - for (; *format != '\0'; format++) { - if (*format == '%') { - os << value; - _informf(format + 1, os, Fargs...); // recursive call - return; - } - os << *format; - } - } - - void setAggregationThreshold(const int thresh) { - myAggregationThreshold = thresh; - } - - /// @brief standard constructor - MsgHandler(MsgType type); - - /// @brief destructor - virtual ~MsgHandler(); - -private: - /// @brief The function to call for new MsgHandlers, nullptr means use default constructor - static Factory myFactory; - - /// @brief The instance to handle debug - static MsgHandler* myDebugInstance; - - /// @brief The instance to handle glDebug - static MsgHandler* myGLDebugInstance; - - /// @brief The instance to handle errors - static MsgHandler* myErrorInstance; - - /// @brief The instance to handle warnings - static MsgHandler* myWarningInstance; - - /// @brief The instance to handle normal messages - static MsgHandler* myMessageInstance; - - /// @brief Information whether a process information is printed to cout - static bool myAmProcessingProcess; - -private: - /// @brief The type of the instance - MsgType myType; - - /// @brief information whether an output occurred at all - bool myWasInformed; - - /// @brief do not output more messages of the same type if the count exceeds this threshold - int myAggregationThreshold; - - /// @brief count for messages of the same type - std::map myAggregationCount; - - /// @brief The list of retrievers that shall be informed about new messages or errors - std::vector myRetrievers; - -private: - /// @brief invalid copy constructor - MsgHandler(const MsgHandler& s) = delete; - - /// @brief invalid assignment operator - MsgHandler& operator=(const MsgHandler& s) = delete; - - /** @brief Flag to enable or disable debug GL Functions - * - * This value is used to show more internal information throught warning messages about certain operations - */ - static bool myWriteDebugMessages; - static bool myWriteDebugGLMessages; -}; - - -// =========================================================================== -// global definitions -// =========================================================================== -#define WRITE_WARNING(msg) MsgHandler::getWarningInstance()->inform(msg); -#define WRITE_WARNINGF(...) MsgHandler::getWarningInstance()->informf(__VA_ARGS__); -#define WRITE_MESSAGE(msg) MsgHandler::getMessageInstance()->inform(msg); -#define PROGRESS_BEGIN_MESSAGE(msg) MsgHandler::getMessageInstance()->beginProcessMsg((msg) + std::string(" ...")); -#define PROGRESS_DONE_MESSAGE() MsgHandler::getMessageInstance()->endProcessMsg("done."); -#define PROGRESS_BEGIN_TIME_MESSAGE(msg) SysUtils::getCurrentMillis(); MsgHandler::getMessageInstance()->beginProcessMsg((msg) + std::string(" ...")); -#define PROGRESS_TIME_MESSAGE(before) MsgHandler::getMessageInstance()->endProcessMsg("done (" + toString(SysUtils::getCurrentMillis() - before) + "ms)."); -#define PROGRESS_FAILED_MESSAGE() MsgHandler::getMessageInstance()->endProcessMsg("failed."); -#define WRITE_ERROR(msg) MsgHandler::getErrorInstance()->inform(msg); -#define WRITE_ERRORF(...) MsgHandler::getErrorInstance()->informf(__VA_ARGS__); -#define WRITE_DEBUG(msg) if(MsgHandler::writeDebugMessages()){MsgHandler::getDebugInstance()->inform(msg);}; -#define WRITE_GLDEBUG(msg) if(MsgHandler::writeDebugGLMessages()){MsgHandler::getGLDebugInstance()->inform(msg);}; diff --git a/Util/OSM2ODR/src/utils/common/MsgRetrievingFunction.h b/Util/OSM2ODR/src/utils/common/MsgRetrievingFunction.h deleted file mode 100644 index d18211258..000000000 --- a/Util/OSM2ODR/src/utils/common/MsgRetrievingFunction.h +++ /dev/null @@ -1,98 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file MsgRetrievingFunction.h -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Mon, 24 Oct 2003 -/// -// Encapsulates an object's method for using it as a message retriever -/****************************************************************************/ -#pragma once -#include -#include -#include -#include "MsgHandler.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class MsgRetrievingFunction - * @brief Encapsulates an object's method for using it as a message retriever - * - * You may find an example for this class' usage in GUIRunThread. - */ -template< class T > -class MsgRetrievingFunction : public OutputDevice { -public: - /// @brief Type of the function to execute. - typedef void(T::* Operation)(const MsgHandler::MsgType, const std::string&); - - - /** @brief Constructor - * @param[in] object The object to call the method of - * @param[in] operation The method to call - * @param[in] type The type of the message - */ - MsgRetrievingFunction(T* object, Operation operation, MsgHandler::MsgType type) : - myObject(object), - myOperation(operation), - myMsgType(type) {} - - - /// @brief Destructor - ~MsgRetrievingFunction() {} - - -protected: - /// @name Methods that override/implement OutputDevice-methods - /// @{ - - /** @brief Returns the associated ostream - * - * The stream is an ostringstream, actually, into which the message - * is written. It is sent when postWriteHook is called. - * - * @return The used stream - * @see postWriteHook - */ - std::ostream& getOStream() { - return myMessage; - } - - - /** @brief Sends the data which was written to the string stream via the retrieving function. - */ - virtual void postWriteHook() { - (myObject->*myOperation)(myMsgType, myMessage.str()); - myMessage.str(""); - } - /// @} - - -private: - /// @brief The object the action is directed to. - T* myObject; - - /// @brief The object's operation to perform. - Operation myOperation; - - /// @brief The type of message to retrieve. - MsgHandler::MsgType myMsgType; - - /// @brief message buffer - std::ostringstream myMessage; - -}; diff --git a/Util/OSM2ODR/src/utils/common/Named.h b/Util/OSM2ODR/src/utils/common/Named.h deleted file mode 100644 index e21dfd757..000000000 --- a/Util/OSM2ODR/src/utils/common/Named.h +++ /dev/null @@ -1,126 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file Named.h -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @date Sept 2002 -/// -// Base class for objects which have an id. -/****************************************************************************/ -#pragma once -#include -#include -#include - - -/// @brief Function-object for stable sorting of objects acting like Named without being derived (SUMOVehicle) -// @note Numbers of different lengths will not be ordered by alphanumerical sorting -struct ComparatorIdLess { - template - bool operator()(const T* const a, const T* const b) const { - return a->getID() < b->getID(); - } -}; - - -/// @brief Function-object for stable sorting of objects with numerical ids -struct ComparatorNumericalIdLess { - template - bool operator()(const T* const a, const T* const b) const { - return a->getNumericalID() < b->getNumericalID(); - } -}; - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class Named - * @brief Base class for objects which have an id. - */ -class Named { -public: - /** @brief Constructor - * @param[in] id The id of the object - */ - Named(const std::string& id) : myID(id) { } - - - /// @brief Destructor - virtual ~Named() { } - - /// @brief get an identifier for Named-like object which may be Null - template - static std::string getIDSecure(const T* obj, const std::string& fallBack = "NULL") { - return obj == 0 ? fallBack : obj->getID(); - } - - /** @brief Returns the id - * @return The stored id - */ - const std::string& getID() const { - return myID; - } - - - /** @brief resets the id - * @param[in] newID The new id of this object - */ - virtual void setID(const std::string& newID) { - myID = newID; - } - - - /** @class StoringVisitor - * @brief Allows to store the object; used as context while traveling the rtree in TraCI - */ - class StoringVisitor { - public: - /// @brief Contructor - StoringVisitor(std::set& objects) : myObjects(objects) {} - - /// @brief Destructor - ~StoringVisitor() {} - - /// @brief Adds the given object to the container - void add(const Named* const o) const { - myObjects.insert(o); - } - - /// @brief The container - std::set& myObjects; - - private: - /// @brief invalidated copy constructor - StoringVisitor(const StoringVisitor& src); - - /// @brief invalidated assignment operator - StoringVisitor& operator=(const StoringVisitor& src); - }; - - - /** @brief Adds this object to the given container - * @param[in, filled] cont The container to add this item to - */ - void addTo(const StoringVisitor& cont) const { - cont.add(this); - } - - -protected: - /// @brief The name of the object - std::string myID; - -}; diff --git a/Util/OSM2ODR/src/utils/common/NamedObjectCont.h b/Util/OSM2ODR/src/utils/common/NamedObjectCont.h deleted file mode 100644 index f7fdffb96..000000000 --- a/Util/OSM2ODR/src/utils/common/NamedObjectCont.h +++ /dev/null @@ -1,154 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2002-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NamedObjectCont.h -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @author Jakob Erdmann -/// @date Sept 2002 -/// -// A map of named object pointers -/****************************************************************************/ -#pragma once -#include -#include -#include -#include - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NamedObjectCont - * @brief A map of named object pointers - * - * An associative storage (map) for objects (pointers to them to be exact), - * which do have a name. - */ -template -class NamedObjectCont { -public: - /// @brief Definition of the key to pointer map type - typedef std::map< std::string, T > IDMap; - - ///@brief Destructor - virtual ~NamedObjectCont() { - // iterate over all elements to delete it - for (auto i : myMap) { - delete i.second; - } - } - - /** @brief Adds an item - * - * If another item with the same name is already known, false is reported - * and the item is not added. - * - * @param[in] id The id of the item to add - * @param[in] item The item to add - * @return If the item could been added (no item with the same id was within the container before) - */ - bool add(const std::string& id, T item) { - if (myMap.find(id) != myMap.end()) { - return false; - } - myMap.insert(std::make_pair(id, item)); - return true; - } - - /** @brief Removes an item - * @param[in] id The id of the item to remove - * @param[in] del delete item after removing of container - * @return If the item could been removed (an item with the id was within the container before) - */ - bool remove(const std::string& id, const bool del = true) { - auto it = myMap.find(id); - if (it == myMap.end()) { - return false; - } else { - if (del) { - delete it->second; - } - myMap.erase(it); - return true; - } - } - - /** @brief Retrieves an item - * - * Returns 0 when no item with the given id is stored within the container - * - * @param[in] id The id of the item to retrieve - * @return The item stored under the given id, or 0 if no such item exists - */ - T get(const std::string& id) const { - auto it = myMap.find(id); - if (it == myMap.end()) { - return 0; - } else { - return it->second; - } - } - - /// @brief Removes all items from the container (deletes them, too) - void clear() { - for (auto i : myMap) { - delete i.second; - } - myMap.clear(); - } - - /// @brief Returns the number of stored items within the container - int size() const { - return (int) myMap.size(); - } - - /* @brief Fills the given vector with the stored objects' ids - * @param[in] into The container to fill - */ - void insertIDs(std::vector& into) const { - for (auto i : myMap) { - into.push_back(i.first); - } - } - - /// @brief change ID of a stored object - bool changeID(const std::string& oldId, const std::string& newId) { - auto i = myMap.find(oldId); - if (i == myMap.end()) { - return false; - } else { - // save Item, remove it from Map, and insert it again with the new ID - T item = i->second; - myMap.erase(i); - myMap.insert(std::make_pair(newId, item)); - return true; - } - } - - /// @brief Returns a reference to the begin iterator for the internal map - typename IDMap::const_iterator begin() const { - return myMap.begin(); - } - - /// @brief Returns a reference to the end iterator for the internal map - typename IDMap::const_iterator end() const { - return myMap.end(); - } - - -private: - /// @brief The map from key to object - IDMap myMap; -}; diff --git a/Util/OSM2ODR/src/utils/common/NamedRTree.h b/Util/OSM2ODR/src/utils/common/NamedRTree.h deleted file mode 100644 index 555db42d0..000000000 --- a/Util/OSM2ODR/src/utils/common/NamedRTree.h +++ /dev/null @@ -1,116 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2008-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NamedRTree.h -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date 27.10.2008 -/// -// A RT-tree for efficient storing of SUMO's Named objects -/****************************************************************************/ -#pragma once -#include -#include -#include - - -// specialized implementation for speedup and avoiding warnings -#define NAMED_RTREE_QUAL RTree - -template<> -inline float NAMED_RTREE_QUAL::RectSphericalVolume(Rect* a_rect) { - ASSERT(a_rect); - const float extent0 = a_rect->m_max[0] - a_rect->m_min[0]; - const float extent1 = a_rect->m_max[1] - a_rect->m_min[1]; - return .78539816f * (extent0 * extent0 + extent1 * extent1); -} - -template<> -inline NAMED_RTREE_QUAL::Rect NAMED_RTREE_QUAL::CombineRect(Rect* a_rectA, Rect* a_rectB) { - ASSERT(a_rectA && a_rectB); - Rect newRect; - newRect.m_min[0] = rtree_min(a_rectA->m_min[0], a_rectB->m_min[0]); - newRect.m_max[0] = rtree_max(a_rectA->m_max[0], a_rectB->m_max[0]); - newRect.m_min[1] = rtree_min(a_rectA->m_min[1], a_rectB->m_min[1]); - newRect.m_max[1] = rtree_max(a_rectA->m_max[1], a_rectB->m_max[1]); - return newRect; -} - -// =========================================================================== -// class definitions -// =========================================================================== -/** @class NamedRTree - * @brief A RT-tree for efficient storing of SUMO's Named objects - * - * This class specialises the used RT-tree implementation from "rttree.h". - * It stores names of "Named"-objects. - * @see Named - */ -class NamedRTree : private NAMED_RTREE_QUAL { -public: - /// @brief Constructor - NamedRTree() : NAMED_RTREE_QUAL(&Named::addTo) { - } - - - /// @brief Destructor - ~NamedRTree() { - } - - - /** @brief Insert entry - * @param a_min Min of bounding rect - * @param a_max Max of bounding rect - * @param a_data The instance of a Named-object to add (the ID is added) - * @see RTree::Insert - */ - void Insert(const float a_min[2], const float a_max[2], Named* const& a_data) { - NAMED_RTREE_QUAL::Insert(a_min, a_max, a_data); - } - - - /** @brief Remove entry - * @param a_min Min of bounding rect - * @param a_max Max of bounding rect - * @param a_data The instance of a Named-object to remove - * @see RTree::Remove - */ - void Remove(const float a_min[2], const float a_max[2], Named* const& a_data) { - NAMED_RTREE_QUAL::Remove(a_min, a_max, a_data); - } - - - /** @brief Remove all enrties - * @see RTree::RemoveAll - */ - void RemoveAll() { - NAMED_RTREE_QUAL::RemoveAll(); - } - - - /** @brief Find all within search rectangle - * @param a_min Min of search bounding rect - * @param a_max Max of search bounding rect - * @param a_searchResult Search result array. Caller should set grow size. Function will reset, not append to array. - * @param a_resultCallback Callback function to return result. Callback should return 'true' to continue searching - * @param a_context User context to pass as parameter to a_resultCallback - * @return Returns the number of entries found - * @see RTree::Search - */ - int Search(const float a_min[2], const float a_max[2], const Named::StoringVisitor& c) const { - return NAMED_RTREE_QUAL::Search(a_min, a_max, c); - } - - -}; diff --git a/Util/OSM2ODR/src/utils/common/Parameterised.cpp b/Util/OSM2ODR/src/utils/common/Parameterised.cpp deleted file mode 100644 index ab81d8320..000000000 --- a/Util/OSM2ODR/src/utils/common/Parameterised.cpp +++ /dev/null @@ -1,272 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file Parameterised.cpp -/// @author Daniel Krajzewicz -/// @date Sept 2002 -/// -// A super class for objects with additional parameters -/****************************************************************************/ -#include -#include -#include -#include -#include - -#include "Parameterised.h" - - -// =========================================================================== -// method definitions -// =========================================================================== - -Parameterised::Parameterised() : - myAttrType(ParameterisedAttrType::STRING) { -} - - -Parameterised::Parameterised(ParameterisedAttrType attrType) : - myAttrType(attrType) { -} - - -Parameterised::Parameterised(const std::map& mapArg) : - myAttrType(ParameterisedAttrType::STRING), - myMap(mapArg) { -} - - -Parameterised::Parameterised(ParameterisedAttrType attrType, const std::map& mapArg) : - myAttrType(attrType) { - // check if map has to be cleaned - if (myAttrType == ParameterisedAttrType::DOUBLE) { - // iterate over map - for (const auto& keyValue : mapArg) { - try { - // try to parse to do double, and if fails, write warning - StringUtils::toDouble(keyValue.second); - // insert keyValue in map - myMap.insert(keyValue); - } catch (NumberFormatException&) { - WRITE_WARNING("Invalid conversion from string to double (" + keyValue.second + ")"); - } - } - } else { - // just update myMap - myMap = mapArg; - } -} - - -Parameterised::~Parameterised() {} - - -void -Parameterised::setParameter(const std::string& key, const std::string& value) { - if (myAttrType == ParameterisedAttrType::DOUBLE) { - try { - // try to parse to do double, and if fails, write warning - StringUtils::toDouble(value); - // insert in map - myMap[key] = value; - } catch (NumberFormatException&) { - WRITE_WARNING("Invalid conversion from string to double (" + value + ")"); - } - } else { - myMap[key] = value; - } -} - - -void -Parameterised::unsetParameter(const std::string& key) { - myMap.erase(key); -} - - -void -Parameterised::updateParameters(const std::map& mapArg) { - for (const auto& keyValue : mapArg) { - setParameter(keyValue.first, keyValue.second); - } -} - - -bool -Parameterised::knowsParameter(const std::string& key) const { - return myMap.find(key) != myMap.end(); -} - - -const std::string -Parameterised::getParameter(const std::string& key, const std::string defaultValue) const { - const auto i = myMap.find(key); - if (i != myMap.end()) { - return i->second; - } - return defaultValue; -} - - -double -Parameterised::getDouble(const std::string& key, const double defaultValue) const { - const auto i = myMap.find(key); - if (i != myMap.end()) { - try { - return StringUtils::toDouble(i->second); - } catch (NumberFormatException&) { - WRITE_WARNING("Invalid conversion from string to double (" + i->second + ")"); - return defaultValue; - } catch (EmptyData&) { - WRITE_WARNING("Invalid conversion from string to double (empty value)"); - return defaultValue; - } - } - return defaultValue; -} - - -void -Parameterised::clearParameter() { - myMap.clear(); -} - - -const std::map& -Parameterised::getParametersMap() const { - return myMap; -} - - -std::string -Parameterised::getParametersStr(const std::string kvsep, const std::string sep) const { - std::string result; - // Generate an string using configurable seperatrs, default: "key1=value1|key2=value2|...|keyN=valueN" - bool addSep = false; - for (const auto& keyValue : myMap) { - if (addSep) { - result += sep; - } - result += keyValue.first + kvsep + keyValue.second; - addSep = true; - } - return result; -} - - -void -Parameterised::setParameters(const Parameterised& params) { - // first clear map - myMap.clear(); - // set parameter - for (const auto& keyValue : params.getParametersMap()) { - setParameter(keyValue.first, keyValue.second); - } -} - - -void -Parameterised::setParametersMap(const std::map& paramsMap) { - // first clear map - myMap.clear(); - // set parameter - for (const auto& keyValue : paramsMap) { - setParameter(keyValue.first, keyValue.second); - } -} - - -void -Parameterised::setParametersStr(const std::string& paramsString, const std::string kvsep, const std::string sep) { - // clear parameters - myMap.clear(); - // separate value in a vector of string using | as separator - std::vector parameters = StringTokenizer(paramsString, sep).getVector(); - // iterate over all values - for (const auto& keyValue : parameters) { - // obtain key and value and save it in myParameters - std::vector keyValueStr = StringTokenizer(keyValue, kvsep).getVector(); - setParameter(keyValueStr.front(), keyValueStr.back()); - } -} - - -void -Parameterised::writeParams(OutputDevice& device) const { - // iterate over all parameters and write it - for (const auto& keyValue : myMap) { - device.openTag(SUMO_TAG_PARAM); - device.writeAttr(SUMO_ATTR_KEY, StringUtils::escapeXML(keyValue.first)); - device.writeAttr(SUMO_ATTR_VALUE, StringUtils::escapeXML(keyValue.second)); - device.closeTag(); - } -} - - -bool -Parameterised::areParametersValid(const std::string& value, bool report, - const ParameterisedAttrType attrType, const std::string kvsep, const std::string sep) { - std::vector parameters = StringTokenizer(value, sep).getVector(); - // first check if parsed parameters are valid - for (const auto& keyValueStr : parameters) { - // check if parameter is valid - if (!isParameterValid(keyValueStr, attrType, kvsep, sep)) { - // report depending of flag - if (report) { - WRITE_WARNING("Invalid format of parameter (" + keyValueStr + ")"); - } - return false; - } - } - // all ok, then return true - return true; -} - -// =========================================================================== -// private -// =========================================================================== - -bool -Parameterised::isParameterValid(const std::string& value, ParameterisedAttrType attrType, - const std::string& kvsep, const std::string& sep) { - if (value.find(sep) != std::string::npos || value.find(kvsep) == std::string::npos) { - return false; - } - // separate key and value - std::vector keyValueStr = StringTokenizer(value, kvsep).getVector(); - // Check that keyValue size is exactly 2 (key, value) - if (keyValueStr.size() == 2) { - // check if key and value contains valid characters - if (SUMOXMLDefinitions::isValidParameterKey(keyValueStr.front()) == false) { - return false; - } else if (SUMOXMLDefinitions::isValidParameterValue(keyValueStr.back()) == false) { - return false; - } else if (attrType == ParameterisedAttrType::DOUBLE) { - // check if can be parsed to double - try { - StringUtils::toDouble(keyValueStr.back()); - return true; - } catch (NumberFormatException&) { - return false; - } - } else { - // key=value valid, then return true - return true; - } - } else { - // invalid format - return false; - } -} - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/utils/common/Parameterised.h b/Util/OSM2ODR/src/utils/common/Parameterised.h deleted file mode 100644 index 43dba5c83..000000000 --- a/Util/OSM2ODR/src/utils/common/Parameterised.h +++ /dev/null @@ -1,147 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2002-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file Parameterised.h -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @author Melanie Knocke -/// @date Sept 2002 -/// -// A super class for objects with additional parameters -/****************************************************************************/ -#pragma once -#include -#include - -// =========================================================================== -// class declarations -// =========================================================================== -class OutputDevice; - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class Parameterised - * @brief An upper class for objects with additional parameters - */ -class Parameterised { -public: - - /// @brie enum for Parameterised type - enum class ParameterisedAttrType { - /// @brief Parameterised accept strings - STRING, - /// @brief Parameterised only accept doubles - DOUBLE - }; - - /// @brief Default constructor (for Strings) - Parameterised(); - - /**@brief Constructor - * @param[in] attrType parameterised attribute type - */ - Parameterised(ParameterisedAttrType attrType); - - /**@brief Constructor with parameters (for Strings) - * @param[in] mapArg Pre-given parameter - */ - Parameterised(const std::map& mapArg); - - /**@brief Constructor with parameters - * @param[in] attrType parameterised attribute type - * @param[in] mapArg Pre-given parameter - */ - Parameterised(ParameterisedAttrType attrType, const std::map& mapArg); - - /// @brief Destructor - ~Parameterised(); - - /**@brief Sets a parameter - * @param[in] key The parameter's name - * @param[in] value The parameter's value - */ - void setParameter(const std::string& key, const std::string& value); - - /**@brief Removes a parameter - * @param[in] key The parameter's name - */ - void unsetParameter(const std::string& key); - - /**@brief Adds or updates all given parameters from the map - * @param[in] mapArg The keys/values to insert - */ - void updateParameters(const std::map& mapArg); - - /**@brief Returns whether the parameter is known - * @param[in] key The key to ask for - * @return Whether the key is known - */ - bool knowsParameter(const std::string& key) const; - - /**@brief Returns the value for a given key - * @param[in] key The key to ask for - * @param[in] defaultValue The default value to return if no value is stored under the key - * @return The value stored under the key - */ - const std::string getParameter(const std::string& key, const std::string defaultValue = "") const; - - /**@brief Returns the value for a given key converted to a double - * @param[in] key The key to ask for - * @param[in] defaultValue The default value to return if no value is stored under the key - * @return The value stored under the key - */ - double getDouble(const std::string& key, const double defaultValue) const; - - /// @brief Clears the parameter map - void clearParameter(); - - /// @brief Returns the inner key/value map - const std::map& getParametersMap() const; - - /// @brief Returns the inner key/value map in string format "key1=value1|key2=value2|...|keyN=valueN" - std::string getParametersStr(const std::string kvsep = "=", const std::string sep = "|") const; - - /// @brief set the inner key/value map in map format - void setParameters(const Parameterised& params); - - /// @brief set the inner key/value map in map format - void setParametersMap(const std::map& paramsMap); - - /**@brief set the inner key/value map in string format "key1=value1|key2=value2|...|keyN=valueN" - * @param[in] paramsString A serialized key-value map - * @param[in] kvsep The separater between key and value - * @param[in] sep The separater between map entries - */ - void setParametersStr(const std::string& paramsString, const std::string kvsep = "=", const std::string sep = "|"); - - /// @brief write Params in the given outputdevice - void writeParams(OutputDevice& device) const; - - /// @brief check if given string can be parsed to a parameters map "key1=value1|key2=value2|...|keyN=valueN" - static bool areParametersValid(const std::string& value, bool report = false, ParameterisedAttrType attrType = ParameterisedAttrType::STRING, - const std::string kvsep = "=", const std::string sep = "|"); - -private: - /// @brief check if given string can be parsed to a parameter of type "key=value" - static bool isParameterValid(const std::string& value, ParameterisedAttrType attrType, - const std::string& kvsep, const std::string& sep); - - /// @brief parameterised type - ParameterisedAttrType myAttrType; - - /// @brief The key->value map - std::map myMap; -}; diff --git a/Util/OSM2ODR/src/utils/common/ParametrisedWrappingCommand.h b/Util/OSM2ODR/src/utils/common/ParametrisedWrappingCommand.h deleted file mode 100644 index 40151a7b6..000000000 --- a/Util/OSM2ODR/src/utils/common/ParametrisedWrappingCommand.h +++ /dev/null @@ -1,111 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file ParametrisedWrappingCommand.h -/// @author Leonhard Luecken -/// @date Apr 2019 -/// -// A wrapper for a Command function with parameter -/****************************************************************************/ - -#pragma once - -#include "Command.h" - - -// =========================================================================== -// class definition -// =========================================================================== -/** - * @class ParametrisedWrappingCommand - * @brief A wrapper for a Command function with parameter - * @see WrappingCommand.h - */ -template< class T, class S > -class ParametrisedWrappingCommand : public Command { -public: - - /// @brief Type of the function to execute. (with parameter) - typedef SUMOTime(T::* Operation)(SUMOTime, S); - -public: - - /** - * @brief Constructor. - * - * @param[in] receiver Pointer to object of type T that will receive a call to one of it's methods. - * @param[in] parameter The methods parameter (must be copy-constructable) - * @param[in] operation The objects' method that will be called on execute() - */ - ParametrisedWrappingCommand(T* receiver, const S& param, Operation operation) - : myReceiver(receiver), myParameter(param), myOperation(operation), - myAmDescheduledByParent(false) {} - - - /// @brief Destructor - ~ParametrisedWrappingCommand() {} - - - /** @brief Marks this Command as being descheduled - * - * A simple boolean marker ("myAmDescheduledByParent") is set which - * prevents this command from being executed. - */ - void deschedule() { - myAmDescheduledByParent = true; - } - - /// @brief whether this command has been descheduled - bool isDescheduled() { - return myAmDescheduledByParent; - } - - - /// @name Derived from Command - /// @{ - - /** @brief Executes the command. - * - * If the command is not descheduled, the stored method of the stored instance - * is called. - * - * @param[in] currentTime The current simulation time - * @return The time after which the command shall be executed again, 0 if this command shall be descheduled. - * @exception ProcessError Derived actions may throw this exception - */ - SUMOTime execute(SUMOTime currentTime) { - // do not execute if the command was descheduled - if (myAmDescheduledByParent) { - return 0; - } - // execute if stil valid - return (myReceiver->*myOperation)(currentTime, myParameter); - } - /// @} - - -private: - /// @brief The object the action is directed to. - T* myReceiver; - - /// @brief The parameter - S myParameter; - - /// @brief The object's operation to perform. - Operation myOperation; - - /// @brief Whether this command was descheduled (is invalid) and shall not be executed - bool myAmDescheduledByParent; - -}; - diff --git a/Util/OSM2ODR/src/utils/common/PolySolver.cpp b/Util/OSM2ODR/src/utils/common/PolySolver.cpp deleted file mode 100644 index 9115736fe..000000000 --- a/Util/OSM2ODR/src/utils/common/PolySolver.cpp +++ /dev/null @@ -1,138 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file PolySolver.cpp -/// @author Jakub Sevcik (RICE) -/// @author Jan Prikryl (RICE) -/// @date Fri, 06.12.2019 -/// -// -/****************************************************************************/ -#include -#include -#include -#include // defines M_PI -#include "PolySolver.h" - - -// =========================================================================== -// static member variables -// =========================================================================== -// (none) - -// =========================================================================== -// member method definitions -// =========================================================================== -std::tuple -PolySolver::quadraticSolve(double a, double b, double c) { - // ax^2 + bx + c = 0 - // return only real roots - if (a == 0) { - //WRITE_WARNING("The coefficient of the quadrat of x is 0. Please use the utility for a FIRST degree linear. No further action taken."); - if (b == 0) { - if (c == 0) { - return std::make_tuple(2, std::numeric_limits::infinity(), -std::numeric_limits::infinity()); - } else { - return std::make_tuple(0, NAN, NAN); - } - } else { - return std::make_tuple(1, -c / b, NAN); - } - } - - if (c == 0) { - //WRITE_WARNING("One root is 0. Now divide through by x and use the utility for a FIRST degree linear to solve the resulting equation for the other one root. No further action taken."); - return std::make_tuple(2, 0, -b / a); - } - - double disc, x1_real, x2_real ; - disc = b * b - 4 * a * c; - - if (disc > 0) { - // two different real roots - x1_real = (-b + sqrt(disc)) / (2 * a); - x2_real = (-b - sqrt(disc)) / (2 * a); - return std::make_tuple(2, x1_real, x2_real); - } else if (disc == 0) { - // a real root with multiplicity 2 - x1_real = (-b + sqrt(disc)) / (2 * a); - return std::make_tuple(1, x1_real, NAN); - } else { - // all roots are complex - return std::make_tuple(0, NAN, NAN); - } -} - -std::tuple -PolySolver::cubicSolve(double a, double b, double c, double d) { - // ax^3 + bx^2 + cx + d = 0 - // return only real roots - if (a == 0) { - //WRITE_WARNING("The coefficient of the cube of x is 0. Please use the utility for a SECOND degree quadratic. No further action taken."); - int numX; - double x1, x2; - std::tie(numX, x1, x2) = quadraticSolve(b, c, d); - return std::make_tuple(numX, x1, x2, NAN); - } - if (d == 0) { - //WRITE_WARNING("One root is 0. Now divide through by x and use the utility for a SECOND degree quadratic to solve the resulting equation for the other two roots. No further action taken."); - int numX; - double x1, x2; - std::tie(numX, x1, x2) = quadraticSolve(a, b, c); - return std::make_tuple(numX + 1, 0, x1, x2); - } - - b /= a; - c /= a; - d /= a; - - double disc, q, r, dum1, s, t, term1, r13; - q = (3.0 * c - (b * b)) / 9.0; - r = -(27.0 * d) + b * (9.0 * c - 2.0 * (b * b)); - r /= 54.0; - disc = q * q * q + r * r; - term1 = (b / 3.0); - - double x1_real, x2_real, x3_real; - if (disc > 0) { // One root real, two are complex - s = r + sqrt(disc); - s = s < 0 ? -cbrt(-s) : cbrt(s); - t = r - sqrt(disc); - t = t < 0 ? -cbrt(-t) : cbrt(t); - x1_real = -term1 + s + t; - term1 += (s + t) / 2.0; - x3_real = x2_real = -term1; - return std::make_tuple(1, x1_real, NAN, NAN); - } - // The remaining options are all real - else if (disc == 0) { // All roots real, at least two are equal. - r13 = r < 0 ? -cbrt(-r) : cbrt(r); - x1_real = -term1 + 2.0 * r13; - x3_real = x2_real = -(r13 + term1); - return std::make_tuple(2, x1_real, x2_real, NAN); - } - // Only option left is that all roots are real and unequal (to get here, q < 0) - else { - q = -q; - dum1 = q * q * q; - dum1 = acos(r / sqrt(dum1)); - r13 = 2.0 * sqrt(q); - x1_real = -term1 + r13 * cos(dum1 / 3.0); - x2_real = -term1 + r13 * cos((dum1 + 2.0 * M_PI) / 3.0); - x3_real = -term1 + r13 * cos((dum1 + 4.0 * M_PI) / 3.0); - return std::make_tuple(3, x1_real, x2_real, x3_real); - } -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/utils/common/PolySolver.h b/Util/OSM2ODR/src/utils/common/PolySolver.h deleted file mode 100644 index d52007bec..000000000 --- a/Util/OSM2ODR/src/utils/common/PolySolver.h +++ /dev/null @@ -1,57 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2005-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file PolySolver.h -/// @author Jakub Sevcik (RICE) -/// @author Jan Prikryl (RICE) -/// @date Fri, 06.12.2019 -/// -// -/****************************************************************************/ -#pragma once -#include - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class PolySolver - * @brief Utility functions for solving quadratic and cubic equations in real domain. - */ -class PolySolver { -public: - - /** @brief Solver of quadratic equation ax^2 + bx + c = 0 - * - * Returns only real-valued roots. - * - * @param[in] a The coefficient of the quadratic term x^2 - * @param[in] b The coefficient of the linear term x - * @param[in] c The coefficient of the constant term - * @return The number of real roots and these real roots - */ - static std::tuple quadraticSolve(double a, double b, double c); - - /** @brief Solver of cubic equation ax^3 + bx^2 + cx + d = 0 - * - * Returns only real-valued roots. - * - * @param[in] a The coefficient of the cubic term x^3 - * @param[in] b The coefficient of the quadratic term x^2 - * @param[in] c The coefficient of the linear term x - * @param[in] d The coefficient of the constant term - * @return The number of real roots and these real roots - */ - static std::tuple cubicSolve(double a, double b, double c, double d); - -}; diff --git a/Util/OSM2ODR/src/utils/common/RGBColor.cpp b/Util/OSM2ODR/src/utils/common/RGBColor.cpp deleted file mode 100644 index c1a2dcf3a..000000000 --- a/Util/OSM2ODR/src/utils/common/RGBColor.cpp +++ /dev/null @@ -1,341 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file RGBColor.cpp -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @author Laura Bieker -/// @date Sept 2002 -/// -// A RGB-color definition -/****************************************************************************/ -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "RGBColor.h" - - -// =========================================================================== -// static member definitions -// =========================================================================== -const RGBColor RGBColor::RED = RGBColor(255, 0, 0, 255); -const RGBColor RGBColor::GREEN = RGBColor(0, 255, 0, 255); -const RGBColor RGBColor::BLUE = RGBColor(0, 0, 255, 255); -const RGBColor RGBColor::YELLOW = RGBColor(255, 255, 0, 255); -const RGBColor RGBColor::CYAN = RGBColor(0, 255, 255, 255); -const RGBColor RGBColor::MAGENTA = RGBColor(255, 0, 255, 255); -const RGBColor RGBColor::ORANGE = RGBColor(255, 128, 0, 255); -const RGBColor RGBColor::WHITE = RGBColor(255, 255, 255, 255); -const RGBColor RGBColor::BLACK = RGBColor(0, 0, 0, 255); -const RGBColor RGBColor::GREY = RGBColor(128, 128, 128, 255); -const RGBColor RGBColor::INVISIBLE = RGBColor(0, 0, 0, 0); - -const RGBColor RGBColor::DEFAULT_COLOR = RGBColor::YELLOW; -const std::string RGBColor::DEFAULT_COLOR_STRING = toString(RGBColor::DEFAULT_COLOR); - -// random colors do not affect the simulation. No initialization is necessary -std::mt19937 RGBColor::myRNG; - -// =========================================================================== -// method definitions -// =========================================================================== -RGBColor::RGBColor() - : myRed(0), myGreen(0), myBlue(0), myAlpha(0) {} - - -RGBColor::RGBColor(unsigned char red, unsigned char green, unsigned char blue, unsigned char alpha) - : myRed(red), myGreen(green), myBlue(blue), myAlpha(alpha) {} - - -RGBColor::RGBColor(const RGBColor& col) - : myRed(col.myRed), myGreen(col.myGreen), myBlue(col.myBlue), myAlpha(col.myAlpha) {} - - -RGBColor::~RGBColor() {} - - -void -RGBColor::set(unsigned char r, unsigned char g, unsigned char b, unsigned char a) { - myRed = r; - myGreen = g; - myBlue = b; - myAlpha = a; -} - - -std::ostream& -operator<<(std::ostream& os, const RGBColor& col) { - if (col == RGBColor::RED) { - return os << "red"; - } - if (col == RGBColor::GREEN) { - return os << "green"; - } - if (col == RGBColor::BLUE) { - return os << "blue"; - } - if (col == RGBColor::YELLOW) { - return os << "yellow"; - } - if (col == RGBColor::CYAN) { - return os << "cyan"; - } - if (col == RGBColor::MAGENTA) { - return os << "magenta"; - } - if (col == RGBColor::ORANGE) { - return os << "orange"; - } - if (col == RGBColor::WHITE) { - return os << "white"; - } - if (col == RGBColor::BLACK) { - return os << "black"; - } - if (col == RGBColor::GREY) { - return os << "grey"; - } - os << static_cast(col.myRed) << "," - << static_cast(col.myGreen) << "," - << static_cast(col.myBlue); - if (col.myAlpha < 255) { - os << "," << static_cast(col.myAlpha); - } - return os; -} - - -bool -RGBColor::operator==(const RGBColor& c) const { - return myRed == c.myRed && myGreen == c.myGreen && myBlue == c.myBlue && myAlpha == c.myAlpha; -} - - -bool -RGBColor::operator!=(const RGBColor& c) const { - return myRed != c.myRed || myGreen != c.myGreen || myBlue != c.myBlue || myAlpha != c.myAlpha; -} - - -RGBColor -RGBColor::invertedColor() const { - // obtain inverse colors - const unsigned char r = (unsigned char)(255 - (int)myRed); - const unsigned char g = (unsigned char)(255 - (int)myGreen); - const unsigned char b = (unsigned char)(255 - (int)myBlue); - // return inverted RBColor - return RGBColor(r, g, b, myAlpha); -} - - -RGBColor -RGBColor::changedBrightness(int change, int toChange) const { - const unsigned char red = (unsigned char)(MIN2(MAX2(myRed + change, 0), 255)); - const unsigned char blue = (unsigned char)(MIN2(MAX2(myBlue + change, 0), 255)); - const unsigned char green = (unsigned char)(MIN2(MAX2(myGreen + change, 0), 255)); - int changed = ((int)red - (int)myRed) + ((int)blue - (int)myBlue) + ((int)green - (int)myGreen); - const RGBColor result(red, green, blue, myAlpha); - if (changed == toChange * change) { - return result; - } else if (changed == 0) { - return result; - } else { - const int maxedColors = (red != myRed + change ? 1 : 0) + (blue != myBlue + change ? 1 : 0) + (green != myGreen + change ? 1 : 0); - if (maxedColors == 3) { - return result; - } else { - const int toChangeNext = 3 - maxedColors; - return result.changedBrightness((int)((toChange * change - changed) / toChangeNext), toChangeNext); - } - } -} - - -RGBColor -RGBColor::parseColor(std::string coldef) { - std::transform(coldef.begin(), coldef.end(), coldef.begin(), tolower); - if (coldef == "red") { - return RED; - } - if (coldef == "green") { - return GREEN; - } - if (coldef == "blue") { - return BLUE; - } - if (coldef == "yellow") { - return YELLOW; - } - if (coldef == "cyan") { - return CYAN; - } - if (coldef == "magenta") { - return MAGENTA; - } - if (coldef == "orange") { - return ORANGE; - } - if (coldef == "white") { - return WHITE; - } - if (coldef == "black") { - return BLACK; - } - if (coldef == "grey" || coldef == "gray") { - return GREY; - } - if (coldef == "invisible") { - return INVISIBLE; - } - if (coldef == "random") { - return fromHSV(RandHelper::rand(360, &myRNG), - // prefer more saturated colors - pow(RandHelper::rand(&myRNG), 0.3), - // prefer brighter colors - pow(RandHelper::rand(&myRNG), 0.3)); - } - unsigned char r = 0; - unsigned char g = 0; - unsigned char b = 0; - unsigned char a = 255; - if (coldef[0] == '#') { - const int coldesc = StringUtils::hexToInt(coldef); - if (coldef.length() == 7) { - r = static_cast((coldesc & 0xFF0000) >> 16); - g = static_cast((coldesc & 0x00FF00) >> 8); - b = coldesc & 0xFF; - } else if (coldef.length() == 9) { - r = static_cast((coldesc & 0xFF000000) >> 24); - g = static_cast((coldesc & 0x00FF0000) >> 16); - b = static_cast((coldesc & 0x0000FF00) >> 8); - a = coldesc & 0xFF; - } else { - throw EmptyData(); - } - } else { - std::vector st = StringTokenizer(coldef, ",").getVector(); - if (st.size() == 3 || st.size() == 4) { - try { - r = static_cast(StringUtils::toInt(st[0])); - g = static_cast(StringUtils::toInt(st[1])); - b = static_cast(StringUtils::toInt(st[2])); - if (st.size() == 4) { - a = static_cast(StringUtils::toInt(st[3])); - } - if (r <= 1 && g <= 1 && b <= 1 && (st.size() == 3 || a <= 1)) { - throw NumberFormatException("(color component) " + coldef); - } - } catch (NumberFormatException&) { - r = static_cast(StringUtils::toDouble(st[0]) * 255. + 0.5); - g = static_cast(StringUtils::toDouble(st[1]) * 255. + 0.5); - b = static_cast(StringUtils::toDouble(st[2]) * 255. + 0.5); - if (st.size() == 4) { - a = static_cast(StringUtils::toDouble(st[3]) * 255. + 0.5); - } - } - } else { - throw EmptyData(); - } - } - return RGBColor(r, g, b, a); -} - - -RGBColor -RGBColor::parseColorReporting( - const std::string& coldef, const std::string& objecttype, - const char* objectid, bool report, bool& ok) { - UNUSED_PARAMETER(report); - try { - return parseColor(coldef); - } catch (NumberFormatException&) { - } catch (EmptyData&) { - } - ok = false; - std::ostringstream oss; - oss << "Attribute 'color' in definition of "; - if (objectid == nullptr) { - oss << "a "; - } - oss << objecttype; - if (objectid != nullptr) { - oss << " '" << objectid << "'"; - } - oss << " is not a valid color."; - WRITE_ERROR(oss.str()); - return RGBColor(); -} - - -RGBColor -RGBColor::interpolate(const RGBColor& minColor, const RGBColor& maxColor, double weight) { - if (weight < 0) { - weight = 0; - } - if (weight > 1) { - weight = 1; - } - const unsigned char r = (unsigned char)((int)minColor.myRed + (((int)maxColor.myRed - (int)minColor.myRed) * weight)); - const unsigned char g = (unsigned char)((int)minColor.myGreen + (((int)maxColor.myGreen - (int)minColor.myGreen) * weight)); - const unsigned char b = (unsigned char)((int)minColor.myBlue + (((int)maxColor.myBlue - (int)minColor.myBlue) * weight)); - const unsigned char a = (unsigned char)((int)minColor.myAlpha + (((int)maxColor.myAlpha - (int)minColor.myAlpha) * weight)); - return RGBColor(r, g, b, a); -} - - -RGBColor -RGBColor::fromHSV(double h, double s, double v) { - h /= 60.; - const int i = int(floor(h)); - double f = h - i; - if (i % 2 == 0) { - f = 1. - f; - } - const unsigned char m = static_cast(v * (1 - s) * 255. + 0.5); - const unsigned char n = static_cast(v * (1 - s * f) * 255. + 0.5); - const unsigned char vv = static_cast(v * 255. + 0.5); - switch (i) { - case 6: - case 0: - return RGBColor(vv, n, m, 255); - case 1: - return RGBColor(n, vv, m, 255); - case 2: - return RGBColor(m, vv, n, 255); - case 3: - return RGBColor(m, n, vv, 255); - case 4: - return RGBColor(n, m, vv, 255); - case 5: - return RGBColor(vv, m, n, 255); - } - return RGBColor(255, 255, 255, 255); -} - -RGBColor -RGBColor::randomHue(double s, double v) { - return fromHSV(RandHelper::rand(360, &myRNG), s, v); -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/utils/common/RGBColor.h b/Util/OSM2ODR/src/utils/common/RGBColor.h deleted file mode 100644 index be626e46e..000000000 --- a/Util/OSM2ODR/src/utils/common/RGBColor.h +++ /dev/null @@ -1,211 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file RGBColor.h -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date Sept 2002 -/// -// A RGB-color definition -/****************************************************************************/ -#pragma once -#include -#include -#include - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class RGBColor - * The definition of a color in the RGB-space with an alpha channel. - * The cube is meant to lie between (0, 0, 0) and (255, 255, 255) - */ -class RGBColor { -public: - /** @brief Constructor - */ - RGBColor(); - - /** @brief Constructor - * @param[in] red The red component's value - * @param[in] green The green component's value - * @param[in] blue The blue component's value - */ - RGBColor(unsigned char red, unsigned char green, unsigned char blue, unsigned char alpha = 255); - - /// @brief Copy constructor - RGBColor(const RGBColor& col); - - /// @brief Destructor - ~RGBColor(); - - /** @brief Returns the red-amount of the color - * @return The red component's value - */ - unsigned char red() const { - return myRed; - } - - /** @brief Returns the green-amount of the color - * @return The green component's value - */ - unsigned char green() const { - return myGreen; - } - - /** @brief Returns the blue-amount of the color - * @return The blue component's value - */ - unsigned char blue() const { - return myBlue; - } - - /** @brief Returns the alpha-amount of the color - * @return The alpha component's value - */ - unsigned char alpha() const { - return myAlpha; - } - - /** @brief assigns new values - * @param[in] r The red component's value - * @param[in] g The green component's value - * @param[in] b The blue component's value - * @param[in] a The alpha component's value - */ - void set(unsigned char r, unsigned char g, unsigned char b, unsigned char a); - - /** @brief Sets a new alpha value - * @param[in] alpha The new value to use - */ - inline void setAlpha(unsigned char alpha) { - myAlpha = alpha; - } - - - /** @brief Returns a new color with altered brightness - * @param[in] change The absolute change applied to all channels (within bounds) - * @param[in] change The number of colors to change - * @return The new color - */ - RGBColor changedBrightness(int change, int toChange = 3) const; - - /// @brief obtain inverted of current RGBColor - RGBColor invertedColor() const; - - static std::mt19937* getColorRNG() { - return &myRNG; - } - - /** @brief Parses a color information - * - * It is assumed that the color is stored as ",," - * and each color is represented as a double. - * Alternatively the color can be stored as ",,," - * and each color is represented as an unsigned byte. - * @param[in] coldef The color definition to parse - * @return The parsed color - * @exception EmptyData If the definition has less than three entries - * @exception NumberFormatException If one of the components is not numeric - */ - static RGBColor parseColor(std::string coldef); - - /** @brief Parses a color information - * - * It is assumed that the color is stored as ",," - * and each color is represented as a double. - * Alternatively the color can be stored as ",,," - * and each color is represented as an unsigned byte. - * @param[in] coldef The color definition to parse - * @param[in] objecttype The type of the currently parsed object - * @param[in] objectid The id of the currently parsed object - * @param[in] report Whether errors shall be reported - * @param[in, out] ok Whether parsing was successful - * @return The parsed color - * @exception EmptyData If the definition has less than three entries - * @exception NumberFormatException If one of the components is not numeric - */ - static RGBColor parseColorReporting(const std::string& coldef, const std::string& objecttype, - const char* objectid, bool report, bool& ok); - - /** @brief Interpolates between two colors - * - * The interpolated color is calculated as a weighted average of - * the RGB values of minColor and maxColor, giving weight to maxColor - * and 1-weight to minColor. - * @param[in] minColor The color to interpolate from - * @param[in] maxColor The color to interpolate to - * @param[in] weight The weight of the first color - * @return The interpolated color - */ - static RGBColor interpolate(const RGBColor& minColor, const RGBColor& maxColor, double weight); - - /** @brief Converts the given hsv-triplet to rgb, inspired by http://alvyray.com/Papers/CG/hsv2rgb.htm - * @param[in] h Hue (0-360) - * @param[in] s Saturation (0-1) - * @param[in] v Value (0-1) - * @return The color as RGB - */ - static RGBColor fromHSV(double h, double s, double v); - - /** @brief Return color with random hue - * @param[in] s Saturation (0-1) - * @param[in] v Value (0-1) - * @return The color as RGB - */ - static RGBColor randomHue(double s = 1, double v = 1); - - /** @brief Writes the color to the given stream - * @param[out] os The stream to write to - * @param[in] col The color to write - * @return The stream - */ - friend std::ostream& operator<<(std::ostream& os, const RGBColor& col); - - // @brief Equality operator - bool operator==(const RGBColor& c) const; - - // @brief Inequality operator - bool operator!=(const RGBColor& c) const; - - /// @brief named colors - /// @{ - static const RGBColor RED; - static const RGBColor GREEN; - static const RGBColor BLUE; - static const RGBColor YELLOW; - static const RGBColor CYAN; - static const RGBColor MAGENTA; - static const RGBColor ORANGE; - static const RGBColor WHITE; - static const RGBColor BLACK; - static const RGBColor GREY; - static const RGBColor INVISIBLE; - /// @} - - /// @brief The default color (for vehicle types and vehicles) - static const RGBColor DEFAULT_COLOR; - - /// @brief The string description of the default color - static const std::string DEFAULT_COLOR_STRING; - -private: - /// @brief The color amounts - unsigned char myRed, myGreen, myBlue, myAlpha; - - /// @brief A random number generator to generate random colors independent of other randomness - static std::mt19937 myRNG; -}; diff --git a/Util/OSM2ODR/src/utils/common/RandHelper.cpp b/Util/OSM2ODR/src/utils/common/RandHelper.cpp deleted file mode 100644 index fa08761aa..000000000 --- a/Util/OSM2ODR/src/utils/common/RandHelper.cpp +++ /dev/null @@ -1,82 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file RandHelper.cpp -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Tue, 29.05.2005 -/// -// -/****************************************************************************/ -#include - -#include -#include -#include -#include "RandHelper.h" - - -// =========================================================================== -// static member variables -// =========================================================================== -std::mt19937 RandHelper::myRandomNumberGenerator; -#ifdef DEBUG_RANDCALLS -std::map RandHelper::myCallCount; -std::map RandHelper::myRngId; -int RandHelper::myDebugIndex(7); -#endif - - -// =========================================================================== -// member method definitions -// =========================================================================== -void -RandHelper::insertRandOptions() { - OptionsCont& oc = OptionsCont::getOptions(); - // registers random number options - oc.addOptionSubTopic("Random Number"); - - oc.doRegister("random", new Option_Bool(false)); - oc.addSynonyme("random", "abs-rand", true); - oc.addDescription("random", "Random Number", "Initialises the random number generator with the current system time"); - - oc.doRegister("seed", new Option_Integer(23423)); - oc.addSynonyme("seed", "srand", true); - oc.addDescription("seed", "Random Number", "Initialises the random number generator with the given value"); -} - - -void -RandHelper::initRand(std::mt19937* which, const bool random, const int seed) { - if (which == nullptr) { - which = &myRandomNumberGenerator; - } -#ifdef DEBUG_RANDCALLS - myRngId[which] = myRngId.size(); -#endif - if (random) { - which->seed((unsigned long)time(nullptr)); - } else { - which->seed(seed); - } -} - - -void -RandHelper::initRandGlobal(std::mt19937* which) { - OptionsCont& oc = OptionsCont::getOptions(); - initRand(which, oc.getBool("random"), oc.getInt("seed")); -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/utils/common/RandHelper.h b/Util/OSM2ODR/src/utils/common/RandHelper.h deleted file mode 100644 index 4002b0096..000000000 --- a/Util/OSM2ODR/src/utils/common/RandHelper.h +++ /dev/null @@ -1,182 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2005-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file RandHelper.h -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @author Jakob Erdmann -/// @date Fri, 29.04.2005 -/// -// -/****************************************************************************/ -#pragma once -#include -#include -#include -#include -#include -#include - -//#define DEBUG_RANDCALLS - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class RandHelper - * @brief Utility functions for using a global, resetable random number generator - */ -class RandHelper { -public: - /// @brief Initialises the given options container with random number options - static void insertRandOptions(); - - /// @brief Initialises the random number generator with hardware randomness or seed - static void initRand(std::mt19937* which = 0, const bool random = false, const int seed = 23423); - - /// @brief Reads the given random number options and initialises the random number generator in accordance - static void initRandGlobal(std::mt19937* which = 0); - - /// @brief Returns a random real number in [0, 1) - static inline double rand(std::mt19937* rng = 0) { - if (rng == 0) { - rng = &myRandomNumberGenerator; - } - const double res = double((*rng)() / 4294967296.0); -#ifdef DEBUG_RANDCALLS - myCallCount[rng]++; - if (myCallCount[rng] == myDebugIndex) { - std::cout << "DEBUG\n"; // for setting breakpoint - } - std::stringstream stream; // to reduce output interleaving from different threads - stream << " rng" << myRngId.find(rng)->second << " rand call=" << myCallCount[rng] << " val=" << res << "\n"; - std::cout << stream.str(); -#endif - return res; - } - - /// @brief Returns a random real number in [0, maxV) - static inline double rand(double maxV, std::mt19937* rng = 0) { - return maxV * rand(rng); - } - - /// @brief Returns a random real number in [minV, maxV) - static inline double rand(double minV, double maxV, std::mt19937* rng = 0) { - return minV + (maxV - minV) * rand(rng); - } - - /// @brief Returns a random integer in [0, maxV-1] - static inline int rand(int maxV, std::mt19937* rng = 0) { - if (rng == 0) { - rng = &myRandomNumberGenerator; - } - unsigned int usedBits = maxV - 1; - usedBits |= usedBits >> 1; - usedBits |= usedBits >> 2; - usedBits |= usedBits >> 4; - usedBits |= usedBits >> 8; - usedBits |= usedBits >> 16; - - // Draw numbers until one is found in [0, maxV-1] - int result; - do { - result = (*rng)() & usedBits; - } while (result >= maxV); - return result; - } - - /// @brief Returns a random integer in [minV, maxV-1] - static inline int rand(int minV, int maxV, std::mt19937* rng = 0) { - return minV + rand(maxV - minV, rng); - } - - /// @brief Returns a random 64 bit integer in [0, maxV-1] - static inline long long int rand(long long int maxV, std::mt19937* rng = 0) { - if (maxV <= std::numeric_limits::max()) { - return rand((int)maxV, rng); - } - if (rng == 0) { - rng = &myRandomNumberGenerator; - } - unsigned long long int usedBits = maxV - 1; - usedBits |= usedBits >> 1; - usedBits |= usedBits >> 2; - usedBits |= usedBits >> 4; - usedBits |= usedBits >> 8; - usedBits |= usedBits >> 16; - usedBits |= usedBits >> 32; - - // Draw numbers until one is found in [0, maxV-1] - long long int result; - do { - result = (((unsigned long long int)(*rng)() << 32) | (*rng)()) & usedBits; // toss unused bits to shorten search - } while (result >= maxV); - return result; - } - - /// @brief Returns a random 64 bit integer in [minV, maxV-1] - static inline long long int rand(long long int minV, long long int maxV, std::mt19937* rng = 0) { - return minV + rand(maxV - minV, rng); - } - - /// @brief Access to a random number from a normal distribution - static inline double randNorm(double mean, double variance, std::mt19937* rng = 0) { - // Polar method to avoid cosine - double u, q; - do { - u = rand(2.0, rng) - 1; - const double v = rand(2.0, rng) - 1; - q = u * u + v * v; - } while (q == 0.0 || q >= 1.0); - return (double)(mean + variance * u * sqrt(-2 * log(q) / q)); - } - - /// @brief Returns a random element from the given vector - template - static inline const T& - getRandomFrom(const std::vector& v, std::mt19937* rng = 0) { - assert(v.size() > 0); - return v[rand((int)v.size(), rng)]; - } - - /// @brief save rng state to string - static std::string saveState(std::mt19937* rng = 0) { - if (rng == 0) { - rng = &myRandomNumberGenerator; - } - std::ostringstream oss; - oss << (*rng); - return oss.str(); - } - - /// @brief load rng state from string - static void loadState(const std::string& state, std::mt19937* rng = 0) { - if (rng == 0) { - rng = &myRandomNumberGenerator; - } - std::istringstream iss(state); - iss >> (*rng); - } - - -protected: - /// @brief the random number generator to use - static std::mt19937 myRandomNumberGenerator; - -#ifdef DEBUG_RANDCALLS - static std::map myCallCount; - static std::map myRngId; - static int myDebugIndex; -#endif - -}; diff --git a/Util/OSM2ODR/src/utils/common/SUMOTime.cpp b/Util/OSM2ODR/src/utils/common/SUMOTime.cpp deleted file mode 100644 index bc42b2f52..000000000 --- a/Util/OSM2ODR/src/utils/common/SUMOTime.cpp +++ /dev/null @@ -1,118 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file SUMOTime.cpp -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date Fri, 29.04.2005 -/// -// Variables, methods, and tools for internal time representation -/****************************************************************************/ -#include - -#include -#include -#include -#include "SUMOTime.h" -#include "StringTokenizer.h" -#include "StringUtils.h" -#include "StdDefs.h" -#include "MsgHandler.h" - - -// =========================================================================== -// type definitions -// =========================================================================== -SUMOTime DELTA_T = 1000; - - -// =========================================================================== -// method definitions -// =========================================================================== - -SUMOTime -string2time(const std::string& r) { - if (r.find(":") == std::string::npos) { - const double time = StringUtils::toDouble(r); - if (time > STEPS2TIME(SUMOTime_MAX)) { - throw TimeFormatException("Input string '" + r + "' exceeds the time value range."); - } - return TIME2STEPS(time); - } else { - // try to parse jj:hh:mm:ss.s - std::vector hrt = StringTokenizer(r, ":").getVector(); - if (hrt.size() == 3) { - //std::cout << "parsed '" << r << "' as " << (3600 * string2time(hrt[0]) + 60 * string2time(hrt[1]) + string2time(hrt[2])) << "\n"; - return 3600 * string2time(hrt[0]) + 60 * string2time(hrt[1]) + string2time(hrt[2]); - } else if (hrt.size() == 4) { - //std::cout << "parsed '" << r << "' as " << (24 * 3600 * string2time(hrt[0]) + 3600 * string2time(hrt[1]) + 60 * string2time(hrt[2]) + string2time(hrt[3])) << "\n"; - return 24 * 3600 * string2time(hrt[0]) + 3600 * string2time(hrt[1]) + 60 * string2time(hrt[2]) + string2time(hrt[3]); - } - throw TimeFormatException("Input string '" + r + "' is not a valid time format (jj:HH:MM:SS.S)."); - } -} - - -std::string -time2string(SUMOTime t) { - std::ostringstream oss; - if (t < 0) { - oss << "-"; - } - // needed for signed zero errors, see #5926 - t = abs(t); - const SUMOTime scale = (SUMOTime)pow(10, MAX2(0, 3 - gPrecision)); - if (scale > 1 && t != SUMOTime_MAX) { - t = (t + scale / 2) / scale; - } - const SUMOTime second = TIME2STEPS(1) / scale; - if (gHumanReadableTime) { - const SUMOTime minute = 60 * second; - const SUMOTime hour = 60 * minute; - const SUMOTime day = 24 * hour; - // 123456 -> "00:00:12.34" - if (t > day) { - oss << t / day << ":"; - t %= day; - } - oss << std::setfill('0') << std::setw(2); - oss << t / hour << ":"; - t %= hour; - oss << std::setw(2) << t / minute << ":"; - t %= minute; - oss << std::setw(2) << t / second; - t %= second; - if (t != 0 || TS < 1.) { - oss << std::setw(MIN2(3, gPrecision)); - oss << "." << t; - } - } else { - oss << t / second << "."; - oss << std::setfill('0') << std::setw(MIN2(3, gPrecision)); - oss << t % second; - } - return oss.str(); -} - - -bool checkStepLengthMultiple(const SUMOTime t, const std::string& error, SUMOTime deltaT) { - if (t % deltaT != 0) { - WRITE_WARNING("The given time value " + time2string(t) + " is not a multiple of the step length " + time2string(deltaT) + error + ".") - } - // next line used to fix build - return false; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/utils/common/SUMOTime.h b/Util/OSM2ODR/src/utils/common/SUMOTime.h deleted file mode 100644 index 3369b6301..000000000 --- a/Util/OSM2ODR/src/utils/common/SUMOTime.h +++ /dev/null @@ -1,73 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file SUMOTime.h -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date Fri, 29.04.2005 -/// -// Variables, methods, and tools for internal time representation -/****************************************************************************/ -#pragma once -#include -#include -#include "UtilExceptions.h" - - -// =========================================================================== -// type definitions -// =========================================================================== -typedef long long int SUMOTime; -#define SUMOTime_MAX std::numeric_limits::max() -#define SUMOTime_MIN std::numeric_limits::min() -#define SUMOTIME_MAXSTRING "9223372036854774" // SUMOTime_MAX / 1000 - 1 (because of rounding errors) - -// the step length in ms -extern SUMOTime DELTA_T; - -// the step length in seconds as double -#define TS (static_cast(DELTA_T/1000.)) - -// x*deltaT -#define SPEED2DIST(x) ((x)*TS) -// x/deltaT -#define DIST2SPEED(x) ((x)/TS) -// x*deltaT*deltaT -#define ACCEL2DIST(x) ((x)*TS*TS) -// x*deltaT -#define ACCEL2SPEED(x) ((x)*TS) -// x*deltaT -#define SPEED2ACCEL(x) ((x)/TS) - -#define STEPS2TIME(x) (static_cast((x)/1000.)) -// static cast to long long int truncates so we must pad away from 0 for correct rounding -#define TIME2STEPS(x) (static_cast((x) * 1000. + ((x) >= 0 ? 0.5 : -0.5))) -#define STEPFLOOR(x) (int(x/DELTA_T)*DELTA_T) -#define STEPS2MS(x) (x) - -#define SIMSTEP MSNet::getInstance()->getCurrentTimeStep() -#define SIMTIME STEPS2TIME(MSNet::getInstance()->getCurrentTimeStep()) - -// =========================================================================== -// method declarations -// =========================================================================== - -/// @brief convert string to SUMOTime -SUMOTime string2time(const std::string& r); - -/// @brief convert SUMOTime to string -std::string time2string(SUMOTime t); - -/// @brief check if given SUMOTime is multiple of the step length -bool checkStepLengthMultiple(const SUMOTime t, const std::string& error = "", SUMOTime deltaT = DELTA_T); diff --git a/Util/OSM2ODR/src/utils/common/SUMOVehicleClass.cpp b/Util/OSM2ODR/src/utils/common/SUMOVehicleClass.cpp deleted file mode 100644 index ce478872c..000000000 --- a/Util/OSM2ODR/src/utils/common/SUMOVehicleClass.cpp +++ /dev/null @@ -1,461 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file SUMOVehicleClass.cpp -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @author Walter Bamberger -/// @author Laura Bieker-Walz -/// @date 2006-01-24 -/// -// Definitions of SUMO vehicle classes and helper functions -/****************************************************************************/ -#include - -#include -#include -#include "SUMOVehicleClass.h" -#include -#include -#include -#include -#include -#include - - -// =========================================================================== -// static members -// =========================================================================== - -StringBijection::Entry sumoVehicleClassStringInitializer[] = { - {"ignoring", SVC_IGNORING}, - {"private", SVC_PRIVATE}, - {"public_emergency", SVC_EMERGENCY}, // !!! deprecated - {"emergency", SVC_EMERGENCY}, - {"public_authority", SVC_AUTHORITY}, // !!! deprecated - {"authority", SVC_AUTHORITY}, - {"public_army", SVC_ARMY}, // !!! deprecated - {"army", SVC_ARMY}, - {"vip", SVC_VIP}, - {"passenger", SVC_PASSENGER}, - {"hov", SVC_HOV}, - {"taxi", SVC_TAXI}, - {"public_transport", SVC_BUS}, // !!! deprecated - {"bus", SVC_BUS}, - {"coach", SVC_COACH}, - {"delivery", SVC_DELIVERY}, - {"transport", SVC_TRUCK}, - {"truck", SVC_TRUCK}, - {"trailer", SVC_TRAILER}, - {"lightrail", SVC_TRAM}, // !!! deprecated - {"tram", SVC_TRAM}, - {"cityrail", SVC_RAIL_URBAN}, // !!! deprecated - {"rail_urban", SVC_RAIL_URBAN}, - {"rail_slow", SVC_RAIL}, // !!! deprecated - {"rail", SVC_RAIL}, - {"rail_fast", SVC_RAIL_FAST}, - {"rail_electric", SVC_RAIL_ELECTRIC}, - {"motorcycle", SVC_MOTORCYCLE}, - {"moped", SVC_MOPED}, - {"bicycle", SVC_BICYCLE}, - {"pedestrian", SVC_PEDESTRIAN}, - {"evehicle", SVC_E_VEHICLE}, - {"ship", SVC_SHIP}, - {"custom1", SVC_CUSTOM1}, - {"custom2", SVC_CUSTOM2} -}; - -StringBijection SumoVehicleClassStrings( - sumoVehicleClassStringInitializer, SVC_CUSTOM2, false); - - -std::set deprecatedVehicleClassesSeen; - - -StringBijection::Entry sumoVehicleShapeStringInitializer[] = { - {"pedestrian", SVS_PEDESTRIAN}, - {"bicycle", SVS_BICYCLE}, - {"moped", SVS_MOPED}, - {"motorcycle", SVS_MOTORCYCLE}, - {"passenger", SVS_PASSENGER}, - {"passenger/sedan", SVS_PASSENGER_SEDAN}, - {"passenger/hatchback", SVS_PASSENGER_HATCHBACK}, - {"passenger/wagon", SVS_PASSENGER_WAGON}, - {"passenger/van", SVS_PASSENGER_VAN}, - {"delivery", SVS_DELIVERY}, - {"transport", SVS_TRUCK}, // !!! deprecated - {"truck", SVS_TRUCK}, - {"transport/semitrailer", SVS_TRUCK_SEMITRAILER}, // !!! deprecated - {"truck/semitrailer", SVS_TRUCK_SEMITRAILER}, - {"transport/trailer", SVS_TRUCK_1TRAILER}, // !!! deprecated - {"truck/trailer", SVS_TRUCK_1TRAILER}, - {"bus/city", SVS_BUS}, // !!! deprecated - {"bus", SVS_BUS}, - {"bus/overland", SVS_BUS_COACH}, // !!! deprecated - {"bus/coach", SVS_BUS_COACH}, - {"bus/flexible", SVS_BUS_FLEXIBLE}, - {"bus/trolley", SVS_BUS_TROLLEY}, - {"rail/slow", SVS_RAIL}, // !!! deprecated - {"rail/fast", SVS_RAIL}, // !!! deprecated - {"rail", SVS_RAIL}, - {"rail/light", SVS_RAIL_CAR}, // !!! deprecated - {"rail/city", SVS_RAIL_CAR}, // !!! deprecated - {"rail/railcar", SVS_RAIL_CAR}, - {"rail/cargo", SVS_RAIL_CARGO}, - {"evehicle", SVS_E_VEHICLE}, - {"ant", SVS_ANT}, - {"ship", SVS_SHIP}, - {"emergency", SVS_EMERGENCY}, - {"firebrigade", SVS_FIREBRIGADE}, - {"police", SVS_POLICE}, - {"rickshaw", SVS_RICKSHAW }, - {"", SVS_UNKNOWN} -}; - - -StringBijection SumoVehicleShapeStrings( - sumoVehicleShapeStringInitializer, SVS_UNKNOWN, false); - -// =========================================================================== -// static values used for cached -// =========================================================================== - -static std::map > vehicleClassNamesListCached; -static std::map parseVehicleClassesCached; -static std::map getVehicleClassNamesCached; -static std::string vehicleClassNameAll = "all"; - -// =========================================================================== -// additional constants -// =========================================================================== - -const SUMOVehicleClass SUMOVehicleClass_MAX = SVC_CUSTOM2; - -const SVCPermissions SVCAll = 2 * (int)SUMOVehicleClass_MAX - 1; // all relevant bits set to 1 - -const SVCPermissions SVC_UNSPECIFIED = -1; - -const std::string DEFAULT_VTYPE_ID("DEFAULT_VEHTYPE"); - -const std::string DEFAULT_PEDTYPE_ID("DEFAULT_PEDTYPE"); - -const std::string DEFAULT_BIKETYPE_ID("DEFAULT_BIKETYPE"); - -const std::string DEFAULT_CONTAINERTYPE_ID("DEFAULT_CONTAINERTYPE"); - -const std::string DEFAULT_TAXITYPE_ID("DEFAULT_TAXITYPE"); - -const double DEFAULT_VEH_PROB(1.); - -const double DEFAULT_PEDESTRIAN_SPEED(5. / 3.6); - -const double DEFAULT_CONTAINER_TRANSHIP_SPEED(5. / 3.6); - -// =========================================================================== -// method definitions -// =========================================================================== -// ------------ Conversion of SUMOVehicleClass - -const std::string& -getVehicleClassNames(SVCPermissions permissions, bool expand) { - if (permissions == SVCAll && !expand) { - return vehicleClassNameAll; - } - // check if previously was cached - if (getVehicleClassNamesCached.count(permissions) == 0) { - getVehicleClassNamesCached[permissions] = joinToString(getVehicleClassNamesList(permissions), ' '); - } - return getVehicleClassNamesCached.at(permissions); -} - - -const std::vector& -getVehicleClassNamesList(SVCPermissions permissions) { - // first check if it's cached - if (vehicleClassNamesListCached.count(permissions) == 0) { - const std::vector classNames = SumoVehicleClassStrings.getStrings(); - std::vector result; - for (std::vector::const_iterator it = classNames.begin(); it != classNames.end(); it++) { - const int svc = (int)SumoVehicleClassStrings.get(*it); - if ((svc & permissions) == svc && svc != SVC_IGNORING) { - result.push_back(*it); - } - } - // add it into vehicleClassNamesListCached - vehicleClassNamesListCached[permissions] = result; - } - return vehicleClassNamesListCached.at(permissions); -} - - -SUMOVehicleClass -getVehicleClassID(const std::string& name) { - if (SumoVehicleClassStrings.hasString(name)) { - return SumoVehicleClassStrings.get(name); - } - throw InvalidArgument("Unknown vehicle class '" + name + "'."); -} - - -int -getVehicleClassCompoundID(const std::string& name) { - int ret = SVC_IGNORING; - const std::vector names = SumoVehicleClassStrings.getStrings(); - for (std::vector::const_iterator it = names.begin(); it != names.end(); it++) { - if (name.find(*it) != std::string::npos) { - ret = ret | (int) SumoVehicleClassStrings.get(*it); - } - } - return ret; -} - - -SVCPermissions -parseVehicleClasses(const std::string& allowedS) { - if (allowedS == "all") { - return SVCAll; - } - // check if allowedS was previously cached - if (parseVehicleClassesCached.count(allowedS) == 0) { - SVCPermissions result = 0; - StringTokenizer sta(allowedS, " "); - while (sta.hasNext()) { - const std::string s = sta.next(); - if (!SumoVehicleClassStrings.hasString(s)) { - WRITE_ERROR("Unknown vehicle class '" + s + "' encountered."); - } else { - const SUMOVehicleClass vc = getVehicleClassID(s); - const std::string& realName = SumoVehicleClassStrings.getString(vc); - if (realName != s) { - deprecatedVehicleClassesSeen.insert(s); - } - result |= vc; - } - } - // save parsed vehicle class cached - parseVehicleClassesCached[allowedS] = result; - } - return parseVehicleClassesCached.at(allowedS); -} - - -bool -canParseVehicleClasses(const std::string& classes) { - if (classes == "all") { - return true; - } - // check if was previously cached - if (parseVehicleClassesCached.count(classes) != 0) { - return true; - } - StringTokenizer sta(classes, " "); - while (sta.hasNext()) { - if (!SumoVehicleClassStrings.hasString(sta.next())) { - return false; - } - } - return true; -} - - -SVCPermissions -parseVehicleClasses(const std::string& allowedS, const std::string& disallowedS, double networkVersion) { - if (allowedS.size() == 0 && disallowedS.size() == 0) { - return SVCAll; - } else if (allowedS.size() > 0 && disallowedS.size() > 0) { - WRITE_WARNING("SVCPermissions must be specified either via 'allow' or 'disallow'. Ignoring 'disallow'"); - return parseVehicleClasses(allowedS); - } else if (allowedS.size() > 0) { - return parseVehicleClasses(allowedS); - } else { - return invertPermissions(parseVehicleClasses(disallowedS) | (networkVersion < 1.3 ? SVC_RAIL_FAST : 0)); - } -} - - -SVCPermissions -invertPermissions(SVCPermissions permissions) { - return SVCAll & ~permissions; -} - - -SVCPermissions -parseVehicleClasses(const std::vector& allowedS) { - SVCPermissions result = 0; - if (std::find(allowedS.begin(), allowedS.end(), "all") != allowedS.end()) { - return SVCAll; - } - for (std::vector::const_iterator i = allowedS.begin(); i != allowedS.end(); ++i) { - const SUMOVehicleClass vc = getVehicleClassID(*i); - const std::string& realName = SumoVehicleClassStrings.getString(vc); - if (realName != *i) { - WRITE_WARNING("The vehicle class '" + (*i) + "' is deprecated, use '" + realName + "' instead."); - } - result |= getVehicleClassID(*i); - } - return result; -} - - -void -writePermissions(OutputDevice& into, SVCPermissions permissions) { - if (permissions == SVCAll) { - return; - } else if (permissions == 0) { - into.writeAttr(SUMO_ATTR_DISALLOW, "all"); - return; - } else { - int num_allowed = 0; - for (int mask = 1; mask <= SUMOVehicleClass_MAX; mask = mask << 1) { - if ((mask & permissions) == mask) { - ++num_allowed; - } - } - if (num_allowed <= (SumoVehicleClassStrings.size() - num_allowed) && num_allowed > 0) { - into.writeAttr(SUMO_ATTR_ALLOW, getVehicleClassNames(permissions)); - } else { - into.writeAttr(SUMO_ATTR_DISALLOW, getVehicleClassNames(~permissions)); - } - } -} - - -void -writePreferences(OutputDevice& into, SVCPermissions preferred) { - if (preferred == SVCAll || preferred == 0) { - return; - } else { - into.writeAttr(SUMO_ATTR_PREFER, getVehicleClassNames(preferred)); - } -} - - -SUMOVehicleShape -getVehicleShapeID(const std::string& name) { - if (SumoVehicleShapeStrings.hasString(name)) { - return SumoVehicleShapeStrings.get(name); - } else { - throw InvalidArgument("Unknown vehicle shape '" + name + "'."); - } -} - - -bool -canParseVehicleShape(const std::string& shape) { - return SumoVehicleShapeStrings.hasString(shape); -} - - -std::string -getVehicleShapeName(SUMOVehicleShape id) { - return SumoVehicleShapeStrings.getString(id); -} - - -bool isRailway(SVCPermissions permissions) { - return (permissions & SVC_RAIL_CLASSES) > 0 && (permissions & SVC_PASSENGER) == 0; -} - - -bool -isWaterway(SVCPermissions permissions) { - return permissions == SVC_SHIP; -} - - -bool -isForbidden(SVCPermissions permissions) { - return (permissions & SVCAll) == 0; -} - - -bool -isSidewalk(SVCPermissions permissions) { - return (permissions & SVCAll) == SVC_PEDESTRIAN; -} - - -bool -noVehicles(SVCPermissions permissions) { - return isForbidden(permissions) || isSidewalk(permissions); -} - - -std::map parseStopOffsets(const SUMOSAXAttributes& attrs, bool& ok) { - const std::string vClasses = attrs.getOpt(SUMO_ATTR_VCLASSES, nullptr, ok, ""); - const std::string exceptions = attrs.getOpt(SUMO_ATTR_EXCEPTIONS, nullptr, ok, ""); - if (attrs.hasAttribute(SUMO_ATTR_VCLASSES) && attrs.hasAttribute(SUMO_ATTR_EXCEPTIONS)) { - WRITE_ERROR("Simultaneous specification of vClasses and exceptions is not allowed!"); - ok = false; - return std::map(); - } - const double value = attrs.get(SUMO_ATTR_VALUE, nullptr, ok); - - int vClassBitset; - if (attrs.hasAttribute(SUMO_ATTR_VCLASSES)) { - vClassBitset = parseVehicleClasses(vClasses); - } else if (attrs.hasAttribute(SUMO_ATTR_EXCEPTIONS)) { - vClassBitset = ~parseVehicleClasses(exceptions); - } else { - // no vClasses specified, thus apply to all - vClassBitset = parseVehicleClasses("all"); - } - - std::map offsets; - offsets[vClassBitset] = value; - return offsets; -} - - -double -getDefaultVehicleLength(const SUMOVehicleClass vc) { - switch (vc) { - case SVC_PEDESTRIAN: - return 0.215; - case SVC_BICYCLE: - return 1.6; - case SVC_MOPED: - return 2.1; - case SVC_MOTORCYCLE: - return 2.2; - case SVC_TRUCK: - return 7.1; - case SVC_TRAILER: - return 16.5; - case SVC_BUS: - return 12.; - case SVC_COACH: - return 14.; - case SVC_TRAM: - return 22.; - case SVC_RAIL_URBAN: - return 36.5 * 3; - case SVC_RAIL: - return 67.5 * 2; - case SVC_RAIL_ELECTRIC: - case SVC_RAIL_FAST: - return 25. * 8; - case SVC_DELIVERY: - case SVC_EMERGENCY: - return 6.5; - case SVC_SHIP: - return 17; - default: - return 5; /*4.3*/ - } -} - - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/utils/common/SUMOVehicleClass.h b/Util/OSM2ODR/src/utils/common/SUMOVehicleClass.h deleted file mode 100644 index 0acd25e89..000000000 --- a/Util/OSM2ODR/src/utils/common/SUMOVehicleClass.h +++ /dev/null @@ -1,368 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file SUMOVehicleClass.h -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @author Walter Bamberger -/// @author Laura Bieker -/// @date 2006-01-24 -/// -// Definitions of SUMO vehicle classes and helper functions -/****************************************************************************/ -#pragma once -#include -#include -#include -#include -#include -#include -#include - - -// =========================================================================== -// class declarations -// =========================================================================== -class OutputDevice; -class SUMOSAXAttributes; - -// =========================================================================== -// enum definitions -// =========================================================================== -/** - * @enum SUMOVehicleShape - * @brief Definition of vehicle classes to differ between different appearences - */ -enum SUMOVehicleShape { - /// @brief not defined - SVS_UNKNOWN, - /// @brief render as a pedestrian - SVS_PEDESTRIAN, - /// @brief render as a bicycle - SVS_BICYCLE, - /// @brief render as a moped - SVS_MOPED, - /// @brief render as a motorcycle - SVS_MOTORCYCLE, - /// @brief render as a passenger vehicle - SVS_PASSENGER, - /// @brief render as a sedan passenger vehicle ("Stufenheck") - SVS_PASSENGER_SEDAN, - /// @brief render as a hatchback passenger vehicle ("Fliessheck") - SVS_PASSENGER_HATCHBACK, - /// @brief render as a wagon passenger vehicle ("Combi") - SVS_PASSENGER_WAGON, - /// @brief render as a van - SVS_PASSENGER_VAN, - /// @brief automated car (with cruise controllers) - //SVS_PASSENGER_AUTOMATED, - /// @brief render as a delivery vehicle - SVS_DELIVERY, - /// @brief render as a transport vehicle - SVS_TRUCK, - /// @brief render as a semi-trailer transport vehicle ("Sattelschlepper") - SVS_TRUCK_SEMITRAILER, - /// @brief render as a transport vehicle with one trailer - SVS_TRUCK_1TRAILER, - /// @brief render as a bus - SVS_BUS, - /// @brief render as a coach - SVS_BUS_COACH, - /// @brief render as a flexible city bus - SVS_BUS_FLEXIBLE, - /// @brief render as a trolley bus - SVS_BUS_TROLLEY, - /// @brief render as a rail - SVS_RAIL, - /// @brief render as a (city) rail without locomotive - SVS_RAIL_CAR, - /// @brief render as a cargo train - SVS_RAIL_CARGO, - /// @brief render as a (futuristic) e-vehicle - SVS_E_VEHICLE, - /// @brief render as a giant ant - SVS_ANT, - /// @brief render as a arbitrary ship - SVS_SHIP, - /// @brief render as an emergency vehicle - SVS_EMERGENCY, - /// @brief render as a fire brigade - SVS_FIREBRIGADE, - /// @brief render as a police car - SVS_POLICE, - /// @brief render as a rickshaw - SVS_RICKSHAW -}; - - - -/** - * @enum SUMOVehicleClass - * @brief Definition of vehicle classes to differ between different lane usage and authority types - * - * Bits: - * @arg 0-7: vehicle ownership - * @arg 8-23: vehicle size - * - * From NavTeq: - * @arg [0] All - * @arg [1] Passenger cars - * @arg [2] High Occupancy Vehicle - * @arg [3] Emergency Vehicle - * @arg [4] Taxi - * @arg [5] Public Bus - * @arg [6] Delivery Truck - * @arg [7] Transport Truck - * @arg [8] Bicycle - * @arg [9] Pedestrian - */ -enum SUMOVehicleClass { - /// @brief vehicles ignoring classes - SVC_IGNORING = 0, - - /// @name vehicle ownership - //@{ - - /// @brief private vehicles - SVC_PRIVATE = 1, - /// @brief public emergency vehicles - SVC_EMERGENCY = 1 << 1, - /// @brief authorities vehicles - SVC_AUTHORITY = 1 << 2, - /// @brief army vehicles - SVC_ARMY = 1 << 3, - /// @brief vip vehicles - SVC_VIP = 1 << 4, - //@} - - - /// @name vehicle size - //@{ - /// @brief pedestrian - SVC_PEDESTRIAN = 1 << 5, - - /// @brief vehicle is a passenger car (a "normal" car) - SVC_PASSENGER = 1 << 6, - /// @brief vehicle is a HOV - SVC_HOV = 1 << 7, - /// @brief vehicle is a taxi - SVC_TAXI = 1 << 8, - /// @brief vehicle is a bus - SVC_BUS = 1 << 9, - /// @brief vehicle is a coach - SVC_COACH = 1 << 10, - /// @brief vehicle is a small delivery vehicle - SVC_DELIVERY = 1 << 11, - /// @brief vehicle is a large transport vehicle - SVC_TRUCK = 1 << 12, - /// @brief vehicle is a large transport vehicle - SVC_TRAILER = 1 << 13, - /// @brief vehicle is a motorcycle - SVC_MOTORCYCLE = 1 << 14, - /// @brief vehicle is a moped - SVC_MOPED = 1 << 15, - /// @brief vehicle is a bicycle - SVC_BICYCLE = 1 << 16, - /// @brief is an electric vehicle - SVC_E_VEHICLE = 1 << 17, - - /// @brief vehicle is a light rail - SVC_TRAM = 1 << 18, - /// @brief vehicle is a city rail - SVC_RAIL_URBAN = 1 << 19, - /// @brief vehicle is a not electrified rail - SVC_RAIL = 1 << 20, - /// @brief rail vehicle that requires electrified tracks - SVC_RAIL_ELECTRIC = 1 << 21, - /// @brief vehicle that is allowed to drive on high-speed rail tracks - SVC_RAIL_FAST = 1 << 22, - - /// @brief is an arbitrary ship - SVC_SHIP = 1 << 23, - - /// @brief is a user-defined type - SVC_CUSTOM1 = 1 << 24, - /// @brief is a user-defined type - SVC_CUSTOM2 = 1 << 25, - //@} - - /// @brief classes which drive on tracks - SVC_RAIL_CLASSES = SVC_RAIL_ELECTRIC | SVC_RAIL_FAST | SVC_RAIL | SVC_RAIL_URBAN | SVC_TRAM, - /// @brief classes which drive on roads - SVC_ROAD_CLASSES = (SVC_PEDESTRIAN | SVC_PASSENGER | SVC_HOV | SVC_TAXI | SVC_BUS | SVC_COACH | SVC_DELIVERY - | SVC_TRUCK | SVC_TRAILER | SVC_MOTORCYCLE | SVC_MOPED | SVC_BICYCLE | SVC_E_VEHICLE), - /// @brief classes which (normally) do not drive on normal roads - SVC_NON_ROAD = SVC_RAIL_CLASSES | SVC_SHIP -}; - -extern const SUMOVehicleClass SUMOVehicleClass_MAX; -extern StringBijection SumoVehicleClassStrings; -extern std::set deprecatedVehicleClassesSeen; -extern StringBijection SumoVehicleShapeStrings; - -/// @brief bitset where each bit declares whether a certain SVC may use this edge/lane -typedef int SVCPermissions; - -/// @brief all VClasses are allowed -extern const SVCPermissions SVCAll; - -/// @brief permissions not specified -extern const SVCPermissions SVC_UNSPECIFIED; - -/** - * @enum SUMOEmissionClass - * @brief Definition of vehicle emission classes - * @see PollutantsInterface - */ -typedef int SUMOEmissionClass; - - -// =========================================================================== -// method declarations -// =========================================================================== - -// --------------------------------------------------------------------------- -// abstract vehicle class / purpose -// --------------------------------------------------------------------------- -/** @brief Returns the ids of the given classes, divided using a ' ' - * @param[in] the permissions to encode - * @param[in] expand whether 'all' should be used - * @return The string representation of these classes - */ -extern const std::string& getVehicleClassNames(SVCPermissions permissions, bool expand = false); - -/** @brief Returns the ids of the given classes, divided using a ' ' - * @param[in] the permissions to encode - * @return The string representation of these classes as a vector - */ -extern const std::vector& getVehicleClassNamesList(SVCPermissions permissions); - -/** @brief Returns the class id of the abstract class given by its name - * @param[in] name The name of the abstract vehicle class - * @return The internal representation of this class. Name must not be a - * compound name - */ -extern SUMOVehicleClass getVehicleClassID(const std::string& name); - -/** @brief Returns the OR'ed id of the compound class given by its name - * @param[in] name The name of the abstract vehicle class - * @return The OR'ed combination of base enum values - */ -extern int getVehicleClassCompoundID(const std::string& name); - -/** @brief Parses the given definition of allowed vehicle classes into the given containers - * Deprecated classes go into a separate container. - * - * @param[in] classNames Space separated class names - * @param[out] container The set of vehicle classes to fill - * throws ProcessError if parsing fails - */ -extern SVCPermissions parseVehicleClasses(const std::string& allowedS); - -/// @brief Checks whether the given string contains only known vehicle classes -extern bool canParseVehicleClasses(const std::string& classes); - -/** @brief Encodes the given vector of allowed and disallowed classes into a bitset - * @param[in] allowedS Definition which classes are allowed - * @param[in] disallowedS Definition which classes are not allowed - */ -extern SVCPermissions parseVehicleClasses(const std::string& allowedS, const std::string& disallowedS, double networkVersion = NETWORK_VERSION); - -/** @brief Encodes the given vector of allowed classs into a bitset - * Unlike the methods which parse a string it gives immediately a warning output on deprecated vehicle classes. - * @param[in] classesS The names vector to parse - */ -extern SVCPermissions parseVehicleClasses(const std::vector& allowedS); - -/// @brief negate the given permissions and ensure that only relevant bits are set -extern SVCPermissions invertPermissions(SVCPermissions permissions); - -/// @brief writes allowed disallowed attributes if needed; -extern void writePermissions(OutputDevice& into, SVCPermissions permissions); - -/// @brief writes allowed disallowed attributes if needed; -extern void writePreferences(OutputDevice& into, SVCPermissions preferred); - -/// @brief Extract stopOffsets from attributes of stopOffset element -extern std::map parseStopOffsets(const SUMOSAXAttributes& attrs, bool& ok); - -// --------------------------------------------------------------------------- -// vehicle shape class -// --------------------------------------------------------------------------- -/** @brief Returns the class name of the shape class given by its id - * @param[in] id The id of the shape class - * @return The string representation of this class - */ -extern std::string getVehicleShapeName(SUMOVehicleShape id); - -/** @brief Returns the class id of the shape class given by its name - * @param[in] name The name of the shape class - * @return The internal representation of this class - */ -extern SUMOVehicleShape getVehicleShapeID(const std::string& name); - -/// @brief Checks whether the given string contains only known vehicle shape -extern bool canParseVehicleShape(const std::string& shape); - -/** @brief Returns whether an edge with the given permission is a railway edge - * @param[in] permissions The permissions of the edge - * @return Whether the edge is a railway edge - */ -extern bool isRailway(SVCPermissions permissions); - -/** @brief Returns whether an edge with the given permission is a waterway edge - * @param[in] permissions The permissions of the edge - * @return Whether the edge is a waterway edge - */ -extern bool isWaterway(SVCPermissions permissions); - -/** @brief Returns whether an edge with the given permission is a forbidden edge - * @param[in] permissions The permissions of the edge - * @return Whether the edge is forbidden - */ -extern bool isForbidden(SVCPermissions permissions); - -/** @brief Returns whether an edge with the given permission is a sidewalk - * @param[in] permissions The permissions of the edge - * @return Whether the edge is a sidewalk - */ -extern bool isSidewalk(SVCPermissions permissions); - -/** @brief Returns whether an edge with the given permission forbids vehicles - * @param[in] permissions The permissions of the edge - * @return Whether the edge is forbidden for vehicles - */ -extern bool noVehicles(SVCPermissions permissions); - -/** @brief Returns the default vehicle length - * This put into a function so it can be used by NBVehicle - * @param[in] vc the vehicle class - * @return the default length in m - */ -extern double getDefaultVehicleLength(const SUMOVehicleClass vc = SVC_IGNORING); - -// --------------------------------------------------------------------------- -// default vehicle type parameter -// --------------------------------------------------------------------------- -extern const std::string DEFAULT_VTYPE_ID; -extern const std::string DEFAULT_PEDTYPE_ID; -extern const std::string DEFAULT_BIKETYPE_ID; -extern const std::string DEFAULT_CONTAINERTYPE_ID; -extern const std::string DEFAULT_TAXITYPE_ID; - -extern const double DEFAULT_VEH_PROB; // !!! does this belong here? - -extern const double DEFAULT_PEDESTRIAN_SPEED; - -extern const double DEFAULT_CONTAINER_TRANSHIP_SPEED; diff --git a/Util/OSM2ODR/src/utils/common/StaticCommand.h b/Util/OSM2ODR/src/utils/common/StaticCommand.h deleted file mode 100644 index ea803d05f..000000000 --- a/Util/OSM2ODR/src/utils/common/StaticCommand.h +++ /dev/null @@ -1,100 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file StaticCommand.h -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Wed, 13.02.2008 -/// -// A wrapper for a Command function -/****************************************************************************/ -#pragma once -#include "Command.h" - - -// =========================================================================== -// class definition -// =========================================================================== -/** - * @class StaticCommand - * @brief A wrapper for a Command function - * - * @see Design Patterns, Gamma et al. - * @see Command - * @see MSEventControl - */ -template< class T > -class StaticCommand : public Command { -public: - /// @brief Type of the function to execute. - typedef SUMOTime(*Operation)(SUMOTime); - - -public: - /** - * @brief Constructor. - * - * @param[in] receiver Pointer to object of type T that will receive a call to one of it's methods. - * @param[in] operation The objects' method that will be called on execute() - */ - StaticCommand(Operation operation) - : myOperation(operation), myAmDescheduledByParent(false) {} - - - /// @brief Destructor - ~StaticCommand() {} - - - /** @brief Marks this Command as being descheduled - * - * A simple boolean marker ("myAmDescheduledByParent") is set which - * prevents this command from being executed. - */ - void deschedule() { - myAmDescheduledByParent = true; - } - - - - /// @name Derived from Command - /// @{ - - /** @brief Executes the command. - * - * If the command is not descheduled, the stored method of the stored instance - * is called. - * - * @param[in] currentTime The current simulation time - * @return The time after which the command shall be executed again, 0 if this command shall be descheduled. - * @exception ProcessError Derived actions may throw this exception - */ - SUMOTime execute(SUMOTime currentTime) { - // do not execute if the command was descheduled - if (myAmDescheduledByParent) { - return 0; - } - // execute if stil valid - return (*myOperation)(currentTime); - } - /// @} - - -private: - /// @brief The object's operation to perform. - Operation myOperation; - - /// @brief Whether this command was descheduled (is invalid) and shall not be executed - bool myAmDescheduledByParent; - - -}; diff --git a/Util/OSM2ODR/src/utils/common/StdDefs.cpp b/Util/OSM2ODR/src/utils/common/StdDefs.cpp deleted file mode 100644 index a2ce2c17a..000000000 --- a/Util/OSM2ODR/src/utils/common/StdDefs.cpp +++ /dev/null @@ -1,47 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2014-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file StdDefs.cpp -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @author Laura Bieker -/// @date 2014-01-07 -/// -/****************************************************************************/ -#include "StdDefs.h" - - -// set by option --precision (see SystemFrame.cpp) -int gPrecision = 2; -int gPrecisionGeo = 6; -bool gHumanReadableTime = false; -bool gSimulation = false; -double gWeightsRandomFactor = 1; - -bool gDebugFlag1 = false; -bool gDebugFlag2 = false; -bool gDebugFlag3 = false; -bool gDebugFlag4 = false; - -double truncate(double x, int fractionBits) { - return ceil(x * (1 << fractionBits)) / (1 << fractionBits); -} - -double roundBits(double x, int fractionBits) { - const double x2 = x * (1 << fractionBits); - const double rounded = x2 < 0 ? ceil(x2 - 0.5) : floor(x2 + 0.5); - return rounded / (1 << fractionBits); -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/utils/common/StdDefs.h b/Util/OSM2ODR/src/utils/common/StdDefs.h deleted file mode 100644 index 8a3a70d63..000000000 --- a/Util/OSM2ODR/src/utils/common/StdDefs.h +++ /dev/null @@ -1,141 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2005-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file StdDefs.h -/// @author Daniel Krajzewicz -/// @author Laura Bieker -/// @author Michael Behrisch -/// @author Jakob Erdmann -/// @date Fri, 29.04.2005 -/// -// -/****************************************************************************/ -#pragma once -#include -#include -#include - -/* avoiding compiler warning unreferenced parameter */ -#define UNUSED_PARAMETER(x) ((void)(x)) - -#ifdef _MSC_VER -#define FALLTHROUGH /* do nothing */ -#elif __GNUC__ < 7 -#define FALLTHROUGH /* do nothing */ -#else -#define FALLTHROUGH __attribute__((fallthrough)) -#endif - -/// @brief the maximum number of connections across an intersection -#define SUMO_MAX_CONNECTIONS 256 - -class RGBColor; - -/* ------------------------------------------------------------------------- - * some constant defaults used by SUMO - * ----------------------------------------------------------------------- */ -const double SUMO_const_laneWidth = (double) 3.2; -const double SUMO_const_laneOffset = (double) 0; -const double SUMO_const_halfLaneWidth = SUMO_const_laneWidth / 2; -const double SUMO_const_quarterLaneWidth = SUMO_const_laneWidth / 4; -const double SUMO_const_laneWidthAndOffset = SUMO_const_laneWidth + SUMO_const_laneOffset; -const double SUMO_const_halfLaneAndOffset = SUMO_const_halfLaneWidth + SUMO_const_laneOffset; -const double SUMO_const_laneMarkWidth = (double) 0.1; -const double SUMO_const_waitingPersonWidth = 0.8; -const double SUMO_const_waitingPersonDepth = 0.67; -const double SUMO_const_waitingContainerWidth = 2.4; -const double SUMO_const_waitingContainerDepth = 6.1; - -/// @brief the speed threshold at which vehicles are considered as halting -const double SUMO_const_haltingSpeed = (double) 0.1; - -const double INVALID_DOUBLE = std::numeric_limits::max(); - -/// @brief version for written networks and default version for loading -const double NETWORK_VERSION = 1.6; - - -/* ------------------------------------------------------------------------- - * templates for mathematical functions missing in some c++-implementations - * ----------------------------------------------------------------------- */ -template -inline T -MIN2(T a, T b) { - return a < b ? a : b; -} - -template -inline T -MAX2(T a, T b) { - return a > b ? a : b; -} - - -template -inline T -MIN3(T a, T b, T c) { - return MIN2(c, a < b ? a : b); -} - - -template -inline T -MAX3(T a, T b, T c) { - return MAX2(c, a > b ? a : b); -} - - -template -inline T -MIN4(T a, T b, T c, T d) { - return MIN2(MIN2(a, b), MIN2(c, d)); -} - - -template -inline T -MAX4(T a, T b, T c, T d) { - return MAX2(MAX2(a, b), MAX2(c, d)); -} - - -template -inline T -ISNAN(T a) { - volatile T d = a; - return d != d; -} - - -/// the precision for floating point outputs -extern int gPrecision; -extern int gPrecisionGeo; // for lon,lat -extern bool gHumanReadableTime; -extern bool gSimulation; // whether the current application is sumo or sumo-gui (as opposed to a router) -extern double gWeightsRandomFactor; // randomization for edge weights - - -/// @brief global utility flags for debugging -extern bool gDebugFlag1; -extern bool gDebugFlag2; -extern bool gDebugFlag3; -extern bool gDebugFlag4; - -// synchronized output to stdout with << (i.e. DEBUGOUT(SIMTIME << " var=" << var << "\n") -#define DEBUGOUT(msg) {std::ostringstream oss; oss << msg; std::cout << oss.str();} - -/// @brief discrds mantissa bits beyond the given number -double truncate(double x, int fractionBits); - -/// @brief round to the given number of mantissa bits beyond the given number -double roundBits(double x, int fractionBits); diff --git a/Util/OSM2ODR/src/utils/common/StringBijection.h b/Util/OSM2ODR/src/utils/common/StringBijection.h deleted file mode 100644 index f46edba89..000000000 --- a/Util/OSM2ODR/src/utils/common/StringBijection.h +++ /dev/null @@ -1,150 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2011-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file StringBijection.h -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @author Jakob Erdmann -/// @date Mar 2011 -/// -// Bidirectional map between string and something else -/****************************************************************************/ -#pragma once -#include -#include -#include -#include -#include - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * Template container for maintaining a bidirectional map between strings and something else - * It is not always a bijection since it allows for duplicate entries on both sides if either - * checkDuplicates is set to false in the constructor or the insert function or if - * the addAlias function is used. - */ - -template< class T > -class StringBijection { - -public: - -#ifdef _MSC_VER -#pragma warning(push) -#pragma warning(disable:4510 4512 4610) // no default constructor and no assignment operator; conflicts with initializer -#endif - struct Entry { - const char* str; - const T key; - }; -#ifdef _MSC_VER -#pragma warning(pop) -#endif - - - StringBijection() {} - - - StringBijection(Entry entries[], T terminatorKey, bool checkDuplicates = true) { - int i = 0; - do { - insert(entries[i].str, entries[i].key, checkDuplicates); - } while (entries[i++].key != terminatorKey); - } - - - void insert(const std::string str, const T key, bool checkDuplicates = true) { - if (checkDuplicates) { - if (has(key)) { - // cannot use toString(key) because that might create an infinite loop - throw InvalidArgument("Duplicate key."); - } - if (hasString(str)) { - throw InvalidArgument("Duplicate string '" + str + "'."); - } - } - myString2T[str] = key; - myT2String[key] = str; - } - - - void addAlias(const std::string str, const T key) { - myString2T[str] = key; - } - - - void remove(const std::string str, const T key) { - myString2T.erase(str); - myT2String.erase(key); - } - - - T get(const std::string& str) const { - if (hasString(str)) { - return myString2T.find(str)->second; - } else { - throw InvalidArgument("String '" + str + "' not found."); - } - } - - - const std::string& getString(const T key) const { - if (has(key)) { - return myT2String.find(key)->second; - } else { - // cannot use toString(key) because that might create an infinite loop - throw InvalidArgument("Key not found."); - } - } - - - bool hasString(const std::string& str) const { - return myString2T.count(str) != 0; - } - - - bool has(const T key) const { - return myT2String.count(key) != 0; - } - - - int size() const { - return (int)myString2T.size(); - } - - - std::vector getStrings() const { - std::vector result; - typename std::map::const_iterator it; // learn something new every day - for (it = myT2String.begin(); it != myT2String.end(); it++) { - result.push_back(it->second); - } - return result; - } - - - void addKeysInto(std::vector& list) const { - typename std::map::const_iterator it; // learn something new every day - for (it = myT2String.begin(); it != myT2String.end(); it++) { - list.push_back(it->first); - } - } - - -private: - std::map myString2T; - std::map myT2String; - -}; diff --git a/Util/OSM2ODR/src/utils/common/StringTokenizer.cpp b/Util/OSM2ODR/src/utils/common/StringTokenizer.cpp deleted file mode 100644 index 1af61c70d..000000000 --- a/Util/OSM2ODR/src/utils/common/StringTokenizer.cpp +++ /dev/null @@ -1,201 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file StringTokenizer.cpp -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date ? -/// -// A java-style StringTokenizer for c++ (stl) -/****************************************************************************/ -#include - -#include -#include -#include // !!! debug only - -#include "UtilExceptions.h" -#include "StringTokenizer.h" - - -// =========================================================================== -// variable definitions -// =========================================================================== -const int StringTokenizer::NEWLINE = -256; -const int StringTokenizer::WHITECHARS = -257; -const int StringTokenizer::SPACE = 32; -const int StringTokenizer::TAB = 9; - - -// =========================================================================== -// method definitions -// =========================================================================== - -StringTokenizer::StringTokenizer() : - myPos(0) { -} - - -StringTokenizer::StringTokenizer(std::string tosplit) : - myTosplit(tosplit), myPos(0) { - prepareWhitechar(tosplit); -} - - -StringTokenizer::StringTokenizer(std::string tosplit, std::string token, bool splitAtAllChars) : - myTosplit(tosplit), myPos(0) { - prepare(tosplit, token, splitAtAllChars); -} - - -StringTokenizer::StringTokenizer(std::string tosplit, int special) : - myTosplit(tosplit), myPos(0) { - switch (special) { - case NEWLINE: - prepare(tosplit, "\r\n", true); - break; - case TAB: - prepare(tosplit, "\t", true); - break; - case WHITECHARS: - prepareWhitechar(tosplit); - break; - default: - char* buf = new char[2]; - buf[0] = (char) special; - buf[1] = 0; - prepare(tosplit, buf, false); - delete[] buf; - break; - } -} - - -StringTokenizer::~StringTokenizer() {} - - -void StringTokenizer::reinit() { - myPos = 0; -} - - -bool StringTokenizer::hasNext() { - return myPos != (int)myStarts.size(); -} - - -std::string StringTokenizer::next() { - if (myPos >= (int)myStarts.size()) { - throw OutOfBoundsException(); - } - if (myLengths[myPos] == 0) { - myPos++; - return ""; - } - int start = myStarts[myPos]; - int length = myLengths[myPos++]; - return myTosplit.substr(start, length); -} - - -std::string StringTokenizer::front() { - if (myStarts.size() == 0) { - throw OutOfBoundsException(); - } - if (myLengths[0] == 0) { - return ""; - } - return myTosplit.substr(myStarts[0], myLengths[0]); -} - - -std::string StringTokenizer::get(int pos) const { - if (pos >= (int)myStarts.size()) { - throw OutOfBoundsException(); - } - if (myLengths[pos] == 0) { - return ""; - } - int start = myStarts[pos]; - int length = myLengths[pos]; - return myTosplit.substr(start, length); -} - - -int StringTokenizer::size() const { - return (int)myStarts.size(); -} - - -void StringTokenizer::prepare(const std::string& tosplit, const std::string& token, bool splitAtAllChars) { - int beg = 0; - int len = (int)token.length(); - if (splitAtAllChars) { - len = 1; - } - while (beg < (int)tosplit.length()) { - std::string::size_type end; - if (splitAtAllChars) { - end = tosplit.find_first_of(token, beg); - } else { - end = tosplit.find(token, beg); - } - if (end == std::string::npos) { - end = tosplit.length(); - } - myStarts.push_back(beg); - myLengths.push_back((int)end - beg); - beg = (int)end + len; - if (beg == (int)tosplit.length()) { - myStarts.push_back(beg - 1); - myLengths.push_back(0); - } - } -} - - -void StringTokenizer::prepareWhitechar(const std::string& tosplit) { - std::string::size_type len = tosplit.length(); - std::string::size_type beg = 0; - while (beg < len && tosplit[beg] <= SPACE) { - beg++; - } - while (beg != std::string::npos && beg < len) { - std::string::size_type end = beg; - while (end < len && tosplit[end] > SPACE) { - end++; - } - myStarts.push_back((int)beg); - myLengths.push_back((int)end - (int)beg); - beg = end; - while (beg < len && tosplit[beg] <= SPACE) { - beg++; - } - } -} - - -std::vector -StringTokenizer::getVector() { - std::vector ret; - ret.reserve(size()); - while (hasNext()) { - ret.push_back(next()); - } - reinit(); - return ret; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/utils/common/StringTokenizer.h b/Util/OSM2ODR/src/utils/common/StringTokenizer.h deleted file mode 100644 index 422e53a10..000000000 --- a/Util/OSM2ODR/src/utils/common/StringTokenizer.h +++ /dev/null @@ -1,146 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file StringTokenizer.h -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date ? -/// -// A java-style StringTokenizer for c++ (stl) -/****************************************************************************/ -#pragma once -#include -#include - -/** - * StringTokenizer - * A class similar to the StringTokenizer from Java. It splits a string at - * the given string or character (or one of the special cases NEWLINE or - * WHITECHAR) and allows to iterate over the so generated substrings. - * - * The normal usage is like this: - *
- * StringTokenizer st(CString("This is a line"), ' ');
- * while(st.hasNext())
- *    cout << st.next() << endl;
- * 
- * This would generate the output: - *
- * This
- * is
- * a
- * line
- * 
- * - * There is something to know about the behaviour: - * When using WHITECHAR, a list of whitechars occuring in the string to - * split is regarded as a single divider. All other parameter will use - * multiple occurences of operators as a list of single divider and the - * string between them will have a length of zero. - */ -// =========================================================================== -// class definitions -// =========================================================================== -/** - * - */ -class StringTokenizer { -public: - /// @brief identifier for splitting the given string at all newline characters - static const int NEWLINE; - - /// @brief identifier for splitting the given string at all whitespace characters - static const int WHITECHARS; - - /// @brief the ascii index of the highest whitespace character - static const int SPACE; - - /// @brief the ascii index of the tab character - static const int TAB; - -public: - /// @brief default constructor - StringTokenizer(); - - /**@brief constructor - * @param tosplit is the string to split into substrings. If the string between two split positions is empty, it will not be returned. - * @note same as StringTokenizer(tosplit, StringTokenizer.WHITECHARS) - */ - StringTokenizer(std::string tosplit); - - /**@brief constructor - * @note the first string will be split at the second string's occurences. - If the optional third parameter is true, the string will be split whenever - a char from the second string occurs. If the string between two split - positions is empty, it will nevertheless be returned. - */ - StringTokenizer(std::string tosplit, std::string token, bool splitAtAllChars = false); - - /**@brief constructor - * @note When StringTokenizer.NEWLINE is used as second parameter, the string - will be split at all occurences of a newline character (0x0d / 0x0a) - When StringTokenizer.WHITECHARS is used as second parameter, the - string will be split at all characters below 0x20 (SPACE) - All other ints specified as second parameter are casted int o a char - at which the string will be splitted. - */ - StringTokenizer(std::string tosplit, int special); - - /// @brief destructor - ~StringTokenizer(); - - /// @brief reinitialises the internal iterator - void reinit(); - - /// @brief returns the information whether further substrings exist - bool hasNext(); - - /// @brief returns the next substring when it exists. Otherwise the behaviour is undefined - std::string next(); - - /// @brief returns the number of existing substrings - int size() const; - - /// @brief returns the first substring without moving the iterator - std::string front(); - - /// @brief returns the item at the given position - std::string get(int pos) const; - - /// @brief return vector of strings - std::vector getVector(); - -private: - /// @brief splits the first string at all occurences of the second. If the third parameter is true split at all chars given in the second - void prepare(const std::string& tosplit, const std::string& token, bool splitAtAllChars); - - /// @brief @brief splits the first string at all occurences of whitechars - void prepareWhitechar(const std::string& tosplit); - -private: - /// @brief a list of positions/lengths - typedef std::vector SizeVector; - - /// @brief the string to split - std::string myTosplit; - - /// @brief the current position in the list of substrings - int myPos; - - /// @brief the list of substring starts - SizeVector myStarts; - - /// @brief the list of substring lengths - SizeVector myLengths; -}; diff --git a/Util/OSM2ODR/src/utils/common/StringUtils.cpp b/Util/OSM2ODR/src/utils/common/StringUtils.cpp deleted file mode 100644 index 41b95f0fe..000000000 --- a/Util/OSM2ODR/src/utils/common/StringUtils.cpp +++ /dev/null @@ -1,412 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file StringUtils.cpp -/// @author Daniel Krajzewicz -/// @author Laura Bieker -/// @author Michael Behrisch -/// @author Robert Hilbrich -/// @date unknown -/// -// Some static methods for string processing -/****************************************************************************/ -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "StringUtils.h" - - -// =========================================================================== -// static member definitions -// =========================================================================== -std::string StringUtils::emptyString; - - -// =========================================================================== -// method definitions -// =========================================================================== -std::string -StringUtils::prune(const std::string& str) { - const std::string::size_type endpos = str.find_last_not_of(" \t\n\r"); - if (std::string::npos != endpos) { - const int startpos = (int)str.find_first_not_of(" \t\n\r"); - return str.substr(startpos, endpos - startpos + 1); - } - return ""; -} - - -std::string -StringUtils::to_lower_case(std::string str) { - for (int i = 0; i < (int)str.length(); i++) { - if (str[i] >= 'A' && str[i] <= 'Z') { - str[i] = str[i] + 'a' - 'A'; - } - } - return str; -} - - -std::string -StringUtils::latin1_to_utf8(std::string str) { - // inspired by http://stackoverflow.com/questions/4059775/convert-iso-8859-1-strings-to-utf-8-in-c-c - std::string result; - for (int i = 0; i < (int)str.length(); i++) { - const unsigned char c = str[i]; - if (c < 128) { - result += c; - } else { - result += (char)(0xc2 + (c > 0xbf)); - result += (char)((c & 0x3f) + 0x80); - } - } - return result; -} - - -std::string -StringUtils::convertUmlaute(std::string str) { - str = replace(str, "\xE4", "ae"); - str = replace(str, "\xC4", "Ae"); - str = replace(str, "\xF6", "oe"); - str = replace(str, "\xD6", "Oe"); - str = replace(str, "\xFC", "ue"); - str = replace(str, "\xDC", "Ue"); - str = replace(str, "\xDF", "ss"); - str = replace(str, "\xC9", "E"); - str = replace(str, "\xE9", "e"); - str = replace(str, "\xC8", "E"); - str = replace(str, "\xE8", "e"); - return str; -} - - - -std::string -StringUtils::replace(std::string str, const char* what, - const char* by) { - const std::string what_tmp(what); - const std::string by_tmp(by); - std::string::size_type idx = str.find(what); - const int what_len = (int)what_tmp.length(); - if (what_len > 0) { - const int by_len = (int)by_tmp.length(); - while (idx != std::string::npos) { - str = str.replace(idx, what_len, by); - idx = str.find(what, idx + by_len); - } - } - return str; -} - - -std::string StringUtils::substituteEnvironment(std::string str) { - // Expression for an environment variables, e.g. ${NAME} - // Note: - R"(...)" is a raw string literal syntax to simplify a regex declaration - // - .+? looks for the shortest match (non-greedy) - // - (.+?) defines a "subgroup" which is already stripped of the $ and {, } - std::regex envVarExpr(R"(\$\{(.+?)\})"); - - // Are there any variables in this string? - std::smatch match; - std::string strIter = str; - - // Loop over the entire value string and look for variable names - while (std::regex_search(strIter, match, envVarExpr)) { - std::string varName = match[1]; - - // Find the variable in the environment and its value - std::string varValue; - if (std::getenv(varName.c_str()) != nullptr) { - varValue = std::getenv(varName.c_str()); - } - - // Replace the variable placeholder with its value in the original string - str = std::regex_replace(str, std::regex("\\$\\{" + varName + "\\}"), varValue); - - // Continue the loop with the remainder of the string - strIter = match.suffix(); - } - - return str; -} - -std::string -StringUtils::toTimeString(int time) { - std::ostringstream oss; - if (time < 0) { - oss << "-"; - time = -time; - } - char buffer[10]; - sprintf(buffer, "%02i:", (time / 3600)); - oss << buffer; - time = time % 3600; - sprintf(buffer, "%02i:", (time / 60)); - oss << buffer; - time = time % 60; - sprintf(buffer, "%02i", time); - oss << buffer; - return oss.str(); -} - - -bool -StringUtils::startsWith(const std::string& str, const std::string prefix) { - return str.compare(0, prefix.length(), prefix) == 0; -} - - -bool -StringUtils::endsWith(const std::string& str, const std::string suffix) { - if (str.length() >= suffix.length()) { - return str.compare(str.length() - suffix.length(), suffix.length(), suffix) == 0; - } else { - return false; - } -} - - -std::string -StringUtils::escapeXML(const std::string& orig, const bool maskDoubleHyphen) { - std::string result = replace(orig, "&", "&"); - result = replace(result, ">", ">"); - result = replace(result, "<", "<"); - result = replace(result, "\"", """); - if (maskDoubleHyphen) { - result = replace(result, "--", "--"); - } - for (char invalid = '\1'; invalid < ' '; invalid++) { - result = replace(result, std::string(1, invalid).c_str(), ""); - } - return replace(result, "'", "'"); -} - - -std::string -StringUtils::urlEncode(const std::string& toEncode, const std::string encodeWhich) { - std::ostringstream out; - - for (int i = 0; i < (int)toEncode.length(); ++i) { - const char t = toEncode.at(i); - - if ((encodeWhich != "" && encodeWhich.find(t) == std::string::npos) || - (encodeWhich == "" && - ((t >= 45 && t <= 57) || // hyphen, period, slash, 0-9 - (t >= 65 && t <= 90) || // A-Z - t == 95 || // underscore - (t >= 97 && t <= 122) || // a-z - t == 126)) // tilde - ) { - out << toEncode.at(i); - } else { - out << charToHex(toEncode.at(i)); - } - } - - return out.str(); -} - - -std::string -StringUtils::urlDecode(const std::string& toDecode) { - std::ostringstream out; - - for (int i = 0; i < (int)toDecode.length(); ++i) { - if (toDecode.at(i) == '%') { - std::string str(toDecode.substr(i + 1, 2)); - out << hexToChar(str); - i += 2; - } else { - out << toDecode.at(i); - } - } - - return out.str(); -} - -std::string -StringUtils::charToHex(unsigned char c) { - short i = c; - - std::stringstream s; - - s << "%" << std::setw(2) << std::setfill('0') << std::hex << i; - - return s.str(); -} - - -unsigned char -StringUtils::hexToChar(const std::string& str) { - short c = 0; - if (!str.empty()) { - std::istringstream in(str); - in >> std::hex >> c; - if (in.fail()) { - throw NumberFormatException(str + " could not be interpreted as hex"); - } - } - return static_cast(c); -} - - -int -StringUtils::toInt(const std::string& sData) { - long long int result = toLong(sData); - if (result > std::numeric_limits::max() || result < std::numeric_limits::min()) { - throw NumberFormatException(toString(result) + " int overflow"); - } - return (int)result; -} - - -int -StringUtils::toIntSecure(const std::string& sData, int def) { - if (sData.length() == 0) { - return def; - } - return toInt(sData); -} - - -long long int -StringUtils::toLong(const std::string& sData) { - const char* const data = sData.c_str(); - if (data == 0 || data[0] == 0) { - throw EmptyData(); - } - char* end; - errno = 0; -#ifdef WIN32 - long long int ret = _strtoi64(data, &end, 10); -#else - long long int ret = strtoll(data, &end, 10); -#endif - if (errno == ERANGE) { - errno = 0; - throw NumberFormatException("(long long integer range) " + sData); - } - if ((int)(end - data) != (int)strlen(data)) { - throw NumberFormatException("(long long integer format) " + sData); - } - return ret; -} - - -int -StringUtils::hexToInt(const std::string& sData) { - if (sData.length() == 0) { - throw EmptyData(); - } - size_t idx = 0; - int result; - try { - if (sData[0] == '#') { // for html color codes - result = std::stoi(sData.substr(1), &idx, 16); - idx++; - } else { - result = std::stoi(sData, &idx, 16); - } - } catch (...) { - throw NumberFormatException("(hex integer format) " + sData); - } - if (idx != sData.length()) { - throw NumberFormatException("(hex integer format) " + sData); - } - return result; -} - - -double -StringUtils::toDouble(const std::string& sData) { - if (sData.size() == 0) { - throw EmptyData(); - } - try { - size_t idx = 0; - const double result = std::stod(sData, &idx); - if (idx != sData.size()) { - throw NumberFormatException("(double format) " + sData); - } else { - return result; - } - } catch (...) { - // invalid_argument or out_of_range - throw NumberFormatException("(double) " + sData); - } -} - - -double -StringUtils::toDoubleSecure(const std::string& sData, const double def) { - if (sData.length() == 0) { - return def; - } - return toDouble(sData); -} - - -bool -StringUtils::toBool(const std::string& sData) { - if (sData.length() == 0) { - throw EmptyData(); - } - std::string s = sData; - // Don't use std::transform(..., ::tolower) due a C4244 Warning in MSVC17 - for (int i = 0; i < (int)s.length(); i++) { - s[i] = (char)::tolower((char)s[i]); - } - if (s == "1" || s == "yes" || s == "true" || s == "on" || s == "x" || s == "t") { - return true; - } else if (s == "0" || s == "no" || s == "false" || s == "off" || s == "-" || s == "f") { - return false; - } else { - throw BoolFormatException(s); - } -} - - -std::string -StringUtils::transcode(const XMLCh* const data, int length) { - if (data == 0) { - throw EmptyData(); - } - if (length == 0) { - return ""; - } -#if _XERCES_VERSION < 30100 - char* t = XERCES_CPP_NAMESPACE::XMLString::transcode(data); - std::string result(t); - XERCES_CPP_NAMESPACE::XMLString::release(&t); - return result; -#else - try { - XERCES_CPP_NAMESPACE::TranscodeToStr utf8(data, "UTF-8"); - return reinterpret_cast(utf8.str()); - } catch (XERCES_CPP_NAMESPACE::TranscodingException&) { - return "?"; - } -#endif -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/utils/common/StringUtils.h b/Util/OSM2ODR/src/utils/common/StringUtils.h deleted file mode 100644 index 89830dc1e..000000000 --- a/Util/OSM2ODR/src/utils/common/StringUtils.h +++ /dev/null @@ -1,141 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file StringUtils.h -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @author Robert Hilbrich -/// @date unknown -/// -// Some static methods for string processing -/****************************************************************************/ -#pragma once -#include -#include -#include - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class StringUtils - * @brief Some static methods for string processing - */ -class StringUtils { -public: - /// Removes trailing and leading whitechars - static std::string prune(const std::string& str); - - /// Transfers the content to lower case - static std::string to_lower_case(std::string str); - - /// Transfers from Latin 1 (ISO-8859-1) to UTF-8 - static std::string latin1_to_utf8(std::string str); - - /// Converts german "Umlaute" to their latin-version - static std::string convertUmlaute(std::string str); - - /** Replaces all occurences of the second string by the third - string within the first string */ - static std::string replace(std::string str, const char* what, - const char* by); - - /** Replaces an environment variable with its value (similar to bash); - syntax for a variable is ${NAME} */ - static std::string substituteEnvironment(std::string str); - - /// Builds a time string (hh:mm:ss) from the given seconds - static std::string toTimeString(int time); - - /// Checks whether a given string starts with the prefix - static bool startsWith(const std::string& str, const std::string prefix); - - /// Checks whether a given string ends with the suffix - static bool endsWith(const std::string& str, const std::string suffix); - - /** - * @brief Replaces the standard escapes by their XML entities. - * - * The strings &, <, >, ", and ' are replaced by &, <, >, ", and ' - * - * @param[in] orig The original string - * @param[in] maskDoubleHyphen Whether -- in input shall be converted to -- (semantically equivalent but allowed in XML comments) - * @return the string with the escaped sequences - */ - static std::string escapeXML(const std::string& orig, const bool maskDoubleHyphen = false); - - /// An empty string - static std::string emptyString; - - // the following methods stem from http://bogomip.net/blog/cpp-url-encoding-and-decoding/ - - static std::string urlEncode(const std::string& url, const std::string encodeWhich = ""); - static std::string urlDecode(const std::string& encoded); - - static std::string charToHex(unsigned char c); - static unsigned char hexToChar(const std::string& str); - - /**@brief converts a string into the integer value described by it by calling the char-type converter, which - * @throw an EmptyData - exception if the given string is empty - * @throw NumberFormatException - exception when the string does not contain an integer - */ - static int toInt(const std::string& sData); - - /// @brief converts a string into the integer value described by it - /// @return the default value if the data is empty - static int toIntSecure(const std::string& sData, int def); - - /**@brief converts a string into the long value described by it by calling the char-type converter, which - * @throw an EmptyData - exception if the given string is empty - * @throw NumberFormatException - exception when the string does not contain a long integer - */ - static long long int toLong(const std::string& sData); - - /**@brief converts a string with a hex value into the integer value described by it by calling the char-type converter - * @throw an EmptyData - exception if the given string is empty - * @throw a NumberFormatException - exception when the string does not contain an integer - */ - static int hexToInt(const std::string& sData); - - /**@brief converts a string into the double value described by it by calling the char-type converter - * @throw an EmptyData - exception if the given string is empty - * @throw a NumberFormatException - exception when the string does not contain a double - */ - static double toDouble(const std::string& sData); - - /// @brief converts a string into the integer value described by it - /// @return the default value if the data is empty - static double toDoubleSecure(const std::string& sData, const double def); - - /**@brief converts a string into the bool value described by it by calling the char-type converter - * @return true if the data* is one of the following (case insensitive): '1', 'x', 'true', 'yes', 'on', 't' - * @return false if the data* is one of the following (case insensitive): '0', '-', 'false', 'no', 'off', 'f' - * @throw EmptyData - exception if the given string is empty or 0 pointer - * @throw BoolFormatException in any other case - */ - static bool toBool(const std::string& sData); - - /**@brief converts a 0-terminated XMLCh* array (usually UTF-16, stemming from Xerces) into std::string in UTF-8 - * @throw an EmptyData - exception if the given pointer is 0 - */ - static inline std::string transcode(const XMLCh* const data) { - return transcode(data, (int)XERCES_CPP_NAMESPACE::XMLString::stringLen(data)); - } - - /**@brief converts a 0-terminated XMLCh* array (usually UTF-16, stemming from Xerces) into std::string in UTF-8 considering the given length - * @throw EmptyData if the given pointer is 0 - */ - static std::string transcode(const XMLCh* const data, int length); -}; diff --git a/Util/OSM2ODR/src/utils/common/SwarmDebug.h b/Util/OSM2ODR/src/utils/common/SwarmDebug.h deleted file mode 100644 index 85c5b6739..000000000 --- a/Util/OSM2ODR/src/utils/common/SwarmDebug.h +++ /dev/null @@ -1,33 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file SwarmDebug.h -/// @author Riccardo Belletti -/// @date 2014-03-21 -/// -// Used for additional optional debug messages -/****************************************************************************/ -#pragma once - - -//#ifndef ASSERT_H -//#define ASSERT_H -#include -//#endif - - -#ifndef SWARM_DEBUG -#define DBG(X) {} -#else -#define DBG(X) {X} -#endif/* DEBUG_H_ */ diff --git a/Util/OSM2ODR/src/utils/common/SysUtils.cpp b/Util/OSM2ODR/src/utils/common/SysUtils.cpp deleted file mode 100644 index 19d5a0dec..000000000 --- a/Util/OSM2ODR/src/utils/common/SysUtils.cpp +++ /dev/null @@ -1,103 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2005-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file SysUtils.cpp -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @date Tue, 29.05.2005 -/// -// A few system-specific functions -/****************************************************************************/ -#include - -#include -#include "SysUtils.h" - -#ifndef WIN32 -#include -#else -#define NOMINMAX -#include -#undef NOMINMAX -#endif - - -// =========================================================================== -// member method definitions -// =========================================================================== -long -SysUtils::getCurrentMillis() { -#ifndef WIN32 - timeval current; - gettimeofday(¤t, 0); - long nanosecs = - (long) current.tv_sec * 1000L + (long) current.tv_usec / 1000L; - return nanosecs; -#else - LARGE_INTEGER val, val2; - BOOL check = QueryPerformanceCounter(&val); - check = QueryPerformanceFrequency(&val2); - return (long)(val.QuadPart * 1000 / val2.QuadPart); -#endif -} - - -#ifdef WIN32 -long -SysUtils::getWindowsTicks() { - return (long) GetTickCount(); -} -#endif - - -unsigned long -SysUtils::runHiddenCommand(const std::string& cmd) { -#ifdef WIN32 - // code inspired by http://www.codeproject.com/Articles/2537/Running-console-applications-silently - STARTUPINFO StartupInfo; - PROCESS_INFORMATION ProcessInfo; - unsigned long rc; - - memset(&StartupInfo, 0, sizeof(StartupInfo)); - StartupInfo.cb = sizeof(STARTUPINFO); - StartupInfo.dwFlags = STARTF_USESHOWWINDOW; - StartupInfo.wShowWindow = SW_HIDE; - - // "/c" option - Do the command then terminate the command window - std::string winCmd = "CMD.exe /c " + cmd; - char* args = new char[winCmd.size() + 1]; - args[0] = 0; - strcpy(args, winCmd.c_str()); - if (!CreateProcess(nullptr, args, nullptr, nullptr, FALSE, - CREATE_NEW_CONSOLE, nullptr, nullptr, &StartupInfo, &ProcessInfo)) { - delete[] args; - return (unsigned long)GetLastError(); - } - - WaitForSingleObject(ProcessInfo.hProcess, INFINITE); - if (!GetExitCodeProcess(ProcessInfo.hProcess, &rc)) { - rc = 0; - } - - CloseHandle(ProcessInfo.hThread); - CloseHandle(ProcessInfo.hProcess); - - delete[] args; - return rc; -#else - return (unsigned long)system(cmd.c_str()); -#endif -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/utils/common/SysUtils.h b/Util/OSM2ODR/src/utils/common/SysUtils.h deleted file mode 100644 index 88fc8c13d..000000000 --- a/Util/OSM2ODR/src/utils/common/SysUtils.h +++ /dev/null @@ -1,49 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file SysUtils.h -/// @author Daniel Krajzewicz -/// @date Fri, 29.04.2005 -/// -// A few system-specific functions -/****************************************************************************/ -#pragma once -#include - -// =========================================================================== -// class definitions -// =========================================================================== -/** @class SysUtils - * @brief A few system-specific functions - */ -class SysUtils { -public: - /** @brief Returns the current time in milliseconds - * @return Current time - */ - static long getCurrentMillis(); - - -#ifdef WIN32 - /** @brief Returns the CPU ticks (windows only) - * - * Used for random number initialisation, linux version - * uses a different method - */ - static long getWindowsTicks(); -#endif - - - /// @brief run a shell command without popping up any windows (particuarly on win32) - static unsigned long runHiddenCommand(const std::string& cmd); -}; diff --git a/Util/OSM2ODR/src/utils/common/SystemFrame.cpp b/Util/OSM2ODR/src/utils/common/SystemFrame.cpp deleted file mode 100644 index 89500f36c..000000000 --- a/Util/OSM2ODR/src/utils/common/SystemFrame.cpp +++ /dev/null @@ -1,146 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file SystemFrame.cpp -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date Mon, 23.06.2003 -/// -// A set of actions common to all applications -/****************************************************************************/ -#include - -#include "SystemFrame.h" -#include -#include -#include -#include -#include -#include -#include "RandHelper.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -void -SystemFrame::addConfigurationOptions(OptionsCont& oc) { - oc.addOptionSubTopic("Configuration"); - - oc.doRegister("configuration-file", 'c', new Option_FileName()); - oc.addSynonyme("configuration-file", "configuration"); - oc.addDescription("configuration-file", "Configuration", "Loads the named config on startup"); - oc.addXMLDefault("configuration-file"); - - oc.doRegister("save-configuration", 'C', new Option_FileName()); - oc.addSynonyme("save-config", "save-configuration"); - oc.addDescription("save-configuration", "Configuration", "Saves current configuration into FILE"); - - oc.doRegister("save-template", new Option_FileName()); - oc.addDescription("save-template", "Configuration", "Saves a configuration template (empty) into FILE"); - - oc.doRegister("save-schema", new Option_FileName()); - oc.addDescription("save-schema", "Configuration", "Saves the configuration schema into FILE"); - - oc.doRegister("save-commented", new Option_Bool(false)); - oc.addSynonyme("save-commented", "save-template.commented"); - oc.addDescription("save-commented", "Configuration", "Adds comments to saved template, configuration, or schema"); -} - - -void -SystemFrame::addReportOptions(OptionsCont& oc) { - oc.addOptionSubTopic("Report"); - - oc.doRegister("verbose", 'v', new Option_Bool(false)); - oc.addDescription("verbose", "Report", "Switches to verbose output"); - - oc.doRegister("print-options", new Option_Bool(false)); - oc.addDescription("print-options", "Report", "Prints option values before processing"); - - oc.doRegister("help", '?', new Option_BoolExtended(false)); - oc.addDescription("help", "Report", "Prints this screen or selected topics"); - - oc.doRegister("version", 'V', new Option_Bool(false)); - oc.addDescription("version", "Report", "Prints the current version"); - - oc.doRegister("xml-validation", 'X', new Option_String("auto")); - oc.addDescription("xml-validation", "Report", "Set schema validation scheme of XML inputs (\"never\", \"auto\" or \"always\")"); - - oc.doRegister("xml-validation.net", new Option_String("never")); - oc.addDescription("xml-validation.net", "Report", "Set schema validation scheme of SUMO network inputs (\"never\", \"auto\" or \"always\")"); - - oc.doRegister("no-warnings", 'W', new Option_Bool(false)); - oc.addSynonyme("no-warnings", "suppress-warnings", true); - oc.addDescription("no-warnings", "Report", "Disables output of warnings"); - - oc.doRegister("aggregate-warnings", new Option_Integer(-1)); - oc.addDescription("aggregate-warnings", "Report", "Aggregate warnings of the same type whenever more than INT occur"); - - oc.doRegister("log", 'l', new Option_FileName()); - oc.addSynonyme("log", "log-file"); - oc.addDescription("log", "Report", "Writes all messages to FILE (implies verbose)"); - - oc.doRegister("message-log", new Option_FileName()); - oc.addDescription("message-log", "Report", "Writes all non-error messages to FILE (implies verbose)"); - - oc.doRegister("error-log", new Option_FileName()); - oc.addDescription("error-log", "Report", "Writes all warnings and errors to FILE"); - - oc.doRegister("write-license", new Option_Bool(false)); - oc.addDescription("write-license", "Output", "Include license info into every output file"); - - oc.doRegister("output-prefix", new Option_String()); - oc.addDescription("output-prefix", "Output", "Prefix which is applied to all output files. The special string 'TIME' is replaced by the current time."); - - oc.doRegister("precision", new Option_Integer(2)); - oc.addDescription("precision", "Output", "Defines the number of digits after the comma for floating point output"); - - oc.doRegister("precision.geo", new Option_Integer(6)); - oc.addDescription("precision.geo", "Output", "Defines the number of digits after the comma for lon,lat output"); - - oc.doRegister("human-readable-time", 'H', new Option_Bool(false)); - oc.addDescription("human-readable-time", "Output", "Write time values as hour:minute:second or day:hour:minute:second rathern than seconds"); -} - - -bool -SystemFrame::checkOptions() { - OptionsCont& oc = OptionsCont::getOptions(); - gPrecision = oc.getInt("precision"); - gPrecisionGeo = oc.getInt("precision.geo"); - gHumanReadableTime = oc.getBool("human-readable-time"); - if (oc.exists("weights.random-factor")) { - gWeightsRandomFactor = oc.getFloat("weights.random-factor"); - } - return true; -} - - -void -SystemFrame::close() { - // flush aggregated warnings - MsgHandler::getWarningInstance()->clear(); - // close all output devices - OutputDevice::closeAll(); - // close the xml-subsystem - XMLSubSys::close(); - // delete build program options - OptionsCont::getOptions().clear(); - // delete messages - MsgHandler::cleanupOnEnd(); -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/utils/common/SystemFrame.h b/Util/OSM2ODR/src/utils/common/SystemFrame.h deleted file mode 100644 index eb10a772c..000000000 --- a/Util/OSM2ODR/src/utils/common/SystemFrame.h +++ /dev/null @@ -1,78 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file SystemFrame.h -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Mon, 23.06.2003 -/// -// A set of actions common to all applications -/****************************************************************************/ -#pragma once -// =========================================================================== -// class declarations -// =========================================================================== -class OptionsCont; - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class SystemFrame - * @brief A set of actions common to all applications - * - * As almost all applications within the SUMO-package share the same - * initialisation procedure, it is encapsulated within this class. - * - * Only two things are done herein, so far. The first is to insert - * options into the given options container that are used for dealing - * with the application's configuration. - * - * Additionally, a closing method may be found, which closes all used - * subsystems. - */ -class SystemFrame { -public: - /** @brief Adds configuration options to the given container - * - * @param[in] oc The options container to add the options to - * @todo let the container be retrieved - */ - static void addConfigurationOptions(OptionsCont& oc); - - - /** @brief Adds reporting options to the given container - * - * @param[in] oc The options container to add the options to - * @todo let the container be retrieved - */ - static void addReportOptions(OptionsCont& oc); - - /// @brief checks shared options and sets StdDefs - static bool checkOptions(); - - /** @brief Closes all of an applications subsystems - * - * Closes (in this order) - * @arg The xml subsystem - * @arg The options subsystem - * @arg The message subsystem - * @see XMLSubSys::close() - * @see OptionsCont::clear() - * @see MsgHandler::cleanupOnEnd() - */ - static void close(); - - -}; diff --git a/Util/OSM2ODR/src/utils/common/ToString.h b/Util/OSM2ODR/src/utils/common/ToString.h deleted file mode 100644 index 8766437cb..000000000 --- a/Util/OSM2ODR/src/utils/common/ToString.h +++ /dev/null @@ -1,362 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2002-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file ToString.h -/// @author Christian Roessel -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date Wed, 23 Sep 2002 -/// -// ------------------- -/****************************************************************************/ -#pragma once -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "StdDefs.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * Template for conversions from origin format to string representation - * (when supplied by c++/the stl) - */ -template -inline std::string toString(const T& t, std::streamsize accuracy = gPrecision) { - std::ostringstream oss; - oss.setf(std::ios::fixed, std::ios::floatfield); - oss << std::setprecision(accuracy); - oss << t; - return oss.str(); -} - - -template -inline std::string toHex(const T i, std::streamsize numDigits = 0) { - // taken from http://stackoverflow.com/questions/5100718/int-to-hex-string-in-c - std::stringstream stream; - stream << "0x" << std::setfill('0') << std::setw(numDigits == 0 ? sizeof(T) * 2 : numDigits) << std::hex << i; - return stream.str(); -} - - -inline std::string toString(const Named* obj, std::streamsize accuracy) { - UNUSED_PARAMETER(accuracy); - return Named::getIDSecure(obj); -} - - -template <> -inline std::string toString(const SumoXMLTag& tag, std::streamsize accuracy) { - UNUSED_PARAMETER(accuracy); - return SUMOXMLDefinitions::Tags.getString(tag); -} - - -template <> -inline std::string toString(const SumoXMLAttr& attr, std::streamsize accuracy) { - UNUSED_PARAMETER(accuracy); - return SUMOXMLDefinitions::Attrs.getString(attr); -} - - -template <> -inline std::string toString(const SumoXMLNodeType& nodeType, std::streamsize accuracy) { - UNUSED_PARAMETER(accuracy); - return SUMOXMLDefinitions::NodeTypes.getString(nodeType); -} - - -template <> -inline std::string toString(const SumoXMLEdgeFunc& edgeFunc, std::streamsize accuracy) { - UNUSED_PARAMETER(accuracy); - return SUMOXMLDefinitions::EdgeFunctions.getString(edgeFunc); -} - - -template <> -inline std::string toString(const SUMOVehicleClass& vClass, std::streamsize accuracy) { - UNUSED_PARAMETER(accuracy); - return SumoVehicleClassStrings.getString(vClass); -} - - -template <> -inline std::string toString(const LaneSpreadFunction& lsf, std::streamsize accuracy) { - UNUSED_PARAMETER(accuracy); - return SUMOXMLDefinitions::LaneSpreadFunctions.getString(lsf); -} - -template <> -inline std::string toString(const RightOfWay& row, std::streamsize accuracy) { - UNUSED_PARAMETER(accuracy); - return SUMOXMLDefinitions::RightOfWayValues.getString(row); -} - -template <> -inline std::string toString(const FringeType& fringeType, std::streamsize accuracy) { - UNUSED_PARAMETER(accuracy); - return SUMOXMLDefinitions::FringeTypeValues.getString(fringeType); -} - -template <> -inline std::string toString(const PersonMode& personMode, std::streamsize accuracy) { - UNUSED_PARAMETER(accuracy); - return SUMOXMLDefinitions::PersonModeValues.getString(personMode); -} - -template <> -inline std::string toString(const LinkState& linkState, std::streamsize accuracy) { - UNUSED_PARAMETER(accuracy); - return SUMOXMLDefinitions::LinkStates.getString(linkState); -} - - -template <> -inline std::string toString(const LinkDirection& linkDir, std::streamsize accuracy) { - UNUSED_PARAMETER(accuracy); - return SUMOXMLDefinitions::LinkDirections.getString(linkDir); -} - - -template <> -inline std::string toString(const TrafficLightType& type, std::streamsize accuracy) { - UNUSED_PARAMETER(accuracy); - return SUMOXMLDefinitions::TrafficLightTypes.getString(type); -} - - -template <> -inline std::string toString(const LaneChangeModel& model, std::streamsize accuracy) { - UNUSED_PARAMETER(accuracy); - return SUMOXMLDefinitions::LaneChangeModels.getString(model); -} - -template <> -inline std::string toString(const LateralAlignment& latA, std::streamsize accuracy) { - UNUSED_PARAMETER(accuracy); - return SUMOXMLDefinitions::LateralAlignments.getString(latA); -} - -template <> -inline std::string toString(const LaneChangeAction& action, std::streamsize accuracy) { - UNUSED_PARAMETER(accuracy); - std::vector strings = SUMOXMLDefinitions::LaneChangeActions.getStrings(); - bool hadOne = false; - std::ostringstream oss; - for (std::vector::const_iterator it = strings.begin(); it != strings.end(); ++it) { - if ((action & SUMOXMLDefinitions::LaneChangeActions.get(*it)) != 0) { - if (hadOne) { - oss << "|"; - } else { - hadOne = true; - } - oss << (*it); - } - } - return oss.str(); -} - -template <> -inline std::string toString(const Distribution_Parameterized& dist, std::streamsize accuracy) { - return dist.toStr(accuracy); -} - -template -inline std::string toString(const std::vector& v, std::streamsize accuracy = gPrecision) { - return toString(v.begin(), v.end(), accuracy); -} - -template -inline std::string toString(const typename std::vector::const_iterator& b, const typename std::vector::const_iterator& e, std::streamsize accuracy = gPrecision) { - UNUSED_PARAMETER(accuracy); - std::ostringstream oss; - for (typename std::vector::const_iterator it = b; it != e; ++it) { - if (it != b) { - oss << " "; - } - oss << Named::getIDSecure(*it); - } - return oss.str(); -} - -template -inline std::string toString(const std::list& v, std::streamsize accuracy = gPrecision) { - return toString(v.begin(), v.end(), accuracy); -} - -template -inline std::string toString(const typename std::list::const_iterator& b, const typename std::list::const_iterator& e, std::streamsize accuracy = gPrecision) { - UNUSED_PARAMETER(accuracy); - std::ostringstream oss; - for (typename std::list::const_iterator it = b; it != e; ++it) { - if (it != b) { - oss << " "; - } - oss << Named::getIDSecure(*it); - } - return oss.str(); -} - - - -//template -//inline std::string toString(const std::vector& v, std::streamsize accuracy = gPrecision) { -// return toString(v.begin(), v.end(), accuracy); -//} -// -// -//template -//inline std::string toString(const typename std::vector::const_iterator& b, const typename std::vector::const_iterator& e, std::streamsize accuracy = gPrecision) { -// UNUSED_PARAMETER(accuracy); -// std::ostringstream oss; -// for (typename std::vector::const_iterator it = b; it != e; ++it) { -// if (it != b) { -// oss << " "; -// } -// oss << Named::getIDSecure(*it); -// } -// return oss.str(); -//} - - -template -inline std::string joinToString(const std::vector& v, const T_BETWEEN& between, std::streamsize accuracy = gPrecision) { - std::ostringstream oss; - bool connect = false; - for (typename std::vector::const_iterator it = v.begin(); it != v.end(); ++it) { - if (connect) { - oss << toString(between, accuracy); - } else { - connect = true; - } - oss << toString(*it, accuracy); - } - return oss.str(); -} - - -template -inline std::string joinToStringSorting(const std::vector& v, const T_BETWEEN& between, std::streamsize accuracy = gPrecision) { - std::vector sorted(v); - std::sort(sorted.begin(), sorted.end()); - return joinToString(sorted, between, accuracy); -} - - -template -inline std::string joinNamedToStringSorting(const std::set& ns, const T_BETWEEN& between) { - std::vector ids; - for (T* n : ns) { - ids.push_back(Named::getIDSecure(n)); - } - return joinToStringSorting(ids, between); -} - - -template -inline std::string joinNamedToString(const std::set& ns, const T_BETWEEN& between) { - std::vector ids; - for (T* n : ns) { - ids.push_back(Named::getIDSecure(n)); - } - return joinToString(ids, between); -} - - -template -inline std::string toString(const std::set& v, std::streamsize accuracy = gPrecision) { - UNUSED_PARAMETER(accuracy); - std::vector ids; - for (typename std::set::const_iterator it = v.begin(); it != v.end(); ++it) { - ids.push_back((*it)->getID()); - } - return joinToStringSorting(ids, " "); -} - - -template <> -inline std::string toString(const std::vector& v, std::streamsize accuracy) { - return joinToString(v, " ", accuracy); -} - - -template <> -inline std::string toString(const std::vector& v, std::streamsize accuracy) { - return joinToString(v, " ", accuracy); -} - - -template <> -inline std::string toString(const std::vector& v, std::streamsize accuracy) { - return joinToString(v, " ", accuracy); -} - - -template -inline std::string joinToString(const std::set& s, const T_BETWEEN& between, std::streamsize accuracy = gPrecision) { - std::ostringstream oss; - bool connect = false; - for (typename std::set::const_iterator it = s.begin(); it != s.end(); ++it) { - if (connect) { - oss << toString(between, accuracy); - } else { - connect = true; - } - oss << toString(*it, accuracy); - } - return oss.str(); -} - - -template <> -inline std::string toString(const std::vector& v, std::streamsize) { - return joinToString(v, " "); -} - - -template <> -inline std::string toString(const std::set& v, std::streamsize) { - return joinToString(v, " "); -} - - -template -inline std::string joinToString(const std::map& s, const T_BETWEEN& between, const T_BETWEEN_KEYVAL& between_keyval, std::streamsize accuracy = gPrecision) { - std::ostringstream oss; - bool connect = false; - for (typename std::map::const_iterator it = s.begin(); it != s.end(); ++it) { - if (connect) { - oss << toString(between, accuracy); - } else { - connect = true; - } - oss << toString(it->first, accuracy) << between_keyval << toString(it->second, accuracy); - } - return oss.str(); -} - - -template <> -inline std::string toString(const std::map& v, std::streamsize) { - return joinToString(v, ", ", ":"); -} diff --git a/Util/OSM2ODR/src/utils/common/UtilExceptions.h b/Util/OSM2ODR/src/utils/common/UtilExceptions.h deleted file mode 100644 index 62415f280..000000000 --- a/Util/OSM2ODR/src/utils/common/UtilExceptions.h +++ /dev/null @@ -1,184 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file UtilExceptions.h -/// @author Daniel Krajzewicz -/// @author Christian Roessel -/// @author Michael Behrisch -/// @author Felix Brack -/// @date Mon, 17 Dec 2001 -/// -// Exceptions for used by some utility classes -/****************************************************************************/ -#pragma once -#include -#include - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * ProcessError - * The base class for all exceptions in SUMO. The reason itself can either be - * reported before throwing the exception or in the message parameter. - */ -class ProcessError : public std::runtime_error { -public: - /// @brief constructor - ProcessError() - : std::runtime_error("Process Error") {} - - /// @brief constructor - ProcessError(const std::string& msg) - : std::runtime_error(msg) {} -}; - - -/** - * InvalidArgument - * Thrown when an argument was not proper in the current context. - * A message will be supplied. - */ -class InvalidArgument : public ProcessError { -public: - /// @brief constructor - InvalidArgument(const std::string& message) - : ProcessError(message) {} -}; - - -/** - * EmptyData - * Thrown when data required by a method is missing - */ -class EmptyData : public ProcessError { -public: - /// @brief constructor - EmptyData() - : ProcessError("Empty Data") {} -}; - - -/** - * FormatException - * Thrown when a string that shall be converted into - * something else contained the wrong characters - */ -class FormatException : public ProcessError { -public: - /// @brief constructor - FormatException(const std::string& msg) - : ProcessError(msg) {} -}; - - -/** - * NumberFormatException - * Thrown when the string that shall be converted into a - * numerical representation has any other characters then - * digits and a dot - */ -class NumberFormatException : public FormatException { -public: - /// @brief constructor - NumberFormatException(const std::string& data) - : FormatException("Invalid Number Format '" + data + "'") {} -}; - - -/** - * TimeFormatException - * Thrown when the string that shall be converted into a - * time representation HH:MM:SS isn't valid - */ -class TimeFormatException : public FormatException { -public: - /// @brief constructor - TimeFormatException(const std::string& data) - : FormatException("Invalid Time Format '" + data + "'") {} -}; - - -/** - * BoolFormatException - * Thrown when the string that shall be converted into a - * boolean does not match - */ -class BoolFormatException : public FormatException { -public: - /// @brief constructor - BoolFormatException(const std::string& data) - : FormatException("Invalid Bool Format '" + data + "'") {} -}; - - -/** - * OutOfBoundsException - * Thrown when an array element out of the array's - * bounderies is accessed - */ -class OutOfBoundsException : public ProcessError { -public: - /// @brief constructor - OutOfBoundsException() - : ProcessError("Out Of Bounds") {} -}; - - -/** - * UnknownElement - * Thrown when a named element is tried to be accessed - * which is not known to the container - */ -class UnknownElement : public ProcessError { -public: - /// @brief constructor - UnknownElement() - : ProcessError("Unknown Element") {} - - /// @brief constructor - UnknownElement(const std::string& msg) - : ProcessError(msg) {} -}; - -/** - * UnknownElement - */ -class IOError : public ProcessError { -public: - /// @brief constructor - IOError(const std::string& message) - : ProcessError(message) {} -}; - -/** - * Abort parsing (intended change in control flow, not realy an error) - */ -class AbortParsing : public ProcessError { -public: - /// @brief constructor - AbortParsing(const std::string& message) - : ProcessError(message) {} -}; - -/// define SOFT_ASSERT raise an assertion in debug mode everywhere except on the windows test server -#ifdef MSVC_TEST_SERVER -#ifdef _DEBUG -#define SOFT_ASSERT(expr) if (!(expr)) {throw ProcessError("should not happen");} -#else -#define SOFT_ASSERT(expr) -#endif -#else -#define SOFT_ASSERT(expr) assert(expr); -#endif diff --git a/Util/OSM2ODR/src/utils/common/ValueRetriever.h b/Util/OSM2ODR/src/utils/common/ValueRetriever.h deleted file mode 100644 index b1b35311e..000000000 --- a/Util/OSM2ODR/src/utils/common/ValueRetriever.h +++ /dev/null @@ -1,34 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file ValueRetriever.h -/// @author Daniel Krajzewicz -/// @date Fri, 29.04.2005 -/// -// -/****************************************************************************/ -#pragma once -// =========================================================================== -// class definitions -// =========================================================================== -/** - * - */ -template -class ValueRetriever { -public: - ValueRetriever() { } - virtual ~ValueRetriever() { } - virtual void addValue(T value) = 0; - -}; diff --git a/Util/OSM2ODR/src/utils/common/ValueSource.h b/Util/OSM2ODR/src/utils/common/ValueSource.h deleted file mode 100644 index ecdc2c6a9..000000000 --- a/Util/OSM2ODR/src/utils/common/ValueSource.h +++ /dev/null @@ -1,36 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file ValueSource.h -/// @author Daniel Krajzewicz -/// @date Fri, 29.04.2005 -/// -// -/****************************************************************************/ -#pragma once -// =========================================================================== -// class definitions -// =========================================================================== -/** - * - */ -template -class ValueSource { -public: - ValueSource() { } - virtual ~ValueSource() { } - virtual T getValue() const = 0; - virtual ValueSource* copy() const = 0; - virtual ValueSource* makedoubleReturningCopy() const = 0; - -}; diff --git a/Util/OSM2ODR/src/utils/common/ValueTimeLine.h b/Util/OSM2ODR/src/utils/common/ValueTimeLine.h deleted file mode 100644 index 0887c8eec..000000000 --- a/Util/OSM2ODR/src/utils/common/ValueTimeLine.h +++ /dev/null @@ -1,170 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file ValueTimeLine.h -/// @author Christian Roessel -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Sept 2002 -/// -// A list of time ranges with assigned values -/****************************************************************************/ -#pragma once -#include -#include -#include -#include - - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class ValueTimeLine - * - * A time line being a sorted container of non-overlapping time-ranges - * with assigned values. The container is sorted by the first value of the - * time-range while being filled. Every new inserted time range - * may overwrite or split one or multiple earlier intervals. - */ -template -class ValueTimeLine { -public: - /// @brief Constructor - ValueTimeLine() { } - - /// @brief Destructor - ~ValueTimeLine() { } - - /** @brief Adds a value for a time interval into the container. - * - * Make sure that begin >= 0 and begin < end. - * - * @param[in] begin the start time of the time range (inclusive) - * @param[in] end the end time of the time range (exclusive) - * @param[in] value the value to store - */ - void add(double begin, double end, T value) { - assert(begin >= 0); - assert(begin < end); - // inserting strictly before the first or after the last interval (includes empty case) - if (myValues.upper_bound(begin) == myValues.end() || - myValues.upper_bound(end) == myValues.begin()) { - myValues[begin] = std::make_pair(true, value); - myValues[end] = std::make_pair(false, value); - return; - } - // our end already has a value - typename TimedValueMap::iterator endIt = myValues.find(end); - if (endIt != myValues.end()) { - myValues.erase(myValues.upper_bound(begin), endIt); - myValues[begin] = std::make_pair(true, value); - return; - } - // we have at least one entry strictly before our end - endIt = myValues.lower_bound(end); - --endIt; - ValidValue oldEndValue = endIt->second; - myValues.erase(myValues.upper_bound(begin), myValues.lower_bound(end)); - myValues[begin] = std::make_pair(true, value); - myValues[end] = oldEndValue; - } - - /** @brief Returns the value for the given time. - * - * There is no bounds checking applied! If there was no value - * set, the return value is undefined, the method may even segfault. - * - * @param[in] the time for which the value should be retrieved - * @return the value for the time - */ - T getValue(double time) const { - assert(myValues.size() != 0); - typename TimedValueMap::const_iterator it = myValues.upper_bound(time); - assert(it != myValues.begin()); - --it; - return it->second.second; - } - - /** @brief Returns whether a value for the given time is known. - * - * This method implements the bounds checking. It returns true - * if and only if an explicit value was set for the given time - * using add. Default values stemming from fillGaps are not - * considered valid. - * - * @param[in] the time for which the value should be retrieved - * @return whether a valid value was set - */ - bool describesTime(double time) const { - typename TimedValueMap::const_iterator afterIt = myValues.upper_bound(time); - if (afterIt == myValues.begin()) { - return false; - } - --afterIt; - return afterIt->second.first; - } - - /** @brief Returns the time point at which the value changes. - * - * If the two input parameters lie in two consecutive time - * intervals, this method returns the point at which the - * interval changes. In any other case -1 is returned. - * - * @param[in] low the time in the first interval - * @param[in] high the time in the second interval - * @return the split point - */ - double getSplitTime(double low, double high) const { - typename TimedValueMap::const_iterator afterLow = myValues.upper_bound(low); - typename TimedValueMap::const_iterator afterHigh = myValues.upper_bound(high); - --afterHigh; - if (afterLow == afterHigh) { - return afterLow->first; - } - return -1; - } - - /** @brief Sets a default value for all unset intervals. - * - * @param[in] value the value to store - * @param[in] extendOverBoundaries whether the first/last value should be valid for later / earlier times as well - */ - void fillGaps(T value, bool extendOverBoundaries = false) { - for (typename TimedValueMap::iterator it = myValues.begin(); it != myValues.end(); ++it) { - if (!it->second.first) { - it->second.second = value; - } - } - if (extendOverBoundaries && !myValues.empty()) { - typename TimedValueMap::iterator it = --myValues.end(); - if (!it->second.first) { - myValues.erase(it, myValues.end()); - } - value = myValues.begin()->second.second; - } - myValues[-1] = std::make_pair(false, value); - } - -private: - /// @brief Value of time line, indicating validity. - typedef std::pair ValidValue; - - /// @brief Sorted map from start of intervals to values. - typedef std::map TimedValueMap; - - /// @brief The list of time periods (with values) - TimedValueMap myValues; - -}; diff --git a/Util/OSM2ODR/src/utils/common/VectorHelper.h b/Util/OSM2ODR/src/utils/common/VectorHelper.h deleted file mode 100644 index bdf6dcca1..000000000 --- a/Util/OSM2ODR/src/utils/common/VectorHelper.h +++ /dev/null @@ -1,156 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file VectorHelper.h -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date Sept 2002 -/// -// A simple vector of doubles -/****************************************************************************/ -#pragma once -#include -#include -#include -#include - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * - */ -template -class VectorHelper { -public: - static T sum(const std::vector& v) { - T sum = 0; - for (typename std::vector::const_iterator i = v.begin(); i != v.end(); i++) { - sum += *i; - } - return sum; - } - - static void normaliseSum(std::vector& v, T msum = 1.0) { - if (msum == 0 || v.size() == 0) { - // is an error; do nothing - return; - } - T rsum = sum(v); - if (rsum == 0) { - set(v, (T) 1.0 * msum / (T) v.size()); - return; - } - div(v, rsum / msum); - } - - static void div(std::vector& v, T by) { - for (typename std::vector::iterator i = v.begin(); i != v.end(); i++) { - *i /= by; - } - } - - static void removeDouble(std::vector& v) { - typename std::vector::iterator i = v.begin(); - while (i != v.end()) { - for (typename std::vector::iterator j = i + 1; j != v.end();) { - if (*i == *j) { - j = v.erase(j); - } else { - j++; - } - } - i++; - } - } - - - static void set(std::vector& v, T to) { - for (typename std::vector::iterator i = v.begin(); i != v.end(); i++) { - *i = to; - } - } - - static T maxValue(const std::vector& v) { - T m = -std::numeric_limits::max(); - for (typename std::vector::const_iterator j = v.begin() ; j != v.end(); j++) { - if ((*j) > m) { - m = *j; - } - } - return m; - } - - static T minValue(const std::vector& v) { - T m = std::numeric_limits::max(); - for (typename std::vector::const_iterator j = v.begin(); j != v.end(); j++) { - if ((*j) < m) { - m = *j; - } - } - return m; - } - - static void remove_smaller_than(std::vector& v, T swell) { - for (typename std::vector::iterator j = v.begin(); j != v.end();) { - if ((*j) < swell) { - j = v.erase(j); - } else { - j++; - } - } - } - - static void remove_larger_than(std::vector& v, T swell) { - for (typename std::vector::iterator j = v.begin(); j != v.end();) { - if ((*j) > swell) { - j = v.erase(j); - } else { - j++; - } - } - } - - static void add2All(std::vector& v, T what) { - for (typename std::vector::iterator j = v.begin(); j != v.end(); j++) { - (*j) += what; - } - } - - /// Returns the information whether at least one element is within both vectors - static bool subSetExists(const std::vector& v1, const std::vector& v2) { - for (typename std::vector::const_iterator i = v1.begin(); i != v1.end(); i++) { - int val1 = (*i); - if (find(v2.begin(), v2.end(), val1) != v2.end()) { - return true; - } - } - return false; - } - - - -}; - -template -std::ostream& operator<<(std::ostream& os, const std::vector& v) { - for (typename std::vector::const_iterator i = v.begin(); i != v.end(); i++) { - if (i != v.begin()) { - os << ", "; - } - os << (*i); - } - return os; -} diff --git a/Util/OSM2ODR/src/utils/common/WrappingCommand.h b/Util/OSM2ODR/src/utils/common/WrappingCommand.h deleted file mode 100644 index 9868bb3b5..000000000 --- a/Util/OSM2ODR/src/utils/common/WrappingCommand.h +++ /dev/null @@ -1,119 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file WrappingCommand.h -/// @author Christian Roessel -/// @author Daniel Krajzewicz -/// @date Thu, 20 Dec 2001 -/// -// A wrapper for a Command function -/****************************************************************************/ -#pragma once -#include "Command.h" - - -// =========================================================================== -// class definition -// =========================================================================== -/** - * @class WrappingCommand - * @brief A wrapper for a Command function - * - * In order to ease life, this class may encapsulate a method of a class which - * in order to be used as a Command. This allows to use a member methods - * of a class to be called as Commands are, avoiding that the instance itself - * is destroyed by the EventHandler. - * - * Because in some cases, the Command may live longer than the instance class, - * a boolean value indicates that the Command is "descheduled". It should - * be set via "deschedule" as soon as the class instance of which a method - * is encapsulated is destroyed and forces that the command (calling of this - * instace's method) is not executed. - * - * @see Design Patterns, Gamma et al. - * @see Command - * @see MSEventControl - */ -template< class T > -class WrappingCommand : public Command { -public: - /// @brief Type of the function to execute. - typedef SUMOTime(T::* Operation)(SUMOTime); - - -public: - /** - * @brief Constructor. - * - * @param[in] receiver Pointer to object of type T that will receive a call to one of it's methods. - * @param[in] operation The objects' method that will be called on execute() - */ - WrappingCommand(T* receiver, Operation operation) - : myReceiver(receiver), myOperation(operation), - myAmDescheduledByParent(false) {} - - - /// @brief Destructor - ~WrappingCommand() {} - - - /** @brief Marks this Command as being descheduled - * - * A simple boolean marker ("myAmDescheduledByParent") is set which - * prevents this command from being executed. - */ - void deschedule() { - myAmDescheduledByParent = true; - } - - /// @brief whether this command has been descheduled - bool isDescheduled() { - return myAmDescheduledByParent; - } - - - /// @name Derived from Command - /// @{ - - /** @brief Executes the command. - * - * If the command is not descheduled, the stored method of the stored instance - * is called. - * - * @param[in] currentTime The current simulation time - * @return The time after which the command shall be executed again, 0 if this command shall be descheduled. - * @exception ProcessError Derived actions may throw this exception - */ - SUMOTime execute(SUMOTime currentTime) { - // do not execute if the command was descheduled - if (myAmDescheduledByParent) { - return 0; - } - // execute if stil valid - return (myReceiver->*myOperation)(currentTime); - } - /// @} - - -private: - /// @brief The object the action is directed to. - T* myReceiver; - - /// @brief The object's operation to perform. - Operation myOperation; - - /// @brief Whether this command was descheduled (is invalid) and shall not be executed - bool myAmDescheduledByParent; - - -}; diff --git a/Util/OSM2ODR/src/utils/distribution/CMakeLists.txt b/Util/OSM2ODR/src/utils/distribution/CMakeLists.txt deleted file mode 100644 index ec79aa8cc..000000000 --- a/Util/OSM2ODR/src/utils/distribution/CMakeLists.txt +++ /dev/null @@ -1,13 +0,0 @@ -set(utils_distribution_STAT_SRCS - Distribution.h - Distribution_Parameterized.cpp - Distribution_Parameterized.h - Distribution_Points.cpp - Distribution_Points.h - DistributionCont.cpp - DistributionCont.h - RandomDistributor.h -) - -add_library(utils_distribution STATIC ${utils_distribution_STAT_SRCS}) -set_property(TARGET utils_distribution PROPERTY PROJECT_LABEL "z_utils_distribution") diff --git a/Util/OSM2ODR/src/utils/distribution/Distribution.h b/Util/OSM2ODR/src/utils/distribution/Distribution.h deleted file mode 100644 index f8605bb53..000000000 --- a/Util/OSM2ODR/src/utils/distribution/Distribution.h +++ /dev/null @@ -1,58 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file Distribution.h -/// @author Daniel Krajzewicz -/// @date Sept 2002 -/// -// The base class for distribution descriptions. -/****************************************************************************/ -#pragma once -#include - -#include -#include - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class Distribution - * The base class for distribution descriptions. Only an interface - * specification. - */ -class Distribution : public Named { -public: - /// Constructor - Distribution(const std::string& id) : Named(id) { } - - /// Destructor - virtual ~Distribution() { } - - /** @brief Draw a sample of the distribution. - * - * A random sample is drawn according to the assigned probabilities. - * - * @param[in] which The random number generator to use; the static one will be used if 0 is passed - * @return the drawn member - */ - virtual double sample(std::mt19937* which = 0) const = 0; - - /// Returns the maximum value of this distribution - virtual double getMax() const = 0; - - /// Returns the string representation of this distribution - virtual std::string toStr(std::streamsize accuracy) const = 0; - -}; diff --git a/Util/OSM2ODR/src/utils/distribution/DistributionCont.cpp b/Util/OSM2ODR/src/utils/distribution/DistributionCont.cpp deleted file mode 100644 index 40ded0b51..000000000 --- a/Util/OSM2ODR/src/utils/distribution/DistributionCont.cpp +++ /dev/null @@ -1,80 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file DistributionCont.cpp -/// @author Daniel Krajzewicz -/// @date Sept 2002 -/// -// A container for distributions -/****************************************************************************/ -#include - -#include "DistributionCont.h" - - -// =========================================================================== -// static variable definitions -// =========================================================================== -DistributionCont::TypedDistDict DistributionCont::myDict; - - -// =========================================================================== -// method definitions -// =========================================================================== -bool -DistributionCont::dictionary(const std::string& type, const std::string& id, - Distribution* d) { - TypedDistDict::iterator i = myDict.find(type); - - if (i == myDict.end()) { - myDict[type][id] = d; - return true; - } - DistDict& dict = (*i).second; - DistDict::iterator j = dict.find(id); - if (j == dict.end()) { - myDict[type][id] = d; - return true; - } - return false; -} - - -Distribution* -DistributionCont::dictionary(const std::string& type, - const std::string& id) { - TypedDistDict::iterator i = myDict.find(type); - if (i == myDict.end()) { - return nullptr; - } - DistDict& dict = (*i).second; - DistDict::iterator j = dict.find(id); - if (j == dict.end()) { - return nullptr; - } - return (*j).second; -} - - -void -DistributionCont::clear() { - for (TypedDistDict::iterator i = myDict.begin(); i != myDict.end(); i++) { - DistDict& dict = (*i).second; - for (DistDict::iterator j = dict.begin(); j != dict.end(); j++) { - delete (*j).second; - } - } -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/utils/distribution/DistributionCont.h b/Util/OSM2ODR/src/utils/distribution/DistributionCont.h deleted file mode 100644 index 534ecace6..000000000 --- a/Util/OSM2ODR/src/utils/distribution/DistributionCont.h +++ /dev/null @@ -1,58 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file DistributionCont.h -/// @author Daniel Krajzewicz -/// @date Sept 2002 -/// -// A container for distributions -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class DistributionCont - * A container for distributions of different type. - */ -class DistributionCont { -public: - /// Adds a distribution of the given type and name to the container - static bool dictionary(const std::string& type, const std::string& id, - Distribution* d); - - /// retrieves the distribution described by a type and a name from the container - static Distribution* dictionary(const std::string& type, - const std::string& id); - - /// delete all stored distributions - static void clear(); - -private: - /// Definition of a map from distribution ids to distributions - typedef std::map DistDict; - - /// Definition of a map from distribution types to distribution ids to distributions - typedef std::map TypedDistDict; - - /// Map from distribution types to distribution ids to distributions - static TypedDistDict myDict; - -}; diff --git a/Util/OSM2ODR/src/utils/distribution/Distribution_Parameterized.cpp b/Util/OSM2ODR/src/utils/distribution/Distribution_Parameterized.cpp deleted file mode 100644 index 29a371a6a..000000000 --- a/Util/OSM2ODR/src/utils/distribution/Distribution_Parameterized.cpp +++ /dev/null @@ -1,149 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file Distribution_Parameterized.cpp -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Sept 2002 -/// -// A distribution described by parameters such as the mean value and std-dev -/****************************************************************************/ -#include - -#include -#include -#include -#include -#include -#include - -#include "Distribution_Parameterized.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -Distribution_Parameterized::Distribution_Parameterized(const std::string& id, double mean, double deviation) : - Distribution(id) { - myParameter.push_back(mean); - myParameter.push_back(deviation); -} - - -Distribution_Parameterized::Distribution_Parameterized(const std::string& id, double mean, double deviation, double min, double max) : - Distribution(id) { - myParameter.push_back(mean); - myParameter.push_back(deviation); - myParameter.push_back(min); - myParameter.push_back(max); -} - - -Distribution_Parameterized::~Distribution_Parameterized() {} - - -void -Distribution_Parameterized::parse(const std::string& description, const bool hardFail) { - try { - const std::string distName = description.substr(0, description.find('(')); - if (distName == "norm" || distName == "normc") { - std::vector params = StringTokenizer(description.substr(distName.size() + 1, description.size() - distName.size() - 2), ',').getVector(); - myParameter.resize(params.size()); - std::transform(params.begin(), params.end(), myParameter.begin(), StringUtils::toDouble); - setID(distName); - } else { - myParameter[0] = StringUtils::toDouble(description); - } - if (myParameter.size() == 1) { - myParameter.push_back(0.); - } - } catch (...) { - // set default distribution parameterized - myParameter = {0., 0.}; - if (hardFail) { - throw ProcessError("Invalid format of distribution parameterized"); - } else { - WRITE_ERROR("Invalid format of distribution parameterized"); - } - } -} - - -double -Distribution_Parameterized::sample(std::mt19937* which) const { - if (myParameter[1] == 0.) { - return myParameter[0]; - } - double val = RandHelper::randNorm(myParameter[0], myParameter[1], which); - if (myParameter.size() > 2) { - const double min = myParameter[2]; - const double max = getMax(); - while (val < min || val > max) { - val = RandHelper::randNorm(myParameter[0], myParameter[1], which); - } - } - return val; -} - - -double -Distribution_Parameterized::getMax() const { - if (myParameter[1] == 0.) { - return myParameter[0]; - } - return myParameter.size() > 3 ? myParameter[3] : std::numeric_limits::infinity(); -} - - -std::vector& -Distribution_Parameterized::getParameter() { - return myParameter; -} - - -const std::vector& -Distribution_Parameterized::getParameter() const { - return myParameter; -} - - -std::string -Distribution_Parameterized::toStr(std::streamsize accuracy) const { - if (myParameter[1] < 0) { - // only write simple speedFactor - return toString(myParameter[0]); - } else { - return (myParameter[1] == 0. - ? myID + "(" + toString(myParameter[0], accuracy) + "," + toString(myParameter[1], accuracy) + ")" - : myID + "(" + joinToString(myParameter, ",", accuracy) + ")"); - } -} - - -bool -Distribution_Parameterized::isValid(std::string& error) { - if (myParameter.size() > 2 && myParameter[1] != 0) { - if (myParameter[0] > getMax()) { - error = "distribution mean " + toString(myParameter[0]) + " is larger than upper boundary " + toString(getMax()); - return false; - } - if (myParameter[0] < myParameter[2]) { - error = "distribution mean " + toString(myParameter[0]) + " is smaller than lower boundary " + toString(myParameter[2]); - return false; - } - } - return true; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/utils/distribution/Distribution_Parameterized.h b/Util/OSM2ODR/src/utils/distribution/Distribution_Parameterized.h deleted file mode 100644 index 4092ad3db..000000000 --- a/Util/OSM2ODR/src/utils/distribution/Distribution_Parameterized.h +++ /dev/null @@ -1,82 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file Distribution_Parameterized.h -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Sept 2002 -/// -// A distribution described by parameters such as the mean value and std-dev -/****************************************************************************/ -#pragma once -#include - -#include -#include - -#include "Distribution.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class Distribution_Parameterized - * A description of distribution by the distribution's mean value and a - * standard deviation. - * Incomplete and unused yet. This class should be overridden by derived - * classes - */ -class Distribution_Parameterized : public Distribution { - -public: - /// @brief Constructor for standard normal distribution - Distribution_Parameterized(const std::string& id, double mean, double deviation); - - /// @brief Constructor for normal distribution with cutoff - Distribution_Parameterized(const std::string& id, double mean, double deviation, double min, double max); - - /// @brief Destructor - virtual ~Distribution_Parameterized(); - - /// @brief Overwrite by parsable distribution description - void parse(const std::string& description, const bool hardFail); - - /** @brief Draw a sample of the distribution. - * - * A random sample is drawn according to the assigned probabilities. - * - * @param[in] which The random number generator to use; the static one will be used if 0 is passed - * @return the drawn member - */ - double sample(std::mt19937* which = 0) const; - - /// @brief Returns the maximum value of this distribution - double getMax() const; - - /// @brief Returns the parameters of this distribution - std::vector& getParameter(); - - /// @brief Returns the unmodifiable parameters of this distribution - const std::vector& getParameter() const; - - /// @brief check whether the distribution is valid - bool isValid(std::string& error); - - /// @brief Returns the string representation of this distribution - std::string toStr(std::streamsize accuracy) const; - -private: - /// @brief The distribution's parameters - std::vector myParameter; -}; diff --git a/Util/OSM2ODR/src/utils/distribution/Distribution_Points.cpp b/Util/OSM2ODR/src/utils/distribution/Distribution_Points.cpp deleted file mode 100644 index 7bd9310fe..000000000 --- a/Util/OSM2ODR/src/utils/distribution/Distribution_Points.cpp +++ /dev/null @@ -1,62 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file Distribution_Points.cpp -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Sept 2002 -/// -// The description of a distribution by a curve -/****************************************************************************/ -#include - -#include -#include -#include -#include -#include "Distribution_Points.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -Distribution_Points::Distribution_Points(const std::string& id) - : Distribution(id) {} - - -Distribution_Points::~Distribution_Points() {} - - -double -Distribution_Points::getMax() const { - assert(getVals().size() > 0); - return getVals().back(); -} - - -std::string -Distribution_Points::toStr(std::streamsize accuracy) const { - std::stringstream oss; - oss << std::setprecision(accuracy); - const std::vector vals = getVals(); - for (int i = 0; i < (int)vals.size(); i++) { - if (i > 0) { - oss << ","; - } - oss << vals[i] << ":" << getProbs()[i]; - } - return "points(" + oss.str() + ")"; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/utils/distribution/Distribution_Points.h b/Util/OSM2ODR/src/utils/distribution/Distribution_Points.h deleted file mode 100644 index 723e900e1..000000000 --- a/Util/OSM2ODR/src/utils/distribution/Distribution_Points.h +++ /dev/null @@ -1,62 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file Distribution_Points.h -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Sept 2002 -/// -// The description of a distribution by a curve -/****************************************************************************/ -#pragma once -#include - -#include "RandomDistributor.h" -#include "Distribution.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class Distribution_Points - * A description of a distribution that uses a set of points in a 2d-space - * to describe the values (each points x-value) and their possibilities - * (each points y-value) - */ -class Distribution_Points : - public Distribution, public RandomDistributor { -public: - /// Constructor - Distribution_Points(const std::string& id); - - /// Destructor - virtual ~Distribution_Points(); - - /** @brief Draw a sample of the distribution. - * - * A random sample is drawn according to the assigned probabilities. - * - * @param[in] which The random number generator to use; the static one will be used if 0 is passed - * @return the drawn member - */ - double sample(std::mt19937* which = 0) const { - return get(which); - } - - /// Returns the maximum value of this distribution - double getMax() const; - - /// Returns the string representation of this distribution - std::string toStr(std::streamsize accuracy) const; -}; diff --git a/Util/OSM2ODR/src/utils/distribution/RandomDistributor.h b/Util/OSM2ODR/src/utils/distribution/RandomDistributor.h deleted file mode 100644 index 2d170133c..000000000 --- a/Util/OSM2ODR/src/utils/distribution/RandomDistributor.h +++ /dev/null @@ -1,172 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2005-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file RandomDistributor.h -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @author Jakob Erdmann -/// @date 2005-09-15 -/// -// Represents a generic random distribution -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include -#include - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class RandomDistributor - * @brief Represents a generic random distribution - * - * This class allows to create random distributions by assigning - * arbitrary (non-negative) probabilities to its elements. The - * random number generator used is specified in RandHelper. - * - * @see RandHelper - */ - -template -class RandomDistributor { -public: - /** @brief Constructor for an empty distribution - */ - RandomDistributor() : - myProb(0) { - } - - /// @brief Destructor - ~RandomDistributor() { } - - /** @brief Adds a value with an assigned probability to the distribution. - * - * If the value is already member of the distribution and checkDuplicates is - * true (the default) the given probability is added to the current. - * The probability has to be non-negative but values larger than one are - * allowed (and scaled accordingly when an element is drawn). - * - * @param[in] val The value to add to the distribution - * @param[in] prob The probability assigned to the value - * @return true if a new value was added, false if just the probability of an existing one was updated - */ - bool add(T val, double prob, bool checkDuplicates = true) { - myProb += prob; - assert(myProb >= 0); - if (checkDuplicates) { - for (int i = 0; i < (int)myVals.size(); i++) { - if (val == myVals[i]) { - myProbs[i] += prob; - assert(myProbs[i] >= 0); - return false; - } - } - } else { - assert(prob >= 0); - } - myVals.push_back(val); - myProbs.push_back(prob); - return true; - } - - /** @brief Removes a value with an assigned probability from the distribution. - * - * @param[in] val The value to remove from the distribution - * @return true if a new value was added, false if just the probability of an existing one was updated - */ - bool remove(T val) { - for (int i = 0; i < (int)myVals.size(); i++) { - if (myVals[i] == val) { - myProb -= myProbs[i]; - myProbs.erase(myProbs.begin() + i); - myVals.erase(myVals.begin() + i); - return true; - } - } - return false; - } - - /** @brief Draw a sample of the distribution. - * - * A random sample is drawn according to the assigned probabilities. - * - * @param[in] which The random number generator to use; the static one will be used if 0 is passed - * @return the drawn member - */ - T get(std::mt19937* which = 0) const { - if (myProb == 0) { - throw OutOfBoundsException(); - } - double prob = RandHelper::rand(myProb, which); - for (int i = 0; i < (int)myVals.size(); i++) { - if (prob < myProbs[i]) { - return myVals[i]; - } - prob -= myProbs[i]; - } - return myVals.back(); - } - - /** @brief Return the sum of the probabilites assigned to the members. - * - * This should be zero if and only if the distribution is empty. - * - * @return the total probability - */ - double getOverallProb() const { - return myProb; - } - - /// @brief Clears the distribution - void clear() { - myProb = 0; - myVals.clear(); - myProbs.clear(); - } - - /** @brief Returns the members of the distribution. - * - * See getProbs for the corresponding probabilities. - * - * @return the members of the distribution - * @see RandomDistributor::getProbs - */ - const std::vector& getVals() const { - return myVals; - } - - /** @brief Returns the probabilities assigned to the members of the distribution. - * - * See getVals for the corresponding members. - * - * @return the probabilities assigned to the distribution - * @see RandomDistributor::getVals - */ - const std::vector& getProbs() const { - return myProbs; - } - -private: - /// @brief the total probability - double myProb; - /// @brief the members - std::vector myVals; - /// @brief the corresponding probabilities - std::vector myProbs; - -}; diff --git a/Util/OSM2ODR/src/utils/foxtools/FXConditionalLock.h b/Util/OSM2ODR/src/utils/foxtools/FXConditionalLock.h deleted file mode 100644 index ab09ce138..000000000 --- a/Util/OSM2ODR/src/utils/foxtools/FXConditionalLock.h +++ /dev/null @@ -1,61 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2018-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file FXConditionalLock.h -/// @author Michael Behrisch -/// @date 2018-11-14 -/// -// A scoped lock which only triggers on condition -/****************************************************************************/ - -#ifndef FXConditionalLock_h -#define FXConditionalLock_h -#include - -#include - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class FXConditionalLock - * @brief A scoped lock which only triggers on condition - */ -class FXConditionalLock { -public: - /// Construct & lock associated mutex if the condition is true - FXConditionalLock(FXMutex& m, const bool condition) - : myMutex(m), myCondition(condition) { - if (condition) { - m.lock(); - } - } - - /// Destroy and unlock associated mutex - ~FXConditionalLock() { - if (myCondition) { - myMutex.unlock(); - } - } - -private: - FXMutex& myMutex; - const bool myCondition; - -private: - FXConditionalLock& operator=(const FXConditionalLock&) = delete; -}; - - -#endif diff --git a/Util/OSM2ODR/src/utils/foxtools/FXSynchQue.h b/Util/OSM2ODR/src/utils/foxtools/FXSynchQue.h deleted file mode 100644 index d03d1bb08..000000000 --- a/Util/OSM2ODR/src/utils/foxtools/FXSynchQue.h +++ /dev/null @@ -1,211 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2004-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file FXSynchQue.h -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date 2004-03-19 -/// -// missing_desc -/****************************************************************************/ -#ifndef FXSynchQue_h -#define FXSynchQue_h -#include - -#ifdef HAVE_FOX -#include -#endif -#include -#include -#include - -//#define DEBUG_LOCKING - -#ifdef DEBUG_LOCKING -#include -#include "FXWorkerThread.h" -#endif - -template > -class FXSynchQue { -public: - FXSynchQue(const bool condition = true): -#ifdef HAVE_FOX - myMutex(true), -#endif - myCondition(condition) - {} - - T top() { - assert(myItems.size() != 0); -#ifdef HAVE_FOX - if (myCondition) { - myMutex.lock(); - } -#endif - T ret = myItems.front(); -#ifdef HAVE_FOX - if (myCondition) { - myMutex.unlock(); - } -#endif - return ret; - } - - void pop() { -#ifdef HAVE_FOX - if (myCondition) { - myMutex.lock(); - } -#endif - myItems.erase(myItems.begin()); -#ifdef HAVE_FOX - if (myCondition) { - myMutex.unlock(); - } -#endif - } - - // Attention! Removes locking behavior - void unsetCondition() { - myCondition = false; - } - - // Attention! Retains the lock - Container& getContainer() { -#ifdef HAVE_FOX - if (myCondition) { - myMutex.lock(); - } -#endif -#ifdef DEBUG_LOCKING - if (debugflag) { - std::cout << " FXSynchQue::getContainer thread=" << FXWorkerThread::current() << "\n"; - } - myOwningThread = FXWorkerThread::current(); -#endif - return myItems; - } - - void unlock() { -#ifdef HAVE_FOX - if (myCondition) { - myMutex.unlock(); - } -#endif -#ifdef DEBUG_LOCKING - if (debugflag) { - std::cout << " FXSynchQue::unlock thread=" << FXWorkerThread::current() << "\n"; - } - myOwningThread = 0; -#endif - } - - void push_back(T what) { -#ifdef HAVE_FOX - if (myCondition) { - myMutex.lock(); - } -#endif - myItems.push_back(what); -#ifdef HAVE_FOX - if (myCondition) { - myMutex.unlock(); - } -#endif - } - - bool empty() { -#ifdef HAVE_FOX - if (myCondition) { - myMutex.lock(); - } -#endif - const bool ret = myItems.size() == 0; -#ifdef HAVE_FOX - if (myCondition) { - myMutex.unlock(); - } -#endif - return ret; - } - - void clear() { -#ifdef HAVE_FOX - if (myCondition) { - myMutex.lock(); - } -#endif - myItems.clear(); -#ifdef HAVE_FOX - if (myCondition) { - myMutex.unlock(); - } -#endif - } - - size_t size() const { -#ifdef HAVE_FOX - if (myCondition) { - myMutex.lock(); - } -#endif - size_t res = myItems.size(); -#ifdef HAVE_FOX - if (myCondition) { - myMutex.unlock(); - } -#endif - return res; - } - - bool contains(const T& item) const { -#ifdef HAVE_FOX - if (myCondition) { - myMutex.lock(); - } -#endif - bool res = std::find(myItems.begin(), myItems.end(), item) != myItems.end(); -#ifdef HAVE_FOX - if (myCondition) { - myMutex.unlock(); - } -#endif - return res; - } - - bool isLocked() const { -#ifdef HAVE_FOX - return myMutex.locked(); -#else - return false; -#endif - } - -private: -#ifdef HAVE_FOX - mutable FXMutex myMutex; -#endif - Container myItems; - bool myCondition; - -#ifdef DEBUG_LOCKING - mutable long long int myOwningThread = 0; -public: - mutable bool debugflag = false; -#endif - -}; - - -#endif diff --git a/Util/OSM2ODR/src/utils/foxtools/FXWorkerThread.h b/Util/OSM2ODR/src/utils/foxtools/FXWorkerThread.h deleted file mode 100644 index a61b6efb1..000000000 --- a/Util/OSM2ODR/src/utils/foxtools/FXWorkerThread.h +++ /dev/null @@ -1,416 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2004-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file FXWorkerThread.h -/// @author Michael Behrisch -/// @date 2014-07-13 -/// -// A thread class together with a pool and a task for parallelized computation -/****************************************************************************/ - -#ifndef FXWorkerThread_h -#define FXWorkerThread_h - -// #define WORKLOAD_PROFILING -// at which interval report maximum workload of the threads, needs WORKLOAD_PROFILING -// undefine to use summary report only -#define WORKLOAD_INTERVAL 100 -#include - -#include -#include -#include -#ifdef WORKLOAD_PROFILING -#include -#include -#include -#endif -#include - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class FXWorkerThread - * @brief A thread repeatingly calculating incoming tasks - */ -class FXWorkerThread : public FXThread { - -public: - /** - * @class FXWorkerThread::Task - * @brief Abstract superclass of a task to be run with an index to keep track of pending tasks - */ - class Task { - public: - /// @brief Desctructor - virtual ~Task() {}; - - /** @brief Abstract method which in subclasses should contain the computations to be performed. - * - * If there is data to be shared among several tasks (but not among several threads) it can be put in the - * a thread class subclassing the FXWorkerThread. the instance of the thread is then made available - * via the context parameter. - * - * @param[in] context The thread which runs the task - */ - virtual void run(FXWorkerThread* context) = 0; - - /** @brief Sets the running index of this task. - * - * Every task receive an index which is unique among all pending tasks of the same thread pool. - * - * @param[in] newIndex the index to assign - */ - void setIndex(const int newIndex) { - myIndex = newIndex; - } - private: - /// @brief the index of the task, valid only after the task has been added to the pool - int myIndex; - }; - - /** - * @class FXWorkerThread::Pool - * @brief A pool of worker threads which distributes the tasks and collects the results - */ - class Pool { - public: - /** @brief Constructor - * - * May initialize the pool with a given number of workers. - * - * @param[in] numThreads the number of threads to create - */ - Pool(int numThreads = 0) : myPoolMutex(true), myRunningIndex(0), myException(nullptr) -#ifdef WORKLOAD_PROFILING - , myNumBatches(0), myTotalMaxLoad(0.), myTotalSpread(0.) -#endif - { -#ifdef WORKLOAD_PROFILING - long long int timeDiff = 0; - for (int i = 0; i < 100; i++) { - const auto begin = std::chrono::high_resolution_clock::now(); - const auto end = std::chrono::high_resolution_clock::now(); - timeDiff += std::chrono::duration_cast(end - begin).count(); - } - //std::cout << ("Average cost of a timing call (in ns): " + toString(timeDiff / 100.)) << std::endl; -#endif - while (numThreads > 0) { - new FXWorkerThread(*this); - numThreads--; - } - } - - /** @brief Destructor - * - * Stopping and deleting all workers by calling clear. - */ - virtual ~Pool() { - clear(); - } - - /** @brief Stops and deletes all worker threads. - */ - void clear() { - for (FXWorkerThread* const worker : myWorkers) { - delete worker; - } - myWorkers.clear(); - } - - /** @brief Adds the given thread to the pool. - * - * @param[in] w the thread to add - */ - void addWorker(FXWorkerThread* const w) { - myWorkers.push_back(w); - } - - /** @brief Gives a number to the given task and assigns it to the worker with the given index. - * If the index is negative, assign to the next (round robin) one. - * - * @param[in] t the task to add - * @param[in] index index of the worker thread to use or -1 for an arbitrary one - */ - void add(Task* const t, int index = -1) { - if (index < 0) { - index = myRunningIndex % myWorkers.size(); - } -#ifdef WORKLOAD_PROFILING - if (myRunningIndex == 0) { - for (FXWorkerThread* const worker : myWorkers) { - worker->startProfile(); - } - myProfileStart = std::chrono::high_resolution_clock::now(); - } -#endif - t->setIndex(myRunningIndex++); - myWorkers[index]->add(t); - } - - /** @brief Adds the given tasks to the list of finished tasks. - * - * Locks the internal mutex and appends the finished tasks. This is to be called by the worker thread only. - * - * @param[in] tasks the tasks to add - */ - void addFinished(std::list& tasks) { - myMutex.lock(); - myFinishedTasks.splice(myFinishedTasks.end(), tasks); - myCondition.signal(); - myMutex.unlock(); - } - - void setException(ProcessError& e) { - myMutex.lock(); - if (myException == nullptr) { - myException = new ProcessError(e); - } - myMutex.unlock(); - } - - /// @brief waits for all tasks to be finished - void waitAll(const bool deleteFinished = true) { - myMutex.lock(); - while ((int)myFinishedTasks.size() < myRunningIndex) { - myCondition.wait(myMutex); - } -#ifdef WORKLOAD_PROFILING - if (myRunningIndex > 0) { - const auto end = std::chrono::high_resolution_clock::now(); - const long long int elapsed = std::chrono::duration_cast(end - myProfileStart).count(); - double minLoad = std::numeric_limits::max(); - double maxLoad = 0.; - for (FXWorkerThread* const worker : myWorkers) { - const double load = worker->endProfile(elapsed); - minLoad = MIN2(minLoad, load); - maxLoad = MAX2(maxLoad, load); - } -#ifdef WORKLOAD_INTERVAL - myTotalMaxLoad += maxLoad; - myTotalSpread += maxLoad / minLoad; - myNumBatches++; - if (myNumBatches % WORKLOAD_INTERVAL == 0) { - WRITE_MESSAGE(toString(myFinishedTasks.size()) + " tasks, average maximum load: " + toString(myTotalMaxLoad / WORKLOAD_INTERVAL) + ", average spread: " + toString(myTotalSpread / WORKLOAD_INTERVAL)); - myTotalMaxLoad = 0.; - myTotalSpread = 0.; - } -#endif - } -#endif - if (deleteFinished) { - for (Task* task : myFinishedTasks) { - delete task; - } - } - ProcessError* toRaise = myException; - myException = nullptr; - myFinishedTasks.clear(); - myRunningIndex = 0; - myMutex.unlock(); - if (toRaise != nullptr) { - throw* toRaise; - } - } - - /** @brief Checks whether there are currently more pending tasks than threads. - * - * This is only a rough estimate because the tasks are already assigned and there could be an idle thread even though the - * number of tasks is large. - * - * @return whether there are enough tasks to let all threads work - */ - bool isFull() const { - return myRunningIndex - (int)myFinishedTasks.size() >= size(); - } - - /** @brief Returns the number of threads in the pool. - * - * @return the number of threads - */ - int size() const { - return (int)myWorkers.size(); - } - - /// @brief locks the pool mutex - void lock() { - myPoolMutex.lock(); - } - - /// @brief unlocks the pool mutex - void unlock() { - myPoolMutex.unlock(); - } - - const std::vector& getWorkers() { - return myWorkers; - } - private: - /// @brief the current worker threads - std::vector myWorkers; - /// @brief the internal mutex for the task list - FXMutex myMutex; - /// @brief the pool mutex for external sync - FXMutex myPoolMutex; - /// @brief the semaphore to wait on for finishing all tasks - FXCondition myCondition; - /// @brief list of finished tasks - std::list myFinishedTasks; - /// @brief the running index for the next task - int myRunningIndex; - /// @brief the exception from a child thread - ProcessError* myException; -#ifdef WORKLOAD_PROFILING - /// @brief the number of finished batch runs - int myNumBatches; - /// @brief the sum over the maximum loads - double myTotalMaxLoad; - /// @brief the sum over the load spreads - double myTotalSpread; - /// @brief the time when profiling started - std::chrono::high_resolution_clock::time_point myProfileStart; -#endif - }; - -public: - /** @brief Constructor - * - * Adds the thread to the given pool and starts it. - * - * @param[in] pool the pool for this thread - */ - FXWorkerThread(Pool& pool): FXThread(), myPool(pool), myStopped(false) -#ifdef WORKLOAD_PROFILING - , myCounter(0), myBusyTime(0), myTotalBusyTime(0), myTotalTime(0) -#endif - { - pool.addWorker(this); - start(); - } - - /** @brief Destructor - * - * Stops the thread by calling stop. - */ - virtual ~FXWorkerThread() { - stop(); -#ifdef WORKLOAD_PROFILING - const double load = 100. * myTotalBusyTime / myTotalTime; - WRITE_MESSAGE("Thread " + toString((long long int)this) + " ran " + toString(myCounter) + - " tasks and had a load of " + toString(load) + "% (" + toString(myTotalBusyTime) + - "us / " + toString(myTotalTime) + "us), " + toString(myTotalBusyTime / (double)myCounter) + " per task."); -#endif - } - - /** @brief Adds the given task to this thread to be calculated - * - * @param[in] t the task to add - */ - void add(Task* t) { - myMutex.lock(); - myTasks.push_back(t); - myCondition.signal(); - myMutex.unlock(); - } - - /** @brief Main execution method of this thread. - * - * Checks for new tasks, calculates them and puts them in the finished list of the pool until being stopped. - * - * @return always 0 - */ - FXint run() { - while (!myStopped) { - myMutex.lock(); - while (!myStopped && myTasks.empty()) { - myCondition.wait(myMutex); - } - if (myStopped) { - myMutex.unlock(); - break; - } - myCurrentTasks.splice(myCurrentTasks.end(), myTasks); - myMutex.unlock(); - try { - for (Task* const t : myCurrentTasks) { -#ifdef WORKLOAD_PROFILING - const auto before = std::chrono::high_resolution_clock::now(); -#endif - t->run(this); -#ifdef WORKLOAD_PROFILING - const auto after = std::chrono::high_resolution_clock::now(); - myBusyTime += std::chrono::duration_cast(after - before).count(); - myCounter++; -#endif - } - } catch (ProcessError& e) { - myPool.setException(e); - } - myPool.addFinished(myCurrentTasks); - } - return 0; - } - - /** @brief Stops the thread - * - * The currently running task will be finished but all further tasks are discarded. - */ - void stop() { - myMutex.lock(); - myStopped = true; - myCondition.signal(); - myMutex.unlock(); - join(); - } - -#ifdef WORKLOAD_PROFILING - void startProfile() { - myBusyTime = 0; - } - - double endProfile(const long long int time) { - myTotalTime += time; - myTotalBusyTime += myBusyTime; - return time == 0 ? 100. : 100. * myBusyTime / time; - } -#endif - -private: - /// @brief the pool for this thread - Pool& myPool; - /// @brief the mutex for the task list - FXMutex myMutex; - /// @brief the semaphore when waiting for new tasks - FXCondition myCondition; - /// @brief the list of pending tasks - std::list myTasks; - /// @brief the list of tasks which are currently calculated - std::list myCurrentTasks; - /// @brief whether we are still running - bool myStopped; -#ifdef WORKLOAD_PROFILING - /// @brief counting completed tasks - int myCounter; - /// @brief the time spent in calculations during the current batch - long long int myBusyTime; - /// @brief the total busy time - long long int myTotalBusyTime; - /// @brief the total time while anyone had tasks - long long int myTotalTime; -#endif -}; - - -#endif diff --git a/Util/OSM2ODR/src/utils/geom/AbstractPoly.h b/Util/OSM2ODR/src/utils/geom/AbstractPoly.h deleted file mode 100644 index c43f8c1f2..000000000 --- a/Util/OSM2ODR/src/utils/geom/AbstractPoly.h +++ /dev/null @@ -1,55 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file AbstractPoly.h -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Sept 2002 -/// -// The base class for polygons -/****************************************************************************/ -#pragma once -#include - -#include "Position.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * - */ -class AbstractPoly { -public: - /// @brief constructor - AbstractPoly() { } - - /// @brief copy constructor - AbstractPoly(const AbstractPoly&) { } - - /// @brief destructor - virtual ~AbstractPoly() { } - - /// @brief Returns whether the AbstractPoly the given coordinate - virtual bool around(const Position& p, double offset = 0) const = 0; - - /// @brief Returns whether the AbstractPoly overlaps with the given polygon - virtual bool overlapsWith(const AbstractPoly& poly, double offset = 0) const = 0; - - /// @brief Returns whether the AbstractPoly is partially within the given polygon - virtual bool partialWithin(const AbstractPoly& poly, double offset = 0) const = 0; - - /// @brief Returns whether the AbstractPoly crosses the given line - virtual bool crosses(const Position& p1, const Position& p2) const = 0; -}; diff --git a/Util/OSM2ODR/src/utils/geom/Boundary.cpp b/Util/OSM2ODR/src/utils/geom/Boundary.cpp deleted file mode 100644 index 9dd2a52b7..000000000 --- a/Util/OSM2ODR/src/utils/geom/Boundary.cpp +++ /dev/null @@ -1,377 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file Boundary.cpp -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date Sept 2002 -/// -// A class that stores the 2D geometrical boundary -/****************************************************************************/ -#include -#include - -#include "GeomHelper.h" -#include "Boundary.h" -#include "PositionVector.h" -#include "Position.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -Boundary::Boundary() - : myXmin(10000000000.0), myXmax(-10000000000.0), - myYmin(10000000000.0), myYmax(-10000000000.0), - myZmin(10000000000.0), myZmax(-10000000000.0), - myWasInitialised(false) {} - - -Boundary::Boundary(double x1, double y1, double x2, double y2) - : myXmin(10000000000.0), myXmax(-10000000000.0), - myYmin(10000000000.0), myYmax(-10000000000.0), - myZmin(10000000000.0), myZmax(-10000000000.0), - myWasInitialised(false) { - add(x1, y1); - add(x2, y2); -} - - -Boundary::Boundary(double x1, double y1, double z1, double x2, double y2, double z2) - : myXmin(10000000000.0), myXmax(-10000000000.0), - myYmin(10000000000.0), myYmax(-10000000000.0), - myZmin(10000000000.0), myZmax(-10000000000.0), - myWasInitialised(false) { - add(x1, y1, z1); - add(x2, y2, z2); -} - - -Boundary::~Boundary() {} - - -void -Boundary::reset() { - myXmin = 10000000000.0; - myXmax = -10000000000.0; - myYmin = 10000000000.0; - myYmax = -10000000000.0; - myZmin = 10000000000.0; - myZmax = -10000000000.0; - myWasInitialised = false; -} - - -void -Boundary::add(double x, double y, double z) { - if (!myWasInitialised) { - myYmin = y; - myYmax = y; - myXmin = x; - myXmax = x; - myZmin = z; - myZmax = z; - } else { - myXmin = myXmin < x ? myXmin : x; - myXmax = myXmax > x ? myXmax : x; - myYmin = myYmin < y ? myYmin : y; - myYmax = myYmax > y ? myYmax : y; - myZmin = myZmin < z ? myZmin : z; - myZmax = myZmax > z ? myZmax : z; - } - myWasInitialised = true; -} - - -void -Boundary::add(const Position& p) { - add(p.x(), p.y(), p.z()); -} - - -void -Boundary::add(const Boundary& p) { - add(p.xmin(), p.ymin(), p.zmin()); - add(p.xmax(), p.ymax(), p.zmax()); -} - - -Position -Boundary::getCenter() const { - return Position((myXmin + myXmax) / (double) 2.0, (myYmin + myYmax) / (double) 2.0, (myZmin + myZmax) / (double) 2.0); -} - - -double -Boundary::xmin() const { - return myXmin; -} - - -double -Boundary::xmax() const { - return myXmax; -} - - -double -Boundary::ymin() const { - return myYmin; -} - - -double -Boundary::ymax() const { - return myYmax; -} - - -double -Boundary::zmin() const { - return myZmin; -} - - -double -Boundary::zmax() const { - return myZmax; -} - - -double -Boundary::getWidth() const { - return myXmax - myXmin; -} - - -double -Boundary::getHeight() const { - return myYmax - myYmin; -} - - -double -Boundary::getZRange() const { - return myZmax - myZmin; -} - - -bool -Boundary::around(const Position& p, double offset) const { - return - (p.x() <= myXmax + offset && p.x() >= myXmin - offset) && - (p.y() <= myYmax + offset && p.y() >= myYmin - offset) && - (p.z() <= myZmax + offset && p.z() >= myZmin - offset); -} - - -bool -Boundary::overlapsWith(const AbstractPoly& p, double offset) const { - if ( - // check whether one of my points lies within the given poly - partialWithin(p, offset) || - // check whether the polygon lies within me - p.partialWithin(*this, offset)) { - return true; - } - // check whether the bounderies cross - return - p.crosses(Position(myXmax + offset, myYmax + offset), Position(myXmin - offset, myYmax + offset)) - || - p.crosses(Position(myXmin - offset, myYmax + offset), Position(myXmin - offset, myYmin - offset)) - || - p.crosses(Position(myXmin - offset, myYmin - offset), Position(myXmax + offset, myYmin - offset)) - || - p.crosses(Position(myXmax + offset, myYmin - offset), Position(myXmax + offset, myYmax + offset)); -} - - -bool -Boundary::crosses(const Position& p1, const Position& p2) const { - const PositionVector line(p1, p2); - return - line.intersects(Position(myXmax, myYmax), Position(myXmin, myYmax)) - || - line.intersects(Position(myXmin, myYmax), Position(myXmin, myYmin)) - || - line.intersects(Position(myXmin, myYmin), Position(myXmax, myYmin)) - || - line.intersects(Position(myXmax, myYmin), Position(myXmax, myYmax)); -} - - -bool -Boundary::isInitialised() const { - return myWasInitialised; -} - - -double -Boundary::distanceTo2D(const Position& p) const { - const double leftDist = myXmin - p.x(); - const double rightDist = p.x() - myXmax; - const double bottomDist = myYmin - p.y(); - const double topDist = p.y() - myYmax; - if (leftDist > 0.) { - if (bottomDist > 0.) { - return sqrt(leftDist * leftDist + bottomDist * bottomDist); - } - if (topDist > 0.) { - return sqrt(leftDist * leftDist + topDist * topDist); - } - return leftDist; - } - if (rightDist > 0.) { - if (bottomDist > 0.) { - return sqrt(rightDist * rightDist + bottomDist * bottomDist); - } - if (topDist > 0.) { - return sqrt(rightDist * rightDist + topDist * topDist); - } - return rightDist; - } - if (bottomDist > 0) { - return bottomDist; - } - if (topDist > 0) { - return topDist; - } - return 0.; -} - - -double -Boundary::distanceTo2D(const Boundary& b) const { - const double leftDist = myXmin - b.myXmax; - const double rightDist = b.myXmin - myXmax; - const double bottomDist = myYmin - b.myYmax; - const double topDist = b.myYmin - myYmax; - if (leftDist > 0.) { - if (bottomDist > 0.) { - return sqrt(leftDist * leftDist + bottomDist * bottomDist); - } - if (topDist > 0.) { - return sqrt(leftDist * leftDist + topDist * topDist); - } - return leftDist; - } - if (rightDist > 0.) { - if (bottomDist > 0.) { - return sqrt(rightDist * rightDist + bottomDist * bottomDist); - } - if (topDist > 0.) { - return sqrt(rightDist * rightDist + topDist * topDist); - } - return rightDist; - } - if (bottomDist > 0) { - return bottomDist; - } - if (topDist > 0) { - return topDist; - } - return 0.; -} - - -bool -Boundary::partialWithin(const AbstractPoly& poly, double offset) const { - return - poly.around(Position(myXmax, myYmax), offset) || - poly.around(Position(myXmin, myYmax), offset) || - poly.around(Position(myXmax, myYmin), offset) || - poly.around(Position(myXmin, myYmin), offset); -} - - -Boundary& -Boundary::grow(double by) { - myXmax += by; - myYmax += by; - myXmin -= by; - myYmin -= by; - return *this; -} - -void -Boundary::growWidth(double by) { - myXmin -= by; - myXmax += by; -} - - -void -Boundary::growHeight(double by) { - myYmin -= by; - myYmax += by; -} - -void -Boundary::flipY() { - myYmin *= -1.0; - myYmax *= -1.0; - double tmp = myYmin; - myYmin = myYmax; - myYmax = tmp; -} - - - -std::ostream& -operator<<(std::ostream& os, const Boundary& b) { - os << b.myXmin << "," << b.myYmin << "," << b.myXmax << "," << b.myYmax; - return os; -} - - -bool -Boundary::operator==(const Boundary& b) const { - return ( - myXmin == b.myXmin && - myXmax == b.myXmax && - myYmin == b.myYmin && - myYmax == b.myYmax && - myZmin == b.myZmin && - myZmax == b.myZmax && - myWasInitialised == b.myWasInitialised); -} - - -bool -Boundary::operator!=(const Boundary& b) const { - return !(*this == b); -} - - -void -Boundary::set(double xmin, double ymin, double xmax, double ymax) { - myXmin = xmin; - myYmin = ymin; - myXmax = xmax; - myYmax = ymax; -} - - -void -Boundary::moveby(double x, double y, double z) { - myXmin += x; - myYmin += y; - myZmin += z; - myXmax += x; - myYmax += y; - myZmax += z; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/utils/geom/Boundary.h b/Util/OSM2ODR/src/utils/geom/Boundary.h deleted file mode 100644 index 7b191ef64..000000000 --- a/Util/OSM2ODR/src/utils/geom/Boundary.h +++ /dev/null @@ -1,154 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file Boundary.h -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date Sept 2002 -/// -// A class that stores a 2D geometrical boundary -/****************************************************************************/ -#pragma once -#include - -#include -#include - -#include "AbstractPoly.h" -#include "Position.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class Boundary - * @brief A class that stores a 2D geometrical boundary - */ -class Boundary : public AbstractPoly { -public: - /// @brief Constructor - the boundary is unset - Boundary(); - - /// @brief Constructor - the boundary will be build using the given values - Boundary(double x1, double y1, double x2, double y2); - - /// @brief Constructor - the boundary will be build using the given values including Z - Boundary(double x1, double y1, double z1, double x2, double y2, double z2); - - /// @brief Destructor - ~Boundary(); - - /// @brief Resets the boundary - void reset(); - - /// @brief Makes the boundary include the given coordinate - void add(double x, double y, double z = 0); - - /// @brief Makes the boundary include the given coordinate - void add(const Position& p); - - /// @brief Makes the boundary include the given boundary - void add(const Boundary& p); - - /// @brief Returns the center of the boundary - Position getCenter() const; - - /// @brief Returns minimum x-coordinate - double xmin() const; - - /// @brief Returns maximum x-coordinate - double xmax() const; - - /// @brief Returns minimum y-coordinate - double ymin() const; - - /// @brief Returns maximum y-coordinate - double ymax() const; - - /// @brief Returns minimum z-coordinate - double zmin() const; - - /// @brief Returns maximum z-coordinate - double zmax() const; - - /// @brief Returns the width of the boudary (x-axis) - double getWidth() const; - - /// @brief Returns the height of the boundary (y-axis) - double getHeight() const; - - /// @brief Returns the elevation range of the boundary (z-axis) - double getZRange() const; - - /// @name inherited from AbstractPoly - /// @{ - /// @brief Returns whether the boundary contains the given coordinate - bool around(const Position& p, double offset = 0) const; - - /// @brief Returns whether the boundary overlaps with the given polygon - bool overlapsWith(const AbstractPoly& poly, double offset = 0) const; - - /// @brief Returns whether the boundary is partially within the given polygon - bool partialWithin(const AbstractPoly& poly, double offset = 0) const; - - /// @brief Returns whether the boundary crosses the given line - bool crosses(const Position& p1, const Position& p2) const; - /// @} - - /// @brief check if Boundary is Initialised - bool isInitialised() const; - - /// @brief returns the euclidean distance in the x-y-plane - double distanceTo2D(const Position& p) const; - - /// @brief returns the euclidean distance in the x-y-plane - double distanceTo2D(const Boundary& b) const; - - /**@brief extends the boundary by the given amount - * @return a reference to the instance for further use - */ - Boundary& grow(double by); - - /// @brief Increases the width of the boundary (x-axis) - void growWidth(double by); - - /// @brief Increases the height of the boundary (y-axis) - void growHeight(double by); - - /// @brief flips ymin and ymax - void flipY(); - - /// @brief Sets the boundary to the given values - void set(double xmin, double ymin, double xmax, double ymax); - - /// @brief Moves the boundary by the given amount - void moveby(double x, double y, double z = 0); - - /// @brief Output operator - friend std::ostream& operator<<(std::ostream& os, const Boundary& b); - - /// @brief Comparison operator equal - bool operator==(const Boundary& b) const; - - /// @brief Comparison operator not equal - bool operator!=(const Boundary& b) const; - -private: - /// @brief The boundaries - double myXmin, myXmax, myYmin, myYmax, myZmin, myZmax; - - /// @brief Information whether the boundary was initialised - bool myWasInitialised; -}; diff --git a/Util/OSM2ODR/src/utils/geom/Bresenham.cpp b/Util/OSM2ODR/src/utils/geom/Bresenham.cpp deleted file mode 100644 index bfd4b2423..000000000 --- a/Util/OSM2ODR/src/utils/geom/Bresenham.cpp +++ /dev/null @@ -1,52 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file Bresenham.cpp -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Fri, 07 Jun 2002 -/// -// A class to realise a uniform n:m - relationship using the -/****************************************************************************/ -#include - -#include -#include -#include "Bresenham.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -void -Bresenham::compute(BresenhamCallBack* callBack, const int val1, const int val2) { - const int smaller = MIN2(val1, val2); - const int greater = MAX2(val1, val2); - int pos = 0; - int c = smaller; - for (int i = 0; i < greater; i++) { - if (smaller == val1) { - callBack->execute(pos, i); - } else { - callBack->execute(i, pos); - } - c += 2 * smaller; - if (c >= 2 * greater) { - pos++; - c -= 2 * greater; - } - } -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/utils/geom/Bresenham.h b/Util/OSM2ODR/src/utils/geom/Bresenham.h deleted file mode 100644 index 2dff640ca..000000000 --- a/Util/OSM2ODR/src/utils/geom/Bresenham.h +++ /dev/null @@ -1,59 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file Bresenham.h -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Mon, 17 Dec 2001 -/// -// A class to realise a uniform n:m - relationship using the -/****************************************************************************/ -#pragma once -#include - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * The class' only static method "execute" obtains a callback object and - * performs the computation of the n:m - relationship - */ -class Bresenham { -public: - /** - * BresenhamCallBack - * This class is the base interface-describing class for a callback class - * for the bresenham-function. - * Derived classes must implement the execute-method which is called - * on every bresenham-step - */ - class BresenhamCallBack { - public: - /** constuctor */ - BresenhamCallBack() { } - - /** destructor */ - virtual ~BresenhamCallBack() { } - - /** called when a bresenham step has been computed */ - virtual void execute(const int val1, const int val2) = 0; - }; - -public: - /** compute the bresenham - interpolation between both values - the higher number is increased by one for each step while the smaller - is increased by smaller/higher. - In each step, the callback is executed. */ - static void compute(BresenhamCallBack* callBack, const int val1, const int val2); -}; diff --git a/Util/OSM2ODR/src/utils/geom/CMakeLists.txt b/Util/OSM2ODR/src/utils/geom/CMakeLists.txt deleted file mode 100644 index 92c4f7458..000000000 --- a/Util/OSM2ODR/src/utils/geom/CMakeLists.txt +++ /dev/null @@ -1,20 +0,0 @@ -set(utils_geom_STAT_SRCS - AbstractPoly.h - Boundary.cpp - Boundary.h - Bresenham.cpp - Bresenham.h - GeomConvHelper.cpp - GeomConvHelper.h - GeoConvHelper.cpp - GeoConvHelper.h - GeomHelper.cpp - GeomHelper.h - Position.cpp - Position.h - PositionVector.cpp - PositionVector.h -) - -add_library(utils_geom STATIC ${utils_geom_STAT_SRCS}) -set_property(TARGET utils_geom PROPERTY PROJECT_LABEL "z_utils_geom") diff --git a/Util/OSM2ODR/src/utils/geom/GeoConvHelper.cpp b/Util/OSM2ODR/src/utils/geom/GeoConvHelper.cpp deleted file mode 100644 index 45c6c4071..000000000 --- a/Util/OSM2ODR/src/utils/geom/GeoConvHelper.cpp +++ /dev/null @@ -1,572 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file GeoConvHelper.cpp -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date 2006-08-01 -/// -// static methods for processing the coordinates conversion for the current net -/****************************************************************************/ -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "GeoConvHelper.h" - - -// =========================================================================== -// static member variables -// =========================================================================== - -GeoConvHelper GeoConvHelper::myProcessing("!", Position(), Boundary(), Boundary()); -GeoConvHelper GeoConvHelper::myLoaded("!", Position(), Boundary(), Boundary()); -GeoConvHelper GeoConvHelper::myFinal("!", Position(), Boundary(), Boundary()); -int GeoConvHelper::myNumLoaded = 0; - -// =========================================================================== -// method definitions -// =========================================================================== - -GeoConvHelper::GeoConvHelper(const std::string& proj, const Position& offset, - const Boundary& orig, const Boundary& conv, double scale, double rot, bool inverse, bool flatten): - myProjString(proj), -#ifdef PROJ_API_FILE - myProjection(nullptr), - myInverseProjection(nullptr), - myGeoProjection(nullptr), -#endif - myOffset(offset), - myGeoScale(scale), - mySin(sin(DEG2RAD(-rot))), // rotate clockwise - myCos(cos(DEG2RAD(-rot))), - myProjectionMethod(NONE), - myUseInverseProjection(inverse), - myFlatten(flatten), - myOrigBoundary(orig), - myConvBoundary(conv) { - if (proj == "!") { - myProjectionMethod = NONE; - } else if (proj == "-") { - myProjectionMethod = SIMPLE; - } else if (proj == "UTM") { - myProjectionMethod = UTM; - } else if (proj == "DHDN") { - myProjectionMethod = DHDN; - } else if (proj == "DHDN_UTM") { - myProjectionMethod = DHDN_UTM; -#ifdef PROJ_API_FILE - } else { - myProjectionMethod = PROJ; -#ifdef PROJ_VERSION_MAJOR - myProjection = proj_create(PJ_DEFAULT_CTX, proj.c_str()); -#else - myProjection = pj_init_plus(proj.c_str()); -#endif - if (myProjection == nullptr) { - // !!! check pj_errno - throw ProcessError("Could not build projection!"); - } -#endif - } -} - - -GeoConvHelper::~GeoConvHelper() { -#ifdef PROJ_API_FILE - if (myProjection != nullptr) { -#ifdef PROJ_VERSION_MAJOR - proj_destroy(myProjection); -#else - pj_free(myProjection); -#endif - } - if (myInverseProjection != nullptr) { -#ifdef PROJ_VERSION_MAJOR - proj_destroy(myInverseProjection); -#else - pj_free(myInverseProjection); -#endif - } - if (myGeoProjection != nullptr) { -#ifdef PROJ_VERSION_MAJOR - proj_destroy(myGeoProjection); -#else - pj_free(myGeoProjection); -#endif - } -#endif -} - -bool -GeoConvHelper::operator==(const GeoConvHelper& o) const { - return ( - myProjString == o.myProjString && - myOffset == o.myOffset && - myProjectionMethod == o.myProjectionMethod && - myOrigBoundary == o.myOrigBoundary && - myConvBoundary == o.myConvBoundary && - myGeoScale == o.myGeoScale && - myCos == o.myCos && - mySin == o.mySin && - myUseInverseProjection == o.myUseInverseProjection && - myFlatten == o.myFlatten - ); -} - -GeoConvHelper& -GeoConvHelper::operator=(const GeoConvHelper& orig) { - myProjString = orig.myProjString; - myOffset = orig.myOffset; - myProjectionMethod = orig.myProjectionMethod; - myOrigBoundary = orig.myOrigBoundary; - myConvBoundary = orig.myConvBoundary; - myGeoScale = orig.myGeoScale; - myCos = orig.myCos; - mySin = orig.mySin; - myUseInverseProjection = orig.myUseInverseProjection; - myFlatten = orig.myFlatten; -#ifdef PROJ_API_FILE - if (myProjection != nullptr) { -#ifdef PROJ_VERSION_MAJOR - proj_destroy(myProjection); -#else - pj_free(myProjection); -#endif - myProjection = nullptr; - } - if (myInverseProjection != nullptr) { -#ifdef PROJ_VERSION_MAJOR - proj_destroy(myInverseProjection); -#else - pj_free(myInverseProjection); -#endif - myInverseProjection = nullptr; - } - if (myGeoProjection != nullptr) { -#ifdef PROJ_VERSION_MAJOR - proj_destroy(myGeoProjection); -#else - pj_free(myGeoProjection); -#endif - myGeoProjection = nullptr; - } - if (orig.myProjection != nullptr) { -#ifdef PROJ_VERSION_MAJOR - myProjection = proj_create(PJ_DEFAULT_CTX, orig.myProjString.c_str()); -#else - myProjection = pj_init_plus(orig.myProjString.c_str()); -#endif - } - if (orig.myInverseProjection != nullptr) { -#ifdef PROJ_VERSION_MAJOR - myInverseProjection = orig.myInverseProjection; -#else - myInverseProjection = pj_init_plus(pj_get_def(orig.myInverseProjection, 0)); -#endif - } - if (orig.myGeoProjection != nullptr) { -#ifdef PROJ_VERSION_MAJOR - myGeoProjection = orig.myGeoProjection; -#else - myGeoProjection = pj_init_plus(pj_get_def(orig.myGeoProjection, 0)); -#endif - } -#endif - return *this; -} - - -bool -GeoConvHelper::init(OptionsCont& oc) { - std::string proj = "!"; // the default - double scale = oc.getFloat("proj.scale"); - double rot = oc.getFloat("proj.rotate"); - Position offset = Position(oc.getFloat("offset.x"), oc.getFloat("offset.y"), oc.getFloat("offset.z")); - bool inverse = oc.exists("proj.inverse") && oc.getBool("proj.inverse"); - bool flatten = oc.exists("flatten") && oc.getBool("flatten"); - - if (oc.getBool("simple-projection")) { - proj = "-"; - } - -#ifdef PROJ_API_FILE - if (oc.getBool("proj.inverse") && oc.getString("proj") == "!") { - WRITE_ERROR("Inverse projection works only with explicit proj parameters."); - return false; - } - unsigned numProjections = oc.getBool("simple-projection") + oc.getBool("proj.utm") + oc.getBool("proj.dhdn") + oc.getBool("proj.dhdnutm") + (oc.getString("proj").length() > 1); - if (numProjections > 1) { - WRITE_ERROR("The projection method needs to be uniquely defined."); - return false; - } - - if (oc.getBool("proj.utm")) { - proj = "UTM"; - } else if (oc.getBool("proj.dhdn")) { - proj = "DHDN"; - } else if (oc.getBool("proj.dhdnutm")) { - proj = "DHDN_UTM"; - } else if (!oc.isDefault("proj")) { - proj = oc.getString("proj"); - } -#endif - myProcessing = GeoConvHelper(proj, offset, Boundary(), Boundary(), scale, rot, inverse, flatten); - myFinal = myProcessing; - return true; -} - - -void -GeoConvHelper::init(const std::string& proj, const Position& offset, const Boundary& orig, - const Boundary& conv, double scale) { - myProcessing = GeoConvHelper(proj, offset, orig, conv, scale); - myFinal = myProcessing; -} - - -void -GeoConvHelper::addProjectionOptions(OptionsCont& oc) { - oc.addOptionSubTopic("Projection"); - - oc.doRegister("simple-projection", new Option_Bool(false)); - oc.addSynonyme("simple-projection", "proj.simple", true); - oc.addDescription("simple-projection", "Projection", "Uses a simple method for projection"); - - oc.doRegister("proj.scale", new Option_Float(1.0)); - oc.addDescription("proj.scale", "Projection", "Scaling factor for input coordinates"); - - oc.doRegister("proj.rotate", new Option_Float(0.0)); - oc.addDescription("proj.rotate", "Projection", "Rotation (clockwise degrees) for input coordinates"); - -#ifdef PROJ_API_FILE - oc.doRegister("proj.utm", new Option_Bool(false)); - oc.addDescription("proj.utm", "Projection", "Determine the UTM zone (for a universal transversal mercator projection based on the WGS84 ellipsoid)"); - - oc.doRegister("proj.dhdn", new Option_Bool(false)); - oc.addDescription("proj.dhdn", "Projection", "Determine the DHDN zone (for a transversal mercator projection based on the bessel ellipsoid, \"Gauss-Krueger\")"); - - oc.doRegister("proj", new Option_String("!")); - oc.addDescription("proj", "Projection", "Uses STR as proj.4 definition for projection"); - - oc.doRegister("proj.inverse", new Option_Bool(false)); - oc.addDescription("proj.inverse", "Projection", "Inverses projection"); - - oc.doRegister("proj.dhdnutm", new Option_Bool(false)); - oc.addDescription("proj.dhdnutm", "Projection", "Convert from Gauss-Krueger to UTM"); -#endif // PROJ_API_FILE -} - - -bool -GeoConvHelper::usingGeoProjection() const { - return myProjectionMethod != NONE; -} - - -bool -GeoConvHelper::usingInverseGeoProjection() const { - return myUseInverseProjection; -} - - -void -GeoConvHelper::cartesian2geo(Position& cartesian) const { - cartesian.sub(getOffsetBase()); - if (myProjectionMethod == NONE) { - return; - } - if (myProjectionMethod == SIMPLE) { - const double y = cartesian.y() / 111136.; - const double x = cartesian.x() / 111320. / cos(DEG2RAD(y)); - cartesian.set(x, y); - return; - } -#ifdef PROJ_API_FILE -#ifdef PROJ_VERSION_MAJOR - PJ_COORD c; - c.xy.x = cartesian.x(); - c.xy.y = cartesian.y(); - c = proj_trans(myProjection, PJ_INV, c); - cartesian.set(proj_todeg(c.lp.lam), proj_todeg(c.lp.phi)); -#else - projUV p; - p.u = cartesian.x(); - p.v = cartesian.y(); - p = pj_inv(p, myProjection); - //!!! check pj_errno - p.u *= RAD_TO_DEG; - p.v *= RAD_TO_DEG; - cartesian.set((double) p.u, (double) p.v); -#endif -#endif -} - - -bool -GeoConvHelper::x2cartesian(Position& from, bool includeInBoundary) { - if (includeInBoundary) { - myOrigBoundary.add(from); - } - // init projection parameter on first use -#ifdef PROJ_API_FILE - if (myProjection == nullptr) { - double x = from.x() * myGeoScale; - switch (myProjectionMethod) { - case DHDN_UTM: { - int zone = (int)((x - 500000.) / 1000000.); - if (zone < 1 || zone > 5) { - WRITE_WARNING("Attempt to initialize DHDN_UTM-projection on invalid longitude " + toString(x)); - return false; - } - myProjString = "+proj=tmerc +lat_0=0 +lon_0=" + toString(3 * zone) + - " +k=1 +x_0=" + toString(zone * 1000000 + 500000) + - " +y_0=0 +ellps=bessel +datum=potsdam +units=m +no_defs"; -#ifdef PROJ_VERSION_MAJOR - myInverseProjection = proj_create(PJ_DEFAULT_CTX, myProjString.c_str()); - myGeoProjection = proj_create(PJ_DEFAULT_CTX, "+proj=latlong +datum=WGS84"); -#else - myInverseProjection = pj_init_plus(myProjString.c_str()); - myGeoProjection = pj_init_plus("+proj=latlong +datum=WGS84"); -#endif - //!!! check pj_errno - x = ((x - 500000.) / 1000000.) * 3; // continues with UTM - } - FALLTHROUGH; - case UTM: { - int zone = (int)(x + 180) / 6 + 1; - myProjString = "+proj=utm +zone=" + toString(zone) + - " +ellps=WGS84 +datum=WGS84 +units=m +no_defs"; -#ifdef PROJ_VERSION_MAJOR - myProjection = proj_create(PJ_DEFAULT_CTX, myProjString.c_str()); -#else - myProjection = pj_init_plus(myProjString.c_str()); -#endif - //!!! check pj_errno - } - break; - case DHDN: { - int zone = (int)(x / 3); - if (zone < 1 || zone > 5) { - WRITE_WARNING("Attempt to initialize DHDN-projection on invalid longitude " + toString(x)); - return false; - } - myProjString = "+proj=tmerc +lat_0=0 +lon_0=" + toString(3 * zone) + - " +k=1 +x_0=" + toString(zone * 1000000 + 500000) + - " +y_0=0 +ellps=bessel +datum=potsdam +units=m +no_defs"; -#ifdef PROJ_VERSION_MAJOR - myProjection = proj_create(PJ_DEFAULT_CTX, myProjString.c_str()); -#else - myProjection = pj_init_plus(myProjString.c_str()); -#endif - //!!! check pj_errno - } - break; - default: - break; - } - } - if (myInverseProjection != nullptr) { -#ifdef PROJ_VERSION_MAJOR - PJ_COORD c; - c.xy.x = from.x(); - c.xy.y = from.y(); - c = proj_trans(myInverseProjection, PJ_INV, c); - from.set(proj_todeg(c.lp.lam), proj_todeg(c.lp.phi)); -#else - double x = from.x(); - double y = from.y(); - if (pj_transform(myInverseProjection, myGeoProjection, 1, 1, &x, &y, nullptr)) { - WRITE_WARNING("Could not transform (" + toString(x) + "," + toString(y) + ")"); - } - from.set(double(x * RAD_TO_DEG), double(y * RAD_TO_DEG)); -#endif - } -#endif - // perform conversion - bool ok = x2cartesian_const(from); - if (ok) { - if (includeInBoundary) { - myConvBoundary.add(from); - } - } - return ok; -} - - -bool -GeoConvHelper::x2cartesian_const(Position& from) const { - double x2 = from.x() * myGeoScale; - double y2 = from.y() * myGeoScale; - double x = x2 * myCos - y2 * mySin; - double y = x2 * mySin + y2 * myCos; - if (myProjectionMethod == NONE) { - // do nothing - } else if (myUseInverseProjection) { - cartesian2geo(from); - } else { - if (x > 180.1 || x < -180.1) { - WRITE_WARNING("Invalid longitude " + toString(x)); - return false; - } - if (y > 90.1 || y < -90.1) { - WRITE_WARNING("Invalid latitude " + toString(y)); - return false; - } -#ifdef PROJ_API_FILE - if (myProjection != nullptr) { -#ifdef PROJ_VERSION_MAJOR - PJ_COORD c; - c.lp.lam = proj_torad(x); - c.lp.phi = proj_torad(y); - c = proj_trans(myProjection, PJ_FWD, c); - //!!! check pj_errno - x = c.xy.x; - y = c.xy.y; -#else - projUV p; - p.u = x * DEG_TO_RAD; - p.v = y * DEG_TO_RAD; - p = pj_fwd(p, myProjection); - //!!! check pj_errno - x = p.u; - y = p.v; -#endif - } -#endif - if (myProjectionMethod == SIMPLE) { - x *= 111320. * cos(DEG2RAD(y)); - y *= 111136.; - //!!! recheck whether the axes are mirrored - } - } - if (x > std::numeric_limits::max() || - y > std::numeric_limits::max()) { - return false; - } - from.set(x, y); - from.add(myOffset); - if (myFlatten) { - from.setz(0); - } - return true; -} - - -void -GeoConvHelper::moveConvertedBy(double x, double y) { - myOffset.add(x, y); - myConvBoundary.moveby(x, y); -} - - -const Boundary& -GeoConvHelper::getOrigBoundary() const { - return myOrigBoundary; -} - - -const Boundary& -GeoConvHelper::getConvBoundary() const { - return myConvBoundary; -} - - -const Position -GeoConvHelper::getOffset() const { - return myOffset; -} - - -const Position -GeoConvHelper::getOffsetBase() const { - return myOffset; -} - - -const std::string& -GeoConvHelper::getProjString() const { - return myProjString; -} - - -void -GeoConvHelper::computeFinal(bool lefthand) { - if (myNumLoaded == 0) { - myFinal = myProcessing; - if (lefthand) { - myFinal.myOffset.mul(1, -1); - } - } else { - if (lefthand) { - myProcessing.myOffset.mul(1, -1); - } - myFinal = GeoConvHelper( - // prefer options over loaded location - myProcessing.usingGeoProjection() ? myProcessing.getProjString() : myLoaded.getProjString(), - // let offset and boundary lead back to the original coords of the loaded data - myProcessing.getOffset() + myLoaded.getOffset(), - myLoaded.getOrigBoundary(), - // the new boundary (updated during loading) - myProcessing.getConvBoundary()); - } - if (lefthand) { - myFinal.myConvBoundary.flipY(); - } -} - - -void -GeoConvHelper::setLoaded(const GeoConvHelper& loaded) { - myNumLoaded++; - if (myNumLoaded > 1) { - WRITE_WARNING("Ignoring loaded location attribute nr. " + toString(myNumLoaded) + " for tracking of original location"); - } else { - myLoaded = loaded; - } -} - - -void -GeoConvHelper::resetLoaded() { - myNumLoaded = 0; -} - - -void -GeoConvHelper::writeLocation(OutputDevice& into) { - into.openTag(SUMO_TAG_LOCATION); - into.writeAttr(SUMO_ATTR_NET_OFFSET, myFinal.getOffsetBase()); - into.writeAttr(SUMO_ATTR_CONV_BOUNDARY, myFinal.getConvBoundary()); - if (myFinal.usingGeoProjection()) { - into.setPrecision(gPrecisionGeo); - } - into.writeAttr(SUMO_ATTR_ORIG_BOUNDARY, myFinal.getOrigBoundary()); - if (myFinal.usingGeoProjection()) { - into.setPrecision(); - } - into.writeAttr(SUMO_ATTR_ORIG_PROJ, myFinal.getProjString()); - into.closeTag(); - into.lf(); -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/utils/geom/GeoConvHelper.h b/Util/OSM2ODR/src/utils/geom/GeoConvHelper.h deleted file mode 100644 index db51164a8..000000000 --- a/Util/OSM2ODR/src/utils/geom/GeoConvHelper.h +++ /dev/null @@ -1,229 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file GeoConvHelper.h -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date 2006-08-01 -/// -// static methods for processing the coordinates conversion for the current net -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include -#include - -#ifdef PROJ_API_FILE -#include PROJ_API_FILE -#ifdef PROJ_VERSION_MAJOR -typedef PJ* projPJ; -#endif -#endif - - -// =========================================================================== -// class declarations -// =========================================================================== - -class OptionsCont; -class PositionVector; -class OutputDevice; - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class GeoConvHelper - * @brief static methods for processing the coordinates conversion for the current net - */ -class GeoConvHelper { -public: - - /**@brief Constructor based on the stored options - * @param[in] oc The OptionsCont from which to read options - */ - GeoConvHelper(OptionsCont& oc); - - /// @brief Constructor - GeoConvHelper(const std::string& proj, const Position& offset, - const Boundary& orig, const Boundary& conv, double scale = 1.0, double rot = 0.0, bool inverse = false, bool flatten = false); - - /// @brief Destructor - ~GeoConvHelper(); - - /**@brief Adds projection options to the given container - * @param[in] oc The options container to add the options to - * @todo let the container be retrieved - */ - static void addProjectionOptions(OptionsCont& oc); - - /// @brief Initialises the processing and the final instance using the given options - static bool init(OptionsCont& oc); - - /// @brief Initialises the processing and the final instance using the given proj.4-definition and complete network parameter - static void init(const std::string& proj, const Position& offset, const Boundary& orig, - const Boundary& conv, double scale = 1.0); - - /**@brief the coordinate transformation to use for input conversion and processing - * @note instance is modified during use: boundary may adapt to new coordinates - */ - static GeoConvHelper& getProcessing() { - return myProcessing; - } - - /// @brief the coordinate transformation that was loaded fron an input file - static GeoConvHelper& getLoaded() { - return myLoaded; - } - - static int getNumLoaded() { - return myNumLoaded; - } - - /**@brief compute the location attributes which will be used for output - * based on the loaded location data, the given options and the transformations applied during processing - */ - static void computeFinal(bool lefthand = false); - - /// @brief the coordinate transformation for writing the location element and for tracking the original coordinate system - static const GeoConvHelper& getFinal() { - return myFinal; - } - - /// @brief sets the coordinate transformation loaded from a location element - static void setLoaded(const GeoConvHelper& loaded); - - /// @brief @brief resets loaded location elements - static void resetLoaded(); - - /// @brief Converts the given cartesian (shifted) position to its geo (lat/long) representation - void cartesian2geo(Position& cartesian) const; - - /**@brief Converts the given coordinate into a cartesian and optionally update myConvBoundary - * @note: initializes UTM / DHDN projection on first use (select zone) - */ - bool x2cartesian(Position& from, bool includeInBoundary = true); - - /// @brief Converts the given coordinate into a cartesian using the previous initialisation - bool x2cartesian_const(Position& from) const; - - /// @brief Returns whether a transformation from geo to metric coordinates will be performed - bool usingGeoProjection() const; - - /// @brief Returns the information whether an inverse transformation will happen - bool usingInverseGeoProjection() const; - - /// @brief Shifts the converted boundary by the given amounts - void moveConvertedBy(double x, double y); - - /// @brief Returns the original boundary - const Boundary& getOrigBoundary() const; - - /// @brief Returns the converted boundary - const Boundary& getConvBoundary() const; - - /// @brief sets the converted boundary - void setConvBoundary(const Boundary& boundary) { - myConvBoundary = boundary; - } - - /// @brief Returns the network offset - const Position getOffset() const; - - /// @brief Returns the network base - const Position getOffsetBase() const; - - /// @brief Returns the original projection definition - const std::string& getProjString() const; - - /// @brief @brief writes the location element - static void writeLocation(OutputDevice& into); - - bool operator==(const GeoConvHelper& o) const; - - bool operator!=(const GeoConvHelper& o) const { - return !(*this == o); - } - -private: - /// @brief projection method - enum ProjectionMethod { - NONE, - SIMPLE, - UTM, - DHDN, - DHDN_UTM, - PROJ - }; - - /// @brief A proj options string describing the proj.4-projection to use - std::string myProjString; - -#ifdef PROJ_API_FILE - /// @brief The proj.4-projection to use - projPJ myProjection; - - /// @brief The inverse proj.4-projection to use first - projPJ myInverseProjection; - - /// @brief The geo proj.4-projection which is the target of the inverse projection - projPJ myGeoProjection; -#endif - - /// @brief The offset to apply - Position myOffset; - - /// @brief The scaling to apply to geo-coordinates - double myGeoScale; - - /// @brief The rotation to apply to geo-coordinates - double mySin; - double myCos; - - /// @brief Information whether no projection shall be done - ProjectionMethod myProjectionMethod; - - /// @brief Information whether inverse projection shall be used - bool myUseInverseProjection; - - /// @brief whether to discard z-data - bool myFlatten; - - /// @brief The boundary before conversion (x2cartesian) - Boundary myOrigBoundary; - - /// @brief The boundary after conversion (x2cartesian) - Boundary myConvBoundary; - - /// @brief coordinate transformation to use for input conversion and processing - static GeoConvHelper myProcessing; - - /// @brief coordinate transformation loaded from a location element - static GeoConvHelper myLoaded; - - /// @brief coordinate transformation to use for writing the location element and for tracking the original coordinate system - static GeoConvHelper myFinal; - - /// @brief the numer of coordinate transformations loaded from location elements - static int myNumLoaded; - - /// @brief make assignment operator private - GeoConvHelper& operator=(const GeoConvHelper&); - - /// @brief invalidated copy constructor. - GeoConvHelper(const GeoConvHelper&) = delete; -}; diff --git a/Util/OSM2ODR/src/utils/geom/GeomConvHelper.cpp b/Util/OSM2ODR/src/utils/geom/GeomConvHelper.cpp deleted file mode 100644 index d66731a1e..000000000 --- a/Util/OSM2ODR/src/utils/geom/GeomConvHelper.cpp +++ /dev/null @@ -1,123 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file GeomConvHelper.cpp -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date Sept 2003 -/// -// Some helping functions for geometry parsing -/****************************************************************************/ -#include - -#include -#include -#include -#include -#include -#include -#include "GeomConvHelper.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -PositionVector -GeomConvHelper::parseShapeReporting(const std::string& shpdef, const std::string& objecttype, - const char* objectid, bool& ok, bool allowEmpty, bool report) { - if (shpdef == "") { - if (!allowEmpty) { - emitError(report, "Shape", objecttype, objectid, "the shape is empty"); - ok = false; - } - return PositionVector(); - } - StringTokenizer st(shpdef, " "); - PositionVector shape; - while (st.hasNext()) { - StringTokenizer pos(st.next(), ","); - if (pos.size() != 2 && pos.size() != 3) { - emitError(report, "Shape", objecttype, objectid, "the position is neither x,y nor x,y,z"); - ok = false; - return PositionVector(); - } - try { - double x = StringUtils::toDouble(pos.next()); - double y = StringUtils::toDouble(pos.next()); - if (pos.size() == 2) { - shape.push_back(Position(x, y)); - } else { - double z = StringUtils::toDouble(pos.next()); - shape.push_back(Position(x, y, z)); - } - } catch (NumberFormatException&) { - emitError(report, "Shape", objecttype, objectid, "not numeric position entry"); - ok = false; - return PositionVector(); - } catch (EmptyData&) { - emitError(report, "Shape", objecttype, objectid, "empty position entry"); - ok = false; - return PositionVector(); - } - } - return shape; -} - - -Boundary -GeomConvHelper::parseBoundaryReporting(const std::string& def, const std::string& objecttype, - const char* objectid, bool& ok, bool report) { - StringTokenizer st(def, ","); - if (st.size() != 4) { - emitError(report, "Bounding box", objecttype, objectid, "mismatching entry number"); - ok = false; - return Boundary(); - } - try { - double xmin = StringUtils::toDouble(st.next()); - double ymin = StringUtils::toDouble(st.next()); - double xmax = StringUtils::toDouble(st.next()); - double ymax = StringUtils::toDouble(st.next()); - return Boundary(xmin, ymin, xmax, ymax); - } catch (NumberFormatException&) { - emitError(report, "Shape", objecttype, objectid, "not numeric entry"); - } catch (EmptyData&) { - emitError(report, "Shape", objecttype, objectid, "empty entry"); - } - ok = false; - return Boundary(); -} - - -void -GeomConvHelper::emitError(bool report, const std::string& what, const std::string& objecttype, - const char* objectid, const std::string& desc) { - if (!report) { - return; - } - std::ostringstream oss; - oss << what << " of "; - if (objectid == nullptr) { - oss << "a(n) "; - } - oss << objecttype; - if (objectid != nullptr) { - oss << " '" << objectid << "'"; - } - oss << " is broken: " << desc << "."; - WRITE_ERROR(oss.str()); -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/utils/geom/GeomConvHelper.h b/Util/OSM2ODR/src/utils/geom/GeomConvHelper.h deleted file mode 100644 index 6f1fbbdf8..000000000 --- a/Util/OSM2ODR/src/utils/geom/GeomConvHelper.h +++ /dev/null @@ -1,80 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file GeomConvHelper.h -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date Sept 2003 -/// -// Some helping functions for geometry parsing -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class GeomConvHelper - * This class holds some helping functions for the parsing of geometries - */ -class GeomConvHelper { -public: - /** @brief Builds a PositionVector from a string representation, reporting occurred errors - * - * It is assumed, the vector is stored as "x,y[ x,y]*" where x and y are doubles. - * @param[in] shpdef The shape definition to parse - * @param[in] objecttype The name of the parsed object type; used for error message generation - * @param[in] objectid The name of the parsed object; used for error message generation - * @param[out] ok Whether the value could be read - * @param[in] allowEmpty Whether an empty shape definition is valid - * @param[in] report Whether errors shall be written to msg handler's error instance - * @return The parsed position vector - */ - static PositionVector parseShapeReporting(const std::string& shpdef, const std::string& objecttype, - const char* objectid, bool& ok, bool allowEmpty, bool report = true); - - - /** @brief Builds a boundary from its string representation, reporting occurred errors - * - * It is assumed that the boundary is stored as a quadruple of double, divided by ','. - * @param[in] def The boundary definition to parse - * @param[in] objecttype The name of the parsed object type; used for error message generation - * @param[in] objectid The name of the parsed object; used for error message generation - * @param[out] ok Whether the value could be read - * @param[in] report Whether errors shall be written to msg handler's error instance - * @return The parsed boundary - */ - static Boundary parseBoundaryReporting(const std::string& def, const std::string& objecttype, - const char* objectid, bool& ok, bool report = true); - - -private: - /** @brief Writes an error message into the MessageHandler - * @param[in] report Whether errors shall be written to msg handler's error instance - * @param[in] what Name of the parsed object ("Shape", or "Boundary") - * @param[in] objecttype The name of the parsed object type the error occurred at - * @param[in] objectid The name of the parsed object type the error occurred at - * @param[out] desc Error description - */ - static void emitError(bool report, const std::string& what, const std::string& objecttype, - const char* objectid, const std::string& desc); - - -}; diff --git a/Util/OSM2ODR/src/utils/geom/GeomHelper.cpp b/Util/OSM2ODR/src/utils/geom/GeomHelper.cpp deleted file mode 100644 index 10963d55e..000000000 --- a/Util/OSM2ODR/src/utils/geom/GeomHelper.cpp +++ /dev/null @@ -1,279 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file GeomHelper.cpp -/// @author Daniel Krajzewicz -/// @author Friedemann Wesner -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date Sept 2002 -/// -// Some static methods performing geometrical operations -/****************************************************************************/ -#include - -#include -#include -#include -#include -#include -#include -#include -#include "Boundary.h" -#include "GeomHelper.h" - -// =========================================================================== -// static members -// =========================================================================== -const double GeomHelper::INVALID_OFFSET = -1; - - -// =========================================================================== -// method definitions -// =========================================================================== - -void -GeomHelper::findLineCircleIntersections(const Position& c, double radius, const Position& p1, const Position& p2, - std::vector& into) { - const double dx = p2.x() - p1.x(); - const double dy = p2.y() - p1.y(); - - const double A = dx * dx + dy * dy; - const double B = 2 * (dx * (p1.x() - c.x()) + dy * (p1.y() - c.y())); - const double C = (p1.x() - c.x()) * (p1.x() - c.x()) + (p1.y() - c.y()) * (p1.y() - c.y()) - radius * radius; - - const double det = B * B - 4 * A * C; - if ((A <= 0.0000001) || (det < 0)) { - // No real solutions. - return; - } - if (det == 0) { - // One solution. - const double t = -B / (2 * A); - if (t >= 0. && t <= 1.) { - into.push_back(t); - } - } else { - // Two solutions. - const double t = (double)((-B + sqrt(det)) / (2 * A)); - Position intersection(p1.x() + t * dx, p1.y() + t * dy); - if (t >= 0. && t <= 1.) { - into.push_back(t); - } - const double t2 = (double)((-B - sqrt(det)) / (2 * A)); - if (t2 >= 0. && t2 <= 1.) { - into.push_back(t2); - } - } -} - - -double -GeomHelper::angle2D(const Position& p1, const Position& p2) { - return angleDiff(atan2(p1.y(), p1.x()), atan2(p2.y(), p2.x())); -} - - -double -GeomHelper::nearest_offset_on_line_to_point2D(const Position& lineStart, - const Position& lineEnd, - const Position& p, bool perpendicular) { - const double lineLength2D = lineStart.distanceTo2D(lineEnd); - if (lineLength2D == 0.0f) { - return 0.0f; - } else { - // scalar product equals length of orthogonal projection times length of vector being projected onto - // dividing the scalar product by the square of the distance gives the relative position - const double u = (((p.x() - lineStart.x()) * (lineEnd.x() - lineStart.x())) + - ((p.y() - lineStart.y()) * (lineEnd.y() - lineStart.y())) - ) / (lineLength2D * lineLength2D); - if (u < 0.0f || u > 1.0f) { // closest point does not fall within the line segment - if (perpendicular) { - return INVALID_OFFSET; - } - if (u < 0.0f) { - return 0.0f; - } - return lineLength2D; - } - return u * lineLength2D; - } -} - - -double -GeomHelper::nearest_offset_on_line_to_point25D(const Position& lineStart, - const Position& lineEnd, - const Position& p, bool perpendicular) { - double result = nearest_offset_on_line_to_point2D(lineStart, lineEnd, p, perpendicular); - if (result != INVALID_OFFSET) { - const double lineLength2D = lineStart.distanceTo2D(lineEnd); - const double lineLength = lineStart.distanceTo(lineEnd); - result *= (lineLength / lineLength2D); - } - return result; -} - -Position -GeomHelper::crossPoint(const Boundary& b, const PositionVector& v) { - if (v.intersects(Position(b.xmin(), b.ymin()), Position(b.xmin(), b.ymax()))) { - return v.intersectionPosition2D( - Position(b.xmin(), b.ymin()), - Position(b.xmin(), b.ymax())); - } - if (v.intersects(Position(b.xmax(), b.ymin()), Position(b.xmax(), b.ymax()))) { - return v.intersectionPosition2D( - Position(b.xmax(), b.ymin()), - Position(b.xmax(), b.ymax())); - } - if (v.intersects(Position(b.xmin(), b.ymin()), Position(b.xmax(), b.ymin()))) { - return v.intersectionPosition2D( - Position(b.xmin(), b.ymin()), - Position(b.xmax(), b.ymin())); - } - if (v.intersects(Position(b.xmin(), b.ymax()), Position(b.xmax(), b.ymax()))) { - return v.intersectionPosition2D( - Position(b.xmin(), b.ymax()), - Position(b.xmax(), b.ymax())); - } - throw 1; -} - -double -GeomHelper::getCCWAngleDiff(double angle1, double angle2) { - double v = angle2 - angle1; - if (v < 0) { - v = 360 + v; - } - return v; -} - - -double -GeomHelper::getCWAngleDiff(double angle1, double angle2) { - double v = angle1 - angle2; - if (v < 0) { - v = 360 + v; - } - return v; -} - - -double -GeomHelper::getMinAngleDiff(double angle1, double angle2) { - return MIN2(getCWAngleDiff(angle1, angle2), getCCWAngleDiff(angle1, angle2)); -} - - -double -GeomHelper::angleDiff(const double angle1, const double angle2) { - double dtheta = angle2 - angle1; - while (dtheta > (double) M_PI) { - dtheta -= (double)(2.0 * M_PI); - } - while (dtheta < (double) - M_PI) { - dtheta += (double)(2.0 * M_PI); - } - return dtheta; -} - - -double -GeomHelper::naviDegree(const double angle) { - double degree = RAD2DEG(M_PI / 2. - angle); - if (std::isinf(degree)) { - //assert(false); - return 0; - } - while (degree >= 360.) { - degree -= 360.; - } - while (degree < 0.) { - degree += 360.; - } - return degree; -} - - -double -GeomHelper::fromNaviDegree(const double angle) { - return M_PI / 2. - DEG2RAD(angle); -} - - -double -GeomHelper::legacyDegree(const double angle, const bool positive) { - double degree = -RAD2DEG(M_PI / 2. + angle); - if (positive) { - while (degree >= 360.) { - degree -= 360.; - } - while (degree < 0.) { - degree += 360.; - } - } else { - while (degree >= 180.) { - degree -= 360.; - } - while (degree < -180.) { - degree += 360.; - } - } - return degree; -} - -PositionVector -GeomHelper::makeCircle(const double radius, const Position& center, unsigned int nPoints) { - if (nPoints < 3) { - WRITE_ERROR("GeomHelper::makeCircle() requires nPoints>=3"); - } - PositionVector circle; - circle.push_back({radius, 0}); - for (unsigned int i = 1; i < nPoints; ++i) { - const double a = 2.0 * M_PI * (double)i / (double) nPoints; - circle.push_back({radius * cos(a), radius * sin(a)}); - } - circle.push_back({radius, 0}); - circle.add(center); - return circle; -} - - -PositionVector -GeomHelper::makeRing(const double radius1, const double radius2, const Position& center, unsigned int nPoints) { - if (nPoints < 3) { - WRITE_ERROR("GeomHelper::makeRing() requires nPoints>=3"); - } - if (radius1 >= radius2) { - WRITE_ERROR("GeomHelper::makeRing() requires radius2>radius1"); - } - PositionVector ring; - ring.push_back({radius1, 0}); - ring.push_back({radius2, 0}); - for (unsigned int i = 1; i < nPoints; ++i) { - const double a = 2.0 * M_PI * (double)i / (double) nPoints; - ring.push_back({radius2 * cos(a), radius2 * sin(a)}); - } - ring.push_back({radius2, 0}); - ring.push_back({radius1, 0}); - for (unsigned int i = 1; i < nPoints; ++i) { - const double a = -2.0 * M_PI * (double)i / (double) nPoints; - ring.push_back({radius1 * cos(a), radius1 * sin(a)}); - } - ring.push_back({radius1, 0}); - ring.add(center); - return ring; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/utils/geom/GeomHelper.h b/Util/OSM2ODR/src/utils/geom/GeomHelper.h deleted file mode 100644 index 962661169..000000000 --- a/Util/OSM2ODR/src/utils/geom/GeomHelper.h +++ /dev/null @@ -1,157 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file GeomHelper.h -/// @author Daniel Krajzewicz -/// @author Friedemann Wesner -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date Sept 2002 -/// -// Some static methods performing geometrical operations -/****************************************************************************/ -#pragma once -#include - -#include -#include "Position.h" -#include "PositionVector.h" -#include - -#ifndef M_PI -#define M_PI 3.1415926535897932384626433832795 -#endif - -#define DEG2RAD(x) static_cast((x) * M_PI / 180.) -#define RAD2DEG(x) static_cast((x) * 180. / M_PI) - - -// =========================================================================== -// class definitions -// =========================================================================== -/** @class GeomHelper - * @brief Some static methods performing geometrical operations - */ -class GeomHelper { - -public: - /// @brief a value to signify offsets outside the range of [0, Line.length()] - static const double INVALID_OFFSET; - - /** @brief Returns the positions the given circle is crossed by the given line - * @param[in] c The center position of the circle - * @param[in] radius The radius of the circle - * @param[in] p1 The begin of the line - * @param[in] p2 The end of the line - * @param[filled] into The list of crossing positions (0-1 along the line's length) - * @see http://blog.csharphelper.com/2010/03/28/determine-where-a-line-intersects-a-circle-in-c.aspx - * @see http://gamedev.stackexchange.com/questions/18333/circle-line-collision-detection-problem (jazzdawg) - */ - static void findLineCircleIntersections(const Position& c, double radius, const Position& p1, const Position& p2, - std::vector& into); - - - /** @brief Returns the angle between two vectors on a plane - The angle is from vector 1 to vector 2, positive anticlockwise - The result is between -pi and pi - */ - static double angle2D(const Position& p1, const Position& p2); - - static double nearest_offset_on_line_to_point2D( - const Position& lineStart, const Position& lineEnd, - const Position& p, bool perpendicular = true); - - static double nearest_offset_on_line_to_point25D( - const Position& lineStart, const Position& lineEnd, - const Position& p, bool perpendicular = true); - - static Position crossPoint(const Boundary& b, - const PositionVector& v); - - /** @brief Returns the distance of second angle from first angle counter-clockwise - * @param[in] angle1 The first angle - * @param[in] angle2 The second angle - * @return Angle (counter-clockwise) starting from first to second angle - */ - static double getCCWAngleDiff(double angle1, double angle2); - - - /** @brief Returns the distance of second angle from first angle clockwise - * @param[in] angle1 The first angle - * @param[in] angle2 The second angle - * @return Angle (clockwise) starting from first to second angle - */ - static double getCWAngleDiff(double angle1, double angle2); - - - /** @brief Returns the minimum distance (clockwise/counter-clockwise) between both angles - * @param[in] angle1 The first angle - * @param[in] angle2 The second angle - * @return The minimum distance between both angles - */ - static double getMinAngleDiff(double angle1, double angle2); - - - /** @brief Returns the difference of the second angle to the first angle in radiants - * - * The results are always between -pi and pi. - * Positive values denote that the second angle is counter clockwise closer, negative values mean - * it is clockwise closer. - * @param[in] angle1 The first angle - * @param[in] angle2 The second angle - * @return angle starting from first to second angle - */ - static double angleDiff(const double angle1, const double angle2); - - - /** Converts an angle from mathematical radians where 0 is to the right and positive angles - * are counterclockwise to navigational degrees where 0 is up and positive means clockwise. - * The result is always in the range [0, 360). - * @param[in] angle The angle in radians to convert - * @return the angle in degrees - */ - static double naviDegree(const double angle); - - /** Converts an angle from navigational degrees to mathematical radians. - * @see naviDegree - * @param[in] angle The angle in degree to convert - * @return the angle in radians - */ - static double fromNaviDegree(const double angle); - - /** Converts an angle from mathematical radians where 0 is to the right and positive angles - * are counterclockwise to the legacy degrees used in sumo where 0 is down and positive means clockwise. - * If positive is true the result is in the range [0, 360), otherwise in the range [-180, 180). - * @param[in] angle The angle in radians to convert - * @return the angle in degrees - */ - static double legacyDegree(const double angle, const bool positive = false); - - /** Creates a circular polygon - * @param[in] radius Radius of the circle - * @param[in] center Position of the circle's center - * @param[in] nPoints Number of points of the circle (Polygon's shape will have noPoints+1 points), must be >=3 - * @return the polygon approximating the circle - */ - static PositionVector makeCircle(const double radius, const Position& center, unsigned int nPoints); - - /** Creates a circular polygon - * @param[in] radius1 Inner radius of the ring - * @param[in] radius2 Outer radius of the ring - * @param[in] center Position of the circle's center - * @param[in] nPoints Number of points of the circle (Polygon's shape will have noPoints+1 points), must be >=3 - * @return the polygon approximating the circle - */ - static PositionVector makeRing(const double radius1, const double radius2, const Position& center, unsigned int nPoints); - -}; diff --git a/Util/OSM2ODR/src/utils/geom/Position.cpp b/Util/OSM2ODR/src/utils/geom/Position.cpp deleted file mode 100644 index a3e0d3acd..000000000 --- a/Util/OSM2ODR/src/utils/geom/Position.cpp +++ /dev/null @@ -1,49 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file Position.cpp -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Axel Wegener -/// @author Michael Behrisch -/// @date Sept 2002 -/// -// A position in the 2D- or 3D-world -/****************************************************************************/ -#include - -#include -#include "Position.h" - - -// =========================================================================== -// static member definitions -// =========================================================================== - -// Position 1Mio km below the surface should suffice for signaling invalidity inside the solar system -const Position Position::INVALID( - - 1024 * 1024 * 1024, - - 1024 * 1024 * 1024, - - 1024 * 1024 * 1024); - - -Position -Position::rotateAround2D(double rad, const Position& origin) { - const double s = sin(rad); - const double c = cos(rad); - Position p = (*this) - origin; - return Position( - p.x() * c - p.y() * s, - p.x() * s + p.y() * c) + origin; - -} diff --git a/Util/OSM2ODR/src/utils/geom/Position.h b/Util/OSM2ODR/src/utils/geom/Position.h deleted file mode 100644 index 3f5d0a1fd..000000000 --- a/Util/OSM2ODR/src/utils/geom/Position.h +++ /dev/null @@ -1,293 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file Position.h -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Axel Wegener -/// @author Michael Behrisch -/// @date Sept 2002 -/// -// A position in the 2D- or 3D-world -/****************************************************************************/ -#pragma once -#include -#include - -#include - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class Position - * @brief A point in 2D or 3D with translation and scaling methods. - */ -class Position { -public: - /// @brief default constructor - Position() : - myX(0.0), myY(0.0), myZ(0.0) { } - - /// @brief Parametrised constructor (only for x-y) - Position(double x, double y) : - myX(x), myY(y), myZ(0) { } - - /// @brief Parametrised constructor - Position(double x, double y, double z) : - myX(x), myY(y), myZ(z) { } - - /// @brief Destructor - ~Position() { } - - /// @brief Returns the x-position - inline double x() const { - return myX; - } - - /// @brief Returns the y-position - inline double y() const { - return myY; - } - - /// @brief Returns the z-position - inline double z() const { - return myZ; - } - - /// @brief set position x - void setx(double x) { - myX = x; - } - - /// @brief set position y - void sety(double y) { - myY = y; - } - - /// @brief set position z - void setz(double z) { - myZ = z; - } - - /// @brief set positions x and y - void set(double x, double y) { - myX = x; - myY = y; - } - - /// @brief set positions x, y and z - void set(double x, double y, double z) { - myX = x; - myY = y; - myZ = z; - } - - /// @brief set position with another position - void set(const Position& pos) { - myX = pos.myX; - myY = pos.myY; - myZ = pos.myZ; - } - - /// @brief Multiplies both positions with the given value - void mul(double val) { - myX *= val; - myY *= val; - myZ *= val; - } - - /// @brief Multiplies position with the given values - void mul(double mx, double my) { - myX *= mx; - myY *= my; - } - - /// @brief Multiplies position with the given values - void mul(double mx, double my, double mz) { - myX *= mx; - myY *= my; - myZ *= mz; - } - - /// @brief Adds the given position to this one - void add(const Position& pos) { - myX += pos.myX; - myY += pos.myY; - myZ += pos.myZ; - } - - /// @brief Adds the given position to this one - void add(double dx, double dy) { - myX += dx; - myY += dy; - } - - /// @brief Adds the given position to this one - void add(double dx, double dy, double dz) { - myX += dx; - myY += dy; - myZ += dz; - } - - /// @brief Substracts the given position from this one - void sub(double dx, double dy) { - myX -= dx; - myY -= dy; - } - - /// @brief Substracts the given position from this one - void sub(double dx, double dy, double dz) { - myX -= dx; - myY -= dy; - myZ -= dz; - } - - /// @brief Substracts the given position from this one - void sub(const Position& pos) { - myX -= pos.myX; - myY -= pos.myY; - myZ -= pos.myZ; - } - - /// @brief - void norm2d() { - double val = sqrt(myX * myX + myY * myY); - myX = myX / val; - myY = myY / val; - } - - /// @brief output operator - friend std::ostream& operator<<(std::ostream& os, const Position& p) { - os << p.x() << "," << p.y(); - if (p.z() != double(0.0)) { - os << "," << p.z(); - } - return os; - } - - /// @brief add operator - Position operator+(const Position& p2) const { - return Position(myX + p2.myX, myY + p2.myY, myZ + p2.myZ); - } - - /// @brief sub operator - Position operator-(const Position& p2) const { - return Position(myX - p2.myX, myY - p2.myY, myZ - p2.myZ); - } - - /// @brief keep the direction but modify the length of the (location) vector to length * scalar - Position operator*(double scalar) const { - return Position(myX * scalar, myY * scalar, myZ * scalar); - } - - /// @brief keep the direction but modify the length of the (location) vector to length + scalar - Position operator+(double offset) const { - const double length = distanceTo(Position(0, 0, 0)); - if (length == 0) { - return *this; - } - const double scalar = (length + offset) / length; - return Position(myX * scalar, myY * scalar, myZ * scalar); - } - - /// @brief comparation operator - bool operator==(const Position& p2) const { - return myX == p2.myX && myY == p2.myY && myZ == p2.myZ; - } - - /// @brief difference operator - bool operator!=(const Position& p2) const { - return myX != p2.myX || myY != p2.myY || myZ != p2.myZ; - } - - /// @brief lexicographical sorting for use in maps and sets - bool operator<(const Position& p2) const { - if (myX < p2.myX) { - return true; - } else if (myY < p2.myY) { - return true; - } else { - return myZ < p2.myZ; - } - } - - /// @brief check if two position is almost the sme as other - bool almostSame(const Position& p2, double maxDiv = POSITION_EPS) const { - return distanceTo(p2) < maxDiv; - } - - /// @brief returns the euclidean distance in 3 dimension - inline double distanceTo(const Position& p2) const { - return sqrt(distanceSquaredTo(p2)); - } - - /// @brief returns the square of the distance to another position - inline double distanceSquaredTo(const Position& p2) const { - return (myX - p2.myX) * (myX - p2.myX) + (myY - p2.myY) * (myY - p2.myY) + (myZ - p2.myZ) * (myZ - p2.myZ); - } - - /// @brief returns the euclidean distance in the x-y-plane - inline double distanceTo2D(const Position& p2) const { - return sqrt(distanceSquaredTo2D(p2)); - } - - /// @brief returns the square of the distance to another position (Only using x and y positions) - inline double distanceSquaredTo2D(const Position& p2) const { - return (myX - p2.myX) * (myX - p2.myX) + (myY - p2.myY) * (myY - p2.myY); - } - - /// @brief returns the angle in the plane of the vector pointing from here to the other position - inline double angleTo2D(const Position& other) const { - return atan2(other.myY - myY, other.myX - myX); - } - - /// @brief returns the cross product between this point and the second one - Position crossProduct(const Position& pos) { - return Position( - myY * pos.myZ - myZ * pos.myY, - myZ * pos.myX - myX * pos.myZ, - myX * pos.myY - myY * pos.myX); - } - - /// @brief returns the dot product (scalar product) between this point and the second one - inline double dotProduct(const Position& pos) { - return myX * pos.myX + myY * pos.myY + myZ * pos.myZ; - } - - /// @brief rotate this position by rad around origin and return the result - Position rotateAround2D(double rad, const Position& origin); - - /// @brief swap position X and Y - void swapXY() { - std::swap(myX, myY); - } - - /// @brief check if position is NAN - bool isNAN() const { - return (std::isnan(myX) || std::isnan(myY) || std::isnan(myZ)); - } - - /// @brief used to indicate that a position is valid - static const Position INVALID; - -private: - /// @brief The x-position - double myX; - - /// @brief The y-position - double myY; - - /// @brief The z-position - double myZ; -}; diff --git a/Util/OSM2ODR/src/utils/geom/PositionVector.cpp b/Util/OSM2ODR/src/utils/geom/PositionVector.cpp deleted file mode 100644 index 2ab2c41cb..000000000 --- a/Util/OSM2ODR/src/utils/geom/PositionVector.cpp +++ /dev/null @@ -1,1738 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file PositionVector.cpp -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @author Walter Bamberger -/// @date Sept 2002 -/// -// A list of positions -/****************************************************************************/ -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "AbstractPoly.h" -#include "Position.h" -#include "PositionVector.h" -#include "GeomHelper.h" -#include "Boundary.h" - -// =========================================================================== -// static members -// =========================================================================== -const PositionVector PositionVector::EMPTY; - -// =========================================================================== -// method definitions -// =========================================================================== - -PositionVector::PositionVector() {} - - -PositionVector::PositionVector(const std::vector& v) { - std::copy(v.begin(), v.end(), std::back_inserter(*this)); -} - - -PositionVector::PositionVector(const std::vector::const_iterator beg, const std::vector::const_iterator end) { - std::copy(beg, end, std::back_inserter(*this)); -} - - -PositionVector::PositionVector(const Position& p1, const Position& p2) { - push_back(p1); - push_back(p2); -} - - -PositionVector::~PositionVector() {} - - -bool -PositionVector::around(const Position& p, double offset) const { - if (size() < 2) { - return false; - } - if (offset != 0) { - PositionVector tmp(*this); - tmp.scaleAbsolute(offset); - return tmp.around(p); - } - double angle = 0; - // iterate over all points, and obtain angle between current and next - for (const_iterator i = begin(); i != (end() - 1); i++) { - Position p1( - i->x() - p.x(), - i->y() - p.y()); - Position p2( - (i + 1)->x() - p.x(), - (i + 1)->y() - p.y()); - angle += GeomHelper::angle2D(p1, p2); - } - // add angle between last and first point - Position p1( - (end() - 1)->x() - p.x(), - (end() - 1)->y() - p.y()); - Position p2( - begin()->x() - p.x(), - begin()->y() - p.y()); - angle += GeomHelper::angle2D(p1, p2); - // if angle is less than PI, then point lying in Polygon - return (!(fabs(angle) < M_PI)); -} - - -bool -PositionVector::overlapsWith(const AbstractPoly& poly, double offset) const { - if ( - // check whether one of my points lies within the given poly - partialWithin(poly, offset) || - // check whether the polygon lies within me - poly.partialWithin(*this, offset)) { - return true; - } - if (size() >= 2) { - for (const_iterator i = begin(); i != end() - 1; i++) { - if (poly.crosses(*i, *(i + 1))) { - return true; - } - } - if (size() > 2 && poly.crosses(back(), front())) { - return true; - } - } - return false; -} - - -double -PositionVector::getOverlapWith(const PositionVector& poly, double zThreshold) const { - double result = 0; - if ((size() == 0) || (poly.size() == 0)) { - return result; - } - // this points within poly - for (const_iterator i = begin(); i != end() - 1; i++) { - if (poly.around(*i)) { - Position closest = poly.positionAtOffset2D(poly.nearest_offset_to_point2D(*i)); - if (fabs(closest.z() - (*i).z()) < zThreshold) { - result = MAX2(result, poly.distance2D(*i)); - } - } - } - // polys points within this - for (const_iterator i = poly.begin(); i != poly.end() - 1; i++) { - if (around(*i)) { - Position closest = positionAtOffset2D(nearest_offset_to_point2D(*i)); - if (fabs(closest.z() - (*i).z()) < zThreshold) { - result = MAX2(result, distance2D(*i)); - } - } - } - return result; -} - - -bool -PositionVector::intersects(const Position& p1, const Position& p2) const { - if (size() < 2) { - return false; - } - for (const_iterator i = begin(); i != end() - 1; i++) { - if (intersects(*i, *(i + 1), p1, p2)) { - return true; - } - } - return false; -} - - -bool -PositionVector::intersects(const PositionVector& v1) const { - if (size() < 2) { - return false; - } - for (const_iterator i = begin(); i != end() - 1; i++) { - if (v1.intersects(*i, *(i + 1))) { - return true; - } - } - return false; -} - - -Position -PositionVector::intersectionPosition2D(const Position& p1, const Position& p2, const double withinDist) const { - for (const_iterator i = begin(); i != end() - 1; i++) { - double x, y, m; - if (intersects(*i, *(i + 1), p1, p2, withinDist, &x, &y, &m)) { - return Position(x, y); - } - } - return Position::INVALID; -} - - -Position -PositionVector::intersectionPosition2D(const PositionVector& v1) const { - for (const_iterator i = begin(); i != end() - 1; i++) { - if (v1.intersects(*i, *(i + 1))) { - return v1.intersectionPosition2D(*i, *(i + 1)); - } - } - return Position::INVALID; -} - - -const Position& -PositionVector::operator[](int index) const { - /* bracket operators works as in Python. Examples: - - A = {'a', 'b', 'c', 'd'} (size 4) - - A [2] returns 'c' because 0 < 2 < 4 - - A [100] thrown an exception because 100 > 4 - - A [-1] returns 'd' because 4 - 1 = 3 - - A [-100] thrown an exception because (4-100) < 0 - */ - if (index >= 0 && index < (int)size()) { - return at(index); - } else if (index < 0 && -index <= (int)size()) { - return at((int)size() + index); - } else { - throw ProcessError("Index out of range in bracket operator of PositionVector"); - } -} - - -Position& -PositionVector::operator[](int index) { - /* bracket operators works as in Python. Examples: - - A = {'a', 'b', 'c', 'd'} (size 4) - - A [2] returns 'c' because 0 < 2 < 4 - - A [100] thrown an exception because 100 > 4 - - A [-1] returns 'd' because 4 - 1 = 3 - - A [-100] thrown an exception because (4-100) < 0 - */ - if (index >= 0 && index < (int)size()) { - return at(index); - } else if (index < 0 && -index <= (int)size()) { - return at((int)size() + index); - } else { - throw ProcessError("Index out of range in bracket operator of PositionVector"); - } -} - - -Position -PositionVector::positionAtOffset(double pos, double lateralOffset) const { - if (size() == 0) { - return Position::INVALID; - } - if (size() == 1) { - return front(); - } - const_iterator i = begin(); - double seenLength = 0; - do { - const double nextLength = (*i).distanceTo(*(i + 1)); - if (seenLength + nextLength > pos) { - return positionAtOffset(*i, *(i + 1), pos - seenLength, lateralOffset); - } - seenLength += nextLength; - } while (++i != end() - 1); - if (lateralOffset == 0 || size() < 2) { - return back(); - } else { - return positionAtOffset(*(end() - 2), *(end() - 1), (*(end() - 2)).distanceTo(*(end() - 1)), lateralOffset); - } -} - - -Position -PositionVector::positionAtOffset2D(double pos, double lateralOffset) const { - if (size() == 0) { - return Position::INVALID; - } - if (size() == 1) { - return front(); - } - const_iterator i = begin(); - double seenLength = 0; - do { - const double nextLength = (*i).distanceTo2D(*(i + 1)); - if (seenLength + nextLength > pos) { - return positionAtOffset2D(*i, *(i + 1), pos - seenLength, lateralOffset); - } - seenLength += nextLength; - } while (++i != end() - 1); - return back(); -} - - -double -PositionVector::rotationAtOffset(double pos) const { - if (size() == 0) { - return INVALID_DOUBLE; - } - if (pos < 0) { - pos += length(); - } - const_iterator i = begin(); - double seenLength = 0; - do { - const Position& p1 = *i; - const Position& p2 = *(i + 1); - const double nextLength = p1.distanceTo(p2); - if (seenLength + nextLength > pos) { - return p1.angleTo2D(p2); - } - seenLength += nextLength; - } while (++i != end() - 1); - const Position& p1 = (*this)[-2]; - const Position& p2 = back(); - return p1.angleTo2D(p2); -} - - -double -PositionVector::rotationDegreeAtOffset(double pos) const { - return GeomHelper::legacyDegree(rotationAtOffset(pos)); -} - - -double -PositionVector::slopeDegreeAtOffset(double pos) const { - if (size() == 0) { - return INVALID_DOUBLE; - } - const_iterator i = begin(); - double seenLength = 0; - do { - const Position& p1 = *i; - const Position& p2 = *(i + 1); - const double nextLength = p1.distanceTo(p2); - if (seenLength + nextLength > pos) { - return RAD2DEG(atan2(p2.z() - p1.z(), p1.distanceTo2D(p2))); - } - seenLength += nextLength; - } while (++i != end() - 1); - const Position& p1 = (*this)[-2]; - const Position& p2 = back(); - return RAD2DEG(atan2(p2.z() - p1.z(), p1.distanceTo2D(p2))); -} - - -Position -PositionVector::positionAtOffset(const Position& p1, const Position& p2, double pos, double lateralOffset) { - const double dist = p1.distanceTo(p2); - if (pos < 0. || dist < pos) { - return Position::INVALID; - } - if (lateralOffset != 0) { - if (dist == 0.) { - return Position::INVALID; - } - const Position offset = sideOffset(p1, p2, -lateralOffset); // move in the same direction as Position::move2side - if (pos == 0.) { - return p1 + offset; - } - return p1 + (p2 - p1) * (pos / dist) + offset; - } - if (pos == 0.) { - return p1; - } - return p1 + (p2 - p1) * (pos / dist); -} - - -Position -PositionVector::positionAtOffset2D(const Position& p1, const Position& p2, double pos, double lateralOffset) { - const double dist = p1.distanceTo2D(p2); - if (pos < 0 || dist < pos) { - return Position::INVALID; - } - if (lateralOffset != 0) { - const Position offset = sideOffset(p1, p2, -lateralOffset); // move in the same direction as Position::move2side - if (pos == 0.) { - return p1 + offset; - } - return p1 + (p2 - p1) * (pos / dist) + offset; - } - if (pos == 0.) { - return p1; - } - return p1 + (p2 - p1) * (pos / dist); -} - - -Boundary -PositionVector::getBoxBoundary() const { - Boundary ret; - for (const Position& i : *this) { - ret.add(i); - } - return ret; -} - - -Position -PositionVector::getPolygonCenter() const { - double x = 0; - double y = 0; - double z = 0; - for (const Position& i : *this) { - x += i.x(); - y += i.y(); - z += i.z(); - } - return Position(x / (double) size(), y / (double) size(), z / (double)size()); -} - - -Position -PositionVector::getCentroid() const { - if (size() == 0) { - return Position::INVALID; - } else if (size() == 1) { - return (*this)[0]; - } else if (size() == 2) { - return ((*this)[0] + (*this)[1]) * 0.5; - } - PositionVector tmp = *this; - if (!isClosed()) { // make sure its closed - tmp.push_back(tmp[0]); - } - // shift to origin to increase numerical stability - Position offset = tmp[0]; - Position result; - tmp.sub(offset); - const int endIndex = (int)tmp.size() - 1; - double div = 0; // 6 * area including sign - double x = 0; - double y = 0; - if (tmp.area() != 0) { // numerical instability ? - // http://en.wikipedia.org/wiki/Polygon - for (int i = 0; i < endIndex; i++) { - const double z = tmp[i].x() * tmp[i + 1].y() - tmp[i + 1].x() * tmp[i].y(); - div += z; // area formula - x += (tmp[i].x() + tmp[i + 1].x()) * z; - y += (tmp[i].y() + tmp[i + 1].y()) * z; - } - div *= 3; // 6 / 2, the 2 comes from the area formula - result = Position(x / div, y / div); - } else { - // compute by decomposing into line segments - // http://en.wikipedia.org/wiki/Centroid#By_geometric_decomposition - double lengthSum = 0; - for (int i = 0; i < endIndex; i++) { - double length = tmp[i].distanceTo(tmp[i + 1]); - x += (tmp[i].x() + tmp[i + 1].x()) * length / 2; - y += (tmp[i].y() + tmp[i + 1].y()) * length / 2; - lengthSum += length; - } - if (lengthSum == 0) { - // it is probably only one point - result = tmp[0]; - } - result = Position(x / lengthSum, y / lengthSum) + offset; - } - return result + offset; -} - - -void -PositionVector::scaleRelative(double factor) { - Position centroid = getCentroid(); - for (int i = 0; i < static_cast(size()); i++) { - (*this)[i] = centroid + (((*this)[i] - centroid) * factor); - } -} - - -void -PositionVector::scaleAbsolute(double offset) { - Position centroid = getCentroid(); - for (int i = 0; i < static_cast(size()); i++) { - (*this)[i] = centroid + (((*this)[i] - centroid) + offset); - } -} - - -Position -PositionVector::getLineCenter() const { - if (size() == 1) { - return (*this)[0]; - } else { - return positionAtOffset(double((length() / 2.))); - } -} - - -double -PositionVector::length() const { - if (size() == 0) { - return 0; - } - double len = 0; - for (const_iterator i = begin(); i != end() - 1; i++) { - len += (*i).distanceTo(*(i + 1)); - } - return len; -} - - -double -PositionVector::length2D() const { - if (size() == 0) { - return 0; - } - double len = 0; - for (const_iterator i = begin(); i != end() - 1; i++) { - len += (*i).distanceTo2D(*(i + 1)); - } - return len; -} - - -double -PositionVector::area() const { - if (size() < 3) { - return 0; - } - double area = 0; - PositionVector tmp = *this; - if (!isClosed()) { // make sure its closed - tmp.push_back(tmp[0]); - } - const int endIndex = (int)tmp.size() - 1; - // http://en.wikipedia.org/wiki/Polygon - for (int i = 0; i < endIndex; i++) { - area += tmp[i].x() * tmp[i + 1].y() - tmp[i + 1].x() * tmp[i].y(); - } - if (area < 0) { // we whether we had cw or ccw order - area *= -1; - } - return area / 2; -} - - -bool -PositionVector::partialWithin(const AbstractPoly& poly, double offset) const { - if (size() < 2) { - return false; - } - for (const_iterator i = begin(); i != end(); i++) { - if (poly.around(*i, offset)) { - return true; - } - } - return false; -} - - -bool -PositionVector::crosses(const Position& p1, const Position& p2) const { - return intersects(p1, p2); -} - - -std::pair -PositionVector::splitAt(double where, bool use2D) const { - const double len = use2D ? length2D() : length(); - if (size() < 2) { - throw InvalidArgument("Vector to short for splitting"); - } - if (where < 0 || where > len) { - throw InvalidArgument("Invalid split position " + toString(where) + " for vector of length " + toString(len)); - } - if (where <= POSITION_EPS || where >= len - POSITION_EPS) { - WRITE_WARNING("Splitting vector close to end (pos: " + toString(where) + ", length: " + toString(len) + ")"); - } - PositionVector first, second; - first.push_back((*this)[0]); - double seen = 0; - const_iterator it = begin() + 1; - double next = use2D ? first.back().distanceTo2D(*it) : first.back().distanceTo(*it); - // see how many points we can add to first - while (where >= seen + next + POSITION_EPS) { - seen += next; - first.push_back(*it); - it++; - next = use2D ? first.back().distanceTo2D(*it) : first.back().distanceTo(*it); - } - if (fabs(where - (seen + next)) > POSITION_EPS || it == end() - 1) { - // we need to insert a new point because 'where' is not close to an - // existing point or it is to close to the endpoint - const Position p = (use2D - ? positionAtOffset2D(first.back(), *it, where - seen) - : positionAtOffset(first.back(), *it, where - seen)); - first.push_back(p); - second.push_back(p); - } else { - first.push_back(*it); - } - // add the remaining points to second - for (; it != end(); it++) { - second.push_back(*it); - } - assert(first.size() >= 2); - assert(second.size() >= 2); - assert(first.back() == second.front()); - assert(fabs((use2D ? first.length2D() + second.length2D() : first.length() + second.length()) - len) < 2 * POSITION_EPS); - return std::pair(first, second); -} - - -std::ostream& -operator<<(std::ostream& os, const PositionVector& geom) { - for (PositionVector::const_iterator i = geom.begin(); i != geom.end(); i++) { - if (i != geom.begin()) { - os << " "; - } - os << (*i); - } - return os; -} - - -void -PositionVector::sortAsPolyCWByAngle() { - std::sort(begin(), end(), as_poly_cw_sorter()); -} - - -void -PositionVector::add(double xoff, double yoff, double zoff) { - for (int i = 0; i < (int)size(); i++) { - (*this)[i].add(xoff, yoff, zoff); - } -} - - -void -PositionVector::sub(const Position& offset) { - sub(offset.x(), offset.y(), offset.z()); -} - - -void -PositionVector::sub(double xoff, double yoff, double zoff) { - for (int i = 0; i < (int)size(); i++) { - (*this)[i].add(-xoff, -yoff, -zoff); - } -} - - -void -PositionVector::add(const Position& offset) { - add(offset.x(), offset.y(), offset.z()); -} - - -PositionVector -PositionVector::added(const Position& offset) const { - PositionVector pv; - for (auto i1 = begin(); i1 != end(); ++i1) { - pv.push_back(*i1 + offset); - } - return pv; -} - - -void -PositionVector::mirrorX() { - for (int i = 0; i < (int)size(); i++) { - (*this)[i].mul(1, -1); - } -} - - -PositionVector::as_poly_cw_sorter::as_poly_cw_sorter() {} - - -int -PositionVector::as_poly_cw_sorter::operator()(const Position& p1, const Position& p2) const { - return atan2(p1.x(), p1.y()) < atan2(p2.x(), p2.y()); -} - - -void -PositionVector::sortByIncreasingXY() { - std::sort(begin(), end(), increasing_x_y_sorter()); -} - - -PositionVector::increasing_x_y_sorter::increasing_x_y_sorter() {} - - -int -PositionVector::increasing_x_y_sorter::operator()(const Position& p1, const Position& p2) const { - if (p1.x() != p2.x()) { - return p1.x() < p2.x(); - } - return p1.y() < p2.y(); -} - - -double -PositionVector::isLeft(const Position& P0, const Position& P1, const Position& P2) const { - return (P1.x() - P0.x()) * (P2.y() - P0.y()) - (P2.x() - P0.x()) * (P1.y() - P0.y()); -} - - -void -PositionVector::append(const PositionVector& v, double sameThreshold) { - if ((size() > 0) && (v.size() > 0) && (back().distanceTo(v[0]) < sameThreshold)) { - copy(v.begin() + 1, v.end(), back_inserter(*this)); - } else { - copy(v.begin(), v.end(), back_inserter(*this)); - } -} - - -PositionVector -PositionVector::getSubpart(double beginOffset, double endOffset) const { - PositionVector ret; - Position begPos = front(); - if (beginOffset > POSITION_EPS) { - begPos = positionAtOffset(beginOffset); - } - Position endPos = back(); - if (endOffset < length() - POSITION_EPS) { - endPos = positionAtOffset(endOffset); - } - ret.push_back(begPos); - - double seen = 0; - const_iterator i = begin(); - // skip previous segments - while ((i + 1) != end() - && - seen + (*i).distanceTo(*(i + 1)) < beginOffset) { - seen += (*i).distanceTo(*(i + 1)); - i++; - } - // append segments in between - while ((i + 1) != end() - && - seen + (*i).distanceTo(*(i + 1)) < endOffset) { - - ret.push_back_noDoublePos(*(i + 1)); - seen += (*i).distanceTo(*(i + 1)); - i++; - } - // append end - ret.push_back_noDoublePos(endPos); - if (ret.size() == 1) { - ret.push_back(endPos); - } - return ret; -} - - -PositionVector -PositionVector::getSubpart2D(double beginOffset, double endOffset) const { - if (size() == 0) { - return PositionVector(); - } - PositionVector ret; - Position begPos = front(); - if (beginOffset > POSITION_EPS) { - begPos = positionAtOffset2D(beginOffset); - } - Position endPos = back(); - if (endOffset < length2D() - POSITION_EPS) { - endPos = positionAtOffset2D(endOffset); - } - ret.push_back(begPos); - - double seen = 0; - const_iterator i = begin(); - // skip previous segments - while ((i + 1) != end() - && - seen + (*i).distanceTo2D(*(i + 1)) < beginOffset) { - seen += (*i).distanceTo2D(*(i + 1)); - i++; - } - // append segments in between - while ((i + 1) != end() - && - seen + (*i).distanceTo2D(*(i + 1)) < endOffset) { - - ret.push_back_noDoublePos(*(i + 1)); - seen += (*i).distanceTo2D(*(i + 1)); - i++; - } - // append end - ret.push_back_noDoublePos(endPos); - if (ret.size() == 1) { - ret.push_back(endPos); - } - return ret; -} - - -PositionVector -PositionVector::getSubpartByIndex(int beginIndex, int count) const { - if (size() == 0) { - return PositionVector(); - } - if (beginIndex < 0) { - beginIndex += (int)size(); - } - assert(count >= 0); - assert(beginIndex < (int)size()); - assert(beginIndex + count <= (int)size()); - PositionVector result; - for (int i = beginIndex; i < beginIndex + count; ++i) { - result.push_back((*this)[i]); - } - return result; -} - - -double -PositionVector::beginEndAngle() const { - if (size() == 0) { - return INVALID_DOUBLE; - } - return front().angleTo2D(back()); -} - - -double -PositionVector::nearest_offset_to_point2D(const Position& p, bool perpendicular) const { - if (size() == 0) { - return INVALID_DOUBLE; - } - double minDist = std::numeric_limits::max(); - double nearestPos = GeomHelper::INVALID_OFFSET; - double seen = 0; - for (const_iterator i = begin(); i != end() - 1; i++) { - const double pos = - GeomHelper::nearest_offset_on_line_to_point2D(*i, *(i + 1), p, perpendicular); - const double dist = pos == GeomHelper::INVALID_OFFSET ? minDist : p.distanceTo2D(positionAtOffset2D(*i, *(i + 1), pos)); - if (dist < minDist) { - nearestPos = pos + seen; - minDist = dist; - } - if (perpendicular && i != begin() && pos == GeomHelper::INVALID_OFFSET) { - // even if perpendicular is set we still need to check the distance to the inner points - const double cornerDist = p.distanceTo2D(*i); - if (cornerDist < minDist) { - const double pos1 = - GeomHelper::nearest_offset_on_line_to_point2D(*(i - 1), *i, p, false); - const double pos2 = - GeomHelper::nearest_offset_on_line_to_point2D(*i, *(i + 1), p, false); - if (pos1 == (*(i - 1)).distanceTo2D(*i) && pos2 == 0.) { - nearestPos = seen; - minDist = cornerDist; - } - } - } - seen += (*i).distanceTo2D(*(i + 1)); - } - return nearestPos; -} - - -double -PositionVector::nearest_offset_to_point25D(const Position& p, bool perpendicular) const { - if (size() == 0) { - return INVALID_DOUBLE; - } - double minDist = std::numeric_limits::max(); - double nearestPos = GeomHelper::INVALID_OFFSET; - double seen = 0; - for (const_iterator i = begin(); i != end() - 1; i++) { - const double pos = - GeomHelper::nearest_offset_on_line_to_point2D(*i, *(i + 1), p, perpendicular); - const double dist = pos == GeomHelper::INVALID_OFFSET ? minDist : p.distanceTo2D(positionAtOffset2D(*i, *(i + 1), pos)); - if (dist < minDist) { - const double pos25D = pos * (*i).distanceTo(*(i + 1)) / (*i).distanceTo2D(*(i + 1)); - nearestPos = pos25D + seen; - minDist = dist; - } - if (perpendicular && i != begin() && pos == GeomHelper::INVALID_OFFSET) { - // even if perpendicular is set we still need to check the distance to the inner points - const double cornerDist = p.distanceTo2D(*i); - if (cornerDist < minDist) { - const double pos1 = - GeomHelper::nearest_offset_on_line_to_point2D(*(i - 1), *i, p, false); - const double pos2 = - GeomHelper::nearest_offset_on_line_to_point2D(*i, *(i + 1), p, false); - if (pos1 == (*(i - 1)).distanceTo2D(*i) && pos2 == 0.) { - nearestPos = seen; - minDist = cornerDist; - } - } - } - seen += (*i).distanceTo(*(i + 1)); - } - return nearestPos; -} - - -Position -PositionVector::transformToVectorCoordinates(const Position& p, bool extend) const { - if (size() == 0) { - return Position::INVALID; - } - // @toDo this duplicates most of the code in nearest_offset_to_point2D. It should be refactored - if (extend) { - PositionVector extended = *this; - const double dist = 2 * distance2D(p); - extended.extrapolate(dist); - return extended.transformToVectorCoordinates(p) - Position(dist, 0); - } - double minDist = std::numeric_limits::max(); - double nearestPos = -1; - double seen = 0; - int sign = 1; - for (const_iterator i = begin(); i != end() - 1; i++) { - const double pos = - GeomHelper::nearest_offset_on_line_to_point2D(*i, *(i + 1), p, true); - const double dist = pos < 0 ? minDist : p.distanceTo2D(positionAtOffset(*i, *(i + 1), pos)); - if (dist < minDist) { - nearestPos = pos + seen; - minDist = dist; - sign = isLeft(*i, *(i + 1), p) >= 0 ? -1 : 1; - } - if (i != begin() && pos == GeomHelper::INVALID_OFFSET) { - // even if perpendicular is set we still need to check the distance to the inner points - const double cornerDist = p.distanceTo2D(*i); - if (cornerDist < minDist) { - const double pos1 = - GeomHelper::nearest_offset_on_line_to_point2D(*(i - 1), *i, p, false); - const double pos2 = - GeomHelper::nearest_offset_on_line_to_point2D(*i, *(i + 1), p, false); - if (pos1 == (*(i - 1)).distanceTo2D(*i) && pos2 == 0.) { - nearestPos = seen; - minDist = cornerDist; - sign = isLeft(*(i - 1), *i, p) >= 0 ? -1 : 1; - } - } - } - seen += (*i).distanceTo2D(*(i + 1)); - } - if (nearestPos != -1) { - return Position(nearestPos, sign * minDist); - } else { - return Position::INVALID; - } -} - - -int -PositionVector::indexOfClosest(const Position& p) const { - if (size() == 0) { - return -1; - } - double minDist = std::numeric_limits::max(); - double dist; - int closest = 0; - for (int i = 0; i < (int)size(); i++) { - dist = p.distanceTo((*this)[i]); - if (dist < minDist) { - closest = i; - minDist = dist; - } - } - return closest; -} - - -int -PositionVector::insertAtClosest(const Position& p, bool interpolateZ) { - if (size() == 0) { - return -1; - } - double minDist = std::numeric_limits::max(); - int insertionIndex = 1; - for (int i = 0; i < (int)size() - 1; i++) { - const double length = GeomHelper::nearest_offset_on_line_to_point2D((*this)[i], (*this)[i + 1], p, false); - const Position& outIntersection = PositionVector::positionAtOffset2D((*this)[i], (*this)[i + 1], length); - const double dist = p.distanceTo2D(outIntersection); - if (dist < minDist) { - insertionIndex = i + 1; - minDist = dist; - } - } - // check if we have to adjust Position Z - if (interpolateZ) { - // obtain previous and next Z - const double previousZ = (begin() + (insertionIndex - 1))->z(); - const double nextZ = (begin() + insertionIndex)->z(); - // insert new position using x and y of p, and the new z - insert(begin() + insertionIndex, Position(p.x(), p.y(), ((previousZ + nextZ) / 2.0))); - } else { - insert(begin() + insertionIndex, p); - } - return insertionIndex; -} - - -int -PositionVector::removeClosest(const Position& p) { - if (size() == 0) { - return -1; - } - double minDist = std::numeric_limits::max(); - int removalIndex = 0; - for (int i = 0; i < (int)size(); i++) { - const double dist = p.distanceTo2D((*this)[i]); - if (dist < minDist) { - removalIndex = i; - minDist = dist; - } - } - erase(begin() + removalIndex); - return removalIndex; -} - - -std::vector -PositionVector::intersectsAtLengths2D(const PositionVector& other) const { - std::vector ret; - if (other.size() == 0) { - return ret; - } - for (const_iterator i = other.begin(); i != other.end() - 1; i++) { - std::vector atSegment = intersectsAtLengths2D(*i, *(i + 1)); - copy(atSegment.begin(), atSegment.end(), back_inserter(ret)); - } - return ret; -} - - -std::vector -PositionVector::intersectsAtLengths2D(const Position& lp1, const Position& lp2) const { - std::vector ret; - if (size() == 0) { - return ret; - } - double pos = 0; - for (const_iterator i = begin(); i != end() - 1; i++) { - const Position& p1 = *i; - const Position& p2 = *(i + 1); - double x, y, m; - if (intersects(p1, p2, lp1, lp2, 0., &x, &y, &m)) { - ret.push_back(Position(x, y).distanceTo2D(p1) + pos); - } - pos += p1.distanceTo2D(p2); - } - return ret; -} - - -void -PositionVector::extrapolate(const double val, const bool onlyFirst, const bool onlyLast) { - if (size() > 0) { - Position& p1 = (*this)[0]; - Position& p2 = (*this)[1]; - const Position offset = (p2 - p1) * (val / p1.distanceTo(p2)); - if (!onlyLast) { - p1.sub(offset); - } - if (!onlyFirst) { - if (size() == 2) { - p2.add(offset); - } else { - const Position& e1 = (*this)[-2]; - Position& e2 = (*this)[-1]; - e2.sub((e1 - e2) * (val / e1.distanceTo(e2))); - } - } - } -} - - -void -PositionVector::extrapolate2D(const double val, const bool onlyFirst) { - if (size() > 0) { - Position& p1 = (*this)[0]; - Position& p2 = (*this)[1]; - if (p1.distanceTo2D(p2) > 0) { - const Position offset = (p2 - p1) * (val / p1.distanceTo2D(p2)); - p1.sub(offset); - if (!onlyFirst) { - if (size() == 2) { - p2.add(offset); - } else { - const Position& e1 = (*this)[-2]; - Position& e2 = (*this)[-1]; - e2.sub((e1 - e2) * (val / e1.distanceTo2D(e2))); - } - } - } - } -} - - -PositionVector -PositionVector::reverse() const { - PositionVector ret; - for (const_reverse_iterator i = rbegin(); i != rend(); i++) { - ret.push_back(*i); - } - return ret; -} - - -Position -PositionVector::sideOffset(const Position& beg, const Position& end, const double amount) { - const double scale = amount / beg.distanceTo2D(end); - return Position((beg.y() - end.y()) * scale, (end.x() - beg.x()) * scale); -} - - -void -PositionVector::move2side(double amount, double maxExtension) { - if (size() < 2) { - return; - } - removeDoublePoints(POSITION_EPS, true); - if (length2D() == 0) { - return; - } - PositionVector shape; - for (int i = 0; i < static_cast(size()); i++) { - if (i == 0) { - const Position& from = (*this)[i]; - const Position& to = (*this)[i + 1]; - if (from != to) { - shape.push_back(from - sideOffset(from, to, amount)); - } - } else if (i == static_cast(size()) - 1) { - const Position& from = (*this)[i - 1]; - const Position& to = (*this)[i]; - if (from != to) { - shape.push_back(to - sideOffset(from, to, amount)); - } - } else { - const Position& from = (*this)[i - 1]; - const Position& me = (*this)[i]; - const Position& to = (*this)[i + 1]; - PositionVector fromMe(from, me); - fromMe.extrapolate2D(me.distanceTo2D(to)); - const double extrapolateDev = fromMe[1].distanceTo2D(to); - if (fabs(extrapolateDev) < POSITION_EPS) { - // parallel case, just shift the middle point - shape.push_back(me - sideOffset(from, to, amount)); - } else if (fabs(extrapolateDev - 2 * me.distanceTo2D(to)) < POSITION_EPS) { - // counterparallel case, just shift the middle point - PositionVector fromMe(from, me); - fromMe.extrapolate2D(amount); - shape.push_back(fromMe[1]); - } else { - Position offsets = sideOffset(from, me, amount); - Position offsets2 = sideOffset(me, to, amount); - PositionVector l1(from - offsets, me - offsets); - PositionVector l2(me - offsets2, to - offsets2); - Position meNew = l1.intersectionPosition2D(l2[0], l2[1], maxExtension); - if (meNew == Position::INVALID) { - throw InvalidArgument("no line intersection"); - } - meNew = meNew + Position(0, 0, me.z()); - shape.push_back(meNew); - } - // copy original z value - shape.back().set(shape.back().x(), shape.back().y(), me.z()); - } - } - *this = shape; -} - - -void -PositionVector::move2side(std::vector amount, double maxExtension) { - if (size() < 2) { - return; - } - if (length2D() == 0) { - return; - } - if (size() != amount.size()) { - throw InvalidArgument("Numer of offsets (" + toString(amount.size()) - + ") does not match number of points (" + toString(size()) + ")"); - } - PositionVector shape; - for (int i = 0; i < static_cast(size()); i++) { - if (i == 0) { - const Position& from = (*this)[i]; - const Position& to = (*this)[i + 1]; - if (from != to) { - shape.push_back(from - sideOffset(from, to, amount[i])); - } - } else if (i == static_cast(size()) - 1) { - const Position& from = (*this)[i - 1]; - const Position& to = (*this)[i]; - if (from != to) { - shape.push_back(to - sideOffset(from, to, amount[i])); - } - } else { - const Position& from = (*this)[i - 1]; - const Position& me = (*this)[i]; - const Position& to = (*this)[i + 1]; - PositionVector fromMe(from, me); - fromMe.extrapolate2D(me.distanceTo2D(to)); - const double extrapolateDev = fromMe[1].distanceTo2D(to); - if (fabs(extrapolateDev) < POSITION_EPS) { - // parallel case, just shift the middle point - shape.push_back(me - sideOffset(from, to, amount[i])); - } else if (fabs(extrapolateDev - 2 * me.distanceTo2D(to)) < POSITION_EPS) { - // counterparallel case, just shift the middle point - PositionVector fromMe(from, me); - fromMe.extrapolate2D(amount[i]); - shape.push_back(fromMe[1]); - } else { - Position offsets = sideOffset(from, me, amount[i]); - Position offsets2 = sideOffset(me, to, amount[i]); - PositionVector l1(from - offsets, me - offsets); - PositionVector l2(me - offsets2, to - offsets2); - Position meNew = l1.intersectionPosition2D(l2[0], l2[1], maxExtension); - if (meNew == Position::INVALID) { - throw InvalidArgument("no line intersection"); - } - meNew = meNew + Position(0, 0, me.z()); - shape.push_back(meNew); - } - // copy original z value - shape.back().set(shape.back().x(), shape.back().y(), me.z()); - } - } - *this = shape; -} - -double -PositionVector::angleAt2D(int pos) const { - if ((pos + 1) < (int)size()) { - return (*this)[pos].angleTo2D((*this)[pos + 1]); - } else { - return INVALID_DOUBLE; - } -} - - -void -PositionVector::closePolygon() { - if ((size() != 0) && ((*this)[0] != back())) { - push_back((*this)[0]); - } -} - - -std::vector -PositionVector::distances(const PositionVector& s, bool perpendicular) const { - std::vector ret; - const_iterator i; - for (i = begin(); i != end(); i++) { - const double dist = s.distance2D(*i, perpendicular); - if (dist != GeomHelper::INVALID_OFFSET) { - ret.push_back(dist); - } - } - for (i = s.begin(); i != s.end(); i++) { - const double dist = distance2D(*i, perpendicular); - if (dist != GeomHelper::INVALID_OFFSET) { - ret.push_back(dist); - } - } - return ret; -} - - -double -PositionVector::distance2D(const Position& p, bool perpendicular) const { - if (size() == 0) { - return std::numeric_limits::max(); - } else if (size() == 1) { - return front().distanceTo(p); - } - const double nearestOffset = nearest_offset_to_point2D(p, perpendicular); - if (nearestOffset == GeomHelper::INVALID_OFFSET) { - return GeomHelper::INVALID_OFFSET; - } else { - return p.distanceTo2D(positionAtOffset2D(nearestOffset)); - } -} - - -void -PositionVector::push_front(const Position& p) { - if (empty()) { - push_back(p); - } else { - insert(begin(), p); - } -} - - -void -PositionVector::pop_front() { - if (empty()) { - throw ProcessError("PositionVector is empty"); - } else { - erase(begin()); - } -} - - -void -PositionVector::push_back_noDoublePos(const Position& p) { - if (size() == 0 || !p.almostSame(back())) { - push_back(p); - } -} - - -void -PositionVector::push_front_noDoublePos(const Position& p) { - if ((size() == 0) || !p.almostSame(front())) { - push_front(p); - } -} - - -void -PositionVector::insert_noDoublePos(const std::vector::iterator& at, const Position& p) { - if (at == begin()) { - push_front_noDoublePos(p); - } else if (at == end()) { - push_back_noDoublePos(p); - } else { - if (!p.almostSame(*at) && !p.almostSame(*(at - 1))) { - insert(at, p); - } - } -} - - -bool -PositionVector::isClosed() const { - return (size() >= 2) && ((*this)[0] == back()); -} - - -bool -PositionVector::isNAN() const { - // iterate over all positions and check if is NAN - for (auto i = begin(); i != end(); i++) { - if (i->isNAN()) { - return true; - } - } - // all ok, then return false - return false; -} - - -void -PositionVector::removeDoublePoints(double minDist, bool assertLength) { - if (size() > 1) { - iterator last = begin(); - for (iterator i = begin() + 1; i != end() && (!assertLength || size() > 2);) { - if (last->almostSame(*i, minDist)) { - if (i + 1 == end()) { - // special case: keep the last point and remove the next-to-last - erase(last); - i = end(); - } else { - i = erase(i); - } - } else { - last = i; - ++i; - } - } - } -} - - -bool -PositionVector::operator==(const PositionVector& v2) const { - return static_cast(*this) == static_cast(v2); -} - - -bool -PositionVector::operator!=(const PositionVector& v2) const { - return static_cast(*this) != static_cast(v2); -} - -PositionVector -PositionVector::operator-(const PositionVector& v2) const { - if (length() != v2.length()) { - WRITE_ERROR("Trying to substract PositionVectors of different lengths."); - } - PositionVector pv; - auto i1 = begin(); - auto i2 = v2.begin(); - while (i1 != end()) { - pv.add(*i1 - *i2); - } - return pv; -} - -PositionVector -PositionVector::operator+(const PositionVector& v2) const { - if (length() != v2.length()) { - WRITE_ERROR("Trying to substract PositionVectors of different lengths."); - } - PositionVector pv; - auto i1 = begin(); - auto i2 = v2.begin(); - while (i1 != end()) { - pv.add(*i1 + *i2); - } - return pv; -} - -bool -PositionVector::hasElevation() const { - if (size() < 2) { - return false; - } - for (const_iterator i = begin(); i != end() - 1; i++) { - if ((*i).z() != (*(i + 1)).z()) { - return true; - } - } - return false; -} - - -bool -PositionVector::intersects(const Position& p11, const Position& p12, const Position& p21, const Position& p22, const double withinDist, double* x, double* y, double* mu) { - const double eps = std::numeric_limits::epsilon(); - const double denominator = (p22.y() - p21.y()) * (p12.x() - p11.x()) - (p22.x() - p21.x()) * (p12.y() - p11.y()); - const double numera = (p22.x() - p21.x()) * (p11.y() - p21.y()) - (p22.y() - p21.y()) * (p11.x() - p21.x()); - const double numerb = (p12.x() - p11.x()) * (p11.y() - p21.y()) - (p12.y() - p11.y()) * (p11.x() - p21.x()); - /* Are the lines coincident? */ - if (fabs(numera) < eps && fabs(numerb) < eps && fabs(denominator) < eps) { - double a1; - double a2; - double a3; - double a4; - double a = -1e12; - if (p11.x() != p12.x()) { - a1 = p11.x() < p12.x() ? p11.x() : p12.x(); - a2 = p11.x() < p12.x() ? p12.x() : p11.x(); - a3 = p21.x() < p22.x() ? p21.x() : p22.x(); - a4 = p21.x() < p22.x() ? p22.x() : p21.x(); - } else { - a1 = p11.y() < p12.y() ? p11.y() : p12.y(); - a2 = p11.y() < p12.y() ? p12.y() : p11.y(); - a3 = p21.y() < p22.y() ? p21.y() : p22.y(); - a4 = p21.y() < p22.y() ? p22.y() : p21.y(); - } - if (a1 <= a3 && a3 <= a2) { - if (a4 < a2) { - a = (a3 + a4) / 2; - } else { - a = (a2 + a3) / 2; - } - } - if (a3 <= a1 && a1 <= a4) { - if (a2 < a4) { - a = (a1 + a2) / 2; - } else { - a = (a1 + a4) / 2; - } - } - if (a != -1e12) { - if (x != nullptr) { - if (p11.x() != p12.x()) { - *mu = (a - p11.x()) / (p12.x() - p11.x()); - *x = a; - *y = p11.y() + (*mu) * (p12.y() - p11.y()); - } else { - *x = p11.x(); - *y = a; - if (p12.y() == p11.y()) { - *mu = 0; - } else { - *mu = (a - p11.y()) / (p12.y() - p11.y()); - } - } - } - return true; - } - return false; - } - /* Are the lines parallel */ - if (fabs(denominator) < eps) { - return false; - } - /* Is the intersection along the segments */ - double mua = numera / denominator; - /* reduce rounding errors for lines ending in the same point */ - if (fabs(p12.x() - p22.x()) < eps && fabs(p12.y() - p22.y()) < eps) { - mua = 1.; - } else { - const double offseta = withinDist / p11.distanceTo2D(p12); - const double offsetb = withinDist / p21.distanceTo2D(p22); - const double mub = numerb / denominator; - if (mua < -offseta || mua > 1 + offseta || mub < -offsetb || mub > 1 + offsetb) { - return false; - } - } - if (x != nullptr) { - *x = p11.x() + mua * (p12.x() - p11.x()); - *y = p11.y() + mua * (p12.y() - p11.y()); - *mu = mua; - } - return true; -} - - -void -PositionVector::rotate2D(double angle) { - const double s = sin(angle); - const double c = cos(angle); - for (int i = 0; i < (int)size(); i++) { - const double x = (*this)[i].x(); - const double y = (*this)[i].y(); - const double z = (*this)[i].z(); - const double xnew = x * c - y * s; - const double ynew = x * s + y * c; - (*this)[i].set(xnew, ynew, z); - } -} - - -PositionVector -PositionVector::simplified() const { - PositionVector result = *this; - bool changed = true; - while (changed && result.size() > 3) { - changed = false; - for (int i = 0; i < (int)result.size(); i++) { - const Position& p1 = result[i]; - const Position& p2 = result[(i + 2) % result.size()]; - const int middleIndex = (i + 1) % result.size(); - const Position& p0 = result[middleIndex]; - // https://en.wikipedia.org/wiki/Distance_from_a_point_to_a_line#Line_defined_by_two_points - const double triangleArea2 = fabs((p2.y() - p1.y()) * p0.x() - (p2.x() - p1.x()) * p0.y() + p2.x() * p1.y() - p2.y() * p1.x()); - const double distIK = p1.distanceTo2D(p2); - if (distIK > NUMERICAL_EPS && triangleArea2 / distIK < NUMERICAL_EPS) { - changed = true; - result.erase(result.begin() + middleIndex); - break; - } - } - } - return result; -} - - -PositionVector -PositionVector::getOrthogonal(const Position& p, double extend, bool before, double length, double deg) const { - PositionVector result; - PositionVector tmp = *this; - tmp.extrapolate2D(extend); - const double baseOffset = tmp.nearest_offset_to_point2D(p); - if (baseOffset == GeomHelper::INVALID_OFFSET || size() < 2) { - // fail - return result; - } - Position base = tmp.positionAtOffset2D(baseOffset); - const int closestIndex = tmp.indexOfClosest(base); - const double closestOffset = tmp.offsetAtIndex2D(closestIndex); - result.push_back(base); - if (fabs(baseOffset - closestOffset) > NUMERICAL_EPS) { - result.push_back(tmp[closestIndex]); - if ((closestOffset < baseOffset) != before) { - deg *= -1; - } - } else if (before) { - // take the segment before closestIndex if possible - if (closestIndex > 0) { - result.push_back(tmp[closestIndex - 1]); - } else { - result.push_back(tmp[1]); - deg *= -1; - } - } else { - // take the segment after closestIndex if possible - if (closestIndex < (int)size() - 1) { - result.push_back(tmp[closestIndex + 1]); - } else { - result.push_back(tmp[-1]); - deg *= -1; - } - } - result = result.getSubpart2D(0, length); - // rotate around base - result.add(base * -1); - result.rotate2D(DEG2RAD(deg)); - result.add(base); - return result; -} - - -PositionVector -PositionVector::smoothedZFront(double dist) const { - PositionVector result = *this; - if (size() == 0) { - return result; - } - const double z0 = (*this)[0].z(); - // the z-delta of the first segment - const double dz = (*this)[1].z() - z0; - // if the shape only has 2 points it is as smooth as possible already - if (size() > 2 && dz != 0) { - dist = MIN2(dist, length2D()); - // check wether we need to insert a new point at dist - Position pDist = positionAtOffset2D(dist); - int iLast = indexOfClosest(pDist); - // prevent close spacing to reduce impact of rounding errors in z-axis - if (pDist.distanceTo2D((*this)[iLast]) > POSITION_EPS * 20) { - iLast = result.insertAtClosest(pDist, false); - } - double dist2 = result.offsetAtIndex2D(iLast); - const double dz2 = result[iLast].z() - z0; - double seen = 0; - for (int i = 1; i < iLast; ++i) { - seen += result[i].distanceTo2D(result[i - 1]); - result[i].set(result[i].x(), result[i].y(), z0 + dz2 * seen / dist2); - } - } - return result; - -} - - -PositionVector -PositionVector::interpolateZ(double zStart, double zEnd) const { - PositionVector result = *this; - if (size() == 0) { - return result; - } - result[0].setz(zStart); - result[-1].setz(zEnd); - const double dz = zEnd - zStart; - const double length = length2D(); - double seen = 0; - for (int i = 1; i < (int)size() - 1; ++i) { - seen += result[i].distanceTo2D(result[i - 1]); - result[i].setz(zStart + dz * seen / length); - } - return result; -} - - -PositionVector -PositionVector::resample(double maxLength) const { - PositionVector result; - if (maxLength == 0) { - return result; - } - const double length = length2D(); - if (length < POSITION_EPS) { - return result; - } - maxLength = length / ceil(length / maxLength); - for (double pos = 0; pos <= length; pos += maxLength) { - result.push_back(positionAtOffset2D(pos)); - } - return result; -} - - -double -PositionVector::offsetAtIndex2D(int index) const { - if (index < 0 || index >= (int)size()) { - return GeomHelper::INVALID_OFFSET; - } - double seen = 0; - for (int i = 1; i <= index; ++i) { - seen += (*this)[i].distanceTo2D((*this)[i - 1]); - } - return seen; -} - - -double -PositionVector::getMaxGrade(double& maxJump) const { - double result = 0; - for (int i = 1; i < (int)size(); ++i) { - const Position& p1 = (*this)[i - 1]; - const Position& p2 = (*this)[i]; - const double distZ = fabs(p1.z() - p2.z()); - const double dist2D = p1.distanceTo2D(p2); - if (dist2D == 0) { - maxJump = MAX2(maxJump, distZ); - } else { - result = MAX2(result, distZ / dist2D); - } - } - return result; -} - - -PositionVector -PositionVector::bezier(int numPoints) { - // inspired by David F. Rogers - assert(size() < 33); - static const double fac[33] = { - 1.0, 1.0, 2.0, 6.0, 24.0, 120.0, 720.0, 5040.0, 40320.0, 362880.0, 3628800.0, 39916800.0, 479001600.0, - 6227020800.0, 87178291200.0, 1307674368000.0, 20922789888000.0, 355687428096000.0, 6402373705728000.0, - 121645100408832000.0, 2432902008176640000.0, 51090942171709440000.0, 1124000727777607680000.0, - 25852016738884976640000.0, 620448401733239439360000.0, 15511210043330985984000000.0, - 403291461126605635584000000.0, 10888869450418352160768000000.0, 304888344611713860501504000000.0, - 8841761993739701954543616000000.0, 265252859812191058636308480000000.0, - 8222838654177922817725562880000000.0, 263130836933693530167218012160000000.0 - }; - PositionVector ret; - const int npts = (int)size(); - // calculate the points on the Bezier curve - const double step = (double) 1.0 / (numPoints - 1); - double t = 0.; - Position prev; - for (int i1 = 0; i1 < numPoints; i1++) { - if ((1.0 - t) < 5e-6) { - t = 1.0; - } - double x = 0., y = 0., z = 0.; - for (int i = 0; i < npts; i++) { - const double ti = (i == 0) ? 1.0 : pow(t, i); - const double tni = (npts == i + 1) ? 1.0 : pow(1 - t, npts - i - 1); - const double basis = fac[npts - 1] / (fac[i] * fac[npts - 1 - i]) * ti * tni; - x += basis * at(i).x(); - y += basis * at(i).y(); - z += basis * at(i).z(); - } - t += step; - Position current(x, y, z); - if (prev != current && !ISNAN(x) && !ISNAN(y) && !ISNAN(z)) { - ret.push_back(current); - } - prev = current; - } - return ret; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/utils/geom/PositionVector.h b/Util/OSM2ODR/src/utils/geom/PositionVector.h deleted file mode 100644 index 2258a99d6..000000000 --- a/Util/OSM2ODR/src/utils/geom/PositionVector.h +++ /dev/null @@ -1,420 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file PositionVector.h -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date Sept 2002 -/// -// A list of positions -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include "AbstractPoly.h" - - -// =========================================================================== -// class declarations -// =========================================================================== - -class Boundary; - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class PositionVector - * @brief A list of positions - */ -class PositionVector : public AbstractPoly, private std::vector { - -private: - /// @brief vector of position - typedef std::vector vp; - -public: - /// @brief Constructor. Creates an empty position vector - PositionVector(); - - /// @brief Copy Constructor. Create a positionVector with the same elements as other positionVector - /// @param[in] v The vector to copy - PositionVector(const std::vector& v); - - /// @brief Parameter Constructor. Create a positionVector using a part of other positionVector - /// @param[in] beg The begin iterator for copy - /// @param[in] end The end iterator to copy - PositionVector(const std::vector::const_iterator beg, const std::vector::const_iterator end); - - /// @brief Parameter Constructor used for lines - /// @param[in] p1 the first position - /// @param[in] p2 the second position - PositionVector(const Position& p1, const Position& p2); - - /// @brief Destructor - ~PositionVector(); - - /// @brief empty Vector - static const PositionVector EMPTY; - - /// @name methode for iterate over PositionVector - /// @{ - /// @brief iterator - using vp::iterator; - - /// @brief constant iterator - using vp::const_iterator; - - /// @brief contant reference - using vp::const_reference; - - /// @brief value type - using vp::value_type; - - /// @brief begin of position vector - using vp::begin; - - /// @brief end of position vector - using vp::end; - - /// @brief push a position in the back of position vector - using vp::push_back; - - /// @brief push a position in the front of position vector - using vp::pop_back; - - /// @brief clear all elements of position vector - using vp::clear; - /// @brief returns size of position vector - using vp::size; - - /// @brief get the front element of position vector - using vp::front; - - /// @brief get back element of position vector - using vp::back; - - /// @brief get a reference of position vector - using vp::reference; - - /// @brief erase a position of position vector gived by iterator - using vp::erase; - - /// @brief insert a position in position vector gived by iterator - using vp::insert; - /// @} - - /// @brief Returns the information whether the position vector describes a polygon lying around the given point - /// @note The optional offset is added to the polygon's boundaries - bool around(const Position& p, double offset = 0) const; - - /// @brief Returns the information whether the given polygon overlaps with this - /// @note Again a boundary may be specified - bool overlapsWith(const AbstractPoly& poly, double offset = 0) const; - - /// @brief Returns the maximum overlaps between this and the given polygon (when not separated by at least zThreshold) - double getOverlapWith(const PositionVector& poly, double zThreshold) const; - - /// @brief Returns the information whether this list of points interesects the given line - bool intersects(const Position& p1, const Position& p2) const; - - /// @brief Returns the information whether this list of points interesects one the given lines - bool intersects(const PositionVector& v1) const; - - /// @brief Returns the position of the intersection - Position intersectionPosition2D(const Position& p1, const Position& p2, const double withinDist = 0.) const; - - /// @brief For all intersections between this vector and other, return the 2D-length of the subvector from this vectors start to the intersection - std::vector intersectsAtLengths2D(const PositionVector& other) const; - - /// @brief For all intersections between this vector and line, return the 2D-length of the subvector from this vectors start to the intersection - std::vector intersectsAtLengths2D(const Position& lp1, const Position& lp2) const; - - /// @brief Returns the position of the intersection - Position intersectionPosition2D(const PositionVector& v1) const; - - /// @brief ensures that the last position equals the first - void closePolygon(); - - /// @brief returns the constat position at the given index - /// @ToDo !!! exceptions? - const Position& operator[](int index) const; - - /// @brief returns the position at the given index - Position& operator[](int index); - - /// @brief Returns the position at the given length - Position positionAtOffset(double pos, double lateralOffset = 0) const; - - /// @brief Returns the position at the given length - Position positionAtOffset2D(double pos, double lateralOffset = 0) const; - - /// @brief Returns the rotation at the given length - double rotationAtOffset(double pos) const; - - /// @brief Returns the rotation at the given length - double rotationDegreeAtOffset(double pos) const; - - /// @brief Returns the slope at the given length - double slopeDegreeAtOffset(double pos) const; - - /// @brief Returns the position between the two given point at the specified position - static Position positionAtOffset(const Position& p1, const Position& p2, double pos, double lateralOffset = 0.); - - /// Returns the position between the two given point at the specified position - static Position positionAtOffset2D(const Position& p1, const Position& p2, double pos, double lateralOffset = 0.); - - /// @brief Returns a boundary enclosing this list of lines - Boundary getBoxBoundary() const; - - /// @brief Returns the arithmetic of all corner points - /// @note: this is different from the centroid! - Position getPolygonCenter() const; - - /// @brief Returns the centroid (closes the polygon if unclosed) - Position getCentroid() const; - - /// @brief enlarges/shrinks the polygon by a factor based at the centroid - void scaleRelative(double factor); - - /// @brief enlarges/shrinks the polygon by an absolute offset based at the centroid - void scaleAbsolute(double offset); - - /// @brief get line center - Position getLineCenter() const; - - /// @brief Returns the length - double length() const; - - /// @brief Returns the length - double length2D() const; - - /// @brief Returns the area (0 for non-closed) - double area() const; - - /// @brief Returns the information whether this polygon lies partially within the given polygon - bool partialWithin(const AbstractPoly& poly, double offset = 0) const; - - /// @brief Returns the two lists made when this list vector is splitted at the given point - std::pair splitAt(double where, bool use2D = false) const; - - //// @brief Output operator - friend std::ostream& operator<<(std::ostream& os, const PositionVector& geom); - - //// @brief check if two positions crosses - bool crosses(const Position& p1, const Position& p2) const; - - //// @brief add a position - void add(double xoff, double yoff, double zoff); - - //// @brief substract a position - void add(const Position& offset); - - //// @brief add a position - void sub(double xoff, double yoff, double zoff); - - //// @brief substract a position - void sub(const Position& offset); - - //// @brief adds a position without modifying the vector itself but returning the result - PositionVector added(const Position& offset) const; - - //// @brief mirror coordinates along the x-axis - void mirrorX(); - - //// @brief rotate all points around (0,0) in the plane by the given angle - void rotate2D(double angle); - - //// @brief append the given vector to this one - void append(const PositionVector& v, double sameThreshold = 2.0); - - /// @brief get subpart of a position vector - PositionVector getSubpart(double beginOffset, double endOffset) const; - - /// @brief get subpart of a position vector in two dimensions (Z is ignored) - PositionVector getSubpart2D(double beginOffset, double endOffset) const; - - /// @brief get subpart of a position vector using index and a cout - PositionVector getSubpartByIndex(int beginIndex, int count) const; - - /// @brief sort as polygon CW by angle - void sortAsPolyCWByAngle(); - - /// @brief sort by increasing X-Y Positions - void sortByIncreasingXY(); - - /// @brief extrapolate position vector - void extrapolate(const double val, const bool onlyFirst = false, const bool onlyLast = false); - - /// @brief extrapolate position vector in two dimensions (Z is ignored) - void extrapolate2D(const double val, const bool onlyFirst = false); - - /// @brief reverse position vector - PositionVector reverse() const; - - /// @brief get a side position of position vector using a offset - static Position sideOffset(const Position& beg, const Position& end, const double amount); - - /// @brief move position vector to side using certain ammount - void move2side(double amount, double maxExtension = 100); - - /// @brief move position vector to side using a custom offset for each geometry point - void move2side(std::vector amount, double maxExtension = 100); - - /// @brief get angle in certain position of position vector - double angleAt2D(int pos) const; - - /**@brief inserts p between the two closest positions - * @param p position to be inserted - * @param interpolateZ flag to enable/disable interpolation of Z Value between the two closest positions - * @return the insertion index - */ - int insertAtClosest(const Position& p, bool interpolateZ); - - /// @brief removes the point closest to p and return the removal index - int removeClosest(const Position& p); - - /// @brief comparing operation - bool operator==(const PositionVector& v2) const; - - /// @brief comparing operation - bool operator!=(const PositionVector& v2) const; - - /// @brief substracts two vectors (requires vectors of the same length) - PositionVector operator-(const PositionVector& v2) const; - - /// @brief adds two vectors (requires vectors of the same length) - PositionVector operator+(const PositionVector& v2) const; - - /// @brief clase for CW Sorter - class as_poly_cw_sorter { - public: - /// @brief constructor - as_poly_cw_sorter(); - - /// @brief comparing operation for sort - int operator()(const Position& p1, const Position& p2) const; - }; - - /// @brief clase for increasing Sorter - class increasing_x_y_sorter { - public: - /// constructor - explicit increasing_x_y_sorter(); - - /// comparing operation - int operator()(const Position& p1, const Position& p2) const; - }; - - /// @brief get left - /// @note previously marked with "!!!" - double isLeft(const Position& P0, const Position& P1, const Position& P2) const; - - /// @brief returns the angle in radians of the line connecting the first and the last position - double beginEndAngle() const; - - /// @brief return the nearest offest to point 2D - double nearest_offset_to_point2D(const Position& p, bool perpendicular = true) const; - - /// @brief return the nearest offest to point 2D projected onto the 3D geometry - double nearest_offset_to_point25D(const Position& p, bool perpendicular = true) const; - - /** @brief return position p within the length-wise coordinate system - * defined by this position vector. The x value is the same as that returned - * by nearest_offset_to_point2D(p) and the y value is the perpendicular distance to this - * vector with the sign indicating the side (right is postive). - * if extend is true, the vector is extended on both sides and the - * x-coordinate of the result may be below 0 or above the length of the original vector - */ - Position transformToVectorCoordinates(const Position& p, bool extend = false) const; - - /// @brief index of the closest position to p - /// @note: may only be called for a non-empty vector - int indexOfClosest(const Position& p) const; - - /// @brief distances of all my points to s and all of s points to myself - /// @note if perpendicular is set to true, only the perpendicular distances are returned - std::vector distances(const PositionVector& s, bool perpendicular = false) const; - - /// @brief closest 2D-distance to point p (or -1 if perpendicular is true and the point is beyond this vector) - double distance2D(const Position& p, bool perpendicular = false) const; - - /// @brief insert in front a Position - void push_front(const Position& p); - - /// @brief pop first Position - void pop_front(); - - /// @brief insert in back a non double position - void push_back_noDoublePos(const Position& p); - - /// @brief insert in front a non double position - void push_front_noDoublePos(const Position& p); - - /// @brief insert in front a non double position - void insert_noDoublePos(const std::vector::iterator& at, const Position& p); - - /// @brief check if PositionVector is closed - bool isClosed() const; - - /// @brief check if PositionVector is NAN - bool isNAN() const; - - /** @brief Removes positions if too near - * @param[in] minDist The minimum accepted distance; default: POSITION_EPS - * @param[in] assertLength Whether the result must at least contain two points (be a line); default: false, to ensure original behaviour - */ - void removeDoublePoints(double minDist = POSITION_EPS, bool assertLength = false); - - /// @brief return whether two positions differ in z-coordinate - bool hasElevation() const; - - /// @brief return the same shape with intermediate colinear points removed - PositionVector simplified() const; - - /** @brief return orthogonal through p (extending this vector if necessary) - * @param[in] p The point through which to draw the orthogonal - * @param[in] extend how long to extend this vector for finding an orthogonal - * @param[in] front Whether to take the segment before or after the base point in case of ambiguity - * @param[in] length the length of the orthogonal - * @param[in] deg the rotation angle relative to the shape direction - */ - PositionVector getOrthogonal(const Position& p, double extend, bool before, double length = 1.0, double deg = 90) const; - - /// @brief returned vector that is smoothed at the front (within dist) - PositionVector smoothedZFront(double dist = std::numeric_limits::max()) const; - - /// @brief returned vector that varies z smoothly over its length - PositionVector interpolateZ(double zStart, double zEnd) const; - - /// @brief resample shape with the given number of points (equal spacing) - PositionVector resample(double maxLength) const; - - /// @brief return the offset at the given index - double offsetAtIndex2D(int index) const; - - /* @brief return the maximum grade of all segments as a fraction of zRange/length2D - * @param[out] maxJump The maximum vertical jump (with grade infinity) - */ - double getMaxGrade(double& maxJump) const; - - /// @brief return a bezier interpolation - PositionVector bezier(int numPoints); - -private: - /// @brief return whether the line segments defined by Line p11,p12 and Line p21,p22 intersect - static bool intersects(const Position& p11, const Position& p12, const Position& p21, const Position& p22, const double withinDist = 0., double* x = 0, double* y = 0, double* mu = 0); -}; diff --git a/Util/OSM2ODR/src/utils/gui/globjects/GUIGlObjectTypes.h b/Util/OSM2ODR/src/utils/gui/globjects/GUIGlObjectTypes.h deleted file mode 100644 index 591152fe6..000000000 --- a/Util/OSM2ODR/src/utils/gui/globjects/GUIGlObjectTypes.h +++ /dev/null @@ -1,210 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file GUIGlObjectTypes.h -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date Sept 2002 -/// -// A list of object types which may be displayed within the gui -// each type has an associated string which will be prefefixed to an object id -// when constructing the full name -/****************************************************************************/ -#pragma once -#include - - -// =========================================================================== -// definitions -// =========================================================================== -/** - * ChooseableArtifact - * Enumeration to differ to show the list of which artefact - * The order is important during the selection of items for displaying their - * tooltips; the item with the hightest type value will be chosen. - */ -enum GUIGlObjectType { - /// @brief The network - empty - GLO_NETWORK = 0, - - /// @name nettork elements - /// @{ - - /// @brief reserved GLO type to pack all network elements - GLO_NETWORKELEMENT = 1, - /// @brief an edge - GLO_EDGE = 2, - /// @brief a lane - GLO_LANE = 3, - /// @brief a junction - GLO_JUNCTION = 4, - /// @brief a tl-logic - GLO_CROSSING = 5, - /// @brief a connection - GLO_CONNECTION = 6, - /// @brief a tl-logic - GLO_TLLOGIC = 8, - - /// @} - - /// @name data elements - /// @{ - - /// @brief edge data - GLO_EDGEDATA = 50, - /// @brief edge relation data - GLO_EDGERELDATA = 51, - /// @brief TAZ relation data - GLO_TAZRELDATA = 52, - - /// @} - - /// @name additional elements - /// @{ - - /// @brief reserved GLO type to pack all additionals elements - GLO_ADDITIONALELEMENT = 100, - /// @brief a busStop - GLO_BUS_STOP = 101, - /// @brief a containerStop - GLO_CONTAINER_STOP = 102, - /// @brief a chargingStation - GLO_CHARGING_STATION = 103, - /// @brief a ParkingArea - GLO_PARKING_AREA = 104, - /// @brief a ParkingSpace - GLO_PARKING_SPACE = 105, - /// @brief a E1 detector - GLO_E1DETECTOR = 106, - /// @brief a E1 detector - GLO_E1DETECTOR_ME = 107, - /// @brief a E1 detector - GLO_E1DETECTOR_INSTANT = 108, - /// @brief a E2 detector - GLO_E2DETECTOR = 109, - /// @brief a E3 detector - GLO_E3DETECTOR = 110, - /// @brief a DetEntry detector - GLO_DET_ENTRY = 111, - /// @brief a DetExit detector - GLO_DET_EXIT = 112, - /// @brief a Rerouter - GLO_REROUTER = 113, - /// @brief a Rerouter - GLO_REROUTER_EDGE = 114, - /// @brief a Variable Speed Sign - GLO_VSS = 115, - /// @brief a Calibrator - GLO_CALIBRATOR = 116, - /// @brief a RouteProbe - GLO_ROUTEPROBE = 117, - /// @brief a Vaporizer - GLO_VAPORIZER = 118, - /// @brief a Acces - GLO_ACCESS = 119, - /// @brief a segment of an overhead line - GLO_OVERHEAD_WIRE_SEGMENT = 121, - - /// @} - - /// @name shape elements - /// @{ - - /// @brief reserved GLO type to pack shapes - GLO_SHAPE = 200, - /// @brief a polygon - GLO_POLYGON = 201, - /// @brief a poi - GLO_POI = 202, - - /// @} - - /// @name demand elements - /// @{ - - /// @brief reserved GLO type to pack all RouteElements (note: In this case the sorting of GLO_ is important!) - GLO_ROUTEELEMENT = 300, - /// @bief vTypes - GLO_VTYPE = 301, - - /// @} - - /// @name routes - /// @{ - - /// @brief a route - GLO_ROUTE = 310, - - /// @} - - /// @name Person plans - /// @{ - - /// @brief a ride - GLO_RIDE = 320, - /// @brief a walk - GLO_WALK = 321, - /// @brief a person trip - GLO_PERSONTRIP = 322, - - /// @} - - /// @name stops - /// @{ - - /// @brief a stop - GLO_STOP = 330, - /// @brief a person stop - GLO_PERSONSTOP = 331, - - /// @} - - /// @name vehicles - /// @{ - - /// @brief a vehicle - GLO_VEHICLE = 340, - /// @brief a trip - GLO_TRIP = 341, - /// @brief a flow - GLO_FLOW = 342, - /// @brief a routeFlow - GLO_ROUTEFLOW = 343, - - /// @} - - /// @name containers (carried by vehicles) - /// @{ - - /// @brief a container - GLO_CONTAINER = 350, - - /// @} - - /// @name persons - /// @{ - - /// @brief a person - GLO_PERSON = 360, - /// @brief a person flow - GLO_PERSONFLOW = 361, - - /// @} - - /// @brief Traffic Assignment Zones (TAZs) - GLO_TAZ = 400, - - /// @brief empty max - GLO_MAX = 2048 -}; diff --git a/Util/OSM2ODR/src/utils/importio/CMakeLists.txt b/Util/OSM2ODR/src/utils/importio/CMakeLists.txt deleted file mode 100644 index 5328c30f1..000000000 --- a/Util/OSM2ODR/src/utils/importio/CMakeLists.txt +++ /dev/null @@ -1,9 +0,0 @@ -set(utils_importio_STAT_SRCS - LineReader.cpp - NamedColumnsParser.cpp - LineReader.h - NamedColumnsParser.h -) - -add_library(utils_importio STATIC ${utils_importio_STAT_SRCS}) -set_property(TARGET utils_importio PROPERTY PROJECT_LABEL "z_utils_importio") diff --git a/Util/OSM2ODR/src/utils/importio/LineHandler.h b/Util/OSM2ODR/src/utils/importio/LineHandler.h deleted file mode 100644 index 26c196862..000000000 --- a/Util/OSM2ODR/src/utils/importio/LineHandler.h +++ /dev/null @@ -1,61 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file LineHandler.h -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Fri, 19 Jul 2002 -/// -// Interface definition for a class which retrieves lines from a LineHandler -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class LineHandler - * @brief Interface definition for a class which retrieves lines from a LineHandler - * - * The LineHandler is an interface for a class which retrieves information - * from a file linewise. The lines are suppoted to this class using the - * "report"-method. The LineHandler is used together with the LineReader - * which reads the lines from a file. - * @see LineReader - */ -class LineHandler { -public: - /// @brief constructor - LineHandler() { } - - - /// @brief (virtual) destructor - virtual ~LineHandler() { } - - - /** @brief Method that obatins a line read by the LineReader - * - * Real interface method, used by a LineReader, which retrieves lines from a file - * - * @param[in] result The read line - * @return Whether the caller shall continue with reading - */ - virtual bool report(const std::string& result) = 0; - -}; diff --git a/Util/OSM2ODR/src/utils/importio/LineReader.cpp b/Util/OSM2ODR/src/utils/importio/LineReader.cpp deleted file mode 100644 index f6269db1d..000000000 --- a/Util/OSM2ODR/src/utils/importio/LineReader.cpp +++ /dev/null @@ -1,234 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file LineReader.cpp -/// @author Daniel Krajzewicz -/// @author Laura Bieker -/// @author Michael Behrisch -/// @date Fri, 19 Jul 2002 -/// -// Retrieves a file linewise and reports the lines to a handler. -/****************************************************************************/ -#include - -#include -#include -#include -#include -#include -#include -#include "LineHandler.h" -#include "LineReader.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -LineReader::LineReader() {} - - -LineReader::LineReader(const std::string& file) - : myFileName(file), - myRead(0) { - reinit(); -} - - -LineReader::~LineReader() {} - - -bool -LineReader::hasMore() const { - return myRread < myAvailable; -} - - -void -LineReader::readAll(LineHandler& lh) { - while (myRread < myAvailable) { - if (!readLine(lh)) { - return; - } - } -} - - -bool -LineReader::readLine(LineHandler& lh) { - std::string toReport; - bool moreAvailable = true; - while (toReport.length() == 0) { - const std::string::size_type idx = myStrBuffer.find('\n'); - if (idx == 0) { - myStrBuffer = myStrBuffer.substr(1); - myRread++; - return lh.report(""); - } - if (idx != std::string::npos) { - toReport = myStrBuffer.substr(0, idx); - myStrBuffer = myStrBuffer.substr(idx + 1); - myRread += (int)idx + 1; - } else { - if (myRead < myAvailable) { - myStrm.read(myBuffer, - myAvailable - myRead < 1024 - ? myAvailable - myRead - : 1024); - int noBytes = myAvailable - myRead; - noBytes = noBytes > 1024 ? 1024 : noBytes; - myStrBuffer += std::string(myBuffer, noBytes); - myRead += 1024; - } else { - toReport = myStrBuffer; - moreAvailable = false; - if (toReport == "") { - return lh.report(toReport); - } - } - } - } - // remove trailing blanks - int idx = (int)toReport.length() - 1; - while (idx >= 0 && toReport[idx] < 32) { - idx--; - } - if (idx >= 0) { - toReport = toReport.substr(0, idx + 1); - } else { - toReport = ""; - } - // give it to the handler - if (!lh.report(toReport)) { - return false; - } - return moreAvailable; -} - - -std::string -LineReader::readLine() { - std::string toReport; - while (toReport.length() == 0 && myStrm.good()) { - const std::string::size_type idx = myStrBuffer.find('\n'); - if (idx == 0) { - myStrBuffer = myStrBuffer.substr(1); - myRread++; - myLinesRead++; - return ""; - } - if (idx != std::string::npos) { - toReport = myStrBuffer.substr(0, idx); - myStrBuffer = myStrBuffer.substr(idx + 1); - myRread += (int) idx + 1; - } else { - if (myRead < myAvailable) { - myStrm.read(myBuffer, - myAvailable - myRead < 1024 - ? myAvailable - myRead - : 1024); - int noBytes = myAvailable - myRead; - noBytes = noBytes > 1024 ? 1024 : noBytes; - myStrBuffer += std::string(myBuffer, noBytes); - myRead += 1024; - } else { - toReport = myStrBuffer; - myRread += 1024; - if (toReport == "") { - myLinesRead++; - return toReport; - } - } - } - } - if (!myStrm.good()) { - return ""; - } - // remove trailing blanks - int idx = (int)toReport.length() - 1; - while (idx >= 0 && toReport[idx] < 32) { - idx--; - } - if (idx >= 0) { - toReport = toReport.substr(0, idx + 1); - } else { - toReport = ""; - } - myLinesRead++; - return toReport; -} - - - -std::string -LineReader::getFileName() const { - return myFileName; -} - - -bool -LineReader::setFile(const std::string& file) { - myFileName = file; - reinit(); - return myStrm.good(); -} - - -unsigned long -LineReader::getPosition() { - return myRread; -} - - -void -LineReader::reinit() { - if (myStrm.is_open()) { - myStrm.close(); - } - myStrm.clear(); - myStrm.open(myFileName.c_str(), std::ios::binary); - myStrm.unsetf(std::ios::skipws); - myStrm.seekg(0, std::ios::end); - myAvailable = static_cast(myStrm.tellg()); - myStrm.seekg(0, std::ios::beg); - if (myAvailable >= 3) { - // check for BOM - myStrm.read(myBuffer, 3); - if (myBuffer[0] == (char)0xef && myBuffer[1] == (char)0xbb && myBuffer[2] == (char)0xbf) { - myAvailable -= 3; - } else { - myStrm.seekg(0, std::ios::beg); - } - } - myRead = 0; - myRread = 0; - myStrBuffer = ""; - myLinesRead = 0; -} - - -void -LineReader::setPos(unsigned long pos) { - myStrm.seekg(pos, std::ios::beg); - myRead = pos; - myRread = pos; - myStrBuffer = ""; -} - - -bool -LineReader::good() const { - return myStrm.good(); -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/utils/importio/LineReader.h b/Util/OSM2ODR/src/utils/importio/LineReader.h deleted file mode 100644 index ae32169b9..000000000 --- a/Util/OSM2ODR/src/utils/importio/LineReader.h +++ /dev/null @@ -1,172 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file LineReader.h -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Fri, 19 Jul 2002 -/// -// Retrieves a file linewise and reports the lines to a handler. -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include - - -// =========================================================================== -// class declarations -// =========================================================================== -class LineHandler; - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class LineReader - * @brief Retrieves a file linewise and reports the lines to a handler. - * - * This class reads the contents from a file line by line and report them to - * a LineHandler-derivate. - * @see LineHandler - * @todo No checks are done so far during reading/setting position etc. - * @todo Should not IOError be thrown if something fails? - */ -class LineReader { -public: - /// @brief Constructor - LineReader(); - - - /** @brief Constructor - * - * Initialises reading from the file with the given name using setFile. - * - * @param[in] file The name of the file to open - * @see setFile - */ - LineReader(const std::string& file); - - - /// @brief Destructor - ~LineReader(); - - - /** @brief Returns whether another line may be read (the file was not read completely) - * @return Whether further reading is possible - */ - bool hasMore() const; - - - /** @brief Reads the whole file linewise, reporting every line to the given LineHandler - * - * When the LineHandler returns false, the reading will be aborted - * - * @param[in] lh The LineHandler to report read lines to - */ - void readAll(LineHandler& lh); - - - /** @brief Reads a single (the next) line from the file and reports it to the given LineHandler - * - * When the LineHandler returns false, the reading will be aborted - * - * @param[in] lh The LineHandler to report read lines to - * @return Whether a further line exists - */ - bool readLine(LineHandler& lh); - - - /** @brief Reads a single (the next) line from the file and returns it - * - * @return The next line in the file - */ - std::string readLine(); - - - /// @brief Closes the reading - void close(); - - - /** @brief Returns the name of the used file - * @return The name of the opened file - */ - std::string getFileName() const; - - - /** @brief Reinitialises the reader for reading from the given file - * - * Returns false when the file is not readable - * - * @param[in] file The name of the file to open - * @return Whether the file could be opened - */ - bool setFile(const std::string& file); - - - /** @brief Returns the current position within the file - * @return The current position within the opened file - */ - unsigned long getPosition(); - - - /// @brief Reinitialises the reading (of the previous file) - void reinit(); - - - /** @brief Sets the current position within the file to the given value - * - * @param[in] pos The new position within the file - */ - void setPos(unsigned long pos); - - - /** @brief Returns the information whether the stream is readable - * @return Whether the file is usable (good()) - */ - bool good() const; - - - int getLineNumber() { - return myLinesRead; - } - -private: - /// @brief the name of the file to read the contents from - std::string myFileName; - - /// @brief the stream used - std::ifstream myStrm; - - /// @brief To override MSVC++-bugs, we use an own getline which uses this buffer - char myBuffer[1024]; - - /// @brief a string-buffer - std::string myStrBuffer; - - /// @brief Information about how many characters were supplied to the LineHandler - int myRead; - - /// @brief Information how many bytes are available within the used file - int myAvailable; - - /// @brief Information how many bytes were read by the reader from the file - int myRread; - - /// @brief Information how many lines were read for meaningful error messages - int myLinesRead; - -}; diff --git a/Util/OSM2ODR/src/utils/importio/NamedColumnsParser.cpp b/Util/OSM2ODR/src/utils/importio/NamedColumnsParser.cpp deleted file mode 100644 index 6a87bef5a..000000000 --- a/Util/OSM2ODR/src/utils/importio/NamedColumnsParser.cpp +++ /dev/null @@ -1,142 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NamedColumnsParser.cpp -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Fri, 19 Jul 2002 -/// -// A parser to retrieve information from a table with known column -/****************************************************************************/ -#include - -#include -#include -#include -#include -#include "NamedColumnsParser.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -NamedColumnsParser::NamedColumnsParser() {} - - -NamedColumnsParser::NamedColumnsParser(const std::string& def, - const std::string& defDelim, - const std::string& lineDelim, - bool prune, bool ignoreCase) - : myLineDelimiter(lineDelim), myAmCaseInsensitive(ignoreCase) { - reinitMap(def, defDelim, prune); -} - - -NamedColumnsParser::~NamedColumnsParser() {} - - -void -NamedColumnsParser::reinit(const std::string& def, - const std::string& defDelim, - const std::string& lineDelim, - bool prune, bool ignoreCase) { - myAmCaseInsensitive = ignoreCase; - reinitMap(def, defDelim, prune); - myLineDelimiter = lineDelim; -} - - -void -NamedColumnsParser::parseLine(const std::string& line) { - myLineParser = StringTokenizer(line, myLineDelimiter); -} - - -std::string -NamedColumnsParser::get(const std::string& name, bool prune) const { - PosMap::const_iterator i = myDefinitionsMap.find(name); - if (i == myDefinitionsMap.end()) { - if (myAmCaseInsensitive) { - i = myDefinitionsMap.find(StringUtils::to_lower_case(name)); - } - if (i == myDefinitionsMap.end()) { - throw UnknownElement("Element '" + name + "' is missing"); - } - } - int pos = (*i).second; - if (myLineParser.size() <= pos) { - throw OutOfBoundsException(); - } - std::string ret = myLineParser.get(pos); - checkPrune(ret, prune); - return ret; -} - - -bool -NamedColumnsParser::know(const std::string& name) const { - PosMap::const_iterator i = myDefinitionsMap.find(name); - if (i == myDefinitionsMap.end()) { - if (myAmCaseInsensitive) { - i = myDefinitionsMap.find(StringUtils::to_lower_case(name)); - } - } - if (i == myDefinitionsMap.end()) { - return false; - } - int pos = (*i).second; - return myLineParser.size() > pos; -} - - -bool -NamedColumnsParser::hasFullDefinition() const { - return (int)myDefinitionsMap.size() == myLineParser.size(); -} - - -void -NamedColumnsParser::reinitMap(std::string s, - const std::string& delim, - bool prune) { - if (myAmCaseInsensitive) { - s = StringUtils::to_lower_case(s); - } - myDefinitionsMap.clear(); - int pos = 0; - StringTokenizer st(s, delim); - while (st.hasNext()) { - std::string next = st.next(); - checkPrune(next, prune); - myDefinitionsMap.insert(std::map::value_type(next, pos++)); - } -} - - -void -NamedColumnsParser::checkPrune(std::string& str, bool prune) const { - if (!prune) { - return; - } - std::string::size_type idx = str.find_first_not_of(" "); - if (idx != std::string::npos) { - str = str.substr(idx); - } - idx = str.find_last_not_of(" "); - if (idx != std::string::npos && idx != str.length() - 1) { - str = str.substr(0, idx + 1); - } -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/utils/importio/NamedColumnsParser.h b/Util/OSM2ODR/src/utils/importio/NamedColumnsParser.h deleted file mode 100644 index 55380408d..000000000 --- a/Util/OSM2ODR/src/utils/importio/NamedColumnsParser.h +++ /dev/null @@ -1,182 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file NamedColumnsParser.h -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Fri, 19 Jul 2002 -/// -// A parser to retrieve information from a table with known columns -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class NamedColumnsParser - * @brief A parser to retrieve information from a table with known columns - * - * When initialised, this parser stores the given information about the - * order of the named elements and allows the retrieval of lines using the - * names of these elements. - * Use it like this: - * @arg Initialise with "Name;PositionX;PositionY" - * (defDelim=default=";") - * (lineDelim=default=";") - * @arg Parse each line of a table using "parseLine" (parseLine("Dummy;0;0")) - * @arg get values using operations like: string posX = get("PositionX"); - * - * @todo What happens if an uninitialised NamedColumnsParser is used? exceptions? - */ -class NamedColumnsParser { -public: - /** @brief Constructor - * - * Does nothing, a later call to reinit is necessary - */ - NamedColumnsParser(); - - - /** @brief Constructor - * - * Initialises the parser (mainly using "reinitMap", only "ignoreCase" and - * "lineDelim" are saved directly into member variables - "reinit" - * does the same). - * - * @param[in] def The line that describes (names) the entries - * @param[in] defDelim Delimiter for the entry names - * @param[in] lineDelim Delimiter used within data lines - * @param[in] chomp Whether the lines shall be trimmed (white spaces shall be removed) - * @param[in] ignoreCase Whether the case shall be ignored when parsing the definitions - */ - NamedColumnsParser(const std::string& def, const std::string& defDelim = ";", - const std::string& lineDelim = ";", bool chomp = false, - bool ignoreCase = true); - - - /// @brief Destructor - ~NamedColumnsParser(); - - - /** @brief Reinitialises the parser - * - * Initialises the parser (mainly using "reinitMap", only "ignoreCase" and - * "lineDelim" are saved directly into member variables - * - * @param[in] def The line that describes (names) the entries - * @param[in] defDelim Delimiter for the entry names - * @param[in] lineDelim Delimiter used within data lines - * @param[in] chomp Whether the lines shall be trimmed (white spaces shall be removed) - * @param[in] ignoreCase Whether the case shall be ignored when parsing the definitions - */ - void reinit(const std::string& def, const std::string& defDelim = ";", - const std::string& lineDelim = ";", bool chomp = false, - bool ignoreCase = true); - - - /** @brief Parses the contents of the line - * - * Parses the line by tokenizing it using a StringTokenizer and the set - * line delimiter ("myLineDelimiter"). Stores the tokenized line into - * "myLineParser" - * - * @param[in] line The line to parse - */ - void parseLine(const std::string& line); - - - /** @brief Returns the named information - * - * Tries to find the given variable name within the parsed definition line - * ("myDefinitionsMap"). If the value was not within the definition, an - * UnknownElement exception is thrown. Otherwise, the method tries to return - * the element from the parsed value line that is at the obtained position. - * If the value line had less tokens than the position assumes, an OutOfBoundsException - * is thrown, otherwise the value at the position returned (optionally prunned). - * - * @param[in] name The name of the value to retrieve - * @param[in] prune Whether the returned value shall be trimmed (leading/trainling spaces removed) - * @return The obtained value - * @exception UnknownElement when the element was not named during the initialisation - * @exception OutOfBoundsException when the line was too short and did not contain the item */ - std::string get(const std::string& name, - bool prune = false) const; - - - /** @brief Returns the information whether the named column is known - * - * @param[in] name The name of the value to check - * @return Whether the named value is stored in the parsed line - */ - bool know(const std::string& name) const; - - - /** @brief Returns whether the number of named columns matches the actual number - * - * @return Whether the number of named columns matches the actual number - */ - bool hasFullDefinition() const; - - -private: - /** @brief Rebuilds the map of attribute names to their positions in a table - * - * The given definition string is split using the given delimiter. The obtained - * tokens are stired in "" together with their positions within the tokenized - * string. - * If wished (myAmCaseInsensitive==true), the definition string is converted - * into lower case, first. Also, if chomp==true, each token ist prunned. - * - * @param[in] def The definition string - * @param[in] delim The delimiter string - * @param[in] chomp Whether the tokens shall be prunned - */ - void reinitMap(std::string def, const std::string& delim = ";", - bool chomp = false); - - - /** @brief Prunes the given string if it shall be done - * - * If prune==true, the given string is prunned (all leading/trailing spaces - * are removed). - * - * @param[in, out] str The string to prune (optionally) - * @param[in] prune Whether the string shall be prunned - */ - void checkPrune(std::string& str, bool prune) const; - - -private: - /** @brief The map's definition of column item names to their positions within the table */ - typedef std::map PosMap; - - /// @brief The map of column item names to their positions within the table - PosMap myDefinitionsMap; - - /// @brief The delimiter to split the column items on - std::string myLineDelimiter; - - /// @brief The contents of the current line - StringTokenizer myLineParser; - - /// @brief Information whether case insensitive match shall be done - bool myAmCaseInsensitive; - -}; diff --git a/Util/OSM2ODR/src/utils/iodevices/CMakeLists.txt b/Util/OSM2ODR/src/utils/iodevices/CMakeLists.txt deleted file mode 100644 index f5ce24cc6..000000000 --- a/Util/OSM2ODR/src/utils/iodevices/CMakeLists.txt +++ /dev/null @@ -1,21 +0,0 @@ -set(utils_iodevices_STAT_SRCS - OutputDevice.cpp - OutputDevice.h - OutputDevice_CERR.cpp - OutputDevice_CERR.h - OutputDevice_COUT.cpp - OutputDevice_COUT.h - OutputDevice_File.cpp - OutputDevice_File.h - OutputDevice_String.cpp - OutputDevice_String.h - OutputDevice_Network.cpp - OutputDevice_Network.h - OutputFormatter.h - PlainXMLFormatter.cpp - PlainXMLFormatter.h -) - -add_library(utils_iodevices STATIC ${utils_iodevices_STAT_SRCS}) -#add_dependencies(utils_iodevices generate-version-h) -set_property(TARGET utils_iodevices PROPERTY PROJECT_LABEL "z_utils_iodevices") diff --git a/Util/OSM2ODR/src/utils/iodevices/OutputDevice.cpp b/Util/OSM2ODR/src/utils/iodevices/OutputDevice.cpp deleted file mode 100644 index 9391dcee3..000000000 --- a/Util/OSM2ODR/src/utils/iodevices/OutputDevice.cpp +++ /dev/null @@ -1,271 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2004-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file OutputDevice.cpp -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date 2004 -/// -// Static storage of an output device and its base (abstract) implementation -/****************************************************************************/ -#include - -#include -#include -#include -#include -#include -#include "OutputDevice.h" -#include "OutputDevice_File.h" -#include "OutputDevice_COUT.h" -#include "OutputDevice_CERR.h" -#include "OutputDevice_Network.h" -#include "PlainXMLFormatter.h" -#include -#include -#include -#include -#include -#include - - -// =========================================================================== -// static member definitions -// =========================================================================== -std::map OutputDevice::myOutputDevices; - - -// =========================================================================== -// static method definitions -// =========================================================================== -OutputDevice& -OutputDevice::getDevice(const std::string& name) { - // check whether the device has already been aqcuired - if (myOutputDevices.find(name) != myOutputDevices.end()) { - return *myOutputDevices[name]; - } - // build the device - OutputDevice* dev = nullptr; - // check whether the device shall print to stdout - if (name == "stdout") { - dev = OutputDevice_COUT::getDevice(); - } else if (name == "stderr") { - dev = OutputDevice_CERR::getDevice(); - } else if (FileHelpers::isSocket(name)) { - try { - int port = StringUtils::toInt(name.substr(name.find(":") + 1)); - dev = new OutputDevice_Network(name.substr(0, name.find(":")), port); - } catch (NumberFormatException&) { - throw IOError("Given port number '" + name.substr(name.find(":") + 1) + "' is not numeric."); - } catch (EmptyData&) { - throw IOError("No port number given."); - } - } else { - const int len = (int)name.length(); - std::string name2 = name; - if (OptionsCont::getOptions().isSet("output-prefix") && name != "/dev/null") { - std::string prefix = OptionsCont::getOptions().getString("output-prefix"); - const std::string::size_type metaTimeIndex = prefix.find("TIME"); - if (metaTimeIndex != std::string::npos) { - time_t rawtime; - char buffer [80]; - time(&rawtime); - struct tm* timeinfo = localtime(&rawtime); - strftime(buffer, 80, "%Y-%m-%d-%H-%M-%S", timeinfo); - prefix.replace(metaTimeIndex, 4, std::string(buffer)); - } - name2 = FileHelpers::prependToLastPathComponent(prefix, name); - } - dev = new OutputDevice_File(name2, len > 3 && name.substr(len - 3) == ".gz"); - } - dev->setPrecision(); - dev->getOStream() << std::setiosflags(std::ios::fixed); - myOutputDevices[name] = dev; - return *dev; -} - - -bool -OutputDevice::createDeviceByOption(const std::string& optionName, - const std::string& rootElement, - const std::string& schemaFile) { - if (!OptionsCont::getOptions().isSet(optionName)) { - return false; - } - OutputDevice& dev = OutputDevice::getDevice(OptionsCont::getOptions().getString(optionName)); - if (rootElement != "") { - dev.writeXMLHeader(rootElement, schemaFile); - } - return true; -} - - -OutputDevice& -OutputDevice::getDeviceByOption(const std::string& optionName) { - std::string devName = OptionsCont::getOptions().getString(optionName); - if (myOutputDevices.find(devName) == myOutputDevices.end()) { - throw InvalidArgument("Device '" + devName + "' has not been created."); - } - return OutputDevice::getDevice(devName); -} - - -void -OutputDevice::closeAll(bool keepErrorRetrievers) { - std::vector errorDevices; - std::vector nonErrorDevices; - for (std::map::iterator i = myOutputDevices.begin(); i != myOutputDevices.end(); ++i) { - if (MsgHandler::getErrorInstance()->isRetriever(i->second)) { - errorDevices.push_back(i->second); - } else { - nonErrorDevices.push_back(i->second); - } - } - for (std::vector::iterator i = nonErrorDevices.begin(); i != nonErrorDevices.end(); ++i) { - try { - //std::cout << " close '" << (*i)->getFilename() << "'\n"; - (*i)->close(); - } catch (const IOError& e) { - WRITE_ERROR("Error on closing output devices."); - WRITE_ERROR(e.what()); - } - } - if (!keepErrorRetrievers) { - for (std::vector::iterator i = errorDevices.begin(); i != errorDevices.end(); ++i) { - try { - (*i)->close(); - } catch (const IOError& e) { - std::cerr << "Error on closing error output devices." << std::endl; - std::cerr << e.what() << std::endl; - } - } - } -} - - -std::string -OutputDevice::realString(const double v, const int precision) { - std::ostringstream oss; - if (v == 0) { - return "0"; - } - if (v < pow(10., -precision)) { - oss.setf(std::ios::scientific, std::ios::floatfield); - } else { - oss.setf(std::ios::fixed, std::ios::floatfield); // use decimal format - oss.setf(std::ios::showpoint); // print decimal point - oss << std::setprecision(precision); - } - oss << v; - return oss.str(); -} - - -// =========================================================================== -// member method definitions -// =========================================================================== -OutputDevice::OutputDevice(const int defaultIndentation, const std::string& filename) : - myFilename(filename) { - myFormatter = new PlainXMLFormatter(defaultIndentation); -} - - -OutputDevice::~OutputDevice() { - delete myFormatter; -} - - -bool -OutputDevice::ok() { - return getOStream().good(); -} - - -const std::string& -OutputDevice::getFilename() { - return myFilename; -} - -void -OutputDevice::close() { - while (closeTag()) {} - for (std::map::iterator i = myOutputDevices.begin(); i != myOutputDevices.end(); ++i) { - if (i->second == this) { - myOutputDevices.erase(i); - break; - } - } - MsgHandler::removeRetrieverFromAllInstances(this); - delete this; -} - - -void -OutputDevice::setPrecision(int precision) { - getOStream() << std::setprecision(precision); -} - - -bool -OutputDevice::writeXMLHeader(const std::string& rootElement, - const std::string& schemaFile, - std::map attrs) { - if (schemaFile != "") { - attrs[SUMO_ATTR_XMLNS] = "http://www.w3.org/2001/XMLSchema-instance"; - attrs[SUMO_ATTR_SCHEMA_LOCATION] = "http://sumo.dlr.de/xsd/" + schemaFile; - } - return myFormatter->writeXMLHeader(getOStream(), rootElement, attrs); -} - - -OutputDevice& -OutputDevice::openTag(const std::string& xmlElement) { - myFormatter->openTag(getOStream(), xmlElement); - return *this; -} - - -OutputDevice& -OutputDevice::openTag(const SumoXMLTag& xmlElement) { - myFormatter->openTag(getOStream(), xmlElement); - return *this; -} - - -bool -OutputDevice::closeTag(const std::string& comment) { - if (myFormatter->closeTag(getOStream(), comment)) { - postWriteHook(); - return true; - } - return false; -} - - -void -OutputDevice::postWriteHook() {} - - -void -OutputDevice::inform(const std::string& msg, const char progress) { - if (progress != 0) { - getOStream() << msg << progress; - } else { - getOStream() << msg << '\n'; - } - postWriteHook(); -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/utils/iodevices/OutputDevice.h b/Util/OSM2ODR/src/utils/iodevices/OutputDevice.h deleted file mode 100644 index f5bf41ece..000000000 --- a/Util/OSM2ODR/src/utils/iodevices/OutputDevice.h +++ /dev/null @@ -1,344 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2004-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file OutputDevice.h -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @author Mario Krumnow -/// @date 2004 -/// -// Static storage of an output device and its base (abstract) implementation -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include -#include -#include "PlainXMLFormatter.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class OutputDevice - * @brief Static storage of an output device and its base (abstract) implementation - * - * OutputDevices are basically a capsule around an std::ostream, which give a - * unified access to sockets, files and stdout. - * - * Usually, an application builds as many output devices as needed. Each - * output device may also be used to save outputs from several sources - * (several detectors, for example). Building is done using OutputDevice::getDevice() - * what also parses the given output description in order to decide - * what kind of an OutputDevice shall be built. OutputDevices are - * closed via OutputDevice::closeAll(), normally called at the application's - * end. - * - * Although everything that can be written to a stream can also be written - * to an OutputDevice, there is special support for XML tags (remembering - * all open tags to close them at the end). OutputDevices are still lacking - * support for function pointers with the '<<' operator (no endl, use '\n'). - * The most important method to implement in subclasses is getOStream, - * the most used part of the interface is the '<<' operator. - * - * The Boolean markers are used rarely and might get removed in future versions. - */ -class OutputDevice { -public: - /// @name static access methods to OutputDevices - /// @{ - - /** @brief Returns the described OutputDevice - * - * Creates and returns the named device. "stdout" and "stderr" refer to the relevant console streams, - * "hostname:port" initiates socket connection. Otherwise a filename - * is assumed (where "nul" and "/dev/null" do what you would expect on both platforms). - * If there already is a device with the same name this one is returned. - * - * @param[in] name The description of the output name/port/whatever - * @return The corresponding (built or existing) device - * @exception IOError If the output could not be built for any reason (error message is supplied) - */ - static OutputDevice& getDevice(const std::string& name); - - - /** @brief Creates the device using the output definition stored in the named option - * - * Creates and returns the device named by the option. Asks whether the option - * and retrieves the name from the option if so. Optionally the XML header - * gets written as well. Returns whether a device was created (option was set). - * - * Please note, that we do not have to consider the "application base" herein, - * because this call is only used to get file names of files referenced - * within XML-declarations of structures which paths already is aware of the - * cwd. - * - * @param[in] optionName The name of the option to use for retrieving the output definition - * @param[in] rootElement The root element to use (XML-output) - * @param[in] schemaFile The basename of the schema file to use (XML-output) - * @return Whether a device was built (the option was set) - * @exception IOError If the output could not be built for any reason (error message is supplied) - */ - static bool createDeviceByOption(const std::string& optionName, - const std::string& rootElement = "", - const std::string& schemaFile = ""); - - - /** @brief Returns the device described by the option - * - * Returns the device named by the option. If the option is unknown, unset - * or the device was not created before, InvalidArgument is thrown. - * - * Please note, that we do not have to consider the "application base" herein. - * - * @param[in] name The name of the option to use for retrieving the output definition - * @return The corresponding (built or existing) device - * @exception IOError If the output could not be built for any reason (error message is supplied) - * @exception InvalidArgument If the option with the given name does not exist - */ - static OutputDevice& getDeviceByOption(const std::string& name); - - - /** Closes all registered devices - */ - static void closeAll(bool keepErrorRetrievers = false); - /// @} - - - /** @brief Helper method for string formatting - * - * @param[in] v The floating point value to be formatted - * @param[in] precision the precision to achieve - * @return The formatted string - */ - static std::string realString(const double v, const int precision = gPrecision); - - -public: - /// @name OutputDevice member methods - /// @{ - - /// @brief Constructor - OutputDevice(const int defaultIndentation = 0, const std::string& filename = ""); - - - /// @brief Destructor - virtual ~OutputDevice(); - - - /** @brief returns the information whether one can write into the device - * @return Whether the device can be used (stream is good) - */ - virtual bool ok(); - - /// @brief get filename or suitable description of this device - const std::string& getFilename(); - - /** @brief Closes the device and removes it from the dictionary - */ - void close(); - - - /** @brief Sets the precison or resets it to default - * @param[in] precision The accuracy (number of digits behind '.') to set - */ - void setPrecision(int precision = gPrecision); - - /** @brief Returns the precison of the underlying stream - */ - int getPrecision() { - return (int)getOStream().precision(); - } - - /** @brief Writes an XML header with optional configuration - * - * If something has been written (myXMLStack is not empty), nothing - * is written and false returned. - * - * @param[in] rootElement The root element to use - * @param[in] schemaFile The basename of the schema file to use - * @param[in] attrs Additional attributes to save within the rootElement - * @return Whether the header could be written (stack was empty) - * @todo Describe what is saved - */ - bool writeXMLHeader(const std::string& rootElement, - const std::string& schemaFile, - std::map attrs = std::map()); - - - template - bool writeHeader(const SumoXMLTag& rootElement) { - return static_cast(myFormatter)->writeHeader(getOStream(), rootElement); - } - - - /** @brief Opens an XML tag - * - * An indentation, depending on the current xml-element-stack size, is written followed - * by the given xml element ("<" + xmlElement) - * The xml element is added to the stack, then. - * - * @param[in] xmlElement Name of element to open - * @return The OutputDevice for further processing - */ - OutputDevice& openTag(const std::string& xmlElement); - - - /** @brief Opens an XML tag - * - * Helper method which finds the correct string before calling openTag. - * - * @param[in] xmlElement Id of the element to open - * @return The OutputDevice for further processing - */ - OutputDevice& openTag(const SumoXMLTag& xmlElement); - - - /** @brief Closes the most recently opened tag and optionally adds a comment - * - * The topmost xml-element from the stack is written into the stream - * as a closing element. Depending on the formatter used - * this may be something like "" or "/>" or - * nothing at all. - * - * @return Whether a further element existed in the stack and could be closed - * @todo it is not verified that the topmost element was closed - */ - bool closeTag(const std::string& comment = ""); - - - - /** @brief writes a line feed if applicable - */ - void lf() { - getOStream() << "\n"; - } - - - /** @brief writes a named attribute - * - * @param[in] attr The attribute (name) - * @param[in] val The attribute value - * @return The OutputDevice for further processing - */ - template - OutputDevice& writeAttr(const SumoXMLAttr attr, const T& val) { - PlainXMLFormatter::writeAttr(getOStream(), attr, val); - return *this; - } - - - /** @brief writes an arbitrary attribute - * - * @param[in] attr The attribute (name) - * @param[in] val The attribute value - * @return The OutputDevice for further processing - */ - template - OutputDevice& writeAttr(const std::string& attr, const T& val) { - PlainXMLFormatter::writeAttr(getOStream(), attr, val); - return *this; - } - - - /** @brief writes a string attribute only if it is not the empty string and not the string "default" - * - * @param[in] attr The attribute (name) - * @param[in] val The attribute value - * @return The OutputDevice for further processing - */ - OutputDevice& writeNonEmptyAttr(const SumoXMLAttr attr, const std::string& val) { - if (val != "" && val != "default") { - writeAttr(attr, val); - } - return *this; - } - - - /** @brief writes a preformatted tag to the device but ensures that any - * pending tags are closed - * @param[in] val The preformatted data - * @return The OutputDevice for further processing - */ - OutputDevice& writePreformattedTag(const std::string& val) { - myFormatter->writePreformattedTag(getOStream(), val); - return *this; - } - - /// @brief writes padding (ignored for binary output) - OutputDevice& writePadding(const std::string& val) { - myFormatter->writePadding(getOStream(), val); - return *this; - } - - /** @brief Retrieves a message to this device. - * - * Implementation of the MessageRetriever interface. Writes the given message to the output device. - * - * @param[in] msg The msg to write to the device - */ - void inform(const std::string& msg, const char progress = 0); - - - /** @brief Abstract output operator - * @return The OutputDevice for further processing - */ - template - OutputDevice& operator<<(const T& t) { - getOStream() << t; - postWriteHook(); - return *this; - } - - void flush() { - getOStream().flush(); - } - -protected: - /// @brief Returns the associated ostream - virtual std::ostream& getOStream() = 0; - - - /** @brief Called after every write access. - * - * Default implementation does nothing. - */ - virtual void postWriteHook(); - - -private: - /// @brief map from names to output devices - static std::map myOutputDevices; - - -private: - /// @brief The formatter for XML - OutputFormatter* myFormatter; - -protected: - std::string myFilename; - -public: - /// @brief Invalidated copy constructor. - OutputDevice(const OutputDevice&); - -private: - - /// @brief Invalidated assignment operator. - OutputDevice& operator=(const OutputDevice&); - -}; diff --git a/Util/OSM2ODR/src/utils/iodevices/OutputDevice_CERR.cpp b/Util/OSM2ODR/src/utils/iodevices/OutputDevice_CERR.cpp deleted file mode 100644 index 2a9896985..000000000 --- a/Util/OSM2ODR/src/utils/iodevices/OutputDevice_CERR.cpp +++ /dev/null @@ -1,71 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2004-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file OutputDevice_CERR.cpp -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date 2004 -/// -// An output device that encapsulates cout -/****************************************************************************/ -#include - -#include -#include "OutputDevice_CERR.h" - - -// =========================================================================== -// static member definitions -// =========================================================================== -OutputDevice* OutputDevice_CERR::myInstance = nullptr; - - -// =========================================================================== -// static method definitions -// =========================================================================== -OutputDevice* -OutputDevice_CERR::getDevice() { - // check whether the device has already been aqcuired - if (myInstance == nullptr) { - myInstance = new OutputDevice_CERR(); - } - return myInstance; -} - - -// =========================================================================== -// method definitions -// =========================================================================== -OutputDevice_CERR::OutputDevice_CERR() { - myFilename = "CERR"; -} - - -OutputDevice_CERR::~OutputDevice_CERR() { - myInstance = nullptr; -} - - -std::ostream& -OutputDevice_CERR::getOStream() { - return std::cerr; -} - - -void -OutputDevice_CERR::postWriteHook() { - std::cerr.flush(); -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/utils/iodevices/OutputDevice_CERR.h b/Util/OSM2ODR/src/utils/iodevices/OutputDevice_CERR.h deleted file mode 100644 index fdfe37099..000000000 --- a/Util/OSM2ODR/src/utils/iodevices/OutputDevice_CERR.h +++ /dev/null @@ -1,77 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2004-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file OutputDevice_CERR.h -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date 2004 -/// -// An output device that encapsulates cerr -/****************************************************************************/ -#pragma once -#include - -#include "OutputDevice.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class OutputDevice_CERR - * @brief An output device that encapsulates cerr - */ -class OutputDevice_CERR : public OutputDevice { -public: - /** @brief Returns the single cerr instance - * - * Creates and returns the cerr device. - */ - static OutputDevice* getDevice(); - - -protected: - /// @name Methods that override/implement OutputDevice-methods - /// @{ - - /** @brief Returns the associated ostream - * @return cerr - */ - std::ostream& getOStream(); - - - /** @brief Called after every write access. - * - * Calls flush on stderr. - */ - virtual void postWriteHook(); - /// @} - - -private: - /** @brief Constructor - * @exception IOError Should not be thrown by this implementation - */ - OutputDevice_CERR(); - - - /// @brief Destructor - ~OutputDevice_CERR(); - - -private: - /// @brief my singular instance - static OutputDevice* myInstance; - - -}; diff --git a/Util/OSM2ODR/src/utils/iodevices/OutputDevice_COUT.cpp b/Util/OSM2ODR/src/utils/iodevices/OutputDevice_COUT.cpp deleted file mode 100644 index d73a8aa9c..000000000 --- a/Util/OSM2ODR/src/utils/iodevices/OutputDevice_COUT.cpp +++ /dev/null @@ -1,71 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2004-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file OutputDevice_COUT.cpp -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date 2004 -/// -// An output device that encapsulates cout -/****************************************************************************/ -#include - -#include -#include "OutputDevice_COUT.h" - - -// =========================================================================== -// static member definitions -// =========================================================================== -OutputDevice* OutputDevice_COUT::myInstance = nullptr; - - -// =========================================================================== -// static method definitions -// =========================================================================== -OutputDevice* -OutputDevice_COUT::getDevice() { - // check whether the device has already been aqcuired - if (myInstance == nullptr) { - myInstance = new OutputDevice_COUT(); - } - return myInstance; -} - - -// =========================================================================== -// method definitions -// =========================================================================== -OutputDevice_COUT::OutputDevice_COUT() { - myFilename = "COUT"; -} - - -OutputDevice_COUT::~OutputDevice_COUT() { - myInstance = nullptr; -} - - -std::ostream& -OutputDevice_COUT::getOStream() { - return std::cout; -} - - -void -OutputDevice_COUT::postWriteHook() { - std::cout.flush(); -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/utils/iodevices/OutputDevice_COUT.h b/Util/OSM2ODR/src/utils/iodevices/OutputDevice_COUT.h deleted file mode 100644 index 8a5eea5a2..000000000 --- a/Util/OSM2ODR/src/utils/iodevices/OutputDevice_COUT.h +++ /dev/null @@ -1,77 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2004-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file OutputDevice_COUT.h -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date 2004 -/// -// An output device that encapsulates cout -/****************************************************************************/ -#pragma once -#include - -#include "OutputDevice.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class OutputDevice_COUT - * @brief An output device that encapsulates cout - */ -class OutputDevice_COUT : public OutputDevice { -public: - /** @brief Returns the single cout instance - * - * Creates and returns the cout device. - */ - static OutputDevice* getDevice(); - - -protected: - /// @name Methods that override/implement OutputDevice-methods - /// @{ - - /** @brief Returns the associated ostream - * @return cout - */ - std::ostream& getOStream(); - - - /** @brief Called after every write access. - * - * Calls flush on stdout. - */ - virtual void postWriteHook(); - /// @} - - -private: - /** @brief Constructor - * @exception IOError Should not be thrown by this implementation - */ - OutputDevice_COUT(); - - - /// @brief Destructor - ~OutputDevice_COUT(); - - -private: - /// @brief my singular instance - static OutputDevice* myInstance; - - -}; diff --git a/Util/OSM2ODR/src/utils/iodevices/OutputDevice_File.cpp b/Util/OSM2ODR/src/utils/iodevices/OutputDevice_File.cpp deleted file mode 100644 index be78588ad..000000000 --- a/Util/OSM2ODR/src/utils/iodevices/OutputDevice_File.cpp +++ /dev/null @@ -1,81 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2004-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file OutputDevice_File.cpp -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @author Jakob Erdmann -/// @date 2004 -/// -// An output device that encapsulates an ofstream -/****************************************************************************/ -#include - -#include -#include -#include -#ifdef HAVE_ZLIB -#include -#endif -#include -#include "OutputDevice_File.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -OutputDevice_File::OutputDevice_File(const std::string& fullName, const bool compressed) - : OutputDevice(0, fullName), myFileStream(nullptr) { -#ifdef WIN32 - if (fullName == "/dev/null") { - myFileStream = new std::ofstream("NUL"); - if (!myFileStream->good()) { - delete myFileStream; - throw IOError("Could not redirect to NUL device (" + std::string(std::strerror(errno)) + ")."); - } - return; - } -#endif -#ifdef HAVE_ZLIB - if (compressed) { - try { - myFileStream = new zstr::ofstream(fullName.c_str(), std::ios_base::out); - } catch (zstr::Exception& e) { - throw IOError("Could not build output file '" + fullName + "' (" + e.what() + ")."); - } - } else { - myFileStream = new std::ofstream(fullName.c_str(), std::ios_base::out); - } -#else - UNUSED_PARAMETER(compressed); - myFileStream = new std::ofstream(fullName.c_str(), binary ? std::ios::binary : std::ios_base::out); -#endif - if (!myFileStream->good()) { - delete myFileStream; - throw IOError("Could not build output file '" + fullName + "' (" + std::strerror(errno) + ")."); - } -} - - -OutputDevice_File::~OutputDevice_File() { - delete myFileStream; -} - - -std::ostream& -OutputDevice_File::getOStream() { - return *myFileStream; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/utils/iodevices/OutputDevice_File.h b/Util/OSM2ODR/src/utils/iodevices/OutputDevice_File.h deleted file mode 100644 index cc659dc23..000000000 --- a/Util/OSM2ODR/src/utils/iodevices/OutputDevice_File.h +++ /dev/null @@ -1,67 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2004-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file OutputDevice_File.h -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date 2004 -/// -// An output device that encapsulates an ofstream -/****************************************************************************/ -#pragma once -#include - -#include -#include "OutputDevice.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class OutputDevice_File - * @brief An output device that encapsulates an ofstream - * - * Please note that the device gots responsible for the stream and deletes - * it (it should not be deleted elsewhere). - */ -class OutputDevice_File : public OutputDevice { -public: - /** @brief Constructor - * @param[in] fullName The name of the output file to use - * @param[in] compressed whether to apply gzip compression - * @exception IOError Should not be thrown by this implementation - */ - OutputDevice_File(const std::string& fullName, const bool compressed = false); - - - /// @brief Destructor - ~OutputDevice_File(); - - -protected: - /// @name Methods that override/implement OutputDevice-methods - /// @{ - - /** @brief Returns the associated ostream - * @return The used stream - */ - std::ostream& getOStream(); - /// @} - - -private: - /// The wrapped ofstream - std::ostream* myFileStream; - -}; diff --git a/Util/OSM2ODR/src/utils/iodevices/OutputDevice_Network.cpp b/Util/OSM2ODR/src/utils/iodevices/OutputDevice_Network.cpp deleted file mode 100644 index 3a6ea9840..000000000 --- a/Util/OSM2ODR/src/utils/iodevices/OutputDevice_Network.cpp +++ /dev/null @@ -1,91 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2006-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file OutputDevice_Network.cpp -/// @author Michael Behrisch -/// @author Daniel Krajzewicz -/// @author Felix Brack -/// @date 2006 -/// -// An output device for TCP/IP Network connections -/****************************************************************************/ - - -// ========================================================================== -// included modules -// ========================================================================== -#include - -#include -#include -#include -#include "OutputDevice_Network.h" -#include "foreign/tcpip/socket.h" -#include "utils/common/ToString.h" - - -// ========================================================================== -// method definitions -// ========================================================================== -OutputDevice_Network::OutputDevice_Network(const std::string& host, - const int port) { - mySocket = new tcpip::Socket(host, port); -#ifdef _MSC_VER -#pragma warning(push) -#pragma warning(disable: 4127) // do not warn about constant conditional expression -#endif - for (int wait = 1000; true; wait += 1000) { -#ifdef _MSC_VER -#pragma warning(pop) -#endif - try { - mySocket->connect(); - break; - } catch (tcpip::SocketException& e) { - if (wait == 9000) { - throw IOError(toString(e.what()) + " (host: " + host + ", port: " + toString(port) + ")"); - } - std::this_thread::sleep_for(std::chrono::milliseconds(wait)); - } - } - myFilename = host + ":" + toString(port); -} - - -OutputDevice_Network::~OutputDevice_Network() { - mySocket->close(); - delete mySocket; -} - - -std::ostream& -OutputDevice_Network::getOStream() { - return myMessage; -} - - -void -OutputDevice_Network::postWriteHook() { - std::string toSend = myMessage.str(); - std::vector msg; - msg.insert(msg.end(), toSend.begin(), toSend.end()); - try { - mySocket->send(msg); - } catch (tcpip::SocketException& e) { - throw IOError(toString(e.what())); - } - myMessage.str(""); -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/utils/iodevices/OutputDevice_Network.h b/Util/OSM2ODR/src/utils/iodevices/OutputDevice_Network.h deleted file mode 100644 index 96fe71acd..000000000 --- a/Util/OSM2ODR/src/utils/iodevices/OutputDevice_Network.h +++ /dev/null @@ -1,93 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2006-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file OutputDevice_Network.h -/// @author Michael Behrisch -/// @author Daniel Krajzewicz -/// @author Felix Brack -/// @date 2006 -/// -// An output device for TCP/IP Network connections -/****************************************************************************/ -#pragma once -#include - -#include "foreign/tcpip/socket.h" -#include "foreign/tcpip/storage.h" -#include "OutputDevice.h" -#include -#include -#include -#include - - -// ========================================================================== -// class definitions -// ========================================================================== -/** - * @class OutputDevice_Network - * @brief An output device for TCP/IP network connections - * - * The implementation uses a portable socket implementation from the Shawn - * project (shawn.sf.net) located in src/foreign/tcpip/socket.h. It uses - * an internal storage for the messages, which is sent via the socket when - * "postWriteHook" is called. - * @see postWriteHook - */ -class OutputDevice_Network : public OutputDevice { -public: - /** @brief Constructor - * - * @param[in] host The host to connect - * @param[in] port The port to connect - * @exception IOError If the connection could not be established - */ - OutputDevice_Network(const std::string& host, - const int port); - - - /// @brief Destructor - ~OutputDevice_Network(); - - -protected: - /// @name Methods that override/implement OutputDevice-methods - /// @{ - - /** @brief Returns the associated ostream - * - * The stream is an ostringstream, actually, into which the message - * is written. It is sent when postWriteHook is called. - * - * @return The used stream - * @see postWriteHook - */ - std::ostream& getOStream(); - - - /** @brief Sends the data which was written to the string stream over the socket. - * - * Converts the stored message into a vector of chars and sends them via to - * the socket implementation. Resets the message, afterwards. - */ - virtual void postWriteHook(); - /// @} - -private: - /// @brief packet buffer - std::ostringstream myMessage; - - /// @brief the socket to transfer the data - tcpip::Socket* mySocket; - -}; diff --git a/Util/OSM2ODR/src/utils/iodevices/OutputDevice_String.cpp b/Util/OSM2ODR/src/utils/iodevices/OutputDevice_String.cpp deleted file mode 100644 index 0a2fc13f1..000000000 --- a/Util/OSM2ODR/src/utils/iodevices/OutputDevice_String.cpp +++ /dev/null @@ -1,53 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2009-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file OutputDevice_String.cpp -/// @author Michael Behrisch -/// @date 2009 -/// -// An output device that encapsulates a stringstream -/****************************************************************************/ -#include - -#include -#include -#include "OutputDevice_String.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -OutputDevice_String::OutputDevice_String(const int defaultIndentation) - : OutputDevice(defaultIndentation) { - setPrecision(); - myStream << std::setiosflags(std::ios::fixed); -} - - -OutputDevice_String::~OutputDevice_String() { -} - - -std::string -OutputDevice_String::getString() const { - return myStream.str(); -} - - -std::ostream& -OutputDevice_String::getOStream() { - return myStream; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/utils/iodevices/OutputDevice_String.h b/Util/OSM2ODR/src/utils/iodevices/OutputDevice_String.h deleted file mode 100644 index e700b67ad..000000000 --- a/Util/OSM2ODR/src/utils/iodevices/OutputDevice_String.h +++ /dev/null @@ -1,69 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2009-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file OutputDevice_String.h -/// @author Michael Behrisch -/// @date 2009 -/// -// An output device that encapsulates a stringstream -/****************************************************************************/ -#pragma once -#include - -#include -#include "OutputDevice.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class OutputDevice_String - * @brief An output device that encapsulates an ofstream - * - * Please note that the device gots responsible for the stream and deletes - * it (it should not be deleted elsewhere). - */ -class OutputDevice_String : public OutputDevice { -public: - /** @brief Constructor - * @exception IOError Should not be thrown by this implementation - */ - OutputDevice_String(const int defaultIndentation = 0); - - - /// @brief Destructor - ~OutputDevice_String(); - - - /** @brief Returns the current content as a string - * @return The content as string - */ - std::string getString() const; - -protected: - /// @name Methods that override/implement OutputDevice-methods - /// @{ - - /** @brief Returns the associated ostream - * @return The used stream - */ - std::ostream& getOStream(); - /// @} - - -private: - /// The wrapped ofstream - std::ostringstream myStream; - -}; diff --git a/Util/OSM2ODR/src/utils/iodevices/OutputFormatter.h b/Util/OSM2ODR/src/utils/iodevices/OutputFormatter.h deleted file mode 100644 index b03aba48b..000000000 --- a/Util/OSM2ODR/src/utils/iodevices/OutputFormatter.h +++ /dev/null @@ -1,105 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2012-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file OutputFormatter.h -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date 2012 -/// -// Abstract base class for output formatters -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include - - -// =========================================================================== -// class declarations -// =========================================================================== -class Boundary; -class Position; -class PositionVector; -class RGBColor; - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class OutputFormatter - * @brief Abstract base class for output formatters - * - * OutputFormatter format XML like output into the output stream. - * There are only two implementation at the moment, "normal" XML - * and binary XML. - */ -class OutputFormatter { -public: - /// @brief Destructor - virtual ~OutputFormatter() { } - - - /** @brief Writes an XML header with optional configuration - * - * If something has been written (myXMLStack is not empty), nothing - * is written and false returned. - * - * @param[in] into The output stream to use - * @param[in] rootElement The root element to use - * @param[in] attrs Additional attributes to save within the rootElement - * @todo Check which parameter is used herein - * @todo Describe what is saved - */ - virtual bool writeXMLHeader(std::ostream& into, const std::string& rootElement, - const std::map& attrs) = 0; - - - /** @brief Opens an XML tag - * - * An indentation, depending on the current xml-element-stack size, is written followed - * by the given xml element ("<" + xmlElement) - * The xml element is added to the stack, then. - * - * @param[in] into The output stream to use - * @param[in] xmlElement Name of element to open - * @return The OutputDevice for further processing - */ - virtual void openTag(std::ostream& into, const std::string& xmlElement) = 0; - - - /** @brief Opens an XML tag - * - * Helper method which finds the correct string before calling openTag. - * - * @param[in] into The output stream to use - * @param[in] xmlElement Id of the element to open - */ - virtual void openTag(std::ostream& into, const SumoXMLTag& xmlElement) = 0; - - - /** @brief Closes the most recently opened tag and optinally add a comment - * - * @param[in] into The output stream to use - * @return Whether a further element existed in the stack and could be closed - * @todo it is not verified that the topmost element was closed - */ - virtual bool closeTag(std::ostream& into, const std::string& comment = "") = 0; - - virtual void writePreformattedTag(std::ostream& into, const std::string& val) = 0; - - virtual void writePadding(std::ostream& into, const std::string& val) = 0; - -}; diff --git a/Util/OSM2ODR/src/utils/iodevices/PlainXMLFormatter.cpp b/Util/OSM2ODR/src/utils/iodevices/PlainXMLFormatter.cpp deleted file mode 100644 index ef06186d8..000000000 --- a/Util/OSM2ODR/src/utils/iodevices/PlainXMLFormatter.cpp +++ /dev/null @@ -1,113 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2012-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file PlainXMLFormatter.cpp -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date 2012 -/// -// Static storage of an output device and its base (abstract) implementation -/****************************************************************************/ -#include - -#include -#include -#include "PlainXMLFormatter.h" - - -// =========================================================================== -// member method definitions -// =========================================================================== -PlainXMLFormatter::PlainXMLFormatter(const int defaultIndentation) - : myDefaultIndentation(defaultIndentation), myHavePendingOpener(false) { -} - - -bool -PlainXMLFormatter::writeHeader(std::ostream& into, const SumoXMLTag& rootElement) { - if (myXMLStack.empty()) { - OptionsCont::getOptions().writeXMLHeader(into); - openTag(into, rootElement); - return true; - } - return false; -} - - -bool -PlainXMLFormatter::writeXMLHeader(std::ostream& into, const std::string& rootElement, - const std::map& attrs) { - if (myXMLStack.empty()) { - OptionsCont::getOptions().writeXMLHeader(into); - openTag(into, rootElement); - for (std::map::const_iterator it = attrs.begin(); it != attrs.end(); ++it) { - writeAttr(into, it->first, it->second); - } - into << ">\n"; - myHavePendingOpener = false; - return true; - } - return false; -} - - -void -PlainXMLFormatter::openTag(std::ostream& into, const std::string& xmlElement) { - if (myHavePendingOpener) { - into << ">\n"; - } - myHavePendingOpener = true; - into << std::string(4 * (myXMLStack.size() + myDefaultIndentation), ' ') << "<" << xmlElement; - myXMLStack.push_back(xmlElement); -} - - -void -PlainXMLFormatter::openTag(std::ostream& into, const SumoXMLTag& xmlElement) { - openTag(into, toString(xmlElement)); -} - - -bool -PlainXMLFormatter::closeTag(std::ostream& into, const std::string& comment) { - if (!myXMLStack.empty()) { - if (myHavePendingOpener) { - into << "/>" << comment << "\n"; - myHavePendingOpener = false; - } else { - const std::string indent(4 * (myXMLStack.size() + myDefaultIndentation - 1), ' '); - into << indent << "" << comment << "\n"; - } - myXMLStack.pop_back(); - return true; - } - return false; -} - - -void -PlainXMLFormatter::writePreformattedTag(std::ostream& into, const std::string& val) { - if (myHavePendingOpener) { - into << ">\n"; - myHavePendingOpener = false; - } - into << val; -} - -void -PlainXMLFormatter::writePadding(std::ostream& into, const std::string& val) { - into << val; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/utils/iodevices/PlainXMLFormatter.h b/Util/OSM2ODR/src/utils/iodevices/PlainXMLFormatter.h deleted file mode 100644 index d183e2eac..000000000 --- a/Util/OSM2ODR/src/utils/iodevices/PlainXMLFormatter.h +++ /dev/null @@ -1,148 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2012-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file PlainXMLFormatter.h -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date 2012 -/// -// Output formatter for plain XML output -/****************************************************************************/ -#pragma once -#include - -#include "OutputFormatter.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class PlainXMLFormatter - * @brief Output formatter for plain XML output - * - * PlainXMLFormatter format XML like output into the output stream. - */ -class PlainXMLFormatter : public OutputFormatter { -public: - /// @brief Constructor - PlainXMLFormatter(const int defaultIndentation = 0); - - - /// @brief Destructor - virtual ~PlainXMLFormatter() { } - - - /** @brief Writes an XML header with optional configuration - * - * If something has been written (myXMLStack is not empty), nothing - * is written and false returned. - * - * @param[in] into The output stream to use - * @param[in] rootElement The root element to use - * @param[in] attrs Additional attributes to save within the rootElement - * @todo Describe what is saved - */ - bool writeXMLHeader(std::ostream& into, const std::string& rootElement, - const std::map& attrs); - - - /** @brief Writes an XML header with optional configuration - * - * If something has been written (myXMLStack is not empty), nothing - * is written and false returned. - * - * @param[in] into The output stream to use - * @param[in] rootElement The root element to use - */ - bool writeHeader(std::ostream& into, const SumoXMLTag& rootElement); - - - /** @brief Opens an XML tag - * - * An indentation, depending on the current xml-element-stack size, is written followed - * by the given xml element ("<" + xmlElement) - * The xml element is added to the stack, then. - * - * @param[in] into The output stream to use - * @param[in] xmlElement Name of element to open - * @return The OutputDevice for further processing - */ - void openTag(std::ostream& into, const std::string& xmlElement); - - - /** @brief Opens an XML tag - * - * Helper method which finds the correct string before calling openTag. - * - * @param[in] into The output stream to use - * @param[in] xmlElement Id of the element to open - */ - void openTag(std::ostream& into, const SumoXMLTag& xmlElement); - - - /** @brief Closes the most recently opened tag - * - * @param[in] into The output stream to use - * @return Whether a further element existed in the stack and could be closed - * @todo it is not verified that the topmost element was closed - */ - bool closeTag(std::ostream& into, const std::string& comment = ""); - - - /** @brief writes a preformatted tag to the device but ensures that any - * pending tags are closed - * @param[in] into The output stream to use - * @param[in] val The preformatted data - */ - void writePreformattedTag(std::ostream& into, const std::string& val); - - /** @brief writes arbitrary padding - */ - void writePadding(std::ostream& into, const std::string& val); - - - /** @brief writes an arbitrary attribute - * - * @param[in] into The output stream to use - * @param[in] attr The attribute (name) - * @param[in] val The attribute value - */ - template - static void writeAttr(std::ostream& into, const std::string& attr, const T& val) { - into << " " << attr << "=\"" << toString(val, into.precision()) << "\""; - } - - - /** @brief writes a named attribute - * - * @param[in] into The output stream to use - * @param[in] attr The attribute (name) - * @param[in] val The attribute value - */ - template - static void writeAttr(std::ostream& into, const SumoXMLAttr attr, const T& val) { - into << " " << toString(attr) << "=\"" << toString(val, into.precision()) << "\""; - } - - -private: - /// @brief The stack of begun xml elements - std::vector myXMLStack; - - /// @brief The initial indentation level - int myDefaultIndentation; - - /// @brief whether a closing ">" might be missing - bool myHavePendingOpener; -}; diff --git a/Util/OSM2ODR/src/utils/options/CMakeLists.txt b/Util/OSM2ODR/src/utils/options/CMakeLists.txt deleted file mode 100644 index 70a6cafdb..000000000 --- a/Util/OSM2ODR/src/utils/options/CMakeLists.txt +++ /dev/null @@ -1,15 +0,0 @@ -set(utils_options_STAT_SRCS - Option.cpp - Option.h - OptionsCont.cpp - OptionsCont.h - OptionsIO.cpp - OptionsIO.h - OptionsLoader.cpp - OptionsLoader.h - OptionsParser.cpp - OptionsParser.h -) - -add_library(utils_options STATIC ${utils_options_STAT_SRCS}) -set_property(TARGET utils_options PROPERTY PROJECT_LABEL "z_utils_options") diff --git a/Util/OSM2ODR/src/utils/options/Option.cpp b/Util/OSM2ODR/src/utils/options/Option.cpp deleted file mode 100644 index 16d580680..000000000 --- a/Util/OSM2ODR/src/utils/options/Option.cpp +++ /dev/null @@ -1,607 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file Option.cpp -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date Mon, 17 Dec 2001 -/// -// A class representing a single program option -/****************************************************************************/ -#include - -#include -#include -#include -#include "Option.h" -#include -#include -#include -#include -#include -#include - - -// =========================================================================== -// method definitions -// =========================================================================== -/* ------------------------------------------------------------------------- - * Option - methods - * ----------------------------------------------------------------------- */ -Option::Option(bool set) - : myAmSet(set), myHaveTheDefaultValue(true), myAmWritable(true) {} - - -Option::Option(const Option& s) - : myAmSet(s.myAmSet), myHaveTheDefaultValue(s.myHaveTheDefaultValue), - myAmWritable(s.myAmWritable) {} - - -Option::~Option() {} - - -Option& -Option::operator=(const Option& s) { - if (this == &s) { - return *this; - } - myAmSet = s.myAmSet; - myHaveTheDefaultValue = s.myHaveTheDefaultValue; - myAmWritable = s.myAmWritable; - return *this; -} - - -bool -Option::isSet() const { - return myAmSet; -} - - -double -Option::getFloat() const { - throw InvalidArgument("This is not a double-option"); -} - - -int -Option::getInt() const { - throw InvalidArgument("This is not an int-option"); -} - - -std::string -Option::getString() const { - throw InvalidArgument("This is not a string-option"); -} - - -bool -Option::getBool() const { - throw InvalidArgument("This is not a bool-option"); -} - - -const IntVector& -Option::getIntVector() const { - throw InvalidArgument("This is not an int vector-option"); -} - -const StringVector& -Option::getStringVector() const { - throw InvalidArgument("This is not a string vector-option"); -} - -bool -Option::markSet() { - bool ret = myAmWritable; - myHaveTheDefaultValue = false; - myAmSet = true; - myAmWritable = false; - return ret; -} - - -void -Option::unSet() { - myAmSet = false; - myAmWritable = true; -} - - -bool -Option::isBool() const { - return false; -} - - -bool -Option::isDefault() const { - return myHaveTheDefaultValue; -} - - -bool -Option::isFileName() const { - return false; -} - - -bool -Option::isWriteable() const { - return myAmWritable; -} - - -void -Option::resetWritable() { - myAmWritable = true; -} - - -void -Option::resetDefault() { - myHaveTheDefaultValue = true; -} - - -const std::string& -Option::getDescription() const { - return myDescription; -} - - -void -Option::setDescription(const std::string& desc) { - myDescription = desc; -} - - -const std::string& -Option::getTypeName() const { - return myTypeName; -} - - - - -/* ------------------------------------------------------------------------- - * Option_Integer - methods - * ----------------------------------------------------------------------- */ -Option_Integer::Option_Integer(int value) - : Option(true), myValue(value) { - myTypeName = "INT"; -} - - -Option_Integer::~Option_Integer() {} - - -Option_Integer::Option_Integer(const Option_Integer& s) - : Option(s) { - myValue = s.myValue; -} - - -Option_Integer& -Option_Integer::operator=(const Option_Integer& s) { - if (this == &s) { - return *this; - } - Option::operator=(s); - myValue = s.myValue; - return *this; -} - - -int -Option_Integer::getInt() const { - return myValue; -} - - -bool -Option_Integer::set(const std::string& v) { - try { - myValue = StringUtils::toInt(v); - return markSet(); - } catch (...) { - std::string s = "'" + v + "' is not a valid integer."; - throw ProcessError(s); - } -} - - -std::string -Option_Integer::getValueString() const { - std::ostringstream s; - s << myValue; - return s.str(); -} - - - -/* ------------------------------------------------------------------------- - * Option_String - methods - * ----------------------------------------------------------------------- */ -Option_String::Option_String() - : Option() { - myTypeName = "STR"; -} - - -Option_String::Option_String(const std::string& value, std::string typeName) - : Option(true), myValue(value) { - myTypeName = typeName; -} - - -Option_String::~Option_String() {} - - -Option_String::Option_String(const Option_String& s) - : Option(s) { - myValue = s.myValue; -} - - -Option_String& -Option_String::operator=(const Option_String& s) { - if (this == &s) { - return *this; - } - Option::operator=(s); - myValue = s.myValue; - return *this; -} - - -std::string -Option_String::getString() const { - return myValue; -} - - -bool -Option_String::set(const std::string& v) { - myValue = v; - return markSet(); -} - - -std::string -Option_String::getValueString() const { - return myValue; -} - - - -/* ------------------------------------------------------------------------- - * Option_Float - methods - * ----------------------------------------------------------------------- */ -Option_Float::Option_Float(double value) - : Option(true), myValue(value) { - myTypeName = "FLOAT"; -} - - -Option_Float::~Option_Float() {} - - -Option_Float::Option_Float(const Option_Float& s) - : Option(s) { - myValue = s.myValue; -} - - -Option_Float& -Option_Float::operator=(const Option_Float& s) { - if (this == &s) { - return *this; - } - Option::operator=(s); - myValue = s.myValue; - return *this; -} - - -double -Option_Float::getFloat() const { - return myValue; -} - - -bool -Option_Float::set(const std::string& v) { - try { - myValue = StringUtils::toDouble(v); - return markSet(); - } catch (...) { - throw ProcessError("'" + v + "' is not a valid float."); - } -} - - -std::string -Option_Float::getValueString() const { - std::ostringstream s; - s << myValue; - return s.str(); -} - - - -/* ------------------------------------------------------------------------- - * Option_Bool - methods - * ----------------------------------------------------------------------- */ -Option_Bool::Option_Bool(bool value) - : Option(true), myValue(value) { - myTypeName = "BOOL"; -} - - -Option_Bool::~Option_Bool() {} - - -Option_Bool::Option_Bool(const Option_Bool& s) - : Option(s) { - myValue = s.myValue; -} - - -Option_Bool& -Option_Bool::operator=(const Option_Bool& s) { - if (this == &s) { - return *this; - } - Option::operator=(s); - myValue = s.myValue; - return *this; -} - - -bool -Option_Bool::getBool() const { - return myValue; -} - - -bool -Option_Bool::set(const std::string& v) { - try { - myValue = StringUtils::toBool(v); - return markSet(); - } catch (...) { - throw ProcessError("'" + v + "' is not a valid bool."); - } -} - - -std::string -Option_Bool::getValueString() const { - if (myValue) { - return "true"; - } - return "false"; -} - - -bool -Option_Bool::isBool() const { - return true; -} - - - -/* ------------------------------------------------------------------------- - * Option_BoolExtended - methods - * ----------------------------------------------------------------------- */ -Option_BoolExtended::Option_BoolExtended(bool value) - : Option_Bool(value), myValueString(value ? "true" : "false") { -} - - -Option_BoolExtended::~Option_BoolExtended() {} - - -Option_BoolExtended::Option_BoolExtended(const Option_BoolExtended& s) - : Option_Bool(s.myValue) { - myValueString = s.myValueString; -} - - -Option_BoolExtended& -Option_BoolExtended::operator=(const Option_BoolExtended& s) { - if (this == &s) { - return *this; - } - Option::operator=(s); - myValue = s.myValue; - myValueString = s.myValueString; - return *this; -} - - -bool -Option_BoolExtended::set(const std::string& v) { - try { - myValue = StringUtils::toBool(v); - myValueString = ""; - } catch (...) { - myValue = true; - myValueString = v; - } - return markSet(); -} - - -std::string -Option_BoolExtended::getValueString() const { - return myValueString; -} - - -/* ------------------------------------------------------------------------- - * Option_UIntVector - methods - * ----------------------------------------------------------------------- */ -Option_IntVector::Option_IntVector() - : Option() { - myTypeName = "INT[]"; -} - - -Option_IntVector::Option_IntVector(const IntVector& value) - : Option(true), myValue(value) { - myTypeName = "INT[]"; -} - - -Option_IntVector::Option_IntVector(const Option_IntVector& s) - : Option(s), myValue(s.myValue) {} - - -Option_IntVector::~Option_IntVector() {} - - -Option_IntVector& -Option_IntVector::operator=(const Option_IntVector& s) { - Option::operator=(s); - myValue = s.myValue; - return (*this); -} - - -const IntVector& -Option_IntVector::getIntVector() const { - return myValue; -} - - -bool -Option_IntVector::set(const std::string& v) { - myValue.clear(); - try { - if (v.find(';') != std::string::npos) { - WRITE_WARNING("Please note that using ';' as list separator is deprecated and not accepted anymore."); - } - StringTokenizer st(v, ",", true); - while (st.hasNext()) { - myValue.push_back(StringUtils::toInt(st.next())); - } - return markSet(); - } catch (EmptyData&) { - throw ProcessError("Empty element occurred in " + v); - } catch (...) { - throw ProcessError("'" + v + "' is not a valid integer vector."); - } -} - - -std::string -Option_IntVector::getValueString() const { - return joinToString(myValue, ','); -} - - -/* ------------------------------------------------------------------------- - * Option_StringVector - methods - * ----------------------------------------------------------------------- */ -Option_StringVector::Option_StringVector() : Option() { - myTypeName = "STR[]"; -} - -Option_StringVector::Option_StringVector(const StringVector& value) - : Option(true), myValue(value) { - myTypeName = "STR[]"; -} - -Option_StringVector::Option_StringVector(const Option_StringVector& s) - : Option(s), myValue(s.myValue) {} - -Option_StringVector::~Option_StringVector() {} - -Option_StringVector& -Option_StringVector::operator=(const Option_StringVector& s) { - Option::operator=(s); - myValue = s.myValue; - return (*this); -} - -const StringVector& -Option_StringVector::getStringVector() const { - return myValue; -} - -bool -Option_StringVector::set(const std::string& v) { - myValue.clear(); - try { - if (v.find(';') != std::string::npos) { - WRITE_WARNING("Please note that using ';' as list separator is deprecated and not accepted anymore."); - } - StringTokenizer st(v, ",", true); - while (st.hasNext()) { - myValue.push_back(StringUtils::prune(st.next())); - } - return markSet(); - } catch (EmptyData&) { - throw ProcessError("Empty element occurred in " + v); - } catch (...) { - throw ProcessError("'" + v + "' is not a valid string vector."); - } -} - -std::string -Option_StringVector::getValueString() const { - return joinToString(myValue, ','); -} - - -/* ------------------------------------------------------------------------- - * Option_FileName - methods - * ----------------------------------------------------------------------- */ -Option_FileName::Option_FileName() : Option_StringVector() { - myTypeName = "FILE"; -} - -Option_FileName::Option_FileName(const StringVector& value) - : Option_StringVector(value) { - myTypeName = "FILE"; -} - -Option_FileName::Option_FileName(const Option_FileName& s) - : Option_StringVector(s) {} - -Option_FileName::~Option_FileName() {} - -Option_FileName& Option_FileName::operator=(const Option_FileName& s) { - Option_StringVector::operator=(s); - return (*this); -} - -bool Option_FileName::isFileName() const { - return true; -} - -std::string -Option_FileName::getString() const { - return Option_StringVector::getValueString(); -} - -std::string Option_FileName::getValueString() const { - return StringUtils::urlEncode(Option_StringVector::getValueString(), " ;%"); -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/utils/options/Option.h b/Util/OSM2ODR/src/utils/options/Option.h deleted file mode 100644 index 59526277a..000000000 --- a/Util/OSM2ODR/src/utils/options/Option.h +++ /dev/null @@ -1,828 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file Option.h -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @author Jakob Erdmann -/// @date Mon, 17 Dec 2001 -/// -// Classes representing a single program option (with different types) -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include -#include - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @typedef IntVector - * @brief Definition of a vector of ints - */ -typedef std::vector IntVector; -/** - * @typedef StringVector - * @brief Definition of a vector of strings - */ -typedef std::vector StringVector; - -/* ------------------------------------------------------------------------- - * Option - * ----------------------------------------------------------------------- */ -/** - * @class Option - * @brief A class representing a single program option - * - * The base class for a single program option. All options which hold values - * are derived from this class as the type of stored values may differ. - * - * Most of the getter-methods throw exceptions because this base class is not meant - * to hold any values by itself. Instead, the derived classes implement the - * appropriate method (Option_Integer implements getInt, f.e.). So, when one - * tries to retrieve a value which is not of the type of the option, an - * exception will be thrown. This behaviour is meant to be valid, because - * errors like this one only occur when building and testing the application. - * - * Due to described behaviour, this class has no public constructors. Only - * construction of derived, value and type holding, classes is allowed. - * - * At the begin (after being constructed) an Option either has a default value or not. - * In dependance to this, myHaveTheDefaultValue is set. Also, myAmSet is set to - * true if a default value was supported. myAmWritable is set to true, - * indicating that a new value may be set. - * - * Each option may have a description about its purpose stored. Furthermore, it - * stores a man-readable type name for this option. - */ -class Option { -public: - /** destructor */ - virtual ~Option(); - - - /** @brief returns the information whether this options holds a valid value - * @return Whether a value has been set - */ - bool isSet() const; - - - /** @brief marks this option as unset - */ - void unSet(); - - - /** @brief Returns the stored double value - * - * Option_Float returns the stored real number in this method's reimplementation. - * All other option classes do not override this method which throws an InvalidArgument-exception. - * - * @return Returns the stored real number if being an instance of Option_Float - * @exception InvalidArgument If the class is not an instance of Option_Float - */ - virtual double getFloat() const; - - - /** @brief Returns the stored integer value - * - * Option_Integer returns the stored integer number in this method's reimplementation. - * All other option classesdo not override this method which throws an InvalidArgument-exception. - * - * @return Returns the stored integer number if being an instance of Option_Integer - * @exception InvalidArgument If the class is not an instance of Option_Integer - */ - virtual int getInt() const; - - - /** @brief Returns the stored string value - * - * Option_String returns the stored string in this method's reimplementation. - * Option_FileName's reimplementation is only to be used for single filename string-vector options. - * All other option classes do not override this method which throws an InvalidArgument-exception. - * - * @return Returns the stored string if being an instance of Option_String or Option_FileName - * @exception InvalidArgument If the class is not an instance of Option_String or Option_FileName - */ - virtual std::string getString() const; - - - /** @brief Returns the stored boolean value - * - * Option_Bool returns the stored boolean in this method's reimplementation. - * All other option classes do not override this method which throws an InvalidArgument-exception. - * - * @return Returns the stored boolean if being an instance of Option_Bool - * @exception InvalidArgument If the class is not an instance of Option_Bool - */ - virtual bool getBool() const; - - - /** @brief Returns the stored integer vector - * - * Option_IntVector returns the stored integer vector in this method's reimplementation. - * All other option classes do not override this method which throws an InvalidArgument-exception. - * - * @return Returns the stored integer vector if being an instance of Option_IntVector - * @exception InvalidArgument If the class is not an instance of Option_IntVector - */ - virtual const IntVector& getIntVector() const; - - /** @brief Returns the stored string vector - * - * Option_StringVector returns the stored string vector in this method's reimplementation. - * All other option classes do not override this method which throws an InvalidArgument-exception. - * - * @return Returns the stored string vector if being an instance of Option_StringVector - * @exception InvalidArgument If the class is not an instance of Option_StringVector - */ - virtual const StringVector& getStringVector() const; - - /** @brief Stores the given value - * - * This method is overriden by all option classes. - * The value is converted into the proper type and stored in "myValue". - * Then, "markSet" is called in order to know that a value has been set. - * - * The method returns whether the value could be set (the return value from - * "markSet"). - * - * If the string could not be converted into the type, an InvalidArgument - * is thrown. - * - * @return Whether the new value could be set - * @exception InvalidArgument If the value could not be converted - */ - virtual bool set(const std::string& v) = 0; - - - /** @brief Returns the string-representation of the value - * - * The stored value is encoded into a string and returned. - * - * @return The stored value encoded into a string- - */ - virtual std::string getValueString() const = 0; - - - /** @brief Returns the information whether the option is a bool option - * - * Returns false. Only Option_Bool overrides this method returning true. - * - * @return true if the Option is an Option_Bool, false otherwise - */ - virtual bool isBool() const; - - - /** @brief Returns the information whether the option holds the default value - * - * @return true if the option was not set from command line / configuration, false otherwise - */ - virtual bool isDefault() const; - - - /** @brief Returns the information whether this option is a file name - * - * Returns false. Only Option_FileName overrides this method returning true. - * - * @return true if the Option is an Option_FileName, false otherwise - */ - virtual bool isFileName() const; - - - /** @brief Returns the information whether the option may be set a further time - * - * This method returns whether the option was not already set using command line - * options / configuration. This is done by returning the value of myAmWritable. - * - * @return Whether the option may be set from the command line / configuration - */ - bool isWriteable() const; - - - /** @brief Resets the option to be writeable - * - * An option is writable after initialisation, but as soon as it gets set, - * it is no longer writeable. This method resets the writable-flag. - */ - void resetWritable(); - - - /** @brief Resets the option to be on its default value - * - * An option is on its default after initialisation with a value, but as soon as it gets set, - * it is no longer. This method resets the default-flag. - */ - void resetDefault(); - - - /** @brief Returns the description of what this option does - * - * The description stored in myDescription is returned. - * - * @return The description of this option's purpose - */ - const std::string& getDescription() const; - - - /** @brief Sets the description of what this option does - * - * The description stored in myDescription is returned. - * - * @return The description of this option's purpose - */ - void setDescription(const std::string& desc); - - - /** @brief Returns the mml-type name of this option - * - * The type name stored in myTypeName is returned. - * - * @return The man-readable type name - */ - virtual const std::string& getTypeName() const; - - - /** @brief Create a new Option of the given type with given default value but make it unset - * @note Was implemented to allow warning once if user didn't set the option, refs. #4567 - * @see MSDeviceSSM::insertOptions() - */ - template - static OptionType* makeUnsetWithDefault(ValueType def) { - OptionType* o = new OptionType(def); - o->unSet(); - return o; - } - - -protected: - /** @brief Marks the information as set - * - * Sets the "myAmSet" - information. Returns whether the option was writeable before. - * - * @return Whether the option was not set before. - */ - bool markSet(); - - -protected: - /** @brief Constructor - * - * This constructor should be used by derived classes. - * The boolean value indicates whether a default value was supplied or not. - * - * @param[in] set A default value was supplied - */ - Option(bool set = false); - - - /** @brief Copy constructor */ - Option(const Option& s); - - - /** @brief Assignment operator */ - virtual Option& operator=(const Option& s); - - -protected: - /// @brief A type name for this option (has presets, but may be overwritten) - std::string myTypeName; - - -private: - /** @brief information whether the value is set */ - bool myAmSet; - - /** @brief information whether the value is the default value (is then set) */ - bool myHaveTheDefaultValue; - - /** @brief information whether the value may be changed */ - bool myAmWritable; - - /// @brief The description what this option does - std::string myDescription; - -}; - - -/* ------------------------------------------------------------------------- - * Option_Integer - * ----------------------------------------------------------------------- */ -/** - * @class Option_Integer - * @brief An integer-option - */ -class Option_Integer : public Option { -public: - /** @brief Constructor for an option with a default value - * - * Calls Option(true) - * - * @param[in] value This option's default value - */ - Option_Integer(int value); - - - /** @brief Copy constructor */ - Option_Integer(const Option_Integer& s); - - - /** @brief Destructor */ - ~Option_Integer(); - - - /** @brief Assignment operator */ - Option_Integer& operator=(const Option_Integer& s); - - - /** @brief Returns the stored integer value - * @see Option::getInt() - * @return Returns the stored integer number - */ - int getInt() const; - - - /** @brief Stores the given value after parsing it into an integer - * - * The value is converted into an integer and stored in "myValue". - * Then, "markSet" is called in order to know that a value has been set. - * - * The method returns whether the value could be set (the return value from - * "markSet"). - * - * If the string could not be converted into an integer, an InvalidArgument - * is thrown. - * - * @see bool Option::set(std::string v) - * @return Whether the new value could be set - * @exception InvalidArgument If the value could not be converted into an integer - */ - bool set(const std::string& v); - - - /** @brief Returns the string-representation of the value - * - * The stored value is encoded into a string and returned. - * - * @see std::string Option::getValueString() - * @return The stored value encoded into a string - */ - std::string getValueString() const; - - -private: - /** the value, valid only when the base-classes "myAmSet"-member is true */ - int myValue; - -}; - - -/* ------------------------------------------------------------------------- - * Option_String - * ----------------------------------------------------------------------- */ -class Option_String : public Option { -public: - /** @brief Constructor for an option with no default value - * - * Calls Option(false) - */ - Option_String(); - - - /** @brief Constructor for an option with a default value - * - * Calls Option(true) - * - * @param[in] value This option's default value - */ - Option_String(const std::string& value, std::string typeName = "STR"); - - - /** @brief Copy constructor */ - Option_String(const Option_String& s); - - - /** @brief Destructor */ - virtual ~Option_String(); - - - /** @brief Assignment operator */ - Option_String& operator=(const Option_String& s); - - - /** @brief Returns the stored string value - * @see std::string Option::getString() - * @return Returns the stored string - */ - std::string getString() const; - - - /** @brief Stores the given value - * - * The value is stored in "myValue". - * Then, "markSet" is called in order to know that a value has been set. - * - * The method returns whether the value could be set (the return value from - * "markSet"). - * - * @see bool Option::set(std::string v) - * @return Whether the new value could be set - */ - bool set(const std::string& v); - - - /** @brief Returns the string-representation of the value - * - * The stored value is encoded into a string and returned. - * - * @see std::string Option::getValueString() - * @return The stored value encoded into a string - */ - std::string getValueString() const; - - -protected: - /** the value, valid only when the base-classes "myAmSet"-member is true */ - std::string myValue; - -}; - - -/* ------------------------------------------------------------------------- - * Option_Float - * ----------------------------------------------------------------------- */ -class Option_Float : public Option { -public: - /** @brief Constructor for an option with a default value - * - * Calls Option(true) - * - * @param[in] value This option's default value - */ - Option_Float(double value); - - - /** @brief Copy constructor */ - Option_Float(const Option_Float& s); - - - /** @brief Destructor */ - ~Option_Float(); - - - /** @brief Assignment operator */ - Option_Float& operator=(const Option_Float& s); - - - /** @brief Returns the stored double value - * @see double Option::getFloat() - * @return Returns the stored real number - */ - double getFloat() const; - - - /** @brief Stores the given value after parsing it into a double - * - * The value is converted into a double and stored in "myValue". - * Then, "markSet" is called in order to know that a value has been set. - * - * The method returns whether the value could be set (the return value from - * "markSet"). - * - * If the string could not be converted into a double, an InvalidArgument - * is thrown. - * - * @see bool Option::set(std::string v) - * @return Whether the new value could be set - * @exception InvalidArgument If the value could not be converted into a double - */ - bool set(const std::string& v); - - - /** @brief Returns the string-representation of the value - * - * The stored value is encoded into a string and returned. - * - * @see std::string Option::getValueString() - * @return The stored value encoded into a string - */ - std::string getValueString() const; - - -private: - /** the value, valid only when the base-classes "myAmSet"-member is true */ - double myValue; - -}; - - -/* ------------------------------------------------------------------------- - * Option_Bool - * ----------------------------------------------------------------------- */ -class Option_Bool : public Option { -public: - /** @brief Constructor for an option with a default value - * - * Calls Option(true) - * - * @param[in] value This option's default value - */ - Option_Bool(bool value); - - - /** @brief Copy constructor */ - Option_Bool(const Option_Bool& s); - - - /** @brief Destructor */ - ~Option_Bool(); - - - /** @brief Assignment operator */ - Option_Bool& operator=(const Option_Bool& s); - - - /** @brief Returns the stored boolean value - * @see bool Option::getBool() - * @return Returns the stored boolean - */ - bool getBool() const; - - /** sets the given value (converts it to bool) */ - virtual bool set(const std::string& v); - - - /** @brief Returns the string-representation of the value - * - * If myValue is true, "true" is returned, "false" otherwise. - * - * @see std::string Option::getValueString() - * @return The stored value encoded into a string - */ - virtual std::string getValueString() const; - - - /** @brief Returns true, the information whether the option is a bool option - * - * Returns true. - * - * @see bool Option::isBool() - * @return true - */ - bool isBool() const; - - -protected: - /** the value, valid only when the base-classes "myAmSet"-member is true */ - bool myValue; - -}; - - - -/* ------------------------------------------------------------------------- - * Option_BoolExtended - * ----------------------------------------------------------------------- */ -class Option_BoolExtended : public Option_Bool { -public: - /** @brief Constructor for an option that can be used without an argument - * like Option_BoolExtended but which also handles value strings - * - * Calls Option(true) - * - * @param[in] value This option's default value - */ - Option_BoolExtended(bool value); - - - /** @brief Copy constructor */ - Option_BoolExtended(const Option_BoolExtended& s); - - - /** @brief Destructor */ - ~Option_BoolExtended(); - - - /** @brief Assignment operator */ - Option_BoolExtended& operator=(const Option_BoolExtended& s); - - - /** sets the given value (converts it to bool) */ - bool set(const std::string& v); - - - /** @brief Returns the string-representation of the value - * - * If myValue is true, "true" is returned, "false" otherwise. - * - * @see std::string Option::getValueString() - * @return The stored value encoded into a string - */ - std::string getValueString() const; - - -private: - /** the value, valid only when the base-classes "myAmSet"-member is true */ - std::string myValueString; - -}; - - -/* ------------------------------------------------------------------------- - * Option_IntVector - * ----------------------------------------------------------------------- */ -class Option_IntVector : public Option { -public: - /** @brief Constructor for an option with no default value - */ - Option_IntVector(); - - - /** @brief Constructor for an option with a default value - * - * @param[in] value This option's default value - */ - Option_IntVector(const IntVector& value); - - - /** @brief Copy constructor */ - Option_IntVector(const Option_IntVector& s); - - - /** @brief Destructor */ - virtual ~Option_IntVector(); - - - /** @brief Assignment operator */ - Option_IntVector& operator=(const Option_IntVector& s); - - - /** @brief Returns the stored integer vector - * @see const IntVector &Option::getIntVector() - * @return Returns the stored integer vector - */ - const IntVector& getIntVector() const; - - - /** @brief Stores the given value after parsing it into a vector of integers - * - * The value is converted into a vector of integers and stored in "myValue". - * Then, "markSet" is called in order to know that a value has been set. - * - * The method returns whether the value could be set (the return value from - * "markSet"). - * - * If the string could not be converted into a vector of integers, an InvalidArgument - * is thrown. - * - * @see bool Option::set(std::string v) - * @return Whether the new value could be set - * @exception InvalidArgument If the value could not be converted into a vector of integers - */ - bool set(const std::string& v); - - - /** @brief Returns the string-representation of the value - * - * The stored value is encoded into a string and returned. - * - * @see std::string Option::getValueString() - * @return The stored value encoded into a string - */ - std::string getValueString() const; - - -private: - /** the value, valid only when the base-classes "myAmSet"-member is true */ - IntVector myValue; -}; - - -/* ------------------------------------------------------------------------- - * Option_StringVector - * ----------------------------------------------------------------------- */ -class Option_StringVector : public Option { -public: - /** @brief Constructor for an option with no default value - */ - Option_StringVector(); - - /** @brief Constructor for an option with a default value - * - * @param[in] value This option's default value - */ - Option_StringVector(const StringVector& value); - - /** @brief Copy constructor */ - Option_StringVector(const Option_StringVector& s); - - /** @brief Destructor */ - virtual ~Option_StringVector(); - - /** @brief Assignment operator */ - Option_StringVector& operator=(const Option_StringVector& s); - - /** @brief Returns the stored string vector - * @see const StringVector &Option::getStringVector() - * @return Returns the stored string vector - */ - const StringVector& getStringVector() const; - - /** @brief Stores the given value after parsing it into a vector of strings - * - * The value is converted into a vector of strings and stored in "myValue". - * Then, "markSet" is called in order to know that a value has been set. - * - * The method returns whether the value could be set (the return value from - * "markSet"). - * - * If the string could not be converted into a vector of strings, an - * InvalidArgument is thrown. - * - * @see bool Option::set(std::string v) - * @return Whether the new value could be set - * @exception InvalidArgument If the value could not be converted into a - * vector of strings - */ - bool set(const std::string& v); - - /** @brief Returns the string-representation of the value - * - * The stored value is encoded into a string and returned. - * - * @see std::string Option::getValueString() - * @return The stored value encoded into a string - */ - std::string getValueString() const; - -private: - /** the value, valid only when the base-classes "myAmSet"-member is true */ - StringVector myValue; -}; - - -/* ------------------------------------------------------------------------- - * Option_FileName - * ----------------------------------------------------------------------- */ -class Option_FileName : public Option_StringVector { -public: - /** @brief Constructor for an option with no default value - */ - Option_FileName(); - - /** @brief Constructor for an option with a default value - * - * @param[in] value This option's default value - */ - Option_FileName(const StringVector& value); - - /** @brief Copy constructor */ - Option_FileName(const Option_FileName& s); - - /** @brief Destructor */ - virtual ~Option_FileName(); - - /** @brief Assignment operator */ - Option_FileName& operator=(const Option_FileName& s); - - /** @brief Returns true, the information whether this option is a file name - * - * Returns true. - * - * @return true - */ - bool isFileName() const; - - /** @brief Legacy method that returns the stored filenames as a comma-separated string. - * - * @see std::string Option::getString() - * @see std::string StringVector::getValueString() - * @return Returns comma-separated string of the stored filenames - * @deprecated Legacy method used when Option_FileName was still derived from Option_String; - * not in line with code style of the Options sub-system. - */ - std::string getString() const; - - /** @brief Returns the string-representation of the value - * - * The value is URL-encoded using StringUtils::urlEncode and returned. - * - * @see std::string Option::getValueString() - * @return The stored value encoded into a string - */ - std::string getValueString() const; -}; diff --git a/Util/OSM2ODR/src/utils/options/OptionsCont.cpp b/Util/OSM2ODR/src/utils/options/OptionsCont.cpp deleted file mode 100644 index 1cae4e7c5..000000000 --- a/Util/OSM2ODR/src/utils/options/OptionsCont.cpp +++ /dev/null @@ -1,946 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file OptionsCont.cpp -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @author Walter Bamberger -/// @date Mon, 17 Dec 2001 -/// -// A storage for options (typed value containers) -/****************************************************************************/ -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "Option.h" -#include "OptionsCont.h" -#include -#include -#include -#include -#include -#include -#include - - -// =========================================================================== -// static member definitions -// =========================================================================== -OptionsCont OptionsCont::myOptions; - - -// =========================================================================== -// method definitions -// =========================================================================== -OptionsCont& -OptionsCont::getOptions() { - return myOptions; -} - - -OptionsCont::OptionsCont() - : myAddresses(), myValues(), myDeprecatedSynonymes() { - myCopyrightNotices.push_back("Copyright (C) 2001-2020 German Aerospace Center (DLR) and others; https://sumo.dlr.de"); -} - - -OptionsCont::~OptionsCont() { - clear(); -} - - -void -OptionsCont::doRegister(const std::string& name, Option* v) { - assert(v != 0); - ItemAddressContType::iterator i = std::find(myAddresses.begin(), myAddresses.end(), v); - if (i == myAddresses.end()) { - myAddresses.push_back(v); - } - if (myValues.find(name) != myValues.end()) { - throw ProcessError(name + " is an already used option name."); - } - myValues[name] = v; -} - - -void -OptionsCont::doRegister(const std::string& name1, char abbr, Option* v) { - doRegister(name1, v); - doRegister(convertChar(abbr), v); -} - - -void -OptionsCont::addSynonyme(const std::string& name1, const std::string& name2, bool isDeprecated) { - KnownContType::iterator i1 = myValues.find(name1); - KnownContType::iterator i2 = myValues.find(name2); - if (i1 == myValues.end() && i2 == myValues.end()) { - throw ProcessError("Neither the option '" + name1 + "' nor the option '" + name2 + "' is known yet"); - } - if (i1 != myValues.end() && i2 != myValues.end()) { - if ((*i1).second == (*i2).second) { - return; - } - throw ProcessError("Both options '" + name1 + "' and '" + name2 + "' do exist and differ."); - } - if (i1 == myValues.end() && i2 != myValues.end()) { - doRegister(name1, (*i2).second); - if (isDeprecated) { - myDeprecatedSynonymes[name1] = false; - } - } - if (i1 != myValues.end() && i2 == myValues.end()) { - doRegister(name2, (*i1).second); - if (isDeprecated) { - myDeprecatedSynonymes[name2] = false; - } - } -} - - -void -OptionsCont::addXMLDefault(const std::string& name, const std::string& xmlRoot) { - myXMLDefaults[xmlRoot] = name; -} - - -bool -OptionsCont::exists(const std::string& name) const { - return myValues.count(name) > 0; -} - - -bool -OptionsCont::isSet(const std::string& name, bool failOnNonExistant) const { - KnownContType::const_iterator i = myValues.find(name); - if (i == myValues.end()) { - if (failOnNonExistant) { - throw ProcessError("Internal request for unknown option '" + name + "'!"); - } else { - return false; - } - } - return (*i).second->isSet(); -} - - -void -OptionsCont::unSet(const std::string& name, bool failOnNonExistant) const { - KnownContType::const_iterator i = myValues.find(name); - if (i == myValues.end()) { - if (failOnNonExistant) { - throw ProcessError("Internal request for unknown option '" + name + "'!"); - } else { - return; - } - } - (*i).second->unSet(); -} - - -bool -OptionsCont::isDefault(const std::string& name) const { - KnownContType::const_iterator i = myValues.find(name); - if (i == myValues.end()) { - return false; - } - return (*i).second->isDefault(); -} - - -Option* -OptionsCont::getSecure(const std::string& name) const { - KnownContType::const_iterator k = myValues.find(name); - if (k == myValues.end()) { - throw ProcessError("No option with the name '" + name + "' exists."); - } - std::map::iterator s = myDeprecatedSynonymes.find(name); - if (s != myDeprecatedSynonymes.end() && !s->second) { - std::string defaultName; - for (std::map >::const_iterator i = mySubTopicEntries.begin(); i != mySubTopicEntries.end(); ++i) { - for (std::vector::const_iterator j = i->second.begin(); j != i->second.end(); ++j) { - KnownContType::const_iterator l = myValues.find(*j); - if (l != myValues.end() && l->second == k->second) { - defaultName = *j; - break; - } - } - if (defaultName != "") { - break; - } - } - WRITE_WARNING("Please note that '" + name + "' is deprecated.\n Use '" + defaultName + "' instead."); - s->second = true; - } - return k->second; -} - - -std::string -OptionsCont::getValueString(const std::string& name) const { - Option* o = getSecure(name); - return o->getValueString(); -} - - -std::string -OptionsCont::getString(const std::string& name) const { - Option* o = getSecure(name); - return o->getString(); -} - - -double -OptionsCont::getFloat(const std::string& name) const { - Option* o = getSecure(name); - return o->getFloat(); -} - - -int -OptionsCont::getInt(const std::string& name) const { - Option* o = getSecure(name); - return o->getInt(); -} - - -bool -OptionsCont::getBool(const std::string& name) const { - Option* o = getSecure(name); - return o->getBool(); -} - - -const IntVector& -OptionsCont::getIntVector(const std::string& name) const { - Option* o = getSecure(name); - return o->getIntVector(); -} - -const StringVector& -OptionsCont::getStringVector(const std::string& name) const { - Option* o = getSecure(name); - return o->getStringVector(); -} - -bool -OptionsCont::set(const std::string& name, const std::string& value) { - Option* o = getSecure(name); - if (!o->isWriteable()) { - reportDoubleSetting(name); - return false; - } - try { - if (!o->set(value)) { - return false; - } - } catch (ProcessError& e) { - WRITE_ERROR("While processing option '" + name + "':\n " + e.what()); - return false; - } - return true; -} - - -bool -OptionsCont::setDefault(const std::string& name, const std::string& value) { - if (set(name, value)) { - getSecure(name)->resetDefault(); - return true; - } - return false; -} - - -bool -OptionsCont::setByRootElement(const std::string& root, const std::string& value) { - if (myXMLDefaults.count(root) > 0) { - return set(myXMLDefaults[root], value); - } - if (myXMLDefaults.count("") > 0) { - return set(myXMLDefaults[""], value); - } - return false; -} - - -std::vector -OptionsCont::getSynonymes(const std::string& name) const { - Option* o = getSecure(name); - std::vector v(0); - for (KnownContType::const_iterator i = myValues.begin(); i != myValues.end(); i++) { - if ((*i).second == o && name != (*i).first) { - v.push_back((*i).first); - } - } - return v; -} - - -const std::string& -OptionsCont::getDescription(const std::string& name) const { - return getSecure(name)->getDescription(); -} - - -std::ostream& -operator<<(std::ostream& os, const OptionsCont& oc) { - std::vector done; - os << "Options set:" << std::endl; - for (OptionsCont::KnownContType::const_iterator i = oc.myValues.begin(); - i != oc.myValues.end(); i++) { - std::vector::iterator j = std::find(done.begin(), done.end(), (*i).first); - if (j == done.end()) { - std::vector synonymes = oc.getSynonymes((*i).first); - if (synonymes.size() != 0) { - os << (*i).first << " ("; - for (j = synonymes.begin(); j != synonymes.end(); j++) { - if (j != synonymes.begin()) { - os << ", "; - } - os << (*j); - } - os << ")"; - } else { - os << (*i).first; - } - if ((*i).second->isSet()) { - os << ": " << (*i).second->getValueString() << std::endl; - } else { - os << ": " << std::endl; - } - done.push_back((*i).first); - copy(synonymes.begin(), synonymes.end(), back_inserter(done)); - } - } - return os; -} - - -void -OptionsCont::relocateFiles(const std::string& configuration) const { - for (Option* const option : myAddresses) { - if (option->isFileName() && option->isSet()) { - StringVector fileList = StringVector(option->getStringVector()); - for (std::string& f : fileList) { - f = FileHelpers::checkForRelativity(f, configuration); - try { - f = StringUtils::urlDecode(f); - } catch (NumberFormatException& e) { - WRITE_WARNING(toString(e.what()) + " when trying to decode filename '" + f + "'."); - } - } - const std::string conv = joinToString(fileList, ','); - if (conv != joinToString(option->getStringVector(), ',')) { - const bool hadDefault = option->isDefault(); - option->set(conv); - if (hadDefault) { - option->resetDefault(); - } - } - } - } -} - - -bool -OptionsCont::isUsableFileList(const std::string& name) const { - Option* o = getSecure(name); - // check whether the option is set - // return false i not - if (!o->isSet()) { - return false; - } - // check whether the list of files is valid - bool ok = true; - std::vector files = getStringVector(name); - if (files.size() == 0) { - WRITE_ERROR("The file list for '" + name + "' is empty."); - ok = false; - } - for (std::vector::const_iterator fileIt = files.begin(); fileIt != files.end(); ++fileIt) { - if (!FileHelpers::isReadable(*fileIt)) { - if (*fileIt != "") { - WRITE_ERROR("File '" + *fileIt + "' is not accessible (" + std::strerror(errno) + ")."); - ok = false; - } else { - WRITE_WARNING("Empty file name given; ignoring."); - } - } - } - return ok; -} - - -bool -OptionsCont::checkDependingSuboptions(const std::string& name, const std::string& prefix) const { - Option* o = getSecure(name); - if (o->isSet()) { - return true; - } - bool ok = true; - std::vector seenSynonymes; - for (KnownContType::const_iterator i = myValues.begin(); i != myValues.end(); i++) { - if (std::find(seenSynonymes.begin(), seenSynonymes.end(), (*i).first) != seenSynonymes.end()) { - continue; - } - if ((*i).second->isSet() && !(*i).second->isDefault() && (*i).first.find(prefix) == 0) { - WRITE_ERROR("Option '" + (*i).first + "' needs option '" + name + "'."); - std::vector synonymes = getSynonymes((*i).first); - std::copy(synonymes.begin(), synonymes.end(), std::back_inserter(seenSynonymes)); - ok = false; - } - } - return ok; -} - - -void -OptionsCont::reportDoubleSetting(const std::string& arg) const { - std::vector synonymes = getSynonymes(arg); - std::ostringstream s; - s << "A value for the option '" + arg + "' was already set.\n Possible synonymes: "; - for (std::vector::iterator i = synonymes.begin(); i != synonymes.end();) { - s << (*i); - i++; - if (i != synonymes.end()) { - s << ", "; - } - } - WRITE_ERROR(s.str()); -} - - -std::string -OptionsCont::convertChar(char abbr) const { - char buf[2]; - buf[0] = abbr; - buf[1] = 0; - std::string s(buf); - return s; -} - - -bool -OptionsCont::isBool(const std::string& name) const { - Option* o = getSecure(name); - return o->isBool(); -} - - -void -OptionsCont::resetWritable() { - for (ItemAddressContType::iterator i = myAddresses.begin(); i != myAddresses.end(); i++) { - (*i)->resetWritable(); - } -} - - -bool -OptionsCont::isWriteable(const std::string& name) { - Option* o = getSecure(name); - return o->isWriteable(); -} - - -void -OptionsCont::clear() { - ItemAddressContType::iterator i; - for (i = myAddresses.begin(); i != myAddresses.end(); i++) { - delete (*i); - } - myAddresses.clear(); - myValues.clear(); - mySubTopics.clear(); - mySubTopicEntries.clear(); -} - - -void -OptionsCont::addDescription(const std::string& name, - const std::string& subtopic, - const std::string& description) { - Option* o = getSecure(name); - assert(o != 0); - assert(find(mySubTopics.begin(), mySubTopics.end(), subtopic) != mySubTopics.end()); - o->setDescription(description); - mySubTopicEntries[subtopic].push_back(name); -} - - -void -OptionsCont::setApplicationName(const std::string& appName, - const std::string& fullName) { - myAppName = appName; - myFullName = fullName; -} - - -void -OptionsCont::setApplicationDescription(const std::string& appDesc) { - myAppDescription = appDesc; -} - - -void -OptionsCont::addCallExample(const std::string& example, const std::string& desc) { - myCallExamples.push_back(std::make_pair(example, desc)); -} - - -void -OptionsCont::setAdditionalHelpMessage(const std::string& add) { - myAdditionalMessage = add; -} - - -void -OptionsCont::addCopyrightNotice(const std::string& copyrightLine) { - myCopyrightNotices.push_back(copyrightLine); -} - - -void -OptionsCont::clearCopyrightNotices() { - myCopyrightNotices.clear(); -} - - -void -OptionsCont::addOptionSubTopic(const std::string& topic) { - mySubTopics.push_back(topic); - mySubTopicEntries[topic] = std::vector(); -} - - -void -OptionsCont::splitLines(std::ostream& os, std::string what, - int offset, int nextOffset) { - while (what.length() > 0) { - if ((int)what.length() > 79 - offset) { - std::string::size_type splitPos = what.rfind(';', 79 - offset); - if (splitPos == std::string::npos) { - splitPos = what.rfind(' ', 79 - offset); - } else { - splitPos++; - } - if (splitPos != std::string::npos) { - os << what.substr(0, splitPos) << std::endl; - what = what.substr(splitPos); - for (int r = 0; r < nextOffset + 1; ++r) { - os << ' '; - } - } else { - os << what; - what = ""; - } - offset = nextOffset; - } else { - os << what; - what = ""; - } - } - os << std::endl; -} - - -bool -OptionsCont::processMetaOptions(bool missingOptions) { - if (missingOptions) { - // no options are given - std::cout << myFullName << std::endl; - std::cout << " Build features: " << HAVE_ENABLED << std::endl; - for (std::vector::const_iterator it = - myCopyrightNotices.begin(); it != myCopyrightNotices.end(); ++it) { - std::cout << " " << *it << std::endl; - } - std::cout << " License EPL-2.0: Eclipse Public License Version 2 \n"; - std::cout << " Use --help to get the list of options." << std::endl; - return true; - } - - myWriteLicense = getBool("write-license"); - // check whether the help shall be printed - if (getBool("help")) { - std::cout << myFullName << std::endl; - for (std::vector::const_iterator it = - myCopyrightNotices.begin(); it != myCopyrightNotices.end(); ++it) { - std::cout << " " << *it << std::endl; - } - printHelp(std::cout); - return true; - } - // check whether the help shall be printed - if (getBool("version")) { - std::cout << myFullName << std::endl; - std::cout << " Build features: " << HAVE_ENABLED << std::endl; - for (std::vector::const_iterator it = - myCopyrightNotices.begin(); it != myCopyrightNotices.end(); ++it) { - std::cout << " " << *it << std::endl; - } - std::cout << "\n" << myFullName << " is part of SUMO.\n"; - std::cout << "This program and the accompanying materials\n"; - std::cout << "are made available under the terms of the Eclipse Public License v2.0\n"; - std::cout << "which accompanies this distribution, and is available at\n"; - std::cout << "http://www.eclipse.org/legal/epl-v20.html\n"; - std::cout << "SPDX-License-Identifier: EPL-2.0" << std::endl; - return true; - } - // check whether the settings shall be printed - if (exists("print-options") && getBool("print-options")) { - std::cout << (*this); - } - // check whether something has to be done with options - // whether the current options shall be saved - if (isSet("save-configuration", false)) { // sumo-gui does not register these - if (getString("save-configuration") == "-" || getString("save-configuration") == "stdout") { - writeConfiguration(std::cout, true, false, getBool("save-commented")); - return true; - } - std::ofstream out(getString("save-configuration").c_str()); - if (!out.good()) { - throw ProcessError("Could not save configuration to '" + getString("save-configuration") + "'"); - } else { - writeConfiguration(out, true, false, getBool("save-commented")); - if (getBool("verbose")) { - WRITE_MESSAGE("Written configuration to '" + getString("save-configuration") + "'"); - } - return true; - } - } - // whether the template shall be saved - if (isSet("save-template", false)) { // sumo-gui does not register these - if (getString("save-template") == "-" || getString("save-template") == "stdout") { - writeConfiguration(std::cout, false, true, getBool("save-commented")); - return true; - } - std::ofstream out(getString("save-template").c_str()); - if (!out.good()) { - throw ProcessError("Could not save template to '" + getString("save-template") + "'"); - } else { - writeConfiguration(out, false, true, getBool("save-commented")); - if (getBool("verbose")) { - WRITE_MESSAGE("Written template to '" + getString("save-template") + "'"); - } - return true; - } - } - if (isSet("save-schema", false)) { // sumo-gui does not register these - if (getString("save-schema") == "-" || getString("save-schema") == "stdout") { - writeSchema(std::cout); - return true; - } - std::ofstream out(getString("save-schema").c_str()); - if (!out.good()) { - throw ProcessError("Could not save schema to '" + getString("save-schema") + "'"); - } else { - writeSchema(out); - if (getBool("verbose")) { - WRITE_MESSAGE("Written schema to '" + getString("save-schema") + "'"); - } - return true; - } - } - return false; -} - -void -OptionsCont::printHelp(std::ostream& os) { - std::vector::const_iterator i, j; - // print application description - splitLines(os, myAppDescription, 0, 0); - os << std::endl; - - // check option sizes first - // we want to know how large the largest not-too-large-entry will be - int tooLarge = 40; - int maxSize = 0; - for (i = mySubTopics.begin(); i != mySubTopics.end(); ++i) { - const std::vector& entries = mySubTopicEntries[*i]; - for (j = entries.begin(); j != entries.end(); ++j) { - Option* o = getSecure(*j); - // name, two leading spaces and "--" - int csize = (int)j->length() + 2 + 4; - // abbreviation length ("-X, "->4chars) if any - const std::vector synonymes = getSynonymes(*j); - for (std::vector::const_iterator s = synonymes.begin(); s != synonymes.end(); ++s) { - if (s->length() == 1 && myDeprecatedSynonymes.count(*s) == 0) { - csize += 4; - break; - } - } - // the type name - if (!o->isBool()) { - csize += 1 + (int)o->getTypeName().length(); - } - // divider - csize += 2; - if (csize < tooLarge && maxSize < csize) { - maxSize = csize; - } - } - } - - const std::string helpTopic = StringUtils::to_lower_case(getSecure("help")->getValueString()); - if (helpTopic != "") { - bool foundTopic = false; - for (const std::string& topic : mySubTopics) { - if (StringUtils::to_lower_case(topic).find(helpTopic) != std::string::npos) { - foundTopic = true; - printHelpOnTopic(topic, tooLarge, maxSize, os); - } - } - if (!foundTopic) { - // print topic list - os << "Help Topics:" << std::endl; - for (std::string t : mySubTopics) { - os << " " << t << std::endl; - } - } - return; - } - // print usage BNF - os << "Usage: " << myAppName << " [OPTION]*" << std::endl; - // print additional text if any - if (myAdditionalMessage.length() > 0) { - os << myAdditionalMessage << std::endl << ' ' << std::endl; - } - // print the options - for (i = mySubTopics.begin(); i != mySubTopics.end(); ++i) { - printHelpOnTopic(*i, tooLarge, maxSize, os); - } - os << std::endl; - // print usage examples, calc size first - if (myCallExamples.size() != 0) { - os << "Examples:" << std::endl; - for (std::vector >::const_iterator e = myCallExamples.begin(); e != myCallExamples.end(); ++e) { - os << " " << myAppName << ' ' << e->first << std::endl; - os << " " << e->second << std::endl; - } - } - os << std::endl; - os << "Report bugs at ." << std::endl; - os << "Get in contact via ." << std::endl; -} - -void -OptionsCont::printHelpOnTopic(const std::string& topic, int tooLarge, int maxSize, std::ostream& os) { - os << topic << " Options:" << std::endl; - for (std::string entry : mySubTopicEntries[topic]) { - // start length computation - int csize = (int)entry.length() + 2; - Option* o = getSecure(entry); - os << " "; - // write abbreviation if given - std::vector synonymes = getSynonymes(entry); - for (std::vector::const_iterator s = synonymes.begin(); s != synonymes.end(); ++s) { - if (s->length() == 1 && myDeprecatedSynonymes.count(*s) == 0) { - os << '-' << *s << ", "; - csize += 4; - break; - } - } - // write leading '-'/"--" - os << "--"; - csize += 2; - // write the name - os << entry; - // write the type if not a bool option - if (!o->isBool()) { - os << ' ' << o->getTypeName(); - csize += 1 + (int)o->getTypeName().length(); - } - csize += 2; - // write the description formatting it - os << " "; - for (int r = maxSize; r > csize; --r) { - os << ' '; - } - int offset = csize > tooLarge ? csize : maxSize; - splitLines(os, o->getDescription(), offset, maxSize); - } - os << std::endl; -} - -void -OptionsCont::writeConfiguration(std::ostream& os, const bool filled, - const bool complete, const bool addComments, - const bool inComment) const { - if (!inComment) { - writeXMLHeader(os, false); - } - os << "" << std::endl << std::endl; - for (std::vector::const_iterator i = mySubTopics.begin(); i != mySubTopics.end(); ++i) { - std::string subtopic = *i; - if (subtopic == "Configuration" && !complete) { - continue; - } - std::replace(subtopic.begin(), subtopic.end(), ' ', '_'); - std::transform(subtopic.begin(), subtopic.end(), subtopic.begin(), tolower); - const std::vector& entries = mySubTopicEntries.find(*i)->second; - bool hadOne = false; - for (const std::string& name : entries) { - Option* o = getSecure(name); - bool write = complete || (filled && !o->isDefault()); - if (!write) { - continue; - } - if (name == "registry-viewport" && !complete) { - continue; - } - if (!hadOne) { - os << " <" << subtopic << ">" << std::endl; - } - // add the comment if wished - if (addComments) { - os << " " << std::endl; - } - // write the option and the value (if given) - os << " <" << name << " value=\""; - if (o->isSet() && (filled || o->isDefault())) { - os << StringUtils::escapeXML(o->getValueString(), inComment); - } - if (complete) { - std::vector synonymes = getSynonymes(name); - if (!synonymes.empty()) { - os << "\" synonymes=\""; - for (std::vector::const_iterator s = synonymes.begin(); s != synonymes.end(); ++s) { - if (s != synonymes.begin()) { - os << " "; - } - os << (*s); - } - } - os << "\" type=\"" << o->getTypeName(); - if (!addComments) { - os << "\" help=\"" << StringUtils::escapeXML(o->getDescription()); - } - } - os << "\"/>" << std::endl; - // append an endline if a comment was printed - if (addComments) { - os << std::endl; - } - hadOne = true; - } - if (hadOne) { - os << " " << std::endl << std::endl; - } - } - os << "" << std::endl; -} - - -void -OptionsCont::writeSchema(std::ostream& os) { - writeXMLHeader(os, false); - os << "\n\n"; - os << " \n"; - os << " \n\n"; - os << " \n"; - os << " \n"; - for (std::vector::const_iterator i = mySubTopics.begin(); i != mySubTopics.end(); ++i) { - std::string subtopic = *i; - if (subtopic == "Configuration") { - continue; - } - std::replace(subtopic.begin(), subtopic.end(), ' ', '_'); - std::transform(subtopic.begin(), subtopic.end(), subtopic.begin(), tolower); - os << " \n"; - } - os << " \n"; - os << " \n\n"; - for (std::vector::const_iterator i = mySubTopics.begin(); i != mySubTopics.end(); ++i) { - std::string subtopic = *i; - if (subtopic == "Configuration") { - continue; - } - std::replace(subtopic.begin(), subtopic.end(), ' ', '_'); - std::transform(subtopic.begin(), subtopic.end(), subtopic.begin(), tolower); - os << " \n"; - os << " \n"; - const std::vector& entries = mySubTopicEntries[*i]; - for (std::vector::const_iterator j = entries.begin(); j != entries.end(); ++j) { - Option* o = getSecure(*j); - std::string type = o->getTypeName(); - std::transform(type.begin(), type.end(), type.begin(), tolower); - if (type == "int[]") { - type = "intArray"; - } - if (type == "str[]") { - type = "strArray"; - } - os << " \n"; - } - os << " \n"; - os << " \n\n"; - } - os << "\n"; -} - - -void -OptionsCont::writeXMLHeader(std::ostream& os, const bool includeConfig) const { - time_t rawtime; - char buffer [80]; - - os << "\n\n"; - time(&rawtime); - strftime(buffer, 80, "\n\n"; -} - - -bool -OptionsCont::isInStringVector(const std::string& optionName, - const std::string& itemName) const { - if (isSet(optionName)) { - std::vector values = getStringVector(optionName); - return std::find(values.begin(), values.end(), itemName) != values.end(); - } - return false; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/utils/options/OptionsCont.h b/Util/OSM2ODR/src/utils/options/OptionsCont.h deleted file mode 100644 index 34974f292..000000000 --- a/Util/OSM2ODR/src/utils/options/OptionsCont.h +++ /dev/null @@ -1,767 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file OptionsCont.h -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @author Walter Bamberger -/// @date Mon, 17 Dec 2001 -/// -// A storage for options (typed value containers) -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include -#include -#include "Option.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class OptionsCont - * @brief A storage for options typed value containers) - * - * This container stores options (typed value containers) by their names. - * In the case of command line tools, this container is the main interface - * between a user's definitions about what to do (command line options, - * configuration files) and the application. - * - * At the begin, the application should initialise the container. Because - * the OptionsCont is also responsible for printing the help screen, one - * should name and describe the application, first. This means that the - * first usage of this container should look similar to this: - * @code - * OptionsCont &oc = OptionsCont::getOptions(); - * // give some application descriptions - * oc.setApplicationDescription(); - * oc.setApplicationName(, "SUMO Version " + (string)VERSION_STRING); - * @endcode - * @see setApplicationDescription - * @see setApplicationName - * - * Then, you may also add some example calls using addCallExample. - * @see addCallExample - * - * In the next step, option subtopics are registered. This is needed - * for the help screen and for writing the templates/saving configurations. - * A subtopic is added using addOptionSubTopic(). - * @see addOptionSubTopic - * - * After this, you may add options to the container. This is done using - * doRegister. This method requires a long name for the option and - * the value container. The value container must be an instance of - * one of the classes derived from "Option". Do not use Option itself! - * This is a base class which is meant to supply a default behaviour, - * but this default behaviour throws exceptions only! - * @see Option - * @see doRegister - * @see addSynonyme - * - * Once stored inside this container, options will not be visible to the - * world and are deleted by the container. Only values and stati of the - * options may be returned. While accessing the options, the programmer - * must assure that he asks for the right value (only Option_Bool is able - * to return a boolean value, other option types will throw exceptions). - * Further, options added to the container must not be deleted outside - * this container (the container becomes the owner). - * - * For being printed in the help screen, a description together with the - * subtopic the option belongs to must be given to OptionsCont. This is - * done using addDescription(, , ). - * @see addDescription - */ -class OptionsCont { -public: - /** @brief Retrieves the options */ - static OptionsCont& getOptions(); - - - /** @brief Constructor */ - OptionsCont(); - - - /** @brief Destructor */ - ~OptionsCont(); - - - - /// @name Methods setting and getting information about the appplication and currently set options - /// @{ - - /** @brief Sets the application name - * - * @param[in] name The name of the excutable - * @param[in] v The name of the executable with version information - */ - void setApplicationName(const std::string& appName, const std::string& fullName); - - - /** @brief Sets the application description - * - * @param[in] appDesc A description of the application - */ - void setApplicationDescription(const std::string& appDesc); - - - /** @brief Add a call example - * - * @param[in] example A call example (without the app name) - * @param[in] desc A verbose description - */ - void addCallExample(const std::string& example, const std::string& desc); - - - /** @brief Sets an additional message to be printed at the begin of the help screen - * - * @param[in] example Some additional information about how to use the application - */ - void setAdditionalHelpMessage(const std::string& add); - - - /** @brief Adds a copyright notice to the help output - * - * @param[in] copyrightLine The line to put out as a copyright notice - */ - void addCopyrightNotice(const std::string& copyrightLine); - - - /** @brief Removes all copyright information - */ - void clearCopyrightNotices(); - - - /** @brief Adds an option subtopic - * - * Sub-topics are used to join several options into one thematic field. - * They are used on writing the help screen and the configuration. They have - * no further meaning besides making the outputs better readable. - * - * @param[in] topic The options sub topic - */ - void addOptionSubTopic(const std::string& topic); - - - /** @brief Prints the help - * - * @param[in] os The stream to write the help into - */ - void printHelp(std::ostream& os); - - /** @brief Prints help on the given topic - * - * @param[in] topic The topic name - * @param[in] os The stream to write the help into - */ - void printHelpOnTopic(const std::string& topic, int tooLarge, int maxSize, std::ostream& os); - - /** @brief Writes the configuration - * - * The configuration is written as XML into the given stream, allowing - * to reload it on a next run. - * - * @param[in] os The stream to write the configuration into - * @param[in] filled Whether only set (and not default) options shall be written - * @param[in] complete Whether all options shall be written - * @param[in] addComments Whether comments (option descriptions) shall be written - * @param[in] inComment Whether -- in input shall be converted to -- (semantically equivalent but allowed in XML comments) - */ - void writeConfiguration(std::ostream& os, const bool filled, - const bool complete, const bool addComments, - const bool inComment = false) const; - - - /** @brief Writes the xml schema for the configuration - * - * The schema for the configuration is written as XML into the given stream, - * allowing to validate the configuration against. - * - * @param[in] os The stream to write the schema into - */ - void writeSchema(std::ostream& os); - - - /** @brief Writes a standard XML header, including the configuration - * - * The header consists of the xml-declaration with encoding as defined - * by SUMOSAXAttributes::ENCODING, followed by a note which contains - * the current date and time and the application configuration (set values). - * - * @param[in] os The stream to write the header into - */ - void writeXMLHeader(std::ostream& os, const bool includeConfig = true) const; - /// @} - - - - - /// @name Methods for registering options - /// @{ - - /** @brief Adds an option under the given name - * @param[in] name The (long) name of the option - * @param[in] v The option (typed value storage) - * @exception InvalidArgument If the name is already used - */ - void doRegister(const std::string& name, Option* v); - - - /** @brief Adds an option under the given name and the given abbreviation - * - * Adds the option under both names using void doRegister(const std::string &name, Option *v); - * - * @param[in] name The (long) name of the option - * @param[in] abbr The (short) name of the option - * @param[in] v The option (typed value storage) - * @exception InvalidArgument If one of the names is already used - */ - void doRegister(const std::string& name, char abbr, Option* v); - - - /** @brief Adds a synonyme for an options name (any order) - * - * Tries to find one of the synonymes. If both are known and the option differs - * for both, an InvalidArgument exception is thrown. If none is known, also. - * - * If one of the synonymes is known and the other not, the option from the known - * one is made accessible by the other. - * - * In the case both synonymes are known and have the same option assigned, nothing - * is done. - * - * @param[in] name1 The first synonyme - * @param[in] name2 The second synonyme - * @param[in] isDeprecated whether the synonyme is considered deprecated - * @exception InvalidArgument If none of the synonymes or both synonymes with different options were registered before - */ - void addSynonyme(const std::string& name1, const std::string& name2, bool isDeprecated = false); - - - /** @brief Adds an XML root element to handle by default. The special root "" denotes the default handler. - * - * @param[in] name The option name - * @param[in] xmlRoot The name of the xml root element to handle - */ - void addXMLDefault(const std::string& name, const std::string& xmlRoot = ""); - - - /** @brief Adds a description for an option - * - * Tries to retrieve the named option and to set the given description. Adds - * the name to the list of option names to be located in the named subtopic. - * - * Throws an InvalidArgument if the option is not known or already has - * a description set. - * - * @param[in] name The option's name - * @param[in] subtopic The subtopic to locate the description within - * @param[in] description The description - * @exception InvalidArgument If none of the synonymes or both synonymes with different options were registered before - */ - void addDescription(const std::string& name, const std::string& subtopic, - const std::string& description); - /// @} - - - - - /// @name Methods for retrieving information about options - /// @{ - - /** @brief Returns the information whether the named option is known - * @return true if an option has been added before under the given name, false otherwise - */ - bool exists(const std::string& name) const; - - - /** @brief Returns the information whether the named option is set - * - * The named option is tried to be retrieved from the container. If - * it does not exist, an InvalidArgument is thrown. If it could be - * retrieved, the information whether the option has a value stored - * is returned. - * - * An option "is set" if a default value was supplied or a value has been - * set from the command line / the configuration file. - * - * @param[in] name The name of the option to check - * @param[in] failOnNonExistant Whether asking for an unregistered option should trigger an exception - * @return true if the option has a valid value, false otherwise - * @exception InvalidArgument If the named option is not known - */ - bool isSet(const std::string& name, bool failOnNonExistant = true) const; - - - /** @brief Marks the option as unset - * @param[in] name The name of the option to check - * @param[in] failOnNonExistant Whether asking for an unregistered option should trigger an exception - */ - void unSet(const std::string& name, bool failOnNonExistant = true) const; - - - /** @brief Returns the information whether the named option has still the default value - * - * The named option is tried to be retrieved from the container. If - * it does not exist, an InvalidArgument is thrown. If it could be - * retrieved, the information whether the option still has the default - * value is returned. - * - * An option "is default" if no value has been set from the command line - * / the configuration file. - * - * @return true if the option still has the default value - * @exception InvalidArgument If the named option is not known - */ - bool isDefault(const std::string& name) const; - - - /** @brief Returns the information whether the option is a boolean option - * - * The option is retrieved from the container, first, what may cause an InvalidArgument - * exception if it is not known. Otherwise, this option's isBool-method is called. - * - * @param[in] name The name of the option to check - * @return Whether the existing named option is a bool option - * @exception InvalidArgument If the option does not exist - */ - bool isBool(const std::string& name) const; - - - /** @brief Checks whether the named option is usable as a file list (with at least a single file) - * - * The method returns true, if the named option is set with entries containing - * names of accessable files. - * - * Throw an InvalidArgument exception if the option is not known. If the option - * is not set, false is returned. Also, if the list is empty (conatins delimiters only) - * or if one of the named files (obtained using getStringVector) does not exist, - * false is returned. Additionally, an error is sent to MsgHandler in both cases. - * - * In the case two delimiters were placed in the option value directly after - * each other, a warning is generated. - * - * @param[in] name The name of the option to check - * @return Whether the option contains names of files which can be accessed (for reading) - * @exception InvalidArgument If the option does not exist or is not a string-option - */ - bool isUsableFileList(const std::string& name) const; - - - /** @brief Checks whether an option is set, which has options with a prefix depending on it. - * - * The method returns true, if the named option is set or no option dependoing on it is set. - * Throws an InvalidArgument exception if the option is not known. - * - * @param[in] name The name of the option to check - * @param[in] prefix The prefix of depending options - * @return Whether the dependencies are fulfilled - * @exception InvalidArgument If the option does not exist - */ - bool checkDependingSuboptions(const std::string& name, const std::string& prefix) const; - - - /** @brief Modifies file name options according to the configuration path - * - * If the configuration path given is a relative one all filenames inside - * are adapted such that they refer to the correct location. - * - * @param[in] configuration The path to the configuration file - */ - void relocateFiles(const std::string& configuration) const; - - - /** @brief Returns the synonymes of an option name - * - * The named option is extracted, first. An InvalidArgument is thrown if it - * does not exist. Otherwise, other names for the named option are searched - * and returned (the original name is not in the list). - * @param[in] name The name of the option to return synonymes of - * @return List of existing synonymes - * @exception InvalidArgument If the named option does not exist - **/ - std::vector getSynonymes(const std::string& name) const; - - /** @brief Returns the option description - * - * @param[in] name The name of the option to return the description of - * @return description - * @exception InvalidArgument If the named option does not exist - **/ - const std::string& getDescription(const std::string& name) const; - - - /** @brief Returns the information whether the named option may be set - * - * An option is writable after initialisation, but as soon as it gets set, - * it is no longer writeable. This method returns whether the named option - * is writeable. If the named option is not known, an InvalidArgument - * is thrown. - * - * @param[in] name The name of the option to check - * @return Whether the value can be set - * @exception InvalidArgument If the option does not exist - */ - bool isWriteable(const std::string& name); - /// @} - - - - - /// @name Methods for retrieving values from options - /// @{ - /** @brief Returns the string-value of the named option (all options) - * - * This method returns the string-value of an existing option. - * If the named option does not exist, an - * InvalidArgument is thrown. - * - * @param[in] name The name of the option to return the string-value of - * @return The string-value of the named, existing option - * @exception InvalidArgument If the option does not exist - */ - std::string getValueString(const std::string& name) const; - - /** @brief Returns the string-value of the named option (only for Option_String) - * - * This method returns the string-value of an existing string-option. - * If the named option does not exist or is not a string-option, an - * InvalidArgument is thrown. - * - * @param[in] name The name of the option to return the string-value of - * @return The string-value of the named, existing string-option - * @exception InvalidArgument If the option does not exist or is not a string-option - */ - std::string getString(const std::string& name) const; - - - /** @brief Returns the double-value of the named option (only for Option_Float) - * - * This method returns the double-value of an existing double-option. - * If the named option does not exist or is not a double-option, an - * InvalidArgument is thrown. - * - * @param[in] name The name of the option to return the double-value of - * @return The double-value of the named, existing double-option - * @exception InvalidArgument If the option does not exist or is not a double-option - */ - double getFloat(const std::string& name) const; - - - /** @brief Returns the int-value of the named option (only for Option_Integer) - * - * This method returns the int-value of an existing int-option. - * If the named option does not exist or is not a int-option, an - * InvalidArgument is thrown. - * - * @param[in] name The name of the option to return the int-value of - * @return The int-value of the named, existing int-option - * @exception InvalidArgument If the option does not exist or is not a int-option - */ - int getInt(const std::string& name) const; - - - /** @brief Returns the boolean-value of the named option (only for Option_Bool) - * - * This method returns the boolean-value of an existing boolean-option. - * If the named option does not exist or is not a boolean-option, an - * InvalidArgument is thrown. - * - * @param[in] name The name of the option to return the boolean-value of - * @return The boolean-value of the named, existing boolean-option - * @exception InvalidArgument If the option does not exist or is not a boolean-option - */ - bool getBool(const std::string& name) const; - - - /** @brief Returns the list of integer-value of the named option (only for Option_IntVector) - * - * This method returns the int-vector-value of an existing int-vector-option. - * If the named option does not exist or is not a int-vector-option, an - * InvalidArgument is thrown. - * - * @param[in] name The name of the option to return the int-vector-value of - * @return The int-vector-value of the named, existing int-vector-option - * @exception InvalidArgument If the option does not exist or is not a int-vector-option - */ - const IntVector& getIntVector(const std::string& name) const; - - /** @brief Returns the list of string-value of the named option (only for Option_StringVector) - * - * This method returns the string-vector-value of an existing string-vector-option. - * If the named option does not exist or is not a string-vector-option, an - * InvalidArgument is thrown. - * - * If the legacy-divider ';' is found within the string, a warning is generated. - * The retrieved string is only splitted at ','. - * - * @param[in] name The name of the option to return the string-vector-value of - * @return The string-vector-value of the named, existing string-vector-option - * @exception InvalidArgument If the option does not exist or is not a string-vector-option - * @todo Is it possible to retrieve a const-reference of the string? - * @see getString() - */ - const StringVector& getStringVector(const std::string& name) const; - - /** @brief Returns the named option is a list of string values containing the specified item - * - * If the named option is not set, false is returned. Otherwise, the string-vector - * of this option is retrieved using getStringVector what may throw an - * InvalidArgument exception if the named option is not a string option or not - * existing at all. - * - * The given itemName is searched in the obtained string-vector and the - * method returns whether it is stored in the list or not. - * - * @param[in] optionName The name of the option to evaluate entries of - * @param[in] itemName The item to be searched for in the entries of the named option - * @return Whether the named item is set in the named string-option - * @exception InvalidArgument If the option does not exist or is not a string-option - * @see getStringVector() - * @todo Try to optimize - at each call, the vector is rebuilt - */ - bool isInStringVector(const std::string& optionName, - const std::string& itemName) const; - /// @} - - - - - /// @name Methods for setting values into options - /// @{ - - /** @brief Sets the given value for the named option - * - * The option is retrieved from the container, first, what yields in a InvalidArgument - * exception for not known options. - * - * If the option is not writable (was set before), an error is generated using - * reportDoubleSetting, and false is returned. Otherwise, the option is - * told to set the given value using Option::set. Possible problems herein - * are caught and reported to the error-handler, yielding in returning false. - * - * If the new value could be set, true is returned. - * - * @param[in] name The name of the option to set - * @param[in] value The value to set - * @return Whether the value could be set - * @exception InvalidArgument If the option does not exist - * @see reportDoubleSetting - * @see Option::set(const std::string &) - */ - bool set(const std::string& name, const std::string& value); - - /** @brief Sets the given value for the named option as new default value - * - * The option is retrieved from the container, first, what yields in a InvalidArgument - * exception for not known options. - * - * If the option is not writable (was set before), an error is generated using - * reportDoubleSetting, and false is returned. Otherwise, the option is - * told to set the given value using Option::set. Possible problems herein - * are caught and reported to the error-handler, yielding in returning false. - * - * If the new value could be set, true is returned. - * - * @param[in] name The name of the option to set - * @param[in] value The value to set - * @return Whether the value could be set - * @exception InvalidArgument If the option does not exist - * @see reportDoubleSetting - * @see Option::set(const std::string &) - */ - bool setDefault(const std::string& name, const std::string& value); - - /** @brief Sets the given value for the option which can handle the given XML root - * - * The option is retrieved from the container, which yields in an InvalidArgument - * exception if no option is registered for the XML root. Then it uses the - * standard set method. - * - * @param[in] root The name of the XML root element to look for - * @param[in] value The value to set - * @return Whether the value could be set - * @exception InvalidArgument If the root element was not registered or the value could not be set - * @see OptionsCont::set(const std::string &, const std::string &) - */ - bool setByRootElement(const std::string& name, const std::string& value); - /// @} - - - /** @brief Resets all options to be writeable - * - * An option is writable after initialisation, but as soon as it gets set, - * it is no longer writeable. This method resets the writable-flag of all - * known options. - */ - void resetWritable(); - - /** @brief Output operator - * - * Generates the output used when current option values shall be printed. - * - * @param[in] os The stream to write into - * @param[in] oc The options to print - * @return The stream to write into - */ - friend std::ostream& operator<<(std::ostream& os, const OptionsCont& oc); - - - /** @brief Removes all information from the container */ - void clear(); - - - /** @brief Checks for help and configuration output, returns whether we should exit - * - * Returns false if no error was detected and the application may be executed - * (at least from this point of view). If missingOptions is true, the user is - * informed that they should be supplied (returns true). Otherwise it is checked - * whether help shall be printed what is done if so, returning true. Also, it - * is checked whether the set options shall be printed and the configuration - * template or the current configuration shall be written. - * - * This method throws a ProcessError if the configuration should be saved, - * but the file is not accessable. An error message is supplied. - * - * @param[in] missingOptions Whether no options have been given - * @return Whether the application shall stop - * @exception ProcessError If the configuration file could not be saved - */ - bool processMetaOptions(bool missingOptions); - - - /// @brief return the list of subtopics - const std::vector& getSubTopics() const { - return mySubTopics; - } - - - /// @brief return the list of entries for the given subtopic - std::vector getSubTopicsEntries(const std::string& subtopic) const { - if (mySubTopicEntries.count(subtopic) > 0) { - return mySubTopicEntries.find(subtopic)->second; - } else { - return std::vector(); - } - } - - - /// @brief return the type name for the given option - std::string getTypeName(const std::string name) { - return getSecure(name)->getTypeName(); - } - - - inline const std::string& getFullName() const { - return myFullName; - } - - std::string input_osm_file; - std::string output_xodr_file; - -private: - /** @brief Returns the named option - * - * If the named option does not exist, an InvalidArgument is thrown. - * - * @param[in] name The name of the option to return - * @return The named option - */ - Option* getSecure(const std::string& name) const; - - - /** @brief Reports an error that the option has already been set - * - * Using the given option name, an error string is generated and reported to - * MsgHandler-error instance. - * - * @param[in] name The name of the option that was already set - */ - void reportDoubleSetting(const std::string& arg) const; - - - /** @brief Converts an abbreviation into a name - * - * Build and returns the string which consists of the given character only. - * - * @param[in] abbr The abbreviation to convert into a string - * @return The abbreviation converted into a string - */ - std::string convertChar(char abbr) const; - - - /** @brief Writes the given string 'formatted' - * - * The given string is split so that no word-wrapping occurs at line ends. - * The text is wrapped at ';' or ' '. - * - * @param[in] os The stream to write the text into - * @param[in] what The text to write - * @param[in] offset ? - * @param[in] nextOffset ? - * @todo Describe parameter - */ - void splitLines(std::ostream& os, std::string what, - int offset, int nextOffset); - - -private: - /// The static options container used - static OptionsCont myOptions; - - /** definition of the type that stores the addresses of used options */ - typedef std::vector ItemAddressContType; - - /** definition of the type that realises the access to options */ - typedef std::map KnownContType; - - /** storage for option-addresses */ - ItemAddressContType myAddresses; - - /** access map of options */ - KnownContType myValues; - - /// some information on the application - std::string myAppName, myFullName, myAppDescription, myAdditionalMessage; - - /// list of call examples - std::vector< std::pair > myCallExamples; - - /// lists of option subtopics and copyright notices - std::vector mySubTopics, myCopyrightNotices; - - /// A map from subtopic to option - std::map > mySubTopicEntries; - - /// A map from XML root element to option - std::map myXMLDefaults; - - /// A map from deprecated options to a bool indicating whether we warned about deprecation - mutable std::map myDeprecatedSynonymes; - - /// Information whether we should always include license information in file headers - bool myWriteLicense; - - -private: - /** invalid copy constructor */ - OptionsCont(const OptionsCont& s); - - /** invalid assignment operator */ - OptionsCont& operator=(const OptionsCont& s); - -}; diff --git a/Util/OSM2ODR/src/utils/options/OptionsIO.cpp b/Util/OSM2ODR/src/utils/options/OptionsIO.cpp deleted file mode 100644 index d6a0c5658..000000000 --- a/Util/OSM2ODR/src/utils/options/OptionsIO.cpp +++ /dev/null @@ -1,171 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file OptionsIO.cpp -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Mon, 17 Dec 2001 -/// -// Helper for parsing command line arguments and reading configuration files -/****************************************************************************/ -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "OptionsIO.h" -#include "OptionsCont.h" -#include "OptionsLoader.h" -#include "OptionsParser.h" -#include -#include -#include -#ifdef HAVE_ZLIB -#include -#endif -#include - - -// =========================================================================== -// static member definitions -// =========================================================================== -int OptionsIO::myArgC = 0; -char** OptionsIO::myArgV; - - -// =========================================================================== -// method definitions -// =========================================================================== -void -OptionsIO::setArgs(int argc, char** argv) { - myArgC = argc; - myArgV = argv; -} - - -void -OptionsIO::setArgs(const std::vector& args) { - char* const app = myArgC > 0 ? myArgV[0] : nullptr; - myArgC = (int)args.size() + 1; - char** argv = new char* [myArgC]; - argv[0] = app; - for (int i = 1; i < myArgC; i++) { - argv[i] = new char[args[i - 1].size() + 1]; - std::strcpy(argv[i], args[i - 1].c_str()); - } - myArgV = argv; -} - - -void -OptionsIO::getOptions(const bool commandLineOnly) { - if (myArgC == 2 && myArgV[1][0] != '-') { - // special case only one parameter, check who can handle it - if (OptionsCont::getOptions().setByRootElement(getRoot(myArgV[1]), myArgV[1])) { - if (!commandLineOnly) { - loadConfiguration(); - } - return; - } - } - // preparse the options - // (maybe another configuration file was chosen) - if (!OptionsParser::parse(myArgC, myArgV)) { - throw ProcessError("Could not parse commandline options."); - } - if (!commandLineOnly || OptionsCont::getOptions().isSet("save-configuration", false)) { - // read the configuration when everything's ok - loadConfiguration(); - } -} - - -void -OptionsIO::loadConfiguration() { - OptionsCont& oc = OptionsCont::getOptions(); - if (!oc.exists("configuration-file") || !oc.isSet("configuration-file")) { - return; - } - const std::string path = oc.getString("configuration-file"); - if (!FileHelpers::isReadable(path)) { - throw ProcessError("Could not access configuration '" + oc.getString("configuration-file") + "'."); - } - PROGRESS_BEGIN_MESSAGE("Loading configuration"); - oc.resetWritable(); - // build parser - XERCES_CPP_NAMESPACE::SAXParser parser; - parser.setValidationScheme(XERCES_CPP_NAMESPACE::SAXParser::Val_Auto); - parser.setDoNamespaces(false); - parser.setDoSchema(false); - // start the parsing - OptionsLoader handler; - try { - parser.setDocumentHandler(&handler); - parser.setErrorHandler(&handler); - parser.parse(path.c_str()); - if (handler.errorOccurred()) { - throw ProcessError("Could not load configuration '" + path + "'."); - } - } catch (const XERCES_CPP_NAMESPACE::XMLException& e) { - throw ProcessError("Could not load configuration '" + path + "':\n " + StringUtils::transcode(e.getMessage())); - } - oc.relocateFiles(path); - if (myArgC > 2) { - // reparse the options (overwrite the settings from the configuration file) - oc.resetWritable(); - OptionsParser::parse(myArgC, myArgV); - } - PROGRESS_DONE_MESSAGE(); -} - - -std::string -OptionsIO::getRoot(const std::string& filename) { - // build parser - XERCES_CPP_NAMESPACE::SAXParser parser; - // start the parsing - OptionsLoader handler; - try { - parser.setDocumentHandler(&handler); - parser.setErrorHandler(&handler); - XERCES_CPP_NAMESPACE::XMLPScanToken token; -#ifdef HAVE_ZLIB - zstr::ifstream istream(filename.c_str(), std::fstream::in | std::fstream::binary); - IStreamInputSource inputStream(istream); - const bool result = parser.parseFirst(inputStream, token); -#else - const bool result = parser.parseFirst(filename.c_str(), token); -#endif - if (!result) { - throw ProcessError("Can not read XML-file '" + filename + "'."); - } - while (parser.parseNext(token) && handler.getItem() == ""); - if (handler.errorOccurred()) { - throw ProcessError("Could not load '" + filename + "'."); - } - } catch (const XERCES_CPP_NAMESPACE::XMLException& e) { - throw ProcessError("Could not load '" + filename + "':\n " + StringUtils::transcode(e.getMessage())); - } - return handler.getItem(); -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/utils/options/OptionsIO.h b/Util/OSM2ODR/src/utils/options/OptionsIO.h deleted file mode 100644 index d6054cec8..000000000 --- a/Util/OSM2ODR/src/utils/options/OptionsIO.h +++ /dev/null @@ -1,104 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file OptionsIO.h -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Mon, 17 Dec 2001 -/// -// Helper for parsing command line arguments and reading configuration files -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include - - -// =========================================================================== -// class declarations -// =========================================================================== -class OptionsCont; - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class OptionsIO - * - * Helping methods for parsing of command line arguments and reading a - * configuration file. - * Any errors are reported by throwing a ProcessError exception which - * contains a description about the failure. - */ -class OptionsIO { -public: - /** @brief Stores the command line arguments for later parsing - * - * @param[in] argc number of arguments given at the command line - * @param[in] argv arguments given at the command line - */ - static void setArgs(int argc, char** argv); - - /** @brief Stores faked command line arguments for later parsing - * - * @param[in] args arguments given as substitute for the command line - */ - static void setArgs(const std::vector& args); - - /** @brief Return the number of command line arguments - */ - static int getArgC() { - return myArgC; - } - - - /** @brief Parses the command line arguments and loads the configuration - * - * Command line arguments are parsed, first, throwing a ProcessError - * if something fails. Then options are reset to being writeable and the - * configuration is loaded using "loadConfiguration". After this, - * the options are reset again and the command line arguments are - * reparsed. - * - * This workflow allows to read the name of a configuration file from - * command line arguments, first, then to load values from this configuration - * file and reset them by other values from the command line. - */ - static void getOptions(const bool commandLineOnly = false); - - - /** @brief Loads and parses the configuration - * - * The name of the configuration file is extracted from the global - * OptionsCont ("configuration-file" is used as the name of the option to get - * the name of the configuration). - */ - static void loadConfiguration(); - - - /** @brief Retrieves the XML root element of a supposed configuration or net - * - * @param[in] filename the XML file to parse - * @return the root element if any - */ - static std::string getRoot(const std::string& filename); - - -private: - static int myArgC; - static char** myArgV; - -}; diff --git a/Util/OSM2ODR/src/utils/options/OptionsLoader.cpp b/Util/OSM2ODR/src/utils/options/OptionsLoader.cpp deleted file mode 100644 index 9064c3cea..000000000 --- a/Util/OSM2ODR/src/utils/options/OptionsLoader.cpp +++ /dev/null @@ -1,157 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file OptionsLoader.cpp -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date Mon, 17 Dec 2001 -/// -// A SAX-Handler for loading options -/****************************************************************************/ -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "OptionsLoader.h" -#include "OptionsCont.h" -#include -#include -#include -#include - - -// =========================================================================== -// method definitions -// =========================================================================== -OptionsLoader::OptionsLoader(const bool rootOnly) - : myRootOnly(rootOnly), myError(false), myOptions(OptionsCont::getOptions()), myItem() {} - - -OptionsLoader::~OptionsLoader() {} - - -void OptionsLoader::startElement(const XMLCh* const name, - XERCES_CPP_NAMESPACE::AttributeList& attributes) { - myItem = StringUtils::transcode(name); - if (!myRootOnly) { - for (int i = 0; i < (int)attributes.getLength(); i++) { - std::string key = StringUtils::transcode(attributes.getName(i)); - std::string value = StringUtils::transcode(attributes.getValue(i)); - if (key == "value" || key == "v") { - // Substitute environment variables defined by ${NAME} with their value - std::string cleanValue = StringUtils::substituteEnvironment(value); - setValue(myItem, cleanValue); - } - // could give a hint here about unsupported attributes in configuration files - } - myValue = ""; - } -} - - -void OptionsLoader::setValue(const std::string& key, - std::string& value) { - if (value.length() > 0) { - try { - if (!setSecure(key, value)) { - WRITE_ERROR("Could not set option '" + key + "' (probably defined twice)."); - myError = true; - } - } catch (ProcessError& e) { - WRITE_ERROR(e.what()); - myError = true; - } - } -} - - -void OptionsLoader::characters(const XMLCh* const chars, - const XERCES3_SIZE_t length) { - myValue = myValue + StringUtils::transcode(chars, (int) length); -} - - -bool -OptionsLoader::setSecure(const std::string& name, - const std::string& value) const { - if (myOptions.isWriteable(name)) { - myOptions.set(name, value); - return true; - } - return false; -} - - -void -OptionsLoader::endElement(const XMLCh* const /*name*/) { - if (myItem.length() == 0 || myValue.length() == 0) { - return; - } - if (myValue.find_first_not_of("\n\t \a") == std::string::npos) { - return; - } - setValue(myItem, myValue); - myItem = ""; - myValue = ""; -} - - -void -OptionsLoader::warning(const XERCES_CPP_NAMESPACE::SAXParseException& exception) { - WRITE_WARNING(StringUtils::transcode(exception.getMessage())); - WRITE_WARNING(" (At line/column " \ - + toString(exception.getLineNumber() + 1) + '/' \ - + toString(exception.getColumnNumber()) + ")."); - myError = true; -} - - -void -OptionsLoader::error(const XERCES_CPP_NAMESPACE::SAXParseException& exception) { - WRITE_ERROR( - StringUtils::transcode(exception.getMessage())); - WRITE_ERROR( - " (At line/column " - + toString(exception.getLineNumber() + 1) + '/' - + toString(exception.getColumnNumber()) + ")."); - myError = true; -} - - -void -OptionsLoader::fatalError(const XERCES_CPP_NAMESPACE::SAXParseException& exception) { - WRITE_ERROR( - StringUtils::transcode(exception.getMessage())); - WRITE_ERROR( - " (At line/column " - + toString(exception.getLineNumber() + 1) + '/' - + toString(exception.getColumnNumber()) + ")."); - myError = true; -} - - -bool -OptionsLoader::errorOccurred() const { - return myError; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/utils/options/OptionsLoader.h b/Util/OSM2ODR/src/utils/options/OptionsLoader.h deleted file mode 100644 index ca5d48662..000000000 --- a/Util/OSM2ODR/src/utils/options/OptionsLoader.h +++ /dev/null @@ -1,172 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file OptionsLoader.h -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Mon, 17 Dec 2001 -/// -// A SAX-Handler for loading options -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include -#include -#include - - -// =========================================================================== -// class declarations -// =========================================================================== -class OptionsCont; - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class OptionsLoader - * @brief A SAX-Handler for loading options - */ -class OptionsLoader : public XERCES_CPP_NAMESPACE::HandlerBase { -public: - /** @brief Constructor - */ - OptionsLoader(const bool routeOnly = false); - - - /** destructor */ - ~OptionsLoader(); - - - - - /// @name Handlers for the SAX DocumentHandler interface - /// @{ - - /** @brief Called on the occurence of the beginning of a tag - * - * Sets the name of the last item - */ - virtual void startElement(const XMLCh* const name, - XERCES_CPP_NAMESPACE::AttributeList& attributes); - - - /** @brief Called on the occurence of character data - * - * If this occurs inside a single tag it sets the option named - * by the tag to the value given by the character data. - * This is considered deprecated in favor of attributes. - * @todo Describe better - */ - void characters(const XMLCh* const chars, const XERCES3_SIZE_t length); - - - /** @brief Called on the end of an element - * - * Resets the element name - */ - void endElement(const XMLCh* const name); - /// @} - - - - - /// @name Handlers for the SAX ErrorHandler interface - /// @{ - - /** @brief Called on an XML-warning - * - * The warning is reported to the the warning-instance of MsgHandler - */ - void warning(const XERCES_CPP_NAMESPACE::SAXParseException& exception); - - - /** @brief Called on an XML-error - * - * The warning is reported to the the error-instance of MsgHandler - */ - void error(const XERCES_CPP_NAMESPACE::SAXParseException& exception); - - - /** @brief Called on an XML-fatal error - * - * The warning is reported to the the error-instance of MsgHandler - */ - void fatalError(const XERCES_CPP_NAMESPACE::SAXParseException& exception); - /// @} - - - - /** @brief Returns the information whether an error occurred */ - bool errorOccurred() const; - - /** @brief Returns the last item read */ - const std::string& getItem() const { - return myItem; - } - - -private: - /** @brief Tries to set the named option to the given value - * - * Also evaluates whether it is a boolean or a filename option and - * does the relevant checks / modifications. - * - * @param[in] key The name of the option to set - * @param[in] value The new value for the option - */ - void setValue(const std::string& key, std::string& value); - - - /** @brief Tries to set the named option to the given value - * - * Checks the item whether it was default before setting it. - * Returns the information whether the item was set before (was not a default value) - * - * @param[in] name The name of the option to set - * @param[in] value The new value for the option - * @return Whether the option could be set - */ - bool setSecure(const std::string& name, const std::string& value) const; - - -private: - /** invalid copy constructor */ - OptionsLoader(const OptionsLoader& s); - - - /** invalid assignment operator */ - OptionsLoader& operator=(const OptionsLoader& s); - - -private: - /// @brief The information whether only the root element should be parsed - bool myRootOnly; - - /// @brief The information whether an error occurred - bool myError; - - /// @brief The options to fill - OptionsCont& myOptions; - - /// @brief The name of the currently parsed option - std::string myItem; - - /// @brief The currently read characters string - std::string myValue; - -}; diff --git a/Util/OSM2ODR/src/utils/options/OptionsParser.cpp b/Util/OSM2ODR/src/utils/options/OptionsParser.cpp deleted file mode 100644 index b35b0a07d..000000000 --- a/Util/OSM2ODR/src/utils/options/OptionsParser.cpp +++ /dev/null @@ -1,190 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file OptionsParser.cpp -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date Mon, 17 Dec 2001 -/// -// Parses the command line arguments -/****************************************************************************/ -#include - -#include -#include -#include "Option.h" -#include "OptionsCont.h" -#include "OptionsParser.h" -#include -#include - - -// =========================================================================== -// method definitions -// =========================================================================== -bool -OptionsParser::parse(int argc, char** argv) { - bool ok = true; - for (int i = 1; i < argc;) { - try { - int add; - // try to set the current option - if (i < argc - 1) { - add = check(argv[i], argv[i + 1], ok); - } else { - add = check(argv[i], nullptr, ok); - } - i += add; - } catch (ProcessError& e) { - WRITE_ERROR("On processing option '" + std::string(argv[i]) + "':\n " + e.what()); - i++; - ok = false; - } - } - return ok; -} - -bool -OptionsParser::parse(std::vector args) { - bool ok = true; - for (size_t i = 1; i < args.size();) { - try { - int add; - // try to set the current option - if (i < args.size()- 1) { - add = check(args[i].c_str(), args[i + 1].c_str(), ok); - } else { - add = check(args[i].c_str(), nullptr, ok); - } - i += add; - } catch (ProcessError& e) { - WRITE_ERROR("On processing option '" + args[i] + "':\n " + e.what()); - i++; - ok = false; - } - } - return ok; -} - -int -OptionsParser::check(const char* arg1, const char* arg2, bool& ok) { - // the first argument should be an option - // (only the second may be a free string) - if (!checkParameter(arg1)) { - ok = false; - return 1; - } - - OptionsCont& oc = OptionsCont::getOptions(); - // process not abbreviated switches - if (!isAbbreviation(arg1)) { - std::string tmp(arg1 + 2); - const std::string::size_type idx1 = tmp.find('='); - // check whether a parameter was submitted - if (idx1 != std::string::npos) { - ok &= oc.set(tmp.substr(0, idx1), tmp.substr(idx1 + 1)); - } else { - if (arg2 == nullptr || (oc.isBool(convert(arg1 + 2)) && arg2[0] == '-')) { - ok &= oc.set(convert(arg1 + 2), "true"); - } else { - ok &= oc.set(convert(arg1 + 2), convert(arg2)); - return 2; - } - } - return 1; - } - // go through the abbreviated switches - for (int i = 1; arg1[i] != 0; i++) { - // set boolean switches - if (oc.isBool(convert(arg1[i]))) { - if (arg2 == nullptr || arg2[0] == '-' || arg1[i + 1] != 0) { - ok &= oc.set(convert(arg1[i]), "true"); - } else { - ok &= oc.set(convert(arg1[i]), convert(arg2)); - return 2; - } - // set non-boolean switches - } else { - // check whether the parameter comes directly after the switch - // and process if so - if (arg2 == nullptr || arg1[i + 1] != 0) { - ok &= processNonBooleanSingleSwitch(oc, arg1 + i); - return 1; - // process parameter following after a space - } else { - ok &= oc.set(convert(arg1[i]), convert(arg2)); - // option name and attribute were in two arguments - return 2; - } - } - } - // all switches within the current argument were boolean switches - return 1; -} - - -bool -OptionsParser::processNonBooleanSingleSwitch(OptionsCont& oc, const char* arg) { - if (arg[1] == '=') { - if (strlen(arg) < 3) { - WRITE_ERROR("Missing value for parameter '" + std::string(arg).substr(0, 1) + "'."); - return false; - } else { - return oc.set(convert(arg[0]), std::string(arg + 2)); - } - } else { - if (strlen(arg) < 2) { - WRITE_ERROR("Missing value for parameter '" + std::string(arg) + "'."); - return false; - } else { - return oc.set(convert(arg[0]), std::string(arg + 1)); - } - } -} - - -bool -OptionsParser::checkParameter(const char* arg1) { - if (arg1[0] != '-') { - WRITE_ERROR("The parameter '" + std::string(arg1) + "' is not allowed in this context.\n Switch or parameter name expected."); - return false; - } - return true; -} - - -bool -OptionsParser::isAbbreviation(const char* arg1) { - return arg1[1] != '-'; -} - - -std::string -OptionsParser::convert(const char* arg) { - std::string s(arg); - return s; -} - - -std::string -OptionsParser::convert(char abbr) { - char buf[2]; - buf[0] = abbr; - buf[1] = 0; - std::string s(buf); - return buf; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/utils/options/OptionsParser.h b/Util/OSM2ODR/src/utils/options/OptionsParser.h deleted file mode 100644 index 793444470..000000000 --- a/Util/OSM2ODR/src/utils/options/OptionsParser.h +++ /dev/null @@ -1,122 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file OptionsParser.h -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date Mon, 17 Dec 2001 -/// -// Parses command line arguments -/****************************************************************************/ -#pragma once -#include - -#include -#include - -// =========================================================================== -// class declarations -// =========================================================================== -class OptionsCont; - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class OptionsParser - * @brief Parses command line arguments - * - * The only public method parses the given list of arguments. It returns false - * when something failed. This may happen if the syntax of the arguments is - * invalid, a value is tried to be set several times or an unknown option - * is tried to be set. - * - * The class assumes all options are unset or using default values only. - */ -class OptionsParser { -public: - /** @brief Parses the given command line arguments - * - * @param[in] oc The options container to fill - * @param[in] argc The number of given command line arguments - * @param[in] argv The command line arguments - * @return Whether the parsing was successfull - * @exception InvalidArgument If a performed setting of an option failed (see Option::set) - */ - static bool parse(int argc, char** argv); - - static bool parse(std::vector args); - -private: - /** @brief parses the previous arguments - * - * @param[in] arg1 The first token to parse - * @param[in] arg2 The second token to parse, 0 if there is none - * @param[in, out] ok Whether the parsing was successfull - * @return Number of read tokens (1 or 2) - * @exception InvalidArgument If a performed setting of an option failed (see Option::set) - */ - static int check(const char* arg1, const char* arg2, bool& ok); - - - /** @brief Returns the whether the given token is an option - * - * The given token is assumed to be an option if it starts with a '-'. - * - * @param[in] arg1 The token to check - * @return Whether the token is an option - */ - static bool checkParameter(const char* arg1); - - - /** @brief returns the whether the given token is an abbreviation - * - * The given token is assumed to be an option if it starts with two '-'. - * - * @param[in] arg1 The token to check - * @return Whether the token is an abbreviation - */ - static bool isAbbreviation(const char* arg1); - - - /** @brief Converts char* to string - * - * @param[in] arg The c-string to convert - * @return The string converted into a std::string - */ - static std::string convert(const char* arg); - - - /** @brief converts char to string - * - * @param[in] abbr The char to convert - * @return The char converted into a std::string - */ - static std::string convert(char abbr); - - - /** @brief Extracts the parameter directly attached to an option - * - * Parses single tokens which contain an option and the parameter - * (like -c=myconfig.cfg) - * - * @param[in] oc The container to store the result into - * @param[in] arg The token to parse - * @exception InvalidArgument If a performed setting of an option failed (see Option::set) - */ - static bool processNonBooleanSingleSwitch(OptionsCont& oc, const char* arg); - - -}; diff --git a/Util/OSM2ODR/src/utils/router/AStarLookupTable.h b/Util/OSM2ODR/src/utils/router/AStarLookupTable.h deleted file mode 100644 index 7ab8a40a6..000000000 --- a/Util/OSM2ODR/src/utils/router/AStarLookupTable.h +++ /dev/null @@ -1,410 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2012-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file AStarLookupTable.h -/// @author Jakob Erdmann -/// @date July 2017 -/// -// Precomputed landmark distances to speed up the A* routing algorithm -/****************************************************************************/ -#pragma once -#include - -#include -#include -#ifdef HAVE_FOX -#include -#endif -#include - -#define UNREACHABLE (std::numeric_limits::max() / 1000.0) - -//#define ASTAR_DEBUG_LOOKUPTABLE -//#define ASTAR_DEBUG_LOOKUPTABLE_FROM "disabled" -//#define ASTAR_DEBUG_UNREACHABLE - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class LandmarkLookupTable - * @brief Computes the shortest path through a network using the A* algorithm. - * - * The template parameters are: - * @param E The edge class to use (MSEdge/ROEdge) - * @param V The vehicle class to use (MSVehicle/ROVehicle) - * @param PF The prohibition function to use (prohibited_withPermissions/noProhibitions) - * @param EC The class to retrieve the effort for an edge from - * - * The router is edge-based. It must know the number of edges for internal reasons - * and whether a missing connection between two given edges (unbuild route) shall - * be reported as an error or as a warning. - * - */ - -template -class AbstractLookupTable { -public: - /// @brief provide a lower bound on the distance between from and to (excluding traveltime of both edges) - virtual double lowerBound(const E* from, const E* to, double speed, double speedFactor, double fromEffort, double toEffort) const = 0; - - /// @brief whether the heuristic ist consistent (found nodes are always visited on the shortest path the first time) - virtual bool consistent() const = 0; -}; - - -template -class FullLookupTable : public AbstractLookupTable { -public: - FullLookupTable(const std::string& filename, const int size) : - myTable(size) { - std::ifstream strm(filename.c_str()); - for (int i = 0; i < size; i++) { - for (int j = 0; j < size; j++) { - double val; - strm >> val; - myTable[i].push_back(val); - } - } - } - - virtual ~FullLookupTable() { - } - - double lowerBound(const E* from, const E* to, double /*speed*/, double speedFactor, double /*fromEffort*/, double /*toEffort*/) const { - return myTable[from->getNumericalID()][to->getNumericalID()] / speedFactor; - } - - bool consistent() const { - return true; - } - -private: - std::vector > myTable; -}; - - -template -class LandmarkLookupTable : public AbstractLookupTable { -public: - LandmarkLookupTable(const std::string& filename, const std::vector& edges, SUMOAbstractRouter* router, - SUMOAbstractRouter, V>* reverseRouter, - const V* defaultVehicle, const std::string& outfile, const int maxNumThreads) { - myFirstNonInternal = -1; - std::map numericID; - for (E* e : edges) { - if (!e->isInternal()) { - if (myFirstNonInternal == -1) { - myFirstNonInternal = e->getNumericalID(); - } - numericID[e->getID()] = e->getNumericalID() - myFirstNonInternal; - } - } - std::ifstream strm(filename.c_str()); - if (!strm.good()) { - throw ProcessError("Could not load landmark-lookup-table from '" + filename + "'."); - } - std::ofstream* ostrm = nullptr; - if (!outfile.empty()) { - ostrm = new std::ofstream(outfile.c_str()); - if (!ostrm->good()) { - throw ProcessError("Could not open file '" + outfile + "' for writing."); - } - } - std::string line; - int numLandMarks = 0; - while (std::getline(strm, line)) { - if (line == "") { - break; - } - //std::cout << "'" << line << "'" << "\n"; - StringTokenizer st(line); - if (st.size() == 1) { - const std::string lm = st.get(0); - myLandmarks[lm] = numLandMarks++; - myFromLandmarkDists.push_back(std::vector(0)); - myToLandmarkDists.push_back(std::vector(0)); - if (ostrm != nullptr) { - (*ostrm) << lm << "\n"; - } - } else { - assert(st.size() == 4); - const std::string lm = st.get(0); - const std::string edge = st.get(1); - if (numericID[edge] != (int)myFromLandmarkDists[myLandmarks[lm]].size()) { - WRITE_WARNING("Unknown or unordered edge '" + edge + "' in landmark file."); - } - const double distFrom = StringUtils::toDouble(st.get(2)); - const double distTo = StringUtils::toDouble(st.get(3)); - myFromLandmarkDists[myLandmarks[lm]].push_back(distFrom); - myToLandmarkDists[myLandmarks[lm]].push_back(distTo); - } - } - if (myLandmarks.empty()) { - WRITE_WARNING("No landmarks in '" + filename + "', falling back to standard A*."); - delete ostrm; - return; - } -#ifdef HAVE_FOX - FXWorkerThread::Pool threadPool; - std::vector currentTasks; -#endif - std::vector landmarks; - for (int i = 0; i < (int)myLandmarks.size(); ++i) { - if ((int)myFromLandmarkDists[i].size() != (int)edges.size() - myFirstNonInternal) { - const std::string landmarkID = getLandmark(i); - const E* landmark = nullptr; - // retrieve landmark edge - for (const E* const edge : edges) { - if (edge->getID() == landmarkID) { - landmark = edge; - landmarks.push_back(edge); - break; - } - } - if (landmark == nullptr) { - WRITE_WARNING("Landmark '" + landmarkID + "' does not exist in the network."); - continue; - } - if (router != nullptr) { - const std::string missing = outfile.empty() ? filename + ".missing" : outfile; - WRITE_WARNING("Not all network edges were found in the lookup table '" + filename + "' for landmark '" + landmarkID + "'. Saving missing values to '" + missing + "'."); - if (ostrm == nullptr) { - ostrm = new std::ofstream(missing.c_str()); - if (!ostrm->good()) { - throw ProcessError("Could not open file '" + missing + "' for writing."); - } - } - } else { - throw ProcessError("Not all network edges were found in the lookup table '" + filename + "' for landmark '" + landmarkID + "'."); - } -#ifdef HAVE_FOX - if (maxNumThreads > 0) { - const double lmCost = router->recomputeCosts({landmark}, defaultVehicle, 0); - router->setAutoBulkMode(true); - if (threadPool.size() == 0) { - if (reverseRouter == nullptr) { - // The CHRouter needs initialization - // before it gets cloned, so we do a dummy routing which is not in parallel - std::vector route; - router->compute(landmark, landmark, defaultVehicle, 0, route); - } else { - reverseRouter->setAutoBulkMode(true); - } - while ((int)threadPool.size() < maxNumThreads) { - auto revClone = reverseRouter == nullptr ? nullptr : reverseRouter->clone(); - new WorkerThread(threadPool, router->clone(), revClone, defaultVehicle); - } - } - for (int j = (int)myFromLandmarkDists[i].size() + myFirstNonInternal; j < (int)edges.size(); ++j) { - const E* const edge = edges[j]; - if (landmark != edge) { - const double sourceDestCost = lmCost + router->recomputeCosts({edge}, defaultVehicle, 0); - currentTasks.push_back(new RoutingTask(landmark, edge, sourceDestCost)); - threadPool.add(currentTasks.back(), i % maxNumThreads); - } - } - } -#endif - } - } -#ifdef HAVE_FOX - threadPool.waitAll(false); - int taskIndex = 0; -#endif - for (int i = 0; i < (int)myLandmarks.size(); ++i) { - if ((int)myFromLandmarkDists[i].size() != (int)edges.size() - myFirstNonInternal) { - const E* landmark = landmarks[i]; - const double lmCost = router->recomputeCosts({landmark}, defaultVehicle, 0); - for (int j = (int)myFromLandmarkDists[i].size() + myFirstNonInternal; j < (int)edges.size(); ++j) { - const E* edge = edges[j]; - double distFrom = -1; - double distTo = -1; - if (landmark == edge) { - distFrom = 0; - distTo = 0; - } else { - if (maxNumThreads > 0) { -#ifdef HAVE_FOX - distFrom = currentTasks[taskIndex]->getFromCost(); - distTo = currentTasks[taskIndex]->getToCost(); - delete currentTasks[taskIndex++]; -#endif - } else { - const double sourceDestCost = lmCost + router->recomputeCosts({edge}, defaultVehicle, 0); - std::vector route; - std::vector*> reversedRoute; - // compute from-distance (skip taz-sources and other unreachable edges) - if (edge->getPredecessors().size() > 0 && landmark->getSuccessors().size() > 0) { - if (router->compute(landmark, edge, defaultVehicle, 0, route)) { - distFrom = MAX2(0.0, router->recomputeCosts(route, defaultVehicle, 0) - sourceDestCost); - route.clear(); - } - } - // compute to-distance (skip unreachable landmarks) - if (landmark->getPredecessors().size() > 0 && edge->getSuccessors().size() > 0) { - if (router->compute(edge, landmark, defaultVehicle, 0, route)) { - distTo = MAX2(0.0, router->recomputeCosts(route, defaultVehicle, 0) - sourceDestCost); - route.clear(); - } - } - } - } - myFromLandmarkDists[i].push_back(distFrom); - myToLandmarkDists[i].push_back(distTo); - (*ostrm) << landmark->getID() << " " << edge->getID() << " " << distFrom << " " << distTo << "\n"; - } - } - } - delete ostrm; - } - - virtual ~LandmarkLookupTable() { - } - - double lowerBound(const E* from, const E* to, double speed, double speedFactor, double fromEffort, double toEffort) const { - double result = from->getDistanceTo(to) / speed; -#ifdef ASTAR_DEBUG_LOOKUPTABLE - if (from->getID() == ASTAR_DEBUG_LOOKUPTABLE_FROM) { - std::cout << " lowerBound to=" << to->getID() << " result1=" << result << "\n"; - } -#endif - for (int i = 0; i < (int)myLandmarks.size(); ++i) { - // a cost of -1 is used to encode unreachability. - const double fl = myToLandmarkDists[i][from->getNumericalID() - myFirstNonInternal]; - const double tl = myToLandmarkDists[i][to->getNumericalID() - myFirstNonInternal]; - if (fl >= 0 && tl >= 0) { - const double bound = (fl - tl - toEffort) / speedFactor; -#ifdef ASTAR_DEBUG_LOOKUPTABLE - if (from->getID() == ASTAR_DEBUG_LOOKUPTABLE_FROM && result < bound) { - std::cout << " landmarkTo=" << getLandmark(i) << " result2=" << bound - << " fl=" << fl << " tl=" << tl << "\n"; - } -#endif - result = MAX2(result, bound); - } - const double lt = myFromLandmarkDists[i][to->getNumericalID() - myFirstNonInternal]; - const double lf = myFromLandmarkDists[i][from->getNumericalID() - myFirstNonInternal]; - if (lt >= 0 && lf >= 0) { - const double bound = (lt - lf - fromEffort) / speedFactor; -#ifdef ASTAR_DEBUG_LOOKUPTABLE - if (from->getID() == ASTAR_DEBUG_LOOKUPTABLE_FROM && result < bound) { - std::cout << " landmarkFrom=" << getLandmark(i) << " result3=" << bound - << " lt=" << lt << " lf=" << lf << "\n"; - } -#endif - result = MAX2(result, bound); - } - if ((tl >= 0 && fl < 0) - || (lf >= 0 && lt < 0)) { - // target unreachable. -#ifdef ASTAR_DEBUG_UNREACHABLE - std::cout << " unreachable: from=" << from->getID() << " to=" << to->getID() << " landmark=" << getLandmark(i) << " " - << ((tl >= 0 && fl < 0) ? " (toLandmark)" : " (fromLandmark)") - << " fl=" << fl << " tl=" << tl << " lt=" << lt << " lf=" << lf - << "\n"; -#endif - return UNREACHABLE; - } - } - return result; - } - - bool consistent() const { - return false; - } - -private: - std::map myLandmarks; - std::vector > myFromLandmarkDists; - std::vector > myToLandmarkDists; - int myFirstNonInternal; - -#ifdef HAVE_FOX -private: - class WorkerThread : public FXWorkerThread { - public: - WorkerThread(FXWorkerThread::Pool& pool, - SUMOAbstractRouter* router, - SUMOAbstractRouter, V>* reverseRouter, const V* vehicle) - : FXWorkerThread(pool), myRouter(router), myReversedRouter(reverseRouter), myVehicle(vehicle) {} - - virtual ~WorkerThread() { - delete myRouter; - } - - const std::pair compute(const E* src, const E* dest, const double costOff) { - double fromResult = -1.; - if (myRouter->compute(src, dest, myVehicle, 0, myRoute)) { - fromResult = MAX2(0.0, myRouter->recomputeCosts(myRoute, myVehicle, 0) + costOff); - myRoute.clear(); - } - double toResult = -1.; - if (myReversedRouter != nullptr) { - if (myReversedRouter->compute(src->getReversedRoutingEdge(), dest->getReversedRoutingEdge(), myVehicle, 0, myReversedRoute)) { - toResult = MAX2(0.0, myReversedRouter->recomputeCosts(myReversedRoute, myVehicle, 0) + costOff); - myReversedRoute.clear(); - } - } else { - if (myRouter->compute(dest, src, myVehicle, 0, myRoute)) { - toResult = MAX2(0.0, myRouter->recomputeCosts(myRoute, myVehicle, 0) + costOff); - myRoute.clear(); - } - } - return std::make_pair(fromResult, toResult); - } - - private: - SUMOAbstractRouter* myRouter; - SUMOAbstractRouter, V>* myReversedRouter; - const V* myVehicle; - std::vector myRoute; - std::vector*> myReversedRoute; - }; - - class RoutingTask : public FXWorkerThread::Task { - public: - RoutingTask(const E* src, const E* dest, const double costOff) - : mySrc(src), myDest(dest), myCostOff(-costOff) {} - void run(FXWorkerThread* context) { - myCost = ((WorkerThread*)context)->compute(mySrc, myDest, myCostOff); - } - double getFromCost() { - return myCost.first; - } - double getToCost() { - return myCost.second; - } - private: - const E* const mySrc; - const E* const myDest; - const double myCostOff; - std::pair myCost; - private: - /// @brief Invalidated assignment operator. - RoutingTask& operator=(const RoutingTask&) = delete; - }; - -private: - /// @brief for multi threaded routing -#endif - - std::string getLandmark(int i) const { - for (std::map::const_iterator it = myLandmarks.begin(); it != myLandmarks.end(); ++it) { - if (it->second == i) { - return it->first; - } - } - return ""; - } -}; diff --git a/Util/OSM2ODR/src/utils/router/AStarRouter.h b/Util/OSM2ODR/src/utils/router/AStarRouter.h deleted file mode 100644 index 47c8e1a39..000000000 --- a/Util/OSM2ODR/src/utils/router/AStarRouter.h +++ /dev/null @@ -1,319 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2012-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file AStarRouter.h -/// @author Jakob Erdmann -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date January 2012 -/// -// A* Algorithm using euclidean distance heuristic. -// Based on DijkstraRouter. For routing by effort a novel heuristic would be needed. -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "AStarLookupTable.h" -#include "SUMOAbstractRouter.h" - -#define UNREACHABLE (std::numeric_limits::max() / 1000.0) - -//#define ASTAR_DEBUG_QUERY -//#define ASTAR_DEBUG_QUERY_FOLLOWERS -//#define ASTAR_DEBUG_QUERY_PERF -//#define ASTAR_DEBUG_VISITED -//#define ASTAR_DEBUG_LOOKUPTABLE -//#define ASTAR_DEBUG_LOOKUPTABLE_FROM "disabled" -//#define ASTAR_DEBUG_UNREACHABLE - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class AStarRouter - * @brief Computes the shortest path through a network using the A* algorithm. - * - * The template parameters are: - * @param E The edge class to use (MSEdge/ROEdge) - * @param V The vehicle class to use (MSVehicle/ROVehicle) - * @param BASE The base class to use (SUMOAbstractRouterPermissions/SUMOAbstractRouter) - * - * The router is edge-based. It must know the number of edges for internal reasons - * and whether a missing connection between two given edges (unbuild route) shall - * be reported as an error or as a warning. - * - */ -template -class AStarRouter : public SUMOAbstractRouter { -public: - typedef AbstractLookupTable LookupTable; - typedef FullLookupTable FLT; - typedef LandmarkLookupTable LMLT; - - /** - * @class EdgeInfoComparator - * Class to compare (and so sort) nodes by their effort - */ - class EdgeInfoComparator { - public: - /// Comparing method - bool operator()(const typename SUMOAbstractRouter::EdgeInfo* nod1, const typename SUMOAbstractRouter::EdgeInfo* nod2) const { - if (nod1->heuristicEffort == nod2->heuristicEffort) { - return nod1->edge->getNumericalID() > nod2->edge->getNumericalID(); - } - return nod1->heuristicEffort > nod2->heuristicEffort; - } - }; - - /// Constructor - AStarRouter(const std::vector& edges, bool unbuildIsWarning, typename SUMOAbstractRouter::Operation operation, const std::shared_ptr lookup = nullptr, - const bool havePermissions = false, const bool haveRestrictions = false) : - SUMOAbstractRouter("AStarRouter", unbuildIsWarning, operation, nullptr, havePermissions, haveRestrictions), - myLookupTable(lookup), - myMaxSpeed(NUMERICAL_EPS) { - for (const E* const edge : edges) { - myEdgeInfos.push_back(typename SUMOAbstractRouter::EdgeInfo(edge)); - myMaxSpeed = MAX2(myMaxSpeed, edge->getSpeedLimit() * MAX2(1.0, edge->getLengthGeometryFactor())); - } - } - - AStarRouter(const std::vector::EdgeInfo>& edgeInfos, bool unbuildIsWarning, typename SUMOAbstractRouter::Operation operation, const std::shared_ptr lookup = nullptr, - const bool havePermissions = false, const bool haveRestrictions = false) : - SUMOAbstractRouter("AStarRouter", unbuildIsWarning, operation, nullptr, havePermissions, haveRestrictions), - myLookupTable(lookup), - myMaxSpeed(NUMERICAL_EPS) { - for (const auto& edgeInfo : edgeInfos) { - myEdgeInfos.push_back(typename SUMOAbstractRouter::EdgeInfo(edgeInfo.edge)); - myMaxSpeed = MAX2(myMaxSpeed, edgeInfo.edge->getSpeedLimit() * edgeInfo.edge->getLengthGeometryFactor()); - } - } - - /// Destructor - virtual ~AStarRouter() {} - - virtual SUMOAbstractRouter* clone() { - return new AStarRouter(myEdgeInfos, this->myErrorMsgHandler == MsgHandler::getWarningInstance(), this->myOperation, myLookupTable); - } - - void init() { - // all EdgeInfos touched in the previous query are either in myFrontierList or myFound: clean those up - for (auto& edgeInfo : myFrontierList) { - edgeInfo->reset(); - } - myFrontierList.clear(); - for (auto& edgeInfo : myFound) { - edgeInfo->reset(); - } - myFound.clear(); - } - - - /** @brief Builds the route between the given edges using the minimum travel time */ - bool compute(const E* from, const E* to, const V* const vehicle, - SUMOTime msTime, std::vector& into, bool silent = false) { - assert(from != nullptr && to != nullptr); - // check whether from and to can be used - if (myEdgeInfos[from->getNumericalID()].prohibited || this->isProhibited(from, vehicle)) { - if (!silent) { - this->myErrorMsgHandler->inform("Vehicle '" + Named::getIDSecure(vehicle) + "' is not allowed on source edge '" + from->getID() + "'."); - } - return false; - } - if (myEdgeInfos[to->getNumericalID()].prohibited || this->isProhibited(to, vehicle)) { - if (!silent) { - this->myErrorMsgHandler->inform("Vehicle '" + Named::getIDSecure(vehicle) + "' is not allowed on destination edge '" + to->getID() + "'."); - } - return false; - } - double length = 0.; // dummy for the via edge cost update - this->startQuery(); -#ifdef ASTAR_DEBUG_QUERY - std::cout << "DEBUG: starting search for '" << Named::getIDSecure(vehicle) << "' speed: " << MIN2(vehicle->getMaxSpeed(), myMaxSpeed * vehicle->getChosenSpeedFactor()) << " time: " << STEPS2TIME(msTime) << "\n"; -#endif - const SUMOVehicleClass vClass = vehicle == 0 ? SVC_IGNORING : vehicle->getVClass(); - if (this->myBulkMode) { - const auto& toInfo = myEdgeInfos[to->getNumericalID()]; - if (toInfo.visited) { - buildPathFrom(&toInfo, into); - this->endQuery(1); - return true; - } - } else { - init(); - // add begin node - auto* const fromInfo = &(myEdgeInfos[from->getNumericalID()]); - fromInfo->effort = 0.; - fromInfo->heuristicEffort = 0.; - fromInfo->prev = nullptr; - fromInfo->leaveTime = STEPS2TIME(msTime); - myFrontierList.push_back(fromInfo); - } - // loop - int num_visited = 0; - const bool mayRevisit = myLookupTable != 0 && !myLookupTable->consistent(); - const double speed = vehicle == nullptr ? myMaxSpeed : MIN2(vehicle->getMaxSpeed(), myMaxSpeed * vehicle->getChosenSpeedFactor()); - while (!myFrontierList.empty()) { - num_visited += 1; - // use the node with the minimal length - auto* const minimumInfo = myFrontierList.front(); - const E* const minEdge = minimumInfo->edge; - // check whether the destination node was already reached - if (minEdge == to) { - buildPathFrom(minimumInfo, into); - this->endQuery(num_visited); -#ifdef ASTAR_DEBUG_QUERY_PERF - std::cout << "visited " + toString(num_visited) + " edges (final path length=" + toString(into.size()) - + " time=" + toString(recomputeCosts(into, vehicle, msTime)) - + " edges=" + toString(into) + ")\n"; -#endif -#ifdef ASTAR_DEBUG_VISITED - OutputDevice& dev = OutputDevice::getDevice(Named::getIDSecure(vehicle) + "_" + time2string(msTime) + "_" + from->getID() + "_" + to->getID()); - for (const auto& i : myEdgeInfos) { - if (i.visited) { - dev << "edge:" << i.edge->getID() << "\n"; - } - } - dev.close(); -#endif - return true; - } - std::pop_heap(myFrontierList.begin(), myFrontierList.end(), myComparator); - myFrontierList.pop_back(); - myFound.push_back(minimumInfo); - minimumInfo->visited = true; -#ifdef ASTAR_DEBUG_QUERY - std::cout << "DEBUG: hit=" << minEdge->getID() - << " TT=" << minimumInfo->effort - << " EF=" << this->getEffort(minEdge, vehicle, minimumInfo->leaveTime) - << " HT=" << minimumInfo->heuristicEffort - << " Q(TT,HT,Edge)="; - for (typename std::vector::iterator it = myFrontierList.begin(); it != myFrontierList.end(); it++) { - std::cout << (*it)->effort << "," << (*it)->heuristicEffort << "," << (*it)->edge->getID() << " "; - } - std::cout << "\n"; -#endif - const double effortDelta = this->getEffort(minEdge, vehicle, minimumInfo->leaveTime); - const double leaveTime = minimumInfo->leaveTime + this->getTravelTime(minEdge, vehicle, minimumInfo->leaveTime, effortDelta); - - // admissible A* heuristic: straight line distance at maximum speed - const double heuristic_remaining = (myLookupTable == nullptr ? minEdge->getDistanceTo(to) / speed : - myLookupTable->lowerBound(minEdge, to, speed, vehicle->getChosenSpeedFactor(), - minEdge->getMinimumTravelTime(nullptr), to->getMinimumTravelTime(nullptr))); - if (heuristic_remaining == UNREACHABLE) { - continue; - } - const double heuristicEffort = minimumInfo->effort + effortDelta + heuristic_remaining; - // check all ways from the node with the minimal length - for (const std::pair& follower : minEdge->getViaSuccessors(vClass)) { - auto* const followerInfo = &(myEdgeInfos[follower.first->getNumericalID()]); - // check whether it can be used - if (followerInfo->prohibited || this->isProhibited(follower.first, vehicle)) { - continue; - } - double effort = minimumInfo->effort + effortDelta; - double time = leaveTime; - this->updateViaEdgeCost(follower.second, vehicle, time, effort, length); - const double oldEffort = followerInfo->effort; - if ((!followerInfo->visited || mayRevisit) && effort < oldEffort) { - followerInfo->effort = effort; - // if we use the effort including the via effort below we would count the via twice as shown by the ticket676 test - followerInfo->heuristicEffort = MIN2(heuristicEffort, followerInfo->heuristicEffort); - followerInfo->leaveTime = time; - followerInfo->prev = minimumInfo; -#ifdef ASTAR_DEBUG_QUERY_FOLLOWERS - std::cout << " follower=" << followerInfo->edge->getID() - << " OEF=" << (oldEffort == std::numeric_limits::max() ? "inf" : toString(oldEffort)) - << " TT=" << effort << " HR=" << heuristic_remaining << " HT=" << followerInfo->heuristicEffort << "\n"; -#endif - if (oldEffort == std::numeric_limits::max()) { - myFrontierList.push_back(followerInfo); - std::push_heap(myFrontierList.begin(), myFrontierList.end(), myComparator); - } else { - auto fi = std::find(myFrontierList.begin(), myFrontierList.end(), followerInfo); - if (fi == myFrontierList.end()) { - assert(mayRevisit); - myFrontierList.push_back(followerInfo); - std::push_heap(myFrontierList.begin(), myFrontierList.end(), myComparator); - } else { - std::push_heap(myFrontierList.begin(), fi + 1, myComparator); - } - } - } - } - } - this->endQuery(num_visited); -#ifdef ASTAR_DEBUG_QUERY_PERF - std::cout << "visited " + toString(num_visited) + " edges (unsuccessful path length: " + toString(into.size()) + ")\n"; -#endif - if (!silent) { - this->myErrorMsgHandler->informf("No connection between edge '%' and edge '%' found.", from->getID(), to->getID()); - } - return false; - } - - - void prohibit(const std::vector& toProhibit) { - for (E* const edge : this->myProhibited) { - myEdgeInfos[edge->getNumericalID()].prohibited = false; - } - for (E* const edge : toProhibit) { - myEdgeInfos[edge->getNumericalID()].prohibited = true; - } - this->myProhibited = toProhibit; - } - - - /// Builds the path from marked edges - void buildPathFrom(const typename SUMOAbstractRouter::EdgeInfo* rbegin, std::vector& edges) { - std::vector tmp; - while (rbegin != 0) { - tmp.push_back(rbegin->edge); - rbegin = rbegin->prev; - } - std::copy(tmp.rbegin(), tmp.rend(), std::back_inserter(edges)); - } - -protected: - /// The container of edge information - std::vector::EdgeInfo> myEdgeInfos; - - /// A container for reusage of the min edge heap - std::vector::EdgeInfo*> myFrontierList; - /// @brief list of visited Edges (for resetting) - std::vector::EdgeInfo*> myFound; - - EdgeInfoComparator myComparator; - - /// @brief the lookup table for travel time heuristics - const std::shared_ptr myLookupTable; - - /// @brief maximum speed in the network - double myMaxSpeed; -}; diff --git a/Util/OSM2ODR/src/utils/router/AccessEdge.h b/Util/OSM2ODR/src/utils/router/AccessEdge.h deleted file mode 100644 index 615370730..000000000 --- a/Util/OSM2ODR/src/utils/router/AccessEdge.h +++ /dev/null @@ -1,70 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file AccessEdge.h -/// @author Michael Behrisch -/// @date Mon, 03 March 2014 -/// -// The AccessEdge is a special intermodal edge connecting different modes -/****************************************************************************/ -#pragma once -#include - -#include "IntermodalEdge.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -/// @brief the access edge connecting different modes that is given to the internal router (SUMOAbstractRouter) -template -class AccessEdge : public IntermodalEdge { -private: - typedef IntermodalEdge _IntermodalEdge; - -public: - AccessEdge(int numericalID, const _IntermodalEdge* inEdge, const _IntermodalEdge* outEdge, const double length, - SVCPermissions modeRestriction = SVC_IGNORING, - SVCPermissions vehicleRestriction = SVC_IGNORING) : - _IntermodalEdge(inEdge->getID() + ":" + outEdge->getID(), numericalID, outEdge->getEdge(), "!access"), - myLength(length > 0. ? length : NUMERICAL_EPS), - myModeRestrictions(modeRestriction), - myVehicleRestriction(vehicleRestriction) - { } - - AccessEdge(int numericalID, const std::string& id, const E* edge, const double length = 0, - SVCPermissions modeRestriction = SVC_IGNORING, - SVCPermissions vehicleRestriction = SVC_IGNORING) : - _IntermodalEdge(id, numericalID, edge, "!access"), - myLength(length > 0. ? length : NUMERICAL_EPS), - myModeRestrictions(modeRestriction), - myVehicleRestriction(vehicleRestriction) - { } - - double getTravelTime(const IntermodalTrip* const trip, double /* time */) const { - return myLength / trip->speed; - } - - bool prohibits(const IntermodalTrip* const trip) const { - return ((trip->modeSet & myModeRestrictions) != myModeRestrictions - || ((trip->vehicle == nullptr ? SVC_IGNORING : trip->vehicle->getVClass()) & myVehicleRestriction) != myVehicleRestriction); - } - -private: - const double myLength; - /// @brief only allow using this edge if the modeSet matches (i.e. entering a taxi) - const SVCPermissions myModeRestrictions; - /// @brief only allow using this edge if the vehicle class matches (i.e. exiting a taxi) - const SVCPermissions myVehicleRestriction; - -}; diff --git a/Util/OSM2ODR/src/utils/router/CHBuilder.h b/Util/OSM2ODR/src/utils/router/CHBuilder.h deleted file mode 100644 index f16dcf26e..000000000 --- a/Util/OSM2ODR/src/utils/router/CHBuilder.h +++ /dev/null @@ -1,520 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file CHBuilder.h -/// @author Jakob Erdmann -/// @author Laura Bieker -/// @author Michael Behrisch -/// @date February 2012 -/// -// Contraction Hierarchy Builder for the shortest path search -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "SPTree.h" - -//#define CHRouter_DEBUG_CONTRACTION -//#define CHRouter_DEBUG_CONTRACTION_WITNESSES -//#define CHRouter_DEBUG_CONTRACTION_QUEUE -//#define CHRouter_DEBUG_CONTRACTION_DEGREE -//#define CHRouter_DEBUG_WEIGHTS - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class CHRouter - * @brief Computes the shortest path through a contracted network - * - * The template parameters are: - * @param E The edge class to use (MSEdge/ROEdge) - * @param V The vehicle class to use (MSVehicle/ROVehicle) - * @param PF The prohibition function to use (prohibited_withPermissions/noProhibitions) - * - * The router is edge-based. It must know the number of edges for internal reasons - * and whether a missing connection between two given edges (unbuild route) shall - * be reported as an error or as a warning. - * - */ -template -class CHBuilder { - -public: - /// @brief Forward/backward connection with associated forward/backward cost - // forward connections are used only in forward search - // backward connections are used only in backwards search - class Connection { - public: - Connection(int t, double c, SVCPermissions p): target(t), cost(c), permissions(p) {} - int target; - double cost; - SVCPermissions permissions; - }; - - typedef std::pair ConstEdgePair; - typedef std::map ShortcutVia; - struct Hierarchy { - ShortcutVia shortcuts; - std::vector > forwardUplinks; - std::vector > backwardUplinks; - }; - - /** @brief Constructor - * @param[in] validatePermissions Whether a multi-permission hierarchy shall be built - * If set to false, the net is pruned in synchronize() and the - * hierarchy is tailored to the svc - */ - CHBuilder(const std::vector& edges, bool unbuildIsWarning, - const SUMOVehicleClass svc, - bool validatePermissions): - myEdges(edges), - myErrorMsgHandler(unbuildIsWarning ? MsgHandler::getWarningInstance() : MsgHandler::getErrorInstance()), - mySPTree(new SPTree(4, validatePermissions)), - mySVC(svc), - myUpdateCount(0) { - for (typename std::vector::const_iterator i = edges.begin(); i != edges.end(); ++i) { - myCHInfos.push_back(CHInfo(*i)); - } - } - - /// Destructor - virtual ~CHBuilder() { - delete mySPTree; - } - - - const Hierarchy* buildContractionHierarchy(SUMOTime time, const V* const vehicle, const SUMOAbstractRouter* effortProvider) { - Hierarchy* result = new Hierarchy(); - const int numEdges = (int)myCHInfos.size(); - const std::string vClass = (mySPTree->validatePermissions() ? - "all vehicle classes " : "vClass='" + SumoVehicleClassStrings.getString(mySVC) + "' "); - PROGRESS_BEGIN_MESSAGE("Building Contraction Hierarchy for " + vClass - + "and time=" + time2string(time) + " (" + toString(numEdges) + " edges)\n"); - const long startMillis = SysUtils::getCurrentMillis(); - // init queue - std::vector queue; // max heap: edge to be contracted is front - // reset previous connections etc - for (int i = 0; i < numEdges; i++) { - myCHInfos[i].resetContractionState(); - result->forwardUplinks.push_back(std::vector()); - result->backwardUplinks.push_back(std::vector()); - } - // copy connections from the original net - const double time_seconds = STEPS2TIME(time); // timelines store seconds! - for (int i = 0; i < numEdges; i++) { - synchronize(myCHInfos[i], time_seconds, vehicle, effortProvider); - } - // synchronization is finished. now we can compute priorities for the first time - for (int i = 0; i < numEdges; i++) { - myCHInfos[i].updatePriority(mySPTree); - queue.push_back(&(myCHInfos[i])); - } - std::make_heap(queue.begin(), queue.end(), myCmp); - int contractionRank = 0; - // contraction loop - while (!queue.empty()) { - while (tryUpdateFront(queue)) {} - CHInfo* max = queue.front(); - max->rank = contractionRank; -#ifdef CHRouter_DEBUG_CONTRACTION - std::cout << "contracting '" << max->edge->getID() << "' with prio: " << max->priority << " (rank " << contractionRank << ")\n"; -#endif - const E* const edge = max->edge; - // add outgoing connections to the forward search - const int edgeID = edge->getNumericalID(); - for (typename CHConnections::const_iterator it = max->followers.begin(); it != max->followers.end(); it++) { - const CHConnection& con = *it; - result->forwardUplinks[edgeID].push_back(Connection(con.target->edge->getNumericalID(), con.cost, con.permissions)); - disconnect(con.target->approaching, max); - con.target->updatePriority(0); - } - // add incoming connections to the backward search - for (typename CHConnections::const_iterator it = max->approaching.begin(); it != max->approaching.end(); it++) { - const CHConnection& con = *it; - result->backwardUplinks[edgeID].push_back(Connection(con.target->edge->getNumericalID(), con.cost, con.permissions)); - disconnect(con.target->followers, max); - con.target->updatePriority(0); - } - // add shortcuts to the net - for (typename std::vector::const_iterator it = max->shortcuts.begin(); it != max->shortcuts.end(); it++) { - const ConstEdgePair& edgePair = it->edgePair; - result->shortcuts[edgePair] = edge; - CHInfo* from = getCHInfo(edgePair.first); - CHInfo* to = getCHInfo(edgePair.second); - from->followers.push_back(CHConnection(to, it->cost, it->permissions, it->underlying)); - to->approaching.push_back(CHConnection(from, it->cost, it->permissions, it->underlying)); - } - // if you need to debug the chrouter with MSVC uncomment the following line, hierarchy building will get slower and the hierarchy may change though - //std::make_heap(queue.begin(), queue.end(), myCmp); - // remove from queue - std::pop_heap(queue.begin(), queue.end(), myCmp); - queue.pop_back(); - /* - if (contractionRank % 10000 == 0) { - // update all and rebuild queue - for (typename std::vector::iterator it = queue.begin(); it != queue.end(); ++it) { - (*it)->updatePriority(mySPTree); - } - std::make_heap(queue.begin(), queue.end(), myCmp); - } - */ - contractionRank++; - } - // reporting - const long duration = SysUtils::getCurrentMillis() - startMillis; - WRITE_MESSAGE("Created " + toString(result->shortcuts.size()) + " shortcuts."); - WRITE_MESSAGE("Recomputed priority " + toString(myUpdateCount) + " times."); - MsgHandler::getMessageInstance()->endProcessMsg("done (" + toString(duration) + "ms)."); - PROGRESS_DONE_MESSAGE(); - myUpdateCount = 0; - return result; - } - -private: - struct Shortcut { - Shortcut(ConstEdgePair e, double c, int u, SVCPermissions p): - edgePair(e), cost(c), underlying(u), permissions(p) {} - ConstEdgePair edgePair; - double cost; - int underlying; - SVCPermissions permissions; - }; - - - class CHInfo; - - /// @brief Forward/backward connection with associated FORWARD cost - class CHConnection { - public: - CHConnection(CHInfo* t, double c, SVCPermissions p, int u): - target(t), cost(c), permissions(p), underlying(u) {} - CHInfo* target; - double cost; - SVCPermissions permissions; - /// the number of connections underlying this connection - int underlying; - }; - - typedef std::vector CHConnections; - typedef std::pair CHConnectionPair; - typedef std::vector CHConnectionPairs; - - /* @brief container class to use when building the contraction hierarchy. - * instances are reused every time the hierarchy is rebuilt (new time slice) - * but they must be synchronized first */ - class CHInfo { - public: - /// @brief Constructor - CHInfo(const E* e) : - edge(e), - priority(0.), - contractedNeighbors(0), - rank(-1), - level(0), - underlyingTotal(0), - visited(false), - traveltime(std::numeric_limits::max()), - depth(0), - permissions(SVC_IGNORING) { - } - - /// @brief recompute the contraction priority and report whether it changed - bool updatePriority(SPTree* spTree) { - if (spTree != 0) { - updateShortcuts(spTree); - updateLevel(); - } else { - contractedNeighbors += 1; // called when a connected edge was contracted - } - const double oldPriority = priority; - // priority term as used by abraham [] - const int edge_difference = (int)followers.size() + (int)approaching.size() - 2 * (int)shortcuts.size(); - priority = (double)(2 * edge_difference - contractedNeighbors - underlyingTotal - 5 * level); - return priority != oldPriority; - } - - /// compute needed shortcuts when contracting this edge - void updateShortcuts(SPTree* spTree) { - const bool validatePermissions = spTree->validatePermissions(); -#ifdef CHRouter_DEBUG_CONTRACTION_DEGREE - const int degree = (int)approaching.size() + (int)followers.size(); - std::cout << "computing shortcuts for '" + edge->getID() + "' with degree " + toString(degree) + "\n"; -#endif - shortcuts.clear(); - underlyingTotal = 0; - for (typename CHConnections::iterator it_a = approaching.begin(); it_a != approaching.end(); it_a++) { - CHConnection& aInfo = *it_a; - // build shortest path tree in a fixed neighborhood - spTree->rebuildFrom(aInfo.target, this); - for (typename CHConnections::iterator it_f = followers.begin(); it_f != followers.end(); it_f++) { - CHConnection& fInfo = *it_f; - const double viaCost = aInfo.cost + fInfo.cost; - const SVCPermissions viaPermissions = (aInfo.permissions & fInfo.permissions); - if (fInfo.target->traveltime > viaCost) { - // found no faster path -> we need a shortcut via edge -#ifdef CHRouter_DEBUG_CONTRACTION_WITNESSES - debugNoWitness(aInfo, fInfo); -#endif - const int underlying = aInfo.underlying + fInfo.underlying; - underlyingTotal += underlying; - shortcuts.push_back(Shortcut(ConstEdgePair(aInfo.target->edge, fInfo.target->edge), - viaCost, underlying, viaPermissions)); - - } else if (validatePermissions) { - if ((fInfo.target->permissions & viaPermissions) != viaPermissions) { - // witness has weaker restrictions. try to find another witness - spTree->registerForValidation(&aInfo, &fInfo); - } else { -#ifdef CHRouter_DEBUG_CONTRACTION_WITNESSES - debugNoWitness(aInfo, fInfo); -#endif - } - } else { -#ifdef CHRouter_DEBUG_CONTRACTION_WITNESSES - debugNoWitness(aInfo, fInfo); -#endif - } - } - } - // insert shortcuts needed due to unmet permissions - if (validatePermissions) { - const CHConnectionPairs& pairs = spTree->getNeededShortcuts(this); - for (typename CHConnectionPairs::const_iterator it = pairs.begin(); it != pairs.end(); ++it) { - const CHConnection* aInfo = it->first; - const CHConnection* fInfo = it->second; - const double viaCost = aInfo->cost + fInfo->cost; - const SVCPermissions viaPermissions = (aInfo->permissions & fInfo->permissions); - const int underlying = aInfo->underlying + fInfo->underlying; - underlyingTotal += underlying; - shortcuts.push_back(Shortcut(ConstEdgePair(aInfo->target->edge, fInfo->target->edge), - viaCost, underlying, viaPermissions)); - } - } - } - - - // update level as defined by Abraham - void updateLevel() { - int maxLower = std::numeric_limits::min(); - int otherRank; - for (typename CHConnections::iterator it = approaching.begin(); it != approaching.end(); it++) { - otherRank = it->target->rank; - if (otherRank < rank) { - maxLower = MAX2(rank, maxLower); - } - } - for (typename CHConnections::iterator it = followers.begin(); it != followers.end(); it++) { - otherRank = it->target->rank; - if (otherRank < rank) { - maxLower = MAX2(rank, maxLower); - } - } - if (maxLower == std::numeric_limits::min()) { - level = 0; - } else { - level = maxLower + 1; - } - } - - // resets state before rebuilding the hierarchy - void resetContractionState() { - contractedNeighbors = 0; - rank = -1; - level = 0; - underlyingTotal = 0; - shortcuts.clear(); - followers.clear(); - approaching.clear(); - } - - - /// @brief The current edge - not const since it may receive shortcut edges - const E* edge; - /// @brief The contraction priority - double priority; - /// @brief The needed shortcuts - std::vector shortcuts; - /// @brief priority subterms - int contractedNeighbors; - int rank; - int level; - int underlyingTotal; - - /// @brief connections (only valid after synchronization) - CHConnections followers; - CHConnections approaching; - - - /// members used in SPTree - bool visited; - /// Effort to reach the edge - double traveltime; - /// number of edges from start - int depth; - /// the permissions when reaching this edge on the fastest path - // @note: we may miss some witness paths by making traveltime the only - // criteria durinng search - SVCPermissions permissions; - - inline void reset() { - traveltime = std::numeric_limits::max(); - visited = false; - } - - - /// debugging methods - inline void debugNoWitness(const CHConnection& aInfo, const CHConnection& fInfo) { - std::cout << "adding shortcut between " << aInfo.target->edge->getID() << ", " << fInfo.target->edge->getID() << " via " << edge->getID() << "\n"; - } - - inline void debugWitness(const CHConnection& aInfo, const CHConnection& fInfo) { - const double viaCost = aInfo.cost + fInfo.cost; - std::cout << "found witness with length " << fInfo.target->traveltime << " against via " << edge->getID() << " (length " << viaCost << ") for " << aInfo.target->edge->getID() << ", " << fInfo.target->edge->getID() << "\n"; - } - - }; - - - /** - * @class EdgeInfoByRankComparator - * Class to compare (and so sort) nodes by their contraction priority - */ - class CHInfoComparator { - public: - /// Comparing method - bool operator()(const CHInfo* a, const CHInfo* b) const { - if (a->priority == b->priority) { - return a->edge->getNumericalID() > b->edge->getNumericalID(); - } else { - return a->priority < b->priority; - }; - } - }; - - - inline CHInfo* getCHInfo(const E* const edge) { - return &(myCHInfos[edge->getNumericalID()]); - } - - - /// @brief copy connections from the original net (modified destructively during contraction) - void synchronize(CHInfo& info, double time, const V* const vehicle, const SUMOAbstractRouter* effortProvider) { - // forward and backward connections are used only in forward search, - // thus approaching costs are those of the approaching edge and not of the edge itself - const bool prune = !mySPTree->validatePermissions(); - const E* const edge = info.edge; - if (prune && ((edge->getPermissions() & mySVC) != mySVC)) { - return; - } - const double baseCost = effortProvider->getEffort(edge, vehicle, time); - - for (const std::pair& successor : edge->getViaSuccessors(mySVC)) { - const E* fEdge = successor.first; - if (prune && ((fEdge->getPermissions() & mySVC) != mySVC)) { - continue; - } - CHInfo* const follower = getCHInfo(fEdge); - const SVCPermissions permissions = (edge->getPermissions() & fEdge->getPermissions()); - double cost = baseCost; - const E* viaEdge = successor.second; - while (viaEdge != nullptr && viaEdge->isInternal()) { - cost += effortProvider->getEffort(viaEdge, vehicle, time); - viaEdge = viaEdge->getViaSuccessors().front().first; - } - info.followers.push_back(CHConnection(follower, cost, permissions, 1)); - follower->approaching.push_back(CHConnection(&info, cost, permissions, 1)); - } -#ifdef CHRouter_DEBUG_WEIGHTS - std::cout << time << ": " << edge->getID() << " cost: " << cost << "\n"; -#endif - // @todo: check whether we even need to save approaching in ROEdge; - } - - - /// @brief remove all connections to/from the given edge (assume it exists only once) - void disconnect(CHConnections& connections, CHInfo* other) { - for (typename CHConnections::iterator it = connections.begin(); it != connections.end(); it++) { - if (it->target == other) { - connections.erase(it); - return; - } - } - assert(false); - } - - /** @brief tries to update the priority of the first edge - * @return wether updating changed the first edge - */ - bool tryUpdateFront(std::vector& queue) { - myUpdateCount++; - CHInfo* max = queue.front(); -#ifdef CHRouter_DEBUG_CONTRACTION_QUEUE - std::cout << "updating '" << max->edge->getID() << "'\n"; - debugPrintQueue(queue); -#endif - if (max->updatePriority(mySPTree)) { - std::pop_heap(queue.begin(), queue.end(), myCmp); - std::push_heap(queue.begin(), queue.end(), myCmp); - return true; - } else { - return false; - } - } - - // helper method for debugging - void debugPrintQueue(std::vector& queue) { - for (typename std::vector::iterator it = queue.begin(); it != queue.end(); it++) { - CHInfo* chInfo = *it; - std::cout << "(" << chInfo->edge->getID() << "," << chInfo->priority << ") "; - } - std::cout << "\n"; - } - -private: - /// @brief all edges with numerical ids - const std::vector& myEdges; - - /// @brief the handler for routing errors - MsgHandler* const myErrorMsgHandler; - - /// @brief static vector for lookup - std::vector myCHInfos; - - /// @brief Comparator for contraction priority - CHInfoComparator myCmp; - - /// @brief the shortest path tree to use when searching for shortcuts - SPTree* mySPTree; - - /// @brief the permissions for which the hierarchy was constructed - const SUMOVehicleClass mySVC; - - /// @brief counters for performance logging - int myUpdateCount; - -private: - /// @brief Invalidated assignment operator - CHBuilder& operator=(const CHBuilder& s); -}; diff --git a/Util/OSM2ODR/src/utils/router/CHRouter.h b/Util/OSM2ODR/src/utils/router/CHRouter.h deleted file mode 100644 index b1e640e6c..000000000 --- a/Util/OSM2ODR/src/utils/router/CHRouter.h +++ /dev/null @@ -1,390 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file CHRouter.h -/// @author Jakob Erdmann -/// @author Laura Bieker -/// @author Michael Behrisch -/// @date February 2012 -/// -// Shortest Path search using a Contraction Hierarchy -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "CHBuilder.h" - -//#define CHRouter_DEBUG_QUERY -//#define CHRouter_DEBUG_QUERY_PERF - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class CHRouter - * @brief Computes the shortest path through a contracted network - * - * The template parameters are: - * @param E The edge class to use (MSEdge/ROEdge) - * @param V The vehicle class to use (MSVehicle/ROVehicle) - * - * The router is edge-based. It must know the number of edges for internal reasons - * and whether a missing connection between two given edges (unbuild route) shall - * be reported as an error or as a warning. - * - */ -template -class CHRouter: public SUMOAbstractRouter { - -public: - /// A meeting point of the two search scopes - typedef std::pair::EdgeInfo*, const typename SUMOAbstractRouter::EdgeInfo*> Meeting; - - /** - * @class Unidirectional - * class for searching in one direction - */ - class Unidirectional { - public: - /// @brief Constructor - Unidirectional(const std::vector& edges, bool forward): - myAmForward(forward), - myVehicle(0) { - for (const E* const e : edges) { - myEdgeInfos.push_back(typename SUMOAbstractRouter::EdgeInfo(e)); - } - } - - inline bool found(const E* const edge) const { - return myFound.count(edge) > 0; - } - - inline typename SUMOAbstractRouter::EdgeInfo* getEdgeInfo(const E* const edge) { - return &(myEdgeInfos[edge->getNumericalID()]); - } - - inline const typename SUMOAbstractRouter::EdgeInfo* getEdgeInfo(const E* const edge) const { - return &(myEdgeInfos[edge->getNumericalID()]); - } - - /** - * @class EdgeInfoByEffortComparator - * Class to compare (and so sort) nodes by their effort - */ - class EdgeInfoByTTComparator { - public: - /// Comparing method - bool operator()(const typename SUMOAbstractRouter::EdgeInfo* nod1, const typename SUMOAbstractRouter::EdgeInfo* nod2) const { - if (nod1->effort == nod2->effort) { - return nod1->edge->getNumericalID() > nod2->edge->getNumericalID(); - } - return nod1->effort > nod2->effort; - } - }; - - - void init(const E* const start, const V* const vehicle) { - assert(vehicle != 0); - // all EdgeInfos touched in the previous query are either in myFrontier or myFound: clean those up - for (auto ei : myFrontier) { - ei->reset(); - } - myFrontier.clear(); - for (auto edge : myFound) { - getEdgeInfo(edge)->reset(); - } - myFound.clear(); - myVehicle = vehicle; - auto startInfo = getEdgeInfo(start); - startInfo->effort = 0.; - startInfo->prev = nullptr; - myFrontier.push_back(startInfo); - } - - - typedef std::vector::Connection> ConnectionVector; - /** @brief explore on element from the frontier,update minTTSeen and meeting - * if an EdgeInfo found by the otherSearch is encountered - * returns whether stepping should continue - */ - bool step(const std::vector& uplinks, const Unidirectional& otherSearch, double& minTTSeen, Meeting& meeting) { - // pop the node with the minimal length - auto* const minimumInfo = myFrontier.front(); - std::pop_heap(myFrontier.begin(), myFrontier.end(), myComparator); - myFrontier.pop_back(); - // check for a meeting with the other search - const E* const minEdge = minimumInfo->edge; -#ifdef CHRouter_DEBUG_QUERY - std::cout << "DEBUG: " << (myAmForward ? "Forward" : "Backward") << " hit '" << minEdge->getID() << "' Q: "; - for (typename std::vector::iterator it = myFrontier.begin(); it != myFrontier.end(); it++) { - std::cout << (*it)->traveltime << "," << (*it)->edge->getID() << " "; - } - std::cout << "\n"; -#endif - if (otherSearch.found(minEdge)) { - const auto* const otherInfo = otherSearch.getEdgeInfo(minEdge); - const double ttSeen = minimumInfo->effort + otherInfo->effort; -#ifdef CHRouter_DEBUG_QUERY - std::cout << "DEBUG: " << (myAmForward ? "Forward" : "Backward") << "-Search hit other search at '" << minEdge->getID() << "', tt: " << ttSeen << " \n"; -#endif - if (ttSeen < minTTSeen) { - minTTSeen = ttSeen; - if (myAmForward) { - meeting.first = minimumInfo; - meeting.second = otherInfo; - } else { - meeting.first = otherInfo; - meeting.second = minimumInfo; - } - } - } - // prepare next steps - minimumInfo->visited = true; - // XXX we only need to keep found elements if they have a higher rank than the lowest rank in the other search queue - myFound.insert(minimumInfo->edge); - for (const auto& uplink : uplinks[minEdge->getNumericalID()]) { - const auto upwardInfo = &myEdgeInfos[uplink.target]; - const double effort = minimumInfo->effort + uplink.cost; - const SUMOVehicleClass svc = myVehicle->getVClass(); - // check whether it can be used - if ((uplink.permissions & svc) != svc) { - continue; - } - const double oldEffort = upwardInfo->effort; - if (!upwardInfo->visited && effort < oldEffort) { - upwardInfo->effort = effort; - upwardInfo->prev = minimumInfo; - if (oldEffort == std::numeric_limits::max()) { - myFrontier.push_back(upwardInfo); - std::push_heap(myFrontier.begin(), myFrontier.end(), myComparator); - } else { - std::push_heap(myFrontier.begin(), - std::find(myFrontier.begin(), myFrontier.end(), upwardInfo) + 1, - myComparator); - } - } - } - // @note: this effectively does a full dijkstra search. - // the effort compared to the naive stopping criterion is thus - // quadrupled. We could implement a better stopping criterion (Holte) - // However since the search shall take place in a contracted graph - // it probably does not matter - return !myFrontier.empty() && myFrontier.front()->effort < minTTSeen; - } - - private: - /// @brief the role of this search - bool myAmForward; - /// @brief the min edge heap - std::vector::EdgeInfo*> myFrontier; - /// @brief the set of visited (settled) Edges - std::set myFound; - /// @brief The container of edge information - std::vector::EdgeInfo> myEdgeInfos; - - EdgeInfoByTTComparator myComparator; - - const V* myVehicle; - - }; - - /** @brief Constructor - * @param[in] validatePermissions Whether a multi-permission hierarchy shall be built - * If set to false, the net is pruned in synchronize() and the - * hierarchy is tailored to the svc - */ - CHRouter(const std::vector& edges, bool unbuildIsWarning, typename SUMOAbstractRouter::Operation operation, - const SUMOVehicleClass svc, - SUMOTime weightPeriod, - const bool havePermissions, const bool haveRestrictions): - SUMOAbstractRouter("CHRouter", unbuildIsWarning, operation, nullptr, havePermissions, haveRestrictions), - myEdges(edges), - myForwardSearch(edges, true), - myBackwardSearch(edges, false), - myHierarchyBuilder(new CHBuilder(edges, unbuildIsWarning, svc, havePermissions)), - myHierarchy(nullptr), - myWeightPeriod(weightPeriod), - myValidUntil(0), - mySVC(svc) { - } - - /** @brief Cloning constructor, should be used only for time independent instances which build a hierarchy only once - */ - CHRouter(const std::vector& edges, bool unbuildIsWarning, typename SUMOAbstractRouter::Operation operation, - const SUMOVehicleClass svc, - const typename CHBuilder::Hierarchy* hierarchy, - const bool havePermissions, const bool haveRestrictions) : - SUMOAbstractRouter("CHRouterClone", unbuildIsWarning, operation, nullptr, havePermissions, haveRestrictions), - myEdges(edges), - myForwardSearch(edges, true), - myBackwardSearch(edges, false), - myHierarchyBuilder(nullptr), - myHierarchy(hierarchy), - myWeightPeriod(SUMOTime_MAX), - myValidUntil(SUMOTime_MAX), - mySVC(svc) { - } - - /// Destructor - virtual ~CHRouter() { - if (myHierarchyBuilder != nullptr) { - delete myHierarchy; - delete myHierarchyBuilder; - } - } - - - virtual SUMOAbstractRouter* clone() { - if (myWeightPeriod == SUMOTime_MAX) { - // we only need one hierarchy - return new CHRouter(myEdges, this->myErrorMsgHandler == MsgHandler::getWarningInstance(), this->myOperation, - mySVC, myHierarchy, this->myHavePermissions, this->myHaveRestrictions); - } - return new CHRouter(myEdges, this->myErrorMsgHandler == MsgHandler::getWarningInstance(), this->myOperation, - mySVC, myWeightPeriod, this->myHavePermissions, this->myHaveRestrictions); - } - - /** @brief Builds the route between the given edges using the minimum traveltime in the contracted graph - * @note: since the contracted graph is static (weights averaged over time) - * the computed routes only approximated shortest paths in the real graph - * */ - virtual bool compute(const E* from, const E* to, const V* const vehicle, - SUMOTime msTime, std::vector& into, bool silent = false) { - assert(from != nullptr && to != nullptr); - // assert(myHierarchyBuilder.mySPTree->validatePermissions() || vehicle->getVClass() == mySVC || mySVC == SVC_IGNORING); - // do we need to rebuild the hierarchy? - if (msTime >= myValidUntil) { - assert(myHierarchyBuilder != nullptr); // only time independent clones do not have a builder - while (msTime >= myValidUntil) { - myValidUntil += myWeightPeriod; - } - delete myHierarchy; - myHierarchy = myHierarchyBuilder->buildContractionHierarchy(myValidUntil - myWeightPeriod, vehicle, this); - } - // ready for routing - this->startQuery(); - myForwardSearch.init(from, vehicle); - myBackwardSearch.init(to, vehicle); - double minTTSeen = std::numeric_limits::max(); - Meeting meeting(nullptr, nullptr); - bool continueForward = true; - bool continueBackward = true; - int num_visited_fw = 0; - int num_visited_bw = 0; - bool result = true; - while (continueForward || continueBackward) { - if (continueForward) { - continueForward = myForwardSearch.step(myHierarchy->forwardUplinks, myBackwardSearch, minTTSeen, meeting); - num_visited_fw += 1; - } - if (continueBackward) { - continueBackward = myBackwardSearch.step(myHierarchy->backwardUplinks, myForwardSearch, minTTSeen, meeting); - num_visited_bw += 1; - } - } - if (minTTSeen < std::numeric_limits::max()) { - buildPathFromMeeting(meeting, into); - } else { - if (!silent) { - this->myErrorMsgHandler->informf("No connection between edge '%' and edge '%' found.", from->getID(), to->getID()); - } - result = false; - } -#ifdef CHRouter_DEBUG_QUERY_PERF - std::cout << "visited " << num_visited_fw + num_visited_bw << " edges (" << num_visited_fw << "," << num_visited_bw << ") ,final path length: " + toString(into.size()) + ")\n"; -#endif - this->endQuery(num_visited_bw + num_visited_fw); - return result; - } - - /// normal routing methods - - /// Builds the path from marked edges - void buildPathFromMeeting(Meeting meeting, std::vector& into) const { - std::deque tmp; - const auto* backtrack = meeting.first; - while (backtrack != 0) { - tmp.push_front((E*) backtrack->edge); // !!! - backtrack = backtrack->prev; - } - backtrack = meeting.second->prev; // don't use central edge twice - while (backtrack != 0) { - tmp.push_back((E*) backtrack->edge); // !!! - backtrack = backtrack->prev; - } - // expand shortcuts - const E* prev = 0; - while (!tmp.empty()) { - const E* cur = tmp.front(); - tmp.pop_front(); - if (prev == 0) { - into.push_back(cur); - prev = cur; - } else { - const E* via = getVia(prev, cur); - if (via == 0) { - into.push_back(cur); - prev = cur; - } else { - tmp.push_front(cur); - tmp.push_front(via); - } - } - } - } - -private: - // retrieve the via edge for a shortcut - const E* getVia(const E* forwardFrom, const E* forwardTo) const { - typename CHBuilder::ConstEdgePair forward(forwardFrom, forwardTo); - typename CHBuilder::ShortcutVia::const_iterator it = myHierarchy->shortcuts.find(forward); - if (it != myHierarchy->shortcuts.end()) { - return it->second; - } else { - return 0; - } - } - - -private: - /// @brief all edges with numerical ids - const std::vector& myEdges; - - /// @brief the unidirectional search queues - Unidirectional myForwardSearch; - Unidirectional myBackwardSearch; - - CHBuilder* myHierarchyBuilder; - const typename CHBuilder::Hierarchy* myHierarchy; - - /// @brief the validity duration of one weight interval - const SUMOTime myWeightPeriod; - - /// @brief the validity duration of the current hierarchy (exclusive) - SUMOTime myValidUntil; - - /// @brief the permissions for which the hierarchy was constructed - const SUMOVehicleClass mySVC; -}; diff --git a/Util/OSM2ODR/src/utils/router/CHRouterWrapper.h b/Util/OSM2ODR/src/utils/router/CHRouterWrapper.h deleted file mode 100644 index 711e62e84..000000000 --- a/Util/OSM2ODR/src/utils/router/CHRouterWrapper.h +++ /dev/null @@ -1,123 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file CHRouterWrapper.h -/// @author Jakob Erdmann -/// @author Laura Bieker -/// @author Michael Behrisch -/// @date March 2012 -/// -// Wraps multiple CHRouters for different vehicle types -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "CHRouter.h" - -#ifdef HAVE_FOX -#include -#endif - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class CHRouterWrapper - * @brief Computes the shortest path through a contracted network - * - * The template parameters are: - * @param E The edge class to use (MSEdge/ROEdge) - * @param V The vehicle class to use (MSVehicle/ROVehicle) - * - * The router is edge-based. It must know the number of edges for internal reasons - * and whether a missing connection between two given edges (unbuild route) shall - * be reported as an error or as a warning. - * - */ -template -class CHRouterWrapper: public SUMOAbstractRouter { - -public: - /** @brief Constructor - */ - CHRouterWrapper(const std::vector& edges, const bool ignoreErrors, typename SUMOAbstractRouter::Operation operation, - const SUMOTime begin, const SUMOTime end, const SUMOTime weightPeriod, const int numThreads) : - SUMOAbstractRouter("CHRouterWrapper", ignoreErrors, operation, nullptr, false, false), - myEdges(edges), - myIgnoreErrors(ignoreErrors), - myBegin(begin), - myEnd(end), - myWeightPeriod(weightPeriod), - myMaxNumInstances(numThreads) { - } - - ~CHRouterWrapper() { - for (typename RouterMap::iterator i = myRouters.begin(); i != myRouters.end(); ++i) { - delete i->second; - } - } - - - virtual SUMOAbstractRouter* clone() { - CHRouterWrapper* clone = new CHRouterWrapper(myEdges, myIgnoreErrors, this->myOperation, myBegin, myEnd, myWeightPeriod, myMaxNumInstances); - for (const auto& item : myRouters) { - clone->myRouters[item.first] = static_cast(item.second->clone()); - } - return clone; - } - - - bool compute(const E* from, const E* to, const V* const vehicle, - SUMOTime msTime, std::vector& into, bool silent = false) { - const std::pair svc = std::make_pair(vehicle->getVClass(), vehicle->getMaxSpeed()); - if (myRouters.count(svc) == 0) { - // create new router for the given permissions and maximum speed - // XXX a new router may also be needed if vehicles differ in speed factor - myRouters[svc] = new CHRouterType( - myEdges, myIgnoreErrors, &E::getTravelTimeStatic, svc.first, myWeightPeriod, false, false); - } - return myRouters[svc]->compute(from, to, vehicle, msTime, into, silent); - } - - -private: - typedef CHRouter CHRouterType; - -private: - typedef std::map, CHRouterType*> RouterMap; - - RouterMap myRouters; - - /// @brief all edges with numerical ids - const std::vector& myEdges; - - const bool myIgnoreErrors; - - const SUMOTime myBegin; - const SUMOTime myEnd; - const SUMOTime myWeightPeriod; - const int myMaxNumInstances; -}; diff --git a/Util/OSM2ODR/src/utils/router/CMakeLists.txt b/Util/OSM2ODR/src/utils/router/CMakeLists.txt deleted file mode 100644 index 80be35019..000000000 --- a/Util/OSM2ODR/src/utils/router/CMakeLists.txt +++ /dev/null @@ -1,33 +0,0 @@ -set(utils_router_STAT_SRCS - AStarLookupTable.h - AStarRouter.h - AccessEdge.h - CarEdge.h - PedestrianEdge.h - PublicTransportEdge.h - StopEdge.h - CHBuilder.h - CHRouter.h - CHRouterWrapper.h - DijkstraRouter.h - IntermodalEdge.h - IntermodalNetwork.h - IntermodalRouter.h - IntermodalTrip.h - RailwayRouter.h - RailEdge.h - EffortCalculator.h - GawronCalculator.h - LogitCalculator.h - RouteCostCalculator.h - PedestrianRouter.h - RouterProvider.h - SUMOAbstractRouter.h - SPTree.h - FareModul.h - FareToken.h - FareZones.h) - -if (MSVC) - add_custom_target(z_utils_router SOURCES ${utils_router_STAT_SRCS}) -endif() diff --git a/Util/OSM2ODR/src/utils/router/CarEdge.h b/Util/OSM2ODR/src/utils/router/CarEdge.h deleted file mode 100644 index f69c57c6a..000000000 --- a/Util/OSM2ODR/src/utils/router/CarEdge.h +++ /dev/null @@ -1,147 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file CarEdge.h -/// @author Michael Behrisch -/// @date Mon, 03 March 2014 -/// -// The CarEdge is a special intermodal edge representing the SUMO network edge -/****************************************************************************/ -#pragma once -#include - -#ifdef HAVE_FOX -#include -#endif -#include "IntermodalEdge.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -/// @brief the car edge type that is given to the internal router (SUMOAbstractRouter) -template -class CarEdge : public IntermodalEdge { -private: - typedef IntermodalEdge _IntermodalEdge; - -public: - CarEdge(int numericalID, const E* edge, const double pos = -1.) : - _IntermodalEdge(edge->getID() + "_car" + toString(pos), numericalID, edge, "!car"), - myStartPos(pos >= 0 ? pos : 0.) { } - - bool includeInRoute(bool /* allEdges */) const { - return true; - } - - const std::vector<_IntermodalEdge*>& getSuccessors(SUMOVehicleClass vClass = SVC_IGNORING) const { - if (vClass == SVC_IGNORING) { - return this->myFollowingEdges; - } -#ifdef HAVE_FOX - FXMutexLock locker(myLock); -#endif - typename std::map >::const_iterator i = myClassesSuccessorMap.find(vClass); - if (i != myClassesSuccessorMap.end()) { - // can use cached value - return i->second; - } else { - // this vClass is requested for the first time. rebuild all successors - const std::set classedCarFollowers = std::set(this->getEdge()->getSuccessors(vClass).begin(), this->getEdge()->getSuccessors(vClass).end()); - for (_IntermodalEdge* const e : this->myFollowingEdges) { - if (!e->includeInRoute(false) || e->getEdge() == this->getEdge() || classedCarFollowers.count(e->getEdge()) > 0) { - myClassesSuccessorMap[vClass].push_back(e); - } - } - return myClassesSuccessorMap[vClass]; - } - } - - virtual const std::vector >& getViaSuccessors(SUMOVehicleClass vClass = SVC_IGNORING) const { - if (vClass == SVC_IGNORING) { - return this->myFollowingViaEdges; - } -#ifdef HAVE_FOX - FXMutexLock locker(myLock); -#endif - typename std::map > >::const_iterator i = myClassesViaSuccessorMap.find(vClass); - if (i != myClassesViaSuccessorMap.end()) { - // can use cached value - return i->second; - } else { - // this vClass is requested for the first time. rebuild all successors - std::set classedCarFollowers; - for (const auto& pair : this->getEdge()->getViaSuccessors(vClass)) { - classedCarFollowers.insert(pair.first); - } - for (const std::pair& e : this->myFollowingViaEdges) { - if (!e.first->includeInRoute(false) || e.first->getEdge() == this->getEdge() || classedCarFollowers.count(e.first->getEdge()) > 0) { - myClassesViaSuccessorMap[vClass].push_back(e); - } - } - return myClassesViaSuccessorMap[vClass]; - } - } - - bool prohibits(const IntermodalTrip* const trip) const { - return trip->vehicle == 0 || this->getEdge()->prohibits(trip->vehicle); - } - - double getTravelTime(const IntermodalTrip* const trip, double time) const { - assert(E::getTravelTimeStatic(this->getEdge(), trip->vehicle, time) >= 0.); - return getPartialTravelTime(E::getTravelTimeStatic(this->getEdge(), trip->vehicle, time), trip); - } - - double getTravelTimeAggregated(const IntermodalTrip* const trip, double time) const { - assert(E::getTravelTimeAggregated(this->getEdge(), trip->vehicle, time) >= 0.); - return getPartialTravelTime(E::getTravelTimeAggregated(this->getEdge(), trip->vehicle, time), trip); - } - - double getStartPos() const { - return myStartPos; - } - - double getEndPos() const { - return myStartPos + this->getLength(); - } - -private: - - inline double getPartialTravelTime(double fullTravelTime, const IntermodalTrip* const trip) const { - double distTravelled = this->getLength(); - // checking arrivalPos first to have it correct for identical depart and arrival edge - if (this->getEdge() == trip->to && trip->arrivalPos >= myStartPos && trip->arrivalPos < myStartPos + this->getLength()) { - distTravelled = trip->arrivalPos - myStartPos; - } - if (this->getEdge() == trip->from && trip->departPos >= myStartPos && trip->departPos < myStartPos + this->getLength()) { - distTravelled -= trip->departPos - myStartPos; - } - assert(fullTravelTime * distTravelled / this->getEdge()->getLength() >= 0.); - return fullTravelTime * distTravelled / this->getEdge()->getLength(); - } - -private: - /// @brief the starting position for split edges - const double myStartPos; - - /// @brief The successors available for a given vClass - mutable std::map > myClassesSuccessorMap; - - /// @brief The successors available for a given vClass - mutable std::map > > myClassesViaSuccessorMap; - -#ifdef HAVE_FOX - /// The mutex used to avoid concurrent updates of myClassesSuccessorMap - mutable FXMutex myLock; -#endif -}; diff --git a/Util/OSM2ODR/src/utils/router/DijkstraRouter.h b/Util/OSM2ODR/src/utils/router/DijkstraRouter.h deleted file mode 100644 index 774eb27bb..000000000 --- a/Util/OSM2ODR/src/utils/router/DijkstraRouter.h +++ /dev/null @@ -1,287 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file DijkstraRouter.h -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date Mon, 25 July 2005 -/// -// Dijkstra shortest path algorithm using travel time or other values -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "EffortCalculator.h" -#include "SUMOAbstractRouter.h" - -//#define DijkstraRouter_DEBUG_QUERY -//#define DijkstraRouter_DEBUG_QUERY_PERF - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class DijkstraRouter - * @brief Computes the shortest path through a network using the Dijkstra algorithm. - * - * The template parameters are: - * @param E The edge class to use (MSEdge/ROEdge) - * @param V The vehicle class to use (MSVehicle/ROVehicle) - * - * The router is edge-based. It must know the number of edges for internal reasons - * and whether a missing connection between two given edges (unbuild route) shall - * be reported as an error or as a warning. - * - */ -template -class DijkstraRouter : public SUMOAbstractRouter { -public: - /** - * @class EdgeInfoByEffortComparator - * Class to compare (and so sort) nodes by their effort - */ - class EdgeInfoByEffortComparator { - public: - /// Comparing method - bool operator()(const typename SUMOAbstractRouter::EdgeInfo* nod1, const typename SUMOAbstractRouter::EdgeInfo* nod2) const { - if (nod1->effort == nod2->effort) { - return nod1->edge->getNumericalID() > nod2->edge->getNumericalID(); - } - return nod1->effort > nod2->effort; - } - }; - - - /// Constructor - DijkstraRouter(const std::vector& edges, bool unbuildIsWarning, typename SUMOAbstractRouter::Operation effortOperation, - typename SUMOAbstractRouter::Operation ttOperation = nullptr, bool silent = false, EffortCalculator* calc = nullptr, - const bool havePermissions = false, const bool haveRestrictions = false) : - SUMOAbstractRouter("DijkstraRouter", unbuildIsWarning, effortOperation, ttOperation, havePermissions, haveRestrictions), - mySilent(silent), myExternalEffort(calc) { - for (typename std::vector::const_iterator i = edges.begin(); i != edges.end(); ++i) { - myEdgeInfos.push_back(typename SUMOAbstractRouter::EdgeInfo(*i)); - } - } - - /// Destructor - virtual ~DijkstraRouter() { } - - virtual SUMOAbstractRouter* clone() { - auto clone = new DijkstraRouter(myEdgeInfos, this->myErrorMsgHandler == MsgHandler::getWarningInstance(), - this->myOperation, this->myTTOperation, mySilent, myExternalEffort, - this->myHavePermissions, this->myHaveRestrictions); - clone->setAutoBulkMode(this->myAutoBulkMode); - return clone; - } - - void init() { - // all EdgeInfos touched in the previous query are either in myFrontierList or myFound: clean those up - for (auto& edgeInfo : myFrontierList) { - edgeInfo->reset(); - } - myFrontierList.clear(); - for (auto& edgeInfo : myFound) { - edgeInfo->reset(); - } - myFound.clear(); - } - - - /** @brief Builds the route between the given edges using the minimum effort at the given time - The definition of the effort depends on the wished routing scheme */ - bool compute(const E* from, const E* to, const V* const vehicle, - SUMOTime msTime, std::vector& into, bool silent = false) { - assert(from != nullptr && (vehicle == nullptr || to != nullptr)); - // check whether from and to can be used - if (myEdgeInfos[from->getNumericalID()].prohibited || this->isProhibited(from, vehicle)) { - if (!silent) { - this->myErrorMsgHandler->inform("Vehicle '" + Named::getIDSecure(vehicle) + "' is not allowed on source edge '" + from->getID() + "'."); - } - return false; - } - if (to != nullptr && (myEdgeInfos[to->getNumericalID()].prohibited || this->isProhibited(to, vehicle))) { - if (!silent) { - this->myErrorMsgHandler->inform("Vehicle '" + Named::getIDSecure(vehicle) + "' is not allowed on destination edge '" + to->getID() + "'."); - } - return false; - } - double length = 0.; // dummy for the via edge cost update - this->startQuery(); -#ifdef DijkstraRouter_DEBUG_QUERY - std::cout << "DEBUG: starting search for '" << Named::getIDSecure(vehicle) << "' time: " << STEPS2TIME(msTime) << "\n"; -#endif - const SUMOVehicleClass vClass = vehicle == nullptr ? SVC_IGNORING : vehicle->getVClass(); - std::tuple query = std::make_tuple(from, vehicle, msTime); - if (this->myBulkMode || (this->myAutoBulkMode && query == myLastQuery)) { - const auto& toInfo = myEdgeInfos[to->getNumericalID()]; - if (toInfo.visited) { - buildPathFrom(&toInfo, into); - this->endQuery(1); - return true; - } - } else { - init(); - // add begin node - auto* const fromInfo = &(myEdgeInfos[from->getNumericalID()]); - fromInfo->effort = 0.; - fromInfo->prev = nullptr; - fromInfo->leaveTime = STEPS2TIME(msTime); - if (myExternalEffort != nullptr) { - myExternalEffort->setInitialState(fromInfo->edge->getNumericalID()); - } - myFrontierList.push_back(fromInfo); - } - myLastQuery = query; - // loop - int num_visited = 0; - while (!myFrontierList.empty()) { - num_visited += 1; - // use the node with the minimal length - auto* const minimumInfo = myFrontierList.front(); - const E* const minEdge = minimumInfo->edge; -#ifdef DijkstraRouter_DEBUG_QUERY - std::cout << "DEBUG: hit '" << minEdge->getID() << "' Eff: " << minimumInfo->effort << ", Leave: " << minimumInfo->leaveTime << " Q: "; - for (auto& it : myFrontierList) { - std::cout << it->effort << "," << it->edge->getID() << " "; - } - std::cout << "\n"; -#endif - // check whether the destination node was already reached - if (minEdge == to) { - //propagate last external effort state to destination edge - if (myExternalEffort != nullptr) { - myExternalEffort->update(minEdge->getNumericalID(), minimumInfo->prev->edge->getNumericalID(), minEdge->getLength()); - } - buildPathFrom(minimumInfo, into); - this->endQuery(num_visited); -#ifdef DijkstraRouter_DEBUG_QUERY_PERF - std::cout << "visited " + toString(num_visited) + " edges (final path length=" + toString(into.size()) + " edges=" + toString(into) + ")\n"; -#endif - return true; - } - std::pop_heap(myFrontierList.begin(), myFrontierList.end(), myComparator); - myFrontierList.pop_back(); - myFound.push_back(minimumInfo); - minimumInfo->visited = true; - const double effortDelta = this->getEffort(minEdge, vehicle, minimumInfo->leaveTime); - const double leaveTime = minimumInfo->leaveTime + this->getTravelTime(minEdge, vehicle, minimumInfo->leaveTime, effortDelta); - if (myExternalEffort != nullptr) { - myExternalEffort->update(minEdge->getNumericalID(), minimumInfo->prev->edge->getNumericalID(), minEdge->getLength()); - } - // check all ways from the node with the minimal length - for (const std::pair& follower : minEdge->getViaSuccessors(vClass)) { - auto* const followerInfo = &(myEdgeInfos[follower.first->getNumericalID()]); - // check whether it can be used - if (followerInfo->prohibited || this->isProhibited(follower.first, vehicle)) { - continue; - } - double effort = minimumInfo->effort + effortDelta; - double time = leaveTime; - this->updateViaEdgeCost(follower.second, vehicle, time, effort, length); - assert(effort >= minimumInfo->effort); - assert(time >= minimumInfo->leaveTime); - const double oldEffort = followerInfo->effort; - if (!followerInfo->visited && effort < oldEffort) { - followerInfo->effort = effort; - followerInfo->leaveTime = time; - followerInfo->prev = minimumInfo; - if (oldEffort == std::numeric_limits::max()) { - myFrontierList.push_back(followerInfo); - std::push_heap(myFrontierList.begin(), myFrontierList.end(), myComparator); - } else { - std::push_heap(myFrontierList.begin(), - std::find(myFrontierList.begin(), myFrontierList.end(), followerInfo) + 1, - myComparator); - } - } - } - } - this->endQuery(num_visited); -#ifdef DijkstraRouter_DEBUG_QUERY_PERF - std::cout << "visited " + toString(num_visited) + " edges (unsuccessful path length: " + toString(into.size()) + ")\n"; -#endif - if (to != nullptr && !mySilent && !silent) { - this->myErrorMsgHandler->informf("No connection between edge '%' and edge '%' found.", from->getID(), to->getID()); - } - return false; - } - - - void prohibit(const std::vector& toProhibit) { - for (E* const edge : this->myProhibited) { - myEdgeInfos[edge->getNumericalID()].prohibited = false; - } - for (E* const edge : toProhibit) { - myEdgeInfos[edge->getNumericalID()].prohibited = true; - } - this->myProhibited = toProhibit; - } - - - /// Builds the path from marked edges - void buildPathFrom(const typename SUMOAbstractRouter::EdgeInfo* rbegin, std::vector& edges) { - std::vector tmp; - while (rbegin != 0) { - tmp.push_back(rbegin->edge); - rbegin = rbegin->prev; - } - std::copy(tmp.rbegin(), tmp.rend(), std::back_inserter(edges)); - } - - const typename SUMOAbstractRouter::EdgeInfo& getEdgeInfo(int index) const { - return myEdgeInfos[index]; - } - -private: - DijkstraRouter(const std::vector::EdgeInfo>& edgeInfos, bool unbuildIsWarning, - typename SUMOAbstractRouter::Operation effortOperation, typename SUMOAbstractRouter::Operation ttOperation, bool silent, EffortCalculator* calc, - const bool havePermissions, const bool haveRestrictions) : - SUMOAbstractRouter("DijkstraRouter", unbuildIsWarning, effortOperation, ttOperation, havePermissions, haveRestrictions), - mySilent(silent), - myExternalEffort(calc) { - for (const auto& edgeInfo : edgeInfos) { - myEdgeInfos.push_back(typename SUMOAbstractRouter::EdgeInfo(edgeInfo.edge)); - } - } - -private: - /// @brief whether to suppress warning/error if no route was found - bool mySilent; - - /// cache of the last query to enable automated bulk routing - std::tuple myLastQuery; - - EffortCalculator* const myExternalEffort; - - /// The container of edge information - std::vector::EdgeInfo> myEdgeInfos; - - /// A container for reusage of the min edge heap - std::vector::EdgeInfo*> myFrontierList; - /// @brief list of visited Edges (for resetting) - std::vector::EdgeInfo*> myFound; - - EdgeInfoByEffortComparator myComparator; -}; diff --git a/Util/OSM2ODR/src/utils/router/EffortCalculator.h b/Util/OSM2ODR/src/utils/router/EffortCalculator.h deleted file mode 100644 index e47b7c704..000000000 --- a/Util/OSM2ODR/src/utils/router/EffortCalculator.h +++ /dev/null @@ -1,52 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file EffortCalculator.h -/// @author Michael Behrisch -/// @date 2018-08-21 -/// -// The EffortCalculator is an interface for additional edge effort calculators -/****************************************************************************/ -#pragma once -#include - -#include - - -// =========================================================================== -// class definitions -// =========================================================================== -/// @brief the effort calculator interface -class EffortCalculator { - -public: - - /** Pass the set of all edges in the routing query to the effortCalculator **/ - virtual void init(const std::vector& edges) = 0; - - /** Add information about stops **/ - virtual void addStop(const int stopEdge, const Parameterised& params) = 0; - - /** Return the effort of a given edge **/ - virtual double getEffort(const int numericalID) const = 0; - - /** Update the effort of the edge **/ - virtual void update(const int edge, const int prev, const double length) = 0; - - /** Set the effort of the first edge in the query to zero **/ - virtual void setInitialState(const int edge) = 0; - - /** basic output facility to inform about effort at this edge **/ - virtual std::string output(const int edge) const = 0; - -}; diff --git a/Util/OSM2ODR/src/utils/router/FareModul.h b/Util/OSM2ODR/src/utils/router/FareModul.h deleted file mode 100644 index 630ef76c5..000000000 --- a/Util/OSM2ODR/src/utils/router/FareModul.h +++ /dev/null @@ -1,558 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2002-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file FareModul.h -/// @author Ricardo Euler -/// @date Thu, 17 August 2018 -/// -// Fare Modul for calculating prices during intermodal routing -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include -#include "EffortCalculator.h" -#include "FareToken.h" -#include "FareZones.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -class ZoneCounter { -public: - - explicit ZoneCounter(unsigned int ct) : - myCount(ct) { - - } - - inline void addZone(int zoneNumber) { - zoneNumber = getOverlayZone(zoneNumber); - if (zoneNumber == 0) { - return; - } - long long int repNum = fareZoneToRep[zoneNumber]; - //assert power of 2 - if (bitcount(repNum) == 0) { - return; - } - myCount = myCount | repNum; - } - - - int numZones() const { - return bitcount(myCount); - } - - -private: - inline int bitcount(long long int intVal) const { - int count = 0; - long long int counter = intVal; - - while (counter != 0) { - counter = counter & (counter - 1); - ++count; - } - return count; - } - -private: - long long int myCount; - - -}; - - - -/** - * A fare state collects all the information that is necessary to compute the price. Is used as an edge label - * in IntermodalRouter - */ -struct FareState { - friend class FareModul; - -public: - - /** default constructor for unlabeled edges**/ - explicit FareState(): - myFareToken(FareToken::None), - myCounter(std::numeric_limits::max()), - myTravelledDistance(std::numeric_limits::max()), - myVisistedStops(std::numeric_limits::max()), - myPriceDiff(0) { - }; - - /** - * - * @param token - */ - explicit FareState(FareToken token): - myFareToken(token), - myCounter(0), - myTravelledDistance(0), - myVisistedStops(0), - myPriceDiff(0) {} - - /** Destructor **/ - ~FareState() = default; - - /** - * returns true if fare state is set and not on default - * @return if state is set - */ - bool isValid() const { - return !(myFareToken == FareToken::None); - } - -private: - - /** fare token **/ - FareToken myFareToken; - /** zone counter **/ - ZoneCounter myCounter; - /** travelled distance in km**/ - double myTravelledDistance; - /**num of visited stops**/ - int myVisistedStops; - /** price diff to previous edge **/ - double myPriceDiff; - -}; - - - -struct Prices { - - - - /** Prices for zones **/ - std::vector zonePrices = std::vector {1.9, 3.4, 4.9, 6.2, 7.7, 9.2}; - double halle = 2.3; - double leipzig = 2.7; - double t1 = 1.5; - double t2 = 1.6; - double t3 = 1.6; - double shortTrip = 1.6; - double shortTripLeipzig = 1.9; - double shortTripHalle = 1.7; - double maxPrice = 10.6; -}; - - -/** - * The fare modul responsible for calculating prices - */ -class FareModul : public EffortCalculator { -public: - - /** Constructor ***/ - FareModul() : - myFareStates() - {}; - - /**Implementation of EffortCalculator **/ - void init(const std::vector& edges) override { - myEdges = edges; - myFareStates.resize(edges.size()); - } - - void addStop(const int stopEdge, const Parameterised& params) override { - myStopFareZone[stopEdge] = StringUtils::toInt(params.getParameter("fareZone")); - myStopFareToken[stopEdge] = FareUtil::stringToToken(params.getParameter("fareToken")); - myStopStartToken[stopEdge] = FareUtil::stringToToken(params.getParameter("startToken")); - } - - /**Implementation of EffortCalculator **/ - double getEffort(const int numericalID) const override { - double effort = 0; - FareState const& state = myFareStates.at(numericalID); - if (state.isValid()) { - effort = state.myPriceDiff; - } else { - effort = std::numeric_limits::max(); - } - return effort; - } - - /** Implementation of EffortCalculator **/ - void update(const int edge, const int prev, const double length) override { - - std::string const& edgeType = myEdges[edge]; - - //get propagated fare state - FareState& state = myFareStates.at(prev); - - double oldPr; - if (state.myFareToken == FareToken::START) { - oldPr = 0; - } else { - oldPr = computePrice(state); - } - //treat public transport edges - if (edgeType.c_str()[0] != '!') { - updateFareStatePublic(state, edge, length); - } else if (edgeType == "!stop") { - updateFareStateStop(state, edge); - } else if (edgeType == "!ped") { - updateFareStatePedestrian(state, edge); - } else if (edgeType == "!access") { - updateFareStateAccess(state, edge, prev); - } else { - updateFareState(state, edge); - } - FareState& stateAtE = myFareStates[edge]; - double newPr = computePrice(stateAtE); - stateAtE.myPriceDiff = newPr - oldPr; - - assert(stateAtE.myPriceDiff >= 0); - - } - - /** Implementation of EffortCalculator - * _IntermodalEdge should be an Connector Edge **/ - void setInitialState(const int edge) override { -// assert( edge->getLine() == "!connector"); - - myFareStates[edge] = FareState(FareToken::START); - - } - - -private: - /** List of all fare states **/ - std::vector myFareStates; - - /** List of all edge line attributes **/ - std::vector myEdges; - - /** the fare zone this stop is a part of **/ - std::map myStopFareZone; - - /** the faretoken that can be collected at this station **/ - std::map myStopFareToken; - - /** the faretoken that is used when a trip is started at this station **/ - std::map myStopStartToken; - - /** List of the prices **/ - Prices prices; - - double computePrice(FareState const& fareState) const { - switch (fareState.myFareToken) { - case FareToken ::H: - return prices.halle; - case FareToken ::L: - return prices.leipzig; - case FareToken ::T1: - return prices.t1; - case FareToken ::T2: - return prices.t2; - case FareToken ::T3: - return prices.t3; - case FareToken::U: - return prices.zonePrices[0]; - case FareToken ::Z: - return prices.zonePrices[fareState.myCounter.numZones() - 1]; - case FareToken ::M: - return prices.maxPrice; - case FareToken ::K: - return prices.shortTrip; - case FareToken ::KL: - case FareToken ::KLZ: - case FareToken ::KLU: - return prices.shortTripLeipzig; - case FareToken ::KH: - case FareToken ::KHU: - case FareToken ::KHZ: - return prices.shortTripHalle; - case FareToken::Free: - return 1.4; - case FareToken ::START: - return 0; - case FareToken::ZU: - case FareToken::None: - assert(false); - - } - return std::numeric_limits::max(); - } - - - - std::string output(const int edge) const override { - - FareState const& my = myFareStates[edge]; - std::stringstream msg; - /* - msg << "Final fare state at edge of type: " << myEdges[edge] << std::endl; - msg << "Faretoken" << FareUtil::tokenToString(my.myFareToken) << std::endl; - msg << "Price:" << computePrice(my) << std::endl; - msg << "Zones " << my.myCounter.numZones() << std::endl; - msg << "Stations: " << my.myVisistedStops << std::endl; - msg << "Distance:" << my.myTravelledDistance << std::endl; - */ - msg << FareUtil::tokenToTicket(my.myFareToken) << " "; - if (my.myFareToken == FareToken::Z) { - msg << my.myCounter.numZones() << " "; - if (my.myCounter.numZones() == 1) { - msg << "Zone"; - } else { - msg << "Zonen"; - } - - } else if (my.myFareToken == FareToken::U) { - msg << my.myCounter.numZones() << "1 Zone"; - - } - msg << ":" << computePrice(my); - return msg.str(); - } - - void updateFareStateStop(FareState const& currentFareState, const int stopEdge) { - - FareToken collectedToken = myStopFareToken[stopEdge]; - - //if station has no fare information, just propagate - if (collectedToken == FareToken::None) { - std::cout << "Progagating fare state for stop w/o a price!" << std::endl; - return; - } - - FareToken const& token = currentFareState.myFareToken; - - FareState& stateAtE = myFareStates[stopEdge]; - - stateAtE = currentFareState; - - stateAtE.myCounter.addZone(myStopFareZone[stopEdge]); - - stateAtE.myVisistedStops++; - - switch (token) { - case FareToken ::Free: - stateAtE.myFareToken = myStopStartToken[stopEdge]; - break; - case FareToken::M : - break; - - case FareToken::Z : - if (stateAtE.myCounter.numZones() > 6) { - stateAtE.myFareToken = FareToken::M; - } - break; - - case FareToken::T1 : - case FareToken::T2 : - case FareToken::T3 : - if (collectedToken == FareToken::Z) { - stateAtE.myFareToken = stateAtE.myTravelledDistance <= 4000 ? FareToken::K : FareToken::Z; - } - break; - case FareToken::U : - if (collectedToken == FareToken::H) { - stateAtE.myFareToken = FareToken::H; - } - if (collectedToken == FareToken::L) { - stateAtE.myFareToken = FareToken::L; - } - if (collectedToken == FareToken::Z) { - stateAtE.myFareToken = FareToken::Z; - } - break; - case FareToken::H: - case FareToken::L: - if (collectedToken == FareToken::Z) { - stateAtE.myFareToken = FareToken::Z; - } - break; - case FareToken::KH: - if (stateAtE.myVisistedStops <= 4) { - if (collectedToken == FareToken::U) { - stateAtE.myFareToken = FareToken::KHU; - } - if (collectedToken == FareToken::Z) { - stateAtE.myFareToken = FareToken::KHZ; - } - } else { - if (collectedToken == FareToken::H) { - stateAtE.myFareToken = FareToken ::H; - } - if (collectedToken == FareToken::Z) { - stateAtE.myFareToken = FareToken ::Z; - } - if (collectedToken == FareToken::U) { - stateAtE.myFareToken = FareToken ::U; - } - } - break; - case FareToken::KL: - if (stateAtE.myVisistedStops <= 4) { - if (collectedToken == FareToken::U) { - stateAtE.myFareToken = FareToken::KLU; - } - if (collectedToken == FareToken::Z) { - stateAtE.myFareToken = FareToken::KLZ; - } - } else { - if (collectedToken == FareToken::L) { - stateAtE.myFareToken = FareToken ::L; - } - if (collectedToken == FareToken::Z) { - stateAtE.myFareToken = FareToken ::Z; - } - if (collectedToken == FareToken::U) { - stateAtE.myFareToken = FareToken ::U; - } - } - break; - case FareToken::K: - if (stateAtE.myTravelledDistance > 4000) { - if (collectedToken == FareToken::U) { - stateAtE.myFareToken = FareToken ::U; - } - if (collectedToken == FareToken::Z) { - stateAtE.myFareToken = FareToken ::Z; - } - } - break; - case FareToken::KHU : - case FareToken::KLU : - if (stateAtE.myVisistedStops > 4) { - if (collectedToken == FareToken::U) { - stateAtE.myFareToken = FareToken::U; - } - } - break; - - case FareToken::KLZ: - case FareToken::KHZ: - if (stateAtE.myVisistedStops > 4) { - if (collectedToken == FareToken::Z) { - stateAtE.myFareToken = FareToken::Z; - } - } - break; - case FareToken::ZU : - assert(false); - if (collectedToken == FareToken::U) { - stateAtE.myFareToken = FareToken::U; - } else { - stateAtE.myFareToken = FareToken::Z; - } - - break; - default: - std::cout << "Reached invalid position in fareToken selection!" << std::endl; - assert(false); - break; - } - } - - void updateFareStatePedestrian(FareState const& currentFareState, const int pedestrianEdge) { - - //only propagates the fare state - FareState& stateAtE = myFareStates[pedestrianEdge]; - - stateAtE = currentFareState; - - if (currentFareState.myFareToken == FareToken::START) { - stateAtE.myFareToken = FareToken::Free; - } - - } - - - void updateFareStatePublic(FareState const& currentFareState, const int publicTransportEdge, const double length) { - - - if (currentFareState.myFareToken == FareToken::None) { - return; - } - - FareState& stateAtE = myFareStates[publicTransportEdge]; - - stateAtE = currentFareState; - stateAtE.myTravelledDistance += length; - } - - void updateFareState(FareState const& currentFareState, const int intermodalEdge) { - - if (currentFareState.myFareToken == FareToken::None) { - return; - } - - FareState& stateAtE = myFareStates[intermodalEdge]; - - stateAtE = currentFareState; - - if (currentFareState.myFareToken == FareToken::START) { - stateAtE.myFareToken = FareToken::Free; - } - - } - - void updateFareStateAccess(FareState const& currentFareState, const int accessEdge, const int prev) { - - FareToken const& token = currentFareState.myFareToken; - - FareState& stateAtE = myFareStates[accessEdge]; - - stateAtE = currentFareState; - - if (currentFareState.myFareToken == FareToken::START) { - stateAtE.myFareToken = FareToken::Free; - } - - if (myEdges[prev] == "!ped") { - switch (token) { - - case FareToken::Free ://we have not yet taken public transport - break; - case FareToken::K : - if (currentFareState.myCounter.numZones() == 0) { - stateAtE.myFareToken = FareToken::U; - } else { - stateAtE.myFareToken = FareToken::Z; - } - break; - case FareToken::KH : - stateAtE.myFareToken = FareToken::H; - break; - case FareToken::KL : - stateAtE.myFareToken = FareToken::L; - break; - case FareToken::KLU : - stateAtE.myFareToken = FareToken::L; - break; - case FareToken::KHU: - stateAtE.myFareToken = FareToken::H; - break; - case FareToken::KLZ : - stateAtE.myFareToken = FareToken::Z; - break; - case FareToken::KHZ: - stateAtE.myFareToken = FareToken::Z; - break; - default: - return; - } - } - - } -}; - - diff --git a/Util/OSM2ODR/src/utils/router/FareToken.h b/Util/OSM2ODR/src/utils/router/FareToken.h deleted file mode 100644 index 2c13c7b89..000000000 --- a/Util/OSM2ODR/src/utils/router/FareToken.h +++ /dev/null @@ -1,207 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2002-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file FareToken.h -/// @author Ricardo Euler -/// @date Thu, 17 August 2018 -/// -// Fare Modul for calculating prices during intermodal routing -/****************************************************************************/ - -#pragma once -enum class FareToken : int { - None = 0, - Free = 1, // walking and other things can be free - H = 2, - L = 3, - T1 = 4, - T2 = 5, - T3 = 6, - Z = 7, - M = 8, - U = 9, - KL = 10, - KH = 11, - K = 12, - KHU = 13, - KLU = 14, - KHZ = 15, - KLZ = 16, - ZU = 17, //Artificial state for after leaving short trip khu or klu since a pedestrian edge does not allow us - //to distinguish between z or u zones - START = 18 - -}; - -namespace FareUtil { - -inline std::string tokenToString(FareToken const& token) { - switch (token) { - case FareToken::H: - return "H"; - case FareToken::L: - return "L"; - case FareToken::T1: - return "T1"; - case FareToken::T2: - return "T2"; - case FareToken::T3: - return "T3"; - case FareToken::U: - return "U"; - case FareToken::Z: - return "Z"; - case FareToken::M: - return "M"; - case FareToken::K: - return "K"; - case FareToken::KL: - return "KL"; - case FareToken::KH: - return "KH"; - case FareToken::ZU: - return "ZU"; - case FareToken::None: - return "None"; - case FareToken::Free: - return "Free"; - case FareToken::KHU: - return "KHU"; - case FareToken::KLU: - return "KLU"; - case FareToken ::KHZ: - return "KHZ"; - case FareToken ::KLZ: - return "KLZ"; - default: - return ""; - } -} - - -inline std::string tokenToTicket(FareToken const& token) { - switch (token) { - case FareToken::H: - return "Einzelticket Halle"; - case FareToken::L: - return "Einzelticket Leipzig"; - case FareToken::T1: - return "Einzelticket Stadtverkehr 1"; - case FareToken::T2: - return "Einzelticket Stadtverkehr 2"; - case FareToken::T3: - return "Einzelticket Stadtverkehr 3"; - case FareToken::U: - return "Einzelticket"; - case FareToken::Z: - return "Einzelticket"; - case FareToken::M: - return "Einzelticket Verbundpreis"; - case FareToken::K: - return "Kurzstreckenticket"; - case FareToken::KL: - return "Kurzstreckenticket Leipzig"; - case FareToken::KH: - return "Kurzstreckenticket Halle"; - case FareToken::ZU: - return "None"; - case FareToken::None: - return "None"; - case FareToken::Free: - return "Free"; - case FareToken::KHU: - return "Kurzstreckenticket Halle"; - case FareToken::KLU: - return "Kurzstreckenticket Leipzig"; - case FareToken ::KHZ: - return "Kurzstreckenticket Halle"; - case FareToken ::KLZ: - return "Kurzstreckenticket Leipzig"; - case FareToken ::START: - return "forbidden START"; - } - return ""; //surpress compiler warning -} - -inline FareToken stringToToken(std::string str) { - if (str == "H") { - return FareToken::H; - } - if (str == "L") { - return FareToken::L; - } - if (str == "T1") { - return FareToken::T1; - } - if (str == "T2") { - return FareToken::T2; - } - if (str == "T3") { - return FareToken::T3; - } - if (str == "1") { - return FareToken::T1; - } - if (str == "2") { - return FareToken::T2; - } - if (str == "3") { - return FareToken::T3; - } - if (str == "U") { - return FareToken::U; - } - if (str == "Z") { - return FareToken::Z; - } - if (str == "M") { - return FareToken::M; - } - if (str == "K") { - return FareToken::K; - } - if (str == "KL") { - return FareToken::KL; - } - if (str == "KH") { - return FareToken::KH; - } - if (str == "ZU") { - return FareToken::ZU; - } - if (str == "None") { - return FareToken::None; - } - if (str == "Free") { - return FareToken::Free; - } - if (str == "KHU") { - return FareToken::KHU; - } - if (str == "KLU") { - return FareToken::KLU; - } - if (str == "KHZ") { - return FareToken::KHZ; - } - if (str == "KLZ") { - return FareToken::KLZ; - } - if (str == "NOTFOUND") { - return FareToken::None; - } - assert(false); - return FareToken::None; -} - -} diff --git a/Util/OSM2ODR/src/utils/router/FareZones.h b/Util/OSM2ODR/src/utils/router/FareZones.h deleted file mode 100644 index 9a590b80e..000000000 --- a/Util/OSM2ODR/src/utils/router/FareZones.h +++ /dev/null @@ -1,206 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2002-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file FareZones.h -/// @author Ricardo Euler -/// @date Thu, 17 August 2018 -/// -// Fare Modul for calculating prices during intermodal routing -/****************************************************************************/ - -#pragma once -#include - -#include -#include - -static std::unordered_map repToFareZone = std::unordered_map { - {1, 110}, - {2, 121}, - {4, 122}, - {8, 123}, - {16, 124}, - {32, 125}, - {64, 126}, - {128, 127}, - {256, 128}, - {512, 129}, - {1024, 131}, - {2048, 132}, - {4096, 133}, - {8192, 134}, - {16384, 141}, - {32768, 142}, - {65536, 143}, - {131072, 144}, - {262144, 145}, - {524288, 146}, - {1048576, 147}, - {2097152, 151}, - {4194304, 152}, - {8388608, 153}, - {16777216, 154}, - {33554432, 155}, - {67108864, 156}, - {134217728, 162}, - {268435456, 163}, - {536870912, 164}, - {1073741824, 165}, - {2147483648, 166}, - {4294967296, 167}, - {8589934592, 168}, - {17179869184, 210}, - {34359738368, 221}, - {68719476736, 222}, - {137438953472, 223}, - {274877906944, 224}, - {549755813888, 225}, - {1099511627776, 231}, - {2199023255552, 232}, - {4398046511104, 233}, - {8796093022208, 234}, - {17592186044416, 241}, - {35184372088832, 242}, - {70368744177664, 243}, - {140737488355328, 251}, - {281474976710656, 252}, - {562949953421312, 253}, - {1125899906842624, 254}, - {2251799813685248, 255}, - {4503599627370496, 256}, - {9007199254740992, 257}, - {18014398509481984, 258}, - {36028797018963968, 259}, - {72057594037927936, 261}, - {144115188075855872, 299}, - {288230376151711744, 321}, - {576460752303423488, 322}, - {1152921504606846976, 323}, - {2305843009213693952, 324} -}; - -static std::unordered_map fareZoneToRep = std::unordered_map { - {110, 1 }, - {121, 2 }, - {122, 4 }, - {123, 8 }, - {124, 16 }, - {125, 32 }, - {126, 64 }, - {127, 128 }, - {128, 256 }, - {129, 512 }, - {131, 1024 }, - {132, 2048 }, - {133, 4096 }, - {134, 8192 }, - {141, 16384 }, - {142, 32768 }, - {143, 65536 }, - {144, 131072 }, - {145, 262144 }, - {146, 524288 }, - {147, 1048576 }, - {151, 2097152 }, - {152, 4194304 }, - {153, 8388608 }, - {154, 16777216 }, - {155, 33554432 }, - {156, 67108864 }, - {162, 134217728 }, - {163, 268435456 }, - {164, 536870912 }, - {165, 1073741824 }, - {166, 2147483648 }, - {167, 4294967296 }, - {168, 8589934592 }, - {210, 17179869184 }, - {221, 34359738368 }, - {222, 68719476736 }, - {223, 137438953472 }, - {224, 274877906944 }, - {225, 549755813888 }, - {231, 1099511627776 }, - {232, 2199023255552 }, - {233, 4398046511104 }, - {234, 8796093022208 }, - {241, 17592186044416 }, - {242, 35184372088832 }, - {243, 70368744177664 }, - {251, 140737488355328 }, - {252, 281474976710656 }, - {253, 562949953421312 }, - {254, 1125899906842624 }, - {255, 2251799813685248 }, - {256, 4503599627370496 }, - {257, 9007199254740992 }, - {258, 18014398509481984 }, - {259, 36028797018963968 }, - {261, 72057594037927936 }, - {299, 144115188075855872 }, - {321, 288230376151711744 }, - {322, 576460752303423488 }, - {323, 1152921504606846976 }, - {324, 2305843009213693952 } -}; - -/** - * Returns the zone the specified lower rank zones is a part of - * @return - */ - -inline int getOverlayZone(int zoneNumber) { - if (zoneNumber < 400) { - return zoneNumber; //real "zone" numbers, no city zones - } - - switch (zoneNumber) { - case 511: - return 165; - case 512: - return 166; - case 513: - return 167; - case 514: - return 142; - case 515: - return 123; - case 516: - return 127; - case 518: - return 145; - case 519: - return 144; - case 521: - return 153; - case 551: - return 231; - case 552: - return 232; - case 553: - return 233; - case 554: - return 259; - case 555: - return 241; - case 556: - return 255; - case 571: - return 322; - case 572: - return 324; - default: - return zoneNumber; - } -} - diff --git a/Util/OSM2ODR/src/utils/router/GawronCalculator.h b/Util/OSM2ODR/src/utils/router/GawronCalculator.h deleted file mode 100644 index 3727fe18f..000000000 --- a/Util/OSM2ODR/src/utils/router/GawronCalculator.h +++ /dev/null @@ -1,111 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2002-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file GawronCalculator.h -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @author Jakob Erdmann -/// @date Sept 2002 -/// -// Calculators for route costs and probabilities -/****************************************************************************/ -#pragma once -#include - -#include -#include - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class GawronCalculator - * @brief Cost calculation with Gawron's method. - */ -template -class GawronCalculator : public RouteCostCalculator { -public: - /// Constructor - GawronCalculator(const double beta, const double a) : myBeta(beta), myA(a) {} - - /// Destructor - virtual ~GawronCalculator() {} - - void setCosts(R* route, const double costs, const bool isActive = false) const { - if (isActive) { - route->setCosts(costs); - } else { - route->setCosts(myBeta * costs + ((double) 1.0 - myBeta) * route->getCosts()); - } - } - - /** @brief calculate the probabilities */ - void calculateProbabilities(std::vector alternatives, const V* const /* veh */, const SUMOTime /* time */) { - for (typename std::vector::iterator i = alternatives.begin(); i != alternatives.end() - 1; i++) { - R* pR = *i; - for (typename std::vector::iterator j = i + 1; j != alternatives.end(); j++) { - R* pS = *j; - // see [Gawron, 1998] (4.2) - const double delta = - (pS->getCosts() - pR->getCosts()) / - (pS->getCosts() + pR->getCosts()); - // see [Gawron, 1998] (4.3a, 4.3b) - double newPR = gawronF(pR->getProbability(), pS->getProbability(), delta); - double newPS = pR->getProbability() + pS->getProbability() - newPR; - if (ISNAN(newPR) || ISNAN(newPS)) { - newPR = pS->getCosts() > pR->getCosts() - ? (double) 1. : 0; - newPS = pS->getCosts() > pR->getCosts() - ? 0 : (double) 1.; - } - newPR = MIN2((double) MAX2(newPR, (double) 0), (double) 1); - newPS = MIN2((double) MAX2(newPS, (double) 0), (double) 1); - pR->setProbability(newPR); - pS->setProbability(newPS); - } - } - } - -private: - /** @brief Performs the gawron - f() function - From "Dynamic User Equilibria..." */ - double gawronF(const double pdr, const double pds, const double x) const { - if (pdr * gawronG(myA, x) + pds == 0) { - return std::numeric_limits::max(); - } - return (pdr * (pdr + pds) * gawronG(myA, x)) / - (pdr * gawronG(myA, x) + pds); - } - - /** @brief Performs the gawron - g() function - From "Dynamic User Equilibria..." */ - double gawronG(const double a, const double x) const { - if (((1.0 - (x * x)) == 0)) { - return std::numeric_limits::max(); - } - return (double) exp((a * x) / (1.0 - (x * x))); - } - -private: - /// @brief gawron beta - value - const double myBeta; - - /// @brief gawron a - value - const double myA; - -private: - /** @brief invalidated assignment operator */ - GawronCalculator& operator=(const GawronCalculator& s); - -}; diff --git a/Util/OSM2ODR/src/utils/router/IntermodalEdge.h b/Util/OSM2ODR/src/utils/router/IntermodalEdge.h deleted file mode 100644 index e09897d19..000000000 --- a/Util/OSM2ODR/src/utils/router/IntermodalEdge.h +++ /dev/null @@ -1,221 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file IntermodalEdge.h -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @author Robert Hilbrich -/// @date Mon, 03 March 2014 -/// -// The Edge definition for the Intermodal Router -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include -#include -#include "IntermodalTrip.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -/// @brief the base edge type that is given to the internal router (SUMOAbstractRouter) -template -class IntermodalEdge : public Named { -public: - IntermodalEdge(const std::string id, int numericalID, const E* edge, const std::string& line, const double length = 0.) : - Named(id), - myNumericalID(numericalID), - myEdge(edge), - myLine(line), - myLength(edge == nullptr || length > 0. ? length : edge->getLength()), - myEfforts(nullptr) { } - - virtual ~IntermodalEdge() {} - - virtual bool includeInRoute(bool /* allEdges */) const { - return false; - } - - inline const std::string& getLine() const { - return myLine; - } - - inline const E* getEdge() const { - return myEdge; - } - - int getNumericalID() const { - return myNumericalID; - } - - void addSuccessor(IntermodalEdge* const s, IntermodalEdge* const via = nullptr) { - myFollowingEdges.push_back(s); - myFollowingViaEdges.push_back(std::make_pair(s, via)); - } - - void transferSuccessors(IntermodalEdge* to) { - to->myFollowingEdges = myFollowingEdges; - to->myFollowingViaEdges = myFollowingViaEdges; - myFollowingEdges.clear(); - myFollowingViaEdges.clear(); - } - - void removeSuccessor(const IntermodalEdge* const edge) { - myFollowingEdges.erase(std::find(myFollowingEdges.begin(), myFollowingEdges.end(), edge)); - for (auto it = myFollowingViaEdges.begin(); it != myFollowingViaEdges.end();) { - if (it->first == edge) { - it = myFollowingViaEdges.erase(it); - } else { - ++it; - } - } - } - - virtual const std::vector& getSuccessors(SUMOVehicleClass vClass = SVC_IGNORING) const { - UNUSED_PARAMETER(vClass); - // the network is already tailored. No need to check for permissions here - return myFollowingEdges; - } - - virtual const std::vector >& getViaSuccessors(SUMOVehicleClass vClass = SVC_IGNORING) const { - UNUSED_PARAMETER(vClass); - // the network is already tailored. No need to check for permissions here - return myFollowingViaEdges; - } - - virtual bool prohibits(const IntermodalTrip* const /* trip */) const { - return false; - } - - virtual bool restricts(const IntermodalTrip* const /* trip */) const { - return false; - } - - virtual double getTravelTime(const IntermodalTrip* const /* trip */, double /* time */) const { - return 0.; - } - - virtual double getTravelTimeAggregated(const IntermodalTrip* const trip, double time) const { - return getTravelTime(trip, time); - } - - /// @brief get intended vehicle id and departure time of next public transport ride - virtual double getIntended(const double /* time */, std::string& /* intended */) const { - return 0.; - } - - static inline double getTravelTimeStatic(const IntermodalEdge* const edge, const IntermodalTrip* const trip, double time) { - return edge == nullptr ? 0. : edge->getTravelTime(trip, time); - } - - static inline double getTravelTimeStaticRandomized(const IntermodalEdge* const edge, const IntermodalTrip* const trip, double time) { - return edge == nullptr ? 0. : edge->getTravelTime(trip, time) * RandHelper::rand(1., gWeightsRandomFactor); - } - - static inline double getTravelTimeAggregated(const IntermodalEdge* const edge, const IntermodalTrip* const trip, double time) { - return edge == nullptr ? 0. : edge->getTravelTimeAggregated(trip, time); - } - - - virtual double getEffort(const IntermodalTrip* const /* trip */, double /* time */) const { - return 0.; - } - - static inline double getEffortStatic(const IntermodalEdge* const edge, const IntermodalTrip* const trip, double time) { - return edge == nullptr || !edge->hasEffort() ? 0. : edge->getEffort(trip, time); - } - - inline double getLength() const { - return myLength; - } - - inline void setLength(const double length) { - myLength = length; - } - - inline bool isInternal() const { - return myEdge != nullptr && myEdge->isInternal(); - } - - virtual bool hasEffort() const { - return myEfforts != nullptr; - } - - virtual double getStartPos() const { - return 0.; - } - - virtual double getEndPos() const { - return myLength; - } - - // only used by AStar - inline double getSpeedLimit() const { - return myEdge != nullptr ? myEdge->getSpeedLimit() : 200. / 3.6; - } - - // only used by AStar - inline double getLengthGeometryFactor() const { - return myEdge != nullptr ? myEdge->getLengthGeometryFactor() : 1; - } - - // only used by AStar - inline double getDistanceTo(const IntermodalEdge* other) const { - return myEdge != nullptr && other->myEdge != nullptr && myEdge != other->myEdge ? myEdge->getDistanceTo(other->myEdge, true) : 0.; - } - - // only used by AStar - inline double getMinimumTravelTime(const IntermodalTrip* const trip) const { - return myLength / trip->getMaxSpeed(); - } - - /// @brief only used by mono-modal routing - IntermodalEdge* getBidiEdge() const { - return nullptr; - } - -protected: - /// @brief List of edges that may be approached from this edge - std::vector myFollowingEdges; - - /// @brief List of edges that may be approached from this edge with optional internal vias - std::vector > myFollowingViaEdges; - -private: - /// @brief the index in myEdges - const int myNumericalID; - - /// @brief the original edge - const E* const myEdge; - - /// @brief public transport line or ped vs car - const std::string myLine; - - /// @brief adaptable length (for splitted edges) - double myLength; - - /// @brief Container for passing effort varying over time for the edge - ValueTimeLine* myEfforts; - -private: - /// @brief Invalidated copy constructor - IntermodalEdge(const IntermodalEdge& src); - - /// @brief Invalidated assignment operator - IntermodalEdge& operator=(const IntermodalEdge& src); - -}; diff --git a/Util/OSM2ODR/src/utils/router/IntermodalNetwork.h b/Util/OSM2ODR/src/utils/router/IntermodalNetwork.h deleted file mode 100644 index b0d8e4b65..000000000 --- a/Util/OSM2ODR/src/utils/router/IntermodalNetwork.h +++ /dev/null @@ -1,840 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file IntermodalNetwork.h -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @author Robert Hilbrich -/// @date Mon, 03 March 2014 -/// -// The Edge definition for the Intermodal Router -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "AccessEdge.h" -#include "CarEdge.h" -#include "IntermodalEdge.h" -#include "PedestrianEdge.h" -#include "PublicTransportEdge.h" -#include "StopEdge.h" - -//#define IntermodalRouter_DEBUG_NETWORK -//#define IntermodalRouter_DEBUG_ACCESS - - -// =========================================================================== -// function definitions -// =========================================================================== -template -inline const L* getSidewalk(const E* edge) { - if (edge == nullptr) { - return nullptr; - } - // prefer lanes that are exclusive to pedestrians - const std::vector& lanes = edge->getLanes(); - for (const L* const lane : lanes) { - if (lane->getPermissions() == SVC_PEDESTRIAN) { - return lane; - } - } - for (const L* const lane : lanes) { - if (lane->allowsVehicleClass(SVC_PEDESTRIAN)) { - return lane; - } - } - return nullptr; -} - - -// =========================================================================== -// class definitions -// =========================================================================== -/// @brief the intermodal network storing edges, connections and the mappings to the "real" edges -template -class IntermodalNetwork { -private: - typedef IntermodalEdge _IntermodalEdge; - typedef AccessEdge _AccessEdge; - typedef PedestrianEdge _PedestrianEdge; - typedef PublicTransportEdge _PTEdge; - typedef std::pair<_IntermodalEdge*, _IntermodalEdge*> EdgePair; - -public: - /** @brief where mode changes are possible - */ - enum ModeChangeOptions { - /// @brief parking areas - PARKING_AREAS = 1, - /// @brief public transport stops and access - PT_STOPS = 2, - /// @brief junctions with edges allowing the additional mode - ALL_JUNCTIONS = 4, - /// @brief all junctions where a taxi customer may exit - ALL_JUNCTIONS_TAXI = 8 - }; - - /* @brief build the pedestrian part of the intermodal network (once) - * @param edges The list of MSEdge or ROEdge to build from - * @param numericalID the start number for the creation of new edges - */ - IntermodalNetwork(const std::vector& edges, const bool pedestrianOnly, const int carWalkTransfer = 0) - : myNumericalID(0), myCarWalkTransfer(carWalkTransfer) { -#ifdef IntermodalRouter_DEBUG_NETWORK - std::cout << "initIntermodalNetwork\n"; -#endif - // build the pedestrian edges and the depart / arrival connectors with lookup tables - bool haveSeenWalkingArea = false; - for (const E* const edge : edges) { - if (edge->isTazConnector()) { - // only a single edge - _AccessEdge* access = new _AccessEdge(myNumericalID++, edge->getID(), edge); - addEdge(access); - myDepartLookup[edge].push_back(access); - myArrivalLookup[edge].push_back(access); - } else { - const L* lane = getSidewalk(edge); - if (lane != 0) { - if (edge->isWalkingArea()) { - // only a single edge - addEdge(new _PedestrianEdge(myNumericalID++, edge, lane, true)); - myBidiLookup[edge] = std::make_pair(myEdges.back(), myEdges.back()); - myDepartLookup[edge].push_back(myEdges.back()); - myArrivalLookup[edge].push_back(myEdges.back()); - haveSeenWalkingArea = true; - } else { // regular edge or crossing - // forward and backward edges - addEdge(new _PedestrianEdge(myNumericalID++, edge, lane, true)); - addEdge(new _PedestrianEdge(myNumericalID++, edge, lane, false)); - myBidiLookup[edge] = std::make_pair(myEdges[myNumericalID - 2], myEdges.back()); - } - } - if (!edge->isWalkingArea()) { - // depart and arrival edges (the router can decide the initial direction to take and the direction to arrive from) - _IntermodalEdge* const departConn = new _IntermodalEdge(edge->getID() + "_depart_connector", myNumericalID++, edge, "!connector"); - _IntermodalEdge* const arrivalConn = new _IntermodalEdge(edge->getID() + "_arrival_connector", myNumericalID++, edge, "!connector"); - addConnectors(departConn, arrivalConn, 0); - } - } - } - - // build the walking connectors if there are no walking areas - for (const E* const edge : edges) { - if (edge->isTazConnector() || edge->isInternal()) { - continue; - } - if (haveSeenWalkingArea) { - // connectivity needs to be ensured only in the real intermodal case, for simple pedestrian routing we don't have connectors if we have walking areas - if (!pedestrianOnly && getSidewalk(edge) == nullptr) { - const N* const node = edge->getToJunction(); - if (myWalkingConnectorLookup.count(node) == 0) { - addEdge(new _IntermodalEdge(node->getID() + "_walking_connector", myNumericalID++, nullptr, "!connector")); - myWalkingConnectorLookup[node] = myEdges.back(); - } - } - } else { - for (const N* const node : { - edge->getFromJunction(), edge->getToJunction() - }) { - if (myWalkingConnectorLookup.count(node) == 0) { - addEdge(new _IntermodalEdge(node->getID() + "_walking_connector", myNumericalID++, nullptr, "!connector")); - myWalkingConnectorLookup[node] = myEdges.back(); - } - } - } - } - // build the connections - for (const E* const edge : edges) { - if (edge->isTazConnector()) { - // since pedestrians walk in both directions, also allow departing at sinks and arriving at sources - _IntermodalEdge* const tazDepart = getDepartConnector(edge); - _IntermodalEdge* const tazArrive = getArrivalConnector(edge); - const E* other = edge->getOtherTazConnector(); - _IntermodalEdge* const otherTazDepart = other != nullptr ? getDepartConnector(other) : tazDepart; - _IntermodalEdge* const otherTazArrive = other != nullptr ? getArrivalConnector(other) : tazArrive; - for (const E* out : edge->getSuccessors()) { - tazDepart->addSuccessor(getDepartConnector(out)); - getArrivalConnector(out)->addSuccessor(otherTazArrive); - } - for (const E* in : edge->getPredecessors()) { - getArrivalConnector(in)->addSuccessor(tazArrive); - otherTazDepart->addSuccessor(getDepartConnector(in)); - } - continue; - } - const L* const sidewalk = getSidewalk(edge); - if (sidewalk == nullptr) { - continue; - } - // find all incoming and outgoing lanes for the sidewalk and - // connect the corresponding IntermodalEdges - const EdgePair& pair = getBothDirections(edge); -#ifdef IntermodalRouter_DEBUG_NETWORK - std::cout << " building connections from " << sidewalk->getID() << "\n"; -#endif - if (haveSeenWalkingArea) { - const std::vector > outgoing = sidewalk->getOutgoingViaLanes(); - // if one of the outgoing lanes is a walking area it must be used. - // All other connections shall be ignored - // if it has no outgoing walking area, it probably is a walking area itself - bool hasWalkingArea = false; - for (const auto& target : outgoing) { - if (target.first->getEdge().isWalkingArea()) { - hasWalkingArea = true; - break; - } - } - for (const auto& target : outgoing) { - const E* const targetEdge = &(target.first->getEdge()); - const bool used = (target.first == getSidewalk(targetEdge) - && (!hasWalkingArea || targetEdge->isWalkingArea())); -#ifdef IntermodalRouter_DEBUG_NETWORK - const L* potTarget = getSidewalk(targetEdge); - std::cout << " lane=" << (potTarget == 0 ? "NULL" : potTarget->getID()) << (used ? "(used)" : "") << "\n"; -#endif - if (used) { - const EdgePair& targetPair = getBothDirections(targetEdge); - pair.first->addSuccessor(targetPair.first); - targetPair.second->addSuccessor(pair.second); -#ifdef IntermodalRouter_DEBUG_NETWORK - std::cout << " " << pair.first->getID() << " -> " << targetPair.first->getID() << "\n"; - std::cout << " " << targetPair.second->getID() << " -> " << pair.second->getID() << "\n"; -#endif - } - } - } - // We may have a network without pedestrian structures or a car-only edge. - // In the first case we assume that all sidewalks at a junction are interconnected, - // in the second we connect all car-only edges to all sidewalks. - _IntermodalEdge* const toNodeConn = myWalkingConnectorLookup[edge->getToJunction()]; - if (toNodeConn != nullptr) { - // Check for the outgoing vias and use the shortest one as an approximation - const std::vector > outgoing = sidewalk->getOutgoingViaLanes(); - double minViaLength = std::numeric_limits::max(); - const E* minVia = nullptr; - for (const auto& target : outgoing) { - if (target.second != nullptr && target.second->getLength() < minViaLength) { - minViaLength = target.second->getLength(); - minVia = target.second; - } - } - EdgePair interVia = std::make_pair(nullptr, nullptr); - if (minVia != nullptr) { - const auto it = myBidiLookup.find(minVia); - if (it != myBidiLookup.end()) { - interVia = it->second; - } - } - if (!haveSeenWalkingArea) { - // if we have walking areas we should use them and not the connector - pair.first->addSuccessor(toNodeConn, interVia.first); - } - toNodeConn->addSuccessor(pair.second, interVia.second); - } - _IntermodalEdge* const fromNodeConn = myWalkingConnectorLookup[edge->getFromJunction()]; - if (fromNodeConn != nullptr) { - if (!haveSeenWalkingArea) { - pair.second->addSuccessor(fromNodeConn); - } - fromNodeConn->addSuccessor(pair.first); - } - if (!edge->isWalkingArea()) { - // build connections from depart connector - _IntermodalEdge* startConnector = getDepartConnector(edge); - startConnector->addSuccessor(pair.first); - startConnector->addSuccessor(pair.second); - // build connections to arrival connector - _IntermodalEdge* endConnector = getArrivalConnector(edge); - pair.first->addSuccessor(endConnector); - pair.second->addSuccessor(endConnector); - } -#ifdef IntermodalRouter_DEBUG_NETWORK - std::cout << " " << startConnector->getID() << " -> " << pair.first->getID() << "\n"; - std::cout << " " << startConnector->getID() << " -> " << pair.second->getID() << "\n"; - std::cout << " " << pair.first->getID() << " -> " << endConnector->getID() << "\n"; - std::cout << " " << pair.second->getID() << " -> " << endConnector->getID() << "\n"; -#endif - } - } - - ~IntermodalNetwork() { - for (typename std::vector<_IntermodalEdge*>::iterator it = myEdges.begin(); it != myEdges.end(); ++it) { - delete *it; - } - } - - void addEdge(_IntermodalEdge* edge) { - while ((int)myEdges.size() <= edge->getNumericalID()) { - myEdges.push_back(0); - } - myEdges[edge->getNumericalID()] = edge; - } - - void addConnectors(_IntermodalEdge* const depConn, _IntermodalEdge* const arrConn, const int index) { - addEdge(depConn); - addEdge(arrConn); - myDepartLookup[depConn->getEdge()].insert(myDepartLookup[depConn->getEdge()].begin() + index, depConn); - myArrivalLookup[arrConn->getEdge()].insert(myArrivalLookup[arrConn->getEdge()].begin() + index, arrConn); - } - - const std::vector<_IntermodalEdge*>& getAllEdges() { - return myEdges; - } - - /// @brief Returns the pair of forward and backward edge - const EdgePair& getBothDirections(const E* e) const { - typename std::map::const_iterator it = myBidiLookup.find(e); - if (it == myBidiLookup.end()) { - assert(false); - throw ProcessError("Edge '" + e->getID() + "' not found in intermodal network.'"); - } - return (*it).second; - } - - /// @brief Returns the departing intermodal edge - const _IntermodalEdge* getDepartEdge(const E* e, const double pos) const { - typename std::map >::const_iterator it = myDepartLookup.find(e); - if (it == myDepartLookup.end()) { - throw ProcessError("Depart edge '" + e->getID() + "' not found in intermodal network."); - } - if (isRailway(e->getPermissions())) { - // use closest split (best trainStop) - double totalLength = 0.; - double bestDist = std::numeric_limits::max(); - const _IntermodalEdge* best = nullptr; - for (const _IntermodalEdge* split : it->second) { - totalLength += split->getLength(); - double dist = fabs(totalLength - pos); - if (dist < bestDist) { - // make sure to use a stop rather than the final departConnector since walking is not possible - if (bestDist != std::numeric_limits::max() && split == it->second.back()) { - break; - } - bestDist = dist; - best = split; - } else { - break; - } - } - assert(best != 0); - return best; - } else { - // use next downstream edge - const std::vector<_IntermodalEdge*>& splitList = it->second; - typename std::vector<_IntermodalEdge*>::const_iterator splitIt = splitList.begin(); - double totalLength = 0.; - while (splitIt + 1 != splitList.end() && totalLength + (*splitIt)->getLength() < pos) { - totalLength += (*splitIt)->getLength(); - ++splitIt; - } - return *splitIt; - } - } - - /// @brief Returns the departing intermodal connector at the given split offset - _IntermodalEdge* getDepartConnector(const E* e, const int splitIndex = 0) const { - typename std::map >::const_iterator it = myDepartLookup.find(e); - if (it == myDepartLookup.end()) { - throw ProcessError("Depart edge '" + e->getID() + "' not found in intermodal network."); - } - if (splitIndex >= (int)it->second.size()) { - throw ProcessError("Split index " + toString(splitIndex) + " invalid for depart edge '" + e->getID() + "' ."); - } - return it->second[splitIndex]; - } - - /// @brief Returns the arriving intermodal edge - _IntermodalEdge* getArrivalEdge(const E* e, const double pos) const { - typename std::map >::const_iterator it = myArrivalLookup.find(e); - if (it == myArrivalLookup.end()) { - throw ProcessError("Arrival edge '" + e->getID() + "' not found in intermodal network."); - } - const std::vector<_IntermodalEdge*>& splitList = it->second; - typename std::vector<_IntermodalEdge*>::const_iterator splitIt = splitList.begin(); - double totalLength = 0.; - while (splitIt != splitList.end() && totalLength + (*splitIt)->getLength() < pos) { - totalLength += (*splitIt)->getLength(); - ++splitIt; - } - return *splitIt; - } - - /// @brief Returns the arriving intermodal connector at the given split offset - _IntermodalEdge* getArrivalConnector(const E* e, const int splitIndex = 0) const { - return myArrivalLookup.find(e)->second[splitIndex]; - } - - /// @brief Returns the outgoing pedestrian edge, which is either a walking area or a walking connector - _IntermodalEdge* getWalkingConnector(const E* e) const { - typename std::map::const_iterator it = myWalkingConnectorLookup.find(e->getToJunction()); - if (it == myWalkingConnectorLookup.end()) { - const L* const sidewalk = getSidewalk(e); - if (e->isInternal() || sidewalk == 0) { - return 0; - } - for (const auto& target : sidewalk->getOutgoingViaLanes()) { - if (target.first->getEdge().isWalkingArea()) { - return getBothDirections(&target.first->getEdge()).first; - } - } - return 0; - } - return it->second; - } - - void addCarEdges(const std::vector& edges) { - for (const E* const edge : edges) { - if (edge->getFunction() == SumoXMLEdgeFunc::NORMAL || edge->getFunction() == SumoXMLEdgeFunc::INTERNAL) { - myCarLookup[edge] = new CarEdge(myNumericalID++, edge); - addEdge(myCarLookup[edge]); - } - } - for (const auto& edgePair : myCarLookup) { - _IntermodalEdge* const carEdge = edgePair.second; - for (const auto& suc : edgePair.first->getViaSuccessors()) { - _IntermodalEdge* const sucCarEdge = getCarEdge(suc.first); - _IntermodalEdge* const sucViaEdge = getCarEdge(suc.second); - if (sucCarEdge != nullptr) { - carEdge->addSuccessor(sucCarEdge, sucViaEdge); - } - } - if ((myCarWalkTransfer & ALL_JUNCTIONS) != 0) { - _IntermodalEdge* const walkCon = getWalkingConnector(edgePair.first); - if (walkCon != 0) { - carEdge->addSuccessor(walkCon); - } else { - // we are on an edge where pedestrians are forbidden and want to continue on an arbitrary pedestrian edge - for (const E* const out : edgePair.first->getToJunction()->getOutgoing()) { - if (!out->isInternal() && !out->isTazConnector() && getSidewalk(out) != 0) { - carEdge->addSuccessor(getBothDirections(out).first); - } - } - for (const E* const in : edgePair.first->getToJunction()->getIncoming()) { - if (!in->isInternal() && !in->isTazConnector() && getSidewalk(in) != 0) { - carEdge->addSuccessor(getBothDirections(in).second); - } - } - } - } - if ((myCarWalkTransfer & ALL_JUNCTIONS) == 0 && (myCarWalkTransfer & ALL_JUNCTIONS_TAXI) != 0) { - // add access edges that allow exiting a taxi - _IntermodalEdge* const walkCon = getWalkingConnector(edgePair.first); - if (walkCon != 0) { - addRestrictedCarExit(carEdge, walkCon, SVC_TAXI); - } else { - // we are on an edge where pedestrians are forbidden and want to continue on an arbitrary pedestrian edge - for (const E* const out : edgePair.first->getToJunction()->getOutgoing()) { - if (!out->isInternal() && !out->isTazConnector() && getSidewalk(out) != 0) { - addRestrictedCarExit(carEdge, getBothDirections(out).first, SVC_TAXI); - } - } - for (const E* const in : edgePair.first->getToJunction()->getIncoming()) { - if (!in->isInternal() && !in->isTazConnector() && getSidewalk(in) != 0) { - addRestrictedCarExit(carEdge, getBothDirections(in).second, SVC_TAXI); - } - } - } - } - getDepartConnector(edgePair.first)->addSuccessor(carEdge); - carEdge->addSuccessor(getArrivalConnector(edgePair.first)); - } - } - - /// @brief Returns the associated car edge - _IntermodalEdge* getCarEdge(const E* e) const { - typename std::map::const_iterator it = myCarLookup.find(e); - if (it == myCarLookup.end()) { - return nullptr; - } - return it->second; - } - - /// @brief Returns the associated stop edge - _IntermodalEdge* getStopEdge(const std::string& stopId) const { - auto it = myStopConnections.find(stopId); - if (it == myStopConnections.end()) { - return nullptr; - } - return it->second; - } - - /** @brief Adds access edges for stopping places to the intermodal network - * - * This method creates an intermodal stop edge to represent the stopping place - * (if not present yet) and determines the edges which need to be splitted (usually the forward - * and the backward pedestrian edges and the car edge) and calls splitEdge for the - * actual split and the connection of the stop edge with access edges. After that it adds and adapts - * the depart and arrival connectors to the new edge(s). - * - * @param[in] stopId The id of the stop to add - * @param[in] stopEdge The edge on which the stop is located - * @param[in] pos The relative position on the edge where the stop is located - * @param[in] category The type of stop - */ - void addAccess(const std::string& stopId, const E* stopEdge, const double pos, const double length, const SumoXMLTag category) { - assert(stopEdge != nullptr); - const bool transferCarWalk = ((category == SUMO_TAG_PARKING_AREA && (myCarWalkTransfer & PARKING_AREAS) != 0) || - (category == SUMO_TAG_BUS_STOP && (myCarWalkTransfer & PT_STOPS) != 0)); -#ifdef IntermodalRouter_DEBUG_ACCESS - std::cout << "addAccess stopId=" << stopId << " stopEdge=" << stopEdge->getID() << " pos=" << pos << " length=" << length << " cat=" << category << "\n"; -#endif - if (myStopConnections.count(stopId) == 0) { - myStopConnections[stopId] = new StopEdge(stopId, myNumericalID++, stopEdge); - addEdge(myStopConnections[stopId]); - } - _IntermodalEdge* const stopConn = myStopConnections[stopId]; - const L* lane = getSidewalk(stopEdge); - if (lane != nullptr) { - const std::pair<_IntermodalEdge*, _IntermodalEdge*>& pair = getBothDirections(stopEdge); - double relPos; - bool needSplit; - const int splitIndex = findSplitIndex(pair.first, pos, relPos, needSplit); - _IntermodalEdge* const fwdSplit = needSplit ? new PedestrianEdge(myNumericalID++, stopEdge, lane, true, pos) : nullptr; - splitEdge(pair.first, splitIndex, fwdSplit, relPos, length, needSplit, stopConn); - _IntermodalEdge* const backSplit = needSplit ? new PedestrianEdge(myNumericalID++, stopEdge, lane, false, pos) : nullptr; - splitEdge(pair.second, splitIndex, backSplit, relPos, length, needSplit, stopConn, false); - _IntermodalEdge* carSplit = nullptr; - if (myCarLookup.count(stopEdge) > 0) { - if (needSplit) { - carSplit = new CarEdge(myNumericalID++, stopEdge, pos); - } - splitEdge(myCarLookup[stopEdge], splitIndex, carSplit, relPos, length, needSplit, stopConn, true, false, transferCarWalk); - } - if (needSplit) { - if (carSplit != nullptr && transferCarWalk) { - // adding access from car to walk - _IntermodalEdge* const beforeSplit = myAccessSplits[myCarLookup[stopEdge]][splitIndex]; - for (_IntermodalEdge* conn : { - fwdSplit, backSplit - }) { - _AccessEdge* access = new _AccessEdge(myNumericalID++, beforeSplit, conn, length); - addEdge(access); - beforeSplit->addSuccessor(access); - access->addSuccessor(conn); - } - } - - // fixing depart connections for the forward pedestrian, the backward pedestrian and the car edge - _IntermodalEdge* const prevDep = getDepartConnector(stopEdge, splitIndex); - const std::vector<_IntermodalEdge*>& backSplitList = myAccessSplits[pair.second]; - _IntermodalEdge* const backBeforeSplit = backSplitList[backSplitList.size() - 2 - splitIndex]; - _IntermodalEdge* const depConn = new _IntermodalEdge(stopEdge->getID() + "_depart_connector" + toString(pos), myNumericalID++, stopEdge, "!connector"); - depConn->addSuccessor(fwdSplit); - depConn->addSuccessor(backBeforeSplit); - depConn->setLength(fwdSplit->getLength()); - prevDep->removeSuccessor(backBeforeSplit); - prevDep->addSuccessor(backSplit); - prevDep->setLength(backSplit->getLength()); - if (carSplit != nullptr) { - depConn->addSuccessor(carSplit); - } - - // fixing arrival connections for the forward pedestrian, the backward pedestrian and the car edge - _IntermodalEdge* const prevArr = getArrivalConnector(stopEdge, splitIndex); - _IntermodalEdge* const fwdBeforeSplit = myAccessSplits[pair.first][splitIndex]; - _IntermodalEdge* const arrConn = new _IntermodalEdge(stopEdge->getID() + "_arrival_connector" + toString(pos), myNumericalID++, stopEdge, "!connector"); - fwdSplit->addSuccessor(arrConn); - backBeforeSplit->addSuccessor(arrConn); - arrConn->setLength(fwdSplit->getLength()); - fwdSplit->removeSuccessor(prevArr); - fwdBeforeSplit->addSuccessor(prevArr); - prevArr->setLength(backSplit->getLength()); - if (carSplit != nullptr) { - carSplit->addSuccessor(arrConn); - carSplit->removeSuccessor(prevArr); - myAccessSplits[myCarLookup[stopEdge]][splitIndex]->addSuccessor(prevArr); - } - addConnectors(depConn, arrConn, splitIndex + 1); - } - } else { - // pedestrians cannot walk here: - // add depart connectors on the stop edge so that pedestrians may start at the stop - std::vector<_IntermodalEdge*>& splitList = myDepartLookup[stopEdge]; - assert(splitList.size() > 0); - typename std::vector<_IntermodalEdge*>::iterator splitIt = splitList.begin(); - double totalLength = 0.; - _IntermodalEdge* last = nullptr; - while (splitIt != splitList.end() && totalLength < pos) { - totalLength += (*splitIt)->getLength(); - last = *splitIt; - ++splitIt; - } - // insert before last - const double newLength = pos - (totalLength - last->getLength()); - stopConn->setLength(newLength); - splitList.insert(splitIt - 1, stopConn); - // correct length of subsequent edge - last->setLength(last->getLength() - newLength); -#ifdef IntermodalRouter_DEBUG_ACCESS - std::cout << " splitList:\n"; - for (auto conEdge : splitList) { - std::cout << " " << conEdge->getID() << " length=" << conEdge->getLength() << "\n"; - } -#endif - } - } - - void addSchedule(const SUMOVehicleParameter& pars, const std::vector* addStops = nullptr) { - SUMOTime lastUntil = 0; - std::vector validStops; - if (addStops != nullptr) { - // stops are part of a stand-alone route. until times are offsets from vehicle departure - for (const SUMOVehicleParameter::Stop& stop : *addStops) { - if (myStopConnections.count(stop.busstop) > 0) { - // compute stop times for the first vehicle - const SUMOTime newUntil = stop.until + pars.depart; - if (newUntil >= lastUntil) { - validStops.push_back(stop); - validStops.back().until = newUntil; - lastUntil = newUntil; - } else { - WRITE_WARNING("Ignoring unordered stop at '" + stop.busstop + "' until " + time2string(stop.until) + " for vehicle '" + pars.id + "'."); - } - } - } - } - for (const SUMOVehicleParameter::Stop& stop : pars.stops) { - // stops are part of the vehicle until times are absolute times for the first vehicle - if (myStopConnections.count(stop.busstop) > 0 && stop.until >= lastUntil) { - validStops.push_back(stop); - lastUntil = stop.until; - } else { - if (stop.busstop != "" && stop.until >= 0) { - WRITE_WARNING("Ignoring stop at '" + stop.busstop + "' until " + time2string(stop.until) + " for vehicle '" + pars.id + "'."); - } - } - } - if (validStops.size() < 2) { - WRITE_WARNING("Not using public transport line '" + pars.line + "' for routing persons. It has less than two usable stops."); - return; - } - - typename std::vector<_PTEdge*>& lineEdges = myPTLines[pars.line]; - if (lineEdges.empty()) { - _IntermodalEdge* lastStop = nullptr; - Position lastPos; - SUMOTime lastTime = 0; - for (const SUMOVehicleParameter::Stop& s : validStops) { - _IntermodalEdge* currStop = myStopConnections[s.busstop]; - Position stopPos = E::getStopPosition(s); - if (lastStop != nullptr) { - _PTEdge* const newEdge = new _PTEdge(s.busstop, myNumericalID++, lastStop, currStop->getEdge(), pars.line, lastPos.distanceTo(stopPos)); - addEdge(newEdge); - newEdge->addSchedule(pars.id, lastTime, pars.repetitionNumber, pars.repetitionOffset, s.until - lastTime); - lastStop->addSuccessor(newEdge); - newEdge->addSuccessor(currStop); - lineEdges.push_back(newEdge); - } - lastTime = s.until; - lastStop = currStop; - lastPos = stopPos; - } - } else { - if (validStops.size() != lineEdges.size() + 1) { - WRITE_WARNING("Number of stops for public transport line '" + pars.line + "' does not match earlier definitions, ignoring schedule."); - return; - } - if (lineEdges.front()->getEntryStop() != myStopConnections[validStops.front().busstop]) { - WRITE_WARNING("Different stop for '" + pars.line + "' compared to earlier definitions, ignoring schedule."); - return; - } - typename std::vector<_PTEdge*>::const_iterator lineEdge = lineEdges.begin(); - typename std::vector::const_iterator s = validStops.begin() + 1; - for (; s != validStops.end(); ++s, ++lineEdge) { - if ((*lineEdge)->getSuccessors(SVC_IGNORING)[0] != myStopConnections[s->busstop]) { - WRITE_WARNING("Different stop for '" + pars.line + "' compared to earlier definitions, ignoring schedule."); - return; - } - } - SUMOTime lastTime = validStops.front().until; - if (lineEdges.front()->hasSchedule(lastTime)) { - WRITE_WARNING("Duplicate schedule for '" + pars.line + "' at time " + time2string(lastTime) + "."); - } - for (lineEdge = lineEdges.begin(), s = validStops.begin() + 1; lineEdge != lineEdges.end(); ++lineEdge, ++s) { - (*lineEdge)->addSchedule(pars.id, lastTime, pars.repetitionNumber, pars.repetitionOffset, s->until - lastTime); - lastTime = s->until; - } - } - } - - /** @brief Adds access edges for transfering from walking to vehicle use - * @param[in] edge The edge on which the transfer takes place - * @param[in] svc The permitted vehicle class for transfering - */ - void addCarAccess(const E* edge, SUMOVehicleClass svc) { - assert(edge != nullptr); - assert(myCarLookup.count(edge) != 0); - assert(myBidiLookup.count(edge) != 0); - EdgePair pedestrianEdges = myBidiLookup[edge]; - _IntermodalEdge* carEdge = myCarLookup[edge]; - _AccessEdge* access = new _AccessEdge(myNumericalID++, pedestrianEdges.first, carEdge, 0, svc); - addEdge(access); - pedestrianEdges.first->addSuccessor(access); - pedestrianEdges.second->addSuccessor(access); - access->addSuccessor(carEdge); - } - - /** @brief Adds access edges for transfering from driving to walking tha are only usable by a particular vehicle class - * @param[in] from The origin edge of the transfer - * @param[in] to The destination edge of the transfer - * @param[in] svc The permitted vehicle class for transfering - */ - void addRestrictedCarExit(_IntermodalEdge* from, _IntermodalEdge* to, SUMOVehicleClass vehicleRestriction) { - _AccessEdge* access = new _AccessEdge(myNumericalID++, from, to, 0, SVC_IGNORING, vehicleRestriction); - addEdge(access); - from->addSuccessor(access); - access->addSuccessor(to); - } - -private: - /** @brief Returns where to insert or use the split edge - * - * This method determines whether an edge needs to be split at the given position - * (if there is not already a split nearby) and returns the corresponding index in the split list. - * - * @param[in] toSplit The first edge in the split list - * @param[in] pos The relative position on the edge where the stop is located - * @param[out] relPos The relative position on the splitted edge - * @param[out] needSplit whether a new split is needed or we reuse an exisiting one - * @return the index in the split list where the split edge needs to be added or reused - */ - int findSplitIndex(_IntermodalEdge* const toSplit, const double pos, double& relPos, bool& needSplit) { - relPos = pos; - needSplit = true; - int splitIndex = 0; - std::vector<_IntermodalEdge*>& splitList = myAccessSplits[toSplit]; - if (!splitList.empty()) { - for (const _IntermodalEdge* const split : splitList) { - if (relPos < split->getLength() + POSITION_EPS) { - break; - } - relPos -= split->getLength(); - splitIndex++; - } - assert(splitIndex < (int)splitList.size()); - if (splitIndex + 1 < (int)splitList.size() && fabs(relPos - splitList[splitIndex]->getLength()) < POSITION_EPS) { - needSplit = false; - } - } - return splitIndex; - } - - /** @brief Splits an edge (if necessary) and connects it to a stopping edge - * - * This method determines whether an edge needs to be split at the given position - * (if there is not already a split nearby) and connects the stop edge via new access edges. - * - * @param[in] toSplit The first edge in the split list - * @param[in] afterSplit The edge to add if a split is performed - * @param[in] pos The relative position on the edge where the stop is located - * @param[in] stopConn The stop edge to connect to - * @param[in] forward whether we are aplitting a forward edge (backward edges get different names) - * @param[in] addExit whether we can just enter the stop or exit as well (cars should not exit yet) - */ - void splitEdge(_IntermodalEdge* const toSplit, int splitIndex, - _IntermodalEdge* afterSplit, const double relPos, const double length, const bool needSplit, - _IntermodalEdge* const stopConn, const bool forward = true, const bool addExit = true, const bool addEntry = true) { - std::vector<_IntermodalEdge*>& splitList = myAccessSplits[toSplit]; - if (splitList.empty()) { - splitList.push_back(toSplit); - } - if (!forward) { - splitIndex = (int)splitList.size() - 1 - splitIndex; - if (!needSplit) { - splitIndex--; - } - } - _IntermodalEdge* beforeSplit = splitList[splitIndex]; - if (needSplit) { - addEdge(afterSplit); - beforeSplit->transferSuccessors(afterSplit); - beforeSplit->addSuccessor(afterSplit); - if (forward) { - afterSplit->setLength(beforeSplit->getLength() - relPos); - beforeSplit->setLength(relPos); - } else { - afterSplit->setLength(relPos); - beforeSplit->setLength(beforeSplit->getLength() - relPos); - // rename backward edges for easier referencing - const std::string newID = beforeSplit->getID(); - beforeSplit->setID(afterSplit->getID()); - afterSplit->setID(newID); - } - splitList.insert(splitList.begin() + splitIndex + 1, afterSplit); - } else { - // don't split, use the present split edges - afterSplit = splitList[splitIndex + 1]; - } - // add access to / from edge - if (addEntry) { - _AccessEdge* access = new _AccessEdge(myNumericalID++, beforeSplit, stopConn, length); - addEdge(access); - beforeSplit->addSuccessor(access); - access->addSuccessor(stopConn); - } - if (addExit) { - // pedestrian case only, exit from public to pedestrian - _AccessEdge* exit = new _AccessEdge(myNumericalID++, stopConn, afterSplit, length); - addEdge(exit); - stopConn->addSuccessor(exit); - exit->addSuccessor(afterSplit); - } - } - - -private: - /// @brief the edge dictionary - std::vector<_IntermodalEdge*> myEdges; - - /// @brief retrieve the forward and backward edge for the given input edge E - std::map myBidiLookup; - - /// @brief retrieve the depart edges for the given input edge E - std::map > myDepartLookup; - - /// @brief retrieve the arrival edges for the given input edge E - std::map > myArrivalLookup; - - /// @brief the walking connector edge (fake walking area) - std::map myWalkingConnectorLookup; - - /// @brief retrieve the car edge for the given input edge E - std::map myCarLookup; - - /// @brief retrieve the public transport edges for the given line - std::map > myPTLines; - - /// @brief retrieve the representing edge for the given stopping place - std::map myStopConnections; - - /// @brief retrieve the splitted edges for the given "original" - std::map<_IntermodalEdge*, std::vector<_IntermodalEdge*> > myAccessSplits; - - int myNumericalID; - const int myCarWalkTransfer; - -private: - /// @brief Invalidated assignment operator - IntermodalNetwork& operator=(const IntermodalNetwork& s); - -}; diff --git a/Util/OSM2ODR/src/utils/router/IntermodalRouter.h b/Util/OSM2ODR/src/utils/router/IntermodalRouter.h deleted file mode 100644 index 2c80442f6..000000000 --- a/Util/OSM2ODR/src/utils/router/IntermodalRouter.h +++ /dev/null @@ -1,309 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file IntermodalRouter.h -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date Mon, 03 March 2014 -/// -// The IntermodalRouter builds a special network and (delegates to a SUMOAbstractRouter) -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include "SUMOAbstractRouter.h" -#include "DijkstraRouter.h" -#include "AStarRouter.h" -#include "IntermodalNetwork.h" -#include "EffortCalculator.h" -#include "CarEdge.h" -#include "StopEdge.h" -#include "PedestrianRouter.h" - -//#define IntermodalRouter_DEBUG_ROUTES - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class IntermodalRouter - * The router for pedestrians (on a bidirectional network of sidewalks and crossings) - */ -template -class IntermodalRouter : public SUMOAbstractRouter > { -public: - typedef IntermodalNetwork Network; - -private: - typedef void(*CreateNetCallback)(IntermodalRouter &); - typedef IntermodalEdge _IntermodalEdge; - typedef IntermodalTrip _IntermodalTrip; - typedef SUMOAbstractRouter<_IntermodalEdge, _IntermodalTrip> _InternalRouter; - typedef DijkstraRouter<_IntermodalEdge, _IntermodalTrip> _InternalDijkstra; - typedef AStarRouter<_IntermodalEdge, _IntermodalTrip> _InternalAStar; - -public: - struct TripItem { - TripItem(const std::string& _line = "") : - line(_line), intended(_line) {} - std::string line; - std::string vType = ""; - std::string destStop = ""; - std::string intended; // intended public transport vehicle id - double depart = -1.; // intended public transport departure - std::vector edges; - double traveltime = 0.; - double cost = 0.; - double length = 0.; - double departPos = INVALID_DOUBLE; - double arrivalPos = INVALID_DOUBLE; - std::string description = ""; - }; - - /// Constructor - IntermodalRouter(CreateNetCallback callback, const int carWalkTransfer, const std::string& routingAlgorithm, - const int routingMode = 0, EffortCalculator* calc = nullptr) : - SUMOAbstractRouter("IntermodalRouter", true, nullptr, nullptr, false, false), - myAmClone(false), myInternalRouter(nullptr), myIntermodalNet(nullptr), - myCallback(callback), myCarWalkTransfer(carWalkTransfer), myRoutingAlgorithm(routingAlgorithm), - myRoutingMode(routingMode), myExternalEffort(calc) { - } - - /// Destructor - virtual ~IntermodalRouter() { - delete myInternalRouter; - if (!myAmClone) { - delete myIntermodalNet; - } - } - - SUMOAbstractRouter* clone() { - createNet(); - return new IntermodalRouter(myIntermodalNet, myCarWalkTransfer, myRoutingAlgorithm, myRoutingMode, myExternalEffort); - } - - int getCarWalkTransfer() const { - return myCarWalkTransfer; - } - - /** @brief Builds the route between the given edges using the minimum effort at the given time - The definition of the effort depends on the wished routing scheme */ - bool compute(const E* from, const E* to, const double departPos, const double arrivalPos, - const std::string stopID, const double speed, - const V* const vehicle, const SVCPermissions modeSet, const SUMOTime msTime, - std::vector& into, const double externalFactor = 0.) { - createNet(); - _IntermodalTrip trip(from, to, departPos, arrivalPos, speed, msTime, 0, vehicle, modeSet, myExternalEffort, externalFactor); - std::vector intoEdges; - //std::cout << "compute from=" << from->getID() << " to=" << to->getID() << " dPos=" << departPos << " aPos=" << arrivalPos << " stopID=" << stopID << " speed=" << speed << " veh=" << Named::getIDSecure(vehicle) << " modeSet=" << modeSet << " t=" << msTime << " iFrom=" << myIntermodalNet->getDepartEdge(from, trip.departPos)->getID() << " iTo=" << (stopID != "" ? myIntermodalNet->getStopEdge(stopID) : myIntermodalNet->getArrivalEdge(to, trip.arrivalPos))->getID() << "\n"; - const bool success = myInternalRouter->compute(myIntermodalNet->getDepartEdge(from, trip.departPos), - stopID != "" ? myIntermodalNet->getStopEdge(stopID) : myIntermodalNet->getArrivalEdge(to, trip.arrivalPos), - &trip, msTime, intoEdges); - if (success) { - std::string lastLine = ""; - double time = STEPS2TIME(msTime); - double effort = 0.; - double length = 0.; - const _IntermodalEdge* prev = nullptr; - for (const _IntermodalEdge* iEdge : intoEdges) { - if (iEdge->includeInRoute(false)) { - if (iEdge->getLine() == "!stop") { - if (into.size() > 0) { - // previous stage ends at stop - into.back().destStop = iEdge->getID(); - if (myExternalEffort != nullptr) { - into.back().description = myExternalEffort->output(iEdge->getNumericalID()); - } - if (lastLine == "!ped") { - lastLine = ""; // a stop always starts a new trip item - } - } else { - // trip starts at stop - lastLine = ""; - into.push_back(TripItem("!stop")); - into.back().destStop = iEdge->getID(); - } - } else { - if (iEdge->getLine() != lastLine) { - lastLine = iEdge->getLine(); - if (lastLine == "!car") { - into.push_back(TripItem(vehicle->getID())); - into.back().vType = vehicle->getParameter().vtypeid; - } else if (lastLine == "!ped") { - into.push_back(TripItem()); - } else { - into.push_back(TripItem(lastLine)); - into.back().depart = iEdge->getIntended(time, into.back().intended); - } - into.back().departPos = iEdge->getStartPos(); - } - if (into.back().edges.empty() || into.back().edges.back() != iEdge->getEdge()) { - into.back().edges.push_back(iEdge->getEdge()); - into.back().arrivalPos = iEdge->getEndPos(); - } - } - } - const double prevTime = time, prevEffort = effort, prevLength = length; - myInternalRouter->updateViaCost(prev, iEdge, &trip, time, effort, length); - prev = iEdge; - if (!into.empty()) { - into.back().traveltime += time - prevTime; - into.back().cost += effort - prevEffort; - into.back().length += length - prevLength; - if (into.back().depart < 0) { - into.back().depart = prevTime; - } - } - } - } -#ifdef IntermodalRouter_DEBUG_ROUTES - double time = STEPS2TIME(msTime); - for (const _IntermodalEdge* iEdge : intoEdges) { - const double edgeEffort = myInternalRouter->getEffort(iEdge, &trip, time); - time += edgeEffort; - std::cout << iEdge->getID() << "(" << iEdge->getLine() << "): " << edgeEffort << std::endl; - } - std::cout << TIME2STEPS(msTime) << " trip from " << from->getID() << " to " << (to != nullptr ? to->getID() : stopID) - << " departPos=" << trip.departPos - << " arrivalPos=" << trip.arrivalPos - << " modes=" << getVehicleClassNames(modeSet) - << " edges=" << toString(intoEdges) -// << " resultEdges=" << toString(into) - << " time=" << time - << "\n"; -#endif - return success; - } - - /** @brief Builds the route between the given edges using the minimum effort at the given time - The definition of the effort depends on the wished routing scheme */ - bool compute(const E*, const E*, const _IntermodalTrip* const, - SUMOTime, std::vector&, bool) { - throw ProcessError("Do not use this method"); - } - - void prohibit(const std::vector& toProhibit) { - createNet(); - std::vector<_IntermodalEdge*> toProhibitPE; - for (typename std::vector::const_iterator it = toProhibit.begin(); it != toProhibit.end(); ++it) { - toProhibitPE.push_back(myIntermodalNet->getBothDirections(*it).first); - toProhibitPE.push_back(myIntermodalNet->getBothDirections(*it).second); - toProhibitPE.push_back(myIntermodalNet->getCarEdge(*it)); - } - myInternalRouter->prohibit(toProhibitPE); - } - - void writeNetwork(OutputDevice& dev) { - createNet(); - for (_IntermodalEdge* e : myIntermodalNet->getAllEdges()) { - dev.openTag(SUMO_TAG_EDGE); - dev.writeAttr(SUMO_ATTR_ID, e->getID()); - dev.writeAttr(SUMO_ATTR_LINE, e->getLine()); - dev.writeAttr(SUMO_ATTR_LENGTH, e->getLength()); - dev.writeAttr("successors", toString(e->getSuccessors(SVC_IGNORING))); - dev.closeTag(); - } - } - - void writeWeights(OutputDevice& dev) { - createNet(); - _IntermodalTrip trip(nullptr, nullptr, 0., 0., DEFAULT_PEDESTRIAN_SPEED, 0, 0, nullptr, SVC_PASSENGER | SVC_BICYCLE | SVC_BUS); - for (_IntermodalEdge* e : myIntermodalNet->getAllEdges()) { - dev.openTag(SUMO_TAG_EDGE); - dev.writeAttr(SUMO_ATTR_ID, e->getID()); - dev.writeAttr("traveltime", e->getTravelTime(&trip, 0.)); - dev.writeAttr("effort", e->getEffort(&trip, 0.)); - dev.closeTag(); - } - } - - Network* getNetwork() const { - return myIntermodalNet; - } - - EffortCalculator* getExternalEffort() const { - return myExternalEffort; - } - -private: - IntermodalRouter(Network* net, const int carWalkTransfer, const std::string& routingAlgorithm, - const int routingMode, EffortCalculator* calc) : - SUMOAbstractRouter("IntermodalRouterClone", true, nullptr, nullptr, false, false), myAmClone(true), - myInternalRouter(new _InternalDijkstra(net->getAllEdges(), true, - gWeightsRandomFactor > 1 ? & _IntermodalEdge::getTravelTimeStaticRandomized : & _IntermodalEdge::getTravelTimeStatic)), - myIntermodalNet(net), myCarWalkTransfer(carWalkTransfer), myRoutingAlgorithm(routingAlgorithm), myRoutingMode(routingMode), myExternalEffort(calc) {} - - static inline double getCombined(const _IntermodalEdge* const edge, const _IntermodalTrip* const trip, double time) { - return edge->getTravelTime(trip, time) + trip->externalFactor * trip->calc->getEffort(edge->getNumericalID()); - } - - inline void createNet() { - if (myIntermodalNet == nullptr) { - myIntermodalNet = new Network(E::getAllEdges(), false, myCarWalkTransfer); - myIntermodalNet->addCarEdges(E::getAllEdges()); - myCallback(*this); - switch (myRoutingMode) { - case 0: - if (myRoutingAlgorithm == "astar") { - myInternalRouter = new _InternalAStar(myIntermodalNet->getAllEdges(), true, - gWeightsRandomFactor > 1 ? &_IntermodalEdge::getTravelTimeStaticRandomized : &_IntermodalEdge::getTravelTimeStatic, nullptr, true); - } else { - myInternalRouter = new _InternalDijkstra(myIntermodalNet->getAllEdges(), true, - gWeightsRandomFactor > 1 ? &_IntermodalEdge::getTravelTimeStaticRandomized : &_IntermodalEdge::getTravelTimeStatic, nullptr, false, nullptr, true); - } - break; - case 1: - myInternalRouter = new _InternalDijkstra(myIntermodalNet->getAllEdges(), true, &_IntermodalEdge::getTravelTimeAggregated, nullptr, false, nullptr, true); - break; - case 2: - myInternalRouter = new _InternalDijkstra(myIntermodalNet->getAllEdges(), true, &_IntermodalEdge::getEffortStatic, &_IntermodalEdge::getTravelTimeStatic, false, nullptr, true); - break; - case 3: - if (myExternalEffort != nullptr) { - std::vector edgeLines; - for (const auto e : myIntermodalNet->getAllEdges()) { - edgeLines.push_back(e->getLine()); - } - myExternalEffort->init(edgeLines); - } - myInternalRouter = new _InternalDijkstra(myIntermodalNet->getAllEdges(), true, &getCombined, &_IntermodalEdge::getTravelTimeStatic, false, myExternalEffort, true); - break; - } - } - } - -private: - const bool myAmClone; - _InternalRouter* myInternalRouter; - Network* myIntermodalNet; - CreateNetCallback myCallback; - const int myCarWalkTransfer; - const std::string myRoutingAlgorithm; - const int myRoutingMode; - EffortCalculator* const myExternalEffort; - - -private: - /// @brief Invalidated assignment operator - IntermodalRouter& operator=(const IntermodalRouter& s); - -}; diff --git a/Util/OSM2ODR/src/utils/router/IntermodalTrip.h b/Util/OSM2ODR/src/utils/router/IntermodalTrip.h deleted file mode 100644 index dbf14bada..000000000 --- a/Util/OSM2ODR/src/utils/router/IntermodalTrip.h +++ /dev/null @@ -1,95 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file IntermodalTrip.h -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @author Robert Hilbrich -/// @date Mon, 03 March 2014 -/// -// The "vehicle" definition for the Intermodal Router -/****************************************************************************/ -#pragma once -#include - -#include -#include - -#include "EffortCalculator.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -/// @brief the "vehicle" type that is given to the internal router (SUMOAbstractRouter) -template -class IntermodalTrip { -public: - IntermodalTrip(const E* _from, const E* _to, double _departPos, double _arrivalPos, - double _speed, SUMOTime _departTime, const N* _node, - const V* _vehicle = 0, const SVCPermissions _modeSet = SVC_PEDESTRIAN, - const EffortCalculator* const _calc = nullptr, const double _externalFactor = 0.) : - from(_from), - to(_to), - departPos(_departPos < 0 ? _from->getLength() + _departPos : _departPos), - arrivalPos(_arrivalPos < 0 ? _to->getLength() + _arrivalPos : _arrivalPos), - speed(_speed), - departTime(_departTime), - node(_node), - vehicle(_vehicle), - modeSet(_modeSet), - calc(_calc), - externalFactor(_externalFactor) { - } - - // exists just for debugging purposes - std::string getID() const { - return from->getID() + ":" + to->getID() + ":" + time2string(departTime); - } - - - inline SUMOVehicleClass getVClass() const { - return vehicle != 0 ? vehicle->getVClass() : SVC_PEDESTRIAN; - } - - inline double getLength() const { - // person length is arbitrary (only used in the context of rail-reversal validity - return vehicle != 0 ? vehicle->getVehicleType().getLength() : 1; - } - - // only used by AStar - inline double getMaxSpeed() const { - return vehicle != nullptr ? vehicle->getMaxSpeed() : speed; - } - - // only used by AStar - inline double getChosenSpeedFactor() const { - return vehicle != nullptr ? vehicle->getChosenSpeedFactor() : 1.0; - } - - const E* const from; - const E* const to; - const double departPos; - const double arrivalPos; - const double speed; - const SUMOTime departTime; - const N* const node; // indicates whether only routing across this node shall be performed - const V* const vehicle; // indicates which vehicle may be used - const SVCPermissions modeSet; - const EffortCalculator* const calc; - const double externalFactor; - -private: - /// @brief Invalidated assignment operator. - IntermodalTrip& operator=(const IntermodalTrip&); -}; diff --git a/Util/OSM2ODR/src/utils/router/LogitCalculator.h b/Util/OSM2ODR/src/utils/router/LogitCalculator.h deleted file mode 100644 index 2d540f528..000000000 --- a/Util/OSM2ODR/src/utils/router/LogitCalculator.h +++ /dev/null @@ -1,149 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2002-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file LogitCalculator.h -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @author Jakob Erdmann -/// @date Sept 2002 -/// -// Calculators for route costs and probabilities -/****************************************************************************/ -#pragma once -#include - -#include -#include - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class LogitCalculator - * @brief Cost calculation with c-logit or logit method. - */ -template -class LogitCalculator : public RouteCostCalculator { -public: - /// Constructor - LogitCalculator(const double beta, const double gamma, - const double theta) : myBeta(beta), myGamma(gamma), myTheta(theta) {} - - /// Destructor - virtual ~LogitCalculator() {} - - void setCosts(R* route, const double costs, const bool /* isActive */) const { - route->setCosts(costs); - } - - /** @brief calculate the probabilities in the logit model */ - void calculateProbabilities(std::vector alternatives, const V* const veh, const SUMOTime time) { - const double theta = myTheta >= 0 ? myTheta : getThetaForCLogit(alternatives); - const double beta = myBeta >= 0 ? myBeta : getBetaForCLogit(alternatives); - if (beta > 0) { - // calculate commonalities - for (typename std::vector::const_iterator i = alternatives.begin(); i != alternatives.end(); i++) { - const R* pR = *i; - double lengthR = 0; - const std::vector& edgesR = pR->getEdgeVector(); - for (typename std::vector::const_iterator edge = edgesR.begin(); edge != edgesR.end(); ++edge) { - //@todo we should use costs here - lengthR += (*edge)->getTravelTime(veh, STEPS2TIME(time)); - } - double overlapSum = 0; - for (typename std::vector::const_iterator j = alternatives.begin(); j != alternatives.end(); j++) { - const R* pS = *j; - double overlapLength = 0.; - double lengthS = 0; - const std::vector& edgesS = pS->getEdgeVector(); - for (typename std::vector::const_iterator edge = edgesS.begin(); edge != edgesS.end(); ++edge) { - lengthS += (*edge)->getTravelTime(veh, STEPS2TIME(time)); - if (std::find(edgesR.begin(), edgesR.end(), *edge) != edgesR.end()) { - overlapLength += (*edge)->getTravelTime(veh, STEPS2TIME(time)); - } - } - overlapSum += pow(overlapLength / sqrt(lengthR * lengthS), myGamma); - } - myCommonalities[pR] = beta * log(overlapSum); - } - } - for (typename std::vector::iterator i = alternatives.begin(); i != alternatives.end(); i++) { - R* pR = *i; - double weightedSum = 0; - for (typename std::vector::iterator j = alternatives.begin(); j != alternatives.end(); j++) { - R* pS = *j; - weightedSum += exp(theta * (pR->getCosts() - pS->getCosts() + myCommonalities[pR] - myCommonalities[pS])); - } - pR->setProbability(1. / weightedSum); - } - } - - -private: - /** @brief calculate the scaling factor in the logit model */ - double getBetaForCLogit(const std::vector alternatives) const { - double min = std::numeric_limits::max(); - for (typename std::vector::const_iterator i = alternatives.begin(); i != alternatives.end(); i++) { - const double cost = (*i)->getCosts() / 3600.; - if (cost < min) { - min = cost; - } - } - return min; - } - - /** @brief calculate the scaling factor in the logit model */ - double getThetaForCLogit(const std::vector alternatives) const { - // @todo this calculation works for travel times only - double sum = 0.; - double diff = 0.; - double min = std::numeric_limits::max(); - for (typename std::vector::const_iterator i = alternatives.begin(); i != alternatives.end(); i++) { - const double cost = (*i)->getCosts() / 3600.; - sum += cost; - if (cost < min) { - min = cost; - } - } - const double meanCost = sum / double(alternatives.size()); - for (typename std::vector::const_iterator i = alternatives.begin(); i != alternatives.end(); i++) { - diff += pow((*i)->getCosts() / 3600. - meanCost, 2); - } - const double cvCost = sqrt(diff / double(alternatives.size())) / meanCost; - // @todo re-evaluate function - // if (cvCost > 0.04) { // Magic numbers from Lohse book - return 3.1415926535897932384626433832795 / (sqrt(6.) * cvCost * (min + 1.1)) / 3600.; - // } - // return 1./3600.; - } - - -private: - /// @brief logit beta - value - const double myBeta; - - /// @brief logit gamma - value - const double myGamma; - - /// @brief logit theta - value - const double myTheta; - - /// @brief The route commonality factors for c-logit - std::map myCommonalities; - -private: - /** @brief invalidated assignment operator */ - LogitCalculator& operator=(const LogitCalculator& s); - -}; diff --git a/Util/OSM2ODR/src/utils/router/PedestrianEdge.h b/Util/OSM2ODR/src/utils/router/PedestrianEdge.h deleted file mode 100644 index eab4937aa..000000000 --- a/Util/OSM2ODR/src/utils/router/PedestrianEdge.h +++ /dev/null @@ -1,104 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file PedestrianEdge.h -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @author Robert Hilbrich -/// @date Mon, 03 March 2014 -/// -// The pedestrian accessible edges for the Intermodal Router -/****************************************************************************/ -#pragma once -#include - -#define TL_RED_PENALTY 20 - -//#define IntermodalRouter_DEBUG_EFFORTS - - -// =========================================================================== -// class definitions -// =========================================================================== -/// @brief the pedestrian edge type that is given to the internal router (SUMOAbstractRouter) -template -class PedestrianEdge : public IntermodalEdge { -public: - PedestrianEdge(int numericalID, const E* edge, const L* lane, bool forward, const double pos = -1.) : - IntermodalEdge(edge->getID() + (edge->isWalkingArea() ? "" : (forward ? "_fwd" : "_bwd")) + toString(pos), numericalID, edge, "!ped"), - myLane(lane), - myForward(forward), - myStartPos(pos >= 0 ? pos : (forward ? 0. : edge->getLength())) { } - - bool includeInRoute(bool allEdges) const { - return allEdges || (!this->getEdge()->isCrossing() && !this->getEdge()->isWalkingArea() && !this->getEdge()->isInternal()); - } - - bool prohibits(const IntermodalTrip* const trip) const { - if (trip->node == 0) { - // network only includes IntermodalEdges - return false; - } else { - // limit routing to the surroundings of the specified node - return (this->getEdge()->getFromJunction() != trip->node - && this->getEdge()->getToJunction() != trip->node); - } - } - - virtual double getTravelTime(const IntermodalTrip* const trip, double time) const { - double length = this->getLength(); - if (this->getEdge() == trip->from && !myForward && trip->departPos < myStartPos) { - length = trip->departPos - (myStartPos - this->getLength()); - } - if (this->getEdge() == trip->to && myForward && trip->arrivalPos < myStartPos + this->getLength()) { - length = trip->arrivalPos - myStartPos; - } - if (this->getEdge() == trip->from && myForward && trip->departPos > myStartPos) { - length -= (trip->departPos - myStartPos); - } - if (this->getEdge() == trip->to && !myForward && trip->arrivalPos > myStartPos - this->getLength()) { - length -= (trip->arrivalPos - (myStartPos - this->getLength())); - } - // ensure that 'normal' edges always have a higher weight than connector edges - length = MAX2(length, NUMERICAL_EPS); - double tlsDelay = 0; - // @note pedestrian traffic lights should never have LINKSTATE_TL_REDYELLOW - if (this->getEdge()->isCrossing() && myLane->getIncomingLinkState() == LINKSTATE_TL_RED) { - // red traffic lights occurring later in the route may be green by the time we arrive - tlsDelay += MAX2(double(0), TL_RED_PENALTY - (time - STEPS2TIME(trip->departTime))); - } -#ifdef IntermodalRouter_DEBUG_EFFORTS - std::cout << " effort for " << trip->getID() << " at " << time << " edge=" << edge->getID() << " effort=" << length / trip->speed + tlsDelay << " l=" << length << " s=" << trip->speed << " tlsDelay=" << tlsDelay << "\n"; -#endif - return length / trip->speed + tlsDelay; - } - - double getStartPos() const { - return myStartPos; - } - - double getEndPos() const { - return myForward ? myStartPos + this->getLength() : myStartPos - this->getLength(); - } - -private: - /// @brief the original edge - const L* myLane; - - /// @brief the direction of this edge - const bool myForward; - - /// @brief the starting position for split edges - const double myStartPos; - -}; diff --git a/Util/OSM2ODR/src/utils/router/PedestrianRouter.h b/Util/OSM2ODR/src/utils/router/PedestrianRouter.h deleted file mode 100644 index 6e7bd9719..000000000 --- a/Util/OSM2ODR/src/utils/router/PedestrianRouter.h +++ /dev/null @@ -1,145 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file PedestrianRouter.h -/// @author Jakob Erdmann -/// @date Mon, 03 March 2014 -/// -// The Pedestrian Router builds a special network and delegates to a SUMOAbstractRouter. -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include -#include -#include -#include -#include -#include "SUMOAbstractRouter.h" -#include "DijkstraRouter.h" -#include "IntermodalNetwork.h" - -//#define PedestrianRouter_DEBUG_ROUTES - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class PedestrianRouter - * The router for pedestrians (on a bidirectional network of sidewalks and crossings) - */ -template -class PedestrianRouter : public SUMOAbstractRouter > { -private: - typedef IntermodalEdge _IntermodalEdge; - typedef IntermodalNetwork _IntermodalNetwork; - typedef IntermodalTrip _IntermodalTrip; - typedef DijkstraRouter<_IntermodalEdge, _IntermodalTrip> _InternalRouter; - -public: - /// Constructor - PedestrianRouter(): - SUMOAbstractRouter("PedestrianRouter", true, nullptr, nullptr, false, false), myAmClone(false) { - myPedNet = new _IntermodalNetwork(E::getAllEdges(), true); - myInternalRouter = new _InternalRouter(myPedNet->getAllEdges(), true, - gWeightsRandomFactor > 1 ? &_IntermodalEdge::getTravelTimeStaticRandomized : &_IntermodalEdge::getTravelTimeStatic); - } - - PedestrianRouter(_IntermodalNetwork* net): - SUMOAbstractRouter("PedestrianRouterClone", true, nullptr, nullptr, false, false), myAmClone(true) { - myPedNet = net; - myInternalRouter = new _InternalRouter(myPedNet->getAllEdges(), true, - gWeightsRandomFactor > 1 ? &_IntermodalEdge::getTravelTimeStaticRandomized : &_IntermodalEdge::getTravelTimeStatic); - } - - /// Destructor - virtual ~PedestrianRouter() { - delete myInternalRouter; - if (!myAmClone) { - delete myPedNet; - } - } - - virtual SUMOAbstractRouter* clone() { - return new PedestrianRouter(myPedNet); - } - - /** @brief Builds the route between the given edges using the minimum effort at the given time - The definition of the effort depends on the wished routing scheme */ - double compute(const E* from, const E* to, double departPos, double arrivalPos, double speed, - SUMOTime msTime, const N* onlyNode, std::vector& into, bool allEdges = false) { - if (getSidewalk(from) == 0) { - WRITE_WARNING("Departure edge '" + from->getID() + "' does not allow pedestrians."); - return false; - } - if (getSidewalk(to) == 0) { - WRITE_WARNING("Destination edge '" + to->getID() + "' does not allow pedestrians."); - return false; - } - _IntermodalTrip trip(from, to, departPos, arrivalPos, speed, msTime, onlyNode); - std::vector intoPed; - const bool success = myInternalRouter->compute(myPedNet->getDepartConnector(from), - myPedNet->getArrivalConnector(to), - &trip, msTime, intoPed); - double time = 0.; - if (success) { - for (const _IntermodalEdge* pedEdge : intoPed) { - if (pedEdge->includeInRoute(allEdges)) { - into.push_back(pedEdge->getEdge()); - } - time += myInternalRouter->getEffort(pedEdge, &trip, time); - } - } -#ifdef PedestrianRouter_DEBUG_ROUTES - std::cout << TIME2STEPS(msTime) << " trip from " << from->getID() << " to " << to->getID() - << " departPos=" << departPos - << " arrivalPos=" << arrivalPos - << " onlyNode=" << (onlyNode == 0 ? "NULL" : onlyNode->getID()) - << " edges=" << toString(intoPed) - << " resultEdges=" << toString(into) - << " time=" << time - << "\n"; -#endif - return success ? time : -1.; - } - - /** @brief Builds the route between the given edges using the minimum effort at the given time - The definition of the effort depends on the wished routing scheme */ - bool compute(const E*, const E*, const _IntermodalTrip* const, - SUMOTime, std::vector&, bool) { - throw ProcessError("Do not use this method"); - } - - void prohibit(const std::vector& toProhibit) { - std::vector<_IntermodalEdge*> toProhibitPE; - for (typename std::vector::const_iterator it = toProhibit.begin(); it != toProhibit.end(); ++it) { - toProhibitPE.push_back(myPedNet->getBothDirections(*it).first); - toProhibitPE.push_back(myPedNet->getBothDirections(*it).second); - } - myInternalRouter->prohibit(toProhibitPE); - } - -private: - const bool myAmClone; - _InternalRouter* myInternalRouter; - _IntermodalNetwork* myPedNet; - - -private: - /// @brief Invalidated assignment operator - PedestrianRouter& operator=(const PedestrianRouter& s); - -}; diff --git a/Util/OSM2ODR/src/utils/router/PublicTransportEdge.h b/Util/OSM2ODR/src/utils/router/PublicTransportEdge.h deleted file mode 100644 index 87f62a29b..000000000 --- a/Util/OSM2ODR/src/utils/router/PublicTransportEdge.h +++ /dev/null @@ -1,157 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file PublicTransportEdge.h -/// @author Michael Behrisch -/// @date Mon, 03 March 2014 -/// -// The PublicTransportEdge is a special intermodal edge connecting the stop edges with scheduled traffic -/****************************************************************************/ -#pragma once -#include - -#include "IntermodalEdge.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -/// @brief the public transport edge type connecting the stop edges -template -class PublicTransportEdge : public IntermodalEdge { -private: - struct Schedule { - Schedule(const std::string& _id, const SUMOTime _begin, const int _repetitionNumber, const SUMOTime _period, const SUMOTime _travelTime) - : ids({ - _id - }), begin(_begin), repetitionNumber(_repetitionNumber), period(_period), travelTime(_travelTime) {} - // the id of the vehicle or flow from which this schedule is generated - std::vector ids; - const SUMOTime begin; - int repetitionNumber; - // the repetition period for a flow or -1 for a vehicle - SUMOTime period; - const SUMOTime travelTime; - private: - /// @brief Invalidated assignment operator - Schedule& operator=(const Schedule& src); - }; - -public: - PublicTransportEdge(const std::string id, int numericalID, const IntermodalEdge* entryStop, const E* endEdge, const std::string& line, const double length) : - IntermodalEdge(line + ":" + (id != "" ? id : endEdge->getID()), numericalID, endEdge, line, length), myEntryStop(entryStop) { } - - bool includeInRoute(bool /* allEdges */) const { - return true; - } - - bool prohibits(const IntermodalTrip* const trip) const { - return (trip->modeSet & SVC_BUS) == 0; - } - - const IntermodalEdge* getEntryStop() const { - return myEntryStop; - } - - bool hasSchedule(const SUMOTime begin) const { - return mySchedules.find(begin) != mySchedules.end(); - } - - void addSchedule(const std::string id, const SUMOTime begin, const int repetitionNumber, const SUMOTime period, const SUMOTime travelTime) { - // try to merge with existing vehicle or flow - bool found = false; - for (auto& it : mySchedules) { - Schedule& s = it.second; - if (travelTime == s.travelTime) { - if (repetitionNumber == -1 && s.repetitionNumber == 1) { - if (begin > s.begin) { - s.period = begin - s.begin; - found = true; - } - } else if (begin == s.begin + s.repetitionNumber * s.period) { - found = true; - } - if (found) { - s.repetitionNumber += MAX2(repetitionNumber, 1); - s.ids.push_back(id); - break; - } - } - } - if (!found) { - mySchedules.insert(std::make_pair(begin, Schedule(id, begin, MAX2(repetitionNumber, 1), MAX2(period, 1), travelTime))); - } - } - - double getTravelTime(const IntermodalTrip* const /* trip */, double time) const { - SUMOTime minArrival = SUMOTime_MAX; - const SUMOTime step = TIME2STEPS(time); - for (typename std::multimap::const_iterator it = mySchedules.begin(); it != mySchedules.end(); ++it) { - const Schedule& s = it->second; - if (it->first > minArrival) { - break; - } - const SUMOTime offset = MAX2(0, step - s.begin); - int running = (int)(offset / s.period); - if (offset % s.period != 0) { - running++; - } - if (running < s.repetitionNumber) { - const SUMOTime nextDepart = s.begin + running * s.period; - minArrival = MIN2(nextDepart + s.travelTime, minArrival); - //std::cout << " edge=" << myEntryStop->getID() << "->" << this->getID() << " beg=" << s.begin << " end=" << s.end - // << " atTime=" << time - // << " running=" << running << " nextDepart=" << nextDepart - // << " minASec=" << minArrivalSec << " travelTime=" << minArrivalSec - time << "\n"; - } - } - return STEPS2TIME(minArrival - step); - } - - double getIntended(const double time, std::string& intended) const { - /// @note: duplicates some code of getTravelTime() - SUMOTime minArrival = SUMOTime_MAX; - double bestDepartTime = std::numeric_limits::max(); - const SUMOTime step = TIME2STEPS(time); - for (typename std::multimap::const_iterator it = mySchedules.begin(); it != mySchedules.end(); ++it) { - const Schedule& s = it->second; - if (it->first > minArrival) { - break; - } - const SUMOTime offset = MAX2(0, step - s.begin); - int running = (int)(offset / s.period); - if (offset % s.period != 0) { - running++; - } - if (running < s.repetitionNumber) { - const SUMOTime nextDepart = s.begin + running * s.period; - if (nextDepart + s.travelTime < minArrival) { - minArrival = nextDepart + s.travelTime; - bestDepartTime = STEPS2TIME(nextDepart); - // see naming scheme inMSInsertionControl::determineCandidates() - if (s.ids.size() == 1 || running >= (int)s.ids.size()) { - intended = s.repetitionNumber == 1 ? s.ids[0] : s.ids[0] + "." + toString(running); - } else { - intended = s.ids[running]; - } - } - } - } - return bestDepartTime; - } - -private: - std::multimap mySchedules; - const IntermodalEdge* const myEntryStop; - -}; diff --git a/Util/OSM2ODR/src/utils/router/RailEdge.h b/Util/OSM2ODR/src/utils/router/RailEdge.h deleted file mode 100644 index e7752a358..000000000 --- a/Util/OSM2ODR/src/utils/router/RailEdge.h +++ /dev/null @@ -1,260 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file RailEdge.h -/// @author Jakob Erdmann -/// @date 26.02.2020 -/// -// The RailEdge is a wrapper around a ROEdge or a MSEdge used for railway routing -/****************************************************************************/ -#pragma once -#include -#include - -//#define RailEdge_DEBUG_TURNS -//#define RailEdge_DEBUG_INIT -//#define RailEdge_DEBUG_SUCCESSORS -#define RailEdge_DEBUGID "" -//#define RailEdge_DEBUG_COND(obj) ((obj != 0 && (obj)->getID() == RailEdge_DEBUGID)) -#define RailEdge_DEBUG_COND(obj) (true) - -// =========================================================================== -// class definitions -// =========================================================================== -/// @brief the edge type representing backward edges -template -class RailEdge { -public: - typedef RailEdge _RailEdge; - typedef std::vector > ConstEdgePairVector; - - RailEdge(const E* orig) : - myNumericalID(orig->getNumericalID()), - myOriginal(orig), - myTurnaround(nullptr), - myIsVirtual(true) - { } - - RailEdge(const E* turnStart, const E* turnEnd, int numericalID) : - myNumericalID(numericalID), - myID("TrainReversal!" + turnStart->getID() + "->" + turnEnd->getID()), - myOriginal(nullptr), - myTurnaround(nullptr), - myIsVirtual(true), - myMaxLength(turnStart->getLength()), - myStartLength(turnStart->getLength()) { - myViaSuccessors.push_back(std::make_pair(turnEnd->getRailwayRoutingEdge(), nullptr)); - } - - void update(double maxTrainLength, const std::vector& replacementEdges) { - if (maxTrainLength > myMaxLength) { - myMaxLength = maxTrainLength; - myReplacementEdges = replacementEdges; -#ifdef RailEdge_DEBUG_INIT - std::cout << " update RailEdge " << getID() << " myMaxLength=" << myMaxLength << " repl=" << toString(myReplacementEdges) << "\n"; -#endif - } - } - - void addVirtualTurns(const E* forward, const E* backward, - std::vector<_RailEdge*>& railEdges, int& numericalID, double dist, - double maxTrainLength, const std::vector& replacementEdges) { - // search backwards until dist and add virtual turnaround edges with - // replacement edges up to the real turnaround -#ifdef RailEdge_DEBUG_INIT - std::cout << "addVirtualTurns forward=" << forward->getID() << " backward=" << backward->getID() << " dist=" << dist - << " maxLength=" << maxTrainLength << " repl=" << toString(replacementEdges) << "\n"; -#endif - if (dist <= 0) { - return; - } - for (const E* prev : forward->getPredecessors()) { - if (prev == backward) { - continue; - } - const E* bidi = prev->getBidiEdge(); - if (backward->isConnectedTo(*bidi, SVC_IGNORING)) { - _RailEdge* prevRailEdge = prev->getRailwayRoutingEdge(); - if (prevRailEdge->myTurnaround == nullptr) { - prevRailEdge->myTurnaround = new _RailEdge(prev, bidi, numericalID++); - prevRailEdge->myViaSuccessors.push_back(std::make_pair(prevRailEdge->myTurnaround, nullptr)); - railEdges.push_back(prevRailEdge->myTurnaround); -#ifdef RailEdge_DEBUG_INIT - std::cout << " RailEdge " << prevRailEdge->getID() << " virtual turnaround " << prevRailEdge->myTurnaround->getID() << "\n"; -#endif - } - prevRailEdge->myTurnaround->update(prev->getLength() + maxTrainLength, replacementEdges); - std::vector replacementEdges2; - replacementEdges2.push_back(prev); - replacementEdges2.insert(replacementEdges2.end(), replacementEdges.begin(), replacementEdges.end()); - addVirtualTurns(prev, bidi, railEdges, numericalID, dist - prev->getLength(), - maxTrainLength + prev->getLength(), replacementEdges2); - } - } - } - - void init(std::vector<_RailEdge*>& railEdges, int& numericalID, double maxTrainLength) { - // replace turnaround-via with an explicit RailEdge that checks length - for (const auto& viaPair : myOriginal->getViaSuccessors()) { - if (viaPair.first == myOriginal->getBidiEdge()) { - // direction reversal - if (myTurnaround == nullptr) { - myTurnaround = new _RailEdge(myOriginal, viaPair.first, numericalID++); - myViaSuccessors.push_back(std::make_pair(myTurnaround, nullptr)); - railEdges.push_back(myTurnaround); -#ifdef RailEdge_DEBUG_INIT - std::cout << "RailEdge " << getID() << " actual turnaround " << myTurnaround->getID() << "\n"; -#endif - } - myTurnaround->myIsVirtual = false; - addVirtualTurns(myOriginal, viaPair.first, railEdges, numericalID, - maxTrainLength - getLength(), getLength(), std::vector {myOriginal}); - } else { - myViaSuccessors.push_back(std::make_pair(viaPair.first->getRailwayRoutingEdge(), - viaPair.second == nullptr ? nullptr : viaPair.second->getRailwayRoutingEdge())); - } - } -#ifdef RailEdge_DEBUG_SUCCESSORS - std::cout << "RailEdge " << getID() << " successors=" << myViaSuccessors.size() << " orig=" << myOriginal->getViaSuccessors().size() << "\n"; - for (const auto& viaPair : myViaSuccessors) { - std::cout << " " << viaPair.first->getID() << "\n"; - } -#endif - } - - /// @brief Returns the index (numeric id) of the edge - inline int getNumericalID() const { - return myNumericalID; - } - - /// @brief Returns the original edge - const E* getOriginal() const { - return myOriginal; - } - - /** @brief Returns the id of the edge - * @return The original edge's id - */ - const std::string& getID() const { - return myOriginal != nullptr ? myOriginal->getID() : myID; - } - - void insertOriginalEdges(double length, std::vector& into) const { - if (myOriginal != nullptr) { - into.push_back(myOriginal); - } else { - double seen = myStartLength; - int nPushed = 0; - if (seen >= length && !myIsVirtual) { - return; - } - // we need to find a replacement edge that has a real turn - for (const E* edge : myReplacementEdges) { - into.push_back(edge); - nPushed++; - seen += edge->getLength(); - if (seen >= length && edge->isConnectedTo(*edge->getBidiEdge(), SVC_IGNORING)) { - break; - } - //std::cout << "insertOriginalEdges length=" << length << " seen=" << seen << " into=" << toString(into) << "\n"; - } - const int last = (int)into.size() - 1; - for (int i = 0; i < nPushed; i++) { - into.push_back(into[last - i]->getBidiEdge()); - } - } - } - - /** @brief Returns the length of the edge - * @return The original edge's length - */ - double getLength() const { - return myOriginal == nullptr ? 0 : myOriginal->getLength(); - } - - //const RailEdge* getBidiEdge() const { - // return myOriginal->getBidiEdge()->getRailwayRoutingEdge(); - //} - - bool isInternal() const { - return myOriginal->isInternal(); - } - - inline bool prohibits(const V* const vehicle) const { -#ifdef RailEdge_DEBUG_TURNS - if (myOriginal == nullptr && RailEdge_DEBUG_COND(vehicle)) { - std::cout << getID() << " maxLength=" << myMaxLength << " veh=" << vehicle->getID() << " length=" << vehicle->getLength() << "\n"; - } -#endif - return vehicle->getLength() > myMaxLength || (myOriginal != nullptr && myOriginal->prohibits(vehicle)); - } - - inline bool restricts(const V* const vehicle) const { - return myOriginal != nullptr && myOriginal->restricts(vehicle); - } - - const ConstEdgePairVector& getViaSuccessors(SUMOVehicleClass vClass = SVC_IGNORING) const { - if (vClass == SVC_IGNORING || myOriginal == nullptr || myOriginal->isTazConnector()) { // || !MSNet::getInstance()->hasPermissions()) { - return myViaSuccessors; - } -#ifdef HAVE_FOX - FXMutexLock lock(mySuccessorMutex); -#endif - auto i = myClassesViaSuccessorMap.find(vClass); - if (i != myClassesViaSuccessorMap.end()) { - // can use cached value - return i->second; - } - // instantiate vector - ConstEdgePairVector& result = myClassesViaSuccessorMap[vClass]; - // this vClass is requested for the first time. rebuild all successors - for (const auto& viaPair : myViaSuccessors) { - if (viaPair.first->myOriginal == nullptr - || viaPair.first->myOriginal->isTazConnector() - || myOriginal->isConnectedTo(*viaPair.first->myOriginal, vClass)) { - result.push_back(viaPair); - } - } - return result; - } - - bool isVirtual() const { - return myIsVirtual; - } - -private: - const int myNumericalID; - const std::string myID; - const E* myOriginal; - _RailEdge* myTurnaround; - bool myIsVirtual; - - /// @brief actual edges to return when passing this (turnaround) edge - only forward - std::vector myReplacementEdges; - - /// @brief maximum train length for passing this (turnaround) edge - double myMaxLength = std::numeric_limits::max(); - /// @brief length of the edge where this turn starts - double myStartLength = 0; - - /// @brief The successors available for a given vClass - mutable std::map myClassesViaSuccessorMap; - - mutable ConstEdgePairVector myViaSuccessors; - -#ifdef HAVE_FOX - /// @brief Mutex for accessing successor edges - mutable FXMutex mySuccessorMutex; -#endif - -}; diff --git a/Util/OSM2ODR/src/utils/router/RailwayRouter.h b/Util/OSM2ODR/src/utils/router/RailwayRouter.h deleted file mode 100644 index c45e517f9..000000000 --- a/Util/OSM2ODR/src/utils/router/RailwayRouter.h +++ /dev/null @@ -1,219 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file RailwayRouter.h -/// @author Jakob Erdmann -/// @date Tue, 25 Feb 2020 -/// -// The RailwayRouter builds a special network for railway routing to handle train reversal restrictions (delegates to a SUMOAbstractRouter) -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include "SUMOAbstractRouter.h" -#include "DijkstraRouter.h" -#include "RailEdge.h" - -//#define RailwayRouter_DEBUG_ROUTES - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class RailwayRouter - * The router for pedestrians (on a bidirectional network of sidewalks and crossings) - */ -template -class RailwayRouter : public SUMOAbstractRouter { - -private: - - - typedef RailEdge _RailEdge; - typedef SUMOAbstractRouter<_RailEdge, V> _InternalRouter; - typedef DijkstraRouter<_RailEdge, V> _InternalDijkstra; - -public: - - /// Constructor - RailwayRouter(const std::vector& edges, bool unbuildIsWarning, typename SUMOAbstractRouter::Operation effortOperation, - typename SUMOAbstractRouter::Operation ttOperation = nullptr, bool silent = false, - const bool havePermissions = false, const bool haveRestrictions = false) : - SUMOAbstractRouter("RailwayRouter", true, effortOperation, ttOperation, havePermissions, haveRestrictions), - myInternalRouter(nullptr) { - myStaticOperation = effortOperation; - std::vector<_RailEdge*> railEdges1; // a RailEdge for existing edge - for (E* edge : edges) { - railEdges1.push_back(edge->getRailwayRoutingEdge()); - } - int numericalID = railEdges1.back()->getNumericalID() + 1; - std::vector<_RailEdge*> railEdges2 = railEdges1; // including additional edges for direction reversal - for (_RailEdge* railEdge : railEdges1) { - railEdge->init(railEdges2, numericalID, myMaxTrainLength); - } - myInternalRouter = new _InternalDijkstra(railEdges2, unbuildIsWarning, &getTravelTimeStatic, nullptr, silent, nullptr, havePermissions, haveRestrictions); - - } - - /// Destructor - virtual ~RailwayRouter() { - delete myInternalRouter; - } - - SUMOAbstractRouter* clone() { - return new RailwayRouter(this); - } - - /** @brief Builds the route between the given edges using the minimum effort at the given time - The definition of the effort depends on the wished routing scheme */ - bool compute(const E* from, const E* to, const V* const vehicle, SUMOTime msTime, std::vector& into, bool silent = false) { - // make sure that the vehicle can turn-around when starting on a short edge (the virtual turn-around for this lies backwards along the route / track) - std::vector backLengths; - double backDist = vehicle->getLength() - from->getLength(); - const E* start = from; - while (backDist > 0) { - const E* prev = getStraightPredecessor(start); - if (prev == nullptr) { - //WRITE_WARNING("Could not determine back edge for vehicle '" + vehicle->getID() + "' when routing from edge '" + from->getID() + "' at time " + time2string(msTime)); - break; - } - backDist -= prev->getLength(); - backLengths.push_back(prev->getLength() + (backLengths.empty() ? from->getLength() : backLengths.back())); - start = prev; - } - - std::vector intoTmp; - bool success = myInternalRouter->compute(start->getRailwayRoutingEdge(), to->getRailwayRoutingEdge(), vehicle, msTime, intoTmp, silent); - //std::cout << "RailRouter veh=" << vehicle->getID() << " from=" << from->getID() << " to=" << to->getID() << " t=" << time2string(msTime) << " success=" << success << "\n"; - if (success) { - const size_t intoSize = into.size(); - const int backIndex = (int)backLengths.size() - 1;; - for (const _RailEdge* railEdge : intoTmp) { - // prevent premature reversal on back edge (extend train length) - const double length = backIndex >= 0 ? backLengths[backIndex] : vehicle->getLength(); - railEdge->insertOriginalEdges(length, into); - } -#ifdef RailwayRouter_DEBUG_ROUTES - std::cout << "RailRouter: internal result=" << toString(intoTmp) << "\n"; - std::cout << "RailRouter: expanded result=" << toString(into) << "\n"; -#endif - if (backLengths.size() > 0) { - // skip the virtual back-edges - into.erase(into.begin() + intoSize, into.begin() + intoSize + backLengths.size()); -#ifdef RailwayRouter_DEBUG_ROUTES - std::cout << "RailRouter: backLengths=" << toString(backLengths) << " final result=" << toString(into) << "\n"; -#endif - if (*(into.begin() + intoSize) != from) { - WRITE_WARNING("Railway routing failure due to turn-around on short edge '" + from->getID() - + "' for vehicle '" + vehicle->getID() + "' time=" + time2string(msTime) + "."); - } - } - } - return success; - } - - void prohibit(const std::vector& toProhibit) { - std::vector<_RailEdge*> railEdges; - for (E* edge : toProhibit) { - railEdges.push_back(edge->getRailwayRoutingEdge()); - } - myInternalRouter->prohibit(railEdges); - } - - -private: - RailwayRouter(RailwayRouter* other) : - SUMOAbstractRouter(other), - myInternalRouter(other->myInternalRouter->clone()) - {} - - static inline double getTravelTimeStatic(const RailEdge* const edge, const V* const veh, double time) { - if (edge->getOriginal() != nullptr) { - return (*myStaticOperation)(edge->getOriginal(), veh, time); - } else { - // turnaround edge - if (edge->isVirtual()) { - // add up time for replacement edges - std::vector repl; - edge->insertOriginalEdges(veh->getLength(), repl); - assert(repl.size() > 0); - double seenDist = 0; - double result = 0; - repl.pop_back(); // last edge must not be used fully - for (const E* e : repl) { - result += (*myStaticOperation)(e, veh, time + result); - seenDist += e->getLength(); - } - const double lengthOnLastEdge = MAX2(0.0, veh->getLength() - seenDist); - return result + myReversalPenalty + lengthOnLastEdge * myReversalPenaltyFactor; - } else { - // XXX if the edge from which this turnaround starts is longer - // than the vehicle, we could return a negative value here - // because the turnaround may happen once the vehicle has driven onto the edge - return myReversalPenalty; - } - } - } - - - static const E* getStraightPredecessor(const E* edge) { - const E* result = nullptr; - //std::cout << " getStraightPredecessor edge=" << edge->getID() << "\n"; - for (const E* cand : edge->getPredecessors()) { - if (!cand->isInternal() && cand->getBidiEdge() != edge) { - //std::cout << " cand=" << cand->getID() << "\n"; - if (result == nullptr) { - result = cand; - } else { - // predecessor not unique. Better abort with a warning - return nullptr; - } - } - } - return result; - } - -private: - _InternalRouter* myInternalRouter; - - /// @brief The object's operation to perform. (hack) - static typename SUMOAbstractRouter::Operation myStaticOperation; - - static double myReversalPenalty; - static double myReversalPenaltyFactor; - static double myMaxTrainLength; - -private: - /// @brief Invalidated assignment operator - RailwayRouter& operator=(const RailwayRouter& s); - -}; - -template -typename SUMOAbstractRouter::Operation RailwayRouter::myStaticOperation(nullptr); -template -double RailwayRouter::myReversalPenalty(60); -template -double RailwayRouter::myReversalPenaltyFactor(0.2); // 1/v -template -double RailwayRouter::myMaxTrainLength(5000); - - diff --git a/Util/OSM2ODR/src/utils/router/ReversedEdge.h b/Util/OSM2ODR/src/utils/router/ReversedEdge.h deleted file mode 100644 index a4bca7b25..000000000 --- a/Util/OSM2ODR/src/utils/router/ReversedEdge.h +++ /dev/null @@ -1,129 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file ReversedEdge.h -/// @author Michael Behrisch -/// @date 29.01.2020 -/// -// The ReversedEdge is a wrapper around a ROEdge or a MSEdge used for -// backward search -/****************************************************************************/ -#pragma once -#include - - -// =========================================================================== -// class definitions -// =========================================================================== -/// @brief the edge type representing backward edges -template -class ReversedEdge { -public: - typedef std::vector*, const ReversedEdge*> > ConstEdgePairVector; - - ReversedEdge(const E* orig) : myOriginal(orig) { - } - - void init() { - if (!myOriginal->isInternal()) { - for (const auto& viaPair : myOriginal->getViaSuccessors()) { - const ReversedEdge* revSource = viaPair.first->getReversedRoutingEdge(); - const E* via = viaPair.second; - const ReversedEdge* preVia = nullptr; - while (via != nullptr && via->isInternal()) { - via->getReversedRoutingEdge()->myViaSuccessors.push_back(std::make_pair(this, preVia)); - preVia = via->getReversedRoutingEdge(); - via = via->getViaSuccessors().front().second; - } - revSource->myViaSuccessors.push_back(std::make_pair(this, preVia)); - } - } - } - - /** @brief Returns the index (numeric id) of the edge - * @return The original edge's numerical id - */ - int getNumericalID() const { - return myOriginal->getNumericalID(); - } - - /** @brief Returns the id of the edge - * @return The original edge's id - */ - const std::string& getID() const { - return myOriginal->getID(); - } - - /** @brief Returns the length of the edge - * @return The original edge's length - */ - double getLength() const { - return myOriginal->getLength(); - } - - const ReversedEdge* getBidiEdge() const { - return myOriginal->getBidiEdge()->getReversedRoutingEdge(); - } - - bool isInternal() const { - return myOriginal->isInternal(); - } - - inline bool prohibits(const V* const vehicle) const { - return myOriginal->prohibits(vehicle); - } - - inline bool restricts(const V* const vehicle) const { - return myOriginal->restricts(vehicle); - } - - static inline double getTravelTimeStatic(const ReversedEdge* const edge, const V* const veh, double time) { - return edge->myOriginal->getTravelTime(veh, time); - } - - const ConstEdgePairVector& getViaSuccessors(SUMOVehicleClass vClass = SVC_IGNORING) const { - if (vClass == SVC_IGNORING || myOriginal->isTazConnector()) { // || !MSNet::getInstance()->hasPermissions()) { - return myViaSuccessors; - } -#ifdef HAVE_FOX - FXMutexLock lock(mySuccessorMutex); -#endif - auto i = myClassesViaSuccessorMap.find(vClass); - if (i != myClassesViaSuccessorMap.end()) { - // can use cached value - return i->second; - } - // instantiate vector - ConstEdgePairVector& result = myClassesViaSuccessorMap[vClass]; - // this vClass is requested for the first time. rebuild all successors - for (const auto& viaPair : myViaSuccessors) { - if (viaPair.first->myOriginal->isTazConnector() || viaPair.first->myOriginal->isConnectedTo(*myOriginal, vClass)) { - result.push_back(viaPair); - } - } - return result; - } - -private: - const E* myOriginal; - /// @brief The successors available for a given vClass - mutable std::map myClassesViaSuccessorMap; - - mutable ConstEdgePairVector myViaSuccessors; - -#ifdef HAVE_FOX - /// @brief Mutex for accessing successor edges - mutable FXMutex mySuccessorMutex; -#endif - -}; diff --git a/Util/OSM2ODR/src/utils/router/RouteCostCalculator.h b/Util/OSM2ODR/src/utils/router/RouteCostCalculator.h deleted file mode 100644 index 643274350..000000000 --- a/Util/OSM2ODR/src/utils/router/RouteCostCalculator.h +++ /dev/null @@ -1,115 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2002-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file RouteCostCalculator.h -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @author Jakob Erdmann -/// @date Sept 2002 -/// -// Calculators for route costs and probabilities -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include -#include -#include -#include - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class RouteCostCalculator - * @brief Abstract base class providing static factory method. - */ -template -class RouteCostCalculator { -public: - static RouteCostCalculator& getCalculator(); - - static void cleanup() { - delete myInstance; - myInstance = 0; - } - - virtual void setCosts(R* route, const double costs, const bool isActive = false) const = 0; - - /** @brief calculate the probabilities in the logit model */ - virtual void calculateProbabilities(std::vector alternatives, const V* const veh, const SUMOTime time) = 0; - - int getMaxRouteNumber() const { - return myMaxRouteNumber; - } - - bool keepRoutes() const { - return myKeepRoutes; - } - - bool skipRouteCalculation() const { - return mySkipRouteCalculation; - } - -protected: - /// @brief Constructor - RouteCostCalculator() { - OptionsCont& oc = OptionsCont::getOptions(); - myMaxRouteNumber = oc.getInt("max-alternatives"); - myKeepRoutes = oc.getBool("keep-all-routes"); - mySkipRouteCalculation = oc.getBool("skip-new-routes"); - } - - /// @brief Destructor - virtual ~RouteCostCalculator() {} - -private: - static RouteCostCalculator* myInstance; - - /// @brief The maximum route alternatives number - int myMaxRouteNumber; - - /// @brief Information whether all routes should be saved - bool myKeepRoutes; - - /// @brief Information whether new routes should be calculated - bool mySkipRouteCalculation; - -}; - - -// =========================================================================== -// static member definitions -// =========================================================================== -template -RouteCostCalculator* RouteCostCalculator::myInstance = 0; - - -#include "GawronCalculator.h" -#include "LogitCalculator.h" - -template -RouteCostCalculator& RouteCostCalculator::getCalculator() { - if (myInstance == 0) { - OptionsCont& oc = OptionsCont::getOptions(); - if (oc.getString("route-choice-method") == "logit") { - myInstance = new LogitCalculator(oc.getFloat("logit.beta"), oc.getFloat("logit.gamma"), oc.getFloat("logit.theta")); - } else if (oc.getString("route-choice-method") == "gawron") { - myInstance = new GawronCalculator(oc.getFloat("gawron.beta"), oc.getFloat("gawron.a")); - } - } - return *myInstance; -} diff --git a/Util/OSM2ODR/src/utils/router/RouterProvider.h b/Util/OSM2ODR/src/utils/router/RouterProvider.h deleted file mode 100644 index 26674e00e..000000000 --- a/Util/OSM2ODR/src/utils/router/RouterProvider.h +++ /dev/null @@ -1,98 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file RouterProvider.h -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date Mon, 03 March 2014 -/// -// The RouterProvider provides car, pedestrian and intermodal routing in one object -/****************************************************************************/ -#pragma once -#include - -#include "IntermodalRouter.h" -#include "RailwayRouter.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class RouterProvider - * The encapsulation of the routers for vehicles and pedestrians - */ -template -class RouterProvider { -public: - RouterProvider(SUMOAbstractRouter* vehRouter, - PedestrianRouter* pedRouter, - IntermodalRouter* interRouter, - RailwayRouter* railRouter) : - myVehRouter(vehRouter), - myPedRouter(pedRouter), - myInterRouter(interRouter), - myRailRouter(railRouter) - {} - - RouterProvider(const RouterProvider& original) : - myVehRouter(original.myVehRouter->clone()), - myPedRouter(static_cast*>(original.myPedRouter == 0 ? 0 : original.myPedRouter->clone())), - myInterRouter(static_cast*>(original.myInterRouter == 0 ? 0 : original.myInterRouter->clone())), - myRailRouter(static_cast*>(original.myRailRouter == 0 ? 0 : original.myRailRouter->clone())) - {} - - RouterProvider* clone() { - return new RouterProvider(*this); - } - - SUMOAbstractRouter& getVehicleRouter(SUMOVehicleClass svc) const { - if (myRailRouter == nullptr || !isRailway(svc)) { - return *myVehRouter; - } else { - return *myRailRouter; - } - } - - PedestrianRouter& getPedestrianRouter() const { - return *myPedRouter; - } - - IntermodalRouter& getIntermodalRouter() const { - return *myInterRouter; - } - - RailwayRouter& getRailwayRouter() const { - return *myRailRouter; - } - - virtual ~RouterProvider() { - delete myVehRouter; - delete myPedRouter; - delete myInterRouter; - delete myRailRouter; - } - - -private: - SUMOAbstractRouter* const myVehRouter; - PedestrianRouter* const myPedRouter; - IntermodalRouter* const myInterRouter; - RailwayRouter* const myRailRouter; - - -private: - /// @brief Invalidated assignment operator - RouterProvider& operator=(const RouterProvider& src); - -}; diff --git a/Util/OSM2ODR/src/utils/router/SPTree.h b/Util/OSM2ODR/src/utils/router/SPTree.h deleted file mode 100644 index 469217b29..000000000 --- a/Util/OSM2ODR/src/utils/router/SPTree.h +++ /dev/null @@ -1,235 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file SPTree.h -/// @author Laura Bieker -/// @author Michael Behrisch -/// @date February 2012 -/// -// Shortest Path tree of limited depth using Dijkstras algorithm -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - - -template -class SPTree { - -public: - typedef std::vector CHConnections; - typedef std::pair CHConnectionPair; - typedef std::vector CHConnectionPairs; - - /** - * @class EdgeInfoByEffortComparator - * Class to compare (and so sort) nodes by their effort - */ - class EdgeByTTComparator { - public: - /// Comparing method - bool operator()(const E* a, const E* b) const { - if (a->traveltime == b->traveltime) { - return a->edge->getNumericalID() > b->edge->getNumericalID(); - } - return a->traveltime > b->traveltime; - } - }; - - - /** - * @brief Constructor - */ - SPTree(int maxDepth, bool validatePermissions) : - myMaxDepth(maxDepth), - myValidatePermissions(validatePermissions) { - } - - - void init() { - // all EdgeInfos touched in the previous query are either in myFrontier or myFound: clean those up - for (typename std::vector::iterator i = myFrontier.begin(); i != myFrontier.end(); i++) { - (*i)->reset(); - } - myFrontier.clear(); - for (typename std::vector::iterator i = myFound.begin(); i != myFound.end(); i++) { - (*i)->reset(); - } - myFound.clear(); - } - - - /** - * @brief build a shortest path tree from start to a depth of myMaxdepth. The given - * edge is excluded from this tree - */ - void rebuildFrom(E* start, const E* excluded) { - init(); - start->traveltime = 0; - start->depth = 0; - start->permissions = start->edge->getPermissions(); - myFrontier.push_back(start); - // build SPT - while (!myFrontier.empty()) { - E* min = myFrontier.front(); - std::pop_heap(myFrontier.begin(), myFrontier.end(), myCmp); - myFrontier.pop_back(); - myFound.push_back(min); - min->visited = true; - if (min->depth < myMaxDepth) { - for (typename CHConnections::iterator it = min->followers.begin(); it != min->followers.end(); it++) { - C& con = *it; - E* follower = con.target; - if (follower == excluded) { - continue; - } - const double traveltime = min->traveltime + con.cost; - const double oldTraveltime = follower->traveltime; - if (!follower->visited && traveltime < oldTraveltime) { - follower->traveltime = traveltime; - follower->depth = min->depth + 1; - follower->permissions = (min->permissions & con.permissions); - if (oldTraveltime == std::numeric_limits::max()) { - myFrontier.push_back(follower); - std::push_heap(myFrontier.begin(), myFrontier.end(), myCmp); - } else { - std::push_heap(myFrontier.begin(), - std::find(myFrontier.begin(), myFrontier.end(), follower) + 1, - myCmp); - } - } - } - } - } - } - - - /// @brief whether permissions should be validated; - inline bool validatePermissions() { - return myValidatePermissions; - } - - /// @brief save source/target pair for later validation - void registerForValidation(const C* aInfo, const C* fInfo) { - assert(myValidatePermissions); - myShortcutsToValidate.push_back(CHConnectionPair(aInfo, fInfo)); - } - - - /* @brief for each path source->excluded->target try to find a witness with a witness - * with equal permissions */ - const CHConnectionPairs& getNeededShortcuts(const E* excluded) { - assert(myValidatePermissions); - myNeededShortcuts.clear(); - for (typename CHConnectionPairs::iterator it = myShortcutsToValidate.begin(); it != myShortcutsToValidate.end(); ++it) { - const C* const aInfo = it->first; - const C* const fInfo = it->second; - const double bestWitness = dijkstraTT( - aInfo->target, fInfo->target, excluded, (aInfo->permissions & fInfo->permissions)); - const double viaCost = aInfo->cost + fInfo->cost; - if (viaCost < bestWitness) { - myNeededShortcuts.push_back(*it); - } - } - myShortcutsToValidate.clear(); - return myNeededShortcuts; - } - - -private: - // perform dijkstra search under permission constraints - double dijkstraTT(E* start, E* dest, const E* excluded, SVCPermissions permissions) { - init(); - start->traveltime = 0; - start->depth = 0; - myFrontier.push_back(start); - // build SPT - while (!myFrontier.empty()) { - E* min = myFrontier.front(); - if (min == dest) { - return dest->traveltime; - } - std::pop_heap(myFrontier.begin(), myFrontier.end(), myCmp); - myFrontier.pop_back(); - myFound.push_back(min); - min->visited = true; - if (min->depth < myMaxDepth) { - for (typename CHConnections::iterator it = min->followers.begin(); it != min->followers.end(); it++) { - C& con = *it; - E* follower = con.target; - if (follower == excluded) { - continue; - } - if ((con.permissions & permissions) != permissions) { - continue; - } - const double traveltime = min->traveltime + con.cost; - const double oldTraveltime = follower->traveltime; - if (!follower->visited && traveltime < oldTraveltime) { - follower->traveltime = traveltime; - follower->depth = min->depth + 1; - follower->permissions = (min->permissions & con.permissions); - if (oldTraveltime == std::numeric_limits::max()) { - myFrontier.push_back(follower); - std::push_heap(myFrontier.begin(), myFrontier.end(), myCmp); - } else { - std::push_heap(myFrontier.begin(), - std::find(myFrontier.begin(), myFrontier.end(), follower) + 1, - myCmp); - } - } - } - } - } - return dest->traveltime; - } - - - // helper method for debugging - void debugPrintVector(std::vector& vec, E* start, const E* excluded) { - std::cout << "computed SPT from '" << start->edge->getID() << "' (excluding " << excluded->edge->getID() << ") with " << myFound.size() << " edges\n"; - for (typename std::vector::iterator it = vec.begin(); it != vec.end(); it++) { - E* e = *it; - std::cout << "(" << e->edge->getID() << "," << e->traveltime << ") "; - } - std::cout << "\n"; - } - - /// @brief the min edge heap - std::vector myFrontier; - /// @brief the list of visited edges (used when resetting) - std::vector myFound; - - /// @brief comparator for search queue - EdgeByTTComparator myCmp; - - /// @brief maximum search depth - int myMaxDepth; - - /// @brief whether permissions should be validated - bool myValidatePermissions; - - /// @brief vector of needed shortcuts after validation - CHConnectionPairs myShortcutsToValidate; - /// @brief vector of needed shortcuts after validation - CHConnectionPairs myNeededShortcuts; -}; diff --git a/Util/OSM2ODR/src/utils/router/SUMOAbstractRouter.h b/Util/OSM2ODR/src/utils/router/SUMOAbstractRouter.h deleted file mode 100644 index 70df395b6..000000000 --- a/Util/OSM2ODR/src/utils/router/SUMOAbstractRouter.h +++ /dev/null @@ -1,323 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2006-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file SUMOAbstractRouter.h -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @author Jakob Erdmann -/// @date 25.Jan 2006 -/// -// An abstract router base class -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class SUMOAbstractRouter - * The interface for routing the vehicles over the network. - */ -template -class SUMOAbstractRouter { -public: - /** - * @class EdgeInfo - * A definition about a route's edge with the effort needed to reach it and - * the information about the previous edge. - */ - class EdgeInfo { - public: - /// Constructor - EdgeInfo(const E* const e) - : edge(e), effort(std::numeric_limits::max()), - heuristicEffort(std::numeric_limits::max()), - leaveTime(0.), prev(nullptr), visited(false), prohibited(false) {} - - /// The current edge - const E* const edge; - - /// Effort to reach the edge - double effort; - - /// Estimated effort to reach the edge (effort + lower bound on remaining effort) - // only used by A* - double heuristicEffort; - - /// The time the vehicle leaves the edge - double leaveTime; - - /// The previous edge - const EdgeInfo* prev; - - /// whether the edge was already evaluated - bool visited; - - /// whether the edge is currently not allowed - bool prohibited; - - inline void reset() { - effort = std::numeric_limits::max(); - heuristicEffort = std::numeric_limits::max(); - visited = false; - } - - private: - /// @brief Invalidated assignment operator - EdgeInfo& operator=(const EdgeInfo& s) = delete; - - }; - - /// Type of the function that is used to retrieve the edge effort. - typedef double(* Operation)(const E* const, const V* const, double); - - /// Constructor - SUMOAbstractRouter(const std::string& type, bool unbuildIsWarning, Operation operation, Operation ttOperation, - const bool havePermissions, const bool haveRestrictions) : - myErrorMsgHandler(unbuildIsWarning ? MsgHandler::getWarningInstance() : MsgHandler::getErrorInstance()), - myOperation(operation), myTTOperation(ttOperation), - myBulkMode(false), - myAutoBulkMode(false), - myHavePermissions(havePermissions), - myHaveRestrictions(haveRestrictions), - myType(type), - myQueryVisits(0), - myNumQueries(0), - myQueryStartTime(0), - myQueryTimeSum(0) { - } - - /// Copy Constructor - SUMOAbstractRouter(SUMOAbstractRouter* other) : - myErrorMsgHandler(other->myErrorMsgHandler), - myOperation(other->myOperation), myTTOperation(other->myTTOperation), - myBulkMode(false), - myAutoBulkMode(false), - myHavePermissions(other->myHavePermissions), - myHaveRestrictions(other->myHaveRestrictions), - myType(other->myType), - myQueryVisits(0), - myNumQueries(0), - myQueryStartTime(0), - myQueryTimeSum(0) { } - - - - /// Destructor - virtual ~SUMOAbstractRouter() { - if (myNumQueries > 0) { - WRITE_MESSAGE(myType + " answered " + toString(myNumQueries) + " queries and explored " + toString(double(myQueryVisits) / myNumQueries) + " edges on average."); - WRITE_MESSAGE(myType + " spent " + toString(myQueryTimeSum) + "ms answering queries (" + toString(double(myQueryTimeSum) / myNumQueries) + "ms on average)."); - } - } - - virtual SUMOAbstractRouter* clone() = 0; - - const std::string& getType() const { - return myType; - } - - /** @brief Builds the route between the given edges using the minimum effort at the given time - The definition of the effort depends on the wished routing scheme */ - virtual bool compute(const E* from, const E* to, const V* const vehicle, - SUMOTime msTime, std::vector& into, bool silent = false) = 0; - - - /** @brief Builds the route between the given edges using the minimum effort at the given time, - * also taking into account position along the edges to ensure currect - * handling of looped routes - * The definition of the effort depends on the wished routing scheme */ - inline bool compute( - const E* from, double fromPos, - const E* to, double toPos, - const V* const vehicle, - SUMOTime msTime, std::vector& into, bool silent = false) { - if (from != to || fromPos <= toPos) { - return compute(from, to, vehicle, msTime, into, silent); - } else { - return computeLooped(from, to, vehicle, msTime, into, silent); - } - } - - - /** @brief Builds the route between the given edges using the minimum effort at the given time - * if from == to, return the shortest looped route */ - inline bool computeLooped(const E* from, const E* to, const V* const vehicle, - SUMOTime msTime, std::vector& into, bool silent = false) { - if (from != to) { - return compute(from, to, vehicle, msTime, into, silent); - } - double minEffort = std::numeric_limits::max(); - std::vector best; - const SUMOVehicleClass vClass = vehicle == 0 ? SVC_IGNORING : vehicle->getVClass(); - for (const std::pair& follower : from->getViaSuccessors(vClass)) { - std::vector tmp; - compute(follower.first, to, vehicle, msTime, tmp, true); - if (tmp.size() > 0) { - double effort = recomputeCosts(tmp, vehicle, msTime); - if (effort < minEffort) { - minEffort = effort; - best = tmp; - } - } - } - if (minEffort != std::numeric_limits::max()) { - into.push_back(from); - std::copy(best.begin(), best.end(), std::back_inserter(into)); - return true; - } else if (!silent && myErrorMsgHandler != nullptr) { - myErrorMsgHandler->informf("No connection between edge '%' and edge '%' found.", from->getID(), to->getID()); - } - return false; - } - - inline bool isProhibited(const E* const edge, const V* const vehicle) const { - return (myHavePermissions && edge->prohibits(vehicle)) || (myHaveRestrictions && edge->restricts(vehicle)); - } - - virtual void prohibit(const std::vector& /* toProhibit */) {} - - inline double getTravelTime(const E* const e, const V* const v, const double t, const double effort) const { - return myTTOperation == nullptr ? effort : (*myTTOperation)(e, v, t); - } - - inline void updateViaEdgeCost(const E* viaEdge, const V* const v, double& time, double& effort, double& length) const { - while (viaEdge != nullptr && viaEdge->isInternal()) { - const double viaEffortDelta = this->getEffort(viaEdge, v, time); - time += getTravelTime(viaEdge, v, time, viaEffortDelta); - effort += viaEffortDelta; - length += viaEdge->getLength(); - viaEdge = viaEdge->getViaSuccessors().front().second; - } - } - - inline void updateViaCost(const E* const prev, const E* const e, const V* const v, double& time, double& effort, double& length) const { - if (prev != nullptr) { - for (const std::pair& follower : prev->getViaSuccessors()) { - if (follower.first == e) { - updateViaEdgeCost(follower.second, v, time, effort, length); - break; - } - } - } - const double effortDelta = this->getEffort(e, v, time); - effort += effortDelta; - time += getTravelTime(e, v, time, effortDelta); - length += e->getLength(); - } - - - inline double recomputeCosts(const std::vector& edges, const V* const v, SUMOTime msTime, double* lengthp = nullptr) const { - double time = STEPS2TIME(msTime); - double effort = 0.; - double length = 0.; - if (lengthp == nullptr) { - lengthp = &length; - } else { - *lengthp = 0.; - } - const E* prev = nullptr; - for (const E* const e : edges) { - if (isProhibited(e, v)) { - return -1; - } - updateViaCost(prev, e, v, time, effort, *lengthp); - prev = e; - } - return effort; - } - - inline double recomputeCosts(const std::vector& edges, const V* const v, double fromPos, double toPos, SUMOTime msTime, double* lengthp = nullptr) const { - double effort = recomputeCosts(edges, v, msTime, lengthp); - if (!edges.empty()) { - double firstEffort = this->getEffort(edges.front(), v, STEPS2TIME(msTime)); - double lastEffort = this->getEffort(edges.back(), v, STEPS2TIME(msTime)); - effort -= firstEffort * fromPos / edges.front()->getLength(); - effort -= lastEffort * (edges.back()->getLength() - toPos) / edges.back()->getLength(); - } - return effort; - } - - - inline double getEffort(const E* const e, const V* const v, double t) const { - return (*myOperation)(e, v, t); - } - - inline void startQuery() { - myNumQueries++; - myQueryStartTime = SysUtils::getCurrentMillis(); - } - - inline void endQuery(int visits) { - myQueryVisits += visits; - myQueryTimeSum += (SysUtils::getCurrentMillis() - myQueryStartTime); - } - - inline void setBulkMode(const bool mode) { - myBulkMode = mode; - } - - inline void setAutoBulkMode(const bool mode) { - myAutoBulkMode = mode; - } - -protected: - /// @brief the handler for routing errors - MsgHandler* const myErrorMsgHandler; - - /// @brief The object's operation to perform. - Operation myOperation; - - /// @brief The object's operation to perform for travel times - Operation myTTOperation; - - /// @brief whether we are currently operating several route queries in a bulk - bool myBulkMode; - - /// @brief whether we are currently trying to detect bulk mode automatically - bool myAutoBulkMode; - - /// @brief whether edge permissions need to be considered - const bool myHavePermissions; - - /// @brief whether edge restrictions need to be considered - const bool myHaveRestrictions; - - std::vector myProhibited; - -private: - /// @brief the type of this router - const std::string myType; - - /// @brief counters for performance logging - long long int myQueryVisits; - long long int myNumQueries; - /// @brief the time spent querying in milliseconds - long long int myQueryStartTime; - long long int myQueryTimeSum; -private: - /// @brief Invalidated assignment operator - SUMOAbstractRouter& operator=(const SUMOAbstractRouter& s); -}; diff --git a/Util/OSM2ODR/src/utils/router/StopEdge.h b/Util/OSM2ODR/src/utils/router/StopEdge.h deleted file mode 100644 index 54aab3d50..000000000 --- a/Util/OSM2ODR/src/utils/router/StopEdge.h +++ /dev/null @@ -1,39 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file StopEdge.h -/// @author Michael Behrisch -/// @date Mon, 03 March 2014 -/// -// The StopEdge is a special intermodal edge representing bus and train stops -/****************************************************************************/ -#pragma once -#include - -#include "IntermodalEdge.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -/// @brief the stop edge type representing bus and train stops -template -class StopEdge : public IntermodalEdge { -public: - StopEdge(const std::string id, int numericalID, const E* edge) : - IntermodalEdge(id, numericalID, edge, "!stop") { } - - bool includeInRoute(bool /* allEdges */) const { - return true; - } -}; diff --git a/Util/OSM2ODR/src/utils/shapes/CMakeLists.txt b/Util/OSM2ODR/src/utils/shapes/CMakeLists.txt deleted file mode 100644 index 0ae62a102..000000000 --- a/Util/OSM2ODR/src/utils/shapes/CMakeLists.txt +++ /dev/null @@ -1,16 +0,0 @@ -set(utils_shapes_STAT_SRCS - PointOfInterest.h - Shape.cpp - Shape.h - SUMOPolygon.cpp - SUMOPolygon.h - PolygonDynamics.cpp - PolygonDynamics.h - ShapeHandler.cpp - ShapeHandler.h - ShapeContainer.cpp - ShapeContainer.h -) - -add_library(utils_shapes STATIC ${utils_shapes_STAT_SRCS}) -set_property(TARGET utils_shapes PROPERTY PROJECT_LABEL "z_utils_shapes") diff --git a/Util/OSM2ODR/src/utils/shapes/PointOfInterest.h b/Util/OSM2ODR/src/utils/shapes/PointOfInterest.h deleted file mode 100644 index 47648f117..000000000 --- a/Util/OSM2ODR/src/utils/shapes/PointOfInterest.h +++ /dev/null @@ -1,192 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2005-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file PointOfInterest.h -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @author Melanie Knocke -/// @date 2005-09-15 -/// -// A point-of-interest (2D) -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include -#include -#include -#include -#include "Shape.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class PointOfInterest - * @brief A point-of-interest - */ -class PointOfInterest : public Shape, public Position, public Parameterised { -public: - /** @brief Constructor - * @param[in] id The name of the POI - * @param[in] type The (abstract) type of the POI - * @param[in] color The color of the POI - * @param[in] pos The position of the POI - * @param[in[ geo use GEO coordinates (lon/lat) - * @param[in] lane The Lane in which this POI is placed - * @param[in] posOverLane The position over Lane - * @param[in] posLat The position lateral over Lane - * @param[in] layer The layer of the POI - * @param[in] angle The rotation of the POI - * @param[in] imgFile The raster image of the shape - * @param[in] relativePath set image file as relative path - * @param[in] width The width of the POI image - * @param[in] height The height of the POI image - */ - PointOfInterest(const std::string& id, const std::string& type, - const RGBColor& color, const Position& pos, bool geo, - const std::string& lane, double posOverLane, double posLat, - double layer = DEFAULT_LAYER, - double angle = DEFAULT_ANGLE, - const std::string& imgFile = DEFAULT_IMG_FILE, - bool relativePath = DEFAULT_RELATIVEPATH, - double width = DEFAULT_IMG_WIDTH, - double height = DEFAULT_IMG_HEIGHT) : - Shape(id, type, color, layer, angle, imgFile, relativePath), - Position(pos), - myGeo(geo), - myLane(lane), - myPosOverLane(posOverLane), - myPosLat(posLat), - myHalfImgWidth(width / 2.0), - myHalfImgHeight(height / 2.0) { - } - - - /// @brief Destructor - virtual ~PointOfInterest() { } - - - /// @name Getter - /// @{ - - /// @brief Returns the image width of the POI - inline double getWidth() const { - return myHalfImgWidth * 2.0; - } - - /// @brief Returns the image height of the POI - inline double getHeight() const { - return myHalfImgHeight * 2.0; - } - - /// @brief Returns the image center of the POI - Position getCenter() const { - return {x() + myHalfImgWidth, y() + myHalfImgHeight}; - } - /// @} - - - /// @name Setter - /// @{ - - /// @brief set the image width of the POI - inline void setWidth(double width) { - myHalfImgWidth = width / 2.0; - } - - /// @brief set the image height of the POI - inline void setHeight(double height) { - myHalfImgHeight = height / 2.0; - } - /// @} - - - /* @brief POI definition to the given device - * @param[in] geo Whether to write the output in geo-coordinates - */ - void writeXML(OutputDevice& out, const bool geo = false, const double zOffset = 0., const std::string laneID = "", const double pos = 0., const double posLat = 0.) { - out.openTag(SUMO_TAG_POI); - out.writeAttr(SUMO_ATTR_ID, StringUtils::escapeXML(getID())); - if (getShapeType().size() > 0) { - out.writeAttr(SUMO_ATTR_TYPE, StringUtils::escapeXML(getShapeType())); - } - out.writeAttr(SUMO_ATTR_COLOR, getShapeColor()); - out.writeAttr(SUMO_ATTR_LAYER, getShapeLayer() + zOffset); - if (laneID != "") { - out.writeAttr(SUMO_ATTR_LANE, laneID); - out.writeAttr(SUMO_ATTR_POSITION, pos); - if (posLat != 0) { - out.writeAttr(SUMO_ATTR_POSITION_LAT, posLat); - } - } else { - if (geo) { - Position POICartesianPos(*this); - GeoConvHelper::getFinal().cartesian2geo(POICartesianPos); - out.setPrecision(gPrecisionGeo); - out.writeAttr(SUMO_ATTR_LON, POICartesianPos.x()); - out.writeAttr(SUMO_ATTR_LAT, POICartesianPos.y()); - out.setPrecision(); - } else { - out.writeAttr(SUMO_ATTR_X, x()); - out.writeAttr(SUMO_ATTR_Y, y()); - } - } - if (getShapeNaviDegree() != Shape::DEFAULT_ANGLE) { - out.writeAttr(SUMO_ATTR_ANGLE, getShapeNaviDegree()); - } - if (getShapeImgFile() != Shape::DEFAULT_IMG_FILE) { - if (getShapeRelativePath()) { - // write only the file name, without file path - std::string file = getShapeImgFile(); - file.erase(0, FileHelpers::getFilePath(getShapeImgFile()).size()); - out.writeAttr(SUMO_ATTR_IMGFILE, file); - } else { - out.writeAttr(SUMO_ATTR_IMGFILE, getShapeImgFile()); - } - } - if (getWidth() != Shape::DEFAULT_IMG_WIDTH) { - out.writeAttr(SUMO_ATTR_WIDTH, getWidth()); - } - if (getHeight() != Shape::DEFAULT_IMG_HEIGHT) { - out.writeAttr(SUMO_ATTR_HEIGHT, getHeight()); - } - writeParams(out); - out.closeTag(); - } - - -protected: - /// @brief flag to check if POI was loaded as GEO Position (main used by netedit) - bool myGeo; - - /// @brief ID of lane in which this POI is placed (main used by netedit) - std::string myLane; - - /// @brief position over lane in which this POI is placed (main used by netedit) - double myPosOverLane; - - /// @brief latereal position over lane in which this POI is placed (main used by netedit) - double myPosLat; - - /// @brief The half width of the image when rendering this POI - double myHalfImgWidth; - - /// @brief The half height of the image when rendering this POI - double myHalfImgHeight; - -}; diff --git a/Util/OSM2ODR/src/utils/shapes/PolygonDynamics.cpp b/Util/OSM2ODR/src/utils/shapes/PolygonDynamics.cpp deleted file mode 100644 index 47753861c..000000000 --- a/Util/OSM2ODR/src/utils/shapes/PolygonDynamics.cpp +++ /dev/null @@ -1,250 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2004-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file PolygonDynamics.cpp -/// @author Leonhard Luecken -/// @date Apr 2019 -/// -// A polygon, which holds a timeSpan for displaying dynamic properties -/****************************************************************************/ - - -#include "PolygonDynamics.h" - -#include -#include "utils/common/StdDefs.h" -#include "utils/common/SUMOTime.h" -#include "utils/vehicle/SUMOTrafficObject.h" - - -//#define DEBUG_DYNAMIC_SHAPES - -PolygonDynamics::PolygonDynamics(double creationTime, - SUMOPolygon* p, - SUMOTrafficObject* trackedObject, - const std::vector& timeSpan, - const std::vector& alphaSpan, - bool looped, - bool rotate) : - myPolygon(p), - myCurrentTime(0), - myLastUpdateTime(creationTime), - animated(!timeSpan.empty()), - looped(looped), - tracking(trackedObject != nullptr), - rotate(rotate), - myTrackedObject(trackedObject), - myTrackedObjectID(""), - myTrackedObjectsInitialPositon(nullptr), - myTrackedObjectsInitialAngle(-1), - myOriginalShape(nullptr), - myTimeSpan(nullptr), - myAlphaSpan(nullptr), - myVis(nullptr) { - // Check for consistency - if (animated) { - myTimeSpan = std::unique_ptr >(new std::vector(timeSpan)); - assert(myTimeSpan->size() >= 2); - assert((*myTimeSpan)[0] == 0.0); - assert(myAlphaSpan == nullptr || myAlphaSpan->size() >= 2); -#ifdef DEBUG_DYNAMIC_SHAPES - if (myTimeSpan->size() >= 2) { - for (unsigned int i = 1; i < myTimeSpan->size(); ++i) { - assert((*myTimeSpan)[i - 1] <= (*myTimeSpan)[i]); - } - } -#endif - myPrevTime = myTimeSpan->begin(); - myNextTime = ++myTimeSpan->begin(); - } -#ifdef DEBUG_DYNAMIC_SHAPES - else { - assert(myAlphaSpan == nullptr); - } -#endif - - myOriginalShape = std::unique_ptr(new PositionVector(p->getShape())); - - if (tracking) { - // Try initializing the tracked position (depends on whether object is already on the road) - initTrackedPosition(); - myTrackedObjectID = myTrackedObject->getID(); - } - - if (!alphaSpan.empty()) { - myAlphaSpan = std::unique_ptr >(new std::vector(alphaSpan)); - assert(myAlphaSpan->size() >= 2); - assert(myAlphaSpan->size() == myTimeSpan->size()); - myPrevAlpha = myAlphaSpan->begin(); - myNextAlpha = ++myAlphaSpan->begin(); - } -} - -PolygonDynamics::~PolygonDynamics() -{} - - -SUMOTime -PolygonDynamics::update(SUMOTime t) { -#ifdef DEBUG_DYNAMIC_SHAPES - std::cout << t << " PolygonDynamics::update() for polygon '" << myPolygon->getID() << "'" << std::endl; -#endif - const double simtime = STEPS2TIME(t); - const double dt = simtime - myLastUpdateTime; - myLastUpdateTime = simtime; - - SUMOTime ret = DELTA_T; - - if (tracking) { - if (myTrackedObjectsInitialPositon == nullptr) { - // Tracked object hasn't entered the network, until now. - // Continuously try to obtain its initial position - initTrackedPosition(); - } - if (myTrackedObjectsInitialPositon != nullptr) { - // Initial position was initialized, relative tracking is possible - const Position& objPos = myTrackedObject->getPosition(); - const bool onRoad = objPos != Position::INVALID; - if (onRoad) { -#ifdef DEBUG_DYNAMIC_SHAPES - std::cout << " Tracked object '" << myTrackedObject->getID() << "' is on the road. Tracked position=" << objPos << std::endl; -#endif - // Update polygon's shape - PositionVector newShape(*myOriginalShape); - if (rotate) { - const double relRotation = myTrackedObject->getAngle() - myTrackedObjectsInitialAngle; - newShape.rotate2D(relRotation); -#ifdef DEBUG_DYNAMIC_SHAPES - std::cout << " Relative rotation wrt original rotation: " << relRotation << std::endl; -#endif - } - newShape.add(objPos); - myPolygon->setShape(newShape); - } -#ifdef DEBUG_DYNAMIC_SHAPES - else { - // tracked object is off road - std::cout << " Tracked object '" << myTrackedObject->getID() << "' is off road." << std::endl; - } -#endif - } -#ifdef DEBUG_DYNAMIC_SHAPES - else { - // Initial position was not initialized, yet - std::cout << " Tracked object '" << myTrackedObject->getID() << "' hasn't entered the network since tracking was started." << std::endl; - } -#endif - } - - if (animated) { - // Continue animation - myCurrentTime += dt; - while (myCurrentTime >= *myNextTime) { - // step forward along time lines to appropriate anchor points - ++myPrevTime; - ++myNextTime; - if (myNextTime == myTimeSpan->end()) { - // Set iterators back to point to valid positions - --myPrevTime; - --myNextTime; - break; - } else { - // Forward corresponding iterators for property time lines - if (myAlphaSpan != nullptr) { - ++myPrevAlpha; - ++myNextAlpha; - } - } - } - - // Linear interpolation factor between previous and next time - double theta = 1.0; -#ifdef DEBUG_DYNAMIC_SHAPES - std::cout << " animation: dt=" << dt - << ", current animation time: " << myCurrentTime - << ", previous anchor time: " << *myPrevTime - << ", next anchor time: " << *myNextTime; -#endif - if (looped) { - const bool resetAnimation = myCurrentTime >= *myNextTime; -#ifdef DEBUG_DYNAMIC_SHAPES - if (resetAnimation) { - std::cout << " (resetting animation!)"; - } -#endif - if (resetAnimation) { - // Reset animation time line to start, if appropriate - while (myCurrentTime >= *myNextTime) { - myCurrentTime -= *myNextTime; - } - myCurrentTime = MAX2(myCurrentTime, 0.0); - myPrevTime = myTimeSpan->begin(); - myNextTime = ++myTimeSpan->begin(); - if (myAlphaSpan != nullptr) { - myPrevAlpha = myAlphaSpan->begin(); - myNextAlpha = ++myAlphaSpan->begin(); - } - } - } - if (myCurrentTime >= *myNextTime) { - assert(!looped); - // Reached the end of the dynamics, indicate expiration by returning zero - // and set all properties to the final state (theta remains one) - ret = 0; -#ifdef DEBUG_DYNAMIC_SHAPES - std::cout << " (animation elapsed!)"; -#endif - } else { - // Animation is still going on, schedule next update - if (*myNextTime - *myPrevTime != 0) { - theta = (myCurrentTime - *myPrevTime) / (*myNextTime - *myPrevTime); - } - } - if (myAlphaSpan != nullptr) { - // Interpolate values of properties - setAlpha(*myPrevAlpha + theta * (*myNextAlpha - *myPrevAlpha)); -#ifdef DEBUG_DYNAMIC_SHAPES - std::cout << ", previous anchor alpha: " << *myPrevAlpha - << ", next anchor alpha: " << *myNextAlpha; -#endif - } -#ifdef DEBUG_DYNAMIC_SHAPES - std::cout << ", theta=" << theta << std::endl; -#endif - } - return ret; -} - -void -PolygonDynamics::initTrackedPosition() { - const Position& objPos = myTrackedObject->getPosition(); - if (objPos != Position::INVALID) { - // Initialize Position of tracked object - myTrackedObjectsInitialPositon = std::unique_ptr(new Position(objPos)); - myTrackedObjectsInitialAngle = myTrackedObject->getAngle(); - // Store original polygon shape relative to the tracked object's original position - myOriginalShape->sub(*myTrackedObjectsInitialPositon); -#ifdef DEBUG_DYNAMIC_SHAPES - std::cout << " Tracking object '" << myTrackedObject->getID() << "' at initial positon: " << *myTrackedObjectsInitialPositon << std::endl; -#endif - } -} - -void -PolygonDynamics::setAlpha(double alpha) { - int a = (int) alpha; - myPolygon->setShapeAlpha((unsigned char) a); -#ifdef DEBUG_DYNAMIC_SHAPES - std::cout << "\n DynamicPolygon::setAlpha() Converted alpha=" << alpha << " into myAlpha=" << a << std::endl; -#endif -} diff --git a/Util/OSM2ODR/src/utils/shapes/PolygonDynamics.h b/Util/OSM2ODR/src/utils/shapes/PolygonDynamics.h deleted file mode 100644 index a0b6f19e5..000000000 --- a/Util/OSM2ODR/src/utils/shapes/PolygonDynamics.h +++ /dev/null @@ -1,144 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2004-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file PolygonDynamics.h -/// @author Leonhard Luecken -/// @date Apr 2019 -/// -// A polygon, which holds a timeSpan for displaying dynamic properties -/****************************************************************************/ - - -#pragma once - -#include -#include "SUMOPolygon.h" -#include "utils/common/SUMOTime.h" - -class SUMOTrafficObject; -class ShapeContainer; -class SUMORTree; - -class PolygonDynamics { -public: - /** - * @brief Constructor that takes a SUMOPolygon and adds timelines for the properties to be modified dynamically. - * @param p Polygon to be modified - * @param trackedObject A tracked object (nullptr indicates that no tracking is desired) - * @param timeSpan Anchor time points - * For animated polygons: assumed to have a size >= 2, and start at timeSpan[0]=0, - * such that timeSpan[i+1] >= timeSpan[i]) - * If no animation is desired, give timeSpan == nullptr - * @param ...Span property timelines (assumed to be either nullptr, or of size equal to timeSpan (in case of animated poly)) - * @param looped Whether the animation should restart when the last keyframe is reached. In that case - * the animation jumps to the first keyframe as soon as the last is reached. - * If looped==false, the controlled polygon is removed as soon as the timeSpan elapses. - * @param rotate Whether the polygon shall be rotated with the tracked object. - */ - PolygonDynamics(double creationTime, - SUMOPolygon* p, - SUMOTrafficObject* trackedObject, - const std::vector& timeSpan, - const std::vector& alphaSpan, - bool looped, - bool rotate); - virtual ~PolygonDynamics(); - - const std::string& getPolygonID() const { - return myPolygon->getID(); - } - - SUMOPolygon* getPolygon() const { - return myPolygon; - } - - inline const std::string& getTrackedObjectID() const { - return myTrackedObjectID; - } - - /// @brief Updates the polygon according to its timeSpan and follows the tracked object - /// @param t Current sumo time step (in ms.) when this is called - /// @returns Next desired update time. - SUMOTime update(SUMOTime t); - - /// @brief Set the RTree - void setRTree(SUMORTree* rtree) { - myVis = rtree; - } - -private: - - /// @brief Sets the alpha value for the shape's color - void setAlpha(double alpha); - - /// @brief Initialize the object's position - void initTrackedPosition(); - - /// @brief The polygon this dynamics acts upon. - SUMOPolygon* myPolygon; - - /// @brief Current time - double myCurrentTime; - - /// @brief The last time the animation has been updated - double myLastUpdateTime; - - /// @brief Whether this polygon is animated, i.e., whether - /// timelines should be used to control properties. - bool animated; - - /// @brief Whether animation should be looped. - bool looped; - - /// @brief Whether this polygon tracks an object - bool tracking; - - /// @brief Whether this polygon should be rotated with the tracked object - bool rotate; - - /// @brief An object tracked by the shape, deletion by caller - SUMOTrafficObject* myTrackedObject; - std::string myTrackedObjectID; - - /// @brief Initial position of the tracked object - std::unique_ptr myTrackedObjectsInitialPositon; - - /// @brief Initial angle of the tracked object - double myTrackedObjectsInitialAngle; - - /// @brief the original shape of the polygon - /// (in case of tracking another object, this is converted to relative - /// coords wrt to the other objects initial position as origin) - std::unique_ptr myOriginalShape; - - /// @brief Time points corresponding to the anchor values of the dynamic properties - /// @note Assumed to have a size >= 2, and start at timeSpan[0]=0, such that timeSpan[i+1] >= timeSpan[i] - std::unique_ptr > myTimeSpan; - - /// @brief Pointer to the next time points in timeSpan - /// @note These iterators are only valid if timeSpan != nullptr - std::vector::const_iterator myPrevTime; - std::vector::const_iterator myNextTime; - - /// @brief Alpha values corresponding to - std::unique_ptr > myAlphaSpan; - /// @brief Pointer to the next alpha points in alphaSpan - /// @note These iterators are only valid if alphaSpan != nullptr - std::vector::const_iterator myPrevAlpha; - std::vector::const_iterator myNextAlpha; - - /// @brief RTree will be supplied in case of GUI simulation to be updated on move - SUMORTree* myVis; - -}; - diff --git a/Util/OSM2ODR/src/utils/shapes/SUMOPolygon.cpp b/Util/OSM2ODR/src/utils/shapes/SUMOPolygon.cpp deleted file mode 100644 index 56b0e82e3..000000000 --- a/Util/OSM2ODR/src/utils/shapes/SUMOPolygon.cpp +++ /dev/null @@ -1,89 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2004-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file SUMOPolygon.cpp -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @author Jakob Erdmann -/// @date Jun 2004 -/// -// A 2D-polygon -/****************************************************************************/ -#include - -#include -#include -#include -#include -#include "SUMOPolygon.h" - - -// =========================================================================== -// member definitions -// =========================================================================== -SUMOPolygon::SUMOPolygon(const std::string& id, const std::string& type, - const RGBColor& color, const PositionVector& shape, bool geo, bool fill, double lineWidth, - double layer, double angle, const std::string& imgFile, bool relativePath) : - Shape(id, type, color, layer, angle, imgFile, relativePath), - myShape(shape), - myGEO(geo), - myFill(fill), - myLineWidth(lineWidth) { -} - - -SUMOPolygon::~SUMOPolygon() {} - - -void -SUMOPolygon::writeXML(OutputDevice& out, bool geo) { - out.openTag(SUMO_TAG_POLY); - out.writeAttr(SUMO_ATTR_ID, StringUtils::escapeXML(getID())); - if (getShapeType().size() > 0) { - out.writeAttr(SUMO_ATTR_TYPE, StringUtils::escapeXML(getShapeType())); - } - out.writeAttr(SUMO_ATTR_COLOR, getShapeColor()); - out.writeAttr(SUMO_ATTR_FILL, getFill()); - if (getLineWidth() != 1) { - out.writeAttr(SUMO_ATTR_LINEWIDTH, getLineWidth()); - } - out.writeAttr(SUMO_ATTR_LAYER, getShapeLayer()); - PositionVector shape = getShape(); - if (geo) { - out.writeAttr(SUMO_ATTR_GEO, true); - for (int i = 0; i < (int) shape.size(); i++) { - GeoConvHelper::getFinal().cartesian2geo(shape[i]); - } - } - out.setPrecision(gPrecisionGeo); - out.writeAttr(SUMO_ATTR_SHAPE, shape); - out.setPrecision(); - if (getShapeNaviDegree() != Shape::DEFAULT_ANGLE) { - out.writeAttr(SUMO_ATTR_ANGLE, getShapeNaviDegree()); - } - if (getShapeImgFile() != Shape::DEFAULT_IMG_FILE) { - if (getShapeRelativePath()) { - // write only the file name, without file path - std::string file = getShapeImgFile(); - file.erase(0, FileHelpers::getFilePath(getShapeImgFile()).size()); - out.writeAttr(SUMO_ATTR_IMGFILE, file); - } else { - out.writeAttr(SUMO_ATTR_IMGFILE, getShapeImgFile()); - } - } - writeParams(out); - out.closeTag(); -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/utils/shapes/SUMOPolygon.h b/Util/OSM2ODR/src/utils/shapes/SUMOPolygon.h deleted file mode 100644 index 5b2acf513..000000000 --- a/Util/OSM2ODR/src/utils/shapes/SUMOPolygon.h +++ /dev/null @@ -1,140 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2004-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file SUMOPolygon.h -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @author Jakob Erdmann -/// @author Melanie Knocke -/// @date Jun 2004 -/// -// A 2D- or 3D-polygon -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include "Shape.h" - - -// =========================================================================== -// class declarations -// =========================================================================== -class OutputDevice; - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class Polygon - * @brief A 2D- or 3D-polygon - */ -class SUMOPolygon : public Shape, public Parameterised { - friend class PolygonDynamics; -public: - /** @brief Constructor - * @param[in] id The name of the polygon - * @param[in] type The (abstract) type of the polygon - * @param[in] color The color of the polygon - * @param[in] layer The layer of the polygon - * @param[in] angle The rotation of the polygon - * @param[in] imgFile The raster image of the polygon - * @param[in] shape The shape of the polygon - * @param[in] geo specifiy if shape was loaded as GEO - * @param[in] fill Whether the polygon shall be filled - * @param[in] lineWidth The line with for drawing an unfilled polygon - * @param[in] relativePath set image file as relative path - */ - SUMOPolygon(const std::string& id, const std::string& type, - const RGBColor& color, const PositionVector& shape, - bool geo, bool fill, double lineWidth, - double layer = DEFAULT_LAYER, - double angle = DEFAULT_ANGLE, - const std::string& imgFile = DEFAULT_IMG_FILE, - bool relativePath = DEFAULT_RELATIVEPATH); - - - /// @brief Destructor - virtual ~SUMOPolygon(); - - - /// @name Getter - /// @{ - - /** @brief Returns whether the shape of the polygon - * @return The shape of the polygon - */ - inline const PositionVector& getShape() const { - return myShape; - } - - - /** @brief Returns whether the polygon is filled - * @return Whether the polygon is filled - */ - inline bool getFill() const { - return myFill; - } - - /** @brief Returns whether the polygon is filled - * @return Whether the polygon is filled - */ - inline double getLineWidth() const { - return myLineWidth; - } - /// @} - - - /// @name Setter - /// @{ - - /** @brief Sets whether the polygon shall be filled - * @param[in] fill Whether the polygon shall be filled - */ - inline void setFill(bool fill) { - myFill = fill; - } - - inline void setLineWidth(double lineWidth) { - myLineWidth = lineWidth; - } - - - /** @brief Sets the shape of the polygon - * @param[in] shape The new shape of the polygon - */ - inline virtual void setShape(const PositionVector& shape) { - myShape = shape; - } - /// @} - - /* @brief polygon definition to the given device - * @param[in] geo Whether to write the output in geo-coordinates - */ - void writeXML(OutputDevice& out, bool geo = false); - -protected: - /// @brief The positions of the polygon - PositionVector myShape; - - /// @brief specify if shape is handled as GEO coordinate (Main used in netedit) - bool myGEO; - - /// @brief Information whether the polygon has to be filled - bool myFill; - - /// @brief The line width for drawing an unfilled polygon - double myLineWidth; -}; diff --git a/Util/OSM2ODR/src/utils/shapes/Shape.cpp b/Util/OSM2ODR/src/utils/shapes/Shape.cpp deleted file mode 100644 index 592f86f80..000000000 --- a/Util/OSM2ODR/src/utils/shapes/Shape.cpp +++ /dev/null @@ -1,58 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2012-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file Shape.cpp -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date Oct 2012 -/// -// A 2D- or 3D-Shape -/****************************************************************************/ -#include -#include - -#include "Shape.h" - -// =========================================================================== -// static member definitions -// =========================================================================== -const std::string Shape::DEFAULT_TYPE = ""; -const double Shape::DEFAULT_LAYER = 128; -const double Shape::DEFAULT_LINEWIDTH = 1; -const double Shape::DEFAULT_LAYER_POI = (double)GLO_POI; -const double Shape::DEFAULT_ANGLE = 0; -const std::string Shape::DEFAULT_IMG_FILE = ""; -const bool Shape::DEFAULT_RELATIVEPATH = false; -const double Shape::DEFAULT_IMG_WIDTH = 1; -const double Shape::DEFAULT_IMG_HEIGHT = 1; - -// =========================================================================== -// member definitions -// =========================================================================== -Shape::Shape(const std::string& id, const std::string& type, - const RGBColor& color, double layer, - double angle, const std::string& imgFile, bool relativePath) : - Named(id), - myType(type), - myColor(color), - myLayer(layer), - myNaviDegreeAngle(angle), - myImgFile(imgFile), - myRelativePath(relativePath) { -} - - -Shape::~Shape() {} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/utils/shapes/Shape.h b/Util/OSM2ODR/src/utils/shapes/Shape.h deleted file mode 100644 index a77c38a6c..000000000 --- a/Util/OSM2ODR/src/utils/shapes/Shape.h +++ /dev/null @@ -1,185 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2012-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file Shape.h -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date Oct 2012 -/// -// A 2D- or 3D-Shape -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class Shape - * @brief A 2D- or 3D-Shape - */ -class Shape : public Named { -public: - /// @nane default shape's values - /// @{ - static const std::string DEFAULT_TYPE; - static const double DEFAULT_LAYER; - static const double DEFAULT_LINEWIDTH; - static const double DEFAULT_LAYER_POI; - static const double DEFAULT_ANGLE; - static const std::string DEFAULT_IMG_FILE; - static const bool DEFAULT_RELATIVEPATH; - static const double DEFAULT_IMG_WIDTH; - static const double DEFAULT_IMG_HEIGHT; - /// @} - - /** @brief Constructor - * @param[in] id The name of the shape - * @param[in] type The (abstract) type of the shape - * @param[in] color The color of the shape - * @param[in] layer The layer of the shape - * @param[in] angle The rotation of the shape in navigational degrees - * @param[in] imgFile The raster image of the shape - * @param[in] relativePath set image file as relative path - */ - Shape(const std::string& id, const std::string& type, - const RGBColor& color, double layer, - double angle, const std::string& imgFile, bool relativePath); - - /// @brief Destructor - virtual ~Shape(); - - /// @name Getter - /// @{ - - /** @brief Returns the (abstract) type of the Shape - * @return The Shape's (abstract) type - */ - inline const std::string& getShapeType() const { - return myType; - } - - /** @brief Returns the color of the Shape - * @return The Shape's color - */ - inline const RGBColor& getShapeColor() const { - return myColor; - } - - /** @brief Returns the layer of the Shape - * @return The Shape's layer - */ - inline double getShapeLayer() const { - return myLayer; - } - - /** @brief Returns the angle of the Shape in navigational degrees - * @return The Shape's rotation angle - */ - inline double getShapeNaviDegree() const { - return myNaviDegreeAngle; - } - - /** @brief Returns the imgFile of the Shape - * @return The Shape's rotation imgFile - */ - inline const std::string& getShapeImgFile() const { - return myImgFile; - } - - /** @brief Returns the relativePath of the Shape - * @return The Shape's relativePath - */ - inline bool getShapeRelativePath() const { - return myRelativePath; - } - /// @} - - - /// @name Setter - /// @{ - - /** @brief Sets a new type - * @param[in] type The new type to use - */ - inline void setShapeType(const std::string& type) { - myType = type; - } - - /** @brief Sets a new color - * @param[in] col The new color to use - */ - inline void setShapeColor(const RGBColor& col) { - myColor = col; - } - - /** @brief Sets a new alpha value - * @param[in] alpha The new value to use - */ - inline void setShapeAlpha(unsigned char alpha) { - myColor.setAlpha(alpha); - } - - /** @brief Sets a new layer - * @param[in] layer The new layer to use - */ - inline void setShapeLayer(const double layer) { - myLayer = layer; - } - - /** @brief Sets a new angle in navigational degrees - * @param[in] layer The new angle to use - */ - virtual void setShapeNaviDegree(const double angle) { - myNaviDegreeAngle = angle; - } - - /** @brief Sets a new imgFile - * @param[in] imgFile The new imgFile to use - */ - inline void setShapeImgFile(const std::string& imgFile) { - myImgFile = imgFile; - } - - /** @brief Sets a new relativePath value - * @param[in] relativePath The new relative path to set - */ - inline void setShapeRelativePath(bool relativePath) { - myRelativePath = relativePath; - } - /// @} - -private: - /// @brief The type of the Shape - std::string myType; - - /// @brief The color of the Shape - RGBColor myColor; - - /// @brief The layer of the Shape - double myLayer; - - /// @brief The angle of the Shape - double myNaviDegreeAngle; - - /// @brief The img file (include path) - std::string myImgFile; - - /// @brief Enable or disable save imgFile as relative path - bool myRelativePath; -}; diff --git a/Util/OSM2ODR/src/utils/shapes/ShapeContainer.cpp b/Util/OSM2ODR/src/utils/shapes/ShapeContainer.cpp deleted file mode 100644 index 5303dba57..000000000 --- a/Util/OSM2ODR/src/utils/shapes/ShapeContainer.cpp +++ /dev/null @@ -1,299 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2002-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file ShapeContainer.cpp -/// @author Daniel Krajzewicz -/// @author Sascha Krieg -/// @author Michael Behrisch -/// @author Jakob Erdmann -/// @date Sept 2002 -/// -// Storage for geometrical objects, sorted by the layers they are in -/****************************************************************************/ -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "PolygonDynamics.h" -#include "ShapeContainer.h" - - -// Debug defines -//#define DEBUG_DYNAMIC_SHAPES - -// =========================================================================== -// method definitions -// =========================================================================== -ShapeContainer::ShapeContainer() {} - -ShapeContainer::~ShapeContainer() { - for (auto& p : myPolygonUpdateCommands) { - p.second->deschedule(); - } - myPolygonUpdateCommands.clear(); - - for (auto& p : myPolygonDynamics) { - delete p.second; - } - myPolygonDynamics.clear(); - -} - -bool -ShapeContainer::addPolygon(const std::string& id, const std::string& type, - const RGBColor& color, double layer, - double angle, const std::string& imgFile, bool relativePath, - const PositionVector& shape, bool geo, bool fill, double lineWidth, bool ignorePruning) { - return add(new SUMOPolygon(id, type, color, shape, geo, fill, lineWidth, layer, angle, imgFile, relativePath), ignorePruning); -} - - -PolygonDynamics* -ShapeContainer::addPolygonDynamics(double simtime, - std::string polyID, - SUMOTrafficObject* trackedObject, - const std::vector& timeSpan, - const std::vector& alphaSpan, - bool looped, - bool rotate) { - -#ifdef DEBUG_DYNAMIC_SHAPES - std::cout << simtime << " ShapeContainer::addPolygonDynamics() called for polygon '" << polyID << "'" << std::endl; -#endif - - SUMOPolygon* p = myPolygons.get(polyID); - if (p == nullptr) { -#ifdef DEBUG_DYNAMIC_SHAPES - std::cout << " polygon '" << polyID << "' doesn't exist!" << std::endl; -#endif - return nullptr; - } - // remove eventually existent previously - removePolygonDynamics(polyID); - - // Add new dynamics - PolygonDynamics* pd = new PolygonDynamics(simtime, p, trackedObject, timeSpan, alphaSpan, looped, rotate); - myPolygonDynamics.insert(std::make_pair(polyID, pd)); - - // Add tracking information - if (trackedObject != nullptr) { - auto i = myTrackingPolygons.find(pd->getTrackedObjectID()); - if (i == myTrackingPolygons.end()) { - myTrackingPolygons.insert(std::make_pair(pd->getTrackedObjectID(), std::set({p}))); - } else { - i->second.insert(p); - } - } - return pd; -} - - -bool -ShapeContainer::removePolygonDynamics(const std::string& polyID) { - SUMOPolygon* p = myPolygons.get(polyID); - if (p == nullptr) { - return false; - } - auto d = myPolygonDynamics.find(polyID); - if (d != myPolygonDynamics.end()) { -#ifdef DEBUG_DYNAMIC_SHAPES - std::cout << " Removing dynamics of polygon '" << polyID << "'" << std::endl; -#endif - const std::string& trackedObjID = d->second->getTrackedObjectID(); - if (trackedObjID != "") { - // Remove tracking information - auto i = myTrackingPolygons.find(trackedObjID); - assert(i != myTrackingPolygons.end()); - assert(i->second.find(p) != i->second.end()); - i->second.erase(p); - // Remove highlighting information - clearHighlights(trackedObjID, p); - } - delete d->second; - myPolygonDynamics.erase(d); - // Clear existing polygon dynamics commands before adding new dynamics - cleanupPolygonDynamics(polyID); - return true; - } else { - return false; - } -} - - -bool -ShapeContainer::addPOI(const std::string& id, const std::string& type, const RGBColor& color, const Position& pos, bool geo, - const std::string& lane, double posOverLane, double posLat, double layer, double angle, - const std::string& imgFile, bool relativePath, double width, double height, bool ignorePruning) { - return add(new PointOfInterest(id, type, color, pos, geo, lane, posOverLane, posLat, layer, angle, imgFile, relativePath, width, height), ignorePruning); -} - - -bool -ShapeContainer::removePolygon(const std::string& id, bool /* useLock */) { -#ifdef DEBUG_DYNAMIC_SHAPES - std::cout << "ShapeContainer: Removing Polygon '" << id << "'" << std::endl; -#endif - removePolygonDynamics(id); - return myPolygons.remove(id); -} - - -bool -ShapeContainer::removePOI(const std::string& id) { - return myPOIs.remove(id); -} - - -void -ShapeContainer::movePOI(const std::string& id, const Position& pos) { - PointOfInterest* p = myPOIs.get(id); - if (p != nullptr) { - static_cast(p)->set(pos); - } -} - - -void -ShapeContainer::reshapePolygon(const std::string& id, const PositionVector& shape) { - SUMOPolygon* p = myPolygons.get(id); - if (p != nullptr) { - p->setShape(shape); - } -} - - -bool -ShapeContainer::add(SUMOPolygon* poly, bool /* ignorePruning */) { - if (!myPolygons.add(poly->getID(), poly)) { - delete poly; - return false; - } - return true; -} - - -bool -ShapeContainer::add(PointOfInterest* poi, bool /* ignorePruning */) { - if (!myPOIs.add(poi->getID(), poi)) { - delete poi; - return false; - } - return true; -} - - -void -ShapeContainer::cleanupPolygonDynamics(const std::string& id) { - auto j = myPolygonUpdateCommands.find(id); - if (j != myPolygonUpdateCommands.end()) { - j->second->deschedule(); - myPolygonUpdateCommands.erase(j); - } -} - - -SUMOTime -ShapeContainer::polygonDynamicsUpdate(SUMOTime t, PolygonDynamics* pd) { - SUMOTime next = pd->update(t); - if (next == 0) { - // Dynamics have expired => remove polygon - myPolygonUpdateCommands[pd->getPolygonID()]->deschedule(); - // Don't aquire lock (in GUI case GUIShapeContainer::polygonDynamicsUpdate() does this) - removePolygon(pd->getPolygonID(), false); - } - return next; -} - -void -ShapeContainer::registerHighlight(const std::string& objectID, const int type, const std::string& polygonID) { - std::string toRemove = ""; - clearHighlight(objectID, type, toRemove); - if (toRemove != "") { - removePolygon(toRemove); - } - auto i = myHighlightPolygons.find(objectID); - if (i == myHighlightPolygons.end()) { - myHighlightPolygons.insert(std::make_pair(objectID, std::map({std::make_pair(type, polygonID)}))); - } else { - i->second.insert(std::make_pair(type, polygonID)); - } - myHighlightedObjects.insert(std::make_pair(polygonID, objectID)); -} - -void -ShapeContainer::clearHighlight(const std::string& objectID, const int type, std::string& toRemove) { - auto i = myHighlightPolygons.find(objectID); - if (i != myHighlightPolygons.end()) { - auto j = i->second.find(type); - if (j != i->second.end()) { - toRemove = j->second; - myHighlightedObjects.erase(toRemove); - i->second.erase(j); - if (i->second.empty()) { - myHighlightPolygons.erase(i); - } - } - } -} - -void -ShapeContainer::clearHighlights(const std::string& objectID, SUMOPolygon* p) { - auto i = myHighlightPolygons.find(objectID); - if (i != myHighlightPolygons.end()) { - auto j = i->second.begin(); - while (j != i->second.end()) { - if (j->second == p->getID()) { - i->second.erase(j); - break; - } else { - ++j; - } - } - if (i->second.empty()) { - myHighlightPolygons.erase(i); - } - } -} - -void -ShapeContainer::addPolygonUpdateCommand(std::string polyID, ParametrisedWrappingCommand* cmd) { - myPolygonUpdateCommands.insert(std::make_pair(polyID, cmd)); -} - - -void -ShapeContainer::removeTrackers(std::string objectID) { - auto i = myTrackingPolygons.find(objectID); - if (i != myTrackingPolygons.end()) { -#ifdef DEBUG_DYNAMIC_SHAPES - std::cout << " Removing tracking polygons for object '" << objectID << "'" << std::endl; -#endif - while (!i->second.empty()) { - removePolygon((*i->second.begin())->getID()); - } - myTrackingPolygons.erase(i); - } -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/utils/shapes/ShapeContainer.h b/Util/OSM2ODR/src/utils/shapes/ShapeContainer.h deleted file mode 100644 index 5b1a38d79..000000000 --- a/Util/OSM2ODR/src/utils/shapes/ShapeContainer.h +++ /dev/null @@ -1,219 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2005-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file ShapeContainer.h -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @author Jakob Erdmann -/// @date 2005-09-15 -/// -// Storage for geometrical objects, sorted by the layers they are in -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include -#include -#include "PointOfInterest.h" -#include "SUMOPolygon.h" - -// =========================================================================== -// class declarations -// =========================================================================== -class PolygonDynamics; -class SUMOTrafficObject; -template -class ParametrisedWrappingCommand; - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class ShapeContainer - * @brief Storage for geometrical objects - */ -class ShapeContainer { -public: - - /// @brief containers - typedef NamedObjectCont Polygons; - typedef NamedObjectCont POIs; - - /// @brief Constructor - ShapeContainer(); - - /// @brief Destructor - virtual ~ShapeContainer(); - - /** @brief Builds a polygon using the given values and adds it to the container - * @param[in] id The name of the polygon - * @param[in] type The (abstract) type of the polygon - * @param[in] color The color of the polygon - * @param[in] layer The layer of the polygon - * @param[in] angle The rotation of the polygon - * @param[in] imgFile The raster image of the polygon - * @param[in] relativePath set image file as relative path - * @param[in] shape The shape of the polygon - * @param[in] geo specify if shape was loaded as GEO coordinate - * @param[in] fill Whether the polygon shall be filled - * @param[in] lineWidth Line width when drawing unfilled polygon - * @return whether the polygon could be added - */ - virtual bool addPolygon(const std::string& id, const std::string& type, - const RGBColor& color, double layer, - double angle, const std::string& imgFile, - bool relativePath, const PositionVector& shape, bool geo, - bool fill, double lineWidth, bool ignorePruning = false); - - /** - * @brief Adds dynamics (animation / tracking) to the given polygon - * @param polyID ID of the polygon which should become dynamic - * @return true if the operation was successful, false if not. - * @see PolygonDynamics() - */ - virtual PolygonDynamics* addPolygonDynamics(double simtime, - std::string polyID, - SUMOTrafficObject* trackedObject, - const std::vector& timeSpan, - const std::vector& alphaSpan, - bool looped, - bool rotate); - - /** - * @brief Remove dynamics (animation / tracking) for the given polygon - * @param polyID ID of the polygon for which dynamics shall be removed - * @return true if the operation was successful (dynamics existed for the polygon), false if not. - */ - virtual bool removePolygonDynamics(const std::string& polyID); - - /** @brief Builds a POI using the given values and adds it to the container - * @param[in] id The name of the POI - * @param[in] type The (abstract) type of the POI - * @param[in] color The color of the POI - * @param[in] pos The position of the POI - * @param[in[ geo use GEO coordinates (lon/lat) - * @param[in] lane The Lane in which this POI is placed - * @param[in] posOverLane The position over Lane - * @param[in] posLat The position lateral over Lane - * @param[in] layer The layer of the POI - * @param[in] angle The rotation of the POI - * @param[in] imgFile The raster image of the POI - * @param[in] relativePath set image file as relative path - * @param[in] width The width of the POI image - * @param[in] height The height of the POI image - * @return whether the poi could be added - */ - virtual bool addPOI(const std::string& id, const std::string& type, const RGBColor& color, const Position& pos, bool geo, - const std::string& lane, double posOverLane, double posLat, double layer, double angle, - const std::string& imgFile, bool relativePath, double width, double height, bool ignorePruning = false); - - /** @brief Removes a polygon from the container - * @param[in] id The id of the polygon - * @return Whether the polygon could be removed - */ - virtual bool removePolygon(const std::string& id, bool useLock = true); - - /** @brief Removes a PoI from the container - * @param[in] id The id of the PoI - * @return Whether the poi could be removed - */ - virtual bool removePOI(const std::string& id); - - /** @brief Assigns a new position to the named PoI - * @param[in] id The id of the PoI to move - * @param[in] pos The PoI's new position - */ - virtual void movePOI(const std::string& id, const Position& pos); - - /** @brief Assigns a shape to the named polygon - * @param[in] id The id of the polygon to reshape - * @param[in] shape The polygon's new shape - */ - virtual void reshapePolygon(const std::string& id, const PositionVector& shape); - - /// @brief Returns all polygons - inline const Polygons& getPolygons() const { - return myPolygons; - } - - /// @brief Returns all pois - inline const POIs& getPOIs() const { - return myPOIs; - } - - /** @brief Regular update event for updating polygon dynamics - * @param[in] t The time at which the update is called - * @param[in] pd The dynamics to be updated - * @returns zero If dynamics has expired, next update time otherwise - */ - virtual SUMOTime polygonDynamicsUpdate(SUMOTime t, PolygonDynamics* pd); - - /// @brief Register update command (for descheduling at removal) - virtual void addPolygonUpdateCommand(std::string polyID, ParametrisedWrappingCommand* cmd); - - /// @brief Remove all tracking polygons for the given object - virtual void removeTrackers(std::string objectID); - - /// @brief register highlight of the specified type if the given id - virtual void registerHighlight(const std::string& objectID, const int type, const std::string& polygonID); - -protected: - /// @brief add polygon - virtual bool add(SUMOPolygon* poly, bool ignorePruning = false); - - /// @brief add poi - virtual bool add(PointOfInterest* poi, bool ignorePruning = false); - - /** @brief Unschedules the removal and update commands of the given polygon. - * @param[in] id The id of the polygon - */ - virtual void cleanupPolygonDynamics(const std::string& id); - - /// @name Management of highlights. For each type, only one highlight can be active, - /// @see myHighlightPolygons, myHighlightedObjects - /// @{ - /// @brief Remove any previously added highlight polygon of the specified type - /// @param[out] toRemove will hold the id of any polygon that was highlighting the given object - virtual void clearHighlight(const std::string& objectID, const int type, std::string& toRemove); - /// @brief Clears all highlight information from the maps when the object leaves the net - /// (Highlight polygons and dynamics are removed via removeTrackers()) - virtual void clearHighlights(const std::string& objectID, SUMOPolygon* p); - /// @} - -protected: - /// @brief stored Polygons - Polygons myPolygons; - - /// @brief stored PolygonDynamics - std::map myPolygonDynamics; - - /// @brief maps objects to a map of highlight types to highlighting polygons - std::map > myHighlightPolygons; - /// @brief inverse map to myHighlightPolygons saves the highlighted object for each polygon - std::map myHighlightedObjects; - - /// @brief Information about tracked objects - /// @note Maps tracked object IDs to set of polygons, which are tracking the object. - /// Needed at object removal to cancel tacking (i.e. remove tracking poly). - std::map > myTrackingPolygons; - - /// @brief stored POIs - POIs myPOIs; - -private: - /// @brief Command pointers for scheduled polygon update. Maps PolyID->Command - std::map*> myPolygonUpdateCommands; - -}; diff --git a/Util/OSM2ODR/src/utils/shapes/ShapeHandler.cpp b/Util/OSM2ODR/src/utils/shapes/ShapeHandler.cpp deleted file mode 100644 index 56fb4d03d..000000000 --- a/Util/OSM2ODR/src/utils/shapes/ShapeHandler.cpp +++ /dev/null @@ -1,300 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file ShapeHandler.cpp -/// @author Jakob Erdmann -/// @date Feb 2015 -/// -// The XML-Handler for network loading -/****************************************************************************/ -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "Shape.h" -#include "ShapeContainer.h" -#include "ShapeHandler.h" - - -// =========================================================================== -// method definitions -// =========================================================================== - -ShapeHandler::ShapeHandler(const std::string& file, ShapeContainer& sc, const GeoConvHelper* geoConvHelper) : - SUMOSAXHandler(file), - myShapeContainer(sc), - myPrefix(""), - myDefaultColor(RGBColor::RED), - myDefaultLayer(0), - myDefaultFill(false), - myLastParameterised(nullptr), - myGeoConvHelper(geoConvHelper) { -} - - -ShapeHandler::~ShapeHandler() {} - - -void -ShapeHandler::myStartElement(int element, const SUMOSAXAttributes& attrs) { - try { - switch (element) { - case SUMO_TAG_POLY: - // default layer is different depending if we're parsing a Poly or a POI, therefore it has to be here defined - myDefaultLayer = Shape::DEFAULT_LAYER; - addPoly(attrs, false, false); - break; - case SUMO_TAG_POI: - // default layer is different depending if we're parsing a Poly or a POI, therefore it has to be here defined - myDefaultLayer = Shape::DEFAULT_LAYER_POI; - addPOI(attrs, false, false); - break; - case SUMO_TAG_PARAM: - if (myLastParameterised != nullptr) { - bool ok = true; - const std::string key = attrs.get(SUMO_ATTR_KEY, nullptr, ok); - // continue if key awas sucesfully loaded - if (ok) { - // circumventing empty string value - const std::string val = attrs.hasAttribute(SUMO_ATTR_VALUE) ? attrs.getString(SUMO_ATTR_VALUE) : ""; - // show warnings if values are invalid - if (key.empty()) { - WRITE_WARNING("Error parsing key from shape generic parameter. Key cannot be empty"); - } else if (!SUMOXMLDefinitions::isValidParameterKey(key)) { - WRITE_WARNING("Error parsing key from shape generic parameter. Key contains invalid characters"); - } else if (!SUMOXMLDefinitions::isValidParameterValue(val)) { - WRITE_WARNING("Error parsing value from shape generic parameter. Value contains invalid characters"); - } else { - WRITE_DEBUG("Inserting generic parameter '" + key + "|" + val + "' into shape."); - myLastParameterised->setParameter(key, val); - } - } - } - default: - break; - } - } catch (InvalidArgument& e) { - WRITE_ERROR(e.what()); - } -} - - -void -ShapeHandler::myEndElement(int element) { - if (element != SUMO_TAG_PARAM) { - myLastParameterised = nullptr; - } -} - - -void -ShapeHandler::addPOI(const SUMOSAXAttributes& attrs, const bool ignorePruning, const bool useProcessing) { - bool ok = true; - const double INVALID_POSITION(-1000000); - const std::string id = myPrefix + attrs.get(SUMO_ATTR_ID, nullptr, ok); - double x = attrs.getOpt(SUMO_ATTR_X, id.c_str(), ok, INVALID_POSITION); - const double y = attrs.getOpt(SUMO_ATTR_Y, id.c_str(), ok, INVALID_POSITION); - double lon = attrs.getOpt(SUMO_ATTR_LON, id.c_str(), ok, INVALID_POSITION); - double lat = attrs.getOpt(SUMO_ATTR_LAT, id.c_str(), ok, INVALID_POSITION); - const double lanePos = attrs.getOpt(SUMO_ATTR_POSITION, id.c_str(), ok, 0); - const double lanePosLat = attrs.getOpt(SUMO_ATTR_POSITION_LAT, id.c_str(), ok, 0); - const double layer = attrs.getOpt(SUMO_ATTR_LAYER, id.c_str(), ok, myDefaultLayer); - const std::string type = attrs.getOpt(SUMO_ATTR_TYPE, id.c_str(), ok, ""); - const std::string laneID = attrs.getOpt(SUMO_ATTR_LANE, id.c_str(), ok, ""); - const RGBColor color = attrs.hasAttribute(SUMO_ATTR_COLOR) ? attrs.get(SUMO_ATTR_COLOR, id.c_str(), ok) : myDefaultColor; - const double angle = attrs.getOpt(SUMO_ATTR_ANGLE, id.c_str(), ok, Shape::DEFAULT_ANGLE); - std::string imgFile = attrs.getOpt(SUMO_ATTR_IMGFILE, id.c_str(), ok, Shape::DEFAULT_IMG_FILE); - bool relativePath = attrs.getOpt(SUMO_ATTR_RELATIVEPATH, id.c_str(), ok, Shape::DEFAULT_RELATIVEPATH); - if (imgFile != "" && !FileHelpers::isAbsolute(imgFile)) { - imgFile = FileHelpers::getConfigurationRelative(getFileName(), imgFile); - } - const double width = attrs.getOpt(SUMO_ATTR_WIDTH, id.c_str(), ok, Shape::DEFAULT_IMG_WIDTH); - const double height = attrs.getOpt(SUMO_ATTR_HEIGHT, id.c_str(), ok, Shape::DEFAULT_IMG_HEIGHT); - // check if ID is valid - if (SUMOXMLDefinitions::isValidTypeID(id) == false) { - WRITE_WARNING("Invalid characters for PoI ID"); - ok = false; - } - // continue - if (ok) { - const GeoConvHelper* gch; - // set GEOConverter - if (myGeoConvHelper != nullptr) { - gch = myGeoConvHelper; - } else if (useProcessing) { - gch = &GeoConvHelper::getProcessing(); - } else { - gch = &GeoConvHelper::getFinal(); - } - // check if GEOProjection has to be used - if (useProcessing && gch->usingGeoProjection()) { - if ((lat == INVALID_POSITION) || (lon == INVALID_POSITION)) { - lon = x; - lat = y; - x = INVALID_POSITION; - } - } - Position pos(x, y); - bool useGeo = false; - if ((x == INVALID_POSITION) || (y == INVALID_POSITION)) { - // try computing x,y from lane,pos - if (laneID != "") { - pos = getLanePos(id, laneID, lanePos, lanePosLat); - } else { - // try computing x,y from lon,lat - if ((lat == INVALID_POSITION) || (lon == INVALID_POSITION)) { - WRITE_ERROR("Either (x, y), (lon, lat) or (lane, pos) must be specified for PoI '" + id + "'."); - return; - } else if (!gch->usingGeoProjection()) { - WRITE_ERROR("(lon, lat) is specified for PoI '" + id + "' but no geo-conversion is specified for the network."); - return; - } - pos.set(lon, lat); - useGeo = true; - bool success = true; - if (useProcessing) { - success = GeoConvHelper::getProcessing().x2cartesian(pos); - } else { - success = gch->x2cartesian_const(pos); - } - if (!success) { - WRITE_ERROR("Unable to project coordinates for PoI '" + id + "'."); - return; - } - } - } - if (!myShapeContainer.addPOI(id, type, color, pos, useGeo, laneID, lanePos, lanePosLat, layer, angle, imgFile, relativePath, width, height, ignorePruning)) { - WRITE_ERROR("PoI '" + id + "' already exists."); - } - myLastParameterised = myShapeContainer.getPOIs().get(id); - if ((laneID != "") && addLanePosParams()) { - myLastParameterised->setParameter(toString(SUMO_ATTR_LANE), laneID); - myLastParameterised->setParameter(toString(SUMO_ATTR_POSITION), toString(lanePos)); - myLastParameterised->setParameter(toString(SUMO_ATTR_POSITION_LAT), toString(lanePosLat)); - } - } -} - - -void -ShapeHandler::addPoly(const SUMOSAXAttributes& attrs, const bool ignorePruning, const bool useProcessing) { - bool ok = true; - const std::string id = myPrefix + attrs.get(SUMO_ATTR_ID, nullptr, ok); - // check if ID is valid - if (SUMOXMLDefinitions::isValidTypeID(id) == false) { - WRITE_WARNING("Invalid characters for Poly ID"); - ok = false; - } - // get the id, report an error if not given or empty... - if (ok) { - // continue loading parameters - const double layer = attrs.getOpt(SUMO_ATTR_LAYER, id.c_str(), ok, myDefaultLayer); - const bool fill = attrs.getOpt(SUMO_ATTR_FILL, id.c_str(), ok, myDefaultFill); - const double lineWidth = attrs.getOpt(SUMO_ATTR_LINEWIDTH, id.c_str(), ok, Shape::DEFAULT_LINEWIDTH); - const std::string type = attrs.getOpt(SUMO_ATTR_TYPE, id.c_str(), ok, Shape::DEFAULT_TYPE); - const RGBColor color = attrs.hasAttribute(SUMO_ATTR_COLOR) ? attrs.get(SUMO_ATTR_COLOR, id.c_str(), ok) : myDefaultColor; - PositionVector shape = attrs.get(SUMO_ATTR_SHAPE, id.c_str(), ok); - const bool geo = attrs.getOpt(SUMO_ATTR_GEO, id.c_str(), ok, false); - // set geo converter - const GeoConvHelper* gch; - if (myGeoConvHelper != nullptr) { - gch = myGeoConvHelper; - } else { - gch = &GeoConvHelper::getFinal(); - } - // check if poly use geo coordinates - if (geo || useProcessing) { - bool success = true; - for (int i = 0; i < (int)shape.size(); i++) { - if (useProcessing) { - success &= GeoConvHelper::getProcessing().x2cartesian(shape[i]); - } else { - success &= gch->x2cartesian_const(shape[i]); - } - } - if (!success) { - WRITE_WARNING("Unable to project coordinates for polygon '" + id + "'."); - return; - } - } - const double angle = attrs.getOpt(SUMO_ATTR_ANGLE, id.c_str(), ok, Shape::DEFAULT_ANGLE); - std::string imgFile = attrs.getOpt(SUMO_ATTR_IMGFILE, id.c_str(), ok, Shape::DEFAULT_IMG_FILE); - bool relativePath = attrs.getOpt(SUMO_ATTR_RELATIVEPATH, id.c_str(), ok, Shape::DEFAULT_RELATIVEPATH); - if (imgFile != "" && !FileHelpers::isAbsolute(imgFile)) { - imgFile = FileHelpers::getConfigurationRelative(getFileName(), imgFile); - } - // check that shape's size is valid - if (shape.size() == 0) { - WRITE_ERROR("Polygon's shape cannot be empty."); - return; - } - // check that lineWidth is positive - if (lineWidth <= 0) { - WRITE_ERROR("Polygon's lineWidth must be greather than 0."); - return; - } - // create polygon, or show an error if polygon already exists - if (!myShapeContainer.addPolygon(id, type, color, layer, angle, imgFile, relativePath, shape, geo, fill, lineWidth, ignorePruning)) { - WRITE_ERROR("Polygon '" + id + "' already exists."); - } - myLastParameterised = myShapeContainer.getPolygons().get(id); - } -} - - -Parameterised* -ShapeHandler::getLastParameterised() const { - return myLastParameterised; -} - - -bool -ShapeHandler::loadFiles(const std::vector& files, ShapeHandler& sh) { - for (const auto& fileIt : files) { - if (!XMLSubSys::runParser(sh, fileIt, false)) { - WRITE_MESSAGE("Loading of shapes from " + fileIt + " failed."); - return false; - } - } - return true; -} - - -void -ShapeHandler::setDefaults(const std::string& prefix, const RGBColor& color, const double layer, const bool fill) { - myPrefix = prefix; - myDefaultColor = color; - myDefaultLayer = layer; - myDefaultFill = fill; -} - - -bool -ShapeHandler::addLanePosParams() { - return false; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/utils/shapes/ShapeHandler.h b/Util/OSM2ODR/src/utils/shapes/ShapeHandler.h deleted file mode 100644 index 75c62bd12..000000000 --- a/Util/OSM2ODR/src/utils/shapes/ShapeHandler.h +++ /dev/null @@ -1,134 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file ShapeHandler.h -/// @author Jakob Erdmann -/// @date Feb 2015 -/// -// The XML-Handler for network loading -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include - - -// =========================================================================== -// class declarations -// =========================================================================== -class ShapeContainer; -class Parameterised; -class GeoConvHelper; - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class ShapeHandler - * @brief The XML-Handler for network loading - * - * The SAX2-handler responsible for parsing networks and routes to load. - * This is an extension of the MSRouteHandler as routes and vehicles may also - * be loaded from network descriptions. - */ -class ShapeHandler : public SUMOSAXHandler { -public: - /** @brief Constructor - * @param[in] file Name of the parsed file - * @param[in, out] net The network to fill - * @param[in] detBuilder The detector builder to use - * @param[in] triggerBuilder The trigger builder to use - * @param[in] edgeBuilder The builder of edges to use - * @param[in] junctionBuilder The builder of junctions to use - */ - ShapeHandler(const std::string& file, ShapeContainer& sc, const GeoConvHelper* = nullptr); - - /// @brief Destructor - virtual ~ShapeHandler(); - - /// @brief loads all of the given files - static bool loadFiles(const std::vector& files, ShapeHandler& sh); - -protected: - /// @name inherited from GenericSAXHandler - //@{ - /** @brief Called on the opening of a tag; - * - * @param[in] element ID of the currently opened element - * @param[in] attrs Attributes within the currently opened element - * @exception ProcessError If something fails - * @see GenericSAXHandler::myStartElement - * @todo Refactor/describe - */ - virtual void myStartElement(int element, const SUMOSAXAttributes& attrs); - - /** @brief Called when a closing tag occurs - * - * @param[in] element ID of the currently opened element - * @exception ProcessError If something fails - * @see GenericSAXHandler::myEndElement - * @todo Refactor/describe - */ - virtual void myEndElement(int element); - //@} - - /// @brief get position for a given laneID (Has to be implemented in all child) - virtual Position getLanePos(const std::string& poiID, const std::string& laneID, double lanePos, double lanePosLat) = 0; - - /// @brief Whether some input attributes shall be automatically added as params (Can be implemented in all child) - virtual bool addLanePosParams(); - -protected: - /// @brief set default values - void setDefaults(const std::string& prefix, const RGBColor& color, const double layer, const bool fill = false); - - /// @brief adds a POI - void addPOI(const SUMOSAXAttributes& attrs, const bool ignorePruning, const bool useProcessing); - - /// @brief adds a polygon - void addPoly(const SUMOSAXAttributes& attrs, const bool ignorePruning, const bool useProcessing); - - /// @brief get last parameterised object - Parameterised* getLastParameterised() const; - -protected: - /// @brief reference to shape container in which all Shares are being added - ShapeContainer& myShapeContainer; - - /// @brief The prefix to use - std::string myPrefix; - - /// @brief The default color to use - RGBColor myDefaultColor; - - /// @brief The default layer to use - double myDefaultLayer; - - /// @brief Information whether polygons should be filled - bool myDefaultFill; - - /// @brief element to receive parameters - Parameterised* myLastParameterised; - - /// @brief geo-conversion to use during loading - const GeoConvHelper* myGeoConvHelper; - - /// @brief invalidate copy constructor - ShapeHandler(const ShapeHandler& s) = delete; - - /// @brief invalidate assignment operator - ShapeHandler& operator=(const ShapeHandler& s) = delete; -}; diff --git a/Util/OSM2ODR/src/utils/traction_wire/CMakeLists.txt b/Util/OSM2ODR/src/utils/traction_wire/CMakeLists.txt deleted file mode 100644 index 87aaffcfb..000000000 --- a/Util/OSM2ODR/src/utils/traction_wire/CMakeLists.txt +++ /dev/null @@ -1,16 +0,0 @@ - -set(utils_traction_wire_STAT_SRCS - Circuit.cpp - Circuit.h - Element.cpp - Element.h -# The following files are only used in standalone mode: -# IO.cpp -# IO.h -# main.cpp - Node.cpp - Node.h -) - -add_library(utils_traction_wire STATIC ${utils_traction_wire_STAT_SRCS}) -set_property(TARGET utils_traction_wire PROPERTY PROJECT_LABEL "z_utils_traction_wire") diff --git a/Util/OSM2ODR/src/utils/traction_wire/Circuit.cpp b/Util/OSM2ODR/src/utils/traction_wire/Circuit.cpp deleted file mode 100644 index 19a168255..000000000 --- a/Util/OSM2ODR/src/utils/traction_wire/Circuit.cpp +++ /dev/null @@ -1,843 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file Circuit.cpp -/// @author Jakub Sevcik (RICE) -/// @author Jan Prikryl (RICE) -/// @date 2019-12-15 -/// -// Representation of electric circuit of overhead wires -/// @note based on work 2017 Ahmad Khaled, Ahmad Essam, Omnia Zakaria, Mary Nader -/****************************************************************************/ -#include -#include -#include -#include -#include -#include -#include -#ifdef HAVE_EIGEN -#include "Eigen/Dense" -#include "Eigen/Sparse" -#include "Eigen/Geometry" -#endif -#include "Element.h" -#include "Circuit.h" - -using namespace std; - -std::mutex circuit_lock; - -Node* Circuit::addNode(string name) { - if (getNode(name) != nullptr) { - //WRITE_ERROR("The node: '" + name + "' already exists."); - std::cout << "The node '" + name + "' already exists." << std::endl; - return nullptr; - } - - if (nodes->size() == 0) { - lastId = -1; - } - Node* tNode = new Node(name, this->lastId); - if (lastId == -1) { - tNode->setGround(true); - } - this->lastId++; - circuit_lock.lock(); - this->nodes->push_back(tNode); - circuit_lock.unlock(); - return tNode; -} - -void Circuit::eraseNode(Node* node) { - circuit_lock.lock(); - this->nodes->erase(std::remove(this->nodes->begin(), this->nodes->end(), node), this->nodes->end()); - circuit_lock.unlock(); -} - -double Circuit::getCurrent(string name) { - Element* tElement = getElement(name); - if (tElement == nullptr) { - return DBL_MAX; - } - return tElement->getCurrent(); -} - -double Circuit::getVoltage(string name) { - Element* tElement = getElement(name); - if (tElement == nullptr) { - Node* node = getNode(name); - if (node != nullptr) { - return node->getVoltage(); - } else { - return DBL_MAX; - } - } else { - return tElement->getVoltage(); - } -} - -double Circuit::getResistance(string name) { - Element* tElement = getElement(name); - if (tElement == nullptr) { - return -1; - } - return tElement->getResistance(); -} - -Node* Circuit::getNode(string name) { - // for (vector::iterator it = this->nodes->begin(); it != nodes->end(); it++) { - for (auto&& it : *this->nodes) { - if (it->getName() == name) { - return it; - } - } - return nullptr; -} - -Node* Circuit::getNode(int id) { - for (vector::iterator it = this->nodes->begin(); it != nodes->end(); it++) { - if ((*it)->getId() == id) { - return (*it); - } - } - return nullptr; -} - -Element* Circuit::getElement(string name) { - for (vector::iterator it = this->elements->begin(); it != elements->end(); it++) { - if ((*it)->getName() == name) { - return (*it); - } - } - for (vector::iterator it = this->voltageSources->begin(); it != voltageSources->end(); it++) { - if ((*it)->getName() == name) { - return (*it); - } - } - return nullptr; -} - -Element* Circuit::getElement(int id) { - for (vector::iterator it = this->elements->begin(); it != elements->end(); it++) { - if ((*it)->getId() == id) { - return (*it); - } - } - for (vector::iterator it = this->voltageSources->begin(); it != voltageSources->end(); it++) { - if ((*it)->getId() == id) { - return (*it); - } - } - return nullptr; -} - -Element* Circuit::getVoltageSource(int id) { - for (vector::iterator it = this->voltageSources->begin(); it != voltageSources->end(); it++) { - if ((*it)->getId() == id) { - return (*it); - } - } - return nullptr; -} - -vector* Circuit::getCurrentSources() { - vector* vsources = new vector(0); - for (vector::iterator it = this->elements->begin(); it != elements->end(); it++) { - if ((*it)->getType() == Element::ElementType::CURRENT_SOURCE_traction_wire) { - //if ((*it)->getType() == Element::ElementType::CURRENT_SOURCE_traction_wire && !isnan((*it)->getPowerWanted())) { - vsources->push_back(*it); - } - } - return vsources; -} - -void Circuit::lock() { - circuit_lock.lock(); -} - -void Circuit::unlock() { - circuit_lock.unlock(); -} - -#ifdef HAVE_EIGEN -void Circuit::removeColumn(Eigen::MatrixXd& matrix, int colToRemove) { - const int numRows = (int)matrix.rows(); - const int numCols = (int)matrix.cols() - 1; - - if (colToRemove < numCols) { - matrix.block(0, colToRemove, numRows, numCols - colToRemove) = matrix.rightCols(numCols - colToRemove); - } - - matrix.conservativeResize(numRows, numCols); -} - -bool Circuit::solveEquationsNRmethod(double* eqn, double* vals, std::vector* removable_ids) { - // removable_ids includes nodes with voltage source already - int numofcolumn = (int)voltageSources->size() + (int)nodes->size() - 1; - int numofeqs = numofcolumn - (int)removable_ids->size(); - - Eigen::MatrixXd A = Eigen::Map < Eigen::Matrix >(eqn, numofeqs, numofcolumn); - - int id; - // removing removable columns - for (std::vector::reverse_iterator it = removable_ids->rbegin(); it != removable_ids->rend(); ++it) { - id = (*it >= 0 ? *it : -(*it)); - removeColumn(A, id); - } - - // detecting number of column for each node - // in other words: detecting elements of x to certain node - int j = 0; - Element* tElem = nullptr; - Node* tNode = nullptr; - for (int i = 0; i < numofcolumn; i++) { - tNode = getNode(i); - if (tNode != nullptr) - if (tNode->isRemovable()) { - tNode->setNumMatrixCol(-1); - continue; - } else { - // TODO: is the numofeqs (defined above) still the same as the part below? - if (j > numofcolumn - (int) removable_ids->size()) { - WRITE_ERROR("Number of column deployment during circuit evaluation was unsuccessfull."); - break; - } - tNode->setNumMatrixCol(j); - j++; - continue; - } else { - tElem = getElement(i); - if (tElem != nullptr) { - // TODO: is the numofeqs (defined above) still the same as the part below? - if (j > numofcolumn - (int) removable_ids->size()) { - WRITE_ERROR("Number of column deployment deployment during circuit evaluation was unsuccessfull."); - break; - } - continue; - } - } - WRITE_ERROR("Number of column deployment during circuit evaluation was unsuccessfull."); - } - - Eigen::Map b(vals, numofeqs); - Eigen::VectorXd x = A.colPivHouseholderQr().solve(b); - // probably unused - // double relative_error = (A*x - b).norm() / b.norm(); - - Eigen::MatrixXd J = A; - Eigen::VectorXd dx; - int max_iter_of_NR = 10; - int attemps = 0; - double alpha = 1; - alphaBest = 0; - //TODORICE alphaBest private and function get and setAlphaBest - std::vector alpha_notSolution; - double alpha_res = 1e-2; - double* x_best = new double[numofeqs]; - //init x_best - for (int i = 0; i < numofeqs; i++) { - x_best[i] = x[i]; - } - if (x.maxCoeff() > 10e6 || x.minCoeff() < -10e6) { - - WRITE_ERROR("Here is the matrix A:\n" + toString(A)); - WRITE_ERROR("Here is the vector b:\n" + toString(b)); - WRITE_ERROR("Here is the vector x:\n" + toString(x)); - for (int i = 0; i < numofeqs; i++) { - x_best[i] = 600; - } - } - //search alpha - while (true) { - - ++attemps; - int iterNR = 0; - // run Newton-Raphson methods - while (true) { - - for (int i = 0; i < numofeqs - (int) voltageSources->size(); i++) { - vals[i] = 0; - } - J = A; - - int i = 0; - for (auto& node : *nodes) { - if (node->isGround() || node->isRemovable() || node->getNumMatrixRow() == -2) { - continue; - } - if (node->getNumMatrixRow() != i) { - WRITE_ERROR("wrongly assigned row of matrix A during solving the circuit"); - } - // TODO: Range-based loop - for (auto it_element = node->getElements()->begin(); it_element != node->getElements()->end(); it_element++) { - if ((*it_element)->getType() == Element::ElementType::CURRENT_SOURCE_traction_wire) { - if ((*it_element)->isEnabled()) { - double diff_voltage; - if ((*it_element)->getPosNode()->getNumMatrixCol() == -1) { - diff_voltage = -x[(*it_element)->getNegNode()->getNumMatrixCol()]; - } else if ((*it_element)->getNegNode()->getNumMatrixCol() == -1) { - diff_voltage = x[(*it_element)->getPosNode()->getNumMatrixCol()]; - } else { - diff_voltage = (x[(*it_element)->getPosNode()->getNumMatrixCol()] - x[(*it_element)->getNegNode()->getNumMatrixCol()]); - } - - if ((*it_element)->getPosNode() == node) { - vals[i] -= alpha * (*it_element)->getPowerWanted() / diff_voltage; - (*it_element)->setCurrent(-alpha * (*it_element)->getPowerWanted() / diff_voltage); - if ((*it_element)->getPosNode()->getNumMatrixCol() != -1) { - J(i, (*it_element)->getPosNode()->getNumMatrixCol()) -= alpha * (*it_element)->getPowerWanted() / diff_voltage / diff_voltage; - } - if ((*it_element)->getNegNode()->getNumMatrixCol() != -1) { - J(i, (*it_element)->getNegNode()->getNumMatrixCol()) += alpha * (*it_element)->getPowerWanted() / diff_voltage / diff_voltage; - } - } else { - vals[i] += alpha * (*it_element)->getPowerWanted() / diff_voltage; - //sign before alpha - or + during setting current? - //(*it_element)->setCurrent(alpha * (*it_element)->getPowerWanted() / diff_voltage); - if ((*it_element)->getPosNode()->getNumMatrixCol() != -1) { - J(i, (*it_element)->getPosNode()->getNumMatrixCol()) += alpha * (*it_element)->getPowerWanted() / diff_voltage / diff_voltage; - } - if ((*it_element)->getNegNode()->getNumMatrixCol() != -1) { - J(i, (*it_element)->getNegNode()->getNumMatrixCol()) -= alpha * (*it_element)->getPowerWanted() / diff_voltage / diff_voltage; - } - } - } - } - } - i++; - } - - // TODO: The variable below was declared as `b`, renamed to `bb`, check if the rename was consistent. - Eigen::Map bb(vals, numofeqs); - - if ((A * x - bb).norm() < 1e-6) { - alphaBest = alpha; - for (int ii = 0; ii < numofeqs; ii++) { - x_best[ii] = x[ii]; - } - break; - } else if (iterNR == max_iter_of_NR) { - alpha_notSolution.push_back(alpha); - for (int ii = 0; ii < numofeqs; ii++) { - x[ii] = x_best[ii]; - } - break; - } - - dx = -J.colPivHouseholderQr().solve(A * x - bb); - x = x + dx; - ++iterNR; - } - - if (alpha_notSolution.empty()) { - break; - } - - if ((alpha_notSolution.back() - alphaBest) < alpha_res) { - max_iter_of_NR = 2 * max_iter_of_NR; - alpha_res = alpha_res / 10; - if (alpha_res < 5e-5) { - break; - } - alpha = alpha_notSolution.back(); - alpha_notSolution.pop_back(); - continue; - } - - alpha = alphaBest + 0.5 * (alpha_notSolution.back() - alphaBest); - } - - for (int i = 0; i < numofeqs; i++) { - vals[i] = x_best[i]; - } - - int i = 0; - for (auto& node : *nodes) { - if (node->isGround() || node->isRemovable() || node->getNumMatrixRow() == -2) { - continue; - } - if (node->getNumMatrixRow() != i) { - WRITE_ERROR("wrongly assigned row of matrix A during solving the circuit"); - } - for (auto it_element = node->getElements()->begin(); it_element != node->getElements()->end(); it_element++) { - if ((*it_element)->getType() == Element::ElementType::CURRENT_SOURCE_traction_wire) { - if ((*it_element)->isEnabled()) { - double diff_voltage; - if ((*it_element)->getPosNode()->getNumMatrixCol() == -1) { - diff_voltage = -x_best[(*it_element)->getNegNode()->getNumMatrixCol()]; - } else if ((*it_element)->getNegNode()->getNumMatrixCol() == -1) { - diff_voltage = x_best[(*it_element)->getPosNode()->getNumMatrixCol()]; - } else { - diff_voltage = (x_best[(*it_element)->getPosNode()->getNumMatrixCol()] - x_best[(*it_element)->getNegNode()->getNumMatrixCol()]); - } - - if ((*it_element)->getPosNode() == node) { - (*it_element)->setCurrent(-alphaBest * (*it_element)->getPowerWanted() / diff_voltage); - } else { - //sign before alpha - or + during setting current? - //(*it_element)->setCurrent(alpha * (*it_element)->getPowerWanted() / diff_voltage); - } - } - } - } - i++; - } - - return true; -} -#endif - -void Circuit::deployResults(double* vals, std::vector* removable_ids) { - int n = (int)(voltageSources->size() + nodes->size() - 1); - int j = 0; - Element* tElem = nullptr; - Node* tNode = nullptr; - for (int i = 0; i < n; i++) { - tNode = getNode(i); - if (tNode != nullptr) - if (tNode->isRemovable()) { - continue; - } else { - // TODO: Is the n - (int) removable_ids->size() constant? - if (j > n - (int) removable_ids->size()) { - WRITE_ERROR("Results deployment during circuit evaluation was unsuccessfull."); - break; - } - tNode->setVoltage(vals[j]); - j++; - continue; - } else { - tElem = getElement(i); - if (tElem != nullptr) { - // TODO: Is the n - (int) removable_ids->size() constant? - if (j > n - (int) removable_ids->size()) { - WRITE_ERROR("Results deployment during circuit evaluation was unsuccessfull."); - break; - } - //tElem->setCurrent(vals[j]); - //TODORICE dodelat vypocet proudu na zdroji z Kirchhofova zakona: proudy dovnitr = proudy ven - //tElem->setCurrent(-1000); - //j++; - continue; - } - } - WRITE_ERROR("Results deployment during circuit evaluation was unsuccessfull."); - } - - Element* el1 = nullptr; - Element* el2 = nullptr; - Node* nextNONremovableNode1 = nullptr; - Node* nextNONremovableNode2 = nullptr; - // interpolate result of voltage to removable nodes - for (vector::iterator it = nodes->begin(); it != nodes->end(); it++) { - if (!(*it)->isRemovable()) { - continue; - } - if ((*it)->getElements()->size() != 2) { - continue; - } - - el1 = (*it)->getElements()->front(); - el2 = (*it)->getElements()->back(); - nextNONremovableNode1 = el1->getTheOtherNode(*it); - nextNONremovableNode2 = el2->getTheOtherNode(*it); - double x = el1->getResistance(); - double y = el2->getResistance(); - - while (nextNONremovableNode1->isRemovable()) { - el1 = nextNONremovableNode1->getAnOtherElement(el1); - x += el1->getResistance(); - nextNONremovableNode1 = el1->getTheOtherNode(nextNONremovableNode1); - } - - while (nextNONremovableNode2->isRemovable()) { - el2 = nextNONremovableNode2->getAnOtherElement(el2); - y += el2->getResistance(); - nextNONremovableNode2 = el2->getTheOtherNode(nextNONremovableNode2); - } - - x = x / (x + y); - y = ((1 - x) * nextNONremovableNode1->getVoltage()) + (x * nextNONremovableNode2->getVoltage()); - (*it)->setVoltage(((1 - x)*nextNONremovableNode1->getVoltage()) + (x * nextNONremovableNode2->getVoltage())); - (*it)->setRemovability(false); - } - - /* - for (int i = 0; i < n; i++) { - Node* tNode = getNode(i); - if (tNode != nullptr) - tNode->setVoltage(vals[i]); - else - { - Element* tElem = getElement(i); - if (tElem != nullptr) { - tElem->setCurrent(vals[i]); - } - } - } - */ -} - -Circuit::Circuit() { - nodes = new vector(0); - elements = new vector(0); - voltageSources = new vector(0); - lastId = 0; - iscleaned = true; -} - -#ifdef HAVE_EIGEN -bool Circuit::_solveNRmethod() { - double* eqn = nullptr; - double* vals = nullptr; - std::vector removable_ids; - - detectRemovableNodes(&removable_ids); - createEquationsNRmethod(eqn, vals, &removable_ids); - if (!solveEquationsNRmethod(eqn, vals, &removable_ids)) { - return false; - } - deployResults(vals, &removable_ids); - - return true; -} - -bool Circuit::solve() { - if (!iscleaned) { - cleanUpSP(); - } - return this->_solveNRmethod(); -} - -bool Circuit::createEquationsNRmethod(double*& eqs, double*& vals, std::vector* removable_ids) { - // removable_ids does not include nodes with voltage source - int n = (int)(voltageSources->size() + nodes->size() - 1); - int m = n - (int)(removable_ids->size() - voltageSources->size()); - //cout << endl << endl << n << endl << endl; - eqs = new double[m * n]; - vals = new double[m]; - - for (int i = 0; i < m; i++) { - vals[i] = 0; - for (int j = 0; j < n; j++) { - eqs[i * n + j] = 0; - } - } - - int i = 0; - for (vector::iterator it = nodes->begin(); it != nodes->end(); it++) { - if ((*it)->isGround() || (*it)->isRemovable()) { - (*it)->setNumMatrixRow(-1); - continue; - } - bool noVoltageSource = createEquationNRmethod((*it), (eqs + n * i), vals[i], removable_ids); - // if the node it has element of type "voltage source" we do not use the equation, because some value of current throw the voltage source can be always find - if (noVoltageSource) { - (*it)->setNumMatrixRow(i); - i++; - } else { - (*it)->setNumMatrixRow(-2); - vals[i] = 0; - for (int j = 0; j < n; j++) { - eqs[n * i + j] = 0; - } - } - } - // removable_ids includes nodes with voltage source already - std::sort(removable_ids->begin(), removable_ids->end(), std::less()); - - for (vector::iterator it = voltageSources->begin(); it != voltageSources->end(); it++) { - createEquation((*it), (eqs + n * i), vals[i]); - i++; - } - - return true; -} - -bool Circuit::createEquation(Element* vsource, double* eqn, double& val) { - if (!vsource->getPosNode()->isGround()) { - eqn[vsource->getPosNode()->getId()] = 1; - } - if (!vsource->getNegNode()->isGround()) { - eqn[vsource->getNegNode()->getId()] = -1; - } - if (vsource->isEnabled()) { - val = vsource->getVoltage(); - } else { - val = 0; - } - return true; -} - -bool Circuit::createEquationNRmethod(Node* node, double* eqn, double& val, std::vector* removable_ids) { - for (vector::iterator it = node->getElements()->begin(); it != node->getElements()->end(); it++) { - double x; - switch ((*it)->getType()) { - case Element::ElementType::RESISTOR_traction_wire: - if ((*it)->isEnabled()) { - x = (*it)->getResistance(); - Node* nextNONremovableNode = (*it)->getTheOtherNode(node); - Element* nextSerialResistor = *it; - while (nextNONremovableNode->isRemovable()) { - nextSerialResistor = nextNONremovableNode->getAnOtherElement(nextSerialResistor); - x += nextSerialResistor->getResistance(); - nextNONremovableNode = nextSerialResistor->getTheOtherNode(nextNONremovableNode); - } - x = 1 / x; - eqn[node->getId()] += x; - if (!nextNONremovableNode->isGround()) { - eqn[nextNONremovableNode->getId()] -= x; - } - //if (!(*it)->getTheOtherNode(node)->isGround()) - // eqn[(*it)->getTheOtherNode(node)->getId()] -= x; - } - break; - case Element::ElementType::CURRENT_SOURCE_traction_wire: - if ((*it)->isEnabled()) { - if ((*it)->getPosNode() == node) { - x = (*it)->getCurrent(); - } else { - x = -(*it)->getCurrent(); - } - } else { - x = 0; - } - val += x; - break; - case Element::ElementType::VOLTAGE_SOURCE_traction_wire: - if ((*it)->getPosNode() == node) { - x = -1; - } else { - x = 1; - } - eqn[(*it)->getId()] += x; - // equations with voltage source can be igored, because some value of current throw the voltage source can be always find - removable_ids->push_back((*it)->getId()); - return false; - break; - case Element::ElementType::ERROR_traction_wire: - return false; - break; - } - } - return true; -} -#endif - -void Circuit::detectRemovableNodes(std::vector* removable_ids) { - for (vector::iterator it = nodes->begin(); it != nodes->end(); it++) { - if ((*it)->getElements()->size() == 2 && !(*it)->isGround()) { - (*it)->setRemovability(true); - for (vector::iterator it2 = (*it)->getElements()->begin(); it2 != (*it)->getElements()->end(); it2++) { - if ((*it2)->getType() != Element::ElementType::RESISTOR_traction_wire) { - (*it)->setRemovability(false); - break; - } - } - if ((*it)->isRemovable()) { - removable_ids->push_back((*it)->getId()); - } - } else { - (*it)->setRemovability(false); - } - } - std::sort(removable_ids->begin(), removable_ids->end(), std::less()); - return; -} - -Element* Circuit::addElement(string name, double value, Node* pNode, Node* nNode, Element::ElementType et) { - if ((et == Element::ElementType::RESISTOR_traction_wire && value <= 0) || et == Element::ElementType::ERROR_traction_wire) { - return nullptr; - } - - Element* e = getElement(name); - - if (e != nullptr) { - //WRITE_ERROR("The element: '" + name + "' already exists."); - std::cout << "The element: '" + name + "' already exists."; - return nullptr; - } - - e = new Element(name, et, value); - if (e->getType() == Element::ElementType::VOLTAGE_SOURCE_traction_wire) { - e->setId(lastId); - lastId++; - circuit_lock.lock(); - this->voltageSources->push_back(e); - circuit_lock.unlock(); - } else { - circuit_lock.lock(); - this->elements->push_back(e); - circuit_lock.unlock(); - } - - e->setPosNode(pNode); - e->setNegNode(nNode); - - pNode->addElement(e); - nNode->addElement(e); - return e; -} - -void Circuit::eraseElement(Element* element) { - //element->getPosNode()->eraseElement(element); - //element->getNegNode()->eraseElement(element); - circuit_lock.lock(); - this->elements->erase(std::remove(this->elements->begin(), this->elements->end(), element), this->elements->end()); - circuit_lock.unlock(); -} - -void Circuit::replaceAndDeleteNode(Node* unusedNode, Node* newNode) { - //replace element node if it is unusedNode - for (auto& voltageSource : *voltageSources) { - if (voltageSource->getNegNode() == unusedNode) { - voltageSource->setNegNode(newNode); - newNode->eraseElement(voltageSource); - newNode->addElement(voltageSource); - } - if (voltageSource->getPosNode() == unusedNode) { - voltageSource->setPosNode(newNode); - newNode->eraseElement(voltageSource); - newNode->addElement(voltageSource); - } - } - for (auto& element : *elements) { - if (element->getNegNode() == unusedNode) { - element->setNegNode(newNode); - newNode->eraseElement(element); - newNode->addElement(element); - } - if (element->getPosNode() == unusedNode) { - element->setPosNode(newNode); - newNode->eraseElement(element); - newNode->addElement(element); - } - } - - //erase unusedNode from nodes vector - this->eraseNode(unusedNode); - - //modify id of other elements and nodes - int modLastId = this->getLastId() - 1; - if (unusedNode->getId() != modLastId) { - Node* node_last = this->getNode(modLastId); - if (node_last != nullptr) { - node_last->setId(unusedNode->getId()); - } else { - Element* elem_last = this->getVoltageSource(modLastId); - if (elem_last != nullptr) { - elem_last->setId(unusedNode->getId()); - } else { - WRITE_ERROR("The element or node with the last Id was not found in the circuit!"); - } - } - } - - this->descreaseLastId(); - delete unusedNode; -} - -void Circuit::cleanUpSP() { - for (vector::iterator it = elements->begin(); it != elements->end(); it++) { - if ((*it)->getType() != Element::ElementType::RESISTOR_traction_wire) { - (*it)->setEnabled(true); - } - } - - for (vector::iterator it = voltageSources->begin(); it != voltageSources->end(); it++) { - (*it)->setEnabled(true); - } - this->iscleaned = true; -} - -bool Circuit::checkCircuit(std::string substationId) { - // check empty nodes - for (vector::iterator it = nodes->begin(); it != nodes->end(); it++) { - if ((*it)->getNumOfElements() < 2) { - //cout << "WARNING: Node [" << (*it)->getName() << "] is connected to less than two elements, please enter other elements.\n"; - if ((*it)->getNumOfElements() < 1) { - return false; - } - } - } - // check voltage sources - for (vector::iterator it = voltageSources->begin(); it != voltageSources->end(); it++) { - if ((*it)->getPosNode() == nullptr || (*it)->getNegNode() == nullptr) { - //cout << "ERROR: Voltage Source [" << (*it)->getName() << "] is connected to less than two nodes, please enter the other end.\n"; - WRITE_ERROR("Circuit Voltage Source '" + (*it)->getName() + "' is connected to less than two nodes, please adjust the definition of the section (with substation '" + substationId + "')."); - return false; - } - } - // check other elements - for (vector::iterator it = elements->begin(); it != elements->end(); it++) { - if ((*it)->getPosNode() == nullptr || (*it)->getNegNode() == nullptr) { - //cout << "ERROR: Element [" << (*it)->getName() << "] is connected to less than two nodes, please enter the other end.\n"; - WRITE_ERROR("Circuit Element '" + (*it)->getName() + "' is connected to less than two nodes, please adjust the definition of the section (with substation '" + substationId + "')."); - return false; - } - } - - // check connectivity - int num = (int)nodes->size() + getNumVoltageSources() - 1; - bool* nodesVisited = new bool[num]; - for (int i = 0; i < num; i++) { - nodesVisited[i] = false; - } - // TODO: Probably unused - // int id = -1; - if (!getNode(-1)->isGround()) { - //cout << "ERROR: Node id -1 is not the ground \n"; - WRITE_ERROR("Circuit Node with id '-1' is not the grounded, please adjust the definition of the section (with substation '" + substationId + "')."); - } - vector* queue = new vector(0); - Node* node = nullptr; - Node* neigboringNode = nullptr; - //start with (voltageSources->front()->getPosNode()) - nodesVisited[voltageSources->front()->getId()] = 1; - node = voltageSources->front()->getPosNode(); - queue->push_back(node); - - while (!queue->empty()) { - node = queue->back(); - queue->pop_back(); - if (!nodesVisited[node->getId()]) { - nodesVisited[node->getId()] = true; - for (auto it = node->getElements()->begin(); it != node->getElements()->end(); it++) { - neigboringNode = (*it)->getTheOtherNode(node); - if (!neigboringNode->isGround()) { - queue->push_back(neigboringNode); - } else if ((*it)->getType() == Element::ElementType::VOLTAGE_SOURCE_traction_wire) { - /// there used to be == 1 which was probably a typo ... check! - nodesVisited[(*it)->getId()] = 1; - } else if ((*it)->getType() == Element::ElementType::RESISTOR_traction_wire) { - //cout << "ERROR: The resistor type connects the ground \n"; - WRITE_ERROR("A Circuit Resistor Element connects the ground, please adjust the definition of the section (with substation '" + substationId + "')."); - } - } - } - } - - for (int i = 0; i < num; i++) { - if (nodesVisited[i] == 0) { - //cout << "ERROR: Node or voltage source with id " << (i) << " has been not visited during checking of the circuit => Disconnectivity of the circuit. \n"; - WRITE_WARNING("Circuit Node or Voltage Source with internal id '" + toString(i) + "' has been not visited during checking of the circuit. The circuit is disconnected, please adjust the definition of the section (with substation '" + substationId + "')."); - } - } - - return true; -} - -int Circuit::getNumVoltageSources() { - return (int) voltageSources->size(); -} diff --git a/Util/OSM2ODR/src/utils/traction_wire/Circuit.h b/Util/OSM2ODR/src/utils/traction_wire/Circuit.h deleted file mode 100644 index 7f310e3f6..000000000 --- a/Util/OSM2ODR/src/utils/traction_wire/Circuit.h +++ /dev/null @@ -1,181 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file Circuit.h -/// @author Jakub Sevcik (RICE) -/// @author Jan Prikryl (RICE) -/// @date 2019-12-15 -/// -// Representation of electric circuit of overhead wires -/// @note based on work 2017 Ahmad Khaled, Ahmad Essam, Omnia Zakaria, Mary Nader -/****************************************************************************/ -#pragma once - -#include -#ifdef HAVE_EIGEN -#include "Eigen/Dense" -#include "Eigen/Geometry" -#endif -#include "Node.h" -#include "Element.h" - -/** - * All interactions will be through this class, the user will know nothing about the other classes, - * and will interact only through the names of the elements/nodes. - */ - - -class Circuit { - -private: - - vector* nodes; - vector* elements; - vector* voltageSources; - - int lastId; - bool iscleaned; - -public: - Node* getNode(string name); - Element* getElement(string name); - Node* getNode(int id); - Element* getVoltageSource(int id); - vector* getCurrentSources(); - - void lock(); - void unlock(); - - /** - * @brief Best alpha scaling value. - * - * This parameter is used to scale down the power demands of current sources (vehicles - * that draw power from the circuit) so that a solution of the system can be found. - * Note: the system is nonlinear (quadratic), hence in some cases (typically too high - * power demands) a solution cannot be found. In that moment we decrease all power - * requirements by `alpha` and try to solve again, until we find alpha that ensures - * stable solution. This is then reported as alphaBest. - */ - double alphaBest; - -private: - Element* getElement(int id); - - /* - * detects removable nodes = sets node variable "isremovable" to true if node is removable and adds id of such node to "removable_ids" vector - * node is denoted as removable if it is connected just to 2 elements and both of them are resistor - * the reason is that in such case there are two serial resistor and we can only sum their resistance value - * - * "removable_ids" vector is sort from the least to the greatest - */ - void detectRemovableNodes(std::vector* removable_ids); - - void deployResults(double* vals, std::vector* removable_ids); - -#ifdef HAVE_EIGEN - /* - * creates all of the equations that represent the circuit - * in the form Ax = B(1/x) where A and B are matricies - * @param eqn : A - * @param vals : B - */ - bool createEquationsNRmethod(double*& eqs, double*& vals, std::vector* removable_ids); - - - /* - * creates the nodal equation of the node 'node' GV = I - * in the form Ax = B(1/x) where A is a matrix with one row - * @param node : the node to be analyzed - * @param eqn : A - * @param val : B - */ - bool createEquationNRmethod(Node* node, double* eqn, double& val, std::vector* removable_ids); - - /** - * @brief Create the equation of the voltage source. - * Create the equation V2 - V1 = E of the voltage source in the form Ax = B, - * where A is a matrix with one row, B a value - * @param[in] vsource The voltage source - * @param[in] eqn : A - * @param[in] val : B - * @return ??? - */ - bool createEquation(Element* vsource, double* eqn, double& val); - - /* - * removes the "colToRemove"-th column from matrix "matrix" - */ - void removeColumn(Eigen::MatrixXd& matrix, const int colToRemove); - - /* - * solves the system of nonlinear equations Ax = B(1/x) - * @param eqn : A - * @param vals : B - */ - bool solveEquationsNRmethod(double* eqn, double* vals, std::vector*); - - bool _solveNRmethod(); - -#endif -public: - - // a Constructor, same functionality as "init" functions - Circuit(); - - // adds an element with name "name", type "type" and value "value" to positive node "pNode" and negative node "nNode"" - Element* addElement(string name, double value, Node* pNode, Node* nNode, Element::ElementType et); - - void eraseElement(Element* element); - - // adds a node with name "name" - Node* addNode(string name); - - // erases a node with name "name" - void eraseNode(Node* node); - - // gets current through element "name" - double getCurrent(string name); - - // gets voltage across element or node "name" - double getVoltage(string name); - - // gets the resistance of an element. - double getResistance(string name); - - // gets the number of voltage sources in the circuit. - int getNumVoltageSources(); - - // checks if the circuit's connections are correct. - bool checkCircuit(std::string substationId = ""); - -#ifdef HAVE_EIGEN - // solves the circuit and deploys the results - bool solve(); -#endif - - // cleans up after superposition. - void cleanUpSP(); - - //replaces unusedNode with newNode everywhere in the circuit, modifies the ids of other nodes and elements, descreases the id by one and deletes unusedNode - void replaceAndDeleteNode(Node* unusedNode, Node* newNode); - - // returns lastId - int getLastId() { - return lastId; - }; - - // decreases lastId by one - void descreaseLastId() { - lastId--; - }; -}; diff --git a/Util/OSM2ODR/src/utils/traction_wire/Element.cpp b/Util/OSM2ODR/src/utils/traction_wire/Element.cpp deleted file mode 100644 index be0637ac9..000000000 --- a/Util/OSM2ODR/src/utils/traction_wire/Element.cpp +++ /dev/null @@ -1,152 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file Element.cpp -/// @author Jakub Sevcik (RICE) -/// @author Jan Prikryl (RICE) -/// @date 2019-12-15 -/// -// Representation of electric circuit elements: resistors, voltage and current sources -/// @note based on work 2017 Ahmad Khaled, Ahmad Essam, Omnia Zakaria, Mary Nader -/****************************************************************************/ -#include -#include -#include "Element.h" -#include "Node.h" - -Element::Element(string name, ElementType type, double value) { - this->id = -2; - this->name = name; - this->type = type; - this->isenabled = true; - this->resistance = 0; - this->current = 0; - this->voltage = 0; - this->powerWanted = NAN; - switch (type) { - case CURRENT_SOURCE_traction_wire: - this->current = value; - break; - case VOLTAGE_SOURCE_traction_wire: - this->voltage = value; - break; - case RESISTOR_traction_wire: - this->resistance = value; - break; - default: - cout << "ERROR: TYPE UNDEFINED.\n"; - break; - } - this->pNode = nullptr; - this->nNode = nullptr; -} - -void Element::setVoltage(double voltageIn) { - this->voltage = voltageIn; -} -void Element::setCurrent(double currentIn) { - this->current = currentIn; -} -void Element::setResistance(double resistanceIn) { - if (resistanceIn <= 1e-6) { - this->resistance = 1e-6; - } else { - this->resistance = resistanceIn; - } -} -void Element::setPowerWanted(double powerWantedIn) { - this->powerWanted = powerWantedIn; -} -double Element::getVoltage() { - if (this->isenabled == false) { - return DBL_MAX; - } - if (getType() == Element::ElementType::VOLTAGE_SOURCE_traction_wire) { - return voltage; - } - return this->pNode->getVoltage() - this->nNode->getVoltage(); -} -double Element::getCurrent() { - if (this->isenabled == false) { - return DBL_MAX; - } - switch (this->type) { - case Element::ElementType::RESISTOR_traction_wire: - return -1 * getVoltage() / resistance; - case Element::ElementType::CURRENT_SOURCE_traction_wire: - case Element::ElementType::VOLTAGE_SOURCE_traction_wire: - return current; - default: - return 0; - } -} -double Element::getResistance() { - return this->resistance; -} -double Element::getPowerWanted() { - return this->powerWanted; -} -double Element::getPower() { - return -1 * getCurrent() * getVoltage(); -} -int Element::getId() { - - return this->id; -} -Node* Element::getPosNode() { - return this->pNode; -} -Node* Element::getNegNode() { - return this->nNode; -} - -Element::ElementType Element::getType() { - return this->type; -} -string Element::getName() { - return this->name; -} - -void Element::setPosNode(Node* node) { - this->pNode = node; - -} -void Element::setNegNode(Node* node) { - this->nNode = node; -} -void Element::setId(int newId) { - this->id = newId; -} - -// if node == pNode, return nNode, else if node == nNode return pNode, else return nullptr -Node* Element::getTheOtherNode(Node* node) { - if (node == pNode) { - return nNode; - } else if (node == nNode) { - return pNode; - } else { - return nullptr; - } -} - -bool Element::isEnabled() { - return isenabled; -} - -void Element::setEnabled(bool newIsEnabled) { - this->isenabled = newIsEnabled; -} - -void Element::setType(ElementType ET) { - this->type = ET; -} diff --git a/Util/OSM2ODR/src/utils/traction_wire/Element.h b/Util/OSM2ODR/src/utils/traction_wire/Element.h deleted file mode 100644 index 70337b733..000000000 --- a/Util/OSM2ODR/src/utils/traction_wire/Element.h +++ /dev/null @@ -1,95 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file Element.h -/// @author Jakub Sevcik (RICE) -/// @author Jan Prikryl (RICE) -/// @date 2019-12-15 -/// -// Representation of electric circuit elements: resistors, voltage and current sources -/// @note based on work 2017 Ahmad Khaled, Ahmad Essam, Omnia Zakaria, Mary Nader -/****************************************************************************/ -#pragma once - -#include -#include -using namespace std; - -class Node; - -/** - * An element is any component in the circuit (resistor, current source, voltage source) - * Every element has two terminals pNode (positive terminal) and nNode (negative terminal) - * value is the resistance in case of a resistor, current in case of a current source - * and voltage in case of voltage source. - * - * Conventions used: - * - * 1 - in case of a current source, "value" represents the current going from nNode to pNode, - * 2 - in case of a voltage source, "value" represents the voltage difference of pNode - nNode. - */ - -class Element { - -public: - enum ElementType { - RESISTOR_traction_wire, - CURRENT_SOURCE_traction_wire, - VOLTAGE_SOURCE_traction_wire, - ERROR_traction_wire - }; - -private: - Node* pNode; - Node* nNode; - double voltage; - double current; - double resistance; - double powerWanted; - ElementType type; - string name; // unique property, each object has distinctive and unique name - int id; // a sequential ID number, might be useful when making the equation - bool isenabled; - -public: - // a constructor. same functionality as init functions in the last project - Element(string name, ElementType type, double value); - - //getters and setters - double getVoltage(); // get the voltage across the element - double getCurrent(); // get the current running through the element - double getResistance(); - double getPowerWanted(); - double getPower(); - int getId(); - Node* getPosNode(); - Node* getNegNode(); - ElementType getType(); - string getName(); - bool isEnabled(); - - void setPosNode(Node* node); - void setNegNode(Node* node); - void setId(int id); - void setVoltage(double voltage); - void setCurrent(double current); - void setResistance(double resistance); - void setPowerWanted(double powerWanted); - void setEnabled(bool isenabled); - - // if node == pNode, return nNode, else if node == nNode return pNode, else return NULL - Node* getTheOtherNode(Node* node); - // sets the type of elements - void setType(ElementType ET); - -}; diff --git a/Util/OSM2ODR/src/utils/traction_wire/Node.cpp b/Util/OSM2ODR/src/utils/traction_wire/Node.cpp deleted file mode 100644 index efdd5c9dc..000000000 --- a/Util/OSM2ODR/src/utils/traction_wire/Node.cpp +++ /dev/null @@ -1,115 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file Node.cpp -/// @author Jakub Sevcik (RICE) -/// @author Jan Prikryl (RICE) -/// @date 2019-12-15 -/// -// Representation of electric circuit nodes, i.e. wire junctions and connection points. -/// @note based on work 2017 Ahmad Khaled, Ahmad Essam, Omnia Zakaria, Mary Nader -/****************************************************************************/ -#include -#include -#include "Node.h" -#include "Element.h" - -using namespace std; - -// A constructor, same functionality as "init" functions -Node::Node(string name, int id) { - isground = false; - this->name = name; // unique property, each object has distinctive and unique name - this->id = id; // a sequential ID number, might be useful when making the equation - this->num_matrixRow = -1; - this->num_matrixCol = -1; - this->voltage = 0; - this->elements = new vector(0); - isremovable = false; -} - -// connects an element to the node -void Node::addElement(Element* element) { - elements->push_back(element); -} - -void Node::eraseElement(Element* element) { - elements->erase(std::remove(elements->begin(), elements->end(), element), elements->end()); -} - -// getters and setters -double Node::getVoltage() { - return this->voltage; -} - -void Node::setVoltage(double voltage) { - this->voltage = voltage; -} - -int Node::getNumOfElements() { - return (int) elements->size(); -} - -string& Node::getName() { - return this->name; -} - -bool Node::isGround() { - return this->isground; -} - -void Node::setGround(bool newIsGround) { - this->isground = newIsGround; -} - -int Node::getId() { - return this->id; -} - -void Node::setId(int newId) { - this->id = newId; -} - -void Node::setNumMatrixRow(int num) { - this->num_matrixRow = num; -} - -int Node::getNumMatrixRow() { - return this->num_matrixRow; -} - -void Node::setNumMatrixCol(int num) { - this->num_matrixCol = num; -} - -int Node::getNumMatrixCol() { - return this->num_matrixCol; -} - -vector* Node::getElements() { - return elements; -} - -void Node::setRemovability(bool newIsRemovable) { - this->isremovable = newIsRemovable; -} - -Element* Node::getAnOtherElement(Element* element) { - // for (vector::iterator it = this->getElements()->begin(); it != this->getElements()->end(); it++) { - for (Element* it : *this->getElements()) { - if (it != element) { - return it; - } - } - return nullptr; -} diff --git a/Util/OSM2ODR/src/utils/traction_wire/Node.h b/Util/OSM2ODR/src/utils/traction_wire/Node.h deleted file mode 100644 index 14b659836..000000000 --- a/Util/OSM2ODR/src/utils/traction_wire/Node.h +++ /dev/null @@ -1,73 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file Node.h -/// @author Jakub Sevcik (RICE) -/// @author Jan Prikryl (RICE) -/// @date 2019-12-15 -/// -// Representation of electric circuit nodes, i.e. wire junctions and connection points. -/// @note based on work 2017 Ahmad Khaled, Ahmad Essam, Omnia Zakaria, Mary Nader -/****************************************************************************/ -#pragma once - -#include -#include - -using namespace std; - -class Element; - -class Node { - -private: - bool isground; - bool isremovable; - string name; // unique property, each object has distinctive and unique name - int id; // a sequential ID number, might be useful when making the equation - int num_matrixRow; // number of matrix row during solving the equations - int num_matrixCol; // number of matrix column during solving the equations - double voltage; - vector* elements; // too lazy to implement a linked list - // each node is connected to one or more element, an element is a resistor or voltage/current source - -public: - // A constructor, same functionality as "init" functions - Node(string name, int id); - - // connects an element to the node - void addElement(Element* element); - // disconnects an element to the node - void eraseElement(Element* element); - // getters and setters - double getVoltage(); - void setVoltage(double voltage); - int getNumOfElements(); - // iterates through the vector of the node's elements and returns the first, which is not equal to "element" in the argument of the function - Element* getAnOtherElement(Element* element); - string& getName(); - bool isGround(); - bool isRemovable() { - return isremovable; - }; - void setGround(bool isground); - int getId(); - void setNumMatrixRow(int num); - int getNumMatrixRow(); - void setNumMatrixCol(int num); - int getNumMatrixCol(); - void setId(int id); - vector* getElements(); - void setRemovability(bool isremovable); -}; - diff --git a/Util/OSM2ODR/src/utils/vehicle/SUMOTrafficObject.h b/Util/OSM2ODR/src/utils/vehicle/SUMOTrafficObject.h deleted file mode 100644 index 36a81e6d8..000000000 --- a/Util/OSM2ODR/src/utils/vehicle/SUMOTrafficObject.h +++ /dev/null @@ -1,155 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file SUMOTrafficObject.h -/// @author Jakob Erdmann -/// @date Mon, 25 Mar 2019 -/// -// Abstract base class for vehicle and person representations -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include -#include -#include - - -// =========================================================================== -// class declarations -// =========================================================================== -class MSVehicleType; -class MSEdge; -class MSLane; -class Position; - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class SUMOTrafficObject - * @brief Representation of a vehicle, person, or container - */ -class SUMOTrafficObject : public Named { -public: - - /// @brief Constructor - SUMOTrafficObject(const std::string& id) : Named(id) {} - - /// @brief Destructor - virtual ~SUMOTrafficObject() {} - - /** @brief Whether it is a vehicle - * @return true for vehicles, false otherwise - */ - virtual bool isVehicle() const { - return false; - } - - /** @brief Whether it is a person - * @return true for persons, false otherwise - */ - virtual bool isPerson() const { - return false; - } - - /** @brief Whether it is a container - * @return true for containers, false otherwise - */ - virtual bool isContainer() const { - return false; - } - - /** @brief Returns the object's "vehicle" type - * @return The vehicle's type - */ - virtual const MSVehicleType& getVehicleType() const = 0; - - /** @brief Returns whether the object is at a stop - * @return Whether it has stopped - */ - virtual bool isStopped() const = 0; - - /** @brief Returns the edge the object is currently at - * - * @return The current edge in the object's route - */ - virtual const MSEdge* getEdge() const = 0; - - /** @brief Returns the slope of the road at object's position - * @return The slope - */ - virtual double getSlope() const = 0; - - virtual double getChosenSpeedFactor() const = 0; - - /** @brief Returns the object's access class - * @return The object's access class - */ - virtual SUMOVehicleClass getVClass() const = 0; - - /** @brief Returns the object's maximum speed - * @return The object's maximum speed - */ - virtual double getMaxSpeed() const = 0; - - virtual SUMOTime getWaitingTime() const = 0; - - /** @brief Returns the object's current speed - * @return The object's speed - */ - virtual double getSpeed() const = 0; - - // This definition was introduced to make the MSVehicle's previousSpeed Refs. #2579 - /** @brief Returns the object's previous speed - * @return The object's previous speed - */ - virtual double getPreviousSpeed() const = 0; - - - /** @brief Returns the object's acceleration - * @return The acceleration - */ - virtual double getAcceleration() const = 0; - - /** @brief Get the object's position along the lane - * @return The position of the object (in m from the lane's begin) - */ - virtual double getPositionOnLane() const = 0; - - /** @brief Get the object's back position along the given lane - * @return The position of the object (in m from the given lane's begin) - */ - virtual double getBackPositionOnLane(const MSLane* lane) const = 0; - - - /** @brief Return current position (x/y, cartesian) - * - * If the object is not in the net, Position::INVALID. - * @param[in] offset optional offset in longitudinal direction - * @return The current position (in cartesian coordinates) - * @see myLane - */ - virtual Position getPosition(const double offset = 0) const = 0; - - /** @brief Returns the object's angle in degrees - */ - virtual double getAngle() const = 0; - - /** @brief Returns whether this object has arrived - */ - virtual bool hasArrived() const = 0; - -}; diff --git a/Util/OSM2ODR/src/utils/vehicle/SUMOVTypeParameter.h b/Util/OSM2ODR/src/utils/vehicle/SUMOVTypeParameter.h deleted file mode 100644 index 73f561860..000000000 --- a/Util/OSM2ODR/src/utils/vehicle/SUMOVTypeParameter.h +++ /dev/null @@ -1,383 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file SUMOVTypeParameter.h -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date 10.09.2009 -/// -// Structure representing possible vehicle parameter -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include -#include -#include -#include -#include - -// =========================================================================== -// class declarations -// =========================================================================== -class OutputDevice; -class OptionsCont; - - -// =========================================================================== -// value definitions -// =========================================================================== -const int VTYPEPARS_LENGTH_SET = 1; -const int VTYPEPARS_MINGAP_SET = 1 << 1; -const int VTYPEPARS_MAXSPEED_SET = 1 << 2; -const int VTYPEPARS_PROBABILITY_SET = 1 << 3; -const int VTYPEPARS_SPEEDFACTOR_SET = 1 << 4; -const int VTYPEPARS_EMISSIONCLASS_SET = 1 << 5; -const int VTYPEPARS_COLOR_SET = 1 << 6; -const int VTYPEPARS_VEHICLECLASS_SET = 1 << 7; -const int VTYPEPARS_WIDTH_SET = 1 << 8; -const int VTYPEPARS_HEIGHT_SET = 1 << 9; -const int VTYPEPARS_SHAPE_SET = 1 << 10; -const int VTYPEPARS_OSGFILE_SET = 1 << 11; -const int VTYPEPARS_IMGFILE_SET = 1 << 12; -const int VTYPEPARS_IMPATIENCE_SET = 1 << 13; -const int VTYPEPARS_LANE_CHANGE_MODEL_SET = 1 << 14; -const int VTYPEPARS_PERSON_CAPACITY = 1 << 15; -const int VTYPEPARS_BOARDING_DURATION = 1 << 16; -const int VTYPEPARS_CONTAINER_CAPACITY = 1 << 17; -const int VTYPEPARS_LOADING_DURATION = 1 << 18; -const int VTYPEPARS_CAR_FOLLOW_MODEL = 1 << 19; -const int VTYPEPARS_MAXSPEED_LAT_SET = 1 << 20; -const int VTYPEPARS_LATALIGNMENT_SET = 1 << 21; -const int VTYPEPARS_MINGAP_LAT_SET = 1 << 22; -const int VTYPEPARS_ACTIONSTEPLENGTH_SET = 1 << 23; - -const int VTYPEPARS_CARRIAGE_LENGTH_SET = 1 << 25; -const int VTYPEPARS_LOCOMOTIVE_LENGTH_SET = 1 << 26; -const int VTYPEPARS_CARRIAGE_GAP_SET = 1 << 27; -const int VTYPEPARS_MANEUVER_ANGLE_TIMES_SET = 1 << 28; - - -const int VTYPEPARS_DEFAULT_EMERGENCYDECEL_DEFAULT = -1; -const int VTYPEPARS_DEFAULT_EMERGENCYDECEL_DECEL = -2; - -// =========================================================================== -// struct definitions -// =========================================================================== -/** - * @class SUMOVTypeParameter - * @brief Structure representing possible vehicle parameter - */ -class SUMOVTypeParameter : public Parameterised { -public: - /// @brief struct for default values that depend of VClass - struct VClassDefaultValues { - /// @brief parameter constructor - VClassDefaultValues(SUMOVehicleClass vClass); - - /// @brief The physical vehicle length - double length; - - /// @brief This class' free space in front of the vehicle itself - double minGap; - - /// @brief The vehicle type's maximum speed [m/s] - double maxSpeed; - - /// @brief This class' width - double width; - - /// @brief This class' height - double height; - - /// @brief This class' shape - SUMOVehicleShape shape; - - /// @brief The emission class of this vehicle - SUMOEmissionClass emissionClass; - - /// @brief The factor by which the maximum speed may deviate from the allowed max speed on the street - Distribution_Parameterized speedFactor; - - /// @brief The person capacity of the vehicle - int personCapacity; - - /// @brief The container capacity of the vehicle - int containerCapacity; - - /// @brief 3D model file for this class - std::string osgFile; - - /// @brief the length of train carriages - double carriageLength; - - /// @brief the length of train locomotive - double locomotiveLength; - - private: - /// @brief default constructor - VClassDefaultValues(); - }; - - /** @brief Constructor - * - * Initialises the structure with default values - */ - SUMOVTypeParameter(const std::string& vtid, const SUMOVehicleClass vc = SVC_IGNORING); - - /// @brief virtual destructor - virtual ~SUMOVTypeParameter() {}; - - /** @brief Returns whether the given parameter was set - * @param[in] what The parameter which one asks for - * @return Whether the given parameter was set - */ - bool wasSet(int what) const { - return (parametersSet & what) != 0; - } - - /** @brief Writes the vtype - * - * @param[in, out] dev The device to write into - * @exception IOError not yet implemented - */ - void write(OutputDevice& dev) const; - - /** @brief Returns the named value from the map, or the default if it is not contained there - * @param[in] attr The corresponding xml attribute - * @param[in] defaultValue The value to return if the given map does not contain the named variable - * @return The named value from the map or the default if it does not exist there - */ - double getCFParam(const SumoXMLAttr attr, const double defaultValue) const; - - /** @brief Returns the named value from the map, or the default if it is not contained there - * @param[in] attr The corresponding xml attribute - * @param[in] defaultValue The value to return if the given map does not contain the named variable - * @return The named value from the map or the default if it does not exist there - */ - std::string getCFParamString(const SumoXMLAttr attr, const std::string defaultValue) const; - - /** @brief Returns the named value from the map, or the default if it is not contained there - * @param[in] attr The corresponding xml attribute - * @param[in] defaultValue The value to return if the given map does not contain the named variable - * @return The named value from the map or the default if it does not exist there - */ - double getLCParam(const SumoXMLAttr attr, const double defaultValue) const; - - /** @brief Returns the named value from the map, or the default if it is not contained there - * @param[in] attr The corresponding xml attribute - * @param[in] defaultValue The value to return if the given map does not contain the named variable - * @return The named value from the map or the default if it does not exist there - */ - std::string getLCParamString(const SumoXMLAttr attr, const std::string& defaultValue) const; - - /// @brief sub-model parameters - typedef std::map SubParams; - - /// @brief Returns the LC parameter - const SubParams& getLCParams() const; - - /** @brief Returns the named value from the map, or the default if it is not contained there - * @param[in] attr The corresponding xml attribute - * @param[in] defaultValue The value to return if the given map does not contain the named variable - * @return The named value from the map or the default if it does not exist there - */ - double getJMParam(const SumoXMLAttr attr, const double defaultValue) const; - - /** @brief Returns the named value from the map, or the default if it is not contained there - * @param[in] attr The corresponding xml attribute - * @param[in] defaultValue The value to return if the given map does not contain the named variable - * @return The named value from the map or the default if it does not exist there - */ - std::string getJMParamString(const SumoXMLAttr attr, const std::string defaultValue) const; - - void cacheParamRestrictions(const std::vector& restrictionKeys); - - /// @brief The vehicle type's id - std::string id; - - /// @brief The physical vehicle length - double length; - - /// @brief This class' free space in front of the vehicle itself - double minGap; - - /// @brief The vehicle type's maximum speed [m/s] - double maxSpeed; - - /// @brief The vehicle type's default actionStepLength [ms], i.e. the interval between two control actions. - /// The default value of 0ms. induces the value to be traced from MSGlobals::gActionStepLength - SUMOTime actionStepLength; - - /// @brief The probability when being added to a distribution without an explicit probability - double defaultProbability; - - /// @brief The factor by which the maximum speed may deviate from the allowed max speed on the street - Distribution_Parameterized speedFactor; - - /// @brief The emission class of this vehicle - SUMOEmissionClass emissionClass; - - /// @brief The color - RGBColor color; - - /// @brief The vehicle's class - SUMOVehicleClass vehicleClass; - - /// @brief The vehicle's impatience (willingness to obstruct others) - double impatience; - - /// @brief The person capacity of the vehicle - int personCapacity; - - /// @brief The container capacity of the vehicle - int containerCapacity; - - /// @brief The time a person needs to board the vehicle - SUMOTime boardingDuration; - - /// @brief The time a container needs to get loaded on the vehicle - SUMOTime loadingDuration; - - /// @name Values for drawing this class' vehicles - /// @{ - - /// @brief This class' width - double width; - - /// @brief This class' height - double height; - - /// @brief This class' shape - SUMOVehicleShape shape; - - /// @brief 3D model file for this class - std::string osgFile; - - /// @brief Image file for this class - std::string imgFile; - /// @} - - - /// @brief The enum-representation of the car-following model to use - SumoXMLTag cfModel; - - /// @brief Car-following parameter - SubParams cfParameter; - - /// @brief Lane-changing parameter - SubParams lcParameter; - - /// @brief Junction-model parameter - SubParams jmParameter; - - /// @brief The lane-change model to use - LaneChangeModel lcModel; - - /// @brief The vehicle type's maximum lateral speed [m/s] - double maxSpeedLat; - - /// @brief The vehicles desired lateral alignment - LateralAlignment latAlignment; - - /// @brief The vehicle type's minimum lateral gap [m] - double minGapLat; - - /// @brief the length of train carriages and locomotive - double carriageLength; - double locomotiveLength; - double carriageGap; - - /// @brief Information for the router which parameter were set - int parametersSet; - - /// @brief Information whether this type was already saved (needed by routers) - mutable bool saved; - - /// @brief Information whether this is a type-stub, being only referenced but not defined (needed by routers) - bool onlyReferenced; - - /// @brief cached value of parameters which may restrict access to certain edges - std::vector paramRestrictions; - - /// @brief satisfy vType / router template requirements - inline double getLength() const { - return length; - } - - /** @brief Returns the default acceleration for the given vehicle class - * This needs to be a function because the actual value is stored in the car following model - * @param[in] vc the vehicle class - * @return the acceleration in m/s^2 - */ - static double getDefaultAccel(const SUMOVehicleClass vc = SVC_IGNORING); - - /** @brief Returns the default deceleration for the given vehicle class - * This needs to be a function because the actual value is stored in the car following model - * @param[in] vc the vehicle class - * @return the deceleration in m/s^2 - */ - static double getDefaultDecel(const SUMOVehicleClass vc = SVC_IGNORING); - - /** @brief Returns the default emergency deceleration for the given vehicle class - * This needs to be a function because the actual value is stored in the car following model - * @param[in] vc the vehicle class - * @param[in] decel the deceleration of the vehicle type - * @return the emergency deceleration in m/s^2 - */ - static double getDefaultEmergencyDecel(const SUMOVehicleClass vc, double decel, double defaultOption); - - /** @brief Returns the default driver's imperfection (sigma or epsilon in Krauss' model) for the given vehicle class - * This needs to be a function because the actual value is stored in the car following model - * @param[in] vc the vehicle class - * @return the imperfection as a value between 0 and 1 - */ - static double getDefaultImperfection(const SUMOVehicleClass vc = SVC_IGNORING); - - /// @brief return the default parameters, this is a function due to the http://www.parashift.com/c++-faq/static-init-order.html - static const SUMOVTypeParameter& getDefault(); - - /// @brief Map of manoeuver angles versus the times (entry, exit) to execute the manoeuver - std::map> myManoeuverAngleTimes; - - /** @brief Initialise the default mapping between manoeuver angle and times dependant on vehicle class - * @param[in] vclass The vehicle class - * @note These default values were 'informed' by a paper by Purnawan, and Yousif: - * @note usir.salford.ac.uk/id/eprint/9729/3/Paper_Kassel_%28Seminar%29.pdf (no reverse park values in paper) - * @note truck values were simply doubled - all are modifiable in the vehicle type definition and there is no limit to the no of triplets - * TODO: - * optionality for 90 degree bay entry (forwards or reverse) not implemented - probably should be a driver propensity - * the defaults assume reverse entry - a reverse manoeuvre has to happen and there will be a small difference in timings depending whether its reverse in or out - */ - void setManoeuverAngleTimes(const SUMOVehicleClass vclass); - - /** @brief Returns the time that will be needed for the vehicle type to execute the (entry) manoeuvre (and be blocking the lane) - * @param[in] angle The angle, in degrees through which the vehicle needs to manoeuver (0-180 degrees) - * @return The SUMOTime value - */ - SUMOTime getEntryManoeuvreTime(const int angle) const; - - /** @brief Returns the time that will be needed for the vehicle type to execute the (exit) manoeuvre (and be blocking the lane) - * @param[in] angle The angle, in degrees through which the vehicle needs to manoeuver (0-180 degrees) - * @return The SUMOTime value - */ - SUMOTime getExitManoeuvreTime(const int angle) const; - - /** @brief Returns myManoeuverAngleTimes as a string for xml output - * @return A string of , separated triplets (angle entry-time exit-time) - */ - std::string getManoeuverAngleTimesS() const; -}; diff --git a/Util/OSM2ODR/src/utils/vehicle/SUMOVehicle.h b/Util/OSM2ODR/src/utils/vehicle/SUMOVehicle.h deleted file mode 100644 index 852369428..000000000 --- a/Util/OSM2ODR/src/utils/vehicle/SUMOVehicle.h +++ /dev/null @@ -1,361 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file SUMOVehicle.h -/// @author Michael Behrisch -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @date Tue, 17 Feb 2009 -/// -// Abstract base class for vehicle representations -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include -#include -#include -#include -#include -#include - - -// =========================================================================== -// class declarations -// =========================================================================== -class MSRoute; -class MSEdge; -class MSLane; -class MSPerson; -class MSTransportable; -class MSParkingArea; -class MSStoppingPlace; -class MSVehicleDevice; -class SUMOSAXAttributes; - -typedef std::vector ConstMSEdgeVector; - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class SUMOVehicle - * @brief Representation of a vehicle - */ -class SUMOVehicle : public SUMOTrafficObject { -public: - typedef long long int NumericalID; - - /// @brief Constructor - SUMOVehicle(const std::string& id) : SUMOTrafficObject(id) {} - - /// @brief Destructor - virtual ~SUMOVehicle() {} - - /** @brief Get the vehicle's lateral position on the lane - * @return The lateral position of the vehicle (in m relative to the - * centerline of the lane) - */ - virtual double getLateralPositionOnLane() const = 0; - - /** @brief Get the vehicle's angle - * @return The angle of the vehicle (in degree) - */ - virtual double getAngle() const = 0; - - /** @brief Returns the lane the vehicle is on - * @return The vehicle's current lane - */ - virtual MSLane* getLane() const = 0; - - - /// Returns the current route - virtual const MSRoute& getRoute() const = 0; - - /// @brief return index of edge within route - virtual int getRoutePosition() const = 0; - - /** @brief Returns the nSuccs'th successor of edge the vehicle is currently at - * - * If the rest of the route (counted from the current edge) than nSuccs, - * 0 is returned. - * @param[in] nSuccs The number of edge to look forward - * @return The nSuccs'th following edge in the vehicle's route - */ - virtual const MSEdge* succEdge(int nSuccs) const = 0; - - /** @brief Replaces the current route by the given edges - * - * It is possible that the new route is not accepted, if a) it does not - * contain the vehicle's current edge, or b) something fails on insertion - * into the routes container (see in-line comments). - * - * @param[in] edges The new list of edges to pass - * @param[in] onInit Whether the vehicle starts with this route - * @param[in] check Whether the route should be checked for validity - * @param[in] removeStops Whether stops should be removed if they do not fit onto the new route - * @return Whether the new route was accepted - */ - virtual bool replaceRouteEdges(ConstMSEdgeVector& edges, double cost, double savings, const std::string& info, bool onInit = false, bool check = false, bool removeStops = true) = 0; - - /// Replaces the current route by the given one - virtual bool replaceRoute(const MSRoute* route, const std::string& info, bool onInit = false, int offset = 0, bool addStops = true, bool removeStops = true) = 0; - - /** @brief Performs a rerouting using the given router - * - * Tries to find a new route between the current edge and the destination edge, first. - * Tries to replace the current route by the new one using replaceRoute. - * - * @param[in] t The time for which the route is computed - * @param[in] router The router to use - * @see replaceRoute - */ - virtual void reroute(SUMOTime t, const std::string& info, SUMOAbstractRouter& router, const bool onInit = false, const bool withTaz = false, const bool silent = false) = 0; - - /** @brief Validates the current or given route - * @param[out] msg Description why the route is not valid (if it is the case) - * @param[in] route The route to check (or 0 if the current route shall be checked) - * @return Whether the vehicle's current route is valid - */ - virtual bool hasValidRoute(std::string& msg, const MSRoute* route = 0) const = 0; - /// @brief checks wether the vehicle can depart on the first edge - virtual bool hasValidRouteStart(std::string& msg) = 0; - - /// @brief computes validity attributes for the current route - virtual int getRouteValidity(bool update = true, bool silent = false) = 0; - - /** @brief Returns an iterator pointing to the current edge in this vehicles route - * @return The current route pointer - */ - virtual const ConstMSEdgeVector::const_iterator& getCurrentRouteEdge() const = 0; - - /** @brief Returns the vehicle's parameter (including departure definition) - * - * @return The vehicle's parameter - */ - virtual const SUMOVehicleParameter& getParameter() const = 0; - - /** @brief Returns the vehicle's emission model parameter - * - * @return The vehicle's emission parameters - */ - virtual const std::map* getEmissionParameters() const = 0; - - /** @brief Replaces the vehicle's parameter - */ - virtual void replaceParameter(const SUMOVehicleParameter* newParameter) = 0; - - /** @brief Called when the vehicle is inserted into the network - * - * Sets optional information about departure time, informs the vehicle - * control about a further running vehicle. - */ - virtual void onDepart() = 0; - - /** @brief Returns the information whether the vehicle is on a road (is simulated) - * @return Whether the vehicle is simulated - */ - virtual bool isOnRoad() const = 0; - - /** @brief Returns whether the vehicle is idling (waiting to re-enter the net - * @return true if the vehicle is waiting to enter the net (eg after parking) - */ - virtual bool isIdling() const = 0; - - /** @brief Returns the information whether the front of the vehhicle is on the given lane - * @return Whether the vehicle's front is on that lane - */ - virtual bool isFrontOnLane(const MSLane*) const = 0; - - /** @brief Returns the information whether the vehicle is parked - * @return Whether the vehicle is parked - */ - virtual bool isParking() const = 0; - - /** @brief Returns the information whether the vehicle is fully controlled - * via TraCI - * @return Whether the vehicle is remote-controlled - */ - virtual bool isRemoteControlled() const = 0; - - /** @brief Returns the information whether the vehicle is fully controlled - * via TraCI - * @return Whether the vehicle was remote-controlled within the given time range - */ - virtual bool wasRemoteControlled(SUMOTime lookBack = DELTA_T) const = 0; - - /** @brief Returns this vehicle's real departure time - * @return This vehicle's real departure time - */ - virtual SUMOTime getDeparture() const = 0; - - /** @brief Returns this vehicle's real departure position - * @return This vehicle's real departure position - */ - virtual double getDepartPos() const = 0; - - /** @brief Returns this vehicle's desired arrivalPos for its current route - * (may change on reroute) - * @return This vehicle's real arrivalPos - */ - virtual double getArrivalPos() const = 0; - - /** @brief Sets this vehicle's desired arrivalPos for its current route - */ - virtual void setArrivalPos(double arrivalPos) = 0; - - /** @brief Returns whether this vehicle has departed - */ - virtual bool hasDeparted() const = 0; - - /** @brief Returns the number of new routes this vehicle got - * @return the number of new routes this vehicle got - */ - virtual int getNumberReroutes() const = 0; - - /// @brief whether the given transportable is allowed to board this vehicle - virtual bool allowsBoarding(MSTransportable* t) const = 0; - - /** @brief Adds a person or container to this vehicle - * - * @param[in] transportable The person/container to add - */ - virtual void addTransportable(MSTransportable* transportable) = 0; - - /** @brief Returns the number of persons - * @return The number of passengers on-board - */ - virtual int getPersonNumber() const = 0; - - /** @brief Returns the list of persons - * @return The list of passengers on-board - */ - virtual std::vector getPersonIDList() const = 0; - - /** @brief Returns the number of containers - * @return The number of contaiers on-board - */ - virtual int getContainerNumber() const = 0; - - /// @brief removes a person or container - virtual void removeTransportable(MSTransportable* t) = 0; - - /// @brief retrieve riding persons - virtual const std::vector& getPersons() const = 0; - - /// @brief retrieve riding containers - virtual const std::vector& getContainers() const = 0; - - /** @brief Adds a stop - * - * The stop is put into the sorted list. - * @param[in] stop The stop to add - * @return Whether the stop could be added - */ - virtual bool addStop(const SUMOVehicleParameter::Stop& stopPar, std::string& errorMsg, SUMOTime untilOffset = 0, bool collision = false, - ConstMSEdgeVector::const_iterator* searchStart = 0) = 0; - - /// @brief return list of route indices and stop positions for the remaining stops - virtual std::vector > getStopIndices() const = 0; - - /// @brief returns whether the vehicle serves a public transport line that serves the given stop - virtual bool isLineStop(double position) const = 0; - - - /** - * returns the next imminent stop in the stop queue - * @return the upcoming stop - */ - virtual MSParkingArea* getNextParkingArea() = 0; - - /** @brief Replaces a stop - * - * The stop replace the next stop into the sorted list. - * @param[in] stop The stop to add - * @return Whether the stop could be added - */ - virtual bool replaceParkingArea(MSParkingArea* parkingArea, std::string& errorMsg) = 0; - - /// @brief Returns the remaining stop duration for a stopped vehicle or 0 - virtual SUMOTime remainingStopDuration() const = 0; - - /** @brief Returns whether the vehicle is at a stop and waiting for a person or container to continue - */ - virtual bool isStoppedTriggered() const = 0; - - /** @brief Returns whether the vehicle is stopped in the range of the given position */ - virtual bool isStoppedInRange(const double pos, const double tolerance) const = 0; - - /** @brief Returns whether the vehicle stops at the given stopping place */ - virtual bool stopsAt(MSStoppingPlace* stop) const = 0; - - /** @brief Returns whether the vehicle stops at the given edge */ - virtual bool stopsAtEdge(const MSEdge* edge) const = 0; - - /** @brief Returns parameters of the next stop or nullptr **/ - virtual const SUMOVehicleParameter::Stop* getNextStopParameter() const = 0; - - virtual void setChosenSpeedFactor(const double factor) = 0; - - virtual SUMOTime getAccumulatedWaitingTime() const = 0; - - virtual SUMOTime getDepartDelay() const = 0; - - virtual SUMOTime getTimeLoss() const = 0; - - /// @brief get distance for coming to a stop (used for rerouting checks) - virtual double getBrakeGap() const = 0; - - /// @brief Returns this vehicles impatience - virtual double getImpatience() const = 0; - - /** @brief Returns this vehicle's devices - * @return This vehicle's devices - */ - virtual const std::vector& getDevices() const = 0; - - /// @brief Returns a device of the given type if it exists or 0 - virtual MSVehicleDevice* getDevice(const std::type_info& type) const = 0; - - /// @brief whether this vehicle is selected in the GUI - virtual bool isSelected() const = 0; - - /// @brief @return The index of the vehicle's associated RNG - virtual int getRNGIndex() const = 0; - - /** @brief Returns the associated RNG for this vehicle - * @return The vehicle's associated RNG - */ - virtual std::mt19937* getRNG() const = 0; - - /// @brief return the numerical ID which is only for internal usage - // (especially fast comparison in maps which need vehicles as keys) - virtual NumericalID getNumericalID() const = 0; - - /// @brief Returns the vehicles's length - virtual double getLength() const = 0; - - /// @name state io - //@{ - - /// Saves the states of a vehicle - virtual void saveState(OutputDevice& out) = 0; - - /** @brief Loads the state of this vehicle from the given description - */ - virtual void loadState(const SUMOSAXAttributes& attrs, const SUMOTime offset) = 0; - //@} -}; diff --git a/Util/OSM2ODR/src/utils/vehicle/SUMOVehicleParameter.h b/Util/OSM2ODR/src/utils/vehicle/SUMOVehicleParameter.h deleted file mode 100644 index bf239fb64..000000000 --- a/Util/OSM2ODR/src/utils/vehicle/SUMOVehicleParameter.h +++ /dev/null @@ -1,713 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file SUMOVehicleParameter.h -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Axel Wegener -/// @author Michael Behrisch -/// @date 2006-01-24 -/// -// Structure representing possible vehicle parameter -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include -#include -#include - - -// =========================================================================== -// class declarations -// =========================================================================== -class OutputDevice; -class OptionsCont; - - -// =========================================================================== -// value definitions -// =========================================================================== -const int VEHPARS_COLOR_SET = 1; -const int VEHPARS_VTYPE_SET = 2; -const int VEHPARS_DEPARTLANE_SET = 2 << 1; -const int VEHPARS_DEPARTPOS_SET = 2 << 2; -const int VEHPARS_DEPARTSPEED_SET = 2 << 3; -const int VEHPARS_END_SET = 2 << 4; -const int VEHPARS_NUMBER_SET = 2 << 5; -const int VEHPARS_PERIOD_SET = 2 << 6; -const int VEHPARS_VPH_SET = 2 << 7; -const int VEHPARS_PROB_SET = 2 << 8; -const int VEHPARS_ROUTE_SET = 2 << 9; -const int VEHPARS_ARRIVALLANE_SET = 2 << 10; -const int VEHPARS_ARRIVALPOS_SET = 2 << 11; -const int VEHPARS_ARRIVALSPEED_SET = 2 << 12; -const int VEHPARS_LINE_SET = 2 << 13; -const int VEHPARS_FROM_TAZ_SET = 2 << 14; -const int VEHPARS_TO_TAZ_SET = 2 << 15; -const int VEHPARS_FORCE_REROUTE = 2 << 16; -const int VEHPARS_PERSON_CAPACITY_SET = 2 << 17; -const int VEHPARS_PERSON_NUMBER_SET = 2 << 18; -const int VEHPARS_CONTAINER_NUMBER_SET = 2 << 19; -const int VEHPARS_DEPARTPOSLAT_SET = 2 << 20; -const int VEHPARS_ARRIVALPOSLAT_SET = 2 << 21; -const int VEHPARS_VIA_SET = 2 << 22; -const int VEHPARS_SPEEDFACTOR_SET = 2 << 23; - -const int STOP_INDEX_END = -1; -const int STOP_INDEX_FIT = -2; - -const int STOP_START_SET = 1; -const int STOP_END_SET = 2; -const int STOP_DURATION_SET = 2 << 1; -const int STOP_UNTIL_SET = 2 << 2; -const int STOP_EXTENSION_SET = 2 << 3; -const int STOP_TRIGGER_SET = 2 << 4; -const int STOP_PARKING_SET = 2 << 5; -const int STOP_EXPECTED_SET = 2 << 6; -const int STOP_CONTAINER_TRIGGER_SET = 2 << 7; -const int STOP_EXPECTED_CONTAINERS_SET = 2 << 8; -const int STOP_TRIP_ID_SET = 2 << 9; -const int STOP_LINE_SET = 2 << 10; -const int STOP_SPEED_SET = 2 << 11; -const int STOP_SPLIT_SET = 2 << 12; -const int STOP_JOIN_SET = 2 << 13; -const int STOP_ARRIVAL_SET = 2 << 14; - -const double MIN_STOP_LENGTH = 2 * POSITION_EPS; - - -// =========================================================================== -// enum definitions -// =========================================================================== -/** - * @enum DepartDefinition - * @brief Possible ways to depart - */ -enum DepartDefinition { - /// @brief The time is given - DEPART_GIVEN, - /// @brief The departure is person triggered - DEPART_TRIGGERED, - /// @brief The departure is container triggered - DEPART_CONTAINER_TRIGGERED, - /// @brief The vehicle is discarded if emission fails (not fully implemented yet) - DEPART_NOW, - /// @brief The departure is triggered by a train split - DEPART_SPLIT, - /// @brief Tag for the last element in the enum for safe int casting - DEPART_DEF_MAX -}; - - -/** - * @enum DepartLaneDefinition - * @brief Possible ways to choose a lane on depart - */ -enum class DepartLaneDefinition { - /// @brief No information given; use default - DEFAULT, - /// @brief The lane is given - GIVEN, - /// @brief The lane is chosen randomly - RANDOM, - /// @brief The least occupied lane is used - FREE, - /// @brief The least occupied lane from lanes which allow the continuation - ALLOWED_FREE, - /// @brief The least occupied lane from best lanes - BEST_FREE, - /// @brief The rightmost lane the vehicle may use - FIRST_ALLOWED -}; - - -/** - * @enum DepartPosDefinition - * @brief Possible ways to choose the departure position - */ -enum class DepartPosDefinition { - /// @brief No information given; use default - DEFAULT, - /// @brief The position is given - GIVEN, - /// @brief The position is chosen randomly - RANDOM, - /// @brief A free position is chosen - FREE, - /// @brief Back-at-zero position - BASE, - /// @brief Insert behind the last vehicle as close as possible to still allow the specified departSpeed. Fallback to DepartPosDefinition::BASE if there is no vehicle on the departLane yet. - LAST, - /// @brief If a fixed number of random choices fails, a free position is chosen - RANDOM_FREE, - /// @brief depart position is endPos of first stop - STOP -}; - - -/** - * @enum DepartPosDefinition - * @brief Possible ways to choose the departure position - */ -enum class DepartPosLatDefinition { - /// @brief No information given; use default - DEFAULT, - /// @brief The position is given - GIVEN, - /// @brief At the rightmost side of the lane - RIGHT, - /// @brief At the center of the lane - CENTER, - /// @brief At the leftmost side of the lane - LEFT, - /// @brief The lateral position is chosen randomly - RANDOM, - /// @brief A free lateral position is chosen - FREE, - /// @brief If a fixed number of random choices fails, a free lateral position is chosen - RANDOM_FREE -}; - - -/** - * @enum DepartSpeedDefinition - * @brief Possible ways to choose the departure speed - */ -enum class DepartSpeedDefinition { - /// @brief No information given; use default - DEFAULT, - /// @brief The speed is given - GIVEN, - /// @brief The speed is chosen randomly - RANDOM, - /// @brief The maximum safe speed is used - MAX, - /// @brief The maximum lane speed is used (speedLimit * speedFactor) - DESIRED, - /// @brief The maximum lane speed is used (speedLimit) - LIMIT -}; - - -/** - * @enum ArrivalLaneDefinition - * @brief Possible ways to choose the arrival lane - */ -enum class ArrivalLaneDefinition { - /// @brief No information given; use default - DEFAULT, - /// @brief The arrival lane is given - GIVEN, - /// @brief The current lane shall be used - CURRENT -}; - - -/** - * @enum ArrivalPosDefinition - * @brief Possible ways to choose the arrival position - */ -enum class ArrivalPosDefinition { - /// @brief No information given; use default - DEFAULT, - /// @brief The arrival position is given - GIVEN, - /// @brief The arrival position is chosen randomly - RANDOM, - /// @brief Half the road length - CENTER, - /// @brief The maximum arrival position is used - MAX -}; - - -/** - * @enum ArrivalPosLatDefinition - * @brief Possible ways to choose the departure position - */ -enum class ArrivalPosLatDefinition { - /// @brief No information given; use default - DEFAULT, - /// @brief The position is given - GIVEN, - /// @brief At the rightmost side of the lane - RIGHT, - /// @brief At the center of the lane - CENTER, - /// @brief At the leftmost side of the lane - LEFT -}; - - -/** - * @enum ArrivalSpeedDefinition - * @brief Possible ways to choose the arrival speed - */ -enum class ArrivalSpeedDefinition { - /// @brief No information given; use default - DEFAULT, - /// @brief The speed is given - GIVEN, - /// @brief The current speed is used - CURRENT -}; - - -// =========================================================================== -// struct definitions -// =========================================================================== -/** - * @class SUMOVehicleParameter - * @brief Structure representing possible vehicle parameter - * - * When used within a vehicle, parameter are usually const except for selected items - * adaptable via TraCI which are flagged as mutable below - * The fields yielding with "Procedure" describe whether the according value - * shall be used or another procedure is used to choose the value. - * @see DepartLaneDefinition - * @see DepartPosDefinition - * @see DepartSpeedDefinition - */ -class SUMOVehicleParameter : public Parameterised { -public: - /** @brief Constructor - * - * Initialises the structure with default values - */ - SUMOVehicleParameter(); - - /// @brief Destructor - virtual ~SUMOVehicleParameter(); - - /** @struct Stop - * @brief Definition of vehicle stop (position and duration) - */ - class Stop : public Parameterised { - - public: - /// @brief constructor - Stop(); - - /** @brief Writes the stop as XML - * - * @param[in, out] dev The device to write into - * @exception IOError not yet implemented - */ - void write(OutputDevice& dev, bool close = true) const; - - /// @brief write trigger attribute - void writeTriggers(OutputDevice& dev) const; - - /// @brief The edge to stop at (used only in NETEDIT) - std::string edge; - - /// @brief The lane to stop at - std::string lane; - - /// @brief (Optional) bus stop if one is assigned to the stop - std::string busstop; - - /// @brief (Optional) container stop if one is assigned to the stop - std::string containerstop; - - /// @brief (Optional) parking area if one is assigned to the stop - std::string parkingarea; - - /// @brief (Optional) charging station if one is assigned to the stop - std::string chargingStation; - - /// @brief (Optional) overhead line segment if one is assigned to the stop - std::string overheadWireSegment; - - /// @brief The stopping position start - double startPos; - - /// @brief The stopping position end - double endPos; - - /// @brief The (expected) time at which the vehicle reaches the stop - SUMOTime arrival; - - /// @brief The stopping duration - SUMOTime duration; - - /// @brief The time at which the vehicle may continue its journey - SUMOTime until; - - /// @brief The maximum time extension for boarding / loading - SUMOTime extension; - - /// @brief whether an arriving person lets the vehicle continue - bool triggered; - - /// @brief whether an arriving container lets the vehicle continue - bool containerTriggered; - - /// @brief whether an joined vehicle lets this vehicle continue - bool joinTriggered; - - /// @brief whether the vehicle is removed from the net while stopping - bool parking; - - /// @brief IDs of persons the vehicle has to wait for until departing - std::set awaitedPersons; - - /// @brief IDs of containers the vehicle has to wait for until departing - std::set awaitedContainers; - - /// @brief enable or disable friendly position (used by NETEDIT) - bool friendlyPos; - - /// @brief act Type (only used by Persons) (used by NETEDIT) - std::string actType; - - /// @brief id of the trip within a cyclical public transport route - std::string tripId; - - /// @brief the new line id of the trip within a cyclical public transport route - std::string line; - - /// @brief the id of the vehicle (train portion) that splits of upon reaching this stop - std::string split; - - /// @brief the id of the vehicle (train portion) to which this vehicle shall be joined - std::string join; - - /// @brief the speed at which this stop counts as reached (waypoint mode) - double speed; - - /// @brief lanes and positions connected to this stop (only used by duarouter where Stop is used to store stopping places) - std::vector > accessPos; - - /// @brief at which position in the stops list - int index; - - /// @brief Information for the output which parameter were set - int parametersSet = 0; - - }; - - - /** @brief Returns whether the given parameter was set - * @param[in] what The parameter which one asks for - * @return Whether the given parameter was set - */ - bool wasSet(int what) const { - return (parametersSet & what) != 0; - } - - /** @brief Writes the parameters as a beginning element - * - * @param[in, out] dev The device to write into - * @param[in] oc The options to get defaults from - * @param[in] tag The "root" tag to write (defaults to vehicle) - * @param[in] tag The typeID to write (defaults to member vtypeid) - * @exception IOError not yet implemented - */ - void write(OutputDevice& dev, const OptionsCont& oc, const SumoXMLTag tag = SUMO_TAG_VEHICLE, const std::string& typeID = "") const; - - /** @brief Returns whether the defaults shall be used - * @param[in] oc The options to get the options from - * @param[in] optionName The name of the option to determine whether its value shall be used - * @return Whether the option is set and --defaults-override was set - */ - bool defaultOptionOverrides(const OptionsCont& oc, const std::string& optionName) const; - - /// @name Depart/arrival-attributes verification - /// @{ - /** @brief Validates a given depart value - * @param[in] val The depart value to parse - * @param[in] element The name of the type of the parsed element, for building the error message - * @param[in] id The id of the parsed element, for building the error message - * @param[out] depart The parsed depart time, if given - * @param[out] dd The parsed departProcedure definition - * @param[out] error Error message, if an error occures - * @return Whether the given value is a valid depart definition - */ - static bool parseDepart(const std::string& val, const std::string& element, const std::string& id, - SUMOTime& depart, DepartDefinition& dd, std::string& error); - - /** @brief Validates a given departLane value - * @param[in] val The departLane value to parse - * @param[in] element The name of the type of the parsed element, for building the error message - * @param[in] id The id of the parsed element, for building the error message - * @param[out] lane The parsed lane, if given - * @param[out] dld The parsed departLane definition - * @param[out] error Error message, if an error occures - * @return Whether the given value is a valid departLane definition - */ - static bool parseDepartLane(const std::string& val, const std::string& element, const std::string& id, - int& lane, DepartLaneDefinition& dld, std::string& error); - - /** @brief Validates a given departPos value - * @param[in] val The departPos value to parse - * @param[in] element The name of the type of the parsed element, for building the error message - * @param[in] id The id of the parsed element, for building the error message - * @param[out] pos The parsed position, if given - * @param[out] dpd The parsed departPos definition - * @param[out] error Error message, if an error occures - * @return Whether the given value is a valid departPos definition - */ - static bool parseDepartPos(const std::string& val, const std::string& element, const std::string& id, - double& pos, DepartPosDefinition& dpd, std::string& error); - - /** @brief Validates a given departPosLat value - * @param[in] val The departPosLat value to parse - * @param[in] element The name of the type of the parsed element, for building the error message - * @param[in] id The id of the parsed element, for building the error message - * @param[out] pos The parsed position, if given - * @param[out] dpd The parsed departPos definition - * @param[out] error Error message, if an error occures - * @return Whether the given value is a valid departPos definition - */ - static bool parseDepartPosLat(const std::string& val, const std::string& element, const std::string& id, - double& pos, DepartPosLatDefinition& dpd, std::string& error); - - /** @brief Validates a given departSpeed value - * @param[in] val The departSpeed value to parse - * @param[in] element The name of the type of the parsed element, for building the error message - * @param[in] id The id of the parsed element, for building the error message - * @param[out] speed The parsed speed, if given - * @param[out] dsd The parsed departSpeed definition - * @param[out] error Error message, if an error occures - * @return Whether the given value is a valid departSpeed definition - */ - static bool parseDepartSpeed(const std::string& val, const std::string& element, const std::string& id, - double& speed, DepartSpeedDefinition& dsd, std::string& error); - - /** @brief Validates a given arrivalLane value - * @param[in] val The arrivalLane value to parse - * @param[in] element The name of the type of the parsed element, for building the error message - * @param[in] id The id of the parsed element, for building the error message - * @param[out] lane The parsed lane, if given - * @param[out] ald The parsed arrivalLane definition - * @param[out] error Error message, if an error occures - * @return Whether the given value is a valid arrivalLane definition - */ - static bool parseArrivalLane(const std::string& val, const std::string& element, const std::string& id, - int& lane, ArrivalLaneDefinition& ald, std::string& error); - - /** @brief Validates a given arrivalPos value - * @param[in] val The arrivalPos value to parse - * @param[in] element The name of the type of the parsed element, for building the error message - * @param[in] id The id of the parsed element, for building the error message - * @param[out] pos The parsed position, if given - * @param[out] apd The parsed arrivalPos definition - * @param[out] error Error message, if an error occures - * @return Whether the given value is a valid arrivalPos definition - */ - static bool parseArrivalPos(const std::string& val, const std::string& element, const std::string& id, - double& pos, ArrivalPosDefinition& apd, std::string& error); - - /** @brief Validates a given arrivalPosLat value - * @param[in] val The arrivalPosLat value to parse - * @param[in] element The name of the type of the parsed element, for building the error message - * @param[in] id The id of the parsed element, for building the error message - * @param[out] pos The parsed position, if given - * @param[out] apd The parsed arrivalPos definition - * @param[out] error Error message, if an error occures - * @return Whether the given value is a valid arrivalPos definition - */ - static bool parseArrivalPosLat(const std::string& val, const std::string& element, const std::string& id, - double& pos, ArrivalPosLatDefinition& apd, std::string& error); - - - /** @brief Validates a given arrivalSpeed value - * @param[in] val The arrivalSpeed value to parse - * @param[in] element The name of the type of the parsed element, for building the error message - * @param[in] id The id of the parsed element, for building the error message - * @param[out] speed The parsed speed, if given - * @param[out] asd The parsed arrivalSpeed definition - * @param[out] error Error message, if an error occures - * @return Whether the given value is a valid arrivalSpeed definition - */ - static bool parseArrivalSpeed(const std::string& val, const std::string& element, const std::string& id, - double& speed, ArrivalSpeedDefinition& asd, std::string& error); - /// @} - - /** @brief Interprets negative edge positions and fits them onto a given edge - * @param[in] pos The position to be interpreted - * @param[in] maximumValue The maximum allowed value (edge length) - * @param[in] attr The attribute from which the value originated - * @param[in] id The id of the object to which this attribute belongs - * @return Whether the interpreted position - */ - static double interpretEdgePos(double pos, double maximumValue, SumoXMLAttr attr, const std::string& id); - - /** @brief Validates a given person modes value - * @param[in] modes The modes value to parse - * @param[in] element The name of the type of the parsed element, for building the error message - * @param[in] id The id of the parsed element, for building the error message - * @param[out] modeSet The parsed modes definition - * @param[out] error Error message, if an error occures - * @return Whether the given value is a valid arrivalSpeed definition - */ - static bool parsePersonModes(const std::string& modes, const std::string& element, const std::string& id, SVCPermissions& modeSet, std::string& error); - - /// @brief parses stop trigger values - static void parseStopTriggers(const std::vector& triggers, bool expectTrigger, Stop& stop); - - /// @brief The vehicle tag - SumoXMLTag tag; - - /// @brief The vehicle's id - std::string id; - - /// @brief The vehicle's route id - std::string routeid; - - /// @brief The vehicle's type id - std::string vtypeid; - - /// @brief The vehicle's color, TraCI may change this - mutable RGBColor color; - - /// @name Departure definition - /// @{ - /// @brief The vehicle's departure time - SUMOTime depart; - - /// @brief Information how the vehicle shall choose the depart time - DepartDefinition departProcedure; - - /// @brief (optional) The lane the vehicle shall depart from (index in edge) - int departLane; - - /// @brief Information how the vehicle shall choose the lane to depart from - DepartLaneDefinition departLaneProcedure; - - /// @brief (optional) The position the vehicle shall depart from - double departPos; - - /// @brief Information how the vehicle shall choose the departure position - DepartPosDefinition departPosProcedure; - - /// @brief (optional) The lateral position the vehicle shall depart from - double departPosLat; - - /// @brief Information how the vehicle shall choose the lateral departure position - DepartPosLatDefinition departPosLatProcedure; - - /// @brief (optional) The initial speed of the vehicle - double departSpeed; - - /// @brief Information how the vehicle's initial speed shall be chosen - DepartSpeedDefinition departSpeedProcedure; - - /// @} - - /// @name Arrival definition - /// @{ - /// @brief (optional) The lane the vehicle shall arrive on (not used yet) - int arrivalLane; - - /// @brief Information how the vehicle shall choose the lane to arrive on - ArrivalLaneDefinition arrivalLaneProcedure; - - /// @brief (optional) The position the vehicle shall arrive on - double arrivalPos; - - /// @brief Information how the vehicle shall choose the arrival position - ArrivalPosDefinition arrivalPosProcedure; - - /// @brief (optional) The lateral position the vehicle shall arrive on - double arrivalPosLat; - - /// @brief Information how the vehicle shall choose the lateral arrival position - ArrivalPosLatDefinition arrivalPosLatProcedure; - - /// @brief (optional) The final speed of the vehicle (not used yet) - double arrivalSpeed; - - /// @brief Information how the vehicle's end speed shall be chosen - ArrivalSpeedDefinition arrivalSpeedProcedure; - - /// @} - - /// @name Repetition definition - /// @{ - /// @brief The number of times the vehicle shall be repeatedly inserted - int repetitionNumber; - - /// @brief The number of times the vehicle was already inserted - int repetitionsDone; - - /// @brief The time offset between vehicle reinsertions - SUMOTime repetitionOffset; - - /// @brief The probability for emitting a vehicle per second - double repetitionProbability; - - /// @brief The time at which the flow ends (only needed when using repetitionProbability) - SUMOTime repetitionEnd; - - /// @} - - /// @brief The vehicle's line (mainly for public transport) - mutable std::string line; - - /// @brief The vehicle's origin zone (district) - std::string fromTaz; - - /// @brief The vehicle's destination zone (district) - std::string toTaz; - - /// @brief List of the stops the vehicle will make, TraCI may add entries here - mutable std::vector stops; - - /// @brief List of the via-edges the vehicle must visit - mutable std::vector via; - - /// @brief The static number of persons in the vehicle when it departs (not including boarding persons) - int personNumber; - - /// @brief The static number of containers in the vehicle when it departs - int containerNumber; - - /// @brief individual speedFactor (overriding distribution from vType) - double speedFactor; - - /// @brief Information for the router which parameter were set, TraCI may modify this (when changing color) - mutable int parametersSet; - -protected: - /// @brief obtain depart parameter in string format - std::string getDepart() const; - - /// @brief obtain depart lane parameter in string format - std::string getDepartLane() const; - - /// @brief obtain depart pos parameter in string format - std::string getDepartPos() const; - - /// @brief obtain depart pos lat parameter in string format - std::string getDepartPosLat() const; - - /// @brief obtain depart speed parameter in string format - std::string getDepartSpeed() const; - - /// @brief obtain arrival lane parameter in string format - std::string getArrivalLane() const; - - /// @brief obtain arrival pos parameter in string format - std::string getArrivalPos() const; - - /// @brief obtain arrival pos lat parameter in string format - std::string getArrivalPosLat() const; - - /// @brief obtain arrival speed parameter in string format - std::string getArrivalSpeed() const; -}; diff --git a/Util/OSM2ODR/src/utils/xml/CMakeLists.txt b/Util/OSM2ODR/src/utils/xml/CMakeLists.txt deleted file mode 100644 index ada496799..000000000 --- a/Util/OSM2ODR/src/utils/xml/CMakeLists.txt +++ /dev/null @@ -1,24 +0,0 @@ -set(utils_xml_STAT_SRCS - GenericSAXHandler.h - GenericSAXHandler.cpp - IStreamInputSource.h - SUMOSAXAttributes.cpp - SUMOSAXAttributes.h - SUMOSAXAttributesImpl_Xerces.cpp - SUMOSAXAttributesImpl_Xerces.h - SUMOSAXAttributesImpl_Cached.cpp - SUMOSAXAttributesImpl_Cached.h - SUMOSAXHandler.cpp - SUMOSAXHandler.h - SUMOSAXReader.cpp - SUMOSAXReader.h - SUMOXMLDefinitions.cpp - SUMOXMLDefinitions.h - SAXWeightsHandler.cpp - SAXWeightsHandler.h - XMLSubSys.cpp - XMLSubSys.h -) - -add_library(utils_xml STATIC ${utils_xml_STAT_SRCS}) -set_property(TARGET utils_xml PROPERTY PROJECT_LABEL "z_utils_xml") diff --git a/Util/OSM2ODR/src/utils/xml/GenericSAXHandler.cpp b/Util/OSM2ODR/src/utils/xml/GenericSAXHandler.cpp deleted file mode 100644 index cbc19f349..000000000 --- a/Util/OSM2ODR/src/utils/xml/GenericSAXHandler.cpp +++ /dev/null @@ -1,232 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2002-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file GenericSAXHandler.cpp -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @author Laura Bieker -/// @date Sept 2002 -/// -// A handler which converts occuring elements and attributes into enums -/****************************************************************************/ -#include - -#include -#include "GenericSAXHandler.h" -#include -#include -#include -#include -#include -#include "SUMOSAXAttributesImpl_Xerces.h" -#include "XMLSubSys.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -GenericSAXHandler::GenericSAXHandler( - StringBijection::Entry* tags, int terminatorTag, - StringBijection::Entry* attrs, int terminatorAttr, - const std::string& file, const std::string& expectedRoot) - : myParentHandler(nullptr), myParentIndicator(SUMO_TAG_NOTHING), myFileName(file), myExpectedRoot(expectedRoot), mySchemaSeen(false) { - int i = 0; - while (tags[i].key != terminatorTag) { - myTagMap.insert(TagMap::value_type(tags[i].str, tags[i].key)); - i++; - } - i = 0; - while (attrs[i].key != terminatorAttr) { - int key = attrs[i].key; - assert(key >= 0); - while (key >= (int)myPredefinedTags.size()) { - myPredefinedTags.push_back(nullptr); - myPredefinedTagsMML.push_back(""); - } - myPredefinedTags[key] = convert(attrs[i].str); - myPredefinedTagsMML[key] = attrs[i].str; - i++; - } -} - - -GenericSAXHandler::~GenericSAXHandler() { - for (AttrMap::iterator i1 = myPredefinedTags.begin(); i1 != myPredefinedTags.end(); i1++) { - delete[](*i1); - } -} - - -void -GenericSAXHandler::setFileName(const std::string& name) { - myFileName = name; -} - - -const std::string& -GenericSAXHandler::getFileName() const { - return myFileName; -} - - -XMLCh* -GenericSAXHandler::convert(const std::string& name) const { - int len = (int)name.length(); - XMLCh* ret = new XMLCh[len + 1]; - int i = 0; - for (; i < len; i++) { - ret[i] = (XMLCh) name[i]; - } - ret[i] = 0; - return ret; -} - - -void -GenericSAXHandler::startElement(const XMLCh* const /*uri*/, - const XMLCh* const /*localname*/, - const XMLCh* const qname, - const XERCES_CPP_NAMESPACE::Attributes& attrs) { - std::string name = StringUtils::transcode(qname); - if (mySchemaSeen && myExpectedRoot != "") { - if (name != myExpectedRoot) { - throw ProcessError("Found root element '" + name + "' in file '" + getFileName() + "' (expected '" + myExpectedRoot + "')."); - } - mySchemaSeen = false; - } - int element = convertTag(name); - myCharactersVector.clear(); - SUMOSAXAttributesImpl_Xerces na(attrs, myPredefinedTags, myPredefinedTagsMML, name); - if (element == SUMO_TAG_INCLUDE) { - std::string file = na.getString(SUMO_ATTR_HREF); - if (!FileHelpers::isAbsolute(file)) { - file = FileHelpers::getConfigurationRelative(getFileName(), file); - } - XMLSubSys::runParser(*this, file); - } else { - myStartElement(element, na); - } -} - - -void -GenericSAXHandler::endElement(const XMLCh* const /*uri*/, - const XMLCh* const /*localname*/, - const XMLCh* const qname) { - std::string name = StringUtils::transcode(qname); - int element = convertTag(name); - // collect characters - if (myCharactersVector.size() != 0) { - int len = 0; - for (int i = 0; i < (int)myCharactersVector.size(); ++i) { - len += (int)myCharactersVector[i].length(); - } - char* buf = new char[len + 1]; - int pos = 0; - for (int i = 0; i < (int)myCharactersVector.size(); ++i) { - memcpy((unsigned char*) buf + pos, (unsigned char*) myCharactersVector[i].c_str(), - sizeof(char)*myCharactersVector[i].length()); - pos += (int)myCharactersVector[i].length(); - } - buf[pos] = 0; - - // call user handler - try { - myCharacters(element, buf); - } catch (std::runtime_error&) { - delete[] buf; - throw; - } - delete[] buf; - } - if (element != SUMO_TAG_INCLUDE) { - myEndElement(element); - if (myParentHandler && myParentIndicator == element) { - XMLSubSys::setHandler(*myParentHandler); - myParentIndicator = SUMO_TAG_NOTHING; - myParentHandler = nullptr; - } - } -} - - -void -GenericSAXHandler::registerParent(const int tag, GenericSAXHandler* handler) { - myParentHandler = handler; - myParentIndicator = tag; - XMLSubSys::setHandler(*this); -} - - -void -GenericSAXHandler::characters(const XMLCh* const chars, - const XERCES3_SIZE_t length) { - myCharactersVector.push_back(StringUtils::transcode(chars, (int)length)); -} - - -int -GenericSAXHandler::convertTag(const std::string& tag) const { - TagMap::const_iterator i = myTagMap.find(tag); - if (i == myTagMap.end()) { - return SUMO_TAG_NOTHING; - } - return (*i).second; -} - - -std::string -GenericSAXHandler::buildErrorMessage(const XERCES_CPP_NAMESPACE::SAXParseException& exception) { - std::ostringstream buf; - char* pMsg = XERCES_CPP_NAMESPACE::XMLString::transcode(exception.getMessage()); - buf << pMsg << std::endl; - buf << " In file '" << getFileName() << "'" << std::endl; - buf << " At line/column " << exception.getLineNumber() + 1 - << '/' << exception.getColumnNumber() << "." << std::endl; - XERCES_CPP_NAMESPACE::XMLString::release(&pMsg); - return buf.str(); -} - - -void -GenericSAXHandler::warning(const XERCES_CPP_NAMESPACE::SAXParseException& exception) { - WRITE_WARNING(buildErrorMessage(exception)); -} - - -void -GenericSAXHandler::error(const XERCES_CPP_NAMESPACE::SAXParseException& exception) { - throw ProcessError(buildErrorMessage(exception)); -} - - -void -GenericSAXHandler::fatalError(const XERCES_CPP_NAMESPACE::SAXParseException& exception) { - throw ProcessError(buildErrorMessage(exception)); -} - - -void -GenericSAXHandler::myStartElement(int, const SUMOSAXAttributes&) {} - - -void -GenericSAXHandler::myCharacters(int, const std::string&) {} - - -void -GenericSAXHandler::myEndElement(int) {} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/utils/xml/GenericSAXHandler.h b/Util/OSM2ODR/src/utils/xml/GenericSAXHandler.h deleted file mode 100644 index e3611ae31..000000000 --- a/Util/OSM2ODR/src/utils/xml/GenericSAXHandler.h +++ /dev/null @@ -1,328 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2002-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file GenericSAXHandler.h -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date Sept 2002 -/// -// A handler which converts occuring elements and attributes into enums -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "SUMOSAXAttributes.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class GenericSAXHandler - * @brief A handler which converts occuring elements and attributes into enums - * - * Normally, when using a standard SAX-handler, we would have to compare - * the incoming XMLCh*-element names with the ones we can parse. The same - * applies to parsing the attributes. This was assumed to be very time consuming, - * that's why we derive our handlers from this class. - * - * The idea behind this second handler layer was avoid repeated conversion - * from strings/whatever to XMLCh* and back again. The usage is quite straight - * forward, the only overhead is the need to define the enums - both elements - * and attributes within "SUMOXMLDefinitions". Still, it maybe helps to avoid typos. - * - * This class implements the SAX-callback and offers a new set of callbacks - * which must be implemented by derived classes. Instead of XMLCh*-values, - * element names are supplied to the derived classes as enums (int). - * - * Also, this class allows to retrieve attributes using enums (int) within - * the implemented "myStartElement" method. - * - * Basically, GenericSAXHandler is not derived within SUMO directly, but via SUMOSAXHandler - * which knows all tags/attributes used by SUMO. It is still kept separate for - * an easier maintainability and later extensions. - */ -class GenericSAXHandler : public XERCES_CPP_NAMESPACE::DefaultHandler { - -public: - /** - * @brief Constructor - * - * This constructor gets the lists of known tag and attribute names with - * their enums (sumotags and sumoattrs in most cases). The end of the list - * is signaled by terminatorTag/terminatorAttr respectively. - * - * The attribute names are converted into XMLCh* and stored within an - * internal container. This container is cleared within the destructor. - * - * @param[in] tags The list of known tags - * @param[in] terminatorTag The tag which signales the end of tags (usually the last entry) - * @param[in] attrs The list of known attributes - * @param[in] terminatorAttr The attr which signales the end of attrs (usually the last entry) - * @param[in] file The name of the processed file - * @param[in] expectedRoot The expected root element, empty string disables the check - * - * @todo Why are both lists non-const and given as pointers? - */ - GenericSAXHandler( - StringBijection::Entry* tags, int terminatorTag, - StringBijection::Entry* attrs, int terminatorAttr, - const std::string& file, const std::string& expectedRoot = ""); - - - /** @brief Destructor */ - virtual ~GenericSAXHandler(); - - - /** - * @brief The inherited method called when a new tag opens - * - * The method parses the supplied XMLCh*-qname using the internal name/enum-map - * to obtain the enum representation of the attribute name. - * - * Then, "myStartElement" is called supplying the enumeration value, the - * string-representation of the name and the attributes. - * - * @todo recheck/describe encoding of the string-representation - * @todo do not generate and report the string-representation - */ - void startElement(const XMLCh* const uri, const XMLCh* const localname, - const XMLCh* const qname, const XERCES_CPP_NAMESPACE::Attributes& attrs); - - - /** - * @brief The inherited method called when characters occurred - * - * The retrieved characters are converted into a string and appended into a - * private buffer. They are reported as soon as the element ends. - * - * @todo recheck/describe what happens with characters when a new element is opened - * @todo describe characters processing in the class' head - */ - void characters(const XMLCh* const chars, const XERCES3_SIZE_t length); - - - /** - * @brief The inherited method called when a tag is being closed - * - * This method calls the user-implemented methods myCharacters with the previously - * collected and converted characters. - * - * Then, myEndElement is called, supplying it the qname converted to its enum- - * and string-representations. - * - * @todo recheck/describe encoding of the string-representation - * @todo do not generate and report the string-representation - */ - void endElement(const XMLCh* const uri, const XMLCh* const localname, - const XMLCh* const qname); - - - /** - * @brief Assigning a parent handler which is enabled when the specified tag is closed - */ - void registerParent(const int tag, GenericSAXHandler* handler); - - - /** - * @brief Sets the current file name - * - * @param[in] name The name of the currently processed file - * - * @todo Hmmm - this is as unsafe as having a direct access to the variable; recheck - */ - void setFileName(const std::string& name); - - - /** - * @brief returns the current file name - * - * @return The name of the currently processed file - */ - const std::string& getFileName() const; - - - /// @name SAX ErrorHandler callbacks - //@{ - - /** - * @brief Handler for XML-warnings - * - * The message is built using buildErrorMessage and reported - * to the warning-instance of the MsgHandler. - * - * @param[in] exception The occurred exception to process - */ - void warning(const XERCES_CPP_NAMESPACE::SAXParseException& exception); - - - /** - * @brief Handler for XML-errors - * - * The message is built using buildErrorMessage and thrown within a ProcessError. - * - * @param[in] exception The occurred exception to process - * @exception ProcessError On any call - */ - void error(const XERCES_CPP_NAMESPACE::SAXParseException& exception); - - - /** - * @brief Handler for XML-errors - * - * The message is built using buildErrorMessage and thrown within a ProcessError. - * - * @exception ProcessError On any call - * @param[in] exception The occurred exception to process - */ - void fatalError(const XERCES_CPP_NAMESPACE::SAXParseException& exception); - //@} - - - // Reader needs access to myStartElement, myEndElement - friend class SUMOSAXReader; - - -protected: - /** - * @brief Builds an error message - * - * The error message includes the file name and the line/column information - * as supported by the given SAXParseException - * - * @param[in] exception The name of the currently processed file - * @return A string describing the given exception - */ - std::string buildErrorMessage(const XERCES_CPP_NAMESPACE::SAXParseException& exception); - - - /** - * @brief Callback method for an opening tag to implement by derived classes - * - * Called by "startElement" (see there). - * @param[in] element The element that contains the characters, given as a int - * @param[in] attrs The SAX-attributes, wrapped as SUMOSAXAttributes - * @exceptions ProcessError These method may throw a ProcessError if something fails - */ - virtual void myStartElement(int element, - const SUMOSAXAttributes& attrs); - - - /** - * @brief Callback method for characters to implement by derived classes - * - * Called by "endElement" (see there). - * @param[in] element The opened element, given as a int - * @param[in] chars The complete embedded character string - * @exceptions ProcessError These method may throw a ProcessError if something fails - */ - virtual void myCharacters(int element, - const std::string& chars); - - - /** @brief Callback method for a closing tag to implement by derived classes - * - * Called by "endElement" (see there). - * @param[in] element The closed element, given as a int - * @exceptions ProcessError These method may throw a ProcessError if something fails - */ - virtual void myEndElement(int element); - - - void setSchemaSeen(const bool schemaSeen = true) { - mySchemaSeen = schemaSeen; - } - -private: - /** - * @brief converts from c++-string into unicode - * - * @todo recheck encoding - * @param[in] name The string to convert - * @return The string converted into a XMLCh-string - */ - XMLCh* convert(const std::string& name) const; - - - /** - * @brief Converts a tag from its string into its numerical representation - * - * Returns the enum-representation stored for the given tag. If the tag is not - * known, SUMO_TAG_NOTHING is returned. - * @param[in] tag The string to convert - * @return The int-value that represents the string, SUMO_TAG_NOTHING if the named attribute is not known - */ - int convertTag(const std::string& tag) const; - - -private: - /// @name attributes parsing - //@{ - - // the type of the map from ids to their unicode-string representation - typedef std::vector AttrMap; - - // the map from ids to their unicode-string representation - AttrMap myPredefinedTags; - - /// the map from ids to their string representation - std::vector myPredefinedTagsMML; - //@} - - - /// @name elements parsing - //@{ - - // the type of the map that maps tag names to ints - typedef std::map TagMap; - - // the map of tag names to their internal numerical representation - TagMap myTagMap; - //@} - - /// A list of character strings obtained so far to build the complete characters string at the end - std::vector myCharactersVector; - - /// @brief The handler to give control back to - GenericSAXHandler* myParentHandler; - - /// @brief The tag indicating that control should be given back - int myParentIndicator; - - /// @brief The name of the currently parsed file - std::string myFileName; - - /// @brief The root element to expect, empty string disables the check - std::string myExpectedRoot; - - /// @brief whether the reader has already seen a schema - bool mySchemaSeen; - -private: - /// @brief invalidated copy constructor - GenericSAXHandler(const GenericSAXHandler& s); - - /// @brief invalidated assignment operator - const GenericSAXHandler& operator=(const GenericSAXHandler& s); - -}; diff --git a/Util/OSM2ODR/src/utils/xml/IStreamInputSource.h b/Util/OSM2ODR/src/utils/xml/IStreamInputSource.h deleted file mode 100644 index 24835d0e2..000000000 --- a/Util/OSM2ODR/src/utils/xml/IStreamInputSource.h +++ /dev/null @@ -1,68 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2002-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file IStreamInputSource.h -/// @author Michael Behrisch -/// @author Gilles Filippini -/// @date Sept 2002 -/// -// Xerces InputSource reading from arbitrary std::istream -// reimplementation inspired by https://marc.info/?l=xerces-dev&m=86952133511623 -/****************************************************************************/ -#pragma once -#include -#include -#include - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class IStreamBinInputStream - * @brief Xerces BinInputStream reading from arbitrary std::istream - */ -class IStreamBinInputStream : public XERCES_CPP_NAMESPACE::BinInputStream { -public: - IStreamBinInputStream(std::istream& in) : myIn(in) { } - virtual ~IStreamBinInputStream(void) { } - virtual XMLFilePos curPos(void) const { - return myIn.tellg(); - } - virtual XMLSize_t readBytes(XMLByte* const buf, const XMLSize_t max) { - myIn.read((char*)buf, max); - return (XMLSize_t)myIn.gcount(); - } - virtual const XMLCh* getContentType() const { - return nullptr; - } -private: - std::istream& myIn; -}; - - -/** - * @class IStreamInputSource - * @brief Xerces InputSource reading from arbitrary std::istream - */ -class IStreamInputSource : public XERCES_CPP_NAMESPACE::InputSource { -public: - IStreamInputSource(std::istream& in) : - XERCES_CPP_NAMESPACE::InputSource("istream"), myIn(in) { } - virtual ~IStreamInputSource(void) { } - virtual XERCES_CPP_NAMESPACE::BinInputStream* makeStream(void) const { - return new IStreamBinInputStream(myIn); - } -private: - std::istream& myIn; -}; diff --git a/Util/OSM2ODR/src/utils/xml/SAXWeightsHandler.cpp b/Util/OSM2ODR/src/utils/xml/SAXWeightsHandler.cpp deleted file mode 100644 index 4a4d460c2..000000000 --- a/Util/OSM2ODR/src/utils/xml/SAXWeightsHandler.cpp +++ /dev/null @@ -1,177 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2007-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file SAXWeightsHandler.cpp -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date Fri, 30 Mar 2007 -/// -// An XML-handler for network weights -/****************************************************************************/ -#include - -#include - -#include "SAXWeightsHandler.h" - - -// =========================================================================== -// method definitions -// =========================================================================== - -// --------------------------------------------------------------------------- -// SAXWeightsHandler::ToRetrieveDefinition methods -// --------------------------------------------------------------------------- - -SAXWeightsHandler::ToRetrieveDefinition::ToRetrieveDefinition(const std::string& attributeName, - bool edgeBased, EdgeFloatTimeLineRetriever& destination) : - myAttributeName(attributeName), - myAmEdgeBased(edgeBased), - myDestination(destination), - myAggValue(0), - myNoLanes(0), - myHadAttribute(0) { -} - - -SAXWeightsHandler::ToRetrieveDefinition::~ToRetrieveDefinition() { -} - -// --------------------------------------------------------------------------- -// SAXWeightsHandler methods -// --------------------------------------------------------------------------- - -SAXWeightsHandler::SAXWeightsHandler(const std::vector& defs, const std::string& file) : - SUMOSAXHandler(file), - myDefinitions(defs), - myCurrentTimeBeg(-1), - myCurrentTimeEnd(-1) { -} - - -SAXWeightsHandler::SAXWeightsHandler(ToRetrieveDefinition* def, const std::string& file) : - SUMOSAXHandler(file), - myDefinitions({def}), - myCurrentTimeBeg(-1), -myCurrentTimeEnd(-1) { -} - - -SAXWeightsHandler::~SAXWeightsHandler() { - for (const auto& definition : myDefinitions) { - delete definition; - } -} - - -void -SAXWeightsHandler::myStartElement(int element, const SUMOSAXAttributes& attrs) { - switch (element) { - case SUMO_TAG_INTERVAL: { - bool ok = true; - myCurrentTimeBeg = STEPS2TIME(attrs.getSUMOTimeReporting(SUMO_ATTR_BEGIN, nullptr, ok)); - myCurrentTimeEnd = STEPS2TIME(attrs.getSUMOTimeReporting(SUMO_ATTR_END, nullptr, ok)); - } - break; - case SUMO_TAG_EDGE: { - bool ok = true; - myCurrentEdgeID = attrs.getOpt(SUMO_ATTR_ID, nullptr, ok, ""); - tryParse(attrs, true); - } - break; - case SUMO_TAG_EDGEREL: { - tryParseEdgeRel(attrs); - } - break; - case SUMO_TAG_LANE: { - tryParse(attrs, false); - } - break; - default: - break; - } -} - - -void -SAXWeightsHandler::tryParse(const SUMOSAXAttributes& attrs, bool isEdge) { - // !!!! no error handling! - if (isEdge) { - // process all that want values directly from the edge - for (const auto& definition : myDefinitions) { - if (definition->myAmEdgeBased) { - if (attrs.hasAttribute(definition->myAttributeName)) { - definition->myAggValue = attrs.getFloat(definition->myAttributeName); - definition->myNoLanes = 1; - definition->myHadAttribute = true; - } else { - definition->myHadAttribute = false; - } - } else { - definition->myAggValue = 0; - definition->myNoLanes = 0; - } - } - } else { - // process the current lane values - for (const auto& definition : myDefinitions) { - if (!definition->myAmEdgeBased) { - try { - definition->myAggValue += attrs.getFloat(definition->myAttributeName); - definition->myNoLanes++; - definition->myHadAttribute = true; - } catch (EmptyData&) { - WRITE_ERROR("Missing value '" + definition->myAttributeName + "' in edge '" + myCurrentEdgeID + "'."); - } catch (NumberFormatException&) { - WRITE_ERROR("The value should be numeric, but is not.\n In edge '" + myCurrentEdgeID + - "' at time step " + toString(myCurrentTimeBeg) + "."); - } - } - } - } -} - - -void -SAXWeightsHandler::tryParseEdgeRel(const SUMOSAXAttributes& attrs) { - if (attrs.hasAttribute(SUMO_ATTR_FROM) && attrs.hasAttribute(SUMO_ATTR_TO)) { - bool ok = true; - const std::string from = attrs.get(SUMO_ATTR_FROM, nullptr, ok); - const std::string to = attrs.get(SUMO_ATTR_TO, nullptr, ok); - for (ToRetrieveDefinition* ret : myDefinitions) { - if (attrs.hasAttribute(ret->myAttributeName)) { - ret->myDestination.addEdgeRelWeight(from, to, - attrs.getFloat(ret->myAttributeName), - myCurrentTimeBeg, myCurrentTimeEnd); - } - } - } -} - - -void -SAXWeightsHandler::myEndElement(int element) { - if (element == SUMO_TAG_EDGE) { - for (const auto& definition : myDefinitions) { - if (definition->myHadAttribute) { - definition->myDestination.addEdgeWeight(myCurrentEdgeID, - definition->myAggValue / (double)definition->myNoLanes, - myCurrentTimeBeg, myCurrentTimeEnd); - } - } - } -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/utils/xml/SAXWeightsHandler.h b/Util/OSM2ODR/src/utils/xml/SAXWeightsHandler.h deleted file mode 100644 index b40549dbc..000000000 --- a/Util/OSM2ODR/src/utils/xml/SAXWeightsHandler.h +++ /dev/null @@ -1,209 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2007-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file SAXWeightsHandler.h -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date Fri, 30 Mar 2007 -/// -// An XML-handler for network weights -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include - - -// =========================================================================== -// class declarations -// =========================================================================== -class OptionsCont; -class RONet; -class ROEdge; - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class SAXWeightsHandler - * @brief An XML-handler for network weights - * - * As network weights are used both in the simulation and the routers, a base - * class for loading them was built. Instances of this class should be supplied - * with at least one definition about what shall be retrieved - * (ToRetrieveDefinition, defined as inner class) which also contains the information - * about the retriever (EdgeFloatTimeLineRetriever, defined as inner class). - * - * The ToRetrieveDefinition names the attribute which the SAXWeightsHandler shall - * parse and reporte. Within the parsed xml-file these attributes may be embedded - * in "lane" or "edge" elements, one for each edge or for each lane (see below). - * These elements should be embedded in interval-tags which specify the time the - * weight is valid at. - * The boolean "edgeBased" tells SAXWeightsHandler whether the weights are supplied - * on edge- or on lane-basis (whether it shall parse the "edge" or the "lane" elements). - * - * Examples for files the SAXWeightsHandler can handle are the edgedump and the lanedump - * generated by the simulation. - * - * The EdgeFloatTimeLineRetriever to which read values will be reported should have the - * method "addEdgeWeight" implemented. It wil be supplied with the current edge name, - * the interval the weight is valid for and the value. - */ -class SAXWeightsHandler : public SUMOSAXHandler { -public: - /** - * @class EdgeFloatTimeLineRetriever - * @brief Interface for a class which obtains read weights for named edges - */ - class EdgeFloatTimeLineRetriever { - - public: - /// @brief Constructor - EdgeFloatTimeLineRetriever() { } - - /// @brief Destructor - virtual ~EdgeFloatTimeLineRetriever() { } - - /** @brief Adds a weight for a given edge and time period - * - * @param[in] id The id of the object to add a weight for - * @param[in] val The weight - * @param[in] beg The begin of the interval the weight is valid for - * @param[in] end The end of the interval the weight is valid for - */ - virtual void addEdgeWeight(const std::string& id, double val, double beg, double end) const = 0; - - virtual void addEdgeRelWeight(const std::string& from, const std::string& to, - double val, double beg, double end) const { - UNUSED_PARAMETER(from); - UNUSED_PARAMETER(to); - UNUSED_PARAMETER(val); - UNUSED_PARAMETER(beg); - UNUSED_PARAMETER(end); - } - - private: - /// @brief we made the assignment operator invalid - EdgeFloatTimeLineRetriever& operator=(const EdgeFloatTimeLineRetriever&) = delete; - }; - - /** - * @class ToRetrieveDefinition - * @brief Complete definition about what shall be retrieved and where to store it - */ - class ToRetrieveDefinition { - public: - /// @brief Constructor - ToRetrieveDefinition(const std::string& attributeName, bool edgeBased, - EdgeFloatTimeLineRetriever& destination); - - /// Destructor - ~ToRetrieveDefinition(); - - public: - /// @brief The attribute name that shall be parsed - std::string myAttributeName; - - /// @brief Information whether edge values shall be used (lane value if false) - bool myAmEdgeBased; - - /// @brief The class that shall be called when new data is avaiable - EdgeFloatTimeLineRetriever& myDestination; - - /// @brief Aggregated value over the lanes read within the current edge - double myAggValue; - - /// @brief The number of lanes read for the current edge - int myNoLanes; - - /// @brief Information whether the attribute has been found for the current edge - bool myHadAttribute; - - private: - /// @brief Invalidated copy constructor. - ToRetrieveDefinition(const ToRetrieveDefinition&) = delete; - - /// @brief Invalidated assignment operator. - ToRetrieveDefinition& operator=(const ToRetrieveDefinition&) = delete; - }; - - /** - * @brief Constructor - * - * Gets a list of retriever definitions. Please note that the retrievers are - * not deleted! - */ - SAXWeightsHandler(const std::vector& defs, const std::string& file); - - /** - * @brief Constructor - * - * Gets a single definition. Please note that the retrievers are not deleted! - */ - SAXWeightsHandler(ToRetrieveDefinition* def, const std::string& file); - - /// @brief Destructor - ~SAXWeightsHandler(); - -protected: - /// @name inherited from GenericSAXHandler - //@{ - - /** @brief Called on the opening of a tag; - * - * @param[in] element ID of the currently opened element - * @param[in] attrs Attributes within the currently opened element - * @exception ProcessError If something fails - * @see GenericSAXHandler::myStartElement - */ - void myStartElement(int element, const SUMOSAXAttributes& attrs); - - /** @brief Called when a closing tag occurs - * - * @param[in] element ID of the currently opened element - * @exception ProcessError If something fails - * @see GenericSAXHandler::myEndElement - */ - void myEndElement(int elemente); - - //@} - -private: - /// @brief Parses the data of an edge or lane for the previously read times - void tryParse(const SUMOSAXAttributes& attrs, bool isEdge); - - /// @brief Parses the data of an edgeRel for the previously read times - void tryParseEdgeRel(const SUMOSAXAttributes& attrs); - - /// @brief List of definitions what shall be read and whereto stored while parsing the file - std::vector myDefinitions; - - /// @brief the begin of the time period that is currently processed - double myCurrentTimeBeg; - - /// @brief the end of the time period that is currently processed - double myCurrentTimeEnd; - - /// @brief the edge which is currently being processed - std::string myCurrentEdgeID; - - /// @brief we made the copy constructor invalid - SAXWeightsHandler(const SAXWeightsHandler& src) = delete; - - /// @brief we made the assignment operator invalid - SAXWeightsHandler& operator=(const SAXWeightsHandler& src) = delete; -}; diff --git a/Util/OSM2ODR/src/utils/xml/SUMOSAXAttributes.cpp b/Util/OSM2ODR/src/utils/xml/SUMOSAXAttributes.cpp deleted file mode 100644 index 6cc402782..000000000 --- a/Util/OSM2ODR/src/utils/xml/SUMOSAXAttributes.cpp +++ /dev/null @@ -1,259 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2007-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file SUMOSAXAttributes.cpp -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date Fri, 30 Mar 2007 -/// -// Encapsulated SAX-Attributes -/****************************************************************************/ -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "SUMOSAXAttributes.h" - - -// =========================================================================== -// static members -// =========================================================================== -const std::string SUMOSAXAttributes::ENCODING = " encoding=\"UTF-8\""; - - -// =========================================================================== -// method definitions -// =========================================================================== -SUMOSAXAttributes::SUMOSAXAttributes(const std::string& objectType): - myObjectType(objectType) {} - - -const std::string invalid_return::value = ""; -const std::string invalid_return::type = "string"; -template<> -std::string SUMOSAXAttributes::getInternal(const int attr) const { - const std::string ret = getString(attr); - if (ret == "") { - throw EmptyData(); - } - return ret; -} - - -SUMOTime -SUMOSAXAttributes::getSUMOTimeReporting(int attr, const char* objectid, - bool& ok, bool report) const { - if (!hasAttribute(attr)) { - if (report) { - emitUngivenError(getName(attr), objectid); - } - ok = false; - return -1; - } - try { - const std::string val = getInternal(attr); - return string2time(val); - } catch (EmptyData&) { - if (report) { - emitEmptyError(getName(attr), objectid); - } - } catch (ProcessError&) { - if (report) { - emitFormatError(getName(attr), "a time value", objectid); - } - } - ok = false; - return (SUMOTime) - 1; -} - - -SUMOTime -SUMOSAXAttributes::getOptSUMOTimeReporting(int attr, const char* objectid, - bool& ok, SUMOTime defaultValue, bool report) const { - if (!hasAttribute(attr)) { - return defaultValue; - } - try { - const std::string val = getInternal(attr); - return string2time(val); - } catch (EmptyData&) { - if (report) { - emitEmptyError(getName(attr), objectid); - } - } catch (ProcessError&) { - if (report) { - emitFormatError(getName(attr), "a real number", objectid); - } - } - ok = false; - return (SUMOTime) - 1; -} - - -const std::vector -SUMOSAXAttributes::getStringVector(int attr) const { - const std::vector& ret = StringTokenizer(getString(attr)).getVector(); - if (ret.empty()) { - throw EmptyData(); - } - return ret; -} - - -const std::vector -SUMOSAXAttributes::getOptStringVector(int attr, const char* objectid, bool& ok, bool report) const { - return getOpt >(attr, objectid, ok, std::vector(), report); -} - -const std::vector -SUMOSAXAttributes::getIntVector(int attr) const { - const std::vector& tmp = StringTokenizer(getString(attr)).getVector(); - if (tmp.empty()) { - throw EmptyData(); - } - std::vector ret; - for (const std::string& s : tmp) { - ret.push_back(StringUtils::toInt(s)); - } - return ret; -} - - -const std::vector -SUMOSAXAttributes::getOptIntVector(int attr, const char* objectid, bool& ok, bool report) const { - return getOpt >(attr, objectid, ok, std::vector(), report); -} - -void -SUMOSAXAttributes::emitUngivenError(const std::string& attrname, const char* objectid) const { - std::ostringstream oss; - oss << "Attribute '" << attrname << "' is missing in definition of "; - if (objectid == nullptr || objectid[0] == 0) { - oss << "a " << myObjectType; - } else { - oss << myObjectType << " '" << objectid << "'"; - } - oss << "."; - WRITE_ERROR(oss.str()); -} - - -void -SUMOSAXAttributes::emitEmptyError(const std::string& attrname, const char* objectid) const { - std::ostringstream oss; - oss << "Attribute '" << attrname << "' in definition of "; - if (objectid == nullptr || objectid[0] == 0) { - oss << "a " << myObjectType; - } else { - oss << myObjectType << " '" << objectid << "'"; - } - oss << " is empty."; - WRITE_ERROR(oss.str()); -} - - -void -SUMOSAXAttributes::emitFormatError(const std::string& attrname, const std::string& type, const char* objectid) const { - std::ostringstream oss; - oss << "Attribute '" << attrname << "' in definition of "; - if (objectid == nullptr || objectid[0] == 0) { - oss << "a " << myObjectType; - } else { - oss << myObjectType << " '" << objectid << "'"; - } - oss << " is not " << type << "."; - WRITE_ERROR(oss.str()); -} - - -const int invalid_return::value = -1; -const std::string invalid_return::type = "int"; -template<> -int SUMOSAXAttributes::getInternal(const int attr) const { - return getInt(attr); -} - - -const long long int invalid_return::value = -1; -const std::string invalid_return::type = "long"; -template<> -long long int SUMOSAXAttributes::getInternal(const int attr) const { - return getLong(attr); -} - - -const double invalid_return::value = -1; -const std::string invalid_return::type = "float"; -template<> -double SUMOSAXAttributes::getInternal(const int attr) const { - return getFloat(attr); -} - - -const bool invalid_return::value = false; -const std::string invalid_return::type = "bool"; -template<> -bool SUMOSAXAttributes::getInternal(const int attr) const { - return getBool(attr); -} - - -const RGBColor invalid_return::value = RGBColor(); -const std::string invalid_return::type = "color"; -template<> -RGBColor SUMOSAXAttributes::getInternal(const int /* attr */) const { - return getColor(); -} - - -const PositionVector invalid_return::value = PositionVector(); -const std::string invalid_return::type = "PositionVector"; -template<> -PositionVector SUMOSAXAttributes::getInternal(const int attr) const { - return getShape(attr); -} - - -const Boundary invalid_return::value = Boundary(); -const std::string invalid_return::type = "Boundary"; -template<> -Boundary SUMOSAXAttributes::getInternal(const int attr) const { - return getBoundary(attr); -} - - -const std::vector invalid_return >::value = std::vector(); -const std::string invalid_return >::type = "StringVector"; -template<> -std::vector SUMOSAXAttributes::getInternal(const int attr) const { - return getStringVector(attr); -} - - -const std::vector invalid_return >::value = std::vector(); -const std::string invalid_return >::type = "StringVector"; -template<> -std::vector SUMOSAXAttributes::getInternal(const int attr) const { - return getIntVector(attr); -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/utils/xml/SUMOSAXAttributes.h b/Util/OSM2ODR/src/utils/xml/SUMOSAXAttributes.h deleted file mode 100644 index f5b0707c0..000000000 --- a/Util/OSM2ODR/src/utils/xml/SUMOSAXAttributes.h +++ /dev/null @@ -1,534 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2007-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file SUMOSAXAttributes.h -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date Fri, 30 Mar 2007 -/// -// Encapsulated SAX-Attributes -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include - -#include -#include -#include -#include "SUMOXMLDefinitions.h" - - -// =========================================================================== -// class declarations -// =========================================================================== -class PositionVector; -class Boundary; -class RGBColor; - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class SUMOSAXAttributes - * @brief Encapsulated SAX-Attributes - * - * This class is an interface for using encapsulated SAX-attributes. - * Encapsulation is done to allow a common acces without the need to - * import all the Xerces-definitions. - */ -class SUMOSAXAttributes { -public: - /* @brief Constructor - * @param[in] tagName The name of the parsed object type; used for error message generation - */ - SUMOSAXAttributes(const std::string& objectType); - - - /// @brief Destructor - virtual ~SUMOSAXAttributes() { } - - - /** @brief Tries to read given attribute assuming it is an int - * - * If an error occurs (the attribute is not there, it is not numeric), "ok" is - * set to false. If report is true an error message is written to MsgHandler::getErrorInstance. - * - * If the value could be read, "ok" is not changed, and the value is returned. - * - * @param[in] attr The id of the attribute to read - * @param[in] objectid The name of the parsed object; used for error message generation - * @param[out] ok Whether the value could be read - * @param[in] report Whether errors shall be written to msg handler's error instance - * @return The read value if given and correct; -1 if an error occurred - */ - template - T get(int attr, const char* objectid, bool& ok, bool report = true) const; - - - /** @brief Tries to read given attribute assuming it is an int - * - * If the attribute is not existing in the current element, the default value is returned. - * If an error occurs on parsing (the attribute is empty, it is not numeric), "ok" is - * set to false. If report is true an error message is written to MsgHandler::getErrorInstance. - * - * If the value could be read, "ok" is not changed, and the value is returned. - * - * @param[in] attr The id of the attribute to read - * @param[in] objectid The name of the parsed object; used for error message generation - * @param[out] ok Whether the value could be read - * @param[in] defaultValue The value to return if the attribute is not within the element - * @param[in] report Whether errors shall be written to msg handler's error instance - * @return The read value if given and correct; the default value if the attribute does not exist; -1 if an error occurred - */ - template - T getOpt(int attr, const char* objectid, bool& ok, T defaultValue, bool report = true) const; - - - /** @brief Tries to read given attribute assuming it is a SUMOTime - * - * If an error occurs (the attribute is not there, it is not numeric), "ok" is - * set to false and an error message is written to MsgHandler::getErrorInstance. - * - * Otherwise, "ok" is not changed. - * - * In dependence to the used time representation, either get or get - * is used. - * - * @param[in] attr The id of the attribute to read - * @param[in] objectid The name of the parsed object; used for error message generation - * @param[out] ok Whether the value could be read - * @param[in] report Whether errors shall be written to msg handler's error instance - * @return The read value if given and correct; -1 if an error occurred - */ - SUMOTime getSUMOTimeReporting(int attr, const char* objectid, bool& ok, - bool report = true) const; - - - - /** @brief Tries to read given attribute assuming it is a SUMOTime - * - * If the attribute is not existing in the current element, the default value is returned. - * If an error occurs on parsing (the attribute is empty, it is not numeric), "ok" is - * set to false. If report is true an error message is written to MsgHandler::getErrorInstance. - * - * Otherwise, "ok" is not changed. - * - * In dependence to the used time representation, either get or get - * is used. - * - * @param[in] attr The id of the attribute to read - * @param[in] objectid The name of the parsed object; used for error message generation - * @param[out] ok Whether the value could be read - * @param[in] defaultValue The value to return if the attribute is not within the element - * @param[in] report Whether errors shall be written to msg handler's error instance - * @return The read value if given and correct; the default value if the attribute does not exist; -1 if an error occurred - */ - SUMOTime getOptSUMOTimeReporting(int attr, const char* objectid, bool& ok, - SUMOTime defaultValue, bool report = true) const; - - - - /// @name virtual methods for retrieving attribute values - /// @{ - - /** @brief Returns the information whether the named (by its enum-value) attribute is within the current list - * - * @param[in] id The id of the attribute to search for - * @return Whether the attribute is within the attributes - */ - virtual bool hasAttribute(int id) const = 0; - - - /** @brief Returns the information whether the named attribute is within the current list - * - * @param[in] id The name of the attribute to search for - * @return Whether the named attribute is within the attributes - */ - virtual bool hasAttribute(const std::string& id) const = 0; - - - /** - * @brief Returns the bool-value of the named (by its enum-value) attribute - * - * Tries to retrieve the attribute from the the attribute list. The retrieved - * attribute (which may be 0) is then parsed using TplConvert::_2bool. - * If the attribute is empty or ==0, TplConvert::_2bool throws an - * EmptyData-exception which is passed. - * If the value can not be parsed to a bool, TplConvert::_2bool throws a - * BoolFormatException-exception which is passed. - * - * @param[in] id The id of the attribute to return the value of - * @return The attribute's value as a bool, if it could be read and parsed - * @exception EmptyData If the attribute is not known or the attribute value is an empty string - * @exception BoolFormatException If the attribute value can not be parsed to a bool - */ - virtual bool getBool(int id) const = 0; - - /** - * @brief Returns the int-value of the named (by its enum-value) attribute - * - * Tries to retrieve the attribute from the the attribute list. The retrieved - * attribute (which may be 0) is then parsed using TplConvert::_2int. - * If the attribute is empty or ==0, TplConvert::_2int throws an - * EmptyData-exception which is passed. - * If the value can not be parsed to an int, TplConvert::_2int throws a - * NumberFormatException-exception which is passed. - * - * @param[in] id The id of the attribute to return the value of - * @return The attribute's value as an int, if it could be read and parsed - * @exception EmptyData If the attribute is not known or the attribute value is an empty string - * @exception NumberFormatException If the attribute value can not be parsed to an int - */ - virtual int getInt(int id) const = 0; - - - /** - * @brief Returns the long-value of the named (by its enum-value) attribute - * - * Tries to retrieve the attribute from the the attribute list. The retrieved - * attribute (which may be 0) is then parsed using TplConvert::_2long. - * If the attribute is empty or ==0, TplConvert::_2long throws an - * EmptyData-exception which is passed. - * If the value can not be parsed to a long, TplConvert::_2long throws a - * NumberFormatException-exception which is passed. - * - * @param[in] id The id of the attribute to return the value of - * @return The attribute's value as an int, if it could be read and parsed - * @exception EmptyData If the attribute is not known or the attribute value is an empty string - * @exception NumberFormatException If the attribute value can not be parsed to an int - */ - virtual long long int getLong(int id) const = 0; - - - /** - * @brief Returns the string-value of the named (by its enum-value) attribute - * - * Tries to retrieve the attribute from the the attribute list. The retrieved - * attribute (which may be 0) is then parsed using TplConvert::_2str. - * If the attribute is ==0, TplConvert::_2str throws an - * EmptyData-exception which is passed. - * - * @param[in] id The id of the attribute to return the value of - * @return The attribute's value as a string, if it could be read and parsed - * @exception EmptyData If the attribute is not known or the attribute value is an empty string - */ - virtual std::string getString(int id) const = 0; - - - /** - * @brief Returns the string-value of the named (by its enum-value) attribute - * - * Tries to retrieve the attribute from the the attribute list. The retrieved - * attribute (which may be 0) is then parsed using TplConvert::_2strSec. - * If the attribute is ==0, TplConvert::_2strSec returns the default value. - * - * @param[in] id The id of the attribute to return the value of - * @param[in] def The default value to return if the attribute is not in attributes - * @return The attribute's value as a string, if it could be read and parsed - * @exception EmptyData If the attribute is not known or the attribute value is an empty string - */ - virtual std::string getStringSecure(int id, - const std::string& def) const = 0; - - - /** - * @brief Returns the double-value of the named (by its enum-value) attribute - * - * Tries to retrieve the attribute from the the attribute list. The retrieved - * attribute (which may be 0) is then parsed using TplConvert::_2double. - * If the attribute is empty or ==0, TplConvert::_2double throws an - * EmptyData-exception which is passed. - * If the value can not be parsed to a double, TplConvert::_2double throws a - * NumberFormatException-exception which is passed. - * - * @param[in] id The id of the attribute to return the value of - * @return The attribute's value as a float, if it could be read and parsed - * @exception EmptyData If the attribute is not known or the attribute value is an empty string - * @exception NumberFormatException If the attribute value can not be parsed to an double - */ - virtual double getFloat(int id) const = 0; - - - /** - * @brief Returns the double-value of the named attribute - * - * Tries to retrieve the attribute from the the attribute list. The retrieved - * attribute (which may be 0) is then parsed using TplConvert::_2double. - * If the attribute is empty or ==0, TplConvert::_2double throws an - * EmptyData-exception which is passed. - * If the value can not be parsed to a double, TplConvert::_2double throws a - * NumberFormatException-exception which is passed. - * - * @param[in] id The name of the attribute to return the value of - * @return The attribute's value as a float, if it could be read and parsed - * @exception EmptyData If the attribute is not known or the attribute value is an empty string - * @exception NumberFormatException If the attribute value can not be parsed to an double - */ - virtual double getFloat(const std::string& id) const = 0; - - - /** - * @brief Returns the string-value of the named (by its enum-value) attribute - * - * Tries to retrieve the attribute from the the attribute list. - * If the attribute is ==0, TplConvert::_2strSec returns the default value. - * @param[in] id The name of the attribute to return the value of - * @param[in] def The default value to return if the attribute is not in attributes - * @return The attribute's value as a string, if it could be read and parsed - */ - virtual std::string getStringSecure(const std::string& id, - const std::string& def) const = 0; - - - /** - * @brief Returns the value of the named attribute - * - * Tries to retrieve the attribute from the the attribute list. - * @return The attribute's value as a string, if it could be read and parsed - */ - virtual SumoXMLEdgeFunc getEdgeFunc(bool& ok) const = 0; - - - /** - * @brief Returns the value of the named attribute - * - * Tries to retrieve the attribute from the the attribute list. - * @return The attribute's value as a string, if it could be read and parsed - */ - virtual SumoXMLNodeType getNodeType(bool& ok) const = 0; - - /** - * @brief Returns the right-of-way method - */ - virtual RightOfWay getRightOfWay(bool& ok) const = 0; - - /// @brief returns fringe type - virtual FringeType getFringeType(bool& ok) const = 0; - - /** - * @brief Returns the value of the named attribute - * - * Tries to retrieve the attribute from the the attribute list. - * @return The attribute's value as a RGBColor, if it could be read and parsed - */ - virtual RGBColor getColor() const = 0; - - - /** @brief Tries to read given attribute assuming it is a PositionVector - * - * @param[in] attr The id of the attribute to read - * @return The read value if given and not empty; empty position vector if an error occurred - */ - virtual PositionVector getShape(int attr) const = 0; - - /** @brief Tries to read given attribute assuming it is a Boundary - * - * @param[in] attr The id of the attribute to read - * @return The read value if given and not empty; empty Boundary if an error occurred - */ - virtual Boundary getBoundary(int attr) const = 0; - - /** @brief Tries to read given attribute assuming it is a string vector - * - * The behavior is similar to Python's string.split(), so multiple consecutive - * whitespace do not generate empty strings and leading and trailing whitespace is silently omitted. - * - * @param[in] attr The id of the attribute to read - * @return The read value if given and not empty; empty vector if an error occurred - */ - const std::vector getStringVector(int attr) const; - - /// @brief convenience function to avoid the default argument and the template stuff at getOpt<> - const std::vector getOptStringVector(int attr, const char* objectid, bool& ok, bool report = true) const; - - /** @brief Tries to read given attribute assuming it is an int vector - * - * The behavior is similar to Python's string.split(), so multiple consecutive - * whitespace do not generate empty strings and leading and trailing whitespace is silently omitted. - * - * @param[in] attr The id of the attribute to read - * @return The read value if given and not empty; empty vector if an error occurred - */ - const std::vector getIntVector(int attr) const; - - /// @brief convenience function to avoid the default argument and the template stuff at getOpt<> - const std::vector getOptIntVector(int attr, const char* objectid, bool& ok, bool report = true) const; - //} - - - /** @brief Converts the given attribute id into a man readable string - * - * @param[in] attr The id of the attribute to return the name of - * @return The name of the described attribute - */ - virtual std::string getName(int attr) const = 0; - - - /** @brief Prints all attribute names and values into the given stream - * - * @param[in] os The stream to use - */ - virtual void serialize(std::ostream& os) const = 0; - - /** @brief Retrieves all attribute names - */ - virtual std::vector getAttributeNames() const = 0; - - - /// @brief return the objecttype to which these attributes belong - const std::string& getObjectType() const { - return myObjectType; - } - - - friend std::ostream& operator<<(std::ostream& os, const SUMOSAXAttributes& src); - - /// @brief return a new deep-copy attributes object - virtual SUMOSAXAttributes* clone() const = 0; - - /** @brief The encoding of parsed strings */ - static const std::string ENCODING; - - -protected: - template T getInternal(const int attr) const; - void emitUngivenError(const std::string& attrname, const char* objectid) const; - void emitEmptyError(const std::string& attrname, const char* objectid) const; - void emitFormatError(const std::string& attrname, const std::string& type, const char* objectid) const; - -private: - /// @brief Invalidated copy constructor. - SUMOSAXAttributes(const SUMOSAXAttributes& src); - - /// @brief Invalidated assignment operator. - SUMOSAXAttributes& operator=(const SUMOSAXAttributes& src); - - /// @brief the object type to use in error reporting - std::string myObjectType; - -}; - - -inline std::ostream& operator<<(std::ostream& os, const SUMOSAXAttributes& src) { - src.serialize(os); - return os; -} - - -template struct invalid_return { - static const X value; - static const std::string type; -}; - -template<> struct invalid_return { - static const bool value; - static const std::string type; -}; - -template<> struct invalid_return { - static const int value; - static const std::string type; -}; - -template<> struct invalid_return { - static const long long int value; - static const std::string type; -}; - -template<> struct invalid_return { - static const double value; - static const std::string type; -}; - -template<> struct invalid_return { - static const std::string value; - static const std::string type; -}; - -template<> struct invalid_return { - static const RGBColor value; - static const std::string type; -}; - -template<> struct invalid_return { - static const PositionVector value; - static const std::string type; -}; - -template<> struct invalid_return { - static const Boundary value; - static const std::string type; -}; - -template<> struct invalid_return > { - static const std::vector value; - static const std::string type; -}; - -template<> struct invalid_return > { - static const std::vector value; - static const std::string type; -}; - - -template -T SUMOSAXAttributes::get(int attr, const char* objectid, - bool& ok, bool report) const { - if (!hasAttribute(attr)) { - if (report) { - emitUngivenError(getName(attr), objectid); - } - ok = false; - return invalid_return::value; - } - try { - return getInternal(attr); - } catch (FormatException&) { - if (report) { - emitFormatError(getName(attr), "of type " + invalid_return::type, objectid); - } - } catch (EmptyData&) { - if (report) { - emitEmptyError(getName(attr), objectid); - } - } - ok = false; - return invalid_return::value; -} - - -template -T SUMOSAXAttributes::getOpt(int attr, const char* objectid, - bool& ok, T defaultValue, bool report) const { - if (!hasAttribute(attr)) { - return defaultValue; - } - try { - return getInternal(attr); - } catch (FormatException&) { - if (report) { - emitFormatError(getName(attr), "of type " + invalid_return::type, objectid); - } - } catch (EmptyData&) { - if (report) { - emitEmptyError(getName(attr), objectid); - } - } - ok = false; - return invalid_return::value; -} diff --git a/Util/OSM2ODR/src/utils/xml/SUMOSAXAttributesImpl_Cached.cpp b/Util/OSM2ODR/src/utils/xml/SUMOSAXAttributesImpl_Cached.cpp deleted file mode 100644 index 3db822f07..000000000 --- a/Util/OSM2ODR/src/utils/xml/SUMOSAXAttributesImpl_Cached.cpp +++ /dev/null @@ -1,267 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2002-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file SUMOSAXAttributesImpl_Cached.cpp -/// @author Jakob Erdmann -/// @date Dec 2016 -/// -// Encapsulated xml-attributes that use a map from string-attr-names to string-attr-values as backend -/****************************************************************************/ -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "SUMOSAXAttributesImpl_Cached.h" -#include "SUMOSAXAttributesImpl_Cached.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -SUMOSAXAttributesImpl_Cached::SUMOSAXAttributesImpl_Cached( - const std::map& attrs, - const std::vector& predefinedTagsMML, - const std::string& objectType) : - SUMOSAXAttributes(objectType), - myAttrs(attrs), - myPredefinedTagsMML(predefinedTagsMML) { } - - -SUMOSAXAttributesImpl_Cached::SUMOSAXAttributesImpl_Cached( - const std::map& attrs, - const std::vector& predefinedTagsMML, - const std::string& objectType) : - SUMOSAXAttributes(objectType), - myPredefinedTagsMML(predefinedTagsMML) { - // parse to - for (const auto& i : attrs) { - myAttrs[toString(i.first)] = i.second; - } -} - - -SUMOSAXAttributesImpl_Cached::~SUMOSAXAttributesImpl_Cached() { } - - -bool -SUMOSAXAttributesImpl_Cached::hasAttribute(int id) const { - assert(id >= 0); - assert(id < (int)myPredefinedTagsMML.size()); - return myAttrs.find(myPredefinedTagsMML[id]) != myAttrs.end(); -} - - -bool -SUMOSAXAttributesImpl_Cached::getBool(int id) const { - return StringUtils::toBool(getAttributeValueSecure(id)); -} - - -int -SUMOSAXAttributesImpl_Cached::getInt(int id) const { - return StringUtils::toInt(getAttributeValueSecure(id)); -} - - -long long int -SUMOSAXAttributesImpl_Cached::getLong(int id) const { - return StringUtils::toLong(getAttributeValueSecure(id)); -} - - -std::string -SUMOSAXAttributesImpl_Cached::getString(int id) const { - return getAttributeValueSecure(id); -} - - -std::string -SUMOSAXAttributesImpl_Cached::getStringSecure(int id, const std::string& str) const { - const std::string& result = getAttributeValueSecure(id); - return result.size() == 0 ? str : result; -} - - -double -SUMOSAXAttributesImpl_Cached::getFloat(int id) const { - return StringUtils::toDouble(getAttributeValueSecure(id)); -} - - -const std::string& -SUMOSAXAttributesImpl_Cached::getAttributeValueSecure(int id) const { - assert(id >= 0); - assert(id < (int)myPredefinedTagsMML.size()); - return myAttrs.find(myPredefinedTagsMML[id])->second; -} - - -double -SUMOSAXAttributesImpl_Cached::getFloat(const std::string& id) const { - return StringUtils::toDouble(myAttrs.find(id)->second); -} - - -bool -SUMOSAXAttributesImpl_Cached::hasAttribute(const std::string& id) const { - return myAttrs.find(id) != myAttrs.end(); -} - - -std::string -SUMOSAXAttributesImpl_Cached::getStringSecure(const std::string& id, - const std::string& str) const { - std::map::const_iterator it = myAttrs.find(id); - if (it != myAttrs.end() && it->second != "") { - return it->second; - } else { - return str; - } -} - - -SumoXMLEdgeFunc -SUMOSAXAttributesImpl_Cached::getEdgeFunc(bool& ok) const { - if (hasAttribute(SUMO_ATTR_FUNCTION)) { - std::string funcString = getString(SUMO_ATTR_FUNCTION); - if (SUMOXMLDefinitions::EdgeFunctions.hasString(funcString)) { - return SUMOXMLDefinitions::EdgeFunctions.get(funcString); - } - ok = false; - } - return SumoXMLEdgeFunc::NORMAL; -} - - -SumoXMLNodeType -SUMOSAXAttributesImpl_Cached::getNodeType(bool& ok) const { - if (hasAttribute(SUMO_ATTR_TYPE)) { - std::string typeString = getString(SUMO_ATTR_TYPE); - if (SUMOXMLDefinitions::NodeTypes.hasString(typeString)) { - return SUMOXMLDefinitions::NodeTypes.get(typeString); - } - ok = false; - } - return SumoXMLNodeType::UNKNOWN; -} - - -RightOfWay -SUMOSAXAttributesImpl_Cached::getRightOfWay(bool& ok) const { - if (hasAttribute(SUMO_ATTR_RIGHT_OF_WAY)) { - std::string rowString = getString(SUMO_ATTR_RIGHT_OF_WAY); - if (SUMOXMLDefinitions::RightOfWayValues.hasString(rowString)) { - return SUMOXMLDefinitions::RightOfWayValues.get(rowString); - } - ok = false; - } - return RightOfWay::DEFAULT; -} - -FringeType -SUMOSAXAttributesImpl_Cached::getFringeType(bool& ok) const { - if (hasAttribute(SUMO_ATTR_FRINGE)) { - std::string fringeString = getString(SUMO_ATTR_FRINGE); - if (SUMOXMLDefinitions::FringeTypeValues.hasString(fringeString)) { - return SUMOXMLDefinitions::FringeTypeValues.get(fringeString); - } - ok = false; - } - return FringeType::DEFAULT; -} - -RGBColor -SUMOSAXAttributesImpl_Cached::getColor() const { - return RGBColor::parseColor(getString(SUMO_ATTR_COLOR)); -} - - -PositionVector -SUMOSAXAttributesImpl_Cached::getShape(int attr) const { - StringTokenizer st(getString(attr)); - PositionVector shape; - while (st.hasNext()) { - StringTokenizer pos(st.next(), ","); - if (pos.size() != 2 && pos.size() != 3) { - throw FormatException("shape format"); - } - double x = StringUtils::toDouble(pos.next()); - double y = StringUtils::toDouble(pos.next()); - if (pos.size() == 2) { - shape.push_back(Position(x, y)); - } else { - double z = StringUtils::toDouble(pos.next()); - shape.push_back(Position(x, y, z)); - } - } - return shape; -} - - -Boundary -SUMOSAXAttributesImpl_Cached::getBoundary(int attr) const { - std::string def = getString(attr); - StringTokenizer st(def, ","); - if (st.size() != 4) { - throw FormatException("boundary format"); - } - const double xmin = StringUtils::toDouble(st.next()); - const double ymin = StringUtils::toDouble(st.next()); - const double xmax = StringUtils::toDouble(st.next()); - const double ymax = StringUtils::toDouble(st.next()); - return Boundary(xmin, ymin, xmax, ymax); -} - - -std::string -SUMOSAXAttributesImpl_Cached::getName(int attr) const { - assert(attr >= 0); - assert(attr < (int)myPredefinedTagsMML.size()); - return myPredefinedTagsMML[attr]; -} - - -void -SUMOSAXAttributesImpl_Cached::serialize(std::ostream& os) const { - for (std::map::const_iterator it = myAttrs.begin(); it != myAttrs.end(); ++it) { - os << " " << it->first; - os << "=\"" << it->second << "\""; - } -} - -std::vector -SUMOSAXAttributesImpl_Cached::getAttributeNames() const { - std::vector result; - for (std::map::const_iterator it = myAttrs.begin(); it != myAttrs.end(); ++it) { - result.push_back(it->first); - } - return result; -} - -SUMOSAXAttributes* -SUMOSAXAttributesImpl_Cached::clone() const { - return new SUMOSAXAttributesImpl_Cached(myAttrs, myPredefinedTagsMML, getObjectType()); -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/utils/xml/SUMOSAXAttributesImpl_Cached.h b/Util/OSM2ODR/src/utils/xml/SUMOSAXAttributesImpl_Cached.h deleted file mode 100644 index 5eb71f963..000000000 --- a/Util/OSM2ODR/src/utils/xml/SUMOSAXAttributesImpl_Cached.h +++ /dev/null @@ -1,294 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2007-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file SUMOSAXAttributesImpl_Cached.h -/// @author Jakob Erdmann -/// @date Dec 2016 -/// -// Encapsulated xml-attributes that use a map from string-attr-names to string-attr-values as backend -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include -#include -#include -#include -#include "SUMOSAXAttributes.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class SUMOSAXAttributesImpl_Cached - * @brief Encapsulated Xerces-SAX-attributes - * - * @see SUMOSAXAttributes - */ -class SUMOSAXAttributesImpl_Cached : public SUMOSAXAttributes { -public: - /** @brief Constructor - * - * @param[in] attrs The encapsulated xerces-attributes (string-string) - * @param[in] predefinedTagsMML Map of attribute ids to their (readable) string-representation - * @param[in] objectType object type in string format - */ - SUMOSAXAttributesImpl_Cached(const std::map& attrs, - const std::vector& predefinedTagsMML, - const std::string& objectType); - - /** @brief Constructor - * - * @param[in] attrs The encapsulated xerces-attributes (SumoXMLAttr-string) - * @param[in] predefinedTagsMML Map of attribute ids to their (readable) string-representation - * @param[in] objectType object type in string format - */ - SUMOSAXAttributesImpl_Cached(const std::map& attrs, - const std::vector& predefinedTagsMML, - const std::string& objectType); - - /// @brief Destructor - ~SUMOSAXAttributesImpl_Cached(); - - /// @name methods for retrieving attribute values - /// @{ - - /** @brief Returns the information whether the named (by its enum-value) attribute is within the current list - * - * @param[in] id The id of the searched attribute - * @return Whether the attribute is within the attributes - */ - bool hasAttribute(int id) const; - - /** - * @brief Returns the bool-value of the named (by its enum-value) attribute - * - * Tries to retrieve the attribute from the the attribute list. The retrieved - * attribute (which may be 0) is then parsed using TplConvert::_2bool. - * If the attribute is empty or ==0, TplConvert::_2bool throws an - * EmptyData-exception which is passed. - * If the value can not be parsed to a bool, TplConvert::_2bool throws a - * BoolFormatException-exception which is passed. - * - * @param[in] id The id of the attribute to return the value of - * @return The attribute's value as a bool, if it could be read and parsed - * @exception EmptyData If the attribute is not known or the attribute value is an empty string - * @exception BoolFormatException If the attribute value can not be parsed to a bool - */ - bool getBool(int id) const; - - /** - * @brief Returns the int-value of the named (by its enum-value) attribute - * - * Tries to retrieve the attribute from the the attribute list. The retrieved - * attribute (which may be 0) is then parsed using TplConvert::_2int. - * If the attribute is empty or ==0, TplConvert::_2int throws an - * EmptyData-exception which is passed. - * If the value can not be parsed to an int, TplConvert::_2int throws a - * NumberFormatException-exception which is passed. - * - * @param[in] id The id of the attribute to return the value of - * @return The attribute's value as an int, if it could be read and parsed - * @exception EmptyData If the attribute is not known or the attribute value is an empty string - * @exception NumberFormatException If the attribute value can not be parsed to an int - */ - int getInt(int id) const; - - /** - * @brief Returns the long-value of the named (by its enum-value) attribute - * - * Tries to retrieve the attribute from the the attribute list. The retrieved - * attribute (which may be 0) is then parsed using TplConvert::_2long. - * If the attribute is empty or ==0, TplConvert::_2long throws an - * EmptyData-exception which is passed. - * If the value can not be parsed to a long, TplConvert::_2long throws a - * NumberFormatException-exception which is passed. - * - * @param[in] id The id of the attribute to return the value of - * @return The attribute's value as an int, if it could be read and parsed - * @exception EmptyData If the attribute is not known or the attribute value is an empty string - * @exception NumberFormatException If the attribute value can not be parsed to an int - */ - long long int getLong(int id) const; - - /** - * @brief Returns the string-value of the named (by its enum-value) attribute - * - * Tries to retrieve the attribute from the the attribute list. The retrieved - * attribute (which may be 0) is then parsed using TplConvert::_2str. - * If the attribute is ==0, TplConvert::_2str throws an - * EmptyData-exception which is passed. - * - * @param[in] id The id of the attribute to return the value of - * @return The attribute's value as a string, if it could be read and parsed - * @exception EmptyData If the attribute is not known or the attribute value is an empty string - */ - std::string getString(int id) const; - - /** - * @brief Returns the string-value of the named (by its enum-value) attribute - * - * Tries to retrieve the attribute from the the attribute list. The retrieved - * attribute (which may be 0) is then parsed using TplConvert::_2strSec. - * If the attribute is ==0, TplConvert::_2strSec returns the default value. - * - * @param[in] id The id of the attribute to return the value of - * @param[in] def The default value to return if the attribute is not in attributes - * @return The attribute's value as a string, if it could be read and parsed - * @exception EmptyData If the attribute is not known or the attribute value is an empty string - */ - std::string getStringSecure(int id, const std::string& def) const; - - /** - * @brief Returns the double-value of the named (by its enum-value) attribute - * - * Tries to retrieve the attribute from the the attribute list. The retrieved - * attribute (which may be 0) is then parsed using TplConvert::_2double. - * If the attribute is empty or ==0, TplConvert::_2double throws an - * EmptyData-exception which is passed. - * If the value can not be parsed to a double, TplConvert::_2double throws a - * NumberFormatException-exception which is passed. - * - * @param[in] id The id of the attribute to return the value of - * @return The attribute's value as a float, if it could be read and parsed - * @exception EmptyData If the attribute is not known or the attribute value is an empty string - * @exception NumberFormatException If the attribute value can not be parsed to an double - */ - double getFloat(int id) const; - - /// @brief Returns the information whether the named attribute is within the current list - bool hasAttribute(const std::string& id) const; - - /** - * @brief Returns the double-value of the named attribute - * - * Tries to retrieve the attribute from the the attribute list. The retrieved - * attribute (which may be 0) is then parsed using TplConvert::_2double. - * If the attribute is empty or ==0, TplConvert::_2double throws an - * EmptyData-exception which is passed. - * If the value can not be parsed to a double, TplConvert::_2double throws a - * NumberFormatException-exception which is passed. - * - * @param[in] id The name of the attribute to return the value of - * @return The attribute's value as a float, if it could be read and parsed - * @exception EmptyData If the attribute is not known or the attribute value is an empty string - * @exception NumberFormatException If the attribute value can not be parsed to an double - */ - double getFloat(const std::string& id) const; - - /** - * @brief Returns the string-value of the named (by its enum-value) attribute - * - * Tries to retrieve the attribute from the the attribute list. - * If the attribute is ==0, TplConvert::_2strSec returns the default value. - * @param[in] id The name of the attribute to return the value of - * @param[in] def The default value to return if the attribute is not in attributes - * @return The attribute's value as a string, if it could be read and parsed - */ - std::string getStringSecure(const std::string& id, - const std::string& def) const; - /// @} - - /** - * @brief Returns the value of the named attribute - * - * Tries to retrieve the attribute from the the attribute list. - * @return The attribute's value as a SumoXMLEdgeFunc, if it could be read and parsed - */ - SumoXMLEdgeFunc getEdgeFunc(bool& ok) const; - - /** - * @brief Returns the value of the named attribute - * - * Tries to retrieve the attribute from the the attribute list. - * @return The attribute's value as a SumoXMLNodeType, if it could be read and parsed - */ - SumoXMLNodeType getNodeType(bool& ok) const; - - /// @brief returns rightOfWay method - RightOfWay getRightOfWay(bool& ok) const; - - /// @brief returns fringe type - FringeType getFringeType(bool& ok) const; - - /** - * @brief Returns the value of the named attribute - * - * Tries to retrieve the attribute from the the attribute list. - * @return The attribute's value as a RGBColor, if it could be read and parsed - */ - RGBColor getColor() const; - - - /** @brief Tries to read given attribute assuming it is a PositionVector - * - * @param[in] attr The id of the attribute to read - * @return The read value if given and not empty; "" if an error occurred - */ - PositionVector getShape(int attr) const; - - /** @brief Tries to read given attribute assuming it is a Boundary - * - * @param[in] attr The id of the attribute to read - * @return The read value if given and not empty; "" if an error occurred - */ - Boundary getBoundary(int attr) const; - - /** @brief Converts the given attribute id into a man readable string - * - * Returns a "?" if the attribute is not known. - * - * @param[in] attr The id of the attribute to return the name of - * @return The name of the described attribute - */ - std::string getName(int attr) const; - - /** @brief Prints all attribute names and values into the given stream - * - * @param[in] os The stream to use - */ - void serialize(std::ostream& os) const; - - /** @brief Retrieves all attribute names - */ - std::vector getAttributeNames() const; - - /// @brief return a new deep-copy attributes object - SUMOSAXAttributes* clone() const; - -private: - /** @brief Returns Xerces-value of the named attribute - * - * It is assumed that this attribute is within the stored attributes. - * @param[in] id The id of the attribute to retrieve the vale of - * @return The xerces-value of the attribute - */ - const std::string& getAttributeValueSecure(int id) const; - -private: - /// @brief The encapsulated attributes - std::map myAttrs; - - /// @brief Map of attribute ids to their (readable) string-representation - const std::vector& myPredefinedTagsMML; - -private: - /// @brief Invalidated copy constructor. - SUMOSAXAttributesImpl_Cached(const SUMOSAXAttributesImpl_Cached& src) = delete; - - /// @brief Invalidated assignment operator. - SUMOSAXAttributesImpl_Cached& operator=(const SUMOSAXAttributesImpl_Cached& src) = delete; -}; diff --git a/Util/OSM2ODR/src/utils/xml/SUMOSAXAttributesImpl_Xerces.cpp b/Util/OSM2ODR/src/utils/xml/SUMOSAXAttributesImpl_Xerces.cpp deleted file mode 100644 index 50ca04421..000000000 --- a/Util/OSM2ODR/src/utils/xml/SUMOSAXAttributesImpl_Xerces.cpp +++ /dev/null @@ -1,274 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2002-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file SUMOSAXAttributesImpl_Xerces.cpp -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date Sept 2002 -/// -// Encapsulated Xerces-SAX-attributes -/****************************************************************************/ -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "XMLSubSys.h" -#include "SUMOSAXAttributesImpl_Xerces.h" -#include "SUMOSAXAttributesImpl_Cached.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -SUMOSAXAttributesImpl_Xerces::SUMOSAXAttributesImpl_Xerces(const XERCES_CPP_NAMESPACE::Attributes& attrs, - const std::vector& predefinedTags, - const std::vector& predefinedTagsMML, - const std::string& objectType) : - SUMOSAXAttributes(objectType), - myAttrs(attrs), - myPredefinedTags(predefinedTags), - myPredefinedTagsMML(predefinedTagsMML) { } - - -SUMOSAXAttributesImpl_Xerces::~SUMOSAXAttributesImpl_Xerces() { -} - - -bool -SUMOSAXAttributesImpl_Xerces::hasAttribute(int id) const { - assert(id >= 0); - assert(id < (int)myPredefinedTags.size()); - return myAttrs.getIndex(myPredefinedTags[id]) >= 0; -} - - -bool -SUMOSAXAttributesImpl_Xerces::getBool(int id) const { - return StringUtils::toBool(getString(id)); -} - - -int -SUMOSAXAttributesImpl_Xerces::getInt(int id) const { - return StringUtils::toInt(getString(id)); -} - - -long long int -SUMOSAXAttributesImpl_Xerces::getLong(int id) const { - return StringUtils::toLong(getString(id)); -} - - -std::string -SUMOSAXAttributesImpl_Xerces::getString(int id) const { - return StringUtils::transcode(getAttributeValueSecure(id)); -} - - -std::string -SUMOSAXAttributesImpl_Xerces::getStringSecure(int id, const std::string& str) const { - const XMLCh* utf16 = getAttributeValueSecure(id); - if (XERCES_CPP_NAMESPACE::XMLString::stringLen(utf16) == 0) { - // TranscodeToStr and debug_new interact badly in this case; - return str; - } else { - return getString(id); - } -} - - -double -SUMOSAXAttributesImpl_Xerces::getFloat(int id) const { - return StringUtils::toDouble(getString(id)); -} - - -const XMLCh* -SUMOSAXAttributesImpl_Xerces::getAttributeValueSecure(int id) const { - assert(id >= 0); - assert(id < (int)myPredefinedTags.size()); - return myAttrs.getValue(myPredefinedTags[id]); -} - - -double -SUMOSAXAttributesImpl_Xerces::getFloat(const std::string& id) const { - XMLCh* t = XERCES_CPP_NAMESPACE::XMLString::transcode(id.c_str()); - const std::string utf8 = StringUtils::transcode(myAttrs.getValue(t)); - XERCES_CPP_NAMESPACE::XMLString::release(&t); - return StringUtils::toDouble(utf8); -} - - -bool -SUMOSAXAttributesImpl_Xerces::hasAttribute(const std::string& id) const { - XMLCh* t = XERCES_CPP_NAMESPACE::XMLString::transcode(id.c_str()); - bool result = myAttrs.getIndex(t) >= 0; - XERCES_CPP_NAMESPACE::XMLString::release(&t); - return result; -} - - -std::string -SUMOSAXAttributesImpl_Xerces::getStringSecure(const std::string& id, - const std::string& str) const { - XMLCh* t = XERCES_CPP_NAMESPACE::XMLString::transcode(id.c_str()); - const XMLCh* v = myAttrs.getValue(t); - XERCES_CPP_NAMESPACE::XMLString::release(&t); - if (v == nullptr) { - return str; - } else { - return StringUtils::transcode(v); - } -} - - -SumoXMLEdgeFunc -SUMOSAXAttributesImpl_Xerces::getEdgeFunc(bool& ok) const { - if (hasAttribute(SUMO_ATTR_FUNCTION)) { - std::string funcString = getString(SUMO_ATTR_FUNCTION); - if (SUMOXMLDefinitions::EdgeFunctions.hasString(funcString)) { - return SUMOXMLDefinitions::EdgeFunctions.get(funcString); - } - ok = false; - } - return SumoXMLEdgeFunc::NORMAL; -} - - -SumoXMLNodeType -SUMOSAXAttributesImpl_Xerces::getNodeType(bool& ok) const { - if (hasAttribute(SUMO_ATTR_TYPE)) { - std::string typeString = getString(SUMO_ATTR_TYPE); - if (SUMOXMLDefinitions::NodeTypes.hasString(typeString)) { - return SUMOXMLDefinitions::NodeTypes.get(typeString); - } - ok = false; - } - return SumoXMLNodeType::UNKNOWN; -} - -RightOfWay -SUMOSAXAttributesImpl_Xerces::getRightOfWay(bool& ok) const { - if (hasAttribute(SUMO_ATTR_RIGHT_OF_WAY)) { - std::string rowString = getString(SUMO_ATTR_RIGHT_OF_WAY); - if (SUMOXMLDefinitions::RightOfWayValues.hasString(rowString)) { - return SUMOXMLDefinitions::RightOfWayValues.get(rowString); - } - ok = false; - } - return RightOfWay::DEFAULT; -} - -FringeType -SUMOSAXAttributesImpl_Xerces::getFringeType(bool& ok) const { - if (hasAttribute(SUMO_ATTR_FRINGE)) { - std::string fringeString = getString(SUMO_ATTR_FRINGE); - if (SUMOXMLDefinitions::FringeTypeValues.hasString(fringeString)) { - return SUMOXMLDefinitions::FringeTypeValues.get(fringeString); - } - ok = false; - } - return FringeType::DEFAULT; -} - -RGBColor -SUMOSAXAttributesImpl_Xerces::getColor() const { - return RGBColor::parseColor(getString(SUMO_ATTR_COLOR)); -} - - -PositionVector -SUMOSAXAttributesImpl_Xerces::getShape(int attr) const { - StringTokenizer st(getString(attr)); - PositionVector shape; - while (st.hasNext()) { - StringTokenizer pos(st.next(), ","); - if (pos.size() != 2 && pos.size() != 3) { - throw FormatException("shape format"); - } - double x = StringUtils::toDouble(pos.next()); - double y = StringUtils::toDouble(pos.next()); - if (pos.size() == 2) { - shape.push_back(Position(x, y)); - } else { - double z = StringUtils::toDouble(pos.next()); - shape.push_back(Position(x, y, z)); - } - } - return shape; -} - - -Boundary -SUMOSAXAttributesImpl_Xerces::getBoundary(int attr) const { - std::string def = getString(attr); - StringTokenizer st(def, ","); - if (st.size() != 4) { - throw FormatException("boundary format"); - } - const double xmin = StringUtils::toDouble(st.next()); - const double ymin = StringUtils::toDouble(st.next()); - const double xmax = StringUtils::toDouble(st.next()); - const double ymax = StringUtils::toDouble(st.next()); - return Boundary(xmin, ymin, xmax, ymax); -} - - -std::string -SUMOSAXAttributesImpl_Xerces::getName(int attr) const { - assert(attr >= 0); - assert(attr < (int)myPredefinedTagsMML.size()); - return myPredefinedTagsMML[attr]; -} - - -void -SUMOSAXAttributesImpl_Xerces::serialize(std::ostream& os) const { - for (int i = 0; i < (int)myAttrs.getLength(); ++i) { - os << " " << StringUtils::transcode(myAttrs.getLocalName(i)); - os << "=\"" << StringUtils::transcode(myAttrs.getValue(i)) << "\""; - } -} - - -std::vector -SUMOSAXAttributesImpl_Xerces::getAttributeNames() const { - std::vector result; - for (int i = 0; i < (int)myAttrs.getLength(); ++i) { - result.push_back(StringUtils::transcode(myAttrs.getLocalName(i))); - } - return result; -} - - -SUMOSAXAttributes* -SUMOSAXAttributesImpl_Xerces::clone() const { - std::map attrs; - for (int i = 0; i < (int)myAttrs.getLength(); ++i) { - attrs[StringUtils::transcode(myAttrs.getLocalName(i))] = StringUtils::transcode(myAttrs.getValue(i)); - } - return new SUMOSAXAttributesImpl_Cached(attrs, myPredefinedTagsMML, getObjectType()); -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/utils/xml/SUMOSAXAttributesImpl_Xerces.h b/Util/OSM2ODR/src/utils/xml/SUMOSAXAttributesImpl_Xerces.h deleted file mode 100644 index a51f7d176..000000000 --- a/Util/OSM2ODR/src/utils/xml/SUMOSAXAttributesImpl_Xerces.h +++ /dev/null @@ -1,314 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2007-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file SUMOSAXAttributesImpl_Xerces.h -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date Fri, 30 Mar 2007 -/// -// Encapsulated Xerces-SAX-attributes -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include -#include -#include -#include -#include "SUMOSAXAttributes.h" - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class SUMOSAXAttributesImpl_Xerces - * @brief Encapsulated Xerces-SAX-attributes - * - * @see SUMOSAXAttributes - */ -class SUMOSAXAttributesImpl_Xerces : public SUMOSAXAttributes { -public: - /** @brief Constructor - * - * @param[in] attrs The encapsulated xerces-attributes - * @param[in] predefinedTags Map of attribute ids to their xerces-representation - * @param[in] predefinedTagsMML Map of attribute ids to their (readable) string-representation - */ - SUMOSAXAttributesImpl_Xerces(const XERCES_CPP_NAMESPACE::Attributes& attrs, - const std::vector& predefinedTags, - const std::vector& predefinedTagsMML, - const std::string& objectType); - - - /// @brief Destructor - virtual ~SUMOSAXAttributesImpl_Xerces(); - - - - - /// @name methods for retrieving attribute values - /// @{ - - /** @brief Returns the information whether the named (by its enum-value) attribute is within the current list - * - * @param[in] id The id of the searched attribute - * @return Whether the attribute is within the attributes - */ - bool hasAttribute(int id) const; - - - /** - * @brief Returns the bool-value of the named (by its enum-value) attribute - * - * Tries to retrieve the attribute from the the attribute list. The retrieved - * attribute (which may be 0) is then parsed using TplConvert::_2bool. - * If the attribute is empty or ==0, TplConvert::_2bool throws an - * EmptyData-exception which is passed. - * If the value can not be parsed to a bool, TplConvert::_2bool throws a - * BoolFormatException-exception which is passed. - * - * @param[in] id The id of the attribute to return the value of - * @return The attribute's value as a bool, if it could be read and parsed - * @exception EmptyData If the attribute is not known or the attribute value is an empty string - * @exception BoolFormatException If the attribute value can not be parsed to a bool - */ - bool getBool(int id) const; - - - /** - * @brief Returns the int-value of the named (by its enum-value) attribute - * - * Tries to retrieve the attribute from the the attribute list. The retrieved - * attribute (which may be 0) is then parsed using TplConvert::_2int. - * If the attribute is empty or ==0, TplConvert::_2int throws an - * EmptyData-exception which is passed. - * If the value can not be parsed to an int, TplConvert::_2int throws a - * NumberFormatException-exception which is passed. - * - * @param[in] id The id of the attribute to return the value of - * @return The attribute's value as an int, if it could be read and parsed - * @exception EmptyData If the attribute is not known or the attribute value is an empty string - * @exception NumberFormatException If the attribute value can not be parsed to an int - */ - int getInt(int id) const; - - - /** - * @brief Returns the long-value of the named (by its enum-value) attribute - * - * Tries to retrieve the attribute from the the attribute list. The retrieved - * attribute (which may be 0) is then parsed using TplConvert::_2long. - * If the attribute is empty or ==0, TplConvert::_2long throws an - * EmptyData-exception which is passed. - * If the value can not be parsed to a long, TplConvert::_2long throws a - * NumberFormatException-exception which is passed. - * - * @param[in] id The id of the attribute to return the value of - * @return The attribute's value as an int, if it could be read and parsed - * @exception EmptyData If the attribute is not known or the attribute value is an empty string - * @exception NumberFormatException If the attribute value can not be parsed to an int - */ - long long int getLong(int id) const; - - - /** - * @brief Returns the string-value of the named (by its enum-value) attribute - * - * Tries to retrieve the attribute from the the attribute list. The retrieved - * attribute (which may be 0) is then parsed using TplConvert::_2str. - * If the attribute is ==0, TplConvert::_2str throws an - * EmptyData-exception which is passed. - * - * @param[in] id The id of the attribute to return the value of - * @return The attribute's value as a string, if it could be read and parsed - * @exception EmptyData If the attribute is not known or the attribute value is an empty string - */ - std::string getString(int id) const; - - /** - * @brief Returns the string-value of the named (by its enum-value) attribute - * - * Tries to retrieve the attribute from the the attribute list. The retrieved - * attribute (which may be 0) is then parsed using TplConvert::_2strSec. - * If the attribute is ==0, TplConvert::_2strSec returns the default value. - * - * @param[in] id The id of the attribute to return the value of - * @param[in] def The default value to return if the attribute is not in attributes - * @return The attribute's value as a string, if it could be read and parsed - * @exception EmptyData If the attribute is not known or the attribute value is an empty string - */ - std::string getStringSecure(int id, - const std::string& def) const; - - - /** - * @brief Returns the double-value of the named (by its enum-value) attribute - * - * Tries to retrieve the attribute from the the attribute list. The retrieved - * attribute (which may be 0) is then parsed using TplConvert::_2double. - * If the attribute is empty or ==0, TplConvert::_2double throws an - * EmptyData-exception which is passed. - * If the value can not be parsed to a double, TplConvert::_2double throws a - * NumberFormatException-exception which is passed. - * - * @param[in] id The id of the attribute to return the value of - * @return The attribute's value as a float, if it could be read and parsed - * @exception EmptyData If the attribute is not known or the attribute value is an empty string - * @exception NumberFormatException If the attribute value can not be parsed to an double - */ - double getFloat(int id) const; - - - /** - * @brief Returns the information whether the named attribute is within the current list - */ - bool hasAttribute(const std::string& id) const; - - - /** - * @brief Returns the double-value of the named attribute - * - * Tries to retrieve the attribute from the the attribute list. The retrieved - * attribute (which may be 0) is then parsed using TplConvert::_2double. - * If the attribute is empty or ==0, TplConvert::_2double throws an - * EmptyData-exception which is passed. - * If the value can not be parsed to a double, TplConvert::_2double throws a - * NumberFormatException-exception which is passed. - * - * @param[in] id The name of the attribute to return the value of - * @return The attribute's value as a float, if it could be read and parsed - * @exception EmptyData If the attribute is not known or the attribute value is an empty string - * @exception NumberFormatException If the attribute value can not be parsed to an double - */ - double getFloat(const std::string& id) const; - - - /** - * @brief Returns the string-value of the named (by its enum-value) attribute - * - * Tries to retrieve the attribute from the the attribute list. - * If the attribute is ==0, TplConvert::_2strSec returns the default value. - * @param[in] id The name of the attribute to return the value of - * @param[in] def The default value to return if the attribute is not in attributes - * @return The attribute's value as a string, if it could be read and parsed - */ - std::string getStringSecure(const std::string& id, - const std::string& def) const; - //} - - - /** - * @brief Returns the value of the named attribute - * - * Tries to retrieve the attribute from the the attribute list. - * @return The attribute's value as a SumoXMLEdgeFunc, if it could be read and parsed - */ - SumoXMLEdgeFunc getEdgeFunc(bool& ok) const; - - - /** - * @brief Returns the value of the named attribute - * - * Tries to retrieve the attribute from the the attribute list. - * @return The attribute's value as a SumoXMLNodeType, if it could be read and parsed - */ - SumoXMLNodeType getNodeType(bool& ok) const; - - /// @brief returns rightOfWay method - RightOfWay getRightOfWay(bool& ok) const; - - /// @brief returns fringe type - FringeType getFringeType(bool& ok) const; - - /** - * @brief Returns the value of the named attribute - * - * Tries to retrieve the attribute from the the attribute list. - * @return The attribute's value as a RGBColor, if it could be read and parsed - */ - RGBColor getColor() const; - - - /** @brief Tries to read given attribute assuming it is a PositionVector - * - * @param[in] attr The id of the attribute to read - * @return The read value if given and not empty; "" if an error occurred - */ - PositionVector getShape(int attr) const; - - - /** @brief Tries to read given attribute assuming it is a Boundary - * - * @param[in] attr The id of the attribute to read - * @return The read value if given and not empty; "" if an error occurred - */ - Boundary getBoundary(int attr) const; - - /** @brief Converts the given attribute id into a man readable string - * - * Returns a "?" if the attribute is not known. - * - * @param[in] attr The id of the attribute to return the name of - * @return The name of the described attribute - */ - std::string getName(int attr) const; - - - /** @brief Prints all attribute names and values into the given stream - * - * @param[in] os The stream to use - */ - void serialize(std::ostream& os) const; - - /** @brief Retrieves all attribute names - */ - std::vector getAttributeNames() const; - - /// @brief return a new deep-copy attributes object - SUMOSAXAttributes* clone() const; - -private: - /** @brief Returns Xerces-value of the named attribute - * - * It is assumed that this attribute is within the stored attributes. - * @param[in] id The id of the attribute to retrieve the vale of - * @return The xerces-value of the attribute - */ - const XMLCh* getAttributeValueSecure(int id) const; - - -private: - /// @brief The encapsulated attributes - const XERCES_CPP_NAMESPACE::Attributes& myAttrs; - - /// @brief Definition of a map of attribute ids to their xerces-representation - typedef std::vector AttrMap; - /// @brief Map of attribute ids to their xerces-representation - const AttrMap& myPredefinedTags; - - /// @brief Map of attribute ids to their (readable) string-representation - const std::vector& myPredefinedTagsMML; - -private: - /// @brief Invalidated copy constructor. - SUMOSAXAttributesImpl_Xerces(const SUMOSAXAttributesImpl_Xerces& src); - - /// @brief Invalidated assignment operator. - SUMOSAXAttributesImpl_Xerces& operator=(const SUMOSAXAttributesImpl_Xerces& src); - - -}; diff --git a/Util/OSM2ODR/src/utils/xml/SUMOSAXHandler.cpp b/Util/OSM2ODR/src/utils/xml/SUMOSAXHandler.cpp deleted file mode 100644 index 426699487..000000000 --- a/Util/OSM2ODR/src/utils/xml/SUMOSAXHandler.cpp +++ /dev/null @@ -1,42 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2002-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file SUMOSAXHandler.cpp -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date Sept 2002 -/// -// SAX-handler base for SUMO-files -/****************************************************************************/ -#include - -#include -#include -#include -#include "SUMOXMLDefinitions.h" -#include "SUMOSAXHandler.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -SUMOSAXHandler::SUMOSAXHandler(const std::string& file, const std::string& expectedRoot) - : GenericSAXHandler(SUMOXMLDefinitions::tags, SUMO_TAG_NOTHING, - SUMOXMLDefinitions::attrs, SUMO_ATTR_NOTHING, file, expectedRoot) {} - - -SUMOSAXHandler::~SUMOSAXHandler() {} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/utils/xml/SUMOSAXHandler.h b/Util/OSM2ODR/src/utils/xml/SUMOSAXHandler.h deleted file mode 100644 index 062bfb9dd..000000000 --- a/Util/OSM2ODR/src/utils/xml/SUMOSAXHandler.h +++ /dev/null @@ -1,60 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2002-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file SUMOSAXHandler.h -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date Sept 2002 -/// -// SAX-handler base for SUMO-files -/****************************************************************************/ -#pragma once -#include - -#include -#include - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class SUMOSAXHandler - * @brief SAX-handler base for SUMO-files - * - * This class is a GenericSAXHandler which knows all tags SUMO uses, so all - * SUMO-XML - loading classes should be derived from it. - */ -class SUMOSAXHandler : public GenericSAXHandler { -public: - /** - * @brief Constructor - * - * @param[in] file The name of the processed file - */ - SUMOSAXHandler(const std::string& file = "", const std::string& expectedRoot = ""); - - - /// Destructor - virtual ~SUMOSAXHandler(); - - -private: - /// @brief invalidated copy constructor - SUMOSAXHandler(const SUMOSAXHandler& s); - - /// @brief invalidated assignment operator - const SUMOSAXHandler& operator=(const SUMOSAXHandler& s); - -}; diff --git a/Util/OSM2ODR/src/utils/xml/SUMOSAXReader.cpp b/Util/OSM2ODR/src/utils/xml/SUMOSAXReader.cpp deleted file mode 100644 index 907b96e41..000000000 --- a/Util/OSM2ODR/src/utils/xml/SUMOSAXReader.cpp +++ /dev/null @@ -1,205 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2012-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file SUMOSAXReader.cpp -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date Nov 2012 -/// -// SAX-reader encapsulation containing binary reader -/****************************************************************************/ -#include - -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include "GenericSAXHandler.h" -#ifdef HAVE_ZLIB -#include -#endif -#include "IStreamInputSource.h" -#include "SUMOSAXReader.h" - - -// =========================================================================== -// method definitions -// =========================================================================== -SUMOSAXReader::SUMOSAXReader(GenericSAXHandler& handler, const XERCES_CPP_NAMESPACE::SAX2XMLReader::ValSchemes validationScheme) - : myHandler(nullptr), myValidationScheme(validationScheme), myXMLReader(nullptr), myIStream(nullptr), myInputStream(nullptr) { - setHandler(handler); -} - - -SUMOSAXReader::~SUMOSAXReader() { - delete myXMLReader; -} - - -void -SUMOSAXReader::setHandler(GenericSAXHandler& handler) { - myHandler = &handler; - mySchemaResolver.setHandler(handler); - if (myXMLReader != nullptr) { - myXMLReader->setContentHandler(&handler); - myXMLReader->setErrorHandler(&handler); - } -} - - -void -SUMOSAXReader::setValidation(const XERCES_CPP_NAMESPACE::SAX2XMLReader::ValSchemes validationScheme) { - if (myXMLReader != nullptr && validationScheme != myValidationScheme) { - if (validationScheme == XERCES_CPP_NAMESPACE::SAX2XMLReader::Val_Never) { - myXMLReader->setEntityResolver(nullptr); - myXMLReader->setProperty(XERCES_CPP_NAMESPACE::XMLUni::fgXercesScannerName, (void*)XERCES_CPP_NAMESPACE::XMLUni::fgWFXMLScanner); - } else { - myXMLReader->setEntityResolver(&mySchemaResolver); - myXMLReader->setProperty(XERCES_CPP_NAMESPACE::XMLUni::fgXercesScannerName, (void*)XERCES_CPP_NAMESPACE::XMLUni::fgIGXMLScanner); - myXMLReader->setFeature(XERCES_CPP_NAMESPACE::XMLUni::fgXercesSchema, true); - myXMLReader->setFeature(XERCES_CPP_NAMESPACE::XMLUni::fgSAX2CoreValidation, true); - myXMLReader->setFeature(XERCES_CPP_NAMESPACE::XMLUni::fgXercesDynamic, validationScheme == XERCES_CPP_NAMESPACE::SAX2XMLReader::Val_Auto); - } - } - myValidationScheme = validationScheme; -} - - -void -SUMOSAXReader::parse(std::string systemID) { - if (myXMLReader == nullptr) { - myXMLReader = getSAXReader(); - } - if (!FileHelpers::isReadable(systemID)) { - throw ProcessError("Cannot read file '" + systemID + "'!"); - } - if (FileHelpers::isDirectory(systemID)) { - throw ProcessError("File '" + systemID + "' is a directory!"); - } -#ifdef HAVE_ZLIB - zstr::ifstream istream(systemID.c_str(), std::fstream::in | std::fstream::binary); - myXMLReader->parse(IStreamInputSource(istream)); -#else - myXMLReader->parse(systemID.c_str()); -#endif -} - - -void -SUMOSAXReader::parseString(std::string content) { - if (myXMLReader == nullptr) { - myXMLReader = getSAXReader(); - } - XERCES_CPP_NAMESPACE::MemBufInputSource memBufIS((const XMLByte*)content.c_str(), content.size(), "registrySettings"); - myXMLReader->parse(memBufIS); -} - - -bool -SUMOSAXReader::parseFirst(std::string systemID) { - if (!FileHelpers::isReadable(systemID)) { - throw ProcessError("Cannot read file '" + systemID + "'!"); - } - if (myXMLReader == nullptr) { - myXMLReader = getSAXReader(); - } - myToken = XERCES_CPP_NAMESPACE::XMLPScanToken(); -#ifdef HAVE_ZLIB - myIStream = std::unique_ptr(new zstr::ifstream(systemID.c_str(), std::fstream::in | std::fstream::binary)); - myInputStream = std::unique_ptr(new IStreamInputSource(*myIStream)); - return myXMLReader->parseFirst(*myInputStream, myToken); -#else - return myXMLReader->parseFirst(systemID.c_str(), myToken); -#endif -} - - -bool -SUMOSAXReader::parseNext() { - if (myXMLReader == nullptr) { - throw ProcessError("The XML-parser was not initialized."); - } - return myXMLReader->parseNext(myToken); -} - - -XERCES_CPP_NAMESPACE::SAX2XMLReader* -SUMOSAXReader::getSAXReader() { - XERCES_CPP_NAMESPACE::SAX2XMLReader* reader = XERCES_CPP_NAMESPACE::XMLReaderFactory::createXMLReader(); - if (reader == nullptr) { - throw ProcessError("The XML-parser could not be build."); - } - // see here https://svn.apache.org/repos/asf/xerces/c/trunk/samples/src/SAX2Count/SAX2Count.cpp for the way to set features - if (myValidationScheme == XERCES_CPP_NAMESPACE::SAX2XMLReader::Val_Never) { - reader->setProperty(XERCES_CPP_NAMESPACE::XMLUni::fgXercesScannerName, (void*)XERCES_CPP_NAMESPACE::XMLUni::fgWFXMLScanner); - } else { - reader->setEntityResolver(&mySchemaResolver); - reader->setFeature(XERCES_CPP_NAMESPACE::XMLUni::fgXercesSchema, true); - reader->setFeature(XERCES_CPP_NAMESPACE::XMLUni::fgSAX2CoreValidation, true); - reader->setFeature(XERCES_CPP_NAMESPACE::XMLUni::fgXercesDynamic, myValidationScheme == XERCES_CPP_NAMESPACE::SAX2XMLReader::Val_Auto); - } - reader->setContentHandler(myHandler); - reader->setErrorHandler(myHandler); - return reader; -} - - -XERCES_CPP_NAMESPACE::InputSource* -SUMOSAXReader::LocalSchemaResolver::resolveEntity(const XMLCh* const /* publicId */, const XMLCh* const systemId) { - const std::string url = StringUtils::transcode(systemId); - const std::string::size_type pos = url.find("/xsd/"); - if (pos != std::string::npos) { - myHandler->setSchemaSeen(); - // const char* sumoPath = std::getenv("SUMO_HOME"); - // if (sumoPath == nullptr) { - // WRITE_WARNING("Environment variable SUMO_HOME is not set, schema resolution will use slow website lookups."); - // return nullptr; - // } - // const std::string file = sumoPath + std::string("/data") + url.substr(pos); - // if (FileHelpers::isReadable(file)) { - // XMLCh* t = XERCES_CPP_NAMESPACE::XMLString::transcode(file.c_str()); - // XERCES_CPP_NAMESPACE::InputSource* const result = new XERCES_CPP_NAMESPACE::LocalFileInputSource(t); - // XERCES_CPP_NAMESPACE::XMLString::release(&t); - // return result; - // } else { - // WRITE_WARNING("Cannot read local schema '" + file + "', will try website lookup."); - // } - const std::string file = std::string("../carla/data") + url.substr(pos); - if (FileHelpers::isReadable(file)) { - XMLCh* t = XERCES_CPP_NAMESPACE::XMLString::transcode(file.c_str()); - XERCES_CPP_NAMESPACE::InputSource* const result = new XERCES_CPP_NAMESPACE::LocalFileInputSource(t); - XERCES_CPP_NAMESPACE::XMLString::release(&t); - return result; - } else { - WRITE_WARNING("Cannot read local schema '" + file + "', will try website lookup."); - } - } - return nullptr; -} - - -void -SUMOSAXReader::LocalSchemaResolver::setHandler(GenericSAXHandler& handler) { - myHandler = &handler; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/utils/xml/SUMOSAXReader.h b/Util/OSM2ODR/src/utils/xml/SUMOSAXReader.h deleted file mode 100644 index 11b7effac..000000000 --- a/Util/OSM2ODR/src/utils/xml/SUMOSAXReader.h +++ /dev/null @@ -1,130 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2012-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file SUMOSAXReader.h -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date Nov 2012 -/// -// SAX-reader encapsulation containing binary reader -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include -#include -#include -#include -#include "SUMOXMLDefinitions.h" - - -// =========================================================================== -// class declarations -// =========================================================================== -class GenericSAXHandler; -class IStreamInputSource; - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class SUMOSAXReader - * @brief SAX-reader encapsulation containing binary reader - * - * This class generates on demand either a SAX2XMLReader or parses the SUMO - * binary xml. The interface is inspired by but not identical to - * SAX2XMLReader. - */ -class SUMOSAXReader { -public: - /** - * @brief Constructor - * - * @param[in] file The name of the processed file - */ - SUMOSAXReader(GenericSAXHandler& handler, const XERCES_CPP_NAMESPACE::SAX2XMLReader::ValSchemes validationScheme); - - /// Destructor - ~SUMOSAXReader(); - - /** - * @brief Sets the given handler as content and error handler for the reader - * - * @param[in] handler The handler to assign to the reader - */ - void setHandler(GenericSAXHandler& handler); - - void setValidation(const XERCES_CPP_NAMESPACE::SAX2XMLReader::ValSchemes validationScheme); - - void parse(std::string systemID); - - void parseString(std::string content); - - bool parseFirst(std::string systemID); - - bool parseNext(); - -private: - class LocalSchemaResolver : public XERCES_CPP_NAMESPACE::EntityResolver { - public: - XERCES_CPP_NAMESPACE::InputSource* resolveEntity(const XMLCh* const publicId, const XMLCh* const systemId); - void setHandler(GenericSAXHandler& handler); - private: - GenericSAXHandler* myHandler; - }; - -private: - /** - * @brief Builds a reader - * - * Tries to build a SAX2XMLReader using XMLReaderFactory::createXMLReader. If this - * fails, 0 is returned. Otherwise the validation is set matching the value of - * "myEnableValidation". If validation is not wanted, a WFXMLScanner is used - * (see http://www.ibm.com/developerworks/library/x-xercesperf.html). - * - * @return The built Xerces-SAX-reader, 0 if something failed - */ - XERCES_CPP_NAMESPACE::SAX2XMLReader* getSAXReader(); - - -private: - GenericSAXHandler* myHandler; - - /// @brief Information whether built reader/parser shall validate XML-documents against schemata - XERCES_CPP_NAMESPACE::SAX2XMLReader::ValSchemes myValidationScheme; - - XERCES_CPP_NAMESPACE::XMLPScanToken myToken; - - XERCES_CPP_NAMESPACE::SAX2XMLReader* myXMLReader; - - std::unique_ptr myIStream; - - std::unique_ptr myInputStream; - - /// @brief The stack of begun xml elements - std::vector myXMLStack; - - LocalSchemaResolver mySchemaResolver; - -private: - /// @brief invalidated copy constructor - SUMOSAXReader(const SUMOSAXReader& s); - - /// @brief invalidated assignment operator - const SUMOSAXReader& operator=(const SUMOSAXReader& s); - -}; diff --git a/Util/OSM2ODR/src/utils/xml/SUMOXMLDefinitions.cpp b/Util/OSM2ODR/src/utils/xml/SUMOXMLDefinitions.cpp deleted file mode 100644 index 6e38d811c..000000000 --- a/Util/OSM2ODR/src/utils/xml/SUMOXMLDefinitions.cpp +++ /dev/null @@ -1,1162 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2002-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file SUMOXMLDefinitions.cpp -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Clemens Honomichl -/// @author Piotr Woznica -/// @author Michael Behrisch -/// @author Walter Bamberger -/// @date Sept 2002 -/// -// Definitions of elements and attributes known by SUMO -/****************************************************************************/ -#include - -#include -#include -#include - -#include "SUMOXMLDefinitions.h" - -// =========================================================================== -// definitions -// =========================================================================== - -StringBijection::Entry SUMOXMLDefinitions::tags[] = { - // Simulation elements - { "net", SUMO_TAG_NET }, - { "edge", SUMO_TAG_EDGE }, - { "lane", SUMO_TAG_LANE }, - { "neigh", SUMO_TAG_NEIGH }, - { "poi", SUMO_TAG_POI }, - { "poiLane", SUMO_TAG_POILANE }, - { "poly", SUMO_TAG_POLY }, - { "junction", SUMO_TAG_JUNCTION }, - { "restriction", SUMO_TAG_RESTRICTION }, - { "e1Detector", SUMO_TAG_E1DETECTOR }, - { "inductionLoop", SUMO_TAG_INDUCTION_LOOP }, - { "e2Detector", SUMO_TAG_E2DETECTOR }, - { "e2MultilaneDetector", SUMO_TAG_E2DETECTOR_MULTILANE }, - { "laneAreaDetector", SUMO_TAG_LANE_AREA_DETECTOR }, - { "e3Detector", SUMO_TAG_E3DETECTOR }, - { "entryExitDetector", SUMO_TAG_ENTRY_EXIT_DETECTOR }, - { "edgeData", SUMO_TAG_MEANDATA_EDGE }, - { "laneData", SUMO_TAG_MEANDATA_LANE }, - { "detEntry", SUMO_TAG_DET_ENTRY }, - { "detExit", SUMO_TAG_DET_EXIT }, - { "edgeFollowDetector", SUMO_TAG_EDGEFOLLOWDETECTOR }, - { "instantInductionLoop", SUMO_TAG_INSTANT_INDUCTION_LOOP }, - { "variableSpeedSign", SUMO_TAG_VSS }, - { "calibrator", SUMO_TAG_CALIBRATOR }, - { "laneCalibrator", SUMO_TAG_LANECALIBRATOR }, - { "rerouter", SUMO_TAG_REROUTER }, - { "busStop", SUMO_TAG_BUS_STOP }, - { "trainStop", SUMO_TAG_TRAIN_STOP }, - { "ptLine", SUMO_TAG_PT_LINE }, - { "access", SUMO_TAG_ACCESS }, - { "containerStop", SUMO_TAG_CONTAINER_STOP }, - { "parkingArea", SUMO_TAG_PARKING_AREA }, - { "space", SUMO_TAG_PARKING_SPACE }, - { "chargingStation", SUMO_TAG_CHARGING_STATION }, - { "overheadWireSegment", SUMO_TAG_OVERHEAD_WIRE_SEGMENT }, - { "overheadWire", SUMO_TAG_OVERHEAD_WIRE_SECTION }, - { "tractionSubstation", SUMO_TAG_TRACTION_SUBSTATION }, - { "overheadWireClamp", SUMO_TAG_OVERHEAD_WIRE_CLAMP }, - { "vTypeProbe", SUMO_TAG_VTYPEPROBE }, - { "routeProbe", SUMO_TAG_ROUTEPROBE }, - { "routes", SUMO_TAG_ROUTES }, - { "vehicle", SUMO_TAG_VEHICLE }, - { "vType", SUMO_TAG_VTYPE }, - { "pType", SUMO_TAG_PTYPE }, - { "route", SUMO_TAG_ROUTE }, - { "request", SUMO_TAG_REQUEST }, - { "source", SUMO_TAG_SOURCE }, - { "taz", SUMO_TAG_TAZ }, - { "tazSource", SUMO_TAG_TAZSOURCE }, - { "tazSink", SUMO_TAG_TAZSINK }, - { "trafficLight", SUMO_TAG_TRAFFIC_LIGHT }, - { "tlLogic", SUMO_TAG_TLLOGIC }, - { "phase", SUMO_TAG_PHASE }, - { "trip", SUMO_TAG_TRIP }, - { "tripTAZ", SUMO_TAG_TRIP_TAZ }, - { "flow", SUMO_TAG_FLOW }, - { "flowCalibrator", SUMO_TAG_FLOW_CALIBRATOR }, - { "flowState", SUMO_TAG_FLOWSTATE }, - { "step", SUMO_TAG_STEP }, - { "interval", SUMO_TAG_INTERVAL }, - { "edgeRelation", SUMO_TAG_EDGEREL }, - { "tazRelation", SUMO_TAG_TAZREL }, - { "timedEvent", SUMO_TAG_TIMEDEVENT }, - { "fromEdge", SUMO_TAG_FROMEDGE }, - { "toEdge", SUMO_TAG_TOEDGE }, - { "sink", SUMO_TAG_SINK }, - { "param", SUMO_TAG_PARAM }, - { "WAUT", SUMO_TAG_WAUT }, - { "wautSwitch", SUMO_TAG_WAUT_SWITCH }, - { "wautJunction", SUMO_TAG_WAUT_JUNCTION }, - { "segment", SUMO_TAG_SEGMENT }, - { "delete", SUMO_TAG_DEL }, - { "stop", SUMO_TAG_STOP }, - { "stopBusStop", SUMO_TAG_STOP_BUSSTOP }, - { "stopContainerStop", SUMO_TAG_STOP_CONTAINERSTOP }, - { "stopChargingStation", SUMO_TAG_STOP_CHARGINGSTATION }, - { "stopParkingArea", SUMO_TAG_STOP_PARKINGAREA }, - { "stopLane", SUMO_TAG_STOP_LANE }, - { "destProbReroute", SUMO_TAG_DEST_PROB_REROUTE }, - { "closingReroute", SUMO_TAG_CLOSING_REROUTE }, - { "closingLaneReroute", SUMO_TAG_CLOSING_LANE_REROUTE }, - { "routeProbReroute", SUMO_TAG_ROUTE_PROB_REROUTE }, - { "parkingAreaReroute", SUMO_TAG_PARKING_ZONE_REROUTE }, - { "polygonType", SUMO_TAG_POLYTYPE }, - { "connection", SUMO_TAG_CONNECTION }, - { "prohibition", SUMO_TAG_PROHIBITION }, - { "split", SUMO_TAG_SPLIT }, - { "node", SUMO_TAG_NODE }, - { "type", SUMO_TAG_TYPE }, - { "detectorDefinition", SUMO_TAG_DETECTOR_DEFINITION }, - { "routeDistribution", SUMO_TAG_ROUTE_DISTRIBUTION }, - { "vTypeDistribution", SUMO_TAG_VTYPE_DISTRIBUTION }, - { "vaporizer", SUMO_TAG_VAPORIZER }, - { "roundabout", SUMO_TAG_ROUNDABOUT }, - { "join", SUMO_TAG_JOIN }, - { "joinExclude", SUMO_TAG_JOINEXCLUDE }, - { "crossing", SUMO_TAG_CROSSING }, - { "walkingArea", SUMO_TAG_WALKINGAREA }, - { "stopOffset", SUMO_TAG_STOPOFFSET }, - // OSM - { "way", SUMO_TAG_WAY }, - { "nd", SUMO_TAG_ND }, - { "tag", SUMO_TAG_TAG }, - { "relation", SUMO_TAG_RELATION }, - { "member", SUMO_TAG_MEMBER }, - // View - { "viewsettings", SUMO_TAG_VIEWSETTINGS }, - { "decal", SUMO_TAG_VIEWSETTINGS_DECAL }, - { "light", SUMO_TAG_VIEWSETTINGS_LIGHT }, - { "scheme", SUMO_TAG_VIEWSETTINGS_SCHEME }, - { "opengl", SUMO_TAG_VIEWSETTINGS_OPENGL }, - { "background", SUMO_TAG_VIEWSETTINGS_BACKGROUND }, - { "edges", SUMO_TAG_VIEWSETTINGS_EDGES }, - { "vehicles", SUMO_TAG_VIEWSETTINGS_VEHICLES }, - { "persons", SUMO_TAG_VIEWSETTINGS_PERSONS }, - { "containers", SUMO_TAG_VIEWSETTINGS_CONTAINERS }, - { "junctions", SUMO_TAG_VIEWSETTINGS_JUNCTIONS }, - { "additionals", SUMO_TAG_VIEWSETTINGS_ADDITIONALS }, - { "pois", SUMO_TAG_VIEWSETTINGS_POIS }, - { "polys", SUMO_TAG_VIEWSETTINGS_POLYS }, - { "legend", SUMO_TAG_VIEWSETTINGS_LEGEND }, - { "event", SUMO_TAG_VIEWSETTINGS_EVENT }, - { "jamTime", SUMO_TAG_VIEWSETTINGS_EVENT_JAM_TIME }, - { "include", SUMO_TAG_INCLUDE }, - { "delay", SUMO_TAG_DELAY }, - { "viewport", SUMO_TAG_VIEWPORT }, - { "snapshot", SUMO_TAG_SNAPSHOT }, - { "breakpoint", SUMO_TAG_BREAKPOINT }, - { "location", SUMO_TAG_LOCATION }, - { "colorScheme", SUMO_TAG_COLORSCHEME }, - { "scalingScheme", SUMO_TAG_SCALINGSCHEME }, - { "entry", SUMO_TAG_ENTRY }, - { "rngState", SUMO_TAG_RNGSTATE }, - { "rngLane", SUMO_TAG_RNGLANE }, - { "vehicleTransfer", SUMO_TAG_VEHICLETRANSFER }, - { "device", SUMO_TAG_DEVICE }, - // Cars - { "carFollowing-IDM", SUMO_TAG_CF_IDM }, - { "carFollowing-IDMM", SUMO_TAG_CF_IDMM }, - { "carFollowing-Krauss", SUMO_TAG_CF_KRAUSS }, - { "carFollowing-KraussPS", SUMO_TAG_CF_KRAUSS_PLUS_SLOPE }, - { "carFollowing-KraussOrig1", SUMO_TAG_CF_KRAUSS_ORIG1 }, - { "carFollowing-KraussX", SUMO_TAG_CF_KRAUSSX }, - { "carFollowing-SmartSK", SUMO_TAG_CF_SMART_SK }, - { "carFollowing-Daniel1", SUMO_TAG_CF_DANIEL1 }, - { "carFollowing-PWagner2009", SUMO_TAG_CF_PWAGNER2009 }, - { "carFollowing-BKerner", SUMO_TAG_CF_BKERNER }, - { "carFollowing-Wiedemann", SUMO_TAG_CF_WIEDEMANN }, - { "carFollowing-W99", SUMO_TAG_CF_W99 }, - { "carFollowing-Rail", SUMO_TAG_CF_RAIL }, - { "carFollowing-ACC", SUMO_TAG_CF_ACC }, - { "carFollowing-CACC", SUMO_TAG_CF_CACC }, - { "carFollowing-CC", SUMO_TAG_CF_CC }, - // Person - { "person", SUMO_TAG_PERSON }, - { "personTrip", SUMO_TAG_PERSONTRIP }, - { "ride", SUMO_TAG_RIDE }, - { "walk", SUMO_TAG_WALK }, - { "personFlow", SUMO_TAG_PERSONFLOW }, - // Data (Netedit) - { "dataSet", SUMO_TAG_DATASET }, - { "dataInterval", SUMO_TAG_DATAINTERVAL }, - // Transport - { "container", SUMO_TAG_CONTAINER }, - { "transport", SUMO_TAG_TRANSPORT }, - { "tranship", SUMO_TAG_TRANSHIP }, - //Trajectories - { "trajectories", SUMO_TAG_TRAJECTORIES }, - { "timestep", SUMO_TAG_TIMESTEP }, - { "timeSlice", SUMO_TAG_TIMESLICE }, - { "actorConfig", SUMO_TAG_ACTORCONFIG }, - { "motionState", SUMO_TAG_MOTIONSTATE }, - { "odPair", SUMO_TAG_OD_PAIR }, - // ActivityGen statistics file - { "general", AGEN_TAG_GENERAL }, - { "street", AGEN_TAG_STREET }, - { "workHours", AGEN_TAG_WORKHOURS }, - { "opening", AGEN_TAG_OPENING }, - { "closing", AGEN_TAG_CLOSING }, - { "schools", AGEN_TAG_SCHOOLS }, - { "school", AGEN_TAG_SCHOOL }, - { "busStation", AGEN_TAG_BUSSTATION }, - { "busLine", AGEN_TAG_BUSLINE }, - { "stations", AGEN_TAG_STATIONS }, - { "revStations", AGEN_TAG_REV_STATIONS }, - { "station", AGEN_TAG_STATION }, - { "frequency", AGEN_TAG_FREQUENCY }, - { "population", AGEN_TAG_POPULATION }, - { "bracket", AGEN_TAG_BRACKET }, - { "cityGates", AGEN_TAG_CITYGATES }, - { "entrance", AGEN_TAG_ENTRANCE }, - { "parameters", AGEN_TAG_PARAM }, - // GNE Person trips - { "personTrip: edge->edge", GNE_TAG_PERSONTRIP_EDGE_EDGE }, - { "personTrip: edge->busStop", GNE_TAG_PERSONTRIP_EDGE_BUSSTOP }, - { "personTrip: busStop->edge", GNE_TAG_PERSONTRIP_BUSSTOP_EDGE }, - { "personTrip: busStop->busStop", GNE_TAG_PERSONTRIP_BUSSTOP_BUSSTOP }, - // GNE Walks - { "walk: edge->edge", GNE_TAG_WALK_EDGE_EDGE }, - { "walk: edge->busStop", GNE_TAG_WALK_EDGE_BUSSTOP }, - { "walk: busStop->edge", GNE_TAG_WALK_BUSSTOP_EDGE }, - { "walk: busStop->busStop", GNE_TAG_WALK_BUSSTOP_BUSSTOP }, - { "walk: edges", GNE_TAG_WALK_EDGES }, - { "walk: route", GNE_TAG_WALK_ROUTE }, - // GNE Rides - { "ride: edge->edge", GNE_TAG_RIDE_EDGE_EDGE }, - { "ride: edge->busStop", GNE_TAG_RIDE_EDGE_BUSSTOP }, - { "ride: busStop->edge", GNE_TAG_RIDE_BUSSTOP_EDGE }, - { "ride: busStop->busStop", GNE_TAG_RIDE_BUSSTOP_BUSSTOP }, - // GNE person Stops - { "personStop: busStop", GNE_TAG_PERSONSTOP_BUSSTOP }, - { "personStop: edge", GNE_TAG_PERSONSTOP_EDGE }, - // special tags to represent different input styles with the same tag internally - { "vehicleWithRoute", GNE_TAG_VEHICLEWITHROUTE }, - { "routeEmbedded", GNE_TAG_ROUTE_EMBEDDED }, - { "flowRoute", GNE_TAG_FLOW_ROUTE }, - { "flowWithRoute", GNE_TAG_FLOW_WITHROUTE }, - { "Person (embedded)", GNE_TAG_PERSON_EMBEDDED }, - // Other - { "", SUMO_TAG_NOTHING } // -> must be the last one -}; - - -StringBijection::Entry SUMOXMLDefinitions::attrs[] = { - // meandata - { "sampledSeconds", SUMO_ATTR_SAMPLEDSECONDS }, - { "density", SUMO_ATTR_DENSITY }, - { "laneDensity", SUMO_ATTR_LANEDENSITY }, - { "occupancy", SUMO_ATTR_OCCUPANCY }, - { "waitingTime", SUMO_ATTR_WAITINGTIME }, - { "speed", SUMO_ATTR_SPEED }, - { "departed", SUMO_ATTR_DEPARTED }, - { "arrived", SUMO_ATTR_ARRIVED }, - { "entered", SUMO_ATTR_ENTERED }, - { "left", SUMO_ATTR_LEFT }, - { "vaporized", SUMO_ATTR_VAPORIZED }, - { "traveltime", SUMO_ATTR_TRAVELTIME }, - { "laneChangedFrom", SUMO_ATTR_LANECHANGEDFROM }, - { "laneChangedTo", SUMO_ATTR_LANECHANGEDTO }, - { "overlapTraveltime", SUMO_ATTR_OVERLAPTRAVELTIME }, - { "CO_abs", SUMO_ATTR_CO_ABS }, - { "CO2_abs", SUMO_ATTR_CO2_ABS }, - { "HC_abs", SUMO_ATTR_HC_ABS }, - { "PMx_abs", SUMO_ATTR_PMX_ABS }, - { "NOx_abs", SUMO_ATTR_NOX_ABS }, - { "fuel_abs", SUMO_ATTR_FUEL_ABS }, - { "electricity_abs", SUMO_ATTR_ELECTRICITY_ABS }, - { "CO_normed", SUMO_ATTR_CO_NORMED }, - { "CO2_normed", SUMO_ATTR_CO2_NORMED }, - { "HC_normed", SUMO_ATTR_HC_NORMED }, - { "PMx_normed", SUMO_ATTR_PMX_NORMED }, - { "NOx_normed", SUMO_ATTR_NOX_NORMED }, - { "fuel_normed", SUMO_ATTR_FUEL_NORMED }, - { "electricity_normed", SUMO_ATTR_ELECTRICITY_NORMED }, - { "CO_perVeh", SUMO_ATTR_CO_PERVEH }, - { "CO2_perVeh", SUMO_ATTR_CO2_PERVEH }, - { "HC_perVeh", SUMO_ATTR_HC_PERVEH }, - { "PMx_perVeh", SUMO_ATTR_PMX_PERVEH }, - { "NOx_perVeh", SUMO_ATTR_NOX_PERVEH }, - { "fuel_perVeh", SUMO_ATTR_FUEL_PERVEH }, - { "electricity_perVeh", SUMO_ATTR_ELECTRICITY_PERVEH }, - { "noise", SUMO_ATTR_NOISE }, - { "amount", SUMO_ATTR_AMOUNT }, - { "averageSpeed", SUMO_ATTR_AVERAGESPEED }, - - // Edge - { "id", SUMO_ATTR_ID }, - { "refId", SUMO_ATTR_REFID }, - { "name", SUMO_ATTR_NAME }, - { "type", SUMO_ATTR_TYPE }, - { "version", SUMO_ATTR_VERSION }, - { "priority", SUMO_ATTR_PRIORITY }, - { "numLanes", SUMO_ATTR_NUMLANES }, - { "oneway", SUMO_ATTR_ONEWAY }, - { "width", SUMO_ATTR_WIDTH }, - { "widthResolution", SUMO_ATTR_WIDTHRESOLUTION }, - { "maxWidth", SUMO_ATTR_MAXWIDTH }, - { "minWidth", SUMO_ATTR_MINWIDTH }, - { "sidewalkWidth", SUMO_ATTR_SIDEWALKWIDTH }, - { "bikeLaneWidth", SUMO_ATTR_BIKELANEWIDTH }, - { "remove", SUMO_ATTR_REMOVE }, - { "length", SUMO_ATTR_LENGTH }, - { "bidi", SUMO_ATTR_BIDI }, - { "distance", SUMO_ATTR_DISTANCE }, - // Split - { "idBefore", SUMO_ATTR_ID_BEFORE }, - { "idAfter", SUMO_ATTR_ID_AFTER }, - // Positions - { "x", SUMO_ATTR_X }, - { "y", SUMO_ATTR_Y }, - { "z", SUMO_ATTR_Z }, - { "centerX", SUMO_ATTR_CENTER_X }, - { "centerY", SUMO_ATTR_CENTER_Y }, - { "centerZ", SUMO_ATTR_CENTER_Z }, - - { "key", SUMO_ATTR_KEY }, - { "requestSize", SUMO_ATTR_REQUESTSIZE }, - { "request", SUMO_ATTR_REQUEST }, - { "response", SUMO_ATTR_RESPONSE }, - { "programID", SUMO_ATTR_PROGRAMID }, - { "offset", SUMO_ATTR_OFFSET }, - { "endOffset", SUMO_ATTR_ENDOFFSET }, - { "incLanes", SUMO_ATTR_INCLANES }, - { "intLanes", SUMO_ATTR_INTLANES }, - - { "weight", SUMO_ATTR_WEIGHT }, - { "node", SUMO_ATTR_NODE }, - { "edge", SUMO_ATTR_EDGE }, - { "edges", SUMO_ATTR_EDGES }, - // Vehicle - { "depart", SUMO_ATTR_DEPART }, - { "departLane", SUMO_ATTR_DEPARTLANE }, - { "departPos", SUMO_ATTR_DEPARTPOS }, - { "departPosLat", SUMO_ATTR_DEPARTPOS_LAT }, - { "departSpeed", SUMO_ATTR_DEPARTSPEED }, - { "arrivalLane", SUMO_ATTR_ARRIVALLANE }, - { "arrivalPos", SUMO_ATTR_ARRIVALPOS }, - { "arrivalPosLat", SUMO_ATTR_ARRIVALPOS_LAT }, - { "arrivalSpeed", SUMO_ATTR_ARRIVALSPEED }, - { "route", SUMO_ATTR_ROUTE }, - { "maxSpeed", SUMO_ATTR_MAXSPEED }, - { "maxSpeedLat", SUMO_ATTR_MAXSPEED_LAT }, - { "latAlignment", SUMO_ATTR_LATALIGNMENT }, - { "minGapLat", SUMO_ATTR_MINGAP_LAT }, - { "accel", SUMO_ATTR_ACCEL }, - { "decel", SUMO_ATTR_DECEL }, - { "emergencyDecel", SUMO_ATTR_EMERGENCYDECEL }, - { "apparentDecel", SUMO_ATTR_APPARENTDECEL }, - { "actionStepLength", SUMO_ATTR_ACTIONSTEPLENGTH }, - { "vClass", SUMO_ATTR_VCLASS }, - { "vClasses", SUMO_ATTR_VCLASSES }, - { "exceptions", SUMO_ATTR_EXCEPTIONS }, - { "repno", SUMO_ATTR_REPNUMBER }, - { "speedFactor", SUMO_ATTR_SPEEDFACTOR }, - { "speedDev", SUMO_ATTR_SPEEDDEV }, - { "laneChangeModel", SUMO_ATTR_LANE_CHANGE_MODEL }, - { "carFollowModel", SUMO_ATTR_CAR_FOLLOW_MODEL }, - { "minGap", SUMO_ATTR_MINGAP }, - { "collisionMinGapFactor", SUMO_ATTR_COLLISION_MINGAP_FACTOR }, - { "boardingDuration", SUMO_ATTR_BOARDING_DURATION }, - { "loadingDuration", SUMO_ATTR_LOADING_DURATION }, - { "maneuverAngleTimes", SUMO_ATTR_MANEUVER_ANGLE_TIMES }, - // MSDevice_ElecHybrid - { "overheadWireChargingPower", SUMO_ATTR_OVERHEADWIRECHARGINGPOWER }, - // OverheadWire - { "overheadWireSegment", SUMO_ATTR_OVERHEAD_WIRE_SEGMENT }, - { "segments", SUMO_ATTR_OVERHEAD_WIRE_SECTION }, - { "voltage", SUMO_ATTR_VOLTAGE }, - { "voltageSource", SUMO_ATTR_VOLTAGESOURCE }, - { "currentLimit", SUMO_ATTR_CURRENTLIMIT }, - { "substationId", SUMO_ATTR_SUBSTATIONID }, - { "wireResistivity", SUMO_ATTR_OVERHEAD_WIRE_RESISTIVITY }, - { "forbiddenInnerLanes", SUMO_ATTR_OVERHEAD_WIRE_FORBIDDEN }, - { "clamps", SUMO_ATTR_OVERHEAD_WIRE_CLAMPS }, - { "idSegmentStartClamp", SUMO_ATTR_OVERHEAD_WIRE_CLAMP_START }, - { "idSegmentEndClamp", SUMO_ATTR_OVERHEAD_WIRE_CLAMP_END }, - // Charging Station - { "power", SUMO_ATTR_CHARGINGPOWER }, - { "efficiency", SUMO_ATTR_EFFICIENCY }, - { "chargeInTransit", SUMO_ATTR_CHARGEINTRANSIT }, - { "chargeDelay", SUMO_ATTR_CHARGEDELAY}, - // MSDevice_Battery - { "actualBatteryCapacity", SUMO_ATTR_ACTUALBATTERYCAPACITY }, - { "maximumBatteryCapacity", SUMO_ATTR_MAXIMUMBATTERYCAPACITY }, - { "maximumPower", SUMO_ATTR_MAXIMUMPOWER }, - { "vehicleMass", SUMO_ATTR_VEHICLEMASS }, - { "frontSurfaceArea", SUMO_ATTR_FRONTSURFACEAREA }, - { "airDragCoefficient", SUMO_ATTR_AIRDRAGCOEFFICIENT }, - { "internalMomentOfInertia", SUMO_ATTR_INTERNALMOMENTOFINERTIA }, - { "radialDragCoefficient", SUMO_ATTR_RADIALDRAGCOEFFICIENT }, - { "rollDragCoefficient", SUMO_ATTR_ROLLDRAGCOEFFICIENT }, - { "constantPowerIntake", SUMO_ATTR_CONSTANTPOWERINTAKE }, - { "propulsionEfficiency", SUMO_ATTR_PROPULSIONEFFICIENCY }, - { "recuperationEfficiency", SUMO_ATTR_RECUPERATIONEFFICIENCY }, - { "recuperationEfficiencyByDecel", SUMO_ATTR_RECUPERATIONEFFICIENCY_BY_DECELERATION }, - { "stoppingTreshold", SUMO_ATTR_STOPPINGTRESHOLD }, - // MSElecHybridExport - { "overheadWireId", SUMO_ATTR_OVERHEADWIREID }, - { "tractionSubstationId", SUMO_ATTR_TRACTIONSUBSTATIONID }, - { "current", SUMO_ATTR_CURRENTFROMOVERHEADWIRE }, - { "circuitVoltage", SUMO_ATTR_VOLTAGEOFOVERHEADWIRE }, - { "alphaCircuitSolver", SUMO_ATTR_ALPHACIRCUITSOLVER }, - // MSBatteryExport - { "energyConsumed", SUMO_ATTR_ENERGYCONSUMED }, - { "chargingStationId", SUMO_ATTR_CHARGINGSTATIONID }, - { "energyCharged", SUMO_ATTR_ENERGYCHARGED }, - { "energyChargedInTransit", SUMO_ATTR_ENERGYCHARGEDINTRANSIT }, - { "energyChargedStopped", SUMO_ATTR_ENERGYCHARGEDSTOPPED }, - { "posOnLane", SUMO_ATTR_POSONLANE }, - { "timeStopped", SUMO_ATTR_TIMESTOPPED }, - // ChargingStation output - { "chargingStatus", SUMO_ATTR_CHARGING_STATUS }, - { "totalEnergyCharged", SUMO_ATTR_TOTALENERGYCHARGED }, - { "chargingSteps", SUMO_ATTR_CHARGINGSTEPS }, - { "totalEnergyChargedIntoVehicle", SUMO_ATTR_TOTALENERGYCHARGED_VEHICLE }, - { "chargingBegin", SUMO_ATTR_CHARGINGBEGIN }, - { "chargingEnd", SUMO_ATTR_CHARGINGEND }, - { "partialCharge", SUMO_ATTR_PARTIALCHARGE }, - - { "sigma", SUMO_ATTR_SIGMA }, - { "tau", SUMO_ATTR_TAU }, - { "tmp1", SUMO_ATTR_TMP1 }, - { "tmp2", SUMO_ATTR_TMP2 }, - { "tmp3", SUMO_ATTR_TMP3 }, - { "tmp4", SUMO_ATTR_TMP4 }, - { "tmp5", SUMO_ATTR_TMP5 }, - - { "speedControlGain", SUMO_ATTR_SC_GAIN }, - { "gapClosingControlGainSpeed", SUMO_ATTR_GCC_GAIN_SPEED }, - { "gapClosingControlGainSpace", SUMO_ATTR_GCC_GAIN_SPACE }, - { "gapControlGainSpeed", SUMO_ATTR_GC_GAIN_SPEED }, - { "gapControlGainSpace", SUMO_ATTR_GC_GAIN_SPACE }, - { "collisionAvoidanceGainSpeed", SUMO_ATTR_CA_GAIN_SPEED }, - { "collisionAvoidanceGainSpace", SUMO_ATTR_CA_GAIN_SPACE }, - - { "speedControlGainCACC", SUMO_ATTR_SC_GAIN_CACC }, - { "gapClosingControlGainGap", SUMO_ATTR_GCC_GAIN_GAP_CACC }, - { "gapClosingControlGainGapDot", SUMO_ATTR_GCC_GAIN_GAP_DOT_CACC }, - { "gapControlGainGap", SUMO_ATTR_GC_GAIN_GAP_CACC }, - { "gapControlGainGapDot", SUMO_ATTR_GC_GAIN_GAP_DOT_CACC }, - { "tauCACCToACC", SUMO_ATTR_HEADWAY_TIME_CACC_TO_ACC }, - { "collisionAvoidanceGainGap", SUMO_ATTR_CA_GAIN_GAP_CACC }, - { "collisionAvoidanceGainGapDot", SUMO_ATTR_CA_GAIN_GAP_DOT_CACC }, - - { "trainType", SUMO_ATTR_TRAIN_TYPE }, - - { "lcStrategic", SUMO_ATTR_LCA_STRATEGIC_PARAM }, - { "lcCooperative", SUMO_ATTR_LCA_COOPERATIVE_PARAM }, - { "lcSpeedGain", SUMO_ATTR_LCA_SPEEDGAIN_PARAM }, - { "lcKeepRight", SUMO_ATTR_LCA_KEEPRIGHT_PARAM }, - { "lcSublane", SUMO_ATTR_LCA_SUBLANE_PARAM }, - { "lcOpposite", SUMO_ATTR_LCA_OPPOSITE_PARAM }, - { "lcPushy", SUMO_ATTR_LCA_PUSHY }, - { "lcPushyGap", SUMO_ATTR_LCA_PUSHYGAP }, - { "lcAssertive", SUMO_ATTR_LCA_ASSERTIVE }, - { "lcImpatience", SUMO_ATTR_LCA_IMPATIENCE }, - { "lcTimeToImpatience", SUMO_ATTR_LCA_TIME_TO_IMPATIENCE }, - { "lcAccelLat", SUMO_ATTR_LCA_ACCEL_LAT }, - { "lcTurnAlignmentDistance", SUMO_ATTR_LCA_TURN_ALIGNMENT_DISTANCE }, - { "lcOvertakeRight", SUMO_ATTR_LCA_OVERTAKE_RIGHT }, - { "lcLookaheadLeft", SUMO_ATTR_LCA_LOOKAHEADLEFT }, - { "lcSpeedGainRight", SUMO_ATTR_LCA_SPEEDGAINRIGHT }, - { "lcSpeedGainLookahead", SUMO_ATTR_LCA_SPEEDGAIN_LOOKAHEAD }, - { "lcCooperativeRoundabout", SUMO_ATTR_LCA_COOPERATIVE_ROUNDABOUT }, - { "lcCooperativeSpeed", SUMO_ATTR_LCA_COOPERATIVE_SPEED }, - { "lcMaxSpeedLatStanding", SUMO_ATTR_LCA_MAXSPEEDLATSTANDING }, - { "lcMaxSpeedLatFactor", SUMO_ATTR_LCA_MAXSPEEDLATFACTOR }, - { "lcLaneDiscipline", SUMO_ATTR_LCA_LANE_DISCIPLINE }, - { "lcSigma", SUMO_ATTR_LCA_SIGMA }, - { "lcExperimental1", SUMO_ATTR_LCA_EXPERIMENTAL1 }, - - { "jmCrossingGap", SUMO_ATTR_JM_CROSSING_GAP }, - { "jmDriveAfterYellowTime", SUMO_ATTR_JM_DRIVE_AFTER_YELLOW_TIME }, - { "jmDriveAfterRedTime", SUMO_ATTR_JM_DRIVE_AFTER_RED_TIME }, - { "jmDriveRedSpeed", SUMO_ATTR_JM_DRIVE_RED_SPEED }, - { "jmIgnoreKeepClearTime", SUMO_ATTR_JM_IGNORE_KEEPCLEAR_TIME }, - { "jmIgnoreFoeSpeed", SUMO_ATTR_JM_IGNORE_FOE_SPEED }, - { "jmIgnoreFoeProb", SUMO_ATTR_JM_IGNORE_FOE_PROB }, - { "jmSigmaMinor", SUMO_ATTR_JM_SIGMA_MINOR }, - { "jmTimegapMinor", SUMO_ATTR_JM_TIMEGAP_MINOR }, - - { "last", SUMO_ATTR_LAST }, - { "cost", SUMO_ATTR_COST }, - { "costs", SUMO_ATTR_COSTS }, - { "savings", SUMO_ATTR_SAVINGS }, - { "probability", SUMO_ATTR_PROB }, - { "count", SUMO_ATTR_COUNT }, - { "probabilities", SUMO_ATTR_PROBS }, - { "routes", SUMO_ATTR_ROUTES }, - { "vTypes", SUMO_ATTR_VTYPES }, - - { "lane", SUMO_ATTR_LANE }, - { "lanes", SUMO_ATTR_LANES }, - { "from", SUMO_ATTR_FROM }, - { "to", SUMO_ATTR_TO }, - { "fromLonLat", SUMO_ATTR_FROMLONLAT }, - { "toLonLat", SUMO_ATTR_TOLONLAT }, - { "fromXY", SUMO_ATTR_FROMXY }, - { "toXY", SUMO_ATTR_TOXY }, - { "fromJunction", SUMO_ATTR_FROMJUNCTION }, - { "toJunction", SUMO_ATTR_TOJUNCTION }, - { "period", SUMO_ATTR_PERIOD }, - { "repeat", SUMO_ATTR_REPEAT }, - { "fromTaz", SUMO_ATTR_FROM_TAZ }, - { "toTaz", SUMO_ATTR_TO_TAZ }, - { "reroute", SUMO_ATTR_REROUTE }, - { "personCapacity", SUMO_ATTR_PERSON_CAPACITY }, - { "containerCapacity", SUMO_ATTR_CONTAINER_CAPACITY }, - { "parkingLength", SUMO_ATTR_PARKING_LENGTH }, - { "personNumber", SUMO_ATTR_PERSON_NUMBER }, - { "containerNumber", SUMO_ATTR_CONTAINER_NUMBER }, - { "modes", SUMO_ATTR_MODES }, - { "walkFactor", SUMO_ATTR_WALKFACTOR }, - - { "function", SUMO_ATTR_FUNCTION }, - { "pos", SUMO_ATTR_POSITION }, - { "posLat", SUMO_ATTR_POSITION_LAT }, - { "freq", SUMO_ATTR_FREQUENCY }, - { "style", SUMO_ATTR_STYLE }, - { "file", SUMO_ATTR_FILE }, - { "junction", SUMO_ATTR_JUNCTION }, - { "number", SUMO_ATTR_NUMBER }, - { "duration", SUMO_ATTR_DURATION }, - { "until", SUMO_ATTR_UNTIL }, - { "arrival", SUMO_ATTR_ARRIVAL }, - { "extension", SUMO_ATTR_EXTENSION }, - { "routeProbe", SUMO_ATTR_ROUTEPROBE }, - { "crossingEdges", SUMO_ATTR_CROSSING_EDGES }, - // Traffic light & Nodes - { "time", SUMO_ATTR_TIME }, - { "begin", SUMO_ATTR_BEGIN }, - { "end", SUMO_ATTR_END }, - { "tl", SUMO_ATTR_TLID }, - { "tlType", SUMO_ATTR_TLTYPE }, - { "linkIndex", SUMO_ATTR_TLLINKINDEX }, - { "linkIndex2", SUMO_ATTR_TLLINKINDEX2 }, - { "shape", SUMO_ATTR_SHAPE }, - { "spreadType", SUMO_ATTR_SPREADTYPE }, - { "radius", SUMO_ATTR_RADIUS }, - { "customShape", SUMO_ATTR_CUSTOMSHAPE }, - { "keepClear", SUMO_ATTR_KEEP_CLEAR }, - { "rightOfWay", SUMO_ATTR_RIGHT_OF_WAY }, - { "fringe", SUMO_ATTR_FRINGE }, - { "color", SUMO_ATTR_COLOR }, - { "dir", SUMO_ATTR_DIR }, - { "state", SUMO_ATTR_STATE }, - { "layer", SUMO_ATTR_LAYER }, - { "fill", SUMO_ATTR_FILL }, - { "lineWidth", SUMO_ATTR_LINEWIDTH }, - { "prefix", SUMO_ATTR_PREFIX }, - { "discard", SUMO_ATTR_DISCARD }, - - { "fromLane", SUMO_ATTR_FROM_LANE }, - { "toLane", SUMO_ATTR_TO_LANE }, - { "dest", SUMO_ATTR_DEST }, - { "source", SUMO_ATTR_SOURCE }, - { "via", SUMO_ATTR_VIA }, - { "viaLonLat", SUMO_ATTR_VIALONLAT }, - { "viaXY", SUMO_ATTR_VIAXY }, - { "viaJunctions", SUMO_ATTR_VIAJUNCTIONS }, - { "nodes", SUMO_ATTR_NODES }, - { "visibility", SUMO_ATTR_VISIBILITY_DISTANCE }, - - { "minDur", SUMO_ATTR_MINDURATION }, - { "maxDur", SUMO_ATTR_MAXDURATION }, - { "next", SUMO_ATTR_NEXT }, - { "foes", SUMO_ATTR_FOES }, - // E2 detector - { "cont", SUMO_ATTR_CONT }, - { "contPos", SUMO_ATTR_CONTPOS }, - { "timeThreshold", SUMO_ATTR_HALTING_TIME_THRESHOLD }, - { "speedThreshold", SUMO_ATTR_HALTING_SPEED_THRESHOLD }, - { "jamThreshold", SUMO_ATTR_JAM_DIST_THRESHOLD }, - { "show", SUMO_ATTR_SHOW_DETECTOR }, - // E3 detector - { "openEntry", SUMO_ATTR_OPEN_ENTRY }, - - { "wautID", SUMO_ATTR_WAUT_ID }, - { "junctionID", SUMO_ATTR_JUNCTION_ID }, - { "procedure", SUMO_ATTR_PROCEDURE }, - { "synchron", SUMO_ATTR_SYNCHRON }, - { "refTime", SUMO_ATTR_REF_TIME }, - { "startProg", SUMO_ATTR_START_PROG }, - { "off", SUMO_ATTR_OFF }, - { "friendlyPos", SUMO_ATTR_FRIENDLY_POS }, - { "splitByType", SUMO_ATTR_SPLIT_VTYPE }, - { "uncontrolled", SUMO_ATTR_UNCONTROLLED }, - { "pass", SUMO_ATTR_PASS }, - { "busStop", SUMO_ATTR_BUS_STOP }, - { "containerStop", SUMO_ATTR_CONTAINER_STOP }, - { "parkingArea", SUMO_ATTR_PARKING_AREA }, - { "roadsideCapacity", SUMO_ATTR_ROADSIDE_CAPACITY }, - { "onRoad", SUMO_ATTR_ONROAD }, - { "chargingStation", SUMO_ATTR_CHARGING_STATION}, - { "group", SUMO_ATTR_GROUP}, - { "line", SUMO_ATTR_LINE }, - { "lines", SUMO_ATTR_LINES }, - { "tripId", SUMO_ATTR_TRIP_ID }, - { "split", SUMO_ATTR_SPLIT }, - { "join", SUMO_ATTR_JOIN }, - { "intended", SUMO_ATTR_INTENDED }, - { "value", SUMO_ATTR_VALUE }, - { "prohibitor", SUMO_ATTR_PROHIBITOR }, - { "prohibited", SUMO_ATTR_PROHIBITED }, - { "allow", SUMO_ATTR_ALLOW }, - { "disallow", SUMO_ATTR_DISALLOW }, - { "prefer", SUMO_ATTR_PREFER }, - { "controlledInner", SUMO_ATTR_CONTROLLED_INNER }, - { "vehsPerHour", SUMO_ATTR_VEHSPERHOUR }, - { "personsPerHour", SUMO_ATTR_PERSONSPERHOUR }, - { "output", SUMO_ATTR_OUTPUT }, - { "height", SUMO_ATTR_HEIGHT }, - { "guiShape", SUMO_ATTR_GUISHAPE }, - { "osgFile", SUMO_ATTR_OSGFILE }, - { "imgFile", SUMO_ATTR_IMGFILE }, - { "relativePath", SUMO_ATTR_RELATIVEPATH }, - { "angle", SUMO_ATTR_ANGLE }, - { "emissionClass", SUMO_ATTR_EMISSIONCLASS }, - { "impatience", SUMO_ATTR_IMPATIENCE }, - { "startPos", SUMO_ATTR_STARTPOS }, - { "endPos", SUMO_ATTR_ENDPOS }, - { "triggered", SUMO_ATTR_TRIGGERED }, - { "containerTriggered", SUMO_ATTR_CONTAINER_TRIGGERED }, - { "parking", SUMO_ATTR_PARKING }, - { "expected", SUMO_ATTR_EXPECTED }, - { "expectedContainers", SUMO_ATTR_EXPECTED_CONTAINERS }, - { "index", SUMO_ATTR_INDEX }, - - { "entering", SUMO_ATTR_ENTERING }, - { "excludeEmpty", SUMO_ATTR_EXCLUDE_EMPTY }, - { "withInternal", SUMO_ATTR_WITH_INTERNAL }, - { "trackVehicles", SUMO_ATTR_TRACK_VEHICLES }, - { "detectPersons", SUMO_ATTR_DETECT_PERSONS }, - { "maxTraveltime", SUMO_ATTR_MAX_TRAVELTIME }, - { "minSamples", SUMO_ATTR_MIN_SAMPLES }, - { "writeAttributes", SUMO_ATTR_WRITE_ATTRIBUTES }, - - { "lon", SUMO_ATTR_LON }, - { "lat", SUMO_ATTR_LAT }, - { "geo", SUMO_ATTR_GEO }, - { "geoShape", SUMO_ATTR_GEOSHAPE }, - { "lon/lat", SUMO_ATTR_GEOPOSITION }, - { "k", SUMO_ATTR_K }, - { "v", SUMO_ATTR_V }, - { "ref", SUMO_ATTR_REF }, - { "href", SUMO_ATTR_HREF }, - { "zoom", SUMO_ATTR_ZOOM }, - { "interpolated", SUMO_ATTR_INTERPOLATED }, - { "threshold", SUMO_ATTR_THRESHOLD }, - - { "netOffset", SUMO_ATTR_NET_OFFSET }, - { "convBoundary", SUMO_ATTR_CONV_BOUNDARY }, - { "origBoundary", SUMO_ATTR_ORIG_BOUNDARY }, - { "projParameter", SUMO_ATTR_ORIG_PROJ }, - - { "tauLast", SUMO_ATTR_CF_PWAGNER2009_TAULAST }, - { "apProb", SUMO_ATTR_CF_PWAGNER2009_APPROB }, - { "delta", SUMO_ATTR_CF_IDM_DELTA }, - { "stepping", SUMO_ATTR_CF_IDM_STEPPING }, - { "adaptFactor", SUMO_ATTR_CF_IDMM_ADAPT_FACTOR }, - { "adaptTime", SUMO_ATTR_CF_IDMM_ADAPT_TIME }, - { "phi", SUMO_ATTR_CF_KERNER_PHI }, - - { "security", SUMO_ATTR_CF_WIEDEMANN_SECURITY }, - { "estimation", SUMO_ATTR_CF_WIEDEMANN_ESTIMATION }, - { "cc1", SUMO_ATTR_CF_W99_CC1 }, - { "cc2", SUMO_ATTR_CF_W99_CC2 }, - { "cc3", SUMO_ATTR_CF_W99_CC3 }, - { "cc4", SUMO_ATTR_CF_W99_CC4 }, - { "cc5", SUMO_ATTR_CF_W99_CC5 }, - { "cc6", SUMO_ATTR_CF_W99_CC6 }, - { "cc7", SUMO_ATTR_CF_W99_CC7 }, - { "cc8", SUMO_ATTR_CF_W99_CC8 }, - { "cc9", SUMO_ATTR_CF_W99_CC9 }, - - { "ccDecel", SUMO_ATTR_CF_CC_CCDECEL }, - { "constSpacing", SUMO_ATTR_CF_CC_CONSTSPACING }, - { "kp", SUMO_ATTR_CF_CC_KP }, - { "lambda", SUMO_ATTR_CF_CC_LAMBDA }, - { "c1", SUMO_ATTR_CF_CC_C1 }, - { "xi", SUMO_ATTR_CF_CC_XI }, - { "omegaN", SUMO_ATTR_CF_CC_OMEGAN }, - { "tauEngine", SUMO_ATTR_CF_CC_TAU }, - { "lanesCount", SUMO_ATTR_CF_CC_LANES_COUNT }, - { "ccAccel", SUMO_ATTR_CF_CC_CCACCEL }, - { "ploegKp", SUMO_ATTR_CF_CC_PLOEG_KP }, - { "ploegKd", SUMO_ATTR_CF_CC_PLOEG_KD }, - { "ploegH", SUMO_ATTR_CF_CC_PLOEG_H }, - { "flatbedKa", SUMO_ATTR_CF_CC_FLATBED_KA }, - { "flatbedKv", SUMO_ATTR_CF_CC_FLATBED_KV }, - { "flatbedKp", SUMO_ATTR_CF_CC_FLATBED_KP }, - { "flatbedD", SUMO_ATTR_CF_CC_FLATBED_D }, - { "flatbedH", SUMO_ATTR_CF_CC_FLATBED_H }, - - { "generateWalks", SUMO_ATTR_GENERATE_WALKS }, - { "actType", SUMO_ATTR_ACTTYPE }, - { "slope", SUMO_ATTR_SLOPE }, - { "junctionCornerDetail", SUMO_ATTR_CORNERDETAIL }, - { "junctionLinkDetail", SUMO_ATTR_LINKDETAIL }, - { "rectangularLaneCut", SUMO_ATTR_RECTANGULAR_LANE_CUT }, - { "walkingareas", SUMO_ATTR_WALKINGAREAS }, - { "lefthand", SUMO_ATTR_LEFTHAND }, - { "limitTurnSpeed", SUMO_ATTR_LIMIT_TURN_SPEED }, - { "checkLaneFoesAll", SUMO_ATTR_CHECKLANEFOES_ALL }, - { "checkLaneFoesRoundabout", SUMO_ATTR_CHECKLANEFOES_ROUNDABOUT }, - { "tlsIgnoreInternalJunctionJam", SUMO_ATTR_TLS_IGNORE_INTERNAL_JUNCTION_JAM }, - { "avoidOverlap", SUMO_ATTR_AVOID_OVERLAP }, - - { "actorConfig", SUMO_ATTR_ACTORCONFIG }, - { "vehicle", SUMO_ATTR_VEHICLE }, - { "startTime", SUMO_ATTR_STARTTIME }, - { "vehicleClass", SUMO_ATTR_VEHICLECLASS }, - { "fuel", SUMO_ATTR_FUEL }, - { "acceleration", SUMO_ATTR_ACCELERATION }, - { "origin", SUMO_ATTR_ORIGIN }, - { "destination", SUMO_ATTR_DESTINATION }, - { "visible", SUMO_ATTR_VISIBLE }, - -#ifndef WIN32 - { "commandPosix", SUMO_ATTR_COMMAND }, -#else - { "commandWindows", SUMO_ATTR_COMMAND }, -#endif - - // ActivityGen statistics file - { "inhabitants", AGEN_ATTR_INHABITANTS }, - { "households", AGEN_ATTR_HOUSEHOLDS }, - { "childrenAgeLimit", AGEN_ATTR_CHILDREN }, - { "retirementAgeLimit", AGEN_ATTR_RETIREMENT }, - { "carRate", AGEN_ATTR_CARS }, - { "unemploymentRate", AGEN_ATTR_UNEMPLOYEMENT }, - { "laborDemand", AGEN_ATTR_LABORDEMAND }, - { "footDistanceLimit", AGEN_ATTR_MAX_FOOT_DIST }, - { "incomingTraffic", AGEN_ATTR_IN_TRAFFIC }, - { "incoming", AGEN_ATTR_INCOMING }, - { "outgoingTraffic", AGEN_ATTR_OUT_TRAFFIC }, - { "outgoing", AGEN_ATTR_OUTGOING }, - { "population", AGEN_ATTR_POPULATION }, - { "workPosition", AGEN_ATTR_OUT_WORKPOSITION }, - { "hour", AGEN_ATTR_HOUR }, - { "proportion", AGEN_ATTR_PROP }, - { "capacity", AGEN_ATTR_CAPACITY }, - { "opening", AGEN_ATTR_OPENING }, - { "closing", AGEN_ATTR_CLOSING }, - { "maxTripDuration", AGEN_ATTR_MAX_TRIP_DURATION }, - { "rate", AGEN_ATTR_RATE }, - { "beginAge", AGEN_ATTR_BEGINAGE }, - { "endAge", AGEN_ATTR_ENDAGE }, - { "peopleNbr", AGEN_ATTR_PEOPLENBR }, - { "carPreference", AGEN_ATTR_CARPREF }, - { "meanTimePerKmInCity", AGEN_ATTR_CITYSPEED }, - { "freeTimeActivityRate", AGEN_ATTR_FREETIMERATE }, - { "uniformRandomTraffic", AGEN_ATTR_UNI_RAND_TRAFFIC }, - { "departureVariation", AGEN_ATTR_DEP_VARIATION }, - - // NETEDIT Attributes - { "selected", GNE_ATTR_SELECTED }, - { "modificationStatusNotForPrinting", GNE_ATTR_MODIFICATION_STATUS }, - { "shapeStart", GNE_ATTR_SHAPE_START }, - { "shapeEnd", GNE_ATTR_SHAPE_END }, - { "bidiRail", GNE_ATTR_BIDIR }, - { "blockMovement", GNE_ATTR_BLOCK_MOVEMENT }, - { "blockShape", GNE_ATTR_BLOCK_SHAPE }, - { "closedShape", GNE_ATTR_CLOSE_SHAPE }, - { "parentItem", GNE_ATTR_PARENT }, - { "dataSet", GNE_ATTR_DATASET }, - { "genericParameter", GNE_ATTR_PARAMETERS }, - { "defaultVTypeModified", GNE_ATTR_DEFAULT_VTYPE_MODIFIED }, - { "centerAfterCreation", GNE_ATTR_CENTER_AFTER_CREATION }, - { "fromBusStop", GNE_ATTR_FROM_BUSSTOP }, - { "toBusStop", GNE_ATTR_TO_BUSSTOP }, - - { "carriageLength", SUMO_ATTR_CARRIAGE_LENGTH }, - { "locomotiveLength", SUMO_ATTR_LOCOMOTIVE_LENGTH }, - { "carriageGap", SUMO_ATTR_CARRIAGE_GAP }, - - { "targetLanes", SUMO_ATTR_TARGETLANE }, - { "crossing", SUMO_ATTR_CROSSING }, - - { "xmlns:xsi", SUMO_ATTR_XMLNS }, - { "xsi:noNamespaceSchemaLocation", SUMO_ATTR_SCHEMA_LOCATION }, - - //@name RNG state saving attributes - // @{ - { "default", SUMO_ATTR_RNG_DEFAULT }, - { "routeHandler", SUMO_ATTR_RNG_ROUTEHANDLER }, - { "insertionControl", SUMO_ATTR_RNG_INSERTIONCONTROL }, - { "device", SUMO_ATTR_RNG_DEVICE }, - { "device.btreceiver", SUMO_ATTR_RNG_DEVICE_BT }, - { "device.toc", SUMO_ATTR_RNG_DEVICE_TOC }, - { "driverState", SUMO_ATTR_RNG_DRIVERSTATE }, - // @} - - // Other - { "", SUMO_ATTR_NOTHING } //< must be the last one -}; - - -const std::string SUMO_PARAM_ORIGID("origId"); - - -StringBijection::Entry SUMOXMLDefinitions::sumoNodeTypeValues[] = { - {"traffic_light", SumoXMLNodeType::TRAFFIC_LIGHT}, - {"traffic_light_unregulated", SumoXMLNodeType::TRAFFIC_LIGHT_NOJUNCTION}, - {"traffic_light_right_on_red", SumoXMLNodeType::TRAFFIC_LIGHT_RIGHT_ON_RED}, - {"rail_signal", SumoXMLNodeType::RAIL_SIGNAL}, - {"rail_crossing", SumoXMLNodeType::RAIL_CROSSING}, - {"priority", SumoXMLNodeType::PRIORITY}, - {"priority_stop", SumoXMLNodeType::PRIORITY_STOP}, - {"right_before_left", SumoXMLNodeType::RIGHT_BEFORE_LEFT}, - {"allway_stop", SumoXMLNodeType::ALLWAY_STOP}, - {"zipper", SumoXMLNodeType::ZIPPER}, - {"district", SumoXMLNodeType::DISTRICT}, - {"unregulated", SumoXMLNodeType::NOJUNCTION}, - {"internal", SumoXMLNodeType::INTERNAL}, - {"dead_end", SumoXMLNodeType::DEAD_END}, - {"DEAD_END", SumoXMLNodeType::DEAD_END_DEPRECATED}, - {"unknown", SumoXMLNodeType::UNKNOWN} //< must be the last one -}; - - -StringBijection::Entry SUMOXMLDefinitions::sumoEdgeFuncValues[] = { - {"unknown", SumoXMLEdgeFunc::UNKNOWN}, - {"normal", SumoXMLEdgeFunc::NORMAL}, - {"connector", SumoXMLEdgeFunc::CONNECTOR}, - {"crossing", SumoXMLEdgeFunc::CROSSING}, - {"walkingarea", SumoXMLEdgeFunc::WALKINGAREA}, - {"internal", SumoXMLEdgeFunc::INTERNAL} //< must be the last one -}; - - -StringBijection::Entry SUMOXMLDefinitions::laneSpreadFunctionValues[] = { - {"right", LaneSpreadFunction::RIGHT }, // default: geometry is left edge border, lanes flare to the right - {"roadCenter", LaneSpreadFunction::ROADCENTER }, // geometry is center of the bidirectional road - {"center", LaneSpreadFunction::CENTER } // geometry is center of the edge (must be the last one) -}; - -StringBijection::Entry SUMOXMLDefinitions::rightOfWayValuesInitializer[] = { - {"edgePriority", RightOfWay::EDGEPRIORITY }, - {"default", RightOfWay::DEFAULT } // default (must be the last one) -}; - -StringBijection::Entry SUMOXMLDefinitions::fringeTypeValuesInitializer[] = { - {"outer", FringeType::OUTER }, - {"inner", FringeType::INNER }, - {"default", FringeType::DEFAULT } // default (must be the last one) -}; - -StringBijection::Entry SUMOXMLDefinitions::personModeValuesInitializer[] = { - {"none", PersonMode::NONE}, - {"walk", PersonMode::WALK}, - {"bicycle", PersonMode::BICYCLE }, - {"car", PersonMode::CAR }, - {"public", PersonMode::PUBLIC} // (must be the last one) -}; - -StringBijection::Entry SUMOXMLDefinitions::linkStateValues[] = { - { "G", LINKSTATE_TL_GREEN_MAJOR }, - { "g", LINKSTATE_TL_GREEN_MINOR }, - { "r", LINKSTATE_TL_RED }, - { "u", LINKSTATE_TL_REDYELLOW }, - { "Y", LINKSTATE_TL_YELLOW_MAJOR }, - { "y", LINKSTATE_TL_YELLOW_MINOR }, - { "o", LINKSTATE_TL_OFF_BLINKING }, - { "O", LINKSTATE_TL_OFF_NOSIGNAL }, - { "M", LINKSTATE_MAJOR }, - { "m", LINKSTATE_MINOR }, - { "=", LINKSTATE_EQUAL }, - { "s", LINKSTATE_STOP }, - { "w", LINKSTATE_ALLWAY_STOP }, - { "Z", LINKSTATE_ZIPPER }, - { "-", LINKSTATE_DEADEND } //< must be the last one -}; - -const char SUMOXMLDefinitions::AllowedTLS_linkStatesInitializer[] = { - LINKSTATE_TL_GREEN_MAJOR, - LINKSTATE_TL_GREEN_MINOR, - LINKSTATE_STOP, // used for SumoXMLNodeType::TRAFFIC_LIGHT_RIGHT_ON_RED - LINKSTATE_TL_RED, - LINKSTATE_TL_REDYELLOW, - LINKSTATE_TL_YELLOW_MAJOR, - LINKSTATE_TL_YELLOW_MINOR, - LINKSTATE_TL_OFF_BLINKING, - LINKSTATE_TL_OFF_NOSIGNAL -}; -const std::string SUMOXMLDefinitions::ALLOWED_TLS_LINKSTATES(AllowedTLS_linkStatesInitializer, 9); - -StringBijection::Entry SUMOXMLDefinitions::linkDirectionValues[] = { - { "s", LinkDirection::STRAIGHT }, - { "t", LinkDirection::TURN }, - { "T", LinkDirection::TURN_LEFTHAND }, - { "l", LinkDirection::LEFT }, - { "r", LinkDirection::RIGHT }, - { "L", LinkDirection::PARTLEFT }, - { "R", LinkDirection::PARTRIGHT }, - { "invalid", LinkDirection::NODIR } //< must be the last one -}; - - -StringBijection::Entry SUMOXMLDefinitions::trafficLightTypesValues[] = { - { "static", TrafficLightType::STATIC }, - { "railSignal", TrafficLightType::RAIL_SIGNAL }, - { "railCrossing", TrafficLightType::RAIL_CROSSING }, - { "actuated", TrafficLightType::ACTUATED }, - { "delay_based", TrafficLightType::DELAYBASED }, - { "sotl_phase", TrafficLightType::SOTL_PHASE }, - { "sotl_platoon", TrafficLightType::SOTL_PLATOON }, - { "sotl_request", TrafficLightType::SOTL_REQUEST }, - { "sotl_wave", TrafficLightType::SOTL_WAVE }, - { "sotl_marching", TrafficLightType::SOTL_MARCHING }, - { "swarm", TrafficLightType::SWARM_BASED }, - { "deterministic", TrafficLightType::HILVL_DETERMINISTIC }, - { "off", TrafficLightType::OFF }, - { "", TrafficLightType::INVALID } //< must be the last one -}; - - -StringBijection::Entry SUMOXMLDefinitions::laneChangeModelValues[] = { - { "DK2008", LCM_DK2008 }, - { "LC2013", LCM_LC2013 }, - { "SL2015", LCM_SL2015 }, - { "default", LCM_DEFAULT } //< must be the last one -}; - -StringBijection::Entry SUMOXMLDefinitions::carFollowModelValues[] = { - { "IDM", SUMO_TAG_CF_IDM }, - { "IDMM", SUMO_TAG_CF_IDMM }, - { "Krauss", SUMO_TAG_CF_KRAUSS }, - { "KraussPS", SUMO_TAG_CF_KRAUSS_PLUS_SLOPE }, - { "KraussOrig1", SUMO_TAG_CF_KRAUSS_ORIG1 }, - { "KraussX", SUMO_TAG_CF_KRAUSSX }, // experimental extensions to the Krauss model - { "SmartSK", SUMO_TAG_CF_SMART_SK }, - { "Daniel1", SUMO_TAG_CF_DANIEL1 }, - { "PWagner2009", SUMO_TAG_CF_PWAGNER2009 }, - { "BKerner", SUMO_TAG_CF_BKERNER }, - { "Rail", SUMO_TAG_CF_RAIL }, - { "CC", SUMO_TAG_CF_CC }, - { "ACC", SUMO_TAG_CF_ACC }, - { "CACC", SUMO_TAG_CF_CACC }, - { "W99", SUMO_TAG_CF_W99 }, - { "Wiedemann", SUMO_TAG_CF_WIEDEMANN } //< must be the last one -}; - -StringBijection::Entry SUMOXMLDefinitions::lateralAlignmentValues[] = { - { "right", LATALIGN_RIGHT }, - { "center", LATALIGN_CENTER }, - { "arbitrary", LATALIGN_ARBITRARY }, - { "nice", LATALIGN_NICE }, - { "compact", LATALIGN_COMPACT }, - { "left", LATALIGN_LEFT } //< must be the last one -}; - -StringBijection::Entry SUMOXMLDefinitions::laneChangeActionValues[] = { - { "stay", LCA_STAY }, - { "left", LCA_LEFT }, - { "right", LCA_RIGHT }, - { "strategic", LCA_STRATEGIC }, - { "cooperative", LCA_COOPERATIVE }, - { "speedGain", LCA_SPEEDGAIN }, - { "keepRight", LCA_KEEPRIGHT }, - { "sublane", LCA_SUBLANE }, - { "traci", LCA_TRACI }, - { "urgent", LCA_URGENT }, - { "overlapping", LCA_OVERLAPPING }, - { "blocked", LCA_BLOCKED }, - { "amBL", LCA_AMBLOCKINGLEADER }, - { "amBF", LCA_AMBLOCKINGFOLLOWER }, - { "amBB", LCA_AMBACKBLOCKER }, - { "amBBS", LCA_AMBACKBLOCKER_STANDING }, - { "MR", LCA_MRIGHT }, - { "ML", LCA_MLEFT }, - - { "unknown", LCA_UNKNOWN } //< must be the last one -}; - -StringBijection::Entry SUMOXMLDefinitions::trainTypeValues[] = { - { "NGT400", TRAINTYPE_NGT400 }, - { "NGT400_16", TRAINTYPE_NGT400_16 }, - { "RB425", TRAINTYPE_RB425 }, - { "RB628", TRAINTYPE_RB628 }, - { "ICE1", TRAINTYPE_ICE1 }, - { "REDosto7", TRAINTYPE_REDOSTO7 }, - { "Freight", TRAINTYPE_FREIGHT }, - { "ICE3", TRAINTYPE_ICE3 } -}; - - -StringBijection SUMOXMLDefinitions::Tags( - SUMOXMLDefinitions::tags, SUMO_TAG_NOTHING); - -StringBijection SUMOXMLDefinitions::Attrs( - SUMOXMLDefinitions::attrs, SUMO_ATTR_NOTHING); - -StringBijection SUMOXMLDefinitions::NodeTypes( - SUMOXMLDefinitions::sumoNodeTypeValues, SumoXMLNodeType::UNKNOWN); - -StringBijection SUMOXMLDefinitions::EdgeFunctions( - SUMOXMLDefinitions::sumoEdgeFuncValues, SumoXMLEdgeFunc::INTERNAL); - -StringBijection SUMOXMLDefinitions::LaneSpreadFunctions( - SUMOXMLDefinitions::laneSpreadFunctionValues, LaneSpreadFunction::CENTER); - -StringBijection SUMOXMLDefinitions::RightOfWayValues( - SUMOXMLDefinitions::rightOfWayValuesInitializer, RightOfWay::DEFAULT); - -StringBijection SUMOXMLDefinitions::FringeTypeValues( - SUMOXMLDefinitions::fringeTypeValuesInitializer, FringeType::DEFAULT); - -StringBijection SUMOXMLDefinitions::PersonModeValues( - SUMOXMLDefinitions::personModeValuesInitializer, PersonMode::PUBLIC); - -StringBijection SUMOXMLDefinitions::LinkStates( - SUMOXMLDefinitions::linkStateValues, LINKSTATE_DEADEND); - -StringBijection SUMOXMLDefinitions::LinkDirections( - SUMOXMLDefinitions::linkDirectionValues, LinkDirection::NODIR); - -StringBijection SUMOXMLDefinitions::TrafficLightTypes( - SUMOXMLDefinitions::trafficLightTypesValues, TrafficLightType::INVALID); - -StringBijection SUMOXMLDefinitions::LaneChangeModels( - SUMOXMLDefinitions::laneChangeModelValues, LCM_DEFAULT); - -StringBijection SUMOXMLDefinitions::CarFollowModels( - SUMOXMLDefinitions::carFollowModelValues, SUMO_TAG_CF_WIEDEMANN); - -StringBijection SUMOXMLDefinitions::LateralAlignments( - SUMOXMLDefinitions::lateralAlignmentValues, LATALIGN_LEFT); - -StringBijection SUMOXMLDefinitions::LaneChangeActions( - SUMOXMLDefinitions::laneChangeActionValues, LCA_UNKNOWN); - -StringBijection SUMOXMLDefinitions::TrainTypes( - SUMOXMLDefinitions::trainTypeValues, TRAINTYPE_ICE3); - - -std::string -SUMOXMLDefinitions::getJunctionIDFromInternalEdge(const std::string internalEdge) { - assert(internalEdge[0] == ':'); - return internalEdge.substr(1, internalEdge.rfind('_') - 1); -} - - -std::string -SUMOXMLDefinitions::getEdgeIDFromLane(const std::string laneID) { - return laneID.substr(0, laneID.rfind('_')); -} - - -bool -SUMOXMLDefinitions::isValidNetID(const std::string& value) { - return (value.size() > 0) && value.find_first_of(" \t\n\r|\\'\";,:!<>&*?") == std::string::npos; -} - - -bool -SUMOXMLDefinitions::isValidVehicleID(const std::string& value) { - return (value.size() > 0) && value.find_first_of(" \t\n\r|\\'\";,!<>&*?") == std::string::npos; -} - - -bool -SUMOXMLDefinitions::isValidTypeID(const std::string& value) { - return (value.size() > 0) && value.find_first_of(" \t\n\r|\\'\";,<>&*?") == std::string::npos; -} - -bool -SUMOXMLDefinitions::isValidAdditionalID(const std::string& value) { - return (value.size() > 0) && value.find_first_of(" \t\n\r|\\'\";,!<>&*?") == std::string::npos; -} - -bool -SUMOXMLDefinitions::isValidDetectorID(const std::string& value) { - // special case: ' ' allowed - return (value.size() > 0) && value.find_first_of("\t\n\r|\\'\";,!<>&*?") == std::string::npos; -} - -bool -SUMOXMLDefinitions::isValidAttribute(const std::string& value) { - return value.find_first_of("\t\n\r@$%^&/|\\{}*'\";<>") == std::string::npos; -} - - -bool -SUMOXMLDefinitions::isValidFilename(const std::string& value) { - return (value.find_first_of("\t\n\r@$%^&|{}*'\";<>") == std::string::npos); -} - - -bool -SUMOXMLDefinitions::isValidListOfNetIDs(const std::string& value) { - const std::vector& typeIDs = StringTokenizer(value).getVector(); - if (typeIDs.empty()) { - return false; - } else { - // check that gives IDs are valid - for (auto i : typeIDs) { - if (!SUMOXMLDefinitions::isValidNetID(i)) { - return false; - } - } - return true; - } -} - - -bool -SUMOXMLDefinitions::isValidListOfTypeID(const std::string& value) { - const std::vector& typeIDs = StringTokenizer(value).getVector(); - if (typeIDs.empty()) { - return false; - } else { - // check that gives IDs are valid - for (const auto& i : typeIDs) { - if (!SUMOXMLDefinitions::isValidTypeID(i)) { - return false; - } - } - return true; - } -} - - -bool -SUMOXMLDefinitions::isValidParameterKey(const std::string& value) { - // Generic parameters keys cannot be empty - if (value.empty()) { - return false; - } else { - return isValidAttribute(value); - } -} - - -bool -SUMOXMLDefinitions::isValidParameterValue(const std::string& /*value*/) { - // Generic parameters should not be restricted (characters such as <>'" only - // reach this function if they are properly escaped in the xml inputs (and - // they are also escaped when writing) - return true; -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/utils/xml/SUMOXMLDefinitions.h b/Util/OSM2ODR/src/utils/xml/SUMOXMLDefinitions.h deleted file mode 100644 index ca6ac9930..000000000 --- a/Util/OSM2ODR/src/utils/xml/SUMOXMLDefinitions.h +++ /dev/null @@ -1,1655 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2002-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file SUMOXMLDefinitions.h -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Clemens Honomichl -/// @author Piotr Woznica -/// @author Michael Behrisch -/// @author Walter Bamberger -/// @date Sept 2002 -/// -// Definitions of elements and attributes known by SUMO -/****************************************************************************/ -#pragma once -#include - -#include - -// =========================================================================== -// definitions -// =========================================================================== -/** - * @enum SumoXMLTag - * @brief Numbers representing SUMO-XML - element names - * @see GenericSAXHandler - * @see SUMOSAXHandler - */ -enum SumoXMLTag { - /// @brief invalid tag - SUMO_TAG_NOTHING, - /// @brief root element of a network file - SUMO_TAG_NET, - /// @brief begin/end of the description of an edge - SUMO_TAG_EDGE, - /// @brief begin/end of the description of a single lane - SUMO_TAG_LANE, - /// @brief begin/end of the description of a neighboring lane - SUMO_TAG_NEIGH, - /// @brief begin/end of the description of a Point of interest - SUMO_TAG_POI, - /// @brief begin/end of the description of a Point of interest over Lane (used by Netedit) - SUMO_TAG_POILANE, - /// @brief begin/end of the description of a polygon - SUMO_TAG_POLY, - /// @brief begin/end of the description of a junction - SUMO_TAG_JUNCTION, - /// @brief begin/end of the description of an edge restriction - SUMO_TAG_RESTRICTION, - /// @brief an e1 detector - SUMO_TAG_E1DETECTOR, - /// @brief alternative tag for e1 detector - SUMO_TAG_INDUCTION_LOOP, - /// @brief an e2 detector - SUMO_TAG_E2DETECTOR, - /// @brief an e2 detector over multiple lanes (used by Netedit) - SUMO_TAG_E2DETECTOR_MULTILANE, - /// @brief alternative tag for e2 detector - SUMO_TAG_LANE_AREA_DETECTOR, - /// @brief an e3 detector - SUMO_TAG_E3DETECTOR, - /// @brief alternative tag for e3 detector - SUMO_TAG_ENTRY_EXIT_DETECTOR, - /// @brief an edge based mean data detector - SUMO_TAG_MEANDATA_EDGE, - /// @brief a lane based mean data detector - SUMO_TAG_MEANDATA_LANE, - /// @brief an e3 entry point - SUMO_TAG_DET_ENTRY, - /// @brief an e3 exit point - SUMO_TAG_DET_EXIT, - /// @brief An edge-following detector - SUMO_TAG_EDGEFOLLOWDETECTOR, - /// @brief An instantenous induction loop - SUMO_TAG_INSTANT_INDUCTION_LOOP, - /// @brief A variable speed sign - SUMO_TAG_VSS, - /// @brief A calibrator placed over edge - SUMO_TAG_CALIBRATOR, - /// @brief A calibrator placed over lane (used in netedit) - SUMO_TAG_LANECALIBRATOR, - /// @brief A rerouter - SUMO_TAG_REROUTER, - /// @brief A bus stop - SUMO_TAG_BUS_STOP, - /// @brief A train stop (alias for bus stop) - SUMO_TAG_TRAIN_STOP, - /// @brief A pt line - SUMO_TAG_PT_LINE, - /// @brief An access point for a train stop - SUMO_TAG_ACCESS, - /// @brief A container stop - SUMO_TAG_CONTAINER_STOP, - /// @brief A parking area - SUMO_TAG_PARKING_AREA, - /// @brief A parking space for a single vehicle within a parking area - SUMO_TAG_PARKING_SPACE, - /// @brief A Charging Station - SUMO_TAG_CHARGING_STATION, - /// @brief An overhead wire segment - SUMO_TAG_OVERHEAD_WIRE_SEGMENT, - /// @brief An overhead wire section - SUMO_TAG_OVERHEAD_WIRE_SECTION, - /// @brief A traction substation - SUMO_TAG_TRACTION_SUBSTATION, - /// @brief An overhead wire clamp (connection of wires in opposite directions) - SUMO_TAG_OVERHEAD_WIRE_CLAMP, - /// @brief a vtypeprobe detector - SUMO_TAG_VTYPEPROBE, - /// @brief a routeprobe detector - SUMO_TAG_ROUTEPROBE, - /// @brief root element of a route file - SUMO_TAG_ROUTES, - /// @brief description of a vehicle - SUMO_TAG_VEHICLE, - /// @brief description of a vehicle type - SUMO_TAG_VTYPE, - /// @brief description of a person type (used in NETEDIT) - SUMO_TAG_PTYPE, - /// @brief begin/end of the description of a route - SUMO_TAG_ROUTE, - /// @brief description of a logic request within the junction - SUMO_TAG_REQUEST, - /// @brief a source - SUMO_TAG_SOURCE, - /// @brief a traffic assignment zone - SUMO_TAG_TAZ, - /// @brief a source within a district (connection road) - SUMO_TAG_TAZSOURCE, - /// @brief a sink within a district (connection road) - SUMO_TAG_TAZSINK, - /// @brief a traffic light - SUMO_TAG_TRAFFIC_LIGHT, - /// @brief a traffic light logic - SUMO_TAG_TLLOGIC, - /// @brief a single phase description - SUMO_TAG_PHASE, - /// @brief a single trip definition (used by router) - SUMO_TAG_TRIP, - /// @brief a single trip definition that uses TAZs (used in NETEDIT) - SUMO_TAG_TRIP_TAZ, - /// @brief a flow definitio nusing a from-to edges instead of a route (used by router) - SUMO_TAG_FLOW, - /// @brief a flow definition within in Calibrator (used in NETEDIT) - SUMO_TAG_FLOW_CALIBRATOR, - /// @brief a flow state definition (used when saving and loading simulatino state) - SUMO_TAG_FLOWSTATE, - /// @brief trigger: a step description - SUMO_TAG_STEP, - /// @brief an aggreagated-output interval - SUMO_TAG_INTERVAL, - /// @brief a relation between two edges - SUMO_TAG_EDGEREL, - /// @brief a relation between two TAZs - SUMO_TAG_TAZREL, - /// @brief The definition of a periodic event - SUMO_TAG_TIMEDEVENT, - /// @brief Incoming edge specification (jtrrouter) - SUMO_TAG_FROMEDGE, - /// @brief Outgoing edge specification (jtrrouter) - SUMO_TAG_TOEDGE, - /// @brief Sink(s) specification - SUMO_TAG_SINK, - /// @brief parameter associated to a certain key - SUMO_TAG_PARAM, - SUMO_TAG_WAUT, - SUMO_TAG_WAUT_SWITCH, - SUMO_TAG_WAUT_JUNCTION, - /// @brief segment of a lane - SUMO_TAG_SEGMENT, - /// @brief delete certain element (note: DELETE is a macro) - SUMO_TAG_DEL, - /// @brief stop for vehicles - SUMO_TAG_STOP, - /// @brief stop placed over a lane (used in netedit) - SUMO_TAG_STOP_LANE, - /// @brief stop placed over a busStop (used in netedit) - SUMO_TAG_STOP_BUSSTOP, - /// @brief stop placed over a containerStop (used in netedit) - SUMO_TAG_STOP_CONTAINERSTOP, - /// @brief stop placed over a charging station (used in netedit) - SUMO_TAG_STOP_CHARGINGSTATION, - /// @brief stop placed over a parking area (used in netedit) - SUMO_TAG_STOP_PARKINGAREA, - /// @brief probability of destiny of a reroute - SUMO_TAG_DEST_PROB_REROUTE, - /// @brief reroute of type closing - SUMO_TAG_CLOSING_REROUTE, - /// @brief lane of a reroute of type closing - SUMO_TAG_CLOSING_LANE_REROUTE, - /// @brief probability of route of a reroute - SUMO_TAG_ROUTE_PROB_REROUTE, - /// @brief entry for an alternative parking zone - SUMO_TAG_PARKING_ZONE_REROUTE, - /// @brief type of polygon - SUMO_TAG_POLYTYPE, - /// @brief connectio between two lanes - SUMO_TAG_CONNECTION, - /// @brief prohibition of circulation between two edges - SUMO_TAG_PROHIBITION, - /// @brief split something - SUMO_TAG_SPLIT, - /// @brief alternative definition for junction - SUMO_TAG_NODE, - /// @brief type - SUMO_TAG_TYPE, - /// @brief definition of a detector - SUMO_TAG_DETECTOR_DEFINITION, - /// @brief distribution of a route - SUMO_TAG_ROUTE_DISTRIBUTION, - /// @brief distribution of a vehicle type - SUMO_TAG_VTYPE_DISTRIBUTION, - /// @brief vaporizer of vehicles - SUMO_TAG_VAPORIZER, - /// @brief roundabout defined in junction - SUMO_TAG_ROUNDABOUT, - /// @brief Join operation - SUMO_TAG_JOIN, - /// @brief join exlude operation - SUMO_TAG_JOINEXCLUDE, - /// @brief crossing between edges for pedestrians - SUMO_TAG_CROSSING, - /// @brief walking area for pedestrians - SUMO_TAG_WALKINGAREA, - /// @brief Information on vClass specific stop offsets at lane end - SUMO_TAG_STOPOFFSET, - - SUMO_TAG_WAY, - SUMO_TAG_ND, - SUMO_TAG_TAG, - SUMO_TAG_RELATION, - SUMO_TAG_MEMBER, - - /// @name parameters associated to view settings - /// @{ - SUMO_TAG_VIEWSETTINGS, - SUMO_TAG_VIEWSETTINGS_DECAL, - SUMO_TAG_VIEWSETTINGS_LIGHT, - SUMO_TAG_VIEWSETTINGS_SCHEME, - SUMO_TAG_VIEWSETTINGS_OPENGL, - SUMO_TAG_VIEWSETTINGS_BACKGROUND, - SUMO_TAG_VIEWSETTINGS_EDGES, - SUMO_TAG_VIEWSETTINGS_VEHICLES, - SUMO_TAG_VIEWSETTINGS_PERSONS, - SUMO_TAG_VIEWSETTINGS_CONTAINERS, - SUMO_TAG_VIEWSETTINGS_JUNCTIONS, - SUMO_TAG_VIEWSETTINGS_ADDITIONALS, - SUMO_TAG_VIEWSETTINGS_POIS, - SUMO_TAG_VIEWSETTINGS_POLYS, - SUMO_TAG_VIEWSETTINGS_LEGEND, - SUMO_TAG_VIEWSETTINGS_EVENT, - SUMO_TAG_VIEWSETTINGS_EVENT_JAM_TIME, - SUMO_TAG_INCLUDE, - SUMO_TAG_DELAY, - SUMO_TAG_VIEWPORT, - SUMO_TAG_SNAPSHOT, - SUMO_TAG_BREAKPOINT, - SUMO_TAG_LOCATION, - SUMO_TAG_COLORSCHEME, - SUMO_TAG_SCALINGSCHEME, - SUMO_TAG_ENTRY, - SUMO_TAG_RNGSTATE, - SUMO_TAG_RNGLANE, - /// @} - - SUMO_TAG_VEHICLETRANSFER, - SUMO_TAG_DEVICE, - - /// @name Car-Following models - /// @{ - SUMO_TAG_CF_KRAUSS, - SUMO_TAG_CF_KRAUSS_PLUS_SLOPE, - SUMO_TAG_CF_KRAUSS_ORIG1, - SUMO_TAG_CF_KRAUSSX, - SUMO_TAG_CF_SMART_SK, - SUMO_TAG_CF_DANIEL1, - SUMO_TAG_CF_IDM, - SUMO_TAG_CF_IDMM, - SUMO_TAG_CF_PWAGNER2009, - SUMO_TAG_CF_BKERNER, - SUMO_TAG_CF_WIEDEMANN, - SUMO_TAG_CF_W99, - SUMO_TAG_CF_ACC, - SUMO_TAG_CF_CACC, - SUMO_TAG_CF_RAIL, - SUMO_TAG_CF_CC, - /// @} - - /// @name Persons - /// @{ - SUMO_TAG_PERSON, - SUMO_TAG_PERSONTRIP, - SUMO_TAG_RIDE, - SUMO_TAG_WALK, - SUMO_TAG_PERSONFLOW, - /// @} - - /// @name Data elements (used by Netedit) - /// @{ - SUMO_TAG_DATASET, - SUMO_TAG_DATAINTERVAL, - /// @} - - SUMO_TAG_CONTAINER, - SUMO_TAG_TRANSPORT, - SUMO_TAG_TRANSHIP, - SUMO_TAG_TRAJECTORIES, - SUMO_TAG_TIMESTEP, - SUMO_TAG_TIMESLICE, - SUMO_TAG_ACTORCONFIG, - SUMO_TAG_MOTIONSTATE, - SUMO_TAG_OD_PAIR, - - /// @brief ActivityGen Tags - AGEN_TAG_GENERAL, - /// @brief streets object - AGEN_TAG_STREET, - /// @brief workingHours object - AGEN_TAG_WORKHOURS, - /// @brief opening for workingHours object - AGEN_TAG_OPENING, - /// @brief closing for workingHours object - AGEN_TAG_CLOSING, - /// @brief school object - AGEN_TAG_SCHOOLS, - /// @brief schools object - AGEN_TAG_SCHOOL, - /// @brief busStation and bus objects - AGEN_TAG_BUSSTATION, - /// @brief bus line - AGEN_TAG_BUSLINE, - /// @brief stations for certain vehicles - AGEN_TAG_STATIONS, - /// @brief rev stations for certain vehicles - AGEN_TAG_REV_STATIONS, - /// @brief station for a certain vehicle - AGEN_TAG_STATION, - /// @brief frequency of a object - AGEN_TAG_FREQUENCY, - /// @brief population and children accompaniment brackets - AGEN_TAG_POPULATION, - /// @brief alternative definition for Population - AGEN_TAG_BRACKET, - //AGEN_TAG_CHILD_ACOMP, - /// @brief city entrances - AGEN_TAG_CITYGATES, - /// @brief alternative definition for city entrances - AGEN_TAG_ENTRANCE, - /// @brief parameters - AGEN_TAG_PARAM, - - /// @name Persons plans (used by Netedit) - /// @{ - // person trips - GNE_TAG_PERSONTRIP_EDGE_EDGE, - GNE_TAG_PERSONTRIP_EDGE_BUSSTOP, - GNE_TAG_PERSONTRIP_BUSSTOP_EDGE, - GNE_TAG_PERSONTRIP_BUSSTOP_BUSSTOP, - // walks - GNE_TAG_WALK_EDGE_EDGE, - GNE_TAG_WALK_BUSSTOP_EDGE, - GNE_TAG_WALK_BUSSTOP_BUSSTOP, - GNE_TAG_WALK_EDGE_BUSSTOP, - GNE_TAG_WALK_EDGES, - GNE_TAG_WALK_ROUTE, - // rides - GNE_TAG_RIDE_EDGE_EDGE, - GNE_TAG_RIDE_EDGE_BUSSTOP, - GNE_TAG_RIDE_BUSSTOP_EDGE, - GNE_TAG_RIDE_BUSSTOP_BUSSTOP, - // person stops - GNE_TAG_PERSONSTOP_BUSSTOP, - GNE_TAG_PERSONSTOP_EDGE, - /// @brief description of a vehicle with an embedded route (used in NETEDIT) - GNE_TAG_VEHICLEWITHROUTE, - /// @brief embedded route (used in NETEDIT) - GNE_TAG_ROUTE_EMBEDDED, - /// @brief a flow definition nusing a route instead of a from-to edges route (used in NETEDIT) - GNE_TAG_FLOW_ROUTE, - /// @brief description of a vehicle with an embedded route (used in NETEDIT) - GNE_TAG_FLOW_WITHROUTE, - /// @brief description of a person with an embedded route (used in NETEDIT) - GNE_TAG_PERSON_EMBEDDED - /// @} -}; - - -/** - * @enum SumoXMLAttr - * @brief Numbers representing SUMO-XML - attributes - * @see GenericSAXHandler - * @see SUMOSAXHandler - */ -enum SumoXMLAttr { - /// @brief invalid attribute - SUMO_ATTR_NOTHING = 0, - - /// @name meanData output attributes - /// @note: sorted first to simplify filtering written attributes with bit operations - /// @{ - /// MSMeanData_Net - SUMO_ATTR_SAMPLEDSECONDS = 1, - SUMO_ATTR_DENSITY = 2, - SUMO_ATTR_LANEDENSITY = 3, - SUMO_ATTR_OCCUPANCY = 4, - SUMO_ATTR_WAITINGTIME = 5, - SUMO_ATTR_SPEED = 6, - SUMO_ATTR_DEPARTED = 7, - SUMO_ATTR_ARRIVED = 8, - SUMO_ATTR_ENTERED = 9, - SUMO_ATTR_LEFT = 10, - SUMO_ATTR_VAPORIZED = 11, - SUMO_ATTR_TRAVELTIME = 12, - SUMO_ATTR_LANECHANGEDFROM = 13, - SUMO_ATTR_LANECHANGEDTO = 14, - SUMO_ATTR_OVERLAPTRAVELTIME = 15, - /// MSMeanData_Emissions - SUMO_ATTR_CO_ABS = 16, - SUMO_ATTR_CO2_ABS = 17, - SUMO_ATTR_HC_ABS = 18, - SUMO_ATTR_PMX_ABS = 19, - SUMO_ATTR_NOX_ABS = 20, - SUMO_ATTR_FUEL_ABS = 21, - SUMO_ATTR_ELECTRICITY_ABS = 22, - SUMO_ATTR_CO_NORMED = 23, - SUMO_ATTR_CO2_NORMED = 24, - SUMO_ATTR_HC_NORMED = 25, - SUMO_ATTR_PMX_NORMED = 26, - SUMO_ATTR_NOX_NORMED = 27, - SUMO_ATTR_FUEL_NORMED = 28, - SUMO_ATTR_ELECTRICITY_NORMED = 29, - SUMO_ATTR_CO_PERVEH = 30, - SUMO_ATTR_CO2_PERVEH = 31, - SUMO_ATTR_HC_PERVEH = 32, - SUMO_ATTR_PMX_PERVEH = 33, - SUMO_ATTR_NOX_PERVEH = 34, - SUMO_ATTR_FUEL_PERVEH = 35, - SUMO_ATTR_ELECTRICITY_PERVEH = 36, - /// MSMeanData_Harmonoise - SUMO_ATTR_NOISE = 37, - /// MSMeanData_Amitran - SUMO_ATTR_AMOUNT = 38, - SUMO_ATTR_AVERAGESPEED = 39, - /// @} - - /// @name common attributes - /// @{ - SUMO_ATTR_ID, - SUMO_ATTR_REFID, - SUMO_ATTR_NAME, - SUMO_ATTR_TYPE, - SUMO_ATTR_VERSION, - SUMO_ATTR_PRIORITY, - SUMO_ATTR_NUMLANES, - SUMO_ATTR_ONEWAY, - SUMO_ATTR_WIDTH, - SUMO_ATTR_WIDTHRESOLUTION, - SUMO_ATTR_MAXWIDTH, - SUMO_ATTR_MINWIDTH, - SUMO_ATTR_SIDEWALKWIDTH, - SUMO_ATTR_BIKELANEWIDTH, - SUMO_ATTR_REMOVE, - SUMO_ATTR_LENGTH, - SUMO_ATTR_BIDI, - SUMO_ATTR_DISTANCE, - SUMO_ATTR_ID_BEFORE, - SUMO_ATTR_ID_AFTER, - SUMO_ATTR_X, - SUMO_ATTR_Y, - SUMO_ATTR_Z, - SUMO_ATTR_CENTER_X, - SUMO_ATTR_CENTER_Y, - SUMO_ATTR_CENTER_Z, - /// @} - - /// @name sumo-junction attributes - /// @{ - SUMO_ATTR_KEY, - SUMO_ATTR_REQUESTSIZE, - SUMO_ATTR_REQUEST, - SUMO_ATTR_RESPONSE, - SUMO_ATTR_PROGRAMID, - SUMO_ATTR_OFFSET, - SUMO_ATTR_ENDOFFSET, - SUMO_ATTR_INCLANES, - SUMO_ATTR_INTLANES, - /// @} - - /// @name the weight of a district's source or sink - /// @{ - SUMO_ATTR_WEIGHT, - SUMO_ATTR_NODE, - SUMO_ATTR_EDGE, - /// @} - - /// @brief the edges of a route - SUMO_ATTR_EDGES, - - /// @name vehicle attributes - /// @{ - SUMO_ATTR_DEPART, - SUMO_ATTR_DEPARTLANE, - SUMO_ATTR_DEPARTPOS, - SUMO_ATTR_DEPARTPOS_LAT, - SUMO_ATTR_DEPARTSPEED, - SUMO_ATTR_ARRIVALLANE, - SUMO_ATTR_ARRIVALPOS, - SUMO_ATTR_ARRIVALPOS_LAT, - SUMO_ATTR_ARRIVALSPEED, - SUMO_ATTR_ROUTE, - SUMO_ATTR_MAXSPEED, - SUMO_ATTR_MAXSPEED_LAT, - SUMO_ATTR_LATALIGNMENT, - SUMO_ATTR_MINGAP_LAT, - SUMO_ATTR_ACCEL, - SUMO_ATTR_DECEL, - SUMO_ATTR_EMERGENCYDECEL, - SUMO_ATTR_APPARENTDECEL, - SUMO_ATTR_ACTIONSTEPLENGTH, - SUMO_ATTR_VCLASS, - SUMO_ATTR_VCLASSES, - SUMO_ATTR_EXCEPTIONS, - SUMO_ATTR_REPNUMBER, - SUMO_ATTR_SPEEDFACTOR, - SUMO_ATTR_SPEEDDEV, - SUMO_ATTR_LANE_CHANGE_MODEL, - SUMO_ATTR_CAR_FOLLOW_MODEL, - SUMO_ATTR_MINGAP, - SUMO_ATTR_COLLISION_MINGAP_FACTOR, - SUMO_ATTR_BOARDING_DURATION, - SUMO_ATTR_LOADING_DURATION, - /// @brief Class specific timing values for vehicle manoeuvering through angle ranges - SUMO_ATTR_MANEUVER_ANGLE_TIMES, - /// @} - - /// @name elecHybrid output attributes - /// @{ - /// @brief power charging from overhead wire to battery if the battery SoC is not full - SUMO_ATTR_OVERHEADWIRECHARGINGPOWER, - /// @} - - /// @name overheadWire attributes - /// @{ - SUMO_ATTR_OVERHEAD_WIRE_SEGMENT, - SUMO_ATTR_OVERHEAD_WIRE_SECTION, - /// @brief voltage of the traction substation [V] - SUMO_ATTR_VOLTAGE, - /// @brief a voltage source on the overhead wire segment [bool] - SUMO_ATTR_VOLTAGESOURCE, - /// @brief current limit of the traction substation [A] - SUMO_ATTR_CURRENTLIMIT, - /// @brief id of a traction substation substation - SUMO_ATTR_SUBSTATIONID, - /// @brief resistivity of overhead wires - SUMO_ATTR_OVERHEAD_WIRE_RESISTIVITY, - /// @brief forbidden lanes for overhead wire segment - SUMO_ATTR_OVERHEAD_WIRE_FORBIDDEN, - /// @brief overhead wire clamps for overhead wire segment - SUMO_ATTR_OVERHEAD_WIRE_CLAMPS, - /// @brief id of the overhead wire segment, to the start of which the overhead wire clamp is connected - SUMO_ATTR_OVERHEAD_WIRE_CLAMP_START, - /// @brief id of the overhead wire segment, to the end of which the overhead wire clamp is connected - SUMO_ATTR_OVERHEAD_WIRE_CLAMP_END, - /// @} - - /// @name charging stations attributes - /// @{ - /// @brief charge in W/s of the Charging Stations - SUMO_ATTR_CHARGINGPOWER, - /// @brief Eficiency of the charge in Charging Stations - SUMO_ATTR_EFFICIENCY, - /// @brief Allow/disallow charge in transit in Charging Stations - SUMO_ATTR_CHARGEINTRANSIT, - /// @brief Delay in the charge of charging stations - SUMO_ATTR_CHARGEDELAY, - /// @} - - /// @name battery device parameters - /// @{ - /// @brief Actual battery capacity - SUMO_ATTR_ACTUALBATTERYCAPACITY, - /// @brief Maxium battery capacity - SUMO_ATTR_MAXIMUMBATTERYCAPACITY, - /// @brief Maximum Power - SUMO_ATTR_MAXIMUMPOWER, - /// @brief Vehicle mass - SUMO_ATTR_VEHICLEMASS, - /// @brief Front surface area - SUMO_ATTR_FRONTSURFACEAREA, - /// @brief Air drag coefficient - SUMO_ATTR_AIRDRAGCOEFFICIENT, - /// @brief Internal moment of inertia - SUMO_ATTR_INTERNALMOMENTOFINERTIA, - /// @brief Radial drag coefficient - SUMO_ATTR_RADIALDRAGCOEFFICIENT, - /// @brief Roll Drag coefficient - SUMO_ATTR_ROLLDRAGCOEFFICIENT, - /// @brief Constant Power Intake - SUMO_ATTR_CONSTANTPOWERINTAKE, - /// @brief Propulsion efficiency - SUMO_ATTR_PROPULSIONEFFICIENCY, - /// @brief Recuperation efficiency (constant) - SUMO_ATTR_RECUPERATIONEFFICIENCY, - /// @brief Recuperation efficiency (by deceleration) - SUMO_ATTR_RECUPERATIONEFFICIENCY_BY_DECELERATION, - /// @brief Stopping treshold - SUMO_ATTR_STOPPINGTRESHOLD, - /// @} - - /// @name elecHybrid device export parameters - /// @{ - // @brief Overhead Wire Segment ID - SUMO_ATTR_OVERHEADWIREID, - // @brief Traction substation ID - SUMO_ATTR_TRACTIONSUBSTATIONID, - // @brief Electric current drawn from overhead wire - SUMO_ATTR_CURRENTFROMOVERHEADWIRE, - // @brief Voltage of overhead wire (above the vehicle) - SUMO_ATTR_VOLTAGEOFOVERHEADWIRE, - // @brief Circuit solver alpha parameter - SUMO_ATTR_ALPHACIRCUITSOLVER, - /// @} - - /// @name battery export parameters - /// @{ - /// @brief charging status - SUMO_ATTR_CHARGING_STATUS, - /// @brief Energy consumed - SUMO_ATTR_ENERGYCONSUMED, - /// @brief Charging Station ID - SUMO_ATTR_CHARGINGSTATIONID, - /// @brief tgotal of Energy charged - SUMO_ATTR_ENERGYCHARGED, - /// @brief Energy charged in transit - SUMO_ATTR_ENERGYCHARGEDINTRANSIT, - /// @brief Energy charged stopped - SUMO_ATTR_ENERGYCHARGEDSTOPPED, - /// @brief Position on lane - SUMO_ATTR_POSONLANE, - /// @brief Time stopped - SUMO_ATTR_TIMESTOPPED, - /// @} - - /// @name chargingStations export parameters - /// @{ - /// @brief total energy charged by charging station - SUMO_ATTR_TOTALENERGYCHARGED, - /// @brief number of steps that a vehicle is charging - SUMO_ATTR_CHARGINGSTEPS, - /// @brief total energy charged into a single vehicle - SUMO_ATTR_TOTALENERGYCHARGED_VEHICLE, - /// @brief timestep in which charging begins - SUMO_ATTR_CHARGINGBEGIN, - /// @brief timesteps in which charging ends - SUMO_ATTR_CHARGINGEND, - /// @brief energy provied by charging station at certain timestep - SUMO_ATTR_PARTIALCHARGE, - /// @} - - /// @name Car following model attributes - /// @{ - SUMO_ATTR_SIGMA, // used by: Krauss - SUMO_ATTR_TAU, // Krauss - SUMO_ATTR_TMP1, - SUMO_ATTR_TMP2, - SUMO_ATTR_TMP3, - SUMO_ATTR_TMP4, - SUMO_ATTR_TMP5, - /// @} - - // @name Train ACC model attributes - /// @{ - SUMO_ATTR_SC_GAIN, - SUMO_ATTR_GCC_GAIN_SPEED, - SUMO_ATTR_GCC_GAIN_SPACE, - SUMO_ATTR_GC_GAIN_SPEED, - SUMO_ATTR_GC_GAIN_SPACE, - SUMO_ATTR_CA_GAIN_SPEED, - SUMO_ATTR_CA_GAIN_SPACE, - /// @} - - // @name Train CACC model attributes - /// @{ - SUMO_ATTR_SC_GAIN_CACC, - SUMO_ATTR_GCC_GAIN_GAP_CACC, - SUMO_ATTR_GCC_GAIN_GAP_DOT_CACC, - SUMO_ATTR_GC_GAIN_GAP_CACC, - SUMO_ATTR_GC_GAIN_GAP_DOT_CACC, - SUMO_ATTR_CA_GAIN_GAP_CACC, - SUMO_ATTR_CA_GAIN_GAP_DOT_CACC, - SUMO_ATTR_HEADWAY_TIME_CACC_TO_ACC, - /// @} - - - /// @name Train model attributes - /// @{ - SUMO_ATTR_TRAIN_TYPE, //used by: Rail - /// @} - - /// @name Lane changing model attributes - /// @{ - SUMO_ATTR_LCA_STRATEGIC_PARAM, - SUMO_ATTR_LCA_COOPERATIVE_PARAM, - SUMO_ATTR_LCA_SPEEDGAIN_PARAM, - SUMO_ATTR_LCA_KEEPRIGHT_PARAM, - SUMO_ATTR_LCA_SUBLANE_PARAM, - SUMO_ATTR_LCA_OPPOSITE_PARAM, - SUMO_ATTR_LCA_PUSHY, - SUMO_ATTR_LCA_PUSHYGAP, - SUMO_ATTR_LCA_ASSERTIVE, - SUMO_ATTR_LCA_IMPATIENCE, - SUMO_ATTR_LCA_TIME_TO_IMPATIENCE, - SUMO_ATTR_LCA_ACCEL_LAT, - SUMO_ATTR_LCA_LOOKAHEADLEFT, - SUMO_ATTR_LCA_SPEEDGAINRIGHT, - SUMO_ATTR_LCA_SPEEDGAIN_LOOKAHEAD, - SUMO_ATTR_LCA_COOPERATIVE_ROUNDABOUT, - SUMO_ATTR_LCA_COOPERATIVE_SPEED, - SUMO_ATTR_LCA_MAXSPEEDLATSTANDING, - SUMO_ATTR_LCA_MAXSPEEDLATFACTOR, - SUMO_ATTR_LCA_TURN_ALIGNMENT_DISTANCE, - SUMO_ATTR_LCA_OVERTAKE_RIGHT, - SUMO_ATTR_LCA_LANE_DISCIPLINE, - SUMO_ATTR_LCA_SIGMA, - SUMO_ATTR_LCA_EXPERIMENTAL1, - /// @} - - /// @name Junction model attributes - /// @{ - SUMO_ATTR_JM_CROSSING_GAP, - SUMO_ATTR_JM_DRIVE_AFTER_YELLOW_TIME, - SUMO_ATTR_JM_DRIVE_AFTER_RED_TIME, - SUMO_ATTR_JM_DRIVE_RED_SPEED, - SUMO_ATTR_JM_IGNORE_KEEPCLEAR_TIME, - SUMO_ATTR_JM_IGNORE_FOE_SPEED, - SUMO_ATTR_JM_IGNORE_FOE_PROB, - SUMO_ATTR_JM_SIGMA_MINOR, - SUMO_ATTR_JM_TIMEGAP_MINOR, - /// @} - - /// @name route alternatives / distribution attributes - /// @{ - SUMO_ATTR_LAST, - SUMO_ATTR_COST, - SUMO_ATTR_COSTS, - SUMO_ATTR_SAVINGS, - SUMO_ATTR_PROB, - SUMO_ATTR_COUNT, - SUMO_ATTR_PROBS, - SUMO_ATTR_ROUTES, - SUMO_ATTR_VTYPES, - /// @} - - /// @name trip definition attributes - /// @{ - SUMO_ATTR_LANE, - SUMO_ATTR_LANES, - SUMO_ATTR_FROM, - SUMO_ATTR_TO, - SUMO_ATTR_FROMLONLAT, - SUMO_ATTR_TOLONLAT, - SUMO_ATTR_FROMXY, - SUMO_ATTR_TOXY, - SUMO_ATTR_FROMJUNCTION, - SUMO_ATTR_TOJUNCTION, - SUMO_ATTR_PERIOD, - SUMO_ATTR_REPEAT, - SUMO_ATTR_FROM_TAZ, - SUMO_ATTR_TO_TAZ, - SUMO_ATTR_REROUTE, - SUMO_ATTR_PERSON_CAPACITY, - SUMO_ATTR_CONTAINER_CAPACITY, - SUMO_ATTR_PARKING_LENGTH, - SUMO_ATTR_PERSON_NUMBER, - SUMO_ATTR_CONTAINER_NUMBER, - SUMO_ATTR_MODES, - SUMO_ATTR_WALKFACTOR, - /// @} - - /// @name source definitions - /// @{ - SUMO_ATTR_FUNCTION, - SUMO_ATTR_POSITION, - SUMO_ATTR_POSITION_LAT, - SUMO_ATTR_FREQUENCY, - SUMO_ATTR_STYLE, - SUMO_ATTR_FILE, - SUMO_ATTR_JUNCTION, - SUMO_ATTR_NUMBER, - SUMO_ATTR_DURATION, - SUMO_ATTR_UNTIL, - SUMO_ATTR_ARRIVAL, - SUMO_ATTR_EXTENSION, - SUMO_ATTR_ROUTEPROBE, - /// @} - - /// @brief the edges crossed by a pedestrian crossing - SUMO_ATTR_CROSSING_EDGES, - /// @brief trigger: the time of the step - SUMO_ATTR_TIME, - /// @brief weights: time range begin - SUMO_ATTR_BEGIN, - /// @brief weights: time range end - SUMO_ATTR_END, - /// @brief link,node: the traffic light id responsible for this link - SUMO_ATTR_TLID, - /// @brief node: the type of traffic light - SUMO_ATTR_TLTYPE, - /// @brief link: the index of the link within the traffic light - SUMO_ATTR_TLLINKINDEX, - /// @brief link: the index of the opposite direction link of a pedestrian crossing - SUMO_ATTR_TLLINKINDEX2, - /// @brief edge: the shape in xml-definition - SUMO_ATTR_SHAPE, - /// @brief The information about how to spread the lanes from the given position - SUMO_ATTR_SPREADTYPE, - /// @brief The turning radius at an intersection in m - SUMO_ATTR_RADIUS, - /// @brief Whether vehicles must keep the junction clear - SUMO_ATTR_KEEP_CLEAR, - /// @brief How to compute right of way - SUMO_ATTR_RIGHT_OF_WAY, - /// @brief Fringe type of node - SUMO_ATTR_FRINGE, - /// @brief whether a given shape is user-defined - SUMO_ATTR_CUSTOMSHAPE, - /// @brief A color information - SUMO_ATTR_COLOR, - /// @brief The abstract direction of a link - SUMO_ATTR_DIR, - /// @brief The state of a link - SUMO_ATTR_STATE, - /// @brief foe visibility distance of a link - SUMO_ATTR_VISIBILITY_DISTANCE, - /// @brief A layer number - SUMO_ATTR_LAYER, - /// @brief Fill the polygon - SUMO_ATTR_FILL, - SUMO_ATTR_LINEWIDTH, - SUMO_ATTR_PREFIX, - SUMO_ATTR_DISCARD, - - SUMO_ATTR_FROM_LANE, - SUMO_ATTR_TO_LANE, - SUMO_ATTR_DEST, - SUMO_ATTR_SOURCE, - SUMO_ATTR_VIA, - SUMO_ATTR_VIALONLAT, - SUMO_ATTR_VIAXY, - SUMO_ATTR_VIAJUNCTIONS, - /// @brief a list of node ids, used for controlling joining - SUMO_ATTR_NODES, - - /// @name Attributes for actuated traffic lights: - /// @{ - /// @brief minimum duration of a phase - SUMO_ATTR_MINDURATION, - /// @brief maximum duration of a phase - SUMO_ATTR_MAXDURATION, - /// @brief succesor phase index - SUMO_ATTR_NEXT, - /// @} - - /// @name Attributes for junction-internal lanes - /// @{ - /// @brief Information within the junction logic which internal lanes block external - SUMO_ATTR_FOES, - /// @} - - /// @name Attributes for detectors - /// @{ - /// @brief Information whether the detector shall be continued on the folowing lanes - SUMO_ATTR_CONT, - SUMO_ATTR_CONTPOS, - SUMO_ATTR_HALTING_TIME_THRESHOLD, - SUMO_ATTR_HALTING_SPEED_THRESHOLD, - SUMO_ATTR_JAM_DIST_THRESHOLD, - SUMO_ATTR_SHOW_DETECTOR, - SUMO_ATTR_OPEN_ENTRY, - /// @} - - SUMO_ATTR_WAUT_ID, - SUMO_ATTR_JUNCTION_ID, - SUMO_ATTR_PROCEDURE, - SUMO_ATTR_SYNCHRON, - SUMO_ATTR_REF_TIME, - SUMO_ATTR_START_PROG, - - SUMO_ATTR_OFF, - SUMO_ATTR_FRIENDLY_POS, - SUMO_ATTR_SPLIT_VTYPE, - SUMO_ATTR_UNCONTROLLED, - SUMO_ATTR_PASS, - SUMO_ATTR_BUS_STOP, - SUMO_ATTR_CONTAINER_STOP, - SUMO_ATTR_PARKING_AREA, - SUMO_ATTR_ROADSIDE_CAPACITY, - SUMO_ATTR_ONROAD, - SUMO_ATTR_CHARGING_STATION, - SUMO_ATTR_GROUP, - SUMO_ATTR_LINE, - SUMO_ATTR_LINES, - SUMO_ATTR_TRIP_ID, - SUMO_ATTR_SPLIT, - SUMO_ATTR_JOIN, - SUMO_ATTR_INTENDED, - SUMO_ATTR_VALUE, - SUMO_ATTR_PROHIBITOR, - SUMO_ATTR_PROHIBITED, - SUMO_ATTR_ALLOW, - SUMO_ATTR_DISALLOW, - SUMO_ATTR_PREFER, - SUMO_ATTR_CONTROLLED_INNER, - SUMO_ATTR_VEHSPERHOUR, - SUMO_ATTR_PERSONSPERHOUR, - SUMO_ATTR_OUTPUT, - SUMO_ATTR_HEIGHT, - SUMO_ATTR_GUISHAPE, - SUMO_ATTR_OSGFILE, - SUMO_ATTR_IMGFILE, - SUMO_ATTR_RELATIVEPATH, - SUMO_ATTR_ANGLE, - SUMO_ATTR_EMISSIONCLASS, - SUMO_ATTR_IMPATIENCE, - SUMO_ATTR_STARTPOS, - SUMO_ATTR_ENDPOS, - SUMO_ATTR_TRIGGERED, - SUMO_ATTR_CONTAINER_TRIGGERED, - SUMO_ATTR_PARKING, - SUMO_ATTR_EXPECTED, - SUMO_ATTR_EXPECTED_CONTAINERS, - SUMO_ATTR_INDEX, - - SUMO_ATTR_ENTERING, - SUMO_ATTR_EXCLUDE_EMPTY, - SUMO_ATTR_WITH_INTERNAL, - SUMO_ATTR_TRACK_VEHICLES, - SUMO_ATTR_DETECT_PERSONS, - SUMO_ATTR_MAX_TRAVELTIME, - SUMO_ATTR_MIN_SAMPLES, - SUMO_ATTR_WRITE_ATTRIBUTES, - - SUMO_ATTR_LON, - SUMO_ATTR_LAT, - SUMO_ATTR_GEO, - SUMO_ATTR_GEOSHAPE, - SUMO_ATTR_GEOPOSITION, - SUMO_ATTR_K, - SUMO_ATTR_V, - SUMO_ATTR_REF, - SUMO_ATTR_HREF, - SUMO_ATTR_ZOOM, - SUMO_ATTR_INTERPOLATED, - SUMO_ATTR_THRESHOLD, - - SUMO_ATTR_NET_OFFSET, - SUMO_ATTR_CONV_BOUNDARY, - SUMO_ATTR_ORIG_BOUNDARY, - SUMO_ATTR_ORIG_PROJ, - - /// @name car-following model attributes - /// @{ - SUMO_ATTR_CF_PWAGNER2009_TAULAST, - SUMO_ATTR_CF_PWAGNER2009_APPROB, - SUMO_ATTR_CF_IDM_DELTA, - SUMO_ATTR_CF_IDM_STEPPING, - SUMO_ATTR_CF_IDMM_ADAPT_FACTOR, - SUMO_ATTR_CF_IDMM_ADAPT_TIME, - SUMO_ATTR_CF_KERNER_PHI, - SUMO_ATTR_CF_WIEDEMANN_SECURITY, - SUMO_ATTR_CF_WIEDEMANN_ESTIMATION, - SUMO_ATTR_CF_W99_CC1, - SUMO_ATTR_CF_W99_CC2, - SUMO_ATTR_CF_W99_CC3, - SUMO_ATTR_CF_W99_CC4, - SUMO_ATTR_CF_W99_CC5, - SUMO_ATTR_CF_W99_CC6, - SUMO_ATTR_CF_W99_CC7, - SUMO_ATTR_CF_W99_CC8, - SUMO_ATTR_CF_W99_CC9, - - SUMO_ATTR_CF_CC_CCDECEL, - SUMO_ATTR_CF_CC_CONSTSPACING, - SUMO_ATTR_CF_CC_KP, - SUMO_ATTR_CF_CC_LAMBDA, - SUMO_ATTR_CF_CC_C1, - SUMO_ATTR_CF_CC_XI, - SUMO_ATTR_CF_CC_OMEGAN, - SUMO_ATTR_CF_CC_TAU, - SUMO_ATTR_CF_CC_LANES_COUNT, - SUMO_ATTR_CF_CC_CCACCEL, - SUMO_ATTR_CF_CC_PLOEG_KP, - SUMO_ATTR_CF_CC_PLOEG_KD, - SUMO_ATTR_CF_CC_PLOEG_H, - SUMO_ATTR_CF_CC_FLATBED_KA, - SUMO_ATTR_CF_CC_FLATBED_KV, - SUMO_ATTR_CF_CC_FLATBED_KP, - SUMO_ATTR_CF_CC_FLATBED_D, - SUMO_ATTR_CF_CC_FLATBED_H, - /// @} - - SUMO_ATTR_GENERATE_WALKS, - SUMO_ATTR_ACTTYPE, - SUMO_ATTR_SLOPE, - SUMO_ATTR_CORNERDETAIL, - SUMO_ATTR_LINKDETAIL, - SUMO_ATTR_RECTANGULAR_LANE_CUT, - SUMO_ATTR_WALKINGAREAS, - SUMO_ATTR_LEFTHAND, - SUMO_ATTR_LIMIT_TURN_SPEED, - SUMO_ATTR_CHECKLANEFOES_ALL, - SUMO_ATTR_CHECKLANEFOES_ROUNDABOUT, - SUMO_ATTR_TLS_IGNORE_INTERNAL_JUNCTION_JAM, - SUMO_ATTR_AVOID_OVERLAP, - SUMO_ATTR_COMMAND, - - SUMO_ATTR_ACTORCONFIG, - SUMO_ATTR_VEHICLE, - SUMO_ATTR_STARTTIME, - SUMO_ATTR_VEHICLECLASS, - SUMO_ATTR_FUEL, - SUMO_ATTR_ACCELERATION, - SUMO_ATTR_ORIGIN, - SUMO_ATTR_DESTINATION, - SUMO_ATTR_VISIBLE, - - - /// @name ActivityGen Tags - /// @{ - - /// @name general object - /// @{ - AGEN_ATTR_INHABITANTS, - AGEN_ATTR_HOUSEHOLDS, - AGEN_ATTR_CHILDREN, - AGEN_ATTR_RETIREMENT, - AGEN_ATTR_CARS, - AGEN_ATTR_UNEMPLOYEMENT, - AGEN_ATTR_LABORDEMAND, - AGEN_ATTR_MAX_FOOT_DIST, - AGEN_ATTR_IN_TRAFFIC, - AGEN_ATTR_OUT_TRAFFIC, - /// @} - - /// @name streets object - /// @{ - //SUMO_ATTR_EDGE already defined - AGEN_ATTR_POPULATION, - AGEN_ATTR_OUT_WORKPOSITION, - /// @} - - /// @name workHours object - /// @{ - AGEN_ATTR_HOUR, - AGEN_ATTR_PROP, - /// @} - - /// @name school object - /// @{ - //SUMO_ATTR_EDGE, SUMO_ATTR_POSITION, SUMO_ATTR_TYPE already defined - AGEN_ATTR_CAPACITY, - AGEN_ATTR_OPENING, - AGEN_ATTR_CLOSING, - /// @} - - /// @name busStation and Bus objects - /// @{ - // ID, EDGE, POSITION, REFID, BEGIN and END are already defined - AGEN_ATTR_MAX_TRIP_DURATION, - //AGEN_ATTR_ORDER, - AGEN_ATTR_RATE, - /// @} - - /// @name population and children accompaniment brackets - /// @{ - AGEN_ATTR_BEGINAGE, - AGEN_ATTR_ENDAGE, - AGEN_ATTR_PEOPLENBR, - /// @} - - /// @name parameters - /// @{ - AGEN_ATTR_CARPREF, - AGEN_ATTR_CITYSPEED, - AGEN_ATTR_FREETIMERATE, - AGEN_ATTR_UNI_RAND_TRAFFIC, - AGEN_ATTR_DEP_VARIATION, - /// @} - - /// @name city gates - /// @{ - AGEN_ATTR_INCOMING, - AGEN_ATTR_OUTGOING, - /// @} - /// @} - - //@name Netedit Attributes (used as virtual property holders, must be in SumoXMLAttr) - //@{ - /// @brief element is selected - GNE_ATTR_SELECTED, - /// @brief whether a feature has been loaded,guessed,modified or approved - GNE_ATTR_MODIFICATION_STATUS, - /// @brief first coordinate of edge shape - GNE_ATTR_SHAPE_START, - /// @brief last coordinate of edge shape - GNE_ATTR_SHAPE_END, - /// @brief whether an edge is part of a bidirectional railway - GNE_ATTR_BIDIR, - /// @brief block movement of a graphic element - GNE_ATTR_BLOCK_MOVEMENT, - /// @brief block shape of a graphic element (Used mainly in GNEShapes) - GNE_ATTR_BLOCK_SHAPE, - /// @brief Close shape of a polygon (Used by GNEPolys) - GNE_ATTR_CLOSE_SHAPE, - /// @brief parent of an additional element - GNE_ATTR_PARENT, - /// @brief data set of a generic data - GNE_ATTR_DATASET, - /// @brief parameters "key1=value1|key2=value2|...|keyN=valueN" - GNE_ATTR_PARAMETERS, - /// @brief min source (used only by TAZs) - GNE_ATTR_MIN_SOURCE, - /// @brief min sink (used only by TAZs) - GNE_ATTR_MIN_SINK, - /// @brief max source (used only by TAZs) - GNE_ATTR_MAX_SOURCE, - /// @brief max sink (used only by TAZs) - GNE_ATTR_MAX_SINK, - /// @brief average source (used only by TAZs) - GNE_ATTR_AVERAGE_SOURCE, - /// @brief average sink (used only by TAZs) - GNE_ATTR_AVERAGE_SINK, - /// @brief Color of TAZSources/TAZSinks - GNE_ATTR_TAZCOLOR, - /// @brief Flag to check if VType is a default VType - GNE_ATTR_DEFAULT_VTYPE, - /// @brief Flag to check if a default VType was modified - GNE_ATTR_DEFAULT_VTYPE_MODIFIED, - /// @brief flag to center camera after element creation - GNE_ATTR_CENTER_AFTER_CREATION, - /// @brief from busStop (used by personPlans) - GNE_ATTR_FROM_BUSSTOP, - /// @brief to busStop (used by personPlans) - GNE_ATTR_TO_BUSSTOP, - - // @} - - /// @name train parameters - /// @{ - SUMO_ATTR_CARRIAGE_LENGTH, - SUMO_ATTR_LOCOMOTIVE_LENGTH, - SUMO_ATTR_CARRIAGE_GAP, - /// @} - - SUMO_ATTR_TARGETLANE, - SUMO_ATTR_CROSSING, - SUMO_ATTR_XMLNS, - SUMO_ATTR_SCHEMA_LOCATION, - - //@name RNG state saving attributes - // @{ - SUMO_ATTR_RNG_DEFAULT, - SUMO_ATTR_RNG_ROUTEHANDLER, - SUMO_ATTR_RNG_INSERTIONCONTROL, - SUMO_ATTR_RNG_DEVICE, - SUMO_ATTR_RNG_DEVICE_BT, - SUMO_ATTR_RNG_DEVICE_TOC, - SUMO_ATTR_RNG_DRIVERSTATE - // @} - -}; - -/* - * @brief definitions of special SumoXML-attribute values. - * Since these enums shall be used in switch statements we keep them separated - * @{ - */ - -/** - * SumoXMLParam Key Constants. Since all usage contexts needs strings rather - * than enum values we do not bother with a StringBijection - */ -extern const std::string SUMO_PARAM_ORIGID; - -/** - * @enum SumoXMLNodeType - * @brief Numbers representing special SUMO-XML-attribute values - * for representing node- (junction-) types used in netbuild/netimport and netload - */ -enum class SumoXMLNodeType { - UNKNOWN, // terminator - TRAFFIC_LIGHT, - TRAFFIC_LIGHT_NOJUNCTION, // junction controlled only by traffic light but without other prohibitions, - TRAFFIC_LIGHT_RIGHT_ON_RED, - RAIL_SIGNAL, - RAIL_CROSSING, - PRIORITY, - PRIORITY_STOP, // like priority but all minor links have stop signs - RIGHT_BEFORE_LEFT, - ALLWAY_STOP, - ZIPPER, - DISTRICT, - NOJUNCTION, - INTERNAL, - DEAD_END, - DEAD_END_DEPRECATED -}; - - -/** - * @enum SumoXMLEdgeFunc - * @brief Numbers representing special SUMO-XML-attribute values - * for representing edge functions used in netbuild/netimport and netload - */ -enum class SumoXMLEdgeFunc { - UNKNOWN, - NORMAL, - CONNECTOR, - CROSSING, - WALKINGAREA, - INTERNAL -}; - - -/** - * @enum LaneSpreadFunction - * @brief Numbers representing special SUMO-XML-attribute values - * Information how the edge's lateral offset shall be computed - * In dependence to this value, lanes will be spread to the right side or - * to both sides from the given edge geometry (Also used when node - * positions are used as edge geometry). - */ -enum class LaneSpreadFunction { - RIGHT = 0, - ROADCENTER = 1, - CENTER = 2 -}; - - -/// @brief algorithms for computing right of way -enum class RightOfWay { - DEFAULT, - EDGEPRIORITY -}; - -/// @brief algorithms for computing right of way -enum class FringeType { - OUTER, - INNER, - DEFAULT -}; - -/// @brief travel modes for persons -enum class PersonMode { - NONE = 0, - WALK = 1 << 1, - BICYCLE = 1 << 2, - CAR = 1 << 3, - PUBLIC = 1 << 4, - TAXI = 1 << 5 -}; - -/** - * @enum LinkState - * @brief The right-of-way state of a link between two lanes - * used when constructing a NBTrafficLightLogic, in MSLink and GNEInternalLane - * - * This enumerations holds the possible right-of-way rules a link - * may have. Beyond the righ-of-way rules, this enumeration also - * holds the possible traffic light states. - * - * enum values are assigned so that chars can be cast back to linkstates - * @todo fix redundancy - */ -enum LinkState { - /// @brief The link has green light, may pass - LINKSTATE_TL_GREEN_MAJOR = 'G', - /// @brief The link has green light, has to brake - LINKSTATE_TL_GREEN_MINOR = 'g', - /// @brief The link has red light (must brake) - LINKSTATE_TL_RED = 'r', - /// @brief The link has red light (must brake) but indicates upcoming green - LINKSTATE_TL_REDYELLOW = 'u', - /// @brief The link has yellow light, may pass - LINKSTATE_TL_YELLOW_MAJOR = 'Y', - /// @brief The link has yellow light, has to brake anyway - LINKSTATE_TL_YELLOW_MINOR = 'y', - /// @brief The link is controlled by a tls which is off and blinks, has to brake - LINKSTATE_TL_OFF_BLINKING = 'o', - /// @brief The link is controlled by a tls which is off, not blinking, may pass - LINKSTATE_TL_OFF_NOSIGNAL = 'O', - /// @brief This is an uncontrolled, major link, may pass - LINKSTATE_MAJOR = 'M', - /// @brief This is an uncontrolled, minor link, has to brake - LINKSTATE_MINOR = 'm', - /// @brief This is an uncontrolled, right-before-left link - LINKSTATE_EQUAL = '=', - /// @brief This is an uncontrolled, minor link, has to stop - LINKSTATE_STOP = 's', - /// @brief This is an uncontrolled, all-way stop link. - LINKSTATE_ALLWAY_STOP = 'w', - /// @brief This is an uncontrolled, zipper-merge link - LINKSTATE_ZIPPER = 'Z', - /// @brief This is a dead end link - LINKSTATE_DEADEND = '-' -}; - -/** - * @enum LinkDirection - * @brief The different directions a link between two lanes may take (or a - * stream between two edges). - * used in netbuild (formerly NBMMLDirection) and MSLink - */ -enum class LinkDirection { - /// @brief The link is a straight direction - STRAIGHT = 0, - /// @brief The link is a 180 degree turn - TURN, - /// @brief The link is a 180 degree turn (left-hand network) - TURN_LEFTHAND, - /// @brief The link is a (hard) left direction - LEFT, - /// @brief The link is a (hard) right direction - RIGHT, - /// @brief The link is a partial left direction - PARTLEFT, - /// @brief The link is a partial right direction - PARTRIGHT, - /// @brief The link has no direction (is a dead end link) - NODIR -}; - - -/// @enum TrafficLightType -enum class TrafficLightType { - STATIC, - RAIL_SIGNAL, - RAIL_CROSSING, - ACTUATED, - DELAYBASED, - SOTL_PHASE, - SOTL_PLATOON, - SOTL_REQUEST, - SOTL_WAVE, - SOTL_MARCHING, - SWARM_BASED, - HILVL_DETERMINISTIC, - OFF, - INVALID //< must be the last one -}; - - -/** @enum LaneChangeAction - * @brief The state of a vehicle's lane-change behavior - */ -enum LaneChangeAction { - /// @name currently wanted lane-change action - /// @{ - /// @brief No action desired - LCA_NONE = 0, - /// @brief Needs to stay on the current lane - LCA_STAY = 1 << 0, - /// @brief Wants go to the left - LCA_LEFT = 1 << 1, - /// @brief Wants go to the right - LCA_RIGHT = 1 << 2, - /// @brief The action is needed to follow the route (navigational lc) - LCA_STRATEGIC = 1 << 3, - /// @brief The action is done to help someone else - LCA_COOPERATIVE = 1 << 4, - /// @brief The action is due to the wish to be faster (tactical lc) - LCA_SPEEDGAIN = 1 << 5, - /// @brief The action is due to the default of keeping right "Rechtsfahrgebot" - LCA_KEEPRIGHT = 1 << 6, - /// @brief The action is due to a TraCI request - LCA_TRACI = 1 << 7, - /// @brief The action is urgent (to be defined by lc-model) - LCA_URGENT = 1 << 8, - /// @brief The action has not been determined - LCA_UNKNOWN = 1 << 30, - /// @} - - /// @name External state - /// @{ - /// @brief The vehicle is blocked by left leader - LCA_BLOCKED_BY_LEFT_LEADER = 1 << 9, - /// @brief The vehicle is blocked by left follower - LCA_BLOCKED_BY_LEFT_FOLLOWER = 1 << 10, - /// @brief The vehicle is blocked by right leader - LCA_BLOCKED_BY_RIGHT_LEADER = 1 << 11, - /// @brief The vehicle is blocked by right follower - LCA_BLOCKED_BY_RIGHT_FOLLOWER = 1 << 12, - /// @brief The vehicle is blocked being overlapping - LCA_OVERLAPPING = 1 << 13, - /// @brief The vehicle does not have enough space to complete a continuous change before the next turn - LCA_INSUFFICIENT_SPACE = 1 << 14, - /// @brief used by the sublane model - LCA_SUBLANE = 1 << 15, - /// @brief Vehicle is too slow to complete a continuous lane change (in case that maxSpeedLatStanding==0) - LCA_INSUFFICIENT_SPEED = 1 << 28, - /// @brief lane can change - LCA_WANTS_LANECHANGE = LCA_LEFT | LCA_RIGHT, - /// @brief lane can change or stay - LCA_WANTS_LANECHANGE_OR_STAY = LCA_WANTS_LANECHANGE | LCA_STAY, - /// @brief blocked left - LCA_BLOCKED_LEFT = LCA_BLOCKED_BY_LEFT_LEADER | LCA_BLOCKED_BY_LEFT_FOLLOWER, - /// @brief blocked right - LCA_BLOCKED_RIGHT = LCA_BLOCKED_BY_RIGHT_LEADER | LCA_BLOCKED_BY_RIGHT_FOLLOWER, - /// @brief blocked by leader - LCA_BLOCKED_BY_LEADER = LCA_BLOCKED_BY_LEFT_LEADER | LCA_BLOCKED_BY_RIGHT_LEADER, - /// @brief blocker by follower - LCA_BLOCKED_BY_FOLLOWER = LCA_BLOCKED_BY_LEFT_FOLLOWER | LCA_BLOCKED_BY_RIGHT_FOLLOWER, - /// @brief blocked in all directions - LCA_BLOCKED = LCA_BLOCKED_LEFT | LCA_BLOCKED_RIGHT | LCA_INSUFFICIENT_SPACE | LCA_INSUFFICIENT_SPEED, - /// @brief reasons of lane change - LCA_CHANGE_REASONS = (LCA_STRATEGIC | LCA_COOPERATIVE | LCA_SPEEDGAIN | LCA_KEEPRIGHT | LCA_SUBLANE | LCA_TRACI), - // LCA_BLOCKED_BY_CURRENT_LEADER = 1 << 28 - // LCA_BLOCKED_BY_CURRENT_FOLLOWER = 1 << 29 - /// @} - - /// @name originally model specific states (migrated here since - /// they were duplicated in all current models) - /// @{ - LCA_AMBLOCKINGLEADER = 1 << 16, - LCA_AMBLOCKINGFOLLOWER = 1 << 17, - LCA_MRIGHT = 1 << 18, - LCA_MLEFT = 1 << 19, - // !!! never set LCA_UNBLOCK = 1 << 20, - LCA_AMBLOCKINGFOLLOWER_DONTBRAKE = 1 << 21, - // !!! never used LCA_AMBLOCKINGSECONDFOLLOWER = 1 << 22, - LCA_CHANGE_TO_HELP = 1 << 23, - // !!! never read LCA_KEEP1 = 1 << 24, - // !!! never used LCA_KEEP2 = 1 << 25, - LCA_AMBACKBLOCKER = 1 << 26, - LCA_AMBACKBLOCKER_STANDING = 1 << 27 - /// @} -}; - - -/// @enum LaneChangeModel -enum LaneChangeModel { - LCM_DK2008, - LCM_LC2013, - LCM_SL2015, - LCM_DEFAULT -}; - -/// @enum train types -enum TrainType { - TRAINTYPE_NGT400, - TRAINTYPE_NGT400_16, - TRAINTYPE_RB425, - TRAINTYPE_RB628, - TRAINTYPE_ICE1, - TRAINTYPE_REDOSTO7, - TRAINTYPE_FREIGHT, - TRAINTYPE_ICE3, - TRAINTYPE_UNKNOWN -}; - -/** - * @enum LateralAlignment - * @brief Numbers representing special SUMO-XML-attribute values - * Information how vehicles align themselves within their lane by default - */ -enum LateralAlignment { - /// @brief drive on the right side - LATALIGN_RIGHT, - /// @brief drive in the middle - LATALIGN_CENTER, - /// @brief maintain the current alignment - LATALIGN_ARBITRARY, - /// @brief align with the closest sublane border - LATALIGN_NICE, - /// @brief align with the rightmost sublane that allows keeping the current speed - LATALIGN_COMPACT, - /// @brief drive on the left side - LATALIGN_LEFT -}; - -// @} - -/** - * @class SUMOXMLDefinitions - * @brief class for maintaining associations between enums and xml-strings - */ -class SUMOXMLDefinitions { - -public: - /// @brief The names of SUMO-XML elements (for passing to GenericSAXHandler) - static StringBijection::Entry tags[]; - - /// @brief The names of SUMO-XML attributes (for passing to GenericSAXHandler) - static StringBijection::Entry attrs[]; - - /// @brief The names of SUMO-XML elements for use in netbuild - static StringBijection Tags; - - /// @brief The names of SUMO-XML attributes for use in netbuild - static StringBijection Attrs; - - /// @name Special values of SUMO-XML attributes - /// @{ - - /// @brief node types - static StringBijection NodeTypes; - - /// @brief edge functions - static StringBijection EdgeFunctions; - - /// @brief lane spread functions - static StringBijection LaneSpreadFunctions; - - /// @brief righ of way algorithms - static StringBijection RightOfWayValues; - - /// @brief fringe types - static StringBijection FringeTypeValues; - - /// @brief person modes - static StringBijection PersonModeValues; - - /// @brief link states - static StringBijection LinkStates; - - /// @brief link directions - static StringBijection LinkDirections; - - /// @brief traffic light types - static StringBijection TrafficLightTypes; - - /// @brief lane change models - static StringBijection LaneChangeModels; - - /// @brief car following models - static StringBijection CarFollowModels; - - /// @brief lateral alignments - static StringBijection LateralAlignments; - - /// @brief lane change actions - static StringBijection LaneChangeActions; - - /// @brief train types - static StringBijection TrainTypes; - /// @} - - /// @name Helper functions for ID-string manipulations - /// @{ - - /// @brief whether the given string is a valid id for a network element - static bool isValidNetID(const std::string& value); - - /// @brief whether the given string is a valid id for a vehicle or flow - static bool isValidVehicleID(const std::string& value); - - /// @brief whether the given string is a valid id for an edge or vehicle type - static bool isValidTypeID(const std::string& value); - - /// @brief whether the given string is a valid id for an additional object - static bool isValidAdditionalID(const std::string& value); - - /// @brief whether the given string is a valid id for an detector - static bool isValidDetectorID(const std::string& value); - - /// @brief whether the given string is a valid attribute for a certain key (for example, a name) - static bool isValidAttribute(const std::string& value); - - /// @brief whether the given string is a valid attribute for a filename (for example, a name) - static bool isValidFilename(const std::string& value); - - /// @brief whether the given string is a valid list of id for a network (empty aren't allowed) - static bool isValidListOfNetIDs(const std::string& value); - - /// @brief whether the given string is a valid list of ids for an edge or vehicle type (empty aren't allowed) - static bool isValidListOfTypeID(const std::string& value); - - /// @brief whether the given string is a valid key for a parameter - static bool isValidParameterKey(const std::string& value); - - /// @brief whether the given string is a valid value for a parameter - static bool isValidParameterValue(const std::string& value); - - /// @brief return the junction id when given an edge of type internal, crossing or WalkingArea - static std::string getJunctionIDFromInternalEdge(const std::string internalEdge); - - /// @brief return edge id when given the lane ID - static std::string getEdgeIDFromLane(const std::string laneID); - /// @} - - /// @brief all allowed characters for phase state - static const std::string ALLOWED_TLS_LINKSTATES; - - - -private: - /// @brief containers for the different SUMOXMLDefinitions - /// @{ - - /// @brief node type values - static StringBijection::Entry sumoNodeTypeValues[]; - - /// @brief edge function values - static StringBijection::Entry sumoEdgeFuncValues[]; - - /// @brief lane spread function values - static StringBijection::Entry laneSpreadFunctionValues[]; - - /// @brief lane spread function values - static StringBijection::Entry rightOfWayValuesInitializer[]; - - /// @brief lane spread function values - static StringBijection::Entry fringeTypeValuesInitializer[]; - - /// @brief person mode values - static StringBijection::Entry personModeValuesInitializer[]; - - /// @brief link state values - static StringBijection::Entry linkStateValues[]; - - /// @brief link direction values - static StringBijection::Entry linkDirectionValues[]; - - /// @brief traffic light types values - static StringBijection::Entry trafficLightTypesValues[]; - - /// @brief lane change model values - static StringBijection::Entry laneChangeModelValues[]; - - /// @brief car follwing model values - static StringBijection::Entry carFollowModelValues[]; - - /// @brief lanteral alignment values - static StringBijection::Entry lateralAlignmentValues[]; - - /// @brief lane change action values - static StringBijection::Entry laneChangeActionValues[]; - - /// @brief train type values values - static StringBijection::Entry trainTypeValues[]; - /// @} - - /// @brief all allowed characters for phase state - static const char AllowedTLS_linkStatesInitializer[]; -}; diff --git a/Util/OSM2ODR/src/utils/xml/XMLSubSys.cpp b/Util/OSM2ODR/src/utils/xml/XMLSubSys.cpp deleted file mode 100644 index 301987241..000000000 --- a/Util/OSM2ODR/src/utils/xml/XMLSubSys.cpp +++ /dev/null @@ -1,184 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2002-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file XMLSubSys.cpp -/// @author Daniel Krajzewicz -/// @author Jakob Erdmann -/// @author Michael Behrisch -/// @date Mon, 1 Jul 2002 -/// -// Utility methods for initialising, closing and using the XML-subsystem -/****************************************************************************/ -#include - -#include -#include -#include -#include -#include "SUMOSAXHandler.h" -#include "SUMOSAXReader.h" -#include "XMLSubSys.h" - - -// =========================================================================== -// static member variables -// =========================================================================== -std::vector XMLSubSys::myReaders; -int XMLSubSys::myNextFreeReader; -XERCES_CPP_NAMESPACE::SAX2XMLReader::ValSchemes XMLSubSys::myValidationScheme = XERCES_CPP_NAMESPACE::SAX2XMLReader::Val_Auto; -XERCES_CPP_NAMESPACE::SAX2XMLReader::ValSchemes XMLSubSys::myNetValidationScheme = XERCES_CPP_NAMESPACE::SAX2XMLReader::Val_Auto; - - -// =========================================================================== -// method definitions -// =========================================================================== -void -XMLSubSys::init() { - try { - XERCES_CPP_NAMESPACE::XMLPlatformUtils::Initialize(); - myNextFreeReader = 0; - } catch (const XERCES_CPP_NAMESPACE::XMLException& e) { - throw ProcessError("Error during XML-initialization:\n " + StringUtils::transcode(e.getMessage())); - } -} - - -void -XMLSubSys::setValidation(const std::string& validationScheme, const std::string& netValidationScheme) { - if (validationScheme == "never") { - myValidationScheme = XERCES_CPP_NAMESPACE::SAX2XMLReader::Val_Never; - } else if (validationScheme == "auto") { - myValidationScheme = XERCES_CPP_NAMESPACE::SAX2XMLReader::Val_Auto; - } else if (validationScheme == "always") { - myValidationScheme = XERCES_CPP_NAMESPACE::SAX2XMLReader::Val_Always; - } else { - throw ProcessError("Unknown xml validation scheme + '" + validationScheme + "'."); - } - if (netValidationScheme == "never") { - myNetValidationScheme = XERCES_CPP_NAMESPACE::SAX2XMLReader::Val_Never; - } else if (netValidationScheme == "auto") { - myNetValidationScheme = XERCES_CPP_NAMESPACE::SAX2XMLReader::Val_Auto; - } else if (netValidationScheme == "always") { - myNetValidationScheme = XERCES_CPP_NAMESPACE::SAX2XMLReader::Val_Always; - } else { - throw ProcessError("Unknown network validation scheme + '" + netValidationScheme + "'."); - } -} - - -bool -XMLSubSys::isValidating(const bool net) { - if (net) { - return myNetValidationScheme != XERCES_CPP_NAMESPACE::SAX2XMLReader::Val_Never; - } - return myValidationScheme != XERCES_CPP_NAMESPACE::SAX2XMLReader::Val_Never; -} - - -void -XMLSubSys::close() { - for (std::vector::iterator i = myReaders.begin(); i != myReaders.end(); ++i) { - delete *i; - } - myReaders.clear(); - XERCES_CPP_NAMESPACE::XMLPlatformUtils::Terminate(); -} - - -SUMOSAXReader* -XMLSubSys::getSAXReader(SUMOSAXHandler& handler) { - return new SUMOSAXReader(handler, myValidationScheme); -} - - -void -XMLSubSys::setHandler(GenericSAXHandler& handler) { - myReaders[myNextFreeReader - 1]->setHandler(handler); -} - - -bool -XMLSubSys::runParser(GenericSAXHandler& handler, - const std::string& file, const bool isNet) { - MsgHandler::getErrorInstance()->clear(); - try { - XERCES_CPP_NAMESPACE::SAX2XMLReader::ValSchemes validationScheme = isNet ? myNetValidationScheme : myValidationScheme; - if (myNextFreeReader == (int)myReaders.size()) { - myReaders.push_back(new SUMOSAXReader(handler, validationScheme)); - } else { - myReaders[myNextFreeReader]->setValidation(validationScheme); - myReaders[myNextFreeReader]->setHandler(handler); - } - myNextFreeReader++; - std::string prevFile = handler.getFileName(); - handler.setFileName(file); - myReaders[myNextFreeReader - 1]->parse(file); - handler.setFileName(prevFile); - myNextFreeReader--; - } catch (AbortParsing&) { - return false; - } catch (ProcessError& e) { - WRITE_ERROR(std::string(e.what()) != std::string("") ? std::string(e.what()) : std::string("Process Error")); - return false; - } catch (const std::runtime_error& re) { - WRITE_ERROR("Runtime error: " + std::string(re.what()) + " while parsing '" + file + "'"); - return false; - } catch (const std::exception& ex) { - WRITE_ERROR("Error occurred: " + std::string(ex.what()) + " while parsing '" + file + "'"); - return false; - } catch (...) { - WRITE_ERROR("Unspecified error occurred wile parsing '" + file + "'"); - return false; - } - return !MsgHandler::getErrorInstance()->wasInformed(); -} - -bool -XMLSubSys::runParserFromString(GenericSAXHandler& handler, - const std::string& xml, const bool isNet) { - std::string file = "String XML"; - MsgHandler::getErrorInstance()->clear(); - try { - XERCES_CPP_NAMESPACE::SAX2XMLReader::ValSchemes validationScheme = isNet ? myNetValidationScheme : myValidationScheme; - if (myNextFreeReader == (int)myReaders.size()) { - myReaders.push_back(new SUMOSAXReader(handler, validationScheme)); - } else { - myReaders[myNextFreeReader]->setValidation(validationScheme); - myReaders[myNextFreeReader]->setHandler(handler); - } - myNextFreeReader++; - std::string prevFile = handler.getFileName(); - handler.setFileName(file); - myReaders[myNextFreeReader - 1]->parseString(xml); - handler.setFileName(prevFile); - myNextFreeReader--; - } catch (AbortParsing&) { - return false; - } catch (ProcessError& e) { - WRITE_ERROR(std::string(e.what()) != std::string("") ? std::string(e.what()) : std::string("Process Error")); - return false; - } catch (const std::runtime_error& re) { - WRITE_ERROR("Runtime error: " + std::string(re.what()) + " while parsing '" + file + "'"); - return false; - } catch (const std::exception& ex) { - WRITE_ERROR("Error occurred: " + std::string(ex.what()) + " while parsing '" + file + "'"); - return false; - } catch (...) { - WRITE_ERROR("Unspecified error occurred wile parsing '" + file + "'"); - return false; - } - return !MsgHandler::getErrorInstance()->wasInformed(); -} - - -/****************************************************************************/ diff --git a/Util/OSM2ODR/src/utils/xml/XMLSubSys.h b/Util/OSM2ODR/src/utils/xml/XMLSubSys.h deleted file mode 100644 index be77fba99..000000000 --- a/Util/OSM2ODR/src/utils/xml/XMLSubSys.h +++ /dev/null @@ -1,165 +0,0 @@ -/****************************************************************************/ -// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo -// Copyright (C) 2002-2020 German Aerospace Center (DLR) and others. -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0/ -// This Source Code may also be made available under the following Secondary -// Licenses when the conditions for such availability set forth in the Eclipse -// Public License 2.0 are satisfied: GNU General Public License, version 2 -// or later which is available at -// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html -// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later -/****************************************************************************/ -/// @file XMLSubSys.h -/// @author Daniel Krajzewicz -/// @author Michael Behrisch -/// @date Mon, 1 Jul 2002 -/// -// Utility methods for initialising, closing and using the XML-subsystem -/****************************************************************************/ -#pragma once -#include - -#include -#include -#include - - -// =========================================================================== -// class declarations -// =========================================================================== -class GenericSAXHandler; -class SUMOSAXHandler; -class SUMOSAXReader; - - -// =========================================================================== -// class definitions -// =========================================================================== -/** - * @class XMLSubSys - * @brief Utility methods for initialising, closing and using the XML-subsystem - * - * The Xerces-parsers need an initialisation and should also be closed. - * - * As we use xerces for both the input files and the configuration we - * would have to check whether the system was initialised before. Instead, - * we call XMLSubSys::init(bool) once at the beginning of our application and - * XMLSubSys::close() at the end. - * - * Closing and initialising the XML subsystem is necessary. Still, we never - * encountered any problems with it. Once, after some modifications, SUMO - * crashed when closing the XML sub system. The reason was a memory leak - * within the microsim-module. On initialisation, a SAX2XMLReader is built - * which can be used during later process. It is destroyed when the subsystem - * is closed. - * - * In addition to initialisation and shutdown, this module allows to build - * SAXReaders and/or running a given handler on a given file without - * dealing with the reader at all. - * - * @todo make schema checking optional - */ -class XMLSubSys { -public: - /** - * @brief Initialises the xml-subsystem. - * - * Calls XMLPlatformUtils::Initialize(). If this fails, the exception is - * caught and its content is reported using a ProcessError. - * - * @exception ProcessError If the initialisation fails - */ - static void init(); - - - /** - * @brief Enables or disables validation. - * - * The setting is only valid for parsers created after the call. Existing parsers are not adapted. - * - * @param[in] validationScheme Whether validation of XML-documents against schemata shall be enabled - * @param[in] netValidationScheme Whether validation of SUMO networks against schemata shall be enabled - */ - static void setValidation(const std::string& validationScheme, const std::string& netValidationScheme); - - - /** - * @brief Returns whether validation is enabled. - * - * @param[in] net Whether validation of SUMO networks is reported - */ - static bool isValidating(const bool net = false); - - - /** - * @brief Closes the xml-subsystem - * - * Deletes the built reader and calls XMLPlatformUtils::Terminate(); - */ - static void close(); - - - /** - * @brief Builds a reader and assigns the handler to it - * - * Tries to build a SAX2XMLReader using "getSAXReader()". If this - * fails, 0 is returned. Otherwise, the given handler is assigned - * to the reader as the current DefaultHandler and ErrorHandler. - * - * @param[in] handler The handler to assign to the built reader - * @return The built Xerces-SAX-reader, 0 if something failed - * @see getSAXReader() - */ - static SUMOSAXReader* getSAXReader(SUMOSAXHandler& handler); - - - /** - * @brief Sets the given handler for the default reader - * - * Uses the reader built on init() which is stored in myReader. - * - * @param[in] handler The handler to assign to the built reader - */ - static void setHandler(GenericSAXHandler& handler); - - - /** - * @brief Runs the given handler on the given file; returns if everything's ok - * - * Uses the reader built on init() which is stored in myReader to parse the given - * file. - * - * All exceptions are catched and reported to the error-instance of the MsgHandler. - * Also, if the reader could not be built, this is reported. - * - * The method returns true if everything went ok. This means, that the reader could be - * built, no exception was caught, and nothing was reported to the error-instance - * of the MsgHandler. - * - * @param[in] handler The handler to assign to the built reader - * @param[in] file The file to run the parser at - * @param[in] isNet whether a network gets loaded - * @return true if the parsing was done without errors, false otherwise (error was printed) - */ - static bool runParser(GenericSAXHandler& handler, - const std::string& file, const bool isNet = false); - - static bool runParserFromString(GenericSAXHandler& handler, - const std::string& xml, const bool isNet = false); - -private: - /// @brief The XML Readers used for repeated parsing - static std::vector myReaders; - - /// @brief Information whether the reader is parsing - static int myNextFreeReader; - - /// @brief Information whether built reader/parser shall validate XML-documents against schemata - static XERCES_CPP_NAMESPACE::SAX2XMLReader::ValSchemes myValidationScheme; - - /// @brief Information whether built reader/parser shall validate SUMO networks against schemata - static XERCES_CPP_NAMESPACE::SAX2XMLReader::ValSchemes myNetValidationScheme; - -}; diff --git a/Util/OSM2ODR/src/version.h b/Util/OSM2ODR/src/version.h deleted file mode 100644 index 5a68d6faf..000000000 --- a/Util/OSM2ODR/src/version.h +++ /dev/null @@ -1,2 +0,0 @@ -// TODO: remove this placeholder, replace with carla version? -#define VERSION_STRING "UNKNOWN"