Coder Social home page Coder Social logo

spnda / fastgltf Goto Github PK

View Code? Open in Web Editor NEW
248.0 4.0 34.0 2.01 MB

A modern C++17 glTF 2.0 library focused on speed, correctness, and usability

Home Page: https://fastgltf.readthedocs.io/v0.7.x/

License: MIT License

CMake 2.40% C++ 96.98% Python 0.34% Rust 0.27%
cpp17 gltf gltf-loader simd gltf2 gltf2-loader khronos cpp cpp-library serialization

fastgltf's Introduction

fastgltf

vcpkg conan center CI_x64 workflow status CI_arm workflow status Documentation Status

fastgltf is a speed and usability focused glTF 2.0 library written in modern C++17 with minimal dependencies. It uses SIMD in various areas to decrease the time the application spends parsing and loading glTF data. By taking advantage of modern C++17 (and optionally C++20) it also provides easy and safe access to the properties and data. It is also available as a C++20 named module.

The library supports the entirety of glTF 2.0 specification, including many extensions. By default, fastgltf will only do the absolute minimum to work with a glTF model. However, it brings many additional features to ease working with the data, including accessor tools, the ability to directly write to mapped GPU buffers, and decomposing transform matrices.

To learn more about fastgltf, its features, performance and API you can read the docs.

Examples and real-world usage

You can find some examples in the examples/ directory of this repository on how to use fastgltf in a 3D renderer to load glTF files. Additionally, this is a list of some interesting projects using fastgltf:

  • Fwog: The examples of this modern OpenGL 4.6 abstraction make use of fastgltf.
  • wad2gltf: A WAD to glTF converter
  • Castor3D: A multi-OS 3D engine
  • Raz: A modern & multiplatform 3D game engine in C++17
  • vkguide: A modern Vulkan tutorial

License

The fastgltf library is licensed under the MIT License.


Libraries embedded in fastgltf:

Libraries used in examples and tests:

  • Catch2: Licensed under BSL-1.0.
  • glad: Licensed under MIT.
  • glfw: Licensed under Zlib.
  • glm: Licensed under MIT.

fastgltf's People

Contributors

apache-hb avatar cyphall avatar dethraid avatar deweh avatar dragonjoker avatar eearslya avatar forenoonwatch avatar hilloftheking avatar juandiegomontoya avatar razakhel avatar spnda avatar stripe2933 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

fastgltf's Issues

Provide an option to skip loading images

Currently, fastgltf loads external images if you specify the option fastgltf::Options::LoadExternalBuffers. An image is not a buffer. Loading images and loading buffers should be separate options

Add option to disable modules even if support is detected

I am working on a project that uses CMake as it's build system want to use this project as a submodule and just add_subdirectory it, however, fastgltf is (correctly) detecting compiler support for C++ modules, but CMake only supports using modules with a limited number of generators, and I'd like my project to be buildable by Unix Makefiles

fastgltf probably shouldn't use tellg to get file sizes, might not always be the file size

Seen here for example:

    std::ifstream file(path, std::ios::ate | std::ios::binary);
    auto length = static_cast<std::streamsize>(file.tellg());
    file.seekg(0);

This has some issues, and there is a bunch of discussion here: https://stackoverflow.com/questions/2409504/using-c-filestreams-fstream-how-can-you-determine-the-size-of-a-file

But long, short, if using c++17 or later, then:

   auto length = std::filesystem::file_size( path );

C++ 20 support

Currently, cmake seems to make sure that we can't use it with a C++ 20 project? Is there a reason to have this restricted to C++ 17, can this limit be removed?

getTransformMatrix redefinition

I'm having an issue with tools.hpp:728 getTransformMatrix getting redefined.
tools.hpp does have #pragma once, so I'm not sure why this is happening.
The lsp server I'm using is warning me that function definitions in a header file can lead to one definition rule violations.
Maybe I'm including fastgltf wrong?
I added fastgltf as a git submodule and have the following in my CMakeLists.txt

add_subdirectory(external/fastgltf/fastgltf/)
target_include_directories("{$PROJECT_NAME}" PUBLIC external/fastgltf)
target_link_libraries("{$PROJECT_NAME}" PUBLIC fastgltf)

My header files all use ifndef, so mine shouldn't be getting included twice, but maybe I made a mistake there. Here's an example of a header include definition.

