KhronosGroup / glTF-CSharp-Loader

C# Reference Loader for glTF
Other
213 stars 60 forks source link

LoadBinaryBuffer is not taking bufferView.byteOffset into account #29

Closed rickomax closed 3 years ago

rickomax commented 4 years ago

When loading embedded data, the entire buffer is returned by the LoadBinaryBuffer method without taking into account the bufferView.byteOffset.

Changing the code to:

public static byte[] LoadBinaryBuffer(this Gltf model, int bufferIndex, Func<string, byte[]> externalReferenceSolver, int bufferViewByteOffset = 0)
        {
            var buffer = model.Buffers[bufferIndex];

            var bufferData = LoadBinaryBufferUnchecked(buffer, externalReferenceSolver);

            // As per https://github.com/KhronosGroup/glTF/issues/1026
            // Due to buffer padding, buffer length can be equal or larger than expected length by only 3 bytes
            if (bufferData.Length < buffer.ByteLength || (bufferData.Length - buffer.ByteLength) > 3)
            {
                throw new InvalidDataException($"The buffer length is {bufferData.Length}, expected {buffer.ByteLength}");
            }

            if (bufferViewByteOffset > 0)
            {
                var newBufferData = new byte[bufferData.Length - bufferViewByteOffset];
                for (var i = 0; i < newBufferData.Length; i++)
                {
                    newBufferData[i] = bufferData[bufferViewByteOffset + i];
                }
                bufferData = newBufferData;
            }

            return bufferData;
        }

Fixes it.

bghgary commented 4 years ago

Would you mind creating a PR with the fix?

rickomax commented 4 years ago

Would you mind creating a PR with the fix?

Will do!

rickomax commented 3 years ago

PR is open: https://github.com/KhronosGroup/glTF-CSharp-Loader/pull/31

rickomax commented 3 years ago

Issue was caused by a custom method I was using, not on the original code.