fastgltf

repository·main·Indexed 20 days ago

https://github.com/spnda/fastgltf

A speed and usability focused glTF 2.0 library written in modern C++17 (with optional C++20 support). It leverages SIMD to optimize parsing and loading, providing full support for the glTF 2.0 specification and various extensions. Key features include a built-in math library for transformations, tools for analyzing accessor data, and the ability to write directly to mapped GPU buffers. The library includes Parser and Exporter classes for I/O operations and supports Android APK asset loading.

Tokens
7.3K
Snippets
12
Records
33
Agent score
67%

What's inside fastgltf

  1. Overview of fastgltf

    main

    fastgltf is a high-performance glTF 2.0 library written in modern C++17 (with optional C++20 support). It is designed for speed and usability, utilizing SIMD to accelerate parsing and loading.

    Key features include:

    • Full support for the glTF 2.0 specification and many extensions.
    • Minimal dependencies.
    • Safe and easy access to glTF properties and data via modern C++ features.
    • Available as a C++20 named module.
    • Accessor tools for data manipulation.
    • Ability to write directly to mapped GPU buffers.
    • Decomposing transform matrices.

    By default, the library performs only the minimum required operations to work with a model, allowing developers to opt-in to additional features as needed.

  2. Overview of fastgltf features and requirements

    main

    fastgltf is a glTF 2.0 library designed for speed and usability. It is written in modern C++17 (with optional C++20 support) and features minimal dependencies.

    Key capabilities include:

    • High Performance: Uses SIMD to accelerate parsing and loading glTF data.
    • Full Specification Support: Supports the complete glTF 2.0 specification and many extensions.
    • Ease of Use: Provides safe and easy access to properties and data via modern C++ features.
    • Advanced Data Tools: Includes accessor tools, support for writing directly to mapped GPU buffers, and transform matrix decomposition.
  3. Use glTF structs to represent asset data

    main

    fastgltf provides a set of structs that represent the core components of a glTF asset. These structs allow you to traverse and manipulate the scene graph and data.

    Core data structures include:

    • Asset: The root object representing the entire glTF file.
    • Scene: A collection of nodes that form a scene.
    • Node: A node in the scene hierarchy, containing transformations and references to meshes or skins.
    • Mesh: Contains primitives that define geometry.
    • Material: Defines the visual appearance of a mesh.
    • Accessor: Describes how to interpret buffer data (e.g., vertex positions).
    • Buffer & BufferView: Represent the raw binary data and its segments.
    • Animation, Camera, Image, Light, Sampler, Skin, and Texture: Other standard glTF components.
  4. Load data from accessors

    main
    Reading raw data from glTF accessors can be complex due to various specification edge cases. fastgltf provides specialized tools (in fastgltf/tools.hpp) designed to simplify reading data from accessors while handling these edge cases automatically.
  5. Provide a custom BufferDataAdapter for external buffers

    main

    Accessor tools use a BufferDataAdapter to access binary data. By default, fastgltf::DefaultBufferDataAdapter works only if buffers are loaded as sources::ByteView, sources::Array, or sources::Vector (e.g., if Options::LoadExternalBuffers was used during parsing).

    If you are using external buffers (loaded as sources::URI), you must provide a custom adapter or a lambda to map the buffer view to memory.

    std::vector<std::byte> fileBytes;
    std::vector<std::uint8_t> accessorData(accessor.count);
    fastgltf::copyFromAccessor(asset.get(), accessor, accessorData.data(), [&](const Asset& asset, const std::size_t bufferViewIdx) const {
        const auto& bufferView = asset.bufferViews[bufferViewIdx];
        return span(fileBytes).subspan(bufferView.byteOffset, bufferView.byteLength);
    });
  6. Define ElementTraits for custom data types

    main

    To use accessor tools with custom math types (like a custom vector class), you must specialize the fastgltf::ElementTraits template. This tells fastgltf how to map the accessor's properties (like Vec3) to your type.

    fastgltf provides built-in support for glm (via fastgltf/glm_element_traits.hpp) and DirectXMath (via fastgltf/dxmath_element_traits.hpp). You can also use fastgltf's own internal math types which are supported out-of-the-box.

    // Example: Specializing ElementTraits for a custom type MyVec3
    template <>
    struct fastgltf::ElementTraits<MyVec3> : fastgltf::ElementTraitsBase<MyVec3, AccessorType::Vec3, float> {};
  7. Load glTF files for parsing using GltfDataGetter

    main

    Before parsing with fastgltf::Parser, you must load the glTF data into memory using a class that implements the fastgltf::GltfDataGetter interface.

    Two common implementations are:

    1. fastgltf::GltfDataBuffer: Holds the entire glTF in a memory buffer. Use factory constructors like FromPath or FromBytes. Always check the returned Expected<T> for errors.
    2. fastgltf::GltfFileStream: A wrapper around std::ifstream for streaming file content.
    // Using GltfDataBuffer
    auto gltfFile = fastgltf::GltfDataBuffer::FromPath("./asset.gltf");
    auto gltfData = fastgltf::GltfDataBuffer::FromBytes(bytes.data(), bytes.size());
    
    // Using GltfFileStream
    fastgltf::GltfFileStream fileStream("./asset.gltf");
    if (!fileStream.isOpen())
        return false;
  8. Configure fastgltf compilation via CMake

    main

    fastgltf provides several CMake options to control its compilation behavior, memory management, and feature support. If you are using a build system other than CMake, these options correspond to preprocessor macros that can be set to 0 or 1.

    Warning: Do not define these macros manually within your source files, as this can break compilation or linking. Let the build system handle them.

  9. Install and integrate fastgltf

    main

    fastgltf is a pure C++17 library with a single dependency: simdjson.

    Installation Options

    • CMake: Use the included CMake 3.11 script. It automatically downloads simdjson during the configuration step.
    • Package Managers: Available via vcpkg and conan.

    Compatibility

    • Requires C++17 (C++20 is optionally supported and available as a named module).
    • Tested on GCC 9, GCC 10, Clang 13, and MSVC 14 (Visual Studio 2022).
  10. Include fastgltf headers

    main

    To use fastgltf, include the main header fastgltf/core.hpp. This single header provides the parser, the exporter, and all required functionality.

    Other specialized headers include:

    • fastgltf/types.hpp: POD types and enumerations.
    • fastgltf/tools.hpp: Accessor tools and node transform utilities.
    • fastgltf/math.hpp: Custom math library for glTF assets.
    • fastgltf/base64.hpp: Optimized SIMD-based base64 decoding.
  11. Enable tests, examples, and documentation

    main

    To build auxiliary targets, use the following options. Note that some require running fetch_test_deps.py before configuring CMake to download necessary dependencies.

    • FASTGLTF_ENABLE_TESTS: Set to YES to configure the fastgltf_tests target.
    • FASTGLTF_ENABLE_EXAMPLES: Set to YES to configure all example targets.
    • FASTGLTF_ENABLE_DOCS: Set to YES to configure documentation targets. Requires Doxygen, Sphinx, and breathe to be installed.
  12. Read and write glTF files with Parser and Exporter

    main

    To perform I/O operations with glTF files, use the Parser and Exporter classes.

    Reading glTF files

    Use the fastgltf::Parser class to load glTF data. The parser handles the conversion from raw data (buffers, streams, or memory) into the structured fastgltf::Asset object.

    • fastgltf::determineGltfFileType: Utility to identify the file type.
    • fastgltf::GltfFileStream: For streaming file access.
    • fastgltf::GltfDataBuffer: For handling data in memory buffers.

    Writing glTF files

    Use the fastgltf::Exporter or fastgltf::FileExporter classes to save an Asset back to a file or buffer. You can provide fastgltf::ExportOptions to control the output format and compression.