Metal和所有其他c ++平台共有哪些c ++数据类型

时间:2018-08-19 20:39:42

标签: android c++ ios metal

我正在尝试为将在Linux,iOS和Android上运行的跨平台应用程序创建后端。

我最初是在考虑到iOS的情况下构建它的,所以我将simd数据类型用于float2和矩阵。但是simd在Linux或Android上不可用,因此我需要其他功能。

我当然可以定义自己的矩阵类型和自己的float2 / 3/4类型,但是我担心我会特别为矩阵乘法而松开硬件加速。

我确实尝试查看是否可以制作与simd类型等效但导致各种问题的c ++结构。这是我的尝试。

struct float2 {
  float x;
  float y;
}; (Was supposed to be equal to simd_float2 and float2 in Metal shading language)

struct float3 {
  float x;
  float y;
  float z;
}; (Was supposed to be equal to simd_float3 and float3 in Metal shading language)

struct float3x3 {
  float columns[3][3];
}; (Was supposed to be equal to simd_float3x3 and matrix_float3x3 in Metal shading language)

struct Vertex {
  float3 color;
  float2 position;
}; (A struct that is supposed to be common between Engine and Metal Shading language however gets read COMPLETELY wrong when I try to do it this way)

// How can simd types possibly be defined in a way that these aren't equivalent

当我开始使用这些结构时,所有的破坏都消失了,很明显,Metal没有得到它。

我真的应该担心将自己的定义和数学用于矩阵乘法的性能成本吗?

是否有任何跨平台库可用于为linux应用程序,我的Vulcan Android应用程序和我的Metal iOS应用程序定义这些结构?

1 个答案:

答案 0 :(得分:2)

问题(除了您的struct float3没有3个组成部分之外)可能是由于对齐问题。例如,如Metal Shading Language (MSL) spec中所述,MSL的float3(以及simd)的大小不是3 float的大小,而是4的大小。这样的结构:

struct float3 {
    float x;
    float y;
    float z;
};

对应于MSL的float3,它对应于packed_float3。如果连接数据结构(例如制作struct float3的数组或构建包含struct float3类型的字段以及之后的其他字段的结构),则这尤其重要。您的struct Vertex遇到了后一个问题。与MSL中的相同结构相比,position字段的偏移量错误。

您可以通过添加第四个字段struct float3来修复float padding;。您还可以使用__attribute__ ((aligned(16)))之类的非标准编译器扩展对其进行修复:

struct float3 {
    float x;
    float y;
    float z;
} __attribute__ ((aligned(16)));

GCC和Clang都支持aligned属性。我确定MSVC支持类似的功能,但我不记得它是副产品。

类似地,MSL的float3x3的大小为48个字节,并对齐为16个字节。它对应于float3[3](假设float3的正确定义)。