Editor/MaterialTextureExporter.cs

Editor helper that exports material texture files when writing OBJ/MTL. It locates textures from Material or VMAT source, copies files into an output directory, and emits appropriate MTL lines or comments for each map.

File Access
using System.Text.RegularExpressions;

namespace Sandbox;

/// <summary>
/// Copies material texture source files next to an OBJ and returns MTL map lines.
/// </summary>
internal static class MaterialTextureExporter
{
	static readonly (string Param, string MtlKey, string Suffix, bool IsCommentOnly)[] TextureMaps =
	[
		( "TextureColor", "map_Kd", "color", false ),
		( "TextureNormal", "map_Bump", "normal", false ),
		( "TextureTranslucency", "map_d", "trans", false ),
		( "TextureRoughness", null, "rough", true ),
		( "TextureMetalness", null, "metal", true ),
		( "TextureAmbientOcclusion", null, "ao", true ),
	];

	static readonly Regex VmatTextureLine = new(
		@"^\s*(TextureColor|TextureNormal|TextureRoughness|TextureMetalness|TextureAmbientOcclusion|TextureTranslucency)\s+""([^""]+)""",
		RegexOptions.Compiled | RegexOptions.Multiline | RegexOptions.IgnoreCase );

	public static string WriteMapsAndCopyTextures( ObjWriter.MaterialSlot slot, string outputDirectory )
	{
		Directory.CreateDirectory( outputDirectory );

		var sb = new StringBuilder();
		var matBase = ObjWriter.SanitizeMtlName( Path.GetFileNameWithoutExtension( slot.Name ) );
		var material = slot.Material;

		if ( material is null )
			return string.Empty;

		var wroteAny = false;

		foreach ( var map in TextureMaps )
		{
			var texture = TryGetTexture( material, map.Param );
			if ( texture is null )
				continue;

			var copiedName = TryCopyTexture( texture, outputDirectory, $"{matBase}_{map.Suffix}" );
			if ( copiedName is null )
				continue;

			AppendMapLine( sb, map, copiedName );
			wroteAny = true;
		}

		// Runtime GetTexture often returns compiled .vtex with no easy source path.
		// Fall back to reading Texture* paths straight from the .vmat source.
		if ( !wroteAny || !HasMapKd( sb ) )
			wroteAny |= TryCopyFromVmatSource( material, matBase, outputDirectory, sb );

		if ( !wroteAny )
		{
			Log.Warning( $"[ModelExporter] No texture sources found for material '{slot.Name}' ({material.ResourcePath}). MTL will be color-only." );
		}

		return sb.ToString();
	}

	static Texture TryGetTexture( Material material, string param )
	{
		try
		{
			var texture = material.GetTexture( param );
			if ( texture is not null )
				return texture;
		}
		catch ( Exception e )
		{
			Log.Warning( $"[ModelExporter] GetTexture('{param}') failed on '{material.ResourcePath}': {e.Message}" );
		}

		try
		{
			return material.Attributes?.GetTexture( param );
		}
		catch
		{
			return null;
		}
	}

	static bool TryCopyFromVmatSource( Material material, string matBase, string outputDirectory, StringBuilder sb )
	{
		var vmatPath = ResolveVmatSourcePath( material );
		if ( vmatPath is null || !File.Exists( vmatPath ) )
			return false;

		string text;
		try
		{
			text = File.ReadAllText( vmatPath );
		}
		catch ( Exception e )
		{
			Log.Warning( $"[ModelExporter] Could not read vmat '{vmatPath}': {e.Message}" );
			return false;
		}

		var wrote = false;
		foreach ( Match match in VmatTextureLine.Matches( text ) )
		{
			var param = match.Groups[1].Value;
			var relative = match.Groups[2].Value.Replace( '\\', '/' );
			var map = TextureMaps.FirstOrDefault( m =>
				string.Equals( m.Param, param, StringComparison.OrdinalIgnoreCase ) );

			// Unknown Texture* keys still get copied as comments.
			var suffix = map.Param is not null ? map.Suffix : param.ToLowerInvariant();
			var mtlKey = map.Param is not null ? map.MtlKey : null;
			var commentOnly = map.Param is null || map.IsCommentOnly;

			// Skip if we already wrote this map key.
			if ( !commentOnly && !string.IsNullOrEmpty( mtlKey ) && sb.ToString().Contains( mtlKey + " ", StringComparison.Ordinal ) )
				continue;

			var copiedName = TryCopyContentRelativeFile( relative, outputDirectory, $"{matBase}_{suffix}" );
			if ( copiedName is null )
			{
				Log.Warning( $"[ModelExporter] VMAT references missing texture '{relative}' in '{vmatPath}'" );
				continue;
			}

			if ( commentOnly || string.IsNullOrEmpty( mtlKey ) )
				sb.AppendLine( $"# {param}: {copiedName}" );
			else
				sb.AppendLine( $"{mtlKey} {copiedName}" );

			wrote = true;
		}

		return wrote;
	}

