Metal框架詳細解析(二十五) —— 基本課程之參數緩沖 - 帶有數組和資源堆的參數緩沖區(五)

版本記錄

版本號 時間
V1.0 2018.10.09 星期二

前言

很多做視頻和圖像的,相信對這個框架都不是很陌生,它渲染高級3D圖形,并使用GPU執行數據并行計算。接下來的幾篇我們就詳細的解析這個框架。感興趣的看下面幾篇文章。
1. Metal框架詳細解析(一)—— 基本概覽
2. Metal框架詳細解析(二) —— 器件和命令(一)
3. Metal框架詳細解析(三) —— 渲染簡單的2D三角形(一)
4. Metal框架詳細解析(四) —— 關于GPU Family 4(一)
5. Metal框架詳細解析(五) —— 關于GPU Family 4之關于Imageblocks(二)
6. Metal框架詳細解析(六) —— 關于GPU Family 4之關于Tile Shading(三)
7. Metal框架詳細解析(七) —— 關于GPU Family 4之關于光柵順序組(四)
8. Metal框架詳細解析(八) —— 關于GPU Family 4之關于增強的MSAA和Imageblock采樣覆蓋控制(五)
9. Metal框架詳細解析(九) —— 關于GPU Family 4之關于線程組共享(六)
10. Metal框架詳細解析(十) —— 基本組件(一)
11. Metal框架詳細解析(十一) —— 基本組件之器件選擇 - 圖形渲染的器件選擇(二)
12. Metal框架詳細解析(十二) —— 基本組件之器件選擇 - 計算處理的設備選擇(三)
13. Metal框架詳細解析(十三) —— 計算處理(一)
14. Metal框架詳細解析(十四) —— 計算處理之你好,計算(二)
15. Metal框架詳細解析(十五) —— 計算處理之關于線程和線程組(三)
16. Metal框架詳細解析(十六) —— 計算處理之計算線程組和網格大小(四)
17. Metal框架詳細解析(十七) —— 工具、分析和調試(一)
18. Metal框架詳細解析(十八) —— 工具、分析和調試之Metal GPU Capture(二)
19. Metal框架詳細解析(十九) —— 工具、分析和調試之GPU活動監視器(三)
20. Metal框架詳細解析(二十) —— 工具、分析和調試之關于Metal著色語言文件名擴展名、使用Metal的命令行工具構建庫和標記Metal對象和命令(四)
21. Metal框架詳細解析(二十一) —— 基本課程之基本緩沖區(一)
22. Metal框架詳細解析(二十二) —— 基本課程之基本紋理(二)
23. Metal框架詳細解析(二十三) —— 基本課程之CPU和GPU同步(三)
24. Metal框架詳細解析(二十四) —— 基本課程之參數緩沖 - 基本參數緩沖(四)

Argument Buffers with Arrays and Resource Heaps - 帶有數組和資源堆的參數緩沖區

演示如何使用數組定義參數緩沖區,并通過將參數緩沖區與資源堆組合來減少CPU開銷。

Basic Argument Buffers示例中,您學習了如何在參數緩沖區中指定,編碼,設置和訪問資源。

在此示例中,您將學習如何將參數緩沖區與資源數組和資源堆組合在一起。 特別是,您將學習如何定義包含數組的參數緩沖區結構以及如何從堆中分配和使用資源。 該示例渲染了一個靜態四邊形,它使用編碼到參數緩沖區中的多個資源。


Arrays of Arguments in the Metal Shading Language - Metal著色語言中的參數數組

數組可用作圖形或計算函數的參數。 當函數將數組作為參數時,數組中第一個資源的索引等于數組參數本身的基本索引。 因此,數組中的每個后續資源都會自動分配一個后續索引值,從基本索引值開始遞增計數。

例如,以下片段函數exampleFragmentFunction有一個參數textureParameters,它是一個包含10個紋理的數組,其基本索引值為5。

fragment float4
exampleFragmentFunction(array<texture2d<float>, 10> textureParameters [[ texture(5) ]])

