您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

Metal 曲面細分(Tessellation)實戰:從因子計算到頂點著色

編輯:iOS 開發綜合

Tessellation 中文一般譯作「細分曲面」,用途是把由少量頂點構成的面,細化成細節度更高的面。原理是:把一個三角形或四邊形交給 GPU,依我們在程式中定義的控制點生成規則自動產生更多頂點,再按規則組合成更多三角形。如此一来,3D 遊戲裡远处的敵人即使用低模也能呈現相當精細的輪廓,同時省下頂點資料的傳輸頻寬。

在 Metal API 中,以 tessellation 繪製的圖形所走的渲染流水線,與傳統頂點著色器版本有所不同。Metal 為了精簡 Metal Shading Language 的語法,複用既有的 Compute Shader 來計算控制點生成規則,把結果交給 Tesselator(曲面細分器)產生具體的控制點,再交給負責細分後處理的 Vertex Shader 輸出頂點資料,之後就和典型的渲染流水線一樣。

在流水線圖中,藍色圓角矩形是可程式化著色器,綠色圓角矩形是 GPU 的固定功能單元,灰色則是資料緩衝物件。可以看到,走 Tessellation 流水線相對於傳統流水線,多了計算著色器(負責算出每個 patch 的細分因子)與曲面細分器單元。所謂 patch,和一般三角形、四邊形差不多,只是用於細分曲面處理時,一個 patch 位於一個平面之內,因此沒有 z 座標;我們可以在細分後處理的頂點著色器中,把轉換後的頂點再做視圖模型變換與投影變換後輸出。Metal API 的細分曲面只支援三角形與四邊形,不支援線段,而 OpenGL 還額外支援線段。

四邊形 patch 的頂點排列與一般矩形不同。我們平常用 Metal 繪製矩形多會採用 triangle strip 模式(Metal 沒有 triangle fan),頂點順序可以是左上、左下、右上、右下。但繪製 patch 不能這樣排,只能把四個頂點依順時針或逆時針順次排列。四邊形 patch 的控制點位於四邊形的邊緣與內部,因此描述它的結構體定義如下:

typedef struct {
    /* NOTE: edgeTessellationFactor and insideTessellationFactor
       are interpreted as half (16-bit floats) */
    uint16_t edgeTessellationFactor[4];
    uint16_t insideTessellationFactor[2];
} MTLQuadTessellationFactorsHalf;

其中 edgeTessellationFactor 描述四邊形四條邊緣的控制點生成情況,insideTessellationFactor 描述內部控制點的生成情況。patch 頂點排列方式不同,edgeTessellationFactor 各元素對應的邊也不同。本文把四邊形 patch 的頂點順序定為左下、右下、右上、左上(逆時針),如此一來 edgeTessellationFactor[0] 對應左邊、[1] 對應下邊、[2] 對應右邊、[3] 對應上邊。

typedef struct {
    /* NOTE: edgeTessellationFactor and insideTessellationFactor
       are interpreted as half (16-bit floats) */
    uint16_t edgeTessellationFactor[3];
    uint16_t insideTessellationFactor;
} MTLTriangleTessellationFactorsHalf;

為統一描述,本文把三角形 patch 的頂點順序定為右下、中上、左下。如此 edgeTessellationFactor[0] 對應左邊、[1] 對應下邊、[2] 對應右邊。

三角形邊緣上控制點的生成方式與四邊形類似,內部控制點的規則則複雜得多。以 insideTessellationFactor 的值為例:小於 3 時,三角形內部只有一個控制點,位於重心(三頂點到對邊中線的交會點)處;等於 3 時,內部剛好有 3 個控制點構成一個小三角形;等於 4 時,在小三角形中再加一個位於其重心的控制點,並在小三角形每條邊緣的中點各加一個控制點;等於 5 時,內部小三角形的每條邊緣含兩個均分邊緣的控制點,並在其內部再構成一個小三角形;等於 6 時,小三角形邊緣含 3 個均分點,內部的小三角形每邊再加 1 個控制點並在其內部再加一個,以此類推。具體算法與對照圖可參考 OpenGL 官方 wiki 的 Tessellation 條目:https://www.opengl.org/wiki/Tessellation

三角形 patch 每個控制點的座標以 (u, v, w) 描述,三者取值都在 [0.0, 1.0] 區間內。以本文的頂點排列順序為例:三角形左邊上所有控制點的 u 座標為 0;下邊上所有控制點的 v 座標為 0;右邊上所有控制點的 w 座標為 0。內部控制點的座標怎麼算?有點反直覺的是,在二維平面中卻用三個值描述一個點,但關鍵性質是:對三角形內任一控制點,u + v + w = 1.0,三者彼此關聯。

