using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Brutal.Memory; using Brutal.Pointers.Extensions; namespace Brutal.ShaderCApi; public static partial class ShaderC { /// /// Default callbacks for the shader compiler. /// public static class Callbacks { // Guards against #include cycles by bounding nesting depth (shaderc increments depth per // nesting level). 200 is far above any realistic include tree, so a legitimate compile never // reaches it; a self- or mutually-recursive #include climbs to the limit and is reported as a // cycle instead of looping until the stack overflows. private const nuint MaxIncludeDepth = 200; /// /// Resolves an #include request by reading the requested file from disk relative to the /// requesting source's directory. /// /// Opaque user-data pointer passed through from the options (unused by this implementation). /// NUL-terminated UTF-8 C string naming the file being requested (the include path). /// The kind of inclusion request ( or ). /// NUL-terminated UTF-8 C string naming the source file that contains the #include directive. /// Include nesting depth; 1 indicates a top-level include from the root source. /// /// A pointer to a heap-allocated whose Content and /// SourceName buffers are also heap-allocated. The caller (shaderc) must invoke /// on the result when it is no longer needed. /// /// /// /// This method and form a matching allocator/deallocator pair: all /// allocations are performed with Mem.Alloc and must be freed by /// using Mem.Free. A custom resolver that replaces this implementation must honor the /// same contract. /// /// /// The returned and its buffers must remain valid until /// is called on it. Do not free or modify the result after returning it. /// /// /// Any exception thrown during resolution (e.g., ) is /// caught and surfaced as a shaderc include-failure result whose Content field /// contains the exception message. The exception does not propagate as a /// managed exception; include-resolution failures appear only in the compiler's error output. /// /// [UnmanagedCallersOnly(CallConvs = [typeof(CallConvCdecl)])] public static unsafe IncludeResult* Resolve( void* data, byte* source, IncludeType type, byte* requestingSource, nuint depth ) { // Allocate a new result var result = Mem.AllocZeroed(); try { ResolveInternal( ref result.Value, data, Utf8.GetNullTerminatedSpan(source), type, Utf8.GetNullTerminatedSpan(requestingSource), depth ); } catch (Exception ex) { // Free any previously allocated memory in Content (we are going to replace it) if (result.Value.Content != null) { Mem.Free(result.Value.Content); result.Value.Content = null; result.Value.ContentLength = ByteSize.Zero; } // Free and reset SourceName (API says it should be empty on failure) if (result.Value.SourceName != null) { Mem.Free(result.Value.SourceName); result.Value.SourceName = null; result.Value.SourceNameLength = ByteSize.Zero; } // Write the error message to Content var byteCount = Utf8.GetByteCount(ex.Message); var span = Mem.Alloc(byteCount); Utf8.GetBytes(ex.Message, span); result.Value.Content = span.AsPointer(); result.Value.ContentLength = ByteSize.Of(byteCount); } return result; } private static unsafe void ResolveInternal( ref IncludeResult result, void* data, ReadOnlySpan source, IncludeType type, ReadOnlySpan requestingSource, nuint depth ) { if (depth > MaxIncludeDepth) throw new InvalidOperationException( $"Include depth {depth} exceeded the maximum of {MaxIncludeDepth}; possible #include cycle." ); // Get the path to the include file, relative to the requesting source. // Decode the path once and reuse it for the error message and file open. var path = Utf8.Path.Combine(Utf8.Path.GetDirectoryName(requestingSource), source); var pathStr = Utf8.GetString(path); // Open directly instead of File.Exists + open, which would stat the file twice on every // include. A missing file surfaces as the framework's own FileNotFoundException / // DirectoryNotFoundException, which is caught by Resolve and reported as an include failure. using (var handle = File.OpenHandle(pathStr)) { // Allocate null-terminated storage for SourceName. // shaderc treats source_name as a C string and re-feeds it as requesting_source, // so the buffer must be null-terminated even though SourceNameLength stays path.Length. var copy = Mem.Alloc(path.Length + 1); path.CopyTo(copy); copy[path.Length] = 0; result.SourceName = copy.AsPointer(); result.SourceNameLength = ByteSize.Of(path.Length); // Read the include file into memory using RandomAccess to avoid the FileStream buffer. var length = RandomAccess.GetLength(handle); if (length > int.MaxValue) throw new IOException($"Include file is too large to read ({length} bytes): {pathStr}"); var dataSize = (int)length; var memory = Mem.Alloc(dataSize); result.Content = memory.AsPointer(); result.ContentLength = ByteSize.Of(dataSize); // RandomAccess.Read is permitted to return a short count, so loop until the buffer fills. Span destination = memory; var totalRead = 0; while (totalRead < dataSize) { var read = RandomAccess.Read(handle, destination[totalRead..], totalRead); if (read == 0) break; totalRead += read; } if (totalRead != dataSize) throw new IOException($"Failed to read expected {dataSize} bytes, read {totalRead} bytes instead."); } } /// /// Frees an previously returned by . /// /// Opaque user-data pointer passed through from the options (unused by this implementation). /// Pointer to the to release, or null (no-op). /// /// /// This method is the matching deallocator for : it frees the /// SourceName buffer, the Content buffer, and the /// struct itself, all previously allocated via Mem.Alloc. /// /// /// A custom resolver that replaces must provide a matching release /// callback that frees whatever its resolver allocated. Do not mix allocators (e.g., do not /// allocate in one callback and free in the other). /// /// [UnmanagedCallersOnly(CallConvs = [typeof(CallConvCdecl)])] public static unsafe void Release(void* data, IncludeResult* result) { if (result != null) { // UserData ownership belongs to whoever allocates it; do not free it here. Mem.Free(result->SourceName); Mem.Free(result->Content); Mem.Free(result); } } } }