Editor/Core/UnityMaterial.cs

Editor helper that parses Unity text-serialized Material and TerrainLayer YAML and converts material properties into s&box VMAT/TMAT representations, mapping textures, numbers and colors, inferring roles for unknown shaders, and emitting warnings/information.

File AccessNetworking
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;

namespace ImportUnityPackage;

/// <summary>Best-effort conversion of text-serialized Standard/URP material properties.</summary>
public sealed class UnityMaterial
{
	public Dictionary<string, string> Textures { get; } = new();
	public Dictionary<string, double> Numbers { get; } = new();
	public Dictionary<string, double[]> Colors { get; } = new();
	public List<string> Warnings { get; } = new();
	public List<string> Information { get; } = new();
	readonly Dictionary<string, string> channelImages = new();
	readonly Dictionary<string, double[]> textureScale = new();
	readonly Dictionary<string, double[]> textureOffset = new();
	bool shaderAlphaTest;
	bool shaderBackfaces;
	bool shaderTranslucent;
	bool terrainLayer;
	HashSet<string> declaredProperties;
	/// <summary>The package shader's colors blended in through a mask: not the tint or opacity.</summary>
	HashSet<string> maskedColors = new();
	// Package shader properties that InferRoles gave a converted role.
	readonly HashSet<string> aliased = new( StringComparer.Ordinal );
	/// <summary>
	/// For a package shader: its visible declared properties that the conversion does not read, grouped by the effect their
	/// names suggest (for example wind, texture layers or triplanar mapping). Empty for Unity's own shaders.
	/// </summary>
	public IReadOnlyDictionary<string, string[]> Unreproduced { get; private set; } = new Dictionary<string, string[]>();
	static readonly string[] ColorProperties = { "_BaseMap", "_Diffuse", "_MainTex", "_Albedo", "_BaseColorMap" };
	// Properties the conversion reads (ToVmat, PrepareChannels and the render-state checks).
	static readonly HashSet<string> ReadProperties = new( ColorProperties.Concat( new[] { "_BumpMap", "_Normal", "_NormalMap", "_OcclusionMap", "_Occlusion",
		"_MetallicGlossMap", "_SpecGlossMap", "_MaskMap", "_EmissionMap", "_EmissiveColorMap", "_Color", "_BaseColor", "_MainColor", "_TintColor", "_EmissionColor",
		"_Cutoff", "_Cull", "_Mode", "_Surface", "_AlphaClip", "_Blend", "_SurfaceType", "_AlphaCutoffEnable", "_AlphaCutoff", "_DoubleSidedEnable", "_Smoothness", "_Glossiness", "_Metallic", "_GlossMapScale", "_SmoothnessTextureChannel", "_WorkflowMode" } ),
		StringComparer.Ordinal );
	// Effects named by unread properties, first match wins; words are matched in lowercased display and reference names.
	static readonly (string Feature, string[] Words)[] FeatureWords =
	{
		("vertex animation (wind, waves)", new[] { "wind", "sway", "wave", "bend", "flutter", "gust", "wiggle", "jitter", "shake" }),
		("water (foam, refraction, caustics)", new[] { "foam", "refract", "caustic", "shore", "underwater", "depthcolor", "shallow" }),
		("depth fade or soft edges", new[] { "depth", "softparticle", "invfade" }),
		("triplanar or world-space mapping", new[] { "triplanar", "worldspace", "worldproj", "worlduv" }),
		("scrolling or flowing UVs", new[] { "flow", "scroll", "speed", "pann" }),
		("texture layers and blending", new[] { "layer", "blend", "splat", "second", "overlay", "snow", "moss", "dirt", "puddle", "wet", "detail", "cover", "mask", "noise" }),
		("rim or fresnel lighting", new[] { "rim", "fresnel" }),
		("translucency or subsurface scattering", new[] { "translucen", "subsurface", "sss", "transmission", "backlight" }),
		("color variation", new[] { "variation", "hue", "gradient", "random", "colorshift" }),
		("distortion", new[] { "distort" }),
		("parallax or height", new[] { "parallax", "height", "displace", "tessell" }),
	};