從簡單的例子切入:對一個等邊三角形(三線合一,中線、垂線、角平分線重疊,中心與重心也同為一點),假設中線長度為 1.0,則重心到三條邊中點的距離都是 1/3。把重心的控制點座標定義為 (1/3, 1/3, 1/3),u + v + w 正好等於 1.0。由此可歸納出判定方式:判定 u 時,把三角形左邊沿其中線平移直到與控制點重合,看平移後的左邊與左邊中線的交點落在此中線上的哪個位置,該位置即為 u 值;v 值同理,把下邊沿其中線平移至與控制點重合,看交點位置;w 值則看右邊沿其中線平移的情況。

有了這些概念,接著說明 Metal API 中完成細分曲面渲染的完整流程。

用計算著色器設定控制點生成規則

constant int4 tessOutFactors   [[function_constant(0)]];
constant int2 tessInnerFactors [[function_constant(1)]];

// 三角形:生成控制點的計算核心
kernel void triangle_kernel(device struct MTLTriangleTessellationFactorsHalf *factors [[buffer(0)]],
                            uint tid [[thread_position_in_grid]]) {
    // Simple passthrough operation
    // Moresophisticatedcomputekernelsmightdeterminethetessellationfactorsbasedonthestateofthescene(e.g.cameradistance)
    factors[tid].edgeTessellationFactor[0] = tessOutFactors.x;
    factors[tid].edgeTessellationFactor[1] = tessOutFactors.y;
    factors[tid].edgeTessellationFactor[2] = tessOutFactors.z;
    factors[tid].insideTessellationFactor   = tessInnerFactors.x;
}

// 四邊形:生成控制點的計算核心
kernel void quad_kernel(device struct MTLQuadTessellationFactorsHalf *factors [[buffer(0)]],
                        uint tid [[thread_position_in_grid]]) {
    factors[tid].edgeTessellationFactor[0] = tessOutFactors.x;
    factors[tid].edgeTessellationFactor[1] = tessOutFactors.y;
    factors[tid].edgeTessellationFactor[2] = tessOutFactors.z;
    factors[tid].edgeTessellationFactor[3] = tessOutFactors.w;
    factors[tid].insideTessellationFactor[0] = tessInnerFactors.x;
    factors[tid].insideTessellationFactor[1] = tessInnerFactors.y;
}

最上面兩個常數由主機端傳入。tessOutFactors 是四元素向量,各分量對應 edgeTessellationFactor 的相應元素;tessInnerFactors 是二元素向量,對四邊形而言,第一個分量作為 insideTessellationFactor[0]、第二個分量作為 [1];對三角形而言,只用第一個分量作為 insideTessellationFactor。核心函式的參數就是指向 MTLTriangleTessellationFactorsHalf 或 MTLQuadTessellationFactorsHalf 結構體陣列的指標,每個元素代表一個 patch 的控制點生成規則。若有多个 patch 需要細分,這裡就會有多個元素;若只有一個,就只有一個元素。可以在主機端控制調度多少個執行緒。

主機端對計算著色器的設定

// 0 號對應外部邊緣的 tess。四邊形順序為左、下、右、上;三角形為左、下、右
[constantValues setConstantValue:(const int[]){5,4,3,2} type:MTLDataTypeInt4 atIndex:0];

// 1 號對應內部的 tess。四邊形分別為水平方向與垂直方向;三角形只用一個值
[constantValues setConstantValue:(const int[]){4,3} type:MTLDataTypeInt2 atIndex:1];

computeProgram = [mLibrary newFunctionWithName:tessControlKernelName
                                 constantValues:constantValues
                                          error:NULL];
if (computeProgram == nil) {
    NSLog(@"計算內核獲取失敗");
    break;
}
[constantValues release];

mComputePipelineState = [device newComputePipelineStateWithFunction:computeProgram error:NULL];
if (mComputePipelineState == nil) {
    NSLog(@"計算流水線創建失敗");
    break;
}

// 細分曲面因子緩衝最終由生成控制點的核心程式產生,不會被 CPU 讀寫,
// 而是直接在流水線內部使用,因此這裡使用 GPU 私有儲存模式
mTessFactorsBuffer = [device newBufferWithLength:256 options:MTLResourceStorageModePrivate];

這段程式碼設定了前面提到的常數向量、建立計算著色器程式與計算流水線。mTessFactorsBuffer 就是存放 MTLTriangleTessellationFactorsHalf 或 MTLQuadTessellationFactorsHalf 資料的緩衝物件。由於這裡只繪製一個 patch,假定長度為 256 位元組,容納這兩個結構綽綽有餘。

