ReFuel.Gltf/ReFuel.Gltf/GltfCollection.cs
2025-10-12 14:33:16 +03:00

135 lines
4.8 KiB
C#
Executable File

using System;
using System.Collections.Generic;
using System.Text.Json;
namespace ReFuel.Gltf
{
/// <summary>
/// An empty object for storing glTF extra and extension properties.
/// </summary>
public class GltfCollection : Dictionary<string, object?>
{
private bool extensionMode;
public GltfCollection(bool extensionMode = false)
{
this.extensionMode = extensionMode;
}
public void Parse(JsonElement collection)
{
if (collection.ValueKind != JsonValueKind.Object)
throw new Exception("Expected a JSON object.");
foreach (JsonProperty property in collection.EnumerateObject())
{
if (extensionMode && GltfDocument.TryGetExtensionProvider(property.Name, out IGltfExtensionProvider? provider))
{
Add(property.Name, provider.ParseExtensionObject(property.Value));
continue;
}
switch (property.Value.ValueKind)
{
case JsonValueKind.Array:
GltfList list = new GltfList();
list.Parse(property.Value);
Add(property.Name, list);
break;
case JsonValueKind.False:
Add(property.Name, false);
break;
case JsonValueKind.Null:
Add(property.Name, null);
break;
case JsonValueKind.Number:
// How do we decide if the thing we want is an integer or a fp value?
// Integer compare them...
property.Value.TryGetDouble(out double d);
property.Value.TryGetInt64(out long l);
if (l == (long)d)
{
Add(property.Name, l);
}
else
{
Add(property.Name, d);
}
break;
case JsonValueKind.Object:
GltfCollection child = new GltfCollection(extensionMode);
child.Parse(property.Value);
Add(property.Name, child);
break;
case JsonValueKind.True:
Add(property.Name, true);
break;
case JsonValueKind.String:
Add(property.Name, property.Value.GetString());
break;
case JsonValueKind.Undefined: break;
}
}
throw new NotImplementedException();
}
}
public class GltfList : List<object?>
{
public GltfList()
{
}
public void Parse(JsonElement collection)
{
if (collection.ValueKind != JsonValueKind.Array)
throw new Exception("Expected a JSON array.");
foreach (JsonElement element in collection.EnumerateArray())
{
switch (element.ValueKind)
{
case JsonValueKind.Array:
GltfList list = new GltfList();
list.Parse(element);
Add(list);
break;
case JsonValueKind.False:
Add(false);
break;
case JsonValueKind.Null:
Add(null);
break;
case JsonValueKind.Number:
// How do we decide if the thing we want is an integer or a fp value?
// Integer compare them...
element.TryGetDouble(out double d);
element.TryGetInt64(out long l);
if (l == (long)d)
{
Add(l);
}
else
{
Add(d);
}
break;
case JsonValueKind.Object:
GltfCollection child = new GltfCollection(false);
child.Parse(element);
Add(child);
break;
case JsonValueKind.True:
Add(true);
break;
case JsonValueKind.String:
Add(element.GetString());
break;
case JsonValueKind.Undefined: break;
}
}
}
}
}