	Dictionary<string, string[]> UnreadFeatures( UnityShaderDeclarations shader )
	{
		var visible = shader.Properties.Where( p => !p.Hidden ).GroupBy( p => p.Name, StringComparer.Ordinal ).ToDictionary( g => g.Key, g => g.First(), StringComparer.Ordinal );
		var hidden = shader.Properties.Where( p => p.Hidden ).Select( p => p.Name ).ToHashSet( StringComparer.Ordinal );
		var groups = new Dictionary<string, List<string>>();
		// Only what the material uses: an assigned texture or a stored value, and not a switched-off toggle.
		bool Used( string name ) => (Textures.ContainsKey( name ) || Numbers.ContainsKey( name ) || Colors.ContainsKey( name )) &&
			!(Regex.IsMatch( name, "(?i)enable|toggle|^_use" ) && Numbers.TryGetValue( name, out var toggle ) && toggle == 0);
		foreach ( var name in shader.Declared.Where( n => !hidden.Contains( n ) && !ReadProperties.Contains( n ) && !aliased.Contains( n ) && Used( n ) ).Order( StringComparer.Ordinal ) )
		{
			var property = visible.GetValueOrDefault( name );
			var words = Regex.Replace( ((property?.Display ?? "") + name).ToLowerInvariant(), "[^a-z0-9]", "" );
			// Unread textures that name no known effect are still listed; other unmatched values are usually settings.
			var feature = FeatureWords.FirstOrDefault( f => f.Words.Any( words.Contains ) ).Feature ?? (property?.Texture == true ? "other textures" : null);
			if ( feature == null ) continue;
			if ( !groups.TryGetValue( feature, out var list ) ) groups[feature] = list = new();
			list.Add( name );
		}
		return groups.ToDictionary( g => g.Key, g => g.Value.ToArray() );
	}
	/// <summary>Texture properties the conversion reads; a missing texture elsewhere does not change the output.</summary>
	internal static readonly HashSet<string> ConvertedTextures = new( ColorProperties.Concat( new[] { "_BumpMap", "_Normal", "_NormalMap", "_OcclusionMap", "_Occlusion",
		"_MetallicGlossMap", "_SpecGlossMap", "_MaskMap", "_EmissionMap", "_EmissiveColorMap", "_ParallaxMap", "_HeightMap" } ), StringComparer.Ordinal );
	readonly HashSet<string> keywords = new( StringComparer.Ordinal );
	bool specularWorkflow;
	bool smoothnessFromAlbedo;
	// Set when a keyword-driven Unity shader has emission enabled, so an emission color applies even without a map.
	bool emissionEnabled;
	bool unlit;
	bool legacyParticle;
	bool additive;
	// Unity's default texture is white; s&box's default color texture is grey. This engine texture is plain white.
	const string White = "materials/default/default_mask.tga";
	// s&box's default roughness texture: 0.5.
	const string MidGrey = "materials/default/default_rough.tga";
	// Smoothness from the material's own pipeline: built-in reads _Glossiness and scales maps by _GlossMapScale, URP and
	// HDRP read _Smoothness (URP's hidden legacy _GlossMapScale is 0). Package and unknown shaders take either.
	double MapSmoothnessScale => pipeline switch
	{
		Pipeline.Builtin => Number( "_GlossMapScale", 1 ),
		Pipeline.Universal => Number( "_Smoothness", 1 ),
		_ => Number( "_GlossMapScale", Number( "_Smoothness", 1 ) ),
	};
	double ScalarSmoothness => pipeline switch
	{
		Pipeline.Builtin => Number( "_Glossiness", 0.5 ),
		Pipeline.Universal or Pipeline.HighDefinition => Number( "_Smoothness", 0.5 ),
		_ => Number( "_Smoothness", Number( "_Glossiness", 0.5 ) ),
	};
	public long ShaderFileId { get; private set; }
	/// <summary>The missing-texture message naming every property that references this texture.</summary>
	internal string MissingTexture( string guid ) =>
		$"Texture for {string.Join( ", ", Textures.Where( p => p.Value.Equals( guid, StringComparison.OrdinalIgnoreCase ) ).Select( p => p.Key ) )} is missing from the package or unsupported ({guid}).";
	public IEnumerable<string> ColorTextureGuids => ColorOrder.Where( Textures.ContainsKey ).Select( p => Textures[p] );
	// Render state comes from the properties of the material's own pipeline: Unity keeps values from earlier shaders, so a
	// Standard material switched from URP can still carry _Surface. Package shaders keep only declared values.
	enum Pipeline { Unknown, Builtin, Universal, HighDefinition }
	Pipeline pipeline;
	// Built-in shaders other than Standard (particles, for example) can declare _Cull; Standard does not.
	bool builtinCull;
	static readonly HashSet<string> RenderStateProperties = new( StringComparer.Ordinal ) { "_Surface", "_Blend", "_AlphaClip", "_Cull", "_Cutoff", "_AlphaCutoff", "_SurfaceType", "_AlphaCutoffEnable", "_DoubleSidedEnable" };
	bool Flag( string name, double value ) => Number( name, double.NaN ) == value;
	bool AlphaTest => shaderAlphaTest || pipeline switch
	{
		Pipeline.Builtin => Flag( "_Mode", 1 ),
		Pipeline.Universal => Flag( "_AlphaClip", 1 ),
		Pipeline.HighDefinition => Flag( "_AlphaCutoffEnable", 1 ),
		_ => Flag( "_Mode", 1 ) || Flag( "_AlphaClip", 1 ) || Flag( "_AlphaCutoffEnable", 1 ),
	};
	bool Translucent => shaderTranslucent || pipeline switch
	{
		Pipeline.Builtin => Number( "_Mode", 0 ) >= 2,
		Pipeline.Universal => Flag( "_Surface", 1 ),
		Pipeline.HighDefinition => Flag( "_SurfaceType", 1 ),
		_ => Number( "_Mode", 0 ) >= 2 || Flag( "_Surface", 1 ) || Flag( "_SurfaceType", 1 ),
	};
	bool TwoSided => shaderBackfaces || pipeline switch
	{
		Pipeline.Builtin => builtinCull && Flag( "_Cull", 0 ),
		Pipeline.Universal => Flag( "_Cull", 0 ),
		Pipeline.HighDefinition => Flag( "_DoubleSidedEnable", 1 ),
		_ => Flag( "_Cull", 0 ) || Flag( "_DoubleSidedEnable", 1 ),
	};
	double AlphaCutoff => pipeline == Pipeline.HighDefinition ? Number( "_AlphaCutoff", 0.5 ) : Number( "_Cutoff", 0.5 );
	/// <summary>Base color properties in the order the material's pipeline reads them.</summary>
	string[] ColorOrder => pipeline switch
	{
		Pipeline.Builtin => new[] { "_MainTex", "_BaseMap", "_Diffuse", "_Albedo", "_BaseColorMap" },
		Pipeline.HighDefinition => new[] { "_BaseColorMap", "_BaseMap", "_MainTex", "_Diffuse", "_Albedo" },
		_ => ColorProperties,
	};
	internal bool UsesAlpha => AlphaTest || Translucent;
	public string ShaderName { get; private set; }
	public string ShaderGuid { get; private set; }
	static readonly Regex GuidPattern = new( @"guid:\s*([a-fA-F0-9]{32})" );