調度執行計算著色器

id<MTLCommandBuffer> commandBuffer = [mCommandQueue commandBuffer];

// 設定命令緩衝執行完成後的處理
[commandBuffer addCompletedHandler:^void(id<MTLCommandBuffer> cmdBuf) {
    // 命令全部執行完畢後,將 mCurrentDrawable 置空,表示可以繪製下一幀
    mCurrentDrawable = nil;
}];

// 從命令緩衝取得計算命令編碼器
id<MTLComputeCommandEncoder> computeCommandEncoder = [commandBuffer computeCommandEncoder];

[computeCommandEncoder setComputePipelineState:mComputePipelineState];
[computeCommandEncoder setBuffer:mTessFactorsBuffer offset:0 atIndex:0];

// 分派執行緒群組。此處僅對一個 patch 做控制點生成規則,一個執行緒即可
[computeCommandEncoder dispatchThreadgroups:MTLSizeMake(1,1,1)
                      threadsPerThreadgroup:MTLSizeMake(1,1,1)];
[computeCommandEncoder endEncoding];

先取得命令緩衝,再由它取得計算命令編碼器,設定計算流水線與緩衝物件,然後分派計算核心以啟動計算著色器,最後結束編碼器。在 Metal 中,一個命令緩衝可以有多個命令編碼器操作,但同一時間通常只有一個處於活動狀態,直到它結束編碼,下一個才能接手;全部完成後,命令緩衝再做提交,讓 GPU 真正執行。

對計算著色器而言,那個結構體陣列其實是輸出,且型別固定,不能隨意替換,但我們可以額外增加緩衝物件來輸入必要參數。

把因子資料傳給曲面細分器

計算著色器算好的結構體資料會直接存進主機端建立的 mTessFactorsBuffer。接著把它交給渲染命令編碼器,最後透過渲染編碼器呼叫 drawPatches 系列介面來啟動 tessellator 並執行後續渲染流程。

在看細分後處理的頂點著色器之前,先看主機端指定的 patch 頂點排列:

// 以逆時針方向構成四邊形,使邊的順序依序為左、下、右、上
static const float sRectangleVertices[] = {
    // 左下頂點
    -0.9f, -0.9f, 0.9f, 0.1f, 0.1f, 1.0f,
    // 右下頂點
     0.9f, -0.9f, 0.1f, 0.9f, 0.1f, 1.0f,
    // 右上頂點
     0.9f,  0.9f, 0.1f, 0.1f, 0.9f, 1.0f,
    // 左上頂點
    -0.9f,  0.9f, 0.9f, 0.9f, 0.1f, 1.0f,
};

// 以逆時針方向構成三角形,使邊的順序依序為左、下、右
static const float sTriangleVertices[] = {
    // 右下頂點
     0.9f, -0.9f, 0.1f, 0.1f, 0.9f, 1.0f,
    // 中上頂點
     0.0f,  0.9f, 0.9f, 0.1f, 0.1f, 1.0f,
    // 左下頂點
    -0.9f, -0.9f, 0.1f, 0.9f, 0.1f, 1.0f,
};

這兩個 patch 的頂點分布與一開始提到的順序一致。若對照 Apple 官方《The Metal Programming Guide》的範例,該處四邊形 patch 是以左上、右上、右下、左下的順時針次序排列;本文則統一採用逆時針。以下是渲染流水線的相關設定:

vertexProgram = [mLibrary newFunctionWithName:tessEvalVertexName];
if (vertexProgram == nil) {
    NSLog(@"頂點著色器獲取失敗");
    break;
}

fragmentProgram = [mLibrary newFunctionWithName:@"square_fragment"];
if (fragmentProgram == nil) {
    NSLog(@"片段著色器獲取失敗");
    break;
}

MTLVertexDescriptor *vertexDescriptor = [MTLVertexDescriptor new];
vertexDescriptor.attributes[0].format    = MTLVertexFormatFloat2;
vertexDescriptor.attributes[0].bufferIndex = 0;
vertexDescriptor.attributes[0].offset    = 0;

vertexDescriptor.attributes[1].format    = MTLVertexFormatFloat4;
vertexDescriptor.attributes[1].bufferIndex = 0;
vertexDescriptor.attributes[1].offset    = 8; // color 從第 8 位元組開始

vertexDescriptor.layouts[0].stride       = 6 * sizeof(float);
vertexDescriptor.layouts[0].stepFunction = MTLVertexStepFunctionPerPatchControlPoint;
vertexDescriptor.layouts[0].stepRate     = 1;

