Coder Social home page Coder Social logo

microsoft / gltf-sdk Goto Github PK

View Code? Open in Web Editor NEW
519.0 28.0 104.0 5.2 MB

glTF-SDK is a C++ Software Development Kit for glTF (GL Transmission Format -https://github.com/KhronosGroup/glTF).

License: MIT License

CMake 5.10% PowerShell 15.11% C++ 79.70% C 0.07% Shell 0.02%
gltf gltf2 gltf2-loader cpp cpp14 windows macos ios android cross-platform

gltf-sdk's Introduction

Build Status

Microsoft glTF SDK - A C++ Deserializer/Serializer for glTF

  • Windows/macOS/Android Compatible
  • glTF & glB support, including embedded Base64 support
  • Flexibility and ease of integration to any 3D engine
  • Strongly typed extension support
  • Built-in schema validation during deserialization
  • Low memory overhead
  • Utilities for converting input data of any type (e.g. float/uint8/uint16 RGB/RGBA color) into a single type such as float RGBA color

Nuget Packages

Trademarks

glTF is a trademark of The Khronos Group Inc.

Contributing

This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit https://cla.microsoft.com.

When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA.

This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact [email protected] with any additional questions or comments.

gltf-sdk's People

Contributors

agrittmsft avatar bartsiwek avatar blake-fisher avatar bschnurr avatar cedricguillemet avatar celoron avatar chriche-ms avatar donno avatar fergsatwork avatar kokuda avatar krzysztofdomanski avatar luncliff avatar luwyang avatar mebrunn avatar microsoft-github-policy-service[bot] avatar microsoftopensource avatar miibond avatar msftgits avatar niello avatar ocitrev avatar polygonalsun avatar sbtron avatar sergiorzmasson avatar zeux 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

gltf-sdk's Issues

Set child name (rootProperty)

Hello,

I am working on a project where setting/updating the name of the child name is important.
I am proposing adding a function to set the name as member of the glTFChildOfRootProperty struct.

Affected file: GLTFSDK/Inc/GLTFSDK/GLTF.h
304: struct glTFChildOfRootProperty : glTFProperty
305: {
306: std::string id;
307: std::string name;
...
320: + public:
321: + void setName ( std::string newName ) { name = newName; }
322: };

If you need more information, do not hesitate to contact me.

Thank you !

Christian

Missing cmake documentation

I'm trying to build a project that use some library like glm, QT, Vulkan etc.
Of course, I'm trying to use glTF-SDK too.
I'm struggling a lot because there is no documentation on how to use CMake with glTF-SDK
To be more specific CMake through the use of the FetchContent command can act as a package manager.
So I'm trying to use it in that way avoiding to use NuGet or vckpg
Can someone add an example on how to use this library from CMake in a proper way?

Add build instructions

Is this project still being supported? I may be missing something here, but master branch doesn't build on VS2022 under > C++14. I'm on Windows 10 21H1

Severity	Code	Description	Project	File	Line	Suppression State
Error	LNK1181	cannot open input file 'C:\Users\colli\source\repos\glTF\Built\Out\v143\x64\Debug\GLTFSDK\GLTFSDK.lib'	GLTFSDK.Test	C:\Users\colli\source\repos\glTF\GLTFSDK.Test\LINK	1	
Error	C2440	'<function-style-cast>': cannot convert from 'initializer list' to 'Microsoft::glTF::rapidjson::SchemaDocument'	GLTFSDK	C:\Users\colli\source\repos\glTF\GLTFSDK\Source\SchemaValidation.cpp	37	
Error	C1189	#error:  The <experimental/filesystem> header providing std::experimental::filesystem is deprecated by Microsoft and will be REMOVED. It is superseded by the C++17 <filesystem> header providing std::filesystem. You can define _SILENCE_EXPERIMENTAL_FILESYSTEM_DEPRECATION_WARNING to acknowledge that you have received this warning.	Serialize	C:\Program Files\Microsoft Visual Studio\2022\Preview\VC\Tools\MSVC\14.30.30528\include\experimental\filesystem	30	
Error	C1189	#error:  The <experimental/filesystem> header providing std::experimental::filesystem is deprecated by Microsoft and will be REMOVED. It is superseded by the C++17 <filesystem> header providing std::filesystem. You can define _SILENCE_EXPERIMENTAL_FILESYSTEM_DEPRECATION_WARNING to acknowledge that you have received this warning.	Deserialize	C:\Program Files\Microsoft Visual Studio\2022\Preview\VC\Tools\MSVC\14.30.30528\include\experimental\filesystem	30	

Are there build instructions for the SLN file? It appears this may require C++ 11 if it's still using the experimental headers?

Exceptions necessary ?

Are these exceptions necessary? They are always stopping the code. It works perfect without them

  1. \GLTFSDK\Source\BufferBuilder.cpp
if (desc.byteOffset % componentTypeSize != 0)     
{       
    throw InvalidGLTFException("asccessor offset within buffer view must be a multiple of the component size");  
 }


if ((desc.byteOffset + bufferView.byteOffset) % componentTypeSize != 0)
{
    throw InvalidGLTFException("accessor offset within buffer must be a multiple of the component size");
 }

desc is just a description of the accessor like this

{ Microsoft::glTF::TYPE_VEC3, Microsoft::glTF::COMPONENT_FLOAT, false, std::move(minValues), std::move(maxValues) }

why has to be divided by float size

size_t componentTypeSize = Microsoft::glTF::Accessor::GetComponentTypeSize(accessorDesc.componentType);
?

  1. \GLTFSDK\Source\ResourceWriter.cpp

    // From the glTF 2.0 spec: the offset of an accessor into a bufferView (accessor.byteOffset) must be a multiple of the size of the accessor's component type
    if (accessor.byteOffset % componentTypeSize)
    {
        throw InvalidGLTFException("accessor.byteOffset must be a multiple of the accessor's component type size");
    }


    // From the glTF 2.0 spec: the offset of an accessor into a buffer (accessor.byteOffset + bufferView.byteOffset) must be a multiple of the size of the accessor's component type
    if ((accessor.byteOffset + bufferView.byteOffset) % componentTypeSize)
    {
       throw InvalidGLTFException("accessor.byteOffset + bufferView.byteOffset must be a multiple of the accessor's component type size");
    }

???

Missing includes

There are several #include missing through out the project.

  • Math.cpp needs <tuple> for std::tie
  • GLTF.h needs <algorithm> for std::all_of
  • GLBResourceReader.cpp needs <string.h> for memcpy and strncmp.

Example code to get .glb binary into stream

Hi,

I have worked on the sample code and is able to get .glb file using the following lines:

glbResourceWriter->Flush(manifest, fileName);

Where fileName is path to the file, something like "c:\fileFile.glb"
How can I use C++ stream instead of file in order to get binary stream and then uuencode it, in order send via web ?
Seems that it should be something very simple, but I am struggling to find the solution.
Any hints are really appreciated....

More general reading / decoding of accessor data

I'm looking into refactoring glTF-SDK support for reading accessor data to make it more general wrt accessor value types.

Specifically, right now there's a fair amount of code dedicated to handling various forms of quantized data but all of this code is special-cased to handle individual cases covered by the spec. Like MeshPrimitiveUtils::GetTexCoords handling float, unsigned byte and unsigned short but not checking that the inputs are normalized, and not handling signed variants (which are not permitted by the spec atm so it's not a bug).