	public static IEnumerable<string> References( string text ) => GuidPattern.Matches( text )
		.Select( m => m.Groups[1].Value ).Where( g => g.Any( c => c != '0' ) ).Distinct( StringComparer.OrdinalIgnoreCase );

	const string NotText = "Material is not Unity text YAML. Re-export it with Asset Serialization set to Force Text in Unity.";

	public static UnityMaterial Parse( string text )
	{
		if ( text.Contains( '\0' ) ) throw new InvalidDataException( NotText );
		var objects = UnityYaml.Parse( text );
		if ( UnityYaml.Objects( objects, "TerrainLayer" ).FirstOrDefault() is YamlNode layer ) return ParseTerrainLayer( layer );
		var body = UnityYaml.Objects( objects, "Material" ).FirstOrDefault() ?? throw new InvalidDataException( NotText );
		var shaderReference = body["m_Shader"]?.Reference ?? default;
		var result = new UnityMaterial { ShaderGuid = shaderReference.Guid ?? "", ShaderFileId = shaderReference.FileId };
		// m_ShaderKeywords (a space-separated string) became m_ValidKeywords in Unity 2021.2. m_InvalidKeywords belong to
		// previous shaders and are ignored.
		var keywordsKnown = body["m_ShaderKeywords"] != null || body["m_ValidKeywords"] != null;
		result.keywords.UnionWith( (body["m_ShaderKeywords"]?.Value ?? "").Split( ' ', StringSplitOptions.RemoveEmptyEntries ) );
		result.keywords.UnionWith( (body["m_ValidKeywords"]?.Items ?? Array.Empty<YamlNode>()).Select( k => k.Value ).Where( k => !string.IsNullOrEmpty( k ) ) );
		var saved = body["m_SavedProperties"];
		foreach ( var section in new[] { "m_TexEnvs", "m_Floats", "m_Colors", "m_Ints" } )
		{
			foreach ( var (name, value) in Properties( saved?[section] ) )
			{
				var named = Regex.IsMatch( name, "^[A-Za-z_][A-Za-z0-9_]*$" );
				if ( value["m_Texture"] is YamlNode texture )
				{
					var scale = Pair( value["m_Scale"] );
					var offset = Pair( value["m_Offset"] );
					if ( !named ) continue;
					if ( texture.Reference.HasGuid ) result.Textures[name] = texture.Reference.Guid;
					if ( scale != null ) result.textureScale[name] = scale;
					if ( offset != null ) result.textureOffset[name] = offset;
				}
				else if ( named && value.Number is double number ) result.Numbers[name] = number;
				else if ( named && new[] { "r", "g", "b", "a" }.Select( c => value[c]?.Number ).ToArray() is var rgba && rgba.All( c => c != null ) )
					result.Colors[name] = rgba.Select( c => c.Value ).ToArray();
			}
		}
		if ( UnityKnownShaders.Identify( shaderReference ) is { } known ) result.ApplyKnownShader( known, keywordsKnown );
		if ( result.Textures.ContainsKey( "_MetallicGlossMap" ) || result.Textures.ContainsKey( "_MaskMap" ) || result.Textures.ContainsKey( "_SpecGlossMap" ) )
			result.Warnings.Add( "Packed metallic/smoothness or HDRP mask maps need channel separation; scalar metallic/roughness values were used." );
		result.Information.Add( "Review the converted material: custom shaders, normal-map conventions and advanced Unity settings are not reproduced exactly." );
		return result;
	}

