-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathserver.js
More file actions
1371 lines (1233 loc) · 56.3 KB
/
Copy pathserver.js
File metadata and controls
1371 lines (1233 loc) · 56.3 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
/**
* ReSplat Local Backend Server
*
* Provides decimate/merge/convert/export APIs for large Gaussian splat files
* that exceed browser memory limits (~4GB V8 heap).
*
* Usage: node server.js [port]
* Default port: 3266
*/
const express = require('express');
const multer = require('multer');
const cors = require('cors');
const path = require('path');
const fs = require('fs');
const os = require('os');
const { Worker } = require('worker_threads');
// C++ native addon — PLY parse + compressed-ply write acceleration
let native;
try { native = require('./native'); } catch (_) { native = null; }
if (native) console.log('[native] C++ ply_reader addon loaded');
const PORT = parseInt(process.env.PORT || process.argv[2] || '3266', 10);
const DIST_DIR = path.join(__dirname, 'dist');
// ---------------------------------------------------------------------------
// Response helpers
// ---------------------------------------------------------------------------
/** Send result inline (for upload endpoints — file may be large so chunk it) */
function sendResult(res, { resultData, outFilename, count }) {
res.setHeader('Content-Type', 'application/octet-stream');
res.setHeader('Content-Disposition', `attachment; filename="${outFilename}"`);
res.setHeader('X-Splat-Count', String(count));
if (typeof resultData === 'string') {
// Native path: data is a file on disk (may exceed 2GB)
const stream = fs.createReadStream(resultData);
stream.pipe(res);
stream.on('end', () => cleanup(resultData));
} else {
// JS fallback: in-memory Uint8Array
const CHUNK = 256 * 1024 * 1024;
for (let offset = 0; offset < resultData.length; offset += CHUNK) {
res.write(Buffer.from(resultData.subarray(offset, offset + CHUNK)));
}
res.end();
}
}
/** Write result to temp/ and return URL (for path endpoints — avoids 4.5GB HTTP body) */
function sendPathResult(res, { resultData, outFilename, count }) {
// Unique temp filename to avoid collisions
const ext = path.extname(outFilename);
const baseName = path.basename(outFilename, ext);
const tempName = `${baseName}_${Date.now()}${ext}`;
const tempPath = path.join(TEMP_DIR, tempName);
if (typeof resultData === 'string') {
// Native path: rename the already-written file directly (avoids >2GB readFileSync crash)
fs.renameSync(resultData, tempPath);
} else {
// JS fallback: write in-memory Uint8Array to disk in chunks
const fd = fs.openSync(tempPath, 'w');
try {
const CHUNK = 256 * 1024 * 1024;
for (let offset = 0; offset < resultData.length; offset += CHUNK) {
const slice = Buffer.from(resultData.subarray(offset, offset + CHUNK));
fs.writeSync(fd, slice, 0, slice.length, offset);
}
} finally {
fs.closeSync(fd);
}
}
// Schedule cleanup after 10 minutes (browser should load it by then)
setTimeout(() => cleanup(tempPath), 10 * 60 * 1000);
const url = `http://localhost:${PORT}/temp/${encodeURIComponent(tempName)}`;
console.log(` → Serving via URL: ${url}`);
res.json({ url, filename: outFilename, count });
}
// ---------------------------------------------------------------------------
// Dynamic import for ESM-only @playcanvas/splat-transform
// ---------------------------------------------------------------------------
let splatTransform = null;
async function loadSplatTransform() {
if (splatTransform) return splatTransform;
splatTransform = await import('@playcanvas/splat-transform');
return splatTransform;
}
// ---------------------------------------------------------------------------
// NodeFileReadSystem — chunked file reader for files > 2 GiB
//
// fs.readFileSync has a ~2 GiB Buffer limit. This custom ReadFileSystem
// reads from disk in chunks via fs.read(), supporting files of any size.
// ---------------------------------------------------------------------------
class NodeFileReadStream {
constructor(fd, size, start, end) {
this._fd = fd;
this._size = size;
this._start = start || 0;
this._end = end || size;
this._pos = this._start;
this.bytesRead = 0;
this.expectedSize = this._end - this._start;
}
async pull(target) {
const maxBytes = Math.min(target.length, this._end - this._pos);
if (maxBytes <= 0) return 0;
return new Promise((resolve, reject) => {
fs.read(this._fd, target, 0, maxBytes, this._pos, (err, bytesRead) => {
if (err) return reject(err);
this._pos += bytesRead;
this.bytesRead += bytesRead;
resolve(bytesRead);
});
});
}
async readAll() {
const buf = Buffer.allocUnsafe(this.expectedSize);
let offset = 0;
let bytesRead = 0;
while ((bytesRead = await this.pull(buf.subarray(offset))) > 0) {
offset += bytesRead;
}
return new Uint8Array(buf.buffer, buf.byteOffset, offset);
}
close() {
// fd is managed by the source
}
}
class NodeFileReadSource {
constructor(filePath, fd, size) {
this._filePath = filePath;
this._fd = fd;
this.size = size;
this.seekable = true;
}
read(start, end) {
return new NodeFileReadStream(this._fd, this.size, start, end);
}
close() {
if (this._fd !== null) {
try { fs.closeSync(this._fd); } catch (_) { /* ignore */ }
this._fd = null;
}
}
}
class NodeFileReadFileSystem {
constructor(filePath, originalName) {
this._filePath = filePath;
this._originalName = originalName;
this._fd = null; // lazy-open, shared
this._source = null; // singleton source
this._closed = false;
}
async createSource(filename, _progress) {
if (this._closed) {
throw new Error('File system already closed');
}
// Single-file upload: only the original filename is available.
// SOG bundles reference webp by path; for single-file uploads,
// return the same source for any request (reader handles bundle internally).
if (this._source) return this._source;
const fd = fs.openSync(this._filePath, 'r');
const stat = fs.fstatSync(fd);
this._fd = fd;
this._source = new NodeFileReadSource(this._filePath, fd, stat.size);
return this._source;
}
close() {
this._closed = true;
if (this._source) {
this._source.close();
this._source = null;
}
this._fd = null;
}
}
// Directory-backed seekable file system for container formats (.lcc/.lcc2):
// the reader resolves sibling payload files (index.bin/data.bin/shcoef.bin for
// LCC, data/3dgs/*.sog for LCC2) against the same root directory.
class NodeDirReadFileSystem {
constructor(rootDir) {
this._root = rootDir;
}
async createSource(filename, _progress) {
const filePath = path.join(this._root, filename);
const fd = fs.openSync(filePath, 'r');
const stat = fs.fstatSync(fd);
return new NodeFileReadSource(filePath, fd, stat.size);
}
close() {
// Sources close their own fds
}
}
// ---------------------------------------------------------------------------
// Express setup
// ---------------------------------------------------------------------------
const app = express();
// CORS: allow localhost (browser/dev) and app:// (Electron with app://
// privileged protocol — see electron/main.cjs registerAppProtocol). Without
// app:// here, BackendClient's HTTP requests from the renderer would be
// blocked: Chromium allows file://→http://localhost without CORS, but app://
// is a custom scheme subject to normal CORS enforcement.
app.use(cors({
origin: (origin, callback) => {
if (!origin || // same-origin / curl / no Origin header
/^https?:\/\/localhost(:\d+)?$/.test(origin) || // browser dev mode
/^app:\/\//.test(origin)) { // Electron app:// protocol
callback(null, true);
} else {
callback(null, false);
}
},
credentials: true
}));
// Increase body/url limits for large file upload proxy
app.use(express.json({ limit: '100mb' }));
app.use(express.urlencoded({ extended: true, limit: '100mb' }));
// Static file serving: dist/ directory
app.use(express.static(DIST_DIR, {
setHeaders: (res, filePath) => {
// Ensure .wasm files get the correct MIME type for WebAssembly
if (filePath.endsWith('.wasm')) {
res.setHeader('Content-Type', 'application/wasm');
}
}
}));
// In packaged Electron, extraResources copies static/ to resourcesPath/static/
// (outside asar). Serve it as a fallback for /static/* requests so LUT files
// and other assets remain accessible even if asar reading has issues, and
// so users can drop new LUT PNGs into resourcesPath/static/luts/ post-install.
if (process.resourcesPath) {
app.use('/static', express.static(path.join(process.resourcesPath, 'static'), {
fallthrough: true
}));
}
// temp directory for path-based conversion output
// Use os.tmpdir() instead of __dirname to avoid ENOTDIR when packaged in asar
const TEMP_DIR = path.join(os.tmpdir(), 'resplat-temp');
if (!fs.existsSync(TEMP_DIR)) fs.mkdirSync(TEMP_DIR, { recursive: true });
app.use('/temp', express.static(TEMP_DIR, { maxAge: 0 }));
// LOD edit pages are generated by server/lod-edit.mjs in their own temporary
// directory so large page files do not share the general conversion cleanup
// namespace. Keep the same public /temp URL for both kinds of output.
const LOD_PAGE_TEMP_DIR = path.join(os.tmpdir(), 'resplat-lod-pages');
if (!fs.existsSync(LOD_PAGE_TEMP_DIR)) fs.mkdirSync(LOD_PAGE_TEMP_DIR, { recursive: true });
app.use('/temp', express.static(LOD_PAGE_TEMP_DIR, { maxAge: 0 }));
// SPA fallback: all non-API, non-file routes → index.html
app.get(/^\/(?!api\/)/, (req, res, next) => {
// Skip if the request looks like a file (has extension) or is an API call
if (path.extname(req.path)) {
return next();
}
res.sendFile(path.join(DIST_DIR, 'index.html'));
});
// ---------------------------------------------------------------------------
// Multer: upload to temp directory
// ---------------------------------------------------------------------------
const upload = multer({
dest: os.tmpdir(),
limits: { fileSize: 20 * 1024 * 1024 * 1024 } // 20 GB max
});
// ---------------------------------------------------------------------------
// API: Health check
// ---------------------------------------------------------------------------
app.get('/api/health', (_req, res) => {
res.json({ ok: true, version: '1.0.4' });
});
// ---------------------------------------------------------------------------
// API: LOD edit pages
//
// This is deliberately selection-driven. The backend never schedules pages
// from camera state; the renderer asks for a page only after a spatial edit
// needs it. The ESM implementation keeps the large source files seekable and
// returns a temporary compressed-PLY page plus its stable source row mapping.
// ---------------------------------------------------------------------------
let lodEditModulePromise = null;
const getLodEditModule = () => {
if (!lodEditModulePromise) {
lodEditModulePromise = import('./server/lod-edit.mjs');
}
return lodEditModulePromise;
};
app.post('/api/lod-edit/open', express.json(), async (req, res) => {
try {
const { filePath, proxyLod } = req.body || {};
if (!filePath || !fs.existsSync(filePath)) {
res.status(400).json({ error: 'Invalid LCC/LCC2 source path' });
return;
}
if (!Number.isInteger(proxyLod) || proxyLod <= 0) {
res.status(400).json({ error: 'proxyLod must be a non-zero LOD index' });
return;
}
const { openLodEditSession } = await getLodEditModule();
res.json(await openLodEditSession({ filePath, proxyLod }));
} catch (error) {
console.error('[lod-edit/open] Error:', error);
res.status(500).json({ error: error.message || 'Failed to open LOD edit source' });
}
});
app.get('/api/lod-edit/page/:sessionId/:pageId', async (req, res) => {
try {
const { loadLodEditPage } = await getLodEditModule();
res.json({
...await loadLodEditPage(req.params.sessionId, req.params.pageId),
baseUrl: `http://localhost:${PORT}`
});
} catch (error) {
console.error('[lod-edit/page] Error:', error);
res.status(500).json({ error: error.message || 'Failed to load LOD edit page' });
}
});
app.post('/api/lod-edit/close', express.json(), async (req, res) => {
try {
const { closeLodEditSession } = await getLodEditModule();
await closeLodEditSession(req.body?.sessionId);
res.json({ ok: true });
} catch (error) {
res.status(500).json({ error: error.message || 'Failed to close LOD edit source' });
}
});
setInterval(() => {
getLodEditModule().then(({ cleanupLodEditSessions }) => cleanupLodEditSessions()).catch(() => {});
}, 5 * 60 * 1000).unref();
// ---------------------------------------------------------------------------
// API: LUT files list
// ---------------------------------------------------------------------------
// LUT files may live in two places depending on dev/packaged mode:
// 1. process.resourcesPath/static/luts — Electron packaged (extraResources,
// copied outside asar for direct filesystem access)
// 2. DIST_DIR/static/luts — dev mode or inside asar
app.get('/api/luts', (_req, res) => {
const candidates = [];
if (process.resourcesPath) {
candidates.push(path.join(process.resourcesPath, 'static', 'luts'));
}
candidates.push(path.join(DIST_DIR, 'static', 'luts'));
for (const lutsDir of candidates) {
try {
if (!fs.existsSync(lutsDir)) continue;
const files = fs.readdirSync(lutsDir);
const pngFiles = files.filter(f => /\.png$/i.test(f));
if (pngFiles.length > 0) {
res.json(pngFiles);
return;
}
} catch (e) {
// try next candidate
}
}
res.json([]);
});
// ---------------------------------------------------------------------------
// Fast PLY reader — synchronous I/O, zero async overhead
// Bypasses splat-transform's ReadStream (39K async fs.read calls → 9 sync reads)
// Uses C++ native addon (mmap + scatter) when available, falls back to JS.
// ---------------------------------------------------------------------------
function readPlyFast(filePath) {
if (native) {
return native.readPlyFast(filePath);
}
const fd = fs.openSync(filePath, 'r');
try {
const fileSize = fs.statSync(filePath).size;
// 1. Read header in one shot (PLY headers are small, < 128KB)
const headerBuf = Buffer.allocUnsafe(Math.min(128 * 1024, fileSize));
const headerBytesRead = fs.readSync(fd, headerBuf, 0, headerBuf.length, 0);
// 2. Find \nend_header\n
const endHeader = Buffer.from('\nend_header\n', 'ascii');
let endIdx = -1;
for (let i = 0; i <= headerBytesRead - endHeader.length; i++) {
let match = true;
for (let j = 0; j < endHeader.length; j++) {
if (headerBuf[i + j] !== endHeader[j]) { match = false; break; }
}
if (match) { endIdx = i; break; }
}
if (endIdx < 0) throw new Error('end_header not found in PLY');
const binaryStart = endIdx + endHeader.length;
// 3. Parse header
const headerStr = headerBuf.toString('ascii', 0, endIdx);
const lines = headerStr.split('\n');
const elements = [];
let currentElement = null;
for (const line of lines) {
const trimmed = line.replace(/\r$/, '');
const words = trimmed.split(' ');
switch (words[0]) {
case 'ply': case 'format': case 'end_header': case '': case 'comment':
break;
case 'element':
currentElement = { name: words[1], count: parseInt(words[2], 10), properties: [] };
elements.push(currentElement);
break;
case 'property':
if (currentElement) {
currentElement.properties.push({ name: words[2], type: words[1] });
}
break;
}
}
// 4. Reject compressed PLY (chunk + vertex elements)
if (elements.length === 2 && elements[0].name === 'chunk' && elements[1].name === 'vertex') {
throw new Error('Compressed PLY not supported in fast path');
}
// 5. Find vertex element
const vertexEl = elements.find(e => e.name === 'vertex');
if (!vertexEl) throw new Error('No vertex element in PLY');
const numRows = vertexEl.count;
const numProps = vertexEl.properties.length;
// 6. Require all-float properties (standard 3DGS PLY)
const allFloat = vertexEl.properties.every(p => p.type === 'float');
if (!allFloat) throw new Error('Non-float PLY properties not supported in fast path');
// 7. Allocate column arrays
const columns = vertexEl.properties.map(p => ({
name: p.name,
data: new Float32Array(numRows)
}));
// 8. Read binary data in 256MB chunks, scatter to columns
const rowSize = numProps * 4;
const chunkRows = Math.min(numRows, Math.floor(256 * 1024 * 1024 / rowSize));
const chunkBuf = Buffer.allocUnsafe(chunkRows * rowSize);
const floatView = new Float32Array(chunkBuf.buffer, chunkBuf.byteOffset, chunkBuf.length / 4);
// Pre-extract column data arrays for direct access
const dsts = columns.map(c => c.data);
let rowBase = 0;
let fileOffset = binaryStart;
while (rowBase < numRows) {
const rowsInChunk = Math.min(chunkRows, numRows - rowBase);
const bytesToRead = rowsInChunk * rowSize;
fs.readSync(fd, chunkBuf, 0, bytesToRead, fileOffset);
// Row-major scatter: sequential floatView reads, linear dst writes
for (let r = 0; r < rowsInChunk; r++) {
const srcOff = r * numProps;
const dstOff = rowBase + r;
for (let p = 0; p < numProps; p++) {
dsts[p][dstOff] = floatView[srcOff + p];
}
}
rowBase += rowsInChunk;
fileOffset += bytesToRead;
}
return { columns, numRows };
} finally {
fs.closeSync(fd);
}
}
// ---------------------------------------------------------------------------
// Core processing function — shared by upload and path-based endpoints
// Returns { resultData, outFilename, count } so callers decide delivery method
// ---------------------------------------------------------------------------
async function processFile(inputPath, originalName, mode, targetPercent, deleteInput) {
let fileSystem = null;
const tag = mode === 'decimate' ? 'decimate' : 'convert';
const fileSizeMB = fs.existsSync(inputPath) ? fs.statSync(inputPath).size / (1024 * 1024) : 0;
console.log(`\n[${tag}] Received: ${originalName} (${fileSizeMB.toFixed(1)} MB)`);
try {
const splatLib = await loadSplatTransform();
const { readFile, getInputFormat, processDataTable, writeFile, getOutputFormat, MemoryFileSystem, Column, DataTable, Transform } = splatLib;
const totalStages = mode === 'decimate' ? 3 : 2;
const t1 = performance.now();
// Detect PLY format for fast path
const lowerName = originalName.toLowerCase();
const isPly = lowerName.endsWith('.ply') && !lowerName.endsWith('.compressed.ply');
let dataTable;
let numRows;
if (isPly) {
// Fast path: synchronous I/O, no async overhead
console.log(`[${tag}] Stage 1/${totalStages}: Reading PLY (fast sync I/O)...`);
try {
const result = readPlyFast(inputPath);
dataTable = new DataTable(
result.columns.map(c => new Column(c.name, c.data)),
Transform.PLY.clone()
);
numRows = result.numRows;
} catch (fastErr) {
// Fall back to splat-transform's reader for compressed/mixed PLY
console.log(`[${tag}] Fast PLY reader failed (${fastErr.message}), falling back to splat-transform...`);
fileSystem = new NodeFileReadFileSystem(inputPath, originalName);
const inputFormat = getInputFormat(originalName);
const data = await readFile({
filename: originalName,
inputFormat,
options: { iterations: 1 },
params: [],
fileSystem
});
if (!data || data.length === 0) {
throw new Error('Failed to read input file');
}
dataTable = data[0];
numRows = dataTable.numRows;
}
} else {
// Non-PLY: use splat-transform's reader (SOG, splat, ksplat, etc.)
console.log(`[${tag}] Stage 1/${totalStages}: Reading file...`);
fileSystem = new NodeFileReadFileSystem(inputPath, originalName);
const inputFormat = getInputFormat(originalName);
const data = await readFile({
filename: originalName,
inputFormat,
options: { iterations: 1 },
params: [],
fileSystem
});
if (!data || data.length === 0) {
throw new Error('Failed to read input file');
}
dataTable = data[0];
numRows = dataTable.numRows;
}
console.log(`[${tag}] Read complete (${((performance.now() - t1) / 1000).toFixed(1)}s), ${numRows.toLocaleString()} Gaussians`);
let stage = 2;
// 2. Decimate (if requested)
if (mode === 'decimate') {
console.log(`[${tag}] Stage 2/3: Decimating to ${targetPercent}% (target ~${Math.round(numRows * targetPercent / 100).toLocaleString()} Gaussians)...`);
const t2 = performance.now();
dataTable = await processDataTable(dataTable, [
{ kind: 'decimate', percent: targetPercent, count: null }
]);
console.log(`[${tag}] Decimate complete (${((performance.now() - t2) / 1000).toFixed(1)}s), ${dataTable.numRows.toLocaleString()} Gaussians`);
stage = 3;
}
// 3. Write output — compressed PLY (SuperSplat chunk-based, ~16 bytes/gaussian GPU)
const writeFilename = mode === 'decimate'
? originalName.replace(/\.\w+$/, `_d${targetPercent}.compressed.ply`)
: originalName.replace(/\.\w+$/, '.compressed.ply');
console.log(`[${tag}] Stage ${stage}/${totalStages}: Writing output compressed PLY...`);
const t3 = performance.now();
let outFilename = writeFilename;
let resultData = null;
// C++ native fast path: direct file write (4.3x faster than JS)
if (native && isPly) {
try {
const colMap = {};
for (const col of dataTable.columns) {
colMap[col.name] = col.data;
}
// Detect SH bands from f_rest column count
let shBands = 0;
let restCount = 0;
while (colMap[`f_rest_${restCount}`] !== undefined) restCount++;
if (restCount >= 45) shBands = 3;
else if (restCount >= 24) shBands = 2;
else if (restCount >= 9) shBands = 1;
const tempOutPath = path.join(TEMP_DIR, `${Date.now()}_${path.basename(writeFilename)}`);
native.writeCompressedPly({
columns: colMap,
numRows: dataTable.numRows,
outputPath: tempOutPath,
shBands
});
// C++ native path: writeCompressedPly writes to disk. Don't readFileSync
// — for >2 GB files it hits ERR_FS_FILE_TOO_LARGE. Keep the file path
// and let sendResult / sendPathResult stream or rename it directly.
resultData = tempOutPath; // file path, not Uint8Array
console.log(`[${tag}] (native) Write done (${((performance.now() - t3) / 1000).toFixed(1)}s)`);
} catch (nativeErr) {
console.log(`[${tag}] Native write failed (${nativeErr.message}), falling back to JS...`);
resultData = null;
}
}
if (!resultData) {
// JS fallback: splat-transform MemoryFileSystem + writeFile
const outFs = new MemoryFileSystem();
await writeFile({
filename: writeFilename,
outputFormat: getOutputFormat(writeFilename, {}),
dataTable: dataTable,
options: {}
}, outFs);
resultData = outFs.results.get(outFilename);
if (!resultData) {
const keys = Array.from(outFs.results.keys());
if (keys.length === 0) {
throw new Error('No output generated');
}
outFilename = keys[0];
resultData = outFs.results.get(keys[0]);
}
}
const outputSizeMB = (typeof resultData === 'string' ? fs.statSync(resultData).size : resultData.length) / (1024 * 1024);
const totalSec = ((performance.now() - t1) / 1000).toFixed(1);
console.log(`[${tag}] Done! Write (${((performance.now() - t3) / 1000).toFixed(1)}s) | Output: ${outputSizeMB.toFixed(1)} MB, ${dataTable.numRows.toLocaleString()} Gaussians | Total: ${totalSec}s`);
return { resultData, outFilename, count: dataTable.numRows };
} finally {
if (fileSystem) fileSystem.close();
if (deleteInput) cleanup(inputPath);
}
}
// ---------------------------------------------------------------------------
// API: Decimate (upload) — reduce Gaussian count via MPMM merging
// ---------------------------------------------------------------------------
app.post('/api/decimate', upload.single('file'), async (req, res) => {
const inputPath = req.file?.path;
const originalName = req.file?.originalname || 'input.sog';
if (!inputPath) { res.status(400).json({ error: 'No file uploaded' }); return; }
const targetPercent = parseInt(req.body.targetPercent || '10', 10);
if (isNaN(targetPercent) || targetPercent < 1 || targetPercent > 100) {
res.status(400).json({ error: 'targetPercent must be 1-100' });
cleanup(inputPath);
return;
}
try {
const result = await processFile(inputPath, originalName, 'decimate', targetPercent, true);
sendResult(res, result);
} catch (error) {
console.error('[decimate] Error:', error);
res.status(500).json({ error: error.message || 'Decimate failed' });
}
});
// ---------------------------------------------------------------------------
// API: Decimate (path) — read file directly from disk, no upload
// ---------------------------------------------------------------------------
app.post('/api/decimate-path', express.json(), async (req, res) => {
const { filePath, targetPercent = 10 } = req.body;
if (!filePath || !fs.existsSync(filePath)) {
res.status(400).json({ error: 'Invalid file path' });
return;
}
const originalName = path.basename(filePath);
try {
const result = await processFile(filePath, originalName, 'decimate', parseInt(targetPercent, 10), false);
sendPathResult(res, result);
} catch (error) {
console.error('[decimate] Error:', error);
res.status(500).json({ error: error.message || 'Decimate failed' });
}
});
// ---------------------------------------------------------------------------
// API: Convert (upload) — read file, write as PLY without decimation
// ---------------------------------------------------------------------------
app.post('/api/convert', upload.single('file'), async (req, res) => {
const inputPath = req.file?.path;
const originalName = req.file?.originalname || 'input.ply';
if (!inputPath) { res.status(400).json({ error: 'No file uploaded' }); return; }
try {
const result = await processFile(inputPath, originalName, 'convert', 0, true);
sendResult(res, result);
} catch (error) {
console.error('[convert] Error:', error);
res.status(500).json({ error: error.message || 'Convert failed' });
}
});
// ---------------------------------------------------------------------------
// API: Convert (path) — read file from disk, convert to PLY, no upload
// ---------------------------------------------------------------------------
app.post('/api/convert-path', express.json(), async (req, res) => {
const { filePath } = req.body;
if (!filePath || !fs.existsSync(filePath)) {
res.status(400).json({ error: 'Invalid file path' });
return;
}
const originalName = path.basename(filePath);
try {
const result = await processFile(filePath, originalName, 'convert', 0, false);
sendPathResult(res, result);
} catch (error) {
console.error('[convert] Error:', error);
res.status(500).json({ error: error.message || 'Convert failed' });
}
});
// ---------------------------------------------------------------------------
// API: Read PLY header — returns vertex count + estimated memory
// ---------------------------------------------------------------------------
app.post('/api/ply-meta', express.json(), async (req, res) => {
const { filePath } = req.body;
if (!filePath || !fs.existsSync(filePath)) {
res.status(400).json({ error: 'Invalid file path' });
return;
}
try {
const fd = fs.openSync(filePath, 'r');
const buf = Buffer.alloc(8192);
fs.readSync(fd, buf, 0, 8192, 0);
fs.closeSync(fd);
const header = buf.toString('ascii');
const endIdx = header.indexOf('end_header');
if (endIdx < 0) { res.status(400).json({ error: 'Invalid PLY header' }); return; }
const section = header.substring(0, endIdx);
const match = section.match(/element\s+vertex\s+(\d+)/i);
if (!match) { res.status(400).json({ error: 'No vertex count found' }); return; }
const count = parseInt(match[1], 10);
const propMatches = section.match(/\bproperty\b/g);
const numProps = propMatches ? propMatches.length : 14;
const estMemMB = Math.round(count * numProps * 4 * 2.5 / (1024 * 1024));
res.json({ count, estMemMB, numProps });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// ---------------------------------------------------------------------------
// API: LOD Convert (upload) — file blob → multi-level compressed-ply for progressive loading
// ---------------------------------------------------------------------------
app.post('/api/lod-convert', upload.single('file'), async (req, res) => {
const inputPath = req.file?.path;
const originalName = req.file?.originalname || 'input.ply';
if (!inputPath) { res.status(400).json({ error: 'No file uploaded' }); return; }
// Parse levels from form field (sent as JSON string)
let levels = [5, 25, 100];
try {
if (req.body.levels) levels = JSON.parse(req.body.levels);
} catch { /* use default */ }
try {
const result = await lodConvert(inputPath, originalName, levels);
res.json(result);
} catch (error) {
console.error('[lod-upload] Error:', error);
res.status(500).json({ error: error.message || 'LOD convert failed' });
}
});
// ---------------------------------------------------------------------------
// API: LOD Convert (path) — generate multi-level compressed-ply for progressive loading
// Levels: [5%, 25%, 100%] by default — preview loaded first, higher LOD in background
// ---------------------------------------------------------------------------
app.post('/api/lod-convert-path', express.json(), async (req, res) => {
const { filePath, levels = [5, 25, 100], lodIndex = 0 } = req.body;
if (!filePath || !fs.existsSync(filePath)) {
res.status(400).json({ error: 'Invalid file path' });
return;
}
const originalName = path.basename(filePath);
try {
const result = await lodConvert(filePath, originalName, levels, lodIndex);
res.json(result);
} catch (error) {
console.error('[lod-path] Error:', error);
res.status(500).json({ error: error.message || 'LOD convert failed' });
}
});
// ---------------------------------------------------------------------------
// LOD Convert (core) — shared by upload and path-based endpoints
// ---------------------------------------------------------------------------
async function lodConvert(inputPath, originalName, levels = [100], lodIndex = 0) {
const t0 = performance.now();
const lowerName = originalName.toLowerCase();
const isPly = lowerName.endsWith('.ply') && !lowerName.endsWith('.compressed.ply');
const fileSizeMB = fs.existsSync(inputPath) ? fs.statSync(inputPath).size / (1024 * 1024) : 0;
console.log(`\n[lod] Received: ${originalName} (${fileSizeMB.toFixed(1)} MB), levels: [${levels.join(', ')}%], lodIndex: ${lodIndex}`);
const splatLib = await loadSplatTransform();
const { Column, DataTable, Transform, MemoryFileSystem } = splatLib;
// Stage 1: read source → columns in the app's native load space:
// * Standard PLY → C++ fast reader (PLY space, as the app loads PLY).
// * LCC/LCC2/SOG/… → splat-transform lazy reader over a seekable
// directory fs; the requested LOD (default 0 = finest) is materialized
// WITHOUT baking — the LOD switcher preserves the splat's entity
// rotation across levels (docDeserialize), so the data must stay in
// the same source space loadLodDataTable returns, or the level would
// render rotated relative to the others.
let columns, numRows;
let transformRotation = null; // source-space rotation (non-PLY), for the import path
if (isPly) {
console.log('[lod] Stage 1/3: Reading PLY...');
const result = readPlyFast(inputPath);
columns = result.columns;
numRows = result.numRows;
} else {
const ext = path.extname(originalName) || originalName;
console.log(`[lod] Stage 1/3: Reading ${ext} (LOD ${lodIndex})...`);
const {
readFile, getInputFormat, selectLod,
materializeToDataTable, createChunkDataPool
} = splatLib;
const dirFs = new NodeDirReadFileSystem(path.dirname(inputPath));
try {
const sources = await readFile({
filename: originalName,
inputFormat: getInputFormat(originalName),
options: {},
params: [],
fileSystem: dirFs
});
const source = sources[0];
const srcRot = source.meta.transform?.rotation;
if (srcRot) transformRotation = [srcRot.x, srcRot.y, srcRot.z, srcRot.w];
const single = source.meta.numLods > 1 ? selectLod(source, lodIndex) : source;
const pool = createChunkDataPool({ chunkSize: single.meta.chunkSize });
try {
const dataTable = await materializeToDataTable(single, pool);
columns = dataTable.columns.map((c) => ({ name: c.name, data: c.data }));
numRows = dataTable.numRows;
} finally {
pool.destroy();
for (const s of sources) await s.close();
}
} finally {
dirFs.close();
}
}
console.log(`[lod] Read complete (${((performance.now() - t0) / 1000).toFixed(1)}s), ${numRows.toLocaleString()} Gaussians`);
const pristineColumns = columns;
const sortedLevels = [...levels].sort((a, b) => b - a); // 100% first, then descending
// — Helper: generate a single LOD level (sampling + compress + serve) —
const generateLevel = async (lvl) => {
const tLvl = performance.now();
console.log(`[lod] Generating ${lvl}% LOD...`);
let lvlDataTable;
if (lvl < 100) {
const sampleRatio = lvl / 100;
const sampleCount = Math.max(1, Math.floor(numRows * sampleRatio));
const step = Math.max(1, Math.floor(numRows / sampleCount));
const sampledColumns = pristineColumns.map(c => {
const src = c.data;
const dst = new Float32Array(sampleCount);
for (let i = 0; i < sampleCount; i++) dst[i] = src[i * step];
return new Column(c.name, dst);
});
lvlDataTable = new DataTable(sampledColumns, Transform.PLY.clone());
} else {
const lvlColumns = pristineColumns.map(c => new Column(c.name, c.data));
lvlDataTable = new DataTable(lvlColumns, Transform.PLY.clone());
}
const writeFilename = originalName.replace(/\.\w+$/, `.lod${lvl}.compressed.ply`);
let resultData;
if (native) {
const colMap = {};
for (const col of lvlDataTable.columns) colMap[col.name] = col.data;
let shBands = 0, restCount = 0;
while (colMap[`f_rest_${restCount}`] !== undefined) restCount++;
if (restCount >= 45) shBands = 3;
else if (restCount >= 24) shBands = 2;
else if (restCount >= 9) shBands = 1;
const tempOutPath = path.join(TEMP_DIR, `${Date.now()}_${path.basename(writeFilename)}`);
native.writeCompressedPly({
columns: colMap,
numRows: lvlDataTable.numRows,
outputPath: tempOutPath,
shBands
});
resultData = tempOutPath;
} else {
const { writeFile, getOutputFormat } = splatLib;
const outFs = new MemoryFileSystem();
await writeFile({
filename: writeFilename,
outputFormat: getOutputFormat(writeFilename, {}),
dataTable: lvlDataTable,
options: {}
}, outFs);
resultData = outFs.results.get(writeFilename);
if (!resultData) {
const keys = Array.from(outFs.results.keys());
if (keys.length === 0) throw new Error('No output generated');
resultData = outFs.results.get(keys[0]);
}
}
const ext = path.extname(writeFilename);
const base = path.basename(writeFilename, ext);
const serveName = `${base}_${Date.now()}${ext}`;
const servePath = path.join(TEMP_DIR, serveName);
if (typeof resultData === 'string') {
fs.renameSync(resultData, servePath);
} else {
const fd = fs.openSync(servePath, 'w');
try {
const CHUNK = 256 * 1024 * 1024;
for (let offset = 0; offset < resultData.length; offset += CHUNK) {
const slice = Buffer.from(resultData.subarray(offset, offset + CHUNK));
fs.writeSync(fd, slice, 0, slice.length, offset);
}
} finally { fs.closeSync(fd); }
}
const cleanupTimer = setTimeout(() => cleanup(servePath), 30 * 60 * 1000);
cleanupTimer.unref?.();
const url = `http://localhost:${PORT}/temp/${encodeURIComponent(serveName)}`;
const { size: sizeBytes } = fs.statSync(servePath);
const sizeMB = sizeBytes / (1024 * 1024);
console.log(`[lod] Level ${lvl}%: ${lvlDataTable.numRows.toLocaleString()} Gaussians, ${sizeMB.toFixed(1)} MB, ${((performance.now() - tLvl) / 1000).toFixed(1)}s`);
// Release per-level buffers
const resultCount = lvlDataTable.numRows;
lvlDataTable = null;
if (global.gc) global.gc();
return { level: lvl, count: resultCount, url, sizeBytes };
};
// — Process: 100% first (needs pristine), then sub-levels in parallel —
const lodResults = [];
const maxLevel = sortedLevels[0]; // 100%
lodResults.push(await generateLevel(maxLevel));
if (sortedLevels.length > 1) {
const subResults = await Promise.all(sortedLevels.slice(1).map(generateLevel));
lodResults.push(...subResults);
}
const totalSec = ((performance.now() - t0) / 1000).toFixed(1);
console.log(`[lod] Done! Total: ${totalSec}s`);
return { levels: lodResults, totalSeconds: parseFloat(totalSec), transformRotation };
}
// ---------------------------------------------------------------------------
// API: Merge (path) — merge multiple PLY files into one compressed-ply, offline
// Uses C++ native mergePlyFiles + writeCompressedPly to avoid browser OOM
// ---------------------------------------------------------------------------
app.post('/api/merge-path', express.json(), async (req, res) => {
const { filePaths } = req.body;
if (!filePaths || !Array.isArray(filePaths) || filePaths.length < 2) {
res.status(400).json({ error: 'Need at least 2 file paths' });
return;
}
// Validate all files exist
for (const fp of filePaths) {
if (!fs.existsSync(fp)) {
res.status(400).json({ error: `File not found: ${fp}` });
return;