//! GLSL declarations from Zig structs, so shaders and the code that feeds //! them share one definition: the Zig one. `Sketchbook.addGlslLayouts` builds a //! small generator around this file for the types it is given; each type //! says how it appears in GLSL with a `glsl` tag: //! //! pub const Viewport = extern struct { //! size: [2]f32, //! pad: [2]f32 = .{ 0, 0 }, //! pub const glsl = .{ .uniform = .{ .set = 1, .instance = "viewport" } }; //! }; //! //! becomes `Viewport.glsl`: //! //! layout(set = 1, binding = 0, std140) uniform Viewport { //! vec2 size; //! vec2 pad; //! } viewport; //! //! Tags: `.vertex` (one `layout(location = N) in` per field, in the order //! `abi.gpu.attributes` uses), `.{ .uniform = .{ .set, .binding = 0, //! .instance } }` (SDL_GPU's SPIR-V sets: 1 vertex, 3 fragment), `.plain` //! (a `struct`, for nesting). const std = @import("std"); /// `T`'s declaration, as GLSL source. pub fn source(comptime T: type, comptime name: []const u8) []const u8 { comptime { @setEvalBranchQuota(100_000); const tag = T.glsl; const s = @typeInfo(T).@"struct"; var out: []const u8 = "// Generated from the Zig struct " ++ @typeName(T) ++ "; do not edit.\n"; if (@TypeOf(tag) == @TypeOf(.enum_literal) and tag == .vertex) { for (s.field_names, s.field_types, 0..) |name_, F, i| out = out ++ std.fmt.comptimePrint("layout(location = {d}) in {s} {s};\n", .{ i, typeName(F, .vertex), name_ }); } else if (@TypeOf(tag) == @TypeOf(.enum_literal) and tag == .plain) { out = out ++ "struct " ++ name ++ " {\n" ++ members(T) ++ "};\n"; } else if (@hasField(@TypeOf(tag), "uniform")) { const u = tag.uniform; assertStd140(T); const binding = if (@hasField(@TypeOf(u), "binding")) u.binding else 0; out = out ++ std.fmt.comptimePrint("layout(set = {d}, binding = {d}, std140) uniform {s} {{\n", .{ u.set, binding, name }) ++ members(T) ++ "} " ++ u.instance ++ ";\n"; } else @compileError(@typeName(T) ++ ".glsl must be .vertex, .plain or .{ .uniform = ... }"); return out; } } fn members(comptime T: type) []const u8 { comptime { var out: []const u8 = ""; const s = @typeInfo(T).@"struct"; for (s.field_names, s.field_types) |name, F| { const array_of_composites = switch (@typeInfo(F)) { .array => |a| @typeInfo(a.child) == .array or @typeInfo(a.child) == .@"struct", else => false, }; out = out ++ if (array_of_composites) std.fmt.comptimePrint(" {s} {s}[{d}];\n", .{ typeName(@typeInfo(F).array.child, .uniform), name, @typeInfo(F).array.len }) else std.fmt.comptimePrint(" {s} {s};\n", .{ typeName(F, .uniform), name }); } return out; } } fn typeName(comptime T: type, comptime use: enum { vertex, uniform }) []const u8 { if (T == f32) return "float"; if (T == u32) return "uint"; if (T == i32) return "int"; if (use == .vertex and (T == [4]u8 or T == @Vector(4, u8))) return "vec4"; return switch (@typeInfo(T)) { .array => |a| vector(a.len, a.child), .vector => |v| vector(v.len, v.child), .@"struct" => @typeName(T)[if (std.mem.lastIndexOfScalar(u8, @typeName(T), '.')) |dot| dot + 1 else 0..], else => @compileError("no GLSL type for " ++ @typeName(T)), }; } fn vector(comptime len: usize, comptime child: type) []const u8 { const prefix = if (child == f32) "" else if (child == u32) "u" else if (child == i32) "i" else @compileError("no GLSL vector of " ++ @typeName(child)); return std.fmt.comptimePrint("{s}vec{d}", .{ prefix, len }); } /// The type at `path` (dot-separated declarations) inside `root`. pub fn resolve(comptime root: type, comptime path: []const u8) type { comptime { var t = root; var it = std.mem.tokenizeScalar(u8, path, '.'); while (it.next()) |name| t = @field(t, name); return t; } } /// Writes `.glsl` for each type path into `dir`. pub fn generate(comptime root: type, comptime paths: []const []const u8, io: std.Io, dir: std.Io.Dir) !void { inline for (paths) |path| { const T = resolve(root, path); const name = comptime path[if (std.mem.lastIndexOfScalar(u8, path, '.')) |dot| dot + 1 else 0..]; try dir.writeFile(io, .{ .sub_path = name ++ ".glsl", .data = comptime source(T, name) }); } } /// Fails to compile unless `U` lays out exactly as a std140 uniform block /// with the same members in GLSL: scalars at 4 bytes, `vec2` at 8, /// `vec3`/`vec4` at 16, arrays and nested structs at 16 with 16-byte strides. pub fn assertStd140(comptime U: type) void { comptime { if (@typeInfo(U).@"struct".layout != .@"extern") @compileError(@typeName(U) ++ " must be extern to be a uniform block"); const s = @typeInfo(U).@"struct"; for (s.field_names, s.field_types) |name, F| { const want = std140Align(F); if (@offsetOf(U, name) % want != 0) @compileError(std.fmt.comptimePrint("{s}.{s} sits at {d}; std140 wants a multiple of {d}", .{ @typeName(U), name, @offsetOf(U, name), want })); } if (@sizeOf(U) % 16 != 0) @compileError(@typeName(U) ++ " must be a multiple of 16 bytes"); } } fn std140Align(comptime T: type) usize { return switch (@typeInfo(T)) { .float, .int => 4, .bool => @compileError("GLSL bools are 4 bytes: use u32"), .vector => |v| if (v.len == 2) 8 else 16, .array => |a| blk: { if (@typeInfo(a.child) == .float or @typeInfo(a.child) == .int) { // `[2]f32` stands for a vec2, `[3]`/`[4]f32` for vec3/vec4. if (a.len == 2) break :blk 8; if (a.len == 3 or a.len == 4) break :blk 16; @compileError("std140 arrays of scalars have a 16-byte stride: use [N][4]f32"); } if (@sizeOf(a.child) % 16 != 0) @compileError("std140 array elements are 16-byte strided"); break :blk 16; }, .@"struct" => blk: { assertStd140(T); break :blk 16; }, else => @compileError("no std140 layout for " ++ @typeName(T)), }; } test "uniform blocks and vertex inputs from structs" { const Root = struct { pub const Paint = extern struct { color: [4]f32, size: [2]f32, pad: [2]f32, stops: [4][4]f32, pub const glsl = .{ .uniform = .{ .set = 3, .instance = "paint" } }; }; pub const Vertex = extern struct { position: [2]f32, tint: [4]u8, pub const glsl = .vertex; }; }; const paint = comptime source(resolve(Root, "Paint"), "Paint"); try std.testing.expect(std.mem.indexOf(u8, paint, "layout(set = 3, binding = 0, std140) uniform Paint {") != null); try std.testing.expect(std.mem.indexOf(u8, paint, " vec4 stops[4];") != null); try std.testing.expect(std.mem.indexOf(u8, paint, "} paint;") != null); const vertex = comptime source(Root.Vertex, "Vertex"); try std.testing.expect(std.mem.indexOf(u8, vertex, "layout(location = 1) in vec4 tint;") != null); }