	/// <summary>Applies what is known about a Unity-shipped shader: its real properties, active keywords and workflow.</summary>
	void ApplyKnownShader( UnityKnownShaders.Shader shader, bool keywordsKnown )
	{
		ShaderName = shader.Name;
		pipeline = shader.Name.StartsWith( "HDRP/", StringComparison.Ordinal ) ? Pipeline.HighDefinition : shader.Universal ? Pipeline.Universal : Pipeline.Builtin;
		builtinCull = !shader.KeywordDriven;
		shaderAlphaTest |= shader.AlphaTest;
		shaderBackfaces |= shader.Backfaces;
		unlit = shader.Unlit;
		legacyParticle = shader.LegacyParticle;
		shaderTranslucent |= shader.LegacyParticle;
		// URP blending: _Blend 2 is additive on transparent surfaces.
		additive = shader.Universal && Number( "_Surface", 0 ) == 1 && Number( "_Blend", 0 ) == 2;
		if ( unlit ) Information.Add( "Unlit shading approximated with self-illumination from the base color; scene lighting still adds to it." );
		var stale = Textures.Keys.Where( k => !UnityKnownShaders.TextureProperties.Contains( k ) ||
			(pipeline == Pipeline.HighDefinition ? UnityKnownShaders.BuiltinUniversalOnly : UnityKnownShaders.HighDefinitionOnly).Contains( k ) ).ToArray();
		foreach ( var property in stale ) Textures.Remove( property );
		if ( stale.Length > 0 ) Information.Add( $"Ignored texture properties left over from a previous shader: {string.Join( ", ", stale.Order( StringComparer.Ordinal ) )}." );
		if ( shader.KeywordDriven && keywordsKnown )
		{
			// Keyword-driven shaders only read a feature's textures when its keyword is enabled.
			bool On( params string[] names ) => names.Any( keywords.Contains );
			var inactive = new List<string>();
			void Gate( bool enabled, string feature, params string[] properties )
			{
				if ( enabled || !properties.Any( Textures.ContainsKey ) ) return;
				foreach ( var property in properties ) Textures.Remove( property );
				inactive.Add( feature );
			}
			// A black emission color multiplies the map to nothing.
			emissionEnabled = On( "_EMISSION" ) && !(Colors.TryGetValue( "_EmissionColor", out var emissive ) && emissive.Take( 3 ).Max() <= 0);
			Gate( emissionEnabled, "emission", "_EmissionMap" );
			Gate( On( "_DETAIL_MULX2", "_DETAIL_SCALED" ), "detail maps", "_DetailAlbedoMap", "_DetailNormalMap", "_DetailMask" );
			Gate( On( "_PARALLAXMAP" ), "parallax", "_ParallaxMap" );
			if ( shader.Universal )
			{
				Gate( On( "_METALLICSPECGLOSSMAP" ), "metallic/specular map", "_MetallicGlossMap", "_SpecGlossMap" );
				Gate( On( "_OCCLUSIONMAP" ), "occlusion map", "_OcclusionMap" );
			}
			else
			{
				Gate( On( "_METALLICGLOSSMAP" ), "metallic map", "_MetallicGlossMap" );
				Gate( On( "_SPECGLOSSMAP" ), "specular map", "_SpecGlossMap" );
			}
			if ( inactive.Count > 0 ) Information.Add( $"Unity features disabled on this material were not converted: {string.Join( ", ", inactive )}." );
			smoothnessFromAlbedo = On( "_SMOOTHNESS_TEXTURE_ALBEDO_CHANNEL_A" );
		}
		else if ( shader.KeywordDriven ) smoothnessFromAlbedo = Number( "_SmoothnessTextureChannel", 0 ) == 1;
		// URP Lit selects its workflow per material; Standard has a separate specular shader.
		specularWorkflow = shader.Workflow == UnityKnownShaders.Workflow.Specular ||
			shader.Universal && shader.KeywordDriven && (keywords.Contains( "_SPECULAR_SETUP" ) || Number( "_WorkflowMode", 1 ) == 0);
		if ( specularWorkflow ) Information.Add( "Unity specular workflow approximated: specular color is not converted and metalness is 0." );
	}

	/// <summary>Material properties as (name, value) in any serialized layout.</summary>
	static IEnumerable<(string Name, YamlNode Value)> Properties( YamlNode section )
	{
		if ( section == null ) yield break;
		// Current Unity: "- _Name: value". Unity 5: "- first: {name: _Name}, second: value".
		// Unity 4: repeated "data:" entries holding the same first/second pairs.
		var entries = section.IsList ? section.Items : section.All( "data" );
		foreach ( var entry in entries )
		{
			if ( entry["first"]?["name"]?.Value is string name ) yield return (name, entry["second"] ?? YamlNode.Scalar( "" ));
			else if ( entry.Pairs.Count == 1 ) yield return (entry.Pairs[0].Key, entry.Pairs[0].Value);
		}
	}

	static double[] Pair( YamlNode node ) => node?["x"]?.Number is double x && node["y"]?.Number is double y ? new[] { x, y } : null;

	/// <summary>Applies a package shader's declarations (ShaderLab source or a Shader Graph file named <paramref name="graphName"/>).</summary>
	public void ConfigureShader( string source, string graphName = null )
	{
		var shader = UnityShaderDeclarations.Parse( source );
		ShaderName = shader.Graph ? graphName : shader.Name;
		declaredProperties = shader.Declared;
		if ( declaredProperties.Count > 0 )
		{
			// Unity retains old shader properties in materials. Only use properties declared by the active shader.
			foreach ( var stale in Textures.Keys.Where( k => !declaredProperties.Contains( k ) ).ToArray() ) Textures.Remove( stale );
			foreach ( var stale in Colors.Keys.Where( k => !declaredProperties.Contains( k ) ).ToArray() ) Colors.Remove( stale );
			// Shader Graph materials can override the target's render state ("Allow Material Override") with values the graph
			// does not declare.
			foreach ( var stale in Numbers.Keys.Where( k => !declaredProperties.Contains( k ) && !(shader.Graph && RenderStateProperties.Contains( k )) ).ToArray() ) Numbers.Remove( stale );
		}
		shaderAlphaTest = shader.AlphaClip;
		shaderBackfaces = shader.TwoSided;
		shaderTranslucent = shader.Transparent;
		maskedColors = shader.MaskedColors;
		foreach ( var masked in maskedColors.Where( Colors.ContainsKey ) )
			Information.Add( $"Shader property '{masked}' is blended in through a mask (its alpha weights a blend in the shader code), which is not reproduced; it is not used as the tint or opacity." );
		InferRoles( shader );
		Unreproduced = UnreadFeatures( shader );
		if ( !string.IsNullOrEmpty( ShaderName ) )
			Warnings.Add( $"Shader '{ShaderName}' is approximated using s&box's complex shader; shader code and graph behavior are not translated" + (Unreproduced.Count == 0 ? "." :
				$". Not reproduced: {string.Join( "; ", Unreproduced.Select( f => $"{f.Key} ({string.Join( ", ", f.Value )})" ) )}.") );
	}

