forked from saavor/mkjs
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathdebug.html
More file actions
3009 lines (2747 loc) · 90 KB
/
Copy pathdebug.html
File metadata and controls
3009 lines (2747 loc) · 90 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
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
<!doctype html>
<html lang="en">
<head>
<link rel="icon" href="data:;base64,iVBORw0KGgo=" />
<meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover" />
<script src="bundle.js"></script>
<script>
var mobile = false;
var gameROM = null;
var gl = null;
var viewer = null; // state of the currently displayed model
var archiveCache = {}; // already-opened narcs, indexed by archive path
var view2d = null; // state of the currently displayed 2D image (NCGR / NCLR)
var animTimeRemainder = 0;
var fileListReady = false;
var DEBUG_LS = {
nameFilter: "debug_nameFilter",
extFilter: "debug_extFilter",
selectedPath: "debug_selectedPath",
};
window.onload = function () {
init();
};
window.onerror = function (...args) {
const [msg, url, line, col, e] = args;
if (e) {
var stack = e.stack
.replace(/^[^\(]+?[\n$]/gm, "")
.replace(/^\s+at\s+/gm, "")
.replace(/^Object.<anonymous>\s*\(/gm, "{anonymous}()@")
.split("\n");
console.error(stack);
}
};
function init() {
gl = initGL(document.getElementById("canvas3d"));
nitroRender.init(gl);
setupViewerControls();
setupFileListControls();
setupRomControls();
setupSdatControls();
restoreDebugFilters();
renderLoop();
setStatus("Loading ROM…");
loadCachedRom();
}
function saveDebugState() {
try {
localStorage.setItem(DEBUG_LS.nameFilter, document.getElementById("nameFilter").value);
localStorage.setItem(DEBUG_LS.extFilter, document.getElementById("extFilter").value);
var sel = document.querySelector("#list .sel");
if (sel) localStorage.setItem(DEBUG_LS.selectedPath, sel.getAttribute("data-path") || "");
} catch (e) {}
}
function restoreDebugFilters() {
try {
var name = localStorage.getItem(DEBUG_LS.nameFilter);
if (name != null) document.getElementById("nameFilter").value = name;
} catch (e) {}
}
function restoreSelectedFile() {
var path = localStorage.getItem(DEBUG_LS.selectedPath);
if (!path || !gameROM || window.romFiles.indexOf(path) === -1) return;
openRomPath(path);
}
function setupRomControls() {
document.getElementById("loadCachedRom").addEventListener("click", loadCachedRom);
document.getElementById("openRomFile").addEventListener("click", promptOverwriteRom);
fileStore.getInstance().checkRom(updateCachedRomButton);
}
function promptOverwriteRom() {
var input = document.getElementById("fileIn");
input.value = "";
input.onchange = function (e) {
var file = e.target.files && e.target.files[0];
if (!file) return;
setStatus("Loading " + file.name + "…");
var reader = new FileReader();
reader.onload = function (ev) {
initWithRom(ev.target.result);
restoreSelectedFile();
};
reader.onerror = function () {
setStatus("Failed to read ROM file");
};
reader.readAsArrayBuffer(file);
};
input.click();
}
function updateCachedRomButton(hasRom) {
var btn = document.getElementById("loadCachedRom");
btn.disabled = !hasRom;
btn.title = hasRom ? "Reload ROM from IndexedDB (game cache)" : "No ROM in IndexedDB — use Open ROM file";
}
function loadCachedRom() {
setStatus("Loading cached ROM…");
fileStore.getInstance().loadRom(onRomLoaded);
}
function onRomLoaded(rom) {
if (!rom) {
showEmptyRomList();
setStatus("No ROM in cache — use Open ROM file to load a .nds into memory");
return;
}
initWithRom(rom);
restoreSelectedFile();
}
function initWithRom(rom) {
gameROM = new ndsFS(rom);
archiveCache = {};
viewer = null;
view2d = null;
show3D();
listROMFiles(gameROM);
document.getElementById("romInfo").textContent = rom.byteLength ? (rom.byteLength / (1024 * 1024)).toFixed(1) + " MiB" : "";
setStatus("ROM loaded — click a file to display it");
fileStore.getInstance().checkRom(updateCachedRomButton);
}
function showEmptyRomList() {
window.romFiles = [];
window.filteredRomFiles = [];
document.getElementById("list").innerHTML = '<div class="rom-placeholder">Load a ROM to browse files</div>';
document.getElementById("extFilter").innerHTML = '<option value="">All extensions</option>';
document.getElementById("romInfo").textContent = "";
}
// ---------------------------------------------------------------------
// ROM file reading / listing
// ---------------------------------------------------------------------
function isArchiveName(name) {
var l = name.toLowerCase();
return l.endsWith(".narc") || l.endsWith(".carc");
}
// Reads a file by its full path, descending through any internal
// archives (.narc / .carc) encountered along the way.
function readROMFile(fullPath) {
if (!gameROM) throw new Error("No ROM loaded");
var parts = fullPath.split("/").filter(function (p) {
return p.length > 0;
});
var fs = gameROM;
var rel = "";
var archiveKey = "";
for (var i = 0; i < parts.length; i++) {
rel += "/" + parts[i];
archiveKey += "/" + parts[i];
if (isArchiveName(parts[i]) && i < parts.length - 1) {
var sub = archiveCache[archiveKey];
if (!sub) {
var buf = fs.getFile(rel);
if (parts[i].toLowerCase().endsWith(".carc")) buf = lz77.decompress(buf);
sub = new narc(buf);
archiveCache[archiveKey] = sub;
}
fs = sub;
rel = "";
}
}
return fs.getFile(rel);
}
// Recursively walks the ROM, expanding archives to collect ALL files.
function collectROMFiles(fs, basePath, out) {
var files = fs.list([], null, "/");
for (var i = 0; i < files.length; i++) {
var rel = files[i];
var full = (basePath === "/" ? "" : basePath) + rel;
out.push(full);
if (isArchiveName(rel)) {
try {
var buf = fs.getFile(rel);
if (rel.toLowerCase().endsWith(".carc")) buf = lz77.decompress(buf);
collectROMFiles(new narc(buf), full, out);
} catch (e) {
// Unreadable archive: keep just the file itself.
}
}
}
return out;
}
function getFileExt(path) {
var name = path.substring(path.lastIndexOf("/") + 1);
var dot = name.lastIndexOf(".");
if (dot <= 0 || dot === name.length - 1) return "";
return name.substring(dot + 1).toLowerCase();
}
function fileClassFromPath(path) {
var l = path.toLowerCase();
return l.endsWith(".nsbmd")
? " mdl"
: l.endsWith(".nsbca")
? " anim"
: l.endsWith(".nsbma")
? " mat"
: l.endsWith(".nsbta")
? " tanim"
: l.endsWith(".nsbtp")
? " tanim"
: l.endsWith(".ncgr")
? " tex"
: l.endsWith(".nclr")
? " pal"
: l.endsWith(".nscr")
? " scr"
: l.endsWith(".ncer")
? " cell"
: l.endsWith(".nsbtx")
? " btx"
: l.endsWith(".nkm")
? " nkm"
: l.endsWith(".spa")
? " spa"
: l.endsWith(".bin")
? " bin"
: l.endsWith(".tbl") || l.endsWith(".mtbl") || l.endsWith(".ktbl")
? " tbl"
: l.endsWith(".sdat")
? " sdat"
: "";
}
function renderFilteredList() {
var files = window.romFiles;
var query = document.getElementById("nameFilter").value.trim().toLowerCase();
var selectedExt = document.getElementById("extFilter").value;
var html = [];
var filtered = [];
for (var i = 0; i < files.length; i++) {
var path = files[i];
var lowerPath = path.toLowerCase();
if (query && lowerPath.indexOf(query) === -1) continue;
if (selectedExt && getFileExt(path) !== selectedExt) continue;
if (path.endsWith(".carc")) continue;
filtered.push(path);
html.push('<div class="f' + fileClassFromPath(path) + '" data-path="' + path + '">' + path + "</div>");
}
window.filteredRomFiles = filtered;
document.getElementById("list").innerHTML = html.join("");
saveDebugState();
}
function openRomPath(path) {
if (!gameROM) return;
var el = null;
var nodes = document.getElementById("list").querySelectorAll("[data-path]");
for (var i = 0; i < nodes.length; i++) {
if (nodes[i].getAttribute("data-path") === path) {
el = nodes[i];
break;
}
}
loadFileByPath(path, el);
}
function loadFileByPath(path, el) {
var lp = path.toLowerCase();
if (
lp.endsWith(".nsbmd") ||
lp.endsWith(".nsbca") ||
lp.endsWith(".nsbma") ||
lp.endsWith(".nsbta") ||
lp.endsWith(".nsbtp")
)
loadView(path, el);
else if (lp.endsWith(".ncgr")) loadNCGR(path, el);
else if (lp.endsWith(".nclr")) loadNCLR(path, el);
else if (lp.endsWith(".nscr")) loadNSCR(path, el);
else if (lp.endsWith(".ncer")) loadNCER(path, el);
else if (lp.endsWith(".nsbtx")) loadNSBTX(path, el);
else if (lp.endsWith(".nkm")) loadNKM(path, el);
else if (lp.endsWith(".spa")) loadSPA(path, el);
else if (lp.endsWith(".bin")) loadBIN(path, el);
else if (lp.endsWith(".tbl") || lp.endsWith(".mtbl") || lp.endsWith(".ktbl")) loadTBL(path, el);
else if (lp.endsWith(".sdat")) loadSDAT(path, el);
}
function setupFileListControls() {
if (fileListReady) return;
fileListReady = true;
var list = document.getElementById("list");
document.getElementById("nameFilter").addEventListener("input", renderFilteredList);
document.getElementById("extFilter").addEventListener("change", renderFilteredList);
list.addEventListener("click", function (e) {
if (!gameROM) return;
var t = e.target;
while (t && t !== list && t.getAttribute("data-path") == null) t = t.parentNode;
if (!t || t === list) return;
loadFileByPath(t.getAttribute("data-path"), t);
});
}
function listROMFiles(rom) {
var files = collectROMFiles(rom, "/", []);
files.sort();
window.romFiles = files;
window.filteredRomFiles = files.slice();
var extMap = Object.create(null);
for (var i = 0; i < files.length; i++) {
var ext = getFileExt(files[i]);
if (ext) extMap[ext] = true;
}
var exts = Object.keys(extMap).sort();
var opts = ['<option value="">All extensions</option>'];
for (var j = 0; j < exts.length; j++) {
opts.push('<option value="' + exts[j] + '">.' + exts[j] + "</option>");
}
document.getElementById("extFilter").innerHTML = opts.join("");
try {
var savedExt = localStorage.getItem(DEBUG_LS.extFilter);
if (savedExt != null && (savedExt === "" || extMap[savedExt])) {
document.getElementById("extFilter").value = savedExt;
}
} catch (e) {}
renderFilteredList();
return files;
}
// ---------------------------------------------------------------------
// Loading a nsbca + its model into the canvas
// ---------------------------------------------------------------------
function findSibling(animPath, ext) {
var slash = animPath.lastIndexOf("/");
var dir = animPath.substring(0, slash + 1);
var base = animPath.substring(slash + 1).replace(/\.[^.]+$/, "");
var exact = dir + base + ext;
if (window.romFiles.indexOf(exact) !== -1) return exact;
// fallback: first file with the desired extension in the same directory
var re = new RegExp("\\" + ext + "$", "i");
for (var i = 0; i < window.romFiles.length; i++) {
var p = window.romFiles[i];
if (p.indexOf(dir) === 0 && p.substring(dir.length).indexOf("/") === -1 && re.test(p)) return p;
}
return null;
}
// Returns all files with the given extension whose filename starts with
// the base name of the .nsbmd. Falls back to findSibling if no results.
function findFilesForBMD(bmdPath, ext) {
var slash = bmdPath.lastIndexOf("/");
var baseName = bmdPath
.substring(slash + 1)
.replace(/\.nsbmd$/i, "")
.toLowerCase();
var results = [];
for (var i = 0; i < window.romFiles.length; i++) {
var p = window.romFiles[i];
if (!p.toLowerCase().endsWith(ext)) continue;
var fname = p.substring(p.lastIndexOf("/") + 1).toLowerCase();
if (fname.indexOf(baseName) === 0) results.push(p);
}
if (results.length === 0) {
var sib = findSibling(bmdPath, ext);
if (sib) results.push(sib);
}
return results;
}
// Populates a <select> with "(none)" + the candidates.
// preferredPath: pre-selects this path if it is in the list.
// autoFirst: selects the first candidate if no preferredPath matches.
// Returns the selected path (null if "(none)").
function populateBMDSelect(id, candidates, preferredPath, autoFirst) {
var sel = document.getElementById(id);
sel.innerHTML = "";
var noneOpt = document.createElement("option");
noneOpt.value = "";
noneOpt.textContent = "(none)";
sel.appendChild(noneOpt);
var selectedIdx = 0;
for (var i = 0; i < candidates.length; i++) {
var opt = document.createElement("option");
opt.value = candidates[i];
opt.textContent = candidates[i].substring(candidates[i].lastIndexOf("/") + 1);
sel.appendChild(opt);
if (preferredPath && candidates[i] === preferredPath) selectedIdx = i + 1;
}
if (selectedIdx === 0 && autoFirst && candidates.length > 0) selectedIdx = 1;
sel.selectedIndex = selectedIdx;
sel.style.display = candidates.length > 0 ? "" : "none";
return sel.options[selectedIdx].value || null;
}
// Loads a model into the canvas from the clicked file.
// - .nsbmd: the model itself + companions auto-detected
// - .nsbca / .nsbtp / .nsbta / .nsbtx: pre-selects the clicked file
// - .nsbma: neighbouring .nsbmd model, static (animations hidden)
function loadView(clickedPath, el) {
show3D();
var lower = clickedPath.toLowerCase();
var isMat = lower.endsWith(".nsbma");
var bmdPath = lower.endsWith(".nsbmd") ? clickedPath : findSibling(clickedPath, ".nsbmd");
if (!bmdPath) {
setStatus("No .nsbmd found for " + clickedPath);
return;
}
var btxPath = populateBMDSelect(
"btxSelect",
findFilesForBMD(bmdPath, ".nsbtx"),
lower.endsWith(".nsbtx") ? clickedPath : null,
true
);
if (isMat) {
document.getElementById("bcaSelect").style.display = "none";
document.getElementById("btpSelect").style.display = "none";
document.getElementById("btaSelect").style.display = "none";
applyViewLoad(bmdPath, btxPath, null, null, null, true, el);
} else {
var bcaPath = populateBMDSelect(
"bcaSelect",
findFilesForBMD(bmdPath, ".nsbca"),
lower.endsWith(".nsbca") ? clickedPath : null,
true
);
var btpPath = populateBMDSelect(
"btpSelect",
findFilesForBMD(bmdPath, ".nsbtp"),
lower.endsWith(".nsbtp") ? clickedPath : null,
true
);
var btaPath = populateBMDSelect(
"btaSelect",
findFilesForBMD(bmdPath, ".nsbta"),
lower.endsWith(".nsbta") ? clickedPath : null,
true
);
applyViewLoad(bmdPath, btxPath, bcaPath, btpPath, btaPath, false, el);
}
}
// Performs the actual model loading with the provided paths.
function applyViewLoad(bmdPath, btxPath, bcaPath, btpPath, btaPath, isMat, el) {
try {
var bmd = new nsbmd(readROMFile(bmdPath));
var loaded = [bmdPath];
var btx = null;
if (btxPath) {
try {
btx = new nsbtx(readROMFile(btxPath));
loaded.push(btxPath);
} catch (e) {
btx = null;
}
}
var model = new nitroModel(bmd, btx);
var anim = null,
bca = null,
length = 1,
hasTexAnim = false;
if (!isMat) {
if (bcaPath) {
try {
bca = new nsbca(readROMFile(bcaPath));
anim = new nitroAnimator(bmd, bca);
length = Math.max(1, anim.getLength(0));
loaded.push(bcaPath);
} catch (e) {
bca = null;
anim = null;
}
}
if (btpPath) {
try {
model.loadTexPAnim(new nsbtp(readROMFile(btpPath)));
hasTexAnim = true;
loaded.push(btpPath);
} catch (e) {}
}
if (btaPath) {
try {
model.loadTexAnim(new nsbta(readROMFile(btaPath)));
hasTexAnim = true;
loaded.push(btaPath);
} catch (e) {}
}
}
animTimeRemainder = 0;
renderLoop.lastTime = 0;
viewer = {
bmdPath: bmdPath,
model: model,
anim: anim,
animMat: null,
animIndex: 0,
length: length,
hasTexAnim: hasTexAnim,
frame: 0,
center: [0, 0, 0],
radius: 0,
dist: 1,
yaw: 0,
pitch: -0.3,
fitted: false,
};
if (bca) {
populateAnimSelect(bca);
} else {
var sel = document.getElementById("animSelect");
sel.innerHTML = "";
sel.style.display = "none";
}
if (el) setSel(el);
var note = isMat ? " (.nsbma not applied: static model)" : "";
setStatus(loaded.join(" + ") + note);
} catch (err) {
console.error(err);
setStatus("Load error: " + (err && err.message ? err.message : err));
}
}
// Reloads the current model from the selector values, preserving the camera.
function reloadFromSelects() {
if (!viewer || !viewer.bmdPath) return;
var camera = {
center: viewer.center.slice(),
radius: viewer.radius,
dist: viewer.dist,
yaw: viewer.yaw,
pitch: viewer.pitch,
fitted: viewer.fitted,
};
var bmdPath = viewer.bmdPath;
var btxPath = document.getElementById("btxSelect").value || null;
var bcaPath = document.getElementById("bcaSelect").value || null;
var btpPath = document.getElementById("btpSelect").value || null;
var btaPath = document.getElementById("btaSelect").value || null;
applyViewLoad(bmdPath, btxPath, bcaPath, btpPath, btaPath, false, null);
if (viewer) {
viewer.center = camera.center;
viewer.radius = camera.radius;
viewer.dist = camera.dist;
viewer.yaw = camera.yaw;
viewer.pitch = camera.pitch;
viewer.fitted = camera.fitted;
}
}
function setStatus(txt) {
document.getElementById("status").textContent = txt;
}
// Populates the selector with the animations contained in the nsbca.
function populateAnimSelect(bca) {
var sel = document.getElementById("animSelect");
var names = bca.animData.names || [];
var count = bca.animData.objectData.length;
sel.innerHTML = "";
for (var i = 0; i < count; i++) {
var opt = document.createElement("option");
opt.value = i;
opt.textContent = (names[i] != null ? names[i] : "anim " + i) + " (" + viewer.anim.getLength(i) + "f)";
sel.appendChild(opt);
}
sel.selectedIndex = 0;
sel.style.display = count > 1 ? "" : "none";
}
// ---------------------------------------------------------------------
// Highlight the selection in the list
// ---------------------------------------------------------------------
function setSel(el) {
document.querySelectorAll("#list .sel").forEach(function (n) {
n.classList.remove("sel");
});
if (el) {
el.classList.add("sel");
el.scrollIntoView({ block: "nearest" });
}
saveDebugState();
}
// ---------------------------------------------------------------------
// 2D display (NCGR / NCLR) in an overlay canvas
// ---------------------------------------------------------------------
// Switches to 3D rendering (models): hides the 2D canvas and 2D selectors.
function show3D() {
view2d = null;
sdatView = null;
document.getElementById("viewSdat").style.display = "none";
document.getElementById("sdatSectionSelect").style.display = "none";
document.getElementById("sdatSeqSelect").style.display = "none";
document.getElementById("sdatVolLabel").style.display = "none";
document.getElementById("sdatVol").style.display = "none";
document.getElementById("sdatPlayBtn").style.display = "none";
document.getElementById("sdatStopBtn").style.display = "none";
document.getElementById("view2d").style.display = "none";
document.getElementById("viewText").style.display = "none";
document.getElementById("canvas3d").style.display = "";
document.getElementById("texSelect").style.display = "none";
document.getElementById("ncgrSelect").style.display = "none";
document.getElementById("nclrSelect").style.display = "none";
document.getElementById("palSelect").style.display = "none";
document.getElementById("animFps").style.display = "";
document.getElementById("animFpsLabel").style.display = "";
}
// Switches to 2D rendering (images): stops 3D rendering.
function show2D() {
viewer = null;
sdatView = null;
document.getElementById("viewSdat").style.display = "none";
document.getElementById("sdatSectionSelect").style.display = "none";
document.getElementById("sdatSeqSelect").style.display = "none";
document.getElementById("sdatVolLabel").style.display = "none";
document.getElementById("sdatVol").style.display = "none";
document.getElementById("sdatPlayBtn").style.display = "none";
document.getElementById("sdatStopBtn").style.display = "none";
document.getElementById("viewText").style.display = "none";
document.getElementById("canvas3d").style.display = "none";
document.getElementById("animSelect").style.display = "none";
document.getElementById("palSelect").style.display = "none";
document.getElementById("texSelect").style.display = "none";
document.getElementById("ncgrSelect").style.display = "none";
document.getElementById("nclrSelect").style.display = "none";
document.getElementById("btxSelect").style.display = "none";
document.getElementById("bcaSelect").style.display = "none";
document.getElementById("btpSelect").style.display = "none";
document.getElementById("btaSelect").style.display = "none";
document.getElementById("animFps").style.display = "none";
document.getElementById("animFpsLabel").style.display = "none";
document.getElementById("view2d").style.display = "block";
}
var sdatView = null;
var sdatPlayer = null;
function showSdatView() {
viewer = null;
view2d = null;
document.getElementById("canvas3d").style.display = "none";
document.getElementById("view2d").style.display = "none";
document.getElementById("viewText").style.display = "none";
document.getElementById("animSelect").style.display = "none";
document.getElementById("palSelect").style.display = "none";
document.getElementById("texSelect").style.display = "none";
document.getElementById("ncgrSelect").style.display = "none";
document.getElementById("nclrSelect").style.display = "none";
document.getElementById("btxSelect").style.display = "none";
document.getElementById("bcaSelect").style.display = "none";
document.getElementById("btpSelect").style.display = "none";
document.getElementById("btaSelect").style.display = "none";
document.getElementById("animFps").style.display = "none";
document.getElementById("animFpsLabel").style.display = "none";
document.getElementById("sdatSectionSelect").style.display = "";
document.getElementById("sdatSeqSelect").style.display = "";
document.getElementById("sdatVolLabel").style.display = "";
document.getElementById("sdatVol").style.display = "";
document.getElementById("sdatPlayBtn").style.display = "";
document.getElementById("sdatStopBtn").style.display = "";
document.getElementById("viewSdat").style.display = "block";
}
function showTextView() {
viewer = null;
view2d = null;
sdatView = null;
document.getElementById("viewSdat").style.display = "none";
document.getElementById("sdatSectionSelect").style.display = "none";
document.getElementById("sdatSeqSelect").style.display = "none";
document.getElementById("sdatVolLabel").style.display = "none";
document.getElementById("sdatVol").style.display = "none";
document.getElementById("sdatPlayBtn").style.display = "none";
document.getElementById("sdatStopBtn").style.display = "none";
document.getElementById("canvas3d").style.display = "none";
document.getElementById("view2d").style.display = "none";
document.getElementById("animSelect").style.display = "none";
document.getElementById("palSelect").style.display = "none";
document.getElementById("texSelect").style.display = "none";
document.getElementById("ncgrSelect").style.display = "none";
document.getElementById("nclrSelect").style.display = "none";
document.getElementById("btxSelect").style.display = "none";
document.getElementById("bcaSelect").style.display = "none";
document.getElementById("btpSelect").style.display = "none";
document.getElementById("btaSelect").style.display = "none";
document.getElementById("viewText").style.display = "block";
}
function readMagic4(view) {
var bytes = [];
for (var i = 0; i < 4; i++) bytes.push(view.getUint8(i));
var text = String.fromCharCode.apply(null, bytes);
var hex = bytes
.map(function (b) {
return (b < 16 ? "0" : "") + b.toString(16);
})
.join(" ");
return { text: text, hex: hex };
}
function prettyJson(value) {
return JSON.stringify(
value,
function (_key, v) {
if (v && typeof v === "object" && v.length === 3 && typeof v[0] === "number" && v.buffer instanceof ArrayBuffer) {
return [+v[0].toFixed(4), +v[1].toFixed(4), +v[2].toFixed(4)];
}
return v;
},
2
);
}
function tryDecodeText(buf) {
var bytes = new Uint8Array(buf);
var printable = 0;
for (var i = 0; i < bytes.length; i++) {
var b = bytes[i];
if (b === 9 || b === 10 || b === 13 || (b >= 32 && b < 127)) printable++;
}
if (bytes.length === 0 || printable / bytes.length < 0.85) return null;
return new TextDecoder("utf-8", { fatal: false }).decode(bytes).replace(/\0/g, "");
}
function formatHexDump(bytes, maxBytes) {
var limit = maxBytes != null ? Math.min(bytes.length, maxBytes) : bytes.length;
var lines = [];
for (var i = 0; i < limit; i += 16) {
var hex = [],
ascii = [];
for (var j = 0; j < 16 && i + j < limit; j++) {
var b = bytes[i + j];
hex.push((b < 16 ? "0" : "") + b.toString(16));
ascii.push(b >= 32 && b < 127 ? String.fromCharCode(b) : ".");
}
var off = ("00000000" + i.toString(16)).slice(-8);
while (hex.length < 16) {
hex.push(" ");
ascii.push(" ");
}
lines.push(off + " " + hex.slice(0, 8).join(" ") + " " + hex.slice(8).join(" ") + " |" + ascii.join("") + "|");
}
if (bytes.length > limit) {
lines.push("... (" + (bytes.length - limit) + " more bytes, scroll not shown)");
}
return lines.join("\n");
}
function parseBinSummary(buf, path) {
var base = path.substring(path.lastIndexOf("/") + 1).toLowerCase();
var view = new DataView(buf);
var lines = ["Size: " + buf.byteLength + " bytes"];
if (buf.byteLength >= 4) {
var magic = readMagic4(view);
lines.push("Magic: " + JSON.stringify(magic.text) + " (" + magic.hex + ")");
}
if (base === "kartoffsetdata.bin") {
try {
var offsets = new kartoffsetdata(buf);
lines.push("", "Parsed as kartoffsetdata (" + offsets.karts.length + " entries):", prettyJson(offsets.karts));
} catch (e) {
lines.push("", "kartoffsetdata parse error: " + (e && e.message ? e.message : e));
}
return lines.join("\n");
}
if (base === "kartphysicalparam.bin") {
try {
var phys = new kartphysicalparam(buf);
lines.push("", "Parsed as kartphysicalparam (" + phys.karts.length + " entries):", prettyJson(phys.karts));
} catch (e) {
lines.push("", "kartphysicalparam parse error: " + (e && e.message ? e.message : e));
}
return lines.join("\n");
}
if (buf.byteLength >= 4 && readMagic4(view).text === "NKDG") {
lines.push("", "Ghost replay (NKDG):");
if (buf.byteLength >= 6) lines.push(" field @4: " + view.getUint16(4, true));
if (buf.byteLength >= 9) lines.push(" course id @8: " + view.getUint8(8));
return lines.join("\n");
}
var text = tryDecodeText(buf);
if (text) {
lines.push("", "Text content:", text);
}
return lines.join("\n");
}
function objIdHex(id) {
var h = id.toString(16);
while (h.length < 4) h = "0" + h;
return "0x" + h;
}
function objDatabaseClassName(id) {
if (typeof ObjDatabase === "undefined" || !ObjDatabase.has(id)) return null;
var cls = ObjDatabase.get(id);
return cls && cls.name ? cls.name : null;
}
function formatNkmObjiSummary(map) {
var objs = map.sections.OBJI ? map.sections.OBJI.entries : [];
var lines = ["OBJI section: " + objs.length + " object(s)", ""];
for (var i = 0; i < objs.length; i++) {
var o = objs[i];
var cls = objDatabaseClassName(o.ID);
var label = cls != null ? cls : "(not in ObjDatabase)";
lines.push(
"#" +
i +
" ID=" +
objIdHex(o.ID) +
" " +
label +
" route=" +
o.routeID +
" pos=[" +
o.pos[0].toFixed(1) +
", " +
o.pos[1].toFixed(1) +
", " +
o.pos[2].toFixed(1) +
"]" +
" angle=[" +
o.angle[0].toFixed(1) +
", " +
o.angle[1].toFixed(1) +
", " +
o.angle[2].toFixed(1) +
"]" +
" scale=[" +
o.scale[0].toFixed(2) +
", " +
o.scale[1].toFixed(2) +
", " +
o.scale[2].toFixed(2) +
"]" +
" s1=" +
o.setting1 +
" s2=" +
o.setting2 +
" s3=" +
o.setting3 +
" s4=" +
o.setting4
);
}
return lines.join("\n");
}
function loadNKM(path, el) {
try {
var buf = readROMFile(path);
var map = new nkm(buf);
showTextView();
var magic = readMagic4(new DataView(buf));
document.getElementById("binSummary").textContent =
"Size: " +
buf.byteLength +
" bytes\nMagic: " +
JSON.stringify(magic.text) +
" (" +
magic.hex +
")\n\n" +
formatNkmObjiSummary(map);
document.getElementById("binHex").textContent = "";
setSel(el);
var n = map.sections.OBJI ? map.sections.OBJI.entries.length : 0;
setStatus(path + " (" + n + " OBJI)");
} catch (err) {
console.error(err);
setStatus("Load error: " + (err && err.message ? err.message : err));
}
}
function grpCollisionLabel(type) {
return ["None", "Sphere", "Spheroid", "Cylinder", "Box", "Custom"][type] || "?" + type;
}
function grpModelLabel(type) {
return ["None", "3D", "2D"][type] || "?" + type;
}
function formatTblSummary(t, path) {
var base = path.substring(path.lastIndexOf("/") + 1);
var lines = ["File: " + base, "Kind: " + t.kind, "Size: " + t.input.byteLength + " bytes", ""];
if (t.kind === "grpconf") {
lines.push("grpconf.tbl — " + t.entries.length + " object entries (16 bytes each, GRPEdit layout)", "");
for (var i = 0; i < t.entries.length; i++) {
var e = t.entries[i];
var cls = objDatabaseClassName(e.objectId);
var label = cls != null ? cls : "(not in ObjDatabase)";
lines.push(
"#" +
i +
" ID=" +
objIdHex(e.objectId) +
" " +
label +
" model=" +
grpModelLabel(e.has3DModel) +
" clip=" +
e.nearClip +
"/" +
e.farClip +
" col=" +
grpCollisionLabel(e.collisionType) +
" size=" +
e.width +
"×" +
e.height +
"×" +
e.depth
);
}
return lines.join("\n");
}
if (t.kind === "kart_appear") {
lines.push(
"kart_appear.ktbl — " + t.kartCount + " karts × " + t.courseCount + " columns (NKKT)",
"Values 0–4 = appearance/unlock state per kart per column",
""
);
var hdr = "kart\\col";
for (var c = 0; c < t.courseCount; c++) hdr += "\t" + c;
lines.push(hdr);
for (var k = 0; k < t.kartCount; k++) {
var row = k + "";
for (var c2 = 0; c2 < t.courseCount; c2++) row += "\t" + t.appearAt(k, c2);
lines.push(row);
}
return lines.join("\n");
}
if (t.kind === "mission") {
lines.push(
"missionTable.mtbl — " + t.missionRows + "×" + t.missionCols + " grid (NKMT)",
"Cell values = mission level indices",
""
);
for (var r = 0; r < t.missionRows; r++) {
var mrow = "row " + r + ":";
for (var mc = 0; mc < t.missionCols; mc++) mrow += " " + t.missionAt(r, mc);
lines.push(mrow);
}
return lines.join("\n");
}
if (t.kind === "emblem") {
lines.push("emblem table — " + t.emblemCount + " entries (8 bytes each)", "");
for (var ei = 0; ei < t.emblems.length; ei++) {
var em = t.emblems[ei];
lines.push("#" + ei + " index=" + em.index + " size=" + em.width + "×" + em.height + " flags=" + em.flags);
}
return lines.join("\n");
}
lines.push("Unknown .tbl layout — showing hex dump only.");
return lines.join("\n");
}
function loadTBL(path, el) {
try {
var buf = readROMFile(path);
var t = new tbl(buf, path.substring(path.lastIndexOf("/") + 1));
showTextView();
document.getElementById("binSummary").textContent = formatTblSummary(t, path);
document.getElementById("binHex").textContent = t.kind === "unknown" ? formatHexDump(new Uint8Array(buf), 65536) : "";
setSel(el);
setStatus(path + " (" + t.kind + ", " + buf.byteLength + " bytes)");
} catch (err) {
console.error(err);
setStatus("Load error: " + (err && err.message ? err.message : err));