├── .gitignore ├── .github └── acis_licensekey.jpg ├── .gitmodules ├── utilities ├── README.md ├── ACIS.supp └── ACIS.natvis ├── 3rdparty ├── CMakeLists.txt ├── jsoncpp.cmake └── jsoncpp │ └── json │ ├── json-forwards.h │ └── json.h ├── cmake_uninstall.cmake.in ├── LICENSE ├── src ├── extract.h ├── common.h ├── ACIS.h ├── satgen.cpp ├── extract.cpp ├── common.cpp └── sat2json.cpp ├── README.md └── CMakeLists.txt /.gitignore: -------------------------------------------------------------------------------- 1 | .idea/* 2 | .vscode/* 3 | build*/* 4 | *.sat 5 | *.err 6 | -------------------------------------------------------------------------------- /.github/acis_licensekey.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/orbingol/rwsat/HEAD/.github/acis_licensekey.jpg -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "cmake-modules"] 2 | path = cmake-modules 3 | url = https://github.com/orbingol/cmake-modules.git 4 | -------------------------------------------------------------------------------- /utilities/README.md: -------------------------------------------------------------------------------- 1 | * `ACIS.natvis`: ACIS NatVis file for Visual Studio 2 | * `ACIS.supp`: Valgrind suppression file for ACIS 3 | -------------------------------------------------------------------------------- /3rdparty/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 2.8.11) 2 | project(RWSAT_THIRDPARTY) 3 | 4 | # Add jsoncpp 5 | include(jsoncpp.cmake) 6 | -------------------------------------------------------------------------------- /3rdparty/jsoncpp.cmake: -------------------------------------------------------------------------------- 1 | # Include jsoncpp source 2 | set(JSONCPP_SRC 3 | ${CMAKE_CURRENT_LIST_DIR}/jsoncpp/jsoncpp.cpp 4 | ${CMAKE_CURRENT_LIST_DIR}/jsoncpp/json/json.h 5 | ${CMAKE_CURRENT_LIST_DIR}/jsoncpp/json/json-forwards.h 6 | ) 7 | 8 | # Compile jsoncpp as a static library 9 | add_library(jsoncpp STATIC ${JSONCPP_SRC}) 10 | target_include_directories(jsoncpp PUBLIC "${CMAKE_CURRENT_LIST_DIR}/jsoncpp") 11 | -------------------------------------------------------------------------------- /utilities/ACIS.supp: -------------------------------------------------------------------------------- 1 | { 2 | SpaACIS-Param_flags 3 | Memcheck:Param 4 | rt_sigaction(act->sa_flags) 5 | ... 6 | obj:/opt/acis_r26sp1/linux_a64/code/bin/libSpaACIS.so 7 | } 8 | { 9 | SpaACIS-Param_mask 10 | Memcheck:Param 11 | rt_sigaction(act->sa_mask) 12 | ... 13 | obj:/opt/acis_r26sp1/linux_a64/code/bin/libSpaACIS.so 14 | } 15 | { 16 | SpaACIS-Cond 17 | Memcheck:Cond 18 | ... 19 | obj:/opt/acis_r26sp1/linux_a64/code/bin/libSpaACIS.so 20 | } 21 | { 22 | SpaACIS-Leak 23 | Memcheck:Leak 24 | ... 25 | obj:/opt/acis_r26sp1/linux_a64/code/bin/libSpaACIS.so 26 | } 27 | -------------------------------------------------------------------------------- /utilities/ACIS.natvis: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | [{coord[0],g}, {coord[1],g}, {coord[2],g}] 9 | 10 | coord[0] 11 | coord[1] 12 | coord[2] 13 | 14 | 15 | 16 | [{comp[0],g}, {comp[1],g}, {comp[2],g}] 17 | 18 | comp[0] 19 | comp[1] 20 | comp[2] 21 | 22 | 23 | 24 | [{comp[0],g}, {comp[1],g}, {comp[2],g}] 25 | 26 | comp[0] 27 | comp[1] 28 | comp[2] 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /cmake_uninstall.cmake.in: -------------------------------------------------------------------------------- 1 | # CMake uninstall target 2 | # https://gitlab.kitware.com/cmake/community/wikis/FAQ#can-i-do-make-uninstall-with-cmake 3 | 4 | if(NOT EXISTS "@CMAKE_BINARY_DIR@/install_manifest.txt") 5 | message(FATAL_ERROR "Cannot find install manifest: @CMAKE_BINARY_DIR@/install_manifest.txt") 6 | endif(NOT EXISTS "@CMAKE_BINARY_DIR@/install_manifest.txt") 7 | 8 | file(READ "@CMAKE_BINARY_DIR@/install_manifest.txt" files) 9 | string(REGEX REPLACE "\n" ";" files "${files}") 10 | foreach(file ${files}) 11 | message(STATUS "Uninstalling $ENV{DESTDIR}${file}") 12 | if(IS_SYMLINK "$ENV{DESTDIR}${file}" OR EXISTS "$ENV{DESTDIR}${file}") 13 | exec_program( 14 | "@CMAKE_COMMAND@" ARGS "-E remove \"$ENV{DESTDIR}${file}\"" 15 | OUTPUT_VARIABLE rm_out 16 | RETURN_VALUE rm_retval 17 | ) 18 | if(NOT "${rm_retval}" STREQUAL 0) 19 | message(FATAL_ERROR "Problem when removing $ENV{DESTDIR}${file}") 20 | endif(NOT "${rm_retval}" STREQUAL 0) 21 | else(IS_SYMLINK "$ENV{DESTDIR}${file}" OR EXISTS "$ENV{DESTDIR}${file}") 22 | message(STATUS "File $ENV{DESTDIR}${file} does not exist.") 23 | endif(IS_SYMLINK "$ENV{DESTDIR}${file}" OR EXISTS "$ENV{DESTDIR}${file}") 24 | endforeach(file) 25 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2019, Integrated Design and Engineering Analysis Laboratory (IDEA Lab) at Iowa State University. 2 | All rights reserved. 3 | 4 | Redistribution and use in source and binary forms, with or without 5 | modification, are permitted provided that the following conditions are met: 6 | * Redistributions of source code must retain the above copyright 7 | notice, this list of conditions and the following disclaimer. 8 | * Redistributions in binary form must reproduce the above copyright 9 | notice, this list of conditions and the following disclaimer in the 10 | documentation and/or other materials provided with the distribution. 11 | * Neither the name of the copyright holder nor the 12 | names of its contributors may be used to endorse or promote products 13 | derived from this software without specific prior written permission. 14 | 15 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 16 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 17 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 18 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY 19 | DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 20 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 21 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 22 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 23 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 24 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 25 | -------------------------------------------------------------------------------- /src/extract.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2019, Integrated Design and Engineering Analysis Laboratory (IDEA Lab) at Iowa State University. 3 | All rights reserved. 4 | 5 | Redistribution and use in source and binary forms, with or without 6 | modification, are permitted provided that the following conditions are met: 7 | * Redistributions of source code must retain the above copyright 8 | notice, this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above copyright 10 | notice, this list of conditions and the following disclaimer in the 11 | documentation and/or other materials provided with the distribution. 12 | * Neither the name of the copyright holder nor the 13 | names of its contributors may be used to endorse or promote products 14 | derived from this software without specific prior written permission. 15 | 16 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 17 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 18 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 19 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY 20 | DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 21 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 22 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 23 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 25 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | */ 27 | 28 | #ifndef EXTRACT_H 29 | #define EXTRACT_H 30 | 31 | #include "common.h" 32 | #include "json/json.h" 33 | 34 | 35 | void extractSurfaceData(bs3_surface &, Config &, Json::Value &); 36 | void extractTrimCurveData(bs2_curve &, Config &, double *, double *, Json::Value &); 37 | 38 | #endif /* EXTRACT_H */ 39 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # RWSAT - ACIS Extensions for NURBS-Python (geomdl) 2 | 3 | This repository contains the `rwsat` project and it contains 2 modules 4 | 5 | * `sat2json` for extracting spline geometries and trim curves from ACIS .SAT files 6 | * `satgen` for generating sample geometries to test `sat2json` 7 | 8 | The `rwsat` project is based on the work of [Dr. Adarsh Krishnamurthy](https://www.me.iastate.edu/faculty/profile/adarsh) 9 | with various improvements and new features. 10 | 11 | ## Requirements 12 | 13 | 1. [CMake](https://cmake.org) 14 | 2. [3D ACIS Modeler](https://www.spatial.com/) 15 | 16 | ## Compiling RWSAT 17 | 18 | 1. Clone the repository: `git clone https://github.com/orbingol/rwsat.git` 19 | 2. Enter the directory: `cd rwsat` 20 | 3. Update submodules: `git submodule update --init` 21 | 4. Use CMake to generate make files 22 | 5. Use `make install` to compile and install into the build directory 23 | 24 | ## Using RWSAT 25 | 26 | ### sat2json 27 | 28 | The simplest way to use `sat2json` is as follows: 29 | 30 | ``` 31 | $ sat2json MODEL.sat licence_file=license.dat 32 | ``` 33 | 34 | This command will convert `MODEL.sat` into a JSON file which is directly readable by 35 | [geomdl](https://github.com/orbingol/NURBS-Python) via `exchange.import_json` API call. 36 | 37 | The `license.dat` contains your **unlock_key** which can be found inside your license 38 | source file at the following location: 39 | 40 | ![ACIS license key location](.github/acis_licensekey.jpg "You can find your license key here") 41 | 42 | Run `sat2json` without any command-line arguments for more details on using the application. 43 | 44 | ### satgen 45 | 46 | The simplest way to use `satgen` is as follows: 47 | 48 | ``` 49 | $ satgen SAMPLE.sat licence_file=license.dat 50 | ``` 51 | 52 | The arguments are very similar to `sat2json` command. Please note that the `SAMPLE.sat` file 53 | is the output of the `satgen` command. 54 | 55 | ## Author 56 | 57 | * Onur Rauf Bingol ([@orbingol](https://github.com/orbingol)) 58 | 59 | ## License 60 | 61 | * RWSAT is licensed under the terms of the [BSD 3-Clause License](LICENSE) 62 | * [JsonCpp](https://github.com/open-source-parsers/jsoncpp) is licensed under the terms of the [MIT License](https://github.com/open-source-parsers/jsoncpp/blob/master/LICENSE) 63 | * ACIS and SAT are registered trademarks of [Spatial Corporation](https://www.spatial.com/) 64 | -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 2.8.11) 2 | project(rwsat) 3 | 4 | # Extend CMake module path for loading custom modules 5 | set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_CURRENT_LIST_DIR}/cmake-modules") 6 | 7 | # Generate a Visual Studio filter "CMakePredefinedTargets" 8 | if(MSVC) 9 | set_property(GLOBAL PROPERTY USE_FOLDERS ON) 10 | set(PREDEFINED_TARGETS_FOLDER "CustomTargets") 11 | # Silence fopen warnings 12 | add_definitions(-D_CRT_SECURE_NO_WARNINGS) 13 | endif() 14 | 15 | # Set runtime path 16 | SET(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE) 17 | 18 | # Use C++11 19 | set(CMAKE_CXX_STANDARD 11) 20 | 21 | # Add 3rd party libraries 22 | add_subdirectory(3rdparty) 23 | 24 | # Set install directory 25 | set(RWSAT_INSTALL_DIR ${PROJECT_BINARY_DIR}/install CACHE PATH "Application install directory") 26 | set(CMAKE_INSTALL_PREFIX ${RWSAT_INSTALL_DIR}) 27 | 28 | # Options 29 | set(RWSAT_BUILD_SATGEN OFF CACHE BOOL "Build and install satgen") 30 | set(RWSAT_INSTALL_DLL ON CACHE BOOL "Install SpaACIS.dll file alongside with the executables") 31 | 32 | # Find ACIS headers and libraries 33 | find_package(ACIS REQUIRED) 34 | 35 | # Include ACIS includes if ACIS is installed 36 | if(ACIS_FOUND) 37 | include_directories(${ACIS_INCLUDE_DIRS}) 38 | else() 39 | message(FATAL_ERROR "ACIS not found") 40 | endif() 41 | 42 | # Set source files 43 | set(SOURCE_FILES_SAT2JSON 44 | src/ACIS.h 45 | src/common.h 46 | src/common.cpp 47 | src/extract.h 48 | src/extract.cpp 49 | src/sat2json.cpp 50 | ) 51 | 52 | # Create the executable 53 | add_executable(sat2json ${SOURCE_FILES_SAT2JSON}) 54 | target_link_libraries(sat2json jsoncpp ${ACIS_LINK_LIBRARIES}) 55 | set_target_properties(sat2json PROPERTIES DEBUG_POSTFIX "d") 56 | 57 | # Install the binary 58 | install( 59 | TARGETS sat2json 60 | DESTINATION ${RWSAT_INSTALL_DIR} 61 | ) 62 | 63 | if(RWSAT_BUILD_SATGEN) 64 | # Set source files for the generator application 65 | set(SOURCE_FILES_SATGEN 66 | src/ACIS.h 67 | src/common.h 68 | src/common.cpp 69 | src/satgen.cpp 70 | ) 71 | 72 | # Create the executable for the generator application 73 | add_executable(satgen ${SOURCE_FILES_SATGEN}) 74 | target_link_libraries(satgen ${ACIS_LINK_LIBRARIES}) 75 | set_target_properties(satgen PROPERTIES DEBUG_POSTFIX "d") 76 | 77 | # Install the generator application 78 | install( 79 | TARGETS satgen 80 | DESTINATION ${RWSAT_INSTALL_DIR} 81 | ) 82 | endif(RWSAT_BUILD_SATGEN) 83 | 84 | # On Windows, it would be wise copy required DLL files into the app directory 85 | if(MSVC AND ${RWSAT_INSTALL_DLL}) 86 | install( 87 | FILES ${ACIS_REDIST_RELEASE} 88 | DESTINATION ${RWSAT_INSTALL_DIR} 89 | CONFIGURATIONS Release RelWithDebInfo MinSizeRel 90 | ) 91 | 92 | install( 93 | FILES ${ACIS_REDIST_DEBUG} 94 | DESTINATION ${RWSAT_INSTALL_DIR} 95 | CONFIGURATIONS Debug 96 | ) 97 | endif() 98 | 99 | # Create uninstall target 100 | if(NOT TARGET uninstall) 101 | configure_file( 102 | "${CMAKE_CURRENT_SOURCE_DIR}/cmake_uninstall.cmake.in" 103 | "${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake" 104 | IMMEDIATE @ONLY) 105 | 106 | add_custom_target(uninstall 107 | COMMAND ${CMAKE_COMMAND} -P ${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake) 108 | endif() 109 | -------------------------------------------------------------------------------- /src/common.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2019, Integrated Design and Engineering Analysis Laboratory (IDEA Lab) at Iowa State University. 3 | All rights reserved. 4 | 5 | Redistribution and use in source and binary forms, with or without 6 | modification, are permitted provided that the following conditions are met: 7 | * Redistributions of source code must retain the above copyright 8 | notice, this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above copyright 10 | notice, this list of conditions and the following disclaimer in the 11 | documentation and/or other materials provided with the distribution. 12 | * Neither the name of the copyright holder nor the 13 | names of its contributors may be used to endorse or promote products 14 | derived from this software without specific prior written permission. 15 | 16 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 17 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 18 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 19 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY 20 | DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 21 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 22 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 23 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 25 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | */ 27 | 28 | #ifndef COMMON_H 29 | #define COMMON_H 30 | 31 | // C++ includes 32 | #include 33 | #include 34 | #include 35 | #include 36 | #include 37 | #include 38 | #include 39 | #include 40 | #include 41 | #include 42 | 43 | // External libraries 44 | #include "ACIS.h" 45 | 46 | 47 | // Application configuration 48 | struct Config { 49 | // Config parameters 50 | std::map< std::string, std::pair > params = { 51 | { "show_config", { "0", "Prints the configuration" } }, 52 | { "license_file",{ "", "Name of the ACIS license file" } }, 53 | { "license_key", { "", "ACIS unlock key" } }, 54 | { "acis_warnings", { "0", "Enable ACIS warnings" } }, 55 | { "warnings", { "0", "Enable application warnings" } }, 56 | { "normalize", { "1", "Normalize knot vectors and and scale trim curves to [0,1] domain" } }, 57 | { "trims", { "1", "Extract trim curves" } }, 58 | { "sense", { "1", "Extract surface and trim curve direction w.r.t. the face" } }, 59 | { "transform", { "0", "Apply transforms" } }, 60 | { "bspline", { "1", "Convert the underlying geometry to B-Spline" } } 61 | }; 62 | 63 | // Methods 64 | const char* acis_license(); 65 | bool show_config(); 66 | bool acis_warnings(); 67 | bool warnings(); 68 | bool normalize(); 69 | bool trims(); 70 | bool sense(); 71 | bool transform(); 72 | bool bspline(); 73 | }; 74 | 75 | // Function prototypes 76 | std::string readLicenseFile(std::string &, bool = true); 77 | void parseConfig(char *, Config &); 78 | void updateConfig(std::string &, std::string &, Config &); 79 | void checkOutcome(const outcome&, const char*, int, Config &); 80 | bool unlockACIS(Config &cfg); 81 | bool saveSatFile(ENTITY_LIST &, std::string &, Config &); 82 | bool readSatFile(std::string &, ENTITY_LIST &, Config &); 83 | 84 | #endif /* COMMON_H */ 85 | -------------------------------------------------------------------------------- /src/ACIS.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2019, Integrated Design and Engineering Analysis Laboratory (IDEA Lab) at Iowa State University. 3 | All rights reserved. 4 | 5 | Redistribution and use in source and binary forms, with or without 6 | modification, are permitted provided that the following conditions are met: 7 | * Redistributions of source code must retain the above copyright 8 | notice, this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above copyright 10 | notice, this list of conditions and the following disclaimer in the 11 | documentation and/or other materials provided with the distribution. 12 | * Neither the name of the copyright holder nor the 13 | names of its contributors may be used to endorse or promote products 14 | derived from this software without specific prior written permission. 15 | 16 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 17 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 18 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 19 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY 20 | DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 21 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 22 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 23 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 25 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | */ 27 | 28 | #ifndef ACIS_H 29 | #define ACIS_H 30 | 31 | //ACIS Includes 32 | #include // Declares system wide parameters 33 | #include // Licensing 34 | #include // Licensing 35 | #include // ACIS versioning 36 | #include // Declares constructor APIs 37 | #include // Declares kernel APIs 38 | #include // Declares BODY class 39 | #include // Declares boolean APIs 40 | #include // Declares FileInfo class 41 | #include // Outcome Progress 42 | #include // Declares position class 43 | #include // Declares vector class 44 | #include // Declares unit vector class 45 | #include // Declares distance utilites 46 | #include // Declares parametric coordinates 47 | #include // Declares ENTITY_LIST class 48 | #include // Declares SURFACE class 49 | #include // Declares surface class 50 | #include // Declares face covering APIs 51 | #include // Declares sweep APIs 52 | #include // Declares stitching APIs 53 | #include // Declares multi-threaded stitching APIs 54 | #include // Declares shelling APIs 55 | #include // Declares wire cover oOptions 56 | #include // Declares 3-dimensional spline surface class 57 | #include // Declares 2-dimensional spline curve class 58 | #include // Declares 3-dimensional spline curve class 59 | #include // Declares 3-D B-spline surface class 60 | #include // Declares 2-D B-spline curve class 61 | #include // Declares 2-D B-spline curve class 62 | #include // Declares 3-D B-spline curve class 63 | #include // Declares projection options 64 | #include // Declares APIs for point in face and check entity 65 | #include // Declares APIs for offseting 66 | #include // Declares offset options class 67 | #include // Declares Generic Attributes API 68 | #include // Declares a generic attribute which stores a string value 69 | #include // Declares a generic attribute which stores an integer value 70 | #include // Declares interfaces related to Model Query 71 | #include // Provides std::vector like interfaces within ACIS 72 | #include 73 | #include 74 | #include 75 | #include // Declares Convert to Spline options class 76 | #include // Declares Local Operations API 77 | #include 78 | #include // Declares Basic Blending API 79 | #include 80 | #include 81 | #include // Declares EDGE class 82 | #include // Declares CURVE class 83 | #include // Declares curve class 84 | #include // Declares mass_prop class for storing physical properties 85 | #include // Declares SPAbox (bounding box) 86 | #include 87 | #include 88 | #include 89 | #include 90 | #include 91 | #include // Declares pcurve class 92 | #include // Declares PCURVE class 93 | #include // Declares colors for entities 94 | #include // Declares rendering apis 95 | #include // Declares poly_point_mesh manager 96 | #include // Declares refinement class 97 | #include // Declares facet options class 98 | #include // Declares enum types 99 | #include // Declares Faceter API 100 | #include // Declares "logical" variable 101 | #include // Declares bs3_surface API 102 | #include // Declares LOOP class 103 | #include // Declares enumarations for relationships between faces and points 104 | #include // Declares entitiy splitting API 105 | 106 | // ACIS Debugging 107 | #include // Declares debugging routines 108 | 109 | #endif /* ACIS_H */ 110 | -------------------------------------------------------------------------------- /src/satgen.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2019, Integrated Design and Engineering Analysis Laboratory (IDEA Lab) at Iowa State University. 3 | All rights reserved. 4 | 5 | Redistribution and use in source and binary forms, with or without 6 | modification, are permitted provided that the following conditions are met: 7 | * Redistributions of source code must retain the above copyright 8 | notice, this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above copyright 10 | notice, this list of conditions and the following disclaimer in the 11 | documentation and/or other materials provided with the distribution. 12 | * Neither the name of the copyright holder nor the 13 | names of its contributors may be used to endorse or promote products 14 | derived from this software without specific prior written permission. 15 | 16 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 17 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 18 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 19 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY 20 | DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 21 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 22 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 23 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 25 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | */ 27 | 28 | #include "common.h" 29 | 30 | 31 | // SATGEN executable 32 | int main(int argc, char **argv) 33 | { 34 | // Print app information 35 | std::cout << "SATGEN: Geometry Generator for ACIS" << std::endl; 36 | std::cout << "Copyright (c) 2019 IDEA Lab at Iowa State University." << std::endl; 37 | std::cout << "Licensed under the terms of BSD License.\n" << std::endl; 38 | 39 | // File name to write 40 | std::string fileName; 41 | 42 | if (argc < 2 || argc > 3) 43 | { 44 | std::cout << "Usage: " << argv[0] << " FILENAME OPTIONS\n" << std::endl; 45 | #ifdef _MSC_VER 46 | std::cout << "Note: A license key should be provided using 'license_key' or 'license_file' arguments." << std::endl; 47 | #endif 48 | return EXIT_FAILURE; 49 | } 50 | else 51 | fileName = std::string(argv[1]); 52 | 53 | // Initialize configuration 54 | Config cfg; 55 | 56 | // Update configuration 57 | if (argc == 3) 58 | parseConfig(argv[2], cfg); 59 | 60 | // Print configuration 61 | if (cfg.show_config()) 62 | { 63 | std::cout << "Using configuration:" << std::endl; 64 | for (auto p : cfg.params) 65 | std::cout << " - " << p.first << ": " << p.second.first << std::endl; 66 | } 67 | 68 | // Initialize a variable to store ACIS API outcome 69 | outcome res; 70 | 71 | // Start ACIS 72 | res = api_start_modeller(); 73 | checkOutcome(res, "api_start_modeller", __LINE__, cfg); 74 | 75 | // Unlock ACIS (required only on Windows) 76 | #ifdef _MSC_VER 77 | if (!unlockACIS(cfg)) 78 | return EXIT_FAILURE; 79 | #endif 80 | 81 | // Entities to be saved 82 | ENTITY_LIST saveList; 83 | 84 | // Create a cuboid 85 | BODY *cuboid; 86 | res = api_make_cuboid(5, 10, 20, cuboid); 87 | checkOutcome(res, "api_make_cuboid", __LINE__, cfg); 88 | 89 | // Create transformation 90 | SPAposition rotate_pos(20, 0, 0); 91 | SPAtransf r = rotate_transf(M_PI / 4, SPAvector(0, 0, 1)); 92 | SPAvector to_rotate_pos = rotate_pos - SPAposition(0, 0, 0); 93 | SPAtransf t = translate_transf(to_rotate_pos); 94 | SPAtransf tc = t.inverse() * r * t; 95 | 96 | // Transform cuboid 97 | res = api_apply_transf(cuboid, tc); 98 | checkOutcome(res, "api_apply_transf", __LINE__, cfg); 99 | res = api_change_body_trans(cuboid, NULL); 100 | checkOutcome(res, "api_change_body_trans", __LINE__, cfg); 101 | 102 | // Add to save list 103 | saveList.add(cuboid); 104 | 105 | // Create a torus 106 | BODY *torus; 107 | res = api_make_torus(25, 12.5, torus); 108 | checkOutcome(res, "api_make_torus", __LINE__, cfg); 109 | 110 | // Create transformation 111 | SPAposition translate_pos1(0, 0, -100); 112 | SPAvector to_translate_pos1 = translate_pos1 - SPAposition(0, 0, 0); 113 | SPAtransf tt1 = translate_transf(to_translate_pos1); 114 | 115 | // Transform torus 116 | res = api_apply_transf(torus, tt1); 117 | checkOutcome(res, "api_apply_transf", __LINE__, cfg); 118 | res = api_change_body_trans(torus, NULL); 119 | checkOutcome(res, "api_change_body_trans", __LINE__, cfg); 120 | 121 | // Add to save list 122 | saveList.add(torus); 123 | 124 | // Create a toroidal face 125 | FACE *torodialFace; 126 | SPAposition center(25, 25, 25); 127 | SPAvector normal(0, 0, 1); 128 | res = api_face_torus(center, 10, 2.5, 0, 360, 0, 180, &normal, torodialFace); 129 | checkOutcome(res, "api_face_torus", __LINE__, cfg); 130 | 131 | // Create a sheet body from the toroidal face 132 | FACE *faces[1]; 133 | faces[0] = torodialFace; 134 | BODY *torus2; 135 | res = api_sheet_from_ff(1, faces, torus2); 136 | checkOutcome(res, "api_sheet_from_ff", __LINE__, cfg); 137 | 138 | // Create transformation 139 | SPAposition translate_pos2(0, 0, -100); 140 | SPAvector to_translate_pos2 = translate_pos2 - SPAposition(0, 0, 0); 141 | SPAtransf tt2 = translate_transf(to_translate_pos1); 142 | 143 | // Transform toroidal sheet body 144 | res = api_apply_transf(torus2, tt2); 145 | checkOutcome(res, "api_apply_transf", __LINE__, cfg); 146 | res = api_change_body_trans(torus2, NULL); 147 | checkOutcome(res, "api_change_body_trans", __LINE__, cfg); 148 | 149 | // Add to save list 150 | saveList.add(torus2); 151 | 152 | // Make a sphere 153 | BODY *sphere; 154 | res = api_make_sphere(2.5, sphere); 155 | checkOutcome(res, "api_make_sphere", __LINE__, cfg); 156 | 157 | // Create transformation 158 | SPAposition translate_pos3(100, 100, 0); 159 | SPAvector to_translate_pos3 = translate_pos3 - SPAposition(0, 0, 0); 160 | SPAtransf ts = translate_transf(to_translate_pos3); 161 | 162 | // Transform sphere 163 | res = api_apply_transf(sphere, ts); 164 | checkOutcome(res, "api_apply_transf", __LINE__, cfg); 165 | res = api_change_body_trans(sphere, NULL); 166 | checkOutcome(res, "api_change_body_trans", __LINE__, cfg); 167 | 168 | // Add to save list 169 | saveList.add(sphere); 170 | 171 | // Save list as a .SAT file 172 | if (saveSatFile(saveList, fileName, cfg)) 173 | std::cout << "[SUCCESS] '" << fileName << "' was generated successfully!" << std::endl; 174 | 175 | // Stop ACIS 176 | res = api_stop_modeller(); 177 | checkOutcome(res, "api_stop_modeller", __LINE__, cfg); 178 | 179 | return EXIT_SUCCESS; 180 | } 181 | -------------------------------------------------------------------------------- /src/extract.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2019, Integrated Design and Engineering Analysis Laboratory (IDEA Lab) at Iowa State University. 3 | All rights reserved. 4 | 5 | Redistribution and use in source and binary forms, with or without 6 | modification, are permitted provided that the following conditions are met: 7 | * Redistributions of source code must retain the above copyright 8 | notice, this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above copyright 10 | notice, this list of conditions and the following disclaimer in the 11 | documentation and/or other materials provided with the distribution. 12 | * Neither the name of the copyright holder nor the 13 | names of its contributors may be used to endorse or promote products 14 | derived from this software without specific prior written permission. 15 | 16 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 17 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 18 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 19 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY 20 | DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 21 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 22 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 23 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 25 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | */ 27 | 28 | #include "extract.h" 29 | 30 | 31 | // Extract spline surface data 32 | void extractSurfaceData(bs3_surface &splineSurf, Config &cfg, Json::Value &surfDef) 33 | { 34 | // Surface spatial dimension 35 | int dim; 36 | 37 | // Surface form = 0 (open -clamped-), 1 (closed -unclamped-), 2 (periodic) 38 | int form_u, form_v; 39 | 40 | // Flag indicating the existence of poles (singularities) 41 | int pole_u, pole_v; 42 | 43 | // Rational/non-rational flag 44 | int rat_u, rat_v; 45 | 46 | // Degrees 47 | int degree_u, degree_v; 48 | 49 | // Knot vectors 50 | int num_knots_u, num_knots_v; 51 | double *knots_u; 52 | double *knots_v; 53 | 54 | // Extract control points and weights (weights != NULL if rational) 55 | int num_u, num_v; 56 | SPAposition *ctrlpts; 57 | double *weights; 58 | 59 | // Extract surface data 60 | bs3_surface_to_array(splineSurf, dim, rat_u, rat_v, form_u, form_v, pole_u, pole_v, 61 | num_u, num_v, ctrlpts, weights, 62 | degree_u, num_knots_u, knots_u, 63 | degree_v, num_knots_v, knots_v 64 | ); 65 | 66 | // Create JSON object for each surface 67 | surfDef["rational"] = (rat_u || rat_v) ? true : false; 68 | surfDef["form_u"] = degree_u; 69 | surfDef["form_v"] = degree_v; 70 | surfDef["degree_u"] = degree_u; 71 | surfDef["degree_v"] = degree_v; 72 | Json::Value kvU; 73 | for (int k = 0; k < num_knots_u; k++) 74 | { 75 | if (cfg.normalize()) 76 | kvU[k] = (knots_u[k] - knots_u[0]) / (knots_u[num_knots_u - 1] - knots_u[0]); 77 | else 78 | kvU[k] = knots_u[k]; 79 | } 80 | surfDef["knotvector_u"] = kvU; 81 | Json::Value kvV; 82 | for (int k = 0; k < num_knots_v; k++) 83 | { 84 | if (cfg.normalize()) 85 | kvV[k] = (knots_v[k] - knots_v[0]) / (knots_v[num_knots_v - 1] - knots_v[0]); 86 | else 87 | kvV[k] = knots_v[k]; 88 | } 89 | surfDef["knotvector_v"] = kvV; 90 | surfDef["size_u"] = num_u; 91 | surfDef["size_v"] = num_v; 92 | Json::Value ctrlptsDef; 93 | Json::Value pointsDef; 94 | for (int ku = 0; ku < num_u; ku++) 95 | { 96 | for (int kv = 0; kv < num_v; kv++) 97 | { 98 | int idx = kv + (num_v * ku); 99 | Json::Value ptDef; 100 | for (int c = 0; c < 3; c++) 101 | { 102 | ptDef[c] = ctrlpts[idx].coordinate(c); 103 | } 104 | pointsDef[idx] = ptDef; 105 | } 106 | } 107 | ctrlptsDef["points"] = pointsDef; 108 | if (weights != nullptr) 109 | { 110 | Json::Value weightsDef; 111 | for (int ku = 0; ku < num_u; ku++) 112 | { 113 | for (int kv = 0; kv < num_v; kv++) 114 | { 115 | int idx = kv + (num_v * ku); 116 | weightsDef[idx] = weights[idx]; 117 | } 118 | } 119 | ctrlptsDef["weights"] = weightsDef; 120 | } 121 | surfDef["control_points"] = ctrlptsDef; 122 | 123 | // Delete arrays 124 | free(knots_u); 125 | free(knots_v); 126 | free(ctrlpts); 127 | if (weights != NULL) 128 | free(weights); 129 | } 130 | 131 | // Extract the trim curve data 132 | void extractTrimCurveData(bs2_curve &trimCurve, Config &cfg, double *paramOffset, double *paramLength, Json::Value &curveDef) 133 | { 134 | // Curve spatial dimension 135 | int cdim; 136 | 137 | // Rational/non-rational flag 138 | int crat; 139 | 140 | // Curve degree 141 | int cdegree; 142 | 143 | // Knot vector 144 | int num_cknots; 145 | double *cknots; 146 | 147 | // Control points (parametric coordinates as [u,v,0]) 148 | int num_cctrlpts; 149 | SPAposition *cctrlpts; 150 | double *cweights; 151 | 152 | // Extract trim curve data 153 | bs2_curve_to_array(trimCurve, cdim, cdegree, crat, num_cctrlpts, cctrlpts, cweights, num_cknots, cknots); 154 | 155 | // Update JSON object for the trim curve 156 | curveDef["type"] = "spline"; // make sure that you are always calling api_convert_to_spline() 157 | curveDef["rational"] = bool(crat); 158 | curveDef["degree"] = cdegree; 159 | Json::Value ckv; 160 | for (int k = 0; k < num_cknots; k++) 161 | { 162 | if (cfg.normalize()) 163 | ckv[k] = (cknots[k] - cknots[0]) / (cknots[num_cknots - 1] - cknots[0]); 164 | else 165 | ckv[k] = cknots[k]; 166 | } 167 | curveDef["knotvector"] = ckv; 168 | Json::Value cctrlptsDef; 169 | Json::Value cpointsDef; 170 | for (int idx = 0; idx < num_cctrlpts; idx++) 171 | { 172 | Json::Value cptDef; 173 | for (int c = 0; c < 2; c++) 174 | { 175 | if (cfg.normalize()) 176 | cptDef[c] = (cctrlpts[idx].coordinate(c) - paramOffset[c]) / paramLength[c]; 177 | else 178 | cptDef[c] = cctrlpts[idx].coordinate(c); 179 | } 180 | cpointsDef[idx] = cptDef; 181 | } 182 | cctrlptsDef["points"] = cpointsDef; 183 | if (cweights != nullptr) 184 | { 185 | Json::Value cweightsDef; 186 | for (int idx = 0; idx < num_cctrlpts; idx++) 187 | { 188 | cweightsDef[idx] = cweights[idx]; 189 | } 190 | cctrlptsDef["weights"] = cweightsDef; 191 | } 192 | curveDef["control_points"] = cctrlptsDef; 193 | 194 | // Delete arrays 195 | free(cknots); 196 | free(cctrlpts); 197 | if (cweights != NULL) 198 | free(cweights); 199 | } 200 | -------------------------------------------------------------------------------- /src/common.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2019, Integrated Design and Engineering Analysis Laboratory (IDEA Lab) at Iowa State University. 3 | All rights reserved. 4 | 5 | Redistribution and use in source and binary forms, with or without 6 | modification, are permitted provided that the following conditions are met: 7 | * Redistributions of source code must retain the above copyright 8 | notice, this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above copyright 10 | notice, this list of conditions and the following disclaimer in the 11 | documentation and/or other materials provided with the distribution. 12 | * Neither the name of the copyright holder nor the 13 | names of its contributors may be used to endorse or promote products 14 | derived from this software without specific prior written permission. 15 | 16 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 17 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 18 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 19 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY 20 | DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 21 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 22 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 23 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 25 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | */ 27 | 28 | #include "common.h" 29 | 30 | 31 | const char* Config::acis_license() 32 | { 33 | if (!params.at("license_file").first.empty()) 34 | params["license_key"].first = readLicenseFile(params.at("license_file").first); 35 | return params.at("license_key").first.c_str(); 36 | } 37 | 38 | bool Config::show_config() 39 | { 40 | return bool(std::atoi(params.at("show_config").first.c_str())); 41 | } 42 | 43 | bool Config::acis_warnings() 44 | { 45 | return bool(std::atoi(params.at("acis_warnings").first.c_str())); 46 | } 47 | 48 | bool Config::warnings() { 49 | return bool(std::atoi(params.at("warnings").first.c_str())); 50 | } 51 | 52 | bool Config::normalize() 53 | { 54 | return bool(std::atoi(params.at("normalize").first.c_str())); 55 | } 56 | 57 | bool Config::trims() 58 | { 59 | return bool(std::atoi(params.at("trims").first.c_str())); 60 | } 61 | 62 | bool Config::sense() 63 | { 64 | return bool(std::atoi(params.at("sense").first.c_str())); 65 | } 66 | 67 | bool Config::transform() 68 | { 69 | return bool(std::atoi(params.at("transform").first.c_str())); 70 | } 71 | 72 | bool Config::bspline() 73 | { 74 | return bool(std::atoi(params.at("bspline").first.c_str())); 75 | } 76 | 77 | // Read license file 78 | std::string readLicenseFile(std::string &fileName, bool clean) 79 | { 80 | std::string fileContent; 81 | std::ifstream fileRead(fileName); 82 | if (fileRead) 83 | { 84 | std::stringstream buf; 85 | buf << fileRead.rdbuf(); 86 | fileContent = buf.str(); 87 | if (clean) 88 | { 89 | fileContent.erase(std::remove(fileContent.begin(), fileContent.end(), ' '), fileContent.end()); 90 | fileContent.erase(std::remove(fileContent.begin(), fileContent.end(), '\n'), fileContent.end()); 91 | fileContent.erase(std::remove(fileContent.begin(), fileContent.end(), '\r'), fileContent.end()); 92 | fileContent.erase(std::remove(fileContent.begin(), fileContent.end(), '\t'), fileContent.end()); 93 | fileContent.erase(std::remove(fileContent.begin(), fileContent.end(), '"'), fileContent.end()); 94 | fileContent.erase(std::remove(fileContent.begin(), fileContent.end(), ';'), fileContent.end()); 95 | } 96 | } 97 | return fileContent; 98 | } 99 | 100 | // Parse configuration from a string 101 | void parseConfig(char *conf_str, Config & cfg) 102 | { 103 | // Define delimiters 104 | std::string delimiter = ";"; 105 | std::string cfg_delimiter = "="; 106 | 107 | // Parse user config string 108 | std::string s(conf_str); 109 | while (true) 110 | { 111 | std::size_t pos = s.find(delimiter); 112 | std::string cfg_directive = s.substr(0, pos); 113 | std::size_t cfg_pos = cfg_directive.find(cfg_delimiter); 114 | if (cfg_pos != std::string::npos) 115 | { 116 | std::string key = cfg_directive.substr(0, cfg_pos); 117 | std::string value = cfg_directive.substr(cfg_pos + 1); 118 | updateConfig(key, value, cfg); 119 | } 120 | if (pos == std::string::npos) 121 | break; 122 | else 123 | s = s.substr(++pos); 124 | } 125 | } 126 | 127 | // Update application configuration 128 | void updateConfig(std::string &key, std::string &value, Config &cfg) 129 | { 130 | auto search = cfg.params.find(key); 131 | if (search != cfg.params.end()) 132 | { 133 | std::string val; 134 | std::transform(value.begin(), value.end(), value.begin(), ::tolower); 135 | if (value == "false" || value == "0") 136 | val = "0"; 137 | else if (value == "true" || value == "0") 138 | val = "1"; 139 | else 140 | val = std::string(value); 141 | cfg.params[key].first = val; 142 | } 143 | } 144 | 145 | // Unlock ACIS 146 | bool unlockACIS(Config &cfg) 147 | { 148 | spa_unlock_result out = spa_unlock_products(cfg.acis_license()); 149 | 150 | bool retVal = true; 151 | switch (out.get_state()) 152 | { 153 | case SPA_UNLOCK_PASS_WARN: 154 | if (cfg.acis_warnings()) 155 | std::cout << "[LICENSE WARNING] " << out.get_message_text() << std::endl; 156 | break; 157 | case SPA_UNLOCK_FAIL: 158 | std::cout << "[LICENSE ERROR] " << out.get_message_text() << std::endl; 159 | retVal = false; 160 | break; 161 | default: 162 | /* License is valid -- SPA_UNLOCK_PASS */; 163 | } 164 | 165 | return retVal; 166 | } 167 | 168 | // Check ACIS API outcome 169 | void checkOutcome(const outcome &res, const char *apiCall, int lineNumber, Config &cfg) 170 | { 171 | // Check if ACIS has encountered any errors (fail-safe or critical) 172 | if (res.encountered_errors()) 173 | { 174 | // Query for ACIS error number 175 | err_mess_type err_no = res.error_number(); 176 | 177 | // Get error message 178 | std::string error_str = std::string(find_err_mess(err_no)) + " (" + std::string(find_err_ident(err_no)) + ")"; 179 | 180 | // Flag to stop the application 181 | bool stopApp = false; 182 | 183 | // Display error information, crash program if critical 184 | if (res.ok()) 185 | { 186 | if (cfg.acis_warnings()) 187 | std::cout << "[ERROR] ACIS encountered a non-critical error: " << error_str << std::endl; 188 | } 189 | else 190 | { 191 | std::cout << "[ERROR] ACIS encountered a critical error: " << error_str << std::endl; 192 | stopApp = true; 193 | } 194 | 195 | // Print function name and its line number 196 | std::cout << "Function: " << apiCall << "; Line: " << lineNumber << std::endl; 197 | 198 | // Stop the application in the ACIS way 199 | if (stopApp) 200 | sys_error(err_no); 201 | } 202 | 203 | // Print warnings 204 | if (cfg.acis_warnings()) 205 | { 206 | err_mess_type *warnings; 207 | int nwarn = get_warnings(warnings); 208 | if (nwarn > 0) 209 | { 210 | std::cout << "[WARNING] ACIS produced the following warnings:" << std::endl; 211 | for (int i = 0; i < nwarn; ++i) 212 | std::cout << " - " << warnings[i] << ": " << find_err_mess(warnings[i]) << std::endl; 213 | // Reset number of warnings to zero 214 | init_warnings(); 215 | } 216 | } 217 | 218 | } 219 | 220 | // Read ACIS file 221 | bool readSatFile(std::string &fileName, ENTITY_LIST &readList, Config &cfg) 222 | { 223 | // Try to open SAT file for reading 224 | FILE *fp = fopen(fileName.c_str(), "r"); 225 | if (fp == NULL) 226 | { 227 | std::cerr << "[ERROR] Cannot open file '" << fileName << "' for reading!" << std::endl; 228 | return false; 229 | } 230 | 231 | // Initialize a variable to store ACIS API outcome 232 | outcome res; 233 | 234 | // Read the SAT file into an ENTITY_LIST 235 | res = api_restore_entity_list(fp, TRUE, readList); 236 | checkOutcome(res, "api_restore_entity_list", __LINE__, cfg); 237 | 238 | // Close file 239 | fclose(fp); 240 | 241 | return true; 242 | } 243 | 244 | // Save ACIS file 245 | bool saveSatFile(ENTITY_LIST &saveList, std::string &fileName, Config &cfg) 246 | { 247 | // Create FileInfo object 248 | FileInfo info; 249 | info.set_product_id(fileName.c_str()); 250 | info.set_units(1.0); // millimeters 251 | api_set_file_info(FileUnits | FileIdent, info); 252 | api_save_version(18, 0); // compatibility with the older versions 253 | 254 | // Set line numbers on 255 | api_set_int_option("sequence_save_files", 1); 256 | 257 | // Open file 258 | FILE *fp = fopen(fileName.c_str(), "w"); 259 | if (fp == NULL) 260 | { 261 | std::cerr << "[ERROR] Cannot open file '" << fileName << "' for writing!" << std::endl; 262 | return false; 263 | } 264 | 265 | // Initialize a variable to store ACIS API outcome 266 | outcome res; 267 | 268 | // Save SAT file 269 | res = api_save_entity_list(fp, true, saveList); 270 | checkOutcome(res, "api_save_entity_list", __LINE__, cfg); 271 | 272 | // Close file 273 | fclose(fp); 274 | 275 | return true; 276 | } 277 | -------------------------------------------------------------------------------- /3rdparty/jsoncpp/json/json-forwards.h: -------------------------------------------------------------------------------- 1 | /// Json-cpp amalgamated forward header (http://jsoncpp.sourceforge.net/). 2 | /// It is intended to be used with #include "json/json-forwards.h" 3 | /// This header provides forward declaration for all JsonCpp types. 4 | 5 | // ////////////////////////////////////////////////////////////////////// 6 | // Beginning of content of file: LICENSE 7 | // ////////////////////////////////////////////////////////////////////// 8 | 9 | /* 10 | The JsonCpp library's source code, including accompanying documentation, 11 | tests and demonstration applications, are licensed under the following 12 | conditions... 13 | 14 | Baptiste Lepilleur and The JsonCpp Authors explicitly disclaim copyright in all 15 | jurisdictions which recognize such a disclaimer. In such jurisdictions, 16 | this software is released into the Public Domain. 17 | 18 | In jurisdictions which do not recognize Public Domain property (e.g. Germany as of 19 | 2010), this software is Copyright (c) 2007-2010 by Baptiste Lepilleur and 20 | The JsonCpp Authors, and is released under the terms of the MIT License (see below). 21 | 22 | In jurisdictions which recognize Public Domain property, the user of this 23 | software may choose to accept it either as 1) Public Domain, 2) under the 24 | conditions of the MIT License (see below), or 3) under the terms of dual 25 | Public Domain/MIT License conditions described here, as they choose. 26 | 27 | The MIT License is about as close to Public Domain as a license can get, and is 28 | described in clear, concise terms at: 29 | 30 | http://en.wikipedia.org/wiki/MIT_License 31 | 32 | The full text of the MIT License follows: 33 | 34 | ======================================================================== 35 | Copyright (c) 2007-2010 Baptiste Lepilleur and The JsonCpp Authors 36 | 37 | Permission is hereby granted, free of charge, to any person 38 | obtaining a copy of this software and associated documentation 39 | files (the "Software"), to deal in the Software without 40 | restriction, including without limitation the rights to use, copy, 41 | modify, merge, publish, distribute, sublicense, and/or sell copies 42 | of the Software, and to permit persons to whom the Software is 43 | furnished to do so, subject to the following conditions: 44 | 45 | The above copyright notice and this permission notice shall be 46 | included in all copies or substantial portions of the Software. 47 | 48 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 49 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 50 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 51 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS 52 | BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN 53 | ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 54 | CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 55 | SOFTWARE. 56 | ======================================================================== 57 | (END LICENSE TEXT) 58 | 59 | The MIT license is compatible with both the GPL and commercial 60 | software, affording one all of the rights of Public Domain with the 61 | minor nuisance of being required to keep the above copyright notice 62 | and license text in the source code. Note also that by accepting the 63 | Public Domain "license" you can re-license your copy using whatever 64 | license you like. 65 | 66 | */ 67 | 68 | // ////////////////////////////////////////////////////////////////////// 69 | // End of content of file: LICENSE 70 | // ////////////////////////////////////////////////////////////////////// 71 | 72 | 73 | 74 | 75 | 76 | #ifndef JSON_FORWARD_AMALGAMATED_H_INCLUDED 77 | # define JSON_FORWARD_AMALGAMATED_H_INCLUDED 78 | /// If defined, indicates that the source file is amalgamated 79 | /// to prevent private header inclusion. 80 | #define JSON_IS_AMALGAMATION 81 | 82 | // ////////////////////////////////////////////////////////////////////// 83 | // Beginning of content of file: include/json/config.h 84 | // ////////////////////////////////////////////////////////////////////// 85 | 86 | // Copyright 2007-2010 Baptiste Lepilleur and The JsonCpp Authors 87 | // Distributed under MIT license, or public domain if desired and 88 | // recognized in your jurisdiction. 89 | // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE 90 | 91 | #ifndef JSON_CONFIG_H_INCLUDED 92 | #define JSON_CONFIG_H_INCLUDED 93 | #include 94 | #include //typedef String 95 | #include //typedef int64_t, uint64_t 96 | 97 | /// If defined, indicates that json library is embedded in CppTL library. 98 | //# define JSON_IN_CPPTL 1 99 | 100 | /// If defined, indicates that json may leverage CppTL library 101 | //# define JSON_USE_CPPTL 1 102 | /// If defined, indicates that cpptl vector based map should be used instead of 103 | /// std::map 104 | /// as Value container. 105 | //# define JSON_USE_CPPTL_SMALLMAP 1 106 | 107 | // If non-zero, the library uses exceptions to report bad input instead of C 108 | // assertion macros. The default is to use exceptions. 109 | #ifndef JSON_USE_EXCEPTION 110 | #define JSON_USE_EXCEPTION 1 111 | #endif 112 | 113 | /// If defined, indicates that the source file is amalgamated 114 | /// to prevent private header inclusion. 115 | /// Remarks: it is automatically defined in the generated amalgamated header. 116 | // #define JSON_IS_AMALGAMATION 117 | 118 | #ifdef JSON_IN_CPPTL 119 | #include 120 | #ifndef JSON_USE_CPPTL 121 | #define JSON_USE_CPPTL 1 122 | #endif 123 | #endif 124 | 125 | #ifdef JSON_IN_CPPTL 126 | #define JSON_API CPPTL_API 127 | #elif defined(JSON_DLL_BUILD) 128 | #if defined(_MSC_VER) || defined(__MINGW32__) 129 | #define JSON_API __declspec(dllexport) 130 | #define JSONCPP_DISABLE_DLL_INTERFACE_WARNING 131 | #endif // if defined(_MSC_VER) 132 | #elif defined(JSON_DLL) 133 | #if defined(_MSC_VER) || defined(__MINGW32__) 134 | #define JSON_API __declspec(dllimport) 135 | #define JSONCPP_DISABLE_DLL_INTERFACE_WARNING 136 | #endif // if defined(_MSC_VER) 137 | #endif // ifdef JSON_IN_CPPTL 138 | #if !defined(JSON_API) 139 | #define JSON_API 140 | #endif 141 | 142 | // If JSON_NO_INT64 is defined, then Json only support C++ "int" type for 143 | // integer 144 | // Storages, and 64 bits integer support is disabled. 145 | // #define JSON_NO_INT64 1 146 | 147 | #if defined(_MSC_VER) // MSVC 148 | # if _MSC_VER <= 1200 // MSVC 6 149 | // Microsoft Visual Studio 6 only support conversion from __int64 to double 150 | // (no conversion from unsigned __int64). 151 | # define JSON_USE_INT64_DOUBLE_CONVERSION 1 152 | // Disable warning 4786 for VS6 caused by STL (identifier was truncated to '255' 153 | // characters in the debug information) 154 | // All projects I've ever seen with VS6 were using this globally (not bothering 155 | // with pragma push/pop). 156 | # pragma warning(disable : 4786) 157 | # endif // MSVC 6 158 | 159 | # if _MSC_VER >= 1500 // MSVC 2008 160 | /// Indicates that the following function is deprecated. 161 | # define JSONCPP_DEPRECATED(message) __declspec(deprecated(message)) 162 | # endif 163 | 164 | #endif // defined(_MSC_VER) 165 | 166 | // In c++11 the override keyword allows you to explicitly define that a function 167 | // is intended to override the base-class version. This makes the code more 168 | // managable and fixes a set of common hard-to-find bugs. 169 | #if __cplusplus >= 201103L 170 | # define JSONCPP_OVERRIDE override 171 | # define JSONCPP_NOEXCEPT noexcept 172 | #elif defined(_MSC_VER) && _MSC_VER > 1600 && _MSC_VER < 1900 173 | # define JSONCPP_OVERRIDE override 174 | # define JSONCPP_NOEXCEPT throw() 175 | #elif defined(_MSC_VER) && _MSC_VER >= 1900 176 | # define JSONCPP_OVERRIDE override 177 | # define JSONCPP_NOEXCEPT noexcept 178 | #else 179 | # define JSONCPP_OVERRIDE 180 | # define JSONCPP_NOEXCEPT throw() 181 | #endif 182 | 183 | #ifndef JSON_HAS_RVALUE_REFERENCES 184 | 185 | #if defined(_MSC_VER) && _MSC_VER >= 1600 // MSVC >= 2010 186 | #define JSON_HAS_RVALUE_REFERENCES 1 187 | #endif // MSVC >= 2010 188 | 189 | #ifdef __clang__ 190 | #if __has_feature(cxx_rvalue_references) 191 | #define JSON_HAS_RVALUE_REFERENCES 1 192 | #endif // has_feature 193 | 194 | #elif defined __GNUC__ // not clang (gcc comes later since clang emulates gcc) 195 | #if defined(__GXX_EXPERIMENTAL_CXX0X__) || (__cplusplus >= 201103L) 196 | #define JSON_HAS_RVALUE_REFERENCES 1 197 | #endif // GXX_EXPERIMENTAL 198 | 199 | #endif // __clang__ || __GNUC__ 200 | 201 | #endif // not defined JSON_HAS_RVALUE_REFERENCES 202 | 203 | #ifndef JSON_HAS_RVALUE_REFERENCES 204 | #define JSON_HAS_RVALUE_REFERENCES 0 205 | #endif 206 | 207 | #ifdef __clang__ 208 | # if __has_extension(attribute_deprecated_with_message) 209 | # define JSONCPP_DEPRECATED(message) __attribute__ ((deprecated(message))) 210 | # endif 211 | #elif defined __GNUC__ // not clang (gcc comes later since clang emulates gcc) 212 | # if (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5)) 213 | # define JSONCPP_DEPRECATED(message) __attribute__ ((deprecated(message))) 214 | # elif (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1)) 215 | # define JSONCPP_DEPRECATED(message) __attribute__((__deprecated__)) 216 | # endif // GNUC version 217 | #endif // __clang__ || __GNUC__ 218 | 219 | #if !defined(JSONCPP_DEPRECATED) 220 | #define JSONCPP_DEPRECATED(message) 221 | #endif // if !defined(JSONCPP_DEPRECATED) 222 | 223 | #if __GNUC__ >= 6 224 | # define JSON_USE_INT64_DOUBLE_CONVERSION 1 225 | #endif 226 | 227 | #if !defined(JSON_IS_AMALGAMATION) 228 | 229 | # include "version.h" 230 | 231 | # if JSONCPP_USING_SECURE_MEMORY 232 | # include "allocator.h" //typedef Allocator 233 | # endif 234 | 235 | #endif // if !defined(JSON_IS_AMALGAMATION) 236 | 237 | namespace Json { 238 | typedef int Int; 239 | typedef unsigned int UInt; 240 | #if defined(JSON_NO_INT64) 241 | typedef int LargestInt; 242 | typedef unsigned int LargestUInt; 243 | #undef JSON_HAS_INT64 244 | #else // if defined(JSON_NO_INT64) 245 | // For Microsoft Visual use specific types as long long is not supported 246 | #if defined(_MSC_VER) // Microsoft Visual Studio 247 | typedef __int64 Int64; 248 | typedef unsigned __int64 UInt64; 249 | #else // if defined(_MSC_VER) // Other platforms, use long long 250 | typedef int64_t Int64; 251 | typedef uint64_t UInt64; 252 | #endif // if defined(_MSC_VER) 253 | typedef Int64 LargestInt; 254 | typedef UInt64 LargestUInt; 255 | #define JSON_HAS_INT64 256 | #endif // if defined(JSON_NO_INT64) 257 | #if JSONCPP_USING_SECURE_MEMORY 258 | #define JSONCPP_STRING std::basic_string, Json::SecureAllocator > 259 | #define JSONCPP_OSTRINGSTREAM std::basic_ostringstream, Json::SecureAllocator > 260 | #define JSONCPP_OSTREAM std::basic_ostream> 261 | #define JSONCPP_ISTRINGSTREAM std::basic_istringstream, Json::SecureAllocator > 262 | #define JSONCPP_ISTREAM std::istream 263 | #else 264 | #define JSONCPP_STRING std::string 265 | #define JSONCPP_OSTRINGSTREAM std::ostringstream 266 | #define JSONCPP_OSTREAM std::ostream 267 | #define JSONCPP_ISTRINGSTREAM std::istringstream 268 | #define JSONCPP_ISTREAM std::istream 269 | #endif // if JSONCPP_USING_SECURE_MEMORY 270 | } // end namespace Json 271 | 272 | #endif // JSON_CONFIG_H_INCLUDED 273 | 274 | // ////////////////////////////////////////////////////////////////////// 275 | // End of content of file: include/json/config.h 276 | // ////////////////////////////////////////////////////////////////////// 277 | 278 | 279 | 280 | 281 | 282 | 283 | // ////////////////////////////////////////////////////////////////////// 284 | // Beginning of content of file: include/json/forwards.h 285 | // ////////////////////////////////////////////////////////////////////// 286 | 287 | // Copyright 2007-2010 Baptiste Lepilleur and The JsonCpp Authors 288 | // Distributed under MIT license, or public domain if desired and 289 | // recognized in your jurisdiction. 290 | // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE 291 | 292 | #ifndef JSON_FORWARDS_H_INCLUDED 293 | #define JSON_FORWARDS_H_INCLUDED 294 | 295 | #if !defined(JSON_IS_AMALGAMATION) 296 | #include "config.h" 297 | #endif // if !defined(JSON_IS_AMALGAMATION) 298 | 299 | namespace Json { 300 | 301 | // writer.h 302 | class FastWriter; 303 | class StyledWriter; 304 | 305 | // reader.h 306 | class Reader; 307 | 308 | // features.h 309 | class Features; 310 | 311 | // value.h 312 | typedef unsigned int ArrayIndex; 313 | class StaticString; 314 | class Path; 315 | class PathArgument; 316 | class Value; 317 | class ValueIteratorBase; 318 | class ValueIterator; 319 | class ValueConstIterator; 320 | 321 | } // namespace Json 322 | 323 | #endif // JSON_FORWARDS_H_INCLUDED 324 | 325 | // ////////////////////////////////////////////////////////////////////// 326 | // End of content of file: include/json/forwards.h 327 | // ////////////////////////////////////////////////////////////////////// 328 | 329 | 330 | 331 | 332 | 333 | #endif //ifndef JSON_FORWARD_AMALGAMATED_H_INCLUDED 334 | -------------------------------------------------------------------------------- /src/sat2json.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2019, Integrated Design and Engineering Analysis Laboratory (IDEA Lab) at Iowa State University. 3 | All rights reserved. 4 | 5 | Redistribution and use in source and binary forms, with or without 6 | modification, are permitted provided that the following conditions are met: 7 | * Redistributions of source code must retain the above copyright 8 | notice, this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above copyright 10 | notice, this list of conditions and the following disclaimer in the 11 | documentation and/or other materials provided with the distribution. 12 | * Neither the name of the copyright holder nor the 13 | names of its contributors may be used to endorse or promote products 14 | derived from this software without specific prior written permission. 15 | 16 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 17 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 18 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 19 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY 20 | DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 21 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 22 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 23 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 25 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | */ 27 | 28 | #include "common.h" 29 | #include "extract.h" 30 | 31 | 32 | // RWSAT executable 33 | int main(int argc, char **argv) 34 | { 35 | // Print app information 36 | std::cout << "SAT2JSON: Spline Geometry Extractor for ACIS" << std::endl; 37 | std::cout << "Copyright (c) 2019 IDEA Lab at Iowa State University." << std::endl; 38 | std::cout << "Licensed under the terms of BSD License.\n" << std::endl; 39 | 40 | // File name to read 41 | std::string filename; 42 | 43 | // Initialize configuration 44 | Config cfg; 45 | 46 | if (argc < 2 || argc > 3) 47 | { 48 | std::cout << "Usage: " << argv[0] << " FILENAME OPTIONS\n" << std::endl; 49 | std::cout << "Available options:" << std::endl; 50 | for (auto p : cfg.params) 51 | std::cout << " - " << p.first << ": " << p.second.second << std::endl; 52 | std::cout << "\nExample: " << argv[0] << " my_file.sat normalize=false;trims=true" << std::endl; 53 | #ifdef _MSC_VER 54 | std::cout << "Note: A license key should be provided using 'license_key' or 'license_file' arguments." << std::endl; 55 | #endif 56 | return EXIT_FAILURE; 57 | } 58 | else 59 | filename = std::string(argv[1]); 60 | 61 | // Update configuration 62 | if (argc == 3) 63 | parseConfig(argv[2], cfg); 64 | 65 | // Print configuration 66 | if (cfg.show_config()) 67 | { 68 | std::cout << "Using configuration:" << std::endl; 69 | for (auto p : cfg.params) 70 | std::cout << " - " << p.first << ": " << p.second.first << std::endl; 71 | } 72 | 73 | // Initialize a variable to store ACIS API outcome 74 | outcome res; 75 | 76 | // Start ACIS 77 | res = api_start_modeller(); 78 | checkOutcome(res, "api_start_modeller", __LINE__, cfg); 79 | 80 | // Unlock ACIS (required only on Windows) 81 | #ifdef _MSC_VER 82 | if (!unlockACIS(cfg)) 83 | return EXIT_FAILURE; 84 | #endif 85 | 86 | // Read the SAT file into an ENTITY_LIST 87 | ENTITY_LIST entities; 88 | if (!readSatFile(filename, entities, cfg)) 89 | { 90 | res = api_stop_modeller(); 91 | checkOutcome(res, "api_stop_modeller", __LINE__, cfg); 92 | return EXIT_FAILURE; 93 | } 94 | 95 | int ent_count = entities.iteration_count(); 96 | for (int i = 0; i < ent_count; i++) 97 | { 98 | // Get current body 99 | BODY *currentBody = (BODY *)entities[i]; 100 | 101 | // Workaround for periodic faces 102 | res = api_set_int_option("new_periodic_splitting", 1); 103 | checkOutcome(res, "api_set_int_option", __LINE__, cfg); 104 | res = api_split_periodic_faces(currentBody); 105 | checkOutcome(res, "api_split_periodic_faces", __LINE__, cfg); 106 | 107 | // Remove transformations 108 | if (!cfg.transform()) 109 | { 110 | res = api_remove_transf(currentBody); 111 | checkOutcome(res, "api_remove_transf", __LINE__, cfg); 112 | } 113 | 114 | // Create the root JSON object 115 | Json::Value root; 116 | 117 | // Create shape definition for JSON 118 | Json::Value shapeDef; 119 | shapeDef["type"] = "surface"; 120 | 121 | // Create data definition for JSON 122 | Json::Value dataDef; 123 | 124 | // Get the face list 125 | ENTITY_LIST face_list; 126 | res = api_get_faces(currentBody, face_list); 127 | checkOutcome(res, "api_get_faces", __LINE__, cfg); 128 | 129 | // Get face count 130 | int face_count = face_list.iteration_count(); 131 | 132 | // Face count is equal to the number of surfaces 133 | shapeDef["count"] = face_count; 134 | 135 | for (int j = 0; j < face_count; j++) 136 | { 137 | // Get the current face 138 | FACE *f = (FACE *)face_list[j]; 139 | 140 | // Get face sense 141 | logical faceSense = f->sense(); 142 | 143 | // Convert the underlying geometry to B-spline representation 144 | if (cfg.bspline()) 145 | { 146 | convert_to_spline_options convertOptions; 147 | convertOptions.set_do_edges(true); 148 | convertOptions.set_do_faces(true); 149 | convertOptions.set_in_place(true); 150 | res = api_convert_to_spline(f, &convertOptions); 151 | checkOutcome(res, "api_convert_to_spline", __LINE__, cfg); 152 | } 153 | 154 | /*** SURFACE EXTRACTION ***/ 155 | 156 | // Check if the face has a spline surface or skip the face 157 | SURFACE *faceSurf = f->geometry(); 158 | if (faceSurf->identity() != SPLINE_TYPE) 159 | { 160 | if (cfg.warnings()) 161 | std::cout << "[WARNING] Face #" << j << " of Body #" << i << " does not have a spline surface. Skipping..." << std::endl; 162 | continue; 163 | } 164 | 165 | // Extract the spline surface from the face 166 | bs3_surface bsurf; 167 | if (cfg.transform()) 168 | { 169 | surface *surf = f->geometry()->trans_surface(get_owner_transf(f), f->sense()); 170 | spline *spsurf = (spline *)surf; 171 | bsurf = spsurf->sur(); 172 | bs3_surface_trans(bsurf, get_owner_transf(f)); 173 | } 174 | else 175 | { 176 | const surface &surf = f->geometry()->equation(); 177 | const spline &spsurf = (spline &)surf; 178 | bsurf = spsurf.sur(); 179 | } 180 | 181 | // Check if ACIS was able to compute the B-spline representation 182 | if (bsurf == NULL) 183 | { 184 | if (cfg.warnings()) 185 | std::cout << "[WARNING] Cannot extract B-spline surface from Face #" << j << " of Body #" << i << ". Skipping..." << std::endl; 186 | continue; 187 | } 188 | 189 | // Get the parametric range of the initial surface 190 | SPAinterval u_range = bs3_surface_range_u(bsurf); 191 | SPAinterval v_range = bs3_surface_range_v(bsurf); 192 | 193 | // Length of the parametric dimensions 194 | double surf_param_len[2]; 195 | surf_param_len[0] = u_range.length(); 196 | surf_param_len[1] = v_range.length(); 197 | 198 | // Offset of the parametric dimensions (not to get negative parameters for trim curves) 199 | double surf_param_offset[2]; 200 | surf_param_offset[0] = u_range.start_pt(); 201 | surf_param_offset[1] = v_range.start_pt(); 202 | 203 | // Extract spline surface data 204 | Json::Value surfDef; 205 | surfDef["reversed"] = faceSense; 206 | extractSurfaceData(bsurf, cfg, surfDef); 207 | 208 | /*** TRIM CURVE EXTRACTION ***/ 209 | 210 | // Get the list of loops (face boundaries) 211 | ENTITY_LIST loop_list; 212 | res = api_get_loops(f, loop_list); 213 | checkOutcome(res, "api_get_loops", __LINE__, cfg); 214 | 215 | // Get number of loops 216 | int loop_count = loop_list.iteration_count(); 217 | 218 | if (cfg.trims()) 219 | { 220 | // Create a JSON object to store trim curve data 221 | Json::Value tDataDef; 222 | 223 | for (int lid = 0; lid < loop_count; lid++) 224 | { 225 | // Get the current loop 226 | LOOP *currLoop = (LOOP *)loop_list[lid]; 227 | 228 | // Get the coedges 229 | ENTITY_LIST coedge_list; 230 | res = api_get_coedges(currLoop, coedge_list); 231 | checkOutcome(res, "api_get_coedges", __LINE__, cfg); 232 | 233 | // Get the number of coedges 234 | int coedge_count = coedge_list.iteration_count(); 235 | 236 | // Detect loop type and skip if necessary 237 | loop_type currLoopType; 238 | res = api_loop_type(currLoop, currLoopType); 239 | checkOutcome(res, "api_loop_type", __LINE__, cfg); 240 | 241 | int trimSense = -1; 242 | switch (currLoopType) 243 | { 244 | case loop_type::loop_hole: // closed loop 245 | trimSense = 0; 246 | break; 247 | case loop_type::loop_periphery: // closed loop 248 | trimSense = 1; 249 | break; 250 | } 251 | 252 | // Store each coedge data in a list 253 | Json::Value tCurvesDataDef; 254 | 255 | // Loop through the trim curves 256 | for (int ce = 0; ce < coedge_count; ce++) 257 | { 258 | // Get the current coedge 259 | COEDGE *coedge = (COEDGE *)coedge_list[ce]; 260 | 261 | // Get coedge sense 262 | logical coedgeSense = coedge->sense(); 263 | 264 | // Extract the spline geometry from the parametric curve object 265 | bs2_curve bcurve2d; 266 | if (cfg.transform()) 267 | { 268 | pcurve* parametric_curve = coedge->geometry()->trans_pcurve(get_owner_transf(f), f->sense()); 269 | bcurve2d = parametric_curve->cur(); 270 | } 271 | else 272 | { 273 | pcurve parametric_curve = coedge->geometry()->equation(); 274 | bcurve2d = parametric_curve.cur(); 275 | } 276 | 277 | // Extract trim curve data to the JSON object 278 | Json::Value curveDef; 279 | curveDef["reversed"] = coedgeSense; 280 | extractTrimCurveData(bcurve2d, cfg, surf_param_offset, surf_param_len, curveDef); 281 | 282 | // Add trim curve to the parent JSON object 283 | tCurvesDataDef[ce] = curveDef; 284 | } 285 | 286 | // Store each loop data in a list 287 | Json::Value tDataDataDef; 288 | tDataDataDef["type"] = "container"; 289 | tDataDataDef["data"] = tCurvesDataDef; 290 | tDataDataDef["loop_type"] = currLoopType; 291 | if (trimSense >= 0 && cfg.trims()) 292 | tDataDataDef["reversed"] = trimSense; 293 | tDataDef[lid] = tDataDataDef; 294 | } 295 | 296 | // Create a JSON object for trim curves 297 | Json::Value surfTrimDef; 298 | 299 | // Add trim curves to the parent JSON object 300 | surfTrimDef["count"] = loop_count; 301 | surfTrimDef["data"] = tDataDef; 302 | 303 | // Add trim data to the parent surface JSON object 304 | surfDef["trims"] = surfTrimDef; 305 | } 306 | 307 | // Add ID field to surface 308 | surfDef["id"] = j + (ent_count * i); 309 | 310 | // Add surface to the data array 311 | dataDef[j] = surfDef; 312 | } 313 | 314 | // Update root JSON object 315 | shapeDef["data"] = dataDef; 316 | root["shape"] = shapeDef; 317 | 318 | // Try to open JSON file for writing 319 | std::string fnameSave = filename.substr(0, filename.find_last_of(".")) + ((ent_count > 1) ? "." + std::to_string(i) : "") + ".json"; 320 | std::ofstream fileSave(fnameSave.c_str(), std::ios::out); 321 | if (!fileSave) 322 | { 323 | std::cerr << "[ERROR] Cannot open file '" << fnameSave << "' for writing!" << std::endl; 324 | return EXIT_FAILURE; 325 | } 326 | else 327 | { 328 | // Convert JSON data structure into a string 329 | Json::StreamWriterBuilder wbuilder; 330 | wbuilder["indentation"] = "\t"; 331 | std::string jsonDocument = Json::writeString(wbuilder, root); 332 | 333 | // Write JSON string to a file 334 | fileSave << jsonDocument << std::endl; 335 | fileSave.close(); 336 | 337 | // Print success message 338 | std::cout << "[SUCCESS] Data was extracted to file '" << fnameSave << "' successfully" << std::endl; 339 | } 340 | } 341 | 342 | // Stop ACIS 343 | res = api_stop_modeller(); 344 | checkOutcome(res, "api_stop_modeller", __LINE__, cfg); 345 | 346 | // Exit successfully 347 | return EXIT_SUCCESS; 348 | } 349 | -------------------------------------------------------------------------------- /3rdparty/jsoncpp/json/json.h: -------------------------------------------------------------------------------- 1 | /// Json-cpp amalgamated header (http://jsoncpp.sourceforge.net/). 2 | /// It is intended to be used with #include "json/json.h" 3 | 4 | // ////////////////////////////////////////////////////////////////////// 5 | // Beginning of content of file: LICENSE 6 | // ////////////////////////////////////////////////////////////////////// 7 | 8 | /* 9 | The JsonCpp library's source code, including accompanying documentation, 10 | tests and demonstration applications, are licensed under the following 11 | conditions... 12 | 13 | Baptiste Lepilleur and The JsonCpp Authors explicitly disclaim copyright in all 14 | jurisdictions which recognize such a disclaimer. In such jurisdictions, 15 | this software is released into the Public Domain. 16 | 17 | In jurisdictions which do not recognize Public Domain property (e.g. Germany as of 18 | 2010), this software is Copyright (c) 2007-2010 by Baptiste Lepilleur and 19 | The JsonCpp Authors, and is released under the terms of the MIT License (see below). 20 | 21 | In jurisdictions which recognize Public Domain property, the user of this 22 | software may choose to accept it either as 1) Public Domain, 2) under the 23 | conditions of the MIT License (see below), or 3) under the terms of dual 24 | Public Domain/MIT License conditions described here, as they choose. 25 | 26 | The MIT License is about as close to Public Domain as a license can get, and is 27 | described in clear, concise terms at: 28 | 29 | http://en.wikipedia.org/wiki/MIT_License 30 | 31 | The full text of the MIT License follows: 32 | 33 | ======================================================================== 34 | Copyright (c) 2007-2010 Baptiste Lepilleur and The JsonCpp Authors 35 | 36 | Permission is hereby granted, free of charge, to any person 37 | obtaining a copy of this software and associated documentation 38 | files (the "Software"), to deal in the Software without 39 | restriction, including without limitation the rights to use, copy, 40 | modify, merge, publish, distribute, sublicense, and/or sell copies 41 | of the Software, and to permit persons to whom the Software is 42 | furnished to do so, subject to the following conditions: 43 | 44 | The above copyright notice and this permission notice shall be 45 | included in all copies or substantial portions of the Software. 46 | 47 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 48 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 49 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 50 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS 51 | BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN 52 | ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 53 | CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 54 | SOFTWARE. 55 | ======================================================================== 56 | (END LICENSE TEXT) 57 | 58 | The MIT license is compatible with both the GPL and commercial 59 | software, affording one all of the rights of Public Domain with the 60 | minor nuisance of being required to keep the above copyright notice 61 | and license text in the source code. Note also that by accepting the 62 | Public Domain "license" you can re-license your copy using whatever 63 | license you like. 64 | 65 | */ 66 | 67 | // ////////////////////////////////////////////////////////////////////// 68 | // End of content of file: LICENSE 69 | // ////////////////////////////////////////////////////////////////////// 70 | 71 | 72 | 73 | 74 | 75 | #ifndef JSON_AMALGAMATED_H_INCLUDED 76 | # define JSON_AMALGAMATED_H_INCLUDED 77 | /// If defined, indicates that the source file is amalgamated 78 | /// to prevent private header inclusion. 79 | #define JSON_IS_AMALGAMATION 80 | 81 | // ////////////////////////////////////////////////////////////////////// 82 | // Beginning of content of file: include/json/version.h 83 | // ////////////////////////////////////////////////////////////////////// 84 | 85 | // DO NOT EDIT. This file (and "version") is generated by CMake. 86 | // Run CMake configure step to update it. 87 | #ifndef JSON_VERSION_H_INCLUDED 88 | # define JSON_VERSION_H_INCLUDED 89 | 90 | # define JSONCPP_VERSION_STRING "1.8.4" 91 | # define JSONCPP_VERSION_MAJOR 1 92 | # define JSONCPP_VERSION_MINOR 8 93 | # define JSONCPP_VERSION_PATCH 4 94 | # define JSONCPP_VERSION_QUALIFIER 95 | # define JSONCPP_VERSION_HEXA ((JSONCPP_VERSION_MAJOR << 24) | (JSONCPP_VERSION_MINOR << 16) | (JSONCPP_VERSION_PATCH << 8)) 96 | 97 | #ifdef JSONCPP_USING_SECURE_MEMORY 98 | #undef JSONCPP_USING_SECURE_MEMORY 99 | #endif 100 | #define JSONCPP_USING_SECURE_MEMORY 0 101 | // If non-zero, the library zeroes any memory that it has allocated before 102 | // it frees its memory. 103 | 104 | #endif // JSON_VERSION_H_INCLUDED 105 | 106 | // ////////////////////////////////////////////////////////////////////// 107 | // End of content of file: include/json/version.h 108 | // ////////////////////////////////////////////////////////////////////// 109 | 110 | 111 | 112 | 113 | 114 | 115 | // ////////////////////////////////////////////////////////////////////// 116 | // Beginning of content of file: include/json/config.h 117 | // ////////////////////////////////////////////////////////////////////// 118 | 119 | // Copyright 2007-2010 Baptiste Lepilleur and The JsonCpp Authors 120 | // Distributed under MIT license, or public domain if desired and 121 | // recognized in your jurisdiction. 122 | // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE 123 | 124 | #ifndef JSON_CONFIG_H_INCLUDED 125 | #define JSON_CONFIG_H_INCLUDED 126 | #include 127 | #include //typedef String 128 | #include //typedef int64_t, uint64_t 129 | 130 | /// If defined, indicates that json library is embedded in CppTL library. 131 | //# define JSON_IN_CPPTL 1 132 | 133 | /// If defined, indicates that json may leverage CppTL library 134 | //# define JSON_USE_CPPTL 1 135 | /// If defined, indicates that cpptl vector based map should be used instead of 136 | /// std::map 137 | /// as Value container. 138 | //# define JSON_USE_CPPTL_SMALLMAP 1 139 | 140 | // If non-zero, the library uses exceptions to report bad input instead of C 141 | // assertion macros. The default is to use exceptions. 142 | #ifndef JSON_USE_EXCEPTION 143 | #define JSON_USE_EXCEPTION 1 144 | #endif 145 | 146 | /// If defined, indicates that the source file is amalgamated 147 | /// to prevent private header inclusion. 148 | /// Remarks: it is automatically defined in the generated amalgamated header. 149 | // #define JSON_IS_AMALGAMATION 150 | 151 | #ifdef JSON_IN_CPPTL 152 | #include 153 | #ifndef JSON_USE_CPPTL 154 | #define JSON_USE_CPPTL 1 155 | #endif 156 | #endif 157 | 158 | #ifdef JSON_IN_CPPTL 159 | #define JSON_API CPPTL_API 160 | #elif defined(JSON_DLL_BUILD) 161 | #if defined(_MSC_VER) || defined(__MINGW32__) 162 | #define JSON_API __declspec(dllexport) 163 | #define JSONCPP_DISABLE_DLL_INTERFACE_WARNING 164 | #endif // if defined(_MSC_VER) 165 | #elif defined(JSON_DLL) 166 | #if defined(_MSC_VER) || defined(__MINGW32__) 167 | #define JSON_API __declspec(dllimport) 168 | #define JSONCPP_DISABLE_DLL_INTERFACE_WARNING 169 | #endif // if defined(_MSC_VER) 170 | #endif // ifdef JSON_IN_CPPTL 171 | #if !defined(JSON_API) 172 | #define JSON_API 173 | #endif 174 | 175 | // If JSON_NO_INT64 is defined, then Json only support C++ "int" type for 176 | // integer 177 | // Storages, and 64 bits integer support is disabled. 178 | // #define JSON_NO_INT64 1 179 | 180 | #if defined(_MSC_VER) // MSVC 181 | # if _MSC_VER <= 1200 // MSVC 6 182 | // Microsoft Visual Studio 6 only support conversion from __int64 to double 183 | // (no conversion from unsigned __int64). 184 | # define JSON_USE_INT64_DOUBLE_CONVERSION 1 185 | // Disable warning 4786 for VS6 caused by STL (identifier was truncated to '255' 186 | // characters in the debug information) 187 | // All projects I've ever seen with VS6 were using this globally (not bothering 188 | // with pragma push/pop). 189 | # pragma warning(disable : 4786) 190 | # endif // MSVC 6 191 | 192 | # if _MSC_VER >= 1500 // MSVC 2008 193 | /// Indicates that the following function is deprecated. 194 | # define JSONCPP_DEPRECATED(message) __declspec(deprecated(message)) 195 | # endif 196 | 197 | #endif // defined(_MSC_VER) 198 | 199 | // In c++11 the override keyword allows you to explicitly define that a function 200 | // is intended to override the base-class version. This makes the code more 201 | // managable and fixes a set of common hard-to-find bugs. 202 | #if __cplusplus >= 201103L 203 | # define JSONCPP_OVERRIDE override 204 | # define JSONCPP_NOEXCEPT noexcept 205 | #elif defined(_MSC_VER) && _MSC_VER > 1600 && _MSC_VER < 1900 206 | # define JSONCPP_OVERRIDE override 207 | # define JSONCPP_NOEXCEPT throw() 208 | #elif defined(_MSC_VER) && _MSC_VER >= 1900 209 | # define JSONCPP_OVERRIDE override 210 | # define JSONCPP_NOEXCEPT noexcept 211 | #else 212 | # define JSONCPP_OVERRIDE 213 | # define JSONCPP_NOEXCEPT throw() 214 | #endif 215 | 216 | #ifndef JSON_HAS_RVALUE_REFERENCES 217 | 218 | #if defined(_MSC_VER) && _MSC_VER >= 1600 // MSVC >= 2010 219 | #define JSON_HAS_RVALUE_REFERENCES 1 220 | #endif // MSVC >= 2010 221 | 222 | #ifdef __clang__ 223 | #if __has_feature(cxx_rvalue_references) 224 | #define JSON_HAS_RVALUE_REFERENCES 1 225 | #endif // has_feature 226 | 227 | #elif defined __GNUC__ // not clang (gcc comes later since clang emulates gcc) 228 | #if defined(__GXX_EXPERIMENTAL_CXX0X__) || (__cplusplus >= 201103L) 229 | #define JSON_HAS_RVALUE_REFERENCES 1 230 | #endif // GXX_EXPERIMENTAL 231 | 232 | #endif // __clang__ || __GNUC__ 233 | 234 | #endif // not defined JSON_HAS_RVALUE_REFERENCES 235 | 236 | #ifndef JSON_HAS_RVALUE_REFERENCES 237 | #define JSON_HAS_RVALUE_REFERENCES 0 238 | #endif 239 | 240 | #ifdef __clang__ 241 | # if __has_extension(attribute_deprecated_with_message) 242 | # define JSONCPP_DEPRECATED(message) __attribute__ ((deprecated(message))) 243 | # endif 244 | #elif defined __GNUC__ // not clang (gcc comes later since clang emulates gcc) 245 | # if (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5)) 246 | # define JSONCPP_DEPRECATED(message) __attribute__ ((deprecated(message))) 247 | # elif (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1)) 248 | # define JSONCPP_DEPRECATED(message) __attribute__((__deprecated__)) 249 | # endif // GNUC version 250 | #endif // __clang__ || __GNUC__ 251 | 252 | #if !defined(JSONCPP_DEPRECATED) 253 | #define JSONCPP_DEPRECATED(message) 254 | #endif // if !defined(JSONCPP_DEPRECATED) 255 | 256 | #if __GNUC__ >= 6 257 | # define JSON_USE_INT64_DOUBLE_CONVERSION 1 258 | #endif 259 | 260 | #if !defined(JSON_IS_AMALGAMATION) 261 | 262 | # include "version.h" 263 | 264 | # if JSONCPP_USING_SECURE_MEMORY 265 | # include "allocator.h" //typedef Allocator 266 | # endif 267 | 268 | #endif // if !defined(JSON_IS_AMALGAMATION) 269 | 270 | namespace Json { 271 | typedef int Int; 272 | typedef unsigned int UInt; 273 | #if defined(JSON_NO_INT64) 274 | typedef int LargestInt; 275 | typedef unsigned int LargestUInt; 276 | #undef JSON_HAS_INT64 277 | #else // if defined(JSON_NO_INT64) 278 | // For Microsoft Visual use specific types as long long is not supported 279 | #if defined(_MSC_VER) // Microsoft Visual Studio 280 | typedef __int64 Int64; 281 | typedef unsigned __int64 UInt64; 282 | #else // if defined(_MSC_VER) // Other platforms, use long long 283 | typedef int64_t Int64; 284 | typedef uint64_t UInt64; 285 | #endif // if defined(_MSC_VER) 286 | typedef Int64 LargestInt; 287 | typedef UInt64 LargestUInt; 288 | #define JSON_HAS_INT64 289 | #endif // if defined(JSON_NO_INT64) 290 | #if JSONCPP_USING_SECURE_MEMORY 291 | #define JSONCPP_STRING std::basic_string, Json::SecureAllocator > 292 | #define JSONCPP_OSTRINGSTREAM std::basic_ostringstream, Json::SecureAllocator > 293 | #define JSONCPP_OSTREAM std::basic_ostream> 294 | #define JSONCPP_ISTRINGSTREAM std::basic_istringstream, Json::SecureAllocator > 295 | #define JSONCPP_ISTREAM std::istream 296 | #else 297 | #define JSONCPP_STRING std::string 298 | #define JSONCPP_OSTRINGSTREAM std::ostringstream 299 | #define JSONCPP_OSTREAM std::ostream 300 | #define JSONCPP_ISTRINGSTREAM std::istringstream 301 | #define JSONCPP_ISTREAM std::istream 302 | #endif // if JSONCPP_USING_SECURE_MEMORY 303 | } // end namespace Json 304 | 305 | #endif // JSON_CONFIG_H_INCLUDED 306 | 307 | // ////////////////////////////////////////////////////////////////////// 308 | // End of content of file: include/json/config.h 309 | // ////////////////////////////////////////////////////////////////////// 310 | 311 | 312 | 313 | 314 | 315 | 316 | // ////////////////////////////////////////////////////////////////////// 317 | // Beginning of content of file: include/json/forwards.h 318 | // ////////////////////////////////////////////////////////////////////// 319 | 320 | // Copyright 2007-2010 Baptiste Lepilleur and The JsonCpp Authors 321 | // Distributed under MIT license, or public domain if desired and 322 | // recognized in your jurisdiction. 323 | // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE 324 | 325 | #ifndef JSON_FORWARDS_H_INCLUDED 326 | #define JSON_FORWARDS_H_INCLUDED 327 | 328 | #if !defined(JSON_IS_AMALGAMATION) 329 | #include "config.h" 330 | #endif // if !defined(JSON_IS_AMALGAMATION) 331 | 332 | namespace Json { 333 | 334 | // writer.h 335 | class FastWriter; 336 | class StyledWriter; 337 | 338 | // reader.h 339 | class Reader; 340 | 341 | // features.h 342 | class Features; 343 | 344 | // value.h 345 | typedef unsigned int ArrayIndex; 346 | class StaticString; 347 | class Path; 348 | class PathArgument; 349 | class Value; 350 | class ValueIteratorBase; 351 | class ValueIterator; 352 | class ValueConstIterator; 353 | 354 | } // namespace Json 355 | 356 | #endif // JSON_FORWARDS_H_INCLUDED 357 | 358 | // ////////////////////////////////////////////////////////////////////// 359 | // End of content of file: include/json/forwards.h 360 | // ////////////////////////////////////////////////////////////////////// 361 | 362 | 363 | 364 | 365 | 366 | 367 | // ////////////////////////////////////////////////////////////////////// 368 | // Beginning of content of file: include/json/features.h 369 | // ////////////////////////////////////////////////////////////////////// 370 | 371 | // Copyright 2007-2010 Baptiste Lepilleur and The JsonCpp Authors 372 | // Distributed under MIT license, or public domain if desired and 373 | // recognized in your jurisdiction. 374 | // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE 375 | 376 | #ifndef CPPTL_JSON_FEATURES_H_INCLUDED 377 | #define CPPTL_JSON_FEATURES_H_INCLUDED 378 | 379 | #if !defined(JSON_IS_AMALGAMATION) 380 | #include "forwards.h" 381 | #endif // if !defined(JSON_IS_AMALGAMATION) 382 | 383 | #pragma pack(push, 8) 384 | 385 | namespace Json { 386 | 387 | /** \brief Configuration passed to reader and writer. 388 | * This configuration object can be used to force the Reader or Writer 389 | * to behave in a standard conforming way. 390 | */ 391 | class JSON_API Features { 392 | public: 393 | /** \brief A configuration that allows all features and assumes all strings 394 | * are UTF-8. 395 | * - C & C++ comments are allowed 396 | * - Root object can be any JSON value 397 | * - Assumes Value strings are encoded in UTF-8 398 | */ 399 | static Features all(); 400 | 401 | /** \brief A configuration that is strictly compatible with the JSON 402 | * specification. 403 | * - Comments are forbidden. 404 | * - Root object must be either an array or an object value. 405 | * - Assumes Value strings are encoded in UTF-8 406 | */ 407 | static Features strictMode(); 408 | 409 | /** \brief Initialize the configuration like JsonConfig::allFeatures; 410 | */ 411 | Features(); 412 | 413 | /// \c true if comments are allowed. Default: \c true. 414 | bool allowComments_; 415 | 416 | /// \c true if root must be either an array or an object value. Default: \c 417 | /// false. 418 | bool strictRoot_; 419 | 420 | /// \c true if dropped null placeholders are allowed. Default: \c false. 421 | bool allowDroppedNullPlaceholders_; 422 | 423 | /// \c true if numeric object key are allowed. Default: \c false. 424 | bool allowNumericKeys_; 425 | }; 426 | 427 | } // namespace Json 428 | 429 | #pragma pack(pop) 430 | 431 | #endif // CPPTL_JSON_FEATURES_H_INCLUDED 432 | 433 | // ////////////////////////////////////////////////////////////////////// 434 | // End of content of file: include/json/features.h 435 | // ////////////////////////////////////////////////////////////////////// 436 | 437 | 438 | 439 | 440 | 441 | 442 | // ////////////////////////////////////////////////////////////////////// 443 | // Beginning of content of file: include/json/value.h 444 | // ////////////////////////////////////////////////////////////////////// 445 | 446 | // Copyright 2007-2010 Baptiste Lepilleur and The JsonCpp Authors 447 | // Distributed under MIT license, or public domain if desired and 448 | // recognized in your jurisdiction. 449 | // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE 450 | 451 | #ifndef CPPTL_JSON_H_INCLUDED 452 | #define CPPTL_JSON_H_INCLUDED 453 | 454 | #if !defined(JSON_IS_AMALGAMATION) 455 | #include "forwards.h" 456 | #endif // if !defined(JSON_IS_AMALGAMATION) 457 | #include 458 | #include 459 | #include 460 | 461 | #ifndef JSON_USE_CPPTL_SMALLMAP 462 | #include 463 | #else 464 | #include 465 | #endif 466 | #ifdef JSON_USE_CPPTL 467 | #include 468 | #endif 469 | 470 | //Conditional NORETURN attribute on the throw functions would: 471 | // a) suppress false positives from static code analysis 472 | // b) possibly improve optimization opportunities. 473 | #if !defined(JSONCPP_NORETURN) 474 | # if defined(_MSC_VER) 475 | # define JSONCPP_NORETURN __declspec(noreturn) 476 | # elif defined(__GNUC__) 477 | # define JSONCPP_NORETURN __attribute__ ((__noreturn__)) 478 | # else 479 | # define JSONCPP_NORETURN 480 | # endif 481 | #endif 482 | 483 | // Disable warning C4251: : needs to have dll-interface to 484 | // be used by... 485 | #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) 486 | #pragma warning(push) 487 | #pragma warning(disable : 4251) 488 | #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) 489 | 490 | #pragma pack(push, 8) 491 | 492 | /** \brief JSON (JavaScript Object Notation). 493 | */ 494 | namespace Json { 495 | 496 | /** Base class for all exceptions we throw. 497 | * 498 | * We use nothing but these internally. Of course, STL can throw others. 499 | */ 500 | class JSON_API Exception : public std::exception { 501 | public: 502 | Exception(JSONCPP_STRING const& msg); 503 | ~Exception() JSONCPP_NOEXCEPT JSONCPP_OVERRIDE; 504 | char const* what() const JSONCPP_NOEXCEPT JSONCPP_OVERRIDE; 505 | protected: 506 | JSONCPP_STRING msg_; 507 | }; 508 | 509 | /** Exceptions which the user cannot easily avoid. 510 | * 511 | * E.g. out-of-memory (when we use malloc), stack-overflow, malicious input 512 | * 513 | * \remark derived from Json::Exception 514 | */ 515 | class JSON_API RuntimeError : public Exception { 516 | public: 517 | RuntimeError(JSONCPP_STRING const& msg); 518 | }; 519 | 520 | /** Exceptions thrown by JSON_ASSERT/JSON_FAIL macros. 521 | * 522 | * These are precondition-violations (user bugs) and internal errors (our bugs). 523 | * 524 | * \remark derived from Json::Exception 525 | */ 526 | class JSON_API LogicError : public Exception { 527 | public: 528 | LogicError(JSONCPP_STRING const& msg); 529 | }; 530 | 531 | /// used internally 532 | JSONCPP_NORETURN void throwRuntimeError(JSONCPP_STRING const& msg); 533 | /// used internally 534 | JSONCPP_NORETURN void throwLogicError(JSONCPP_STRING const& msg); 535 | 536 | /** \brief Type of the value held by a Value object. 537 | */ 538 | enum ValueType { 539 | nullValue = 0, ///< 'null' value 540 | intValue, ///< signed integer value 541 | uintValue, ///< unsigned integer value 542 | realValue, ///< double value 543 | stringValue, ///< UTF-8 string value 544 | booleanValue, ///< bool value 545 | arrayValue, ///< array value (ordered list) 546 | objectValue ///< object value (collection of name/value pairs). 547 | }; 548 | 549 | enum CommentPlacement { 550 | commentBefore = 0, ///< a comment placed on the line before a value 551 | commentAfterOnSameLine, ///< a comment just after a value on the same line 552 | commentAfter, ///< a comment on the line after a value (only make sense for 553 | /// root value) 554 | numberOfCommentPlacement 555 | }; 556 | 557 | //# ifdef JSON_USE_CPPTL 558 | // typedef CppTL::AnyEnumerator EnumMemberNames; 559 | // typedef CppTL::AnyEnumerator EnumValues; 560 | //# endif 561 | 562 | /** \brief Lightweight wrapper to tag static string. 563 | * 564 | * Value constructor and objectValue member assignment takes advantage of the 565 | * StaticString and avoid the cost of string duplication when storing the 566 | * string or the member name. 567 | * 568 | * Example of usage: 569 | * \code 570 | * Json::Value aValue( StaticString("some text") ); 571 | * Json::Value object; 572 | * static const StaticString code("code"); 573 | * object[code] = 1234; 574 | * \endcode 575 | */ 576 | class JSON_API StaticString { 577 | public: 578 | explicit StaticString(const char* czstring) : c_str_(czstring) {} 579 | 580 | operator const char*() const { return c_str_; } 581 | 582 | const char* c_str() const { return c_str_; } 583 | 584 | private: 585 | const char* c_str_; 586 | }; 587 | 588 | /** \brief Represents a JSON value. 589 | * 590 | * This class is a discriminated union wrapper that can represents a: 591 | * - signed integer [range: Value::minInt - Value::maxInt] 592 | * - unsigned integer (range: 0 - Value::maxUInt) 593 | * - double 594 | * - UTF-8 string 595 | * - boolean 596 | * - 'null' 597 | * - an ordered list of Value 598 | * - collection of name/value pairs (javascript object) 599 | * 600 | * The type of the held value is represented by a #ValueType and 601 | * can be obtained using type(). 602 | * 603 | * Values of an #objectValue or #arrayValue can be accessed using operator[]() 604 | * methods. 605 | * Non-const methods will automatically create the a #nullValue element 606 | * if it does not exist. 607 | * The sequence of an #arrayValue will be automatically resized and initialized 608 | * with #nullValue. resize() can be used to enlarge or truncate an #arrayValue. 609 | * 610 | * The get() methods can be used to obtain default value in the case the 611 | * required element does not exist. 612 | * 613 | * It is possible to iterate over the list of a #objectValue values using 614 | * the getMemberNames() method. 615 | * 616 | * \note #Value string-length fit in size_t, but keys must be < 2^30. 617 | * (The reason is an implementation detail.) A #CharReader will raise an 618 | * exception if a bound is exceeded to avoid security holes in your app, 619 | * but the Value API does *not* check bounds. That is the responsibility 620 | * of the caller. 621 | */ 622 | class JSON_API Value { 623 | friend class ValueIteratorBase; 624 | public: 625 | typedef std::vector Members; 626 | typedef ValueIterator iterator; 627 | typedef ValueConstIterator const_iterator; 628 | typedef Json::UInt UInt; 629 | typedef Json::Int Int; 630 | #if defined(JSON_HAS_INT64) 631 | typedef Json::UInt64 UInt64; 632 | typedef Json::Int64 Int64; 633 | #endif // defined(JSON_HAS_INT64) 634 | typedef Json::LargestInt LargestInt; 635 | typedef Json::LargestUInt LargestUInt; 636 | typedef Json::ArrayIndex ArrayIndex; 637 | 638 | // Required for boost integration, e. g. BOOST_TEST 639 | typedef std::string value_type; 640 | 641 | static const Value& null; ///< We regret this reference to a global instance; prefer the simpler Value(). 642 | static const Value& nullRef; ///< just a kludge for binary-compatibility; same as null 643 | static Value const& nullSingleton(); ///< Prefer this to null or nullRef. 644 | 645 | /// Minimum signed integer value that can be stored in a Json::Value. 646 | static const LargestInt minLargestInt; 647 | /// Maximum signed integer value that can be stored in a Json::Value. 648 | static const LargestInt maxLargestInt; 649 | /// Maximum unsigned integer value that can be stored in a Json::Value. 650 | static const LargestUInt maxLargestUInt; 651 | 652 | /// Minimum signed int value that can be stored in a Json::Value. 653 | static const Int minInt; 654 | /// Maximum signed int value that can be stored in a Json::Value. 655 | static const Int maxInt; 656 | /// Maximum unsigned int value that can be stored in a Json::Value. 657 | static const UInt maxUInt; 658 | 659 | #if defined(JSON_HAS_INT64) 660 | /// Minimum signed 64 bits int value that can be stored in a Json::Value. 661 | static const Int64 minInt64; 662 | /// Maximum signed 64 bits int value that can be stored in a Json::Value. 663 | static const Int64 maxInt64; 664 | /// Maximum unsigned 64 bits int value that can be stored in a Json::Value. 665 | static const UInt64 maxUInt64; 666 | #endif // defined(JSON_HAS_INT64) 667 | 668 | private: 669 | #ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION 670 | class CZString { 671 | public: 672 | enum DuplicationPolicy { 673 | noDuplication = 0, 674 | duplicate, 675 | duplicateOnCopy 676 | }; 677 | CZString(ArrayIndex index); 678 | CZString(char const* str, unsigned length, DuplicationPolicy allocate); 679 | CZString(CZString const& other); 680 | #if JSON_HAS_RVALUE_REFERENCES 681 | CZString(CZString&& other); 682 | #endif 683 | ~CZString(); 684 | CZString& operator=(const CZString& other); 685 | 686 | #if JSON_HAS_RVALUE_REFERENCES 687 | CZString& operator=(CZString&& other); 688 | #endif 689 | 690 | bool operator<(CZString const& other) const; 691 | bool operator==(CZString const& other) const; 692 | ArrayIndex index() const; 693 | //const char* c_str() const; ///< \deprecated 694 | char const* data() const; 695 | unsigned length() const; 696 | bool isStaticString() const; 697 | 698 | private: 699 | void swap(CZString& other); 700 | 701 | struct StringStorage { 702 | unsigned policy_: 2; 703 | unsigned length_: 30; // 1GB max 704 | }; 705 | 706 | char const* cstr_; // actually, a prefixed string, unless policy is noDup 707 | union { 708 | ArrayIndex index_; 709 | StringStorage storage_; 710 | }; 711 | }; 712 | 713 | public: 714 | #ifndef JSON_USE_CPPTL_SMALLMAP 715 | typedef std::map ObjectValues; 716 | #else 717 | typedef CppTL::SmallMap ObjectValues; 718 | #endif // ifndef JSON_USE_CPPTL_SMALLMAP 719 | #endif // ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION 720 | 721 | public: 722 | /** \brief Create a default Value of the given type. 723 | 724 | This is a very useful constructor. 725 | To create an empty array, pass arrayValue. 726 | To create an empty object, pass objectValue. 727 | Another Value can then be set to this one by assignment. 728 | This is useful since clear() and resize() will not alter types. 729 | 730 | Examples: 731 | \code 732 | Json::Value null_value; // null 733 | Json::Value arr_value(Json::arrayValue); // [] 734 | Json::Value obj_value(Json::objectValue); // {} 735 | \endcode 736 | */ 737 | Value(ValueType type = nullValue); 738 | Value(Int value); 739 | Value(UInt value); 740 | #if defined(JSON_HAS_INT64) 741 | Value(Int64 value); 742 | Value(UInt64 value); 743 | #endif // if defined(JSON_HAS_INT64) 744 | Value(double value); 745 | Value(const char* value); ///< Copy til first 0. (NULL causes to seg-fault.) 746 | Value(const char* begin, const char* end); ///< Copy all, incl zeroes. 747 | /** \brief Constructs a value from a static string. 748 | 749 | * Like other value string constructor but do not duplicate the string for 750 | * internal storage. The given string must remain alive after the call to this 751 | * constructor. 752 | * \note This works only for null-terminated strings. (We cannot change the 753 | * size of this class, so we have nowhere to store the length, 754 | * which might be computed later for various operations.) 755 | * 756 | * Example of usage: 757 | * \code 758 | * static StaticString foo("some text"); 759 | * Json::Value aValue(foo); 760 | * \endcode 761 | */ 762 | Value(const StaticString& value); 763 | Value(const JSONCPP_STRING& value); ///< Copy data() til size(). Embedded zeroes too. 764 | #ifdef JSON_USE_CPPTL 765 | Value(const CppTL::ConstString& value); 766 | #endif 767 | Value(bool value); 768 | /// Deep copy. 769 | Value(const Value& other); 770 | #if JSON_HAS_RVALUE_REFERENCES 771 | /// Move constructor 772 | Value(Value&& other); 773 | #endif 774 | ~Value(); 775 | 776 | /// Deep copy, then swap(other). 777 | /// \note Over-write existing comments. To preserve comments, use #swapPayload(). 778 | Value& operator=(Value other); 779 | 780 | /// Swap everything. 781 | void swap(Value& other); 782 | /// Swap values but leave comments and source offsets in place. 783 | void swapPayload(Value& other); 784 | 785 | /// copy everything. 786 | void copy(const Value& other); 787 | /// copy values but leave comments and source offsets in place. 788 | void copyPayload(const Value& other); 789 | 790 | ValueType type() const; 791 | 792 | /// Compare payload only, not comments etc. 793 | bool operator<(const Value& other) const; 794 | bool operator<=(const Value& other) const; 795 | bool operator>=(const Value& other) const; 796 | bool operator>(const Value& other) const; 797 | bool operator==(const Value& other) const; 798 | bool operator!=(const Value& other) const; 799 | int compare(const Value& other) const; 800 | 801 | const char* asCString() const; ///< Embedded zeroes could cause you trouble! 802 | #if JSONCPP_USING_SECURE_MEMORY 803 | unsigned getCStringLength() const; //Allows you to understand the length of the CString 804 | #endif 805 | JSONCPP_STRING asString() const; ///< Embedded zeroes are possible. 806 | /** Get raw char* of string-value. 807 | * \return false if !string. (Seg-fault if str or end are NULL.) 808 | */ 809 | bool getString( 810 | char const** begin, char const** end) const; 811 | #ifdef JSON_USE_CPPTL 812 | CppTL::ConstString asConstString() const; 813 | #endif 814 | Int asInt() const; 815 | UInt asUInt() const; 816 | #if defined(JSON_HAS_INT64) 817 | Int64 asInt64() const; 818 | UInt64 asUInt64() const; 819 | #endif // if defined(JSON_HAS_INT64) 820 | LargestInt asLargestInt() const; 821 | LargestUInt asLargestUInt() const; 822 | float asFloat() const; 823 | double asDouble() const; 824 | bool asBool() const; 825 | 826 | bool isNull() const; 827 | bool isBool() const; 828 | bool isInt() const; 829 | bool isInt64() const; 830 | bool isUInt() const; 831 | bool isUInt64() const; 832 | bool isIntegral() const; 833 | bool isDouble() const; 834 | bool isNumeric() const; 835 | bool isString() const; 836 | bool isArray() const; 837 | bool isObject() const; 838 | 839 | bool isConvertibleTo(ValueType other) const; 840 | 841 | /// Number of values in array or object 842 | ArrayIndex size() const; 843 | 844 | /// \brief Return true if empty array, empty object, or null; 845 | /// otherwise, false. 846 | bool empty() const; 847 | 848 | /// Return !isNull() 849 | explicit operator bool() const; 850 | 851 | /// Remove all object members and array elements. 852 | /// \pre type() is arrayValue, objectValue, or nullValue 853 | /// \post type() is unchanged 854 | void clear(); 855 | 856 | /// Resize the array to size elements. 857 | /// New elements are initialized to null. 858 | /// May only be called on nullValue or arrayValue. 859 | /// \pre type() is arrayValue or nullValue 860 | /// \post type() is arrayValue 861 | void resize(ArrayIndex size); 862 | 863 | /// Access an array element (zero based index ). 864 | /// If the array contains less than index element, then null value are 865 | /// inserted 866 | /// in the array so that its size is index+1. 867 | /// (You may need to say 'value[0u]' to get your compiler to distinguish 868 | /// this from the operator[] which takes a string.) 869 | Value& operator[](ArrayIndex index); 870 | 871 | /// Access an array element (zero based index ). 872 | /// If the array contains less than index element, then null value are 873 | /// inserted 874 | /// in the array so that its size is index+1. 875 | /// (You may need to say 'value[0u]' to get your compiler to distinguish 876 | /// this from the operator[] which takes a string.) 877 | Value& operator[](int index); 878 | 879 | /// Access an array element (zero based index ) 880 | /// (You may need to say 'value[0u]' to get your compiler to distinguish 881 | /// this from the operator[] which takes a string.) 882 | const Value& operator[](ArrayIndex index) const; 883 | 884 | /// Access an array element (zero based index ) 885 | /// (You may need to say 'value[0u]' to get your compiler to distinguish 886 | /// this from the operator[] which takes a string.) 887 | const Value& operator[](int index) const; 888 | 889 | /// If the array contains at least index+1 elements, returns the element 890 | /// value, 891 | /// otherwise returns defaultValue. 892 | Value get(ArrayIndex index, const Value& defaultValue) const; 893 | /// Return true if index < size(). 894 | bool isValidIndex(ArrayIndex index) const; 895 | /// \brief Append value to array at the end. 896 | /// 897 | /// Equivalent to jsonvalue[jsonvalue.size()] = value; 898 | Value& append(const Value& value); 899 | 900 | #if JSON_HAS_RVALUE_REFERENCES 901 | Value& append(Value&& value); 902 | #endif 903 | 904 | /// Access an object value by name, create a null member if it does not exist. 905 | /// \note Because of our implementation, keys are limited to 2^30 -1 chars. 906 | /// Exceeding that will cause an exception. 907 | Value& operator[](const char* key); 908 | /// Access an object value by name, returns null if there is no member with 909 | /// that name. 910 | const Value& operator[](const char* key) const; 911 | /// Access an object value by name, create a null member if it does not exist. 912 | /// \param key may contain embedded nulls. 913 | Value& operator[](const JSONCPP_STRING& key); 914 | /// Access an object value by name, returns null if there is no member with 915 | /// that name. 916 | /// \param key may contain embedded nulls. 917 | const Value& operator[](const JSONCPP_STRING& key) const; 918 | /** \brief Access an object value by name, create a null member if it does not 919 | exist. 920 | 921 | * If the object has no entry for that name, then the member name used to store 922 | * the new entry is not duplicated. 923 | * Example of use: 924 | * \code 925 | * Json::Value object; 926 | * static const StaticString code("code"); 927 | * object[code] = 1234; 928 | * \endcode 929 | */ 930 | Value& operator[](const StaticString& key); 931 | #ifdef JSON_USE_CPPTL 932 | /// Access an object value by name, create a null member if it does not exist. 933 | Value& operator[](const CppTL::ConstString& key); 934 | /// Access an object value by name, returns null if there is no member with 935 | /// that name. 936 | const Value& operator[](const CppTL::ConstString& key) const; 937 | #endif 938 | /// Return the member named key if it exist, defaultValue otherwise. 939 | /// \note deep copy 940 | Value get(const char* key, const Value& defaultValue) const; 941 | /// Return the member named key if it exist, defaultValue otherwise. 942 | /// \note deep copy 943 | /// \note key may contain embedded nulls. 944 | Value get(const char* begin, const char* end, const Value& defaultValue) const; 945 | /// Return the member named key if it exist, defaultValue otherwise. 946 | /// \note deep copy 947 | /// \param key may contain embedded nulls. 948 | Value get(const JSONCPP_STRING& key, const Value& defaultValue) const; 949 | #ifdef JSON_USE_CPPTL 950 | /// Return the member named key if it exist, defaultValue otherwise. 951 | /// \note deep copy 952 | Value get(const CppTL::ConstString& key, const Value& defaultValue) const; 953 | #endif 954 | /// Most general and efficient version of isMember()const, get()const, 955 | /// and operator[]const 956 | /// \note As stated elsewhere, behavior is undefined if (end-begin) >= 2^30 957 | Value const* find(char const* begin, char const* end) const; 958 | /// Most general and efficient version of object-mutators. 959 | /// \note As stated elsewhere, behavior is undefined if (end-begin) >= 2^30 960 | /// \return non-zero, but JSON_ASSERT if this is neither object nor nullValue. 961 | Value const* demand(char const* begin, char const* end); 962 | /// \brief Remove and return the named member. 963 | /// 964 | /// Do nothing if it did not exist. 965 | /// \return the removed Value, or null. 966 | /// \pre type() is objectValue or nullValue 967 | /// \post type() is unchanged 968 | /// \deprecated 969 | void removeMember(const char* key); 970 | /// Same as removeMember(const char*) 971 | /// \param key may contain embedded nulls. 972 | /// \deprecated 973 | void removeMember(const JSONCPP_STRING& key); 974 | /// Same as removeMember(const char* begin, const char* end, Value* removed), 975 | /// but 'key' is null-terminated. 976 | bool removeMember(const char* key, Value* removed); 977 | /** \brief Remove the named map member. 978 | 979 | Update 'removed' iff removed. 980 | \param key may contain embedded nulls. 981 | \return true iff removed (no exceptions) 982 | */ 983 | bool removeMember(JSONCPP_STRING const& key, Value* removed); 984 | /// Same as removeMember(JSONCPP_STRING const& key, Value* removed) 985 | bool removeMember(const char* begin, const char* end, Value* removed); 986 | /** \brief Remove the indexed array element. 987 | 988 | O(n) expensive operations. 989 | Update 'removed' iff removed. 990 | \return true iff removed (no exceptions) 991 | */ 992 | bool removeIndex(ArrayIndex i, Value* removed); 993 | 994 | /// Return true if the object has a member named key. 995 | /// \note 'key' must be null-terminated. 996 | bool isMember(const char* key) const; 997 | /// Return true if the object has a member named key. 998 | /// \param key may contain embedded nulls. 999 | bool isMember(const JSONCPP_STRING& key) const; 1000 | /// Same as isMember(JSONCPP_STRING const& key)const 1001 | bool isMember(const char* begin, const char* end) const; 1002 | #ifdef JSON_USE_CPPTL 1003 | /// Return true if the object has a member named key. 1004 | bool isMember(const CppTL::ConstString& key) const; 1005 | #endif 1006 | 1007 | /// \brief Return a list of the member names. 1008 | /// 1009 | /// If null, return an empty list. 1010 | /// \pre type() is objectValue or nullValue 1011 | /// \post if type() was nullValue, it remains nullValue 1012 | Members getMemberNames() const; 1013 | 1014 | //# ifdef JSON_USE_CPPTL 1015 | // EnumMemberNames enumMemberNames() const; 1016 | // EnumValues enumValues() const; 1017 | //# endif 1018 | 1019 | /// \deprecated Always pass len. 1020 | JSONCPP_DEPRECATED("Use setComment(JSONCPP_STRING const&) instead.") 1021 | void setComment(const char* comment, CommentPlacement placement); 1022 | /// Comments must be //... or /* ... */ 1023 | void setComment(const char* comment, size_t len, CommentPlacement placement); 1024 | /// Comments must be //... or /* ... */ 1025 | void setComment(const JSONCPP_STRING& comment, CommentPlacement placement); 1026 | bool hasComment(CommentPlacement placement) const; 1027 | /// Include delimiters and embedded newlines. 1028 | JSONCPP_STRING getComment(CommentPlacement placement) const; 1029 | 1030 | JSONCPP_STRING toStyledString() const; 1031 | 1032 | const_iterator begin() const; 1033 | const_iterator end() const; 1034 | 1035 | iterator begin(); 1036 | iterator end(); 1037 | 1038 | // Accessors for the [start, limit) range of bytes within the JSON text from 1039 | // which this value was parsed, if any. 1040 | void setOffsetStart(ptrdiff_t start); 1041 | void setOffsetLimit(ptrdiff_t limit); 1042 | ptrdiff_t getOffsetStart() const; 1043 | ptrdiff_t getOffsetLimit() const; 1044 | 1045 | private: 1046 | void initBasic(ValueType type, bool allocated = false); 1047 | 1048 | Value& resolveReference(const char* key); 1049 | Value& resolveReference(const char* key, const char* end); 1050 | 1051 | struct CommentInfo { 1052 | CommentInfo(); 1053 | ~CommentInfo(); 1054 | 1055 | void setComment(const char* text, size_t len); 1056 | 1057 | char* comment_; 1058 | }; 1059 | 1060 | // struct MemberNamesTransform 1061 | //{ 1062 | // typedef const char *result_type; 1063 | // const char *operator()( const CZString &name ) const 1064 | // { 1065 | // return name.c_str(); 1066 | // } 1067 | //}; 1068 | 1069 | union ValueHolder { 1070 | LargestInt int_; 1071 | LargestUInt uint_; 1072 | double real_; 1073 | bool bool_; 1074 | char* string_; // actually ptr to unsigned, followed by str, unless !allocated_ 1075 | ObjectValues* map_; 1076 | } value_; 1077 | ValueType type_ : 8; 1078 | unsigned int allocated_ : 1; // Notes: if declared as bool, bitfield is useless. 1079 | // If not allocated_, string_ must be null-terminated. 1080 | CommentInfo* comments_; 1081 | 1082 | // [start, limit) byte offsets in the source JSON text from which this Value 1083 | // was extracted. 1084 | ptrdiff_t start_; 1085 | ptrdiff_t limit_; 1086 | }; 1087 | 1088 | /** \brief Experimental and untested: represents an element of the "path" to 1089 | * access a node. 1090 | */ 1091 | class JSON_API PathArgument { 1092 | public: 1093 | friend class Path; 1094 | 1095 | PathArgument(); 1096 | PathArgument(ArrayIndex index); 1097 | PathArgument(const char* key); 1098 | PathArgument(const JSONCPP_STRING& key); 1099 | 1100 | private: 1101 | enum Kind { 1102 | kindNone = 0, 1103 | kindIndex, 1104 | kindKey 1105 | }; 1106 | JSONCPP_STRING key_; 1107 | ArrayIndex index_; 1108 | Kind kind_; 1109 | }; 1110 | 1111 | /** \brief Experimental and untested: represents a "path" to access a node. 1112 | * 1113 | * Syntax: 1114 | * - "." => root node 1115 | * - ".[n]" => elements at index 'n' of root node (an array value) 1116 | * - ".name" => member named 'name' of root node (an object value) 1117 | * - ".name1.name2.name3" 1118 | * - ".[0][1][2].name1[3]" 1119 | * - ".%" => member name is provided as parameter 1120 | * - ".[%]" => index is provied as parameter 1121 | */ 1122 | class JSON_API Path { 1123 | public: 1124 | Path(const JSONCPP_STRING& path, 1125 | const PathArgument& a1 = PathArgument(), 1126 | const PathArgument& a2 = PathArgument(), 1127 | const PathArgument& a3 = PathArgument(), 1128 | const PathArgument& a4 = PathArgument(), 1129 | const PathArgument& a5 = PathArgument()); 1130 | 1131 | const Value& resolve(const Value& root) const; 1132 | Value resolve(const Value& root, const Value& defaultValue) const; 1133 | /// Creates the "path" to access the specified node and returns a reference on 1134 | /// the node. 1135 | Value& make(Value& root) const; 1136 | 1137 | private: 1138 | typedef std::vector InArgs; 1139 | typedef std::vector Args; 1140 | 1141 | void makePath(const JSONCPP_STRING& path, const InArgs& in); 1142 | void addPathInArg(const JSONCPP_STRING& path, 1143 | const InArgs& in, 1144 | InArgs::const_iterator& itInArg, 1145 | PathArgument::Kind kind); 1146 | void invalidPath(const JSONCPP_STRING& path, int location); 1147 | 1148 | Args args_; 1149 | }; 1150 | 1151 | /** \brief base class for Value iterators. 1152 | * 1153 | */ 1154 | class JSON_API ValueIteratorBase { 1155 | public: 1156 | typedef std::bidirectional_iterator_tag iterator_category; 1157 | typedef unsigned int size_t; 1158 | typedef int difference_type; 1159 | typedef ValueIteratorBase SelfType; 1160 | 1161 | bool operator==(const SelfType& other) const { return isEqual(other); } 1162 | 1163 | bool operator!=(const SelfType& other) const { return !isEqual(other); } 1164 | 1165 | difference_type operator-(const SelfType& other) const { 1166 | return other.computeDistance(*this); 1167 | } 1168 | 1169 | /// Return either the index or the member name of the referenced value as a 1170 | /// Value. 1171 | Value key() const; 1172 | 1173 | /// Return the index of the referenced Value, or -1 if it is not an arrayValue. 1174 | UInt index() const; 1175 | 1176 | /// Return the member name of the referenced Value, or "" if it is not an 1177 | /// objectValue. 1178 | /// \note Avoid `c_str()` on result, as embedded zeroes are possible. 1179 | JSONCPP_STRING name() const; 1180 | 1181 | /// Return the member name of the referenced Value. "" if it is not an 1182 | /// objectValue. 1183 | /// \deprecated This cannot be used for UTF-8 strings, since there can be embedded nulls. 1184 | JSONCPP_DEPRECATED("Use `key = name();` instead.") 1185 | char const* memberName() const; 1186 | /// Return the member name of the referenced Value, or NULL if it is not an 1187 | /// objectValue. 1188 | /// \note Better version than memberName(). Allows embedded nulls. 1189 | char const* memberName(char const** end) const; 1190 | 1191 | protected: 1192 | Value& deref() const; 1193 | 1194 | void increment(); 1195 | 1196 | void decrement(); 1197 | 1198 | difference_type computeDistance(const SelfType& other) const; 1199 | 1200 | bool isEqual(const SelfType& other) const; 1201 | 1202 | void copy(const SelfType& other); 1203 | 1204 | private: 1205 | Value::ObjectValues::iterator current_; 1206 | // Indicates that iterator is for a null value. 1207 | bool isNull_; 1208 | 1209 | public: 1210 | // For some reason, BORLAND needs these at the end, rather 1211 | // than earlier. No idea why. 1212 | ValueIteratorBase(); 1213 | explicit ValueIteratorBase(const Value::ObjectValues::iterator& current); 1214 | }; 1215 | 1216 | /** \brief const iterator for object and array value. 1217 | * 1218 | */ 1219 | class JSON_API ValueConstIterator : public ValueIteratorBase { 1220 | friend class Value; 1221 | 1222 | public: 1223 | typedef const Value value_type; 1224 | //typedef unsigned int size_t; 1225 | //typedef int difference_type; 1226 | typedef const Value& reference; 1227 | typedef const Value* pointer; 1228 | typedef ValueConstIterator SelfType; 1229 | 1230 | ValueConstIterator(); 1231 | ValueConstIterator(ValueIterator const& other); 1232 | 1233 | private: 1234 | /*! \internal Use by Value to create an iterator. 1235 | */ 1236 | explicit ValueConstIterator(const Value::ObjectValues::iterator& current); 1237 | public: 1238 | SelfType& operator=(const ValueIteratorBase& other); 1239 | 1240 | SelfType operator++(int) { 1241 | SelfType temp(*this); 1242 | ++*this; 1243 | return temp; 1244 | } 1245 | 1246 | SelfType operator--(int) { 1247 | SelfType temp(*this); 1248 | --*this; 1249 | return temp; 1250 | } 1251 | 1252 | SelfType& operator--() { 1253 | decrement(); 1254 | return *this; 1255 | } 1256 | 1257 | SelfType& operator++() { 1258 | increment(); 1259 | return *this; 1260 | } 1261 | 1262 | reference operator*() const { return deref(); } 1263 | 1264 | pointer operator->() const { return &deref(); } 1265 | }; 1266 | 1267 | /** \brief Iterator for object and array value. 1268 | */ 1269 | class JSON_API ValueIterator : public ValueIteratorBase { 1270 | friend class Value; 1271 | 1272 | public: 1273 | typedef Value value_type; 1274 | typedef unsigned int size_t; 1275 | typedef int difference_type; 1276 | typedef Value& reference; 1277 | typedef Value* pointer; 1278 | typedef ValueIterator SelfType; 1279 | 1280 | ValueIterator(); 1281 | explicit ValueIterator(const ValueConstIterator& other); 1282 | ValueIterator(const ValueIterator& other); 1283 | 1284 | private: 1285 | /*! \internal Use by Value to create an iterator. 1286 | */ 1287 | explicit ValueIterator(const Value::ObjectValues::iterator& current); 1288 | public: 1289 | SelfType& operator=(const SelfType& other); 1290 | 1291 | SelfType operator++(int) { 1292 | SelfType temp(*this); 1293 | ++*this; 1294 | return temp; 1295 | } 1296 | 1297 | SelfType operator--(int) { 1298 | SelfType temp(*this); 1299 | --*this; 1300 | return temp; 1301 | } 1302 | 1303 | SelfType& operator--() { 1304 | decrement(); 1305 | return *this; 1306 | } 1307 | 1308 | SelfType& operator++() { 1309 | increment(); 1310 | return *this; 1311 | } 1312 | 1313 | reference operator*() const { return deref(); } 1314 | 1315 | pointer operator->() const { return &deref(); } 1316 | }; 1317 | 1318 | } // namespace Json 1319 | 1320 | 1321 | namespace std { 1322 | /// Specialize std::swap() for Json::Value. 1323 | template<> 1324 | inline void swap(Json::Value& a, Json::Value& b) { a.swap(b); } 1325 | } 1326 | 1327 | #pragma pack(pop) 1328 | 1329 | #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) 1330 | #pragma warning(pop) 1331 | #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) 1332 | 1333 | #endif // CPPTL_JSON_H_INCLUDED 1334 | 1335 | // ////////////////////////////////////////////////////////////////////// 1336 | // End of content of file: include/json/value.h 1337 | // ////////////////////////////////////////////////////////////////////// 1338 | 1339 | 1340 | 1341 | 1342 | 1343 | 1344 | // ////////////////////////////////////////////////////////////////////// 1345 | // Beginning of content of file: include/json/reader.h 1346 | // ////////////////////////////////////////////////////////////////////// 1347 | 1348 | // Copyright 2007-2010 Baptiste Lepilleur and The JsonCpp Authors 1349 | // Distributed under MIT license, or public domain if desired and 1350 | // recognized in your jurisdiction. 1351 | // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE 1352 | 1353 | #ifndef CPPTL_JSON_READER_H_INCLUDED 1354 | #define CPPTL_JSON_READER_H_INCLUDED 1355 | 1356 | #if !defined(JSON_IS_AMALGAMATION) 1357 | #include "features.h" 1358 | #include "value.h" 1359 | #endif // if !defined(JSON_IS_AMALGAMATION) 1360 | #include 1361 | #include 1362 | #include 1363 | #include 1364 | #include 1365 | 1366 | // Disable warning C4251: : needs to have dll-interface to 1367 | // be used by... 1368 | #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) 1369 | #pragma warning(push) 1370 | #pragma warning(disable : 4251) 1371 | #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) 1372 | 1373 | #pragma pack(push, 8) 1374 | 1375 | namespace Json { 1376 | 1377 | /** \brief Unserialize a JSON document into a 1378 | *Value. 1379 | * 1380 | * \deprecated Use CharReader and CharReaderBuilder. 1381 | */ 1382 | class JSONCPP_DEPRECATED("Use CharReader and CharReaderBuilder instead") JSON_API Reader { 1383 | public: 1384 | typedef char Char; 1385 | typedef const Char* Location; 1386 | 1387 | /** \brief An error tagged with where in the JSON text it was encountered. 1388 | * 1389 | * The offsets give the [start, limit) range of bytes within the text. Note 1390 | * that this is bytes, not codepoints. 1391 | * 1392 | */ 1393 | struct StructuredError { 1394 | ptrdiff_t offset_start; 1395 | ptrdiff_t offset_limit; 1396 | JSONCPP_STRING message; 1397 | }; 1398 | 1399 | /** \brief Constructs a Reader allowing all features 1400 | * for parsing. 1401 | */ 1402 | Reader(); 1403 | 1404 | /** \brief Constructs a Reader allowing the specified feature set 1405 | * for parsing. 1406 | */ 1407 | Reader(const Features& features); 1408 | 1409 | /** \brief Read a Value from a JSON 1410 | * document. 1411 | * \param document UTF-8 encoded string containing the document to read. 1412 | * \param root [out] Contains the root value of the document if it was 1413 | * successfully parsed. 1414 | * \param collectComments \c true to collect comment and allow writing them 1415 | * back during 1416 | * serialization, \c false to discard comments. 1417 | * This parameter is ignored if 1418 | * Features::allowComments_ 1419 | * is \c false. 1420 | * \return \c true if the document was successfully parsed, \c false if an 1421 | * error occurred. 1422 | */ 1423 | bool 1424 | parse(const std::string& document, Value& root, bool collectComments = true); 1425 | 1426 | /** \brief Read a Value from a JSON 1427 | document. 1428 | * \param beginDoc Pointer on the beginning of the UTF-8 encoded string of the 1429 | document to read. 1430 | * \param endDoc Pointer on the end of the UTF-8 encoded string of the 1431 | document to read. 1432 | * Must be >= beginDoc. 1433 | * \param root [out] Contains the root value of the document if it was 1434 | * successfully parsed. 1435 | * \param collectComments \c true to collect comment and allow writing them 1436 | back during 1437 | * serialization, \c false to discard comments. 1438 | * This parameter is ignored if 1439 | Features::allowComments_ 1440 | * is \c false. 1441 | * \return \c true if the document was successfully parsed, \c false if an 1442 | error occurred. 1443 | */ 1444 | bool parse(const char* beginDoc, 1445 | const char* endDoc, 1446 | Value& root, 1447 | bool collectComments = true); 1448 | 1449 | /// \brief Parse from input stream. 1450 | /// \see Json::operator>>(std::istream&, Json::Value&). 1451 | bool parse(JSONCPP_ISTREAM& is, Value& root, bool collectComments = true); 1452 | 1453 | /** \brief Returns a user friendly string that list errors in the parsed 1454 | * document. 1455 | * \return Formatted error message with the list of errors with their location 1456 | * in 1457 | * the parsed document. An empty string is returned if no error 1458 | * occurred 1459 | * during parsing. 1460 | * \deprecated Use getFormattedErrorMessages() instead (typo fix). 1461 | */ 1462 | JSONCPP_DEPRECATED("Use getFormattedErrorMessages() instead.") 1463 | JSONCPP_STRING getFormatedErrorMessages() const; 1464 | 1465 | /** \brief Returns a user friendly string that list errors in the parsed 1466 | * document. 1467 | * \return Formatted error message with the list of errors with their location 1468 | * in 1469 | * the parsed document. An empty string is returned if no error 1470 | * occurred 1471 | * during parsing. 1472 | */ 1473 | JSONCPP_STRING getFormattedErrorMessages() const; 1474 | 1475 | /** \brief Returns a vector of structured erros encounted while parsing. 1476 | * \return A (possibly empty) vector of StructuredError objects. Currently 1477 | * only one error can be returned, but the caller should tolerate 1478 | * multiple 1479 | * errors. This can occur if the parser recovers from a non-fatal 1480 | * parse error and then encounters additional errors. 1481 | */ 1482 | std::vector getStructuredErrors() const; 1483 | 1484 | /** \brief Add a semantic error message. 1485 | * \param value JSON Value location associated with the error 1486 | * \param message The error message. 1487 | * \return \c true if the error was successfully added, \c false if the 1488 | * Value offset exceeds the document size. 1489 | */ 1490 | bool pushError(const Value& value, const JSONCPP_STRING& message); 1491 | 1492 | /** \brief Add a semantic error message with extra context. 1493 | * \param value JSON Value location associated with the error 1494 | * \param message The error message. 1495 | * \param extra Additional JSON Value location to contextualize the error 1496 | * \return \c true if the error was successfully added, \c false if either 1497 | * Value offset exceeds the document size. 1498 | */ 1499 | bool pushError(const Value& value, const JSONCPP_STRING& message, const Value& extra); 1500 | 1501 | /** \brief Return whether there are any errors. 1502 | * \return \c true if there are no errors to report \c false if 1503 | * errors have occurred. 1504 | */ 1505 | bool good() const; 1506 | 1507 | private: 1508 | enum TokenType { 1509 | tokenEndOfStream = 0, 1510 | tokenObjectBegin, 1511 | tokenObjectEnd, 1512 | tokenArrayBegin, 1513 | tokenArrayEnd, 1514 | tokenString, 1515 | tokenNumber, 1516 | tokenTrue, 1517 | tokenFalse, 1518 | tokenNull, 1519 | tokenArraySeparator, 1520 | tokenMemberSeparator, 1521 | tokenComment, 1522 | tokenError 1523 | }; 1524 | 1525 | class Token { 1526 | public: 1527 | TokenType type_; 1528 | Location start_; 1529 | Location end_; 1530 | }; 1531 | 1532 | class ErrorInfo { 1533 | public: 1534 | Token token_; 1535 | JSONCPP_STRING message_; 1536 | Location extra_; 1537 | }; 1538 | 1539 | typedef std::deque Errors; 1540 | 1541 | bool readToken(Token& token); 1542 | void skipSpaces(); 1543 | bool match(Location pattern, int patternLength); 1544 | bool readComment(); 1545 | bool readCStyleComment(); 1546 | bool readCppStyleComment(); 1547 | bool readString(); 1548 | void readNumber(); 1549 | bool readValue(); 1550 | bool readObject(Token& token); 1551 | bool readArray(Token& token); 1552 | bool decodeNumber(Token& token); 1553 | bool decodeNumber(Token& token, Value& decoded); 1554 | bool decodeString(Token& token); 1555 | bool decodeString(Token& token, JSONCPP_STRING& decoded); 1556 | bool decodeDouble(Token& token); 1557 | bool decodeDouble(Token& token, Value& decoded); 1558 | bool decodeUnicodeCodePoint(Token& token, 1559 | Location& current, 1560 | Location end, 1561 | unsigned int& unicode); 1562 | bool decodeUnicodeEscapeSequence(Token& token, 1563 | Location& current, 1564 | Location end, 1565 | unsigned int& unicode); 1566 | bool addError(const JSONCPP_STRING& message, Token& token, Location extra = 0); 1567 | bool recoverFromError(TokenType skipUntilToken); 1568 | bool addErrorAndRecover(const JSONCPP_STRING& message, 1569 | Token& token, 1570 | TokenType skipUntilToken); 1571 | void skipUntilSpace(); 1572 | Value& currentValue(); 1573 | Char getNextChar(); 1574 | void 1575 | getLocationLineAndColumn(Location location, int& line, int& column) const; 1576 | JSONCPP_STRING getLocationLineAndColumn(Location location) const; 1577 | void addComment(Location begin, Location end, CommentPlacement placement); 1578 | void skipCommentTokens(Token& token); 1579 | 1580 | static bool containsNewLine(Location begin, Location end); 1581 | static JSONCPP_STRING normalizeEOL(Location begin, Location end); 1582 | 1583 | typedef std::stack Nodes; 1584 | Nodes nodes_; 1585 | Errors errors_; 1586 | JSONCPP_STRING document_; 1587 | Location begin_; 1588 | Location end_; 1589 | Location current_; 1590 | Location lastValueEnd_; 1591 | Value* lastValue_; 1592 | JSONCPP_STRING commentsBefore_; 1593 | Features features_; 1594 | bool collectComments_; 1595 | }; // Reader 1596 | 1597 | /** Interface for reading JSON from a char array. 1598 | */ 1599 | class JSON_API CharReader { 1600 | public: 1601 | virtual ~CharReader() {} 1602 | /** \brief Read a Value from a JSON 1603 | document. 1604 | * The document must be a UTF-8 encoded string containing the document to read. 1605 | * 1606 | * \param beginDoc Pointer on the beginning of the UTF-8 encoded string of the 1607 | document to read. 1608 | * \param endDoc Pointer on the end of the UTF-8 encoded string of the 1609 | document to read. 1610 | * Must be >= beginDoc. 1611 | * \param root [out] Contains the root value of the document if it was 1612 | * successfully parsed. 1613 | * \param errs [out] Formatted error messages (if not NULL) 1614 | * a user friendly string that lists errors in the parsed 1615 | * document. 1616 | * \return \c true if the document was successfully parsed, \c false if an 1617 | error occurred. 1618 | */ 1619 | virtual bool parse( 1620 | char const* beginDoc, char const* endDoc, 1621 | Value* root, JSONCPP_STRING* errs) = 0; 1622 | 1623 | class JSON_API Factory { 1624 | public: 1625 | virtual ~Factory() {} 1626 | /** \brief Allocate a CharReader via operator new(). 1627 | * \throw std::exception if something goes wrong (e.g. invalid settings) 1628 | */ 1629 | virtual CharReader* newCharReader() const = 0; 1630 | }; // Factory 1631 | }; // CharReader 1632 | 1633 | /** \brief Build a CharReader implementation. 1634 | 1635 | Usage: 1636 | \code 1637 | using namespace Json; 1638 | CharReaderBuilder builder; 1639 | builder["collectComments"] = false; 1640 | Value value; 1641 | JSONCPP_STRING errs; 1642 | bool ok = parseFromStream(builder, std::cin, &value, &errs); 1643 | \endcode 1644 | */ 1645 | class JSON_API CharReaderBuilder : public CharReader::Factory { 1646 | public: 1647 | // Note: We use a Json::Value so that we can add data-members to this class 1648 | // without a major version bump. 1649 | /** Configuration of this builder. 1650 | These are case-sensitive. 1651 | Available settings (case-sensitive): 1652 | - `"collectComments": false or true` 1653 | - true to collect comment and allow writing them 1654 | back during serialization, false to discard comments. 1655 | This parameter is ignored if allowComments is false. 1656 | - `"allowComments": false or true` 1657 | - true if comments are allowed. 1658 | - `"strictRoot": false or true` 1659 | - true if root must be either an array or an object value 1660 | - `"allowDroppedNullPlaceholders": false or true` 1661 | - true if dropped null placeholders are allowed. (See StreamWriterBuilder.) 1662 | - `"allowNumericKeys": false or true` 1663 | - true if numeric object keys are allowed. 1664 | - `"allowSingleQuotes": false or true` 1665 | - true if '' are allowed for strings (both keys and values) 1666 | - `"stackLimit": integer` 1667 | - Exceeding stackLimit (recursive depth of `readValue()`) will 1668 | cause an exception. 1669 | - This is a security issue (seg-faults caused by deeply nested JSON), 1670 | so the default is low. 1671 | - `"failIfExtra": false or true` 1672 | - If true, `parse()` returns false when extra non-whitespace trails 1673 | the JSON value in the input string. 1674 | - `"rejectDupKeys": false or true` 1675 | - If true, `parse()` returns false when a key is duplicated within an object. 1676 | - `"allowSpecialFloats": false or true` 1677 | - If true, special float values (NaNs and infinities) are allowed 1678 | and their values are lossfree restorable. 1679 | 1680 | You can examine 'settings_` yourself 1681 | to see the defaults. You can also write and read them just like any 1682 | JSON Value. 1683 | \sa setDefaults() 1684 | */ 1685 | Json::Value settings_; 1686 | 1687 | CharReaderBuilder(); 1688 | ~CharReaderBuilder() JSONCPP_OVERRIDE; 1689 | 1690 | CharReader* newCharReader() const JSONCPP_OVERRIDE; 1691 | 1692 | /** \return true if 'settings' are legal and consistent; 1693 | * otherwise, indicate bad settings via 'invalid'. 1694 | */ 1695 | bool validate(Json::Value* invalid) const; 1696 | 1697 | /** A simple way to update a specific setting. 1698 | */ 1699 | Value& operator[](JSONCPP_STRING key); 1700 | 1701 | /** Called by ctor, but you can use this to reset settings_. 1702 | * \pre 'settings' != NULL (but Json::null is fine) 1703 | * \remark Defaults: 1704 | * \snippet src/lib_json/json_reader.cpp CharReaderBuilderDefaults 1705 | */ 1706 | static void setDefaults(Json::Value* settings); 1707 | /** Same as old Features::strictMode(). 1708 | * \pre 'settings' != NULL (but Json::null is fine) 1709 | * \remark Defaults: 1710 | * \snippet src/lib_json/json_reader.cpp CharReaderBuilderStrictMode 1711 | */ 1712 | static void strictMode(Json::Value* settings); 1713 | }; 1714 | 1715 | /** Consume entire stream and use its begin/end. 1716 | * Someday we might have a real StreamReader, but for now this 1717 | * is convenient. 1718 | */ 1719 | bool JSON_API parseFromStream( 1720 | CharReader::Factory const&, 1721 | JSONCPP_ISTREAM&, 1722 | Value* root, std::string* errs); 1723 | 1724 | /** \brief Read from 'sin' into 'root'. 1725 | 1726 | Always keep comments from the input JSON. 1727 | 1728 | This can be used to read a file into a particular sub-object. 1729 | For example: 1730 | \code 1731 | Json::Value root; 1732 | cin >> root["dir"]["file"]; 1733 | cout << root; 1734 | \endcode 1735 | Result: 1736 | \verbatim 1737 | { 1738 | "dir": { 1739 | "file": { 1740 | // The input stream JSON would be nested here. 1741 | } 1742 | } 1743 | } 1744 | \endverbatim 1745 | \throw std::exception on parse error. 1746 | \see Json::operator<<() 1747 | */ 1748 | JSON_API JSONCPP_ISTREAM& operator>>(JSONCPP_ISTREAM&, Value&); 1749 | 1750 | } // namespace Json 1751 | 1752 | #pragma pack(pop) 1753 | 1754 | #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) 1755 | #pragma warning(pop) 1756 | #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) 1757 | 1758 | #endif // CPPTL_JSON_READER_H_INCLUDED 1759 | 1760 | // ////////////////////////////////////////////////////////////////////// 1761 | // End of content of file: include/json/reader.h 1762 | // ////////////////////////////////////////////////////////////////////// 1763 | 1764 | 1765 | 1766 | 1767 | 1768 | 1769 | // ////////////////////////////////////////////////////////////////////// 1770 | // Beginning of content of file: include/json/writer.h 1771 | // ////////////////////////////////////////////////////////////////////// 1772 | 1773 | // Copyright 2007-2010 Baptiste Lepilleur and The JsonCpp Authors 1774 | // Distributed under MIT license, or public domain if desired and 1775 | // recognized in your jurisdiction. 1776 | // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE 1777 | 1778 | #ifndef JSON_WRITER_H_INCLUDED 1779 | #define JSON_WRITER_H_INCLUDED 1780 | 1781 | #if !defined(JSON_IS_AMALGAMATION) 1782 | #include "value.h" 1783 | #endif // if !defined(JSON_IS_AMALGAMATION) 1784 | #include 1785 | #include 1786 | #include 1787 | 1788 | // Disable warning C4251: : needs to have dll-interface to 1789 | // be used by... 1790 | #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) && defined(_MSC_VER) 1791 | #pragma warning(push) 1792 | #pragma warning(disable : 4251) 1793 | #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) 1794 | 1795 | #pragma pack(push, 8) 1796 | 1797 | namespace Json { 1798 | 1799 | class Value; 1800 | 1801 | /** 1802 | 1803 | Usage: 1804 | \code 1805 | using namespace Json; 1806 | void writeToStdout(StreamWriter::Factory const& factory, Value const& value) { 1807 | std::unique_ptr const writer( 1808 | factory.newStreamWriter()); 1809 | writer->write(value, &std::cout); 1810 | std::cout << std::endl; // add lf and flush 1811 | } 1812 | \endcode 1813 | */ 1814 | class JSON_API StreamWriter { 1815 | protected: 1816 | JSONCPP_OSTREAM* sout_; // not owned; will not delete 1817 | public: 1818 | StreamWriter(); 1819 | virtual ~StreamWriter(); 1820 | /** Write Value into document as configured in sub-class. 1821 | Do not take ownership of sout, but maintain a reference during function. 1822 | \pre sout != NULL 1823 | \return zero on success (For now, we always return zero, so check the stream instead.) 1824 | \throw std::exception possibly, depending on configuration 1825 | */ 1826 | virtual int write(Value const& root, JSONCPP_OSTREAM* sout) = 0; 1827 | 1828 | /** \brief A simple abstract factory. 1829 | */ 1830 | class JSON_API Factory { 1831 | public: 1832 | virtual ~Factory(); 1833 | /** \brief Allocate a CharReader via operator new(). 1834 | * \throw std::exception if something goes wrong (e.g. invalid settings) 1835 | */ 1836 | virtual StreamWriter* newStreamWriter() const = 0; 1837 | }; // Factory 1838 | }; // StreamWriter 1839 | 1840 | /** \brief Write into stringstream, then return string, for convenience. 1841 | * A StreamWriter will be created from the factory, used, and then deleted. 1842 | */ 1843 | JSONCPP_STRING JSON_API writeString(StreamWriter::Factory const& factory, Value const& root); 1844 | 1845 | 1846 | /** \brief Build a StreamWriter implementation. 1847 | 1848 | Usage: 1849 | \code 1850 | using namespace Json; 1851 | Value value = ...; 1852 | StreamWriterBuilder builder; 1853 | builder["commentStyle"] = "None"; 1854 | builder["indentation"] = " "; // or whatever you like 1855 | std::unique_ptr writer( 1856 | builder.newStreamWriter()); 1857 | writer->write(value, &std::cout); 1858 | std::cout << std::endl; // add lf and flush 1859 | \endcode 1860 | */ 1861 | class JSON_API StreamWriterBuilder : public StreamWriter::Factory { 1862 | public: 1863 | // Note: We use a Json::Value so that we can add data-members to this class 1864 | // without a major version bump. 1865 | /** Configuration of this builder. 1866 | Available settings (case-sensitive): 1867 | - "commentStyle": "None" or "All" 1868 | - "indentation": "" 1869 | - "enableYAMLCompatibility": false or true 1870 | - slightly change the whitespace around colons 1871 | - "dropNullPlaceholders": false or true 1872 | - Drop the "null" string from the writer's output for nullValues. 1873 | Strictly speaking, this is not valid JSON. But when the output is being 1874 | fed to a browser's JavaScript, it makes for smaller output and the 1875 | browser can handle the output just fine. 1876 | - "useSpecialFloats": false or true 1877 | - If true, outputs non-finite floating point values in the following way: 1878 | NaN values as "NaN", positive infinity as "Infinity", and negative infinity 1879 | as "-Infinity". 1880 | 1881 | You can examine 'settings_` yourself 1882 | to see the defaults. You can also write and read them just like any 1883 | JSON Value. 1884 | \sa setDefaults() 1885 | */ 1886 | Json::Value settings_; 1887 | 1888 | StreamWriterBuilder(); 1889 | ~StreamWriterBuilder() JSONCPP_OVERRIDE; 1890 | 1891 | /** 1892 | * \throw std::exception if something goes wrong (e.g. invalid settings) 1893 | */ 1894 | StreamWriter* newStreamWriter() const JSONCPP_OVERRIDE; 1895 | 1896 | /** \return true if 'settings' are legal and consistent; 1897 | * otherwise, indicate bad settings via 'invalid'. 1898 | */ 1899 | bool validate(Json::Value* invalid) const; 1900 | /** A simple way to update a specific setting. 1901 | */ 1902 | Value& operator[](JSONCPP_STRING key); 1903 | 1904 | /** Called by ctor, but you can use this to reset settings_. 1905 | * \pre 'settings' != NULL (but Json::null is fine) 1906 | * \remark Defaults: 1907 | * \snippet src/lib_json/json_writer.cpp StreamWriterBuilderDefaults 1908 | */ 1909 | static void setDefaults(Json::Value* settings); 1910 | }; 1911 | 1912 | /** \brief Abstract class for writers. 1913 | * \deprecated Use StreamWriter. (And really, this is an implementation detail.) 1914 | */ 1915 | class JSONCPP_DEPRECATED("Use StreamWriter instead") JSON_API Writer { 1916 | public: 1917 | virtual ~Writer(); 1918 | 1919 | virtual JSONCPP_STRING write(const Value& root) = 0; 1920 | }; 1921 | 1922 | /** \brief Outputs a Value in JSON format 1923 | *without formatting (not human friendly). 1924 | * 1925 | * The JSON document is written in a single line. It is not intended for 'human' 1926 | *consumption, 1927 | * but may be usefull to support feature such as RPC where bandwith is limited. 1928 | * \sa Reader, Value 1929 | * \deprecated Use StreamWriterBuilder. 1930 | */ 1931 | #if defined(_MSC_VER) 1932 | #pragma warning(push) 1933 | #pragma warning(disable:4996) // Deriving from deprecated class 1934 | #endif 1935 | class JSONCPP_DEPRECATED("Use StreamWriterBuilder instead") JSON_API FastWriter : public Writer { 1936 | public: 1937 | FastWriter(); 1938 | ~FastWriter() JSONCPP_OVERRIDE {} 1939 | 1940 | void enableYAMLCompatibility(); 1941 | 1942 | /** \brief Drop the "null" string from the writer's output for nullValues. 1943 | * Strictly speaking, this is not valid JSON. But when the output is being 1944 | * fed to a browser's JavaScript, it makes for smaller output and the 1945 | * browser can handle the output just fine. 1946 | */ 1947 | void dropNullPlaceholders(); 1948 | 1949 | void omitEndingLineFeed(); 1950 | 1951 | public: // overridden from Writer 1952 | JSONCPP_STRING write(const Value& root) JSONCPP_OVERRIDE; 1953 | 1954 | private: 1955 | void writeValue(const Value& value); 1956 | 1957 | JSONCPP_STRING document_; 1958 | bool yamlCompatibilityEnabled_; 1959 | bool dropNullPlaceholders_; 1960 | bool omitEndingLineFeed_; 1961 | }; 1962 | #if defined(_MSC_VER) 1963 | #pragma warning(pop) 1964 | #endif 1965 | 1966 | /** \brief Writes a Value in JSON format in a 1967 | *human friendly way. 1968 | * 1969 | * The rules for line break and indent are as follow: 1970 | * - Object value: 1971 | * - if empty then print {} without indent and line break 1972 | * - if not empty the print '{', line break & indent, print one value per 1973 | *line 1974 | * and then unindent and line break and print '}'. 1975 | * - Array value: 1976 | * - if empty then print [] without indent and line break 1977 | * - if the array contains no object value, empty array or some other value 1978 | *types, 1979 | * and all the values fit on one lines, then print the array on a single 1980 | *line. 1981 | * - otherwise, it the values do not fit on one line, or the array contains 1982 | * object or non empty array, then print one value per line. 1983 | * 1984 | * If the Value have comments then they are outputed according to their 1985 | *#CommentPlacement. 1986 | * 1987 | * \sa Reader, Value, Value::setComment() 1988 | * \deprecated Use StreamWriterBuilder. 1989 | */ 1990 | #if defined(_MSC_VER) 1991 | #pragma warning(push) 1992 | #pragma warning(disable:4996) // Deriving from deprecated class 1993 | #endif 1994 | class JSONCPP_DEPRECATED("Use StreamWriterBuilder instead") JSON_API StyledWriter : public Writer { 1995 | public: 1996 | StyledWriter(); 1997 | ~StyledWriter() JSONCPP_OVERRIDE {} 1998 | 1999 | public: // overridden from Writer 2000 | /** \brief Serialize a Value in JSON format. 2001 | * \param root Value to serialize. 2002 | * \return String containing the JSON document that represents the root value. 2003 | */ 2004 | JSONCPP_STRING write(const Value& root) JSONCPP_OVERRIDE; 2005 | 2006 | private: 2007 | void writeValue(const Value& value); 2008 | void writeArrayValue(const Value& value); 2009 | bool isMultilineArray(const Value& value); 2010 | void pushValue(const JSONCPP_STRING& value); 2011 | void writeIndent(); 2012 | void writeWithIndent(const JSONCPP_STRING& value); 2013 | void indent(); 2014 | void unindent(); 2015 | void writeCommentBeforeValue(const Value& root); 2016 | void writeCommentAfterValueOnSameLine(const Value& root); 2017 | bool hasCommentForValue(const Value& value); 2018 | static JSONCPP_STRING normalizeEOL(const JSONCPP_STRING& text); 2019 | 2020 | typedef std::vector ChildValues; 2021 | 2022 | ChildValues childValues_; 2023 | JSONCPP_STRING document_; 2024 | JSONCPP_STRING indentString_; 2025 | unsigned int rightMargin_; 2026 | unsigned int indentSize_; 2027 | bool addChildValues_; 2028 | }; 2029 | #if defined(_MSC_VER) 2030 | #pragma warning(pop) 2031 | #endif 2032 | 2033 | /** \brief Writes a Value in JSON format in a 2034 | human friendly way, 2035 | to a stream rather than to a string. 2036 | * 2037 | * The rules for line break and indent are as follow: 2038 | * - Object value: 2039 | * - if empty then print {} without indent and line break 2040 | * - if not empty the print '{', line break & indent, print one value per 2041 | line 2042 | * and then unindent and line break and print '}'. 2043 | * - Array value: 2044 | * - if empty then print [] without indent and line break 2045 | * - if the array contains no object value, empty array or some other value 2046 | types, 2047 | * and all the values fit on one lines, then print the array on a single 2048 | line. 2049 | * - otherwise, it the values do not fit on one line, or the array contains 2050 | * object or non empty array, then print one value per line. 2051 | * 2052 | * If the Value have comments then they are outputed according to their 2053 | #CommentPlacement. 2054 | * 2055 | * \sa Reader, Value, Value::setComment() 2056 | * \deprecated Use StreamWriterBuilder. 2057 | */ 2058 | #if defined(_MSC_VER) 2059 | #pragma warning(push) 2060 | #pragma warning(disable:4996) // Deriving from deprecated class 2061 | #endif 2062 | class JSONCPP_DEPRECATED("Use StreamWriterBuilder instead") JSON_API StyledStreamWriter { 2063 | public: 2064 | /** 2065 | * \param indentation Each level will be indented by this amount extra. 2066 | */ 2067 | StyledStreamWriter(JSONCPP_STRING indentation = "\t"); 2068 | ~StyledStreamWriter() {} 2069 | 2070 | public: 2071 | /** \brief Serialize a Value in JSON format. 2072 | * \param out Stream to write to. (Can be ostringstream, e.g.) 2073 | * \param root Value to serialize. 2074 | * \note There is no point in deriving from Writer, since write() should not 2075 | * return a value. 2076 | */ 2077 | void write(JSONCPP_OSTREAM& out, const Value& root); 2078 | 2079 | private: 2080 | void writeValue(const Value& value); 2081 | void writeArrayValue(const Value& value); 2082 | bool isMultilineArray(const Value& value); 2083 | void pushValue(const JSONCPP_STRING& value); 2084 | void writeIndent(); 2085 | void writeWithIndent(const JSONCPP_STRING& value); 2086 | void indent(); 2087 | void unindent(); 2088 | void writeCommentBeforeValue(const Value& root); 2089 | void writeCommentAfterValueOnSameLine(const Value& root); 2090 | bool hasCommentForValue(const Value& value); 2091 | static JSONCPP_STRING normalizeEOL(const JSONCPP_STRING& text); 2092 | 2093 | typedef std::vector ChildValues; 2094 | 2095 | ChildValues childValues_; 2096 | JSONCPP_OSTREAM* document_; 2097 | JSONCPP_STRING indentString_; 2098 | unsigned int rightMargin_; 2099 | JSONCPP_STRING indentation_; 2100 | bool addChildValues_ : 1; 2101 | bool indented_ : 1; 2102 | }; 2103 | #if defined(_MSC_VER) 2104 | #pragma warning(pop) 2105 | #endif 2106 | 2107 | #if defined(JSON_HAS_INT64) 2108 | JSONCPP_STRING JSON_API valueToString(Int value); 2109 | JSONCPP_STRING JSON_API valueToString(UInt value); 2110 | #endif // if defined(JSON_HAS_INT64) 2111 | JSONCPP_STRING JSON_API valueToString(LargestInt value); 2112 | JSONCPP_STRING JSON_API valueToString(LargestUInt value); 2113 | JSONCPP_STRING JSON_API valueToString(double value); 2114 | JSONCPP_STRING JSON_API valueToString(bool value); 2115 | JSONCPP_STRING JSON_API valueToQuotedString(const char* value); 2116 | 2117 | /// \brief Output using the StyledStreamWriter. 2118 | /// \see Json::operator>>() 2119 | JSON_API JSONCPP_OSTREAM& operator<<(JSONCPP_OSTREAM&, const Value& root); 2120 | 2121 | } // namespace Json 2122 | 2123 | #pragma pack(pop) 2124 | 2125 | #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) 2126 | #pragma warning(pop) 2127 | #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) 2128 | 2129 | #endif // JSON_WRITER_H_INCLUDED 2130 | 2131 | // ////////////////////////////////////////////////////////////////////// 2132 | // End of content of file: include/json/writer.h 2133 | // ////////////////////////////////////////////////////////////////////// 2134 | 2135 | 2136 | 2137 | 2138 | 2139 | 2140 | // ////////////////////////////////////////////////////////////////////// 2141 | // Beginning of content of file: include/json/assertions.h 2142 | // ////////////////////////////////////////////////////////////////////// 2143 | 2144 | // Copyright 2007-2010 Baptiste Lepilleur and The JsonCpp Authors 2145 | // Distributed under MIT license, or public domain if desired and 2146 | // recognized in your jurisdiction. 2147 | // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE 2148 | 2149 | #ifndef CPPTL_JSON_ASSERTIONS_H_INCLUDED 2150 | #define CPPTL_JSON_ASSERTIONS_H_INCLUDED 2151 | 2152 | #include 2153 | #include 2154 | 2155 | #if !defined(JSON_IS_AMALGAMATION) 2156 | #include "config.h" 2157 | #endif // if !defined(JSON_IS_AMALGAMATION) 2158 | 2159 | /** It should not be possible for a maliciously designed file to 2160 | * cause an abort() or seg-fault, so these macros are used only 2161 | * for pre-condition violations and internal logic errors. 2162 | */ 2163 | #if JSON_USE_EXCEPTION 2164 | 2165 | // @todo <= add detail about condition in exception 2166 | # define JSON_ASSERT(condition) \ 2167 | {if (!(condition)) {Json::throwLogicError( "assert json failed" );}} 2168 | 2169 | # define JSON_FAIL_MESSAGE(message) \ 2170 | { \ 2171 | JSONCPP_OSTRINGSTREAM oss; oss << message; \ 2172 | Json::throwLogicError(oss.str()); \ 2173 | abort(); \ 2174 | } 2175 | 2176 | #else // JSON_USE_EXCEPTION 2177 | 2178 | # define JSON_ASSERT(condition) assert(condition) 2179 | 2180 | // The call to assert() will show the failure message in debug builds. In 2181 | // release builds we abort, for a core-dump or debugger. 2182 | # define JSON_FAIL_MESSAGE(message) \ 2183 | { \ 2184 | JSONCPP_OSTRINGSTREAM oss; oss << message; \ 2185 | assert(false && oss.str().c_str()); \ 2186 | abort(); \ 2187 | } 2188 | 2189 | 2190 | #endif 2191 | 2192 | #define JSON_ASSERT_MESSAGE(condition, message) \ 2193 | if (!(condition)) { \ 2194 | JSON_FAIL_MESSAGE(message); \ 2195 | } 2196 | 2197 | #endif // CPPTL_JSON_ASSERTIONS_H_INCLUDED 2198 | 2199 | // ////////////////////////////////////////////////////////////////////// 2200 | // End of content of file: include/json/assertions.h 2201 | // ////////////////////////////////////////////////////////////////////// 2202 | 2203 | 2204 | 2205 | 2206 | 2207 | #endif //ifndef JSON_AMALGAMATED_H_INCLUDED 2208 | --------------------------------------------------------------------------------