	// Words that name a texture's role in shader property names (display or reference, lowercased, letters and digits only).
	static readonly string[] BaseColorWords = { "albedo", "basecolor", "basecolour", "basemap", "basetexture", "basetex", "maintex", "maintexture", "diffuse", "colormap", "colortexture", "colourmap", "colourtexture" };
	static readonly string[] NotColorWords = { "normal", "bump", "emissi", "mask", "noise", "metal", "smooth", "rough", "spec", "occlusion", "height", "detail", "overlay", "triplanar", "flow", "distort", "cube", "reflect", "parallax" };
	static readonly string[] TintWords = { "basecolor", "basecolour", "maincolor", "maincolour", "albedocolor", "albedocolour", "tint" };
	// Words of effects (FeatureWords) and other non-surface maps: a property named after one never takes a role, since a
	// wrong role (foam as the base color, a detail normal as the normal map, a rim tint as the tint) looks worse than none.
	static readonly string[] EffectWords = FeatureWords.SelectMany( f => f.Words ).Concat( new[] { "ramp", "lut", "matcap", "dissolve", "spec", "gloss" } ).ToArray();
	// Effect words that are word stems: they also match longer words (Emission, Translucency, Specular, Panning).
	static readonly HashSet<string> EffectStems = new( StringComparer.Ordinal ) { "emissi", "translucen", "refract", "caustic", "displace", "tessell", "distort", "pann", "scroll", "spec", "gloss", "subsurface", "variation", "parallax", "triplanar" };

	/// <summary>
	/// Whether a property is named after an effect: its display and reference names split into words (separators and
	/// camelCase), matched as whole words or two- and three-word phrases (plurals and stems allowed), so "Primary" is not
	/// "rim" and "Window" is not "wind".
	/// </summary>
	static bool IsEffect( UnityShaderDeclarations.Property p )
	{
		var words = new List<string>();
		foreach ( var part in Regex.Split( p.Display + " " + p.Name, "[^A-Za-z0-9]+" ) )
			words.AddRange( Regex.Split( part, "(?<=[a-z])(?=[A-Z])|(?<=[A-Za-z])(?=[0-9])|(?<=[0-9])(?=[A-Za-z])" ).Where( w => w.Length > 0 ).Select( w => w.ToLowerInvariant() ) );
		var phrases = new List<string>( words );
		for ( var i = 0; i + 1 < words.Count; i++ ) phrases.Add( words[i] + words[i + 1] );
		for ( var i = 0; i + 2 < words.Count; i++ ) phrases.Add( words[i] + words[i + 1] + words[i + 2] );
		return phrases.Any( w => EffectWords.Any( e => w == e || w == e + "s" || EffectStems.Contains( e ) && w.StartsWith( e, StringComparison.Ordinal ) ) );
	}

	/// <summary>
	/// Gives an unknown shader's properties the base color, normal, emission and tint roles the conversion reads, when the
	/// material has none of the usual property names. Explicit declarations come first; name matches must be unique.
	/// </summary>
	void InferRoles( UnityShaderDeclarations shader )
	{
		static string Words( UnityShaderDeclarations.Property p ) => Regex.Replace( (p.Display + " " + p.Name).ToLowerInvariant(), "[^a-z0-9 ]", "" );
		static string Joined( UnityShaderDeclarations.Property p ) => Words( p ).Replace( " ", "" );
		bool Any( string text, IEnumerable<string> words ) => words.Any( text.Contains );
		var textures = shader.Properties.Where( p => p.Texture && !p.Hidden && Textures.ContainsKey( p.Name ) ).ToArray();
		var colors = shader.Properties.Where( p => p.Color && !p.Hidden && Colors.ContainsKey( p.Name ) && !maskedColors.Contains( p.Name ) ).ToArray();
		// A usual property name the shader only declares as hidden (Amplify adds a hidden _EmissionColor) does not hold the role.
		bool Present( string name, bool texture ) => (texture ? Textures.ContainsKey( name ) : Colors.ContainsKey( name )) && !shader.Properties.Any( p => p.Name == name && p.Hidden );
		void Alias( string role, string canonical, UnityShaderDeclarations.Property property, string evidence, bool texture )
		{
			if ( texture )
			{
				Textures[canonical] = Textures[property.Name];
				if ( textureScale.TryGetValue( property.Name, out var scale ) ) textureScale[canonical] = scale;
				if ( textureOffset.TryGetValue( property.Name, out var offset ) ) textureOffset[canonical] = offset;
			}
			else Colors[canonical] = Colors[property.Name];
			aliased.Add( property.Name );
			Information.Add( $"Shader property '{property.Name}' ({property.Display}) used as the {role} ({evidence})." );
		}
		// Picks the property marked explicitly, else the only name match; several matches are left unresolved and reported.
		UnityShaderDeclarations.Property Pick( string role, IEnumerable<UnityShaderDeclarations.Property> marked, IEnumerable<UnityShaderDeclarations.Property> named, out string evidence, string prefer = null )
		{
			evidence = "declared";
			if ( marked.FirstOrDefault() is { } explicitProperty ) return explicitProperty;
			var matches = named.ToArray();
			// Several matches: prefer the one sharing the base color texture's first word (Leaf Texture → Leaf Base Color).
			if ( matches.Length > 1 && prefer != null ) matches = matches.Where( p => Words( p ).Split( ' ' )[0] == prefer ).ToArray();
			evidence = "inferred from its name";
			if ( matches.Length == 1 ) return matches[0];
			if ( matches.Length > 1 ) Information.Add( $"Several shader properties could be the {role} ({string.Join( ", ", matches.Select( p => p.Name ) )}); none was chosen." );
			return null;
		}
		string colorWord = null;
		if ( !ColorProperties.Any( p => Present( p, true ) ) )
		{
			var candidates = textures.Where( p => !p.Normal && !Any( Joined( p ), NotColorWords ) && !IsEffect( p ) ).ToArray();
			var named = candidates.Where( p => Any( Joined( p ), BaseColorWords ) ).ToArray();
			// A single remaining texture that names no other role is the base color.
			if ( named.Length == 0 && candidates.Length == 1 ) named = candidates;
			else if ( named.Length == 0 && candidates.Length > 1 ) Information.Add( $"Several shader textures could be the base color ({string.Join( ", ", candidates.Select( p => p.Name ) )}); none was chosen." );
			if ( Pick( "base color", textures.Where( p => p.MainTexture ), named, out var evidence ) is { } color )
			{
				Alias( "base color", "_MainTex", color, evidence, true );
				colorWord = Words( color ).Split( ' ' )[0];
			}
		}
		if ( !new[] { "_BumpMap", "_Normal", "_NormalMap" }.Any( p => Present( p, true ) ) &&
			Pick( "normal map", textures.Where( p => p.Normal && !IsEffect( p ) ), textures.Where( p => Any( Joined( p ), new[] { "normal", "bump" } ) && !IsEffect( p ) ), out var normalEvidence, colorWord ) is { } normal )
			Alias( "normal map", "_BumpMap", normal, normalEvidence, true );
		if ( !Present( "_EmissionMap", true ) && Pick( "emission map", Array.Empty<UnityShaderDeclarations.Property>(),
			textures.Where( p => Any( Joined( p ), new[] { "emissi" } ) ), out var emissionEvidence, colorWord ) is { } emissionMap )
			Alias( "emission map", "_EmissionMap", emissionMap, emissionEvidence, true );
		// Specific tint names first (Base Color, Color Tint); a plain "Color" only when nothing more specific exists.
		var tints = colors.Where( p => !Any( Joined( p ), new[] { "emissi" } ) && !IsEffect( p ) ).ToArray();
		var tintNames = tints.Where( p => Any( Joined( p ), TintWords ) ).ToArray();
		if ( tintNames.Length == 0 ) tintNames = tints.Where( p => Regex.Replace( p.Display.ToLowerInvariant(), "[^a-z]", "" ) is "color" or "colour" ).ToArray();
		if ( !new[] { "_BaseColor", "_Color" }.Any( p => Present( p, false ) ) && Pick( "color tint", colors.Where( p => p.MainColor ), tintNames, out var tintEvidence, colorWord ) is { } tint )
			Alias( "color tint", "_BaseColor", tint, tintEvidence, false );
		if ( !Present( "_EmissionColor", false ) && Pick( "emission color", Array.Empty<UnityShaderDeclarations.Property>(),
			colors.Where( p => Any( Joined( p ), new[] { "emissi" } ) ), out var glowEvidence, colorWord ) is { } glow )
		{
			Alias( "emission color", "_EmissionColor", glow, glowEvidence, false );
			// No keyword gates a custom shader's emission: a non-black color glows.
			emissionEnabled = Colors["_EmissionColor"].Take( 3 ).Max() > 0;
		}
	}