#ifndef MODEL_H_
#define MODEL_H_
#define GLM_FORCE_RADIANS
#define GLM_ENABLE_EXPERIMENTAL
#include <glm/glm.hpp>
#include <glm/gtx/hash.hpp>
#include <fastgltf/core.hpp>
#include <fastgltf/glm_element_traits.hpp>
...
#endif // MODEL_H_

If I move getTransformMatrix into iterateSceneNodes as a lambda function, it does fix the issue, but this isn't an ideal solution.

/**
 * Iterates over every node within a scene recursively, computing the world space transform of each node,
 * and calling the callback function with that node and the transform.
 */
template <typename Callback>
void iterateSceneNodes(fastgltf::Asset& asset, std::size_t sceneIndex, math::fmat4x4 initial, Callback callback) {
    auto& scene = asset.scenes[sceneIndex];

    /**
     * Computes the transform matrix for a given node, and multiplies the given base with that matrix.
     */
    auto getTransformMatrix = [](const Node& node, const math::fmat4x4& base = math::fmat4x4()) {
        return std::visit(visitor{[&](const math::fmat4x4& matrix) { return base * matrix; },
                                  [&](const TRS& trs) {
                                      return base * translate(math::fmat4x4(), trs.translation) * asMatrix(trs.rotation) *
                                             scale(math::fmat4x4(), trs.scale);
                                  }},
                          node.transform);
    };

    auto function = [&](std::size_t nodeIndex, math::fmat4x4 nodeMatrix, auto& self) -> void {
        assert(asset.nodes.size() > nodeIndex);
        auto& node = asset.nodes[nodeIndex];
        nodeMatrix = getTransformMatrix(node, nodeMatrix);

        callback(node, nodeMatrix);

        for (auto& child : node.children) {
            self(child, nodeMatrix, self);
        }
    };

    for (auto& sceneNode : scene.nodeIndices) {
        function(sceneNode, initial, function);
    }
}

Bug in fg::Parser::generateMeshIndices(): accessor.count assignment uses invalid positionAccessor reference

Error in fg::Parser::generateMeshIndices() when assigning accessor.count from dead positionAccessor.count data.
Results in "bad allcoation" error when trying to allocate the given huge accessor.count data later.
Repro:
MSVS 2022 Debug 64 build.
Load the file https://github.com/KhronosGroup/glTF-Sample-Models/blob/main/2.0/TriangleWithoutIndices/glTF/TriangleWithoutIndices.gltf
with fastgltf::Options::GenerateMeshIndices enabled.
I used these settings

  constexpr auto gltfOptions = fastgltf::Options::None 
    | fastgltf::Options::DontRequireValidAssetMember
    | fastgltf::Options::LoadGLBBuffers
    | fastgltf::Options::LoadExternalBuffers
    | fastgltf::Options::LoadExternalImages
    | fastgltf::Options::GenerateMeshIndices;

BUG: The fg::Parser::generateMeshIndices() function assignment accessor.count = positionAccessor.count; in line 895 is using stale data because the auto& accessor = asset.accessors.emplace_back(); changed the accessor vector and invalidates the previously read positionAccessor reference. In debug mode, all positionAccessor data becomes 0xdddddddd, which is a huge count and results in an allocation error when used later.

Unix makefile support issue

Since the commit "ac86fcc5d3ceda0c1c6017ca1945845f21940afc" in cannot compile anymore with unix makefiles.

This is the message i get from cmake :

CMake Error in external/fastgltf/CMakeLists.txt:
  The target named "fastgltf_module" has C++ sources that may use modules,
  but modules are not supported by this generator:

    Unix Makefiles

  Modules are supported only by Ninja, Ninja Multi-Config, and Visual Studio
  generators for VS 17.4 and newer.  See the cmake-cxxmodules(7) manual for
  details.  Use the CMAKE_CXX_SCAN_FOR_MODULES variable to enable or disable
  scanning.

Myriad syntax issues when trying to include parser.hpp

I added fastgltf 0.6.0 as a dependency to my project by adding the source as a subdirectory in CMake, after which building was fine.
However, when I tried to add "#include <fastgltf/parser.hpp>" to a source file, I was treated to a litany of syntax errors coming from util.hpp:

E:\game_projects\ProRender\fastgltf\include\fastgltf\util.hpp(126,31): error C2146: syntax error: missing ')' before identifier 'a' [E:\game_project
s\ProRender\build\ProRender\ProRender.vcxproj]
E:\game_projects\ProRender\fastgltf\include\fastgltf\util.hpp(126,31): error C2365: 'T': redefinition; previous definition was 'template parameter'
[E:\game_projects\ProRender\build\ProRender\ProRender.vcxproj]
E:\game_projects\ProRender\fastgltf\include\fastgltf\util.hpp(126,31): error C2061: syntax error: identifier 'a' [E:\game_projects\ProRender\build\P
roRender\ProRender.vcxproj]
E:\game_projects\ProRender\fastgltf\include\fastgltf\util.hpp(126,31): error C2059: syntax error: ')' [E:\game_projects\ProRender\build\ProRender\Pr
oRender.vcxproj]
E:\game_projects\ProRender\fastgltf\include\fastgltf\util.hpp(126,31): error C2146: syntax error: missing ')' before identifier 'b' [E:\game_project
s\ProRender\build\ProRender\ProRender.vcxproj]
E:\game_projects\ProRender\fastgltf\include\fastgltf\util.hpp(126,31): error C2146: syntax error: missing ';' before identifier 'b' [E:\game_project
s\ProRender\build\ProRender\ProRender.vcxproj]
E:\game_projects\ProRender\fastgltf\include\fastgltf\util.hpp(126,54): error C2143: syntax error: missing ';' before '{' [E:\game_projects\ProRender
\build\ProRender\ProRender.vcxproj]
E:\game_projects\ProRender\fastgltf\include\fastgltf\util.hpp(126,54): error C2447: '{': missing function header (old-style formal list?) [E:\game_p
rojects\ProRender\build\ProRender\ProRender.vcxproj]
E:\game_projects\ProRender\fastgltf\include\fastgltf\types.hpp(725,75): error C2589: '(': illegal token on right side of '::' [E:\game_projects\ProR
ender\build\ProRender\ProRender.vcxproj]
E:\game_projects\ProRender\fastgltf\include\fastgltf\types.hpp(725,1): error C2062: type 'unknown-type' unexpected [E:\game_projects\ProRender\build
\ProRender\ProRender.vcxproj]
E:\game_projects\ProRender\fastgltf\include\fastgltf\types.hpp(725,39): error C2080: 'missing_value': the type for 'auto' can only be deduced from a
single initializer expression [E:\game_projects\ProRender\build\ProRender\ProRender.vcxproj]
E:\game_projects\ProRender\fastgltf\include\fastgltf\types.hpp(725,39): error C2789: 'fastgltf::OptionalFlagValue<size_t,void>::missing_value': an o
bject of const-qualified type must be initialized [E:\game_projects\ProRender\build\ProRender\ProRender.vcxproj]
E:\game_projects\ProRender\fastgltf\include\fastgltf\types.hpp(725,1): error C2059: syntax error: ')' [E:\game_projects\ProRender\build\ProRender\Pr
oRender.vcxproj]
E:\game_projects\ProRender\fastgltf\include\fastgltf\types.hpp(742,114): error C2589: '(': illegal token on right side of '::' [E:\game_projects\Pro
Render\build\ProRender\ProRender.vcxproj]
E:\game_projects\ProRender\fastgltf\include\fastgltf\types.hpp(742,1): error C2062: type 'unknown-type' unexpected [E:\game_projects\ProRender\build
\ProRender\ProRender.vcxproj]
E:\game_projects\ProRender\fastgltf\include\fastgltf\types.hpp(742,1): error C2144: syntax error: 'unknown-type' should be preceded by '(' [E:\game_
projects\ProRender\build\ProRender\ProRender.vcxproj]
E:\game_projects\ProRender\fastgltf\include\fastgltf\types.hpp(742,1): error C4430: missing type specifier - int assumed. Note: C++ does not support
default-int [E:\game_projects\ProRender\build\ProRender\ProRender.vcxproj]
E:\game_projects\ProRender\fastgltf\include\fastgltf\types.hpp(742,1): fatal error C1903: unable to recover from previous error(s); stopping compil
ation [E:\game_projects\ProRender\build\ProRender\ProRender.vcxproj]

I'm targeting C++20 using MSVC as my compiler. Strangely, while VSCode agrees that the hpp file is littered with syntax errors, it disagrees on the details. I have C++20 set everywhere as the standard I'm using, so I just don't know.

Support the `extras` field

I'd like to request support for the extras field in fastgltf. I don't need anything fancy, a simple string will suffice

I know there's been some discussion about this on Discord, but this feature is crucial to what I'm trying to do so I'm making an Issue about it

clang + Apple M1 compiler warnings

[353/354] Compiling C++ object libmango-import3d.0.1.2.dylib.p/.._source_external_fastgltf_src_fastgltf.cpp.o
../../source/external/fastgltf/src/fastgltf.cpp:2709:41: warning: lambda capture 'this' is not used [-Wunused-lambda-capture]
auto parseAttributes = [this](dom::object& object, decltype(primitive.attributes)& attributes) -> auto {
^~~~
../../source/external/fastgltf/src/fastgltf.cpp:2928:45: warning: lambda capture 'this' is not used [-Wunused-lambda-capture]
auto parseAttributes = [this](dom::object& object, decltype(node.instancingAttributes)& attributes) -> auto {
^~~~
../../source/external/fastgltf/src/fastgltf.cpp:130:24: warning: unused variable 'crcFunction' [-Wunused-variable]
static CRCFunction crcFunction = crc32c;

The lambda capture warnings only appear on Apple M1 + clang, compiles clean on Intel clang on macOS, GCC + Linux, MSVC and so on.

Compiler version information:

Apple clang version 12.0.5 (clang-1205.0.22.11)
Target: arm64-apple-darwin23.2.0
Thread model: posix

Crash when trying to assign a new asset to an existing asset

1.) BUG
Crash when trying to assign an asset to an existing asset (while implementing drag-and-drop of glTF files.)
The problem seems to be the order in which things are moved.
Given the comment about the importance of the order of the memoryResource field here:

#if !FASTGLTF_DISABLE_CUSTOM_MEMORY_POOL
		// This has to be first in this struct so that it gets destroyed last, leaving all allocations
		// alive until the end.
		std::shared_ptr<ChunkMemoryResource> memoryResource;
#endif

I tried changing the order of operations inside the Asset move operators and things work when the memoryResource is moved last(!) like this:

        Asset(Asset&& other) noexcept :
				assetInfo(std::move(other.assetInfo)),
				extensionsUsed(std::move(other.extensionsUsed)),
				extensionsRequired(std::move(other.extensionsRequired)),
				defaultScene(other.defaultScene),
				accessors(std::move(other.accessors)),
				animations(std::move(other.animations)),
				buffers(std::move(other.buffers)),
				bufferViews(std::move(other.bufferViews)),
				cameras(std::move(other.cameras)),
				images(std::move(other.images)),
				lights(std::move(other.lights)),
				materials(std::move(other.materials)),
				meshes(std::move(other.meshes)),
				nodes(std::move(other.nodes)),
				samplers(std::move(other.samplers)),
				scenes(std::move(other.scenes)),
				skins(std::move(other.skins)),
				textures(std::move(other.textures)),
				materialVariants(std::move(other.materialVariants)),
				availableCategories(other.availableCategories)
#if !FASTGLTF_DISABLE_CUSTOM_MEMORY_POOL
				, memoryResource(std::move(other.memoryResource)) // FIX assigning assets works when this happens last.
#endif
        {}

		Asset& operator=(const Asset& other) = delete;
		Asset& operator=(Asset&& other) noexcept {
			assetInfo = std::move(other.assetInfo);
			extensionsUsed = std::move(other.extensionsUsed);
			extensionsRequired = std::move(other.extensionsRequired);
			defaultScene = other.defaultScene;
			accessors = std::move(other.accessors);
			animations = std::move(other.animations);
			buffers = std::move(other.buffers);
			bufferViews = std::move(other.bufferViews);
			cameras = std::move(other.cameras);
			images = std::move(other.images);
			lights = std::move(other.lights);
			materials = std::move(other.materials);
			meshes = std::move(other.meshes);
			nodes = std::move(other.nodes);
			samplers = std::move(other.samplers);
			scenes = std::move(other.scenes);
			skins = std::move(other.skins);
			textures = std::move(other.textures);
			materialVariants = std::move(other.materialVariants);
			availableCategories = other.availableCategories;
#if !FASTGLTF_DISABLE_CUSTOM_MEMORY_POOL
			memoryResource = std::move(other.memoryResource); // FIX assigning assets works when this happens last.
#endif
			return *this;
		}

2.) BUG
Trying to isolate it by disabling FASTGLTF_DISABLE_CUSTOM_MEMORY_POOL inside the CMake GUI didn't work at all.
That crashed in parseAccessors() with uninitialized data, accessor.size() is huge.
(Using KhronosGroup glTF-Sample-Assets BoomBox.gltf.)

fg::Error fg::Parser::parseAccessors(simdjson::dom::array& accessors, Asset& asset) {
    using namespace simdjson;

    asset.accessors.reserve(accessors.size()); // BUG This is huge. Works with FASTGLTF_DISABLE_CUSTOM_MEMORY_POOL enabled.
...
I didn't look into that further.

Integration issues with the downloaded simdjson when using find_package()

Im trying to build this library and use it in my project with find_package(), but get the following CMake error:
I'm on ubuntu and generally find_package() works fine for most libraries im trying to build, but i'm not an cmake expert. I can't really find what im doing wrong or missing, and my skills is lacking when trying to trace back through the internal CMakeLists.txt.

How i installed the library: (with simdjson downloaded = ON)

  1. mkdir build; cd build;
  2. cmake..
  3. make
  4. sudo make install
    Am i missing any steps? CMake obviously finds the fastgltfConfig file, but there are problems with the simdjson installation.
    When building my own project with this library i get:
CMake Error at CMakeLists.txt:71 (find_package):
  Found package configuration file:

 /usr/local/lib/cmake/fastgltf/fastgltfConfig.cmake

  but it set fastgltf_FOUND to FALSE so package "fastgltf" is considered to
  be NOT FOUND.  Reason given by package:

  The following imported targets are referenced, but are missing:
  fastgltf::fastgltf_simdjson

Output when running make install:

Consolidate compiler generated dependencies of target fastgltf_simdjson
[ 40%] Built target fastgltf_simdjson
Consolidate compiler generated dependencies of target fastgltf
[100%] Built target fastgltf
Install the project...
-- Install configuration: ""
-- Installing: /usr/local/include/simdjson.h
-- Installing: /usr/local/lib/libfastgltf_simdjson.a
-- Installing: /usr/local/lib/cmake/fastgltf/fastgltf_simdjsonTargets.cmake
-- Installing: /usr/local/lib/cmake/fastgltf/fastgltf_simdjsonTargets-noconfig.cmake
-- Up-to-date: /usr/local/include/fastgltf/base64.hpp
-- Up-to-date: /usr/local/include/fastgltf/glm_element_traits.hpp
-- Up-to-date: /usr/local/include/fastgltf/parser.hpp
-- Up-to-date: /usr/local/include/fastgltf/tools.hpp
-- Up-to-date: /usr/local/include/fastgltf/types.hpp
-- Up-to-date: /usr/local/include/fastgltf/util.hpp
-- Installing: /usr/local/lib/libfastgltf.a
-- Old export file "/usr/local/lib/cmake/fastgltf/fastgltfConfig.cmake" will be replaced.  Removing files [/usr/local/lib/cmake/fastgltf/fastgltfConfig-noconfig.cmake].
-- Installing: /usr/local/lib/cmake/fastgltf/fastgltfConfig.cmake
-- Installing: /usr/local/lib/cmake/fastgltf/fastgltfConfig-noconfig.cmake

Doesn't work with /SUBSYSTEM:WINDOWS and #include <windows.h>

Still a bit of a C++ noob and so I'm not sure if this is a bug or not but for whatever reason as soon as I switch my application to /SUBSYSTEM:WINDOWS and include "windows.h" with WIN32_LEAN_AND_MEAN defined a bunch of errors pop up in Visual Studio Code 2022. It works fine when the app is set to /SUBSTEM:CONSOLE though.

Sorry in advance if this is a stupid question, I tried and failed to find some info online about it. :)

lack of extensions or so...

Hello!
Thank you for fastgltf. It's impressive but not open all files from https://github.com/gkjohnson/3d-demo-data.git which use and can open https://github.com/gkjohnson/three-gpu-pathtracer.git
For example, I try to open https://raw.githubusercontent.com/gkjohnson/3d-demo-data/main/models/pathtracing-bathroom/modernbathroom.glb and fastgltf_gl_viewer fails with error

Loading c:\msys64\home\user\from-git\3d-demo-data\models\pathtracing-bathroom\modernbathroom.glb
Failed to load glTF: One or more extensions are required by the glTF but not enabled in the Parser.
Failed to parse glTF.

I find here is extension list and extend it to all possible

fastgltf::Parser parser(fastgltf::Extensions::KHR_mesh_quantization);

with change to
fastgltf::Parser parser((fastgltf::Extensions)~0);

After change fastgltf_gl_viewer fails with error

Loading c:\msys64\home\user\from-git\3d-demo-data\models\pathtracing-bathroom\modernbathroom.glb
Failed to load glTF: The glTF is either missing something or has invalid data.
Failed to parse glTF

Can you fix this error?

Parsing error when an animation channel's target has no `node` field

When trying to load a glTF file containing an animation channel with no node field, the parser fails with the error "The glTF is either missing something or has invalid data.".

According to the specs, a channel which does not contain a "node" property is perfectly valid and an implementation should ignore it, unless an extension defines the animated object and the implementation supports this extension.

The nodeIndex member of the AnimationChannel structure should probably be turned into an Optional like other optional properties.

Content of the embedded buffer is not written to the GLB file when exporting

When exporting an asset as GLB, the first buffer is correctly flagged as embedded and no .bin is created, but the content of said buffer is never actually written to the GLB file.

This is caused by missing const qualifiers in the parameter of the visitor handlers:

fastgltf/src/fastgltf.cpp

Lines 5515 to 5539 in 753b161

if (withEmbeddedBuffer) {
const auto& buffer = asset.buffers.front();
BinaryGltfChunk dataChunk;
dataChunk.chunkType = binaryGltfDataChunkMagic;
dataChunk.chunkLength = static_cast<std::uint32_t>(alignUp(buffer.byteLength, 4));
write(&dataChunk, sizeof dataChunk);
for (std::size_t i = 0; i < buffer.byteLength % 4; ++i) {
static constexpr std::uint8_t zero = 0x0U;
write(&zero, sizeof zero);
}
std::visit(visitor {
[](auto arg) {},
[&](sources::Array& vector) {
write(vector.bytes.data(), buffer.byteLength);
},
[&](sources::Vector& vector) {
write(vector.bytes.data(), buffer.byteLength);
},
[&](sources::ByteView& byteView) {
write(byteView.bytes.data(), buffer.byteLength);
},
}, buffer.data);
}

Since buffer is const, buffer.data is also const, but none of the visitor handlers take a const value as parameter so they never get called.
All cases are currently routed to the default handler [](auto arg) {}.

URIs are corrupt if not using fastgltf::Options::LoadExternalBuffers

I'm not entirely sure why yet, but I just updated to the latest and retrofitted around the new URI changes to find that if I don't specify fastgltf::Options::LoadExternalBuffers as an option, when I parse buffers myself (to load manually) I get URIs that claim to be valid local file paths - but they contain garbage strings. Nothing else really going on that should be able to corrupt anything on my end.

Will let you know if I find out more, perhaps I am missing something or making an assumption? My debug code is something along the lines of this:

	auto& buffers = model->buffers;
	for ( auto& buffer : buffers )
	{
		if ( std::holds_alternative<fastgltf::sources::URI>( buffer.data ) )
		{
			const auto& data = std::get<fastgltf::sources::URI>( buffer.data );
			if ( data.uri.isLocalPath() )
			{
				printf( "Corrupt: %s\n", std::string( data.uri.path() ).c_str() );
			}
		}
	}

is EXT_meshopt_compression supported?

I try to open with examples/gl_viewer file https://github.com/gkjohnson/3d-demo-data/tree/main/models/interior-scene/scene.gltf and viewer failed with error code
Failed to parse glTF: 2
Failed to parse glTF
I searched for this error in source code and understand it is an Error::MissingExtensions(2).
I find in src/fastgltf.cpp
line
SET_ERROR_RETURN_ERROR(Error::MissingExtensions)

and before it added
printf("extension: %s\n", std::string(extensionString).c_str());
and now error message is
Loading c:\msys64\home\user\from-git\3d-demo-data\models\interior-scene\scene.gltf
extension: EXT_meshopt_compression
Failed to parse glTF: 2
Failed to parse glTF

i.e EXT_meshopt_compression not supported?
Maybe I need to set some config flags?

Change c++17 standard visibility to private

Can the visibility of the used C++ standard version be changed from PUBLIC to PRIVATE?

target_compile_features(fastgltf PUBLIC cxx_std_17)

When it is public, and the project is consumed by another cmake project, the c++17 flag unnecessarily propagates and generates additional warnings if the main project uses e.g., c++20.

like:

 cl : Command line warning D9025 : overriding '/std:c++17' with '/std:c++latest'

SEGV when iterating .gltf primitive indicied accessor via iterateAccessor or iterateAccessorWithIndex

See the attached test scene.
pineapple_only.zip

Load and parse the scene and try to iterate over the first primitive's indicesAccessor using iterateAccessor() or iterateAccessorWithIndex(). For example:

`
fastgltf::Asset& asset // exists
fastgltf::Primitive& primitive // exists

if (auto indiciesAccessorIndex = primitive.indicesAccessor) {

	vector<uint32_t> indices;
	if (primitive.indicesAccessor.has_value()) {
		auto &accessor = asset.accessors[*indiciesAccessorIndex];
		indices.resize(accessor.count);

		iterateAccessorWithIndex<uint32_t>(
				asset, accessor, [&](uint32_t index, size_t idx) {
					indices[idx] = index;
				});
	}
}

`

Observe SEGV at getAccessorElementAt(), case ComponentType::UnsignedShort.

Thanks! Awesome library!

Add `operator~` for enums

fastgltf has a number of enums that can be or'd together, like fastgltf::Category or fastgltf::Options. These enums should support the bit-inverse operator ~, and any other bitwise operators

Buffer URIs are exported with backslash as directory separator on Windows

Calling fastgltf::FileExporter::setBufferPath with "." and adding a buffer named "test" results in the buffer URI having a backslash as separator in the generated glTF file:

"buffers":[
    {
        "uri":".\\test.bin",
        "byteLength":720,
        "name":"test"
    }
],

However, URIs are expected to only ever use forward slashes as separators.
This makes the glTF file invalid.

After going through the code, I believe that this issue is caused by the use of std::filesystem::path::string (which uses the native separators) instead of std::filesystem::path::generic_string (which always uses forward slashes as separators).

gl_viewer skips primitive morph targets

Follow-up to #36

Using continue when the accessor has no buffer view index for TEXCOORD_0 is incorrect.
https://github.com/spnda/fastgltf/blob/main/examples/gl_viewer/gl_viewer.cpp#L423
The continue only works for the position attribute because that is strictly required.

For all other attributes that needs to be a runtime check, like in this case if (texCoordAccessor.bufferViewIndex.has_value()) to just skip the VAO 1 setting.
The per mesh glVertexArrayElementBuffer at the end must still be done unconditionally or OpenGL will complain about an invalid input data types.

Don't use 0 as the default value for fields

fastgltf seems to use 0 as the default value for various fields - possibly because you're not setting an explicit default value. This has caused a bunch of issues we I'm trying to create glTF files. I'd like to request that fastgltf only use 0 as a default value when it's what the glTF spec says as the default, and use a different value when appropriate

Runtime performance for debug compilation with debugger attached

I'm curious if any measurement has been made with a debug build of the library.

Background; my personal number one use-case as a developer is starting programs with a debugger attached, all in debug build, when trying to find bugs or understand a program I am new to. Hence this performance metric is very valuable to me.

Exporting as glb with embedded buffer does not work for fastgltf::sources::ByteView

Seems to be caused by the sources::ByteView case missing the if statement present in sources::Array and sources::Vector:

fastgltf/src/fastgltf.cpp

Lines 4189 to 4211 in f8ed5a0

[&](const sources::Array& vector) {
if (bufferIdx == 0 && exportingBinary) {
bufferPaths.emplace_back(std::nullopt);
return;
}
auto path = getBufferFilePath(asset, bufferIdx);
json += std::string(R"("uri":")") + fg::escapeString(path.string()) + '"' + ',';
bufferPaths.emplace_back(path);
},
[&](const sources::Vector& vector) {
if (bufferIdx == 0 && exportingBinary) {
bufferPaths.emplace_back(std::nullopt);
return;
}
auto path = getBufferFilePath(asset, bufferIdx);
json += std::string(R"("uri":")") + fg::escapeString(path.string()) + '"' + ',';
bufferPaths.emplace_back(path);
},
[&](const sources::ByteView& view) {
auto path = getBufferFilePath(asset, bufferIdx);
json += std::string(R"("uri":")") + fg::escapeString(path.string()) + '"' + ',';
bufferPaths.emplace_back(path);
},

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.