-
Notifications
You must be signed in to change notification settings - Fork 1
/
PFB-converter-kaitai-050.html
870 lines (733 loc) · 29.1 KB
/
PFB-converter-kaitai-050.html
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
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<body>
PFB files folder: <a href="https://pds-imaging.jpl.nasa.gov/data/mer/spirit/mer2mw_0xxx/data/navcam/site0137/">link</a><br>
PFB converter sources: <a href="https://github.com/jumpjack/VST-converter">link</a><br>
<br>
<!--
Get texture references from PFB file: <input type="file" id="inpHeaderFile" name = "inpHeaderFile" width="100" accept=".PFB" ><br>
Texture references: <span id = "spnTextureRef" name = "spnTextureRef">-</span><br>
Load PFB+texture : <input type="file" id="inpPFB_TXTfile" name = "inpPFB_TXTfile" width="100" accept= ".PFB,.img" multiple><br>
-->
Load PFB file only: <input type="file" id="inpPFBfile" name = "inpPFBfile" width="100" accept=".PFB"><br>
Load textures only: <input type="file" id="inpTXTfile" name = "inpTXTfile" width="100" accept=".IMG" multiple><br>
Extract only textures: <input type="checkbox" id ="chkTextures"><br>
<span id="file_status" name="file_status" >waiting</span><br>
<span id="file_length" name="file_length" >-</span><br>
<button id="PLY" name="PLY" onclick = "savePLY()">Save as .PLY</button><br>
<br>
<button id="XYZ" name="XYZ" onclick = "saveXYZ()">Save as .XYZ</button><br>
<br>
<span id = "spnBlender" name="spnBlender"></span><br>
<span id = "spnTextureLinks" name="spnTextureLinks"></span><br>
<span id = "spnXYZLinks" name="spnXYZLinks"></span><br>
<span id = "spnVSTLinks" name="spnVSTLinks"></span><br>
<span id = "spnThumbnails" name="spnThumbnails"></span><br>
-----<br>
<canvas id="texture" name="texture" width="2048" height="2048"></canvas><br>
-----<br>
<script src="KaitaiStream.js"></script>
<script src="PFB.js"></script>
<script src="img_gray16.js"></script>
<script>
// 0.4.1 - Added texture loading
// 0.4.0 - Added list of textures, meshes and their folders
// Added list of product ids for direct import in Blender using modded "phaseIV/Blender-Navcam-Importer" (https://github.com/jumpjack/Blender-Navcam-Importer)
// 0.3.0 -
// 0.2.0 - XYZ export working; experimenting with faces and PLY export (faces not working, format unknown)
VSTlinksArray = [];
BASE_IMG_URL = "https://planetarydata.jpl.nasa.gov/w10n/mer2-m-navcam-5-disparity-ops-v1.0/mer2no_0xxx/";
IMG_RAW_FOLDER = "data/";
IMG_JPG_FOLDER = "browse/";
PRODUCT_FOLDER = "sol#SOLNUMBER#/rdr/"; // sol must be determined from VST // DEBUG!! (Sol number is in .lbl of .vst file)
BASE_VST_URL = "https://planetarydata.jpl.nasa.gov/img/data/mer/spirit/mer2mw_0xxx/";
VST_CAMERA_FOLDER = "data/pancam/"; // (pancam --> mer2po_0xxx for images) // DEBUG: add other cameras!
VST_FOLDER_SITE_NAME = "site0137/"; // DEBUG! Site number is in filename (137=B1)
product_name_no_ext = "2n292378085vilb128f0006l0m1"; // 2n292377885vilb126f0006l0m1 = small vst for testing, sol 1870 // DEBUG
base_VST_filename = BASE_VST_URL + VST_CAMERA_FOLDER + VST_FOLDER_SITE_NAME + product_name_no_ext;
base_texture_folder = BASE_IMG_URL + IMG_JPG_FOLDER + PRODUCT_FOLDER;
base_texture_folderIMG = BASE_IMG_URL + IMG_RAW_FOLDER + PRODUCT_FOLDER;
proxyURL = "https://win98.altervista.org/space/exploration/myp.php?pass=miapass&mode=native&url=";
canvas = document.getElementById('texture');
ctx = canvas.getContext('2d');
canvasWidth = 2048;
canvasHeight = 2048;
ctx.clearRect(0, 0, canvasWidth, canvasHeight);
ctx.rect(0, 0, canvasWidth, canvasHeight);
ctx.fillStyle = 'blue';
ctx.fill();
/* Nodes types (https://irix7.com/techpubs/007-2783-001.pdf) :
pfNode General node (base class)
pfScene Top level node.
pfGroup Node with multiple children.
pfSCS Static coordinate system.
pfDCS Dynamic coordinate system.
pfLOD Level of detail node.
pfSequence Sequential animation node.
pfSwitch Switch node.
pfLayer Layer or decal node.
pfGeode Fundamental geometry node.
pfGeoStates [graphic state]
pfGeoSets [geometry]
pfBillboard Special tracking leaf node.
pfLightPoint One or more emissive light points.
pfLightSource Definition of a graphics hardware light.
pfPartition Special culling acceleration node.
pfText 2D and 3D text geometry.
list of pfStrings
pfMorph Geometry morphing node.
pfMaterial
pfMtlSide
pfMtlAlpha
pfMtlShininess
pfMtlColor
pfMtlColorMode
pfTexture
pfTexName
pfTexImage
pfGetTexImage(const pfTexture* tex, uint** image, int* comp, int* sx, int* sy, int* sz);
image is an array of 4-byte words containing the texel data
The texture image is loaded from left to right, bottom to top
comp: number of 8-bit components per image pixel; 1, 2, 3, and 4 component textures are supported
ns, nt, nr: number of texels in the s, t, and r dimensions of image
pfTexBorderColor
pfTexBorderType
pfTexFormat
pfTexFilter
pfTexRepeat
pfTexSpline
pfTexDetail
pfDetailTexTile
pfTexList
pfTexFrame
pfTexLoadMode
pfTexLevel
*/
/*
================== TEXTURES ===============
https://techpubs.jurassic.nl/manuals/0640/developer/Perf_GetStarted/sgi_html/ch08.html
Textures can have as many as four components. The following are example uses:
1 component: intensity (I) or luminance (L) only.
2 components: intensity and transparency (IA).
3 components: red, green, and blue (RGB).
4 components: red, green, blue, and alpha (RGBA).
*/
/*
// ????????:
// https://github.com/NPSNET-IV/NPSNET-IV/blob/09ad5905964b1eb3463b8500b0a6c541707fa13f/src/database/tsg/tsgROpen.c
pfTexEnv *tenv;
ieee32 red,green,blue,alpha;
int8 bval;
int mode_val;
pfTexGen *tgen;
int8 bval;
ieee32 x,y,z,d; // texture plane equation
int mode_val,type;
int i;
pfTexture *tex;
char *name;
int8 clamp;
int i;
int pfflags;
int32 flags;
pfGeoState *gst;
void *arena = pfGetSharedArena();
int8 bval;
int32 ival;
ieee32 fval;
int mode_val;
pfMaterial *mtl;
int i,j,k;
int8 fieldid;
pfMaterial *mtl;
int8 bval;
ieee32 fval;
ieee32 color[3];
int mode_val,side,colormode_side;
pfColortable *table;
int32 numcolors;
ieee32 red,green,blue,alpha;
pfVec4 color;
int i;
pfFog *fog;
int8 bval;
ieee32 red,green,blue;
ieee32 near,far;
ieee32 bias;
ieee32 *range,*density;
int32 numpoints;
int mode_val;
void *arena = pfGetSharedArena();
int i;
pfLightModel *lmodel;
int8 bval;
ieee32 atten0,atten1,atten2;
int mode;
ieee32 red,green,blue;
*/
myPFB = null;
myImg = null;
TEXTURE_WIDTH = 1024; // to do: implement KSY reader for just PDS label, extract texture metadata and use them to implement generic texture reader
TEXTURE_HEIGHT = 1024;
MAGIC_LENGTH = 4;
UNK_LENGTH = 4;
PFB_HEADER_LENGTH = MAGIC_LENGTH + 3*UNK_LENGTH; // 16 bytes
TYTPE_LENGTH = 4;
COUNT_LENGTH = 4;
TOTAL_SIZE_LENGTH = 4;
NODE_HEADER_LENGTH = TYTPE_LENGTH + COUNT_LENGTH + TOTAL_SIZE_LENGTH; // 12 bytes
OPPORTUNITY = "1"; // First letter of filename
SPIRIT = "2";
roverName = ["","opportunity", "spirit"];
PLY_HEADER_BASE = "" +
"ply\n" +
"format ascii 1.0\n" +
"comment Created by PFB JS convereter\n" +
"element vertex VVVV\n" +
"property float x\n" +
"property float y\n" +
"property float z\n" +
/* "TTTT" +*/
"element face FFFF\n" +
"property list uchar int vertex_index\n" +
"end_header\n";
PLY_TEXTURE_HEADER = "" +
"property uchar red\n" +
"property uchar green\n" +
"property uchar blue\n";
PLYfiles = [];
XYZfiles = [];
/*
const headerSelector = document.getElementById('inpHeaderFile');
headerSelector.addEventListener('change', (event) => {
loadPFBheader(event.target.files[0])
});
*/
/*
const PFB_TXT_Selector = document.getElementById('inpPFB_TXTfile');
PFB_TXT_Selector.addEventListener('change', (event) => {
if (event.target.files.length !== 2) {
alert("You must select one .PFB file and one .img file");
return;
} else {
loadPFB_TXT(event.target.files[0], event.target.files[1])
}
});
*/
const PFB_Selector = document.getElementById('inpPFBfile');
PFB_Selector.addEventListener('change', (event) => {
loadPFB(event.target.files[0])
});
const TXT_Selector = document.getElementById('inpTXTfile');
TXT_Selector.addEventListener('change', (event) => {
loadTextures(event.target.files[0], event.target.files[1])
});
function saveFile(fileContent, filename,status_id) {
myBlob = new Blob([fileContent], {type: "application/octet-stream"});
var url = window.URL.createObjectURL(myBlob);
var anchor = document.createElement("a");
anchor.href = url;
anchor.download = filename;
// a(anchor);
anchor.addEventListener('load', (event) => {
console.log("LOAD");
});
anchor.addEventListener('ended', (event) => {
console.log("ENDED");
});
anchor.addEventListener('loadeddata', (event) => {
console.log("loadeddata");
});
anchor.addEventListener('loadstart', (event) => {
console.log("loadstart");
});
anchor.addEventListener('mousedown', (event) => {
console.log("mousedown");
});
anchor.click();
window.URL.revokeObjectURL(url);
document.getElementById(status_id).innerHTML = "Saved to " + filename;
}
/*
function loadPFBheader(fileHandler) {
const reader = new FileReader();
reader.addEventListener('load', (event) => {
rawFileContents = event.target.result;
fileContentsUInt8 = new Uint8Array(rawFileContents);
console.log("Loaded: ", event, rawFileContents.length);
document.getElementById("file_status").innerHTML = "Loaded";
document.getElementById("file_length").innerHTML = fileContentsUInt8.length + " bytes";
st = new KaitaiStream(fileContentsUInt8);
myPFBHeader = new PFBh(st);
console.log("This file contains:");
console.log(myPFBHeader.vistaHeader.lodsCount, " LODs");
sliceUInt8 = myPFBHeader.textureRef;
textureRefRaw = String.fromCharCode(...sliceUInt8)
textureRef = textureRefRaw.split("\x00");
textureName = textureRef[2];
spnTextureRef.innerHTML = textureName;
//console.log(textureName);
});
reader.readAsArrayBuffer(fileHandler);
console.log("Header reading process initiated...");
}
*/
function loadTextures(handler1, handler2) { // debug test con 2 sole texture; handler; xyz, ffl, ffl
//console.log(handler1, handler2)
textureHandler1 = handler1;
textureHandler2 = handler2;
console.log("TEXTURE:", textureHandler1, textureHandler2)
// Texture 1:
const reader = new FileReader();
reader.addEventListener('load', (event) => {
rawFileContents = event.target.result;
fileContentsUInt8 = new Uint8Array(rawFileContents);
console.log("Loaded: ", event, rawFileContents.length);
document.getElementById("file_status").innerHTML = "Loaded";
document.getElementById("file_length").innerHTML = fileContentsUInt8.length + " bytes";
st = new KaitaiStream(fileContentsUInt8);
myImg1 = new ImgGray16(st);
console.log("myImg1=",myImg1);
/* for (x=0; x< 1023; x++) {
for(y=0; y<1023; y++) {
rgb = (myImg.lines[y].samples[x])/10;
r = rgb;
g = rgb;
b = rgb;
writeCanvas(x,y,r,g,b);
}
}*/
});
reader.readAsArrayBuffer(textureHandler1);
// Texture 2:
const reader2 = new FileReader();
reader2.addEventListener('load', (event) => {
rawFileContents = event.target.result;
fileContentsUInt8 = new Uint8Array(rawFileContents);
console.log("Loaded: ", event, rawFileContents.length);
document.getElementById("file_status").innerHTML = "Loaded";
document.getElementById("file_length").innerHTML = fileContentsUInt8.length + " bytes";
st = new KaitaiStream(fileContentsUInt8);
myImg2 = new ImgGray16(st);
console.log("myImg2=",myImg2);
/* for (x=0; x< 1023; x++) {
for(y=0; y<1023; y++) {
rgb = (myImg.lines[y].samples[x])/10;
r = rgb;
g = rgb;
b = rgb;
writeCanvas(x,y,r,g,b);
}
}*/
});
reader2.readAsArrayBuffer(textureHandler2);
}
nodeTypes = [
"Materials", //0
"Textures list", //1
"Texenv?", //2
"GeoStates", //3
"Lenghts lists", //4
"Vertex lists", //5
"Colors lists", //6
"Normals lists", //7
"Texcoords lists",//8
"UNKNOWN", //9
"GeoSets", //10
"UNKNOWN", //11
"Nodes", //12
"UNKNOWN", //13
"UNKNOWN", //14
"UNKNOWN", //15
"UNKNOWN", //16
"TexGens", //17
"Light models", //18
"UNKNOWN", //19
"UNKNOWN", //20
"UNKNOWN", //21
"UNKNOWN", //22
"UNKNOWN", //23
"UNKNOWN", //24
"UNKNOWN", //25
"UNKNOWN", //26
"Images", //27
]
function nodeIs(received, mustBe) {
return (nodeTypes[received].toUpperCase().indexOf(mustBe) >= 0);
}
function loadPFB(fileHandler) {
totalListLenght = [];
totalLenght = 0;
myName = fileHandler.name;
const reader = new FileReader();
reader.addEventListener('load', (event) => {
rawFileContents = event.target.result;
fileContentsUInt8 = new Uint8Array(rawFileContents); // Extract from the generic ArrayBuffer an array of Unsigned Integers (0..255)
console.log("Loaded", rawFileContents.byteLength , " bytes.");
document.getElementById("file_status").innerHTML = "Loaded";
document.getElementById("file_length").innerHTML = fileContentsUInt8.length + " bytes";
st = new KaitaiStream(fileContentsUInt8);
myPFB = new Pfb (st);
nodeOffset = PFB_HEADER_LENGTH;
console.log(myPFB);
console.log("Total nodes:", myPFB.nodes.length);
vertexDB = [];
vertexDBstr = "";
facesDB = [];
facesDBstr = "";
normalsDB = [];
normalsDBstr = "";
checkTextures=document.getElementById("chkTextures").value;
texturesNodesFound = false;
console.log("CHECK=",checkTextures && texturesNodesFound);
for (var nodeIndex = 0; ((nodeIndex < myPFB.nodes.length) && (checkTextures && !texturesNodesFound)); nodeIndex++) {
console.log("======================");
thisNode = myPFB.nodes[nodeIndex];
console.log(nodeIndex +
" - type: " + thisNode.type + " (" + nodeTypes[thisNode.type] + "), count: " +
myPFB.nodes[nodeIndex].contents.count + ", size: dec" +
myPFB.nodes[nodeIndex].contents.totalSize + ", Offset: 0x" +
nodeOffset.toString(16)
);
/////// Put all vertices in a single sequence:
if (nodeIs(thisNode.type,"VERTEX")) {
if (!checkTextures) {
console.log(" Processing VERTEX");
totalListLenghtV = [];
totalLenghtV = 0;
for (var listIndex=0 ; listIndex < thisNode.contents.lists.length; listIndex++) {
var thisListV = thisNode.contents.lists[listIndex];
//console.log("Processing list " + listIndex + ", containing " + thisListV.elements.length + " vertices...");
totalListLenghtV[listIndex] = 0;
for (var elemIndex = 0; elemIndex < thisListV.elements.length ;elemIndex++) {
totalListLenghtV[listIndex] += 1
vertexObj = thisListV.elements[elemIndex];
vertexDB.push(vertexObj);
vertexStr = "";
vertexStr += vertexObj.x + " " + vertexObj.y + " " + vertexObj.z;
vertexDBstr += vertexStr + "\n";
}
// console.log(" ListV " , listIndex, ": ", thisListV.size , " vertices, ", totalListLenght[listIndex] );
totalLenghtV += totalListLenghtV[listIndex];
}
}
} else
/////// Create faces as groups of pointers to vertices
// LENGTHSLISTS
// |
// +-- Num of lists (69)
// |
// +-- LENGHTSLIST [0]
// | |
// | +-- Num of lengths (54)
// | |
// | +-- LENGTH 0 = 3 // 3 vertex = 1 triangle in the strip? Each length means 1 strip?
// | |
// | +-- LENGTH 1 = 6 // 6 vertex = 4 triangles in the strip? Each length means 1 strip?
// | |
// | ...
// | |
// | +-- LENGTH 63 = 4
// |
// |
// +-- LENGHTSLIST [1]
// |
// ...
// |
// +-- LENGHTSLIST [68]
//
// Each lenght a strip? How many triangles? len or len-2 as in VST format?
if (nodeIs(thisNode.type,"LENGHTS") ) {
if (!checkTextures) {
console.log(" Processing LENGHTS");
var listsCount = thisNode.contents.lists.length;
vertexOffset = 0;
strips = [];
for (var listIndex=0 ; listIndex < listsCount; listIndex++) { // Each list is a strip of faces or a list of strips of faces?
thisList = thisNode.contents.lists[listIndex];
arrayLengths = thisList.elements; // Each length refers to a strip, i.e. length <=> strip
for (var arrayLengthIndex = 0; arrayLengthIndex < arrayLengths.length; arrayLengthIndex++) {
var thisArrayLength = arrayLengths[arrayLengthIndex];
// array = [0,1,2,3,4], arrayLength = 5, striplLength = 3
strip = [];
for(var triangleIndex = 2; triangleIndex < thisArrayLength; triangleIndex++) { // Create triangle strip
triangle = [vertexOffset+2, vertexOffset+1, vertexOffset+0];
strip.push(triangle);
vertexOffset++;
} // parse vertices
strips.push(strip);
} // parse lengths
} // parse lists
}
} else // if node is lengthslists
if (nodeIs(thisNode.type,"TEXTURES LIST")) {
console.log(" Processing TEXTURES LIST");
texturesNodesFound = true;
texturesList = thisNode.contents.textures;
blenderList = "";
productsList = "<br>";
textureLinksArray = [];
XYZlinksArray = [];
VSTlinksArray = [];
thumbnailLinksArray = [];
textureFolderLinksArray = [];
XYZfolderLinksArray = [];
texturesList.forEach ((textureElement) => {
console.log(textureElement.filename.contents);
/*
2N290962708XYLB0HMP0755L0M2
# 0: 2 = MER2
# 1: N = Navcam
# 2-10: 290962708 = Spacecraft clock
# 11-13: XYL = XYL product
# 14-15: B0 = site
# 16-17: HM = drive/position w.r.t site
# 18-22: P0755 = sequence (�P� - PMA & Remote Sensing instr. (Pancam, Navcam, Hazcam, MI, Mini-TES)
# 23: L = left
# 24: 0 = filter
# 25: M = Author (MIPL)
# 26: 2 = Product version
*/
roverId = textureElement.filename.contents.substr(0,1);
cameraId = textureElement.filename.contents.substr(1,1)
sclk = textureElement.filename.contents.substr(2,9);
sol = sclkToSol(sclk, roverId);
siteId = textureElement.filename.contents.substr(14,2);
driveId = textureElement.filename.contents.substr(16,2);
sequenceId = textureElement.filename.contents.substr(18,5);
textureBaseUrl = "https://pds-imaging.jpl.nasa.gov/data/mer/" + roverName[roverId*1] + "/mer" + roverId + cameraId.toLowerCase() + "o_0xxx/browse/sol" + zeroes(sol,4) + "/rdr/";
XYZBaseUrl = "https://pds-imaging.jpl.nasa.gov/data/mer/" + roverName[roverId*1] + "/mer" + roverId + cameraId.toLowerCase() + "o_0xxx/data/sol" + zeroes(sol,4) + "/rdr/";
rawProductId = textureElement.filename.contents.toUpperCase().replace(".RGB","");
siteString = "site0" + siteCodeToString(siteId);
getSolNumberFromLabel(rawProductId + ".lbl", siteString)
blenderList += rawProductId + ",";
productsList += rawProductId + " - (clock: " + sclk + ", sol: " + sol + ", site: " + siteId + ", drive: " + driveId + ", sequence: " + sequenceId + ")<br>";
textureProductId = rawProductId.replace("XYL","FFL").toLowerCase();
textureLink = textureBaseUrl + textureProductId + ".img.jpg";
textureLinksArray.push(textureLink);
XYZproductId = rawProductId.toLowerCase();
XYZLink = XYZBaseUrl + XYZproductId + ".img";
XYZlinksArray.push(XYZLink);
VSTproductId = rawProductId.replace("XYL","VIL").toLowerCase();
VSTLink = BASE_VST_URL + VST_CAMERA_FOLDER + siteString + "/" + VSTproductId + ".vst";
console.log("VSTLink=",VSTLink);
VSTlinksArray.push(VSTLink);
thumbnailProductId = rawProductId.replace("XYL","RSN").toLowerCase();
thumbnailLink = textureBaseUrl + thumbnailProductId + ".img.jpg";
thumbnailLinksArray.push(thumbnailLink);
textureFolderLinksArray.push(textureBaseUrl);
XYZfolderLinksArray.push(XYZBaseUrl);
});
blenderList = blenderList.substr(0,blenderList.length-1);
/*console.log("Textures list for blender importer:");
console.log(blenderList);
console.log("Links list:");
console.log(textureLinksArray);
console.log(XYZlinksArray);
console.log(thumbnailLinksArray);*/
addLinksToPage();
} else // if node is Textures
if (nodeIs(thisNode.type,"NORMALS LIST")) {
if (!checkTextures) {
console.log(" Processing NORMALS LIST");
totalListLenghtN = [];
totalLenghtN = 0;
//console.log("Building normals db...");
for (var listIndex=0 ; listIndex<thisNode.contents.lists.length; listIndex++) {
var thisListN = thisNode.contents.lists[listIndex];
//console.log("Processing list " + listIndex + ", containing " + thisListN.elements.length + " vertices...");
totalListLenghtN[listIndex] = 0;
for (var elemIndex = 0; elemIndex < thisListN.elements.length ;elemIndex++) {
totalListLenghtN[listIndex] += 1
normalObj = thisListN.elements[elemIndex];
normalsDB.push(normalObj);
normalStr = "";
normalStr += normalObj.x + " " + normalObj.y + " " + normalObj.z;
normalsDBstr += normalStr + "\n";
}
// console.log(" ListV " , listIndex, ": ", thisListN.size , " vertices, ", totalListLenght[listIndex] );
totalLenghtN += totalListLenghtN[listIndex];
}
}
} else { // if node is NormalsLists
console.log(" SKIPPING " + thisNode.type + " (" + nodeTypes[thisNode.type] + ", not implemented yet.");
}
nodeOffset += NODE_HEADER_LENGTH + thisNode.contents.totalSize;
} // nodes
if (!checkTextures) {
createPLY();
XYZfile = "";
vertexGlobalIndex = 0;
var PFBvertexNode = myPFB.nodes[1]; // debug: non � detto che sia sempre in posizione 1
var PFBtexturesNode = myPFB.nodes[4]
PFBvertexLists = PFBvertexNode.contents.lists;
PFBtexturesLists = PFBtexturesNode.contents.lists;
for (var vertListIndex = 0; vertListIndex < PFBvertexLists.length; vertListIndex++) {
PFBvertList = PFBvertexLists[vertListIndex];
PFBtextureList = PFBtexturesLists[vertListIndex];
for (vertIndex = 0; vertIndex < PFBvertList.elements.length; vertIndex++) {
var vertex = PFBvertList.elements[vertIndex];
var texture = PFBtextureList.elements[vertIndex];
TextureX = (texture.s * 2048).toFixed(0)*1; // debug orizz
TextureY = (texture.t * 1024).toFixed(0)*1; //
if (TextureX < 1024) {
colorVal = myImg1.lines[TextureX].samples[TextureY]
} else {
colorVal = myImg2.lines[TextureX-1024].samples[TextureY]
}
writeCanvas(TextureX,TextureY,colorVal/16,colorVal/16,colorVal/16)
XYZline = "" +
vertex.x + " " +
vertex.y + " " +
vertex.z + " " +
colorVal + " " +
colorVal + " " +
colorVal;
/* if (normalsDB.length > 0) {
XYZline += "" +
normalsDB[vertexGlobalIndex]
}*/
vertexGlobalIndex++;
XYZfile += XYZline + "\n";
}
}
}
alert("Done");
});
reader.readAsArrayBuffer(fileHandler);
}
function createPLY() {
for (stripIndex = 0; stripIndex < strips.length; stripIndex++) {
strip = strips[stripIndex];
for (var triangleIndex = 0; triangleIndex < strip.length; triangleIndex++) {
triangle = strip[triangleIndex];
face = []
faceStr = triangle.length + " ";
for (var vertexIndex =0; vertexIndex<triangle.length; vertexIndex++) {
vertexPointer = triangle[vertexIndex];
face.push(vertexPointer);
faceStr += vertexPointer + " ";
}
facesDB.push(face);
facesDBstr += faceStr + "\n";
}
}
PLYheader = PLY_HEADER_BASE.replace("VVVV", vertexDB.length);
PLYheader = PLYheader.replace("FFFF", facesDB.length);
PLYfile = PLYheader + vertexDBstr + facesDBstr;
}
function savePLY() {
saveFile(PLYfile, myName + ".ply","file_status");
}
function saveXYZ() {
saveFile(XYZfile, myName + ".txt","file_status");
}
function loadTexture() {
}
function sclkToSol(sclkstring, rover) {
// Calculate sol number given SCLK string (credits: https://github.com/phaseIV/Blender-Navcam-Importer )
MSD = (sclkstring/88775.244) + 44795.9998;
sol = MSD - 49269.2432411704;
sol = sol + 1; // for sol 0
sol = Math.floor(Math.ceil(sol));
deviate = 0;
if (rover == OPPORTUNITY) {
deviate = 3028
}
if (rover == SPIRIT) {
deviate = 3048
}
return sol+deviate
}
function zeroes(number, figures) {
temp = "";
for(var i = figures; i > 0 ; i--) {
confr = 10**(i-1);
if (number < confr)
temp += "0";
}
return temp + number;
}
function addLinksToPage() {
document.getElementById("spnBlender").innerHTML = "Past this sequence into <a href='https://github.com/jumpjack/Blender-Navcam-Importer'>Blender Navcam Importer</a> dialog:<br>" + blenderList + "<br>" + productsList + "<br>";
document.getElementById("spnTextureLinks").innerHTML = "Links to save in %TEMP%\\MarsRoverImages\\mer\\gallery\\all\\" + roverId + "\\" + cameraId.toLowerCase() + "\\" + zeroes(sol,4) + "<br>";
for (var textureIndex = 0; textureIndex < textureLinksArray.length; textureIndex++) {
//console.log("aggiungo " + textureLinksArray[textureIndex] );
document.getElementById("spnTextureLinks").innerHTML += "<a href='" + textureLinksArray[textureIndex] + "'>" + textureLinksArray[textureIndex] + "</a> (<a href='" + textureFolderLinksArray[textureIndex] + "'>Folder</a>)<br>";
}
// C:\Users\USER\AppData\Local\Temp\MarsRoverImages\mer\mer2no_0xxx\data\sol01907
document.getElementById("spnXYZLinks").innerHTML = "Links to save in %TEMP%\\MarsRoverImages\\mer\\mer" + roverId + cameraId.toLowerCase() + "o_0xxx\\data\\sol" + zeroes(sol,4) + "<br>";
document.getElementById("spnVSTLinks").innerHTML = "Links to VST files:<br>";
for (var XYZIndex = 0; XYZIndex < XYZlinksArray.length; XYZIndex++) {
//console.log(" aggiungo " + XYZlinksArray[XYZIndex] );
document.getElementById("spnXYZLinks").innerHTML += "<a href='" + XYZlinksArray[XYZIndex] + "'>" + XYZlinksArray[XYZIndex] + "</a> (<a href='" + XYZfolderLinksArray[XYZIndex] + "'>Folder</a>)<br>";
document.getElementById("spnVSTLinks").innerHTML += "<a href='" + VSTlinksArray[XYZIndex] + "'>" + VSTlinksArray[XYZIndex] + "</a> (<a href='" + XYZfolderLinksArray[XYZIndex] + "'>Folder</a>)<br>";
}
document.getElementById("spnThumbnails").innerHTML = "";
for (var thIndex = 0; thIndex < thumbnailLinksArray.length; thIndex++) {
//console.log(" aggiungo " + thumbnailLinksArray[thIndex] );
document.getElementById("spnThumbnails").innerHTML += "<img src='" + thumbnailLinksArray[thIndex] + "'>";
}}
function writeCanvas(x,y,r,g,b) {
ctx.fillStyle = 'rgb(' + r + ',' + g + ',' + b + ')';
ctx.fillRect(x,y,x+1,y+1);
}
async function getSolNumberFromLabel(lblFileName, siteNumberString) {
lblUrl = BASE_VST_URL + VST_CAMERA_FOLDER + siteNumberString + "/" + lblFileName ; // DEBUG: valid only up to site 0138, for Spirit!!
lblFinalUrl = proxyURL + encodeURIComponent(lblUrl.toLowerCase());
console.log("------- DOWNLOADING ",lblUrl);
try {
const response = await fetch(lblFinalUrl);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const blob = await response.blob();
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onloadend = () => {
let VSTlabel = reader.result;
let solNumber = extractSol(VSTlabel);
resolve(solNumber);
};
reader.onerror = reject;
reader.readAsText(blob);
});
} catch (error) {
throw new Error(`Errore durante la conversione dell'immagine: ${error.message}`);
}
}
function siteCodeToString(code) {
if (code.length !== 2) {
throw new Error("Il codice deve essere una stringa di due caratteri.");
}
const firstChar = code[0];
const secondChar = code[1];
// Caso 1: numerico puro ("00" - "99")
if (!isNaN(firstChar) && !isNaN(secondChar)) {
return parseInt(code, 10);
}
// Caso 2: alfanumerico ("A0" - "ZZ")
const alphabetOffset = 'A'.charCodeAt(0); // Offset per calcolare il valore delle lettere
const firstValue = firstChar.charCodeAt(0) - alphabetOffset;
let secondValue;
if (isNaN(secondChar)) {
// Se il secondo carattere è una lettera
secondValue = secondChar.charCodeAt(0) - alphabetOffset + 10;
} else {
// Se il secondo carattere è un numero
secondValue = parseInt(secondChar, 10);
}
// Formula per calcolare l'intervallo corretto (da 100 in poi)
return 100 + firstValue * 36 + secondValue;
}
function extractSol(labelContent) {
const match = labelContent.match(/PLANET_DAY_NUMBER\s*=\s*(\d+)/);
if (match) {
return parseInt(match[1], 10);
} else {
throw new Error("PLANET_DAY_NUMBER non trovato nel contenuto fornito.");
}
}
</script>
</body>
</html>