	public void PrepareChannels( Func<string, int, double, bool, string> extract )
	{
		void Channel( string target, string guid, int channel, double scale = 1, bool invert = false )
		{
			var path = extract( guid, channel, scale, invert );
			if ( path != null ) channelImages[target] = path;
		}
		if ( Textures.TryGetValue( "_MetallicGlossMap", out var packed ) )
		{
			Channel( "metal", packed, 0 );
			Channel( "rough", packed, 3, MapSmoothnessScale, true );
		}
		if ( Textures.TryGetValue( "_MaskMap", out var mask ) )
		{
			Channel( "metal", mask, 0 );
			Channel( "ao", mask, 1 );
			// TerrainLit stores height in B; HDRP Lit stores a detail mask instead.
			if ( terrainLayer ) Channel( "height", mask, 2 );
			Channel( "rough", mask, 3, 1, true );
		}
		var smoothnessScale = MapSmoothnessScale;
		// Specular workflow: smoothness is the specular map's alpha. Metalness stays 0.
		if ( specularWorkflow && Textures.TryGetValue( "_SpecGlossMap", out var specular ) ) Channel( "rough", specular, 3, smoothnessScale, true );
		// Standard/URP can take smoothness from the base color's alpha instead of the metallic/specular map.
		if ( smoothnessFromAlbedo && ColorOrder.FirstOrDefault( Textures.ContainsKey ) is string albedo ) Channel( "rough", Textures[albedo], 3, smoothnessScale, true );
		if ( Textures.TryGetValue( "_OcclusionMap", out var ao ) ) Channel( "ao", ao, 1 );
		if ( AlphaTest || Translucent )
		{
			foreach ( var property in ColorOrder )
			{
				if ( !Textures.TryGetValue( property, out var guid ) ) continue;
				Channel( "opacity", guid, 3 );
				if ( channelImages.ContainsKey( "opacity" ) ) break;
			}
		}
		if ( channelImages.Count > 0 ) Warnings.RemoveAll( w => w.StartsWith( "Packed metallic/" ) || w.StartsWith( "Unity terrain mask channels" ) );
	}

	static UnityMaterial ParseTerrainLayer( YamlNode body )
	{
		var result = new UnityMaterial { terrainLayer = true };
		foreach ( var (source, target) in new[] { ("m_DiffuseTexture", "_MainTex"), ("m_NormalMapTexture", "_BumpMap"), ("m_MaskMapTexture", "_MaskMap") } )
			if ( body[source]?.Reference is { HasGuid: true } texture ) result.Textures[target] = texture.Guid;
		foreach ( var (source, target) in new[] { ("m_Metallic", "_Metallic"), ("m_Smoothness", "_Smoothness"), ("m_NormalScale", "_NormalScale") } )
			if ( body[source]?.Number is double value ) result.Numbers[target] = value;
		// The size in meters one repeat of the layer's textures covers on the terrain.
		if ( body["m_TileSize"] is { } tile && tile["x"]?.Number is double x && tile["y"]?.Number is double y && x > 0 && y > 0 ) result.Numbers["_TileSize"] = (x + y) / 2;
		result.Warnings.Add( "Terrain layer converted; review remapping and tile offset in the terrain material editor." );
		if ( result.Textures.ContainsKey( "_MaskMap" ) ) result.Warnings.Add( "Unity terrain mask channels need separation; packed mask was preserved as a source texture." );
		return result;
	}