MTLRenderPipelineDescriptor *descriptor = [MTLRenderPipelineDescriptor new];
descriptor.sampleCount = 4; // 使用 MSAA,每個像素由 4 個樣本構成
descriptor.vertexFunction   = vertexProgram;
descriptor.fragmentFunction = fragmentProgram;
descriptor.depthAttachmentPixelFormat   = MTLPixelFormatInvalid; // 不啟用深度測試
descriptor.stencilAttachmentPixelFormat = MTLPixelFormatInvalid; // 不啟用模板測試
descriptor.vertexDescriptor = vertexDescriptor;
[vertexDescriptor release];

descriptor.colorAttachments[0].pixelFormat      = self.pixelFormat;
descriptor.colorAttachments[0].blendingEnabled  = YES;
descriptor.colorAttachments[0].rgbBlendOperation   = MTLBlendOperationAdd;
descriptor.colorAttachments[0].alphaBlendOperation = MTLBlendOperationAdd;
descriptor.colorAttachments[0].sourceRGBBlendFactor      = MTLBlendFactorSourceAlpha;
descriptor.colorAttachments[0].sourceAlphaBlendFactor    = MTLBlendFactorSourceAlpha;
descriptor.colorAttachments[0].destinationRGBBlendFactor = MTLBlendFactorOneMinusSourceAlpha;
descriptor.colorAttachments[0].destinationAlphaBlendFactor = MTLBlendFactorOneMinusSourceAlpha;

// 細分曲面相關設定
descriptor.tessellationFactorScaleEnabled       = NO;
descriptor.tessellationFactorFormat             = MTLTessellationFactorFormatHalf;
descriptor.tessellationControlPointIndexType    = MTLTessellationControlPointIndexTypeNone;
descriptor.tessellationFactorStepFunction       = MTLTessellationFactorStepFunctionConstant;
// 頂點以逆時針作為順序,因此這裡使用逆時針
descriptor.tessellationOutputWindingOrder = MTLWindingCounterClockwise;
descriptor.tessellationPartitionMode      = MTLTessellationPartitionModeInteger;

// macOS 中最大細分曲面因子為 64,預設為 16
descriptor.maxTessellationFactor = 64;

mRenderPipelineState = [device newRenderPipelineStateWithDescriptor:descriptor error:NULL];
[descriptor release];
if (mRenderPipelineState == nil) {
    NSLog(@"渲染流水線創建失敗");
    break;
}

if (mIsForRectangle)
    mVertexBuffer = [device newBufferWithBytes:sRectangleVertices
                                        length:sizeof(sRectangleVertices)
                                       options:MTLResourceCPUCacheModeWriteCombined];
else
    mVertexBuffer = [device newBufferWithBytes:sTriangleVertices
                                        length:sizeof(sTriangleVertices)
                                       options:MTLResourceCPUCacheModeWriteCombined];