It feels like the code could be simpler if GLTFResourceReader provided smth like std::vector<float> DecodeBinaryData() that handled all format conversions and could be used in contexts where floating-point data is desired.

My ulterior motive is to use these helpers for decoding texture coordinate, position, normal and tangent data in MeshPrimitiveUtils - this would allow glTF SDK to work with quantized position/normal/tangent streams. This is currently outside of the set of types supported by specification but I'm hoping to make an extension that makes these types officially supported, and in the meantime this would allow files processed using gltfpack (http://github.com/zeux/meshoptimizer#gltfpack) to load using glTF-SDK (and, presumably by extension, using the 3D preview program in Win10).

Since the main goal here is to add support for files that are technically outside of the spec right now, I thought I'd ask first - is a PR that implement this likely to get merged? Does the implementation approach sound reasonable?

Update GenerateSchemaJsonHeader.ps1 to fix linker issues when including SchemaJson.h in multiple translation units

The generated header SchemaJson.h has some issues:

  1. Class SchemaJson should be a namespace
  2. Schema strings (e.g. accessor_schema_json) don't follow the correct naming convention, and should either be defined in a separate .cpp or made constexpr const char[] to avoid linker issues.
  3. Bracing style is not consistent with the rest of the codebase
  4. GLTF_SCHEMA_MAP should be defined in a separate .cpp file.
  5. Schema URIs shouldn't be hardcoded literals, instead move the relevant variables from Schema.h into the generated header.

