-
Notifications
You must be signed in to change notification settings - Fork 366
Expand file tree
/
Copy pathmcSchematicHandler.ts
More file actions
388 lines (331 loc) · 14.4 KB
/
Copy pathmcSchematicHandler.ts
File metadata and controls
388 lines (331 loc) · 14.4 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
import type { FileData, FileFormat, FormatHandler } from "src/FormatHandler";
import * as NBT from "nbtify";
import { gunzipSync, gzipSync } from "fflate";
import { Category } from "src/CommonFormats.ts";
class mcSchematicHandler implements FormatHandler {
public name: string = "mcSchematic";
public supportedFormats?: FileFormat[];
public ready: boolean = false;
async init() {
this.supportedFormats = [
{
name: "Minecraft Schematic",
format: "schematic",
extension: "schematic",
mime: "application/x-minecraft-schematic",
from: true,
to: true,
internal: "schematic",
category: Category.DATA,
lossless: true
},
{
name: "Sponge Schematic",
format: "schem",
extension: "schem",
mime: "application/x-minecraft-schem",
from: true,
to: true,
internal: "schem",
category: Category.DATA,
lossless: true
},
{
name: "Litematica Schematic",
format: "litematic",
extension: "litematic",
mime: "application/x-minecraft-litematic",
from: true,
to: true,
internal: "litematic",
category: Category.DATA,
lossless: true
},
// Target internal format for graph routing
{
name: "Named Binary Tag",
format: "nbt",
extension: "nbt",
mime: "application/x-minecraft-nbt",
from: false,
to: true,
internal: "nbt",
category: Category.DATA,
lossless: true
}
];
this.ready = true;
}
async doConvert(
inputFiles: FileData[],
inputFormat: FileFormat,
outputFormat: FileFormat
): Promise<FileData[]> {
const outputFiles: FileData[] = [];
for (const file of inputFiles) {
// Decompress GZipped NBT input
let unzipped;
try {
unzipped = gunzipSync(file.bytes);
} catch (e) {
// Fallback for uncompressed NBT
unzipped = file.bytes;
}
const nbt = await NBT.read(unzipped);
let resultNbt = new NBT.NBTData({});
if (inputFormat.internal === "litematic") {
resultNbt = this.litematicToSchem(nbt.data);
} else if (inputFormat.internal === "schematic" || inputFormat.internal === "schem") {
if (outputFormat.internal === "litematic") {
resultNbt = this.schemToLitematic(nbt.data);
} else {
// Route Native Schematic NBTs to graph path
resultNbt = nbt;
}
} else {
throw new TypeError(`Unsupported conversion route: ${inputFormat.internal} -> ${outputFormat.internal}`);
}
// Output processed intermediate NBT
let outBytes = await NBT.write(resultNbt);
// Handle file compression natively for endpoints (Litematic <-> Schem)
if (outputFormat.internal === "litematic" || outputFormat.internal === "schem" || outputFormat.internal === "schematic") {
outBytes = gzipSync(outBytes);
outputFiles.push({
name: file.name.split(".").slice(0, -1).join(".") + "." + outputFormat.extension,
bytes: outBytes
});
} else {
// Not a native out-format (e.g., routing to JSON). Fallback to NBT extension for graph bridges.
outputFiles.push({
name: file.name.split(".").slice(0, -1).join(".") + ".nbt",
bytes: outBytes
});
}
}
return outputFiles;
}
/**
* Converts a Litematica NBT compound into a Sponge Schematic V2 NBT compound.
* Note: Currently supports single-region Litematica files.
*/
private litematicToSchem(data: any): NBT.NBTData {
const root = data as any;
// 1. Validate
if (!root.Regions) {
throw new Error("Invalid Litematica file: Missing Regions tag.");
}
// 2. Select first region
const regionNames = Object.keys(root.Regions);
if (regionNames.length === 0) {
throw new Error("Invalid Litematica file: No regions defined.");
}
const region = root.Regions[regionNames[0]];
// Dimensions
const width = Math.abs(region.Size.x);
const height = Math.abs(region.Size.y);
const length = Math.abs(region.Size.z);
const totalBlocks = width * height * length;
// 3. Extract Palette
const litePalette = region.BlockStatePalette;
const schemPalette: { [key: string]: NBT.Tag } = {};
for (let i = 0; i < litePalette.length; i++) {
const entry = litePalette[i];
let name = entry.Name;
if (entry.Properties) {
const props = [];
for (const key of Object.keys(entry.Properties)) {
props.push(`${key}=${entry.Properties[key]}`);
}
if (props.length > 0) {
name += `[${props.join(",")}]`;
}
}
schemPalette[name] = new NBT.Int32(i);
}
// 4. Extract Block Data
// Calculate bits per block using palette size
const bitsPerBlock = Math.max(2, Math.ceil(Math.log2(litePalette.length)));
const blockStates = region.BlockStates; // nbtify LongArray
const blockData = new Uint8Array(totalBlocks);
if (blockStates && blockStates.length > 0) {
// Unpack bit logic payload into Uint8Array
const longs = new BigInt64Array(blockStates.buffer);
let blockIndex = 0;
const mask = (1n << BigInt(bitsPerBlock)) - 1n;
for (let y = 0; y < height; y++) {
for (let z = 0; z < length; z++) {
for (let x = 0; x < width; x++) {
if (blockIndex >= totalBlocks) break;
const bitIndex = BigInt(blockIndex) * BigInt(bitsPerBlock);
const longIndex = Number(bitIndex / 64n);
const bitOffset = bitIndex % 64n;
let value = (longs[longIndex] >> bitOffset) & mask;
// Handle 64-bit boundary overlap
if (bitOffset + BigInt(bitsPerBlock) > 64n && longIndex + 1 < longs.length) {
const remainingBits = (bitOffset + BigInt(bitsPerBlock)) - 64n;
const nextValueMask = (1n << remainingBits) - 1n;
const nextValue = longs[longIndex + 1] & nextValueMask;
value = value | (nextValue << (64n - bitOffset));
}
// Write mapped block ID (y, z, x)
blockData[blockIndex] = Number(value);
blockIndex++;
}
}
}
}
// 5. Build Schem NBT
// Encode blockData as VarInt array
const varIntBlockData: number[] = [];
for (let i = 0; i < totalBlocks; i++) {
let value = blockData[i];
while ((value & -128) !== 0) {
varIntBlockData.push((value & 127) | 128);
value >>>= 7;
}
varIntBlockData.push(value);
}
let metadata = {
Name: root.Metadata?.Name || "Converted Litematic",
Author: root.Metadata?.Author || "Unknown",
Date: BigInt(Date.now()),
RequiredMods: []
};
const result = new NBT.NBTData({
Version: new NBT.Int32(2),
DataVersion: new NBT.Int32(root.MinecraftDataVersion || 2566),
Metadata: metadata,
Width: new NBT.Int16(width),
Height: new NBT.Int16(height),
Length: new NBT.Int16(length),
PaletteMax: new NBT.Int32(litePalette.length),
Palette: schemPalette,
BlockData: new Int8Array(varIntBlockData),
BlockEntities: region.TileEntities || [],
Entities: region.Entities || []
}, { rootName: "Schematic" });
return result;
}
/**
* Converts a Sponge Schematic V2 NBT compound into a Litematica NBT compound.
*/
private schemToLitematic(data: any): NBT.NBTData {
const root = data as any;
// 1. Validate
if (!root.Width || !root.Height || !root.Length || !root.Palette || !root.BlockData) {
throw new Error("Invalid Schematic file: Missing required size or block data tags.");
}
const width = root.Width.valueOf();
const height = root.Height.valueOf();
const length = root.Length.valueOf();
const totalBlocks = width * height * length;
// 2. Extract Palette
const schemPalette = root.Palette; // Dictionary of { "minecraft:stone": NBT.Int32 }
const litePalette: any[] = [];
// Invert schematic palette to an array indexed by the ID
const invertedPalette: { [id: number]: string } = {};
for (const [key, value] of Object.keys(schemPalette).map(k => [k, schemPalette[k].valueOf()])) {
invertedPalette[value as number] = key as string;
}
const paletteSize = Object.keys(invertedPalette).length;
// Build Litematica Palette Array [{Name: "minecraft:stone", Properties: {...}}]
for (let i = 0; i < paletteSize; i++) {
const rawName = invertedPalette[i];
if (!rawName) {
// Fallback if missing id
litePalette.push({ Name: "minecraft:air" });
continue;
}
// Parse Properties "minecraft:stairs[facing=east,half=bottom]"
const bracketIndex = rawName.indexOf('[');
if (bracketIndex > -1) {
const name = rawName.substring(0, bracketIndex);
const propsString = rawName.substring(bracketIndex + 1, rawName.length - 1);
const props: any = {};
propsString.split(',').forEach(p => {
const [k, v] = p.split('=');
props[k] = v;
});
litePalette.push({ Name: name, Properties: props });
} else {
litePalette.push({ Name: rawName });
}
}
// 3. Extract Block Data (VarInt Byte Array -> Integer Array)
const blockDataBytes = new Uint8Array(root.BlockData);
let blockIds = new Int32Array(totalBlocks);
let byteIndex = 0;
for (let i = 0; i < totalBlocks; i++) {
let value = 0;
let varIntLength = 0;
let currentByte;
while (true) {
currentByte = blockDataBytes[byteIndex];
value |= (currentByte & 127) << (varIntLength++ * 7);
byteIndex++;
if (varIntLength > 5) {
throw new RangeError(`VarInt is too big: ${varIntLength}`);
}
if ((currentByte & 128) !== 128) {
break;
}
}
blockIds[i] = value;
}
// 4. Pack Block Data (Integer Array -> Bit-Packed BigInt64Array)
const bitsPerBlock = Math.max(2, Math.ceil(Math.log2(paletteSize)));
const longsCount = Math.ceil((totalBlocks * bitsPerBlock) / 64);
const longs = new BigInt64Array(longsCount);
let blockIndex = 0;
for (let y = 0; y < height; y++) {
for (let z = 0; z < length; z++) {
for (let x = 0; x < width; x++) {
if (blockIndex >= totalBlocks) break;
const blockId = BigInt(blockIds[blockIndex]);
const bitIndex = BigInt(blockIndex) * BigInt(bitsPerBlock);
const longIndex = Number(bitIndex / 64n);
const bitOffset = bitIndex % 64n;
// Pack value into long
longs[longIndex] |= (blockId << bitOffset);
// Handle boundary overlap
if (bitOffset + BigInt(bitsPerBlock) > 64n && longIndex + 1 < longs.length) {
const remainingBits = (bitOffset + BigInt(bitsPerBlock)) - 64n;
longs[longIndex + 1] |= (blockId >> (64n - bitOffset));
}
blockIndex++;
}
}
}
// 5. Build Litematic NBT
const litematicMetadata = {
Author: root.Metadata?.Author || "Converted",
Name: root.Metadata?.Name || "Converted Schematic",
Description: "",
RegionCount: new NBT.Int32(1),
TimeCreated: new NBT.Float32(Date.now()),
TimeModified: new NBT.Float32(Date.now()),
TotalBlocks: new NBT.Int32(totalBlocks),
TotalVolume: new NBT.Int32(totalBlocks)
};
const region = {
Position: { x: new NBT.Int32(0), y: new NBT.Int32(0), z: new NBT.Int32(0) },
Size: { x: new NBT.Int32(width), y: new NBT.Int32(height), z: new NBT.Int32(length) },
BlockStatePalette: litePalette,
BlockStates: new BigInt64Array(longs), // NBT Long Array
TileEntities: root.BlockEntities || [],
Entities: root.Entities || [],
PendingBlockTicks: [],
PendingFluidTicks: []
};
const result = new NBT.NBTData({
MinecraftDataVersion: new NBT.Int32(root.DataVersion?.valueOf() || 2566),
Version: new NBT.Int32(6), // Litematic format v6
Metadata: litematicMetadata,
Regions: {
"Converted": region
}
}, { rootName: "Litematic" });
return result;
}
}
export default mcSchematicHandler;