這裡要注意:對細分後處理的頂點著色器而言,原始 patch 的頂點必須以 stage-in 方式傳入,不能是普通的資料緩衝物件;同時在 Metal Shading Language 中必須用 patch_control_point 結構體範本把輸入的 patch 結構體封裝起來,著色器會逐個讀入 patch 頂點資料。另外,上述頂點描述符中 layouts[0] 的 stepFunction 必須設為 MTLVertexStepFunctionPerPatchControlPoint,表示該頂點作為 patch 控制點使用。關於 tessellationPartitionMode 各模式的細節,可參考相關專文(如 https://www.cnblogs.com/zenny-chen/p/4280100.html 中「指定細分曲面座標的空間」一節),本文使用 MTLTessellationPartitionModeInteger 表示均分。建立 patch 頂點緩衝的方式與建立一般圖形頂點緩衝相同。

渲染 patch

// 從命令緩衝取得渲染命令編碼器
id<MTLRenderCommandEncoder> renderCommandEncoder =
    [commandBuffer renderCommandEncoderWithDescriptor:mRenderPassDescriptor];

[renderCommandEncoder setRenderPipelineState:mRenderPipelineState];
[renderCommandEncoder setCullMode:MTLCullModeBack];
[renderCommandEncoder setFrontFacingWinding:MTLWindingCounterClockwise];
[renderCommandEncoder setTriangleFillMode:mIsWireFrameMode
                                      ? MTLTriangleFillModeLines
                                      : MTLTriangleFillModeFill];
[renderCommandEncoder setVertexBuffer:mVertexBuffer offset:0 atIndex:0];
[renderCommandEncoder setTessellationFactorBuffer:mTessFactorsBuffer offset:0 instanceStride:0];

const NSUInteger patchControlPoints = mIsForRectangle ? 4 : 3;
[renderCommandEncoder drawPatches:patchControlPoints
                        patchStart:0
                         patchCount:1
                  patchIndexBuffer:NULL
            patchIndexBufferOffset:0
                      instanceCount:1
                       baseInstance:0];
[renderCommandEncoder endEncoding];

[commandBuffer presentDrawable:mCurrentDrawable];
[commandBuffer commit];

這裡透過 setTessellationFactorBuffer 把計算著色器輸出的、存放細分因子的 mTessFactorsBuffer 傳進去。這個物件不需要在 Metal Shader 中作為參數傳遞,因為它會直接交給 tessellator 固定功能單元;在細分後處理的頂點著色器中我們不必關心這些資料,拿到的將是 tessellator 幫我們算好的具體控制點資訊。順序上要注意:先讓計算命令編碼器活動並結束,再使用渲染命令編碼器,最後提交命令緩衝。

細分後處理頂點著色器

// 控制點結構體
struct ControlPoint {
    float2 position [[attribute(0)]];
    float4 color    [[attribute(1)]];
};

// Patch 結構體
struct PatchIn {
    patch_control_point<ControlPoint> control_points;
};

// 頂點著色器輸出到片段著色器的結構體
struct FunctionOutIn {
    float4 position [[position]];
    half4  color    [[flat]];
};

// 三角形細分後處理頂點著色器
[[patch(triangle, 3)]]
vertex struct FunctionOutIn triangle_vertex(struct PatchIn patchIn [[stage_in]],
                                            float3 patch_coord [[position_in_patch]]) {
    float u = patch_coord.x;
    float v = patch_coord.y;
    float w = patch_coord.z;

    // 把當前控制點座標 (u,v,w) 線性插值轉換為笛卡兒座標 (x,y)
    float x = u * patchIn.control_points[0].position.x
            + v * patchIn.control_points[1].position.x
            + w * patchIn.control_points[2].position.x;
    float y = u * patchIn.control_points[0].position.y
            + v * patchIn.control_points[1].position.y
            + w * patchIn.control_points[2].position.y;

    struct FunctionOutIn vertexOut;
    vertexOut.position = float4(x, y, 0.0, 1.0);
    vertexOut.color    = half4(u, v, w, 1.0);
    return vertexOut;
}

// 四邊形細分後處理頂點著色器
[[patch(quad, 4)]]
vertex struct FunctionOutIn quad_vertex(struct PatchIn patchIn [[stage_in]],
                                        float2 patch_coord [[position_in_patch]]) {
    // tessellator 給出的是正規化後的控制點座標,
    // uv 座標原點 (0,0) 位於原 patch 的左下頂點
    float u = patch_coord.x;
    float v = patch_coord.y;

    // 線性插值把正規化座標轉回相對於輸入頂點的座標
    float2 lower_middle = mix(patchIn.control_points[0].position.xy,
                              patchIn.control_points[1].position.xy, u);
    float2 upper_middle = mix(patchIn.control_points[2].position.xy,
                              patchIn.control_points[3].position.xy, 1 - u);

    struct FunctionOutIn vertexOut;
    vertexOut.position = float4(mix(lower_middle, upper_middle, v), 0.0f, 1.0f);
    vertexOut.color    = half4(u, v, 1.0f - v, 1.0h);

    // 靠左下的頂點使用原 patch 左下頂點的顏色
    if (u < 0.5f && v < 0.5f)
        vertexOut.color = half4(patchIn.control_points[0].color);
    // 靠右下
    else if (u > 0.5f && v < 0.5f)
        vertexOut.color = half4(patchIn.control_points[1].color);
    // 靠右上
    else if (u > 0.5f && v > 0.5f)
        vertexOut.color = half4(patchIn.control_points[2].color);
    // 靠左上
    else if (u < 0.5f && v > 0.5f)
        vertexOut.color = half4(patchIn.control_points[3].color);

    return vertexOut;
}

細分後處理的頂點著色器以 [[patch()]] 屬性修飾。在 macOS 中必須明確指定當前 patch 的頂點個數,iOS 中則可省略。patch_coord 參數存放來自 tessellator 的當前控制點相對座標(四邊形為 (u, v),三角形為 (u, v, w)),著色器的工作就是把它們轉換成標準笛卡兒座標系下的值,也就是與原 patch 頂點座標同一套座標系。四邊形的後處理著色器另外依控制點所在區域,分別套用頂點資料中攜帶的顏色。最後 vertexOut 的輸出交給光柵化器,再送進片段著色器。

若本文有任何疏漏或表達不精準之處,也歡迎先進指正,我會相應修正。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved