Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions Obj2Gltf/Ktx2/Ktx2Encoder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,7 @@ public static void Encode(string inputImagePath, string outputKtx2Path, bool srg
try
{
using var image = Image.Load<Rgba32>(inputImagePath);
AlignToBlocks(image);
var width = image.Width;
var height = image.Height;
var hasAlpha = HasAlpha(image);
Expand Down Expand Up @@ -350,6 +351,34 @@ public static void Encode(string inputImagePath, string outputKtx2Path, bool srg
}
}

/// <summary>
/// The size nearest to <paramref name="size"/> that is a whole number of 4x4 blocks (at least one).
/// </summary>
private static int BlockAlignedSize(int size) => Math.Max(BlockSize, (size + BlockSize / 2) / BlockSize * BlockSize);

private const int BlockSize = 4;

// KHR_texture_basisu requires the width and height of a KTX2 image to be multiples of 4: the GPU formats
// Basis Universal transcodes to (BC1-7, ETC, ASTC) are made of 4x4 blocks, and WebGL refuses a BC (S3TC)
// texture whose size is not a multiple of 4 (INVALID_OPERATION), so viewers show it black. An image of
// another size is stretched to the nearest aligned size: the texture coordinates are fractions of the
// image, so they still address the same texels (padding would move them). Every mip level of an aligned
// image is then valid too, as WebGL checks the level's size shifted back to level 0.
private static void AlignToBlocks(Image<Rgba32> image)
{
var width = BlockAlignedSize(image.Width);
var height = BlockAlignedSize(image.Height);
if (width == image.Width && height == image.Height)
return;

image.Mutate(ctx => ctx.Resize(new ResizeOptions
{
Size = new Size(width, height),
Sampler = KnownResamplers.Lanczos3,
Mode = ResizeMode.Stretch
}));
}

// Encode one tiny texture to force libktx's lazy, non-thread-safe Basis encoder init to run
// once on this (serialized) code path before any concurrent encoding begins.
private static void WarmUp(GltfConverterOptions options)
Expand Down
178 changes: 178 additions & 0 deletions Obj2Tiles.Library.Test/ModelPartsLoadingTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,178 @@
using System;
using System.IO;
using System.Linq;
using NUnit.Framework;
using Obj2Tiles.Library.Geometry;
using Obj2Tiles.Library.Materials;
using Shouldly;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
using Path = System.IO.Path;

namespace Obj2Tiles.Library.Test;

/// <summary>
/// MeshUtils.LoadMesh (the reader of the split stage, so of the finest level) on models whose parts differ:
/// parts with and without texture coordinates, material names with spaces, faces before the first usemtl,
/// vertex colours on some objects only. Every face must reach the mesh with the material it was written with.
/// </summary>
public class ModelPartsLoadingTests
{
private const string TestOutputPath = "TestOutput";

private static string Folder(string testName)
{
var folder = Path.Combine(TestOutputPath, nameof(ModelPartsLoadingTests), testName);
if (Directory.Exists(folder))
Directory.Delete(folder, true);
Directory.CreateDirectory(folder);
return folder;
}

// Writes model.obj (and model.mtl and a 16x16 tex.png when mtl is given) and returns the OBJ path.
private static string Write(string testName, string obj, string? mtl = null)
{
var folder = Folder(testName);
File.WriteAllText(Path.Combine(folder, "model.obj"), obj);

if (mtl != null)
{
File.WriteAllText(Path.Combine(folder, "model.mtl"), mtl);
using var texture = new Image<Rgba32>(16, 16, new Rgba32(200, 30, 30, 255));
texture.SaveAsPng(Path.Combine(folder, "tex.png"));
}

return Path.Combine(folder, "model.obj");
}

// Two unit squares (two triangles each): the first textured with "textured", the second without
// texture coordinates, with the material given. No texture coordinate of the textured square is (0, 0),
// the one given to the faces without, so that theirs cannot be mistaken for one of the textured square.
private static string TexturedAndPlain(string plainMaterialStatement) =>
"mtllib model.mtl\n" +
"v 0 0 0\nv 1 0 0\nv 1 1 0\nv 0 1 0\n" +
"vt 0.1 0.1\nvt 0.9 0.1\nvt 0.9 0.9\nvt 0.1 0.9\n" +
"v 5 0 0\nv 6 0 0\nv 6 1 0\nv 5 1 0\n" +
"usemtl textured\nf 1/1 2/2 3/3\nf 1/1 3/3 4/4\n" +
plainMaterialStatement +
"f 5 6 7\nf 5 7 8\n";

private const string TexturedAndPlainMtl =
"newmtl textured\nKd 1 1 1\nmap_Kd tex.png\n\nnewmtl Paint 1 Carmine\nKd 0.6 0.05 0.1\n";

private static string[] MaterialOfEachFace(MeshT mesh) =>
mesh.Faces.Select(f => mesh.Materials[f.MaterialIndex].Name).ToArray();

[Test]
public void LoadMesh_FacesWithoutTextureCoordinates_InATexturedModel_AreKeptWithTheirMaterial()
{
var path = Write(nameof(LoadMesh_FacesWithoutTextureCoordinates_InATexturedModel_AreKeptWithTheirMaterial),
TexturedAndPlain("usemtl Paint 1 Carmine\n"), TexturedAndPlainMtl);

var mesh = MeshUtils.LoadMesh(path).ShouldBeOfType<MeshT>();

mesh.FacesCount.ShouldBe(4);
MaterialOfEachFace(mesh).ShouldBe(new[] { "textured", "textured", "Paint 1 Carmine", "Paint 1 Carmine" },
ignoreOrder: true);
mesh.Faces.ShouldAllBe(f => f.TextureIndexA < mesh.TextureVertices.Count &&
f.TextureIndexB < mesh.TextureVertices.Count &&
f.TextureIndexC < mesh.TextureVertices.Count);
}

[Test]
public void LoadMesh_MaterialNameWithSpaces_IsOneName()
{
var path = Write(nameof(LoadMesh_MaterialNameWithSpaces_IsOneName),
"mtllib model.mtl\n" +
"v 0 0 0\nv 1 0 0\nv 1 1 0\nv 0 1 0\nvt 0 0\nvt 1 0\nvt 1 1\nvt 0 1\n" +
"usemtl textured\nf 1/1 2/2 3/3\nusemtl Paint 1 Carmine \nf 1/1 3/3 4/4\n",
TexturedAndPlainMtl);

var mesh = MeshUtils.LoadMesh(path).ShouldBeOfType<MeshT>();

MaterialOfEachFace(mesh).ShouldBe(new[] { "textured", "Paint 1 Carmine" });
}

private const string TwoSquares =
"mtllib model.mtl\n" +
"v 0 0 0\nv 1 0 0\nv 1 1 0\nv 0 1 0\n" +
"vt 0 0\nvt 1 0\nvt 1 1\nvt 0 1\n" +
"v 5 0 0\nv 6 0 0\nv 6 1 0\nv 5 1 0\n";

[TestCase("f 1/1 2/2 3/3\nf 1/1 3/3 4/4\n", TestName = "LoadMesh_TexturedFacesBeforeTheFirstUsemtl_GetTheDefaultMaterial")]
[TestCase("f 1 2 3\nf 1 3 4\n", TestName = "LoadMesh_UntexturedFacesBeforeTheFirstUsemtl_GetTheDefaultMaterial")]
public void LoadMesh_FacesBeforeTheFirstUsemtl_GetTheDefaultMaterial(string facesWithoutMaterial)
{
var path = Write(TestContext.CurrentContext.Test.Name,
TwoSquares + facesWithoutMaterial + "usemtl textured\nf 5/1 6/2 7/3\nf 5/1 7/3 8/4\n",
TexturedAndPlainMtl);

var mesh = MeshUtils.LoadMesh(path).ShouldBeOfType<MeshT>();

MaterialOfEachFace(mesh).ShouldBe(new[]
{ MeshUtils.DefaultMaterialName, MeshUtils.DefaultMaterialName, "textured", "textured" },
ignoreOrder: true);
mesh.Materials.Single(m => m.Name == MeshUtils.DefaultMaterialName).Texture.ShouldBeNull();
}

[Test]
public void LoadMesh_TextureCoordinatesWithoutMaterials_IsAnUntexturedMeshWithEveryFace()
{
// As Blender writes objects without material when only the last one has UVs.
var path = Write(nameof(LoadMesh_TextureCoordinatesWithoutMaterials_IsAnUntexturedMeshWithEveryFace),
"v 0 0 0\nv 1 0 0\nv 1 1 0\nf 1 2 3\n" +
"v 5 0 0\nv 6 0 0\nv 6 1 0\nvt 0 0\nvt 1 0\nvt 1 1\nf 4/1 5/2 6/3\n");

var mesh = MeshUtils.LoadMesh(path).ShouldBeOfType<Mesh>();

mesh.FacesCount.ShouldBe(2);
mesh.Faces.ShouldAllBe(f => f.GetType() == typeof(Face));
}

[Test]
public void LoadMesh_SomeVerticesWithoutColours_AreWhite()
{
var path = Write(nameof(LoadMesh_SomeVerticesWithoutColours_AreWhite),
"v 0 0 0\nv 1 0 0\nv 1 1 0\n" +
"v 5 0 0 1 0 0\nv 6 0 0 0 1 0\nv 6 1 0 0 0 1\n" +
"v 9 0 0\n" +
"f 1 2 3\nf 4 5 6\nf 4 6 7\n");

var mesh = MeshUtils.LoadMesh(path).ShouldBeOfType<Mesh>();

mesh.VertexColors.ShouldNotBeNull();
mesh.VertexColors!.Select(c => (c.R, c.G, c.B)).ShouldBe(new[]
{
(1d, 1d, 1d), (1d, 1d, 1d), (1d, 1d, 1d),
(1d, 0d, 0d), (0d, 1d, 0d), (0d, 0d, 1d),
(1d, 1d, 1d)
});
}

[TestCase(TexturesStrategy.Repack)]
[TestCase(TexturesStrategy.RepackCompressed)]
[TestCase(TexturesStrategy.KeepOriginal)]
public void WriteObj_TexturedModelWithAnUntexturedPart_KeepsEveryFaceAndValidTextureCoordinates(
TexturesStrategy strategy)
{
var testName = nameof(WriteObj_TexturedModelWithAnUntexturedPart_KeepsEveryFaceAndValidTextureCoordinates) +
strategy;
var path = Write(testName, TexturedAndPlain("usemtl Paint 1 Carmine\n"), TexturedAndPlainMtl);
var mesh = MeshUtils.LoadMesh(path).ShouldBeOfType<MeshT>();
mesh.TexturesStrategy = strategy;

var output = Path.Combine(Path.GetDirectoryName(path)!, "out", "Mesh.obj");
Directory.CreateDirectory(Path.GetDirectoryName(output)!);
mesh.WriteObj(output);

var written = File.ReadAllLines(output);
var textureVertices = written.Count(l => l.StartsWith("vt "));
foreach (var face in written.Where(l => l.StartsWith("f ")))
foreach (var corner in face.Split(' ').Skip(1))
int.Parse(corner.Split('/')[1]).ShouldBeInRange(1, textureVertices, face);

var reloaded = MeshUtils.LoadMesh(output).ShouldBeOfType<MeshT>();
MaterialOfEachFace(reloaded).ShouldBe(new[] { "textured", "textured", "Paint 1 Carmine", "Paint 1 Carmine" },
ignoreOrder: true);
}
}
3 changes: 2 additions & 1 deletion Obj2Tiles.Library.Test/ObjParsingTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -258,7 +258,8 @@ public void LoadMesh_LeadingWhitespaceOnAllKeywords_ParsesCorrectly()

var mesh = MeshUtils.LoadMesh(obj);

mesh.ShouldBeOfType<MeshT>();
// No material, so no texture: the texture coordinates are not kept.
mesh.ShouldBeOfType<Mesh>();
// Without TrimStart, the second face (leading tabs) would be silently skipped.
// With the fix, both faces are parsed.
mesh.FacesCount.ShouldBe(2);
Expand Down
44 changes: 44 additions & 0 deletions Obj2Tiles.Library.Test/ObjStatementTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
using System.IO;
using NUnit.Framework;
using Obj2Tiles.Library.Materials;
using Shouldly;

namespace Obj2Tiles.Library.Test;

/// <summary>
/// The keyword and argument of OBJ and MTL statements: names (usemtl, newmtl, mtllib) run to the end of the line.
/// </summary>
public class ObjStatementTests
{
[TestCase("usemtl Paint 1 Carmine", "usemtl", "Paint 1 Carmine")]
[TestCase(" usemtl Paint 1 Carmine ", "usemtl", "Paint 1 Carmine")]
[TestCase("newmtl\tBand Carbon Fiber\r", "newmtl", "Band Carbon Fiber")]
[TestCase("usemtl", "usemtl", "")]
[TestCase("mtllib my model.mtl", "mtllib", "my model.mtl")]
public void Split_TheArgumentIsTheRestOfTheLine(string line, string keyword, string argument)
{
ObjStatement.Split(line).ShouldBe((keyword, argument));
ObjStatement.Argument(line).ShouldBe(argument);
}

[Test]
public void ReadMtl_MaterialNamesWithSpacesOrAfterATab_AreWholeNames()
{
var path = Path.Combine(Path.GetTempPath(), "obj2tiles-names-" + Path.GetRandomFileName() + ".mtl");
try
{
File.WriteAllText(path, "newmtl Paint 1 Carmine\nKd 1 0 0\n\nnewmtl\tBezel Frame\nKd 0 1 0\n");

var materials = Material.ReadMtl(path, out _);

materials.Length.ShouldBe(2);
materials[0].Name.ShouldBe("Paint 1 Carmine");
materials[1].Name.ShouldBe("Bezel Frame");
materials[1].DiffuseColor!.G.ShouldBe(1);
}
finally
{
File.Delete(path);
}
}
}
13 changes: 12 additions & 1 deletion Obj2Tiles.Library/Extenders.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,15 @@ public static int AddIndex<T>(this IDictionary<T, int> dictionary, T item)
return dictionary.Count - 1;

}
}