因為textureParameters具有[[texture(5)]]屬性限定符,所以設置此參數的相應Metal框架方法是setFragmentTexture:atIndex:,其中index的值從5開始。因此,數組索引0處的紋理設置為索引號5,數組索引1處的紋理設置為索引號6,依此類推。 陣列索引為9的數組中的最后一個紋理設置為索引號14。


Define Argument Buffers with Arrays - 使用數組定義參數緩沖區

數組也可以用作參數緩沖結構的元素。 在這種情況下,參數緩沖區的[[id(n)]]屬性限定符的行為與函數參數的[[texture(n)]]屬性限定符的行為相同,其中n是數組的基本索引值。 但是,您不要調用MTLRenderCommandEncoder對象的setFragmentTexture:atIndex:方法來設置數組中的紋理。 相反,您調用MTLArgumentEncoder對象的setTexture:atIndex:方法,將數組中的紋理編碼到參數緩沖區中,其中index對應于基本索引值n,加上數組中紋理的索引。

此示例中的參數緩沖區被聲明為FragmentShaderArguments結構,這是它的定義:

typedef struct FragmentShaderArguments {
    array<texture2d<float>, AAPLNumTextureArguments> exampleTextures  [[ id(AAPLArgumentBufferIDExampleTextures)  ]];
    array<device float *,  AAPLNumBufferArguments>   exampleBuffers   [[ id(AAPLArgumentBufferIDExampleBuffers)   ]];
    array<uint32_t, AAPLNumBufferArguments>          exampleConstants [[ id(AAPLArgumentBufferIDExampleConstants) ]];
} FragmentShaderArguments;

此結構的每個元素都使用array<T, N>模板,該模板將元素定義為特定類型的數組,T和元素數量N。此參數緩沖區包含以下資源:

  • exampleTextures,一個包含32個2D紋理的數組,其基本索引值為0。
  • exampleBuffers,一個由32個浮點緩沖區組成的數組,其基本索引值為100。
  • exampleConstants,一個由32個uint32_t常量組成的數組,其基本索引值為200。

Encode Array Elements into an Argument Buffer - 將數組元素編碼到參數緩沖區中

