[MetalKit]15-Using-MetalKit-part-9使用MetalKit9

862 阅读6分钟

本系列文章是对 metalkit.org 上面MetalKit内容的全面翻译和学习.

MetalKit系统文章目录


我打赌很多读者很相信MetalKit系列,所以今天我重回这个系列,我们将学习如何在Metal中绘制3D内容.让我们继续我们在playground中的工作,继续本系列的第8部分 part 8.

在本章结束时,我们将渲染一个3D立方体,但是首先让我们绘制一个2D矩形并复用这个矩形的逻辑来建议立方体的所有面.让我们修改vertex_data数组来保存4个顶点而不是原来三角形的3个顶点:

let vertex_data = [
    Vertex(pos: [-1.0, -1.0, 0.0,  1.0], col: [1, 0, 0, 1]),
    Vertex(pos: [ 1.0, -1.0, 0.0,  1.0], col: [0, 1, 0, 1]),
    Vertex(pos: [ 1.0,  1.0, 0.0,  1.0], col: [0, 0, 1, 1]),
    Vertex(pos: [-1.0,  1.0, 0.0,  1.0], col: [1, 1, 1, 1])
]

最有意思的部分来了.矩形和其它复杂几何体都是由三角形组成,并且大部分顶点属于2个或更多三角形,就不需要给这些顶点创建复本了,因为我们有一种办法通过index buffer索引缓冲器来复用它们,这种方法可以从vertex buffer顶点缓冲器中保存顶点索引到列表中,来追踪那些将要用到的顶点的顺序.所以让我们创建这样一份索引列表:

let index_data: [UInt16] = [
    0, 1, 2, 2, 3, 0
]

为了理解这些索引是如何被保存的,让我们看下面这幅图:

chapter09_1.jpg

对于前方的面(矩形)来说,我们用到的顶点储存在vertex buffer顶点缓冲器03号位.稍后我们将添加另外4个顶点.前面是由两个三角形构成.我们先用顶点0,12绘制一个三角形,然后用顶点2,30再绘制一个三角形.请注意,正如期待的那样,有两个顶点被重用了.还要注意的是绘制是以clockwise顺时针完成的.这是Metal中默认的正面绕序,但是也能被设置为counterclockwise逆时针的.

然后我们需要创建index_buffer:

var index_buffer: MTLBuffer!

下一步,我们需要在createBuffers()函数中把index_data赋值给index buffer:

index_buffer = device!.newBufferWithBytes(index_data, length: sizeof(UInt16) * index_data.count , options: [])

最后,在drawRect(:)函数中我们需要将drawPrimitives调用:

command_encoder.drawPrimitives(.Triangle, vertexStart: 0, vertexCount: 3, instanceCount: 1)

替换为drawIndexedPrimitives调用:

command_encoder.drawIndexedPrimitives(.Triangle, indexCount: index_buffer.length / sizeof(UInt16), indexType: MTLIndexType.UInt16, indexBuffer: index_buffer, indexBufferOffset: 0)

在playground主页面中,看看新产生的图像:

chapter09_2.png

现在我们知道如何绘制一个矩形了,让我们看看如何绘制更多矩形!

let vertex_data = [
    Vertex(pos: [-1.0, -1.0,  1.0, 1.0], col: [1, 0, 0, 1]),
    Vertex(pos: [ 1.0, -1.0,  1.0, 1.0], col: [0, 1, 0, 1]),
    Vertex(pos: [ 1.0,  1.0,  1.0, 1.0], col: [0, 0, 1, 1]),
    Vertex(pos: [-1.0,  1.0,  1.0, 1.0], col: [1, 1, 1, 1]),
    Vertex(pos: [-1.0, -1.0, -1.0, 1.0], col: [0, 0, 1, 1]),
    Vertex(pos: [ 1.0, -1.0, -1.0, 1.0], col: [1, 1, 1, 1]),
    Vertex(pos: [ 1.0,  1.0, -1.0, 1.0], col: [1, 0, 0, 1]),
    Vertex(pos: [-1.0,  1.0, -1.0, 1.0], col: [0, 1, 0, 1])
]
let index_data: [UInt16] = [
    0, 1, 2, 2, 3, 0,   // front

    1, 5, 6, 6, 2, 1,   // right

    3, 2, 6, 6, 7, 3,   // top

    4, 5, 1, 1, 0, 4,   // bottom

    4, 0, 3, 3, 7, 4,   // left

    7, 6, 5, 5, 4, 7,   // back

]

现在我们有了准备渲染的整个立方体,让我们来到MathUtils.swift中,在modelMatrix()中注释掉rotationtranslation调用,只保留缩放倍数为0.5.你将很可能看到一个像这样的图像:

chapter09_3.png

呃,但是仍然是一个矩形!是的,因为我们仍没有depth深度概念所以立方体看起来只是个平的.是时候来点数学魔法了.我们不需要使用Matrix矩阵结构体因为simd框架给我们提供了类似的数据结构和数学函数,我们可以直接使用.我们能轻易用matrix_float4x4代替自定义的Matrix结构体来重写我们的转换函数.

但是你可能会问,如何在我们2D屏幕上显示3D物体.这个过程将每个像素经过一系列变换.首先,modelMatrix() 将像素从物体空间转换到世界空间.这个矩阵是我们已经知道的,负责平移,旋转和缩放的那个.添加新的重写过的函数后,modelMatrix应该看起来像这样:

func modelMatrix() -> matrix_float4x4 {
    let scaled = scalingMatrix(0.5)
    let rotatedY = rotationMatrix(Float(M_PI)/4, float3(0, 1, 0))
    let rotatedX = rotationMatrix(Float(M_PI)/4, float3(1, 0, 0))
    return matrix_multiply(matrix_multiply(rotatedX, rotatedY), scaled)
}

你注意到用到的matrix_multiply函数因为Matrix结构体已经不能用了.同时,因为所有像素将经历同样的变换,我们想要把矩阵储存为一个Uniform并传递到vertex shader.为此,让我们创建一个新的结构体:

struct Uniforms {
    var modelViewProjectionMatrix: matrix_float4x4
}

回到createBuffers()函数,让我们用传递modelMatrix时用到的缓冲器指针来传递全局变量到着色器:

let modelViewProjectionMatrix = modelMatrix()
var uniforms = Uniforms(modelViewProjectionMatrix: modelViewProjectionMatrix)
memcpy(bufferPointer, &uniforms, sizeof(Uniforms))

在playground主页面中,看看新产生的图像:

chapter09_4.png

呃...立方体看上去差不多了,可是有些地方没了.下一步变换,像素将从世界空间摄像机空间.我们在屏幕上看到的所有东西都是被一个虚拟摄像机观察到的,它通过带有near最近far最远平面的frustum平头截体(金字塔形)来限制观察(摄像机)空间:

chapter09_5.png

回到MathUtils.swift让我们创建viewMatrix():

func viewMatrix() -> matrix_float4x4 {
    let cameraPosition = vector_float3(0, 0, -3)
    return translationMatrix(cameraPosition)
}

下一步的变换,像素将从camera space摄像机空间变换到clip space裁剪空间.这里,所有不在clip space裁剪空间里面的顶点将被判断,看三角形被culled剔除(所有顶点都在裁剪空间外)或clipped to bounds截断(某些顶点在外面某些在内部).projectionMatrix() 会帮我们计算边界并判断顶点在哪里:

func projectionMatrix(near: Float, far: Float, aspect: Float, fovy: Float) -> matrix_float4x4 {
    let scaleY = 1 / tan(fovy * 0.5)
    let scaleX = scaleY / aspect
    let scaleZ = -(far + near) / (far - near)
    let scaleW = -2 * far * near / (far - near)
    let X = vector_float4(scaleX, 0, 0, 0)
    let Y = vector_float4(0, scaleY, 0, 0)
    let Z = vector_float4(0, 0, scaleZ, -1)
    let W = vector_float4(0, 0, scaleW, 0)
    return matrix_float4x4(columns:(X, Y, Z, W))
}

最后两个变换是从clip space裁剪空间normalized device coordinates (NDC)规格化设备坐标,还有从NDCscreen space屏幕空间.这两步是由Metal框架为我们处理的.

下一步,回到createBuffers()函数,让我们修改modelViewProjectionMatrix,我们之前为了适应modelMatrix来设置的:

let aspect = Float(drawableSize.width / drawableSize.height)
let projMatrix = projectionMatrix(1, far: 100, aspect: aspect, fovy: 1.1)
let modelViewProjectionMatrix = matrix_multiply(projMatrix, matrix_multiply(viewMatrix(), modelMatrix()))

drawRect(:)中我们需要设置裁剪模式,正面模式,来避免出现奇怪的现象比如立方体透明了:

command_encoder.setFrontFacingWinding(.CounterClockwise)
command_encoder.setCullMode(.Back)

在playground主页面中,看看新产生的图像:

chapter09_6.png

这就是我们一直想看到的最终版3D立方体! 还要做一件事来让它更真实:让它旋转起来.首先,让我们创建一个全局变量命名为rotation,我们想要随着时间流逝来刷新它:

var rotation: Float = 0

下一步,从createBuffers()函数中取出矩阵,并创建一个新的命名为update().下面是我们每帧更新rotation来创建平滑滚动效果的地方:

func update() {
    let scaled = scalingMatrix(0.5)
    rotation += 1 / 100 * Float(M_PI) / 4
    let rotatedY = rotationMatrix(rotation, float3(0, 1, 0))
    let rotatedX = rotationMatrix(Float(M_PI) / 4, float3(1, 0, 0))
    let modelMatrix = matrix_multiply(matrix_multiply(rotatedX, rotatedY), scaled)
    let cameraPosition = vector_float3(0, 0, -3)
    let viewMatrix = translationMatrix(cameraPosition)
    let aspect = Float(drawableSize.width / drawableSize.height)
    let projMatrix = projectionMatrix(0, far: 10, aspect: aspect, fovy: 1)
    let modelViewProjectionMatrix = matrix_multiply(projMatrix, matrix_multiply(viewMatrix, modelMatrix))
    let bufferPointer = uniform_buffer.contents()
    var uniforms = Uniforms(modelViewProjectionMatrix: modelViewProjectionMatrix)
    memcpy(bufferPointer, &uniforms, sizeof(Uniforms))
}

drawRect(:)中调用update函数:

update()

在playground主页面中,看看新产生的图像:

chapter09_7.gif

源代码source code 已发布在Github上.

下次见!