/// <summary>
/// Appends <paramref name="value"/> to <paramref name="list"/> until it has <paramref name="count"/> items:
/// a per-vertex attribute that only some vertices of a model give (a colour, a normal, a texture coordinate)
/// is given this default for the others, so the attribute of a vertex stays at the index of the vertex.
/// </summary>
public static void PadTo<T>(this List<T> list, int count, T value)
{
while (list.Count < count)
list.Add(value);
}
}
19 changes: 19 additions & 0 deletions Obj2Tiles.Library/Geometry/MeshT.cs
Original file line number Diff line number Diff line change
Expand Up @@ -522,6 +522,14 @@ private void TrimTextures(string targetFolder)
if (facesIndexes.Count == 0)
continue;

// A material without texture has no atlas: its faces keep their texture coordinates, which must
// move to the new list as the coordinates of the packed faces do.
if (material.Texture == null && material.NormalMap == null)
{
KeepTextureVertices(facesIndexes, newTextureVertices);
continue;
}

var edgesMapper = GetEdgesMapper(facesIndexes, canonicalIndex);
var facesMapper = GetFacesMapper(edgesMapper);
var clusters = GetFacesClusters(facesIndexes, facesMapper);
Expand All @@ -547,6 +555,17 @@ private void TrimTextures(string targetFolder)
}
}

private void KeepTextureVertices(IEnumerable<int> facesIndexes, IDictionary<Vertex2, int> newTextureVertices)
{
foreach (var faceIndex in facesIndexes)
{
var face = _faces[faceIndex];
face.TextureIndexA = newTextureVertices.AddIndex(_textureVertices[face.TextureIndexA]);
face.TextureIndexB = newTextureVertices.AddIndex(_textureVertices[face.TextureIndexB]);
face.TextureIndexC = newTextureVertices.AddIndex(_textureVertices[face.TextureIndexC]);
}
}

// Exporters (Blender in particular) commonly emit a separate position vertex per
// unique (position, normal, uv) corner, so the SAME 3D point can appear under many
// different vertex indices. Canonicalizing by value once - now that Vertex3.Equals
Expand Down
Loading
Loading