mirror of
https://github.com/clusterio/clusterio.git
synced 2026-11-24 00:23:12 +09:00
Lint and refactor
This commit is contained in:
1 parent
ae7a1744ad
commit
2bce506d96
5 files changed
+828
-475
No files matched your search
+134
-87
@@ -22,7 +22,7 @@ import {
|
|||||||
renderTileToPixels,
|
renderTileToPixels,
|
||||||
pixelsToRGBA,
|
pixelsToRGBA,
|
||||||
parseRecipeTileBinary,
|
parseRecipeTileBinary,
|
||||||
ParsedRecipeTile
|
ParsedRecipeTile,
|
||||||
} from "./tile-utils";
|
} from "./tile-utils";
|
||||||
|
|
||||||
const CHUNK_SIZE = 32;
|
const CHUNK_SIZE = 32;
|
||||||
@@ -51,7 +51,9 @@ export class ControllerPlugin extends BaseControllerPlugin {
|
|||||||
icon?: any;
|
icon?: any;
|
||||||
last_user?: string;
|
last_user?: string;
|
||||||
}>>();
|
}>>();
|
||||||
private lastSeenRecipeContent = new Map<string, Map<string, string | undefined>>(); // tileKey -> posKey -> recipe
|
|
||||||
|
// tileKey -> posKey -> recipe
|
||||||
|
private lastSeenRecipeContent = new Map<string, Map<string, string | undefined>>();
|
||||||
private savingTiles: boolean = false;
|
private savingTiles: boolean = false;
|
||||||
private savingChartTags = new Set<string>();
|
private savingChartTags = new Set<string>();
|
||||||
private saveInterval: NodeJS.Timeout | null = null;
|
private saveInterval: NodeJS.Timeout | null = null;
|
||||||
@@ -109,7 +111,12 @@ export class ControllerPlugin extends BaseControllerPlugin {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Compare two pixel arrays and return changes
|
// Compare two pixel arrays and return changes
|
||||||
private comparePixels(oldPixels: Uint16Array, newPixels: Uint16Array, chunkX: number, chunkY: number): PixelChange[] {
|
private comparePixels(
|
||||||
|
oldPixels: Uint16Array,
|
||||||
|
newPixels: Uint16Array,
|
||||||
|
chunkX: number,
|
||||||
|
chunkY: number
|
||||||
|
): PixelChange[] {
|
||||||
const changes: PixelChange[] = [];
|
const changes: PixelChange[] = [];
|
||||||
|
|
||||||
for (let y = 0; y < 32; y++) {
|
for (let y = 0; y < 32; y++) {
|
||||||
@@ -146,7 +153,7 @@ export class ControllerPlugin extends BaseControllerPlugin {
|
|||||||
const groups = new Map<string, PixelChange[]>();
|
const groups = new Map<string, PixelChange[]>();
|
||||||
for (const ch of changes) {
|
for (const ch of changes) {
|
||||||
const key = `${ch.newColor}_${ch.oldColor}`;
|
const key = `${ch.newColor}_${ch.oldColor}`;
|
||||||
if (!groups.has(key)) groups.set(key, []);
|
if (!groups.has(key)) { groups.set(key, []); }
|
||||||
groups.get(key)!.push(ch);
|
groups.get(key)!.push(ch);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -184,8 +191,8 @@ export class ControllerPlugin extends BaseControllerPlugin {
|
|||||||
app.get("/api/minimap/tile/:instanceId/:surface/:force/:z/:x/:y.png", async (req, res) => {
|
app.get("/api/minimap/tile/:instanceId/:surface/:force/:z/:x/:y.png", async (req, res) => {
|
||||||
try {
|
try {
|
||||||
const { instanceId, surface, force, z, x, y } = req.params;
|
const { instanceId, surface, force, z, x, y } = req.params;
|
||||||
const tileX = parseInt(x);
|
const tileX = parseInt(x, 10);
|
||||||
const tileY = parseInt(y);
|
const tileY = parseInt(y, 10);
|
||||||
|
|
||||||
const tileName = `${instanceId}_${surface}_${force}_${tileX}_${tileY}.bin`;
|
const tileName = `${instanceId}_${surface}_${force}_${tileX}_${tileY}.bin`;
|
||||||
const tilePath = path.join(this.tilesPath, tileName);
|
const tilePath = path.join(this.tilesPath, tileName);
|
||||||
@@ -243,7 +250,7 @@ export class ControllerPlugin extends BaseControllerPlugin {
|
|||||||
|
|
||||||
// Create and return the image directly
|
// Create and return the image directly
|
||||||
return sharp(raw, {
|
return sharp(raw, {
|
||||||
raw: { width: 256, height: 256, channels: 4 }
|
raw: { width: 256, height: 256, channels: 4 },
|
||||||
}).png().toBuffer();
|
}).png().toBuffer();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -285,7 +292,10 @@ export class ControllerPlugin extends BaseControllerPlugin {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async updateTile(existingTile: Buffer, newChunks: Map<string, { data: ChartData, tick: number }>): Promise<Buffer | undefined> {
|
async updateTile(
|
||||||
|
existingTile: Buffer,
|
||||||
|
newChunks: Map<string, { data: ChartData, tick: number }>
|
||||||
|
): Promise<Buffer | undefined> {
|
||||||
const existingChunks = new Map<string, { tick: number, data: Buffer }>();
|
const existingChunks = new Map<string, { tick: number, data: Buffer }>();
|
||||||
|
|
||||||
// Parse existing tile data to find existing chunks
|
// Parse existing tile data to find existing chunks
|
||||||
@@ -300,49 +310,17 @@ export class ControllerPlugin extends BaseControllerPlugin {
|
|||||||
offset += 1;
|
offset += 1;
|
||||||
|
|
||||||
if (type === 1) { // Chunk
|
if (type === 1) { // Chunk
|
||||||
if (offset + 7 > existingTile.length) {
|
const parseResult = this.parseChunkData(existingTile, offset, existingChunks);
|
||||||
this.logger.error(`Invalid tile data: insufficient chunk header data at offset ${offset}`);
|
if (!parseResult.success) {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
offset = parseResult.newOffset;
|
||||||
const tick = existingTile.readUInt32BE(offset);
|
|
||||||
offset += 4;
|
|
||||||
const chunkCoordsByte = existingTile.readUInt8(offset);
|
|
||||||
offset += 1;
|
|
||||||
const length = existingTile.readUInt16BE(offset);
|
|
||||||
offset += 2;
|
|
||||||
|
|
||||||
if (offset + length > existingTile.length) {
|
|
||||||
this.logger.error(`Invalid tile data: insufficient chunk data at offset ${offset}`);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
const chunkX = chunkCoordsByte >> 4;
|
|
||||||
const chunkY = chunkCoordsByte & 0x0F;
|
|
||||||
const chunkName = `${chunkX}_${chunkY}`;
|
|
||||||
const data = existingTile.slice(offset, offset + length);
|
|
||||||
offset += length;
|
|
||||||
existingChunks.set(chunkName, { tick, data });
|
|
||||||
|
|
||||||
} else if (type === 2) { // Pixels
|
} else if (type === 2) { // Pixels
|
||||||
if (offset + 6 > existingTile.length) {
|
const parseResult = this.parsePixelData(existingTile, offset);
|
||||||
this.logger.error(`Invalid tile data: insufficient pixel header data at offset ${offset}`);
|
if (!parseResult.success) {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
offset = parseResult.newOffset;
|
||||||
const tick = existingTile.readUInt32BE(offset);
|
|
||||||
offset += 4;
|
|
||||||
const pixelCount = existingTile.readUInt16BE(offset);
|
|
||||||
offset += 2;
|
|
||||||
const pixelDataLength = pixelCount * 6;
|
|
||||||
|
|
||||||
if (offset + pixelDataLength > existingTile.length) {
|
|
||||||
this.logger.error(`Invalid tile data: insufficient pixel data at offset ${offset}`);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Skip pixel data since we're not rebuilding the file
|
|
||||||
offset += pixelDataLength;
|
|
||||||
} else {
|
} else {
|
||||||
this.logger.error(`Unknown tile data type: ${type} at offset ${offset}`);
|
this.logger.error(`Unknown tile data type: ${type} at offset ${offset}`);
|
||||||
break;
|
break;
|
||||||
@@ -399,13 +377,71 @@ export class ControllerPlugin extends BaseControllerPlugin {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (!hasChanges) {
|
if (!hasChanges) {
|
||||||
return;
|
return undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Append new data to existing tile (never modify existing data)
|
// Append new data to existing tile (never modify existing data)
|
||||||
return Buffer.concat([existingTile, ...appendBuffers]);
|
return Buffer.concat([existingTile, ...appendBuffers]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private parseChunkData(
|
||||||
|
existingTile: Buffer,
|
||||||
|
offset: number,
|
||||||
|
existingChunks: Map<string, { tick: number, data: Buffer }>
|
||||||
|
): { success: boolean, newOffset: number } {
|
||||||
|
if (offset + 7 > existingTile.length) {
|
||||||
|
this.logger.error(`Invalid tile data: insufficient chunk header data at offset ${offset}`);
|
||||||
|
return { success: false, newOffset: offset };
|
||||||
|
}
|
||||||
|
|
||||||
|
const tick = existingTile.readUInt32BE(offset);
|
||||||
|
offset += 4;
|
||||||
|
const chunkCoordsByte = existingTile.readUInt8(offset);
|
||||||
|
offset += 1;
|
||||||
|
const length = existingTile.readUInt16BE(offset);
|
||||||
|
offset += 2;
|
||||||
|
|
||||||
|
if (offset + length > existingTile.length) {
|
||||||
|
this.logger.error(`Invalid tile data: insufficient chunk data at offset ${offset}`);
|
||||||
|
return { success: false, newOffset: offset };
|
||||||
|
}
|
||||||
|
|
||||||
|
const chunkX = chunkCoordsByte >> 4;
|
||||||
|
const chunkY = chunkCoordsByte & 0x0F;
|
||||||
|
const chunkName = `${chunkX}_${chunkY}`;
|
||||||
|
const data = existingTile.slice(offset, offset + length);
|
||||||
|
offset += length;
|
||||||
|
existingChunks.set(chunkName, { tick, data });
|
||||||
|
|
||||||
|
return { success: true, newOffset: offset };
|
||||||
|
}
|
||||||
|
|
||||||
|
private parsePixelData(
|
||||||
|
existingTile: Buffer,
|
||||||
|
offset: number
|
||||||
|
): { success: boolean, newOffset: number } {
|
||||||
|
if (offset + 6 > existingTile.length) {
|
||||||
|
this.logger.error(`Invalid tile data: insufficient pixel header data at offset ${offset}`);
|
||||||
|
return { success: false, newOffset: offset };
|
||||||
|
}
|
||||||
|
|
||||||
|
const tick = existingTile.readUInt32BE(offset);
|
||||||
|
offset += 4;
|
||||||
|
const pixelCount = existingTile.readUInt16BE(offset);
|
||||||
|
offset += 2;
|
||||||
|
const pixelDataLength = pixelCount * 6;
|
||||||
|
|
||||||
|
if (offset + pixelDataLength > existingTile.length) {
|
||||||
|
this.logger.error(`Invalid tile data: insufficient pixel data at offset ${offset}`);
|
||||||
|
return { success: false, newOffset: offset };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Skip pixel data since we're not rebuilding the file
|
||||||
|
offset += pixelDataLength;
|
||||||
|
|
||||||
|
return { success: true, newOffset: offset };
|
||||||
|
}
|
||||||
|
|
||||||
async loadExistingTagContent() {
|
async loadExistingTagContent() {
|
||||||
try {
|
try {
|
||||||
if (!await fs.pathExists(this.chartTagsPath)) {
|
if (!await fs.pathExists(this.chartTagsPath)) {
|
||||||
@@ -413,10 +449,18 @@ export class ControllerPlugin extends BaseControllerPlugin {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const files = await fs.readdir(this.chartTagsPath);
|
const files = await fs.readdir(this.chartTagsPath);
|
||||||
const tagFiles = files.filter(file => file.endsWith('_chart_tags.json'));
|
const tagFiles = files.filter(file => file.endsWith("_chart_tags.json"));
|
||||||
|
|
||||||
for (const file of tagFiles) {
|
for (const file of tagFiles) {
|
||||||
const fileKey = file.replace('_chart_tags.json', '');
|
await this.loadTagContentFromFile(file);
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
this.logger.error(`Error loading existing tag content: ${err}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async loadTagContentFromFile(file: string) {
|
||||||
|
const fileKey = file.replace("_chart_tags.json", "");
|
||||||
const filePath = path.join(this.chartTagsPath, file);
|
const filePath = path.join(this.chartTagsPath, file);
|
||||||
|
|
||||||
if (!this.lastSeenTagContent.has(fileKey)) {
|
if (!this.lastSeenTagContent.has(fileKey)) {
|
||||||
@@ -425,24 +469,11 @@ export class ControllerPlugin extends BaseControllerPlugin {
|
|||||||
const seenTags = this.lastSeenTagContent.get(fileKey)!;
|
const seenTags = this.lastSeenTagContent.get(fileKey)!;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const content = await fs.readFile(filePath, 'utf-8');
|
const content = await fs.readFile(filePath, "utf-8");
|
||||||
const lines = content.trim().split('\n').filter(line => line.trim());
|
const lines = content.trim().split("\n").filter(line => line.trim());
|
||||||
|
|
||||||
for (const line of lines) {
|
for (const line of lines) {
|
||||||
try {
|
this.processTagLine(line, seenTags);
|
||||||
const tagData = JSON.parse(line);
|
|
||||||
if (typeof tagData.tag_number === 'number' && !tagData.end_tick) {
|
|
||||||
// Only store the latest content for tags that haven't been deleted
|
|
||||||
seenTags.set(tagData.tag_number, {
|
|
||||||
position: tagData.position,
|
|
||||||
text: tagData.text,
|
|
||||||
icon: tagData.icon,
|
|
||||||
last_user: tagData.last_user
|
|
||||||
});
|
|
||||||
}
|
|
||||||
} catch (parseErr) {
|
|
||||||
this.logger.warn(`Failed to parse chart tag line in ${file}: ${parseErr}`);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
this.logger.info(`Loaded ${seenTags.size} existing tag contents from ${file}`);
|
this.logger.info(`Loaded ${seenTags.size} existing tag contents from ${file}`);
|
||||||
@@ -450,8 +481,24 @@ export class ControllerPlugin extends BaseControllerPlugin {
|
|||||||
this.logger.warn(`Failed to read chart tag file ${file}: ${readErr}`);
|
this.logger.warn(`Failed to read chart tag file ${file}: ${readErr}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (err) {
|
|
||||||
this.logger.error(`Error loading existing tag content: ${err}`);
|
private processTagLine(line: string, seenTags: Map<number, any>) {
|
||||||
|
try {
|
||||||
|
const tagData = JSON.parse(line);
|
||||||
|
const isNumberTag = typeof tagData.tag_number === "number";
|
||||||
|
const notDeleted = !tagData.end_tick;
|
||||||
|
|
||||||
|
if (isNumberTag && notDeleted) {
|
||||||
|
// Only store the latest content for tags that haven't been deleted
|
||||||
|
seenTags.set(tagData.tag_number, {
|
||||||
|
position: tagData.position,
|
||||||
|
text: tagData.text,
|
||||||
|
icon: tagData.icon,
|
||||||
|
last_user: tagData.last_user,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} catch (parseErr) {
|
||||||
|
this.logger.warn(`Failed to parse chart tag line: ${parseErr}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -496,8 +543,8 @@ export class ControllerPlugin extends BaseControllerPlugin {
|
|||||||
private async parseRecipeTileForState(tileKey: string, buffer: Buffer) {
|
private async parseRecipeTileForState(tileKey: string, buffer: Buffer) {
|
||||||
// Derive tile coordinates from key (last two underscore-separated parts)
|
// Derive tile coordinates from key (last two underscore-separated parts)
|
||||||
const parts = tileKey.split("_");
|
const parts = tileKey.split("_");
|
||||||
const tileY = parseInt(parts.pop()!); // last
|
const tileY = parseInt(parts.pop()!, 10); // last
|
||||||
const tileX = parseInt(parts.pop()!); // second last
|
const tileX = parseInt(parts.pop()!, 10); // second last
|
||||||
const parsed: ParsedRecipeTile = parseRecipeTileBinary(tileX, tileY, buffer, null);
|
const parsed: ParsedRecipeTile = parseRecipeTileBinary(tileX, tileY, buffer, null);
|
||||||
|
|
||||||
// Populate dictionary mapping (name -> index)
|
// Populate dictionary mapping (name -> index)
|
||||||
@@ -505,7 +552,7 @@ export class ControllerPlugin extends BaseControllerPlugin {
|
|||||||
for (const [id, name] of parsed.dictionary) {
|
for (const [id, name] of parsed.dictionary) {
|
||||||
dict.set(name, id);
|
dict.set(name, id);
|
||||||
const currentNext = this.nextRecipeIndex.get(tileKey) ?? 0;
|
const currentNext = this.nextRecipeIndex.get(tileKey) ?? 0;
|
||||||
if (id + 1 > currentNext) this.nextRecipeIndex.set(tileKey, id + 1);
|
if (id + 1 > currentNext) { this.nextRecipeIndex.set(tileKey, id + 1); }
|
||||||
}
|
}
|
||||||
|
|
||||||
// Populate active recipe cache
|
// Populate active recipe cache
|
||||||
@@ -583,9 +630,9 @@ export class ControllerPlugin extends BaseControllerPlugin {
|
|||||||
const filePath = path.join(this.chartTagsPath, `${fileKey}_chart_tags.json`);
|
const filePath = path.join(this.chartTagsPath, `${fileKey}_chart_tags.json`);
|
||||||
|
|
||||||
// Convert chart tags to newline-delimited JSON format
|
// Convert chart tags to newline-delimited JSON format
|
||||||
const jsonLines = tagsToSave.map(tag => JSON.stringify(tag)).join('\n');
|
const jsonLines = tagsToSave.map(tag => JSON.stringify(tag)).join("\n");
|
||||||
|
|
||||||
await fs.appendFile(filePath, jsonLines + '\n');
|
await fs.appendFile(filePath, `${jsonLines}\n`);
|
||||||
|
|
||||||
// Mark tags as successfully saved
|
// Mark tags as successfully saved
|
||||||
if (!this.lastSeenTagContent.has(fileKey)) {
|
if (!this.lastSeenTagContent.has(fileKey)) {
|
||||||
@@ -597,7 +644,7 @@ export class ControllerPlugin extends BaseControllerPlugin {
|
|||||||
position: tag.position,
|
position: tag.position,
|
||||||
text: tag.text,
|
text: tag.text,
|
||||||
icon: tag.icon,
|
icon: tag.icon,
|
||||||
last_user: tag.last_user
|
last_user: tag.last_user,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -638,11 +685,11 @@ export class ControllerPlugin extends BaseControllerPlugin {
|
|||||||
} else if (lastSeenContent) {
|
} else if (lastSeenContent) {
|
||||||
// For creation/modification events, check if content has actually changed
|
// For creation/modification events, check if content has actually changed
|
||||||
const contentUnchanged =
|
const contentUnchanged =
|
||||||
lastSeenContent.position[0] === tag_data.position[0] &&
|
lastSeenContent.position[0] === tag_data.position[0]
|
||||||
lastSeenContent.position[1] === tag_data.position[1] &&
|
&& lastSeenContent.position[1] === tag_data.position[1]
|
||||||
lastSeenContent.text === tag_data.text &&
|
&& lastSeenContent.text === tag_data.text
|
||||||
JSON.stringify(lastSeenContent.icon) === JSON.stringify(tag_data.icon) &&
|
&& JSON.stringify(lastSeenContent.icon) === JSON.stringify(tag_data.icon)
|
||||||
lastSeenContent.last_user === tag_data.last_user;
|
&& lastSeenContent.last_user === tag_data.last_user;
|
||||||
|
|
||||||
if (contentUnchanged) {
|
if (contentUnchanged) {
|
||||||
return; // Skip if content hasn't changed
|
return; // Skip if content hasn't changed
|
||||||
@@ -652,7 +699,7 @@ export class ControllerPlugin extends BaseControllerPlugin {
|
|||||||
// Add instance_id to the tag data for storage
|
// Add instance_id to the tag data for storage
|
||||||
const enrichedTagData = {
|
const enrichedTagData = {
|
||||||
...tag_data,
|
...tag_data,
|
||||||
instance_id
|
instance_id,
|
||||||
};
|
};
|
||||||
|
|
||||||
// Immediately update last seen content to improve deduplication before save completes
|
// Immediately update last seen content to improve deduplication before save completes
|
||||||
@@ -663,7 +710,7 @@ export class ControllerPlugin extends BaseControllerPlugin {
|
|||||||
position: tag_data.position,
|
position: tag_data.position,
|
||||||
text: tag_data.text,
|
text: tag_data.text,
|
||||||
icon: tag_data.icon,
|
icon: tag_data.icon,
|
||||||
last_user: tag_data.last_user
|
last_user: tag_data.last_user,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -678,7 +725,7 @@ export class ControllerPlugin extends BaseControllerPlugin {
|
|||||||
// Send live update to connected web clients
|
// Send live update to connected web clients
|
||||||
const updateEvent = new ChartTagDataEvent(instance_id, tag_data);
|
const updateEvent = new ChartTagDataEvent(instance_id, tag_data);
|
||||||
|
|
||||||
// Broadcast to web clients (overriding the formal src/dst routing)
|
// Broadcast to web clients
|
||||||
this.controller.sendTo(new lib.Address(lib.Address.broadcast, lib.Address.control), updateEvent);
|
this.controller.sendTo(new lib.Address(lib.Address.broadcast, lib.Address.control), updateEvent);
|
||||||
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
@@ -716,7 +763,7 @@ export class ControllerPlugin extends BaseControllerPlugin {
|
|||||||
chunk
|
chunk
|
||||||
);
|
);
|
||||||
|
|
||||||
// Broadcast to web clients (overriding the formal src/dst routing)
|
// Broadcast to web clients
|
||||||
this.controller.sendTo(new lib.Address(lib.Address.broadcast, lib.Address.control), updateEvent);
|
this.controller.sendTo(new lib.Address(lib.Address.broadcast, lib.Address.control), updateEvent);
|
||||||
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
@@ -737,10 +784,10 @@ export class ControllerPlugin extends BaseControllerPlugin {
|
|||||||
try {
|
try {
|
||||||
const tileData = await fs.readFile(tilePath);
|
const tileData = await fs.readFile(tilePath);
|
||||||
|
|
||||||
const base64Data = tileData.toString('base64');
|
const base64Data = tileData.toString("base64");
|
||||||
|
|
||||||
return {
|
return {
|
||||||
tile_data: base64Data
|
tile_data: base64Data,
|
||||||
};
|
};
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
this.logger.error(`Error reading tile file: ${err}`);
|
this.logger.error(`Error reading tile file: ${err}`);
|
||||||
@@ -759,8 +806,8 @@ export class ControllerPlugin extends BaseControllerPlugin {
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const content = await fs.readFile(filePath, 'utf-8');
|
const content = await fs.readFile(filePath, "utf-8");
|
||||||
const lines = content.trim().split('\n').filter(line => line.trim());
|
const lines = content.trim().split("\n").filter(line => line.trim());
|
||||||
|
|
||||||
const chartTags: ChartTagData[] = [];
|
const chartTags: ChartTagData[] = [];
|
||||||
for (const line of lines) {
|
for (const line of lines) {
|
||||||
@@ -852,7 +899,7 @@ export class ControllerPlugin extends BaseControllerPlugin {
|
|||||||
buffersToWrite = this.encodeSet(tileKey, recipe_data.start_tick ?? 0, px, py, recipe_data.recipe);
|
buffersToWrite = this.encodeSet(tileKey, recipe_data.start_tick ?? 0, px, py, recipe_data.recipe);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (buffersToWrite.length === 0) return;
|
if (buffersToWrite.length === 0) { return; }
|
||||||
|
|
||||||
if (!this.recipeSavingQueue.has(tileKey)) {
|
if (!this.recipeSavingQueue.has(tileKey)) {
|
||||||
this.recipeSavingQueue.set(tileKey, []);
|
this.recipeSavingQueue.set(tileKey, []);
|
||||||
|
|||||||
@@ -86,7 +86,7 @@ export class InstancePlugin extends BaseInstancePlugin {
|
|||||||
chart
|
chart
|
||||||
));
|
));
|
||||||
|
|
||||||
return Promise.all(TileDataEvents.map(event => this.instance.sendTo("controller", event)));
|
TileDataEvents.map(event => this.instance.sendTo("controller", event));
|
||||||
}
|
}
|
||||||
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
@@ -96,7 +96,7 @@ export class InstancePlugin extends BaseInstancePlugin {
|
|||||||
|
|
||||||
async handleChartTagDataFromLua(data: ChartTagDataIpc) {
|
async handleChartTagDataFromLua(data: ChartTagDataIpc) {
|
||||||
// Validate the chart tag data
|
// Validate the chart tag data
|
||||||
if (!data || typeof data.tag_number !== 'number') {
|
if (!data || typeof data.tag_number !== "number") {
|
||||||
this.logger.error("Invalid chart tag data received");
|
this.logger.error("Invalid chart tag data received");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -108,14 +108,14 @@ export class InstancePlugin extends BaseInstancePlugin {
|
|||||||
);
|
);
|
||||||
|
|
||||||
// Send to controller
|
// Send to controller
|
||||||
return this.instance.sendTo("controller", chartTagEvent);
|
this.instance.sendTo("controller", chartTagEvent);
|
||||||
}
|
}
|
||||||
|
|
||||||
async handleRecipeDataFromLua(data: RecipeDataIpc) {
|
async handleRecipeDataFromLua(data: RecipeDataIpc) {
|
||||||
try {
|
try {
|
||||||
if (!data) {
|
if (!data) {
|
||||||
this.logger.error("Invalid recipe data received")
|
this.logger.error("Invalid recipe data received");
|
||||||
return
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const recipeData: RecipeData = {
|
const recipeData: RecipeData = {
|
||||||
@@ -133,8 +133,7 @@ export class InstancePlugin extends BaseInstancePlugin {
|
|||||||
recipeData
|
recipeData
|
||||||
);
|
);
|
||||||
|
|
||||||
return this.instance.sendTo("controller", event);
|
this.instance.sendTo("controller", event);
|
||||||
|
|
||||||
} catch (err: unknown) {
|
} catch (err: unknown) {
|
||||||
this.logger.error(`Failed to process recipe data from Lua: ${err}`);
|
this.logger.error(`Failed to process recipe data from Lua: ${err}`);
|
||||||
}
|
}
|
||||||
|
|||||||
+299
-80
@@ -1,7 +1,7 @@
|
|||||||
import * as zlib from "zlib";
|
import * as zlib from "zlib";
|
||||||
|
|
||||||
// Environment detection
|
// Environment detection
|
||||||
const isNode = typeof Buffer !== 'undefined' && typeof process !== 'undefined' && process.versions?.node;
|
const isNode = typeof Buffer !== "undefined" && typeof process !== "undefined" && process.versions?.node;
|
||||||
|
|
||||||
// Cross-platform type for binary data
|
// Cross-platform type for binary data
|
||||||
type BinaryData = Buffer | Uint8Array;
|
type BinaryData = Buffer | Uint8Array;
|
||||||
@@ -49,15 +49,28 @@ async function inflateData(data: BinaryData): Promise<Buffer | Uint8Array> {
|
|||||||
const { promisify } = await import("util");
|
const { promisify } = await import("util");
|
||||||
const inflateAsync = promisify(zlib.inflate);
|
const inflateAsync = promisify(zlib.inflate);
|
||||||
return inflateAsync(data as Buffer);
|
return inflateAsync(data as Buffer);
|
||||||
} else {
|
|
||||||
// Browser environment - use sync version (it's actually async-friendly due to polyfill)
|
|
||||||
const buffer = data instanceof Buffer ? data : Buffer.from(data);
|
|
||||||
return zlib.inflateSync(buffer);
|
|
||||||
}
|
}
|
||||||
|
// Browser environment - use promisified inflate
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
try {
|
||||||
|
const buffer = data instanceof Buffer ? data : Buffer.from(data);
|
||||||
|
zlib.inflate(buffer, (err, result) => {
|
||||||
|
if (err) {
|
||||||
|
reject(err);
|
||||||
|
} else {
|
||||||
|
resolve(result);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
reject(err);
|
||||||
|
}
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Convert RGB565 to RGB888 values using Factorio's exact method
|
* Convert RGB565 to RGB888 values using Factorio's exact method
|
||||||
|
* @param rgb565Value The RGB565 color value to convert
|
||||||
|
* @returns Tuple of RGB values [r, g, b]
|
||||||
*/
|
*/
|
||||||
export function rgb565ToRgb888(rgb565Value: number): [number, number, number] {
|
export function rgb565ToRgb888(rgb565Value: number): [number, number, number] {
|
||||||
// This matches ByteColor(uint16_t rgb5) constructor in Factorio source
|
// This matches ByteColor(uint16_t rgb5) constructor in Factorio source
|
||||||
@@ -69,6 +82,8 @@ export function rgb565ToRgb888(rgb565Value: number): [number, number, number] {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Render chunk data to get RGB565 pixel array
|
* Render chunk data to get RGB565 pixel array
|
||||||
|
* @param chunkData The compressed chunk data to render
|
||||||
|
* @returns RGB565 pixel array for 32x32 chunk
|
||||||
*/
|
*/
|
||||||
export async function renderChunkToPixels(chunkData: BinaryData): Promise<Uint16Array> {
|
export async function renderChunkToPixels(chunkData: BinaryData): Promise<Uint16Array> {
|
||||||
try {
|
try {
|
||||||
@@ -89,7 +104,6 @@ export async function renderChunkToPixels(chunkData: BinaryData): Promise<Uint16
|
|||||||
|
|
||||||
return pixels;
|
return pixels;
|
||||||
} catch (decompressError) {
|
} catch (decompressError) {
|
||||||
console.error(`Failed to decompress chunk data: ${decompressError}`);
|
|
||||||
// Return black pixels on error
|
// Return black pixels on error
|
||||||
return new Uint16Array(32 * 32);
|
return new Uint16Array(32 * 32);
|
||||||
}
|
}
|
||||||
@@ -97,6 +111,10 @@ export async function renderChunkToPixels(chunkData: BinaryData): Promise<Uint16
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Extract a 32x32 chunk area from a 256x256 tile
|
* Extract a 32x32 chunk area from a 256x256 tile
|
||||||
|
* @param tilePixels The full tile pixel data
|
||||||
|
* @param chunkX Chunk X coordinate within tile
|
||||||
|
* @param chunkY Chunk Y coordinate within tile
|
||||||
|
* @returns RGB565 pixel array for 32x32 chunk
|
||||||
*/
|
*/
|
||||||
export function extractChunkFromTile(tilePixels: Uint16Array, chunkX: number, chunkY: number): Uint16Array {
|
export function extractChunkFromTile(tilePixels: Uint16Array, chunkX: number, chunkY: number): Uint16Array {
|
||||||
const chunkPixels = new Uint16Array(32 * 32);
|
const chunkPixels = new Uint16Array(32 * 32);
|
||||||
@@ -117,6 +135,9 @@ export function extractChunkFromTile(tilePixels: Uint16Array, chunkX: number, ch
|
|||||||
/**
|
/**
|
||||||
* Render tile data to RGB565 pixel array (256x256)
|
* Render tile data to RGB565 pixel array (256x256)
|
||||||
* Supports rendering up to a specific tick for timelapse functionality
|
* Supports rendering up to a specific tick for timelapse functionality
|
||||||
|
* @param tileData The binary tile data to render
|
||||||
|
* @param maxTick Optional maximum tick to render up to
|
||||||
|
* @returns RGB565 pixel array for 256x256 tile
|
||||||
*/
|
*/
|
||||||
export async function renderTileToPixels(tileData: BinaryData, maxTick?: number): Promise<Uint16Array> {
|
export async function renderTileToPixels(tileData: BinaryData, maxTick?: number): Promise<Uint16Array> {
|
||||||
const currentPixels = new Uint16Array(256 * 256); // 256x256 tile
|
const currentPixels = new Uint16Array(256 * 256); // 256x256 tile
|
||||||
@@ -131,9 +152,44 @@ export async function renderTileToPixels(tileData: BinaryData, maxTick?: number)
|
|||||||
offset += 1;
|
offset += 1;
|
||||||
|
|
||||||
if (type === 1) { // Chunk
|
if (type === 1) { // Chunk
|
||||||
if (offset + 7 > tileData.length) {
|
const chunkResult = await processChunkData(
|
||||||
|
tileData, offset, currentPixels, maxTick
|
||||||
|
);
|
||||||
|
if (!chunkResult.success) {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
offset = chunkResult.newOffset;
|
||||||
|
} else if (type === 2) { // Pixels
|
||||||
|
const pixelResult = processPixelData(tileData, offset, currentPixels, maxTick);
|
||||||
|
if (!pixelResult.success) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
offset = pixelResult.newOffset;
|
||||||
|
} else {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return currentPixels;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Process chunk data during tile rendering
|
||||||
|
* @param tileData The binary tile data being processed
|
||||||
|
* @param offset Current offset in the tile data
|
||||||
|
* @param currentPixels The pixel array to update
|
||||||
|
* @param maxTick Optional maximum tick to render up to
|
||||||
|
* @returns Processing result with success status and new offset
|
||||||
|
*/
|
||||||
|
async function processChunkData(
|
||||||
|
tileData: BinaryData,
|
||||||
|
offset: number,
|
||||||
|
currentPixels: Uint16Array,
|
||||||
|
maxTick?: number
|
||||||
|
): Promise<{ success: boolean; newOffset: number }> {
|
||||||
|
if (offset + 7 > tileData.length) {
|
||||||
|
return { success: false, newOffset: offset };
|
||||||
|
}
|
||||||
|
|
||||||
const tick = readUInt32BE(tileData, offset) * 60; // Convert back to actual tick
|
const tick = readUInt32BE(tileData, offset) * 60; // Convert back to actual tick
|
||||||
offset += 4;
|
offset += 4;
|
||||||
@@ -145,7 +201,7 @@ export async function renderTileToPixels(tileData: BinaryData, maxTick?: number)
|
|||||||
const length = readUInt16BE(tileData, offset);
|
const length = readUInt16BE(tileData, offset);
|
||||||
offset += 2;
|
offset += 2;
|
||||||
offset += length; // Skip chunk data
|
offset += length; // Skip chunk data
|
||||||
continue;
|
return { success: true, newOffset: offset };
|
||||||
}
|
}
|
||||||
|
|
||||||
const chunkCoordsByte = readUInt8(tileData, offset);
|
const chunkCoordsByte = readUInt8(tileData, offset);
|
||||||
@@ -154,7 +210,7 @@ export async function renderTileToPixels(tileData: BinaryData, maxTick?: number)
|
|||||||
offset += 2;
|
offset += 2;
|
||||||
|
|
||||||
if (offset + length > tileData.length) {
|
if (offset + length > tileData.length) {
|
||||||
break;
|
return { success: false, newOffset: offset };
|
||||||
}
|
}
|
||||||
|
|
||||||
const chunkX = chunkCoordsByte >> 4;
|
const chunkX = chunkCoordsByte >> 4;
|
||||||
@@ -165,23 +221,30 @@ export async function renderTileToPixels(tileData: BinaryData, maxTick?: number)
|
|||||||
const chunkPixels = await renderChunkToPixels(chunkData);
|
const chunkPixels = await renderChunkToPixels(chunkData);
|
||||||
|
|
||||||
// Update current pixel state
|
// Update current pixel state
|
||||||
for (let y = 0; y < 32; y++) {
|
updateTilePixelsWithChunk(currentPixels, chunkPixels, chunkX, chunkY);
|
||||||
for (let x = 0; x < 32; x++) {
|
|
||||||
const chunkIndex = y * 32 + x;
|
|
||||||
const tileX = chunkX * 32 + x;
|
|
||||||
const tileY = chunkY * 32 + y;
|
|
||||||
const tileIndex = tileY * 256 + tileX;
|
|
||||||
currentPixels[tileIndex] = chunkPixels[chunkIndex];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (decompressError) {
|
} catch (decompressError) {
|
||||||
console.error(`Failed to decompress chunk data: ${decompressError}`);
|
// Continue processing other chunks on error
|
||||||
}
|
}
|
||||||
|
|
||||||
offset += length;
|
return { success: true, newOffset: offset + length };
|
||||||
} else if (type === 2) { // Pixels
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Process pixel data during tile rendering
|
||||||
|
* @param tileData The binary tile data being processed
|
||||||
|
* @param offset Current offset in the tile data
|
||||||
|
* @param currentPixels The pixel array to update
|
||||||
|
* @param maxTick Optional maximum tick to render up to
|
||||||
|
* @returns Processing result with success status and new offset
|
||||||
|
*/
|
||||||
|
function processPixelData(
|
||||||
|
tileData: BinaryData,
|
||||||
|
offset: number,
|
||||||
|
currentPixels: Uint16Array,
|
||||||
|
maxTick?: number
|
||||||
|
): { success: boolean; newOffset: number } {
|
||||||
if (offset + 6 > tileData.length) {
|
if (offset + 6 > tileData.length) {
|
||||||
break;
|
return { success: false, newOffset: offset };
|
||||||
}
|
}
|
||||||
|
|
||||||
const tick = readUInt32BE(tileData, offset) * 60; // Convert back to actual tick
|
const tick = readUInt32BE(tileData, offset) * 60; // Convert back to actual tick
|
||||||
@@ -195,13 +258,12 @@ export async function renderTileToPixels(tileData: BinaryData, maxTick?: number)
|
|||||||
|
|
||||||
const expectedDataLength = pixelCount * 2; // x,y per pixel
|
const expectedDataLength = pixelCount * 2; // x,y per pixel
|
||||||
if (offset + expectedDataLength > tileData.length) {
|
if (offset + expectedDataLength > tileData.length) {
|
||||||
break;
|
return { success: false, newOffset: offset };
|
||||||
}
|
}
|
||||||
|
|
||||||
// Skip if beyond target tick
|
// Skip if beyond target tick
|
||||||
if (maxTick !== undefined && tick > maxTick) {
|
if (maxTick !== undefined && tick > maxTick) {
|
||||||
offset += expectedDataLength;
|
return { success: true, newOffset: offset + expectedDataLength };
|
||||||
continue;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
for (let i = 0; i < pixelCount; i++) {
|
for (let i = 0; i < pixelCount; i++) {
|
||||||
@@ -213,18 +275,38 @@ export async function renderTileToPixels(tileData: BinaryData, maxTick?: number)
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
offset += expectedDataLength;
|
return { success: true, newOffset: offset + expectedDataLength };
|
||||||
} else {
|
}
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return currentPixels;
|
/**
|
||||||
|
* Update tile pixels with chunk data
|
||||||
|
* @param currentPixels The tile pixel array to update
|
||||||
|
* @param chunkPixels The chunk pixel data to apply
|
||||||
|
* @param chunkX Chunk X coordinate within tile
|
||||||
|
* @param chunkY Chunk Y coordinate within tile
|
||||||
|
*/
|
||||||
|
function updateTilePixelsWithChunk(
|
||||||
|
currentPixels: Uint16Array,
|
||||||
|
chunkPixels: Uint16Array,
|
||||||
|
chunkX: number,
|
||||||
|
chunkY: number
|
||||||
|
): void {
|
||||||
|
for (let y = 0; y < 32; y++) {
|
||||||
|
for (let x = 0; x < 32; x++) {
|
||||||
|
const chunkIndex = y * 32 + x;
|
||||||
|
const tileX = chunkX * 32 + x;
|
||||||
|
const tileY = chunkY * 32 + y;
|
||||||
|
const tileIndex = tileY * 256 + tileX;
|
||||||
|
currentPixels[tileIndex] = chunkPixels[chunkIndex];
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Convert RGB565 pixel array to RGBA pixel data for canvas rendering
|
* Convert RGB565 pixel array to RGBA pixel data for canvas rendering
|
||||||
* Returns Uint8ClampedArray that can be used to create ImageData in browser
|
* Returns Uint8ClampedArray that can be used to create ImageData in browser
|
||||||
|
* @param pixels The RGB565 pixel array to convert
|
||||||
|
* @returns RGBA pixel data as Uint8ClampedArray
|
||||||
*/
|
*/
|
||||||
export function pixelsToRGBA(pixels: Uint16Array): Uint8ClampedArray {
|
export function pixelsToRGBA(pixels: Uint16Array): Uint8ClampedArray {
|
||||||
const imageData = new Uint8ClampedArray(256 * 256 * 4);
|
const imageData = new Uint8ClampedArray(256 * 256 * 4);
|
||||||
@@ -245,10 +327,12 @@ export function pixelsToRGBA(pixels: Uint16Array): Uint8ClampedArray {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Convert RGB565 pixel array to ImageData for canvas rendering (browser only)
|
* Convert RGB565 pixel array to ImageData for canvas rendering (browser only)
|
||||||
|
* @param pixels The RGB565 pixel array to convert
|
||||||
|
* @returns ImageData object for canvas rendering
|
||||||
*/
|
*/
|
||||||
export function pixelsToImageData(pixels: Uint16Array): any {
|
export function pixelsToImageData(pixels: Uint16Array): any {
|
||||||
if (typeof (globalThis as any).ImageData === 'undefined') {
|
if (typeof (globalThis as any).ImageData === "undefined") {
|
||||||
throw new Error('ImageData is not available in this environment. Use pixelsToRGBA() instead.');
|
throw new Error("ImageData is not available in this environment. Use pixelsToRGBA() instead.");
|
||||||
}
|
}
|
||||||
const rgbaData = pixelsToRGBA(pixels);
|
const rgbaData = pixelsToRGBA(pixels);
|
||||||
return new (globalThis as any).ImageData(rgbaData, 256, 256);
|
return new (globalThis as any).ImageData(rgbaData, 256, 256);
|
||||||
@@ -256,6 +340,8 @@ export function pixelsToImageData(pixels: Uint16Array): any {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Parse tile data and extract all available ticks for timelapse functionality
|
* Parse tile data and extract all available ticks for timelapse functionality
|
||||||
|
* @param tileData The binary tile data to parse
|
||||||
|
* @returns Array of available ticks sorted in ascending order
|
||||||
*/
|
*/
|
||||||
export function extractAvailableTicks(tileData: BinaryData): number[] {
|
export function extractAvailableTicks(tileData: BinaryData): number[] {
|
||||||
const ticks = new Set<number>();
|
const ticks = new Set<number>();
|
||||||
@@ -347,6 +433,8 @@ export interface ParsedTileData {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Parse tile data into structured change records for efficient timelapse navigation
|
* Parse tile data into structured change records for efficient timelapse navigation
|
||||||
|
* @param tileData The binary tile data to parse
|
||||||
|
* @returns Parsed tile data with chunks, pixel changes, and all ticks
|
||||||
*/
|
*/
|
||||||
export function parseTileData(tileData: BinaryData): ParsedTileData {
|
export function parseTileData(tileData: BinaryData): ParsedTileData {
|
||||||
const chunks: ChunkRecord[] = [];
|
const chunks: ChunkRecord[] = [];
|
||||||
@@ -363,9 +451,46 @@ export function parseTileData(tileData: BinaryData): ParsedTileData {
|
|||||||
offset += 1;
|
offset += 1;
|
||||||
|
|
||||||
if (type === 1) { // Chunk
|
if (type === 1) { // Chunk
|
||||||
if (offset + 7 > tileData.length) {
|
const result = parseChunkRecord(tileData, offset, chunks, ticks);
|
||||||
|
if (!result.success) {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
offset = result.newOffset;
|
||||||
|
} else if (type === 2) { // Pixels
|
||||||
|
const result = parsePixelChangeRecord(tileData, offset, pixelChanges, ticks);
|
||||||
|
if (!result.success) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
offset = result.newOffset;
|
||||||
|
} else {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
chunks,
|
||||||
|
pixelChanges,
|
||||||
|
allTicks: Array.from(ticks).sort((a, b) => a - b),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parse chunk record from tile data
|
||||||
|
* @param tileData The binary tile data being processed
|
||||||
|
* @param offset Current offset in the tile data
|
||||||
|
* @param chunks Array to add the parsed chunk to
|
||||||
|
* @param ticks Set to add the chunk tick to
|
||||||
|
* @returns Processing result with success status and new offset
|
||||||
|
*/
|
||||||
|
function parseChunkRecord(
|
||||||
|
tileData: BinaryData,
|
||||||
|
offset: number,
|
||||||
|
chunks: ChunkRecord[],
|
||||||
|
ticks: Set<number>
|
||||||
|
): { success: boolean; newOffset: number } {
|
||||||
|
if (offset + 7 > tileData.length) {
|
||||||
|
return { success: false, newOffset: offset };
|
||||||
|
}
|
||||||
|
|
||||||
const tick = readUInt32BE(tileData, offset) * 60; // Convert back to actual tick
|
const tick = readUInt32BE(tileData, offset) * 60; // Convert back to actual tick
|
||||||
ticks.add(tick);
|
ticks.add(tick);
|
||||||
@@ -377,7 +502,7 @@ export function parseTileData(tileData: BinaryData): ParsedTileData {
|
|||||||
offset += 2;
|
offset += 2;
|
||||||
|
|
||||||
if (offset + length > tileData.length) {
|
if (offset + length > tileData.length) {
|
||||||
break;
|
return { success: false, newOffset: offset };
|
||||||
}
|
}
|
||||||
|
|
||||||
const chunkX = chunkCoordsByte >> 4;
|
const chunkX = chunkCoordsByte >> 4;
|
||||||
@@ -388,13 +513,28 @@ export function parseTileData(tileData: BinaryData): ParsedTileData {
|
|||||||
tick,
|
tick,
|
||||||
chunkX,
|
chunkX,
|
||||||
chunkY,
|
chunkY,
|
||||||
data
|
data,
|
||||||
});
|
});
|
||||||
|
|
||||||
offset += length;
|
return { success: true, newOffset: offset + length };
|
||||||
} else if (type === 2) { // Pixels
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parse pixel change record from tile data
|
||||||
|
* @param tileData The binary tile data being processed
|
||||||
|
* @param offset Current offset in the tile data
|
||||||
|
* @param pixelChanges Array to add the parsed pixel changes to
|
||||||
|
* @param ticks Set to add the pixel change tick to
|
||||||
|
* @returns Processing result with success status and new offset
|
||||||
|
*/
|
||||||
|
function parsePixelChangeRecord(
|
||||||
|
tileData: BinaryData,
|
||||||
|
offset: number,
|
||||||
|
pixelChanges: PixelChangeRecord[],
|
||||||
|
ticks: Set<number>
|
||||||
|
): { success: boolean; newOffset: number } {
|
||||||
if (offset + 6 > tileData.length) {
|
if (offset + 6 > tileData.length) {
|
||||||
break;
|
return { success: false, newOffset: offset };
|
||||||
}
|
}
|
||||||
|
|
||||||
const tick = readUInt32BE(tileData, offset) * 60; // Convert back to actual tick
|
const tick = readUInt32BE(tileData, offset) * 60; // Convert back to actual tick
|
||||||
@@ -409,7 +549,7 @@ export function parseTileData(tileData: BinaryData): ParsedTileData {
|
|||||||
|
|
||||||
const expectedDataLength = pixelCount * 2;
|
const expectedDataLength = pixelCount * 2;
|
||||||
if (offset + expectedDataLength > tileData.length) {
|
if (offset + expectedDataLength > tileData.length) {
|
||||||
break;
|
return { success: false, newOffset: offset };
|
||||||
}
|
}
|
||||||
|
|
||||||
const changes: PixelChange[] = [];
|
const changes: PixelChange[] = [];
|
||||||
@@ -421,43 +561,27 @@ export function parseTileData(tileData: BinaryData): ParsedTileData {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pixelChanges.push({ tick, changes });
|
pixelChanges.push({ tick, changes });
|
||||||
offset += expectedDataLength;
|
return { success: true, newOffset: offset + expectedDataLength };
|
||||||
} else {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
chunks,
|
|
||||||
pixelChanges,
|
|
||||||
allTicks: Array.from(ticks).sort((a, b) => a - b)
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Apply chunk data to RGB565 pixel array
|
* Apply chunk data to RGB565 pixel array
|
||||||
|
* @param pixels The tile pixel array to update
|
||||||
|
* @param chunkRecord The chunk record to apply
|
||||||
*/
|
*/
|
||||||
export async function applyChunkToPixels(pixels: Uint16Array, chunkRecord: ChunkRecord): Promise<void> {
|
export async function applyChunkToPixels(pixels: Uint16Array, chunkRecord: ChunkRecord): Promise<void> {
|
||||||
try {
|
try {
|
||||||
const chunkPixels = await renderChunkToPixels(chunkRecord.data);
|
const chunkPixels = await renderChunkToPixels(chunkRecord.data);
|
||||||
|
updateTilePixelsWithChunk(pixels, chunkPixels, chunkRecord.chunkX, chunkRecord.chunkY);
|
||||||
// Update tile pixels with chunk data
|
|
||||||
for (let y = 0; y < 32; y++) {
|
|
||||||
for (let x = 0; x < 32; x++) {
|
|
||||||
const chunkIndex = y * 32 + x;
|
|
||||||
const tileX = chunkRecord.chunkX * 32 + x;
|
|
||||||
const tileY = chunkRecord.chunkY * 32 + y;
|
|
||||||
const tileIndex = tileY * 256 + tileX;
|
|
||||||
pixels[tileIndex] = chunkPixels[chunkIndex];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error(`Failed to apply chunk ${chunkRecord.chunkX},${chunkRecord.chunkY}:`, err);
|
// Error applying chunk - continue without this chunk
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Clear chunk area to black (for rewinding past chunk creation)
|
* Clear chunk area to black (for rewinding past chunk creation)
|
||||||
|
* @param pixels The tile pixel array to update
|
||||||
|
* @param chunkRecord The chunk record to clear
|
||||||
*/
|
*/
|
||||||
export function clearChunkInPixels(pixels: Uint16Array, chunkRecord: ChunkRecord): void {
|
export function clearChunkInPixels(pixels: Uint16Array, chunkRecord: ChunkRecord): void {
|
||||||
for (let y = 0; y < 32; y++) {
|
for (let y = 0; y < 32; y++) {
|
||||||
@@ -472,6 +596,8 @@ export function clearChunkInPixels(pixels: Uint16Array, chunkRecord: ChunkRecord
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Apply pixel changes to RGB565 pixel array (forward direction)
|
* Apply pixel changes to RGB565 pixel array (forward direction)
|
||||||
|
* @param pixels The tile pixel array to update
|
||||||
|
* @param changes Array of pixel changes to apply
|
||||||
*/
|
*/
|
||||||
export function applyPixelChanges(pixels: Uint16Array, changes: PixelChange[]): void {
|
export function applyPixelChanges(pixels: Uint16Array, changes: PixelChange[]): void {
|
||||||
for (const change of changes) {
|
for (const change of changes) {
|
||||||
@@ -482,6 +608,8 @@ export function applyPixelChanges(pixels: Uint16Array, changes: PixelChange[]):
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Revert pixel changes from RGB565 pixel array (backward direction)
|
* Revert pixel changes from RGB565 pixel array (backward direction)
|
||||||
|
* @param pixels The tile pixel array to update
|
||||||
|
* @param changes Array of pixel changes to revert
|
||||||
*/
|
*/
|
||||||
export function revertPixelChanges(pixels: Uint16Array, changes: PixelChange[]): void {
|
export function revertPixelChanges(pixels: Uint16Array, changes: PixelChange[]): void {
|
||||||
for (const change of changes) {
|
for (const change of changes) {
|
||||||
@@ -493,6 +621,10 @@ export function revertPixelChanges(pixels: Uint16Array, changes: PixelChange[]):
|
|||||||
/**
|
/**
|
||||||
* Render tile data incrementally from one tick to another
|
* Render tile data incrementally from one tick to another
|
||||||
* Much more efficient than re-rendering from scratch
|
* Much more efficient than re-rendering from scratch
|
||||||
|
* @param parsedData The parsed tile data
|
||||||
|
* @param currentPixels The current pixel state
|
||||||
|
* @param fromTick The starting tick
|
||||||
|
* @param toTick The target tick
|
||||||
*/
|
*/
|
||||||
export async function renderTileIncremental(
|
export async function renderTileIncremental(
|
||||||
parsedData: ParsedTileData,
|
parsedData: ParsedTileData,
|
||||||
@@ -509,8 +641,27 @@ export async function renderTileIncremental(
|
|||||||
const forward = toTick > fromTick;
|
const forward = toTick > fromTick;
|
||||||
|
|
||||||
if (forward) {
|
if (forward) {
|
||||||
// Apply changes forward from fromTick to toTick
|
await applyChangesForward(chunks, pixelChanges, currentPixels, fromTick, toTick);
|
||||||
|
} else {
|
||||||
|
await applyChangesBackward(chunks, pixelChanges, currentPixels, fromTick, toTick);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Apply changes in forward direction
|
||||||
|
* @param chunks Array of chunk records to process
|
||||||
|
* @param pixelChanges Array of pixel change records to process
|
||||||
|
* @param currentPixels The pixel array to update
|
||||||
|
* @param fromTick The starting tick
|
||||||
|
* @param toTick The target tick
|
||||||
|
*/
|
||||||
|
async function applyChangesForward(
|
||||||
|
chunks: ChunkRecord[],
|
||||||
|
pixelChanges: PixelChangeRecord[],
|
||||||
|
currentPixels: Uint16Array,
|
||||||
|
fromTick: number,
|
||||||
|
toTick: number
|
||||||
|
): Promise<void> {
|
||||||
// Apply chunks that occur in this range
|
// Apply chunks that occur in this range
|
||||||
for (const chunk of chunks) {
|
for (const chunk of chunks) {
|
||||||
if (chunk.tick > fromTick && chunk.tick <= toTick) {
|
if (chunk.tick > fromTick && chunk.tick <= toTick) {
|
||||||
@@ -524,9 +675,23 @@ export async function renderTileIncremental(
|
|||||||
applyPixelChanges(currentPixels, record.changes);
|
applyPixelChanges(currentPixels, record.changes);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
}
|
||||||
// Revert changes backward from fromTick to toTick
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Apply changes in backward direction
|
||||||
|
* @param chunks Array of chunk records to process
|
||||||
|
* @param pixelChanges Array of pixel change records to process
|
||||||
|
* @param currentPixels The pixel array to update
|
||||||
|
* @param fromTick The starting tick
|
||||||
|
* @param toTick The target tick
|
||||||
|
*/
|
||||||
|
async function applyChangesBackward(
|
||||||
|
chunks: ChunkRecord[],
|
||||||
|
pixelChanges: PixelChangeRecord[],
|
||||||
|
currentPixels: Uint16Array,
|
||||||
|
fromTick: number,
|
||||||
|
toTick: number
|
||||||
|
): Promise<void> {
|
||||||
// Revert pixel changes in reverse order
|
// Revert pixel changes in reverse order
|
||||||
for (let i = pixelChanges.length - 1; i >= 0; i--) {
|
for (let i = pixelChanges.length - 1; i >= 0; i--) {
|
||||||
const record = pixelChanges[i];
|
const record = pixelChanges[i];
|
||||||
@@ -542,7 +707,6 @@ export async function renderTileIncremental(
|
|||||||
clearChunkInPixels(currentPixels, chunk);
|
clearChunkInPixels(currentPixels, chunk);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -562,7 +726,12 @@ export interface ParsedRecipeTile {
|
|||||||
* @param targetTick Target tick for filtering (null = latest state)
|
* @param targetTick Target tick for filtering (null = latest state)
|
||||||
* @returns Parsed recipe data with ticks and active recipes
|
* @returns Parsed recipe data with ticks and active recipes
|
||||||
*/
|
*/
|
||||||
export function parseRecipeTileBinary(tileX: number, tileY: number, buf: BinaryData, targetTick: number | null): ParsedRecipeTile {
|
export function parseRecipeTileBinary(
|
||||||
|
tileX: number,
|
||||||
|
tileY: number,
|
||||||
|
buf: BinaryData,
|
||||||
|
targetTick: number | null
|
||||||
|
): ParsedRecipeTile {
|
||||||
const ticks: number[] = [];
|
const ticks: number[] = [];
|
||||||
const dict = new Map<number, string>();
|
const dict = new Map<number, string>();
|
||||||
const active = new Map<string, string>();
|
const active = new Map<string, string>();
|
||||||
@@ -574,6 +743,34 @@ export function parseRecipeTileBinary(tileX: number, tileY: number, buf: BinaryD
|
|||||||
offset += 1;
|
offset += 1;
|
||||||
|
|
||||||
if (type === 0) { // Dictionary entry
|
if (type === 0) { // Dictionary entry
|
||||||
|
const result = parseDictionaryEntry(buf, offset, dict);
|
||||||
|
offset = result.newOffset;
|
||||||
|
} else if (type === 1 || type === 2) { // Set recipe (1) or Clear recipe (2)
|
||||||
|
const result = parseRecipeEntry(
|
||||||
|
buf, offset, type, tileX, tileY, ticks, active, targetSec, dict
|
||||||
|
);
|
||||||
|
offset = result.newOffset;
|
||||||
|
} else {
|
||||||
|
// Unknown recipe record type - stop parsing
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { ticks, activeRecipes: active, dictionary: dict };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parse dictionary entry from recipe tile
|
||||||
|
* @param buf The binary recipe tile data
|
||||||
|
* @param offset Current offset in the data
|
||||||
|
* @param dict Dictionary map to add the entry to
|
||||||
|
* @returns Processing result with new offset
|
||||||
|
*/
|
||||||
|
function parseDictionaryEntry(
|
||||||
|
buf: BinaryData,
|
||||||
|
offset: number,
|
||||||
|
dict: Map<number, string>
|
||||||
|
): { newOffset: number } {
|
||||||
const idx = readUInt16BE(buf, offset);
|
const idx = readUInt16BE(buf, offset);
|
||||||
offset += 2;
|
offset += 2;
|
||||||
const len = readUInt8(buf, offset);
|
const len = readUInt8(buf, offset);
|
||||||
@@ -584,13 +781,39 @@ export function parseRecipeTileBinary(tileX: number, tileY: number, buf: BinaryD
|
|||||||
// Convert to string using cross-platform method
|
// Convert to string using cross-platform method
|
||||||
let recipeName: string;
|
let recipeName: string;
|
||||||
if (isNode && nameBytes instanceof Buffer) {
|
if (isNode && nameBytes instanceof Buffer) {
|
||||||
recipeName = nameBytes.toString('utf-8');
|
recipeName = nameBytes.toString("utf-8");
|
||||||
} else {
|
} else {
|
||||||
recipeName = new TextDecoder().decode(nameBytes as Uint8Array);
|
recipeName = new TextDecoder().decode(nameBytes as Uint8Array);
|
||||||
}
|
}
|
||||||
|
|
||||||
dict.set(idx, recipeName);
|
dict.set(idx, recipeName);
|
||||||
} else if (type === 1 || type === 2) { // Set recipe (1) or Clear recipe (2)
|
return { newOffset: offset };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parse recipe entry from recipe tile
|
||||||
|
* @param buf The binary recipe tile data
|
||||||
|
* @param offset Current offset in the data
|
||||||
|
* @param type Entry type (1 = set recipe, 2 = clear recipe)
|
||||||
|
* @param tileX Tile X coordinate for world position calculation
|
||||||
|
* @param tileY Tile Y coordinate for world position calculation
|
||||||
|
* @param ticks Array to add the entry tick to
|
||||||
|
* @param active Map of active recipes to update
|
||||||
|
* @param targetSec Target second for filtering
|
||||||
|
* @param dict Dictionary map for recipe name lookup
|
||||||
|
* @returns Processing result with new offset
|
||||||
|
*/
|
||||||
|
function parseRecipeEntry(
|
||||||
|
buf: BinaryData,
|
||||||
|
offset: number,
|
||||||
|
type: number,
|
||||||
|
tileX: number,
|
||||||
|
tileY: number,
|
||||||
|
ticks: number[],
|
||||||
|
active: Map<string, string>,
|
||||||
|
targetSec: number,
|
||||||
|
dict: Map<number, string>
|
||||||
|
): { newOffset: number } {
|
||||||
const sec = readUInt32BE(buf, offset);
|
const sec = readUInt32BE(buf, offset);
|
||||||
offset += 4;
|
offset += 4;
|
||||||
const px = readUInt8(buf, offset);
|
const px = readUInt8(buf, offset);
|
||||||
@@ -608,9 +831,8 @@ export function parseRecipeTileBinary(tileX: number, tileY: number, buf: BinaryD
|
|||||||
ticks.push(tickVal);
|
ticks.push(tickVal);
|
||||||
|
|
||||||
if (sec > targetSec) {
|
if (sec > targetSec) {
|
||||||
// Future to target time – we can skip rest if file is chronological
|
// Future to target time – skip without applying
|
||||||
// but to be safe just continue without applying
|
return { newOffset: offset };
|
||||||
continue;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const worldX = tileX * 256 + px;
|
const worldX = tileX * 256 + px;
|
||||||
@@ -619,15 +841,12 @@ export function parseRecipeTileBinary(tileX: number, tileY: number, buf: BinaryD
|
|||||||
|
|
||||||
if (type === 1 && idx !== undefined) {
|
if (type === 1 && idx !== undefined) {
|
||||||
const name = dict.get(idx);
|
const name = dict.get(idx);
|
||||||
if (name) active.set(posKey, name);
|
if (name) {
|
||||||
|
active.set(posKey, name);
|
||||||
|
}
|
||||||
} else if (type === 2) {
|
} else if (type === 2) {
|
||||||
active.delete(posKey);
|
active.delete(posKey);
|
||||||
}
|
}
|
||||||
} else {
|
|
||||||
console.warn("Unknown recipe record type", type);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return { ticks, activeRecipes: active, dictionary: dict };
|
return { newOffset: offset };
|
||||||
}
|
}
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -38,9 +38,7 @@ export default function MinimapPage() {
|
|||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const loadSurfaceForceData = async () => {
|
const loadSurfaceForceData = async () => {
|
||||||
try {
|
|
||||||
const response = await fetch(`${window.location.origin}/api/minimap/surfaces`);
|
const response = await fetch(`${window.location.origin}/api/minimap/surfaces`);
|
||||||
console.log(response);
|
|
||||||
const data = await response.json();
|
const data = await response.json();
|
||||||
setSurfaceForceData(data);
|
setSurfaceForceData(data);
|
||||||
|
|
||||||
@@ -51,9 +49,6 @@ export default function MinimapPage() {
|
|||||||
if (data.forces.length > 0 && !selectedForce) {
|
if (data.forces.length > 0 && !selectedForce) {
|
||||||
setSelectedForce(data.forces.includes("player") ? "player" : data.forces[0]);
|
setSelectedForce(data.forces.includes("player") ? "player" : data.forces[0]);
|
||||||
}
|
}
|
||||||
} catch (err) {
|
|
||||||
console.error("Failed to load surface/force data:", err);
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// Use default map bounds centered around origin
|
// Use default map bounds centered around origin
|
||||||
@@ -78,7 +73,7 @@ export default function MinimapPage() {
|
|||||||
loading={loading}
|
loading={loading}
|
||||||
options={[...instances.values()].map(instance => ({
|
options={[...instances.values()].map(instance => ({
|
||||||
value: instance.id,
|
value: instance.id,
|
||||||
label: instance.name
|
label: instance.name,
|
||||||
}))}
|
}))}
|
||||||
/>
|
/>
|
||||||
<Select
|
<Select
|
||||||
@@ -112,7 +107,7 @@ export default function MinimapPage() {
|
|||||||
<div
|
<div
|
||||||
style={{
|
style={{
|
||||||
height: "700px",
|
height: "700px",
|
||||||
width: "100%"
|
width: "100%",
|
||||||
}}
|
}}
|
||||||
className="minimap-container"
|
className="minimap-container"
|
||||||
>
|
>
|
||||||
@@ -137,6 +132,7 @@ export default function MinimapPage() {
|
|||||||
>
|
>
|
||||||
{/* Chart layer with surface and force data */}
|
{/* Chart layer with surface and force data */}
|
||||||
<TileLayer
|
<TileLayer
|
||||||
|
// eslint-disable-next-line max-len
|
||||||
url={`${window.location.origin}/api/minimap/chart/${selectedInstance}/${selectedSurface}/${selectedForce}/{z}/{x}/{y}.png?refresh=${refreshTiles}`}
|
url={`${window.location.origin}/api/minimap/chart/${selectedInstance}/${selectedSurface}/${selectedForce}/{z}/{x}/{y}.png?refresh=${refreshTiles}`}
|
||||||
maxNativeZoom={10}
|
maxNativeZoom={10}
|
||||||
minNativeZoom={10}
|
minNativeZoom={10}
|
||||||
|
|||||||
Reference in new issue
Block a user