	static string ResolveVmatSourcePath( Material material )
	{
		var resourcePath = material.ResourcePath;
		if ( string.IsNullOrWhiteSpace( resourcePath ) )
			return null;

		var asset = AssetSystem.FindByPath( resourcePath );
		if ( asset is not null )
		{
			var source = asset.GetSourceFile( true );
			if ( !string.IsNullOrWhiteSpace( source ) && File.Exists( source ) )
				return source;

			if ( !string.IsNullOrWhiteSpace( asset.AbsolutePath ) && File.Exists( asset.AbsolutePath ) )
				return asset.AbsolutePath;
		}

		return ResolveUnderAssets( resourcePath );
	}

	static string TryCopyTexture( Texture texture, string outputDirectory, string fileBase )
	{
		var resourcePath = texture.ResourcePath;
		if ( string.IsNullOrWhiteSpace( resourcePath ) )
			return null;

		var asset = AssetSystem.FindByPath( resourcePath );
		string sourcePath = null;

		if ( asset is not null )
		{
			sourcePath = asset.GetSourceFile( true );
			if ( string.IsNullOrWhiteSpace( sourcePath ) || !File.Exists( sourcePath ) )
				sourcePath = asset.AbsolutePath;
		}

		if ( string.IsNullOrWhiteSpace( sourcePath ) || !File.Exists( sourcePath ) )
			sourcePath = ResolveUnderAssets( resourcePath );

		// Compiled .vtex with no usable source — caller can fall back to vmat parse.
		if ( string.IsNullOrWhiteSpace( sourcePath ) || !File.Exists( sourcePath ) )
			return null;

		if ( Path.GetExtension( sourcePath ).Equals( ".vtex", StringComparison.OrdinalIgnoreCase ) )
			return null;

		return CopyToOutput( sourcePath, outputDirectory, fileBase );
	}

	static string TryCopyContentRelativeFile( string contentRelativePath, string outputDirectory, string fileBase )
	{
		var sourcePath = ResolveUnderAssets( contentRelativePath );
		if ( sourcePath is null || !File.Exists( sourcePath ) )
			return null;

		return CopyToOutput( sourcePath, outputDirectory, fileBase );
	}

	static string ResolveUnderAssets( string contentRelativePath )
	{
		try
		{
			var project = Project.Current;
			if ( project is null )
				return null;

			var assetsRoot = project.GetAssetsPath();
			if ( string.IsNullOrWhiteSpace( assetsRoot ) )
				return null;

			var candidate = Path.Combine( assetsRoot, contentRelativePath.Replace( '/', Path.DirectorySeparatorChar ) );
			return File.Exists( candidate ) ? candidate : null;
		}
		catch
		{
			return null;
		}
	}

	static string CopyToOutput( string sourcePath, string outputDirectory, string fileBase )
	{
		var ext = Path.GetExtension( sourcePath );
		if ( string.IsNullOrWhiteSpace( ext ) )
			ext = ".png";

		var destName = fileBase + ext.ToLowerInvariant();
		var destPath = Path.Combine( outputDirectory, destName );

		try
		{
			File.Copy( sourcePath, destPath, overwrite: true );
			return destName;
		}
		catch ( Exception e )
		{
			Log.Warning( $"[ModelExporter] Failed to copy '{sourcePath}' → '{destPath}': {e.Message}" );
			return null;
		}
	}

	static void AppendMapLine( StringBuilder sb, (string Param, string MtlKey, string Suffix, bool IsCommentOnly) map, string copiedName )
	{
		if ( map.IsCommentOnly || string.IsNullOrEmpty( map.MtlKey ) )
			sb.AppendLine( $"# {map.Param}: {copiedName}" );
		else
			sb.AppendLine( $"{map.MtlKey} {copiedName}" );
	}

	static bool HasMapKd( StringBuilder sb )
	{
		return sb.ToString().Contains( "map_Kd ", StringComparison.Ordinal );
	}
}