CI is broken

At some point in the last two months or so, CI stopped working completely.

Support for base64 encoded buffers

Hello,

Currently, the buffers are referenced by URI (path to bin file)
I propose adding a function to set the URI as a base64 encoded string. The encoding itself could be done outside of the library.

As a work-around a base64 buffer can be set by using the URI variable with the appropriate length.
Update on GLTFSDK/Source/BufferBuilder.cpp to add setCurrentBufferURI function
280: + bool BufferBuilder::setCurrentBufferURI ( const std::string &data )
281: + {
282: + assert ( m_buffers.size() > 0 );
283: + size_t index = m_buffers.size() - 1;
284: + m_buffers [ index ].uri = data;
285: + m_buffers [ index ].length = data.length();
286: + return true;
287: + }
288: +

Please let me know if I should create a pull request.

Thank you !

Is it possible to write not interleaved buffers?

The BufferBuilder::AddAccessors API seems to rely on data being an interleaved buffer. I was wondering if it is possible to write also non-interleaved buffers with the same API or other APIs?
Something along these lines:

std::vector<float> vertices ={
        -1.0f, 1.0f, 0.0f, // pos0
         1.0f, 1.0f, 0.0f,  // pos1
        -1.0f, -1.0f, 0.0f, // pos2
         1.0f, -1.0f, 0.0f, // pos3
         0.0f, 0.0f, -1.0f, // norm0
         0.0f, 0.0f, -1.0f, // norm1
         0.0f, 0.0f, -1.0f,  // norm2
         0.0f, 0.0f, -1.0f, // norm3
};

const size_t componentSize = sizeof(decltype(vertices)::value_type);     // 4
const size_t stride = 3 * componentSize;                                 // 12
const size_t count = 4;                                                  // ?8

AccessorDesc descs[2] = 
{
          { TYPE_VEC3, COMPONENT_FLOAT, false, { -1.0f, -1.0f, 0.0f }, { 1.0f, 1.0f, 0.0f }, 0 },
          { TYPE_VEC3, COMPONENT_FLOAT, false, { 0.0f, 0.0f, -1.0f },{ 0.0f, 0.0f, -1.0f },  48},
 };

 bufferBuilder.AddBufferView(BufferViewTarget::ARRAY_BUFFER);
 bufferBuilder.AddAccessors(vertices.data(), count, stride, descs, ArrayCount(descs), nullptr);

This code doesn't seem to work. Setting count to 8 is not correct either as then the accessors count is wrong.
Thank you for your help!

Missing cmake usage documentation

I'm trying to build a project that use some library like glm, QT, Vulkan etc.
Of course, I'm trying to use glTF-SDK too.
I'm struggling a lot because there is no documentation on how to use CMake with glTF-SDK
To be more specific CMake through the use of the FetchContent command can act as a package manager.
So I'm trying to use it in that way avoid to use NuGet or vckpg
Can someone add an example on how to use this library from CMake in a proper way?

Direct access to buffers and accessors

Hello,

I am working on a project where direct access to buffers and accessors is needed.
I am proposing adding the following two functions.

Affected file: GLTFSDK/Inc/GLTFSDK/BufferBuilder.h
85: ResourceWriter& GetResourceWriter();
86: const ResourceWriter& GetResourceWriter() const;
87: +
88: + Buffer getBuffer ( size_t index ) {
89: + assert ( index < m_buffers.Size() );
90: + return m_buffers [ index ];
91: + }
92: +
93: + Accessor getAccessor ( size_t index ) {
94: + assert ( index < m_accessors.Size() );
95: + return m_accessors [ index ];
96: + }

