[MetalKit]Using ARKit with Metal part 2使用ARKit與Metal 2
本系列文章是對 http://metalkit.org 上面MetalKit內容的全面翻譯和學習.
正如上次強調的那樣,在ARKit應用中共有三個層級:渲染
,追蹤
和場景理解
.上次我們詳細分析瞭如何用Metal
在自定義view中實現渲染. ARKit
使用了視覺慣性里程計
來精確追蹤周圍的世界,並將相機感測器資料和CoreMotion
資料結合起來.即使當我們在運動時,也無需額外調校來保持畫面穩定.本文中,我們關注場景理解-用平面檢測,點選測試和光線估計來描述場景屬性的方法.ARKit
能分析相機中的場景,並找到類似地板那樣的水平面.首先,我們需要啟用平面檢測功能(預設是off),只需在執行會話配置羊新增一行:
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let configuration = ARWorldTrackingConfiguration()
configuration.planeDetection = .horizontal
session.run(configuration)
}
注意:當前
API
版本下,只能檢測水平面
ARSessionObserver代理方法對處理會話錯誤,追蹤改變和打斷非常有用:
func session(_ session: ARSession, didFailWithError error: Error) {}
func session(_ session: ARSession, cameraDidChangeTrackingState camera: ARCamera) {}
func session(_ session: ARSession, didOutputAudioSampleBuffer audioSampleBuffer: CMSampleBuffer) {}
func sessionWasInterrupted(_ session: ARSession) {}
func sessionInterruptionEnded(_ session: ARSession) {}
還有另一些代理方法屬於ARSessionDelegate協議(屬於ARSessionObserver
擴充套件)能讓我們處理錨點.在第一個裡面寫上print():
func session(_ session: ARSession, didAdd anchors: [ARAnchor]) {
print(anchors)
}
func session(_ session: ARSession, didRemove anchors: [ARAnchor]) {}
func session(_ session: ARSession, didUpdate anchors: [ARAnchor]) {}
func session(_ session: ARSession, didUpdate frame: ARFrame) {}
讓我們進入到Renderer.swift裡面.首先,建立一些需要的類屬性.這些變數將幫助我們建立並在螢幕上顯示一個除錯用的平面:
var debugUniformBuffer: MTLBuffer!
var debugPipelineState: MTLRenderPipelineState!
var debugDepthState: MTLDepthStencilState!var debugMesh: MTKMesh!
var debugUniformBufferOffset: Int = 0
var debugUniformBufferAddress: UnsafeMutableRawPointer!
var debugInstanceCount: Int = 0
下一步,在setupPipeline()我們建立緩衝器:
debugUniformBuffer = device.makeBuffer(length: anchorUniformBufferSize, options: .storageModeShared)
我們需要給我們的平面建立新的頂點及片段函式,還有新的渲染管線和深度模板狀態.在建立命令佇列的前面新增幾行:
let debugGeometryVertexFunction = defaultLibrary.makeFunction(name: "vertexDebugPlane")!
let debugGeometryFragmentFunction = defaultLibrary.makeFunction(name: "fragmentDebugPlane")!
anchorPipelineStateDescriptor.vertexFunction = debugGeometryVertexFunction
anchorPipelineStateDescriptor.fragmentFunction = debugGeometryFragmentFunction
do { try debugPipelineState = device.makeRenderPipelineState(descriptor: anchorPipelineStateDescriptor)
} catch let error { print(error) }
debugDepthState = device.makeDepthStencilState(descriptor: anchorDepthStateDescriptor)
下一步,在setupAssets()裡我們需要建立一個新的Model I/O
平面網格,並用它建立Metal
網格.在函式的末尾新增幾行:
mdlMesh = MDLMesh(planeWithExtent: vector3(0.1, 0.1, 0.1), segments: vector2(1, 1), geometryType: .triangles, allocator: metalAllocator)
mdlMesh.vertexDescriptor = vertexDescriptor
do { try debugMesh = MTKMesh(mesh: mdlMesh, device: device)
} catch let error { print(error) }
下一步,在updateBufferStates()中我們需要更新平面所在緩衝器的地址.新增下面幾行:
debugUniformBufferOffset = alignedInstanceUniformSize * uniformBufferIndex
debugUniformBufferAddress = debugUniformBuffer.contents().advanced(by: debugUniformBufferOffset)
下一步,在updateAnchors()中我們需要更新變換矩陣和錨點數.在迴圈之前新增下面幾行:
let count = frame.anchors.filter{ $0.isKind(of: ARPlaneAnchor.self) }.count
debugInstanceCount = min(count, maxAnchorInstanceCount - (anchorInstanceCount - count))
然後,在迴圈中用下面幾行替換最後的三行:
if anchor.isKind(of: ARPlaneAnchor.self) {
let transform = anchor.transform * rotationMatrix(rotation: float3(0, 0, Float.pi/2))
let modelMatrix = simd_mul(transform, coordinateSpaceTransform)
let debugUniforms = debugUniformBufferAddress.assumingMemoryBound(to: InstanceUniforms.self).advanced(by: index)
debugUniforms.pointee.modelMatrix = modelMatrix
} else {
let modelMatrix = simd_mul(anchor.transform, coordinateSpaceTransform)
let anchorUniforms = anchorUniformBufferAddress.assumingMemoryBound(to: InstanceUniforms.self).advanced(by: index)
anchorUniforms.pointee.modelMatrix = modelMatrix
}
我們必須將平面繞z軸旋轉90度,來讓它呈水平
狀態.注意,我們使用了一個自定義方法,名為rotationMatrix(),讓我們來定義它.我們在以前的文章中,當第一次介紹3D
矩陣時就見過了這個矩陣:
func rotationMatrix(rotation: float3) -> float4x4 {
var matrix: float4x4 = matrix_identity_float4x4
let x = rotation.x
let y = rotation.y
let z = rotation.z
matrix.columns.0.x = cos(y) * cos(z)
matrix.columns.0.y = cos(z) * sin(x) * sin(y) - cos(x) * sin(z)
matrix.columns.0.z = cos(x) * cos(z) * sin(y) + sin(x) * sin(z)
matrix.columns.1.x = cos(y) * sin(z)
matrix.columns.1.y = cos(x) * cos(z) + sin(x) * sin(y) * sin(z)
matrix.columns.1.z = -cos(z) * sin(x) + cos(x) * sin(y) * sin(z)
matrix.columns.2.x = -sin(y)
matrix.columns.2.y = cos(y) * sin(x)
matrix.columns.2.z = cos(x) * cos(y)
matrix.columns.3.w = 1.0
return matrix
}
下一步,在drawAnchorGeometry()中我們需要確保我們在繪製之前至少有一個錨點.將第一行替換為下面這行:
guard anchorInstanceCount - debugInstanceCount > 0 else { return }
下一步,讓我們建立drawDebugGeometry()函式來繪製我們的平面.它非常類似於錨點繪製函式:
func drawDebugGeometry(renderEncoder: MTLRenderCommandEncoder) {
guard debugInstanceCount > 0 else { return }
renderEncoder.pushDebugGroup("DrawDebugPlanes")
renderEncoder.setCullMode(.back)
renderEncoder.setRenderPipelineState(debugPipelineState)
renderEncoder.setDepthStencilState(debugDepthState)
renderEncoder.setVertexBuffer(debugUniformBuffer, offset: debugUniformBufferOffset, index: 2)
renderEncoder.setVertexBuffer(sharedUniformBuffer, offset: sharedUniformBufferOffset, index: 3)
renderEncoder.setFragmentBuffer(sharedUniformBuffer, offset: sharedUniformBufferOffset, index: 3)
for bufferIndex in 0..<debugMesh.vertexBuffers.count {
let vertexBuffer = debugMesh.vertexBuffers[bufferIndex]
renderEncoder.setVertexBuffer(vertexBuffer.buffer, offset: vertexBuffer.offset, index:bufferIndex)
}
for submesh in debugMesh.submeshes {
renderEncoder.drawIndexedPrimitives(type: submesh.primitiveType, indexCount: submesh.indexCount, indexType: submesh.indexType, indexBuffer: submesh.indexBuffer.buffer, indexBufferOffset: submesh.indexBuffer.offset, instanceCount: debugInstanceCount)
}
renderEncoder.popDebugGroup()
}
在Renderer
中,還有一件需要完成,就是-在update()中結束編碼前,呼叫這個函式:
drawDebugGeometry(renderEncoder: renderEncoder)
最後,讓我們進入Shaders.metal檔案中.我們需要一個新的結構體,只包含從頂點描述符中傳遞過來的頂點位置:
typedef struct {
float3 position [[attribute(0)]];
} DebugVertex;
在頂點著色器中我們用模型-檢視矩陣來更新頂點位置:
vertex float4 vertexDebugPlane(DebugVertex in [[ stage_in]],
constant SharedUniforms &sharedUniforms [[ buffer(3) ]],
constant InstanceUniforms *instanceUniforms [[ buffer(2) ]],
ushort vid [[vertex_id]],
ushort iid [[instance_id]]) {
float4 position = float4(in.position, 1.0);
float4x4 modelMatrix = instanceUniforms[iid].modelMatrix;
float4x4 modelViewMatrix = sharedUniforms.viewMatrix * modelMatrix;
float4 outPosition = sharedUniforms.projectionMatrix * modelViewMatrix * position;
return outPosition;
}
最後,在片段著色器中,我們給平面一個顯眼在顏色以便於在檢視中觀察到它:
fragment float4 fragmentDebugPlane() {
return float4(0.99, 0.42, 0.62, 1.0);
}
如果你執行應用,當檢測到平面時,你將看到新增了一個矩形,像這樣:
接下來要做的是當我們檢測到更多或從先前檢測到的平面上移開時,更新/移除平面.別一個代理方法能幫助我們實現這個效果.接下來,我們將研究碰撞和物理效果.只是對以後的思考.
我要感謝Caroline為本文構造了平面檢測.
原始碼source code已釋出在Github上.
下次見!
相關文章
- [MetalKit]38-Using-ARKit-with-Metal-part-2使用ARKit與Metal-2
- [MetalKit]37-Using-ARKit-with-Metal使用ARKit與Metal
- [MetalKit]45-Using eGPUs with Metal 在 eGPU上使用 MetalGPU
- [MetalKit]32-Shadows-in-Metal-part-2陰影2
- [MetalKit]36-Introducing-Metal-2介紹Metal2
- [譯]基於 Metal 的 ARKit 使用指南(下)
- [譯] 基於 Metal 的 ARKit 使用指南(上)
- [MetalKit]35-Working-with-memory-in-Metal-part-2記憶體管理2記憶體
- [MetalKit]3-Using-MetalKit-part-2使用MetalKit2
- [MetalKit]42-Metal 2 on the A11 GPUGPU
- [MetalKit]40-Working-with-Particles-in-Metal-part2粒子系統2
- [MetalKit]28-Using-MetalKit-part-2-3^2使用MetalKit18
- [MetalKit]2-Using-MetalKit-part-1使用MetalKit1
- [MetalKit]43-Metal By Tutorials book! Metal教程書籍
- [MetalKit]46-Introduction to compute using Metal 用 Metal 進行計算的簡介
- Developing for ARKit 1.5 update using Unity ARKit PlugindevUnityPlugin
- [MetalKit]31-Shadows-in-Metal-part-1陰影1
- [MetalKit]47-Introducing Metal 3 Metal 3簡介
- [MetalKit]23-Using-MetalKit-part-16使用MetalKit16
- [MetalKit]22-Using-MetalKit-part-15使用MetalKit15
- [MetalKit]20-Using-MetalKit-part-14使用MetalKit14
- [MetalKit]19-Using-MetalKit-part-13使用MetalKit13
- [MetalKit]18-Using-MetalKit-part-12使用MetalKit12
- [MetalKit]27-Using-MetalKit-part-17使用MetalKit17
- [MetalKit]17-Using-MetalKit-part-11使用MetalKit11
- [MetalKit]16-Using-MetalKit-part-10使用MetalKit10
- [MetalKit]15-Using-MetalKit-part-9使用MetalKit9
- [MetalKit]9-Using-MetalKit-part-8使用MetalKit8
- [MetalKit]8-Using-MetalKit-part-7使用MetalKit7
- [MetalKit]7-Using-MetalKit-part-6使用MetalKit6
- [MetalKit]6-Using-MetalKit-part-5使用MetalKit5
- [MetalKit]5-Using-MetalKit-part-4使用MetalKit4
- [MetalKit]4-Using-MetalKit-part-3使用MetalKit3
- [MetalKit]41-Working-with-Particles-in-Metal-part3粒子系統3
- ARKit 入坑 2 開發篇
- [MetalKit]1-Introducing介紹Metal
- 魅藍metal2和魅藍metal有什麼區別?
- [MetalKit]39-Working-with-Particles-in-Metal粒子系統