diff --git a/bindings/python/src/model/mixin/core/vertex_identifier.cpp b/bindings/python/src/model/mixin/core/vertex_identifier.cpp index 24edb2013..198c5f126 100644 --- a/bindings/python/src/model/mixin/core/vertex_identifier.cpp +++ b/bindings/python/src/model/mixin/core/vertex_identifier.cpp @@ -90,8 +90,11 @@ namespace geode }, pybind11::arg( "unique_vertex_id" ), "Return the list of ComponentMeshVertex identified with the " - "unique vertex; raise an IndexError if unique_vertex_id is not " - "in [0, nb_unique_vertices)" ) + "unique vertex, in insertion order (after loading a native " + "file of the current format: Corners, Lines, Surfaces then " + "Blocks in the model order, then increasing vertex " + "indices); raise an IndexError if " + "unique_vertex_id is not in [0, nb_unique_vertices)" ) .def( "is_unique_vertex_isolated", []( const VertexIdentifier& identifier, diff --git a/cmake/ConfigureMinizip.cmake b/cmake/ConfigureMinizip.cmake index 482289e74..b8d478fba 100644 --- a/cmake/ConfigureMinizip.cmake +++ b/cmake/ConfigureMinizip.cmake @@ -29,6 +29,7 @@ ExternalProject_Add(minizip GIT_TAG 4.1.0 GIT_SHALLOW ON GIT_PROGRESS ON + DEPENDS zlib CMAKE_GENERATOR ${CMAKE_GENERATOR} CMAKE_GENERATOR_PLATFORM ${CMAKE_GENERATOR_PLATFORM} CMAKE_ARGS @@ -39,7 +40,11 @@ ExternalProject_Add(minizip -DCMAKE_CXX_STANDARD=${CMAKE_CXX_STANDARD} CMAKE_CACHE_ARGS -DMZ_COMPAT:BOOL=OFF - -DMZ_ZLIB:BOOL=OFF + -DMZ_ZLIB:BOOL=ON + -DMZ_FETCH_LIBS:BOOL=OFF + -DMZ_FORCE_FETCH_LIBS:BOOL=OFF + -DCMAKE_FIND_PACKAGE_PREFER_CONFIG:BOOL=ON + -DZLIB_ROOT:PATH=${ZLIB_INSTALL_PREFIX} -DMZ_BZIP2:BOOL=OFF -DMZ_LZMA:BOOL=OFF -DMZ_PKCRYPT:BOOL=OFF diff --git a/cmake/OpenGeode.cmake b/cmake/OpenGeode.cmake index 202df4920..6b0abd898 100644 --- a/cmake/OpenGeode.cmake +++ b/cmake/OpenGeode.cmake @@ -32,11 +32,15 @@ find_package(absl REQUIRED CONFIG NO_DEFAULT_PATH PATHS ${ABSEIL_INSTALL_PREFIX} find_package(Async++ REQUIRED CONFIG NO_DEFAULT_PATH PATHS ${ASYNCPLUSPLUS_INSTALL_PREFIX}) find_package(Bitsery REQUIRED CONFIG NO_DEFAULT_PATH PATHS ${BITSERY_INSTALL_PREFIX}) find_package(earcut_hpp REQUIRED CONFIG NO_DEFAULT_PATH PATHS ${EARCUT_INSTALL_PREFIX}) +find_package(ZLIB REQUIRED CONFIG NO_DEFAULT_PATH PATHS ${ZLIB_INSTALL_PREFIX}) +# minizip-ng calls find_dependency(ZLIB): reuse the zlib-ng config found above +set(GEODE_PREFER_CONFIG ${CMAKE_FIND_PACKAGE_PREFER_CONFIG}) +set(CMAKE_FIND_PACKAGE_PREFER_CONFIG ON) find_package(minizip-ng REQUIRED CONFIG NO_DEFAULT_PATH PATHS ${MINIZIP_INSTALL_PREFIX}) +set(CMAKE_FIND_PACKAGE_PREFER_CONFIG ${GEODE_PREFER_CONFIG}) find_package(nanoflann REQUIRED CONFIG NO_DEFAULT_PATH PATHS ${NANOFLANN_INSTALL_PREFIX}) find_package(spdlog REQUIRED CONFIG NO_DEFAULT_PATH PATHS ${SPDLOG_INSTALL_PREFIX}) find_package(nlohmann_json REQUIRED CONFIG NO_DEFAULT_PATH PATHS ${JSON_INSTALL_PREFIX}) -find_package(zlib REQUIRED CONFIG NO_DEFAULT_PATH PATHS ${ZLIB_INSTALL_PREFIX}) find_package(Threads REQUIRED) # Install OpenGeode third-parties diff --git a/cmake/OpenGeodeConfig.cmake.in b/cmake/OpenGeodeConfig.cmake.in index 5222dd224..e8d304a28 100644 --- a/cmake/OpenGeodeConfig.cmake.in +++ b/cmake/OpenGeodeConfig.cmake.in @@ -44,7 +44,12 @@ find_dependency(Async++) get_target_property(library_type OpenGeode::basic TYPE) if(library_type STREQUAL "STATIC_LIBRARY") find_dependency(earcut_hpp) + find_dependency(ZLIB CONFIG) + # minizip-ng calls find_dependency(ZLIB): use the installed zlib-ng config + set(GEODE_PREFER_CONFIG ${CMAKE_FIND_PACKAGE_PREFER_CONFIG}) + set(CMAKE_FIND_PACKAGE_PREFER_CONFIG ON) find_dependency(minizip-ng) + set(CMAKE_FIND_PACKAGE_PREFER_CONFIG ${GEODE_PREFER_CONFIG}) find_dependency(nanoflann) find_dependency(spdlog) find_dependency(nlohmann_json) diff --git a/cmake/SuperBuild.cmake b/cmake/SuperBuild.cmake index 05415925e..60b8abf42 100644 --- a/cmake/SuperBuild.cmake +++ b/cmake/SuperBuild.cmake @@ -63,6 +63,7 @@ include(${PROJECT_SOURCE_DIR}/cmake/ConfigureAbseil.cmake) include(${PROJECT_SOURCE_DIR}/cmake/ConfigureAsync++.cmake) include(${PROJECT_SOURCE_DIR}/cmake/ConfigureBitsery.cmake) include(${PROJECT_SOURCE_DIR}/cmake/ConfigureEarcut.cmake) +include(${PROJECT_SOURCE_DIR}/cmake/ConfigureZlib.cmake) include(${PROJECT_SOURCE_DIR}/cmake/ConfigureMinizip.cmake) include(${PROJECT_SOURCE_DIR}/cmake/ConfigureNanoflann.cmake) include(${PROJECT_SOURCE_DIR}/cmake/ConfigureSpdlog.cmake) @@ -70,7 +71,6 @@ include(${PROJECT_SOURCE_DIR}/cmake/ConfigureSQLite.cmake) include(${PROJECT_SOURCE_DIR}/cmake/ConfigurePROJ.cmake) include(${PROJECT_SOURCE_DIR}/cmake/ConfigureGDAL.cmake) include(${PROJECT_SOURCE_DIR}/cmake/ConfigureJson.cmake) -include(${PROJECT_SOURCE_DIR}/cmake/ConfigureZlib.cmake) if(OPENGEODE_WITH_PYTHON OR INCLUDE_PYBIND11) include(${PROJECT_SOURCE_DIR}/cmake/ConfigurePybind11.cmake) diff --git a/include/geode/basic/bitsery_archive.hpp b/include/geode/basic/bitsery_archive.hpp index 40ffc3486..dc529677d 100644 --- a/include/geode/basic/bitsery_archive.hpp +++ b/include/geode/basic/bitsery_archive.hpp @@ -23,9 +23,16 @@ #pragma once +#include +#include +#include +#include + #include #include +#include +#include #include #include #include @@ -33,9 +40,37 @@ #include #include +#include #include +#include #include +namespace bitsery +{ + namespace traits + { + template <> + struct ContainerTraits< geode::ByteSpan > + { + using TValue = char; + static constexpr bool isResizable = false; + static constexpr bool isContiguous = true; + static size_t size( const geode::ByteSpan &container ) + { + return container.size(); + } + }; + + template <> + struct BufferAdapterTraits< geode::ByteSpan > + { + using TIterator = const char *; + using TConstIterator = const char *; + using TValue = char; + }; + } // namespace traits +} // namespace bitsery + namespace geode { using PContext = @@ -45,13 +80,13 @@ namespace geode bitsery::ext::InheritanceContext >; using Serializer = bitsery::Serializer< bitsery::OutputBufferedStreamAdapter, TContext >; + /*! + * Deserializer reading a ByteSpan: + * Deserializer archive{ context, bytes.data(), bytes.size() }. + */ using Deserializer = - bitsery::Deserializer< bitsery::InputStreamAdapter, TContext >; - - enum struct BITSERY - { - constructor - }; + bitsery::Deserializer< bitsery::InputBufferAdapter< ByteSpan >, + TContext >; /*! * Register all the information needed by Bitsery to serialize the objects @@ -83,6 +118,29 @@ namespace geode static void register_deserialize_pcontext( PContext &context ); }; + + namespace detail + { + /*! + * Deserialize an object from bytes, with the deserialize contexts of + * every registered library. + * @return true if the bytes were read without error, entirely, and + * every pointer was linked. + */ + template < typename Object > + [[nodiscard]] bool deserialize_bytes( ByteSpan bytes, Object &object ) + { + TContext context{}; + BitseryExtensions::register_deserialize_pcontext( + std::get< 0 >( context ) ); + Deserializer archive{ context, bytes.data(), bytes.size() }; + archive.object( object ); + const auto &adapter = archive.adapter(); + return adapter.error() == bitsery::ReaderError::NoError + && adapter.isCompletedSuccessfully() + && std::get< 1 >( context ).isValid(); + } + } // namespace detail } // namespace geode namespace bitsery diff --git a/include/geode/basic/byte_span.hpp b/include/geode/basic/byte_span.hpp new file mode 100644 index 000000000..dc220c59e --- /dev/null +++ b/include/geode/basic/byte_span.hpp @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2019 - 2026 Geode-solutions + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * + */ + +#pragma once + +#include + +namespace geode +{ + /*! + * Read-only bytes to deserialize, owned elsewhere (file content, slice of + * an archive in memory...). + */ + using ByteSpan = absl::Span< const char >; +} // namespace geode diff --git a/include/geode/basic/detail/file_content.hpp b/include/geode/basic/detail/file_content.hpp new file mode 100644 index 000000000..52b642b17 --- /dev/null +++ b/include/geode/basic/detail/file_content.hpp @@ -0,0 +1,151 @@ +/* + * Copyright (c) 2019 - 2026 Geode-solutions + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * + */ + +#pragma once + +#include +#include +#include +#include + +#include +#include + +namespace geode::detail +{ + /*! + * Owned bytes, uninitialized at construction. + */ + class ByteBuffer + { + public: + explicit ByteBuffer( size_t size ) + : data_{ new char[size] }, size_{ size } + { + } + + [[nodiscard]] char* data() + { + return data_.get(); + } + + [[nodiscard]] size_t size() const + { + return size_; + } + + [[nodiscard]] ByteSpan span() const + { + return { data_.get(), size_ }; + } + + private: + std::unique_ptr< char[] > data_; + size_t size_; + }; + + /*! + * A whole file mapped read-only in memory: its pages are read from the + * file when first accessed, and belong to the system file cache. + * The file must not be truncated while it is mapped. + */ + class opengeode_basic_api MappedFile + { + public: + /*! + * Map a whole file (UTF-8 path) read-only. + * @return nullptr if the file cannot be mapped (missing, not a regular + * file, or mapping not supported). + */ + [[nodiscard]] static std::shared_ptr< const MappedFile > map( + std::string_view filename ); + + MappedFile( const MappedFile& ) = delete; + MappedFile& operator=( const MappedFile& ) = delete; + MappedFile( MappedFile&& ) = delete; + MappedFile& operator=( MappedFile&& ) = delete; + ~MappedFile(); + + /*! + * Bytes of the file (empty for an empty file). + */ + [[nodiscard]] ByteSpan span() const; + + /*! + * Remove the pages lying entirely within the given bytes of span() + * from the memory of the process (they stay in the file cache). + * The bytes stay readable: their pages are mapped again if accessed. + */ + void release( ByteSpan bytes ) const; + + private: + MappedFile( const char* data, size_t size ); + + private: + const char* data_; + size_t size_; + }; + + /*! + * Bytes of a file: either a slice of a mapped file (kept mapped while + * this object lives, and released from memory when it is destroyed), or + * an owned buffer. + */ + class opengeode_basic_api FileContent + { + public: + explicit FileContent( ByteBuffer buffer ); + + /*! + * @param[in] bytes Bytes inside mapping->span(). + */ + FileContent( + std::shared_ptr< const MappedFile > mapping, ByteSpan bytes ); + + FileContent( const FileContent& ) = delete; + FileContent& operator=( const FileContent& ) = delete; + FileContent( FileContent&& other ) noexcept; + FileContent& operator=( FileContent&& ) = delete; + ~FileContent(); + + [[nodiscard]] ByteSpan span() const + { + return bytes_; + } + + private: + std::shared_ptr< const MappedFile > mapping_; + std::optional< ByteBuffer > buffer_; + ByteSpan bytes_; + }; + + /*! + * Content of a whole file (UTF-8 path): mapped when possible, otherwise + * read into memory. + * @return std::nullopt if the file cannot be opened or is not a regular + * file. + * @exception OpenGeodeException (data) if the file cannot be read. + */ + [[nodiscard]] std::optional< FileContent > + opengeode_basic_api map_file_content( std::string_view filename ); +} // namespace geode::detail diff --git a/include/geode/basic/detail/geode_input_impl.hpp b/include/geode/basic/detail/geode_input_impl.hpp index ce987ddfc..4eecea6a4 100644 --- a/include/geode/basic/detail/geode_input_impl.hpp +++ b/include/geode/basic/detail/geode_input_impl.hpp @@ -32,6 +32,7 @@ #include #include +#include #include #include #include @@ -80,6 +81,54 @@ namespace geode::detail return objects; } + /*! + * Load the objects of one of the given files with the input registered + * for its extension: from its content in memory when the input supports + * it, otherwise from the file on disk (written to a temporary directory + * if the files are not in a directory). + */ + template < typename Factory, typename... Args > + [[nodiscard]] std::vector< typename Factory::BaseClass::InputData > + geode_object_input_from_files( std::string_view type, + const InputFiles& files, + std::string_view name, + const Args&... args ) + { + const Timer timer; + const auto location = files.location( name ); + const auto extension = lowercase_extension( name ); + OpenGeodeBasicException::check_exception( + Factory::has_creator( extension ), nullptr, + OpenGeodeException::TYPE::data, "Unknown extension \"", extension, + "\" for file \"", location, "\". Available extensions: ", + absl::StrJoin( Factory::list_creators(), ", " ), + ". Other formats may be provided by IO libraries, which must be " + "initialized (or imported in Python) first" ); + auto objects = [&] { + const auto content = files.content( name ); + auto input = Factory::create( extension, location ); + std::vector< typename Factory::BaseClass::InputData > from_bytes; + if( input->read_bytes( content.span(), from_bytes, args... ) ) + { + return from_bytes; + } + if( const auto path = files.path( name ) ) + { + return Factory::create( extension, path.value() ) + ->read( args... ); + } + const TemporaryFile file{ name, content.span() }; + return Factory::create( extension, file.path() )->read( args... ); + }(); + OpenGeodeBasicException::check_exception( !objects.empty(), nullptr, + OpenGeodeException::TYPE::data, "[", type, + "] No object found in file \"", location, "\"" ); + Logger::info( type, " loaded from ", location, " in ", timer.duration(), + " (", objects.size(), + objects.size() == 1 ? " object)" : " objects)" ); + return objects; + } + template < typename Exception, typename Factory, typename... ParentFactories, diff --git a/include/geode/basic/detail/input_files.hpp b/include/geode/basic/detail/input_files.hpp new file mode 100644 index 000000000..cc38a4557 --- /dev/null +++ b/include/geode/basic/detail/input_files.hpp @@ -0,0 +1,175 @@ +/* + * Copyright (c) 2019 - 2026 Geode-solutions + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * + */ + +#pragma once + +#include +#include +#include +#include + +#include +#include +#include + +namespace geode::detail +{ + /*! + * Read-only set of named files making up a saved object (e.g. a model): + * either the files of a directory or the entries of an archive. + * All the const functions can be called concurrently. + */ + class opengeode_basic_api InputFiles + { + public: + InputFiles( const InputFiles& ) = delete; + InputFiles& operator=( const InputFiles& ) = delete; + InputFiles( InputFiles&& ) = delete; + InputFiles& operator=( InputFiles&& ) = delete; + virtual ~InputFiles(); + + /*! + * Return true if there is a file of this name. + */ + [[nodiscard]] virtual bool has( std::string_view name ) const = 0; + + /*! + * Names of every file (directories excluded), in a deterministic + * order. + */ + [[nodiscard]] virtual std::vector< std::string > names() const = 0; + + /*! + * Bytes of a file, without copy when possible. + * @exception OpenGeodeException (data) if the file is missing, cannot + * be read, or is corrupted. + */ + [[nodiscard]] virtual FileContent content( + std::string_view name ) const = 0; + + /*! + * Path of a file on disk, if the files are in a directory. + * @return std::nullopt for an entry of an archive. + */ + [[nodiscard]] virtual std::optional< std::string > path( + std::string_view name ) const = 0; + + /*! + * Description of a file for messages: its path, or the archive path + * followed by the entry name. + */ + [[nodiscard]] virtual std::string location( + std::string_view name ) const = 0; + + protected: + InputFiles() = default; + }; + + /*! + * Files of a directory (not recursive): files are mapped in memory when + * read. + */ + class opengeode_basic_api DirectoryInputFiles final : public InputFiles + { + public: + explicit DirectoryInputFiles( std::string_view directory ); + ~DirectoryInputFiles() final; + + [[nodiscard]] bool has( std::string_view name ) const final; + + [[nodiscard]] std::vector< std::string > names() const final; + + [[nodiscard]] FileContent content( std::string_view name ) const final; + + [[nodiscard]] std::optional< std::string > path( + std::string_view name ) const final; + + [[nodiscard]] std::string location( std::string_view name ) const final; + + private: + std::string directory_; + }; + + /*! + * Entries of a zip archive, read in place: the archive is mapped in + * memory (or read entry by entry if it cannot be mapped), stored entries + * are returned without copy and deflated entries are decompressed. + * The CRC-32 of an entry is checked each time it is read. + */ + class opengeode_basic_api ArchiveInputFiles final : public InputFiles + { + public: + /*! + * Read the list of entries of a zip archive (UTF-8 path). + * @exception OpenGeodeException (data) if the file is not a readable + * zip archive or holds an entry with an unsafe path (absolute or + * with ".."), encrypted or compressed by another method than DEFLATE. + */ + explicit ArchiveInputFiles( std::string_view filename ); + ~ArchiveInputFiles() final; + + [[nodiscard]] bool has( std::string_view name ) const final; + + [[nodiscard]] std::vector< std::string > names() const final; + + /*! + * @exception OpenGeodeException (data) if the entry is missing, + * cannot be read or decompressed, or does not match its CRC-32. + */ + [[nodiscard]] FileContent content( std::string_view name ) const final; + + [[nodiscard]] std::optional< std::string > path( + std::string_view name ) const final; + + [[nodiscard]] std::string location( std::string_view name ) const final; + + private: + IMPLEMENTATION_MEMBER( impl_ ); + }; + + /*! + * A file holding the given bytes, in a new directory of the temporary + * directory of the system. Both are removed on destruction. + */ + class opengeode_basic_api TemporaryFile + { + public: + /*! + * @param[in] name Name of the file (without directory). + * @exception OpenGeodeException (internal) if there is no temporary + * directory, or if the directory or the file cannot be created. + */ + TemporaryFile( std::string_view name, ByteSpan content ); + TemporaryFile( const TemporaryFile& ) = delete; + TemporaryFile& operator=( const TemporaryFile& ) = delete; + TemporaryFile( TemporaryFile&& ) = delete; + TemporaryFile& operator=( TemporaryFile&& ) = delete; + ~TemporaryFile(); + + [[nodiscard]] const std::string& path() const; + + private: + std::string directory_; + std::string path_; + }; +} // namespace geode::detail diff --git a/include/geode/basic/growable.hpp b/include/geode/basic/growable.hpp index c2b55fd31..2f809d273 100644 --- a/include/geode/basic/growable.hpp +++ b/include/geode/basic/growable.hpp @@ -32,6 +32,15 @@ namespace geode { + /*! + * Tag of the constructors building an object only to deserialize it + * (no expensive initialization of values about to be overwritten). + */ + enum struct BITSERY + { + constructor + }; + /*! * Maximum size of a serialized name. Prevents corrupted files from * requesting huge allocations. diff --git a/include/geode/basic/identifier.hpp b/include/geode/basic/identifier.hpp index 7346175cf..cc7bceb4a 100644 --- a/include/geode/basic/identifier.hpp +++ b/include/geode/basic/identifier.hpp @@ -34,10 +34,16 @@ namespace bitsery class Access; } // namespace bitsery +namespace geode::detail +{ + class InputFiles; +} // namespace geode::detail + namespace geode { class IdentifierBuilder; struct uuid; + enum struct BITSERY; } // namespace geode namespace geode @@ -64,13 +70,19 @@ namespace geode void set_name( std::string_view name, IdentifierKey /*key*/ ); void load_identifier( - std::string_view directory, IdentifierKey /*key*/ ); + const detail::InputFiles& files, IdentifierKey /*key*/ ); void copy_identifier( const Identifier& other, IdentifierKey /*key*/ ); protected: Identifier(); + /*! + * Nil identifier (no uuid generated), for an object about to be + * deserialized. + */ + explicit Identifier( BITSERY bitsery ); + Identifier& operator=( Identifier&& other ) noexcept; void set_id( const uuid& unique_id ); diff --git a/include/geode/basic/identifier_builder.hpp b/include/geode/basic/identifier_builder.hpp index b8fcb4bbb..a456b1f9c 100644 --- a/include/geode/basic/identifier_builder.hpp +++ b/include/geode/basic/identifier_builder.hpp @@ -25,6 +25,11 @@ #include +namespace geode::detail +{ + class InputFiles; +} // namespace geode::detail + namespace geode { class Identifier; @@ -46,6 +51,8 @@ namespace geode void load_identifier( std::string_view directory ); + void load_identifier( const detail::InputFiles& files ); + private: Identifier& identifier_; }; diff --git a/include/geode/basic/input.hpp b/include/geode/basic/input.hpp index 638acac27..fd2083008 100644 --- a/include/geode/basic/input.hpp +++ b/include/geode/basic/input.hpp @@ -23,11 +23,13 @@ #pragma once +#include #include #include #include +#include #include #include #include @@ -78,6 +80,22 @@ namespace geode [[nodiscard]] virtual std::vector< Object > read( const Args&... args ) = 0; + /*! + * Read the objects from the content of the file, already in memory + * (e.g. an entry of an archive), instead of opening the file: the + * filename only names the content in messages. + * @param[out] objects Receives the objects read (only when returning + * true). + * @return false if this input can only read files: the caller then + * calls read() on a file holding the content. + */ + [[nodiscard]] virtual bool read_bytes( ByteSpan /*content*/, + std::vector< Object >& /*objects*/, + const Args&... /*args*/ ) + { + return false; + } + ~Input() { if( inspect_required_ ) diff --git a/include/geode/basic/uuid.hpp b/include/geode/basic/uuid.hpp index 4b0962455..abeedeb81 100644 --- a/include/geode/basic/uuid.hpp +++ b/include/geode/basic/uuid.hpp @@ -37,8 +37,16 @@ namespace geode struct opengeode_basic_api uuid { public: + /*! + * Generate a new unique identifier (UUIDv7). + */ uuid(); explicit uuid( std::string_view string ); + /*! + * Nil uuid (all bytes zero), without generating a new identifier: for + * a uuid about to be overwritten by deserialization. + */ + explicit uuid( BITSERY /*unused*/ ) : bytes_{} {} uuid( const uuid & ) = default; uuid( uuid && ) = default; uuid &operator=( uuid &&other ) = default; @@ -96,6 +104,17 @@ namespace geode }; } // namespace geode +namespace bitsery +{ + // Bitsery builds the uuids it deserializes (map keys, optionals...) with + // Access::create: do not generate an identifier about to be overwritten. + template <> + inline geode::uuid Access::create< geode::uuid >() + { + return geode::uuid{ geode::BITSERY::constructor }; + } +} // namespace bitsery + namespace std { template <> diff --git a/include/geode/image/io/geode/geode_bitsery_raster_input.hpp b/include/geode/image/io/geode/geode_bitsery_raster_input.hpp index d8328cb3c..3852efe49 100644 --- a/include/geode/image/io/geode/geode_bitsery_raster_input.hpp +++ b/include/geode/image/io/geode/geode_bitsery_raster_input.hpp @@ -24,6 +24,9 @@ #pragma once #include +#include + +#include #include #include @@ -41,29 +44,18 @@ namespace geode [[nodiscard]] std::vector< RasterImage< dimension > > read() final { - std::ifstream file{ to_string( this->filename() ), - std::ifstream::binary }; - OpenGeodeImageException::check_exception( !file.fail(), nullptr, - OpenGeodeException::TYPE::data, - "[RasterImageInput] Failed to open file: ", - to_string( this->filename() ) ); - TContext context{}; - BitseryExtensions::register_deserialize_pcontext( - std::get< 0 >( context ) ); - Deserializer archive{ context, file }; - RasterImage< dimension > image; - archive.object( image ); - const auto& adapter = archive.adapter(); - OpenGeodeImageException::check_exception( - adapter.error() == bitsery::ReaderError::NoError - && adapter.isCompletedSuccessfully() - && std::get< 1 >( context ).isValid(), + const auto content = detail::map_file_content( this->filename() ); + OpenGeodeImageException::check_exception( content.has_value(), nullptr, OpenGeodeException::TYPE::data, - "[Bitsery::read] Error while reading file: ", - this->filename() ); - std::vector< RasterImage< dimension > > images; - images.emplace_back( std::move( image ) ); - return images; + "[RasterImageInput] Failed to open file: ", this->filename() ); + return read_image( content->span() ); + } + + [[nodiscard]] bool read_bytes( ByteSpan content, + std::vector< RasterImage< dimension > >& images ) final + { + images = read_image( content ); + return true; } AdditionalFiles additional_files() const final @@ -80,6 +72,21 @@ namespace geode { return Percentage{ 1 }; } + + private: + [[nodiscard]] std::vector< RasterImage< dimension > > read_image( + ByteSpan content ) const + { + RasterImage< dimension > image; + OpenGeodeImageException::check_exception( + detail::deserialize_bytes( content, image ), nullptr, + OpenGeodeException::TYPE::data, + "[Bitsery::read] Error while reading file: ", + this->filename() ); + std::vector< RasterImage< dimension > > images; + images.emplace_back( std::move( image ) ); + return images; + } }; ALIAS_1D_AND_2D_AND_3D( OpenGeodeRasterImageInput ); } // namespace geode diff --git a/include/geode/image/io/geode/geode_bitsery_raster_output.hpp b/include/geode/image/io/geode/geode_bitsery_raster_output.hpp index 4f699dac0..195f1825f 100644 --- a/include/geode/image/io/geode/geode_bitsery_raster_output.hpp +++ b/include/geode/image/io/geode/geode_bitsery_raster_output.hpp @@ -23,6 +23,7 @@ #pragma once +#include #include #include #include @@ -44,7 +45,8 @@ namespace geode std::vector< std::string > write( const RasterImage< dimension >& mesh ) const final { - std::ofstream file{ to_string( this->filename() ), + std::ofstream file{ std::filesystem::u8path( + to_string( this->filename() ) ), std::ofstream::binary }; OpenGeodeImageException::check_exception( !file.fail(), nullptr, OpenGeodeException::TYPE::data, diff --git a/include/geode/mesh/core/geode/geode_vertex_set.hpp b/include/geode/mesh/core/geode/geode_vertex_set.hpp index f1eeb19c1..239777ca5 100644 --- a/include/geode/mesh/core/geode/geode_vertex_set.hpp +++ b/include/geode/mesh/core/geode/geode_vertex_set.hpp @@ -44,7 +44,7 @@ namespace geode using Builder = OpenGeodeVertexSetBuilder; OpenGeodeVertexSet() = default; - OpenGeodeVertexSet( BITSERY ) {}; + OpenGeodeVertexSet( BITSERY bitsery ) : VertexSet{ bitsery } {}; [[nodiscard]] static MeshImpl impl_name_static() { diff --git a/include/geode/mesh/core/point_set.hpp b/include/geode/mesh/core/point_set.hpp index 0d0335cf4..fa1a68324 100644 --- a/include/geode/mesh/core/point_set.hpp +++ b/include/geode/mesh/core/point_set.hpp @@ -73,6 +73,7 @@ namespace geode protected: PointSet() = default; + explicit PointSet( BITSERY bitsery ) : VertexSet{ bitsery } {} PointSet( PointSet&& other ) noexcept = default; PointSet& operator=( PointSet&& other ) noexcept = default; diff --git a/include/geode/mesh/core/vertex_set.hpp b/include/geode/mesh/core/vertex_set.hpp index accce45f7..9fd891db2 100644 --- a/include/geode/mesh/core/vertex_set.hpp +++ b/include/geode/mesh/core/vertex_set.hpp @@ -82,6 +82,11 @@ namespace geode protected: VertexSet(); + /*! + * Nil identifier (no uuid generated), for a mesh about to be + * deserialized. + */ + explicit VertexSet( BITSERY bitsery ); VertexSet( VertexSet&& other ) noexcept; VertexSet& operator=( VertexSet&& other ) noexcept; diff --git a/include/geode/mesh/io/geode/geode_bitsery_mesh_input.hpp b/include/geode/mesh/io/geode/geode_bitsery_mesh_input.hpp index 67329ba25..a087bf572 100644 --- a/include/geode/mesh/io/geode/geode_bitsery_mesh_input.hpp +++ b/include/geode/mesh/io/geode/geode_bitsery_mesh_input.hpp @@ -24,6 +24,9 @@ #pragma once #include +#include + +#include #include @@ -35,21 +38,33 @@ [[nodiscard]] std::vector< std::unique_ptr< Mesh > > read( \ const MeshImpl& /*impl*/ ) final \ { \ - std::ifstream file{ to_string( this->filename() ), \ - std::ifstream::binary }; \ - geode::OpenGeodeMeshException::check_exception( !file.fail(), nullptr, \ - geode::OpenGeodeException::TYPE::data, \ - "[Bitsery::read] Failed to open file: ", \ - to_string( this->filename() ) ); \ - TContext context{}; \ - BitseryExtensions::register_deserialize_pcontext( \ - std::get< 0 >( context ) ); \ - Deserializer archive{ context, file }; \ + const auto content = \ + geode::detail::map_file_content( this->filename() ); \ + geode::OpenGeodeMeshException::check_exception( content.has_value(), \ + nullptr, geode::OpenGeodeException::TYPE::data, \ + "[Bitsery::read] Failed to open file: ", this->filename() ); \ + return read_mesh( content->span() ); \ + } \ + \ + [[nodiscard]] bool read_bytes( geode::ByteSpan content, \ + std::vector< std::unique_ptr< Mesh > >& meshes, \ + const MeshImpl& /*impl*/ ) final \ + { \ + meshes = read_mesh( content ); \ + return true; \ + } \ + \ +private: \ + [[nodiscard]] std::vector< std::unique_ptr< Mesh > > read_mesh( \ + geode::ByteSpan content ) const \ + { \ std::unique_ptr< Mesh > mesh{ new OpenGeode##Mesh{ \ BITSERY::constructor } }; \ + bool success{ false }; \ try \ { \ - archive.object( dynamic_cast< OpenGeode##Mesh& >( *mesh ) ); \ + success = geode::detail::deserialize_bytes( \ + content, dynamic_cast< OpenGeode##Mesh& >( *mesh ) ); \ } \ catch( const geode::OpenGeodeException& ) \ { \ @@ -62,18 +77,15 @@ "[Bitsery::read] Error while reading file: ", \ this->filename(), " (", exception.what(), ")" }; \ } \ - const auto& adapter = archive.adapter(); \ - geode::OpenGeodeMeshException::check_exception( \ - adapter.error() == bitsery::ReaderError::NoError \ - && adapter.isCompletedSuccessfully() \ - && std::get< 1 >( context ).isValid(), \ - nullptr, geode::OpenGeodeException::TYPE::internal, \ + geode::OpenGeodeMeshException::check_exception( success, nullptr, \ + geode::OpenGeodeException::TYPE::internal, \ "[Bitsery::read] Error while reading file: ", this->filename() ); \ std::vector< std::unique_ptr< Mesh > > meshes; \ meshes.emplace_back( std::move( mesh ) ); \ return meshes; \ } \ \ +public: \ index_t object_priority() const final \ { \ return 0; \ diff --git a/include/geode/mesh/io/geode/geode_bitsery_mesh_output.hpp b/include/geode/mesh/io/geode/geode_bitsery_mesh_output.hpp index c7edbb812..77b7cbb58 100644 --- a/include/geode/mesh/io/geode/geode_bitsery_mesh_output.hpp +++ b/include/geode/mesh/io/geode/geode_bitsery_mesh_output.hpp @@ -23,6 +23,7 @@ #pragma once +#include #include #include @@ -44,7 +45,8 @@ geode::OpenGeodeException::TYPE::data, "[Bitsery] Cannot save ", \ mesh.type_name().get(), " in native format because it is not ", \ OpenGeode##Mesh::impl_name_static().get() ); \ - std::ofstream file{ to_string( this->filename() ), \ + std::ofstream file{ std::filesystem::u8path( \ + to_string( this->filename() ) ), \ std::ofstream::binary }; \ geode::OpenGeodeMeshException::check_exception( !file.fail(), nullptr, \ geode::OpenGeodeException::TYPE::data, \ diff --git a/include/geode/mesh/io/geode/geode_light_regular_grid_input.hpp b/include/geode/mesh/io/geode/geode_light_regular_grid_input.hpp index 2cdc1a258..f70320df7 100644 --- a/include/geode/mesh/io/geode/geode_light_regular_grid_input.hpp +++ b/include/geode/mesh/io/geode/geode_light_regular_grid_input.hpp @@ -23,8 +23,10 @@ #pragma once +#include #include +#include #include #include @@ -55,16 +57,40 @@ namespace geode [[nodiscard]] std::vector< LightRegularGrid< dimension > > read() override { - std::ifstream file{ to_string( this->filename() ), - std::ifstream::binary }; - OpenGeodeMeshException::check_exception( !file.fail(), nullptr, - OpenGeodeException::TYPE::data, + const auto content = detail::map_file_content( this->filename() ); + OpenGeodeMeshException::check_exception( content.has_value(), + nullptr, OpenGeodeException::TYPE::data, "[LightRegularGridInput] Failed to open file: ", - to_string( this->filename() ) ); - TContext context{}; - BitseryExtensions::register_deserialize_pcontext( - std::get< 0 >( context ) ); - Deserializer archive{ context, file }; + this->filename() ); + return read_grid( content->span() ); + } + + [[nodiscard]] bool read_bytes( ByteSpan content, + std::vector< LightRegularGrid< dimension > >& grids ) override + { + grids = read_grid( content ); + return true; + } + + AdditionalFiles additional_files() const override + { + return {}; + } + + index_t object_priority() const override + { + return 0; + } + + Percentage is_loadable() const final + { + return Percentage{ 1 }; + } + + private: + [[nodiscard]] std::vector< LightRegularGrid< dimension > > read_grid( + ByteSpan content ) const + { Point< dimension > origin; std::array< index_t, dimension > cells_number; cells_number.fill( 1 ); @@ -72,9 +98,10 @@ namespace geode cells_length.fill( 1 ); LightRegularGrid< dimension > grid{ origin, cells_number, cells_length }; + bool success{ false }; try { - archive.object( grid ); + success = detail::deserialize_bytes( content, grid ); } catch( const OpenGeodeException& ) { @@ -87,33 +114,14 @@ namespace geode "[Bitsery::read] Error while reading file: ", this->filename(), " (", exception.what(), ")" }; } - const auto& adapter = archive.adapter(); - OpenGeodeMeshException::check_exception( - adapter.error() == bitsery::ReaderError::NoError - && adapter.isCompletedSuccessfully() - && std::get< 1 >( context ).isValid(), - nullptr, OpenGeodeException::TYPE::internal, + OpenGeodeMeshException::check_exception( success, nullptr, + OpenGeodeException::TYPE::internal, "[Bitsery::read] Error while reading file: ", this->filename() ); std::vector< LightRegularGrid< dimension > > grids; grids.emplace_back( std::move( grid ) ); return grids; } - - AdditionalFiles additional_files() const override - { - return {}; - } - - index_t object_priority() const override - { - return 0; - } - - Percentage is_loadable() const final - { - return Percentage{ 1 }; - } }; ALIAS_2D_AND_3D( OpenGeodeLightRegularGridInput ); } // namespace geode diff --git a/include/geode/model/mixin/builder/block_collections_builder.hpp b/include/geode/model/mixin/builder/block_collections_builder.hpp index e91badfb5..cf9b0259e 100644 --- a/include/geode/model/mixin/builder/block_collections_builder.hpp +++ b/include/geode/model/mixin/builder/block_collections_builder.hpp @@ -27,6 +27,11 @@ #include +namespace geode::detail +{ + class InputFiles; +} // namespace geode::detail + namespace geode { FORWARD_DECLARATION_DIMENSION_CLASS( BlockCollection ); @@ -43,6 +48,8 @@ namespace geode public: void load_block_collections( std::string_view directory ); + void load_block_collections( const detail::InputFiles& files ); + void set_block_collection_name( const BlockCollection< dimension >& block_collection, std::string_view name ); diff --git a/include/geode/model/mixin/builder/blocks_builder.hpp b/include/geode/model/mixin/builder/blocks_builder.hpp index de5e7bf10..5adc9744b 100644 --- a/include/geode/model/mixin/builder/blocks_builder.hpp +++ b/include/geode/model/mixin/builder/blocks_builder.hpp @@ -33,6 +33,11 @@ #include +namespace geode::detail +{ + class InputFiles; +} // namespace geode::detail + namespace geode { FORWARD_DECLARATION_DIMENSION_CLASS( Block ); @@ -51,6 +56,8 @@ namespace geode public: void load_blocks( std::string_view directory ); + void load_blocks( const detail::InputFiles& files ); + /*! * Get a pointer to the builder of a Block mesh * @param[in] Block Block component to get the builder of diff --git a/include/geode/model/mixin/builder/corner_collections_builder.hpp b/include/geode/model/mixin/builder/corner_collections_builder.hpp index d6970d356..257461b8a 100644 --- a/include/geode/model/mixin/builder/corner_collections_builder.hpp +++ b/include/geode/model/mixin/builder/corner_collections_builder.hpp @@ -27,6 +27,11 @@ #include +namespace geode::detail +{ + class InputFiles; +} // namespace geode::detail + namespace geode { FORWARD_DECLARATION_DIMENSION_CLASS( CornerCollection ); @@ -43,6 +48,8 @@ namespace geode public: void load_corner_collections( std::string_view directory ); + void load_corner_collections( const detail::InputFiles& files ); + void set_corner_collection_name( const CornerCollection< dimension >& corner_collection, std::string_view name ); diff --git a/include/geode/model/mixin/builder/corners_builder.hpp b/include/geode/model/mixin/builder/corners_builder.hpp index 68e9a2986..7a29701d3 100644 --- a/include/geode/model/mixin/builder/corners_builder.hpp +++ b/include/geode/model/mixin/builder/corners_builder.hpp @@ -32,6 +32,11 @@ #include +namespace geode::detail +{ + class InputFiles; +} // namespace geode::detail + namespace geode { FORWARD_DECLARATION_DIMENSION_CLASS( Corner ); @@ -50,6 +55,8 @@ namespace geode public: void load_corners( std::string_view directory ); + void load_corners( const detail::InputFiles& files ); + /*! * Get a pointer to the builder of a Corner mesh * @param[in] corner Corner in the model diff --git a/include/geode/model/mixin/builder/line_collections_builder.hpp b/include/geode/model/mixin/builder/line_collections_builder.hpp index 96faa9173..c90cf0da0 100644 --- a/include/geode/model/mixin/builder/line_collections_builder.hpp +++ b/include/geode/model/mixin/builder/line_collections_builder.hpp @@ -27,6 +27,11 @@ #include +namespace geode::detail +{ + class InputFiles; +} // namespace geode::detail + namespace geode { FORWARD_DECLARATION_DIMENSION_CLASS( LineCollection ); @@ -43,6 +48,8 @@ namespace geode public: void load_line_collections( std::string_view directory ); + void load_line_collections( const detail::InputFiles& files ); + void set_line_collection_name( const LineCollection< dimension >& line_collection, std::string_view name ); diff --git a/include/geode/model/mixin/builder/lines_builder.hpp b/include/geode/model/mixin/builder/lines_builder.hpp index 214e79ac1..6a3d273c4 100644 --- a/include/geode/model/mixin/builder/lines_builder.hpp +++ b/include/geode/model/mixin/builder/lines_builder.hpp @@ -32,6 +32,11 @@ #include +namespace geode::detail +{ + class InputFiles; +} // namespace geode::detail + namespace geode { FORWARD_DECLARATION_DIMENSION_CLASS( Line ); @@ -50,6 +55,8 @@ namespace geode public: void load_lines( std::string_view directory ); + void load_lines( const detail::InputFiles& files ); + /*! * Get a pointer to the builder of a Line mesh * @param[in] line Line component to get the builder of diff --git a/include/geode/model/mixin/builder/model_boundaries_builder.hpp b/include/geode/model/mixin/builder/model_boundaries_builder.hpp index 00ef7d9d1..0a4b468c6 100644 --- a/include/geode/model/mixin/builder/model_boundaries_builder.hpp +++ b/include/geode/model/mixin/builder/model_boundaries_builder.hpp @@ -27,6 +27,11 @@ #include +namespace geode::detail +{ + class InputFiles; +} // namespace geode::detail + namespace geode { FORWARD_DECLARATION_DIMENSION_CLASS( ModelBoundary ); @@ -43,6 +48,8 @@ namespace geode public: void load_model_boundaries( std::string_view directory ); + void load_model_boundaries( const detail::InputFiles& files ); + void set_model_boundary_name( const ModelBoundary< dimension >& id, std::string_view name ); diff --git a/include/geode/model/mixin/builder/physical_properties_builder.hpp b/include/geode/model/mixin/builder/physical_properties_builder.hpp index dfa201fbd..d77dd6659 100644 --- a/include/geode/model/mixin/builder/physical_properties_builder.hpp +++ b/include/geode/model/mixin/builder/physical_properties_builder.hpp @@ -28,6 +28,11 @@ #include #include +namespace geode::detail +{ + class InputFiles; +} // namespace geode::detail + namespace geode { struct uuid; @@ -60,6 +65,8 @@ namespace geode void load_physical_properties( std::string_view directory ); + void load_physical_properties( const detail::InputFiles& files ); + private: PhysicalProperties& physical_properties_; }; diff --git a/include/geode/model/mixin/builder/relationships_builder.hpp b/include/geode/model/mixin/builder/relationships_builder.hpp index 5d8c447ef..2c3b9d4f7 100644 --- a/include/geode/model/mixin/builder/relationships_builder.hpp +++ b/include/geode/model/mixin/builder/relationships_builder.hpp @@ -26,6 +26,11 @@ #include #include +namespace geode::detail +{ + class InputFiles; +} // namespace geode::detail + namespace geode { /*! @@ -81,6 +86,8 @@ namespace geode void load_relationships( std::string_view directory ); + void load_relationships( const detail::InputFiles& files ); + private: Relationships& relationships_; }; diff --git a/include/geode/model/mixin/builder/surface_collections_builder.hpp b/include/geode/model/mixin/builder/surface_collections_builder.hpp index 681fc6c6c..38c98a227 100644 --- a/include/geode/model/mixin/builder/surface_collections_builder.hpp +++ b/include/geode/model/mixin/builder/surface_collections_builder.hpp @@ -27,6 +27,11 @@ #include +namespace geode::detail +{ + class InputFiles; +} // namespace geode::detail + namespace geode { FORWARD_DECLARATION_DIMENSION_CLASS( SurfaceCollection ); @@ -43,6 +48,8 @@ namespace geode public: void load_surface_collections( std::string_view directory ); + void load_surface_collections( const detail::InputFiles& files ); + void set_surface_collection_name( const SurfaceCollection< dimension >& surface_collection, std::string_view name ); diff --git a/include/geode/model/mixin/builder/surfaces_builder.hpp b/include/geode/model/mixin/builder/surfaces_builder.hpp index 63d131b3b..8b2f3e02d 100644 --- a/include/geode/model/mixin/builder/surfaces_builder.hpp +++ b/include/geode/model/mixin/builder/surfaces_builder.hpp @@ -33,6 +33,11 @@ #include +namespace geode::detail +{ + class InputFiles; +} // namespace geode::detail + namespace geode { FORWARD_DECLARATION_DIMENSION_CLASS( Surface ); @@ -51,6 +56,8 @@ namespace geode public: void load_surfaces( std::string_view directory ); + void load_surfaces( const detail::InputFiles& files ); + /*! * Get a pointer to the builder of a Surface mesh * @param[in] surface Surface component to get the builder of diff --git a/include/geode/model/mixin/builder/vertex_identifier_builder.hpp b/include/geode/model/mixin/builder/vertex_identifier_builder.hpp index d88540af8..fdda4544d 100644 --- a/include/geode/model/mixin/builder/vertex_identifier_builder.hpp +++ b/include/geode/model/mixin/builder/vertex_identifier_builder.hpp @@ -28,6 +28,11 @@ #include #include +namespace geode::detail +{ + class InputFiles; +} // namespace geode::detail + namespace geode { /*! @@ -107,20 +112,29 @@ namespace geode /*! * Load the VertexIdentifier from a file. + * Files saved by the current version do not store the component + * vertices: they are rebuilt by repair_component_vertices once the + * mesh components are loaded. * @param[in] directory Folder containing the file that stores * VertexIdentifier information. */ void load_unique_vertices( std::string_view directory ); + void load_unique_vertices( const detail::InputFiles& files ); + /*! * Delete all unique vertices not associated with any component */ std::vector< index_t > delete_isolated_vertices(); /*! - * Remove component vertices referencing an unregistered component or - * an invalid vertex, and restore missing links from component vertices - * to their unique vertex. Used after loading a model. + * Used after loading a model, once its mesh components are loaded. + * Rebuild the component vertices from the component mesh attributes + * if the file does not store them (components in their registration + * order, then vertices in increasing order), otherwise remove + * component vertices referencing an unregistered component or an + * invalid vertex, and restore missing links from component vertices + * to their unique vertex. */ void repair_component_vertices(); diff --git a/include/geode/model/mixin/core/block_collections.hpp b/include/geode/model/mixin/core/block_collections.hpp index 49cd9addc..65fefe449 100644 --- a/include/geode/model/mixin/core/block_collections.hpp +++ b/include/geode/model/mixin/core/block_collections.hpp @@ -29,6 +29,11 @@ #include #include +namespace geode::detail +{ + class InputFiles; +} // namespace geode::detail + namespace geode { FORWARD_DECLARATION_DIMENSION_CLASS( BlockCollection ); @@ -156,7 +161,7 @@ namespace geode BlockCollectionsBuilderKey key ); void load_block_collections( - std::string_view directory, BlockCollectionsBuilderKey key ); + const detail::InputFiles& files, BlockCollectionsBuilderKey key ); [[nodiscard]] ModifiableBlockCollectionRange modifiable_block_collections( BlockCollectionsBuilderKey key ); diff --git a/include/geode/model/mixin/core/blocks.hpp b/include/geode/model/mixin/core/blocks.hpp index ded38a484..43ab93b47 100644 --- a/include/geode/model/mixin/core/blocks.hpp +++ b/include/geode/model/mixin/core/blocks.hpp @@ -31,6 +31,11 @@ #include #include +namespace geode::detail +{ + class InputFiles; +} // namespace geode::detail + namespace geode { FORWARD_DECLARATION_DIMENSION_CLASS( Block ); @@ -170,7 +175,8 @@ namespace geode void delete_block( const Block< dimension >& block, BlocksBuilderKey key ); - void load_blocks( std::string_view directory, BlocksBuilderKey key ); + void load_blocks( + const detail::InputFiles& files, BlocksBuilderKey key ); [[nodiscard]] ModifiableBlockRange modifiable_blocks( BlocksBuilderKey key ); diff --git a/include/geode/model/mixin/core/component_type.hpp b/include/geode/model/mixin/core/component_type.hpp index 7805b57f7..c51e4a068 100644 --- a/include/geode/model/mixin/core/component_type.hpp +++ b/include/geode/model/mixin/core/component_type.hpp @@ -48,6 +48,15 @@ namespace geode { ComponentID() : ComponentID( ComponentType{ "undefined" }, uuid{} ) {} + /*! + * Undefined type and nil uuid, without generating a new identifier: + * for a ComponentID about to be overwritten by deserialization. + */ + explicit ComponentID( BITSERY bitsery ) + : ComponentID( ComponentType{ "undefined" }, uuid{ bitsery } ) + { + } + ComponentID( ComponentType component_type, uuid input_id ) : type{ std::move( component_type ) }, id{ std::move( input_id ) } {}; @@ -101,6 +110,15 @@ namespace geode } // namespace geode +namespace bitsery +{ + template <> + inline geode::ComponentID Access::create< geode::ComponentID >() + { + return geode::ComponentID{ geode::BITSERY::constructor }; + } +} // namespace bitsery + namespace std { template <> diff --git a/include/geode/model/mixin/core/corner_collections.hpp b/include/geode/model/mixin/core/corner_collections.hpp index 49b35be5f..143203b35 100644 --- a/include/geode/model/mixin/core/corner_collections.hpp +++ b/include/geode/model/mixin/core/corner_collections.hpp @@ -31,6 +31,11 @@ #include #include +namespace geode::detail +{ + class InputFiles; +} // namespace geode::detail + namespace geode { FORWARD_DECLARATION_DIMENSION_CLASS( CornerCollection ); @@ -159,7 +164,7 @@ namespace geode CornerCollectionsBuilderKey key ); void load_corner_collections( - std::string_view directory, CornerCollectionsBuilderKey key ); + const detail::InputFiles& files, CornerCollectionsBuilderKey key ); [[nodiscard]] ModifiableCornerCollectionRange modifiable_corner_collections( CornerCollectionsBuilderKey key ); diff --git a/include/geode/model/mixin/core/corners.hpp b/include/geode/model/mixin/core/corners.hpp index a2aa8ce52..e3ad3c87b 100644 --- a/include/geode/model/mixin/core/corners.hpp +++ b/include/geode/model/mixin/core/corners.hpp @@ -31,6 +31,11 @@ #include #include +namespace geode::detail +{ + class InputFiles; +} // namespace geode::detail + namespace geode { FORWARD_DECLARATION_DIMENSION_CLASS( Corner ); @@ -169,7 +174,8 @@ namespace geode void delete_corner( const Corner< dimension >& corner, CornersBuilderKey key ); - void load_corners( std::string_view directory, CornersBuilderKey key ); + void load_corners( + const detail::InputFiles& files, CornersBuilderKey key ); [[nodiscard]] ModifiableCornerRange modifiable_corners( CornersBuilderKey key ); diff --git a/include/geode/model/mixin/core/detail/components_storage.hpp b/include/geode/model/mixin/core/detail/components_storage.hpp index 78ac4af53..1a3184219 100644 --- a/include/geode/model/mixin/core/detail/components_storage.hpp +++ b/include/geode/model/mixin/core/detail/components_storage.hpp @@ -34,7 +34,10 @@ #include #include +#include +#include #include +#include #include #include @@ -87,6 +90,31 @@ namespace geode::detail MeshFactory::default_impl( fallback_type ) ); } + /*! + * Load the single mesh of a component file of the input files, with the + * input of the given factory registered for its extension. + */ + template < typename Factory > + [[nodiscard]] typename Factory::BaseClass::InputData load_component_mesh( + const InputFiles& files, std::string_view name, const MeshImpl& impl ) + { + const auto& type = MeshFactory::type( impl ).get(); + try + { + return load_one( geode_object_input_from_files< Factory >( + type, files, name, impl ), + files.location( name ) ); + } + catch( const std::exception& exception ) + { + Logger::error( exception.what() ); + throw OpenGeodeModelException{ nullptr, + OpenGeodeException::TYPE::data, "Cannot load ", type, + " from file: ", files.location( name ), ": ", + exception.what() }; + } + } + template < typename Component > class ComponentsStorage { @@ -168,56 +196,53 @@ namespace geode::detail } /*! - * Load the components stored in the given file. + * Load the components stored in the given file of the input files. * @param[in] required If false, a missing file is expected (e.g. for * files written before this component type existed) and silently * ignored. Otherwise a warning is emitted. */ - void load_components( std::string_view filename, bool required = true ) + void load_components( + const InputFiles& files, std::string_view name, bool required ) { - const auto path = std::filesystem::u8path( to_string( filename ) ); - if( !std::filesystem::exists( path ) ) + if( !files.has( name ) ) { if( required ) { Logger::warning( "[ComponentsStorage::load_components] " "Missing file: ", - filename, ", no component loaded from it" ); + files.location( name ), + ", no component loaded from it" ); } return; } - std::ifstream file{ path, std::ifstream::binary }; - TContext context{}; - BitseryExtensions::register_deserialize_pcontext( - std::get< 0 >( context ) ); - Deserializer archive{ context, file }; - archive.object( *this ); - const auto& adapter = archive.adapter(); + const auto location = files.location( name ); + const auto content = files.content( name ); OpenGeodeModelException::check_exception( - adapter.error() == bitsery::ReaderError::NoError - && adapter.isCompletedSuccessfully() - && std::get< 1 >( context ).isValid(), - nullptr, OpenGeodeException::TYPE::internal, + detail::deserialize_bytes( content.span(), *this ), nullptr, + OpenGeodeException::TYPE::internal, "[ComponentsStorage::load_components] Error while reading " "file: ", - filename ); - repair_loaded_components( filename ); + location ); + repair_loaded_components( location ); } + /*! + * Map the uuid ending the name of each file (before its extension) + * to the file name. + */ [[nodiscard]] absl::flat_hash_map< std::string, std::string > - file_mapping( std::string_view directory ) const + file_mapping( const InputFiles& files ) const { absl::flat_hash_map< std::string, std::string > mapping; - for( const auto& file : std::filesystem::directory_iterator( - std::filesystem::u8path( to_string( directory ) ) ) ) + for( auto& name : files.names() ) { - auto path = file.path(); - auto filename = path.replace_extension( "" ).u8string(); - if( filename.size() > 36 ) + const auto stem = std::filesystem::u8path( name ) + .replace_extension( "" ) + .u8string(); + if( stem.size() > 36 ) { - auto uuid = filename.substr( filename.size() - 36 ); mapping.emplace( - std::move( uuid ), file.path().u8string() ); + stem.substr( stem.size() - 36 ), std::move( name ) ); } } return mapping; diff --git a/include/geode/model/mixin/core/line_collections.hpp b/include/geode/model/mixin/core/line_collections.hpp index c66d8b5c6..a6ac349e4 100644 --- a/include/geode/model/mixin/core/line_collections.hpp +++ b/include/geode/model/mixin/core/line_collections.hpp @@ -31,6 +31,11 @@ #include #include +namespace geode::detail +{ + class InputFiles; +} // namespace geode::detail + namespace geode { FORWARD_DECLARATION_DIMENSION_CLASS( LineCollection ); @@ -155,7 +160,7 @@ namespace geode LineCollectionsBuilderKey key ); void load_line_collections( - std::string_view directory, LineCollectionsBuilderKey key ); + const detail::InputFiles& files, LineCollectionsBuilderKey key ); [[nodiscard]] ModifiableLineCollectionRange modifiable_line_collections( LineCollectionsBuilderKey key ); diff --git a/include/geode/model/mixin/core/lines.hpp b/include/geode/model/mixin/core/lines.hpp index 81344e7bc..67c6efaef 100644 --- a/include/geode/model/mixin/core/lines.hpp +++ b/include/geode/model/mixin/core/lines.hpp @@ -31,6 +31,11 @@ #include #include +namespace geode::detail +{ + class InputFiles; +} // namespace geode::detail + namespace geode { FORWARD_DECLARATION_DIMENSION_CLASS( Line ); @@ -152,7 +157,7 @@ namespace geode void delete_line( const Line< dimension >& line, LinesBuilderKey key ); - void load_lines( std::string_view directory, LinesBuilderKey key ); + void load_lines( const detail::InputFiles& files, LinesBuilderKey key ); [[nodiscard]] ModifiableLineRange modifiable_lines( LinesBuilderKey key ); diff --git a/include/geode/model/mixin/core/model_boundaries.hpp b/include/geode/model/mixin/core/model_boundaries.hpp index 7ea024013..1236660bc 100644 --- a/include/geode/model/mixin/core/model_boundaries.hpp +++ b/include/geode/model/mixin/core/model_boundaries.hpp @@ -31,6 +31,11 @@ #include #include +namespace geode::detail +{ + class InputFiles; +} // namespace geode::detail + namespace geode { FORWARD_DECLARATION_DIMENSION_CLASS( ModelBoundary ); @@ -154,7 +159,7 @@ namespace geode ModelBoundariesBuilderKey key ); void load_model_boundaries( - std::string_view directory, ModelBoundariesBuilderKey key ); + const detail::InputFiles& files, ModelBoundariesBuilderKey key ); [[nodiscard]] ModifiableModelBoundaryRange modifiable_model_boundaries( ModelBoundariesBuilderKey key ); diff --git a/include/geode/model/mixin/core/physical_properties.hpp b/include/geode/model/mixin/core/physical_properties.hpp index b82aa7e72..ebd2ef2c8 100644 --- a/include/geode/model/mixin/core/physical_properties.hpp +++ b/include/geode/model/mixin/core/physical_properties.hpp @@ -34,6 +34,11 @@ #include #include +namespace geode::detail +{ + class InputFiles; +} // namespace geode::detail + namespace geode { class PhysicalPropertiesBuilder; @@ -119,7 +124,7 @@ namespace geode const PhysicalProperties& other, BuilderKey /*key*/ ); void load_physical_properties( - std::string_view directory, BuilderKey /*key*/ ); + const detail::InputFiles& files, BuilderKey /*key*/ ); protected: PhysicalProperties( PhysicalProperties&& other ) noexcept; diff --git a/include/geode/model/mixin/core/relationships.hpp b/include/geode/model/mixin/core/relationships.hpp index 094ffcea5..88b834b39 100644 --- a/include/geode/model/mixin/core/relationships.hpp +++ b/include/geode/model/mixin/core/relationships.hpp @@ -35,6 +35,11 @@ #include #include +namespace geode::detail +{ + class InputFiles; +} // namespace geode::detail + namespace geode { class AttributeManager; @@ -489,7 +494,7 @@ namespace geode RelationshipsBuilderKey /*key*/ ); void load_relationships( - std::string_view directory, RelationshipsBuilderKey /*key*/ ); + const detail::InputFiles& files, RelationshipsBuilderKey /*key*/ ); protected: Relationships( Relationships&& other ) noexcept; diff --git a/include/geode/model/mixin/core/surface_collections.hpp b/include/geode/model/mixin/core/surface_collections.hpp index 77950340b..b5ac9fd0f 100644 --- a/include/geode/model/mixin/core/surface_collections.hpp +++ b/include/geode/model/mixin/core/surface_collections.hpp @@ -31,6 +31,11 @@ #include #include +namespace geode::detail +{ + class InputFiles; +} // namespace geode::detail + namespace geode { FORWARD_DECLARATION_DIMENSION_CLASS( SurfaceCollection ); @@ -161,7 +166,7 @@ namespace geode SurfaceCollectionsBuilderKey key ); void load_surface_collections( - std::string_view directory, SurfaceCollectionsBuilderKey key ); + const detail::InputFiles& files, SurfaceCollectionsBuilderKey key ); [[nodiscard]] ModifiableSurfaceCollectionRange modifiable_surface_collections( SurfaceCollectionsBuilderKey key ); diff --git a/include/geode/model/mixin/core/surfaces.hpp b/include/geode/model/mixin/core/surfaces.hpp index dbaca2c4d..92e459f92 100644 --- a/include/geode/model/mixin/core/surfaces.hpp +++ b/include/geode/model/mixin/core/surfaces.hpp @@ -31,6 +31,11 @@ #include #include +namespace geode::detail +{ + class InputFiles; +} // namespace geode::detail + namespace geode { FORWARD_DECLARATION_DIMENSION_CLASS( Surface ); @@ -156,7 +161,7 @@ namespace geode const Surface< dimension >& surface, SurfacesBuilderKey key ); void load_surfaces( - std::string_view directory, SurfacesBuilderKey key ); + const detail::InputFiles& files, SurfacesBuilderKey key ); [[nodiscard]] ModifiableSurfaceRange modifiable_surfaces( SurfacesBuilderKey key ); diff --git a/include/geode/model/mixin/core/vertex_identifier.hpp b/include/geode/model/mixin/core/vertex_identifier.hpp index 226b9d5f5..884c1b105 100644 --- a/include/geode/model/mixin/core/vertex_identifier.hpp +++ b/include/geode/model/mixin/core/vertex_identifier.hpp @@ -35,6 +35,11 @@ #include #include +namespace geode::detail +{ + class InputFiles; +} // namespace geode::detail + namespace geode { struct MeshVertex; @@ -103,6 +108,10 @@ namespace geode /*! * Return the component vertices identified with an unique vertex. + * The order is the insertion order; after loading a file, it is the + * order of the rebuild done by repair_component_vertices (components + * in their registration order, then vertices in increasing order), + * which can differ from the order before saving. * @param[in] unique_vertex_id Indice of the unique vertex. */ [[nodiscard]] const std::vector< ComponentMeshVertex >& @@ -130,6 +139,10 @@ namespace geode /*! * Save the VertexIdentifier into a file. + * The file stores the number of unique vertices and the identifier of + * the "unique vertices" attribute of the component meshes, not the + * component vertices: these are rebuilt from the component mesh + * attributes when loading (see repair_component_vertices). * @param[in] directory Folder in which create the file. */ void save_unique_vertices( std::string_view directory ) const; @@ -203,11 +216,15 @@ namespace geode /*! * Load the VertexIdentifier from a file. + * Files saved by the current version do not store the component + * vertices: unique vertices are isolated until the mesh components + * are loaded (load_mesh_component) and repair_component_vertices + * rebuilds the component vertices. Older files store them. * @param[in] directory Folder containing the file that stores * VertexIdentifier information. */ void load_unique_vertices( - std::string_view directory, BuilderKey /*key*/ ); + const detail::InputFiles& files, BuilderKey /*key*/ ); /*! * Delete all unique vertices not associated with any component @@ -215,9 +232,14 @@ namespace geode std::vector< index_t > delete_isolated_vertices( BuilderKey /*key*/ ); /*! - * Remove component vertices referencing an unregistered component or - * an invalid vertex, and restore missing links from component vertices - * to their unique vertex. Used after loading a model. + * Used after loading a model, once its mesh components are loaded. + * If the loaded file does not store the component vertices, rebuild + * them from the component mesh attributes: components in their + * registration order, then their vertices in increasing order. + * Attribute values out of the unique vertex range are removed. + * Otherwise, remove component vertices referencing an unregistered + * component or an invalid vertex, and restore missing links from + * component vertices to their unique vertex. */ void repair_component_vertices( BuilderKey /*key*/ ); diff --git a/include/geode/model/representation/io/geode/geode_brep_input.hpp b/include/geode/model/representation/io/geode/geode_brep_input.hpp index 5b5e8668e..1bfdd1b5c 100644 --- a/include/geode/model/representation/io/geode/geode_brep_input.hpp +++ b/include/geode/model/representation/io/geode/geode_brep_input.hpp @@ -25,6 +25,8 @@ #include +#include + #include #include #include @@ -66,52 +68,56 @@ namespace geode namespace detail { + /*! + * Load the files of a BRep (identifier, components, meshes, + * relationships, unique vertices) into an empty model. + */ template < typename Model > - void load_brep_files( Model& brep, std::string_view directory ) + void load_brep_files( Model& brep, const detail::InputFiles& files ) { BRepBuilder builder{ brep }; const detail::ScopedLoggerLevel scoped_level{ Logger::LEVEL::warning }; async::parallel_invoke( - [&builder, &directory] { - builder.load_identifier( directory ); + [&builder, &files] { + builder.load_identifier( files ); }, - [&builder, &directory] { - builder.load_physical_properties( directory ); + [&builder, &files] { + builder.load_physical_properties( files ); }, - [&builder, &directory] { - builder.load_corners( directory ); + [&builder, &files] { + builder.load_corners( files ); }, - [&builder, &directory] { - builder.load_lines( directory ); + [&builder, &files] { + builder.load_lines( files ); }, - [&builder, &directory] { - builder.load_surfaces( directory ); + [&builder, &files] { + builder.load_surfaces( files ); }, - [&builder, &directory] { - builder.load_blocks( directory ); + [&builder, &files] { + builder.load_blocks( files ); }, - [&builder, &directory] { - builder.load_model_boundaries( directory ); + [&builder, &files] { + builder.load_model_boundaries( files ); }, - [&builder, &directory] { - builder.load_corner_collections( directory ); + [&builder, &files] { + builder.load_corner_collections( files ); }, - [&builder, &directory] { - builder.load_line_collections( directory ); + [&builder, &files] { + builder.load_line_collections( files ); }, - [&builder, &directory] { - builder.load_surface_collections( directory ); + [&builder, &files] { + builder.load_surface_collections( files ); }, - [&builder, &directory] { - builder.load_block_collections( directory ); + [&builder, &files] { + builder.load_block_collections( files ); }, - [&builder, &directory] { - builder.load_relationships( directory ); + [&builder, &files] { + builder.load_relationships( files ); }, - [&builder, &directory] { - builder.load_unique_vertices( directory ); + [&builder, &files] { + builder.load_unique_vertices( files ); } ); detail::register_all_components( brep ); detail::filter_unsupported_components( brep ); diff --git a/include/geode/model/representation/io/geode/geode_section_input.hpp b/include/geode/model/representation/io/geode/geode_section_input.hpp index 00b8572d5..699e76388 100644 --- a/include/geode/model/representation/io/geode/geode_section_input.hpp +++ b/include/geode/model/representation/io/geode/geode_section_input.hpp @@ -25,6 +25,8 @@ #include +#include + #include #include #include @@ -66,43 +68,48 @@ namespace geode namespace detail { + /*! + * Load the files of a Section (identifier, components, meshes, + * relationships, unique vertices) into an empty model. + */ template < typename Model > - void load_section_files( Model& section, std::string_view directory ) + void load_section_files( + Model& section, const detail::InputFiles& files ) { SectionBuilder builder{ section }; const detail::ScopedLoggerLevel scoped_level{ Logger::LEVEL::warning }; async::parallel_invoke( - [&builder, &directory] { - builder.load_identifier( directory ); + [&builder, &files] { + builder.load_identifier( files ); }, - [&builder, &directory] { - builder.load_corners( directory ); + [&builder, &files] { + builder.load_corners( files ); }, - [&builder, &directory] { - builder.load_lines( directory ); + [&builder, &files] { + builder.load_lines( files ); }, - [&builder, &directory] { - builder.load_surfaces( directory ); + [&builder, &files] { + builder.load_surfaces( files ); }, - [&builder, &directory] { - builder.load_model_boundaries( directory ); + [&builder, &files] { + builder.load_model_boundaries( files ); }, - [&builder, &directory] { - builder.load_corner_collections( directory ); + [&builder, &files] { + builder.load_corner_collections( files ); }, - [&builder, &directory] { - builder.load_line_collections( directory ); + [&builder, &files] { + builder.load_line_collections( files ); }, - [&builder, &directory] { - builder.load_surface_collections( directory ); + [&builder, &files] { + builder.load_surface_collections( files ); }, - [&builder, &directory] { - builder.load_relationships( directory ); + [&builder, &files] { + builder.load_relationships( files ); }, - [&builder, &directory] { - builder.load_unique_vertices( directory ); + [&builder, &files] { + builder.load_unique_vertices( files ); } ); detail::register_all_components( section ); detail::filter_unsupported_components( section ); diff --git a/src/geode/basic/CMakeLists.txt b/src/geode/basic/CMakeLists.txt index 021ddaaaf..0e75ff62e 100644 --- a/src/geode/basic/CMakeLists.txt +++ b/src/geode/basic/CMakeLists.txt @@ -33,10 +33,12 @@ add_geode_library( "console_logger_client.cpp" "console_progress_logger_client.cpp" "file.cpp" + "file_content.cpp" "file_logger_client.cpp" "filename.cpp" "identifier.cpp" "identifier_builder.cpp" + "input_files.cpp" "library.cpp" "logger.cpp" "logger_manager.cpp" @@ -58,6 +60,7 @@ add_geode_library( "attribute.hpp" "bitsery_archive.hpp" "bitsery_attribute.hpp" + "byte_span.hpp" "cell_array.hpp" "chronometer.hpp" "common.hpp" @@ -103,8 +106,10 @@ add_geode_library( "detail/count_range_elements.hpp" "detail/disable_debug_logger.hpp" "detail/enable_debug_logger.hpp" + "detail/file_content.hpp" "detail/geode_input_impl.hpp" "detail/geode_output_impl.hpp" + "detail/input_files.hpp" INTERNAL_HEADERS "internal/array_impl.hpp" PUBLIC_DEPENDENCIES @@ -120,7 +125,19 @@ add_geode_library( absl::time spdlog::spdlog_header_only MINIZIP::minizip-ng + ZLIB::ZLIB ) if(WIN32 AND BUILD_SHARED_LIBS) target_link_libraries(basic PUBLIC absl::abseil_dll) +endif() +if(UNIX AND NOT APPLE AND BUILD_SHARED_LIBS) + # Keep the static zlib-ng and minizip-ng private: exported, they would + # interpose the zlib of the process (or be interposed by it) + include(CheckLinkerFlag) + check_linker_flag(CXX "-Wl,--exclude-libs,ALL" GEODE_LINKER_EXCLUDE_LIBS) + if(GEODE_LINKER_EXCLUDE_LIBS) + target_link_options(basic PRIVATE + "-Wl,--exclude-libs,$:$" + ) + endif() endif() \ No newline at end of file diff --git a/src/geode/basic/file_content.cpp b/src/geode/basic/file_content.cpp new file mode 100644 index 000000000..159f793e3 --- /dev/null +++ b/src/geode/basic/file_content.cpp @@ -0,0 +1,300 @@ +/* + * Copyright (c) 2019 - 2026 Geode-solutions + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * + */ + +#include + +#include +#include + +#ifdef _WIN32 +# ifndef NOMINMAX +# define NOMINMAX +# endif +# ifndef WIN32_LEAN_AND_MEAN +# define WIN32_LEAN_AND_MEAN +# endif +# include +#else +# include +# include +# include +# include +#endif + +#include + +namespace +{ + std::filesystem::path to_path( std::string_view utf8_path ) + { + return std::filesystem::u8path( utf8_path.begin(), utf8_path.end() ); + } + + size_t page_size() + { +#ifdef _WIN32 + SYSTEM_INFO info; + GetSystemInfo( &info ); + return static_cast< size_t >( info.dwPageSize ); +#else + return static_cast< size_t >( sysconf( _SC_PAGESIZE ) ); +#endif + } + + struct MappedBytes + { + const char* data{ nullptr }; + size_t size{ 0 }; + bool mapped{ false }; + }; + +#ifdef _WIN32 + MappedBytes map_bytes( const std::filesystem::path& path ) + { + const auto file = + CreateFileW( path.wstring().c_str(), GENERIC_READ, FILE_SHARE_READ, + nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr ); + if( file == INVALID_HANDLE_VALUE ) + { + return {}; + } + MappedBytes result; + LARGE_INTEGER size; + if( GetFileType( file ) == FILE_TYPE_DISK + && GetFileSizeEx( file, &size ) && size.QuadPart >= 0 ) + { + if( size.QuadPart == 0 ) + { + result.mapped = true; + } + else if( const auto mapping = CreateFileMappingW( + file, nullptr, PAGE_READONLY, 0, 0, nullptr ) ) + { + if( const auto* view = + MapViewOfFile( mapping, FILE_MAP_READ, 0, 0, 0 ) ) + { + result.data = static_cast< const char* >( view ); + result.size = static_cast< size_t >( size.QuadPart ); + result.mapped = true; + } + CloseHandle( mapping ); + } + } + CloseHandle( file ); + return result; + } + + void unmap_bytes( const char* data, size_t /*size*/ ) + { + UnmapViewOfFile( data ); + } + + void release_pages( const char* data, size_t size ) + { + // Unlocking pages that are not locked removes them from the working + // set + VirtualUnlock( const_cast< char* >( data ), size ); + } +#else + MappedBytes map_bytes( const std::filesystem::path& path ) + { + const auto file = open( path.c_str(), O_RDONLY | O_CLOEXEC ); + if( file < 0 ) + { + return {}; + } + MappedBytes result; + struct stat status; + if( fstat( file, &status ) == 0 && S_ISREG( status.st_mode ) + && status.st_size >= 0 ) + { + if( status.st_size == 0 ) + { + result.mapped = true; + } + else + { + const auto size = static_cast< size_t >( status.st_size ); + auto* data = + mmap( nullptr, size, PROT_READ, MAP_PRIVATE, file, 0 ); + if( data != MAP_FAILED ) + { + result.data = static_cast< const char* >( data ); + result.size = size; + result.mapped = true; + } + } + } + close( file ); + return result; + } + + void unmap_bytes( const char* data, size_t size ) + { + munmap( const_cast< char* >( data ), size ); + } + + void release_pages( const char* data, size_t size ) + { + // Read-only file mapping: the pages are read again from the file if + // accessed + madvise( const_cast< char* >( data ), size, MADV_DONTNEED ); + } +#endif + + /*! + * Read the whole content of a regular file (UTF-8 path) into memory. + * @return std::nullopt if the file cannot be opened or is not a regular + * file. + * @exception OpenGeodeException (data) if the file cannot be read. + */ + std::optional< geode::detail::ByteBuffer > read_file_content( + std::string_view filename ) + { + const auto path = to_path( filename ); + std::error_code error; + if( !std::filesystem::is_regular_file( path, error ) ) + { + return std::nullopt; + } + std::ifstream file{ path, std::ifstream::binary | std::ifstream::ate }; + if( !file ) + { + return std::nullopt; + } + const auto end = file.tellg(); + geode::OpenGeodeBasicException::check_exception( end >= 0, nullptr, + geode::OpenGeodeException::TYPE::data, + "[read_file_content] Cannot read file: ", filename ); + geode::detail::ByteBuffer buffer{ static_cast< size_t >( end ) }; + file.seekg( 0 ); + file.read( + buffer.data(), static_cast< std::streamsize >( buffer.size() ) ); + geode::OpenGeodeBasicException::check_exception( + file.gcount() == static_cast< std::streamsize >( buffer.size() ), + nullptr, geode::OpenGeodeException::TYPE::data, + "[read_file_content] Cannot read file: ", filename ); + return buffer; + } +} // namespace + +namespace geode +{ + namespace detail + { + std::shared_ptr< const MappedFile > MappedFile::map( + std::string_view filename ) + { + const auto bytes = map_bytes( to_path( filename ) ); + if( !bytes.mapped ) + { + return nullptr; + } + return std::shared_ptr< const MappedFile >{ new MappedFile{ + bytes.data, bytes.size } }; + } + + MappedFile::MappedFile( const char* data, size_t size ) + : data_{ data }, size_{ size } + { + } + + MappedFile::~MappedFile() + { + if( data_ != nullptr ) + { + unmap_bytes( data_, size_ ); + } + } + + ByteSpan MappedFile::span() const + { + return { data_, size_ }; + } + + void MappedFile::release( ByteSpan bytes ) const + { + if( bytes.empty() || data_ == nullptr ) + { + return; + } + static const auto page = page_size(); + const auto begin_offset = + static_cast< size_t >( bytes.data() - data_ ); + const auto end_offset = begin_offset + bytes.size(); + const auto first_page = ( begin_offset + page - 1 ) / page * page; + const auto last_page = end_offset / page * page; + if( first_page >= last_page ) + { + return; + } + release_pages( data_ + first_page, last_page - first_page ); + } + + FileContent::FileContent( ByteBuffer buffer ) + : buffer_{ std::move( buffer ) }, bytes_{ buffer_->span() } + { + } + + FileContent::FileContent( + std::shared_ptr< const MappedFile > mapping, ByteSpan bytes ) + : mapping_{ std::move( mapping ) }, bytes_{ bytes } + { + } + + FileContent::FileContent( FileContent&& other ) noexcept + : mapping_{ std::move( other.mapping_ ) }, + buffer_{ std::move( other.buffer_ ) }, + bytes_{ other.bytes_ } + { + other.mapping_.reset(); + other.buffer_.reset(); + other.bytes_ = {}; + } + + FileContent::~FileContent() + { + if( mapping_ ) + { + mapping_->release( bytes_ ); + } + } + + std::optional< FileContent > map_file_content( + std::string_view filename ) + { + if( auto mapping = MappedFile::map( filename ) ) + { + const auto bytes = mapping->span(); + return FileContent{ std::move( mapping ), bytes }; + } + Logger::debug( "[map_file_content] Cannot map file ", filename, + ", reading it" ); + if( auto buffer = read_file_content( filename ) ) + { + return FileContent{ std::move( *buffer ) }; + } + return std::nullopt; + } + } // namespace detail +} // namespace geode diff --git a/src/geode/basic/identifier.cpp b/src/geode/basic/identifier.cpp index 496cd02b9..48365f5c7 100644 --- a/src/geode/basic/identifier.cpp +++ b/src/geode/basic/identifier.cpp @@ -29,6 +29,7 @@ #include #include +#include #include #include @@ -37,6 +38,10 @@ namespace geode class Identifier::Impl { public: + Impl() = default; + + explicit Impl( BITSERY bitsery ) : id_{ bitsery } {} + const uuid& id() const { return id_; @@ -77,27 +82,19 @@ namespace geode "[Identifier::save] Error while writing file: ", filename ); } - void load( std::string_view directory ) + void load( const detail::InputFiles& files ) { - const auto filename = absl::StrCat( directory, "/identifier" ); - std::ifstream file{ std::filesystem::u8path( filename ), - std::ifstream::binary }; - if( !file ) + static constexpr auto FILENAME = "identifier"; + if( !files.has( FILENAME ) ) { return; } - TContext context{}; - BitseryExtensions::register_deserialize_pcontext( - std::get< 0 >( context ) ); - Deserializer archive{ context, file }; - archive.object( *this ); - const auto& adapter = archive.adapter(); + const auto content = files.content( FILENAME ); OpenGeodeBasicException::check_exception( - adapter.error() == bitsery::ReaderError::NoError - && adapter.isCompletedSuccessfully() - && std::get< 1 >( context ).isValid(), - nullptr, OpenGeodeException::TYPE::internal, - "[Identifier::load] Error while reading file: ", filename ); + detail::deserialize_bytes( content.span(), *this ), nullptr, + OpenGeodeException::TYPE::internal, + "[Identifier::load] Error while reading file: ", + files.location( FILENAME ) ); } private: @@ -138,6 +135,8 @@ namespace geode Identifier::Identifier() = default; + Identifier::Identifier( BITSERY bitsery ) : impl_{ bitsery } {} + Identifier::~Identifier() = default; Identifier::Identifier( Identifier&& ) noexcept = default; @@ -160,9 +159,9 @@ namespace geode } void Identifier::load_identifier( - std::string_view directory, IdentifierKey /*unused*/ ) + const detail::InputFiles& files, IdentifierKey /*unused*/ ) { - impl_->load( directory ); + impl_->load( files ); } void Identifier::set_id( const uuid& unique_id, IdentifierKey /*unused*/ ) diff --git a/src/geode/basic/identifier_builder.cpp b/src/geode/basic/identifier_builder.cpp index ced7ee485..d41e31590 100644 --- a/src/geode/basic/identifier_builder.cpp +++ b/src/geode/basic/identifier_builder.cpp @@ -23,6 +23,7 @@ #include +#include #include #include @@ -50,7 +51,12 @@ namespace geode void IdentifierBuilder::load_identifier( std::string_view directory ) { - identifier_.load_identifier( directory, Identifier::IdentifierKey{} ); + load_identifier( detail::DirectoryInputFiles{ directory } ); + } + + void IdentifierBuilder::load_identifier( const detail::InputFiles& files ) + { + identifier_.load_identifier( files, Identifier::IdentifierKey{} ); } } // namespace geode diff --git a/src/geode/basic/input_files.cpp b/src/geode/basic/input_files.cpp new file mode 100644 index 000000000..2c58744d8 --- /dev/null +++ b/src/geode/basic/input_files.cpp @@ -0,0 +1,141 @@ +/* + * Copyright (c) 2019 - 2026 Geode-solutions + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * + */ + +#include + +#include +#include + +#include +#include + +#include +#include + +namespace +{ + std::filesystem::path to_path( std::string_view utf8_path ) + { + return std::filesystem::u8path( utf8_path.begin(), utf8_path.end() ); + } +} // namespace + +namespace geode +{ + namespace detail + { + InputFiles::~InputFiles() = default; + + DirectoryInputFiles::DirectoryInputFiles( std::string_view directory ) + : directory_{ to_string( directory ) } + { + } + + DirectoryInputFiles::~DirectoryInputFiles() = default; + + bool DirectoryInputFiles::has( std::string_view name ) const + { + std::error_code error; + return std::filesystem::is_regular_file( + to_path( location( name ) ), error ); + } + + std::vector< std::string > DirectoryInputFiles::names() const + { + std::vector< std::string > names; + std::error_code error; + for( const auto& file : std::filesystem::directory_iterator( + to_path( directory_ ), error ) ) + { + if( file.is_regular_file( error ) ) + { + names.emplace_back( file.path().filename().u8string() ); + } + } + absl::c_sort( names ); + return names; + } + + FileContent DirectoryInputFiles::content( std::string_view name ) const + { + const auto file = location( name ); + auto content = map_file_content( file ); + OpenGeodeBasicException::check_exception( content.has_value(), + nullptr, OpenGeodeException::TYPE::data, + "[DirectoryInputFiles] Cannot open file: ", file ); + return std::move( content.value() ); + } + + std::optional< std::string > DirectoryInputFiles::path( + std::string_view name ) const + { + return location( name ); + } + + std::string DirectoryInputFiles::location( std::string_view name ) const + { + return absl::StrCat( directory_, "/", name ); + } + + TemporaryFile::TemporaryFile( std::string_view name, ByteSpan content ) + { + std::error_code error; + const auto temp_directory = + std::filesystem::temp_directory_path( error ); + OpenGeodeBasicException::check_exception( !error, nullptr, + OpenGeodeException::TYPE::internal, + "[TemporaryFile] No temporary directory: ", error.message() ); + const auto directory = temp_directory / uuid{}.string(); + std::filesystem::create_directories( directory, error ); + OpenGeodeBasicException::check_exception( !error, nullptr, + OpenGeodeException::TYPE::internal, + "[TemporaryFile] Cannot create directory: ", + directory.u8string(), " (", error.message(), ")" ); + directory_ = directory.u8string(); + const auto file = directory / to_path( name ).filename(); + path_ = file.u8string(); + std::ofstream stream{ file, std::ofstream::binary }; + stream.write( content.data(), + static_cast< std::streamsize >( content.size() ) ); + stream.close(); + if( !stream ) + { + std::filesystem::remove_all( directory, error ); + throw OpenGeodeBasicException{ nullptr, + OpenGeodeException::TYPE::internal, + "[TemporaryFile] Cannot write file: ", path_ }; + } + } + + TemporaryFile::~TemporaryFile() + { + std::error_code error; + std::filesystem::remove_all( to_path( directory_ ), error ); + } + + const std::string& TemporaryFile::path() const + { + return path_; + } + } // namespace detail +} // namespace geode diff --git a/src/geode/basic/singleton.cpp b/src/geode/basic/singleton.cpp index 87ae9c241..e8bf734ee 100644 --- a/src/geode/basic/singleton.cpp +++ b/src/geode/basic/singleton.cpp @@ -21,6 +21,9 @@ * */ +// common.hpp includes library.hpp, which needs singleton.hpp +#include + #include #include diff --git a/src/geode/basic/zip_file.cpp b/src/geode/basic/zip_file.cpp index 6042bd272..51ccd6812 100644 --- a/src/geode/basic/zip_file.cpp +++ b/src/geode/basic/zip_file.cpp @@ -23,17 +23,26 @@ #include +#include +#include +#include #include #include #include #include +#include +#include + #include #include #include #include #include +#include + +#include #include #include @@ -74,6 +83,100 @@ namespace } return true; } + + constexpr size_t LOCAL_HEADER_SIZE{ 30 }; + constexpr uint32_t LOCAL_HEADER_SIGNATURE{ 0x04034b50 }; + + uint32_t read_little_endian( const char* bytes, size_t nb_bytes ) + { + uint32_t value{ 0 }; + for( size_t byte = nb_bytes; byte > 0; byte-- ) + { + value = ( value << 8U ) + | static_cast< unsigned char >( bytes[byte - 1] ); + } + return value; + } + + class ZipReader + { + public: + explicit ZipReader( const std::filesystem::path& file ) + : reader_{ mz_zip_reader_create() } + { + status_ = reader_ == nullptr ? MZ_MEM_ERROR + : mz_zip_reader_open_file( reader_, + file.u8string().c_str() ); + } + + ~ZipReader() + { + if( reader_ ) + { + mz_zip_reader_close( reader_ ); + mz_zip_reader_delete( &reader_ ); + } + } + + ZipReader( const ZipReader& ) = delete; + ZipReader& operator=( const ZipReader& ) = delete; + + [[nodiscard]] bool is_open() const + { + return status_ == MZ_OK; + } + + [[nodiscard]] void* get() const + { + return reader_; + } + + private: + void* reader_; + int32_t status_; + }; + + geode::detail::ByteBuffer inflate_entry( + geode::ByteSpan compressed, size_t uncompressed_size, bool& success ) + { + geode::detail::ByteBuffer buffer{ uncompressed_size }; + z_stream stream{}; + success = false; + if( inflateInit2_( &stream, -MAX_WBITS, ZLIB_VERSION, + static_cast< int >( sizeof( z_stream ) ) ) + != Z_OK ) + { + return buffer; + } + using Chunk = decltype( stream.avail_in ); + constexpr auto MAX_CHUNK = + static_cast< size_t >( std::numeric_limits< Chunk >::max() ); + const auto* input = + reinterpret_cast< const unsigned char* >( compressed.data() ); + auto input_left = compressed.size(); + auto* output = reinterpret_cast< unsigned char* >( buffer.data() ); + auto output_left = buffer.size(); + auto status = Z_OK; + while( status == Z_OK ) + { + const auto input_chunk = std::min( input_left, MAX_CHUNK ); + const auto output_chunk = std::min( output_left, MAX_CHUNK ); + stream.next_in = const_cast< unsigned char* >( input ); + stream.avail_in = static_cast< Chunk >( input_chunk ); + stream.next_out = output; + stream.avail_out = static_cast< Chunk >( output_chunk ); + status = inflate( &stream, Z_NO_FLUSH ); + const auto nb_read = input_chunk - stream.avail_in; + const auto nb_written = output_chunk - stream.avail_out; + input += nb_read; + input_left -= nb_read; + output += nb_written; + output_left -= nb_written; + } + inflateEnd( &stream ); + success = status == Z_STREAM_END && output_left == 0; + return buffer; + } } // namespace namespace geode @@ -458,6 +561,294 @@ namespace geode return impl_->directory(); } + namespace detail + { + class ArchiveInputFiles::Impl + { + struct ArchiveEntry + { + uint64_t header_offset; + uint64_t compressed_size; + uint64_t uncompressed_size; + uint32_t crc; + uint16_t method; + }; + + public: + explicit Impl( std::string_view filename ) + : filename_{ to_string( filename ) } + { + OpenGeodeBasicException::check_exception( + std::filesystem::exists( to_path( filename ) ), nullptr, + OpenGeodeException::TYPE::data, "[ArchiveInputFiles] File ", + filename, " doesn't exist" ); + read_entries(); + mapping_ = MappedFile::map( filename_ ); + if( !mapping_ ) + { + Logger::debug( "[ArchiveInputFiles] Cannot map ", filename_, + ", reading its entries from disk" ); + } + } + + bool has( std::string_view name ) const + { + return entries_.contains( name ); + } + + std::vector< std::string > names() const + { + return names_; + } + + FileContent content( std::string_view name ) const + { + const auto entry = entries_.find( name ); + OpenGeodeBasicException::check_exception( + entry != entries_.end(), nullptr, + OpenGeodeException::TYPE::data, + "[ArchiveInputFiles] Missing entry ", location( name ) ); + auto content = entry->second.method == MZ_COMPRESS_METHOD_STORE + ? stored_content( name, entry->second ) + : inflated_content( name, entry->second ); + const auto bytes = content.span(); + const auto crc = crc32_z( 0, + reinterpret_cast< const unsigned char* >( bytes.data() ), + bytes.size() ); + OpenGeodeBasicException::check_exception( + static_cast< uint32_t >( crc ) == entry->second.crc, + nullptr, OpenGeodeException::TYPE::data, + "[ArchiveInputFiles] Corrupted entry ", location( name ), + " (CRC-32 mismatch)" ); + return content; + } + + std::string location( std::string_view name ) const + { + return absl::StrCat( filename_, "/", name ); + } + + private: + void read_entries() + { + const ZipReader reader{ to_path( filename_ ) }; + OpenGeodeBasicException::check_exception( reader.is_open(), + nullptr, OpenGeodeException::TYPE::data, + "[ArchiveInputFiles] Error opening zip for reading: ", + filename_ ); + auto status = mz_zip_reader_goto_first_entry( reader.get() ); + while( status == MZ_OK ) + { + read_entry( reader.get() ); + status = mz_zip_reader_goto_next_entry( reader.get() ); + } + OpenGeodeBasicException::check_exception( + status == MZ_END_OF_LIST, nullptr, + OpenGeodeException::TYPE::data, + "[ArchiveInputFiles] Error while reading zip entries of ", + filename_, " (", status, ")" ); + } + + void read_entry( void* reader ) + { + mz_zip_file* info = nullptr; + const auto info_status = + mz_zip_reader_entry_get_info( reader, &info ); + OpenGeodeBasicException::check_exception( + info_status == MZ_OK && info != nullptr, nullptr, + OpenGeodeException::TYPE::data, + "[ArchiveInputFiles] Cannot read zip entry information " + "of ", + filename_, " (", info_status, ")" ); + std::string name{ info->filename }; + OpenGeodeBasicException::check_exception( + is_safe_entry_path( to_path( name ) ), nullptr, + OpenGeodeException::TYPE::data, + "[ArchiveInputFiles] Unsafe zip entry path: ", name ); + if( mz_zip_reader_entry_is_dir( reader ) == MZ_OK ) + { + return; + } + OpenGeodeBasicException::check_exception( + ( info->flag & MZ_ZIP_FLAG_ENCRYPTED ) == 0, nullptr, + OpenGeodeException::TYPE::data, + "[ArchiveInputFiles] Encrypted zip entry: ", + location( name ) ); + OpenGeodeBasicException::check_exception( + info->compression_method == MZ_COMPRESS_METHOD_STORE + || info->compression_method + == MZ_COMPRESS_METHOD_DEFLATE, + nullptr, OpenGeodeException::TYPE::data, + "[ArchiveInputFiles] Unsupported compression method ", + info->compression_method, " of zip entry ", + location( name ) ); + OpenGeodeBasicException::check_exception( + info->disk_offset >= 0 && info->compressed_size >= 0 + && info->uncompressed_size >= 0, + nullptr, OpenGeodeException::TYPE::data, + "[ArchiveInputFiles] Invalid zip entry ", + location( name ) ); + ArchiveEntry entry{ static_cast< uint64_t >( + info->disk_offset ), + static_cast< uint64_t >( info->compressed_size ), + static_cast< uint64_t >( info->uncompressed_size ), + info->crc, info->compression_method }; + const auto [_, inserted] = + entries_.insert_or_assign( name, entry ); + if( inserted ) + { + names_.emplace_back( std::move( name ) ); + } + } + + /*! + * Return the offset of the data of an entry, after its local + * header. + */ + uint64_t data_offset( + std::string_view name, const ArchiveEntry& entry ) const + { + std::array< char, LOCAL_HEADER_SIZE > header_buffer; + const char* header = header_buffer.data(); + if( mapping_ ) + { + const auto archive = mapping_->span(); + check_inside_archive( + name, entry.header_offset, LOCAL_HEADER_SIZE ); + header = archive.data() + entry.header_offset; + } + else + { + read_at( name, entry.header_offset, header_buffer.data(), + LOCAL_HEADER_SIZE ); + } + OpenGeodeBasicException::check_exception( + read_little_endian( header, 4 ) == LOCAL_HEADER_SIGNATURE, + nullptr, OpenGeodeException::TYPE::data, + "[ArchiveInputFiles] Invalid local header of zip entry ", + location( name ) ); + const auto name_length = read_little_endian( header + 26, 2 ); + const auto extra_length = read_little_endian( header + 28, 2 ); + return entry.header_offset + LOCAL_HEADER_SIZE + name_length + + extra_length; + } + + /*! + * Return the raw (compressed) bytes of an entry: a slice of the + * mapped archive, or a buffer read from the file. + */ + FileContent raw_content( + std::string_view name, const ArchiveEntry& entry ) const + { + const auto offset = data_offset( name, entry ); + if( mapping_ ) + { + check_inside_archive( name, offset, entry.compressed_size ); + return { mapping_, mapping_->span().subspan( + offset, entry.compressed_size ) }; + } + ByteBuffer buffer{ entry.compressed_size }; + read_at( name, offset, buffer.data(), buffer.size() ); + return FileContent{ std::move( buffer ) }; + } + + FileContent stored_content( + std::string_view name, const ArchiveEntry& entry ) const + { + OpenGeodeBasicException::check_exception( + entry.compressed_size == entry.uncompressed_size, nullptr, + OpenGeodeException::TYPE::data, + "[ArchiveInputFiles] Invalid size of stored zip entry ", + location( name ) ); + return raw_content( name, entry ); + } + + FileContent inflated_content( + std::string_view name, const ArchiveEntry& entry ) const + { + const auto compressed = raw_content( name, entry ); + bool success{ false }; + auto buffer = inflate_entry( + compressed.span(), entry.uncompressed_size, success ); + OpenGeodeBasicException::check_exception( success, nullptr, + OpenGeodeException::TYPE::data, + "[ArchiveInputFiles] Cannot decompress zip entry ", + location( name ) ); + return FileContent{ std::move( buffer ) }; + } + + void check_inside_archive( + std::string_view name, uint64_t offset, uint64_t size ) const + { + const auto archive_size = mapping_->span().size(); + OpenGeodeBasicException::check_exception( + offset <= archive_size && size <= archive_size - offset, + nullptr, OpenGeodeException::TYPE::data, + "[ArchiveInputFiles] Truncated zip entry ", + location( name ) ); + } + + /*! + * Positional read, used when the archive cannot be mapped. + */ + void read_at( std::string_view name, + uint64_t offset, + char* data, + size_t size ) const + { + std::ifstream file{ to_path( filename_ ), std::ios::binary }; + file.seekg( static_cast< std::streamoff >( offset ) ); + file.read( data, static_cast< std::streamsize >( size ) ); + OpenGeodeBasicException::check_exception( + file.good() + && file.gcount() + == static_cast< std::streamsize >( size ), + nullptr, OpenGeodeException::TYPE::data, + "[ArchiveInputFiles] Cannot read zip entry ", + location( name ) ); + } + + private: + std::string filename_; + absl::flat_hash_map< std::string, ArchiveEntry > entries_; + std::vector< std::string > names_; + std::shared_ptr< const MappedFile > mapping_; + }; + + ArchiveInputFiles::ArchiveInputFiles( std::string_view filename ) + : impl_{ filename } + { + } + + ArchiveInputFiles::~ArchiveInputFiles() = default; + + bool ArchiveInputFiles::has( std::string_view name ) const + { + return impl_->has( name ); + } + + std::vector< std::string > ArchiveInputFiles::names() const + { + return impl_->names(); + } + + FileContent ArchiveInputFiles::content( std::string_view name ) const + { + return impl_->content( name ); + } + + std::optional< std::string > ArchiveInputFiles::path( + std::string_view /*name*/ ) const + { + return std::nullopt; + } + + std::string ArchiveInputFiles::location( std::string_view name ) const + { + return impl_->location( name ); + } + } // namespace detail + bool is_zip_file( std::string_view file ) { void* reader = mz_zip_reader_create(); diff --git a/src/geode/mesh/core/geode/geode_point_set.cpp b/src/geode/mesh/core/geode/geode_point_set.cpp index 1d19c576c..21d2a0f90 100644 --- a/src/geode/mesh/core/geode/geode_point_set.cpp +++ b/src/geode/mesh/core/geode/geode_point_set.cpp @@ -69,7 +69,8 @@ namespace geode } template < index_t dimension > - OpenGeodePointSet< dimension >::OpenGeodePointSet( BITSERY ) + OpenGeodePointSet< dimension >::OpenGeodePointSet( BITSERY bitsery ) + : PointSet< dimension >{ bitsery } { } diff --git a/src/geode/mesh/core/graph.cpp b/src/geode/mesh/core/graph.cpp index 2eb0a396c..0a2d2af32 100644 --- a/src/geode/mesh/core/graph.cpp +++ b/src/geode/mesh/core/graph.cpp @@ -201,7 +201,7 @@ namespace geode Graph::Graph() = default; - Graph::Graph( BITSERY ) {} + Graph::Graph( BITSERY bitsery ) : VertexSet{ bitsery } {} Graph::Graph( Graph&& ) noexcept = default; diff --git a/src/geode/mesh/core/solid_mesh.cpp b/src/geode/mesh/core/solid_mesh.cpp index 411be21c9..78acb95f3 100644 --- a/src/geode/mesh/core/solid_mesh.cpp +++ b/src/geode/mesh/core/solid_mesh.cpp @@ -1045,7 +1045,7 @@ namespace geode SolidMesh< dimension >::SolidMesh() = default; template < index_t dimension > - SolidMesh< dimension >::SolidMesh( BITSERY ) + SolidMesh< dimension >::SolidMesh( BITSERY bitsery ) : VertexSet{ bitsery } { } diff --git a/src/geode/mesh/core/surface_mesh.cpp b/src/geode/mesh/core/surface_mesh.cpp index e548ab084..adfd24933 100644 --- a/src/geode/mesh/core/surface_mesh.cpp +++ b/src/geode/mesh/core/surface_mesh.cpp @@ -589,7 +589,8 @@ namespace geode SurfaceMesh< dimension >::SurfaceMesh() = default; template < index_t dimension > - SurfaceMesh< dimension >::SurfaceMesh( BITSERY ) + SurfaceMesh< dimension >::SurfaceMesh( BITSERY bitsery ) + : VertexSet{ bitsery } { } diff --git a/src/geode/mesh/core/vertex_set.cpp b/src/geode/mesh/core/vertex_set.cpp index 8fb717eef..4333c2807 100644 --- a/src/geode/mesh/core/vertex_set.cpp +++ b/src/geode/mesh/core/vertex_set.cpp @@ -58,6 +58,8 @@ namespace geode VertexSet::VertexSet() = default; + VertexSet::VertexSet( BITSERY bitsery ) : Identifier{ bitsery } {} + VertexSet::VertexSet( VertexSet&& ) noexcept = default; VertexSet& VertexSet::operator=( VertexSet&& ) noexcept = default; @@ -97,6 +99,8 @@ namespace geode *this, Growable< Archive, VertexSet >{ { []( Archive& archive, VertexSet& vertex_set ) { archive.object( vertex_set.impl_ ); + // Identifier not stored in this version + vertex_set.set_id( uuid{} ); }, []( Archive& archive, VertexSet& vertex_set ) { archive.object( vertex_set.impl_ ); diff --git a/src/geode/mesh/io/light_regular_grid_output.cpp b/src/geode/mesh/io/light_regular_grid_output.cpp index 45af78c42..5d712792a 100644 --- a/src/geode/mesh/io/light_regular_grid_output.cpp +++ b/src/geode/mesh/io/light_regular_grid_output.cpp @@ -23,6 +23,7 @@ #include +#include #include #include #include @@ -40,7 +41,8 @@ namespace geode std::vector< std::string > LightRegularGridOutput< dimension >::write( const LightRegularGrid< dimension >& grid ) const { - std::ofstream file{ to_string( this->filename() ), + std::ofstream file{ std::filesystem::u8path( + to_string( this->filename() ) ), std::ofstream::binary }; OpenGeodeMeshException::check_exception( !file.fail(), nullptr, OpenGeodeException::TYPE::data, diff --git a/src/geode/model/mixin/builder/block_collections_builder.cpp b/src/geode/model/mixin/builder/block_collections_builder.cpp index 7a75bc9ef..884285b00 100644 --- a/src/geode/model/mixin/builder/block_collections_builder.cpp +++ b/src/geode/model/mixin/builder/block_collections_builder.cpp @@ -23,6 +23,8 @@ #include +#include + #include #include @@ -59,9 +61,16 @@ namespace geode void BlockCollectionsBuilder< dimension >::load_block_collections( std::string_view directory ) { - return block_collections_.load_block_collections( - directory, typename BlockCollections< - dimension >::BlockCollectionsBuilderKey{} ); + load_block_collections( detail::DirectoryInputFiles{ directory } ); + } + + template < index_t dimension > + void BlockCollectionsBuilder< dimension >::load_block_collections( + const detail::InputFiles& files ) + { + block_collections_.load_block_collections( + files, typename BlockCollections< + dimension >::BlockCollectionsBuilderKey{} ); } template < index_t dimension > diff --git a/src/geode/model/mixin/builder/blocks_builder.cpp b/src/geode/model/mixin/builder/blocks_builder.cpp index 0352ec56b..9235533b4 100644 --- a/src/geode/model/mixin/builder/blocks_builder.cpp +++ b/src/geode/model/mixin/builder/blocks_builder.cpp @@ -23,6 +23,8 @@ #include +#include + #include #include @@ -71,8 +73,15 @@ namespace geode template < index_t dimension > void BlocksBuilder< dimension >::load_blocks( std::string_view directory ) { - return blocks_.load_blocks( - directory, typename Blocks< dimension >::BlocksBuilderKey{} ); + load_blocks( detail::DirectoryInputFiles{ directory } ); + } + + template < index_t dimension > + void BlocksBuilder< dimension >::load_blocks( + const detail::InputFiles& files ) + { + blocks_.load_blocks( + files, typename Blocks< dimension >::BlocksBuilderKey{} ); } template < index_t dimension > diff --git a/src/geode/model/mixin/builder/corner_collections_builder.cpp b/src/geode/model/mixin/builder/corner_collections_builder.cpp index b84a5a1bc..082499e71 100644 --- a/src/geode/model/mixin/builder/corner_collections_builder.cpp +++ b/src/geode/model/mixin/builder/corner_collections_builder.cpp @@ -23,6 +23,8 @@ #include +#include + #include #include @@ -60,9 +62,16 @@ namespace geode void CornerCollectionsBuilder< dimension >::load_corner_collections( std::string_view directory ) { - return corner_collections_.load_corner_collections( - directory, typename CornerCollections< - dimension >::CornerCollectionsBuilderKey{} ); + load_corner_collections( detail::DirectoryInputFiles{ directory } ); + } + + template < index_t dimension > + void CornerCollectionsBuilder< dimension >::load_corner_collections( + const detail::InputFiles& files ) + { + corner_collections_.load_corner_collections( + files, typename CornerCollections< + dimension >::CornerCollectionsBuilderKey{} ); } template < index_t dimension > diff --git a/src/geode/model/mixin/builder/corners_builder.cpp b/src/geode/model/mixin/builder/corners_builder.cpp index d86124264..0b5aa8629 100644 --- a/src/geode/model/mixin/builder/corners_builder.cpp +++ b/src/geode/model/mixin/builder/corners_builder.cpp @@ -23,6 +23,8 @@ #include +#include + #include #include @@ -72,8 +74,15 @@ namespace geode template < index_t dimension > void CornersBuilder< dimension >::load_corners( std::string_view directory ) { - return corners_.load_corners( - directory, typename Corners< dimension >::CornersBuilderKey{} ); + load_corners( detail::DirectoryInputFiles{ directory } ); + } + + template < index_t dimension > + void CornersBuilder< dimension >::load_corners( + const detail::InputFiles& files ) + { + corners_.load_corners( + files, typename Corners< dimension >::CornersBuilderKey{} ); } template < index_t dimension > diff --git a/src/geode/model/mixin/builder/line_collections_builder.cpp b/src/geode/model/mixin/builder/line_collections_builder.cpp index 21d33106c..f32e081d3 100644 --- a/src/geode/model/mixin/builder/line_collections_builder.cpp +++ b/src/geode/model/mixin/builder/line_collections_builder.cpp @@ -23,6 +23,8 @@ #include +#include + #include #include @@ -59,9 +61,16 @@ namespace geode void LineCollectionsBuilder< dimension >::load_line_collections( std::string_view directory ) { - return line_collections_.load_line_collections( - directory, typename LineCollections< - dimension >::LineCollectionsBuilderKey{} ); + load_line_collections( detail::DirectoryInputFiles{ directory } ); + } + + template < index_t dimension > + void LineCollectionsBuilder< dimension >::load_line_collections( + const detail::InputFiles& files ) + { + line_collections_.load_line_collections( + files, typename LineCollections< + dimension >::LineCollectionsBuilderKey{} ); } template < index_t dimension > diff --git a/src/geode/model/mixin/builder/lines_builder.cpp b/src/geode/model/mixin/builder/lines_builder.cpp index 6fac0ff4a..20cfc4e37 100644 --- a/src/geode/model/mixin/builder/lines_builder.cpp +++ b/src/geode/model/mixin/builder/lines_builder.cpp @@ -23,6 +23,8 @@ #include +#include + #include #include @@ -70,8 +72,15 @@ namespace geode template < index_t dimension > void LinesBuilder< dimension >::load_lines( std::string_view directory ) { - return lines_.load_lines( - directory, typename Lines< dimension >::LinesBuilderKey{} ); + load_lines( detail::DirectoryInputFiles{ directory } ); + } + + template < index_t dimension > + void LinesBuilder< dimension >::load_lines( + const detail::InputFiles& files ) + { + lines_.load_lines( + files, typename Lines< dimension >::LinesBuilderKey{} ); } template < index_t dimension > diff --git a/src/geode/model/mixin/builder/model_boundaries_builder.cpp b/src/geode/model/mixin/builder/model_boundaries_builder.cpp index fe74b903f..603c52ba4 100644 --- a/src/geode/model/mixin/builder/model_boundaries_builder.cpp +++ b/src/geode/model/mixin/builder/model_boundaries_builder.cpp @@ -23,6 +23,8 @@ #include +#include + #include #include @@ -58,9 +60,16 @@ namespace geode void ModelBoundariesBuilder< dimension >::load_model_boundaries( std::string_view directory ) { - return model_boundaries_.load_model_boundaries( - directory, typename ModelBoundaries< - dimension >::ModelBoundariesBuilderKey{} ); + load_model_boundaries( detail::DirectoryInputFiles{ directory } ); + } + + template < index_t dimension > + void ModelBoundariesBuilder< dimension >::load_model_boundaries( + const detail::InputFiles& files ) + { + model_boundaries_.load_model_boundaries( + files, typename ModelBoundaries< + dimension >::ModelBoundariesBuilderKey{} ); } template < index_t dimension > diff --git a/src/geode/model/mixin/builder/physical_properties_builder.cpp b/src/geode/model/mixin/builder/physical_properties_builder.cpp index 6187dd88a..6ff033b71 100644 --- a/src/geode/model/mixin/builder/physical_properties_builder.cpp +++ b/src/geode/model/mixin/builder/physical_properties_builder.cpp @@ -23,6 +23,8 @@ #include +#include + #include namespace geode @@ -52,8 +54,14 @@ namespace geode void PhysicalPropertiesBuilder::load_physical_properties( std::string_view directory ) + { + load_physical_properties( detail::DirectoryInputFiles{ directory } ); + } + + void PhysicalPropertiesBuilder::load_physical_properties( + const detail::InputFiles& files ) { physical_properties_.load_physical_properties( - directory, PhysicalProperties::BuilderKey{} ); + files, PhysicalProperties::BuilderKey{} ); } } // namespace geode diff --git a/src/geode/model/mixin/builder/relationships_builder.cpp b/src/geode/model/mixin/builder/relationships_builder.cpp index 7e4e1e4dd..55557250c 100644 --- a/src/geode/model/mixin/builder/relationships_builder.cpp +++ b/src/geode/model/mixin/builder/relationships_builder.cpp @@ -23,6 +23,8 @@ #include +#include + namespace geode { RelationshipsBuilder::RelationshipsBuilder( Relationships& relationships ) @@ -79,9 +81,15 @@ namespace geode } void RelationshipsBuilder::load_relationships( std::string_view directory ) + { + load_relationships( detail::DirectoryInputFiles{ directory } ); + } + + void RelationshipsBuilder::load_relationships( + const detail::InputFiles& files ) { relationships_.load_relationships( - directory, Relationships::RelationshipsBuilderKey{} ); + files, Relationships::RelationshipsBuilderKey{} ); } } // namespace geode diff --git a/src/geode/model/mixin/builder/surface_collections_builder.cpp b/src/geode/model/mixin/builder/surface_collections_builder.cpp index 40d1c13bf..92daaf8e5 100644 --- a/src/geode/model/mixin/builder/surface_collections_builder.cpp +++ b/src/geode/model/mixin/builder/surface_collections_builder.cpp @@ -23,6 +23,8 @@ #include +#include + #include #include @@ -60,9 +62,16 @@ namespace geode void SurfaceCollectionsBuilder< dimension >::load_surface_collections( std::string_view directory ) { - return surface_collections_.load_surface_collections( - directory, typename SurfaceCollections< - dimension >::SurfaceCollectionsBuilderKey{} ); + load_surface_collections( detail::DirectoryInputFiles{ directory } ); + } + + template < index_t dimension > + void SurfaceCollectionsBuilder< dimension >::load_surface_collections( + const detail::InputFiles& files ) + { + surface_collections_.load_surface_collections( + files, typename SurfaceCollections< + dimension >::SurfaceCollectionsBuilderKey{} ); } template < index_t dimension > diff --git a/src/geode/model/mixin/builder/surfaces_builder.cpp b/src/geode/model/mixin/builder/surfaces_builder.cpp index 889570330..729b12754 100644 --- a/src/geode/model/mixin/builder/surfaces_builder.cpp +++ b/src/geode/model/mixin/builder/surfaces_builder.cpp @@ -23,6 +23,8 @@ #include +#include + #include #include @@ -73,8 +75,15 @@ namespace geode void SurfacesBuilder< dimension >::load_surfaces( std::string_view directory ) { - return surfaces_.load_surfaces( - directory, typename Surface< dimension >::SurfacesBuilderKey{} ); + load_surfaces( detail::DirectoryInputFiles{ directory } ); + } + + template < index_t dimension > + void SurfacesBuilder< dimension >::load_surfaces( + const detail::InputFiles& files ) + { + surfaces_.load_surfaces( + files, typename Surface< dimension >::SurfacesBuilderKey{} ); } template < index_t dimension > diff --git a/src/geode/model/mixin/builder/vertex_identifier_builder.cpp b/src/geode/model/mixin/builder/vertex_identifier_builder.cpp index 5d53799f7..baf038a95 100644 --- a/src/geode/model/mixin/builder/vertex_identifier_builder.cpp +++ b/src/geode/model/mixin/builder/vertex_identifier_builder.cpp @@ -23,6 +23,8 @@ #include +#include + namespace geode { VertexIdentifierBuilder::VertexIdentifierBuilder( @@ -67,9 +69,15 @@ namespace geode void VertexIdentifierBuilder::load_unique_vertices( std::string_view directory ) + { + load_unique_vertices( detail::DirectoryInputFiles{ directory } ); + } + + void VertexIdentifierBuilder::load_unique_vertices( + const detail::InputFiles& files ) { vertex_identifier_.load_unique_vertices( - directory, VertexIdentifier::BuilderKey{} ); + files, VertexIdentifier::BuilderKey{} ); } std::vector< index_t > VertexIdentifierBuilder::delete_isolated_vertices() diff --git a/src/geode/model/mixin/core/block_collections.cpp b/src/geode/model/mixin/core/block_collections.cpp index 635054ca6..eed661809 100644 --- a/src/geode/model/mixin/core/block_collections.cpp +++ b/src/geode/model/mixin/core/block_collections.cpp @@ -97,10 +97,9 @@ namespace geode template < index_t dimension > void BlockCollections< dimension >::load_block_collections( - std::string_view directory, BlockCollectionsBuilderKey /*key*/ ) + const detail::InputFiles& files, BlockCollectionsBuilderKey /*key*/ ) { - impl_->load_components( - absl::StrCat( directory, "/block_collections" ), false ); + impl_->load_components( files, "block_collections", false ); } template < index_t dimension > diff --git a/src/geode/model/mixin/core/blocks.cpp b/src/geode/model/mixin/core/blocks.cpp index a620fa7b4..aea548d93 100644 --- a/src/geode/model/mixin/core/blocks.cpp +++ b/src/geode/model/mixin/core/blocks.cpp @@ -181,15 +181,15 @@ namespace geode template < index_t dimension > void Blocks< dimension >::load_blocks( - std::string_view directory, BlocksBuilderKey builder_key ) + const detail::InputFiles& files, BlocksBuilderKey builder_key ) { - impl_->load_components( absl::StrCat( directory, "/blocks" ) ); - const auto mapping = impl_->file_mapping( directory ); + impl_->load_components( files, "blocks", true ); + const auto mapping = impl_->file_mapping( files ); absl::FixedArray< async::task< void > > tasks( nb_blocks() ); index_t count{ 0 }; for( auto& block : modifiable_blocks( builder_key ) ) { - tasks[count++] = async::spawn( [&block, &mapping] { + tasks[count++] = async::spawn( [&block, &mapping, &files] { const auto file = mapping.find( block.id().string() ); if( file == mapping.end() ) { @@ -199,38 +199,39 @@ namespace geode typename Block< dimension >::BlocksKey{} ); return; } + const auto& name = file->second; const auto impl = detail::loadable_mesh_impl( block.mesh_type(), - solid_type_from_file< dimension >( file->second ), - file->second ); + solid_type_from_file< dimension >( name ), + files.location( name ) ); const auto& type = MeshFactory::type( impl ); if( type == TetrahedralSolid< dimension >::type_name_static() ) { block.set_mesh( - load_one( load_tetrahedral_solid< dimension >( - impl, file->second ), - file->second ), + detail::load_component_mesh< + TetrahedralSolidInputFactory< dimension > >( + files, name, impl ), typename Block< dimension >::BlocksKey{} ); } else if( type == HybridSolid< dimension >::type_name_static() ) { - block.set_mesh( load_one( load_hybrid_solid< dimension >( - impl, file->second ), - file->second ), + block.set_mesh( detail::load_component_mesh< + HybridSolidInputFactory< dimension > >( + files, name, impl ), typename Block< dimension >::BlocksKey{} ); } else if( type == RegularGrid< dimension >::type_name_static() ) { - block.set_mesh( load_one( load_regular_grid< dimension >( - impl, file->second ), - file->second ), + block.set_mesh( detail::load_component_mesh< + RegularGridInputFactory< dimension > >( + files, name, impl ), typename Block< dimension >::BlocksKey{} ); } else { block.set_mesh( - load_one( load_polyhedral_solid< dimension >( - impl, file->second ), - file->second ), + detail::load_component_mesh< + PolyhedralSolidInputFactory< dimension > >( + files, name, impl ), typename Block< dimension >::BlocksKey{} ); } } ); diff --git a/src/geode/model/mixin/core/component.cpp b/src/geode/model/mixin/core/component.cpp index 886b95f49..98b76e7f4 100644 --- a/src/geode/model/mixin/core/component.cpp +++ b/src/geode/model/mixin/core/component.cpp @@ -77,7 +77,8 @@ namespace geode private: std::string backward_compatible_name_ = std::string{ "unknown" }; - uuid backward_compatible_id_; + // Only read (and used) by the first version of Component + uuid backward_compatible_id_{ BITSERY::constructor }; bool is_active_{ true }; }; diff --git a/src/geode/model/mixin/core/corner_collections.cpp b/src/geode/model/mixin/core/corner_collections.cpp index 77e8b3b04..9f6e04a12 100644 --- a/src/geode/model/mixin/core/corner_collections.cpp +++ b/src/geode/model/mixin/core/corner_collections.cpp @@ -98,10 +98,9 @@ namespace geode template < index_t dimension > void CornerCollections< dimension >::load_corner_collections( - std::string_view directory, CornerCollectionsBuilderKey /*key*/ ) + const detail::InputFiles& files, CornerCollectionsBuilderKey /*key*/ ) { - impl_->load_components( - absl::StrCat( directory, "/corner_collections" ), false ); + impl_->load_components( files, "corner_collections", false ); } template < index_t dimension > diff --git a/src/geode/model/mixin/core/corners.cpp b/src/geode/model/mixin/core/corners.cpp index 63e3f69e1..7ca7c555d 100644 --- a/src/geode/model/mixin/core/corners.cpp +++ b/src/geode/model/mixin/core/corners.cpp @@ -115,15 +115,15 @@ namespace geode template < index_t dimension > void Corners< dimension >::load_corners( - std::string_view directory, CornersBuilderKey key ) + const detail::InputFiles& files, CornersBuilderKey key ) { - impl_->load_components( absl::StrCat( directory, "/corners" ) ); - const auto mapping = impl_->file_mapping( directory ); + impl_->load_components( files, "corners", true ); + const auto mapping = impl_->file_mapping( files ); absl::FixedArray< async::task< void > > tasks( nb_corners() ); index_t count{ 0 }; for( auto& corner : modifiable_corners( key ) ) { - tasks[count++] = async::spawn( [&corner, &mapping] { + tasks[count++] = async::spawn( [&corner, &mapping, &files] { const auto& type = PointSet< dimension >::type_name_static(); const auto file = mapping.find( corner.id().string() ); if( file == mapping.end() ) @@ -134,11 +134,11 @@ namespace geode return; } corner.set_mesh( - load_one( load_point_set< dimension >( - detail::loadable_mesh_impl( - corner.mesh_type(), type, file->second ), - file->second ), - file->second ), + detail::load_component_mesh< + PointSetInputFactory< dimension > >( files, + file->second, + detail::loadable_mesh_impl( corner.mesh_type(), type, + files.location( file->second ) ) ), typename Corner< dimension >::CornersKey{} ); } ); } diff --git a/src/geode/model/mixin/core/line_collections.cpp b/src/geode/model/mixin/core/line_collections.cpp index 9bcd9b5d6..3635c597f 100644 --- a/src/geode/model/mixin/core/line_collections.cpp +++ b/src/geode/model/mixin/core/line_collections.cpp @@ -97,10 +97,9 @@ namespace geode template < index_t dimension > void LineCollections< dimension >::load_line_collections( - std::string_view directory, LineCollectionsBuilderKey /*key*/ ) + const detail::InputFiles& files, LineCollectionsBuilderKey /*key*/ ) { - impl_->load_components( - absl::StrCat( directory, "/line_collections" ), false ); + impl_->load_components( files, "line_collections", false ); } template < index_t dimension > diff --git a/src/geode/model/mixin/core/lines.cpp b/src/geode/model/mixin/core/lines.cpp index f061743b4..cae622555 100644 --- a/src/geode/model/mixin/core/lines.cpp +++ b/src/geode/model/mixin/core/lines.cpp @@ -113,15 +113,15 @@ namespace geode template < index_t dimension > void Lines< dimension >::load_lines( - std::string_view directory, LinesBuilderKey key ) + const detail::InputFiles& files, LinesBuilderKey key ) { - impl_->load_components( absl::StrCat( directory, "/lines" ) ); - const auto mapping = impl_->file_mapping( directory ); + impl_->load_components( files, "lines", true ); + const auto mapping = impl_->file_mapping( files ); absl::FixedArray< async::task< void > > tasks( nb_lines() ); index_t count{ 0 }; for( auto& line : modifiable_lines( key ) ) { - tasks[count++] = async::spawn( [&line, &mapping] { + tasks[count++] = async::spawn( [&line, &mapping, &files] { const auto& type = EdgedCurve< dimension >::type_name_static(); const auto file = mapping.find( line.id().string() ); if( file == mapping.end() ) @@ -131,12 +131,11 @@ namespace geode typename Line< dimension >::LinesKey{} ); return; } - line.set_mesh( - load_one( load_edged_curve< dimension >( - detail::loadable_mesh_impl( - line.mesh_type(), type, file->second ), - file->second ), - file->second ), + line.set_mesh( detail::load_component_mesh< + EdgedCurveInputFactory< dimension > >( files, + file->second, + detail::loadable_mesh_impl( line.mesh_type(), + type, files.location( file->second ) ) ), typename Line< dimension >::LinesKey{} ); } ); } diff --git a/src/geode/model/mixin/core/model_boundaries.cpp b/src/geode/model/mixin/core/model_boundaries.cpp index 218241a1f..4c7498509 100644 --- a/src/geode/model/mixin/core/model_boundaries.cpp +++ b/src/geode/model/mixin/core/model_boundaries.cpp @@ -97,10 +97,9 @@ namespace geode template < index_t dimension > void ModelBoundaries< dimension >::load_model_boundaries( - std::string_view directory, ModelBoundariesBuilderKey /*key*/ ) + const detail::InputFiles& files, ModelBoundariesBuilderKey /*key*/ ) { - impl_->load_components( - absl::StrCat( directory, "/model_boundaries" ) ); + impl_->load_components( files, "model_boundaries", true ); } template < index_t dimension > diff --git a/src/geode/model/mixin/core/physical_properties.cpp b/src/geode/model/mixin/core/physical_properties.cpp index 688d07aef..8a611ba11 100644 --- a/src/geode/model/mixin/core/physical_properties.cpp +++ b/src/geode/model/mixin/core/physical_properties.cpp @@ -36,6 +36,7 @@ #include #include +#include #include #include #include @@ -145,7 +146,8 @@ namespace namespace geode { PhysicalProperties::Info::Info() - : component_type( bitsery::Access::create< ComponentType >() ) + : component_type( bitsery::Access::create< ComponentType >() ), + attribute_id( BITSERY::constructor ) { } @@ -220,28 +222,18 @@ namespace geode filename ); } - void load( std::string_view directory ) + void load( const detail::InputFiles& files ) { - const auto filename = - absl::StrCat( directory, "/physical_properties" ); - if( !std::filesystem::exists( - std::filesystem::u8path( filename ) ) ) + static constexpr auto FILENAME = "physical_properties"; + if( !files.has( FILENAME ) ) { return; } - std::ifstream file{ std::filesystem::u8path( filename ), - std::ifstream::binary }; - TContext context{}; - BitseryExtensions::register_deserialize_pcontext( - std::get< 0 >( context ) ); - Deserializer archive{ context, file }; - archive.object( *this ); - const auto& adapter = archive.adapter(); + const auto filename = files.location( FILENAME ); + const auto content = files.content( FILENAME ); OpenGeodeModelException::check_exception( - adapter.error() == bitsery::ReaderError::NoError - && adapter.isCompletedSuccessfully() - && std::get< 1 >( context ).isValid(), - nullptr, OpenGeodeException::TYPE::internal, + detail::deserialize_bytes( content.span(), *this ), nullptr, + OpenGeodeException::TYPE::internal, "[PhysicalProperties::load] Error while reading file: ", filename ); } @@ -321,9 +313,9 @@ namespace geode } void PhysicalProperties::load_physical_properties( - std::string_view directory, BuilderKey /*key*/ ) + const detail::InputFiles& files, BuilderKey /*key*/ ) { - impl_->load( directory ); + impl_->load( files ); } void PhysicalProperties::set_physical_property( PHYSICAL_PROPERTY_NAME name, diff --git a/src/geode/model/mixin/core/relationships.cpp b/src/geode/model/mixin/core/relationships.cpp index 912d2d05e..73e029038 100644 --- a/src/geode/model/mixin/core/relationships.cpp +++ b/src/geode/model/mixin/core/relationships.cpp @@ -29,6 +29,7 @@ #include #include #include +#include #include #include @@ -198,23 +199,18 @@ namespace geode "[Relationships::save] Error while writing file: ", filename ); } - void load( std::string_view directory ) + void load( const detail::InputFiles& files ) { - const auto filename = absl::StrCat( directory, "/relationships" ); - std::ifstream file{ std::filesystem::u8path( filename ), - std::ifstream::binary }; - TContext context{}; - BitseryExtensions::register_deserialize_pcontext( - std::get< 0 >( context ) ); - Deserializer archive{ context, file }; - archive.object( *this ); - const auto& adapter = archive.adapter(); - OpenGeodeModelException::check_exception( - adapter.error() == bitsery::ReaderError::NoError - && adapter.isCompletedSuccessfully() - && std::get< 1 >( context ).isValid(), + static constexpr auto FILENAME = "relationships"; + const auto filename = files.location( FILENAME ); + OpenGeodeModelException::check_exception( files.has( FILENAME ), nullptr, OpenGeodeException::TYPE::internal, "[Relationships::load] Error while reading file: ", filename ); + const auto content = files.content( FILENAME ); + OpenGeodeModelException::check_exception( + detail::deserialize_bytes( content.span(), *this ), nullptr, + OpenGeodeException::TYPE::internal, + "[Relationships::load] Error while reading file: ", filename ); } private: @@ -483,9 +479,9 @@ namespace geode } void Relationships::load_relationships( - std::string_view directory, RelationshipsBuilderKey /*key*/ ) + const detail::InputFiles& files, RelationshipsBuilderKey /*key*/ ) { - return impl_->load( directory ); + return impl_->load( files ); } AttributeManager& Relationships::relation_attribute_manager() const diff --git a/src/geode/model/mixin/core/surface_collections.cpp b/src/geode/model/mixin/core/surface_collections.cpp index 8009639b9..f7824eb26 100644 --- a/src/geode/model/mixin/core/surface_collections.cpp +++ b/src/geode/model/mixin/core/surface_collections.cpp @@ -99,10 +99,9 @@ namespace geode template < index_t dimension > void SurfaceCollections< dimension >::load_surface_collections( - std::string_view directory, SurfaceCollectionsBuilderKey /*key*/ ) + const detail::InputFiles& files, SurfaceCollectionsBuilderKey /*key*/ ) { - impl_->load_components( - absl::StrCat( directory, "/surface_collections" ), false ); + impl_->load_components( files, "surface_collections", false ); } template < index_t dimension > diff --git a/src/geode/model/mixin/core/surfaces.cpp b/src/geode/model/mixin/core/surfaces.cpp index dfbfc07ce..bbfa66adc 100644 --- a/src/geode/model/mixin/core/surfaces.cpp +++ b/src/geode/model/mixin/core/surfaces.cpp @@ -87,14 +87,15 @@ namespace std::unique_ptr< geode::SurfaceMesh< dimension > > load_grid_surface( const geode::MeshType& type, const geode::MeshImpl& impl, - std::string_view file ) + const geode::detail::InputFiles& files, + std::string_view name ) { if constexpr( dimension == 2 ) { if( type == geode::RegularGrid< 2 >::type_name_static() ) { - return geode::load_one( - geode::load_regular_grid< 2 >( impl, file ), file ); + return geode::detail::load_component_mesh< + geode::RegularGridInputFactory< 2 > >( files, name, impl ); } } return nullptr; @@ -197,15 +198,15 @@ namespace geode template < index_t dimension > void Surfaces< dimension >::load_surfaces( - std::string_view directory, SurfacesBuilderKey key ) + const detail::InputFiles& files, SurfacesBuilderKey key ) { - impl_->load_components( absl::StrCat( directory, "/surfaces" ) ); - const auto mapping = impl_->file_mapping( directory ); + impl_->load_components( files, "surfaces", true ); + const auto mapping = impl_->file_mapping( files ); absl::FixedArray< async::task< void > > tasks( nb_surfaces() ); index_t count{ 0 }; for( auto& surface : modifiable_surfaces( key ) ) { - tasks[count++] = async::spawn( [&surface, &mapping] { + tasks[count++] = async::spawn( [&surface, &mapping, &files] { const auto file = mapping.find( surface.id().string() ); if( file == mapping.end() ) { @@ -215,22 +216,23 @@ namespace geode typename Surface< dimension >::SurfacesKey{} ); return; } + const auto& name = file->second; const auto impl = detail::loadable_mesh_impl( surface.mesh_type(), - surface_type_from_file< dimension >( file->second ), - file->second ); + surface_type_from_file< dimension >( name ), + files.location( name ) ); const auto& type = MeshFactory::type( impl ); if( type == TriangulatedSurface< dimension >::type_name_static() ) { surface.set_mesh( - load_one( load_triangulated_surface< dimension >( - impl, file->second ), - file->second ), + detail::load_component_mesh< + TriangulatedSurfaceInputFactory< dimension > >( + files, name, impl ), typename Surface< dimension >::SurfacesKey{} ); } else if( auto grid = load_grid_surface< dimension >( - type, impl, file->second ) ) + type, impl, files, name ) ) { surface.set_mesh( std::move( grid ), typename Surface< dimension >::SurfacesKey{} ); @@ -238,9 +240,9 @@ namespace geode else { surface.set_mesh( - load_one( load_polygonal_surface< dimension >( - impl, file->second ), - file->second ), + detail::load_component_mesh< + PolygonalSurfaceInputFactory< dimension > >( + files, name, impl ), typename Surface< dimension >::SurfacesKey{} ); } } ); diff --git a/src/geode/model/mixin/core/vertex_identifier.cpp b/src/geode/model/mixin/core/vertex_identifier.cpp index a24634140..86342159d 100644 --- a/src/geode/model/mixin/core/vertex_identifier.cpp +++ b/src/geode/model/mixin/core/vertex_identifier.cpp @@ -36,13 +36,13 @@ #include #include +#include #include #include #include #include -#include #include #include #include @@ -66,7 +66,7 @@ namespace geode } ComponentMeshVertex::ComponentMeshVertex() - : component_id( bitsery::Access::create< ComponentID >() ) + : component_id( BITSERY::constructor ) { } @@ -111,21 +111,32 @@ namespace geode struct RegisteredComponent { - explicit RegisteredComponent( - std::shared_ptr< VariableAttribute< index_t > > attribute_in ) - : attribute( std::move( attribute_in ) ) + RegisteredComponent( ComponentID component_id_in, + std::shared_ptr< VariableAttribute< index_t > > attribute_in, + index_t registration_in ) + : component_id( std::move( component_id_in ) ), + attribute( std::move( attribute_in ) ), + registration( registration_in ) { } RegisteredComponent( RegisteredComponent&& other ) noexcept - : attribute( std::move( other.attribute ) ), + : component_id( std::move( other.component_id ) ), + attribute( std::move( other.attribute ) ), + registration( other.registration ), nb_component_mesh_vertices( other.nb_component_mesh_vertices.load( std::memory_order_relaxed ) ) { } + ComponentID component_id; std::shared_ptr< VariableAttribute< index_t > > attribute; + /*! + * Registration rank, giving a deterministic component order to + * the rebuild of component_vertices_ + */ + index_t registration; /*! * Number of ComponentMeshVertex of this component stored in * component_vertices_. Used to detect inconsistencies between @@ -135,33 +146,13 @@ namespace geode }; public: - Impl() - { - AttributeProperties attribute_properties; - attribute_properties.assignable = false; - attribute_properties.interpolable = false; - attribute_properties.transferable = false; - AttributeValues< std::vector< ComponentMeshVertex > > - component_vertices_attribute_values; - component_vertices_attribute_values.default_value = {}; - const auto unique_vertices_attribute_id = - unique_vertices_.vertex_attribute_manager() - .create_attribute< VariableAttribute, - std::vector< ComponentMeshVertex > >( - "component vertices", - component_vertices_attribute_values, - attribute_properties ); - component_vertices_ = unique_vertices_.vertex_attribute_manager() - .find_attribute< VariableAttribute, - std::vector< ComponentMeshVertex > >( - unique_vertices_attribute_id ); - } + Impl() = default; - Impl( BITSERY ) {} + Impl( BITSERY bitsery ) : unique_vertex_id_{ bitsery } {} index_t nb_unique_vertices() const { - return unique_vertices_.nb_vertices(); + return static_cast< index_t >( component_vertices_.size() ); } bool is_unique_vertex_isolated( index_t unique_vertex_id ) const @@ -177,7 +168,7 @@ namespace geode "[VertexIdentifier::component_mesh_vertices] Given " "unique_vertex_id is bigger than the number of unique " "vertices." ); - return component_vertices_->value( unique_vertex_id ); + return component_vertices_[unique_vertex_id]; } index_t unique_vertex( @@ -236,11 +227,13 @@ namespace geode .template create_attribute< VariableAttribute, index_t >( UNIQUE_VERTICES_NAME, unique_vertex_id_, unique_vertex_attribute_values, attribute_properties ); - const auto [_, inserted] = - vertex2unique_vertex_.try_emplace( component.id(), - mesh.vertex_attribute_manager() - .template find_attribute< VariableAttribute, index_t >( - unique_vertex_id_ ) ); + const auto [_, inserted] = vertex2unique_vertex_.try_emplace( + component.id(), component.component_id(), + mesh.vertex_attribute_manager() + .template find_attribute< VariableAttribute, index_t >( + unique_vertex_id_ ), + nb_registrations_ ); + nb_registrations_++; OpenGeodeModelException::check_exception( inserted, component.component_id(), OpenGeodeException::TYPE::data, "[VertexIdentifier::register_component] Component ", @@ -257,11 +250,13 @@ namespace geode import_old_attribute_based_on_name( mesh.vertex_attribute_manager(), mesh.nb_vertices() ); } - const auto [_, inserted] = - vertex2unique_vertex_.try_emplace( component.id(), - mesh.vertex_attribute_manager() - .template find_attribute< VariableAttribute, index_t >( - unique_vertex_id_ ) ); + const auto [_, inserted] = vertex2unique_vertex_.try_emplace( + component.id(), component.component_id(), + mesh.vertex_attribute_manager() + .template find_attribute< VariableAttribute, index_t >( + unique_vertex_id_ ), + nb_registrations_ ); + nb_registrations_++; OpenGeodeModelException::check_exception( inserted, component.component_id(), OpenGeodeException::TYPE::data, "[VertexIdentifier::load_component] Component ", @@ -287,14 +282,14 @@ namespace geode index_t create_unique_vertex() { - return VertexSetBuilder::create( unique_vertices_ ) - ->create_vertex(); + return create_unique_vertices( 1 ); } index_t create_unique_vertices( const index_t nb ) { - return VertexSetBuilder::create( unique_vertices_ ) - ->create_vertices( nb ); + const auto first = nb_unique_vertices(); + component_vertices_.resize( component_vertices_.size() + nb ); + return first; } void set_unique_vertex( ComponentMeshVertex component_vertex_id, @@ -316,17 +311,14 @@ namespace geode } component.attribute->set_value( component_vertex_id.vertex, unique_vertex_id ); - component_vertices_->modify_value( unique_vertex_id, - [&component_vertex_id, &component]( - std::vector< ComponentMeshVertex >& value ) { - if( absl::c_find( value, component_vertex_id ) - == value.end() ) - { - value.emplace_back( std::move( component_vertex_id ) ); - component.nb_component_mesh_vertices.fetch_add( - 1, std::memory_order_relaxed ); - } - } ); + auto& vertices = component_vertices_[unique_vertex_id]; + if( absl::c_find( vertices, component_vertex_id ) + == vertices.end() ) + { + vertices.emplace_back( std::move( component_vertex_id ) ); + component.nb_component_mesh_vertices.fetch_add( + 1, std::memory_order_relaxed ); + } } void unset_unique_vertex( @@ -343,8 +335,7 @@ namespace geode const index_t unique_vertex_id ) { component.attribute->set_value( component_vertex_id.vertex, NO_ID ); - const auto& vertices = - component_vertices_->value( unique_vertex_id ); + auto& vertices = component_vertices_[unique_vertex_id]; const auto it = absl::c_find( vertices, component_vertex_id ); if( it == vertices.end() ) { @@ -352,12 +343,7 @@ namespace geode } component.nb_component_mesh_vertices.fetch_sub( 1, std::memory_order_relaxed ); - component_vertices_->modify_value( unique_vertex_id, - [&it]( std::vector< ComponentMeshVertex >& value ) { - value.erase( - // workaround for gcc < 4.9 - value.begin() + ( it - value.cbegin() ) ); - } ); + vertices.erase( it ); } void update_unique_vertices( const ComponentID& component_id, @@ -371,12 +357,12 @@ namespace geode { return; } - const auto& all_vertices = component_vertices_->value( uv ); + auto& all_vertices = component_vertices_[uv]; std::vector< bool > to_delete( all_vertices.size(), false ); bool need_to_delete{ false }; for( const auto v : Indices{ all_vertices } ) { - const auto& cmv = all_vertices[v]; + auto& cmv = all_vertices[v]; if( cmv.component_id.id != component_id.id ) { continue; @@ -389,11 +375,7 @@ namespace geode } else { - component_vertices_->modify_value( uv, - [v, new_id]( std::vector< ComponentMeshVertex >& - vertices ) { - vertices[v].vertex = new_id; - } ); + cmv.vertex = new_id; } } if( need_to_delete ) @@ -402,11 +384,7 @@ namespace geode static_cast< index_t >( absl::c_count( to_delete, true ) ), std::memory_order_relaxed ); - component_vertices_->modify_value( uv, - [&to_delete]( - std::vector< ComponentMeshVertex >& vertices ) { - delete_vector_elements( to_delete, vertices ); - } ); + delete_vector_elements( to_delete, all_vertices ); } } ); const auto component_it = @@ -438,14 +416,30 @@ namespace geode absl::c_iota( old2new, index_t{ 0 } ); return old2new; } - const auto old2new = VertexSetBuilder::create( unique_vertices_ ) - ->delete_vertices( to_delete ); + std::vector< index_t > old2new( nb_vertices ); + index_t nb_kept{ 0 }; + for( const auto v : Range{ nb_vertices } ) + { + if( to_delete[v] ) + { + old2new[v] = NO_ID; + continue; + } + old2new[v] = nb_kept; + if( nb_kept != v ) + { + component_vertices_[nb_kept] = + std::move( component_vertices_[v] ); + } + nb_kept++; + } + component_vertices_.resize( nb_kept ); // Unique vertices before the first deleted one keep their index const uuid* last_component{ nullptr }; VariableAttribute< index_t >* attribute{ nullptr }; for( const auto uv : Range{ first_deleted, nb_unique_vertices() } ) { - for( const auto& cmv : component_vertices_->value( uv ) ) + for( const auto& cmv : component_vertices_[uv] ) { if( !last_component || *last_component != cmv.component_id.id ) @@ -474,13 +468,18 @@ namespace geode void repair_component_vertices() { + if( rebuild_component_vertices_ ) + { + rebuild_component_vertices(); + return; + } // Read-only parallel scan, nothing to repair in a valid model std::vector< uint8_t > to_repair( nb_unique_vertices(), 0 ); async::parallel_for( async::irange( index_t{ 0 }, nb_unique_vertices() ), [this, &to_repair]( index_t unique_vertex ) { for( const auto& vertex : - component_vertices_->value( unique_vertex ) ) + component_vertices_[unique_vertex] ) { if( !is_linked_to_unique_vertex( vertex, unique_vertex ) ) @@ -504,6 +503,80 @@ namespace geode repair.log(); } + /*! + * Rebuild component_vertices_ from the component mesh attributes. + * Components are visited in their registration order (the model + * component order when loading), then their vertices in increasing + * order: the result does not depend on hash order. + */ + void rebuild_component_vertices() + { + rebuild_component_vertices_ = false; + std::vector< RegisteredComponent* > components; + components.reserve( vertex2unique_vertex_.size() ); + for( auto& [_, component] : vertex2unique_vertex_ ) + { + components.push_back( &component ); + } + absl::c_sort( components, []( const RegisteredComponent* lhs, + const RegisteredComponent* rhs ) { + return lhs->registration < rhs->registration; + } ); + const auto nb_vertices = nb_unique_vertices(); + std::vector< index_t > nb_component_vertices( nb_vertices, 0 ); + index_t nb_invalid_links{ 0 }; + for( auto* component : components ) + { + auto& attribute = *component->attribute; + for( const auto v : Range{ attribute.size() } ) + { + const auto unique_vertex = attribute.value( v ); + if( unique_vertex == NO_ID ) + { + continue; + } + if( unique_vertex >= nb_vertices ) + { + attribute.set_value( v, NO_ID ); + nb_invalid_links++; + continue; + } + nb_component_vertices[unique_vertex]++; + } + } + for( const auto unique_vertex : Range{ nb_vertices } ) + { + auto& vertices = component_vertices_[unique_vertex]; + vertices.clear(); + vertices.reserve( nb_component_vertices[unique_vertex] ); + } + for( auto* component : components ) + { + const auto& attribute = *component->attribute; + index_t nb_vertices_in_component{ 0 }; + for( const auto v : Range{ attribute.size() } ) + { + const auto unique_vertex = attribute.value( v ); + if( unique_vertex == NO_ID ) + { + continue; + } + component_vertices_[unique_vertex].emplace_back( + component->component_id, v ); + nb_vertices_in_component++; + } + component->nb_component_mesh_vertices.store( + nb_vertices_in_component, std::memory_order_relaxed ); + } + nb_component_mesh_vertices_up_to_date_ = true; + if( nb_invalid_links > 0 ) + { + Logger::warning( "[VertexIdentifier::load] Removed ", + nb_invalid_links, + " component vertex links to unknown unique vertices" ); + } + } + void save( std::string_view directory ) const { const auto filename = absl::StrCat( directory, "/vertices" ); @@ -525,85 +598,126 @@ namespace geode filename ); } - void load( std::string_view directory ) + void load( const detail::InputFiles& files ) { - const auto filename = absl::StrCat( directory, "/vertices" ); - std::ifstream file{ std::filesystem::u8path( filename ), - std::ifstream::binary }; - TContext context{}; - BitseryExtensions::register_deserialize_pcontext( - std::get< 0 >( context ) ); - Deserializer archive{ context, file }; - archive.object( *this ); - nb_component_mesh_vertices_up_to_date_ = false; - const auto& adapter = archive.adapter(); - OpenGeodeModelException::check_exception( - adapter.error() == bitsery::ReaderError::NoError - && adapter.isCompletedSuccessfully() - && std::get< 1 >( context ).isValid(), + static constexpr auto FILENAME = "vertices"; + const auto filename = files.location( FILENAME ); + OpenGeodeModelException::check_exception( files.has( FILENAME ), nullptr, OpenGeodeException::TYPE::internal, "[VertexIdentifier::load] Error while reading file: ", filename ); + const auto content = files.content( FILENAME ); + // Versions before 5 store the component vertices and reset this + // flag + component_vertices_.clear(); + rebuild_component_vertices_ = true; + const auto success = + detail::deserialize_bytes( content.span(), *this ); + nb_component_mesh_vertices_up_to_date_ = false; + OpenGeodeModelException::check_exception( success, nullptr, + OpenGeodeException::TYPE::internal, + "[VertexIdentifier::load] Error while reading file: ", + filename ); } private: friend class bitsery::Access; + using LegacyComponentVertices = + VariableAttribute< std::vector< ComponentMeshVertex > >; + + /*! + * Versions 1 to 4 stored the unique vertices as a vertex set holding + * the component vertices in an attribute. + */ + template < typename Archive > + void serialize_legacy_unique_vertices( Archive& archive ) + { + OpenGeodeVertexSet unique_vertices{ BITSERY::constructor }; + std::shared_ptr< LegacyComponentVertices > component_vertices; + archive.object( unique_vertices ); + archive.ext( component_vertices, bitsery::ext::StdSmartPtr{} ); + set_legacy_component_vertices( + component_vertices, unique_vertices.nb_vertices() ); + } + + template < typename Archive > + static void serialize_legacy_map( Archive& archive ) + { + absl::flat_hash_map< uuid, + std::shared_ptr< VariableAttribute< index_t > > > + old_map; + archive.ext( old_map, bitsery::ext::StdMap{ old_map.max_size() }, + []( Archive& archive2, uuid& id, + std::shared_ptr< VariableAttribute< index_t > >& + attribute ) { + archive2.object( id ); + archive2.ext( attribute, bitsery::ext::StdSmartPtr{} ); + } ); + } + + void set_legacy_component_vertices( + const std::shared_ptr< LegacyComponentVertices >& + component_vertices, + index_t nb_unique_vertices ) + { + component_vertices_.resize( nb_unique_vertices ); + rebuild_component_vertices_ = false; + if( !component_vertices ) + { + return; + } + const auto nb_values = + std::min( nb_unique_vertices, component_vertices->size() ); + for( const auto uv : Range{ nb_values } ) + { + component_vertices->modify_value( uv, + [this, uv]( std::vector< ComponentMeshVertex >& value ) { + component_vertices_[uv] = std::move( value ); + } ); + } + } + template < typename Archive > void serialize( Archive& serializer ) { serializer.ext( *this, Growable< Archive, Impl >{ { []( Archive& archive, Impl& impl ) { - archive.object( impl.unique_vertices_ ); - archive.ext( impl.component_vertices_, - bitsery::ext::StdSmartPtr{} ); - absl::flat_hash_map< uuid, - std::shared_ptr< VariableAttribute< index_t > > > - old_map; - archive.ext( old_map, - bitsery::ext::StdMap{ old_map.max_size() }, - []( Archive& archive2, uuid& id, - std::shared_ptr< VariableAttribute< - index_t > >& attribute ) { - archive2.object( id ); - archive2.ext( - attribute, bitsery::ext::StdSmartPtr{} ); - } ); - const auto& old_component_vertices_properties = - impl.component_vertices_->properties(); - impl.component_vertices_->set_properties( - { old_component_vertices_properties.assignable, - old_component_vertices_properties.interpolable, - false } ); + // Not stored in this version + impl.unique_vertex_id_ = uuid{}; + impl.serialize_legacy_unique_vertices( archive ); + serialize_legacy_map( archive ); }, []( Archive& archive, Impl& impl ) { - archive.object( impl.unique_vertices_ ); - archive.ext( impl.component_vertices_, - bitsery::ext::StdSmartPtr{} ); - absl::flat_hash_map< uuid, - std::shared_ptr< - VariableAttribute< index_t > > > - old_map; - archive.ext( old_map, - bitsery::ext::StdMap{ old_map.max_size() }, - []( Archive& archive2, uuid& id, - std::shared_ptr< VariableAttribute< - index_t > >& attribute ) { - archive2.object( id ); - archive2.ext( attribute, - bitsery::ext::StdSmartPtr{} ); - } ); + // Not stored in this version + impl.unique_vertex_id_ = uuid{}; + impl.serialize_legacy_unique_vertices( archive ); + serialize_legacy_map( archive ); + }, + []( Archive& archive, Impl& impl ) { + // Not stored in this version + impl.unique_vertex_id_ = uuid{}; + impl.serialize_legacy_unique_vertices( archive ); }, []( Archive& archive, Impl& impl ) { - archive.object( impl.unique_vertices_ ); - archive.ext( impl.component_vertices_, - bitsery::ext::StdSmartPtr{} ); + impl.serialize_legacy_unique_vertices( archive ); + archive.object( impl.unique_vertex_id_ ); }, []( Archive& archive, Impl& impl ) { - archive.object( impl.unique_vertices_ ); - archive.ext( impl.component_vertices_, - bitsery::ext::StdSmartPtr{} ); + // Component vertices are not stored, they are + // rebuilt from the component mesh attributes + // (see rebuild_component_vertices). Loading + // starts from an empty Impl, so the size only + // changes on reading. + auto nb_unique_vertices = impl.nb_unique_vertices(); + archive.value4b( nb_unique_vertices ); archive.object( impl.unique_vertex_id_ ); + if( nb_unique_vertices + != impl.nb_unique_vertices() ) + { + impl.component_vertices_.resize( + nb_unique_vertices ); + } } } } ); } @@ -661,28 +775,20 @@ namespace geode index_t filter_unique_vertex( index_t unique_vertex_id, const uuid& component_id ) { - const auto& component_mesh_vertices = - component_vertices_->value( unique_vertex_id ); + auto& vertices = component_vertices_[unique_vertex_id]; const auto is_component = [&component_id]( const ComponentMeshVertex& cmv ) { return cmv.component_id.id == component_id; }; - if( absl::c_none_of( component_mesh_vertices, is_component ) ) + if( absl::c_none_of( vertices, is_component ) ) { return 0; } - index_t nb_removed{ 0 }; - component_vertices_->modify_value( unique_vertex_id, - [&is_component, &nb_removed]( - std::vector< ComponentMeshVertex >& vertices ) { - const auto old_size = vertices.size(); - vertices.erase( std::remove_if( vertices.begin(), - vertices.end(), is_component ), - vertices.end() ); - nb_removed = - static_cast< index_t >( old_size - vertices.size() ); - } ); - return nb_removed; + const auto old_size = vertices.size(); + vertices.erase( std::remove_if( vertices.begin(), vertices.end(), + is_component ), + vertices.end() ); + return static_cast< index_t >( old_size - vertices.size() ); } void filter_component_vertices( const uuid& component_id ) @@ -707,7 +813,7 @@ namespace geode } for( const auto uv : Range{ nb_unique_vertices() } ) { - for( const auto& cmv : component_vertices_->value( uv ) ) + for( const auto& cmv : component_vertices_[uv] ) { const auto it = vertex2unique_vertex_.find( cmv.component_id.id ); @@ -832,7 +938,7 @@ namespace geode void repair_unique_vertex( index_t unique_vertex, ComponentVerticesRepair& repair ) { - const auto& vertices = component_vertices_->value( unique_vertex ); + auto& vertices = component_vertices_[unique_vertex]; std::vector< bool > to_keep( vertices.size(), true ); bool update{ false }; for( const auto v : Indices{ vertices } ) @@ -870,18 +976,24 @@ namespace geode } if( update ) { - component_vertices_->set_value( unique_vertex, - extract_vector_elements( to_keep, vertices ) ); + vertices = extract_vector_elements( to_keep, vertices ); } } - OpenGeodeVertexSet unique_vertices_; - std::shared_ptr< - VariableAttribute< std::vector< ComponentMeshVertex > > > - component_vertices_; + /*! + * Component mesh vertices of each unique vertex, its size is the + * number of unique vertices + */ + std::vector< std::vector< ComponentMeshVertex > > component_vertices_; absl::flat_hash_map< uuid, RegisteredComponent > vertex2unique_vertex_; geode::uuid unique_vertex_id_; + index_t nb_registrations_{ 0 }; bool nb_component_mesh_vertices_up_to_date_{ true }; + /*! + * True after loading a file not storing the component vertices: + * repair_component_vertices rebuilds them + */ + bool rebuild_component_vertices_{ false }; }; VertexIdentifier::VertexIdentifier() = default; @@ -1000,9 +1112,9 @@ namespace geode } void VertexIdentifier::load_unique_vertices( - std::string_view directory, BuilderKey /*key*/ ) + const detail::InputFiles& files, BuilderKey /*key*/ ) { - return impl_->load( directory ); + return impl_->load( files ); } std::vector< index_t > VertexIdentifier::delete_isolated_vertices( diff --git a/src/geode/model/representation/io/external_time_series_input.cpp b/src/geode/model/representation/io/external_time_series_input.cpp index 80cc38cf3..c2c287aae 100644 --- a/src/geode/model/representation/io/external_time_series_input.cpp +++ b/src/geode/model/representation/io/external_time_series_input.cpp @@ -23,8 +23,6 @@ #include -#include - #include #include #include @@ -44,22 +42,14 @@ namespace geode "[load_external_time_series] Wrong extension for file ", filename, ", only ", ExternalTimeSeries::native_extension_static(), " is supported" ); - std::ifstream file{ to_string( filename ), std::ifstream::binary }; - OpenGeodeModelException::check_exception( !file.fail(), nullptr, + const auto content = detail::map_file_content( filename ); + OpenGeodeModelException::check_exception( content.has_value(), nullptr, OpenGeodeException::TYPE::data, "[load_external_time_series] Failed to open file: ", filename ); - TContext context{}; - BitseryExtensions::register_deserialize_pcontext( - std::get< 0 >( context ) ); - Deserializer archive{ context, file }; ExternalTimeSeries time_series; - archive.object( time_series ); - const auto& adapter = archive.adapter(); OpenGeodeModelException::check_exception( - adapter.error() == bitsery::ReaderError::NoError - && adapter.isCompletedSuccessfully() - && std::get< 1 >( context ).isValid(), - nullptr, OpenGeodeException::TYPE::internal, + detail::deserialize_bytes( content->span(), time_series ), nullptr, + OpenGeodeException::TYPE::internal, "[load_external_time_series] Error while reading file: ", filename ); Logger::info( "ExternalTimeSeries loaded from ", filename, " in ", diff --git a/src/geode/model/representation/io/geode/geode_brep_input.cpp b/src/geode/model/representation/io/geode/geode_brep_input.cpp index 37c0047c6..cbf9c5fd2 100644 --- a/src/geode/model/representation/io/geode/geode_brep_input.cpp +++ b/src/geode/model/representation/io/geode/geode_brep_input.cpp @@ -24,8 +24,7 @@ #include #include -#include -#include +#include #include #include @@ -42,10 +41,9 @@ namespace geode { std::vector< BRep > OpenGeodeBRepInput::read() { - const UnzipFile zip_reader{ filename(), uuid{}.string() }; - zip_reader.extract_all(); + const detail::ArchiveInputFiles files{ filename() }; BRep brep{ BITSERY::constructor }; - detail::load_brep_files( brep, zip_reader.directory() ); + detail::load_brep_files( brep, files ); std::vector< BRep > breps; breps.emplace_back( std::move( brep ) ); return breps; diff --git a/src/geode/model/representation/io/geode/geode_section_input.cpp b/src/geode/model/representation/io/geode/geode_section_input.cpp index 52a57cd5a..ad1c3f47c 100644 --- a/src/geode/model/representation/io/geode/geode_section_input.cpp +++ b/src/geode/model/representation/io/geode/geode_section_input.cpp @@ -26,8 +26,7 @@ #include #include -#include -#include +#include #include #include @@ -42,10 +41,9 @@ namespace geode { std::vector< Section > OpenGeodeSectionInput::read() { - const UnzipFile zip_reader{ filename(), uuid{}.string() }; - zip_reader.extract_all(); + const detail::ArchiveInputFiles files{ filename() }; Section section{ BITSERY::constructor }; - detail::load_section_files( section, zip_reader.directory() ); + detail::load_section_files( section, files ); std::vector< Section > sections; sections.emplace_back( std::move( section ) ); return sections; diff --git a/tests/basic/CMakeLists.txt b/tests/basic/CMakeLists.txt index 36e57b511..b0a312242 100644 --- a/tests/basic/CMakeLists.txt +++ b/tests/basic/CMakeLists.txt @@ -70,6 +70,12 @@ add_geode_test( DEPENDENCIES ${PROJECT_NAME}::basic ) +add_geode_test( + SOURCE "test-input-files.cpp" + DEPENDENCIES + Async++ + ${PROJECT_NAME}::basic +) add_geode_test( SOURCE "test-logger.cpp" DEPENDENCIES @@ -111,3 +117,12 @@ add_geode_test( DEPENDENCIES ${PROJECT_NAME}::basic ) +if(UNIX AND NOT APPLE AND BUILD_SHARED_LIBS AND CMAKE_NM) + add_test( + NAME test-hidden-zlib-symbols + COMMAND ${CMAKE_COMMAND} + -DNM=${CMAKE_NM} + -DLIBRARY=$ + -P ${CMAKE_CURRENT_SOURCE_DIR}/check-hidden-symbols.cmake + ) +endif() diff --git a/tests/basic/check-hidden-symbols.cmake b/tests/basic/check-hidden-symbols.cmake new file mode 100644 index 000000000..65e5dcb1e --- /dev/null +++ b/tests/basic/check-hidden-symbols.cmake @@ -0,0 +1,38 @@ +# Copyright (c) 2019 - 2026 Geode-solutions +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +# Fails if LIBRARY exports a zlib or minizip-ng symbol (they must stay private) +execute_process( + COMMAND "${NM}" -D --defined-only "${LIBRARY}" + OUTPUT_VARIABLE symbols + RESULT_VARIABLE result +) +if(NOT result EQUAL 0) + message(FATAL_ERROR "[Test] nm failed on ${LIBRARY}") +endif() +string(REGEX MATCHALL + "[ \t](crc32|crc32_z|inflate|inflateInit2_|deflate|deflateInit2_|mz_[A-Za-z0-9_]+)\n" + exported "${symbols}\n" +) +if(exported) + string(REGEX REPLACE "[ \t\n]" "" exported "${exported}") + message(FATAL_ERROR "[Test] ${LIBRARY} exports zlib/minizip-ng symbols: ${exported}") +endif() +message(STATUS "[Test] no zlib/minizip-ng symbol exported by ${LIBRARY}") diff --git a/tests/basic/test-attribute.cpp b/tests/basic/test-attribute.cpp index 1ca08cbc1..7eeefe613 100644 --- a/tests/basic/test-attribute.cpp +++ b/tests/basic/test-attribute.cpp @@ -31,6 +31,7 @@ #include #include #include +#include #include #include @@ -524,7 +525,9 @@ void test_serialize_manager( geode::AttributeManager& manager, geode::OpenGeodeBasicException::test( std::get< 1 >( context ).isValid(), "Error while writing file: ", filename ); - std::ifstream infile{ filename, std::ifstream::binary }; + const auto content = geode::detail::map_file_content( filename ); + geode::OpenGeodeBasicException::test( + content.has_value(), "Cannot open file: ", filename ); geode::AttributeManager reloaded_manager; geode::TContext reload_context{}; geode::register_attribute_type< std::array< double, 30 >, @@ -536,7 +539,8 @@ void test_serialize_manager( geode::AttributeManager& manager, geode::register_attribute_type< std::array< double, 2 >, geode::Deserializer >( std::get< 0 >( reload_context ), "array_double_2" ); - geode::Deserializer unarchive{ reload_context, infile }; + geode::Deserializer unarchive{ reload_context, content->span().data(), + content->span().size() }; unarchive.object( reloaded_manager ); const auto& adapter = unarchive.adapter(); geode::OpenGeodeBasicException::test( @@ -925,12 +929,15 @@ void test_no_value() geode::OpenGeodeBasicException::test( std::get< 1 >( context ).isValid(), "Error while writing file: ", filename ); - std::ifstream infile{ filename, std::ifstream::binary }; + const auto content = geode::detail::map_file_content( filename ); + geode::OpenGeodeBasicException::test( + content.has_value(), "Cannot open file: ", filename ); geode::AttributeManager reloaded_manager; geode::TContext reload_context{}; geode::register_basic_deserialize_pcontext( std::get< 0 >( reload_context ) ); - geode::Deserializer unarchive{ reload_context, infile }; + geode::Deserializer unarchive{ reload_context, content->span().data(), + content->span().size() }; unarchive.object( reloaded_manager ); const auto& adapter = unarchive.adapter(); geode::OpenGeodeBasicException::test( @@ -1124,7 +1131,8 @@ void test_time_series_serialization( const geode::AttributeManager& manager ) geode::TContext reload_context{}; geode::register_basic_deserialize_pcontext( std::get< 0 >( reload_context ) ); - geode::Deserializer unarchive{ reload_context, stream }; + const auto bytes = stream.str(); + geode::Deserializer unarchive{ reload_context, bytes.data(), bytes.size() }; unarchive.object( reloaded ); geode::OpenGeodeBasicException::test( unarchive.adapter().error() == bitsery::ReaderError::NoError, diff --git a/tests/basic/test-growable.cpp b/tests/basic/test-growable.cpp index 02faf7fc3..e00356d73 100644 --- a/tests/basic/test-growable.cpp +++ b/tests/basic/test-growable.cpp @@ -24,6 +24,7 @@ #include #include +#include #include #include @@ -110,9 +111,13 @@ Out test_growable( const T &foo ) serializer.object( foo ); serializer.adapter().flush(); - std::ifstream input{ "name", std::ifstream::binary }; + output.close(); + const auto content = geode::detail::map_file_content( "name" ); + geode::OpenGeodeBasicException::test( + content.has_value(), "Cannot open file" ); geode::TContext context_input{}; - geode::Deserializer deserializer{ context_input, input }; + geode::Deserializer deserializer{ context_input, content->span().data(), + content->span().size() }; Out new_foo; deserializer.object( new_foo ); const auto &adapter = deserializer.adapter(); diff --git a/tests/basic/test-input-files.cpp b/tests/basic/test-input-files.cpp new file mode 100644 index 000000000..474ba38b4 --- /dev/null +++ b/tests/basic/test-input-files.cpp @@ -0,0 +1,598 @@ +/* + * Copyright (c) 2019 - 2026 Geode-solutions + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include + +#include +#include +#include +#include +#include + +#include + +using Entries = std::vector< std::pair< std::string, std::string > >; + +std::string as_string( geode::ByteSpan bytes ) +{ + return { bytes.data(), bytes.size() }; +} + +void write_file( const std::filesystem::path& file, std::string_view content ) +{ + std::ofstream stream{ file, std::ios::binary }; + stream.write( + content.data(), static_cast< std::streamsize >( content.size() ) ); + geode::OpenGeodeBasicException::test( + stream.good(), "Cannot write file ", file.u8string() ); +} + +void append_uint( std::string& data, uint32_t value, size_t size ) +{ + for( const auto i : geode::Range{ size } ) + { + data.push_back( static_cast< char >( ( value >> ( 8 * i ) ) & 0xFF ) ); + } +} + +uint32_t crc32( std::string_view content ) +{ + uint32_t crc{ 0xFFFFFFFF }; + for( const auto byte : content ) + { + crc ^= static_cast< unsigned char >( byte ); + for( const auto bit : geode::Range{ 8 } ) + { + geode_unused( bit ); + crc = ( crc >> 1 ) ^ ( 0xEDB88320 & ( 0 - ( crc & 1 ) ) ); + } + } + return ~crc; +} + +/*! + * Write a zip archive whose entries are stored (not compressed). + */ +void write_stored_zip( const std::string& zip, const Entries& entries ) +{ + std::string archive; + std::string central_directory; + for( const auto& [name, content] : entries ) + { + const auto offset = static_cast< uint32_t >( archive.size() ); + const auto crc = crc32( content ); + const auto size = static_cast< uint32_t >( content.size() ); + const auto name_size = static_cast< uint32_t >( name.size() ); + append_uint( archive, 0x04034b50, 4 ); // local header signature + append_uint( archive, 20, 2 ); // version needed + append_uint( archive, 0, 2 ); // flags + append_uint( archive, 0, 2 ); // method: store + append_uint( archive, 0, 2 ); // time + append_uint( archive, 0x21, 2 ); // date: 1980-01-01 + append_uint( archive, crc, 4 ); + append_uint( archive, size, 4 ); // compressed size + append_uint( archive, size, 4 ); // uncompressed size + append_uint( archive, name_size, 2 ); + append_uint( archive, 0, 2 ); // extra field length + absl::StrAppend( &archive, name, content ); + append_uint( central_directory, 0x02014b50, 4 ); + append_uint( central_directory, 20, 2 ); // version made by + append_uint( central_directory, 20, 2 ); // version needed + append_uint( central_directory, 0, 2 ); // flags + append_uint( central_directory, 0, 2 ); // method: store + append_uint( central_directory, 0, 2 ); // time + append_uint( central_directory, 0x21, 2 ); // date: 1980-01-01 + append_uint( central_directory, crc, 4 ); + append_uint( central_directory, size, 4 ); // compressed size + append_uint( central_directory, size, 4 ); // uncompressed size + append_uint( central_directory, name_size, 2 ); + append_uint( central_directory, 0, 2 ); // extra field length + append_uint( central_directory, 0, 2 ); // comment length + append_uint( central_directory, 0, 2 ); // disk number + append_uint( central_directory, 0, 2 ); // internal attributes + append_uint( central_directory, 0, 4 ); // external attributes + append_uint( central_directory, offset, 4 ); // local header offset + absl::StrAppend( ¢ral_directory, name ); + } + const auto central_directory_offset = + static_cast< uint32_t >( archive.size() ); + const auto nb_entries = static_cast< uint32_t >( entries.size() ); + absl::StrAppend( &archive, central_directory ); + append_uint( archive, 0x06054b50, 4 ); // end of central directory + append_uint( archive, 0, 2 ); // disk number + append_uint( archive, 0, 2 ); // disk of the central directory + append_uint( archive, nb_entries, 2 ); // entries on this disk + append_uint( archive, nb_entries, 2 ); // entries + append_uint( + archive, static_cast< uint32_t >( central_directory.size() ), 4 ); + append_uint( archive, central_directory_offset, 4 ); + append_uint( archive, 0, 2 ); // comment length + write_file( zip, archive ); +} + +/*! + * Archive written by Python zipfile with ZIP_DEFLATED, containing the + * test_entries() in the same order. + */ +std::string deflate_zip() +{ + return absl::StrCat( geode::DATA_PATH, "input_files_deflate.zip" ); +} + +Entries test_entries() +{ + std::string text; + for( const auto i : geode::Range{ 10000 } ) + { + absl::StrAppend( &text, "line ", i, " of a compressible file\n" ); + } + std::string binary; + for( const auto i : geode::Range{ 100000 } ) + { + binary.push_back( static_cast< char >( ( i * i ) % 7 ) ); + } + return { { "text.txt", text }, { "folder/binary.bin", binary }, + { "empty", "" }, { "small", "abc" } }; +} + +template < typename Function > +void check_data_error( Function&& function, + std::string_view expected_message, + std::string_view test_name ) +{ + try + { + function(); + } + catch( const geode::OpenGeodeException& exception ) + { + geode::OpenGeodeBasicException::test( + exception.type() == geode::OpenGeodeException::TYPE::data, + test_name, ": expected a data error, got ", exception.what() ); + geode::OpenGeodeBasicException::test( + absl::StrContains( exception.what(), expected_message ), test_name, + ": message \"", exception.what(), "\" does not contain ", + expected_message ); + return; + } + throw geode::OpenGeodeBasicException{ nullptr, + geode::OpenGeodeException::TYPE::internal, test_name, + ": no exception thrown" }; +} + +void check_files_content( const geode::detail::InputFiles& files, + const Entries& entries, + std::string_view test_name ) +{ + for( const auto& [name, content] : entries ) + { + geode::OpenGeodeBasicException::test( + files.has( name ), test_name, ": missing entry ", name ); + const auto file = files.content( name ); + geode::OpenGeodeBasicException::test( + as_string( file.span() ) == content, test_name, + ": wrong content of ", name ); + } + geode::OpenGeodeBasicException::test( + !files.has( "missing" ), test_name, ": unexpected entry" ); + check_data_error( + [&files] { + geode_unused( files.content( "missing" ) ); + }, + "missing", test_name ); +} + +void test_mapped_file() +{ + const std::string filename{ "mapped_file.bin" }; + const auto entries = test_entries(); + const auto& content = entries[1].second; + write_file( filename, content ); + { + const auto mapping = geode::detail::MappedFile::map( filename ); + geode::OpenGeodeBasicException::test( + mapping != nullptr, "[MappedFile] Cannot map a regular file" ); + geode::OpenGeodeBasicException::test( + as_string( mapping->span() ) == content, + "[MappedFile] Wrong mapped content" ); + // Released pages are mapped again when read + mapping->release( mapping->span().subspan( 10, 50000 ) ); + geode::OpenGeodeBasicException::test( + as_string( mapping->span() ) == content, + "[MappedFile] Wrong content after release" ); + geode::detail::FileContent slice{ mapping, + mapping->span().subspan( 100, 30000 ) }; + geode::OpenGeodeBasicException::test( + as_string( slice.span() ) == content.substr( 100, 30000 ), + "[MappedFile] Wrong slice" ); + const auto moved = std::move( slice ); + geode::OpenGeodeBasicException::test( + slice.span().empty() && moved.span().size() == 30000, + "[MappedFile] Wrong moved slice" ); + } + const auto mapped = geode::detail::map_file_content( filename ); + geode::OpenGeodeBasicException::test( + mapped.has_value() && as_string( mapped->span() ) == content, + "[map_file_content] Wrong content" ); + geode::OpenGeodeBasicException::test( + geode::detail::MappedFile::map( "missing_file.bin" ) == nullptr + && !geode::detail::map_file_content( "missing_file.bin" ), + "[MappedFile] Missing file should not be mapped" ); + const std::string empty{ "empty_file.bin" }; + write_file( empty, "" ); + const auto empty_content = geode::detail::map_file_content( empty ); + geode::OpenGeodeBasicException::test( + empty_content.has_value() && empty_content->span().empty(), + "[map_file_content] Wrong empty file content" ); + std::filesystem::remove( filename ); + std::filesystem::remove( empty ); +} + +void test_directory_input_files() +{ + const std::filesystem::path directory{ "input_files_directory" }; + std::filesystem::remove_all( directory ); + std::filesystem::create_directories( directory / "folder" ); + const auto entries = test_entries(); + for( const auto& [name, content] : entries ) + { + write_file( directory / name, content ); + } + const geode::detail::DirectoryInputFiles files{ directory.u8string() }; + check_files_content( files, entries, "[DirectoryInputFiles]" ); + const std::vector< std::string > expected_names{ "empty", "small", + "text.txt" }; + geode::OpenGeodeBasicException::test( files.names() == expected_names, + "[DirectoryInputFiles] Wrong names (not recursive, sorted)" ); + geode::OpenGeodeBasicException::test( + files.path( "small" ) == ( directory.u8string() + "/small" ) + && files.location( "small" ) == files.path( "small" ), + "[DirectoryInputFiles] Wrong path" ); + geode::OpenGeodeBasicException::test( !files.has( "folder" ), + "[DirectoryInputFiles] A directory is not a file" ); + geode::OpenGeodeBasicException::test( + !geode::detail::map_file_content( ( directory / "folder" ).u8string() ), + "[map_file_content] A directory has no content" ); + check_data_error( + [&files] { + geode_unused( files.content( "folder" ) ); + }, + "folder", "[DirectoryInputFiles] directory content" ); + std::filesystem::remove_all( directory ); +} + +void test_archive_input_files( + const std::string& zip, std::string_view test_name ) +{ + const auto entries = test_entries(); + const geode::detail::ArchiveInputFiles files{ zip }; + check_files_content( files, entries, test_name ); + std::vector< std::string > expected_names; + for( const auto& entry : entries ) + { + expected_names.push_back( entry.first ); + } + geode::OpenGeodeBasicException::test( + files.names() == expected_names, test_name, ": wrong names" ); + geode::OpenGeodeBasicException::test( + !files.path( "small" ).has_value() + && files.location( "small" ) == zip + "/small", + test_name, ": wrong path" ); + // Several threads can read the entries + std::vector< async::task< bool > > tasks; + for( const auto& entry : entries ) + { + tasks.push_back( async::spawn( [&files, &entry] { + const auto& [name, content] = entry; + return as_string( files.content( name ).span() ) == content; + } ) ); + } + for( auto& task : tasks ) + { + geode::OpenGeodeBasicException::test( + task.get(), test_name, ": wrong concurrent content" ); + } +} + +void test_stored_archive_input_files() +{ + const std::string zip{ "input_files_stored.zip" }; + write_stored_zip( zip, test_entries() ); + test_archive_input_files( zip, "[ArchiveInputFiles] stored" ); + std::filesystem::remove( zip ); +} + +std::string read_file( const std::string& file ) +{ + const auto content = geode::detail::map_file_content( file ); + geode::OpenGeodeBasicException::test( + content.has_value(), "Cannot read ", file ); + return as_string( content->span() ); +} + +void test_corrupted_entry() +{ + const std::string zip{ "corrupted_entry.zip" }; + const auto entries = test_entries(); + write_stored_zip( zip, entries ); + auto archive = read_file( zip ); + // Flip one byte in the middle of the stored text entry + const auto position = archive.find( "line 5000 " ); + geode::OpenGeodeBasicException::test( + position != std::string::npos, "Entry not found in the archive" ); + archive[position] = 'X'; + write_file( zip, archive ); + const geode::detail::ArchiveInputFiles files{ zip }; + check_data_error( + [&files] { + geode_unused( files.content( "text.txt" ) ); + }, + "text.txt", "[ArchiveInputFiles] corrupted entry" ); + // The other entries are still readable + geode::OpenGeodeBasicException::test( + as_string( files.content( "small" ).span() ) == "abc", + "[ArchiveInputFiles] Wrong entry next to a corrupted one" ); + std::filesystem::remove( zip ); +} + +uint32_t read_uint( const std::string& data, size_t offset, size_t size ) +{ + uint32_t value{ 0 }; + for( const auto i : geode::Range{ size } ) + { + value |= static_cast< uint32_t >( + static_cast< unsigned char >( data[offset + i] ) ) + << ( 8 * i ); + } + return value; +} + +void write_uint( std::string& data, size_t offset, size_t size, uint32_t value ) +{ + for( const auto i : geode::Range{ size } ) + { + data[offset + i] = static_cast< char >( ( value >> ( 8 * i ) ) & 0xFF ); + } +} + +/*! + * Return the offset of the central directory header of the given entry. + */ +size_t central_header( const std::string& archive, std::string_view name ) +{ + const std::string signature{ "PK\x01\x02" }; + for( auto position = archive.find( signature ); + position != std::string::npos; + position = archive.find( signature, position + 1 ) ) + { + const auto name_length = read_uint( archive, position + 28, 2 ); + if( archive.compare( position + 46, name_length, name ) == 0 + && name_length == name.size() ) + { + return position; + } + } + throw geode::OpenGeodeBasicException{ nullptr, + geode::OpenGeodeException::TYPE::internal, "Entry ", name, + " not found in the central directory" }; +} + +void test_corrupted_deflate_stream() +{ + const std::string zip{ "corrupted_deflate.zip" }; + auto archive = read_file( deflate_zip() ); + // First entry: its local header is at the start of the archive + geode::OpenGeodeBasicException::test( + archive.compare( 30, 8, "text.txt" ) == 0, + "[ArchiveInputFiles] text.txt should be the first entry" ); + const auto data = + 30 + read_uint( archive, 26, 2 ) + read_uint( archive, 28, 2 ); + // Final block of the reserved (invalid) block type 3 + archive[data] = static_cast< char >( 0x07 ); + write_file( zip, archive ); + const geode::detail::ArchiveInputFiles files{ zip }; + check_data_error( + [&files] { + geode_unused( files.content( "text.txt" ) ); + }, + "Cannot decompress zip entry corrupted_deflate.zip/text.txt", + "[ArchiveInputFiles] corrupted deflate stream" ); + geode::OpenGeodeBasicException::test( + as_string( files.content( "small" ).span() ) == "abc", + "[ArchiveInputFiles] Wrong entry next to a corrupted deflate stream" ); + std::filesystem::remove( zip ); +} + +void test_truncated_entry() +{ + const std::string zip{ "truncated_entry.zip" }; + auto archive = read_file( deflate_zip() ); + const auto archive_size = static_cast< uint32_t >( archive.size() ); + // Local header of "small" beyond the end of the archive + write_uint( archive, central_header( archive, "small" ) + 42, 4, + archive_size + 1000 ); + // Local header of "empty" not on a local header signature + write_uint( archive, central_header( archive, "empty" ) + 42, 4, 1 ); + // Data of "text.txt" larger than the archive + write_uint( + archive, central_header( archive, "text.txt" ) + 20, 4, archive_size ); + write_file( zip, archive ); + const geode::detail::ArchiveInputFiles files{ zip }; + check_data_error( + [&files] { + geode_unused( files.content( "small" ) ); + }, + "Truncated zip entry truncated_entry.zip/small", + "[ArchiveInputFiles] local header out of range" ); + check_data_error( + [&files] { + geode_unused( files.content( "empty" ) ); + }, + "Invalid local header of zip entry truncated_entry.zip/empty", + "[ArchiveInputFiles] invalid local header" ); + check_data_error( + [&files] { + geode_unused( files.content( "text.txt" ) ); + }, + "Truncated zip entry truncated_entry.zip/text.txt", + "[ArchiveInputFiles] data out of range" ); + geode::OpenGeodeBasicException::test( + files.content( "folder/binary.bin" ).span().size() == 100000, + "[ArchiveInputFiles] Wrong entry next to truncated ones" ); + std::filesystem::remove( zip ); +} + +void test_unsafe_entry() +{ + const std::string zip{ "unsafe_entry.zip" }; + write_stored_zip( zip, { { "../outside", "abc" } } ); + check_data_error( + [&zip] { + const geode::detail::ArchiveInputFiles files{ zip }; + }, + "../outside", "[ArchiveInputFiles] unsafe entry" ); + std::filesystem::remove( zip ); +} + +void test_not_an_archive() +{ + check_data_error( + [] { + const geode::detail::ArchiveInputFiles files{ absl::StrCat( + geode::DATA_PATH, "triangle.og_tsf3d" ) }; + }, + "triangle.og_tsf3d", "[ArchiveInputFiles] not an archive" ); + check_data_error( + [] { + const geode::detail::ArchiveInputFiles files{ "missing.zip" }; + }, + "missing.zip", "[ArchiveInputFiles] missing archive" ); +} + +void test_temporary_file() +{ + std::string directory; + { + const geode::detail::TemporaryFile file{ "entry.txt", { "abc", 3 } }; + const std::filesystem::path path{ file.path() }; + geode::OpenGeodeBasicException::test( + path.filename() == "entry.txt" && read_file( file.path() ) == "abc", + "[TemporaryFile] Wrong file" ); + directory = path.parent_path().u8string(); + } + geode::OpenGeodeBasicException::test( !std::filesystem::exists( directory ), + "[TemporaryFile] Directory not removed" ); +} + +void set_environment( + const char* name, const std::optional< std::string >& value ) +{ +#ifdef _WIN32 + _putenv_s( name, value ? value->c_str() : "" ); +#else + if( value ) + { + setenv( name, value->c_str(), 1 ); + } + else + { + unsetenv( name ); + } +#endif +} + +std::optional< std::string > get_environment( const char* name ) +{ + const auto* value = std::getenv( name ); + if( value == nullptr ) + { + return std::nullopt; + } + return std::string{ value }; +} + +void test_temporary_file_without_temporary_directory() +{ + // Not a directory: the temporary directory cannot be used + const std::string not_a_directory{ "temporary_file_not_a_directory" }; + write_file( not_a_directory, "abc" ); + const auto absolute = + std::filesystem::absolute( not_a_directory ).u8string(); + std::vector< std::pair< const char*, std::optional< std::string > > > saved; + for( const auto* name : { "TMPDIR", "TMP", "TEMP", "TEMPDIR" } ) + { + saved.emplace_back( name, get_environment( name ) ); + set_environment( name, absolute ); + } + bool internal_error{ false }; + try + { + const geode::detail::TemporaryFile file{ "entry.txt", { "abc", 3 } }; + } + catch( const geode::OpenGeodeException& exception ) + { + internal_error = + exception.type() == geode::OpenGeodeException::TYPE::internal; + } + catch( ... ) + { + } + for( const auto& [name, value] : saved ) + { + set_environment( name, value ); + } + std::filesystem::remove( not_a_directory ); + geode::OpenGeodeBasicException::test( internal_error, + "[TemporaryFile] Unusable temporary directory should raise an " + "internal OpenGeodeException" ); +} + +void test() +{ + test_mapped_file(); + test_directory_input_files(); + test_stored_archive_input_files(); + test_archive_input_files( deflate_zip(), "[ArchiveInputFiles] deflated" ); + test_corrupted_entry(); + test_corrupted_deflate_stream(); + test_truncated_entry(); + test_unsafe_entry(); + test_not_an_archive(); + test_temporary_file(); + test_temporary_file_without_temporary_directory(); +} + +OPENGEODE_TEST( "input-files" ) diff --git a/tests/basic/test-uuid.cpp b/tests/basic/test-uuid.cpp index 24f86f8b8..11c78b38b 100644 --- a/tests/basic/test-uuid.cpp +++ b/tests/basic/test-uuid.cpp @@ -21,6 +21,13 @@ * */ +#include + +#include + +#include + +#include #include #include #include @@ -70,10 +77,67 @@ void test_invalid_string() } } +void test_deserialization() +{ + const geode::uuid nil{ geode::BITSERY::constructor }; + for( const auto byte : nil.bytes_ ) + { + geode::OpenGeodeBasicException::test( + byte == 0, "UUID built for deserialization should be nil" ); + } + geode::OpenGeodeBasicException::test( + bitsery::Access::create< geode::uuid >() == nil, + "UUID created by bitsery should be nil (not generated)" ); + + using Map = absl::flat_hash_map< geode::uuid, geode::index_t >; + const geode::uuid id; + Map map; + for( const auto i : geode::Range{ 10 } ) + { + map.emplace( geode::uuid{}, i ); + } + std::stringstream stream; + { + geode::TContext context{}; + geode::Serializer archive{ context, stream }; + archive.object( id ); + archive.ext( map, bitsery::ext::StdMap{ map.size() }, + []( geode::Serializer& local_archive, geode::uuid& key, + geode::index_t& value ) { + local_archive.object( key ); + local_archive.value4b( value ); + } ); + archive.adapter().flush(); + } + geode::uuid loaded_id{ geode::BITSERY::constructor }; + Map loaded_map; + { + geode::TContext context{}; + const auto bytes = stream.str(); + geode::Deserializer archive{ context, bytes.data(), bytes.size() }; + archive.object( loaded_id ); + archive.ext( loaded_map, bitsery::ext::StdMap{ map.size() }, + []( geode::Deserializer& local_archive, geode::uuid& key, + geode::index_t& value ) { + local_archive.object( key ); + local_archive.value4b( value ); + } ); + geode::OpenGeodeBasicException::test( + archive.adapter().error() == bitsery::ReaderError::NoError + && archive.adapter().isCompletedSuccessfully(), + "UUID deserialization should succeed" ); + } + geode::OpenGeodeBasicException::test( + loaded_id == id, "Deserialized UUID should be the saved one" ); + geode::OpenGeodeBasicException::test( + loaded_map == map, "Deserialized UUID keys should be the saved ones" ); +} + void test() { test_generation(); test_invalid_string(); + test_deserialization(); } OPENGEODE_TEST( "uuid" ) \ No newline at end of file diff --git a/tests/basic/test-zip-file.cpp b/tests/basic/test-zip-file.cpp index a85d3a78e..5c6203624 100644 --- a/tests/basic/test-zip-file.cpp +++ b/tests/basic/test-zip-file.cpp @@ -21,15 +21,121 @@ * */ +#include +#include +#include +#include +#include +#include +#include + #include #include +#include +#include #include #include +using ZipEntries = std::vector< std::pair< std::string, std::string > >; + +std::string read_file( const std::filesystem::path& file ) +{ + std::ifstream stream{ file, std::ios::binary }; + geode::OpenGeodeBasicException::test( + stream.is_open(), "Cannot open file ", file.u8string() ); + return { std::istreambuf_iterator< char >{ stream }, + std::istreambuf_iterator< char >{} }; +} + +uint32_t read_uint( const std::string& data, size_t offset, size_t size ) +{ + uint32_t value{ 0 }; + for( const auto i : geode::Range{ size } ) + { + value |= static_cast< uint32_t >( + static_cast< unsigned char >( data[offset + i] ) ) + << ( 8 * i ); + } + return value; +} + +void check_entries_are_deflated( + const std::string& zip, const ZipEntries& entries ) +{ + const auto archive = read_file( zip ); + // End of central directory record (no archive comment) + constexpr size_t END_RECORD_SIZE{ 22 }; + const auto end_record = archive.size() - END_RECORD_SIZE; + geode::OpenGeodeBasicException::test( + archive.compare( end_record, 4, "PK\x05\x06" ) == 0, + "End of central directory not found in ", zip ); + const auto nb_entries = read_uint( archive, end_record + 10, 2 ); + size_t header = read_uint( archive, end_record + 16, 4 ); + geode::index_t nb_checked{ 0 }; + for( const auto entry : geode::Range{ nb_entries } ) + { + geode_unused( entry ); + geode::OpenGeodeBasicException::test( + archive.compare( header, 4, "PK\x01\x02" ) == 0, + "Invalid central directory header in ", zip ); + const auto name_length = read_uint( archive, header + 28, 2 ); + const auto name = archive.substr( header + 46, name_length ); + geode::OpenGeodeBasicException::test( + read_uint( archive, header + 10, 2 ) == 8, "Zip entry ", name, + " is not DEFLATE-compressed" ); + for( const auto& [entry_name, content] : entries ) + { + if( entry_name == name ) + { + geode::OpenGeodeBasicException::test( + read_uint( archive, header + 20, 4 ) + < read_uint( archive, header + 24, 4 ), + "Zip entry ", name, " is not DEFLATE-compressed" ); + nb_checked++; + } + } + header += 46 + name_length + read_uint( archive, header + 30, 2 ) + + read_uint( archive, header + 32, 2 ); + } + geode::OpenGeodeBasicException::test( nb_checked == entries.size(), + "Missing DEFLATE-compressed entries in ", zip ); +} + +void test_unzip_deflate() +{ + std::string text; + for( const auto i : geode::Range{ 10000 } ) + { + absl::StrAppend( &text, "line ", i, " of a compressible file\n" ); + } + std::string binary; + for( const auto i : geode::Range{ 100000 } ) + { + binary.push_back( static_cast< char >( ( i * i ) % 7 ) ); + } + const ZipEntries entries{ { "text.txt", text }, + { "folder/binary.bin", binary } }; + // Written by Python zipfile with ZIP_DEFLATED + const auto zip = + absl::StrCat( geode::DATA_PATH, "input_files_deflate.zip" ); + check_entries_are_deflated( zip, entries ); + + const geode::UnzipFile unzip{ zip, geode::uuid{}.string() }; + unzip.extract_all(); + const std::filesystem::path directory{ unzip.directory() }; + for( const auto& [name, content] : entries ) + { + geode::OpenGeodeBasicException::test( + read_file( directory / name ) == content, "Extracted entry ", name, + " differs from the DEFLATE-compressed content" ); + } +} + void test() { + test_unzip_deflate(); const auto is_not_a_zip = geode::is_zip_file( absl::StrCat( geode::DATA_PATH, "triange.og_tsf3d" ) ); geode::OpenGeodeBasicException::test( diff --git a/tests/data/backward_io/v20_2/v20_2.og_brep b/tests/data/backward_io/v20_2/v20_2.og_brep new file mode 100644 index 000000000..2bb0d1ed0 Binary files /dev/null and b/tests/data/backward_io/v20_2/v20_2.og_brep differ diff --git a/tests/data/backward_io/v20_2/v20_2.og_sctn b/tests/data/backward_io/v20_2/v20_2.og_sctn new file mode 100644 index 000000000..63bfd4d95 Binary files /dev/null and b/tests/data/backward_io/v20_2/v20_2.og_sctn differ diff --git a/tests/data/input_files_deflate.zip b/tests/data/input_files_deflate.zip new file mode 100644 index 000000000..3eaba2684 Binary files /dev/null and b/tests/data/input_files_deflate.zip differ diff --git a/tests/data/layers_deflate.og_brep b/tests/data/layers_deflate.og_brep new file mode 100644 index 000000000..af463c900 Binary files /dev/null and b/tests/data/layers_deflate.og_brep differ diff --git a/tests/geometry/test-octree.cpp b/tests/geometry/test-octree.cpp index 33fb0cc77..a5757f4c2 100644 --- a/tests/geometry/test-octree.cpp +++ b/tests/geometry/test-octree.cpp @@ -33,6 +33,7 @@ #include #include +#include #include #include @@ -690,13 +691,16 @@ namespace } geode::Octree< dimension > reloaded; { - std::ifstream file{ filename, std::ifstream::binary }; + const auto content = geode::detail::map_file_content( filename ); + geode::OpenGeodeGeometryException::test( + content.has_value(), "[Test] Cannot open file" ); geode::TContext context{}; geode::register_basic_deserialize_pcontext( std::get< 0 >( context ) ); geode::register_geometry_deserialize_pcontext( std::get< 0 >( context ) ); - geode::Deserializer archive{ context, file }; + geode::Deserializer archive{ context, content->span().data(), + content->span().size() }; archive.object( reloaded ); const auto& adapter = archive.adapter(); geode::OpenGeodeGeometryException::test( diff --git a/tests/image/test-raster-image.cpp b/tests/image/test-raster-image.cpp index 435bcdfa2..39baf93c0 100644 --- a/tests/image/test-raster-image.cpp +++ b/tests/image/test-raster-image.cpp @@ -235,6 +235,11 @@ void test() geode::load_one( geode::load_raster_image< 2 >( filename_with_spaces ), filename_with_spaces ); test_raster( reload ); + // UTF-8 file name + const std::string utf8_filename{ "image_\xc3\xa9t\xc3\xa9.og_img2d" }; + geode::save_raster_image( raster, utf8_filename ); + test_raster( geode::load_one( + geode::load_raster_image< 2 >( utf8_filename ), utf8_filename ) ); test_save_failure( raster ); test_unknown_extension( raster ); test_io< 1 >( { 7 } ); diff --git a/tests/mesh/CMakeLists.txt b/tests/mesh/CMakeLists.txt index 01cb77eb6..1a00675a5 100644 --- a/tests/mesh/CMakeLists.txt +++ b/tests/mesh/CMakeLists.txt @@ -141,6 +141,19 @@ add_geode_test( ${PROJECT_NAME}::basic ${PROJECT_NAME}::mesh ) +add_geode_test( + SOURCE "test-mesh-input-bytes.cpp" + DEPENDENCIES + ${PROJECT_NAME}::basic + ${PROJECT_NAME}::image + ${PROJECT_NAME}::mesh +) +add_geode_test( + SOURCE "test-mesh-input-forward-declaration.cpp" + DEPENDENCIES + ${PROJECT_NAME}::basic + ${PROJECT_NAME}::mesh +) add_geode_test( SOURCE "test-mesh-corrupted-files.cpp" DEPENDENCIES diff --git a/tests/mesh/test-graph.cpp b/tests/mesh/test-graph.cpp index 1fc8b795c..a41a79042 100644 --- a/tests/mesh/test-graph.cpp +++ b/tests/mesh/test-graph.cpp @@ -22,6 +22,7 @@ */ #include #include +#include #include #include @@ -137,6 +138,9 @@ void test_io( const geode::Graph& graph, const std::string& filename ) void test_backward_io( const std::string& filename ) { auto graph = geode::load_one( geode::load_graph( filename ), filename ); + geode::OpenGeodeMeshException::test( + graph->id() != geode::uuid{ geode::BITSERY::constructor }, + "Backward Graph should have a valid id" ); geode::OpenGeodeMeshException::test( graph->edges_around_vertex( 2 ).size() == 3, diff --git a/tests/mesh/test-light-regular-grid.cpp b/tests/mesh/test-light-regular-grid.cpp index 0ed80438c..da68f6043 100644 --- a/tests/mesh/test-light-regular-grid.cpp +++ b/tests/mesh/test-light-regular-grid.cpp @@ -719,6 +719,9 @@ void test() test_nan_query( grid ); test_clone_exact_geometry(); test_io( grid, absl::StrCat( "test.", grid.native_extension() ) ); + // UTF-8 file name + test_io( grid, + absl::StrCat( "grille_\xc3\xa9t\xc3\xa9.", grid.native_extension() ) ); test_save_unwritable( grid ); test_coordinate_reference_systems(); test_backward_io(); diff --git a/tests/mesh/test-mesh-input-bytes.cpp b/tests/mesh/test-mesh-input-bytes.cpp new file mode 100644 index 000000000..ecf5741d3 --- /dev/null +++ b/tests/mesh/test-mesh-input-bytes.cpp @@ -0,0 +1,453 @@ +/* + * Copyright (c) 2019 - 2026 Geode-solutions + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * + */ + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace +{ + template < typename Mesh, typename = void > + struct HasPoints : std::false_type + { + }; + + template < typename Mesh > + struct HasPoints< Mesh, + std::void_t< decltype( std::declval< const Mesh& >().point( 0 ) ) > > + : std::true_type + { + }; + + std::string describe_attributes( const geode::AttributeManager& manager ) + { + std::vector< std::string > ids; + for( const auto& id : manager.attribute_ids() ) + { + // Attributes of old files get a new uuid at each load + ids.push_back( absl::StrCat( manager.attribute_type( id ), ":", + manager.find_generic_attribute( id )->name().value_or( "" ) ) ); + } + absl::c_sort( ids ); + return absl::StrCat( + manager.nb_elements(), "[", absl::StrJoin( ids, "," ), "]" ); + } + + /*! + * Text describing a mesh: its vertices, elements and attributes (not + * its identifier: meshes of old files get a new one at each load). + */ + template < typename Mesh > + std::string describe( const Mesh& mesh ) + { + auto text = absl::StrCat( mesh.nb_vertices(), " vertices ", + describe_attributes( mesh.vertex_attribute_manager() ) ); + if constexpr( HasPoints< Mesh >::value ) + { + for( const auto vertex : geode::Range{ mesh.nb_vertices() } ) + { + absl::StrAppend( &text, " ", mesh.point( vertex ).string() ); + } + } + if constexpr( std::is_base_of_v< geode::Graph, Mesh > ) + { + absl::StrAppend( &text, " edges ", + describe_attributes( mesh.edge_attribute_manager() ) ); + for( const auto edge : geode::Range{ mesh.nb_edges() } ) + { + absl::StrAppend( &text, " ", mesh.edge_vertex( { edge, 0 } ), + "-", mesh.edge_vertex( { edge, 1 } ) ); + } + } + if constexpr( std::is_base_of_v< geode::SurfaceMesh< 2 >, Mesh > + || std::is_base_of_v< geode::SurfaceMesh< 3 >, Mesh > ) + { + absl::StrAppend( &text, " polygons ", + describe_attributes( mesh.polygon_attribute_manager() ) ); + for( const auto polygon : geode::Range{ mesh.nb_polygons() } ) + { + absl::StrAppend( &text, " (" ); + for( const auto v : + geode::LRange{ mesh.nb_polygon_vertices( polygon ) } ) + { + absl::StrAppend( + &text, mesh.polygon_vertex( { polygon, v } ), "," ); + } + absl::StrAppend( &text, ")" ); + } + } + if constexpr( std::is_base_of_v< geode::SolidMesh< 3 >, Mesh > ) + { + absl::StrAppend( &text, " polyhedra ", + describe_attributes( mesh.polyhedron_attribute_manager() ) ); + for( const auto polyhedron : geode::Range{ mesh.nb_polyhedra() } ) + { + absl::StrAppend( &text, " (" ); + for( const auto v : + geode::LRange{ mesh.nb_polyhedron_vertices( polyhedron ) } ) + { + absl::StrAppend( &text, + mesh.polyhedron_vertex( { polyhedron, v } ), "," ); + } + absl::StrAppend( &text, ")" ); + } + } + return text; + } + + template < geode::index_t dimension > + std::string describe_grid( + const geode::LightRegularGrid< dimension >& grid ) + { + auto text = absl::StrCat( grid.nb_cells(), " cells ", + grid.grid_point( {} ).string(), " ", + describe_attributes( grid.cell_attribute_manager() ), + describe_attributes( grid.grid_vertex_attribute_manager() ) ); + for( const auto direction : geode::LRange{ dimension } ) + { + absl::StrAppend( &text, " ", + grid.nb_cells_in_direction( direction ), "x", + grid.cell_length_in_direction( direction ) ); + } + return text; + } + + std::string describe_image( const geode::RasterImage2D& image ) + { + auto text = absl::StrCat( image.nb_cells(), " cells" ); + for( const auto cell : geode::Range{ image.nb_cells() } ) + { + absl::StrAppend( &text, " ", image.color( cell ).string() ); + } + return text; + } + + std::string data_file( std::string_view name ) + { + return absl::StrCat( geode::DATA_PATH, name ); + } + + geode::detail::FileContent read_whole_file( std::string_view filename ) + { + auto content = geode::detail::map_file_content( filename ); + geode::OpenGeodeMeshException::test( + content.has_value(), "Cannot read ", filename ); + return std::move( content.value() ); + } + + /*! + * Read a native mesh file by path, from its bytes, and through the + * input files of its directory: the three meshes must be identical. + */ + template < typename OpenGeodeMesh, typename Factory > + void check_mesh( std::string_view filename ) + { + const auto impl = OpenGeodeMesh::impl_name_static(); + const auto extension = geode::detail::lowercase_extension( filename ); + const auto by_path = geode::load_one( + Factory::create( extension, filename )->read( impl ), filename ); + const auto reference = describe( *by_path ); + + const auto bytes = read_whole_file( filename ); + std::vector< typename Factory::BaseClass::InputData > from_bytes; + geode::OpenGeodeMeshException::test( + Factory::create( extension, "name_only" ) + ->read_bytes( bytes.span(), from_bytes, impl ), + "Native input of ", filename, " cannot read bytes" ); + geode::OpenGeodeMeshException::test( + describe( *geode::load_one( std::move( from_bytes ), filename ) ) + == reference, + "Mesh read from bytes differs from the file ", filename ); + + const std::filesystem::path path{ filename }; + const geode::detail::DirectoryInputFiles files{ + path.parent_path().u8string() + }; + const auto from_files = geode::load_one( + geode::detail::geode_object_input_from_files< Factory >( + "Mesh", files, path.filename().u8string(), impl ), + filename ); + geode::OpenGeodeMeshException::test( + describe( *from_files ) == reference, + "Mesh read from input files differs from the file ", filename ); + } + + template < typename Object, typename Factory, typename Describe > + void check_object( std::string_view filename, const Describe& describe ) + { + const auto extension = geode::detail::lowercase_extension( filename ); + const auto by_path = geode::load_one( + Factory::create( extension, filename )->read(), filename ); + const auto bytes = read_whole_file( filename ); + std::vector< typename Factory::BaseClass::InputData > from_bytes; + geode::OpenGeodeMeshException::test( + Factory::create( extension, "name_only" ) + ->read_bytes( bytes.span(), from_bytes ), + "Native input of ", filename, " cannot read bytes" ); + geode::OpenGeodeMeshException::test( + describe( geode::load_one( std::move( from_bytes ), filename ) ) + == describe( by_path ), + "Object read from bytes differs from the file ", filename ); + } + + void test_native_meshes() + { + check_mesh< geode::OpenGeodeTriangulatedSurface3D, + geode::TriangulatedSurfaceInputFactory3D >( + data_file( "triangle.og_tsf3d" ) ); + check_mesh< geode::OpenGeodeTriangulatedSurface2D, + geode::TriangulatedSurfaceInputFactory2D >( + data_file( "3patches.og_tsf2d" ) ); + check_mesh< geode::OpenGeodeTetrahedralSolid3D, + geode::TetrahedralSolidInputFactory3D >( + data_file( "backward_io/v18_5/v18_5.og_tso3d" ) ); + check_mesh< geode::OpenGeodePolygonalSurface3D, + geode::PolygonalSurfaceInputFactory3D >( + data_file( "backward_io/v18_5/v18_5.og_psf3d" ) ); + check_mesh< geode::OpenGeodePolyhedralSolid3D, + geode::PolyhedralSolidInputFactory3D >( + data_file( "backward_io/v17/v17.og_pso3d" ) ); + check_mesh< geode::OpenGeodeHybridSolid3D, + geode::HybridSolidInputFactory3D >( + data_file( "backward_io/v17/v17.og_hso3d" ) ); + check_mesh< geode::OpenGeodeEdgedCurve3D, + geode::EdgedCurveInputFactory3D >( + data_file( "backward_io/v18_5/v18_5.og_edc3d" ) ); + check_mesh< geode::OpenGeodePointSet3D, geode::PointSetInputFactory3D >( + data_file( "backward_io/v17/v17.og_pts3d" ) ); + check_mesh< geode::OpenGeodeRegularGrid3D, + geode::RegularGridInputFactory3D >( + data_file( "backward_io/v17/v17.og_rgd3d" ) ); + check_mesh< geode::OpenGeodeGraph, geode::GraphInputFactory >( + data_file( "backward_io/v18_5/v18_5.og_grp" ) ); + check_object< geode::LightRegularGrid3D, + geode::LightRegularGridInputFactory3D >( + data_file( "backward_io/v19_8/v19_8.og_lrgd3d" ), + describe_grid< 3 > ); + check_object< geode::LightRegularGrid2D, + geode::LightRegularGridInputFactory2D >( + data_file( "backward_io/v19_8/v19_8.og_lrgd2d" ), + describe_grid< 2 > ); + } + + void test_raster_image() + { + geode::RasterImage2D image{ { 3, 2 } }; + for( const auto cell : geode::Range{ image.nb_cells() } ) + { + image.set_color( + cell, geode::RGBColor{ + static_cast< geode::local_index_t >( cell ), 2, 3 } ); + } + const std::string filename{ "bytes_raster.og_img2d" }; + geode::save_raster_image( image, filename ); + check_object< geode::RasterImage2D, geode::RasterImageInputFactory2D >( + filename, describe_image ); + std::filesystem::remove( filename ); + } + + /*! + * Input reading only files, to check the fallback of the input files. + */ + class PathOnlyInput : public geode::TriangulatedSurfaceInput< 3 > + { + public: + explicit PathOnlyInput( std::string_view filename ) + : geode::TriangulatedSurfaceInput< 3 >( filename ) + { + } + + std::vector< std::unique_ptr< geode::TriangulatedSurface3D > > read( + const geode::MeshImpl& impl ) final + { + read_paths().emplace_back( filename() ); + geode::OpenGeodeMeshException::test( + std::filesystem::exists( + std::filesystem::u8path( geode::to_string( filename() ) ) ), + "[PathOnlyInput] File ", filename(), " does not exist" ); + const auto bytes = read_whole_file( filename() ); + std::vector< std::unique_ptr< geode::TriangulatedSurface3D > > + meshes; + geode::OpenGeodeMeshException::test( + geode::TriangulatedSurfaceInputFactory3D::create( + "og_tsf3d", filename() ) + ->read_bytes( bytes.span(), meshes, impl ), + "[PathOnlyInput] Cannot read bytes of ", filename() ); + return meshes; + } + + geode::AdditionalFiles additional_files() const final + { + return {}; + } + + geode::index_t object_priority() const final + { + return 0; + } + + geode::Percentage is_loadable() const final + { + return geode::Percentage{ 1 }; + } + + static std::vector< std::string >& read_paths() + { + static std::vector< std::string > paths; + return paths; + } + }; + + void write_stored_zip( const std::string& zip, + const std::string& name, + geode::ByteSpan content ) + { + const std::filesystem::path directory{ "path_only_zip_content" }; + std::filesystem::create_directories( directory ); + const auto file = directory / name; + { + std::ofstream stream{ file, std::ios::binary }; + stream.write( content.data(), + static_cast< std::streamsize >( content.size() ) ); + } + geode::ZipFile archive{ zip, geode::uuid{}.string() }; + archive.archive_file( file.u8string() ); + archive.finalize(); + std::filesystem::remove_all( directory ); + } + + void test_fallback_to_file() + { + geode::TriangulatedSurfaceInputFactory3D::register_creator< + PathOnlyInput >( "path_only" ); + const auto bytes = read_whole_file( data_file( "triangle.og_tsf3d" ) ); + const auto impl = + geode::OpenGeodeTriangulatedSurface3D::impl_name_static(); + const auto reference = + describe( *geode::load_one( geode::load_triangulated_surface< 3 >( + data_file( "triangle.og_tsf3d" ) ), + "triangle" ) ); + + // Entry of an archive: written to a temporary file + const std::string zip{ "path_only.zip" }; + write_stored_zip( zip, "mesh.path_only", bytes.span() ); + { + const geode::detail::ArchiveInputFiles files{ zip }; + const auto mesh = + geode::load_one( geode::detail::geode_object_input_from_files< + geode::TriangulatedSurfaceInputFactory3D >( + "Mesh", files, "mesh.path_only", impl ), + "mesh" ); + geode::OpenGeodeMeshException::test( describe( *mesh ) == reference, + "Wrong mesh read from a temporary file" ); + } + auto& paths = PathOnlyInput::read_paths(); + geode::OpenGeodeMeshException::test( + paths.size() == 1, "The path only input should be called once" ); + const std::filesystem::path temporary{ paths.front() }; + geode::OpenGeodeMeshException::test( + temporary.filename() == "mesh.path_only" + && !std::filesystem::exists( temporary.parent_path() ), + "The temporary file should be removed: ", paths.front() ); + std::filesystem::remove( zip ); + + // File of a directory: read in place + const std::filesystem::path directory{ "path_only_directory" }; + std::filesystem::create_directories( directory ); + { + std::ofstream file{ directory / "mesh.path_only", + std::ios::binary }; + file.write( bytes.span().data(), + static_cast< std::streamsize >( bytes.span().size() ) ); + } + const geode::detail::DirectoryInputFiles files{ directory.u8string() }; + geode_unused( geode::detail::geode_object_input_from_files< + geode::TriangulatedSurfaceInputFactory3D >( + "Mesh", files, "mesh.path_only", impl ) ); + geode::OpenGeodeMeshException::test( + paths.size() == 2 + && paths.back() == files.location( "mesh.path_only" ), + "A file of a directory should be read in place" ); + std::filesystem::remove_all( directory ); + } +} // namespace + +void test() +{ + geode::OpenGeodeMeshLibrary::initialize(); + test_native_meshes(); + test_raster_image(); + test_fallback_to_file(); +} + +OPENGEODE_TEST( "mesh-input-bytes" ) diff --git a/tests/mesh/test-mesh-input-forward-declaration.cpp b/tests/mesh/test-mesh-input-forward-declaration.cpp new file mode 100644 index 000000000..f209eb1e9 --- /dev/null +++ b/tests/mesh/test-mesh-input-forward-declaration.cpp @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2019 - 2026 Geode-solutions + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * + */ + +/* + * The input headers only forward declare the meshes: instantiating every + * member of their Input base class (as MSVC does for the virtual functions) + * must not need the complete mesh type. + */ +#include +#include +#include +#include +#include +#include +#include + +#include + +template class geode::Input< std::unique_ptr< geode::EdgedCurve< 3 > >, + geode::MeshImpl >; +template class geode::Input< std::unique_ptr< geode::HybridSolid< 3 > >, + geode::MeshImpl >; +template class geode::Input< std::unique_ptr< geode::PointSet< 3 > >, + geode::MeshImpl >; +template class geode::Input< std::unique_ptr< geode::PolygonalSurface< 3 > >, + geode::MeshImpl >; +template class geode::Input< std::unique_ptr< geode::PolyhedralSolid< 3 > >, + geode::MeshImpl >; +template class geode::Input< std::unique_ptr< geode::TetrahedralSolid< 3 > >, + geode::MeshImpl >; +template class geode::Input< std::unique_ptr< geode::TriangulatedSurface< 3 > >, + geode::MeshImpl >; + +void test() +{ + geode::Logger::info( + "Input base classes instantiated with forward declared meshes" ); +} + +OPENGEODE_TEST( "mesh-input-forward-declaration" ) diff --git a/tests/mesh/test-mesh-truncated-files.cpp b/tests/mesh/test-mesh-truncated-files.cpp index 8c3d37f93..8525823ac 100644 --- a/tests/mesh/test-mesh-truncated-files.cpp +++ b/tests/mesh/test-mesh-truncated-files.cpp @@ -128,6 +128,38 @@ namespace nb_throws > 0, "Truncated files of ", filename, " should throw" ); } + /* + * Load a copy of the given file truncated at half its size: data error. + */ + void test_half_file( const std::string& filename, const Loader& loader ) + { + const auto content = read_file( filename ); + const auto extension = + std::filesystem::path{ filename }.extension().string(); + const auto truncated_filename = absl::StrCat( "half", extension ); + { + std::ofstream file{ truncated_filename, std::ofstream::binary }; + file.write( content.data(), + static_cast< std::streamsize >( content.size() / 2 ) ); + } + try + { + loader( truncated_filename ); + } + catch( const geode::OpenGeodeException& exception ) + { + geode::Logger::info( "Half ", filename, ": ", exception.what() ); + geode::OpenGeodeMeshException::test( + exception.type() == geode::OpenGeodeException::TYPE::data, + "[Test] Half ", filename, + " should raise a data error: ", exception.string() ); + return; + } + throw geode::OpenGeodeMeshException{ nullptr, + geode::OpenGeodeException::TYPE::internal, "[Test] Half ", filename, + " should not be loaded" }; + } + std::string data_file( std::string_view name ) { return absl::StrCat( geode::DATA_PATH, "backward_io/", name ); @@ -233,6 +265,11 @@ void test() data_file( "v18_5/v18_5.og_tso3d" ), tetrahedral_solid ); test_truncated_file( save_textured_surface(), triangulated_surface2d ); test_truncated_file( save_light_grid(), light_grid ); + test_half_file( + data_file( "v18_5/v18_5.og_tsf3d" ), triangulated_surface3d ); + test_half_file( data_file( "v17/v17.og_pso3d" ), polyhedral_solid ); + test_half_file( save_textured_surface(), triangulated_surface2d ); + test_half_file( save_light_grid(), light_grid ); } OPENGEODE_TEST( "mesh-truncated-files" ) diff --git a/tests/mesh/test-polygonal-surface.cpp b/tests/mesh/test-polygonal-surface.cpp index b73db1ce9..a0acef5b3 100644 --- a/tests/mesh/test-polygonal-surface.cpp +++ b/tests/mesh/test-polygonal-surface.cpp @@ -27,6 +27,7 @@ #include #include #include +#include #include #include @@ -566,6 +567,10 @@ void test_backward_io( const std::string& filename ) geode::load_polygonal_surface< 3 >( geode::OpenGeodePolygonalSurface3D::impl_name_static(), filename ), filename ); + geode::OpenGeodeMeshException::test( + new_polygonal_surface->id() + != geode::uuid{ geode::BITSERY::constructor }, + "Backward PolygonalSurface should have a valid id" ); geode::OpenGeodeMeshException::test( new_polygonal_surface->nb_vertices() == 7, @@ -780,12 +785,7 @@ std::string serialize_edges( const FacetEdges& edges ) void deserialize_edges( const std::string& buffer, FacetEdges& edges ) { - std::istringstream input{ buffer, std::ios::binary }; - geode::TContext context{}; - geode::BitseryExtensions::register_deserialize_pcontext( - std::get< 0 >( context ) ); - geode::Deserializer archive{ context, input }; - archive.object( edges ); + geode_unused( geode::detail::deserialize_bytes( buffer, edges ) ); } constexpr std::array< geode::index_t, 2 > EDGE_A{ 1000001, 1000002 }; diff --git a/tests/mesh/test-polyhedral-solid.cpp b/tests/mesh/test-polyhedral-solid.cpp index ac00a4caf..da1699450 100644 --- a/tests/mesh/test-polyhedral-solid.cpp +++ b/tests/mesh/test-polyhedral-solid.cpp @@ -29,6 +29,7 @@ #include #include +#include #include #include @@ -473,6 +474,10 @@ void test_backward_io( const std::string& filename ) { const auto new_polyhedral_solid = geode::load_one( geode::load_polyhedral_solid< 3 >( filename ), filename ); + geode::OpenGeodeMeshException::test( + new_polyhedral_solid->id() + != geode::uuid{ geode::BITSERY::constructor }, + "Backward PolyhedralSolid should have a valid id" ); geode::OpenGeodeMeshException::test( new_polyhedral_solid->nb_vertices() == 8, diff --git a/tests/mesh/test-tetrahedral-solid.cpp b/tests/mesh/test-tetrahedral-solid.cpp index e8a830dad..5868dccc8 100644 --- a/tests/mesh/test-tetrahedral-solid.cpp +++ b/tests/mesh/test-tetrahedral-solid.cpp @@ -21,6 +21,7 @@ * */ +#include #include #include @@ -343,6 +344,24 @@ void test_delete_polyhedron( const geode::TetrahedralSolid3D& solid, "TetrahedralSolid facet vertex index is not correct" ); } +void check_same_attribute_ids( const geode::AttributeManager& manager, + const geode::AttributeManager& manager2 ) +{ + auto ids = manager.attribute_ids(); + auto ids2 = manager2.attribute_ids(); + std::sort( ids.begin(), ids.end() ); + std::sort( ids2.begin(), ids2.end() ); + geode::OpenGeodeMeshException::test( + std::equal( ids.begin(), ids.end(), ids2.begin(), ids2.end() ), + "Reloaded attribute ids should be the saved ones" ); + for( const auto& id : ids2 ) + { + geode::OpenGeodeMeshException::test( + manager2.find_generic_attribute( id )->id() == id, + "Reloaded attribute should keep its id" ); + } +} + void test_io( const geode::TetrahedralSolid3D& solid, const std::string& filename ) { @@ -369,6 +388,12 @@ void test_io( "Reloaded TetrahedralSolid should have 12 edges" ); geode::OpenGeodeMeshException::test( new_solid->nb_polyhedra() == 3, "Reloaded TetrahedralSolid should have 3 polyhedra" ); + geode::OpenGeodeMeshException::test( new_solid->id() == solid.id(), + "Reloaded TetrahedralSolid should keep its id" ); + check_same_attribute_ids( solid.vertex_attribute_manager(), + new_solid->vertex_attribute_manager() ); + check_same_attribute_ids( solid.polyhedron_attribute_manager(), + new_solid->polyhedron_attribute_manager() ); } void test_backward_io( const std::string& filename ) @@ -377,6 +402,9 @@ void test_backward_io( const std::string& filename ) geode::load_tetrahedral_solid< 3 >( filename ), filename ); geode::OpenGeodeMeshException::test( solid->nb_vertices() == 6, "Backward TetrahedralSolid should have 6 vertices" ); + geode::OpenGeodeMeshException::test( + solid->id() != geode::uuid{ geode::BITSERY::constructor }, + "Backward TetrahedralSolid should have a valid id" ); geode::OpenGeodeMeshException::test( solid->nb_polyhedra() == 3, "Backward TetrahedralSolid should have 3 polyhedra" ); geode::OpenGeodeMeshException::test( solid->edges().nb_edges() == 12, diff --git a/tests/mesh/test-texture-manager.cpp b/tests/mesh/test-texture-manager.cpp index f8cb0b641..593fe8c64 100644 --- a/tests/mesh/test-texture-manager.cpp +++ b/tests/mesh/test-texture-manager.cpp @@ -24,6 +24,7 @@ #include #include +#include #include #include @@ -101,13 +102,16 @@ void save( const geode::TextureStorage2D& storage, std::string_view filename ) geode::TextureStorage2D load( std::string_view filename ) { - std::ifstream file{ geode::to_string( filename ), std::ifstream::binary }; + const auto content = geode::detail::map_file_content( filename ); + geode::OpenGeodeMeshException::test( + content.has_value(), "[Bitsery::read] Cannot open file: ", filename ); geode::TContext context{}; geode::register_basic_deserialize_pcontext( std::get< 0 >( context ) ); geode::register_geometry_deserialize_pcontext( std::get< 0 >( context ) ); geode::register_image_deserialize_pcontext( std::get< 0 >( context ) ); geode::register_mesh_deserialize_pcontext( std::get< 0 >( context ) ); - geode::Deserializer archive{ context, file }; + geode::Deserializer archive{ context, content->span().data(), + content->span().size() }; geode::TextureStorage2D storage; archive.object( storage ); const auto& adapter = archive.adapter(); diff --git a/tests/mesh/test-triangulated-surface.cpp b/tests/mesh/test-triangulated-surface.cpp index eda20b41f..f13f2bee6 100644 --- a/tests/mesh/test-triangulated-surface.cpp +++ b/tests/mesh/test-triangulated-surface.cpp @@ -21,6 +21,8 @@ * */ +#include + #include #include #include @@ -238,6 +240,24 @@ void test_delete_polygon( const geode::TriangulatedSurface3D& surface, "TriangulatedSurface should have 5 edges" ); } +void check_same_attribute_ids( const geode::AttributeManager& manager, + const geode::AttributeManager& manager2 ) +{ + auto ids = manager.attribute_ids(); + auto ids2 = manager2.attribute_ids(); + std::sort( ids.begin(), ids.end() ); + std::sort( ids2.begin(), ids2.end() ); + geode::OpenGeodeMeshException::test( + std::equal( ids.begin(), ids.end(), ids2.begin(), ids2.end() ), + "Reloaded attribute ids should be the saved ones" ); + for( const auto& id : ids2 ) + { + geode::OpenGeodeMeshException::test( + manager2.find_generic_attribute( id )->id() == id, + "Reloaded attribute should keep its id" ); + } +} + void test_io( const geode::TriangulatedSurface3D& surface, std::string_view filename ) { @@ -262,6 +282,12 @@ void test_io( .inexact_equal( surface2->point( vertex_id ) ), "Wrong reloaded mesh point coordinates." ); } + geode::OpenGeodeMeshException::test( surface2->id() == surface.id(), + "Reloaded TriangulatedSurface should keep its id" ); + check_same_attribute_ids( surface.vertex_attribute_manager(), + surface2->vertex_attribute_manager() ); + check_same_attribute_ids( surface.polygon_attribute_manager(), + surface2->polygon_attribute_manager() ); } void test_backward_io( const std::string& filename ) @@ -270,6 +296,9 @@ void test_backward_io( const std::string& filename ) geode::load_triangulated_surface< 3 >( filename ), filename ); geode::OpenGeodeMeshException::test( surface->nb_vertices() == 5, "Backward TriangulatedSurface should have 5 vertices" ); + geode::OpenGeodeMeshException::test( + surface->id() != geode::uuid{ geode::BITSERY::constructor }, + "Backward TriangulatedSurface should have a valid id" ); geode::OpenGeodeMeshException::test( surface->nb_polygons() == 3, "Backward TriangulatedSurface should have 3 polygons" ); geode::OpenGeodeMeshException::test( @@ -776,6 +805,9 @@ void test() test_create_polygons( *surface, *builder ); test_polygon_adjacencies( *surface, *builder ); test_io( *surface, absl::StrCat( "test.", surface->native_extension() ) ); + // UTF-8 file name + test_io( *surface, absl::StrCat( "surface_\xc3\xa9t\xc3\xa9.", + surface->native_extension() ) ); test_backward_io( absl::StrCat( geode::DATA_PATH, "backward_io/v17/v17.", surface->native_extension() ) ); test_permutation( *surface, *builder ); diff --git a/tests/model/CMakeLists.txt b/tests/model/CMakeLists.txt index 38d6ea10e..2643169ba 100644 --- a/tests/model/CMakeLists.txt +++ b/tests/model/CMakeLists.txt @@ -96,6 +96,20 @@ add_geode_test( ${PROJECT_NAME}::mesh ${PROJECT_NAME}::model ) +add_geode_test( + SOURCE "test-model-archive-input.cpp" + DEPENDENCIES + ${PROJECT_NAME}::basic + ${PROJECT_NAME}::mesh + ${PROJECT_NAME}::model +) +add_geode_test( + SOURCE "test-model-deflate-archive.cpp" + DEPENDENCIES + ${PROJECT_NAME}::basic + ${PROJECT_NAME}::mesh + ${PROJECT_NAME}::model +) add_geode_test( SOURCE "test-model-component-filter.cpp" DEPENDENCIES diff --git a/tests/model/test-brep.cpp b/tests/model/test-brep.cpp index 4c3cd6962..3b01ff199 100644 --- a/tests/model/test-brep.cpp +++ b/tests/model/test-brep.cpp @@ -23,6 +23,7 @@ #include +#include #include #include #include @@ -1190,6 +1191,125 @@ void test_block_collection_ranges( const geode::BRep& model, "ItemBlockRange should iterates on 1 Block." ); } +std::vector< geode::ComponentMeshVertex > sorted_component_mesh_vertices( + const geode::BRep& model, geode::index_t unique_vertex ) +{ + auto vertices = model.component_mesh_vertices( unique_vertex ); + absl::c_sort( vertices ); + return vertices; +} + +/* + * Loaded component mesh vertices are rebuilt from the component meshes: + * components in the model order (Corners, Lines, Surfaces, Blocks), then + * their vertices in increasing order. + */ +void check_loaded_component_mesh_vertices_order( const geode::BRep& model ) +{ + absl::flat_hash_map< geode::uuid, geode::index_t > ranks; + geode::index_t rank{ 0 }; + for( const auto& component : model.corners() ) + { + ranks.emplace( component.id(), rank++ ); + } + for( const auto& component : model.lines() ) + { + ranks.emplace( component.id(), rank++ ); + } + for( const auto& component : model.surfaces() ) + { + ranks.emplace( component.id(), rank++ ); + } + for( const auto& component : model.blocks() ) + { + ranks.emplace( component.id(), rank++ ); + } + for( const auto unique_vertex : geode::Range{ model.nb_unique_vertices() } ) + { + const auto& vertices = model.component_mesh_vertices( unique_vertex ); + for( const auto v : geode::Range{ 1, vertices.size() } ) + { + const auto& previous = vertices[v - 1]; + const auto& current = vertices[v]; + geode::OpenGeodeModelException::test( + std::make_pair( + ranks.at( previous.component_id.id ), previous.vertex ) + < std::make_pair( + ranks.at( current.component_id.id ), current.vertex ), + "[Test] Loaded component mesh vertices of unique vertex ", + unique_vertex, " are not in the model order" ); + } + } +} + +void test_compare_component_mesh_vertices( + const geode::BRep& model, const geode::BRep& model2 ) +{ + geode::OpenGeodeModelException::test( model.nb_unique_vertices() > 0, + "[Test] Model should have unique vertices" ); + geode::OpenGeodeModelException::test( + model.nb_unique_vertices() == model2.nb_unique_vertices(), + "[Test] Reloaded model should have ", model.nb_unique_vertices(), + " unique vertices" ); + const geode::uuid nil{ geode::BITSERY::constructor }; + for( const auto unique_vertex : geode::Range{ model.nb_unique_vertices() } ) + { + geode::OpenGeodeModelException::test( + sorted_component_mesh_vertices( model, unique_vertex ) + == sorted_component_mesh_vertices( model2, unique_vertex ), + "[Test] Reloaded component mesh vertices of unique vertex ", + unique_vertex, " should be equal to the saved ones" ); + for( const auto& vertex : + model2.component_mesh_vertices( unique_vertex ) ) + { + geode::OpenGeodeModelException::test( vertex.component_id.id != nil, + "[Test] Reloaded component id should not be nil" ); + geode::OpenGeodeModelException::test( + model2.unique_vertex( vertex ) == unique_vertex, + "[Test] Reloaded component mesh vertex should map to unique " + "vertex ", + unique_vertex ); + } + } + check_loaded_component_mesh_vertices_order( model2 ); +} + +/* + * Loading the same model twice gives the same component mesh vertices, in + * the same order. + */ +void test_compare_component_mesh_vertices_order( + const geode::BRep& model, const geode::BRep& model2 ) +{ + for( const auto unique_vertex : geode::Range{ model.nb_unique_vertices() } ) + { + geode::OpenGeodeModelException::test( + model.component_mesh_vertices( unique_vertex ) + == model2.component_mesh_vertices( unique_vertex ), + "[Test] Component mesh vertices of unique vertex ", unique_vertex, + " should be in the same order in both loaded models" ); + } +} + +void test_component_mesh_vertices_round_trip() +{ + const auto filename = absl::StrCat( geode::DATA_PATH, "layers.og_brep" ); + const auto model = + geode::load_one( geode::load_brep( filename ), filename ); + const auto file_io = absl::StrCat( + "test_component_mesh_vertices.", model.native_extension() ); + geode::save_brep( model, file_io ); + const auto model2 = geode::load_one( geode::load_brep( file_io ), file_io ); + test_compare_component_mesh_vertices( model, model2 ); + const auto file_io2 = absl::StrCat( + "test_component_mesh_vertices2.", model.native_extension() ); + geode::save_brep( model2, file_io2 ); + const auto model3 = + geode::load_one( geode::load_brep( file_io2 ), file_io2 ); + test_compare_component_mesh_vertices( model, model3 ); + test_compare_component_mesh_vertices_order( model2, model3 ); +} + void test_compare_brep( const geode::BRep& model, const geode::BRep& model2 ) { geode::OpenGeodeModelException::test( @@ -1824,6 +1944,11 @@ void test_backward_io() absl::StrCat( geode::DATA_PATH, "backward_io/v17/v17.og_brep" ); auto brep_v17 = geode::load_one( geode::load_brep( brep_v17_filename ), brep_v17_filename ); + geode::OpenGeodeModelException::test( + brep_v17.unique_vertex_attribute_id() + != geode::uuid{ geode::BITSERY::constructor }, + "[Backward_IO] v17 BRep should have a valid unique vertex attribute " + "id" ); geode::BRepBuilder brep_builder_v17{ brep_v17 }; for( const auto& block : brep_v17.blocks() ) { @@ -1862,6 +1987,11 @@ void test_backward_io() absl::StrCat( geode::DATA_PATH, "backward_io/v18_0/v18_0.og_brep" ); auto brep_v18_0 = geode::load_one( geode::load_brep( brep_v18_0_filename ), brep_v18_0_filename ); + geode::OpenGeodeModelException::test( + brep_v18_0.unique_vertex_attribute_id() + != geode::uuid{ geode::BITSERY::constructor }, + "[Backward_IO] v18_0 BRep should have a valid unique vertex attribute " + "id" ); geode::BRepBuilder brep_builder_v18{ brep_v18_0 }; for( const auto& block : brep_v18_0.blocks() ) { @@ -1898,6 +2028,97 @@ void test_backward_io() test_registry( brep_v18_0, 4, 6, 9, 5, 1, 5, 2, 2, 2, 1, 3 ); } +geode::index_t count_multi_type_unique_vertices( const geode::BRep& model ) +{ + geode::index_t count{ 0 }; + for( const auto unique_vertex : geode::Range{ model.nb_unique_vertices() } ) + { + const auto& vertices = model.component_mesh_vertices( unique_vertex ); + for( const auto& vertex : vertices ) + { + if( vertex.component_id.type != vertices.front().component_id.type ) + { + count++; + break; + } + } + } + return count; +} + +/* + * v20_2.og_brep was saved from box_brep.og_brep with 3 more isolated unique + * vertices, when the component mesh vertices were stored in the file. + */ +void test_backward_io_component_mesh_vertices() +{ + const auto box_filename = + absl::StrCat( geode::DATA_PATH, "box_brep.og_brep" ); + const auto box = + geode::load_one( geode::load_brep( box_filename ), box_filename ); + const auto filename = + absl::StrCat( geode::DATA_PATH, "backward_io/v20_2/v20_2.og_brep" ); + const auto brep = geode::load_one( geode::load_brep( filename ), filename ); + const auto nb_box_vertices = box.nb_unique_vertices(); + geode::OpenGeodeModelException::test( + brep.nb_unique_vertices() == nb_box_vertices + 3, + "[Backward_IO] Wrong number of unique vertices" ); + geode::OpenGeodeModelException::test( + brep.nb_blocks() > 0, "[Backward_IO] v20_2 model should have blocks" ); + geode::OpenGeodeModelException::test( + count_multi_type_unique_vertices( brep ) > 0, + "[Backward_IO] Some unique vertices should have several component " + "types" ); + for( const auto unique_vertex : geode::Range{ brep.nb_unique_vertices() } ) + { + if( unique_vertex >= nb_box_vertices ) + { + geode::OpenGeodeModelException::test( + brep.is_unique_vertex_isolated( unique_vertex ), + "[Backward_IO] Unique vertex ", unique_vertex, + " should be isolated" ); + continue; + } + geode::OpenGeodeModelException::test( + sorted_component_mesh_vertices( box, unique_vertex ) + == sorted_component_mesh_vertices( brep, unique_vertex ), + "[Backward_IO] Wrong component mesh vertices of unique vertex ", + unique_vertex ); + for( const auto& vertex : + brep.component_mesh_vertices( unique_vertex ) ) + { + geode::OpenGeodeModelException::test( + brep.unique_vertex( vertex ) == unique_vertex, + "[Backward_IO] Wrong unique vertex of ", vertex.string() ); + } + } + + const auto file_io = + absl::StrCat( "v20_2_resaved.", brep.native_extension() ); + geode::save_brep( brep, file_io ); + auto reloaded = geode::load_one( geode::load_brep( file_io ), file_io ); + test_compare_component_mesh_vertices( brep, reloaded ); + for( const auto unique_vertex : + geode::Range{ nb_box_vertices, reloaded.nb_unique_vertices() } ) + { + geode::OpenGeodeModelException::test( + reloaded.is_unique_vertex_isolated( unique_vertex ), + "[Backward_IO] Reloaded unique vertex ", unique_vertex, + " should be isolated" ); + } + + geode::BRepBuilder builder{ reloaded }; + const auto old2new = builder.delete_isolated_vertices(); + std::vector< geode::index_t > expected( nb_box_vertices + 3, geode::NO_ID ); + for( const auto unique_vertex : geode::Range{ nb_box_vertices } ) + { + expected[unique_vertex] = unique_vertex; + } + geode::OpenGeodeModelException::test( old2new == expected, + "[Backward_IO] Wrong mapping after deleting isolated unique vertices" ); + test_compare_component_mesh_vertices( box, reloaded ); +} + void test_registry_remove_unknown_type() { geode::BRep brep; @@ -2353,7 +2574,9 @@ void test() geode::BRep model3{ std::move( model2 ) }; test_compare_brep( model, model3 ); + test_component_mesh_vertices_round_trip(); test_backward_io(); + test_backward_io_component_mesh_vertices(); test_physical_properties_backward_io(); test_components_filter(); test_registry_remove_unknown_type(); diff --git a/tests/model/test-model-archive-input.cpp b/tests/model/test-model-archive-input.cpp new file mode 100644 index 000000000..0e1408822 --- /dev/null +++ b/tests/model/test-model-archive-input.cpp @@ -0,0 +1,368 @@ +/* + * Copyright (c) 2019 - 2026 Geode-solutions + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * + */ + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace +{ + template < typename Model > + void check_same_components( + const Model& model, const Model& reference, std::string_view filename ) + { + for( const auto& corner : reference.corners() ) + { + const auto& mesh = model.corner( corner.id() ).mesh(); + geode::OpenGeodeModelException::test( + mesh.nb_vertices() == corner.mesh().nb_vertices(), + "Corner mesh differs in ", filename ); + } + for( const auto& line : reference.lines() ) + { + const auto& mesh = model.line( line.id() ).mesh(); + geode::OpenGeodeModelException::test( + mesh.nb_vertices() == line.mesh().nb_vertices() + && mesh.nb_edges() == line.mesh().nb_edges(), + "Line mesh differs in ", filename ); + } + for( const auto& surface : reference.surfaces() ) + { + const auto& mesh = model.surface( surface.id() ).mesh(); + geode::OpenGeodeModelException::test( + mesh.nb_vertices() == surface.mesh().nb_vertices() + && mesh.nb_polygons() == surface.mesh().nb_polygons() + && mesh.type_name() == surface.mesh().type_name(), + "Surface mesh differs in ", filename ); + } + for( const auto uv : geode::Range{ reference.nb_unique_vertices() } ) + { + auto vertices = model.component_mesh_vertices( uv ); + auto expected = reference.component_mesh_vertices( uv ); + absl::c_sort( vertices ); + absl::c_sort( expected ); + geode::OpenGeodeModelException::test( vertices == expected, + "Unique vertex ", uv, " differs in ", filename ); + } + geode::OpenGeodeModelException::test( + model.nb_corners() == reference.nb_corners() + && model.nb_lines() == reference.nb_lines() + && model.nb_surfaces() == reference.nb_surfaces() + && model.nb_model_boundaries() + == reference.nb_model_boundaries(), + "Components differ in ", filename ); + geode::OpenGeodeModelException::test( + model.nb_unique_vertices() == reference.nb_unique_vertices(), + "Unique vertices differ in ", filename ); + const geode::detail::ArchiveInputFiles files{ filename }; + // Without identifier file, the model gets a new identifier + geode::OpenGeodeModelException::test( + !files.has( "identifier" ) || model.id() == reference.id(), + "Identifier differs in ", filename, ": ", model.id().string(), + " vs ", reference.id().string() ); + geode::OpenGeodeModelException::test( + model.name() == reference.name(), "Name differs in ", filename ); + for( const auto& surface : reference.surfaces() ) + { + geode::OpenGeodeModelException::test( + model.nb_relations( surface.id() ) + == reference.nb_relations( surface.id() ), + "Relations differ in ", filename ); + } + } + + void check_same_brep( const geode::BRep& model, + const geode::BRep& reference, + std::string_view filename ) + { + check_same_components( model, reference, filename ); + geode::OpenGeodeModelException::test( + model.nb_blocks() == reference.nb_blocks(), "Blocks differ in ", + filename ); + for( const auto& block : reference.blocks() ) + { + const auto& mesh = model.block( block.id() ).mesh(); + geode::OpenGeodeModelException::test( + mesh.nb_vertices() == block.mesh().nb_vertices() + && mesh.nb_polyhedra() == block.mesh().nb_polyhedra() + && mesh.type_name() == block.mesh().type_name(), + "Block mesh differs in ", filename ); + } + } + + /*! + * Load every native model file from its archive and from its extracted + * directory (through the directory input files): same models. + */ + void test_data_files() + { + geode::index_t nb_files{ 0 }; + for( const auto& file : std::filesystem::recursive_directory_iterator( + std::filesystem::u8path( geode::DATA_PATH ) ) ) + { + const auto path = file.path().u8string(); + const auto extension = file.path().extension().u8string(); + if( extension != ".og_brep" && extension != ".og_sctn" ) + { + continue; + } + geode::Logger::info( "Checking ", path ); + const geode::UnzipFile unzip{ path, geode::uuid{}.string() }; + unzip.extract_all(); + if( extension == ".og_brep" ) + { + geode::BRep reference{ geode::BITSERY::constructor }; + geode::detail::load_brep_files( reference, + geode::detail::DirectoryInputFiles{ unzip.directory() } ); + const auto brep = + geode::load_one( geode::load_brep( path ), path ); + check_same_brep( brep, reference, path ); + } + else + { + geode::Section reference{ geode::BITSERY::constructor }; + geode::detail::load_section_files( reference, + geode::detail::DirectoryInputFiles{ unzip.directory() } ); + const auto section = + geode::load_one( geode::load_section( path ), path ); + check_same_components( section, reference, path ); + } + nb_files++; + } + geode::OpenGeodeModelException::test( + nb_files >= 10, "Too few model files found: ", nb_files ); + } + + void set_environment( + const char* name, const std::optional< std::string >& value ) + { +#ifdef _WIN32 + _putenv_s( name, value ? value->c_str() : "" ); +#else + if( value ) + { + setenv( name, value->c_str(), 1 ); + } + else + { + unsetenv( name ); + } +#endif + } + + /*! + * Loading a model does not use the temporary directory: pointing it to a + * regular file makes any use of it fail. + */ + void test_no_temporary_directory() + { + const auto brep_file = + absl::StrCat( geode::DATA_PATH, "layers.og_brep" ); + const auto section_file = + absl::StrCat( geode::DATA_PATH, "fractures.og_sctn" ); + const auto reference_brep = + geode::load_one( geode::load_brep( brep_file ), brep_file ); + const auto reference_section = geode::load_one( + geode::load_section( section_file ), section_file ); + const std::vector< std::string > variables{ "TMPDIR", "TMP", "TEMP" }; + std::vector< std::optional< std::string > > old_values; + for( const auto& variable : variables ) + { + const auto* value = std::getenv( variable.c_str() ); + old_values.emplace_back( + value ? std::optional< std::string >{ value } : std::nullopt ); + } + const auto not_a_directory = + std::filesystem::absolute( "temporary_directory_file" ); + { + std::ofstream file{ not_a_directory }; + file << "not a directory"; + } + const auto empty_directory = + std::filesystem::absolute( "empty_temporary_directory" ); + std::filesystem::remove_all( empty_directory ); + std::filesystem::create_directories( empty_directory ); + for( const auto& temporary : { not_a_directory, empty_directory } ) + { + for( const auto& variable : variables ) + { + set_environment( variable.c_str(), temporary.u8string() ); + } + const auto brep = + geode::load_one( geode::load_brep( brep_file ), brep_file ); + check_same_brep( brep, reference_brep, brep_file ); + const auto section = geode::load_one( + geode::load_section( section_file ), section_file ); + check_same_components( section, reference_section, section_file ); + } + for( const auto i : geode::Indices{ variables } ) + { + set_environment( variables[i].c_str(), old_values[i] ); + } + geode::OpenGeodeModelException::test( + std::filesystem::is_empty( empty_directory ), + "Loading a model created files in the temporary directory" ); + std::filesystem::remove( not_a_directory ); + std::filesystem::remove_all( empty_directory ); + } + + std::string read_file( const std::string& filename ) + { + const auto content = geode::detail::map_file_content( filename ); + geode::OpenGeodeModelException::test( + content.has_value(), "Cannot read ", filename ); + return { content->span().data(), content->span().size() }; + } + + /*! + * Flip a byte in the middle of the data of an entry of a stored archive. + */ + void corrupt_entry( + const std::string& archive_file, const std::string& name ) + { + const auto size = [&] { + const geode::detail::ArchiveInputFiles files{ archive_file }; + return files.content( name ).span().size(); + }(); + auto archive = read_file( archive_file ); + // Find the local header of the entry + const std::string signature{ "PK\x03\x04" }; + auto header = archive.find( signature ); + const auto read_uint16 = [&archive]( size_t position ) { + return static_cast< size_t >( + static_cast< unsigned char >( archive[position] ) + + 256U + * static_cast< unsigned char >( archive[position + 1] ) ); + }; + while( + header != std::string::npos + && !( read_uint16( header + 26 ) == name.size() + && archive.compare( header + 30, name.size(), name ) == 0 ) ) + { + header = archive.find( signature, header + 1 ); + } + geode::OpenGeodeModelException::test( + header != std::string::npos, "Entry ", name, " not found" ); + const auto name_position = header + 30; + const auto extra_length = read_uint16( header + 28 ); + const auto data = name_position + name.size() + extra_length; + archive[data + size / 2] = + static_cast< char >( ~archive[data + size / 2] ); + std::ofstream file{ std::filesystem::u8path( archive_file ), + std::ios::binary }; + file.write( + archive.data(), static_cast< std::streamsize >( archive.size() ) ); + } + + void test_corrupted_entries() + { + const auto source = absl::StrCat( geode::DATA_PATH, "layers.og_brep" ); + std::string mesh_entry; + { + const geode::detail::ArchiveInputFiles files{ source }; + for( const auto& name : files.names() ) + { + if( absl::StartsWith( name, "Surface" ) ) + { + mesh_entry = name; + break; + } + } + } + for( const auto& entry : { mesh_entry, std::string{ "vertices" }, + std::string{ "surfaces" } } ) + { + const std::string corrupted{ "corrupted_entry.og_brep" }; + std::filesystem::copy_file( source, corrupted, + std::filesystem::copy_options::overwrite_existing ); + corrupt_entry( corrupted, entry ); + bool thrown{ false }; + try + { + geode_unused( geode::load_brep( corrupted ) ); + } + catch( const geode::OpenGeodeException& exception ) + { + thrown = true; + geode::OpenGeodeModelException::test( + exception.type() == geode::OpenGeodeException::TYPE::data + && absl::StrContains( exception.what(), + absl::StrCat( corrupted, "/", entry ) ) + && absl::StrContains( exception.what(), "CRC" ), + "Corrupted entry ", entry, + ": wrong error: ", exception.what() ); + } + geode::OpenGeodeModelException::test( + thrown, "Corrupted entry ", entry, " was not detected" ); + std::filesystem::remove( corrupted ); + } + } +} // namespace + +void test() +{ + geode::OpenGeodeModelLibrary::initialize(); + test_data_files(); + test_no_temporary_directory(); + test_corrupted_entries(); +} + +OPENGEODE_TEST( "model-archive-input" ) diff --git a/tests/model/test-model-corrupted-files.cpp b/tests/model/test-model-corrupted-files.cpp index af475bfe0..7a21b35f9 100644 --- a/tests/model/test-model-corrupted-files.cpp +++ b/tests/model/test-model-corrupted-files.cpp @@ -338,12 +338,16 @@ namespace /* * Mesh components have a "unique vertices" attribute linking their * vertices to the model unique vertices. When this attribute is missing, - * it is restored from the unique vertices. + * it is restored from the unique vertices of the files storing their + * component mesh vertices (before version 5 of the vertices file). */ void test_missing_unique_vertices_attribute() { - const auto brep = saved_brep( "unique_vertices.og_brep" ); - auto files = extract_archive( "unique_vertices.og_brep" ); + const auto legacy_filename = + absl::StrCat( geode::DATA_PATH, "backward_io/v20_2/v20_2.og_brep" ); + const auto brep = geode::load_one( + geode::load_brep( legacy_filename ), legacy_filename ); + auto files = extract_archive( legacy_filename ); replace_unique( files.at( "vertices" ), serialized_uuid( brep.unique_vertex_attribute_id() ), serialized_uuid( geode::uuid{} ), "Unique vertex attribute id" ); @@ -361,6 +365,60 @@ namespace check_same_unique_vertices( brep, loaded ); } + /* + * The vertices file stores the number of unique vertices, the component + * mesh vertices are rebuilt from the "unique vertices" attribute of the + * component meshes. Attribute values out of the unique vertex range are + * removed. + */ + void test_invalid_unique_vertex_links() + { + const auto brep = saved_brep( "invalid_links.og_brep" ); + auto files = extract_archive( "invalid_links.og_brep" ); + const auto nb_unique_vertices = brep.nb_unique_vertices(); + const auto last = nb_unique_vertices - 1; + geode::OpenGeodeModelException::test( + !brep.is_unique_vertex_isolated( last ), + "[Test] Last unique vertex should not be isolated" ); + const auto id = serialized_uuid( brep.unique_vertex_attribute_id() ); + replace_unique( files.at( "vertices" ), + absl::StrCat( serialized_u32( nb_unique_vertices ), id ), + absl::StrCat( serialized_u32( last ), id ), + "Number of unique vertices" ); + write_archive( files, "corrupted_invalid_links.og_brep" ); + + WarningRecorder::start(); + const auto loaded = geode::load_one( + geode::load_brep( "corrupted_invalid_links.og_brep" ), + "corrupted_invalid_links.og_brep" ); + check_warning( "component vertex links to unknown unique vertices" ); + geode::OpenGeodeModelException::test( + loaded.nb_unique_vertices() == last, + "[Test] Wrong number of unique vertices" ); + for( const auto& vertex : brep.component_mesh_vertices( last ) ) + { + geode::OpenGeodeModelException::test( + loaded.unique_vertex( vertex ) == geode::NO_ID, + "[Test] Link to a removed unique vertex should be removed" ); + } + for( const auto unique_vertex : geode::Range{ last } ) + { + const auto& vertices = + brep.component_mesh_vertices( unique_vertex ); + geode::OpenGeodeModelException::test( + loaded.component_mesh_vertices( unique_vertex ).size() + == vertices.size(), + "[Test] Wrong number of component vertices for unique vertex ", + unique_vertex ); + for( const auto& vertex : vertices ) + { + geode::OpenGeodeModelException::test( + loaded.unique_vertex( vertex ) == unique_vertex, + "[Test] Wrong unique vertex for component vertex" ); + } + } + } + /* * Unique vertices referencing a component that does not exist in the * model are removed. @@ -776,6 +834,97 @@ namespace "[Test] Truncated relationships should not be loaded" }; } + /* Messages of the exception thrown by loading the BRep, parents included */ + std::string brep_load_error( + std::string_view filename, geode::OpenGeodeException::TYPE type ) + { + try + { + geode_unused( geode::load_brep( filename ) ); + } + catch( const geode::OpenGeodeException& exception ) + { + geode::OpenGeodeModelException::test( exception.type() == type, + "[Test] Wrong exception type loading ", filename, ": ", + exception.string() ); + std::string messages; + const geode::OpenGeodeException* current = &exception; + while( true ) + { + absl::StrAppend( &messages, current->what(), "\n" ); + if( !current->has_parent() ) + { + break; + } + current = ¤t->parent(); + } + return messages; + } + throw geode::OpenGeodeModelException{ nullptr, + geode::OpenGeodeException::TYPE::internal, "[Test] Loading ", + filename, " should throw" }; + } + + /* + * Truncated model files are not loaded: data error raised by the loading + * of the file. + */ + void test_truncated_model_files() + { + saved_brep( "truncated_files.og_brep" ); + const auto files = extract_archive( "truncated_files.og_brep" ); + for( const std::string name : { "identifier", "physical_properties", + "corners", "relationships", "vertices" } ) + { + auto truncated = files; + auto& content = truncated.at( name ); + content.resize( content.size() / 2 ); + const auto filename = + absl::StrCat( "truncated_", name, ".og_brep" ); + write_archive( truncated, filename ); + const auto messages = brep_load_error( + filename, geode::OpenGeodeException::TYPE::data ); + geode::Logger::info( "Truncated ", name, ": ", messages ); + geode::OpenGeodeModelException::test( + absl::StrContains( messages, filename ), + "[Test] Wrong error for truncated ", name, ": ", messages ); + } + } + + /* + * Optional model files: missing ones are ignored, empty ones are not + * valid files. + */ + void test_empty_optional_files() + { + saved_brep( "optional_files.og_brep" ); + const auto files = extract_archive( "optional_files.og_brep" ); + for( const std::string name : { "identifier", "physical_properties" } ) + { + auto missing = files; + missing.erase( name ); + const auto missing_filename = + absl::StrCat( "missing_", name, ".og_brep" ); + write_archive( missing, missing_filename ); + const auto loaded = geode::load_one( + geode::load_brep( missing_filename ), missing_filename ); + geode::OpenGeodeModelException::test( loaded.nb_corners() != 0, + "[Test] Model without ", name, " should be loaded" ); + + auto empty = files; + empty.at( name ).clear(); + const auto empty_filename = + absl::StrCat( "empty_", name, ".og_brep" ); + write_archive( empty, empty_filename ); + const auto messages = brep_load_error( + empty_filename, geode::OpenGeodeException::TYPE::data ); + geode::Logger::info( "Empty ", name, ": ", messages ); + geode::OpenGeodeModelException::test( + absl::StrContains( messages, empty_filename ), + "[Test] Wrong error for empty ", name, ": ", messages ); + } + } + template < typename Base > class ThrowingInput final : public Base { @@ -890,6 +1039,7 @@ void test() geode::OpenGeodeModelLibrary::initialize(); test_inconsistent_relationships_map(); test_missing_unique_vertices_attribute(); + test_invalid_unique_vertex_links(); test_unknown_component_vertices(); test_missing_components_file(); test_wrong_component_key(); @@ -902,6 +1052,8 @@ void test() test_too_long_component_name(); test_logger_level_restored(); test_std_exceptions(); + test_truncated_model_files(); + test_empty_optional_files(); } OPENGEODE_TEST( "model-corrupted-files" ) diff --git a/tests/model/test-model-deflate-archive.cpp b/tests/model/test-model-deflate-archive.cpp new file mode 100644 index 000000000..958b878db --- /dev/null +++ b/tests/model/test-model-deflate-archive.cpp @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2019 - 2026 Geode-solutions + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * + */ + +#include + +#include + +#include +#include + +#include +#include +#include +#include + +#include + +void check_same_brep( const geode::BRep& brep, const geode::BRep& reference ) +{ + geode::OpenGeodeModelException::test( + brep.nb_corners() == reference.nb_corners() + && brep.nb_lines() == reference.nb_lines() + && brep.nb_surfaces() == reference.nb_surfaces() + && brep.nb_blocks() == reference.nb_blocks() + && brep.nb_unique_vertices() == reference.nb_unique_vertices(), + "BRep loaded from the DEFLATE archive differs from the reference" ); + for( const auto& surface : reference.surfaces() ) + { + const auto& mesh = brep.surface( surface.id() ).mesh(); + geode::OpenGeodeModelException::test( + mesh.nb_vertices() == surface.mesh().nb_vertices() + && mesh.nb_polygons() == surface.mesh().nb_polygons(), + "Surface mesh loaded from the DEFLATE archive differs" ); + } + for( const auto& block : reference.blocks() ) + { + const auto& mesh = brep.block( block.id() ).mesh(); + geode::OpenGeodeModelException::test( + mesh.nb_vertices() == block.mesh().nb_vertices() + && mesh.nb_polyhedra() == block.mesh().nb_polyhedra(), + "Block mesh loaded from the DEFLATE archive differs" ); + } +} + +void test() +{ + geode::OpenGeodeModelLibrary::initialize(); + const auto filename = absl::StrCat( geode::DATA_PATH, "layers.og_brep" ); + // layers.og_brep re-zipped by Python zipfile with ZIP_DEFLATED + const auto deflated = + absl::StrCat( geode::DATA_PATH, "layers_deflate.og_brep" ); + const auto reference = + geode::load_one( geode::load_brep( filename ), filename ); + const auto brep = geode::load_one( geode::load_brep( deflated ), deflated ); + check_same_brep( brep, reference ); +} + +OPENGEODE_TEST( "model-deflate-archive" ) diff --git a/tests/model/test-section.cpp b/tests/model/test-section.cpp index 8711170f2..db458128f 100644 --- a/tests/model/test-section.cpp +++ b/tests/model/test-section.cpp @@ -21,6 +21,9 @@ * */ +#include +#include + #include #include #include @@ -880,6 +883,196 @@ void test_clone( const geode::Section& section ) } } +std::vector< geode::ComponentMeshVertex > sorted_component_mesh_vertices( + const geode::Section& model, geode::index_t unique_vertex ) +{ + auto vertices = model.component_mesh_vertices( unique_vertex ); + absl::c_sort( vertices ); + return vertices; +} + +/* + * Loaded component mesh vertices are rebuilt from the component meshes: + * components in the model order (Corners, Lines, Surfaces), then + * their vertices in increasing order. + */ +void check_loaded_component_mesh_vertices_order( const geode::Section& model ) +{ + absl::flat_hash_map< geode::uuid, geode::index_t > ranks; + geode::index_t rank{ 0 }; + for( const auto& component : model.corners() ) + { + ranks.emplace( component.id(), rank++ ); + } + for( const auto& component : model.lines() ) + { + ranks.emplace( component.id(), rank++ ); + } + for( const auto& component : model.surfaces() ) + { + ranks.emplace( component.id(), rank++ ); + } + for( const auto unique_vertex : geode::Range{ model.nb_unique_vertices() } ) + { + const auto& vertices = model.component_mesh_vertices( unique_vertex ); + for( const auto v : geode::Range{ 1, vertices.size() } ) + { + const auto& previous = vertices[v - 1]; + const auto& current = vertices[v]; + geode::OpenGeodeModelException::test( + std::make_pair( + ranks.at( previous.component_id.id ), previous.vertex ) + < std::make_pair( + ranks.at( current.component_id.id ), current.vertex ), + "[Test] Loaded component mesh vertices of unique vertex ", + unique_vertex, " are not in the model order" ); + } + } +} + +void test_compare_component_mesh_vertices( + const geode::Section& model, const geode::Section& model2 ) +{ + geode::OpenGeodeModelException::test( model.nb_unique_vertices() > 0, + "[Test] Model should have unique vertices" ); + geode::OpenGeodeModelException::test( + model.nb_unique_vertices() == model2.nb_unique_vertices(), + "[Test] Reloaded model should have ", model.nb_unique_vertices(), + " unique vertices" ); + const geode::uuid nil{ geode::BITSERY::constructor }; + for( const auto unique_vertex : geode::Range{ model.nb_unique_vertices() } ) + { + geode::OpenGeodeModelException::test( + sorted_component_mesh_vertices( model, unique_vertex ) + == sorted_component_mesh_vertices( model2, unique_vertex ), + "[Test] Reloaded component mesh vertices of unique vertex ", + unique_vertex, " should be equal to the saved ones" ); + for( const auto& vertex : + model2.component_mesh_vertices( unique_vertex ) ) + { + geode::OpenGeodeModelException::test( vertex.component_id.id != nil, + "[Test] Reloaded component id should not be nil" ); + geode::OpenGeodeModelException::test( + model2.unique_vertex( vertex ) == unique_vertex, + "[Test] Reloaded component mesh vertex should map to unique " + "vertex ", + unique_vertex ); + } + } + check_loaded_component_mesh_vertices_order( model2 ); +} + +/* + * Loading the same model twice gives the same component mesh vertices, in + * the same order. + */ +void test_compare_component_mesh_vertices_order( + const geode::Section& model, const geode::Section& model2 ) +{ + for( const auto unique_vertex : geode::Range{ model.nb_unique_vertices() } ) + { + geode::OpenGeodeModelException::test( + model.component_mesh_vertices( unique_vertex ) + == model2.component_mesh_vertices( unique_vertex ), + "[Test] Component mesh vertices of unique vertex ", unique_vertex, + " should be in the same order in both loaded models" ); + } +} + +void test_component_mesh_vertices_round_trip() +{ + const auto filename = absl::StrCat( geode::DATA_PATH, "fractures.og_sctn" ); + const auto model = + geode::load_one( geode::load_section( filename ), filename ); + const auto file_io = absl::StrCat( + "test_component_mesh_vertices.", model.native_extension() ); + geode::save_section( model, file_io ); + const auto model2 = + geode::load_one( geode::load_section( file_io ), file_io ); + test_compare_component_mesh_vertices( model, model2 ); + const auto file_io2 = absl::StrCat( + "test_component_mesh_vertices2.", model.native_extension() ); + geode::save_section( model2, file_io2 ); + const auto model3 = + geode::load_one( geode::load_section( file_io2 ), file_io2 ); + test_compare_component_mesh_vertices( model, model3 ); + test_compare_component_mesh_vertices_order( model2, model3 ); +} + +/* + * v20_2.og_sctn was saved when the component mesh vertices were stored in the + * file: a triangle Surface, its 3 Lines and 3 Corners on unique vertices 0 to + * 2, and 2 isolated unique vertices. + */ +void test_backward_io_component_mesh_vertices() +{ + const auto filename = + absl::StrCat( geode::DATA_PATH, "backward_io/v20_2/v20_2.og_sctn" ); + const auto section = + geode::load_one( geode::load_section( filename ), filename ); + geode::OpenGeodeModelException::test( section.nb_unique_vertices() == 5, + "[Backward_IO] Wrong number of unique vertices" ); + for( const auto unique_vertex : geode::Range{ 3 } ) + { + const auto& vertices = section.component_mesh_vertices( unique_vertex ); + geode::index_t nb_corners{ 0 }; + geode::index_t nb_lines{ 0 }; + geode::index_t nb_surfaces{ 0 }; + for( const auto& vertex : vertices ) + { + geode::OpenGeodeModelException::test( + section.unique_vertex( vertex ) == unique_vertex, + "[Backward_IO] Wrong unique vertex of ", vertex.string() ); + if( vertex.component_id.type + == geode::Corner2D::component_type_static() ) + { + nb_corners++; + } + else if( vertex.component_id.type + == geode::Line2D::component_type_static() ) + { + nb_lines++; + } + else if( vertex.component_id.type + == geode::Surface2D::component_type_static() ) + { + geode::OpenGeodeModelException::test( + vertex.vertex == unique_vertex, + "[Backward_IO] Wrong surface vertex" ); + nb_surfaces++; + } + } + geode::OpenGeodeModelException::test( + vertices.size() == 4 && nb_corners == 1 && nb_lines == 2 + && nb_surfaces == 1, + "[Backward_IO] Wrong component mesh vertices of unique vertex ", + unique_vertex ); + } + for( const auto unique_vertex : geode::Range{ 3, 5 } ) + { + geode::OpenGeodeModelException::test( + section.is_unique_vertex_isolated( unique_vertex ), + "[Backward_IO] Unique vertex ", unique_vertex, + " should be isolated" ); + } + + const auto file_io = + absl::StrCat( "v20_2_resaved.", section.native_extension() ); + geode::save_section( section, file_io ); + auto reloaded = geode::load_one( geode::load_section( file_io ), file_io ); + test_compare_component_mesh_vertices( section, reloaded ); + + geode::SectionBuilder builder{ reloaded }; + const auto old2new = builder.delete_isolated_vertices(); + geode::OpenGeodeModelException::test( + old2new + == std::vector< geode::index_t >{ 0, 1, 2, geode::NO_ID, + geode::NO_ID }, + "[Backward_IO] Wrong mapping after deleting isolated unique vertices" ); + geode::OpenGeodeModelException::test( reloaded.nb_unique_vertices() == 3, + "[Backward_IO] Wrong number of unique vertices after deletion" ); +} + void test_compare_section( const geode::Section& model, const geode::Section& model2 ) { @@ -1101,11 +1294,18 @@ void test() auto backward_model = geode::load_one( geode::load_section( backward_model_filename ), backward_model_filename ); + geode::OpenGeodeModelException::test( + backward_model.unique_vertex_attribute_id() + != geode::uuid{ geode::BITSERY::constructor }, + "[Backward_IO] v17 Section should have a valid unique vertex " + "attribute id" ); auto model2 = geode::load_one( geode::load_section( file_io ), file_io ); test_compare_section( model, model2 ); geode::Section model3{ std::move( model2 ) }; test_compare_section( model, model3 ); + test_component_mesh_vertices_round_trip(); + test_backward_io_component_mesh_vertices(); } OPENGEODE_TEST( "section" ) \ No newline at end of file diff --git a/tests/model/test-vertex-identifier.cpp b/tests/model/test-vertex-identifier.cpp index 22aa35fb7..64faa1cb3 100644 --- a/tests/model/test-vertex-identifier.cpp +++ b/tests/model/test-vertex-identifier.cpp @@ -21,7 +21,15 @@ * */ +#include +#include + +#include + +#include + #include +#include #include #include @@ -165,10 +173,31 @@ void test_modify_unique_vertices( geode::VertexIdentifier& vertex_identifier ) "Reset of a unique vertex is not correct - values" ); } +std::vector< geode::ComponentMeshVertex > sorted_component_mesh_vertices( + const geode::VertexIdentifier& vertex_identifier, + geode::index_t unique_vertex ) +{ + auto vertices = vertex_identifier.component_mesh_vertices( unique_vertex ); + absl::c_sort( vertices ); + return vertices; +} + +std::uintmax_t vertices_file_size() +{ + return std::filesystem::file_size( std::filesystem::u8path( "vertices" ) ); +} + +/* + * The vertices file stores the number of unique vertices, not their component + * mesh vertices: these are rebuilt from the component mesh attributes when + * the components are loaded, by repair_component_vertices. The rebuilt order + * follows the component registration order, so lists are compared as sets. + */ void test_save_and_load_unique_vertices( - geode::VertexIdentifier& vertex_identifier ) + geode::VertexIdentifier& vertex_identifier, const CornerProvider& provider ) { vertex_identifier.save_unique_vertices( "." ); + const auto file_size = vertices_file_size(); geode::VertexIdentifier vertex_identifier2; geode::VertexIdentifierBuilder loader{ vertex_identifier2 }; loader.load_unique_vertices( "." ); @@ -181,20 +210,34 @@ void test_save_and_load_unique_vertices( geode::Range{ vertex_identifier2.nb_unique_vertices() } ) { geode::OpenGeodeModelException::test( - vertex_identifier.component_mesh_vertices( v_id ).size() - == vertex_identifier2.component_mesh_vertices( v_id ).size(), + vertex_identifier2.is_unique_vertex_isolated( v_id ), + "Loaded unique vertices should be isolated before loading their " + "components" ); + } + for( const auto& corner : provider.corners() ) + { + loader.load_mesh_component( corner ); + } + loader.repair_component_vertices(); + for( const auto v_id : + geode::Range{ vertex_identifier2.nb_unique_vertices() } ) + { + geode::OpenGeodeModelException::test( + sorted_component_mesh_vertices( vertex_identifier, v_id ) + == sorted_component_mesh_vertices( vertex_identifier2, v_id ), "Save/Load of unique vertices are not correct (different " - "number of component mesh vertices)" ); - for( const auto cmv : geode::Range{ - vertex_identifier.component_mesh_vertices( v_id ).size() } ) - { - geode::OpenGeodeModelException::test( - vertex_identifier.component_mesh_vertices( v_id )[cmv] - == vertex_identifier2.component_mesh_vertices( v_id )[cmv], - "Save/Load of unique vertices are not correct " - "(different component mesh vertices)" ); - } + "component mesh vertices)" ); } + + // The file size does not depend on the number of component mesh vertices + geode::VertexIdentifier empty_identifier; + geode::VertexIdentifierBuilder{ empty_identifier }.create_unique_vertices( + vertex_identifier.nb_unique_vertices() ); + empty_identifier.save_unique_vertices( "." ); + geode::OpenGeodeModelException::test( vertices_file_size() == file_size, + "Saved unique vertices should not store the component mesh vertices " + "(file size ", + file_size, " instead of ", vertices_file_size(), ")" ); } void test_update_unique_vertices() @@ -425,9 +468,60 @@ void test_unregister_after_load() } } +void test_component_mesh_vertex_deserialization() +{ + const geode::uuid nil{ geode::BITSERY::constructor }; + const auto created_id = bitsery::Access::create< geode::ComponentID >(); + geode::OpenGeodeModelException::test( + created_id.type.get() == "undefined" && created_id.id == nil, + "ComponentID created by bitsery should be undefined and nil" ); + const auto created_vertex = + bitsery::Access::create< geode::ComponentMeshVertex >(); + geode::OpenGeodeModelException::test( + created_vertex.component_id.type.get() == "undefined" + && created_vertex.component_id.id == nil, + "ComponentMeshVertex created by bitsery should have an undefined and " + "nil ComponentID" ); + const geode::ComponentID default_id; + geode::OpenGeodeModelException::test( + default_id.id != nil, "Default ComponentID should generate its uuid" ); + + const geode::ComponentID component_id{ + geode::Corner2D::component_type_static(), geode::uuid{} + }; + std::vector< geode::ComponentMeshVertex > vertices{ { component_id, 3 }, + { { geode::Surface2D::component_type_static(), geode::uuid{} }, 7 } }; + std::stringstream stream; + { + geode::TContext context{}; + geode::Serializer archive{ context, stream }; + archive.object( component_id ); + archive.container( vertices, vertices.size() ); + archive.adapter().flush(); + } + geode::ComponentID loaded_id{ geode::BITSERY::constructor }; + std::vector< geode::ComponentMeshVertex > loaded_vertices; + { + geode::TContext context{}; + const auto bytes = stream.str(); + geode::Deserializer archive{ context, bytes.data(), bytes.size() }; + archive.object( loaded_id ); + archive.container( loaded_vertices, vertices.size() ); + geode::OpenGeodeModelException::test( + archive.adapter().error() == bitsery::ReaderError::NoError + && archive.adapter().isCompletedSuccessfully(), + "ComponentMeshVertex deserialization should succeed" ); + } + geode::OpenGeodeModelException::test( loaded_id == component_id, + "Deserialized ComponentID should be the saved one" ); + geode::OpenGeodeModelException::test( loaded_vertices == vertices, + "Deserialized ComponentMeshVertex should be the saved ones" ); +} + void test() { geode::OpenGeodeModelLibrary::initialize(); + test_component_mesh_vertex_deserialization(); geode::VertexIdentifier vertex_identifier; geode::OpenGeodeModelException::test( vertex_identifier.nb_unique_vertices() == 0, @@ -458,7 +552,7 @@ void test() test_create_unique_vertices( vertex_identifier ); test_set_unique_vertices( vertex_identifier, provider ); test_modify_unique_vertices( vertex_identifier ); - test_save_and_load_unique_vertices( vertex_identifier ); + test_save_and_load_unique_vertices( vertex_identifier, provider ); test_update_unique_vertices(); test_unregister_mesh_component();