Skip to content

armgit / Filee

Public Imported from GitHub
0

Free, open-source file converter. Convert 263 formats offline by drag & drop — images, PDF, Word, Excel, PowerPoint, HWP/HWPX, video, audio, e-books and archives. No upload, no Office needed.

glTF buffers and pictures stay beside the model too

KnifeLemon871136246eec
diff --git a/docs/ENGINES.md b/docs/ENGINES.md
index f2d7d6a3..dd352fd3 100644
--- a/docs/ENGINES.md
+++ b/docs/ENGINES.md
@@ -876,6 +876,11 @@ textures; and every format drops what Filee's model has no place for: animations
lights, metallic / roughness / normal / emissive maps, and lines and points. Draco- and meshopt-compressed glTF fail with
a clear message, as do damaged files ("cut short", an index that does not exist, no triangles).
+**Files a model refers to** (OBJ's `.mtl` and textures, glTF's separate buffers and pictures, PLY's `TextureFile`,
+FBX's texture names) are read only from the model's folder or a folder below it. A path that climbs out (`../`) or
+points anywhere else is looked up by its name in the model's folder instead, so a downloaded model cannot pull a
+picture from elsewhere on the disk into its output.
+
**3D → pictures**: a small software rasteriser (`MeshRenderer`) draws an isometric view from the front right, above,
with one light and flat shading per triangle, vertex colours or the texture interpolated across it, and a z-buffer,
at 2048 px and scaled down to 1024 px for smooth edges, on a transparent background. The preset's image options
diff --git a/src/Filee.Engines/Models3D/GltfFormat.cs b/src/Filee.Engines/Models3D/GltfFormat.cs
index d9db5624..42cd040a 100644
--- a/src/Filee.Engines/Models3D/GltfFormat.cs
+++ b/src/Filee.Engines/Models3D/GltfFormat.cs
@@ -23,7 +23,14 @@ internal static class GltfFormat
ModelRoot root;
try
{
- root = ModelRoot.Load(path, new ReadSettings { Validation = ValidationMode.Skip });
+ // Separate buffers and pictures are read only from the model's folder (ObjFormat.Resolve), never from a
+ // path the file names elsewhere on the disk.
+ var directory = Path.GetDirectoryName(Path.GetFullPath(path))!;
+ var context = ReadContext.Create(name => File.ReadAllBytes(
+ ObjFormat.Resolve(directory, name) ?? throw new FileNotFoundException($"{name} is not in the model's folder.", name)));
+ context.Validation = ValidationMode.Skip;
+ using var stream = File.OpenRead(path);
+ root = context.ReadSchema2(stream);
}
catch (FileNotFoundException ex)
{
diff --git a/src/Filee.Engines/Models3D/ObjFormat.cs b/src/Filee.Engines/Models3D/ObjFormat.cs
index 8a051a6a..f544a767 100644
--- a/src/Filee.Engines/Models3D/ObjFormat.cs
+++ b/src/Filee.Engines/Models3D/ObjFormat.cs
@@ -187,7 +187,11 @@ internal static class ObjFormat
return text.Split([' ', '\t'], StringSplitOptions.RemoveEmptyEntries).Select(n => Resolve(directory, n)).OfType<string>();
}
- /// <summary>Finds a file referenced from a 3D model inside <paramref name="directory"/>, else by name only.</summary>
+ /// <summary>
+ /// Finds a file referenced from a 3D model (an .mtl, a texture, a glTF buffer) inside <paramref name="directory"/>
+ /// or a folder below it, else by name only in <paramref name="directory"/>. A path that climbs out or points
+ /// elsewhere is never opened: a downloaded model must not pull a picture from anywhere on the disk into its output.
+ /// </summary>
internal static string? Resolve(string directory, string reference)
{
reference = reference.Trim().Trim('"').Replace('\\', '/');
@@ -195,7 +199,9 @@ internal static class ObjFormat
return null;
try
{
- var root = Path.TrimEndingDirectorySeparator(Path.GetFullPath(directory)) + Path.DirectorySeparatorChar;
+ var root = Path.GetFullPath(directory);
+ if (!Path.EndsInDirectorySeparator(root))
+ root += Path.DirectorySeparatorChar; // a drive or "/" already ends in one
var comparison = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;
var candidate = Path.GetFullPath(Path.Combine(root, reference));
if (candidate.StartsWith(root, comparison) && File.Exists(candidate))
diff --git a/tests/Filee.Engines.Tests/ModelTests.cs b/tests/Filee.Engines.Tests/ModelTests.cs
index 164e2564..9b5ce4b6 100644
--- a/tests/Filee.Engines.Tests/ModelTests.cs
+++ b/tests/Filee.Engines.Tests/ModelTests.cs
@@ -233,23 +233,8 @@ public class ModelTests(EngineFixture fx) : IClassFixture<EngineFixture>
public async Task Gltf_with_a_separate_buffer_and_texture_is_read()
{
var folder = fx.NewFolder();
- var root = ModelRoot.CreateModel();
- var material = root.CreateMaterial("Painted");
- material.InitializePBRMetallicRoughness();
- material.FindChannel("BaseColor")!.Value.SetTexture(0, root.UseImage(new SharpGLTF.Memory.MemoryImage(ModelBuilders.Checker())), null,
- TextureWrapMode.REPEAT, TextureWrapMode.REPEAT, TextureMipMapFilter.DEFAULT, TextureInterpolationFilter.DEFAULT);
- var mesh = root.CreateMesh("Quad");
- var primitive = mesh.CreatePrimitive();
- primitive.SetVertexAccessor("POSITION", Accessor(root, [new Vector3(0, 0, 0), new Vector3(1, 0, 0), new Vector3(1, 1, 0), new Vector3(0, 1, 0)]));
- primitive.SetVertexAccessor("TEXCOORD_0", Accessor(root, [new Vector2(0, 1), new Vector2(1, 1), new Vector2(1, 0), new Vector2(0, 0)]));
- var indices = root.CreateAccessor();
- indices.SetIndexData(root.UseBufferView(new byte[] { 0, 0, 1, 0, 2, 0, 0, 0, 2, 0, 3, 0 }, 0, null, 0, BufferMode.ELEMENT_ARRAY_BUFFER), 0, 6, IndexEncodingType.UNSIGNED_SHORT);
- primitive.SetIndexAccessor(indices);
- primitive.Material = material;
// The node scales by 2 and moves up by 1 m: both end up in the vertices.
- var node = root.UseScene("Scene").CreateNode("Quad");
- node.Mesh = mesh;
- node.LocalMatrix = Matrix4x4.CreateScale(2) * Matrix4x4.CreateTranslation(0, 1, 0);
+ var root = TexturedQuad(Matrix4x4.CreateScale(2) * Matrix4x4.CreateTranslation(0, 1, 0));
var gltf = Path.Combine(folder, "quad.gltf");
root.SaveGLTF(gltf, new WriteSettings { ImageWriting = ResourceWriteMode.SatelliteFile });
Assert.NotEmpty(Directory.GetFiles(folder, "*.bin"));
@@ -266,6 +251,59 @@ public class ModelTests(EngineFixture fx) : IClassFixture<EngineFixture>
Assert.Equal(3, objJob.Outputs.Count()); // .obj, .mtl and the texture
}
+ [Fact]
+ public void Gltf_buffers_and_pictures_stay_beside_the_model()
+ {
+ var folder = fx.NewFolder();
+ var source = Directory.CreateDirectory(Path.Combine(folder, "source")).FullName;
+ var outside = Directory.CreateDirectory(Path.Combine(folder, "outside")).FullName;
+ Directory.CreateDirectory(Path.Combine(source, "textures"));
+ var gltf = Path.Combine(source, "quad.gltf");
+ TexturedQuad(Matrix4x4.Identity).SaveGLTF(gltf, new WriteSettings { ImageWriting = ResourceWriteMode.SatelliteFile });
+ var picture = Path.GetFileName(Directory.GetFiles(source, "*.png").Single());
+ var buffer = Path.GetFileName(Directory.GetFiles(source, "*.bin").Single());
+ var json = File.ReadAllText(gltf);
+ Model3D Load(string from, string to)
+ {
+ File.WriteAllText(gltf, json.Replace($"\"{from}\"", $"\"{to}\"", StringComparison.Ordinal));
+ return ModelBuilders.Load(gltf, "gltf");
+ }
+
+ // A folder below the model's is fine.
+ File.Move(Path.Combine(source, picture), Path.Combine(source, "textures", picture));
+ var model = Load(picture, "textures/" + picture);
+ Assert.Equal(ModelBuilders.Checker(), model.MaterialOf(model.Parts.Single())!.BaseColorTexture!.Data);
+
+ // A picture up and out of it, or a buffer at an absolute path, is never opened.
+ File.Move(Path.Combine(source, "textures", picture), Path.Combine(outside, picture));
+ Assert.Contains(picture, Assert.Throws<InvalidDataException>(() => Load(picture, "../outside/" + picture)).Message);
+ File.Move(Path.Combine(outside, picture), Path.Combine(source, picture));
+ File.Move(Path.Combine(source, buffer), Path.Combine(outside, buffer));
+ Assert.Throws<InvalidDataException>(() => Load(buffer, new Uri(Path.Combine(outside, buffer)).AbsoluteUri));
+ Assert.Throws<InvalidDataException>(() => Load(buffer, Path.Combine(outside, buffer).Replace('\\', '/')));
+ }
+
+ private static ModelRoot TexturedQuad(Matrix4x4 transform)
+ {
+ var root = ModelRoot.CreateModel();
+ var material = root.CreateMaterial("Painted");
+ material.InitializePBRMetallicRoughness();
+ material.FindChannel("BaseColor")!.Value.SetTexture(0, root.UseImage(new SharpGLTF.Memory.MemoryImage(ModelBuilders.Checker())), null,
+ TextureWrapMode.REPEAT, TextureWrapMode.REPEAT, TextureMipMapFilter.DEFAULT, TextureInterpolationFilter.DEFAULT);
+ var mesh = root.CreateMesh("Quad");
+ var primitive = mesh.CreatePrimitive();
+ primitive.SetVertexAccessor("POSITION", Accessor(root, [new Vector3(0, 0, 0), new Vector3(1, 0, 0), new Vector3(1, 1, 0), new Vector3(0, 1, 0)]));
+ primitive.SetVertexAccessor("TEXCOORD_0", Accessor(root, [new Vector2(0, 1), new Vector2(1, 1), new Vector2(1, 0), new Vector2(0, 0)]));
+ var indices = root.CreateAccessor();
+ indices.SetIndexData(root.UseBufferView(new byte[] { 0, 0, 1, 0, 2, 0, 0, 0, 2, 0, 3, 0 }, 0, null, 0, BufferMode.ELEMENT_ARRAY_BUFFER), 0, 6, IndexEncodingType.UNSIGNED_SHORT);
+ primitive.SetIndexAccessor(indices);
+ primitive.Material = material;
+ var node = root.UseScene("Scene").CreateNode("Quad");
+ node.Mesh = mesh;
+ node.LocalMatrix = transform;
+ return root;
+ }
+
private static Accessor Accessor<T>(ModelRoot root, T[] values) where T : unmanaged
{
var view = root.UseBufferView(System.Runtime.InteropServices.MemoryMarshal.AsBytes(values.AsSpan()).ToArray(), 0, null, 0, BufferMode.ARRAY_BUFFER);