	string Texture( Func<string, string> resolve, params string[] names )
	{
		foreach ( var name in names )
			if ( Textures.TryGetValue( name, out var guid ) && resolve( guid ) is string path ) return path;
		return null;
	}
	public double Number( string name, double fallback ) => Numbers.GetValueOrDefault( name, fallback );
	static string N( double value ) => double.IsFinite( value ) ? value.ToString( "0.######", CultureInfo.InvariantCulture ) : "0";
	internal static string Quote( string value ) => JsonSerializer.Serialize( value );

	/// <summary>The VMAT text. <paramref name="resolveNormal"/> resolves normal-map textures when they need their own preparation (Unity import settings such as Flip Green Channel).</summary>
	public string ToVmat( Func<string, string> resolve, Func<string, string> resolveNormal = null )
	{
		var text = new StringBuilder( "Layer0\n{\n\tshader \"shaders/complex.shader_c\"\n" );
		void Set( string key, string value ) => text.AppendLine( $"\t{key} {Quote( value )}" );
		var colorOrder = ColorOrder;
		Set( "TextureColor", Texture( resolve, colorOrder ) ?? White );
		var colorProperty = colorOrder.FirstOrDefault( p => Textures.TryGetValue( p, out var guid ) && resolve( guid ) != null );
		// s&box has one tiling per material, the base color's: other textures with a different tiling are reported.
		var tiling = colorProperty == null ? null : textureScale.GetValueOrDefault( colorProperty ) ?? new[] { 1.0, 1.0 };
		var shifted = colorProperty == null ? null : textureOffset.GetValueOrDefault( colorProperty ) ?? new[] { 0.0, 0.0 };
		foreach ( var other in ConvertedTextures.Where( p => p != colorProperty && Textures.ContainsKey( p ) && resolve( Textures[p] ) != null ) )
			if ( !(textureScale.GetValueOrDefault( other ) ?? new[] { 1.0, 1.0 }).SequenceEqual( tiling ?? new[] { 1.0, 1.0 } ) ||
				!(textureOffset.GetValueOrDefault( other ) ?? new[] { 0.0, 0.0 }).SequenceEqual( shifted ?? new[] { 0.0, 0.0 } ) )
				Warnings.Add( $"Texture '{other}' has its own tiling or offset; s&box uses the base color's for every texture." );
		if ( colorProperty != null && (textureScale.ContainsKey( colorProperty ) || textureOffset.ContainsKey( colorProperty )) )
		{
			var scale = textureScale.GetValueOrDefault( colorProperty ) ?? new[] { 1.0, 1.0 };
			var offset = textureOffset.GetValueOrDefault( colorProperty ) ?? new[] { 0.0, 0.0 };
			// Unity's texture V runs up from the bottom and s&box's down from the top, so Unity's vertical tiling is anchored
			// at the other edge: the s&box offset is 1 - scale - offset (measured in the engine). Horizontal is the same.
			var vertical = 1 - scale[1] - offset[1];
			Set( "g_vTexCoordScale", $"[{N( scale[0] )} {N( scale[1] )}]" );
			Set( "g_vTexCoordOffset", $"[{N( offset[0] )} {N( Math.Round( vertical - Math.Floor( vertical ), 6 ) )}]" );
		}
		Set( "TextureNormal", Texture( resolveNormal ?? resolve, "_BumpMap", "_Normal", "_NormalMap" ) ?? "materials/default/default_normal.tga" );
		Set( "TextureAmbientOcclusion", channelImages.GetValueOrDefault( "ao" ) ?? Texture( resolve, "_OcclusionMap", "_Occlusion" ) ?? "materials/default/default_ao.tga" );
		// The complex shader raises the roughness texture to the power of g_flRoughnessScaleFactor. A scalar roughness r
		// therefore uses s&box's mid-grey roughness texture with the exponent ln r / ln 0.5. A pure white roughness texture
		// renders mirror-smooth (measured in the engine), so it is never used; generated roughness maps stop at 254/255.
		if ( channelImages.TryGetValue( "rough", out var roughMap ) )
		{
			Set( "TextureRoughness", roughMap );
			Set( "g_flRoughnessScaleFactor", "1" );
		}
		else
		{
			var roughness = Math.Clamp( 1 - ScalarSmoothness, 0.02, 1 );
			Set( "TextureRoughness", MidGrey );
			Set( "g_flRoughnessScaleFactor", N( Math.Round( Math.Log( roughness ) / Math.Log( 0.5 ), 4 ) ) );
		}
		if ( channelImages.TryGetValue( "metal", out var metal ) )
		{
			text.AppendLine( "\tF_METALNESS_TEXTURE 1" );
			Set( "TextureMetalness", metal );
		}
		Set( "g_flMetalness", N( specularWorkflow ? 0 : Math.Clamp( Number( "_Metallic", 0 ), 0, 1 ) ) );
		// Unity keeps colors from earlier shaders: built-in shaders read _Color, URP and HDRP _BaseColor, so a material
		// switched between pipelines can carry both, and only its own shader's one applies.
		var builtinShader = (ShaderGuid ?? "").Equals( UnityKnownShaders.BuiltinGuid, StringComparison.OrdinalIgnoreCase );
		// A package shader's masked color is not a tint (see ConfigureShader).
		double[] Tint( string name ) => maskedColors.Contains( name ) ? null : Colors.GetValueOrDefault( name );
		var color = (builtinShader ? Tint( "_Color" ) : null) ?? Tint( "_BaseColor" ) ?? (colorProperty == "_Diffuse" ? Tint( "_MainColor" ) : null) ?? Tint( "_Color" );
		// Built-in particle shaders multiply by twice the tint color.
		if ( legacyParticle && Colors.TryGetValue( "_TintColor", out var particleTint ) ) color = particleTint.Select( c => Math.Min( 1, 2 * c ) ).ToArray();
		if ( color != null ) Set( "g_vColorTint", $"[{N( color[0] )} {N( color[1] )} {N( color[2] )} {N( color[3] )}]" );
		if ( channelImages.TryGetValue( "opacity", out var opacity ) ) Set( "TextureTranslucency", opacity );
		else if ( UsesAlpha ) Set( "TextureTranslucency", White );
		// Unity's opacity is the base color alpha times the color's alpha (glass is often an untextured color with low alpha).
		if ( UsesAlpha && color != null && color.Length > 3 && color[3] < 1 ) Set( "g_flOpacityScale", N( Math.Clamp( color[3], 0, 1 ) ) );
		if ( AlphaTest )
		{
			text.AppendLine( "\tF_ALPHA_TEST 1" );
			Set( "g_flAlphaTestReference", N( AlphaCutoff ) );
		}
		if ( TwoSided ) text.AppendLine( "\tF_RENDER_BACKFACES 1" );
		if ( Translucent ) text.AppendLine( "\tF_TRANSLUCENT 1" );
		if ( additive && Translucent ) text.AppendLine( "\tF_ADDITIVE_BLEND 1" );
		if ( unlit )
		{
			// Self-illumination scaled by the base color stands in for unlit shading.
			text.AppendLine( "\tF_SELF_ILLUM 1" );
			Set( "TextureSelfIllumMask", White );
			Set( "g_flSelfIllumAlbedoFactor", "1" );
			return text.AppendLine( "}" ).ToString();
		}
		var emission = Texture( resolve, "_EmissionMap", "_EmissiveColorMap" );
		// Unity multiplies the emission map (white when absent) by an HDR color; s&box takes a tint and a brightness scale.
		var emissionColor = Colors.GetValueOrDefault( "_EmissionColor" );
		var glow = emissionColor?.Take( 3 ).Max() ?? 0;
		// A known black emission color multiplies any map to nothing.
		if ( emission != null && (emissionColor == null || glow > 0) || emissionEnabled && glow > 0 )
		{
			text.AppendLine( "\tF_SELF_ILLUM 1" );
			Set( "TextureSelfIllumMask", emission ?? White );
			if ( glow > 0 )
			{
				var tint = emissionColor.Take( 3 ).Select( c => Math.Clamp( c / Math.Max( glow, 1 ), 0, 1 ) ).ToArray();
				Set( "g_vSelfIllumTint", $"[{N( tint[0] )} {N( tint[1] )} {N( tint[2] )} 1]" );
				// The shader clamps g_flSelfIllumScale to 1; brightness above that is g_flSelfIllumBrightness, in stops.
				if ( glow > 1 ) Set( "g_flSelfIllumBrightness", N( Math.Round( Math.Min( 10, Math.Log2( glow ) ), 4 ) ) );
			}
			// Unity adds emission on top of the surface; s&box multiplies it by the base color unless this is 0.
			Set( "g_flSelfIllumAlbedoFactor", "0" );
		}
		return text.AppendLine( "}" ).ToString();
	}

