fix(pbr): preserve ORM/emissive UV material overrides (#307)

* fix(pbr): preserve ORM precedence and per-channel UV transforms

* test(pbr): validate all four UV channels, ORM precedence and malformed transforms
This commit is contained in:
OpenGenesis (MPL 2.0) authored and GitHub committed 2026-10-25 20:15:26 +01:00
1 parent 41d9466ca4
commit b2dade1e0a
2 files changed
+188 -80

No files matched your search

@@ -1092,41 +1092,74 @@ namespace OpenSim.Region.OptionalModules.Materials
return true;
}
private static bool GetExtentionTransform(OSDMap Inmap, out OSDMap outmap)
// Keep the four Firestorm PBR texture transforms at their exact slots:
// base color=0, normal=1, ORM=2, emissive=3. Sparse updates MUST
// include placeholders; appending otherwise shifts channel indices.
private static void SetTextureTransform(OSDArray transforms, int channel, OSDMap texture)
{
OSD tmposd;
if (Inmap.TryGetValue("extensions", out tmposd) && tmposd is OSDMap extmap)
{
if (extmap.TryGetValue("KHR_texture_transform", out tmposd) && tmposd is OSDMap trmap)
{
OSDMap tmpmap = new OSDMap();
if (trmap.TryGetValue("offset", out tmposd) && tmposd is OSDArray offset)
{
tmpmap["o"] = new OSDArray()
{
Math.Round((double) offset[0], 3),
Math.Round((double) offset[1], 3)
};
}
if (trmap.TryGetValue("rotation", out tmposd) && tmposd is OSDReal rotation)
{
tmpmap["r"] = Math.Round((double)rotation, 6);
}
if (trmap.TryGetValue("scale", out tmposd) && tmposd is OSDArray scale)
{
tmpmap["s"] = new OSDArray()
{
Math.Round((double) scale[0], 3),
Math.Round((double) scale[1], 3)
};
}
outmap = tmpmap;
return true;
}
}
outmap = null;
return false;
if (!GetExtentionTransform(texture, out OSDMap transform))
return;
while (transforms.Count <= channel)
transforms.Add(new OSD());
transforms[channel] = transform;
}
private static OSDArray RequireFiniteVector2(OSD value)
{
if (value is not OSDArray items || items.Count != 2)
throw new FormatException("KHR_texture_transform vector must have two components");
for (int i = 0; i < 2; ++i)
{
if ((items[i] is not OSDReal && items[i] is not OSDInteger) ||
!double.IsFinite(items[i].AsReal()))
throw new FormatException("KHR_texture_transform components must be finite numbers");
}
return items;
}
private static bool GetExtentionTransform(OSDMap input, out OSDMap output)
{
output = null;
if (!input.TryGetValue("extensions", out OSD extensions))
return false;
if (extensions is not OSDMap extmap)
throw new FormatException("Invalid glTF texture extensions");
if (!extmap.TryGetValue("KHR_texture_transform", out OSD raw))
return false;
if (raw is not OSDMap transform)
throw new FormatException("Invalid KHR_texture_transform");
OSDMap mapped = new OSDMap();
if (transform.TryGetValue("offset", out OSD offsetValue))
{
OSDArray offset = RequireFiniteVector2(offsetValue);
mapped["o"] = new OSDArray
{
Math.Round(offset[0].AsReal(), 3),
Math.Round(offset[1].AsReal(), 3)
};
}
if (transform.TryGetValue("rotation", out OSD rotationValue))
{
if ((rotationValue is not OSDReal && rotationValue is not OSDInteger) ||
!double.IsFinite(rotationValue.AsReal()))
throw new FormatException("Invalid glTF texture rotation");
mapped["r"] = Math.Round(rotationValue.AsReal(), 6);
}
if (transform.TryGetValue("scale", out OSD scaleValue))
{
OSDArray scale = RequireFiniteVector2(scaleValue);
mapped["s"] = new OSDArray
{
Math.Round(scale[0].AsReal(), 3),
Math.Round(scale[1].AsReal(), 3)
};
}
output = mapped;
return true;
}
private static bool AddMaterialOverride(ref RenderMaterialOverrideEntry[] overrides, string data, int side)
{
if (side < 0 || side > byte.MaxValue)
@@ -1180,7 +1213,10 @@ namespace OpenSim.Region.OptionalModules.Materials
OSDMap outosd = new();
OSDArray ti = new(4);
OSDMap tmpmap;
// OpenSim/Firestorm stores occlusion and metallic-roughness as
// one packed ORM texture. Prefer the metallic-roughness entry
// when both are present; do not let occlusion overwrite it.
bool hasMetallicRoughnessMap = false;
bool texturesChanged = false;
Span<UUID> textureIDs = stackalloc UUID[4];
@@ -1206,13 +1242,11 @@ namespace OpenSim.Region.OptionalModules.Materials
return false;
}
}
if (GetExtentionTransform(pmrMapbct, out tmpmap))
{
ti.Add(tmpmap);
}
SetTextureTransform(ti, 0, pmrMapbct);
}
if (pmrMap.TryGetValue("metallicRoughnessTexture", out tmposd) && tmposd is OSDMap pmrMapmrt && pmrMapmrt.Count > 0)
{
hasMetallicRoughnessMap = true;
if (hasTexURIS && pmrMapmrt.TryGetValue("index", out tmposd) && tmposd is OSDInteger pmrMapbcti)
{
int v = pmrMapbcti.value;
@@ -1227,12 +1261,7 @@ namespace OpenSim.Region.OptionalModules.Materials
return false;
}
}
if (GetExtentionTransform(pmrMapmrt, out tmpmap))
{
while (ti.Count < 2)
ti.Add(new OSD());
ti.Add(tmpmap);
}
SetTextureTransform(ti, 2, pmrMapmrt);
}
if (pmrMap.TryGetValue("baseColorFactor", out tmposd) && tmposd is OSDArray baseColorFactor)
{
@@ -1270,17 +1299,7 @@ namespace OpenSim.Region.OptionalModules.Materials
return false;
}
}
if (GetExtentionTransform(ntMap, out tmpmap))
{
if (ti.Count < 2)
{
if (ti.Count == 0)
ti.Add(new OSD());
ti.Add(tmpmap);
}
else
ti[1] = tmpmap;
}
SetTextureTransform(ti, 1, ntMap);
}
if (material.TryGetValue("occlusionTexture", out tmposd) && tmposd is OSDMap otMap && otMap.Count > 0)
@@ -1290,26 +1309,24 @@ namespace OpenSim.Region.OptionalModules.Materials
int v = otMapi.value;
if (v >= 0 && v < texturesURIs.Length)
{
textureIDs[2] = texturesURIs[v];
textureIDchanged[2] = true;
texturesChanged = true;
if (!hasMetallicRoughnessMap)
{
textureIDs[2] = texturesURIs[v];
textureIDchanged[2] = true;
texturesChanged = true;
}
}
else
{
return false;
}
}
if (GetExtentionTransform(otMap, out tmpmap))
{
if (ti.Count > 2)
ti[2] = tmpmap;
else
{
while (ti.Count < 2)
ti.Add(new OSD());
ti.Add(tmpmap);
}
}
// Validate occlusion UV metadata even when the packed ORM
// entry uses the metallic-roughness transform.
if (hasMetallicRoughnessMap)
GetExtentionTransform(otMap, out _);
else
SetTextureTransform(ti, 2, otMap);
}
if (material.TryGetValue("emissiveTexture", out tmposd) && tmposd is OSDMap etMap && etMap.Count > 0)
@@ -1328,17 +1345,7 @@ namespace OpenSim.Region.OptionalModules.Materials
return false;
}
}
if (GetExtentionTransform(etMap, out tmpmap))
{
if (ti.Count > 3)
ti[3] = tmpmap;
else
{
while (ti.Count < 3)
ti.Add(new OSD());
ti.Add(tmpmap);
}
}
SetTextureTransform(ti, 3, etMap);
}
if (material.TryGetValue("alphaMode", out tmposd) && tmposd is OSDString aMode)
@@ -42,6 +42,33 @@ internal static class Program
return accepted;
}
private static OSDMap DecodeOverride(RenderMaterialOverrideEntry[] entries)
{
Assert(entries != null && entries.Length == 1, "unexpected override entries");
OSDMap result = OSDParser.DeserializeLLSDNotation(entries[0].data) as OSDMap;
Assert(result != null, "invalid serialized LLSD material override");
return result;
}
private static void AssertUv(OSDArray transforms, int slot,
double scaleU, double scaleV, double offsetU, double offsetV)
{
Assert(transforms.Count > slot && transforms[slot] is OSDMap,
"missing PBR UV transform for channel " + slot);
OSDMap channel = (OSDMap)transforms[slot];
Assert(channel["s"] is OSDArray && channel["o"] is OSDArray,
"PBR scale or offset missing for channel " + slot);
OSDArray scales = (OSDArray)channel["s"];
OSDArray offsets = (OSDArray)channel["o"];
Assert(scales.Count == 2 && offsets.Count == 2,
"wrong PBR vector length for channel " + slot);
Assert(Math.Abs(scales[0].AsReal() - scaleU) < 0.002 &&
Math.Abs(scales[1].AsReal() - scaleV) < 0.002 &&
Math.Abs(offsets[0].AsReal() - offsetU) < 0.002 &&
Math.Abs(offsets[1].AsReal() - offsetV) < 0.002,
"PBR UV transform changed for channel " + slot);
}
private static void Main()
{
RenderMaterialEntry[] empty = null;
@@ -150,6 +177,80 @@ internal static class Program
Assert(!(bool)add.Invoke(null, addArgs),
"byte-overflowing PBR face accepted by override converter");
// Reproduce Firestorm's four-channel glTF KHR_texture_transform
// contract and verify the exact LLSD 'ti' channel positions.
const string uvBase = "{\"extensions\":{\"KHR_texture_transform\":{\"scale\":[1.5,1.25],\"offset\":[0.1,-0.1],\"rotation\":0.0}}}";
const string uvNormal = "{\"extensions\":{\"KHR_texture_transform\":{\"scale\":[2.0,2.25],\"offset\":[0.0,0.2],\"rotation\":0.0}}}";
const string uvOrm = "{\"extensions\":{\"KHR_texture_transform\":{\"scale\":[3.0,3.25],\"offset\":[0.25,0.0],\"rotation\":0.0}}}";
const string uvOcclusion = "{\"extensions\":{\"KHR_texture_transform\":{\"scale\":[9.0,9.0],\"offset\":[0.75,0.75],\"rotation\":0.0}}}";
const string uvEmissive = "{\"extensions\":{\"KHR_texture_transform\":{\"scale\":[4.0,4.25],\"offset\":[0.0,0.25],\"rotation\":0.0}}}";
UUID metallicAsset = UUID.Random(), occlusionAsset = UUID.Random();
string allChannels = "{\"images\":[{\"uri\":\"" + metallicAsset +
"\"},{\"uri\":\"" + occlusionAsset + "\"}],\"textures\":[{\"source\":0},{\"source\":1}]," +
"\"materials\":[{\"pbrMetallicRoughness\":{\"baseColorTexture\":" + uvBase +
",\"metallicRoughnessTexture\":{\"index\":0,\"extensions\":" +
uvOrm.Substring(14, uvOrm.Length - 15) + "}},\"normalTexture\":" + uvNormal +
",\"occlusionTexture\":{\"index\":1,\"extensions\":" +
uvOcclusion.Substring(14, uvOcclusion.Length - 15) + "},\"emissiveTexture\":" + uvEmissive + "}]}";
// Build the indexed entries without losing the KHR extension; the
// metallic and occlusion textures deliberately carry different UVs.
RenderMaterialOverrideEntry[] uvEntries = null;
object[] uvArgs = { uvEntries, allChannels, 3 };
Assert((bool)add.Invoke(null, uvArgs), "four-channel PBR UV update rejected");
uvEntries = (RenderMaterialOverrideEntry[])uvArgs[0];
OSDMap decoded = DecodeOverride(uvEntries);
OSDArray transforms = decoded["ti"] as OSDArray;
Assert(transforms != null && transforms.Count == 4,
"four-channel PBR UV array has wrong size");
AssertUv(transforms, 0, 1.5, 1.25, 0.1, -0.1);
AssertUv(transforms, 1, 2.0, 2.25, 0.0, 0.2);
AssertUv(transforms, 2, 3.0, 3.25, 0.25, 0.0);
AssertUv(transforms, 3, 4.0, 4.25, 0.0, 0.25);
OSDArray mappedTextures = decoded["tex"] as OSDArray;
Assert(mappedTextures != null && mappedTextures.Count == 4 &&
mappedTextures[2].AsUUID() == metallicAsset,
"occlusion replaced the metallic-roughness (ORM) texture ID");
// Sparse updates must not shift emissive to ORM or ORM to normal.
uvArgs = new object[] { null, "{\"materials\":[{\"emissiveTexture\":" + uvEmissive + "}]}", 3 };
Assert((bool)add.Invoke(null, uvArgs), "emissive-only override rejected");
OSDArray sparse = DecodeOverride((RenderMaterialOverrideEntry[])uvArgs[0])["ti"] as OSDArray;
Assert(sparse != null && sparse.Count == 4 && sparse[0] is not OSDMap &&
sparse[1] is not OSDMap && sparse[2] is not OSDMap,
"emissive-only UV was assigned to the wrong channel");
AssertUv(sparse, 3, 4.0, 4.25, 0.0, 0.25);
uvArgs = new object[] { null, "{\"materials\":[{\"pbrMetallicRoughness\":{\"metallicRoughnessTexture\":" + uvOrm + "}}]}", 3 };
Assert((bool)add.Invoke(null, uvArgs), "ORM-only override rejected");
sparse = DecodeOverride((RenderMaterialOverrideEntry[])uvArgs[0])["ti"] as OSDArray;
Assert(sparse != null && sparse.Count == 3 && sparse[0] is not OSDMap &&
sparse[1] is not OSDMap, "ORM-only UV shifted to an earlier channel");
AssertUv(sparse, 2, 3.0, 3.25, 0.25, 0.0);
// Compatibility fallback: occlusion-only glTF still populates ORM.
uvArgs = new object[] { null, "{\"materials\":[{\"occlusionTexture\":" + uvOcclusion + "}]}", 3 };
Assert((bool)add.Invoke(null, uvArgs), "occlusion-only material rejected");
sparse = DecodeOverride((RenderMaterialOverrideEntry[])uvArgs[0])["ti"] as OSDArray;
AssertUv(sparse, 2, 9.0, 9.0, 0.75, 0.75);
// A malformed or nonnumeric KHR transform must never mutate the last
// successfully committed face, including on a channel-only update.
string pristine = uvEntries[0].data;
foreach (string malformed in new[] {
"{\"materials\":[{\"emissiveTexture\":{\"extensions\":{\"KHR_texture_transform\":{\"scale\":[1.0]}}}}]}",
"{\"materials\":[{\"pbrMetallicRoughness\":{\"metallicRoughnessTexture\":{\"extensions\":{\"KHR_texture_transform\":{\"offset\":[\"invalid\",0]}}}}}]}",
"{\"materials\":[{\"emissiveTexture\":{\"extensions\":{\"KHR_texture_transform\":{\"rotation\":\"invalid\"}}}}]}"
})
{
uvArgs = new object[] { uvEntries, malformed, 3 };
Assert(!(bool)add.Invoke(null, uvArgs), "invalid glTF UV transform accepted");
uvEntries = (RenderMaterialOverrideEntry[])uvArgs[0];
Assert(uvEntries[0].data == pristine, "invalid UV mutated existing PBR face");
}
Console.WriteLine("OpenGenesisLINK PBR ORM/emissive UV channel roundtrip and invalid-input regression: OK");
Console.WriteLine("OpenGenesisLINK PBR face bounds and glTF texture validation regression: OK");
}
}