[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]45-Using eGPUs with Metal 在 eGPU上使用 MetalGPU
- [MetalKit]46-Introduction to compute using Metal 用 Metal 進行計算的簡介
- [MetalKit]43-Metal By Tutorials book! Metal教程書籍
- [MetalKit]47-Introducing Metal 3 Metal 3簡介
- Developing for ARKit 1.5 update using Unity ARKit PlugindevUnityPlugin
- [MetalKit]44-Raytracing with Metal射線追蹤
- WWDC 2018: ARKit 2 的新功能
- metal2的四個新features
- metal
- 在 SwiftUI 中使用 Metal ShaderSwiftUI
- 初識ARKit
- [ARKit]7-ARKit1.5的圖片識別功能
- 15-《ARKit by Tutorials》讀書筆記2:時空門筆記
- Metal日記:使用步驟指南
- 翻譯 | Learning React Without Using React Part 2React
- [譯]Metal 渲染管線教程
- [ARKit]12-[譯]在ARKit中建立一個時空門App:新增物體APP
- [ARKit]11-[譯]在ARKit中建立一個時空門App:準備開始APP
- [ARKit]13-[譯]在ARKit中建立一個時空門App:材質和光照APP
- iOS計算機視覺—ARKitiOS計算機視覺
- 直擊蘋果 ARKit 技術蘋果
- LoadBalancer for bare metal Kubernetes cluster-MetalLB
- Metal入門教程(四)灰度計算
- ARKit中控制.dae動畫的播放動畫
- ARKit 如何給SCNNode貼Gif圖片CNN
- Unity3D ARKit 參考文章Unity3D
- Metal入門教程(一)圖片繪製
- Metal入門教程(二)三維變換
- 基於ARkit和SceneKit檢測相機位置和設定2個物體碰撞的事件事件
- [ARKit]6-3D與AR/VR應用Debug與優化淺談3DVR優化
- iOS ARKit錄製視訊(AVAssetWriter & 有聲音)iOS
- Flutter在iOS上採用Metal驅動GPUFlutteriOSGPU
- Metal新特性:大幅度提升iOS端效能iOS
- 裸金屬伺服器(Bare Metal Server,BMS)伺服器Server
- 使用JDK 17執行IntelliJ IDEA以獲得更好的Metal渲染效能JDKIntelliJIdea
- Metal入門教程(三)攝像頭採集渲染
- [ARKit]9-3D/AR 中的 simd 型別3D型別
- JVM的GC理論知識 – Bare.Metal.DevJVMGCdev
- Selenium Part2: WebDriverAPI 的使用WebAPI