最近在看Metal, Metal Shader不仅绕不过, 还是Metal学习的重点. 学习Metal Shader的资料很少, 庆幸的是苹果提供了很好的文档. 尽管是英文的, 我还是希望自己能坚持下来啃完.

下载: Metal Shading Language Specification

前言

本文档是关于Metal 通用图形和计算的语言. Metal Shader是一门基于C++的编程语言, 开发者可以使用它来写出可以运行在GPU上的图形或者通用并行计算的程序. 图形和通用计算程序可以紧密地集成在一起, 因为他们都是由Metal Shader这个统一的语言写成的.

PS: 原文似乎不再区分Metal和Metal Shader. 所以, 我也不再区分.

1.1 适用读者

使用Metal framework的开发者应该阅读本文档.

1.2 文档结构

  • 简介, 本文档简介, 覆盖了Metal Shader和C++ 14之间的相同和不同之处.

  • 数据结构, 列举了Metal的数据类型. 向量(vector), 矩阵(matrices), buffer, 纹理(texture), 采样器(sampler). 还讨论了数据对齐(type alignment), 类型转换.

  • 运算操作, Metal 运算.

  • 函数和变量, 函数和变量的声明细节, 属性(attribute)

  • Metal 标准库, 一系列内置函数

  • 编译, Metal 编译器(complier)的可选项, 包括, 预编译指令, (options for math intrinsics), 流程(control) 优化.

  • Numerical Compliance, describes requirements for representing floating-point numbers, including accuracy in mathematical operations.

如果没有特殊说明, 本文档提及的特性都在Metal 1.0后都适用.

1.3 参考

C++:

C++程序设计语言(第四版) 有中文版

Metal:

官方文档, https://developer.apple.com/documentation/metal

1.4 Metal和C++14

Metal基于C++ 14的标准, 进行了一些扩展, 也有一些限制.

PS: C++ 14 Specification, http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4296.pdf

1.4.1 重载(overloading)

Metal支持重载. The function overloading rules are extended to include the address space attribute of an argument. Metal的图形和计算(kernel)函数不能被重载. (C++ 14 Spec, Section 13)

1.4.2 模版(Templates)

Metal 支持模版.

1.4.3 预编译指令

Meal 支持. (C++ 14 Spec, Section 16)

1.4.4 限制

下列C++ 14的特性, Metal不支持.

  • lambda 表达式 (C++ 14 Spec, Section 5.1.2)

  • dynamic_cast 动态类型转换 (C++ 14 Spec, Section 5.2.7)

  • 类型识别 (C++ 14 Spec, Section 5.2.8)

  • 递归调用 (C++ 14 Spec, Section 5.2.2)

  • new 和 delete 操作 (C++ 14 Spec, Section 5.3.4, 5.3.5)

  • noexcept 操作 (C++ 14 Spec, Section 5.3.7)

  • goto 语句 (C++ 14 Spec, Section 6.6)

  • register, thread_local storage attribute (C++ 14 Spec, Section 7.1.1)

  • virtual function attribute (C++ 14 Spec, Section 7.1.2)

  • 类的继承 (C++ 14 Spec, Section 10, Section 11)

  • 异常处理 (C++ 14 Spec, Section 15)

不能在Metal中使用C++ 标准库, Metal拥有自己的标准库.

Metal 限制了指针的使用:

  • Arguments to Metal graphics and kernel functions declared in a program that are pointers must be declared with the Metal device, threadgroup, threadgroup_imageblock, or constant address space attribute.

  • 函数指针不支持.

Metal函数不能命名为 main.

1.5 Metal 像素坐标系统

Pixel coordinate, framebuffer attachment, 左上角为坐标原点.