-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkrt.html
More file actions
621 lines (570 loc) · 27.5 KB
/
krt.html
File metadata and controls
621 lines (570 loc) · 27.5 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>KRT Web — Mario Kart Wii RKGT Editor</title>
<style>
:root {
--bg: #0f1115;
--panel: #151923;
--muted: #7f8ca3;
--text: #e6e9ef;
--accent: #6ea8fe;
--accent-2: #9aedfe;
--ok: #2ecc71;
--warn: #f39c12;
--err: #e74c3c;
--border: #232a36;
--shadow: 0 6px 20px rgba(0,0,0,.25);
--radius: 16px;
--radius-sm: 10px;
}
html, body { height: 100%; }
body {
margin: 0; font-family: ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, "Helvetica Neue", Arial, "Noto Sans", "Apple Color Emoji", "Segoe UI Emoji";
background: radial-gradient(1200px 800px at 20% -10%, #1a2030, var(--bg));
color: var(--text);
}
header {
display: grid; gap: 12px; padding: 18px; border-bottom: 1px solid var(--border);
background: linear-gradient(180deg, rgba(255,255,255,.02), rgba(255,255,255,0));
position: sticky; top: 0; z-index: 10; backdrop-filter: blur(6px);
}
.title { display:flex; align-items: center; gap: 12px; }
.title h1 { font-size: 20px; margin: 0; letter-spacing: .3px; }
.tag { font-size: 12px; color: var(--muted); border:1px solid var(--border); padding:2px 8px; border-radius:999px; }
.toolbar { display:flex; flex-wrap:wrap; gap: 10px; align-items: center; }
.toolbar .group { background: var(--panel); border:1px solid var(--border); border-radius: var(--radius-sm); padding: 8px; display:flex; gap:8px; align-items: center; box-shadow: var(--shadow); }
.toolbar label { font-size: 12px; color: var(--muted); }
input[type="number"], input[type="text"], select, button {
background: #0f1320; color: var(--text); border:1px solid var(--border); border-radius: 10px; padding:8px 10px; font-size: 13px;
}
input[type="number"]:focus, input[type="text"]:focus, select:focus { outline: 2px solid var(--accent); border-color: transparent; }
button { cursor: pointer; transition: transform .05s ease; }
button:hover { transform: translateY(-1px); }
button.primary { background: linear-gradient(180deg, #1f60ff, #174bd6); border: none; }
button.ghost { background: transparent; }
button.ok { background: #1e7a45; border: none; }
button.warn { background: #9b6b11; border:none; }
button.error { background: #8b2b20; border:none; }
.hint { color: var(--muted); font-size: 12px; }
main { padding: 18px; display: grid; gap: 16px; }
.grid { display:grid; grid-template-columns: 1fr; gap: 16px; }
@media (min-width: 1100px) { .grid { grid-template-columns: 2fr 1fr; } }
.card { background: var(--panel); border:1px solid var(--border); border-radius: var(--radius); box-shadow: var(--shadow); overflow: hidden; }
.card h2 { font-size: 15px; letter-spacing: .4px; margin: 0; padding: 12px 14px; border-bottom:1px solid var(--border); background: linear-gradient(180deg, rgba(255,255,255,.02), rgba(255,255,255,0)); }
.card .body { padding: 12px; }
table { width: 100%; border-collapse: collapse; }
th, td { border-bottom: 1px solid var(--border); padding: 8px; text-align: left; font-size: 13px; }
thead th { position: sticky; top: 0; background: #121725; z-index: 1; }
tbody tr:hover { background: rgba(255,255,255,.02); }
.muted { color: var(--muted); }
.pill { padding: 2px 8px; border-radius: 999px; background: #111624; border: 1px solid var(--border); font-size: 12px; }
.warn-text { color: var(--warn); }
.ok-text { color: var(--ok); }
.err-text { color: var(--err); }
.warn-list { margin: 6px 0 0; padding-left: 18px; color: var(--warn); font-size: 12px; }
.warn-list li { margin: 2px 0; }
.footer { color: var(--muted); font-size: 12px; padding: 10px 0 16px; }
.k { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace; }
.sr { position: absolute; left: -9999px; }
.row-actions { display:flex; gap: 6px; align-items: center; }
.sticky-actions { position: sticky; bottom: 0; background: #0e1320d0; backdrop-filter: blur(8px); border-top:1px solid var(--border); padding: 8px; display:flex; justify-content: space-between; align-items: center; }
</style>
</head>
<body>
<header>
<div class="title">
<div class="tag">Single‑file web tool</div>
<h1>KRT Web — Mario Kart Wii RKGT Editor</h1>
</div>
<div class="toolbar">
<div class="group">
<label for="fileInput">Open .krt</label>
<input id="fileInput" type="file" accept=".krt,application/octet-stream" />
<button id="btnDemo" title="Start with an empty 32‑entry file">New 32‑entry</button>
</div>
<div class="group">
<label>Display</label>
<select id="displayMode">
<option value="frames">Frames</option>
<option value="ms">mm:ss.mmm</option>
</select>
<label>FPS</label>
<select id="fps">
<option value="59.952" selected>59.952 (Wiki)</option>
<option value="60">60</option>
<option value="59.94">59.94</option>
<option value="50">50</option>
</select>
</div>
<div class="group">
<label>Order</label>
<select id="orderMode">
<option value="krt" selected>Special Slot (KRT)</option>
<option value="vanilla">Vanilla (ODS)</option>
</select>
</div>
<div class="group">
<label>Download</label>
<button id="btnSave" class="primary">Export .krt</button>
<button id="btnSaveJson">Export JSON</button>
<button id="btnSaveCsv">Export CSV</button>
</div>
<div class="group">
<label>Import</label>
<button id="btnImportJson">Import JSON</button>
<button id="btnImportCsv">Import CSV</button>
<input id="jsonInput" type="file" accept=".json" style="display:none" aria-hidden="true" />
<input id="csvInput" type="file" accept=".csv,text/csv" style="display:none" aria-hidden="true" />
</div>
</div>
<div class="hint">Magic must be <span class="k">RKGT</span>. Values are Big‑Endian. Each entry = 3×UInt16 (50cc, 100cc, 150/Mirror) + 2 bytes padding.</div>
</header>
<main>
<div class="grid">
<section class="card" id="fileCard">
<h2>Header</h2>
<div class="body" style="display:grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 12px;">
<div>
<label>Magic</label>
<input id="magic" type="text" value="RKGT" maxlength="4" class="k" readonly aria-readonly="true" title="Locked by spec (RKGT)" />
<div class="hint">Locked by spec (RKGT).</div>
</div>
<div>
<label>Rank time delta factor (UInt32)</label>
<input id="factor" type="number" min="0" max="4294967295" step="1" />
<div class="hint">Unused by the game (hardcoded to 1000), but preserved.</div>
</div>
<div>
<label>Header size (UInt16)</label>
<input id="headerSize" type="number" min="12" max="65535" step="1" readonly aria-readonly="true" title="Locked by spec (12 / 0x0C)" />
<div class="hint">Locked by spec (12 / 0x0C).</div>
</div>
<div>
<label>Entries</label>
<input id="numEntries" type="number" min="0" max="4096" step="1" readonly aria-readonly="true" title="Read-only; auto-updated to table size" />
<div class="hint">Read‑only; auto‑updated to match the table.</div>
</div>
</div>
</section>
<section class="card">
<h2>Inspector</h2>
<div class="body" id="inspector">
<div class="hint">Select a cell to see friendly time formatting, keyboard shortcuts, and validation.
<ul>
<li>Arrows / Enter / Tab to navigate.</li>
<li><span class="k">Ctrl/⌘ + D</span> duplicate row, <span class="k">Ctrl/⌘ + ⌫</span> delete row.</li>
<li>Switch “Display” to edit in <em>mm:ss.mmm</em> — we’ll convert to frames using FPS.</li>
</ul></div>
<div id="inspectorInfo" class="pill">No selection</div>
</div>
</section>
</div>
<section class="card">
<h2>Entries</h2>
<div class="body">
<div style="overflow:auto; max-height: 56vh; border:1px solid var(--border); border-radius: var(--radius);">
<table id="tbl">
<thead>
<tr>
<th>#</th>
<th>Track (hint)</th>
<th>50cc</th>
<th>100cc</th>
<th>150/Mirror</th>
<th class="muted">≈ mm:ss.mmm (150)</th>
<th></th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
<div class="sticky-actions">
<div class="hint" id="status">Ready.</div>
<ul id="warnList" class="warn-list" style="display:none"></ul>
<div class="row-actions">
<button id="btnAddRow">Add row</button>
<button id="btnReset" class="ghost">Reset changes</button>
</div>
</div>
</div>
</section>
<section class="footer">
<div><strong>Notes.</strong> This tool reads & writes Big‑Endian KRT (RKGT) files used by Mario Kart Wii for GP rank timing. It preserves header fields and re‑writes padding as 0. Made by ChatGPT 5 Thinking.</div>
</section>
</main>
<template id="rowTemplate">
<tr>
<td class="k idx"></td>
<td class="muted track"></td>
<td><input class="t50" type="number" min="0" max="65535" inputmode="numeric"></td>
<td><input class="t100" type="number" min="0" max="65535" inputmode="numeric"></td>
<td><input class="t150" type="number" min="0" max="65535" inputmode="numeric"></td>
<td class="muted approx"></td>
<td class="row-actions">
<button class="dup" title="Duplicate row">⧉</button>
<button class="del" title="Delete row">✕</button>
</td>
</tr>
</template>
<script>
'use strict';
// —— Utilities ——
const $ = function(sel, el){ return (el||document).querySelector(sel); };
const $$ = function(sel, el){ return Array.prototype.slice.call((el||document).querySelectorAll(sel)); };
const clamp = function(v, lo, hi){ return Math.min(Math.max(v, lo), hi); };
const beU16 = function(dv, off){ return dv.getUint16(off, false); };
const beU32 = function(dv, off){ return dv.getUint32(off, false); };
const setBeU16 = function(dv, off, v){ dv.setUint16(off, v>>>0, false); };
const setBeU32 = function(dv, off, v){ dv.setUint32(off, v>>>0, false); };
const download = function(blob, name){
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url; a.download = name; document.body.appendChild(a); a.click();
setTimeout(function(){ URL.revokeObjectURL(url); a.remove(); }, 0);
};
// Track names in KRT slot order
const TRACK_NAMES = [
'Mario Circuit','Moo Moo Meadows','Mushroom Gorge','Grumble Volcano',
"Toad's Factory","Coconut Mall","DK Summit","Wario's Gold Mine",
'Luigi Circuit','Daisy Circuit','Moonview Highway','Maple Treeway',
"Bowser's Castle","Rainbow Road","Dry Dry Ruins","Koopa Cape",
'GCN Peach Beach','GCN Mario Circuit','GCN Waluigi Stadium','GCN DK Mountain',
'DS Yoshi Falls','DS Desert Hills','DS Peach Gardens','DS Delfino Square',
'SNES Mario Circuit 3','SNES Ghost Valley 2','N64 Mario Raceway','N64 Sherbet Land',
"N64 Bowser's Castle","N64 DK's Jungle Parkway","GBA Bowser's Castle 3","GBA Shy Guy Beach"
];
// Vanilla (ODS) visual order mapped to KRT slot indices
const VANILLA_ORDER = [
8, 1, 2, 4, 0, 5, 6, 7,
9, 15, 11, 3, 14, 10, 12, 13,
16, 20, 25, 26, 27, 31, 23, 18,
21, 30, 29, 17, 24, 22, 19, 28
];
// —— App State ——
const state = {
original: null,
header: { magic:'RKGT', factor:1000, headerSize:12, numEntries:0 },
entries: []
};
// —— Parsing / Building ——
function parseKRT(buf){
const dv = new DataView(buf);
if (dv.byteLength < 12) throw new Error('File too small');
const magic = new TextDecoder().decode(new Uint8Array(buf,0,4));
const factor = beU32(dv,4);
const numEntriesDecl = beU16(dv,8);
const headerSizeDecl = beU16(dv,10);
const expected = headerSizeDecl + numEntriesDecl * 8;
const actual = dv.byteLength;
var inferred = numEntriesDecl;
if (actual !== expected){
inferred = Math.max(0, Math.floor((actual - headerSizeDecl)/8));
console.warn('Size mismatch: expected', expected, 'actual', actual, '- using inferred entries =', inferred);
}
const entries = [];
for (var i=0;i<inferred;i++){
const off = headerSizeDecl + i*8;
if (off + 8 > dv.byteLength) break;
const t50 = beU16(dv, off);
const t100 = beU16(dv, off+2);
const t150 = beU16(dv, off+4);
entries.push({ t50:t50, t100:t100, t150:t150 });
}
return {
header: { magic: magic, factor: factor, headerSize: headerSizeDecl, numEntries: numEntriesDecl },
meta: { inferredNumEntries: inferred, fileSize: actual, expectedSize: expected },
entries: entries
};
}
function buildKRT(data){
const headerSize = (data.header.headerSize|0) || 12;
const n = data.entries.length|0;
const buf = new ArrayBuffer(headerSize + n*8);
const dv = new DataView(buf);
// header
const magicBytes = new TextEncoder().encode((data.header.magic || 'RKGT').slice(0,4).padEnd(4,'\0'));
new Uint8Array(buf,0,4).set(magicBytes);
setBeU32(dv,4, data.header.factor>>>0);
setBeU16(dv,8, n);
setBeU16(dv,10, headerSize);
// entries
var off = headerSize;
for (var i=0;i<n;i++){
const e = data.entries[i];
setBeU16(dv, off+0, clamp(e.t50|0,0,0xFFFF));
setBeU16(dv, off+2, clamp(e.t100|0,0,0xFFFF));
setBeU16(dv, off+4, clamp(e.t150|0,0,0xFFFF));
dv.setUint8(off+6,0); dv.setUint8(off+7,0);
off += 8;
}
return buf;
}
// —— Formatting ——
function framesToMmssmmm(frames, fps){
var msVal = frames * 1000 / fps;
var totalMs = (Math.abs(fps - 59.952) < 1e-9) ? Math.floor(msVal) : Math.round(msVal);
var m = Math.floor(totalMs / 60000);
var s = Math.floor((totalMs % 60000) / 1000);
var ms = totalMs % 1000; // 0..999
return m + ':' + String(s).padStart(2,'0') + '.' + String(ms).padStart(3,'0');
}
function mmssmmmToFrames(text, fps){
const t = (text || '').trim();
const intRe = new RegExp('^[0-9]+$');
const decRe = new RegExp('^[0-9]+(?:\.[0-9]+)?$');
const mmssRe = new RegExp('^([0-9]+):([0-9]{1,2})(?:\.([0-9]{1,3}))?$');
if (intRe.test(t)) return parseInt(t,10);
if (decRe.test(t)) return Math.round(parseFloat(t)*fps);
const mRes = t.match(mmssRe);
if (!mRes) throw new Error('Invalid time; expected m:ss.mmm');
const minutes = parseInt(mRes[1],10);
const seconds = parseInt(mRes[2],10);
const msStr = mRes[3] || '0';
if (seconds < 0 || seconds >= 60) throw new Error('Seconds must be 0..59');
if (msStr.length > 3) throw new Error('Milliseconds must be 0..999');
const millis = parseInt(msStr.padEnd(3,'0'),10);
const totalMs = minutes*60000 + seconds*1000 + millis;
return Math.round((totalMs/1000)*fps);
}
// —— Render Table ——
function render(){
// Header fields
$('#magic').value = state.header.magic;
$('#factor').value = state.header.factor;
$('#headerSize').value = state.header.headerSize;
$('#numEntries').value = state.entries.length;
const tbody = $('#tbl tbody');
tbody.innerHTML = '';
const t = document.getElementById('rowTemplate');
const fps = parseFloat($('#fps').value);
const showMs = $('#displayMode').value === 'ms';
const order = ($('#orderMode') && $('#orderMode').value) || 'krt';
const indices = (order === 'vanilla') ? VANILLA_ORDER.slice(0, state.entries.length)
: state.entries.map(function(_, idx){ return idx; });
indices.forEach(function(i, j){
const e = state.entries[i];
const row = t.content.firstElementChild.cloneNode(true);
row.dataset.index = String(i);
$('.idx', row).textContent = i.toString().padStart(2,'0'); // authentic slot id
$('.track', row).textContent = TRACK_NAMES[i] || '';
const in50 = $('.t50', row), in100 = $('.t100', row), in150 = $('.t150', row);
if (showMs){
in50.type = in100.type = in150.type = 'text';
in50.value = framesToMmssmmm(e.t50, fps);
in100.value = framesToMmssmmm(e.t100, fps);
in150.value = framesToMmssmmm(e.t150, fps);
} else {
in50.type = in100.type = in150.type = 'number';
in50.value = e.t50; in100.value = e.t100; in150.value = e.t150;
}
$('.approx', row).textContent = framesToMmssmmm(e.t150, fps);
const updateFromInputs = function(){
try{
if (showMs){
e.t50 = clamp(mmssmmmToFrames(in50.value, fps), 0, 0xFFFF);
e.t100 = clamp(mmssmmmToFrames(in100.value, fps), 0, 0xFFFF);
e.t150 = clamp(mmssmmmToFrames(in150.value, fps), 0, 0xFFFF);
} else {
e.t50 = clamp(parseInt(in50.value||'0',10), 0, 0xFFFF);
e.t100 = clamp(parseInt(in100.value||'0',10), 0, 0xFFFF);
e.t150 = clamp(parseInt(in150.value||'0',10), 0, 0xFFFF);
}
$('.approx', row).textContent = framesToMmssmmm(e.t150, fps);
setStatus('Edited row ' + j + ' (slot ' + i + ')', 'ok');
} catch(err){
setStatus('Row ' + j + ' (slot ' + i + '): ' + err.message, 'err');
}
};
in50.addEventListener('change', updateFromInputs);
in100.addEventListener('change', updateFromInputs);
in150.addEventListener('change', updateFromInputs);
$('.dup', row).addEventListener('click', function(){ state.entries.splice(i+1,0, { t50:e.t50, t100:e.t100, t150:e.t150 }); syncHeader(); render(); });
$('.del', row).addEventListener('click', function(){ state.entries.splice(i,1); syncHeader(); render(); });
$$('input', row).forEach(function(inp){
inp.addEventListener('focus', function(){ inspectorShow(i, inp.className); });
inp.addEventListener('blur', function(){ inspectorClear(); });
});
tbody.appendChild(row);
});
}
function inspectorShow(idx, field){
const e = state.entries[idx];
const fps = parseFloat($('#fps').value);
const lines = [];
lines.push('<div class="pill">Row ' + idx + ' - ' + (TRACK_NAMES[idx]||'Track') + '</div>');
lines.push('<div>50cc: <span class="k">' + e.t50 + '</span> frames ≈ ' + framesToMmssmmm(e.t50,fps) + '</div>');
lines.push('<div>100cc: <span class="k">' + e.t100 + '</span> frames ≈ ' + framesToMmssmmm(e.t100,fps) + '</div>');
lines.push('<div>150/Mirror: <span class="k">' + e.t150 + '</span> frames ≈ ' + framesToMmssmmm(e.t150,fps) + '</div>');
lines.push('<div class="muted">Editing: <span class="k">' + field + '</span></div>');
$('#inspectorInfo').innerHTML = lines.join('');
}
function inspectorClear(){ $('#inspectorInfo').textContent = 'No selection'; }
// —— Status & Warnings ——
function setStatus(text, kind){
if (kind===void 0) kind='info';
const el = $('#status');
el.textContent = text;
el.classList.remove('warn-text','ok-text','err-text');
if (kind==='warn') el.classList.add('warn-text');
else if (kind==='ok') el.classList.add('ok-text');
else if (kind==='err') el.classList.add('err-text');
}
function clearWarnings(){
const ul = $('#warnList');
if (ul){ ul.innerHTML=''; ul.style.display='none'; }
}
function addWarning(msg){
const ul = $('#warnList');
if (!ul) return;
const li = document.createElement('li');
li.textContent = String(msg);
ul.appendChild(li);
ul.style.display = '';
}
// —— Synchronize header ↔ data ——
function syncHeader(){
state.header.magic = 'RKGT';
const magicEl = $('#magic'); if (magicEl) magicEl.value = 'RKGT';
state.header.factor = clamp(parseInt($('#factor').value||'1000',10), 0, 0xFFFFFFFF);
state.header.headerSize = 12; const hsEl = $('#headerSize'); if (hsEl) hsEl.value = 12;
$('#numEntries').value = state.entries.length;
}
// —— File I/O Handlers ——
$('#fileInput').addEventListener('change', async function(ev){
const file = ev.target.files[0]; if (!file) return;
const buf = await file.arrayBuffer();
try{
const parsed = parseKRT(buf);
state.header = parsed.header; state.entries = parsed.entries;
state.original = { header: { magic:parsed.header.magic, factor:parsed.header.factor, headerSize:parsed.header.headerSize, numEntries:parsed.header.numEntries }, entries: parsed.entries.map(function(x){ return { t50:x.t50, t100:x.t100, t150:x.t150 }; }) };
render();
validateBasic(parsed, file.name);
const hasWarn = ($('#warnList') && $('#warnList').children.length > 0);
setStatus('Loaded ' + file.name + ' — ' + state.entries.length + ' entries', hasWarn ? 'warn' : 'ok');
} catch(err){ setStatus('Failed to load: ' + err.message, 'err'); }
});
$('#btnDemo').addEventListener('click', function(){
state.header = { magic:'RKGT', factor:1000, headerSize:12, numEntries:32 };
state.entries = Array.from({length:32}, function(){ return { t50:0, t100:0, t150:0 }; });
state.original = { header: { magic:'RKGT', factor:1000, headerSize:12, numEntries:32 }, entries: state.entries.map(function(x){ return { t50:x.t50, t100:x.t100, t150:x.t150 }; }) };
render(); setStatus('Created new 32-entry file');
});
$('#btnReset').addEventListener('click', function(){
if (!state.original) { setStatus('Nothing to reset','warn'); return; }
state.header = { magic:state.original.header.magic, factor:state.original.header.factor, headerSize:state.original.header.headerSize, numEntries:state.original.header.numEntries };
state.entries = state.original.entries.map(function(x){ return { t50:x.t50, t100:x.t100, t150:x.t150 }; });
render(); setStatus('Reset to last loaded file');
});
$('#btnAddRow').addEventListener('click', function(){
state.entries.push({ t50:0, t100:0, t150:0 });
$('#numEntries').value = state.entries.length; render();
});
$('#displayMode').addEventListener('change', render);
$('#orderMode').addEventListener('change', render);
$('#fps').addEventListener('change', render);
$('#factor').addEventListener('change', function(){ syncHeader(); setStatus('Header updated','ok'); });
$('#btnImportJson').addEventListener('click', function(){ $('#jsonInput').click(); });
$('#btnImportCsv').addEventListener('click', function(){ $('#csvInput').click(); });
$('#btnSave').addEventListener('click', function(){
syncHeader();
const buf = buildKRT(state);
const blob = new Blob([buf], { type:'application/octet-stream' });
download(blob, 'ranktimeGP.krt'); setStatus('Exported .krt','ok');
});
$('#btnSaveJson').addEventListener('click', function(){
const out = JSON.stringify(state, null, 2);
const blob = new Blob([out], { type:'application/json' });
download(blob, 'ranktimeGP.json');
});
$('#btnSaveCsv').addEventListener('click', function(){
const rows = [ ['index','track','t50','t100','t150'] ];
state.entries.forEach(function(e,i){ rows.push([i, TRACK_NAMES[i]||'', e.t50, e.t100, e.t150]); });
const csv = rows.map(function(r){
return r.map(function(x){ return String(x).includes(',') ? ('"' + String(x).replace(/\"/g,'\"\"') + '"') : x; }).join(',');
}).join('\n');
download(new Blob([csv], {type:'text/csv'}), 'ranktimeGP.csv');
});
$('#jsonInput').addEventListener('change', async function(ev){
const file = ev.target.files[0]; if (!file) return;
try{
const text = await file.text();
const obj = JSON.parse(text);
if (!obj || !obj.header || !Array.isArray(obj.entries)) throw new Error('Invalid JSON');
state.header = { magic:obj.header.magic, factor:obj.header.factor, headerSize:obj.header.headerSize, numEntries:obj.header.numEntries };
state.entries = obj.entries.map(function(x){ return { t50:x.t50|0, t100:x.t100|0, t150:x.t150|0 }; });
state.original = { header: { magic:state.header.magic, factor:state.header.factor, headerSize:state.header.headerSize, numEntries:state.header.numEntries }, entries: state.entries.map(function(x){ return { t50:x.t50, t100:x.t100, t150:x.t150 }; }) };
render(); setStatus('Imported JSON','ok');
} catch(err){ setStatus('JSON import failed: ' + err.message, 'err'); }
});
$('#csvInput').addEventListener('change', async function(ev){
const file = ev.target.files[0]; if (!file) return;
try{
const text = await file.text();
const lines = text.split(/\r?\n/).filter(Boolean);
const out = [];
for (var i=1;i<lines.length;i++){
const cols = parseCsvLine(lines[i]);
const t50 = parseInt(cols[2]||'0',10), t100 = parseInt(cols[3]||'0',10), t150 = parseInt(cols[4]||'0',10);
out.push({ t50: clamp(t50,0,0xFFFF), t100: clamp(t100,0,0xFFFF), t150: clamp(t150,0,0xFFFF) });
}
state.entries = out; syncHeader(); render(); setStatus('Imported CSV (' + out.length + ' rows)','ok');
} catch(err){ setStatus('CSV import failed: ' + err.message, 'err'); }
});
function parseCsvLine(line){
const res = []; var cur = ''; var inQ = false;
for (var i=0;i<line.length;i++){
const ch = line[i];
if (inQ){
if (ch==='"' && line[i+1]==='"'){ cur+='"'; i++; }
else if (ch==='"'){ inQ=false; }
else cur+=ch;
} else {
if (ch===','){ res.push(cur); cur=''; }
else if (ch==='"'){ inQ=true; }
else cur+=ch;
}
}
res.push(cur); return res;
}
function validateBasic(parsed, fileName){
clearWarnings();
if (parsed.header.magic !== 'RKGT') addWarning('Magic is not RKGT (got ' + parsed.header.magic + ')');
if (parsed.header.headerSize !== 12) addWarning('Header size is ' + parsed.header.headerSize + ' (usually 12)');
if (parsed.meta){
if (parsed.meta.fileSize !== parsed.meta.expectedSize){
addWarning('Size/entry count mismatch: file ' + parsed.meta.fileSize + ' bytes vs expected ' + parsed.meta.expectedSize + ' (headerSize=' + parsed.header.headerSize + ', numEntries=' + parsed.header.numEntries + '). Inferred entries=' + parsed.meta.inferredNumEntries + ', parsed=' + parsed.entries.length + '.');
}
} else {
if ((12 + parsed.entries.length*8) !== (parsed.header.headerSize + parsed.header.numEntries*8)){
addWarning('Size/entry count mismatch (legacy check).');
}
}
}
// —— Keyboard shortcuts ——
window.addEventListener('keydown', function(ev){
if ((ev.ctrlKey || ev.metaKey) && ev.key.toLowerCase()==='d'){
ev.preventDefault();
const row = document.activeElement && document.activeElement.closest('tr');
if (!row) return; const i = parseInt(row.dataset.index, 10);
const e = state.entries[i]; if (!e) return;
state.entries.splice(i+1,0,{ t50:e.t50, t100:e.t100, t150:e.t150 }); render();
}
if ((ev.ctrlKey || ev.metaKey) && (ev.key==='Backspace' || ev.key==='Delete')){
ev.preventDefault();
const row = document.activeElement && document.activeElement.closest('tr');
if (!row) return; const i = parseInt(row.dataset.index, 10);
state.entries.splice(i,1); render();
}
});
// —— Init ——
(function(){
state.header = { magic:'RKGT', factor:1000, headerSize:12, numEntries:0 };
state.entries = [];
render();
})();
</script>
</body>
</html>