You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将给定GLSL片段着色器转换为符合规范的Metal Shader代码

GLSL转Metal Shader完整实现

转换要点说明

  • 基础类型直接替换:mat2 → float2x2、vec2 → float2、vec3 → float3、vec4 → float4
  • GLSL内置变量适配:gl_FragCoord替换为带[[position]]修饰的片段坐标输入参数,gl_FragColor替换为带[[color(0)]]修饰的片段函数返回值
  • 外部 uniform 参数(resolution、time)通过Metal缓冲机制传入,示例中使用索引为0的缓冲存放统一参数结构体

注:原GLSL代码中连续两个减号--为排版笔误,转换时修正为单个减号,符合原代码坐标变换的逻辑需求


完整转换后代码

#include <metal_stdlib>
using namespace metal;

constant float PI = 3.14159265359;

float2x2 rotate2d(float _angle) {
    return float2x2(cos(_angle), -sin(_angle),
                    sin(_angle), cos(_angle));
}

// 统一参数结构体,存储外部传入的全局参数
struct Uniforms {
    float2 resolution;
    float time;
};

fragment float4 mainFragment(
    float4 fragCoord [[position]],
    constant Uniforms& uniforms [[buffer(0)]]
) {
    float2 st = (fragCoord.xy * 2.0 - uniforms.resolution) / min(uniforms.resolution.x, uniforms.resolution.y);
    float p = 0.0;
    
    st = rotate2d(sin(uniforms.time) * PI) * st;
    
    float2 c = max(abs(st) - 0.2, 0.0);
    p = length(c);
    p = ceil(p);
    
    float3 color = float3(1.0 - p);

    return float4(color, 1.0);
}

内容的提问来源于stack exchange,提问作者x001017

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 02:39:04