namespace Brutal.ShaderCApi;
///
/// Contains methods for inferring shader kind from file paths.
///
public static partial class ShaderC
{
///
/// Attempts to infer the shader kind from a file path's extension.
///
/// The file path to infer the shader kind from.
///
/// When this method returns , the inferred shader kind. When it returns
/// it is set to , which is a real stage
/// (), so callers must branch on the return value, not on
/// .
///
/// True if the extension was recognized, false otherwise.
public static bool TryInferShaderKind(ReadOnlySpan path, out ShaderKind kind)
{
// Path.GetExtension returns the extension including the leading '.', and ignores dots that
// appear in directory names. It is empty when there is no extension (including a trailing '.').
ReadOnlySpan extension = Path.GetExtension(path);
if (extension.Length <= 1)
{
kind = default;
return false;
}
extension = extension[1..]; // drop the leading '.'
// Lowercase into a small stack buffer; an extension longer than this is not one we recognise.
Span lowercased = stackalloc char[16];
if (extension.Length > lowercased.Length)
{
kind = default;
return false;
}
int written = extension.ToLowerInvariant(lowercased);
ReadOnlySpan lower = lowercased[..written];
// Single match table: a recognised extension yields its kind, anything else yields null so the
// caller can distinguish "no match" from the (zero-valued) VertexShader default.
ShaderKind? match = lower switch
{
"vert" => ShaderKind.VertexShader,
"frag" => ShaderKind.FragmentShader,
"comp" => ShaderKind.ComputeShader,
"geom" => ShaderKind.GeometryShader,
"tesc" => ShaderKind.TessControlShader,
"tese" => ShaderKind.TessEvaluationShader,
"mesh" => ShaderKind.MeshShader,
"task" => ShaderKind.TaskShader,
"rgen" => ShaderKind.RayGenShader,
"rmiss" => ShaderKind.MissShader,
"rchit" => ShaderKind.ClosestHitShader,
"rahit" => ShaderKind.AnyHitShader,
"rint" => ShaderKind.IntersectionShader,
"rcall" => ShaderKind.CallableShader,
_ => null,
};
kind = match ?? default;
return match.HasValue;
}
///
/// Infers the shader kind from a file path's extension.
///
/// The file path to infer the shader kind from.
/// The inferred shader kind.
/// Thrown if the extension is not recognized.
public static ShaderKind InferShaderKind(ReadOnlySpan path)
{
if (!TryInferShaderKind(path, out var kind))
{
throw new ArgumentException($"Could not infer ShaderKind from path '{path}'.", nameof(path));
}
return kind;
}
}