-
-
Notifications
You must be signed in to change notification settings - Fork 3.4k
/
Copy pathloading.js
executable file
·1306 lines (1235 loc) · 37.5 KB
/
loading.js
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
/**
* @module Shape
* @submodule 3D Models
* @for p5
* @requires core
* @requires p5.Geometry
*/
import p5 from '../core/main';
import './p5.Geometry';
/**
* Loads a 3D model to create a
* <a href="#/p5.Geometry">p5.Geometry</a> object.
*
* `loadModel()` can load 3D models from OBJ and STL files. Once the model is
* loaded, it can be displayed with the
* <a href="#/p5/model">model()</a> function, as in `model(shape)`.
*
* There are three ways to call `loadModel()` with optional parameters to help
* process the model.
*
* The first parameter, `path`, is always a `String` with the path to the
* file. Paths to local files should be relative, as in
* `loadModel('assets/model.obj')`. URLs such as
* `'https://example.com/model.obj'` may be blocked due to browser security.
*
* Note: When loading a `.obj` file that references materials stored in
* `.mtl` files, p5.js will attempt to load and apply those materials.
* To ensure that the `.obj` file reads the `.mtl` file correctly include the
* `.mtl` file alongside it.
*
* The first way to call `loadModel()` has three optional parameters after the
* file path. The first optional parameter, `successCallback`, is a function
* to call once the model loads. For example,
* `loadModel('assets/model.obj', handleModel)` will call the `handleModel()`
* function once the model loads. The second optional parameter,
* `failureCallback`, is a function to call if the model fails to load. For
* example, `loadModel('assets/model.obj', handleModel, handleFailure)` will
* call the `handleFailure()` function if an error occurs while loading. The
* third optional parameter, `fileType`, is the model’s file extension as a
* string. For example,
* `loadModel('assets/model', handleModel, handleFailure, '.obj')` will try to
* load the file model as a `.obj` file.
*
* The second way to call `loadModel()` has four optional parameters after the
* file path. The first optional parameter is a `Boolean` value. If `true` is
* passed, as in `loadModel('assets/model.obj', true)`, then the model will be
* resized to ensure it fits the canvas. The next three parameters are
* `successCallback`, `failureCallback`, and `fileType` as described above.
*
* The third way to call `loadModel()` has one optional parameter after the
* file path. The optional parameter, `options`, is an `Object` with options,
* as in `loadModel('assets/model.obj', options)`. The `options` object can
* have the following properties:
*
* ```js
* let options = {
* // Enables standardized size scaling during loading if set to true.
* normalize: true,
*
* // Function to call once the model loads.
* successCallback: handleModel,
*
* // Function to call if an error occurs while loading.
* failureCallback: handleError,
*
* // Model's file extension.
* fileType: '.stl',
*
* // Flips the U texture coordinates of the model.
* flipU: false,
*
* // Flips the V texture coordinates of the model.
* flipV: false
* };
*
* // Pass the options object to loadModel().
* loadModel('assets/model.obj', options);
* ```
*
* Models can take time to load. Calling `loadModel()` in
* <a href="#/p5/preload">preload()</a> ensures models load before they're
* used in <a href="#/p5/setup">setup()</a> or <a href="#/p5/draw">draw()</a>.
*
* Note: There’s no support for colored STL files. STL files with color will
* be rendered without color.
*
* @method loadModel
* @param {String} path path of the model to be loaded.
* @param {Boolean} normalize if `true`, scale the model to fit the canvas.
* @param {function(p5.Geometry)} [successCallback] function to call once the model is loaded. Will be passed
* the <a href="#/p5.Geometry">p5.Geometry</a> object.
* @param {function(Event)} [failureCallback] function to call if the model fails to load. Will be passed an `Error` event object.
* @param {String} [fileType] model’s file extension. Either `'.obj'` or `'.stl'`.
* @return {p5.Geometry} the <a href="#/p5.Geometry">p5.Geometry</a> object
*
* @example
* <div>
* <code>
* // Click and drag the mouse to view the scene from different angles.
*
* let shape;
*
* // Load the file and create a p5.Geometry object.
* function preload() {
* shape = loadModel('assets/teapot.obj');
* }
*
* function setup() {
* createCanvas(100, 100, WEBGL);
*
* describe('A white teapot drawn against a gray background.');
* }
*
* function draw() {
* background(200);
*
* // Enable orbiting with the mouse.
* orbitControl();
*
* // Draw the shape.
* model(shape);
* }
* </code>
* </div>
*
* <div>
* <code>
* // Click and drag the mouse to view the scene from different angles.
*
* let shape;
*
* // Load the file and create a p5.Geometry object.
* // Normalize the geometry's size to fit the canvas.
* function preload() {
* shape = loadModel('assets/teapot.obj', true);
* }
*
* function setup() {
* createCanvas(100, 100, WEBGL);
*
* describe('A white teapot drawn against a gray background.');
* }
*
* function draw() {
* background(200);
*
* // Enable orbiting with the mouse.
* orbitControl();
*
* // Draw the shape.
* model(shape);
* }
* </code>
* </div>
*
* <div>
* <code>
* // Click and drag the mouse to view the scene from different angles.
*
* let shape;
*
* // Load the file and create a p5.Geometry object.
* function preload() {
* loadModel('assets/teapot.obj', true, handleModel);
* }
*
* function setup() {
* createCanvas(100, 100, WEBGL);
*
* describe('A white teapot drawn against a gray background.');
* }
*
* function draw() {
* background(200);
*
* // Enable orbiting with the mouse.
* orbitControl();
*
* // Draw the shape.
* model(shape);
* }
*
* // Set the shape variable and log the geometry's
* // ID to the console.
* function handleModel(data) {
* shape = data;
* console.log(shape.gid);
* }
* </code>
* </div>
*
* <div class='notest'>
* <code>
* // Click and drag the mouse to view the scene from different angles.
*
* let shape;
*
* // Load the file and create a p5.Geometry object.
* function preload() {
* loadModel('assets/wrong.obj', true, handleModel, handleError);
* }
*
* function setup() {
* createCanvas(100, 100, WEBGL);
*
* describe('A white teapot drawn against a gray background.');
* }
*
* function draw() {
* background(200);
*
* // Enable orbiting with the mouse.
* orbitControl();
*
* // Draw the shape.
* model(shape);
* }
*
* // Set the shape variable and print the geometry's
* // ID to the console.
* function handleModel(data) {
* shape = data;
* console.log(shape.gid);
* }
*
* // Print an error message if the file doesn't load.
* function handleError(error) {
* console.error('Oops!', error);
* }
* </code>
* </div>
*
* <div>
* <code>
* // Click and drag the mouse to view the scene from different angles.
*
* let shape;
*
* // Load the file and create a p5.Geometry object.
* function preload() {
* loadModel('assets/teapot.obj', true, handleModel, handleError, '.obj');
* }
*
* function setup() {
* createCanvas(100, 100, WEBGL);
*
* describe('A white teapot drawn against a gray background.');
* }
*
* function draw() {
* background(200);
*
* // Enable orbiting with the mouse.
* orbitControl();
*
* // Draw the shape.
* model(shape);
* }
*
* // Set the shape variable and print the geometry's
* // ID to the console.
* function handleModel(data) {
* shape = data;
* console.log(shape.gid);
* }
*
* // Print an error message if the file doesn't load.
* function handleError(error) {
* console.error('Oops!', error);
* }
* </code>
* </div>
*
* <div>
* <code>
* // Click and drag the mouse to view the scene from different angles.
*
* let shape;
* let options = {
* normalize: true,
* successCallback: handleModel,
* failureCallback: handleError,
* fileType: '.obj'
* };
*
* // Load the file and create a p5.Geometry object.
* function preload() {
* loadModel('assets/teapot.obj', options);
* }
*
* function setup() {
* createCanvas(100, 100, WEBGL);
*
* describe('A white teapot drawn against a gray background.');
* }
*
* function draw() {
* background(200);
*
* // Enable orbiting with the mouse.
* orbitControl();
*
* // Draw the shape.
* model(shape);
* }
*
* // Set the shape variable and print the geometry's
* // ID to the console.
* function handleModel(data) {
* shape = data;
* console.log(shape.gid);
* }
*
* // Print an error message if the file doesn't load.
* function handleError(error) {
* console.error('Oops!', error);
* }
* </code>
* </div>
*/
/**
* @method loadModel
* @param {String} path
* @param {function(p5.Geometry)} [successCallback]
* @param {function(Event)} [failureCallback]
* @param {String} [fileType]
* @return {p5.Geometry} new <a href="#/p5.Geometry">p5.Geometry</a> object.
*/
/**
* @method loadModel
* @param {String} path
* @param {Object} [options] loading options.
* @param {function(p5.Geometry)} [options.successCallback]
* @param {function(Event)} [options.failureCallback]
* @param {String} [options.fileType]
* @param {boolean} [options.normalize]
* @param {boolean} [options.flipU]
* @param {boolean} [options.flipV]
* @return {p5.Geometry} new <a href="#/p5.Geometry">p5.Geometry</a> object.
*/
p5.prototype.loadModel = function(path,options) {
p5._validateParameters('loadModel', arguments);
let normalize= false;
let successCallback;
let failureCallback;
let flipU = false;
let flipV = false;
let fileType = path.slice(-4);
if (options && typeof options === 'object') {
normalize = options.normalize || false;
successCallback = options.successCallback;
failureCallback = options.failureCallback;
fileType = options.fileType || fileType;
flipU = options.flipU || false;
flipV = options.flipV || false;
} else if (typeof options === 'boolean') {
normalize = options;
successCallback = arguments[2];
failureCallback = arguments[3];
if (typeof arguments[4] !== 'undefined') {
fileType = arguments[4];
}
} else {
successCallback = typeof arguments[1] === 'function' ? arguments[1] : undefined;
failureCallback = arguments[2];
if (typeof arguments[3] !== 'undefined') {
fileType = arguments[3];
}
}
const model = new p5.Geometry();
model.gid = `${path}|${normalize}`;
const self = this;
async function getMaterials(lines){
const parsedMaterialPromises=[];
for (let i = 0; i < lines.length; i++) {
const mtllibMatch = lines[i].match(/^mtllib (.+)/);
if (mtllibMatch) {
let mtlPath='';
const mtlFilename = mtllibMatch[1];
const objPathParts = path.split('/');
if(objPathParts.length > 1){
objPathParts.pop();
const objFolderPath = objPathParts.join('/');
mtlPath = objFolderPath + '/' + mtlFilename;
}else{
mtlPath = mtlFilename;
}
parsedMaterialPromises.push(
fileExists(mtlPath).then(exists => {
if (exists) {
return parseMtl(self, mtlPath);
} else {
console.warn(`MTL file not found or error in parsing; proceeding without materials: ${mtlPath}`);
return {};
}
}).catch(error => {
console.warn(`Error loading MTL file: ${mtlPath}`, error);
return {};
})
);
}
}
try {
const parsedMaterials = await Promise.all(parsedMaterialPromises);
const materials= Object.assign({}, ...parsedMaterials);
return materials ;
} catch (error) {
return {};
}
}
async function fileExists(url) {
try {
const response = await fetch(url, { method: 'HEAD' });
return response.ok;
} catch (error) {
return false;
}
}
if (fileType.match(/\.stl$/i)) {
this.httpDo(
path,
'GET',
'arrayBuffer',
arrayBuffer => {
parseSTL(model, arrayBuffer);
if (normalize) {
model.normalize();
}
if (flipU) {
model.flipU();
}
if (flipV) {
model.flipV();
}
self._decrementPreload();
if (typeof successCallback === 'function') {
successCallback(model);
}
},
failureCallback
);
} else if (fileType.match(/\.obj$/i)) {
this.loadStrings(
path,
async lines => {
try{
const parsedMaterials=await getMaterials(lines);
parseObj(model, lines, parsedMaterials);
}catch (error) {
if (failureCallback) {
failureCallback(error);
} else {
p5._friendlyError('Error during parsing: ' + error.message);
}
return;
}
finally{
if (normalize) {
model.normalize();
}
if (flipU) {
model.flipU();
}
if (flipV) {
model.flipV();
}
model._makeTriangleEdges();
self._decrementPreload();
if (typeof successCallback === 'function') {
successCallback(model);
}
}
},
failureCallback
);
} else {
p5._friendlyFileLoadError(3, path);
if (failureCallback) {
failureCallback();
} else {
p5._friendlyError(
'Sorry, the file type is invalid. Only OBJ and STL files are supported.'
);
}
}
return model;
};
function parseMtl(p5,mtlPath){
return new Promise((resolve, reject)=>{
let currentMaterial = null;
let materials= {};
p5.loadStrings(
mtlPath,
lines => {
for (let line = 0; line < lines.length; ++line){
const tokens = lines[line].trim().split(/\s+/);
if(tokens[0] === 'newmtl') {
const materialName = tokens[1];
currentMaterial = materialName;
materials[currentMaterial] = {};
}else if (tokens[0] === 'Kd'){
//Diffuse color
materials[currentMaterial].diffuseColor = [
parseFloat(tokens[1]),
parseFloat(tokens[2]),
parseFloat(tokens[3])
];
} else if (tokens[0] === 'Ka'){
//Ambient Color
materials[currentMaterial].ambientColor = [
parseFloat(tokens[1]),
parseFloat(tokens[2]),
parseFloat(tokens[3])
];
}else if (tokens[0] === 'Ks'){
//Specular color
materials[currentMaterial].specularColor = [
parseFloat(tokens[1]),
parseFloat(tokens[2]),
parseFloat(tokens[3])
];
}else if (tokens[0] === 'map_Kd') {
//Texture path
materials[currentMaterial].texturePath = tokens[1];
}
}
resolve(materials);
},reject
);
});
}
/**
* Parse OBJ lines into model. For reference, this is what a simple model of a
* square might look like:
*
* v -0.5 -0.5 0.5
* v -0.5 -0.5 -0.5
* v -0.5 0.5 -0.5
* v -0.5 0.5 0.5
*
* f 4 3 2 1
*/
function parseObj(model, lines, materials= {}) {
// OBJ allows a face to specify an index for a vertex (in the above example),
// but it also allows you to specify a custom combination of vertex, UV
// coordinate, and vertex normal. So, "3/4/3" would mean, "use vertex 3 with
// UV coordinate 4 and vertex normal 3". In WebGL, every vertex with different
// parameters must be a different vertex, so loadedVerts is used to
// temporarily store the parsed vertices, normals, etc., and indexedVerts is
// used to map a specific combination (keyed on, for example, the string
// "3/4/3"), to the actual index of the newly created vertex in the final
// object.
const loadedVerts = {
v: [],
vt: [],
vn: []
};
// Map from source index → Map of material → destination index
const usedVerts = {}; // Track colored vertices
let currentMaterial = null;
const coloredVerts = new Set(); //unique vertices with color
let hasColoredVertices = false;
let hasColorlessVertices = false;
for (let line = 0; line < lines.length; ++line) {
// Each line is a separate object (vertex, face, vertex normal, etc)
// For each line, split it into tokens on whitespace. The first token
// describes the type.
const tokens = lines[line].trim().split(/\b\s+/);
if (tokens.length > 0) {
if (tokens[0] === 'usemtl') {
// Switch to a new material
currentMaterial = tokens[1];
}else if (tokens[0] === 'v' || tokens[0] === 'vn') {
// Check if this line describes a vertex or vertex normal.
// It will have three numeric parameters.
const vertex = new p5.Vector(
parseFloat(tokens[1]),
parseFloat(tokens[2]),
parseFloat(tokens[3])
);
loadedVerts[tokens[0]].push(vertex);
} else if (tokens[0] === 'vt') {
// Check if this line describes a texture coordinate.
// It will have two numeric parameters U and V (W is omitted).
// Because of WebGL texture coordinates rendering behaviour, the V
// coordinate is inversed.
const texVertex = [parseFloat(tokens[1]), 1 - parseFloat(tokens[2])];
loadedVerts[tokens[0]].push(texVertex);
} else if (tokens[0] === 'f') {
// Check if this line describes a face.
// OBJ faces can have more than three points. Triangulate points.
for (let tri = 3; tri < tokens.length; ++tri) {
const face = [];
const vertexTokens = [1, tri - 1, tri];
for (let tokenInd = 0; tokenInd < vertexTokens.length; ++tokenInd) {
// Now, convert the given token into an index
const vertString = tokens[vertexTokens[tokenInd]];
let vertParts=vertString.split('/');
// TODO: Faces can technically use negative numbers to refer to the
// previous nth vertex. I haven't seen this used in practice, but
// it might be good to implement this in the future.
for (let i = 0; i < vertParts.length; i++) {
vertParts[i] = parseInt(vertParts[i]) - 1;
}
if (!usedVerts[vertString]) {
usedVerts[vertString] = {};
}
if (usedVerts[vertString][currentMaterial] === undefined) {
const vertIndex = model.vertices.length;
model.vertices.push(loadedVerts.v[vertParts[0]].copy());
model.uvs.push(loadedVerts.vt[vertParts[1]] ?
loadedVerts.vt[vertParts[1]].slice() : [0, 0]);
model.vertexNormals.push(loadedVerts.vn[vertParts[2]] ?
loadedVerts.vn[vertParts[2]].copy() : new p5.Vector());
usedVerts[vertString][currentMaterial] = vertIndex;
face.push(vertIndex);
if (currentMaterial
&& materials[currentMaterial]
&& materials[currentMaterial].diffuseColor) {
// Mark this vertex as colored
coloredVerts.add(loadedVerts.v[vertParts[0]]); //since a set would only push unique values
}
} else {
face.push(usedVerts[vertString][currentMaterial]);
}
}
if (
face[0] !== face[1] &&
face[0] !== face[2] &&
face[1] !== face[2]
) {
model.faces.push(face);
//same material for all vertices in a particular face
if (currentMaterial
&& materials[currentMaterial]
&& materials[currentMaterial].diffuseColor) {
hasColoredVertices=true;
//flag to track color or no color model
hasColoredVertices = true;
const materialDiffuseColor =
materials[currentMaterial].diffuseColor;
for (let i = 0; i < face.length; i++) {
model.vertexColors.push(materialDiffuseColor[0]);
model.vertexColors.push(materialDiffuseColor[1]);
model.vertexColors.push(materialDiffuseColor[2]);
}
}else{
hasColorlessVertices=true;
}
}
}
}
}
}
// If the model doesn't have normals, compute the normals
if (model.vertexNormals.length === 0) {
model.computeNormals();
}
if (hasColoredVertices === hasColorlessVertices) {
// If both are true or both are false, throw an error because the model is inconsistent
throw new Error('Model coloring is inconsistent. Either all vertices should have colors or none should.');
}
return model;
}
/**
* STL files can be of two types, ASCII and Binary,
*
* We need to convert the arrayBuffer to an array of strings,
* to parse it as an ASCII file.
*/
function parseSTL(model, buffer) {
if (isBinary(buffer)) {
parseBinarySTL(model, buffer);
} else {
const reader = new DataView(buffer);
if (!('TextDecoder' in window)) {
console.warn(
'Sorry, ASCII STL loading only works in browsers that support TextDecoder (https://caniuse.com/#feat=textencoder)'
);
return model;
}
const decoder = new TextDecoder('utf-8');
const lines = decoder.decode(reader);
const lineArray = lines.split('\n');
parseASCIISTL(model, lineArray);
}
return model;
}
/**
* This function checks if the file is in ASCII format or in Binary format
*
* It is done by searching keyword `solid` at the start of the file.
*
* An ASCII STL data must begin with `solid` as the first six bytes.
* However, ASCII STLs lacking the SPACE after the `d` are known to be
* plentiful. So, check the first 5 bytes for `solid`.
*
* Several encodings, such as UTF-8, precede the text with up to 5 bytes:
* https://en.wikipedia.org/wiki/Byte_order_mark#Byte_order_marks_by_encoding
* Search for `solid` to start anywhere after those prefixes.
*/
function isBinary(data) {
const reader = new DataView(data);
// US-ASCII ordinal values for `s`, `o`, `l`, `i`, `d`
const solid = [115, 111, 108, 105, 100];
for (let off = 0; off < 5; off++) {
// If "solid" text is matched to the current offset, declare it to be an ASCII STL.
if (matchDataViewAt(solid, reader, off)) return false;
}
// Couldn't find "solid" text at the beginning; it is binary STL.
return true;
}
/**
* This function matches the `query` at the provided `offset`
*/
function matchDataViewAt(query, reader, offset) {
// Check if each byte in query matches the corresponding byte from the current offset
for (let i = 0, il = query.length; i < il; i++) {
if (query[i] !== reader.getUint8(offset + i, false)) return false;
}
return true;
}
/**
* This function parses the Binary STL files.
* https://en.wikipedia.org/wiki/STL_%28file_format%29#Binary_STL
*
* Currently there is no support for the colors provided in STL files.
*/
function parseBinarySTL(model, buffer) {
const reader = new DataView(buffer);
// Number of faces is present following the header
const faces = reader.getUint32(80, true);
let r,
g,
b,
hasColors = false,
colors;
let defaultR, defaultG, defaultB;
// Binary files contain 80-byte header, which is generally ignored.
for (let index = 0; index < 80 - 10; index++) {
// Check for `COLOR=`
if (
reader.getUint32(index, false) === 0x434f4c4f /*COLO*/ &&
reader.getUint8(index + 4) === 0x52 /*'R'*/ &&
reader.getUint8(index + 5) === 0x3d /*'='*/
) {
hasColors = true;
colors = [];
defaultR = reader.getUint8(index + 6) / 255;
defaultG = reader.getUint8(index + 7) / 255;
defaultB = reader.getUint8(index + 8) / 255;
// To be used when color support is added
// alpha = reader.getUint8(index + 9) / 255;
}
}
const dataOffset = 84;
const faceLength = 12 * 4 + 2;
// Iterate the faces
for (let face = 0; face < faces; face++) {
const start = dataOffset + face * faceLength;
const normalX = reader.getFloat32(start, true);
const normalY = reader.getFloat32(start + 4, true);
const normalZ = reader.getFloat32(start + 8, true);
if (hasColors) {
const packedColor = reader.getUint16(start + 48, true);
if ((packedColor & 0x8000) === 0) {
// facet has its own unique color
r = (packedColor & 0x1f) / 31;
g = ((packedColor >> 5) & 0x1f) / 31;
b = ((packedColor >> 10) & 0x1f) / 31;
} else {
r = defaultR;
g = defaultG;
b = defaultB;
}
}
const newNormal = new p5.Vector(normalX, normalY, normalZ);
for (let i = 1; i <= 3; i++) {
const vertexstart = start + i * 12;
const newVertex = new p5.Vector(
reader.getFloat32(vertexstart, true),
reader.getFloat32(vertexstart + 4, true),
reader.getFloat32(vertexstart + 8, true)
);
model.vertices.push(newVertex);
model.vertexNormals.push(newNormal);
if (hasColors) {
colors.push(r, g, b);
}
}
model.faces.push([3 * face, 3 * face + 1, 3 * face + 2]);
model.uvs.push([0, 0], [0, 0], [0, 0]);
}
if (hasColors) {
// add support for colors here.
}
return model;
}
/**
* ASCII STL file starts with `solid 'nameOfFile'`
* Then contain the normal of the face, starting with `facet normal`
* Next contain a keyword indicating the start of face vertex, `outer loop`
* Next comes the three vertex, starting with `vertex x y z`
* Vertices ends with `endloop`
* Face ends with `endfacet`
* Next face starts with `facet normal`
* The end of the file is indicated by `endsolid`
*/
function parseASCIISTL(model, lines) {
let state = '';
let curVertexIndex = [];
let newNormal, newVertex;
for (let iterator = 0; iterator < lines.length; ++iterator) {
const line = lines[iterator].trim();
const parts = line.split(' ');
for (let partsiterator = 0; partsiterator < parts.length; ++partsiterator) {
if (parts[partsiterator] === '') {
// Ignoring multiple whitespaces
parts.splice(partsiterator, 1);
}
}
if (parts.length === 0) {
// Remove newline
continue;
}
switch (state) {
case '': // First run
if (parts[0] !== 'solid') {
// Invalid state
console.error(line);
console.error(`Invalid state "${parts[0]}", should be "solid"`);
return;
} else {
state = 'solid';
}
break;
case 'solid': // First face
if (parts[0] !== 'facet' || parts[1] !== 'normal') {
// Invalid state
console.error(line);
console.error(
`Invalid state "${parts[0]}", should be "facet normal"`
);
return;
} else {
// Push normal for first face
newNormal = new p5.Vector(
parseFloat(parts[2]),
parseFloat(parts[3]),
parseFloat(parts[4])
);
model.vertexNormals.push(newNormal, newNormal, newNormal);
state = 'facet normal';
}
break;
case 'facet normal': // After normal is defined
if (parts[0] !== 'outer' || parts[1] !== 'loop') {
// Invalid State
console.error(line);
console.error(`Invalid state "${parts[0]}", should be "outer loop"`);
return;
} else {
// Next should be vertices
state = 'vertex';
}
break;
case 'vertex':
if (parts[0] === 'vertex') {
//Vertex of triangle
newVertex = new p5.Vector(
parseFloat(parts[1]),
parseFloat(parts[2]),
parseFloat(parts[3])
);
model.vertices.push(newVertex);
model.uvs.push([0, 0]);
curVertexIndex.push(model.vertices.indexOf(newVertex));
} else if (parts[0] === 'endloop') {
// End of vertices
model.faces.push(curVertexIndex);
curVertexIndex = [];
state = 'endloop';
} else {
// Invalid State
console.error(line);
console.error(
`Invalid state "${parts[0]}", should be "vertex" or "endloop"`
);
return;
}
break;
case 'endloop':
if (parts[0] !== 'endfacet') {
// End of face
console.error(line);
console.error(`Invalid state "${parts[0]}", should be "endfacet"`);
return;
} else {
state = 'endfacet';
}
break;
case 'endfacet':
if (parts[0] === 'endsolid') {
// End of solid
} else if (parts[0] === 'facet' && parts[1] === 'normal') {
// Next face
newNormal = new p5.Vector(
parseFloat(parts[2]),
parseFloat(parts[3]),
parseFloat(parts[4])
);
model.vertexNormals.push(newNormal, newNormal, newNormal);
state = 'facet normal';
} else {
// Invalid State
console.error(line);
console.error(
`Invalid state "${
parts[0]
}", should be "endsolid" or "facet normal"`
);
return;
}
break;
default:
console.error(`Invalid state "${state}"`);
break;
}
}
return model;
}
/**
* Draws a <a href="#/p5.Geometry">p5.Geometry</a> object to the canvas.
*
* The parameter, `model`, is the
* <a href="#/p5.Geometry">p5.Geometry</a> object to draw.
* <a href="#/p5.Geometry">p5.Geometry</a> objects can be built with
* <a href="#/p5/buildGeometry">buildGeometry()</a>, or
* <a href="#/p5/beginGeometry">beginGeometry()</a> and