此示例通過匹配每個setTexture:atIndex:setBuffer:offset:atIndex:constantDataAtIndex:方法的索引參數調用元素的相應索引值(由參數緩沖區中的屬性限定符[[id(n)]定義)將數組元素編碼到參數緩沖區中 。

for(uint32_t i = 0; i < AAPLNumTextureArguments; i++)
{
    [argumentEncoder setTexture:_texture[i]
                        atIndex:AAPLArgumentBufferIDExampleTextures+i];
}
for(uint32_t i = 0; i < AAPLNumBufferArguments; i++)
{
    [argumentEncoder setBuffer:_dataBuffer[i]
                        offset:0
                        atIndex:AAPLArgumentBufferIDExampleBuffers+i];

    uint32_t *elementCountAddress =
        [argumentEncoder constantDataAtIndex:AAPLArgumentBufferIDExampleConstants+i];

    *elementCountAddress = (uint32_t)_dataBuffer[i].length / 4;
}

Access Array Elements in an Argument Buffer - 訪問參數緩沖區中的數組元素

在函數內,訪問參數緩沖區中編碼的數組元素與訪問標準數組的元素相同。 在此示例中,exampleTexturesexampleBuffersexampleConstants數組通過fragmentShader函數的fragmentShaderArgs參數進行訪問。 使用[n]下標語法訪問每個數組元素,其中n是數組中元素的索引。

for(uint32_t textureToSample = 0; textureToSample < AAPLNumBufferArguments; textureToSample++)
{
    float4 textureValue = fragmentShaderArgs.exampleTextures[textureToSample].sample(textureSampler, in.texCoord);

    color += textureValue;
}

fragmentShader函數包含if-else條件,該條件評估texCoordx分量以確定片段所在的四邊形的哪一側。 如果片段位于四邊形的左側,則該函數對exampleTextures數組中的每個紋理進行采樣,并添加采樣值以確定最終輸出顏色。

如果片段位于四邊形的右側,則該函數從exampleBuffers數組中讀取一個值。 該函數使用texCoordx組件來確定要讀取的緩沖區,然后使用texCoordy組件來確定緩沖區中的讀取位置。 緩沖區中的值確定最終輸出顏色。

// Use texCoord.x to select the buffer to read from
uint32_t bufferToRead = (in.texCoord.x-0.5)*2.0 * (AAPLNumBufferArguments-1);

// Retrieve the number of elements for the selected buffer from
// the array of constants in the argument buffer
uint32_t numElements = fragmentShaderArgs.exampleConstants[bufferToRead];

// Determine the index used to read from the buffer
uint32_t indexToRead = in.texCoord.y * numElements;

// Retrieve the buffer to read from by accessing the array of
// buffers in the argument buffer
device float* buffer = fragmentShaderArgs.exampleBuffers[bufferToRead];

// Read from the buffer and assign the value to the output color
color = buffer[indexToRead];

Combine Argument Buffers with Resource Heaps - 將參數緩沖區與資源堆組合在一起

片段函數通過參數緩沖區訪問32個紋理和32個緩沖區,總共64個不同的資源。 如果每個資源的內存都是單獨分配的,盡管存在于數組中,Metal需要驗證64個獨立資源的內存,然后才能使GPU訪問這些資源。

相反,此示例從MTLHeap對象分配資源。 堆是單個內存區域,可以從中分配多個資源。 因此,示例可以通過調用useHeap:方法一次使堆的整個內存(包括堆內所有資源的內存)可供GPU訪問。

該示例實現了一個loadResources方法,該方法將資源數據加載到臨時MTLTextureMTLBuffer對象中。 然后,該示例實現了一個createHeap方法,該方法計算將資源數據存儲在堆中所需的總大小,并創建堆本身。

- (void) createHeap
{
    MTLHeapDescriptor *heapDescriptor = [MTLHeapDescriptor new];
    heapDescriptor.storageMode = MTLStorageModePrivate;
    heapDescriptor.size =  0;
    
    // Build a descriptor for each texture and calculate the size required to store all textures in the heap
    for(uint32_t i = 0; i < AAPLNumTextureArguments; i++)
    {
        // Create a descriptor using the texture's properties
        MTLTextureDescriptor *descriptor = [AAPLRenderer newDescriptorFromTexture:_texture[i]
                                                                      storageMode:heapDescriptor.storageMode];
        
        // Determine the size required for the heap for the given descriptor
        MTLSizeAndAlign sizeAndAlign = [_device heapTextureSizeAndAlignWithDescriptor:descriptor];

        // Align the size so that more resources will fit in the heap after this texture
        sizeAndAlign.size += (sizeAndAlign.size & (sizeAndAlign.align - 1)) + sizeAndAlign.align;
        
        // Accumulate the size required to store this texture in the heap
        heapDescriptor.size += sizeAndAlign.size;
    }
    
    // Calculate the size required to store all buffers in the heap
    for(uint32_t i = 0; i < AAPLNumBufferArguments; i++)
    {
        // Determine the size required for the heap for the given buffer size
        MTLSizeAndAlign sizeAndAlign = [_device heapBufferSizeAndAlignWithLength:_dataBuffer[i].length
                                                                         options:MTLResourceStorageModePrivate];
        
        // Align the size so that more resources will fit in the heap after this buffer
        sizeAndAlign.size +=  (sizeAndAlign.size & (sizeAndAlign.align - 1)) + sizeAndAlign.align;
        
        // Accumulate the size required to store this buffer in the heap
        heapDescriptor.size += sizeAndAlign.size;
    }
    
    // Create a heap large enough to store all resources
    _heap = [_device newHeapWithDescriptor:heapDescriptor];
}

該示例實現了一個moveResourcesToHeap方法,該方法創建從堆分配的永久MTLTextureMTLBuffer對象。 然后,該方法使用MTLBlitCommandEncoder將資源數據從臨時對象復制到永久對象。

- (void)moveResourcesToHeap
{
    // Create a command buffer and blit encoder to copy data from the existing resources to
    // the new resources created from the heap
    id <MTLCommandBuffer> commandBuffer = [_commandQueue commandBuffer];
    commandBuffer.label = @"Heap Copy Command Buffer";
    id <MTLBlitCommandEncoder> blitEncoder = commandBuffer.blitCommandEncoder;

    // Create new textures from the heap and copy the contents of the existing textures to
    // the new textures
    for(uint32_t i = 0; i < AAPLNumTextureArguments; i++)
    {
        // Create a descriptor using the texture's properties
        MTLTextureDescriptor *descriptor = [AAPLRenderer newDescriptorFromTexture:_texture[i]
                                                                      storageMode:_heap.storageMode];
        
        // Create a texture from the heap
        id<MTLTexture> heapTexture = [_heap newTextureWithDescriptor:descriptor];

        // Blit every slice of every level from the existing texture to the new texture
        MTLRegion region = MTLRegionMake2D(0, 0, _texture[i].width, _texture[i].height);
        for(NSUInteger level = 0; level < _texture[i].mipmapLevelCount;  level++)
        {
            for(NSUInteger slice = 0; slice < _texture[i].arrayLength; slice++)
            {
                [blitEncoder copyFromTexture:_texture[i]
                                 sourceSlice:slice
                                 sourceLevel:level
                                sourceOrigin:region.origin
                                  sourceSize:region.size
                                   toTexture:heapTexture
                            destinationSlice:slice
                            destinationLevel:level
                           destinationOrigin:region.origin];
            }
            region.size.width /= 2;
            region.size.height /= 2;
            if(region.size.width == 0) region.size.width = 1;
            if(region.size.height == 0) region.size.height = 1;
        }

        // Replace the existing texture with the new texture
        _texture[i] = heapTexture;
    }

    // Create new buffers from the heap and copy the contents of existing buffers to the
    // new buffers
    for(uint32_t i = 0; i < AAPLNumBufferArguments; i++)
    {
        // Create a buffer from the heap
        id<MTLBuffer> heapBuffer = [_heap newBufferWithLength:_dataBuffer[i].length
                                                      options:MTLResourceStorageModePrivate];

        // Blit contents of the original buffer to the new buffer
        [blitEncoder copyFromBuffer:_dataBuffer[i]
                       sourceOffset:0
                           toBuffer:heapBuffer
                  destinationOffset:0
                               size:heapBuffer.length];

        // Replace the existing buffer with the new buffer
        _dataBuffer[i] = heapBuffer;
    }

    [blitEncoder endEncoding];
    [commandBuffer commit];
}

在使用這些資源之前,該示例不是為每個資源調用useResource:usage:方法一次,而是為整個堆調用useHeap:方法一次。

#if ENABLE_RESOURCE_HEAP
        // Make a single `useHeap:` call for the entire heap, instead of one
        // `useResource:usage:` call per texture and per buffer
        [renderEncoder useHeap:_heap];
#else
        for(uint32_t i = 0; i < AAPLNumTextureArguments; i++)
        {
            // Indicate to Metal that these textures will be accessed by the GPU and
            // therefore must be mapped to the GPU's address space
            [renderEncoder useResource:_texture[i] usage:MTLResourceUsageSample];
        }

        for(uint32_t i = 0; i < AAPLNumBufferArguments; i++)
        {
            // Indicate to Metal that these buffers will be accessed by the GPU and
            // therefore must be mapped to the GPU's address space
            [renderEncoder useResource:_dataBuffer[i] usage:MTLResourceUsageRead];
        }
#endif

在此示例中,您學習了如何將參數緩沖區與資源數組和資源堆組合在一起。

后記

本篇主要講述了帶有數組和資源堆的參數緩沖區,感興趣的給個贊或者關注~~~

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容