Affected file: GLTFSDK/Inc/GLTFSDK/IndexedContainer.h
35: class IndexedContainer<const T, true>
36: {
37: public:
38: + const size_t size() const
39: + {
40: + return m_elements.size();
41: + }
42: +
...
206: public:
207: + size_t size()
208: + {
209: + return (IndexedContainer::size());
210: + }
211: +
...
271: // accessible (the mutable versions replace rather than complement them)
272: + using IndexedContainer::size;
273: using IndexedContainer::Front;

If you need more information, do not hesitate to contact me.

Thank you !

Christian

Accessor::Sparse needs various improvements

  1. Accessor.sparse member should be a unique_ptr instead of just Sparse so that a null value can be represented properly
  2. Accessor::Sparse should inherit from glTFProperty
  3. Accessor::Sparse.indices and Accessor::Sparse.values should inherit from glTFProperty

Currently any extensions or extras stored on these nodes will be lost upon import.

Example for retrieve buffer size of bin file via ostream* pointer

I am intented to get buffer size from ostream, after performing the method "GetBufferStream"

std::string bufferStr; for (auto ele : doc.bufferViews.Elements()) { // std::stringstream std::ostream* ostrem = glbResourceWriter->GetBufferStream(ele.id); (*ostrem) << bufferStr; bufferStr += bufferStr; } bin_out.append(bufferStr.data(), bufferStr.data() + bufferStr.length());

the issue is that value of bufferStr is awalys empty or null, therefore, it is impossible to calculate the buffer size and data from the bufferStr.

the screenshot of result:
image

it's appreciated if you can reply my question.

Deserialize raises GLTFException: Unknown Schema uri glTFProperty.schema.jso

I'm trying to package gltf-SDK 1.9.5.0 for conan (with minimal modifications like std::powf replaced by std::pow, unvendoring of rapidjson, fix of installation folders).

I've written a simple cpp file, based on the tests in SerializeTests.cpp to see that produced package makes sense:

#include <GLTFSDK/GLTF.h>
#include <GLTFSDK/Deserialize.h>
#include <GLTFSDK/Document.h>
#include <GLTFSDK/Math.h>
#include <GLTFSDK/Serialize.h>

#include <utility>

int main() {
  Microsoft::glTF::Document originalDoc;

  Microsoft::glTF::Scene sc;
  sc.id = "0";
  sc.nodes = { "0" };
  originalDoc.SetDefaultScene(std::move(sc));

  Microsoft::glTF::Node matrixNode;
  matrixNode.id = "0";
  matrixNode.name = "matrixNode";
  matrixNode.matrix = Microsoft::glTF::Matrix4::IDENTITY;
  originalDoc.nodes.Append(std::move(matrixNode));

  auto outputString = Microsoft::glTF::Serialize(originalDoc);
  auto twoPassDoc = Microsoft::glTF::Deserialize(outputString);
  return 0;
}

GLTFException: Unknown Schema uri glTFProperty.schema.jso (without the "n") is raided in Microsoft::glTF::Deserialize (tested on Windows with gcc 7 and 8, Visual Studio 2015/2017/2019, and on Macos with apple-clang 12).

Troubling compiling with ResourceReader

I'm having trouble compiling with two of the GLTF headers. I'm simply including them in the sample DX11 UWP project, I have added GLTF via nuget. Other GLTF headers do not throw any errors when compiling.

#include <GLTFSDK/GLTFResourceReader.h>
#include <GLTFSDK/GLBResourceReader.h>
1>------ Build started: Project: dx11, Configuration: Debug Win32 ------
1>Sample3DSceneRenderer.cpp
1>c:\users\chris\source\repos\dx11\packages\microsoft.gltf.cpp.1.6.3.1\build\native\include\gltfsdk\resourcereaderutils.h(98): warning C4003: not enough arguments for function-like macro invocation 'max'
1>c:\users\chris\source\repos\dx11\packages\microsoft.gltf.cpp.1.6.3.1\build\native\include\gltfsdk\resourcereaderutils.h(98): error C2589: '(': illegal token on right side of '::'
1>c:\users\chris\source\repos\dx11\packages\microsoft.gltf.cpp.1.6.3.1\build\native\include\gltfsdk\resourcereaderutils.h(98): error C2062: type 'unknown-type' unexpected
1>c:\users\chris\source\repos\dx11\packages\microsoft.gltf.cpp.1.6.3.1\build\native\include\gltfsdk\resourcereaderutils.h(98): error C2059: syntax error: ')'
1>c:\users\chris\source\repos\dx11\packages\microsoft.gltf.cpp.1.6.3.1\build\native\include\gltfsdk\resourcereaderutils.h(104): error C2065: 'decodeTable': undeclared identifier
1>c:\users\chris\source\repos\dx11\packages\microsoft.gltf.cpp.1.6.3.1\build\native\include\gltfsdk\resourcereaderutils.h(107): error C2065: 'decodeTable': undeclared identifier
1>c:\users\chris\source\repos\dx11\packages\microsoft.gltf.cpp.1.6.3.1\build\native\include\gltfsdk\resourcereaderutils.h(135): warning C4003: not enough arguments for function-like macro invocation 'max'
1>c:\users\chris\source\repos\dx11\packages\microsoft.gltf.cpp.1.6.3.1\build\native\include\gltfsdk\resourcereaderutils.h(135): error C2589: '(': illegal token on right side of '::'
1>c:\users\chris\source\repos\dx11\packages\microsoft.gltf.cpp.1.6.3.1\build\native\include\gltfsdk\resourcereaderutils.h(135): error C2062: type 'unknown-type' unexpected
1>c:\users\chris\source\repos\dx11\packages\microsoft.gltf.cpp.1.6.3.1\build\native\include\gltfsdk\resourcereaderutils.h(135): error C2059: syntax error: ')'
1>c:\users\chris\source\repos\dx11\packages\microsoft.gltf.cpp.1.6.3.1\build\native\include\gltfsdk\resourcereaderutils.h(136): error C2143: syntax error: missing ';' before '{'
1>c:\users\chris\source\repos\dx11\packages\microsoft.gltf.cpp.1.6.3.1\build\native\include\gltfsdk\streamcachelru.h(20): warning C4003: not enough arguments for function-like macro invocation 'max'
1>c:\users\chris\source\repos\dx11\packages\microsoft.gltf.cpp.1.6.3.1\build\native\include\gltfsdk\streamcachelru.h(20): error C2589: '(': illegal token on right side of '::'
1>c:\users\chris\source\repos\dx11\packages\microsoft.gltf.cpp.1.6.3.1\build\native\include\gltfsdk\streamcachelru.h(104): note: see reference to class template instantiation 'Microsoft::glTF::StreamCacheLRU<TStream>' being compiled
1>c:\users\chris\source\repos\dx11\packages\microsoft.gltf.cpp.1.6.3.1\build\native\include\gltfsdk\streamcachelru.h(20): error C2059: syntax error: ')'
1>Done building project "dx11.vcxproj" -- FAILED.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

gltf-sdk build failures with latest rapidjson on macOS

Hi Guys,

I'm a maintiner of vcpkg team, we noticed the following error in building ms-gltf on macOS with depending on latest rapidjson, it seems gltf-sdk use the old version of rapidjson? could you please help take a look? thank you! We found this issue when upgrade rapidjson to latest version.

Repro steps:

  1. git clone https://github.com/alexander-smyslov/vcpkg
  2. git checkout rapidjson01112021
  3. ./bootstrap-vcpkg.bat
  4. ./vcpkg install ms-glft

Failures:

/Users/vagrant/Data/buildtrees/ms-gltf/src/f2ebc72787-4b56b975bf.clean/GLTFSDK/Source/ExtensionsKHR.cpp:237:28: error: conversion from 'Microsoft::glTF::rapidjson::GenericValue<Microsoft::glTF::rapidjson::UTF8<>>::Object' (aka 'GenericObject<false, GenericValue<Microsoft::glTF::rapidjson::UTF8<>>>') to 'const rapidjson::Value' (aka 'const GenericValue<UTF8<>>') is ambiguous
    const rapidjson::Value sit = doc.GetObject();
                           ^     ~~~~~~~~~~~~~~~
/Users/vagrant/Data/installed/x64-osx/share/rapidjson/../../include/rapidjson/document.h:872:5: note: candidate constructor
    GenericValue(Object o) RAPIDJSON_NOEXCEPT : data_(o.value_.data_) {
    ^
/Users/vagrant/Data/installed/x64-osx/share/rapidjson/../../include/rapidjson/document.h:2956:5: note: candidate function
    operator ValueType&() const { return value_; }
    ^
/Users/vagrant/Data/buildtrees/ms-gltf/src/f2ebc72787-4b56b975bf.clean/GLTFSDK/Source/ExtensionsKHR.cpp:317:28: error: conversion from 'Microsoft::glTF::rapidjson::GenericValue<Microsoft::glTF::rapidjson::UTF8<>>::Object' (aka 'GenericObject<false, GenericValue<Microsoft::glTF::rapidjson::UTF8<>>>') to 'const rapidjson::Value' (aka 'const GenericValue<UTF8<>>') is ambiguous
    const rapidjson::Value objValue = doc.GetObject();
                           ^          ~~~~~~~~~~~~~~~
/Users/vagrant/Data/installed/x64-osx/share/rapidjson/../../include/rapidjson/document.h:872:5: note: candidate constructor
    GenericValue(Object o) RAPIDJSON_NOEXCEPT : data_(o.value_.data_) {
    ^
/Users/vagrant/Data/installed/x64-osx/share/rapidjson/../../include/rapidjson/document.h:2956:5: note: candidate function
    operator ValueType&() const { return value_; }
    ^

Error ALPHA_MASK and Windows.h

Hi,
If I using the library with Windows.h (here with MFC), I have an error with ALPHA_MASK in GLTF.h. Because ALPHA_MASK is already defined.

Compiler Error C2059 and more.
I have fixed the problem in my case by adding:

#undef ALPHA_MASK

        enum AlphaMode
        {
            ALPHA_UNKNOWN = 0,
            ALPHA_OPAQUE,
            ALPHA_BLEND,
            ALPHA_MASK
        };

Why not define in "enum class" instead? Or change the name?
Thanks!

Target webassembly

From a procgen perspective, ie generating assets within the browser, being able to compile gltf sdk as webassembly would be "huge".

KHR_Draco_Mesh_Compression Extension Support

Hello, I have created sample glb file using glTF-SDK but now i want to Use Draco Compression. I'm able to add "KHR_draco_mesh_compression" extension in glb file. But only issue is byteLength of .bin file is the same as compared to without using this extension. I've added following codes to use this Extension.

   //The Document instance represents the glTF JSON manifest
     Document document;
    document.extensionsRequired.insert("KHR_draco_mesh_compression");
    document.extensionsUsed.insert("KHR_draco_mesh_compression"); 

    //Create a Buffer - it will be the 'current' Buffer that all the BufferViews
    //created by this BufferBuilder will automatically reference 

    Buffer buffer;
    buffer = bufferBuilder.AddBuffer();
    bufferBuilder.AddBufferView(BufferViewTarget::ARRAY_BUFFER);

   std::string strIndicesId = bufferBuilder.AddAccessor(indices, { TYPE_SCALAR, COMPONENT_UNSIGNED_SHORT }).id;  // add the   indices

   //Create a BufferView with target ARRAY_BUFFER (as it will reference vertex attribute data)
       
   std::string strVertexId = bufferBuilder.AddAccessor(VertexData, { TYPE_VEC3, COMPONENT_FLOAT, false, std::move(minValues), std::move(maxValues) }).id;    // add Vertex positions
            
   std::string strNormalId= bufferBuilder.AddAccessor(NormalData, { TYPE_VEC3, COMPONENT_FLOAT, false }).id; // add normal 
        
    Microsoft::glTF::KHR::MeshPrimitives::DracoMeshCompression dRacoMeshCompression;
    dRacoMeshCompression.bufferViewId = "0";
    string strNormal = accessorIdNormal.at(nIndex);  //get the Normal Id 
    dRacoMeshCompression.attributes[ACCESSOR_NORMAL] = std::stoul(strNormal);

    string strPosition = accessorIdPosition.at(nIndex);  //get the Vertexl Id 
    dRacoMeshCompression.attributes[ACCESSOR_POSITION] = std::stoul(strPosition);

    const auto extensionSerializer = KHR::GetKHRExtensionSerializer();
    string strDracoMesh = SerializeDracoMeshCompression(dRacoMeshCompression, document, extensionSerializer);
     meshPrimitive.extensions["KHR_draco_mesh_compression"] = strDracoMesh;

The Following above code only write the extension in glb file but doesn't compress the length of Binary file.
How to write Vertex, Indices and Normal data using this extension. I also looked at source code of gltf-sdk but didn't find it.
Is there something I forget to add then mention it and feel free to ask. I'm new to this gltf.

Byte offset greater than byte length

I'm trying to read data from scene.bin file into memory. I am achieving this with this piece of code.

`

		if (bufferInfo.buffersAccessors.buffer.uri.length() > 0 || bufferInfo.buffersAccessors.buffer.byteLength > 0) {
		Microsoft::glTF::Buffer buffer = bufferInfo.buffersAccessors.buffer;
		
		path += bufferInfo.buffersAccessors.buffer.uri;
		path = std::filesystem::absolute(path);
		buffer.uri = path.string();

		std::shared_ptr<StreamReader> streamReader = std::make_shared<StreamReader>(path);
		Microsoft::glTF::GLTFResourceReader reader(streamReader);

		stream = reader.ReadBinaryData<T>(buffer, bufferInfo.buffersAccessors.view);
	}`

Then I simply do this.

`

	const size_t bufferDataOffset = mainPart.accessor.byteOffset + mainPart.view.byteOffset;

	bufferData.erase(bufferData.begin(), bufferData.begin() + bufferDataOffset);

	bufferInfo.bufferData = bufferData;`

When I'm trying to read attribute TEXCOORD_0 of MeshPrimitive from scene.bin file, I always get a situation where ByteOfsset is greater than ByteLength. This results in a crash at bufferData.erase(). What should I do in these situations? Is my offset calculation even correct?

Update glTF 1.0 Deserialize Unit Tests

The following test inputs are using the 1.0 spec!

c_negativeAccessorOffset
c_negativeAccessorCount
c_negativeBufferLength
c_negativeBufferViewOffset
c_negativeBufferViewLength
c_invalidAccessorComponentType

The tests need rewriting so that:

  1. The test input is written against the 2.0 spec
  2. The tests need an assert adding, one that checks that the throw exception's message matches the known schema violation in the input manifest.

Consider also adding at least one assert for the following tests or test inputs:

c_extraFieldsJson
SerializerGLTFTests_InvalidDefaultScene
c_validPrimitiveNoIndices
c_invalidPrimitiveAccessorComponentType
c_invalidPrimitiveAccessorType

Examples of Serializing existing mesh

Hi,
I checked your example of how to serialize 1 triangle. Do you have any documentation on how to create a gltf/glb mesh with more than 1 triangle and probably how to convert an existing mesh (I have mine in STL format) with facets and nodes correspondences.
Thanks!

KHR_mesh_quantization support

Now that #51 is merged I'd like to discuss how to add support for KHR_mesh_quantization (https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_mesh_quantization) to this SDK.

All of the code that could support reading quantized accessors is here, but we're missing good validation. Specifically:

  • When KHR_mesh_quantization is set, certain attribute types are now valid to use for mesh geometry inputs
  • When KHR_mesh_quantization is not set, I'd like to improve the current validation code to properly check normalized attribute.

My suggestion is as follows.

  1. Change the existing accessor validation to use tables of admissible component types, e.g.
struct GeometryAccessor
{
    bool quantized;
    ComponentType type;
    bool normalized;
};

std::vector<GeometryAccessor> kPositionAccessors =
{
    { false, COMPONENT_FLOAT, false },
    { true, COMPONENT_SHORT, true }, // etc.
};
  1. When loading the document, cache the presence of required KHR_mesh_quantization extension in the document field to alleviate concerns around string comparisons (alternatively we could look this up when reading accessor data)

  2. Instead of current ad-hoc code, use somewhat more generic code e.g. Validation::ValidateGeometryAccessor(accessor, kPositionAccessors, doc.RequiresMeshQuantization()));

As a result, files that don't require KHR_mesh_quantization will be validated using the existing validation rules (+ a normalized check); files that require KHR_mesh_quantization will be automatically de-quantized on load.

Thoughts/suggestions welcome.

Can it export quads into gltf ?

For the time being it works well for triangles, but not for quads as it considers them as triangles. Is there any option to denote that a mesh consists of quads ?

Best,
Dimitrios

Related code:


               accessorIdIndices = bufferBuilder.AddAccessor(indices, {Microsoft::glTF::TYPE_SCALAR, 
                                                                                                  Microsoft::glTF::COMPONENT_UNSIGNED_SHORT }).id;

               Microsoft::glTF::AccessorDesc accessorDesc = { Microsoft::glTF::TYPE_VEC3, Microsoft::glTF::COMPONENT_FLOAT, false, std::move(minValues), std::move(maxValues) };

                accessorIdPositions = bufferBuilder.AddAccessor(coordinates, accessorDesc).id;

                Microsoft::glTF::MeshPrimitive meshPrimitive;
                meshPrimitive.materialId = materialId;
                meshPrimitive.indicesAccessorId = accessorIdIndices;
                meshPrimitive.attributes[Microsoft::glTF::ACCESSOR_POSITION] = accessorIdPositions;

                Microsoft::glTF::Mesh mesh;
                mesh.primitives.push_back(std::move(meshPrimitive));
                mesh.name = part->GetLabel();

                auto meshId = document.meshes.Append(std::move(mesh),
                                                     Microsoft::glTF::AppendIdPolicy::GenerateOnEmpty).id;

                Microsoft::glTF::Node node;
                node.meshId = meshId;
                node.name = part->GetLabel();

                auto nodeId = document.nodes.Append(std::move(node),
                                                    Microsoft::glTF::AppendIdPolicy::GenerateOnEmpty).id;

How to export data as ascii text in GLTF?

Hi,

  1. is there an option to export buffer arrays of coordinates and indices as text instead of binary?

  2. Are there any limitations in the size of meshes? For some meshes, the indices are getting scrambled. Especially for big Meshes.

Best,
Dimitrios

Validation fails when using Draco with no fallback

When using Draco compression as a required extension, the validator complains that my accessors for the uncompressed data are invalid because they don't have bufferViews.

throw ValidationException("Non-Sparse Accessor " + accessor.id + ": does not have a bufferView");

However, according to the Draco extension spec, they should not have bufferViews defined.

draco_test.zip

cmake documentation, install for iOS app

Hi,

I am missing any documentation how to compile to static/dynamic lib to use inside iOS app.

I have tried to compile in the usual way, e.g.:

git clone https://github.com/microsoft/glTF-SDK.git
cd glTF-SDK/Build/
cmake ..
cmake --build . --target install

It worked, but install was done in: glTF-SDK/Built/Out/macOS/RelWithDebInfo/GLTFSDK/libGLTFSDK.a

How can I configure cmake to install it into /usr/local/include/ in order to use later in Xcode inside iPhone app ?

Using Webp with glb File

How to use webp in glb. I don't understand properly from here.
https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/EXT_texture_webp#ext_texture_webp

"textures": [
    {
        "extensions": {
            "EXT_texture_webp": {
                "source": 1
            }
        }
    }
]

I have already created a simple .glb file with png images but now want to use .webp instead of .png.
and also don't know how to add EXT_texture_webp extension using this SDK.
Anyone Explain How to do it .
I appreciate your help very much!

GLB 3D model fails to import correctly

There appears to be an issue with the glb import of an octopus 3d model from sketchfab.com.

Please download the GLB 3d model from here: https://skfb.ly/opvx9 (This is a short link for the octopus 3d model on sketchfab.com https://sketchfab.com/3d-models/octopus-14a73529b33d48d9990d030896c67028)

The 3d model imports correctly in Blender and the online GTLF viewer: https://github.khronos.org/glTF-Sample-Viewer-Release/

In the Microsoft GLTF library, use the GLBResourceReader to import the 3d model.

I'm unsure if there is an issue in the json returned from GLBResourceReader::GetJson()

Specifically, search for the part that starts Bone001|Unreal Take|...

"name": "Bone001|Unreal Take|Base Layer Retarget",
            "samplers": [
                {
                    "input": 7,
                    "interpolation": "LINEAR",
                    "output": 8
                },
                {
                    "input": 7,
                    "interpolation": "LINEAR",
                    "output": 9
                },

All inputs refer to 7. However, the json file retrieved from the octopus 3d model in GLTF format has incremental values for the input of each sampler.

Not sure if this is the reason for the failed animation. The static 3d model imports correctly.

Using the GLTFResourceReader the 3d model of the octopus animates in exactly the same way as shown in the sketchfab.com site.

Please let me know if you can see an issue in the GLTF library or the GLB 3d model.

Code samples request

Good day,
Are there any code samples/documentation available, how to work with SDK? For example, how to create a glTF::Document with mesh.

Write primitive with more than 65535 vertices

When I set the accessor component type to COMPONENT_UNSIGNED_INT I get an error when serializing:

ComponentType indexType = (verts.size() / 3) <= USHRT_MAX ? COMPONENT_UNSIGNED_SHORT : COMPONENT_UNSIGNED_INT;
string trisId = bufferBuilder.AddAccessor(tris, { TYPE_SCALAR, indexType }).id; // error on this line

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.