-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathViewController.swift
More file actions
719 lines (500 loc) · 30.9 KB
/
ViewController.swift
File metadata and controls
719 lines (500 loc) · 30.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
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
//
// ViewController.swift
// RestARant
//
// Created by Maxwell Hubbard on 10/12/18.
// Copyright © 2018 Maxwell Hubbard. All rights reserved.
//
import UIKit
import SceneKit
import ARKit
import Vision
import FirebaseStorage
extension UIColor {
convenience init(red: Int, green: Int, blue: Int) {
assert(red >= 0 && red <= 255, "Invalid red component")
assert(green >= 0 && green <= 255, "Invalid green component")
assert(blue >= 0 && blue <= 255, "Invalid blue component")
self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0)
}
convenience init(rgb: Int) {
self.init(
red: (rgb >> 16) & 0xFF,
green: (rgb >> 8) & 0xFF,
blue: rgb & 0xFF
)
}
}
extension UIView {
func fadeTo(_ alpha: CGFloat, duration: TimeInterval? = 0.3) {
DispatchQueue.main.async {
UIView.animate(withDuration: duration != nil ? duration! : 0.3) {
self.alpha = alpha
}
}
}
func fadeIn(_ duration: TimeInterval? = 0.3) {
fadeTo(1.0, duration: duration)
}
func fadeOut(_ duration: TimeInterval? = 0.3) {
fadeTo(0.0, duration: duration)
}
}
protocol PropertyStoring {
associatedtype T
func getAssociatedObject(_ key: UnsafeRawPointer!, defaultValue: T) -> T
}
extension PropertyStoring {
func getAssociatedObject(_ key: UnsafeRawPointer!, defaultValue: T) -> T {
guard let value = objc_getAssociatedObject(self, key) as? T else {
return defaultValue
}
return value
}
}
extension UIView : PropertyStoring{
typealias T = UIView
private struct CustomProperties {
static var toggleState = UIView()
}
var container: UIView {
get {
return getAssociatedObject(&CustomProperties.toggleState, defaultValue: CustomProperties.toggleState)
}
set {
return objc_setAssociatedObject(self, &CustomProperties.toggleState, newValue, .OBJC_ASSOCIATION_RETAIN)
}
}
func showActivityIndicatory() {
if container != nil {
container.removeFromSuperview()
}
container = UIView()
container.frame = frame
container.center = center
container.backgroundColor = UIColor(rgb: 0xffffff).withAlphaComponent(0.3)
let loadingView: UIView = UIView()
loadingView.frame = CGRect(x:0, y:0, width:80, height:80)
loadingView.center = center
loadingView.backgroundColor = UIColor(rgb: 0x444444).withAlphaComponent(0.7)
loadingView.clipsToBounds = true
loadingView.layer.cornerRadius = 10
let actInd: UIActivityIndicatorView = UIActivityIndicatorView()
actInd.frame = CGRect(x:0.0, y:0.0, width:40.0, height:40.0);
actInd.style =
UIActivityIndicatorView.Style.whiteLarge
actInd.center = CGPoint(x:loadingView.frame.size.width / 2,
y:loadingView.frame.size.height / 2);
loadingView.addSubview(actInd)
container.addSubview(loadingView)
addSubview(container)
actInd.startAnimating()
}
}
class ViewController: UIViewController, ARSCNViewDelegate {
@IBOutlet var sceneView: ARSCNView!
@IBOutlet weak var foodVisualView: UIVisualEffectView!
@IBOutlet weak var foodLabel: UILabel!
@IBOutlet weak var closeVisualView: UIVisualEffectView!
@IBOutlet weak var closeButton: UIButton!
@IBOutlet weak var calorieVisualView: UIVisualEffectView!
@IBOutlet weak var calorieLabel: UILabel!
@IBOutlet weak var ingredientVisualView: UIVisualEffectView!
@IBOutlet weak var ingredientScroller: UIScrollView!
var requests = [VNRequest]()
var looking: Bool = false
var loaded: Bool = false
var info: Information = Information()
func startDetection() {
let request = VNDetectBarcodesRequest(completionHandler: self.detectHandler)
request.symbologies = [VNBarcodeSymbology.QR]
self.requests = [request]
}
func detectHandler(request: VNRequest, error: Error?) {
guard let observations = request.results else {
//print("no result")
return
}
let results = observations.map({$0 as? VNBarcodeObservation})
if results.count > 0 && !looking {
let result = results[0]
self.view.showActivityIndicatory()
if (result!.payloadStringValue!.contains(" | ")) {
print(result!.payloadStringValue!)
let res = result!.payloadStringValue!.components(separatedBy: " | ")[0]
let dataSearch = result!.payloadStringValue!.components(separatedBy: " | ")[1]
let storage = Storage.storage()
let storageRef = storage.reference()
let modelReference = storageRef.child("Models/" + res + ".scn")
let textureReference = storageRef.child("Textures/" + res + "/Color.png")
let ingredientsReference = storageRef.child("Information/" + res + ".json")
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let modelURL = documentsURL.appendingPathComponent(res + "/" + res + ".scn")
let texURL = documentsURL.appendingPathComponent(res + "/Color.png")
self.looking = true
textureReference.write(toFile: texURL) { url, error in
if let error = error {
// Uh-oh, an error occurred!
print("ERROR: ",error.localizedDescription)
self.view.container.removeFromSuperview()
let alert = UIAlertController(title: "Invalid", message: "Sorry! This QR code is invalid!", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alert, animated: true)
self.looking = false
} else {
// Download to the local filesystem
modelReference.write(toFile: modelURL) { url, error in
if let error = error {
// Uh-oh, an error occurred!
print("Here's the error", error.localizedDescription)
self.looking = false
} else {
self.view.container.removeFromSuperview()
self.foodLabel.text = res
self.foodVisualView.fadeIn()
self.foodLabel.fadeIn()
self.closeVisualView.fadeIn()
self.closeButton.fadeIn()
USDA.search(s: res, ds: dataSearch) { item in
let ndbno = (item["ndbno"] as! NSString)
USDA.getNutrients(id: ndbno as String) { (nutrients) in
for nut in nutrients {
if ((nut["nutrient_id"]!) as AnyObject).isKind(of: NSNumber.self) {
if nut["nutrient_id"] as! Int == 208 {
self.info.calories = nut["value"] as! Double
DispatchQueue.main.async {
self.calorieLabel.text = String(describing: self.info.calories) + " Calories"
self.calorieVisualView.fadeIn()
self.calorieLabel.fadeIn()
}
} else {
let name = nut["name"] as! String
let unit = nut["unit"] as! String
var value = 0.0;
if ((nut["value"]!) as AnyObject).isKind(of: NSNumber.self) {
value = nut["value"] as! Double
} else {
value = (nut["value"] as! NSString).doubleValue
}
let regex = try! NSRegularExpression(pattern: "[a-zA-Z, \\s]+", options: [])
let range = regex.rangeOfFirstMatch(in: name, options: [], range: NSRange(location: 0, length: name.characters.count))
if range.length == name.characters.count {
self.info.nutrients[name] = String(describing: value) + unit
}
}
} else if nut["nutrient_id"] as! String == "208" {
self.info.calories = (nut["value"] as! NSString).doubleValue
DispatchQueue.main.async {
self.calorieLabel.text = String(describing: self.info.calories) + " Calories"
self.calorieVisualView.fadeIn()
self.calorieLabel.fadeIn()
}
} else {
let name = nut["name"] as! String
let unit = nut["unit"] as! String
var value = 0.0;
if ((nut["value"]!) as AnyObject).isKind(of: NSNumber.self) {
value = nut["value"] as! Double
} else {
value = (nut["value"] as! NSString).doubleValue
}
let regex = try! NSRegularExpression(pattern: "[a-zA-Z, \\s]+", options: [])
let range = regex.rangeOfFirstMatch(in: name, options: [], range: NSRange(location: 0, length: name.characters.count))
if range.length == name.characters.count {
self.info.nutrients[name] = String(describing: value) + unit
}
}
}
}
}
ingredientsReference.getData(maxSize: 1 * 1024 * 1024) { data, error in
if let error = error {
// Uh-oh, an error occurred!
print(error.localizedDescription)
} else {
// Data for "images/island.jpg" is returned
let json = try? JSONSerialization.jsonObject(with: data!, options: [])
if let dictionary = json as? [String: Any] {
self.info.calories = dictionary["Calories"] as! Double
if let ingredients = dictionary["Ingredients"] as? [String] {
self.info.ingredients = ingredients
for c in self.ingredientScroller.subviews {
c.removeFromSuperview()
}
let contentView = self.ingredientVisualView.contentView
for i in 0...self.info.ingredients.count - 1 {
let label = UILabel()
label.text = self.info.ingredients[i]
label.frame = CGRect(x: 0, y: i * 40, width: Int(contentView.frame.width), height: 35)
label.textAlignment = .center
label.adjustsFontSizeToFitWidth = true
label.adjustsFontForContentSizeCategory = true
label.isUserInteractionEnabled = true
label.numberOfLines = 0
label.textColor = .white
self.ingredientScroller.addSubview(label)
}
self.ingredientScroller.contentSize = CGSize(width: contentView.frame.width, height: CGFloat(self.info.ingredients.count * 40))
}
if let scale = dictionary["Scale"] as? [CGFloat] {
self.info.scale = SCNVector3(scale[0], scale[1], scale[2])
do {
try self.sceneView.scene = SCNScene(url: url!, options: nil)
let root = self.sceneView.scene.rootNode
if root.childNodes.count > 0 {
root.childNodes[0].scale = self.info.scale
}
} catch{}
}
self.ingredientVisualView.fadeIn()
self.ingredientScroller.fadeIn()
self.loaded = true
}
}
}
}
}
}
}
}
}
}
var detectedDataAnchor: ARAnchor?
func hitTestQrCode(center: CGPoint) {
let hitTestResults = self.sceneView.hitTest(center, types: [.featurePoint] )
let hitTestResult = hitTestResults.first
if hitTestResult != nil {
if let detectedDataAnchor = self.detectedDataAnchor,
let node = self.sceneView.node(for: detectedDataAnchor) {
node.transform = SCNMatrix4(hitTestResult!.worldTransform)
} else {
// Create an anchor. The node will be created in delegate methods
self.detectedDataAnchor = ARAnchor(transform: hitTestResult!.worldTransform)
self.sceneView.session.add(anchor: self.detectedDataAnchor!)
}
}
}
@IBAction func nutrientsChange(_ sender: UIButton) {
if sender.titleLabel!.text == "Nutrients" {
// Add Nutrients
sender.setTitle("Ingredients", for: .normal)
for c in self.ingredientScroller.subviews {
c.removeFromSuperview()
}
let contentView = self.ingredientVisualView.contentView
var j = 0
for i in self.info.nutrients {
let label = UILabel()
label.text = i.key + ": " + i.value
label.frame = CGRect(x: 0, y: j * 40, width: Int(contentView.frame.width), height: 35)
label.textAlignment = .center
label.adjustsFontSizeToFitWidth = true
label.adjustsFontForContentSizeCategory = true
label.isUserInteractionEnabled = true
label.numberOfLines = 0
label.textColor = .white
self.ingredientScroller.addSubview(label)
j += 1
}
self.ingredientScroller.contentSize = CGSize(width: contentView.frame.width, height: CGFloat(self.info.nutrients.count * 40))
} else {
// Add Ingredients
sender.setTitle("Nutrients", for: .normal)
for c in self.ingredientScroller.subviews {
c.removeFromSuperview()
}
let contentView = self.ingredientVisualView.contentView
for i in 0...self.info.ingredients.count - 1 {
let label = UILabel()
label.text = self.info.ingredients[i]
label.frame = CGRect(x: 0, y: i * 40, width: Int(contentView.frame.width), height: 35)
label.textAlignment = .center
label.adjustsFontSizeToFitWidth = true
label.adjustsFontForContentSizeCategory = true
label.isUserInteractionEnabled = true
label.numberOfLines = 0
label.textColor = .white
self.ingredientScroller.addSubview(label)
}
self.ingredientScroller.contentSize = CGSize(width: contentView.frame.width, height: CGFloat(self.info.ingredients.count * 40))
}
}
override func viewDidLoad() {
super.viewDidLoad()
foodVisualView.layer.cornerRadius = 5
foodVisualView.layer.masksToBounds = true
foodVisualView.alpha = 0
foodLabel.alpha = 0
closeVisualView.layer.cornerRadius = 5
closeVisualView.layer.masksToBounds = true
closeVisualView.alpha = 0
closeButton.alpha = 0
ingredientVisualView.layer.cornerRadius = 5
ingredientVisualView.layer.masksToBounds = true
ingredientVisualView.alpha = 0
ingredientScroller.alpha = 0
calorieVisualView.layer.cornerRadius = 5
calorieVisualView.layer.masksToBounds = true
calorieVisualView.alpha = 0
calorieLabel.alpha = 0
// Set the view's delegate
sceneView.delegate = self
// Show statistics such as fps and timing information
sceneView.showsStatistics = false
// Create a new scene
let scene = SCNScene()
// Set the scene to the view
sceneView.scene = scene
let panGesture = UIPanGestureRecognizer(target: self, action: #selector(moveNode(_:)))
self.view.addGestureRecognizer(panGesture)
let rotateGesture = UIRotationGestureRecognizer(target: self, action: #selector(rotateNode(_:)))
self.view.addGestureRecognizer(rotateGesture)
let scaleGesture = UIPinchGestureRecognizer(target: self, action: #selector(scaleNode(_:)))
self.view.addGestureRecognizer(scaleGesture)
startDetection()
startCapture()
}
@IBAction func closeHit(_ sender: UIButton) {
let root = sceneView.scene.rootNode
DispatchQueue.main.async {
UIView.animate(withDuration: 0.3, animations: {
root.childNodes[0].opacity = 0
}, completion: {
bool in
root.childNodes[0].removeAllAnimations()
root.childNodes[0].removeAllActions()
root.childNodes[0].removeFromParentNode()
})
}
foodVisualView.fadeOut()
foodLabel.fadeOut()
closeVisualView.fadeOut()
closeButton.fadeOut()
calorieVisualView.fadeOut()
calorieLabel.fadeOut()
ingredientVisualView.fadeOut()
ingredientScroller.fadeOut()
looking = false
loaded = false
}
var capTimer: Timer!
func startCapture() {
capTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(capture), userInfo: nil, repeats: true)
capTimer.fire()
}
@objc func capture() {
if (sceneView.session.currentFrame != nil) {
DispatchQueue.main.async {
if self.loaded && self.calorieVisualView.alpha == 0 {
self.calorieLabel.text = String(describing: self.info.calories) + " Calories"
self.calorieVisualView.fadeIn()
self.calorieLabel.fadeIn()
}
}
let buff = sceneView.session.currentFrame!.capturedImage
var requestOptions:[VNImageOption:Any] = [:]
if let camData = CMGetAttachment(buff, key: kCMSampleBufferAttachmentKey_CameraIntrinsicMatrix, attachmentModeOut: nil) {
requestOptions = [.cameraIntrinsics:camData]
}
let imageRequestHandler = VNImageRequestHandler(cvPixelBuffer: buff, orientation: CGImagePropertyOrientation(rawValue: 6)!, options: requestOptions)
do {
try imageRequestHandler.perform(self.requests)
} catch {
print(error)
}
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Create a session configuration
let configuration = ARWorldTrackingConfiguration()
// Run the view's session
sceneView.session.run(configuration)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
// Pause the view's session
sceneView.session.pause()
}
// MARK: - ARSCNViewDelegate
// Override to create and configure nodes for anchors added to the view's session.
func renderer(_ renderer: SCNSceneRenderer, nodeFor anchor: ARAnchor) -> SCNNode? {
// If this is our anchor, create a node
if self.detectedDataAnchor?.identifier == anchor.identifier {
let root = sceneView.scene.rootNode
root.childNodes[0].transform = SCNMatrix4(anchor.transform)
root.childNodes[0].scale = info.scale
DispatchQueue.main.async {
if self.calorieVisualView.alpha == 0 {
self.calorieLabel.text = String(describing: self.info.calories) + " Calories"
self.calorieVisualView.fadeIn()
self.calorieLabel.fadeIn()
}
}
return nil
}
return nil
}
func session(_ session: ARSession, didFailWithError error: Error) {
// Present an error message to the user
}
func sessionWasInterrupted(_ session: ARSession) {
// Inform the user that the session has been interrupted, for example, by presenting an overlay
}
func sessionInterruptionEnded(_ session: ARSession) {
// Reset tracking and/or remove existing anchors if consistent tracking is required
}
// Rotate & Pan Node
var currentAngleY: Float = 0.0
var isRotating = false
@objc func scaleNode(_ gesture: UIPinchGestureRecognizer) {
let root = sceneView.scene.rootNode
if (root.childNodes.count > 0 && !isRotating) {
let nodeToScale = root.childNodes[0]
if gesture.state == .changed {
let pinchScaleX: CGFloat = gesture.scale * CGFloat((nodeToScale.scale.x))
let pinchScaleY: CGFloat = gesture.scale * CGFloat((nodeToScale.scale.y))
let pinchScaleZ: CGFloat = gesture.scale * CGFloat((nodeToScale.scale.z))
nodeToScale.scale = SCNVector3Make(Float(pinchScaleX), Float(pinchScaleY), Float(pinchScaleZ))
gesture.scale = 1
}
if gesture.state == .ended { }
}
}
@objc func moveNode(_ gesture: UIPanGestureRecognizer) {
if !isRotating{
let root = sceneView.scene.rootNode
if (root.childNodes.count > 0) {
let currentNode = root.childNodes[0]
//1. Get The Current Touch Point
let currentTouchPoint = gesture.location(in: self.sceneView)
//2. Get The Next Feature Point Etc
guard let hitTest = self.sceneView.hitTest(currentTouchPoint, types: .featurePoint).first else { return }
//3. Convert To World Coordinates
let worldTransform = hitTest.worldTransform
//4. Set The New Position
let newPosition = SCNVector3(worldTransform.columns.3.x, worldTransform.columns.3.y, worldTransform.columns.3.z)
//5. Apply To The Node
currentNode.simdPosition = float3(newPosition.x, newPosition.y, newPosition.z)
}
}
}
@objc func rotateNode(_ gesture: UIRotationGestureRecognizer){
let root = sceneView.scene.rootNode
if (root.childNodes.count > 0) {
let currentNode = root.childNodes[0]
//1. Get The Current Rotation From The Gesture
let rotation = Float(gesture.rotation)
//2. If The Gesture State Has Changed Set The Nodes EulerAngles.y
if gesture.state == .changed{
isRotating = true
currentNode.eulerAngles.y = currentAngleY + rotation
}
//3. If The Gesture Has Ended Store The Last Angle Of The Cube
if(gesture.state == .ended) {
currentAngleY = currentNode.eulerAngles.y
isRotating = false
}
}
}
}