-
-
Notifications
You must be signed in to change notification settings - Fork 89
/
GLTFUnarchiver.swift
1699 lines (1426 loc) · 72 KB
/
GLTFUnarchiver.swift
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
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// GLTFUnarhiver.swift
// GLTFSceneKit
//
// Created by magicien on 2017/08/17.
// Copyright © 2017 DarkHorse. All rights reserved.
//
import SceneKit
import SpriteKit
import QuartzCore
import CoreGraphics
let glbMagic = 0x46546C67 // "glTF"
let chunkTypeJSON = 0x4E4F534A // "JSON"
let chunkTypeBIN = 0x004E4942 // "BIN"
public class GLTFUnarchiver {
private var directoryPath: URL? = nil
private var json: GLTFGlTF! = nil
private var bin: Data?
private var scene: SCNScene?
private var scenes: [SCNScene?] = []
private var cameras: [SCNCamera?] = []
private var nodes: [SCNNode?] = []
private var skins: [SCNSkinner?] = []
//private var animationChannels: [[Any?]?] = [] // SCNAcnimation
private var animationChannels: [[CAAnimation?]?] = []
private var animationSamplers: [[CAAnimation?]?] = []
private var meshes: [SCNNode?] = []
private var accessors: [Any?] = []
private var durations: [CFTimeInterval?] = []
private var bufferViews: [Data?] = []
private var buffers: [Data?] = []
private var materials: [SCNMaterial?] = []
private var textures: [SCNMaterialProperty?] = []
private var images: [Image?] = []
private var maxAnimationDuration: CFTimeInterval = 0.0
#if !os(watchOS)
private var workingAnimationGroup: CAAnimationGroup! = nil
#endif
convenience public init(path: String, extensions: [String:Codable.Type]? = nil) throws {
var url: URL?
if let mainPath = Bundle.main.path(forResource: path, ofType: "") {
url = URL(fileURLWithPath: mainPath)
} else {
url = URL(fileURLWithPath: path)
}
guard let _url = url else {
throw URLError(.fileDoesNotExist)
}
try self.init(url: _url, extensions: extensions)
}
convenience public init(url: URL, extensions: [String:Codable.Type]? = nil) throws {
let data = try Data(contentsOf: url)
try self.init(data: data, extensions: extensions)
self.directoryPath = url.deletingLastPathComponent()
}
public init(data: Data, extensions: [String:Codable.Type]? = nil) throws {
let decoder = JSONDecoder()
var _extensions = extensionList
extensions?.forEach { (ext) in _extensions[ext.key] = ext.value }
decoder.userInfo[GLTFExtensionCodingUserInfoKey] = _extensions
var jsonData = data
let magic: UInt32 = data.subdata(in: 0..<4).withUnsafeBytes { $0.pointee }
if magic == glbMagic {
let version: UInt32 = data.subdata(in: 4..<8).withUnsafeBytes { $0.pointee }
if version != 2 {
throw GLTFUnarchiveError.NotSupported("version \(version) is not supported")
}
let length: UInt32 = data.subdata(in: 8..<12).withUnsafeBytes { $0.pointee }
let chunk0Length: UInt32 = data.subdata(in: 12..<16).withUnsafeBytes { $0.pointee }
let chunk0Type: UInt32 = data.subdata(in: 16..<20).withUnsafeBytes { $0.pointee }
if chunk0Type != chunkTypeJSON {
throw GLTFUnarchiveError.NotSupported("chunkType \(chunk0Type) is not supported")
}
let chunk0EndPos = 20 + Int(chunk0Length)
jsonData = data.subdata(in: 20..<chunk0EndPos)
if length > chunk0EndPos {
let chunk1Length: UInt32 = data.subdata(in: chunk0EndPos..<chunk0EndPos+4).withUnsafeBytes { $0.pointee }
let chunk1Type: UInt32 = data.subdata(in: chunk0EndPos+4..<chunk0EndPos+8).withUnsafeBytes { $0.pointee }
if chunk1Type != chunkTypeBIN {
throw GLTFUnarchiveError.NotSupported("chunkType \(chunk1Type) is not supported")
}
let chunk1EndPos = chunk0EndPos + 8 + Int(chunk1Length)
self.bin = data.subdata(in: chunk0EndPos+8..<chunk1EndPos)
}
}
// just throw the error to the user
do {
self.json = try decoder.decode(GLTFGlTF.self, from: jsonData)
} catch DecodingError.keyNotFound(let key, let context) {
print("keyNotFound: \(key): \(context)")
} catch DecodingError.typeMismatch(let type, let context) {
print("typeMismatch: \(type): \(context)")
} catch DecodingError.valueNotFound(let type, let context) {
print("valueNotFound: \(type): \(context)")
}
self.initArrays()
}
private func initArrays() {
if let scenes = self.json.scenes {
self.scenes = [SCNScene?](repeating: nil, count: scenes.count)
}
if let cameras = self.json.cameras {
self.cameras = [SCNCamera?](repeating: nil, count: cameras.count)
}
if let nodes = self.json.nodes {
self.nodes = [SCNNode?](repeating: nil, count: nodes.count)
}
if let skins = self.json.skins {
self.skins = [SCNSkinner?](repeating: nil, count: skins.count)
}
if let animations = self.json.animations {
//if #available(OSX 10.13, *) {
// self.animationChannels = [[SCNAnimation?]?](repeating: nil, count: animations.count)
self.animationChannels = [[CAAnimation?]?](repeating: nil, count: animations.count)
self.animationSamplers = [[CAAnimation?]?](repeating: nil, count: animations.count)
//} else {
// print("GLTFAnimation is not supported for this OS version.")
//}
}
if let meshes = self.json.meshes {
self.meshes = [SCNNode?](repeating: nil, count: meshes.count)
}
if let accessors = self.json.accessors {
self.accessors = [Any?](repeating: nil, count: accessors.count)
self.durations = [CFTimeInterval?](repeating: nil, count: accessors.count)
}
if let bufferViews = self.json.bufferViews {
self.bufferViews = [Data?](repeating: nil, count: bufferViews.count)
}
if let buffers = self.json.buffers {
self.buffers = [Data?](repeating: nil, count: buffers.count)
}
if let materials = self.json.materials {
self.materials = [SCNMaterial?](repeating: nil, count: materials.count)
}
if let textures = self.json.textures {
self.textures = [SCNMaterialProperty?](repeating: nil, count: textures.count)
}
if let images = self.json.images {
self.images = [Image?](repeating: nil, count: images.count)
}
}
private func getBase64Str(from str: String) -> String? {
guard str.starts(with: "data:") else { return nil }
let mark = ";base64,"
guard str.contains(mark) else { return nil }
guard let base64Str = str.components(separatedBy: mark).last else { return nil }
return base64Str
}
private func calcPrimitiveCount(ofCount count: Int, primitiveType: SCNGeometryPrimitiveType) -> Int {
switch primitiveType {
case .line:
return count / 2
case .point:
return count
case .polygon:
// Is it correct?
return count - 2
case .triangles:
return count / 3
case .triangleStrip:
return count - 2
}
}
private func loadCamera(index: Int) throws -> SCNCamera {
guard index < self.cameras.count else {
throw GLTFUnarchiveError.DataInconsistent("loadCamera: out of index: \(index) < \(self.cameras.count)")
}
if let camera = self.cameras[index] {
return camera
}
guard let cameras = self.json.cameras else {
throw GLTFUnarchiveError.DataInconsistent("loadCamera: cameras is not defined")
}
let glCamera = cameras[index]
let camera = SCNCamera()
if let name = glCamera.name {
camera.name = name
}
switch glCamera.type {
case "perspective":
camera.usesOrthographicProjection = false
guard let perspective = glCamera.perspective else {
throw GLTFUnarchiveError.DataInconsistent("loadCamera: perspective is not defined")
}
camera.yFov = Double(perspective.yfov) * 180.0 / Double.pi
if let aspectRatio = perspective.aspectRatio {
camera.xFov = camera.yFov * Double(aspectRatio)
}
camera.zNear = Double(perspective.znear)
camera.zFar = Double(perspective.zfar ?? Float.infinity)
perspective.didLoad(by: camera, unarchiver: self)
case "orthographic":
camera.usesOrthographicProjection = true
guard let orthographic = glCamera.orthographic else {
throw GLTFUnarchiveError.DataInconsistent("loadCamera: orthographic is not defined")
}
// TODO: use xmag
camera.orthographicScale = Double(orthographic.ymag)
camera.zNear = Double(orthographic.znear)
camera.zFar = Double(orthographic.zfar)
orthographic.didLoad(by: camera, unarchiver: self)
default:
throw GLTFUnarchiveError.NotSupported("loadCamera: type \(glCamera.type) is not supported")
}
glCamera.didLoad(by: camera, unarchiver: self)
return camera
}
private func loadBuffer(index: Int) throws -> Data {
guard index < self.buffers.count else {
throw GLTFUnarchiveError.DataInconsistent("loadBuffer: out of index: \(index) < \(self.buffers.count)")
}
if let buffer = self.buffers[index] {
return buffer
}
guard let buffers = self.json.buffers else {
throw GLTFUnarchiveError.DataInconsistent("loadBufferView: buffers is not defined")
}
let glBuffer = buffers[index]
var _buffer: Data?
if let uri = glBuffer.uri {
if let base64Str = self.getBase64Str(from: uri) {
_buffer = Data(base64Encoded: base64Str)
} else {
let url = URL(fileURLWithPath: uri, relativeTo: self.directoryPath)
_buffer = try Data(contentsOf: url)
}
} else {
_buffer = self.bin
}
guard let buffer = _buffer else {
throw GLTFUnarchiveError.Unknown("loadBufferView: buffer \(index) load error")
}
guard buffer.count >= glBuffer.byteLength else {
throw GLTFUnarchiveError.DataInconsistent("loadBuffer: buffer.count < byteLength: \(buffer.count) < \(glBuffer.byteLength)")
}
self.buffers[index] = buffer
glBuffer.didLoad(by: buffer, unarchiver: self)
return buffer
}
private func loadBufferView(index: Int, expectedTarget: Int? = nil) throws -> Data {
guard index < self.bufferViews.count else {
throw GLTFUnarchiveError.DataInconsistent("loadBufferView: out of index: \(index) < \(self.bufferViews.count)")
}
if let bufferView = self.bufferViews[index] {
return bufferView
}
guard let bufferViews = self.json.bufferViews else {
throw GLTFUnarchiveError.DataInconsistent("loadBufferView: bufferViews is not defined")
}
let glBufferView = bufferViews[index]
if let expectedTarget = expectedTarget {
if let target = glBufferView.target {
guard expectedTarget == target else {
throw GLTFUnarchiveError.DataInconsistent("loadBufferView: index \(index): target inconsistent")
}
}
}
let buffer = try self.loadBuffer(index: glBufferView.buffer)
let bufferView = buffer.subdata(in: glBufferView.byteOffset..<glBufferView.byteOffset + glBufferView.byteLength)
self.bufferViews[index] = bufferView
glBufferView.didLoad(by: bufferView, unarchiver: self)
return bufferView
}
private func iterateBufferView(index: Int, offset: Int, stride: Int, count: Int, block: @escaping (UnsafeRawPointer) -> Void) throws {
guard count > 0 else { return }
let bufferView = try self.loadBufferView(index: index)
let glBufferView = self.json.bufferViews![index]
var byteStride = stride
if let glByteStride = glBufferView.byteStride {
byteStride = glByteStride
}
print("iterateBufferView: byteStride: \(byteStride)")
guard offset + byteStride * count <= glBufferView.byteLength else {
throw GLTFUnarchiveError.DataInconsistent("iterateBufferView: offset (\(offset)) + byteStride (\(byteStride)) * count (\(count)) shoule be equal or less than byteLength (\(glBufferView.byteLength)))")
}
bufferView.withUnsafeBytes { (pointer: UnsafePointer<UInt8>) in
var p = pointer.advanced(by: offset)
for _ in 0..<count {
block(UnsafeRawPointer(p))
p = p.advanced(by: byteStride)
}
}
}
private func getDataStride(ofBufferViewIndex index: Int) throws -> Int? {
guard let bufferViews = self.json.bufferViews else {
throw GLTFUnarchiveError.DataInconsistent("getDataStride: bufferViews is not defined")
}
guard index < bufferViews.count else {
throw GLTFUnarchiveError.DataInconsistent("getDataStride: out of index: \(index) < \(bufferViews.count)")
}
// it could be nil because it is not required.
guard let stride = bufferViews[index].byteStride else { return nil }
return stride
}
private func createIndexData(_ data: Data, offset: Int, size: Int, stride: Int, count: Int) -> Data {
let dataSize = size * count
if stride == size {
if offset == 0 {
return data
}
return data.subdata(in: offset..<offset + dataSize)
}
var indexData = Data(capacity: dataSize)
data.withUnsafeBytes { (s: UnsafePointer<UInt8>) in
indexData.withUnsafeMutableBytes { (d: UnsafeMutablePointer<UInt8>) in
let srcStep = stride - size
var srcPos = offset
var dstPos = 0
for _ in 0..<count {
for _ in 0..<size {
d[dstPos] = s[srcPos]
srcPos += 1
dstPos += 1
}
srcPos += srcStep
}
}
}
return indexData
}
private func loadVertexAccessor(index: Int, semantic: SCNGeometrySource.Semantic) throws -> SCNGeometrySource {
guard index < self.accessors.count else {
throw GLTFUnarchiveError.DataInconsistent("loadVertexAccessor: out of index: \(index) < \(self.accessors.count)")
}
if let accessor = self.accessors[index] as? SCNGeometrySource {
return accessor
}
if self.accessors[index] != nil {
throw GLTFUnarchiveError.DataInconsistent("loadVertexAccessor: the accessor \(index) is not SCNGeometrySource")
}
guard let accessors = self.json.accessors else {
throw GLTFUnarchiveError.DataInconsistent("loadVertexAccessor: accessors is not defined")
}
let glAccessor = accessors[index]
let vectorCount = glAccessor.count
guard let usesFloatComponents = usesFloatComponentsMap[glAccessor.componentType] else {
throw GLTFUnarchiveError.NotSupported("loadVertexAccessor: user defined accessor.componentType is not supported")
}
guard let componentsPerVector = componentsPerVectorMap[glAccessor.type] else {
throw GLTFUnarchiveError.NotSupported("loadVertexAccessor: user defined accessor.type is not supported")
}
guard let bytesPerComponent = bytesPerComponentMap[glAccessor.componentType] else {
throw GLTFUnarchiveError.NotSupported("loadVertexAccessor: user defined accessor.componentType is not supported")
}
let dataOffset = glAccessor.byteOffset
var bufferView: Data
var dataStride: Int = bytesPerComponent * componentsPerVector
var padding = 0
if let bufferViewIndex = glAccessor.bufferView {
let bv = try self.loadBufferView(index: bufferViewIndex)
bufferView = bv
if let ds = try self.getDataStride(ofBufferViewIndex: bufferViewIndex) {
guard ds >= dataStride else {
throw GLTFUnarchiveError.DataInconsistent("loadVertexAccessor: dataStride is too small: \(ds) < \(dataStride)")
}
padding = ds - dataStride
dataStride = ds
}
} else {
let dataSize = dataStride * vectorCount
bufferView = Data(count: dataSize)
}
/*
print("==================================================")
print("semantic: \(semantic)")
print("vectorCount: \(vectorCount)")
print("usesFloatComponents: \(usesFloatComponents)")
print("componentsPerVector: \(componentsPerVector)")
print("bytesPerComponent: \(bytesPerComponent)")
print("dataOffset: \(dataOffset)")
print("dataStride: \(dataStride)")
print("bufferView.count: \(bufferView.count)")
print("padding: \(padding)")
print("dataOffset + dataStride * vectorCount - padding: \(dataOffset + dataStride * vectorCount - padding)")
print("==================================================")
*/
#if SEEMS_TO_HAVE_VALIDATE_VERTEX_ATTRIBUTE_BUG
// Metal validateVertexAttribute function seems to have a bug, so dateOffset must be 0.
bufferView = bufferView.subdata(in: dataOffset..<dataOffset + dataStride * vectorCount - padding)
let geometrySource = SCNGeometrySource(data: bufferView, semantic: semantic, vectorCount: vectorCount, usesFloatComponents: usesFloatComponents, componentsPerVector: componentsPerVector, bytesPerComponent: bytesPerComponent, dataOffset: 0, dataStride: dataStride)
#else
let geometrySource = SCNGeometrySource(data: bufferView, semantic: semantic, vectorCount: vectorCount, usesFloatComponents: usesFloatComponents, componentsPerVector: componentsPerVector, bytesPerComponent: bytesPerComponent, dataOffset: dataOffset, dataStride: dataStride)
#endif
self.accessors[index] = geometrySource
glAccessor.didLoad(by: geometrySource, unarchiver: self)
return geometrySource
}
private func createIndexAccessor(for source: SCNGeometrySource, primitiveMode: Int) throws -> SCNGeometryElement {
assert(source.semantic == .vertex)
guard let primitiveType = primitiveTypeMap[primitiveMode] else {
throw GLTFUnarchiveError.NotSupported("createIndexAccessor: primitve mode \(primitiveMode) is not supported")
}
if source.vectorCount <= 0xFFFF {
var indices = [UInt16](repeating: 0, count: source.vectorCount)
for i in 0..<source.vectorCount {
indices[i] = UInt16(i)
}
let geometryElement = SCNGeometryElement(indices: indices, primitiveType: primitiveType)
return geometryElement
}
if source.vectorCount <= 0xFFFFFFFF {
var indices = [UInt32](repeating: 0, count: source.vectorCount)
for i in 0..<source.vectorCount {
indices[i] = UInt32(i)
}
let geometryElement = SCNGeometryElement(indices: indices, primitiveType: primitiveType)
return geometryElement
}
var indices = [UInt64](repeating: 0, count: source.vectorCount)
for i in 0..<source.vectorCount {
indices[i] = UInt64(i)
}
let geometryElement = SCNGeometryElement(indices: indices, primitiveType: primitiveType)
return geometryElement
}
private func loadIndexAccessor(index: Int, primitiveMode: Int) throws -> SCNGeometryElement {
guard index < self.accessors.count else {
throw GLTFUnarchiveError.DataInconsistent("loadIndexAccessor: out of index: \(index) < \(self.accessors.count)")
}
if let accessor = self.accessors[index] as? SCNGeometryElement {
return accessor
}
//if (self.accessors[index] as? SCNGeometrySource) != nil {
// throw GLTFUnarchiveError.DataInconsistent("loadIndexAccessor: the accessor \(index) is defined as SCNGeometrySource")
//}
if self.accessors[index] != nil {
throw GLTFUnarchiveError.DataInconsistent("loadIndexAccessor: the accessor \(index) is not SCNGeometryElement")
}
guard let accessors = self.json.accessors else {
throw GLTFUnarchiveError.DataInconsistent("loadIndexAccessor: accessors is not defined")
}
let glAccessor = accessors[index]
guard let primitiveType = primitiveTypeMap[primitiveMode] else {
throw GLTFUnarchiveError.NotSupported("loadIndexAccessor: primitve mode \(primitiveMode) is not supported")
}
let primitiveCount = self.calcPrimitiveCount(ofCount: glAccessor.count, primitiveType: primitiveType)
guard let usesFloatComponents = usesFloatComponentsMap[glAccessor.componentType] else {
throw GLTFUnarchiveError.NotSupported("loadIndexAccessor: user defined accessor.componentType is not supported")
}
if usesFloatComponents {
throw GLTFUnarchiveError.DataInconsistent("loadIndexAccessor: cannot use Float for index accessor")
}
guard let componentsPerVector = componentsPerVectorMap[glAccessor.type] else {
throw GLTFUnarchiveError.NotSupported("loadIndexAccessor: user defined accessor.type is not supported")
}
if componentsPerVector != 1 {
throw GLTFUnarchiveError.DataInconsistent("loadIndexAccessor: accessor type must be SCALAR")
}
guard let bytesPerComponent = bytesPerComponentMap[glAccessor.componentType] else {
throw GLTFUnarchiveError.NotSupported("loadndexIAccessor: user defined accessor.componentType is not supported")
}
let dataOffset = glAccessor.byteOffset
var bufferView: Data
var dataStride: Int = bytesPerComponent
if let bufferViewIndex = glAccessor.bufferView {
let bv = try self.loadBufferView(index: bufferViewIndex)
bufferView = bv
if let ds = try self.getDataStride(ofBufferViewIndex: bufferViewIndex) {
dataStride = ds
}
} else {
let dataSize = dataStride * glAccessor.count
bufferView = Data(count: dataSize)
}
let data = self.createIndexData(bufferView, offset: dataOffset, size: bytesPerComponent, stride: dataStride, count: glAccessor.count)
let geometryElement = SCNGeometryElement(data: data, primitiveType: primitiveType, primitiveCount: primitiveCount, bytesPerIndex: bytesPerComponent)
self.accessors[index] = geometryElement
glAccessor.didLoad(by: geometryElement, unarchiver: self)
return geometryElement
}
private func createNormalSource(for vertexSource: SCNGeometrySource, elements: [SCNGeometryElement]) throws -> SCNGeometrySource {
let vertexArray = try createVertexArray(from: vertexSource)
let dummyNormal = SCNVector3()
var normals = [SCNVector3](repeating: dummyNormal, count: vertexArray.count)
var counts = [Int](repeating: 0, count: vertexArray.count)
for element in elements {
if element.primitiveType != .triangles {
throw GLTFUnarchiveError.NotSupported("createNormalSource: only triangles primitveType is supported: \(element.primitiveType)")
}
let indexArray = createIndexArray(from: element)
var indexPos = 0
for _ in 0..<indexArray.count/3 {
let i0 = indexArray[indexPos]
let i1 = indexArray[indexPos+1]
let i2 = indexArray[indexPos+2]
let v0 = vertexArray[i0]
let v1 = vertexArray[i1]
let v2 = vertexArray[i2]
let n = createNormal(v0, v1, v2)
normals[i0] = add(normals[i0], n)
normals[i1] = add(normals[i1], n)
normals[i2] = add(normals[i2], n)
counts[i0] += 1
counts[i1] += 1
counts[i2] += 1
indexPos += 3
}
}
for i in 0..<normals.count {
if counts[i] != 0 {
normals[i] = normalize(div(normals[i], SCNFloat(counts[i])))
}
}
let normalSource = SCNGeometrySource(normals: normals)
return normalSource
}
private func loadKeyTimeAccessor(index: Int) throws -> ([NSNumber], CFTimeInterval) {
guard index < self.accessors.count else {
throw GLTFUnarchiveError.DataInconsistent("loadKeyTimeAccessor: out of index: \(index) < \(self.accessors.count)")
}
if let accessor = self.accessors[index] as? [NSNumber] {
return (accessor, self.durations[index]!)
}
if self.accessors[index] != nil {
throw GLTFUnarchiveError.DataInconsistent("loadKeyTimeAccessor: the accessor \(index) is not [Float]")
}
guard let accessors = self.json.accessors else {
throw GLTFUnarchiveError.DataInconsistent("loadKeyTimeAccessor: accessors is not defined")
}
let glAccessor = accessors[index]
guard let usesFloatComponents = usesFloatComponentsMap[glAccessor.componentType] else {
throw GLTFUnarchiveError.NotSupported("loadKeyTimeAccessor: user defined accessor.componentType is not supported")
}
if !usesFloatComponents {
throw GLTFUnarchiveError.DataInconsistent("loadKeyTimeAccessor: not Float keyTime accessor")
}
guard let componentsPerVector = componentsPerVectorMap[glAccessor.type] else {
throw GLTFUnarchiveError.NotSupported("loadKeyTimeAccessor: user defined accessor.type is not supported")
}
if componentsPerVector != 1 {
throw GLTFUnarchiveError.DataInconsistent("loadKeyTimeAccessor: accessor type must be SCALAR")
}
guard let bytesPerComponent = bytesPerComponentMap[glAccessor.componentType] else {
throw GLTFUnarchiveError.NotSupported("loadndexIAccessor: user defined accessor.componentType is not supported")
}
let dataOffset = glAccessor.byteOffset
var bufferView: Data
var dataStride: Int = bytesPerComponent
if let bufferViewIndex = glAccessor.bufferView {
let bv = try self.loadBufferView(index: bufferViewIndex)
bufferView = bv
if let ds = try self.getDataStride(ofBufferViewIndex: bufferViewIndex) {
dataStride = ds
}
} else {
let dataSize = dataStride * glAccessor.count
bufferView = Data(count: dataSize)
}
let (keyTimeArray, duration) = createKeyTimeArray(from: bufferView, offset: dataOffset, stride: dataStride, count: glAccessor.count)
self.accessors[index] = keyTimeArray
self.durations[index] = duration
return (keyTimeArray, duration)
}
private func loadValueAccessor(index: Int, flipW: Bool = false) throws -> [Any] {
guard index < self.accessors.count else {
throw GLTFUnarchiveError.DataInconsistent("loadValueAccessor: out of index: \(index) < \(self.accessors.count)")
}
if let accessor = self.accessors[index] as? [Any] {
return accessor
}
if self.accessors[index] != nil {
throw GLTFUnarchiveError.DataInconsistent("loadValueAccessor: the accessor \(index) is not [Float]")
}
guard let accessors = self.json.accessors else {
throw GLTFUnarchiveError.DataInconsistent("loadValueAccessor: accessors is not defined")
}
let glAccessor = accessors[index]
guard let bufferViewIndex = glAccessor.bufferView else {
throw GLTFUnarchiveError.DataInconsistent("loadValueAccessor: bufferView is not defined")
}
/*
guard let usesFloatComponents = usesFloatComponentsMap[glAccessor.componentType] else {
throw GLTFUnarchiveError.NotSupported("loadValueAccessor: user defined accessor.componentType is not supported")
}
if usesFloatComponents {
throw GLTFUnarchiveError.DataInconsistent("loadValueAccessor: not Float keyTime accessor")
}
guard let componentsPerVector = componentsPerVectorMap[glAccessor.type] else {
throw GLTFUnarchiveError.NotSupported("loadValueAccessor: user defined accessor.type is not supported")
}
if componentsPerVector != 1 {
throw GLTFUnarchiveError.DataInconsistent("loadValueAccessor: accessor type must be SCALAR")
}
guard let bytesPerComponent = bytesPerComponentMap[glAccessor.componentType] else {
throw GLTFUnarchiveError.NotSupported("loadValueAccessor: user defined accessor.componentType is not supported")
}
*/
let dataOffset = glAccessor.byteOffset
let bytesPerComponent = bytesPerComponentMap[glAccessor.componentType]!
let componentsPerVector = componentsPerVectorMap[glAccessor.type]!
let dataStride = bytesPerComponent * componentsPerVector
/*
var bufferView: Data
var dataStride: Int = bytesPerComponent
if let bufferViewIndex = glAccessor.bufferView {
let bv = try self.loadBufferView(index: bufferViewIndex)
bufferView = bv
if let ds = try self.getDataStride(ofBufferViewIndex: bufferViewIndex) {
dataStride = ds
}
} else {
let dataSize = dataStride * glAccessor.count
bufferView = Data(count: dataSize)
}
*/
//let valueArray = self.createValueArray(of: glAccessor)
if glAccessor.type == "SCALAR" {
var valueArray = [NSNumber]()
valueArray.reserveCapacity(glAccessor.count)
try self.iterateBufferView(index: bufferViewIndex, offset: dataOffset, stride: dataStride, count: glAccessor.count) { (p) in
// TODO: it could be BYTE, UNSIGNED_BYTE, ...
let value = p.load(fromByteOffset: 0, as: Float32.self)
//let value = p.bindMemory(to: Float32.self, capacity: 1).pointee
//print("value: \(value)")
valueArray.append(NSNumber(value: value))
}
self.accessors[index] = valueArray
return valueArray
}
var valueArray = [NSValue]()
valueArray.reserveCapacity(glAccessor.count)
if glAccessor.type == "VEC3" {
try self.iterateBufferView(index: bufferViewIndex, offset: dataOffset, stride: dataStride, count: glAccessor.count) { (p) in
let x = p.load(fromByteOffset: 0, as: Float32.self)
let y = p.load(fromByteOffset: 4, as: Float32.self)
let z = p.load(fromByteOffset: 8, as: Float32.self)
let v = SCNVector3(x, y, z)
valueArray.append(NSValue(scnVector3: v))
}
}
else if glAccessor.type == "VEC4" {
try self.iterateBufferView(index: bufferViewIndex, offset: dataOffset, stride: dataStride, count: glAccessor.count) { (p) in
let x = p.load(fromByteOffset: 0, as: Float32.self)
let y = p.load(fromByteOffset: 4, as: Float32.self)
let z = p.load(fromByteOffset: 8, as: Float32.self)
let w = p.load(fromByteOffset: 12, as: Float32.self)
let v = SCNVector4(x, y, z, flipW ? -w : w)
valueArray.append(NSValue(scnVector4: v))
}
}
return valueArray
}
private func loadImage(index: Int) throws -> Image {
guard index < self.images.count else {
throw GLTFUnarchiveError.DataInconsistent("loadImage: out of index: \(index) < \(self.images.count)")
}
if let image = self.images[index] {
return image
}
guard let images = self.json.images else {
throw GLTFUnarchiveError.DataInconsistent("loadImage: images is not defined")
}
let glImage = images[index]
var image: Image?
if let uri = glImage.uri {
if let base64Str = self.getBase64Str(from: uri) {
guard let data = Data(base64Encoded: base64Str) else {
throw GLTFUnarchiveError.Unknown("loadImage: cannot convert the base64 string to Data")
}
image = try loadImageData(from: data)
} else {
let url = URL(fileURLWithPath: uri, relativeTo: self.directoryPath)
image = try loadImageFile(from: url)
}
} else if let bufferViewIndex = glImage.bufferView {
let bufferView = try self.loadBufferView(index: bufferViewIndex)
image = try loadImageData(from: bufferView)
}
guard let _image = image else {
throw GLTFUnarchiveError.Unknown("loadImage: image \(index) is not loaded")
}
self.images[index] = _image
glImage.didLoad(by: _image, unarchiver: self)
return _image
}
private func setSampler(index: Int, to property: SCNMaterialProperty) throws {
guard let samplers = self.json.samplers else {
throw GLTFUnarchiveError.DataInconsistent("setSampler: samplers is not defined")
}
if index >= samplers.count {
throw GLTFUnarchiveError.DataInconsistent("setSampler: out of index: \(index) < \(samplers.count)")
}
let sampler = samplers[index]
if let magFilter = sampler.magFilter {
guard let filter = filterModeMap[magFilter] else {
throw GLTFUnarchiveError.NotSupported("setSampler: magFilter \(magFilter) is not supported")
}
property.magnificationFilter = filter
}
if let minFilter = sampler.minFilter {
switch minFilter {
case GLTF_NEAREST:
property.minificationFilter = .nearest
property.mipFilter = .none
case GLTF_LINEAR:
property.minificationFilter = .linear
property.mipFilter = .none
case GLTF_NEAREST_MIPMAP_NEAREST:
property.minificationFilter = .nearest
property.mipFilter = .nearest
case GLTF_LINEAR_MIPMAP_NEAREST:
property.minificationFilter = .linear
property.mipFilter = .nearest
case GLTF_NEAREST_MIPMAP_LINEAR:
property.minificationFilter = .nearest
property.mipFilter = .linear
case GLTF_LINEAR_MIPMAP_LINEAR:
property.minificationFilter = .linear
property.mipFilter = .linear
default:
throw GLTFUnarchiveError.NotSupported("setSampler: minFilter \(minFilter) is not supported")
}
}
guard let wrapS = wrapModeMap[sampler.wrapS] else {
throw GLTFUnarchiveError.NotSupported("setSampler: wrapS \(sampler.wrapS) is not supported")
}
property.wrapS = wrapS
guard let wrapT = wrapModeMap[sampler.wrapT] else {
throw GLTFUnarchiveError.NotSupported("setSampler: wrapT \(sampler.wrapT) is not supported")
}
property.wrapT = wrapT
}
private func loadTexture(index: Int) throws -> SCNMaterialProperty {
guard index < self.textures.count else {
throw GLTFUnarchiveError.DataInconsistent("loadTexture: out of index: \(index) < \(self.textures.count)")
}
if let texture = self.textures[index] {
return texture
}
guard let textures = self.json.textures else {
throw GLTFUnarchiveError.DataInconsistent("loadTexture: textures is not defined")
}
let glTexture = textures[index]
guard let sourceIndex = glTexture.source else {
throw GLTFUnarchiveError.NotSupported("loadTexture: texture without source is not supported")
}
let image = try self.loadImage(index: sourceIndex)
let texture = SCNMaterialProperty(contents: image)
// TODO: retain glTexture.name somewhere
if let sampler = glTexture.sampler {
try self.setSampler(index: sampler, to: texture)
} else {
// set default values
texture.wrapS = .repeat
texture.wrapT = .repeat
}
self.textures[index] = texture
glTexture.didLoad(by: texture, unarchiver: self)
return texture
}
func setTexture(index: Int, to property: SCNMaterialProperty) throws {
let texture = try self.loadTexture(index: index)
guard let contents = texture.contents else {
throw GLTFUnarchiveError.DataInconsistent("setTexture: contents of texture \(index) is nil")
}
property.contents = contents
property.minificationFilter = texture.minificationFilter
property.magnificationFilter = texture.magnificationFilter
property.mipFilter = texture.mipFilter
property.wrapS = texture.wrapS
property.wrapT = texture.wrapT
property.intensity = texture.intensity
property.maxAnisotropy = texture.maxAnisotropy
property.contentsTransform = texture.contentsTransform
property.mappingChannel = texture.mappingChannel
if #available(OSX 10.13, *) {
property.textureComponents = texture.textureComponents
}
}
var defaultMaterial: SCNMaterial {
get {
let material = SCNMaterial()
material.lightingModel = .physicallyBased
material.diffuse.contents = createColor([1.0, 1.0, 1.0, 1.0])
material.metalness.contents = createGrayColor(white: 1.0)
material.roughness.contents = createGrayColor(white: 1.0)
material.isDoubleSided = false
return material
}
}
private func loadMaterial(index: Int) throws -> SCNMaterial {
guard index < self.materials.count else {
throw GLTFUnarchiveError.DataInconsistent("loadMaterial: out of index: \(index) < \(self.materials.count)")
}
if let material = self.materials[index] {
return material
}
guard let materials = self.json.materials else {
throw GLTFUnarchiveError.DataInconsistent("loadMaterials: materials it not defined")
}
let glMaterial = materials[index]
let material = SCNMaterial()
self.materials[index] = material
material.setValue(Float(1.0), forKey: "baseColorFactorR")
material.setValue(Float(1.0), forKey: "baseColorFactorG")
material.setValue(Float(1.0), forKey: "baseColorFactorB")
material.setValue(Float(1.0), forKey: "baseColorFactorA")
material.setValue(Float(1.0), forKey: "metallicFactor")
material.setValue(Float(1.0), forKey: "roughnessFactor")
material.setValue(glMaterial.emissiveFactor[0], forKey: "emissiveFactorR")
material.setValue(glMaterial.emissiveFactor[1], forKey: "emissiveFactorG")
material.setValue(glMaterial.emissiveFactor[2], forKey: "emissiveFactorB")
material.setValue(glMaterial.alphaCutoff, forKey: "alphaCutoff")
if let pbr = glMaterial.pbrMetallicRoughness {
material.lightingModel = .physicallyBased
material.diffuse.contents = createColor(pbr.baseColorFactor)
material.metalness.contents = createGrayColor(white: pbr.metallicFactor)
material.roughness.contents = createGrayColor(white: pbr.roughnessFactor)
if let baseTexture = pbr.baseColorTexture {
try self.setTexture(index: baseTexture.index, to: material.diffuse)
material.diffuse.mappingChannel = baseTexture.texCoord
//let baseColorFactor = createVector4(pbr.baseColorFactor)
//material.setValue(NSValue(scnVector4: baseColorFactor), forKeyPath: "baseColorFactor")
material.setValue(pbr.baseColorFactor[0], forKey: "baseColorFactorR")
material.setValue(pbr.baseColorFactor[1], forKey: "baseColorFactorG")
material.setValue(pbr.baseColorFactor[2], forKey: "baseColorFactorB")
material.setValue(pbr.baseColorFactor[3], forKey: "baseColorFactorA")
}
if let metallicTexture = pbr.metallicRoughnessTexture {
try self.setTexture(index: metallicTexture.index, to: material.metalness)
material.metalness.mappingChannel = metallicTexture.texCoord
try self.setTexture(index: metallicTexture.index, to: material.roughness)
material.roughness.mappingChannel = metallicTexture.texCoord
if #available(OSX 10.13, *) {
material.metalness.textureComponents = .blue
material.roughness.textureComponents = .green
} else {
// Fallback on earlier versions
if let image = material.metalness.contents as? Image {
let (metalness, roughness) = try getMetallicRoughnessTexture(from: image)
material.metalness.contents = metalness
material.roughness.contents = roughness
}