	public string ToTmat( Func<string, string> resolve )
	{
		// TerrainMaterial image fields are source image paths, not .vmat references.
		var values = new Dictionary<string, object>
		{
			["__version"] = 1,
			["AlbedoImage"] = "materials/default/default_color.tga",
			["NormalImage"] = "materials/default/default_normal.tga",
			["RoughnessImage"] = "materials/default/default_rough.tga",
			["AOImage"] = "materials/default/default_ao.tga",
			["HeightImage"] = "materials/default/default_height.tga"
		};
		void Set( string key, params string[] names )
		{
			var value = Texture( resolve, names );
			if ( value != null ) values[key] = value;
		}
		Set( "AlbedoImage", "_BaseMap", "_Diffuse", "_MainTex", "_Albedo", "_BaseColorMap" );
		Set( "NormalImage", "_BumpMap", "_Normal", "_NormalMap" );
		Set( "AOImage", "_OcclusionMap", "_Occlusion" );
		Set( "HeightImage", "_ParallaxMap", "_HeightMap" );
		foreach ( var (channel, field) in new[] { ("rough", "RoughnessImage"), ("ao", "AOImage"), ("height", "HeightImage") } )
			if ( channelImages.TryGetValue( channel, out var image ) ) values[field] = image;
		if ( terrainLayer )
		{
			// s&box repeats a terrain material every 32 units times UVScale; Unity repeats a layer every tile size in meters.
			if ( Numbers.TryGetValue( "_TileSize", out var tile ) ) values["UVScale"] = Math.Round( tile / 0.0254 / 32, 4 );
			if ( Numbers.TryGetValue( "_Metallic", out var metallic ) ) values["Metalness"] = metallic;
			if ( Numbers.TryGetValue( "_NormalScale", out var normal ) && Textures.ContainsKey( "_BumpMap" ) ) values["NormalStrength"] = normal;
		}
		return JsonSerializer.Serialize( values, new JsonSerializerOptions { WriteIndented = true } );
	}
}