diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 115ce13..2f42c41 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -35,3 +35,6 @@ jobs: - run: nim r tests/test_shady.nim - run: nim r tests/test_backends.nim - run: nim r tests/test_metal_resources.nim + - run: nim r tests/test_metal_parameters.nim + - run: nim r tests/test_metal_builtins.nim + - run: nim r tests/test_metal_inline.nim diff --git a/src/shady/backends/metal4.nim b/src/shady/backends/metal4.nim index 98cba05..6fa3d70 100644 --- a/src/shady/backends/metal4.nim +++ b/src/shady/backends/metal4.nim @@ -5,9 +5,12 @@ type UniformParam* = tuple[name, typ: string] TextureParam* = tuple[name, typ: string, binding: int, samplerBinding: int] -const metalHeader* = "#include \nusing namespace metal;\n" +const metalHeader* = """#include +using namespace metal; +""" proc metalTypeRename*(t: string): string = + ## Maps shader types to Metal, which has no double precision support. case t of "Mat2": "float2x2" of "Mat3": "float3x3" @@ -25,15 +28,18 @@ proc metalTypeRename*(t: string): string = of "UVec3": "uint3" of "UVec4": "uint4" - of "DVec2": "double2" - of "DVec3": "double3" - of "DVec4": "double4" + of "DVec2": "float2" + of "DVec3": "float3" + of "DVec4": "float4" + of "DMat2": "float2x2" + of "DMat3": "float3x3" + of "DMat4": "float4x4" of "int32": "int" of "uint32": "uint" of "float32": "float" - of "float64": "double" + of "float64": "float" of "ColorRGBX": "float4" of "SamplerBuffer": "texture_buffer" @@ -47,6 +53,7 @@ proc metalTypeRename*(t: string): string = else: t proc metalProcRename*(t: string): string = + ## Maps shader builtins to Metal equivalents. case t of "not": "!" of "and": "&&" @@ -64,10 +71,10 @@ proc metalProcRename*(t: string): string = of "ivec3": "int3" of "ivec4": "int4" of "mix": "mix" + of "inversesqrt": "rsqrt" of "atan": "atan2" of "dFdx": "dfdx" of "dFdy": "-dfdy" - of "fmod": "fmod" of "mod": "%" of "div": "/" else: t.replace("`", "_") @@ -95,11 +102,14 @@ proc metalTypeDefault*(t: string): string = else: "" proc metalAttribute*(name: string, index: int, isOutput: bool): string = + ## Returns the Metal attribute associated with a shader interface value. case name of "fragColor", "gl_FragColor": " [[color(0)]]" - of "gl_Position": + of "gl_Position", "gl_FragCoord": " [[position]]" + of "gl_FragDepth": + " [[depth(any)]]" of "gl_VertexID": " [[vertex_id]]" of "gl_InstanceID": @@ -157,41 +167,59 @@ proc metalResourceCall*( firstArgIsShadowSampler: bool, firstArgIsSamplerArray = false ): string = + ## Translates texture operations while preserving GLSL coordinate conventions. case name of "texture": if args.len != 2: return "" if firstArgIsShadowSampler: args[0] & ".sample_compare(" & args[0] & "Sampler, " & - args[1] & ".xy, " & args[1] & ".z)" + "(" & args[1] & ").xy, (" & args[1] & ").z)" + elif firstArgIsSamplerArray: + args[0] & ".sample(" & args[0] & "Sampler, (" & args[1] & + ").xy, uint((" & args[1] & ").z))" else: args[0] & ".sample(" & args[0] & "Sampler, " & args[1] & ")" of "textureLod": if args.len != 3: return "" - args[0] & ".sample(" & args[0] & "Sampler, " & args[1] & ", metal::level(" & args[2] & "))" + if firstArgIsSamplerArray: + args[0] & ".sample(" & args[0] & "Sampler, (" & args[1] & + ").xy, uint((" & args[1] & ").z), metal::level(" & args[2] & "))" + else: + args[0] & ".sample(" & args[0] & "Sampler, " & args[1] & + ", metal::level(" & args[2] & "))" of "textureGrad": if args.len != 4: return "" - let coordinates = - if firstArgIsSamplerArray: - "(" & args[1] & ").xy, uint((" & args[1] & ").z)" - else: - args[1] - args[0] & ".sample(" & args[0] & "Sampler, " & coordinates & - ", metal::gradient2d(" & args[2] & ", " & args[3] & "))" + if firstArgIsSamplerArray: + args[0] & ".sample(" & args[0] & "Sampler, (" & args[1] & + ").xy, uint((" & args[1] & ").z), metal::gradient2d(" & + args[2] & ", " & args[3] & "))" + else: + args[0] & ".sample(" & args[0] & "Sampler, " & args[1] & + ", metal::gradient2d(" & args[2] & ", " & args[3] & "))" of "textureSize": if args.len < 1: return "" if firstArgIsSamplerBuffer: - args[0] & ".get_width()" + "int(" & args[0] & ".get_width())" else: let level = if args.len >= 2: args[1] else: "0" - "int2(" & args[0] & ".get_width(" & level & "), " & - args[0] & ".get_height(" & level & "))" + if firstArgIsSamplerArray: + "int3(" & args[0] & ".get_width(" & level & "), " & + args[0] & ".get_height(" & level & "), " & + args[0] & ".get_array_size())" + else: + "int2(" & args[0] & ".get_width(" & level & "), " & + args[0] & ".get_height(" & level & "))" of "texelFetch": if args.len < 2: return "" if firstArgIsSamplerBuffer: - "float4(" & args[0] & ".read(uint(" & args[1] & ")), 0.0, 0.0, 0.0)" + args[0] & ".read(uint(" & args[1] & "))" else: let level = if args.len >= 3: args[2] else: "0" - args[0] & ".read(uint2(" & args[1] & "), uint(" & level & "))" + if firstArgIsSamplerArray: + args[0] & ".read(uint2((" & args[1] & ").xy), uint((" & + args[1] & ").z), uint(" & level & "))" + else: + args[0] & ".read(uint2(" & args[1] & "), uint(" & level & "))" of "imageLoad": if args.len != 2: return "" args[0] & "[" & args[1] & "]" @@ -213,7 +241,14 @@ proc hasParam(params: openArray[EntryParam], name: string): bool = return true proc isSpecialInput(p: EntryParam): bool = - p.name in ["gl_VertexID", "gl_InstanceID", "gl_FrontFacing"] + ## Identifies stage builtins passed separately from interpolated attributes. + p.name in [ + "gl_VertexID", "gl_InstanceID", "gl_FrontFacing", "gl_FragCoord" + ] + +proc isIntegerType(typ: string): bool = + ## Identifies values that must not be interpolated between vertices. + typ in ["int", "int2", "int3", "int4", "uint", "uint2", "uint3", "uint4"] proc outputLocals(params: openArray[EntryParam], level: int): string = let indent = repeat(" ", level) @@ -250,6 +285,8 @@ proc inputStruct( result.add p.name if stage == 1: result.add metalAttribute(p.name, i, false) + elif p.typ.isIntegerType(): + result.add " [[flat]]" result.add ";\n" result.add "};\n" @@ -305,13 +342,57 @@ proc resourceParams( texture.samplerBinding ) -proc emitMetalEntry*( +proc specialInputParams( params: openArray[EntryParam], bodyCode: string, + stage: int +): seq[string] = + ## Includes explicit builtin parameters and builtin globals used by the body. + let builtins = + if stage == 1: + @[("gl_VertexID", "uint"), ("gl_InstanceID", "uint")] + else: + @[("gl_FragCoord", "float4"), ("gl_FrontFacing", "bool")] + for (name, typ) in builtins: + if params.hasParam(name) or name in bodyCode: + var inputName = name + for param in params: + if param.name == name and param.typ != typ: + inputName = "shady_" & name + result.add typ & " " & inputName & metalAttribute(name, 0, false) + +proc specialInputLocals(params: openArray[EntryParam]): string = + ## Converts Metal's unsigned vertex identifiers to explicit parameter types. + for param in params: + if param.name in ["gl_VertexID", "gl_InstanceID"] and param.typ != "uint": + result.add " " & param.typ & " " & param.name & " = " & + param.typ & "(shady_" & param.name & ");\n" + +proc vertexReturn(outputs: openArray[EntryParam]): string = + ## Populates the stage output and converts OpenGL clip depth to Metal depth. + for param in outputs: + result.add " output." & metalOutputFieldName(param.name) & + " = " & param.name & ";\n" + if param.name == "gl_Position": + result.add " output.position.z = " & + "(output.position.z + output.position.w) * 0.5;\n" + result.add " return output;\n" + +proc emitMetalEntry*( + entryParams: openArray[EntryParam], + bodyCode: string, stage: int, uniforms: openArray[UniformParam] = [], textures: openArray[TextureParam] = [] ): string = + ## Builds native entry points with correctly attributed inputs and outputs. + var params = @entryParams + if stage == 1 and not params.hasParam("gl_Position") and + "gl_Position" in bodyCode: + params.add ("gl_Position", "float4", true) + if stage == 2 and not params.hasParam("gl_FragDepth") and + "gl_FragDepth" in bodyCode: + params.add ("gl_FragDepth", "float", true) case stage of 1: var outputs: seq[EntryParam] @@ -327,6 +408,8 @@ proc emitMetalEntry*( result.add " " result.add metalOutputFieldName(p.name) result.add metalAttribute(p.name, 0, true) + if p.typ.isIntegerType(): + result.add " [[flat]]" result.add ";\n" result.add "};\n\n" result.add inputStruct("VertexIn", params, stage) @@ -336,12 +419,9 @@ proc emitMetalEntry*( if params.inputParams().len > 0: result.addComma(first) result.add " VertexIn input [[stage_in]]" - if not params.hasParam("gl_VertexID") and "gl_VertexID" in bodyCode: + for builtin in specialInputParams(params, bodyCode, stage): result.addComma(first) - result.add " uint gl_VertexID [[vertex_id]]" - if not params.hasParam("gl_InstanceID") and "gl_InstanceID" in bodyCode: - result.addComma(first) - result.add " uint gl_InstanceID [[instance_id]]" + result.add " " & builtin for resource in resourceParams(uniforms, textures, stage): result.addComma(first) result.add " " @@ -351,19 +431,12 @@ proc emitMetalEntry*( result.add ") {\n" result.add " VertexOut output;\n" result.add " output.pointSize = 1.0;\n" + result.add specialInputLocals(params) result.add inputLocals(params, "input", 1) result.add outputLocals(params, 1) - result.add bodyCode - for p in outputs: - result.add " output." - result.add metalOutputFieldName(p.name) - result.add " = " - result.add p.name - result.add ";\n" - if p.name == "gl_Position": - result.add " output.position.z = " - result.add "(output.position.z + output.position.w) * 0.5;\n" - result.add " return output;\n" + let epilogue = vertexReturn(outputs) + result.add bodyCode.replace("return;", "{\n" & epilogue & " }") + result.add epilogue result.add "}\n" of 2: @@ -382,9 +455,16 @@ proc emitMetalEntry*( "void" if outputs.len > 1: result.add "struct FragmentOut {\n" - for i, param in outputs: - result.add " " & param.typ & " " & param.name & - " [[color(" & $i & ")]];\n" + var colorIndex = 0 + for param in outputs: + let attribute = + if param.name == "gl_FragDepth": + metalAttribute(param.name, 0, true) + else: + " [[color(" & $colorIndex & ")]]" + result.add " " & param.typ & " " & param.name & attribute & ";\n" + if param.name != "gl_FragDepth": + inc colorIndex result.add "};\n" var names: seq[string] for param in outputs: @@ -400,16 +480,19 @@ proc emitMetalEntry*( if params.inputParams().len > 0: result.addComma(first) result.add " FragmentIn input [[stage_in]]" - if not params.hasParam("gl_FrontFacing") and "gl_FrontFacing" in bodyCode: + for builtin in specialInputParams(params, bodyCode, stage): result.addComma(first) - result.add " bool gl_FrontFacing [[front_facing]]" + result.add " " & builtin for resource in resourceParams(uniforms, textures, stage): result.addComma(first) result.add " " result.add resource if not first: result.add "\n" - result.add ") {\n" + result.add ")" + if outputs.len == 1 and outputs[0].name == "gl_FragDepth": + result.add " [[depth(any)]]" + result.add " {\n" result.add inputLocals(params, "input", 1) result.add outputLocals(params, 1) result.add bodyCode.replace("return;", diff --git a/src/shady/backends/shared.nim b/src/shady/backends/shared.nim index bbaf492..25bae75 100644 --- a/src/shady/backends/shared.nim +++ b/src/shady/backends/shared.nim @@ -33,6 +33,8 @@ const var useResult {.compiletime.}: bool var shaderTarget* {.compiletime.}: ShaderTarget var shaderStage* {.compiletime.}: ShaderStage +var metalMatrixConversions {.compiletime.}: Table[string, string] +var metalInlineDeclarations {.compiletime.}: seq[string] const shaderSamplerTypes = [ "Sampler2d", "SamplerCube", "Sampler2dShadow", "USampler2d", @@ -103,9 +105,18 @@ proc typeString(n: NimNode): string = of "GVec2[float32]": typeRename("Vec2") of "GVec3[float32]": typeRename("Vec3") of "GVec4[float32]": typeRename("Vec4") - of "GMat2[float64]": (if isGlsl(): "dmat2" else: "double2x2") - of "GMat3[float64]": (if isGlsl(): "dmat3" else: "double3x3") - of "GMat4[float64]": (if isGlsl(): "dmat4" else: "double4x4") + of "GMat2[float64]": + if isMetal(): typeRename("DMat2") + elif isGlsl(): "dmat2" + else: "double2x2" + of "GMat3[float64]": + if isMetal(): typeRename("DMat3") + elif isGlsl(): "dmat3" + else: "double3x3" + of "GMat4[float64]": + if isMetal(): typeRename("DMat4") + elif isGlsl(): "dmat4" + else: "double4x4" of "GVec2[float64]": typeRename("DVec2") of "GVec3[float64]": typeRename("DVec3") of "GVec4[float64]": typeRename("DVec4") @@ -327,6 +338,92 @@ proc isSamplerArrayExpr(n: NimNode): bool = proc codeExpr(n: NimNode): string = n.toCode(result) +proc isMetalInlineValue(n: NimNode): bool = + ## Identifies values that can be repeated without evaluating any calls. + case n.kind + of nnkSym, nnkIdent, nnkCharLit .. nnkUInt64Lit, + nnkFloatLit .. nnkFloat128Lit: + true + of nnkDotExpr, nnkHiddenDeref, nnkHiddenAddr: + n[0].isMetalInlineValue() + of nnkHiddenStdConv, nnkHiddenSubConv, nnkConv, nnkCast: + n[^1].isMetalInlineValue() + else: + false + +proc metalInlineArguments( + n: NimNode, + firstArg: int, + args: var seq[string] +): string = + ## Snapshots arguments at the expression site when expansion repeats values. + var needsTemporaries = false + for i in firstArg ..< n.len: + if not n[i].isMetalInlineValue(): + needsTemporaries = true + if not needsTemporaries: + return + for i in firstArg ..< n.len: + # Nim identifiers cannot start with an underscore, avoiding user collisions. + let name = "_shadyValue" & $metalInlineDeclarations.len + var typ = n[i].getTypeInst() + if typ.kind == nnkVarTy: + typ = typ[0] + metalInlineDeclarations.add " " & typeString(typ) & " " & name & ";\n" + result.add name & " = (" & args[i - 1] & "), " + args[i - 1] = name + +proc emitMetalModulo(n: NimNode, res: var string) = + ## Emits GLSL floor-based modulo without a shader helper function. + var args = @[n[1].codeExpr(), n[2].codeExpr()] + let prefix = metalInlineArguments(n, 1, args) + res.add "(" & prefix & "(" & args[0] & ") - (" & args[1] & + ") * floor((" & args[0] & ") / (" & args[1] & ")))" + +proc metalInlineBody(bodyCode: string): string = + ## Declares temporaries locally without hoisting expression evaluation. + for declaration in metalInlineDeclarations: + result.add declaration + result.add bodyCode + metalInlineDeclarations.setLen(0) + +proc metalMatrixSize(typ: string): int = + ## Returns the dimension of a native Metal matrix type. + case typ + of "float2x2": 2 + of "float3x3": 3 + of "float4x4": 4 + else: 0 + +proc emitMetalMatrixCast(n: NimNode, res: var string): bool = + ## Narrows matrices by columns while evaluating the source expression once. + if not isMetal() or n.len != 2: + return false + let + targetType = typeString(n.getTypeInst()) + targetSize = metalMatrixSize(targetType) + if targetSize == 0: + return false + let + sourceType = typeString(n[1].getTypeInst()) + sourceSize = metalMatrixSize(sourceType) + if sourceSize <= targetSize: + return false + let name = "shadyMat" & $targetSize & "FromMat" & $sourceSize + if name notin metalMatrixConversions: + var body = "inline " & targetType & " " & name & "(" & sourceType & + " value) {\n return " & targetType & "(" + for column in 0 ..< targetSize: + if column > 0: + body.add ", " + body.add "value[" & $column & "]." & "xyzw"[0 ..< targetSize] + body.add ");\n}\n" + metalMatrixConversions[name] = body + res.add name & "(" + n[1].toCode(res) + res.add ")" + true + proc emitBackendCall(n: NimNode, res: var string): bool = ## Builtin resource operations are where the shader languages differ most. if isGlsl() or n.kind notin {nnkCall, nnkCommand}: @@ -342,6 +439,17 @@ proc emitBackendCall(n: NimNode, res: var string): bool = for i in 1 ..< n.len: args.add n[i].codeExpr() + var prefix = "" + if isMetal() and n.len > 2: + let repeatsArgument = + (n[1].isSamplerArrayExpr and name in [ + "texture", "textureLod", "textureGrad", "texelFetch" + ]) or + (n[1].isShadowSamplerExpr and name == "texture") or + (name == "textureSize" and not n[1].isSamplerBufferExpr) + if repeatsArgument: + prefix = metalInlineArguments(n, 2, args) + let call = if isHlsl(): hlslResourceCall( @@ -360,7 +468,10 @@ proc emitBackendCall(n: NimNode, res: var string): bool = ) if call.len == 0: return false - res.add call + if prefix.len > 0: + res.add "(" & prefix & call & ")" + else: + res.add call return true proc toCode(n: NimNode, res: var string, level = 0) = @@ -377,6 +488,9 @@ proc toCode(n: NimNode, res: var string, level = 0) = of nnkInfix: if n[0].repr in ["mod"] and not isIntegerType(n[1].getType().repr): + if isMetal(): + n.emitMetalModulo(res) + return # In Nim float mod and integer made are same thing. # In GLSL mod(float, float) is a function while % is for integers. if isGlsl(): @@ -459,6 +573,9 @@ proc toCode(n: NimNode, res: var string, level = 0) = n[0].toCode(res) of nnkCall, nnkCommand: + if isMetal() and n[0].strVal == "fmod" and n.len == 3: + n.emitMetalModulo(res) + return if n[0].strVal == "discardFragment": # Special case for discarding the fragment. # Because both Nim discard and GLSL discard are keywords that do different things. @@ -486,6 +603,9 @@ proc toCode(n: NimNode, res: var string, level = 0) = if n.emitBackendCall(res): return var procName = procRename(n[0].strVal) + if isMetal() and metalMatrixSize(procName) > 0 and + n.emitMetalMatrixCast(res): + return if isHlsl() and n.len == 2 and procName in [ "float2", "float3", "float4", "int2", "int3", "int4", "uint2", "uint3", "uint4"] and not n[1].getTypeInst.repr.isVectorTypeName(): @@ -623,6 +743,8 @@ proc toCode(n: NimNode, res: var string, level = 0) = # res.add ")" of nnkConv: + if n.emitMetalMatrixCast(res): + return res.add typeRename(n[0].strVal) res.add "(" n[1].toCode(res) @@ -880,6 +1002,9 @@ proc gatherEntryParams(formalParams: NimNode): seq[EntryParam] = for paramDefs in formalParams: if paramDefs.kind == nnkIdentDefs: let typeNode = paramDefs[^2] + if not isHlsl() and typeNode.kind == nnkBracketExpr and + typeNode[0].repr == "Uniform": + continue for i in 0 ..< paramDefs.len - 2: let param = paramDefs[i] if typeNode.kind == nnkVarTy: @@ -920,7 +1045,10 @@ proc emitBackendEntry( var bodyCode = "" let oldUseResult = useResult useResult = false + metalInlineDeclarations.setLen(0) body.toCodeStmts(bodyCode, 1) + if isMetal(): + bodyCode = metalInlineBody(bodyCode) useResult = oldUseResult let stage = resolvedStage(params).stageId() if isHlsl(): @@ -1065,6 +1193,7 @@ proc procDef(topLevelNode: NimNode): string = var procName = "" var paramsStr = "" var returnType = "void" + metalInlineDeclarations.setLen(0) assert topLevelNode.kind in {nnkFuncDef, nnkProcDef} for n in topLevelNode: @@ -1115,7 +1244,14 @@ proc procDef(topLevelNode: NimNode): string = result.addIndent(1) result.add returnType result.add " result;" - n.toCodeStmts(result, 1) + if isMetal(): + if useResult: + result.add "\n" + var bodyCode = "" + n.toCodeStmts(bodyCode, 1) + result.add metalInlineBody(bodyCode) + else: + n.toCodeStmts(result, 1) if useResult: if "return result" notin result[^20..^1]: result.addIndent(1) @@ -1162,6 +1298,42 @@ proc gatherTypes( def.add "};" types[name] = def +proc gatherMetalEntryUniforms( + topLevelNode: NimNode, + types: var Table[string, string], + uniforms: var seq[metal4.UniformParam], + uniformNames: var Table[string, bool], + textures: var seq[metal4.TextureParam], + textureNames: var Table[string, int] +) = + ## Binds uniform entry parameters through the same resources as globals. + for n in topLevelNode: + if n.kind != nnkFormalParams: + continue + for paramDefs in n: + if paramDefs.kind != nnkIdentDefs: + continue + let typeNode = paramDefs[^2] + if typeNode.kind != nnkBracketExpr or typeNode[0].repr != "Uniform": + continue + gatherTypes(typeNode[1], types) + let (typ, arraySuffix) = splitArrayType(typeNode[1]) + for i in 0 ..< paramDefs.len - 2: + let name = procRename(paramDefs[i].strVal) + if typeNode[1].repr in shaderSamplerTypes: + if name notin textureNames: + let binding = textures.len + textureNames[name] = binding + textures.add ( + name: name, + typ: typ, + binding: binding, + samplerBinding: binding + ) + elif name notin uniformNames: + uniformNames[name] = true + uniforms.add (name: name & arraySuffix, typ: typ) + proc gatherFunction( topLevelNode: NimNode, functions: var Table[string, string], @@ -1374,6 +1546,7 @@ proc gatherFunction( proc toGLSLInner*(s: NimNode, version, extra: string): string = var code: string + metalMatrixConversions.clear() # Add shader header stuff. if isGlsl(): @@ -1403,6 +1576,15 @@ proc toGLSLInner*(s: NimNode, version, extra: string): string = var metalUniformNames: Table[string, bool] var metalTextures: seq[metal4.TextureParam] var metalTextureNames: Table[string, int] + if isMetal(): + gatherMetalEntryUniforms( + n, + types, + metalUniforms, + metalUniformNames, + metalTextures, + metalTextureNames + ) gatherFunction( n, functions, @@ -1469,6 +1651,9 @@ proc toGLSLInner*(s: NimNode, version, extra: string): string = # Put functions definition (just name and types part). code.addGap() + for name, conversion in metalMatrixConversions: + code.add conversion + code.add "\n" for k, v in functions: var funCode = v.split(" {")[0] funCode = funCode diff --git a/tests/test_backends.nim b/tests/test_backends.nim index 08b68c3..0105aa6 100644 --- a/tests/test_backends.nim +++ b/tests/test_backends.nim @@ -29,6 +29,8 @@ block: doAssert "fragment float4 fragmentMain()" in msl doAssert "float4 fragColor = float4(0.0, 0.0, 0.0, 0.0);" in msl doAssert "return fragColor;" in msl + doAssert "shadyMod" notin msl and "shadyArray" notin msl + doAssert "template<" notin msl block: proc fragmentDepth( @@ -227,7 +229,7 @@ block: let msl = toMSL(sampledShadow, shaderFragment) doAssert "depth2d shadowMap [[texture(0)]]" in msl - doAssert "shadowMap.sample_compare(shadowMapSampler, uvz.xy, uvz.z)" in msl + doAssert "sample_compare(shadowMapSampler, (uvz).xy, (uvz).z)" in msl block: var atlas: Uniform[Sampler2d] @@ -424,8 +426,9 @@ block: hlsl = toHLSL(layerGradient, shaderFragment) msl = toMSL(layerGradient, shaderFragment) doAssert "layers.SampleGrad(layersSampler, uvw," in hlsl - doAssert "layers.sample(layersSampler, (uvw).xy, uint((uvw).z)," in msl + doAssert "layers.sample(layersSampler," in msl doAssert "metal::gradient2d(" in msl + doAssert "shadyArray" notin msl block: type ShapeData = object diff --git a/tests/test_metal_builtins.nim b/tests/test_metal_builtins.nim new file mode 100644 index 0000000..2585bf1 --- /dev/null +++ b/tests/test_metal_builtins.nim @@ -0,0 +1,116 @@ +import std/strutils, shady, vmath + +var + layers: Uniform[Sampler2dArray] + data: Uniform[SamplerBuffer] + +proc texture(s: Uniform[Sampler2dArray], uvw: Vec3): Vec4 = + ## Provides the CPU signature for an array texture sample. + vec4(0.0'f) + +proc textureLod(s: Uniform[Sampler2dArray], uvw: Vec3, lod: float32): Vec4 = + ## Provides the CPU signature for an array texture sample at a fixed LOD. + vec4(0.0'f) + +proc texelFetch(s: Uniform[Sampler2dArray], uvw: IVec3, lod: int): Vec4 = + ## Provides the CPU signature for an array texture texel read. + vec4(0.0'f) + +proc textureSize(s: Uniform[Sampler2dArray], lod: int): IVec3 = + ## Provides the CPU signature for all three array texture dimensions. + ivec3(1) + +proc vertex( + gl_VertexID: int32, + gl_Position: var Vec4, + identifier: var int32 +) = + ## Exercises an explicit vertex builtin, integer varying, and early exit. + identifier = gl_VertexID + gl_Position = vec4(float32(gl_VertexID), 0.0'f, 0.0'f, 1.0'f) + if gl_VertexID == 0: + return + gl_Position.x = -1.0'f + +proc fragment( + gl_FragCoord: Vec4, + gl_FrontFacing: bool, + identifier: int32, + gl_FragDepth: var float32, + fragColor: var Vec4 +) = + ## Exercises position, facing, depth, float promotion, and negative modulo. + let + promoted = float64(gl_FragCoord.x) * 0.1 + wrapped = float32(promoted) mod 1.0'f + inverse = inversesqrt(gl_FragCoord.w) + gl_FragDepth = gl_FragCoord.z * 0.5'f + fragColor = vec4(wrapped, inverse, float32(identifier), 1.0'f) + if not gl_FrontFacing: + return + fragColor.z = 0.0'f + +proc globalFragment(fragColor: var Vec4) = + ## Exercises builtin variables referenced without entry parameters. + gl_FragDepth = gl_FragCoord.z + fragColor = gl_FragCoord + +proc sampled(uv: Vec2, fragColor: var Vec4) = + ## Exercises array sampling, explicit LOD, dimensions, and buffer reads. + let + uvw = vec3(uv, 1.0'f) + size = textureSize(layers, 0) + fragColor = texture(layers, uvw) + textureLod(layers, uvw, 0.0'f) + + texelFetch(layers, ivec3(size.x - 1, 0, 0), 0) + texelFetch(data, 0) + +const + Vertex = toShader(vertex, metalMSL, shaderVertex) + Fragment = toShader(fragment, metalMSL, shaderFragment) + GlobalFragment = toShader(globalFragment, metalMSL, shaderFragment) + Sampled = toShader(sampled, metalMSL, shaderFragment) + +doAssert "uint shady_gl_VertexID [[vertex_id]]" in Vertex +doAssert "int gl_VertexID = int(shady_gl_VertexID);" in Vertex +doAssert "return;" notin Vertex +doAssert Vertex.count("output.position.z =") == 2 +doAssert "int identifier [[flat]]" in Vertex +doAssert "int identifier [[flat]]" in Fragment +for source in [Fragment, GlobalFragment]: + doAssert "float4 gl_FragCoord [[position]]" in source + doAssert "float gl_FragDepth [[depth(any)]]" in source + doAssert "float4 fragColor [[color(0)]]" in source + doAssert "[[color(1)]]" notin source +doAssert "bool gl_FrontFacing [[front_facing]]" in Fragment +doAssert "double" notin Fragment +doAssert "floor(" in Fragment and "rsqrt(" in Fragment +doAssert "layers.sample(layersSampler," in Sampled +doAssert "layers.read(uint2(" in Sampled +for source in [Vertex, Fragment, GlobalFragment, Sampled]: + doAssert "shadyMod" notin source + doAssert "shadyArray" notin source +doAssert "get_array_size()" in Sampled +doAssert "data.read(uint(0))" in Sampled + +when defined(macosx): + import metal4 + let device = MTLCreateSystemDefaultDevice() + var + libraries: seq[MTLLibrary] + error: NSError + for source in [Vertex, Fragment, GlobalFragment, Sampled]: + error = 0.NSError + let library = device.newLibraryWithSource(@source, 0.ID, error.addr) + doAssert not library.isNil, "Generated Metal builtins failed: " & $error + libraries.add(library) + let descriptor = MTLRenderPipelineDescriptor.alloc().init() + descriptor.setVertexFunction(libraries[0].newFunctionWithName(@"vertexMain")) + descriptor.setFragmentFunction(libraries[1].newFunctionWithName(@"fragmentMain")) + descriptor.colorAttachments().objectAtIndexedSubscript(0). + setPixelFormat(MTLPixelFormatRGBA16Float) + descriptor.setDepthAttachmentPixelFormat(MTLPixelFormatDepth32Float) + error = 0.NSError + let pipeline = device.newRenderPipelineStateWithDescriptor(descriptor, error.addr) + doAssert not pipeline.isNil, "Generated Metal stage interface failed: " & $error + echo "Metal builtin, texture, numeric, and stage interface regressions passed" +else: + echo "Metal builtin generation passed; GPU compiler requires macOS" diff --git a/tests/test_metal_inline.nim b/tests/test_metal_inline.nim new file mode 100644 index 0000000..07fb7d5 --- /dev/null +++ b/tests/test_metal_inline.nim @@ -0,0 +1,322 @@ +import std/strutils, shady, vmath + +var + layers: Uniform[Sampler2dArray] + shadowMap: Uniform[Sampler2dShadow] + +proc texture(image: Uniform[Sampler2dArray], coordinate: Vec3): Vec4 = + ## Provides the CPU signature for an array texture sample. + vec4(0.0'f) + +proc textureLod( + image: Uniform[Sampler2dArray], coordinate: Vec3, lod: float32 +): Vec4 = + ## Provides the CPU signature for an explicit array texture LOD. + vec4(0.0'f) + +proc texelFetch( + image: Uniform[Sampler2dArray], coordinate: IVec3, lod: int +): Vec4 = + ## Provides the CPU signature for an array texture texel read. + vec4(0.0'f) + +proc textureSize(image: Uniform[Sampler2dArray], lod: int): IVec3 = + ## Provides the CPU signature for an array texture's three dimensions. + ivec3(1) + +proc countedValue(calls: var int32, value: float32): float32 = + ## Counts each evaluation of a modulo operand. + calls += 1 + result = value + +proc countedCoordinate(calls: var int32): Vec3 = + ## Counts each evaluation of a coordinate split into UV and array layer. + calls += 1 + result = vec3(0.5'f, 0.5'f, 1.0'f) + +proc countedTexel(calls: var int32): IVec3 = + ## Counts each evaluation of an integer coordinate split into two parts. + calls += 1 + result = ivec3(0, 0, 1) + +proc countedLod(calls: var int32): int = + ## Counts each LOD evaluation shared by width and height queries. + calls += 1 + result = 0 + +proc mutateValue(value: var float32): float32 = + ## Mutates a preceding argument after its value should have been captured. + value = 9.0'f + result = 1.0'f + +proc wrappedValue(calls: var int32): float32 = + ## Exercises inline lowering inside an ordinary helper function. + fmod(countedValue(calls, -1.25'f), 1.0'f) + +proc vertex(gl_VertexID: int32, gl_Position: var Vec4) = + ## Covers a one-pixel render target without vertex buffers. + gl_Position = vec4(-1.0'f, -1.0'f, 0.0'f, 1.0'f) + if gl_VertexID == 1: + gl_Position.x = 3.0'f + if gl_VertexID == 2: + gl_Position.y = 3.0'f + +proc scalarModulo(fragColor: var Vec4) = + ## Covers negative dividends, negative divisors, and infix modulo. + fragColor = vec4( + fmod(-1.25'f, 1.0'f), + fmod(1.25'f, -1.0'f), + -1.25'f mod 1.0'f, + 1.25'f mod -1.0'f + ) + +proc vectorModulo(fragColor: var Vec4) = + ## Covers vector and scalar divisors with mixed signs. + let + vector = fmod( + vec4(-1.25'f, 1.25'f, -2.5'f, 2.5'f), + vec4(1.0'f, -1.0'f, 2.0'f, -2.0'f) + ) + scalar = fmod(vec3(-1.25'f, 1.25'f, 2.5'f), 1.0'f) + fragColor = vec4(vector.x, vector.y, vector.z, scalar.x) + +proc countedModulo(fragColor: var Vec4) = + ## Requires both operands of each modulo expression to execute once. + var calls = 0'i32 + let + call = fmod(countedValue(calls, -1.25'f), countedValue(calls, 1.0'f)) + infix = countedValue(calls, 1.25'f) mod countedValue(calls, -1.0'f) + fragColor = vec4(call, infix, float32(calls), 1.0'f) + +proc expressionFlow(fragColor: var Vec4) = + ## Preserves short circuits, ternary branches, and loop condition timing. + var calls = 0'i32 + if calls < 0 and fmod(countedValue(calls, -1.25'f), 1.0'f) > 0.0'f: + calls = 99 + let selected = + if calls == 0: + fmod(countedValue(calls, -1.25'f), 1.0'f) + else: + fmod(countedValue(calls, -1.5'f), 1.0'f) + var iterations = 0'i32 + while fmod(countedValue(calls, float32(iterations)), 3.0'f) < 2.0'f: + iterations += 1 + let wrapped = wrappedValue(calls) + fragColor = vec4(selected, float32(calls), float32(iterations), wrapped) + +proc nestedModulo(fragColor: var Vec4) = + ## Preserves nested evaluation and captures a value before later mutation. + var + calls = 0'i32 + value = -1.25'f + let + snapshot = fmod(value, mutateValue(value)) + nested = fmod( + countedValue(calls, -3.25'f), + fmod(countedValue(calls, 2.0'f), countedValue(calls, 1.25'f)) + ) + fragColor = vec4(snapshot, nested, float32(calls), value) + +proc sampled(fragColor: var Vec4) = + ## Samples one array layer with one coordinate evaluation. + var calls = 0'i32 + let color = texture(layers, countedCoordinate(calls)) + fragColor = vec4(color.x, color.y, color.z, float32(calls)) + +proc sampledLod(fragColor: var Vec4) = + ## Samples an explicit LOD with one coordinate evaluation. + var calls = 0'i32 + let color = textureLod(layers, countedCoordinate(calls), 0.0'f) + fragColor = vec4(color.x, color.y, color.z, float32(calls)) + +proc sampledGradient(fragColor: var Vec4) = + ## Samples explicit gradients with one coordinate evaluation. + var calls = 0'i32 + let color = textureGrad( + layers, countedCoordinate(calls), vec2(0.0'f), vec2(0.0'f) + ) + fragColor = vec4(color.x, color.y, color.z, float32(calls)) + +proc fetched(fragColor: var Vec4) = + ## Reads an array texel with one coordinate evaluation. + var calls = 0'i32 + let color = texelFetch(layers, countedTexel(calls), 0) + fragColor = vec4(color.x, color.y, color.z, float32(calls)) + +proc sized(fragColor: var Vec4) = + ## Queries all array dimensions with one LOD expression evaluation. + var calls = 0'i32 + let dimensions = textureSize(layers, countedLod(calls)) + fragColor = vec4(vec3(dimensions), float32(calls)) + +proc shadowed(fragColor: var Vec4) = + ## Splits one shadow coordinate into UV and comparison depth. + var calls = 0'i32 + let value = texture(shadowMap, countedCoordinate(calls)) + fragColor = vec4(value, value, value, float32(calls)) + +const + Vertex = toMSL(vertex, shaderVertex) + ScalarModulo = toMSL(scalarModulo, shaderFragment) + VectorModulo = toMSL(vectorModulo, shaderFragment) + CountedModulo = toMSL(countedModulo, shaderFragment) + ExpressionFlow = toMSL(expressionFlow, shaderFragment) + NestedModulo = toMSL(nestedModulo, shaderFragment) + Sampled = toMSL(sampled, shaderFragment) + SampledLod = toMSL(sampledLod, shaderFragment) + SampledGradient = toMSL(sampledGradient, shaderFragment) + Fetched = toMSL(fetched, shaderFragment) + Sized = toMSL(sized, shaderFragment) + Shadowed = toMSL(shadowed, shaderFragment) + Sources = [ + ScalarModulo, VectorModulo, CountedModulo, ExpressionFlow, NestedModulo, + Sampled, SampledLod, SampledGradient, Fetched, Sized + ] + Expected = [ + [0.75'f, -0.75'f, 0.75'f, -0.75'f], + [0.75'f, -0.75'f, 1.5'f, 0.75'f], + [0.75'f, -0.75'f, 4.0'f, 1.0'f], + [0.75'f, 5.0'f, 2.0'f, 0.75'f], + [0.75'f, 0.5'f, 3.0'f, 9.0'f], + [0.25'f, 0.5'f, 0.75'f, 1.0'f], + [0.25'f, 0.5'f, 0.75'f, 1.0'f], + [0.25'f, 0.5'f, 0.75'f, 1.0'f], + [0.25'f, 0.5'f, 0.75'f, 1.0'f], + [1.0'f, 1.0'f, 2.0'f, 1.0'f] + ] + +for source in Sources: + doAssert "shadyMod" notin source and "shadyArray" notin source + doAssert "template<" notin source +for source in [ScalarModulo, VectorModulo, CountedModulo]: + doAssert "floor(" in source + doAssert "fmod(" notin source +for source in [Sampled, SampledLod, SampledGradient]: + doAssert "layers.sample(layersSampler," in source +doAssert "level(" in SampledLod +doAssert "gradient2d(" in SampledGradient +doAssert "layers.read(uint2(" in Fetched +doAssert "shadowMap.sample_compare(shadowMapSampler," in Shadowed +doAssert Shadowed.count("countedCoordinate(calls)") == 1 +doAssert "layers.get_width(" in Sized +doAssert Sized.count("countedLod(calls)") == 1 +for source in [ + toShader(countedModulo, glsl4Desktop, shaderFragment), + toShader(countedModulo, glsl3WebGL, shaderFragment) +]: + doAssert "mod(countedValue(calls," in source + doAssert "shadyMod" notin source +for source in [ + toShader(sampledGradient, glsl4Desktop, shaderFragment), + toShader(sampledGradient, glsl3WebGL, shaderFragment) +]: + doAssert "textureGrad(layers, countedCoordinate(calls)," in source + doAssert ".sample(" notin source + +when defined(macosx): + import metal4 + + objc: + proc setTextureType(self: MTLTextureDescriptor, x: uint) = + ## Selects the native two-dimensional array texture shape. + proc setArrayLength(self: MTLTextureDescriptor, x: uint) = + ## Allocates the two distinct texture layers used by this test. + proc replaceRegion( + self: MTLTexture, x: MTLRegion, mipmapLevel: uint, slice: uint, + withBytes: pointer, bytesPerRow: uint, bytesPerImage: uint + ) = + ## Uploads a known color to one array texture layer. + + proc runGpuTests() = + ## Compiles and evaluates every inline lowering on a native Metal device. + let device = MTLCreateSystemDefaultDevice() + doAssert not device.isNil, "A Metal device is required for this test" + defer: device.release() + let queue = device.newCommandQueue() + doAssert not queue.isNil + defer: queue.release() + var error: NSError + let vertexLibrary = device.newLibraryWithSource(@Vertex, 0.ID, error.addr) + doAssert not vertexLibrary.isNil, "Metal vertex compilation: " & $error + defer: vertexLibrary.release() + error = 0.NSError + let shadowLibrary = device.newLibraryWithSource(@Shadowed, 0.ID, error.addr) + doAssert not shadowLibrary.isNil, "Metal shadow compilation: " & $error + defer: shadowLibrary.release() + let vertexFunction = vertexLibrary.newFunctionWithName(@"vertexMain") + defer: vertexFunction.release() + let + descriptor = MTLTextureDescriptor.texture2DDescriptorWithPixelFormat( + MTLPixelFormatRGBA32Float, 1, 1, false + ) + region = MTLRegion(size: MTLSize(width: 1, height: 1, depth: 1)) + descriptor.setStorageMode(MTLStorageModeShared) + descriptor.setUsage(MTLTextureUsageRenderTarget) + let target = device.newTextureWithDescriptor(descriptor) + doAssert not target.isNil + defer: target.release() + descriptor.setUsage(MTLTextureUsageShaderRead) + descriptor.setTextureType(3) + descriptor.setArrayLength(2) + let image = device.newTextureWithDescriptor(descriptor) + doAssert not image.isNil + defer: image.release() + let pixels = [ + [0.9'f, 0.8'f, 0.7'f, 1.0'f], + [0.25'f, 0.5'f, 0.75'f, 1.0'f] + ] + for i in 0 ..< pixels.len: + image.replaceRegion(region, 0, i.uint, pixels[i].unsafeAddr, 16, 16) + let samplerDescriptor = MTLSamplerDescriptor.alloc().init() + defer: samplerDescriptor.release() + samplerDescriptor.setMinFilter(MTLSamplerMinMagFilterNearest) + samplerDescriptor.setMagFilter(MTLSamplerMinMagFilterNearest) + let sampler = device.newSamplerStateWithDescriptor(samplerDescriptor) + doAssert not sampler.isNil + defer: sampler.release() + for i, source in Sources: + error = 0.NSError + let library = device.newLibraryWithSource(@source, 0.ID, error.addr) + doAssert not library.isNil, + "Metal fragment compilation " & $i & ": " & $error & "\n" & source + defer: library.release() + let fragmentFunction = library.newFunctionWithName(@"fragmentMain") + defer: fragmentFunction.release() + let pipelineDescriptor = MTLRenderPipelineDescriptor.alloc().init() + defer: pipelineDescriptor.release() + pipelineDescriptor.setVertexFunction(vertexFunction) + pipelineDescriptor.setFragmentFunction(fragmentFunction) + pipelineDescriptor.colorAttachments().objectAtIndexedSubscript(0). + setPixelFormat(MTLPixelFormatRGBA32Float) + let pipeline = device.newRenderPipelineStateWithDescriptor( + pipelineDescriptor, error.addr + ) + doAssert not pipeline.isNil, "Metal pipeline: " & $error + defer: pipeline.release() + let + command = queue.commandBuffer() + pass = MTLRenderPassDescriptor.renderPassDescriptor() + attachment = pass.colorAttachments().objectAtIndexedSubscript(0) + attachment.setTexture(target) + attachment.setLoadAction(MTLLoadActionClear) + attachment.setStoreAction(MTLStoreActionStore) + let encoder = command.renderCommandEncoderWithDescriptor(pass) + encoder.setRenderPipelineState(pipeline) + encoder.setFragmentTexture(image, 0) + encoder.setFragmentSamplerState(sampler, 0) + encoder.drawPrimitives(MTLPrimitiveTypeTriangle, 0, 3) + encoder.endEncoding() + command.commit() + command.waitUntilCompleted() + doAssert command.status() == MTLCommandBufferStatusCompleted, + "Metal execution: " & $command.error() + var actual: array[4, float32] + target.getBytes(actual[0].addr, 16, region, 0) + for channel in 0 ..< actual.len: + doAssert abs(actual[channel] - Expected[i][channel]) < 0.0001'f, + "Shader " & $i & ": " & $actual & " expected " & $Expected[i] + echo "Metal inline math and texture evaluation passed on the GPU" + + runGpuTests() +else: + echo "Metal inline generation passed; GPU execution requires macOS" diff --git a/tests/test_metal_parameters.nim b/tests/test_metal_parameters.nim new file mode 100644 index 0000000..c3d1d69 --- /dev/null +++ b/tests/test_metal_parameters.nim @@ -0,0 +1,63 @@ +import std/[strutils, tables], shady, vmath + +var tint: Uniform[Vec4] + +proc tintColor(color: Vec4): Vec4 = + ## Exercises global capture alongside uniforms passed to the entry point. + color * tint + +proc matrixValue(matrix: Mat4): Mat4 = + ## Keeps matrix constructor arguments as function calls in generated code. + matrix + +proc parameters( + uv: Vec2, + fragColor: var Vec4, + image, mask: Uniform[Sampler2d], + inverseView: Uniform[Mat4], + strength: Uniform[float32], + weights: Uniform[array[2, Vec4]] +) = + ## Combines uniform entry resources, arrays, captures, and matrix narrowing. + let + basis = mat3(matrixValue(inverseView)) + position = basis * vec3(uv, 1.0'f) + fragColor = tintColor(texture(image, uv) * texture(mask, uv) * + strength * weights[1] + vec4(position, 1.0'f)) + +const + Source = toShader(parameters, metalMSL, shaderFragment) + Desktop = toShader(parameters, glsl4Desktop, shaderFragment) + WebGL = toShader(parameters, glsl3WebGL, shaderFragment) + +let + layout = metalUniformLayout(Source) + stageIn = Source.split("struct FragmentIn {")[1].split("};")[0] + +doAssert "float2 uv;" in stageIn +doAssert "image" notin stageIn and "inverseView" notin stageIn +doAssert "strength" notin stageIn and "weights" notin stageIn +doAssert "texture2d image [[texture(0)]]" in Source +doAssert "texture2d mask [[texture(1)]]" in Source +doAssert "constant ShadyUniforms1 &shadyUniforms1 [[buffer(1)]]" in Source +doAssert "float4 weights[2];" in Source +for uniform in ["inverseView", "strength", "weights", "tint"]: + doAssert layout.offsets.hasKey(uniform) +doAssert "shadyMat3FromMat4(matrixValue(inverseView))" in Source +doAssert "float3x3(value[0].xyz, value[1].xyz, value[2].xyz)" in Source +for source in [Desktop, WebGL]: + doAssert "sampler2D image;" in source + doAssert "uniform mat4 inverseView;" in source + doAssert "mat3(matrixValue(inverseView))" in source + doAssert "shadyMat3FromMat4" notin source + +when defined(macosx): + import metal4 + let device = MTLCreateSystemDefaultDevice() + var error: NSError + let library = device.newLibraryWithSource(@Source, 0.ID, error.addr) + doAssert not library.isNil, "Generated Metal parameters failed: " & $error + doAssert not library.newFunctionWithName(@"fragmentMain").isNil + echo "Metal uniform entry parameters and matrix narrowing compiled" +else: + echo "Metal parameter generation passed; GPU compiler requires macOS"