-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathUtilities.swift
More file actions
526 lines (409 loc) · 14.9 KB
/
Utilities.swift
File metadata and controls
526 lines (409 loc) · 14.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
/*
See LICENSE folder for this sample’s licensing information.
Abstract:
Utility functions and type extensions used throughout the projects.
*/
import Foundation
import ARKit
// - MARK: UIImage extensions
extension UIImage {
func inverted() -> UIImage? {
guard let ciImage = CIImage(image: self) else {
return nil
}
return UIImage(ciImage: ciImage.applyingFilter("CIColorInvert"))
}
static func composeButtonImage(from thumbImage: UIImage, alpha: CGFloat = 1.0) -> UIImage {
let maskImage = #imageLiteral(resourceName: "buttonring")
var thumbnailImage = thumbImage
if let invertedImage = thumbImage.inverted() {
thumbnailImage = invertedImage
}
// Compose a button image based on a white background and the inverted thumbnail image.
UIGraphicsBeginImageContextWithOptions(maskImage.size, false, 0.0)
let maskDrawRect = CGRect(origin: CGPoint.zero,
size: maskImage.size)
let thumbDrawRect = CGRect(origin: CGPoint((maskImage.size - thumbImage.size) / 2),
size: thumbImage.size)
maskImage.draw(in: maskDrawRect, blendMode: .normal, alpha: alpha)
thumbnailImage.draw(in: thumbDrawRect, blendMode: .normal, alpha: alpha)
let composedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return composedImage!
}
}
// MARK: - Collection extensions
extension Array where Iterator.Element == CGFloat {
var average: CGFloat? {
guard !isEmpty else {
return nil
}
var ret = self.reduce(CGFloat(0)) { (cur, next) -> CGFloat in
var cur = cur
cur += next
return cur
}
let fcount = CGFloat(count)
ret /= fcount
return ret
}
}
extension Array where Iterator.Element == SCNVector3 {
var average: SCNVector3? {
guard !isEmpty else {
return nil
}
var ret = self.reduce(SCNVector3Zero) { (cur, next) -> SCNVector3 in
var cur = cur
cur.x += next.x
cur.y += next.y
cur.z += next.z
return cur
}
let fcount = Float(count)
ret.x /= fcount
ret.y /= fcount
ret.z /= fcount
return ret
}
}
extension RangeReplaceableCollection where IndexDistance == Int {
mutating func keepLast(_ elementsToKeep: Int) {
if count > elementsToKeep {
self.removeFirst(count - elementsToKeep)
}
}
}
// MARK: - SCNNode extension
extension SCNNode {
func setUniformScale(_ scale: Float) {
self.scale = SCNVector3Make(scale, scale, scale)
}
func renderOnTop() {
self.renderingOrder = 2
if let geom = self.geometry {
for material in geom.materials {
material.readsFromDepthBuffer = false
}
}
for child in self.childNodes {
child.renderOnTop()
}
}
}
// MARK: - SCNMaterial extensions
extension SCNMaterial {
static func material(withDiffuse diffuse: Any?, respondsToLighting: Bool = true) -> SCNMaterial {
let material = SCNMaterial()
material.diffuse.contents = diffuse
material.isDoubleSided = true
if respondsToLighting {
material.locksAmbientWithDiffuse = true
} else {
material.ambient.contents = UIColor.black
material.lightingModel = .constant
material.emission.contents = diffuse
}
return material
}
}
// MARK: - CGPoint extensions
extension CGPoint {
init(_ size: CGSize) {
self.x = size.width
self.y = size.height
}
init(_ vector: SCNVector3) {
self.x = CGFloat(vector.x)
self.y = CGFloat(vector.y)
}
func distanceTo(_ point: CGPoint) -> CGFloat {
return (self - point).length()
}
func length() -> CGFloat {
return sqrt(self.x * self.x + self.y * self.y)
}
func midpoint(_ point: CGPoint) -> CGPoint {
return (self + point) / 2
}
func friendlyString() -> String {
return "(\(String(format: "%.2f", x)), \(String(format: "%.2f", y)))"
}
}
func + (left: CGPoint, right: CGPoint) -> CGPoint {
return CGPoint(x: left.x + right.x, y: left.y + right.y)
}
func - (left: CGPoint, right: CGPoint) -> CGPoint {
return CGPoint(x: left.x - right.x, y: left.y - right.y)
}
func += (left: inout CGPoint, right: CGPoint) {
left = left + right
}
func -= (left: inout CGPoint, right: CGPoint) {
left = left - right
}
func / (left: CGPoint, right: CGFloat) -> CGPoint {
return CGPoint(x: left.x / right, y: left.y / right)
}
func * (left: CGPoint, right: CGFloat) -> CGPoint {
return CGPoint(x: left.x * right, y: left.y * right)
}
func /= (left: inout CGPoint, right: CGFloat) {
left = left / right
}
func *= (left: inout CGPoint, right: CGFloat) {
left = left * right
}
// MARK: - CGSize extensions
extension CGSize {
init(_ point: CGPoint) {
self.width = point.x
self.height = point.y
}
func friendlyString() -> String {
return "(\(String(format: "%.2f", width)), \(String(format: "%.2f", height)))"
}
}
func + (left: CGSize, right: CGSize) -> CGSize {
return CGSize(width: left.width + right.width, height: left.height + right.height)
}
func - (left: CGSize, right: CGSize) -> CGSize {
return CGSize(width: left.width - right.width, height: left.height - right.height)
}
func += (left: inout CGSize, right: CGSize) {
left = left + right
}
func -= (left: inout CGSize, right: CGSize) {
left = left - right
}
func / (left: CGSize, right: CGFloat) -> CGSize {
return CGSize(width: left.width / right, height: left.height / right)
}
func * (left: CGSize, right: CGFloat) -> CGSize {
return CGSize(width: left.width * right, height: left.height * right)
}
func /= (left: inout CGSize, right: CGFloat) {
left = left / right
}
func *= (left: inout CGSize, right: CGFloat) {
left = left * right
}
// MARK: - CGRect extensions
extension CGRect {
var mid: CGPoint {
return CGPoint(x: midX, y: midY)
}
}
func rayIntersectionWithHorizontalPlane(rayOrigin: SCNVector3, direction: SCNVector3, planeY: Float) -> SCNVector3? {
let direction = direction.normalized()
// Special case handling: Check if the ray is horizontal as well.
if direction.y == 0 {
if rayOrigin.y == planeY {
// The ray is horizontal and on the plane, thus all points on the ray intersect with the plane.
// Therefore we simply return the ray origin.
return rayOrigin
} else {
// The ray is parallel to the plane and never intersects.
return nil
}
}
// The distance from the ray's origin to the intersection point on the plane is:
// (pointOnPlane - rayOrigin) dot planeNormal
// --------------------------------------------
// direction dot planeNormal
// Since we know that horizontal planes have normal (0, 1, 0), we can simplify this to:
let dist = (planeY - rayOrigin.y) / direction.y
// Do not return intersections behind the ray's origin.
if dist < 0 {
return nil
}
// Return the intersection point.
return rayOrigin + (direction * dist)
}
extension ARSCNView {
struct HitTestRay {
let origin: SCNVector3
let direction: SCNVector3
}
func hitTestRayFromScreenPos(_ point: CGPoint) -> HitTestRay? {
guard let frame = self.session.currentFrame else {
return nil
}
let cameraPos = SCNVector3.positionFromTransform(frame.camera.transform)
// Note: z: 1.0 will unproject() the screen position to the far clipping plane.
let positionVec = SCNVector3(x: Float(point.x), y: Float(point.y), z: 1.0)
let screenPosOnFarClippingPlane = self.unprojectPoint(positionVec)
var rayDirection = screenPosOnFarClippingPlane - cameraPos
rayDirection.normalize()
return HitTestRay(origin: cameraPos, direction: rayDirection)
}
func hitTestWithInfiniteHorizontalPlane(_ point: CGPoint, _ pointOnPlane: SCNVector3) -> SCNVector3? {
guard let ray = hitTestRayFromScreenPos(point) else {
return nil
}
// Do not intersect with planes above the camera or if the ray is almost parallel to the plane.
if ray.direction.y > -0.03 {
return nil
}
// Return the intersection of a ray from the camera through the screen position with a horizontal plane
// at height (Y axis).
return rayIntersectionWithHorizontalPlane(rayOrigin: ray.origin, direction: ray.direction, planeY: pointOnPlane.y)
}
struct FeatureHitTestResult {
let position: SCNVector3
let distanceToRayOrigin: Float
let featureHit: SCNVector3
let featureDistanceToHitResult: Float
}
func hitTestWithFeatures(_ point: CGPoint, coneOpeningAngleInDegrees: Float,
minDistance: Float = 0,
maxDistance: Float = Float.greatestFiniteMagnitude,
maxResults: Int = 1) -> [FeatureHitTestResult] {
var results = [FeatureHitTestResult]()
guard let features = self.session.currentFrame?.rawFeaturePoints else {
return results
}
guard let ray = hitTestRayFromScreenPos(point) else {
return results
}
let maxAngleInDeg = min(coneOpeningAngleInDegrees, 360) / 2
let maxAngle = ((maxAngleInDeg / 180) * Float.pi)
let points = features.__points
for i in 0...features.__count {
let feature = points.advanced(by: Int(i))
let featurePos = SCNVector3(feature.pointee)
let originToFeature = featurePos - ray.origin
let crossProduct = originToFeature.cross(ray.direction)
let featureDistanceFromResult = crossProduct.length
let hitTestResult = ray.origin + (ray.direction * ray.direction.dot(originToFeature))
let hitTestResultDistance = (hitTestResult - ray.origin).length
if hitTestResultDistance < minDistance || hitTestResultDistance > maxDistance {
// Skip this feature - it is too close or too far away.
continue
}
let originToFeatureNormalized = originToFeature.normalized()
let angleBetweenRayAndFeature = acos(ray.direction.dot(originToFeatureNormalized))
if angleBetweenRayAndFeature > maxAngle {
// Skip this feature - is is outside of the hit test cone.
continue
}
// All tests passed: Add the hit against this feature to the results.
results.append(FeatureHitTestResult(position: hitTestResult,
distanceToRayOrigin: hitTestResultDistance,
featureHit: featurePos,
featureDistanceToHitResult: featureDistanceFromResult))
}
// Sort the results by feature distance to the ray.
results = results.sorted(by: { (first, second) -> Bool in
return first.distanceToRayOrigin < second.distanceToRayOrigin
})
// Cap the list to maxResults.
var cappedResults = [FeatureHitTestResult]()
var i = 0
while i < maxResults && i < results.count {
cappedResults.append(results[i])
i += 1
}
return cappedResults
}
func hitTestWithFeatures(_ point: CGPoint) -> [FeatureHitTestResult] {
var results = [FeatureHitTestResult]()
guard let ray = hitTestRayFromScreenPos(point) else {
return results
}
if let result = self.hitTestFromOrigin(origin: ray.origin, direction: ray.direction) {
results.append(result)
}
return results
}
func hitTestFromOrigin(origin: SCNVector3, direction: SCNVector3) -> FeatureHitTestResult? {
guard let features = self.session.currentFrame?.rawFeaturePoints else {
return nil
}
let points = features.__points
// Determine the point from the whole point cloud which is closest to the hit test ray.
var closestFeaturePoint = origin
var minDistance = Float.greatestFiniteMagnitude
for i in 0...features.__count {
let feature = points.advanced(by: Int(i))
let featurePos = SCNVector3(feature.pointee)
let originVector = origin - featurePos
let crossProduct = originVector.cross(direction)
let featureDistanceFromResult = crossProduct.length
if featureDistanceFromResult < minDistance {
closestFeaturePoint = featurePos
minDistance = featureDistanceFromResult
}
}
// Compute the point along the ray that is closest to the selected feature.
let originToFeature = closestFeaturePoint - origin
let hitTestResult = origin + (direction * direction.dot(originToFeature))
let hitTestResultDistance = (hitTestResult - origin).length
return FeatureHitTestResult(position: hitTestResult,
distanceToRayOrigin: hitTestResultDistance,
featureHit: closestFeaturePoint,
featureDistanceToHitResult: minDistance)
}
}
// MARK: - Simple geometries
func createAxesNode(quiverLength: CGFloat, quiverThickness: CGFloat) -> SCNNode {
let quiverThickness = (quiverLength / 50.0) * quiverThickness
let chamferRadius = quiverThickness / 2.0
let xQuiverBox = SCNBox(width: quiverLength, height: quiverThickness, length: quiverThickness, chamferRadius: chamferRadius)
xQuiverBox.materials = [SCNMaterial.material(withDiffuse: UIColor.red, respondsToLighting: false)]
let xQuiverNode = SCNNode(geometry: xQuiverBox)
xQuiverNode.position = SCNVector3Make(Float(quiverLength / 2.0), 0.0, 0.0)
let yQuiverBox = SCNBox(width: quiverThickness, height: quiverLength, length: quiverThickness, chamferRadius: chamferRadius)
yQuiverBox.materials = [SCNMaterial.material(withDiffuse: UIColor.green, respondsToLighting: false)]
let yQuiverNode = SCNNode(geometry: yQuiverBox)
yQuiverNode.position = SCNVector3Make(0.0, Float(quiverLength / 2.0), 0.0)
let zQuiverBox = SCNBox(width: quiverThickness, height: quiverThickness, length: quiverLength, chamferRadius: chamferRadius)
zQuiverBox.materials = [SCNMaterial.material(withDiffuse: UIColor.blue, respondsToLighting: false)]
let zQuiverNode = SCNNode(geometry: zQuiverBox)
zQuiverNode.position = SCNVector3Make(0.0, 0.0, Float(quiverLength / 2.0))
let quiverNode = SCNNode()
quiverNode.addChildNode(xQuiverNode)
quiverNode.addChildNode(yQuiverNode)
quiverNode.addChildNode(zQuiverNode)
quiverNode.name = "Axes"
return quiverNode
}
func createCrossNode(size: CGFloat = 0.01, color: UIColor = UIColor.green, horizontal: Bool = true, opacity: CGFloat = 1.0) -> SCNNode {
// Create a size x size m plane and put a grid texture onto it.
let planeDimension = size
var fileName = ""
switch color {
case UIColor.blue:
fileName = "crosshair_blue"
case UIColor.yellow:
fallthrough
default:
fileName = "crosshair_yellow"
}
let path = Bundle.main.path(forResource: fileName, ofType: "png", inDirectory: "Models.scnassets")!
let image = UIImage(contentsOfFile: path)
let planeNode = SCNNode(geometry: createSquarePlane(size: planeDimension, contents: image))
if let material = planeNode.geometry?.firstMaterial {
material.ambient.contents = UIColor.black
material.lightingModel = .constant
}
if horizontal {
planeNode.eulerAngles = SCNVector3Make(Float.pi / 2.0, 0, Float.pi) // Horizontal.
} else {
planeNode.constraints = [SCNBillboardConstraint()] // Facing the screen.
}
let cross = SCNNode()
cross.addChildNode(planeNode)
cross.opacity = opacity
return cross
}
func createSquarePlane(size: CGFloat, contents: AnyObject?) -> SCNPlane {
let plane = SCNPlane(width: size, height: size)
plane.materials = [SCNMaterial.material(withDiffuse: contents)]
return plane
}
func createPlane(size: CGSize, contents: AnyObject?) -> SCNPlane {
let plane = SCNPlane(width: size.width, height: size.height)
plane.materials = [SCNMaterial.material(withDiffuse: contents)]
return plane
}