mirror of
https://github.com/clusterio/clusterio.git
synced 2026-11-23 00:13:13 +09:00
Extend minimap components to allow external use
This commit is contained in:
1 parent
73ab8fc4f3
commit
b0fd90d273
4 files changed
+473
-250
No files matched your search
@@ -1,4 +1,4 @@
|
|||||||
import React, { useState, useEffect, useContext, useRef, useCallback } from "react";
|
import React, { useState, useEffect, useContext, useRef, useCallback, useMemo } from "react";
|
||||||
import {
|
import {
|
||||||
Row,
|
Row,
|
||||||
Col,
|
Col,
|
||||||
@@ -16,20 +16,17 @@ import {
|
|||||||
import { EllipsisOutlined } from "@ant-design/icons";
|
import { EllipsisOutlined } from "@ant-design/icons";
|
||||||
import { ControlContext, useInstances, useItemMetadata, useAccount, notify } from "@clusterio/web_ui";
|
import { ControlContext, useInstances, useItemMetadata, useAccount, notify } from "@clusterio/web_ui";
|
||||||
import {
|
import {
|
||||||
GetRawTileRequest,
|
|
||||||
GetChartTagsRequest,
|
|
||||||
GetRawRecipeTileRequest,
|
|
||||||
GetPlayerPathRequest,
|
|
||||||
ClearMinimapSurfaceDataRequest,
|
ClearMinimapSurfaceDataRequest,
|
||||||
ClearMinimapDataRequest,
|
ClearMinimapDataRequest,
|
||||||
type TileDataEvent,
|
type TileDataEvent,
|
||||||
type ChartTagData,
|
|
||||||
type ChartTagDataEvent,
|
type ChartTagDataEvent,
|
||||||
type SignalID,
|
type SignalID,
|
||||||
type RecipeDataEvent,
|
type RecipeDataEvent,
|
||||||
type PlayerPositionEvent,
|
type PlayerPositionEvent,
|
||||||
type PlayerData,
|
type PlayerData,
|
||||||
} from "../messages";
|
} from "../messages";
|
||||||
|
import type { ChartTagDataWithInstance, MinimapDataSource } from "./minimap-data-source";
|
||||||
|
import { SingleInstanceDataSource } from "./dataSources/SingleInstanceDataSource";
|
||||||
import * as zlib from "zlib";
|
import * as zlib from "zlib";
|
||||||
import {
|
import {
|
||||||
renderTileToPixels,
|
renderTileToPixels,
|
||||||
@@ -45,8 +42,11 @@ import { parseAndDeduplicatePlayerPositions, type ParsedPlayerPos } from "../uti
|
|||||||
|
|
||||||
const { Text } = Typography;
|
const { Text } = Typography;
|
||||||
|
|
||||||
interface ChartTagDataWithInstance extends ChartTagData {
|
interface CanvasMinimapPageProps {
|
||||||
instance_id: number;
|
dataSource?: MinimapDataSource;
|
||||||
|
title?: string;
|
||||||
|
showInstanceSelector?: boolean;
|
||||||
|
showManageActions?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface MergedChartTag {
|
interface MergedChartTag {
|
||||||
@@ -62,6 +62,10 @@ interface MergedChartTag {
|
|||||||
instance_id: number;
|
instance_id: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface ParsedPlayerPosWithInstance extends ParsedPlayerPos {
|
||||||
|
instanceId: number;
|
||||||
|
}
|
||||||
|
|
||||||
interface SurfaceForceData {
|
interface SurfaceForceData {
|
||||||
surfaces: string[];
|
surfaces: string[];
|
||||||
forces: string[];
|
forces: string[];
|
||||||
@@ -128,7 +132,13 @@ async function chartDataToImageData(chartData: string): Promise<ImageData> {
|
|||||||
return new ImageData(imageData, 32, 32);
|
return new ImageData(imageData, 32, 32);
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function CanvasMinimapPage() {
|
/* eslint-disable complexity */
|
||||||
|
export default function CanvasMinimapPage({
|
||||||
|
dataSource: externalDataSource,
|
||||||
|
title = "Factorio Instance Minimap",
|
||||||
|
showInstanceSelector = true,
|
||||||
|
showManageActions = true,
|
||||||
|
}: CanvasMinimapPageProps) {
|
||||||
// UI-related states (these need React re-renders)
|
// UI-related states (these need React re-renders)
|
||||||
const [instances] = useInstances();
|
const [instances] = useInstances();
|
||||||
const [selectedInstance, setSelectedInstance] = useState<number | null>(null);
|
const [selectedInstance, setSelectedInstance] = useState<number | null>(null);
|
||||||
@@ -153,6 +163,7 @@ export default function CanvasMinimapPage() {
|
|||||||
const [showRecipes, setShowRecipes] = useState(true);
|
const [showRecipes, setShowRecipes] = useState(true);
|
||||||
const [rawChartTags, setRawChartTags] = useState<ChartTagDataWithInstance[]>([]);
|
const [rawChartTags, setRawChartTags] = useState<ChartTagDataWithInstance[]>([]);
|
||||||
const [mergedChartTags, setMergedChartTags] = useState<MergedChartTag[]>([]);
|
const [mergedChartTags, setMergedChartTags] = useState<MergedChartTag[]>([]);
|
||||||
|
const [activeViewKey, setActiveViewKey] = useState(0);
|
||||||
|
|
||||||
// Player position states
|
// Player position states
|
||||||
const [showPlayerPositions, setShowPlayerPositions] = useState(true);
|
const [showPlayerPositions, setShowPlayerPositions] = useState(true);
|
||||||
@@ -184,13 +195,13 @@ export default function CanvasMinimapPage() {
|
|||||||
const tileStateCache = useRef<Map<string, TileState>>(new Map());
|
const tileStateCache = useRef<Map<string, TileState>>(new Map());
|
||||||
const chunkCache = useRef<Map<string, ImageData>>(new Map());
|
const chunkCache = useRef<Map<string, ImageData>>(new Map());
|
||||||
const loadingTiles = useRef<Map<string, Promise<ImageData | null>>>(new Map());
|
const loadingTiles = useRef<Map<string, Promise<ImageData | null>>>(new Map());
|
||||||
const playerPathBufRef = useRef<Uint8Array | null>(null);
|
const playerPathBufRef = useRef<Map<number, Uint8Array> | null>(null);
|
||||||
|
|
||||||
// Cache for recipes currently active
|
// Cache for recipes currently active
|
||||||
const recipeCache = useRef<Map<string, string>>(new Map());
|
const recipeCache = useRef<Map<string, string>>(new Map());
|
||||||
|
|
||||||
// Cache for deduplicated player positions
|
// Cache for deduplicated player positions
|
||||||
const deduplicatedPlayerPositions = useRef<Map<number, ParsedPlayerPos[]>>(new Map());
|
const deduplicatedPlayerPositions = useRef<Map<number, ParsedPlayerPosWithInstance[]>>(new Map());
|
||||||
|
|
||||||
// Animation frame ref
|
// Animation frame ref
|
||||||
const animationFrameRef = useRef<number>();
|
const animationFrameRef = useRef<number>();
|
||||||
@@ -279,6 +290,7 @@ export default function CanvasMinimapPage() {
|
|||||||
selectedInstance: null as number | null,
|
selectedInstance: null as number | null,
|
||||||
selectedSurface: "nauvis",
|
selectedSurface: "nauvis",
|
||||||
selectedForce: "player",
|
selectedForce: "player",
|
||||||
|
isReady: false,
|
||||||
isTimelapseMode: false,
|
isTimelapseMode: false,
|
||||||
currentTick: null as number | null,
|
currentTick: null as number | null,
|
||||||
availableTicks: [] as number[],
|
availableTicks: [] as number[],
|
||||||
@@ -291,6 +303,22 @@ export default function CanvasMinimapPage() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const control = useContext(ControlContext);
|
const control = useContext(ControlContext);
|
||||||
|
const dataSource = useMemo(
|
||||||
|
() => externalDataSource ?? new SingleInstanceDataSource(control),
|
||||||
|
[control, externalDataSource],
|
||||||
|
);
|
||||||
|
const isReady = dataSource.isReady();
|
||||||
|
const controlsDisabled = showInstanceSelector ? !selectedInstance : !isReady;
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (dataSource.setInstance) {
|
||||||
|
dataSource.setInstance(selectedInstance);
|
||||||
|
}
|
||||||
|
}, [dataSource, selectedInstance]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
dataSource.setSurfaceForce(selectedSurface, selectedForce);
|
||||||
|
}, [dataSource, selectedSurface, selectedForce]);
|
||||||
const itemMetadata = useItemMetadata();
|
const itemMetadata = useItemMetadata();
|
||||||
|
|
||||||
// Keep latest metadata in a ref so long-living callbacks (render loop) can access fresh data
|
// Keep latest metadata in a ref so long-living callbacks (render loop) can access fresh data
|
||||||
@@ -472,6 +500,7 @@ export default function CanvasMinimapPage() {
|
|||||||
selectedInstance,
|
selectedInstance,
|
||||||
selectedSurface,
|
selectedSurface,
|
||||||
selectedForce,
|
selectedForce,
|
||||||
|
isReady,
|
||||||
isTimelapseMode,
|
isTimelapseMode,
|
||||||
currentTick,
|
currentTick,
|
||||||
availableTicks,
|
availableTicks,
|
||||||
@@ -495,6 +524,8 @@ export default function CanvasMinimapPage() {
|
|||||||
mergedChartTags,
|
mergedChartTags,
|
||||||
chartTagTimestamps,
|
chartTagTimestamps,
|
||||||
playerPositions,
|
playerPositions,
|
||||||
|
dataSource,
|
||||||
|
isReady,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
// Define pixel-perfect zoom levels to eliminate seaming issues
|
// Define pixel-perfect zoom levels to eliminate seaming issues
|
||||||
@@ -588,29 +619,16 @@ export default function CanvasMinimapPage() {
|
|||||||
|
|
||||||
for (let tileY = topTile; tileY <= bottomTile; tileY++) {
|
for (let tileY = topTile; tileY <= bottomTile; tileY++) {
|
||||||
for (let tileX = leftTile; tileX <= rightTile; tileX++) {
|
for (let tileX = leftTile; tileX <= rightTile; tileX++) {
|
||||||
const response = await control.send(new GetRawTileRequest(
|
|
||||||
selectedInstance!,
|
|
||||||
selectedSurface,
|
|
||||||
selectedForce,
|
|
||||||
tileX,
|
|
||||||
tileY
|
|
||||||
));
|
|
||||||
|
|
||||||
tilesChecked += 1;
|
tilesChecked += 1;
|
||||||
|
const tileData = await dataSource.getTileData(tileX, tileY, null);
|
||||||
|
if (!tileData) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
if (response.tile_data) {
|
const ticks = extractAvailableTicks(tileData);
|
||||||
const binaryString = atob(response.tile_data);
|
if (ticks.length > 0) {
|
||||||
const tileData = new Uint8Array(binaryString.length);
|
tilesWithData += 1;
|
||||||
for (let i = 0; i < binaryString.length; i += 1) {
|
ticks.forEach(tick => allTicks.add(tick));
|
||||||
tileData[i] = binaryString.charCodeAt(i);
|
|
||||||
}
|
|
||||||
|
|
||||||
const ticks = extractAvailableTicks(tileData);
|
|
||||||
|
|
||||||
if (ticks.length > 0) {
|
|
||||||
tilesWithData += 1;
|
|
||||||
ticks.forEach(tick => allTicks.add(tick));
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -654,24 +672,14 @@ export default function CanvasMinimapPage() {
|
|||||||
|
|
||||||
for (let tileY = topTile; tileY <= bottomTile; tileY++) {
|
for (let tileY = topTile; tileY <= bottomTile; tileY++) {
|
||||||
for (let tileX = leftTile; tileX <= rightTile; tileX++) {
|
for (let tileX = leftTile; tileX <= rightTile; tileX++) {
|
||||||
const recipeResp = await control.send(new GetRawRecipeTileRequest(
|
const recipeData = await dataSource.getRecipeTileData(tileX, tileY, null);
|
||||||
selectedInstance!,
|
if (!recipeData) {
|
||||||
selectedSurface,
|
continue;
|
||||||
selectedForce,
|
}
|
||||||
tileX,
|
const parsed = parseRecipeTileBinary(tileX, tileY, recipeData, null);
|
||||||
tileY
|
for (const t of parsed.ticks) {
|
||||||
));
|
allTicks.add(t);
|
||||||
if (recipeResp.recipe_tile) {
|
recipeTicksAdded += 1;
|
||||||
const binStr = atob(recipeResp.recipe_tile);
|
|
||||||
const buf = new Uint8Array(binStr.length);
|
|
||||||
for (let i = 0; i < binStr.length; i += 1) {
|
|
||||||
buf[i] = binStr.charCodeAt(i);
|
|
||||||
}
|
|
||||||
const parsed = parseRecipeTileBinary(tileX, tileY, buf, null);
|
|
||||||
for (const t of parsed.ticks) {
|
|
||||||
allTicks.add(t);
|
|
||||||
recipeTicksAdded += 1;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -679,47 +687,47 @@ export default function CanvasMinimapPage() {
|
|||||||
return recipeTicksAdded;
|
return recipeTicksAdded;
|
||||||
};
|
};
|
||||||
|
|
||||||
const fetchPlayerPathBuffer = async (): Promise<Uint8Array | null> => {
|
const fetchPlayerPaths = async (): Promise<boolean> => {
|
||||||
if (!selectedInstance) { return null; }
|
if (!dataSource.isReady()) { return false; }
|
||||||
if (playerPathBufRef.current) { return playerPathBufRef.current; }
|
if (playerPathBufRef.current) { return true; }
|
||||||
try {
|
try {
|
||||||
const resp = await control.send(new GetPlayerPathRequest(
|
const responses = await dataSource.getPlayerPaths();
|
||||||
selectedInstance,
|
if (responses.length === 0) { return false; }
|
||||||
selectedSurface,
|
const bufferMap = new Map<number, Uint8Array>();
|
||||||
));
|
const deduplicatedTimelines = new Map<number, ParsedPlayerPosWithInstance[]>();
|
||||||
if (!resp.positions) { return null; }
|
const instanceOffset = 1_000_000;
|
||||||
const binStr = atob(resp.positions);
|
for (const response of responses) {
|
||||||
const buf = new Uint8Array(binStr.length);
|
bufferMap.set(response.instanceId, response.data);
|
||||||
for (let i = 0; i < binStr.length; i++) {
|
const perInstance = parseAndDeduplicatePlayerPositions(response.data);
|
||||||
buf[i] = binStr.charCodeAt(i);
|
for (const [playerId, timeline] of perInstance) {
|
||||||
|
const key = response.instanceId * instanceOffset + playerId;
|
||||||
|
deduplicatedTimelines.set(
|
||||||
|
key,
|
||||||
|
timeline.map(pos => ({ ...pos, instanceId: response.instanceId })),
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
playerPathBufRef.current = buf;
|
playerPathBufRef.current = bufferMap;
|
||||||
|
|
||||||
// Use the utility function to parse and deduplicate player positions
|
|
||||||
const deduplicatedTimelines = parseAndDeduplicatePlayerPositions(buf);
|
|
||||||
|
|
||||||
// Store deduplicated data in cache
|
|
||||||
deduplicatedPlayerPositions.current = deduplicatedTimelines;
|
deduplicatedPlayerPositions.current = deduplicatedTimelines;
|
||||||
|
return true;
|
||||||
return buf;
|
} catch (_e) {
|
||||||
} catch (_e) { return null; }
|
return false;
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const loadPlayerTimestamps = async (
|
const loadPlayerTimestamps = async (
|
||||||
allTicks: Set<number>
|
allTicks: Set<number>
|
||||||
): Promise<number> => {
|
): Promise<number> => {
|
||||||
if (!selectedInstance) { return 0; }
|
|
||||||
let added = 0;
|
let added = 0;
|
||||||
const buf = await fetchPlayerPathBuffer();
|
const loaded = await fetchPlayerPaths();
|
||||||
if (buf) {
|
if (!loaded) { return 0; }
|
||||||
// Extract ticks from deduplicated positions instead of raw buffer
|
// Extract ticks from deduplicated positions instead of raw buffer
|
||||||
for (const timeline of deduplicatedPlayerPositions.current.values()) {
|
for (const timeline of deduplicatedPlayerPositions.current.values()) {
|
||||||
for (const pos of timeline) {
|
for (const pos of timeline) {
|
||||||
const tick = pos.sec * 60;
|
const tick = pos.sec * 60;
|
||||||
if (!allTicks.has(tick)) {
|
if (!allTicks.has(tick)) {
|
||||||
allTicks.add(tick);
|
allTicks.add(tick);
|
||||||
added += 1;
|
added += 1;
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -728,7 +736,7 @@ export default function CanvasMinimapPage() {
|
|||||||
|
|
||||||
// Timelapse functions
|
// Timelapse functions
|
||||||
const loadAvailableTicks = async () => {
|
const loadAvailableTicks = async () => {
|
||||||
if (!selectedInstance) {
|
if (!dataSource.isReady()) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -767,7 +775,7 @@ export default function CanvasMinimapPage() {
|
|||||||
|
|
||||||
if (enabled) {
|
if (enabled) {
|
||||||
// Ensure chart tags are loaded before getting available ticks
|
// Ensure chart tags are loaded before getting available ticks
|
||||||
if (selectedInstance && selectedSurface && selectedForce) {
|
if (dataSource.isReady()) {
|
||||||
await loadExistingChartTags();
|
await loadExistingChartTags();
|
||||||
}
|
}
|
||||||
await loadAvailableTicks();
|
await loadAvailableTicks();
|
||||||
@@ -934,26 +942,20 @@ export default function CanvasMinimapPage() {
|
|||||||
|
|
||||||
// Set default instance when instances become available
|
// Set default instance when instances become available
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
if (!showInstanceSelector) { return; }
|
||||||
if (instances.size > 0 && !selectedInstance) {
|
if (instances.size > 0 && !selectedInstance) {
|
||||||
const firstInstance = instances.values().next().value;
|
const firstInstance = instances.values().next().value;
|
||||||
if (firstInstance) {
|
if (firstInstance) {
|
||||||
setSelectedInstance(firstInstance.id);
|
setSelectedInstance(firstInstance.id);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}, [instances, selectedInstance]);
|
}, [instances, selectedInstance, showInstanceSelector]);
|
||||||
|
|
||||||
// Load surface and force data on component mount
|
// Load surface and force data on component mount
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
loadSurfaceForceData();
|
loadSurfaceForceData();
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
// Keep the minimap subscription filters in sync with current selection
|
|
||||||
useEffect(() => {
|
|
||||||
const plugin = control.plugins.get("minimap") as import("./index").WebPlugin;
|
|
||||||
if (!plugin) { return; }
|
|
||||||
plugin.setInstanceSurfaceFilter(selectedInstance, selectedSurface || null);
|
|
||||||
}, [control, selectedInstance, selectedSurface]);
|
|
||||||
|
|
||||||
// Set up keyboard and mouse event listeners (one-time setup)
|
// Set up keyboard and mouse event listeners (one-time setup)
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const isTypingInInput = (): boolean => {
|
const isTypingInInput = (): boolean => {
|
||||||
@@ -1178,29 +1180,12 @@ export default function CanvasMinimapPage() {
|
|||||||
|
|
||||||
// Load existing chart tags from disk
|
// Load existing chart tags from disk
|
||||||
const loadExistingChartTags = async () => {
|
const loadExistingChartTags = async () => {
|
||||||
if (!selectedInstance || !selectedSurface || !selectedForce) {
|
if (!dataSource.isReady()) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const response = await control.send(new GetChartTagsRequest(
|
const existingTags = await dataSource.getChartTags();
|
||||||
selectedInstance,
|
setRawChartTags(existingTags);
|
||||||
selectedSurface,
|
|
||||||
selectedForce
|
|
||||||
));
|
|
||||||
|
|
||||||
if (response.chart_tags && response.chart_tags.length > 0) {
|
|
||||||
// Convert to ChartTagDataWithInstance format
|
|
||||||
const existingTags: ChartTagDataWithInstance[] = response.chart_tags.map((tag: ChartTagData) => ({
|
|
||||||
...tag,
|
|
||||||
instance_id: selectedInstance,
|
|
||||||
}));
|
|
||||||
|
|
||||||
// Replace existing tags with loaded ones
|
|
||||||
setRawChartTags(existingTags);
|
|
||||||
} else {
|
|
||||||
// Clear tags if no existing data
|
|
||||||
setRawChartTags([]);
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// Load a tile from the server using raw tile data
|
// Load a tile from the server using raw tile data
|
||||||
@@ -1208,8 +1193,8 @@ export default function CanvasMinimapPage() {
|
|||||||
// Get current state from ref
|
// Get current state from ref
|
||||||
const currentState = currentStateRef.current;
|
const currentState = currentStateRef.current;
|
||||||
|
|
||||||
// Early return if no instance is selected
|
// Early return if data source is not ready
|
||||||
if (!currentState.selectedInstance) {
|
if (!currentState.isReady) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1246,26 +1231,16 @@ export default function CanvasMinimapPage() {
|
|||||||
const loadPromise = (async () => {
|
const loadPromise = (async () => {
|
||||||
try {
|
try {
|
||||||
// Load the raw tile data from server
|
// Load the raw tile data from server
|
||||||
const response = await control.send(new GetRawTileRequest(
|
const tileData = await dataSource.getTileData(
|
||||||
currentState.selectedInstance!, // We already checked for null above
|
|
||||||
currentState.selectedSurface,
|
|
||||||
currentState.selectedForce,
|
|
||||||
tileX,
|
tileX,
|
||||||
tileY,
|
tileY,
|
||||||
currentState.isTimelapseMode ? currentState.currentTick || undefined : undefined
|
currentState.isTimelapseMode ? currentState.currentTick : null,
|
||||||
));
|
);
|
||||||
|
|
||||||
if (!response.tile_data) {
|
if (!tileData) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Decode base64 tile data
|
|
||||||
const binaryString = atob(response.tile_data);
|
|
||||||
const tileData = new Uint8Array(binaryString.length);
|
|
||||||
for (let i = 0; i < binaryString.length; i++) {
|
|
||||||
tileData[i] = binaryString.charCodeAt(i);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Parse the tile data into structured change records
|
// Parse the tile data into structured change records
|
||||||
const parsedData = parseTileData(tileData);
|
const parsedData = parseTileData(tileData);
|
||||||
|
|
||||||
@@ -1379,9 +1354,9 @@ export default function CanvasMinimapPage() {
|
|||||||
// Get current state from ref
|
// Get current state from ref
|
||||||
const currentState = currentStateRef.current;
|
const currentState = currentStateRef.current;
|
||||||
|
|
||||||
// Don't create virtual tiles if no instance is selected
|
// Don't create virtual tiles if data source is not ready
|
||||||
if (!currentState.selectedInstance) {
|
if (!currentState.isReady) {
|
||||||
throw new Error("Cannot create virtual tile: no instance selected");
|
throw new Error("Cannot create virtual tile: data source not ready");
|
||||||
}
|
}
|
||||||
|
|
||||||
const tileKey = `${tileX},${tileY}`;
|
const tileKey = `${tileX},${tileY}`;
|
||||||
@@ -1567,13 +1542,13 @@ export default function CanvasMinimapPage() {
|
|||||||
ctx.fillRect(clippedX, clippedY, clippedWidth, clippedHeight);
|
ctx.fillRect(clippedX, clippedY, clippedWidth, clippedHeight);
|
||||||
|
|
||||||
// Start loading the tile in the background (but don't wait for it)
|
// Start loading the tile in the background (but don't wait for it)
|
||||||
// Only attempt to load if we have all required parameters
|
// Only attempt to load if data source is ready
|
||||||
if (currentState.selectedInstance && currentState.selectedSurface && currentState.selectedForce) {
|
if (currentState.isReady) {
|
||||||
getVirtualTile(tileX, tileY).then(() => {
|
getVirtualTile(tileX, tileY).then(() => {
|
||||||
// When tile loads, trigger a re-render
|
// When tile loads, trigger a re-render
|
||||||
// But only if we're still looking at the same area
|
// But only if we're still looking at the same area
|
||||||
const latestState = currentStateRef.current;
|
const latestState = currentStateRef.current;
|
||||||
if (latestState.selectedInstance && latestState.selectedSurface && latestState.selectedForce) {
|
if (latestState.isReady) {
|
||||||
// Use a small delay to batch multiple tile loads
|
// Use a small delay to batch multiple tile loads
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
if (animationFrameRef.current) {
|
if (animationFrameRef.current) {
|
||||||
@@ -1586,7 +1561,6 @@ export default function CanvasMinimapPage() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
// Render the canvas
|
// Render the canvas
|
||||||
// eslint-disable-next-line complexity
|
|
||||||
const renderCanvas = () => {
|
const renderCanvas = () => {
|
||||||
const canvas = canvasRef.current;
|
const canvas = canvasRef.current;
|
||||||
if (!canvas) { return; }
|
if (!canvas) { return; }
|
||||||
@@ -1594,8 +1568,8 @@ export default function CanvasMinimapPage() {
|
|||||||
// Get current state from ref to ensure consistency
|
// Get current state from ref to ensure consistency
|
||||||
const currentState = currentStateRef.current;
|
const currentState = currentStateRef.current;
|
||||||
|
|
||||||
// Early return if no instance selected
|
// Early return if data source not ready
|
||||||
if (!currentState.selectedInstance) {
|
if (!currentState.isReady) {
|
||||||
// Draw dark background and return
|
// Draw dark background and return
|
||||||
const ctx = canvas.getContext("2d") as CanvasRenderingContext2D;
|
const ctx = canvas.getContext("2d") as CanvasRenderingContext2D;
|
||||||
ctx.fillStyle = "#1a1a1a";
|
ctx.fillStyle = "#1a1a1a";
|
||||||
@@ -1616,6 +1590,15 @@ export default function CanvasMinimapPage() {
|
|||||||
// Calculate visible tiles using shared function
|
// Calculate visible tiles using shared function
|
||||||
const visibleTiles = calculateVisibleTiles();
|
const visibleTiles = calculateVisibleTiles();
|
||||||
if (!visibleTiles) { return; }
|
if (!visibleTiles) { return; }
|
||||||
|
const viewUpdate = dataSource.setActiveView({
|
||||||
|
worldLeft: visibleTiles.worldLeft,
|
||||||
|
worldTop: visibleTiles.worldTop,
|
||||||
|
worldRight: visibleTiles.worldRight,
|
||||||
|
worldBottom: visibleTiles.worldBottom,
|
||||||
|
});
|
||||||
|
if (viewUpdate.changed) {
|
||||||
|
setActiveViewKey(prev => prev + 1);
|
||||||
|
}
|
||||||
|
|
||||||
// Render all visible tiles
|
// Render all visible tiles
|
||||||
renderVisibleTiles(ctx, visibleTiles, currentState);
|
renderVisibleTiles(ctx, visibleTiles, currentState);
|
||||||
@@ -1815,7 +1798,7 @@ export default function CanvasMinimapPage() {
|
|||||||
|
|
||||||
// Ensure proper canvas sizing when instance selection changes
|
// Ensure proper canvas sizing when instance selection changes
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (selectedInstance) {
|
if (isReady) {
|
||||||
// Force a resize check when instance becomes available
|
// Force a resize check when instance becomes available
|
||||||
const canvas = canvasRef.current;
|
const canvas = canvasRef.current;
|
||||||
const container = containerRef.current;
|
const container = containerRef.current;
|
||||||
@@ -1825,11 +1808,11 @@ export default function CanvasMinimapPage() {
|
|||||||
canvas.height = rect.height;
|
canvas.height = rect.height;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}, [selectedInstance]);
|
}, [isReady]);
|
||||||
|
|
||||||
// Reset view when instance changes and snap to pixel-perfect zoom
|
// Reset view when instance changes and snap to pixel-perfect zoom
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (selectedInstance) {
|
if (isReady) {
|
||||||
// Reset to center view with default zoom when switching instances
|
// Reset to center view with default zoom when switching instances
|
||||||
updateViewState({
|
updateViewState({
|
||||||
centerX: 0,
|
centerX: 0,
|
||||||
@@ -1847,20 +1830,22 @@ export default function CanvasMinimapPage() {
|
|||||||
deduplicatedPlayerPositions.current.clear();
|
deduplicatedPlayerPositions.current.clear();
|
||||||
setPlayerPositions(new Map());
|
setPlayerPositions(new Map());
|
||||||
}
|
}
|
||||||
}, [selectedInstance]);
|
}, [isReady, selectedInstance, dataSource]);
|
||||||
|
|
||||||
// Clear player cache when surface changes
|
// Clear player cache when surface or active view changes
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (selectedSurface) {
|
if (!isReady) { return; }
|
||||||
playerPathBufRef.current = null;
|
playerPathBufRef.current = null;
|
||||||
deduplicatedPlayerPositions.current.clear();
|
deduplicatedPlayerPositions.current.clear();
|
||||||
setPlayerPositions(new Map());
|
setPlayerPositions(new Map());
|
||||||
|
if (isTimelapseMode && currentTick !== null) {
|
||||||
|
updatePlayerPositionsForTick(currentTick).catch(() => undefined);
|
||||||
}
|
}
|
||||||
}, [selectedSurface]);
|
}, [selectedSurface, activeViewKey, isReady, isTimelapseMode, currentTick]);
|
||||||
|
|
||||||
// Reload ticks when instance, surface, force changes or timelapse mode toggles
|
// Reload ticks when instance, surface, force changes or timelapse mode toggles
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (isTimelapseMode && selectedInstance && selectedSurface && selectedForce) {
|
if (isTimelapseMode && isReady) {
|
||||||
// Debounce the reload to avoid too many requests during navigation
|
// Debounce the reload to avoid too many requests during navigation
|
||||||
const timeoutId = setTimeout(async () => {
|
const timeoutId = setTimeout(async () => {
|
||||||
// Ensure chart tags are loaded before getting available ticks
|
// Ensure chart tags are loaded before getting available ticks
|
||||||
@@ -1871,18 +1856,18 @@ export default function CanvasMinimapPage() {
|
|||||||
return () => clearTimeout(timeoutId);
|
return () => clearTimeout(timeoutId);
|
||||||
}
|
}
|
||||||
return () => { };
|
return () => { };
|
||||||
}, [selectedInstance, selectedSurface, selectedForce, isTimelapseMode]);
|
}, [selectedSurface, selectedForce, isTimelapseMode, activeViewKey, isReady, dataSource]);
|
||||||
|
|
||||||
// Load existing chart tags when instance/surface/force selection changes
|
// Load existing chart tags when instance/surface/force selection changes
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (selectedInstance && selectedSurface && selectedForce) {
|
if (isReady) {
|
||||||
loadExistingChartTags();
|
loadExistingChartTags();
|
||||||
} else {
|
} else {
|
||||||
// Clear chart tags if no valid selection
|
// Clear chart tags if no valid selection
|
||||||
setRawChartTags([]);
|
setRawChartTags([]);
|
||||||
setPlayerPositions(new Map());
|
setPlayerPositions(new Map());
|
||||||
}
|
}
|
||||||
}, [selectedInstance, selectedSurface, selectedForce]);
|
}, [selectedSurface, selectedForce, activeViewKey, isReady, dataSource]);
|
||||||
|
|
||||||
// Snap current zoom level to nearest pixel-perfect level on mount
|
// Snap current zoom level to nearest pixel-perfect level on mount
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -1903,14 +1888,13 @@ export default function CanvasMinimapPage() {
|
|||||||
// Use the same ref state that the render function uses for consistency
|
// Use the same ref state that the render function uses for consistency
|
||||||
const currentState = currentStateRef.current;
|
const currentState = currentStateRef.current;
|
||||||
|
|
||||||
if (!currentState.selectedInstance || !currentState.showChartTags) {
|
if (!currentState.isReady || !currentState.showChartTags) {
|
||||||
return [];
|
return [];
|
||||||
}
|
}
|
||||||
|
|
||||||
return currentState.mergedChartTags.filter((tag: MergedChartTag) => {
|
return currentState.mergedChartTags.filter((tag: MergedChartTag) => {
|
||||||
// Filter by instance, surface, and force
|
// Filter by surface and force
|
||||||
if (tag.instance_id !== currentState.selectedInstance
|
if (tag.surface !== currentState.selectedSurface
|
||||||
|| tag.surface !== currentState.selectedSurface
|
|
||||||
|| tag.force !== currentState.selectedForce) {
|
|| tag.force !== currentState.selectedForce) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -1936,15 +1920,10 @@ export default function CanvasMinimapPage() {
|
|||||||
|
|
||||||
// Set up live chunk update listener (only in live mode)
|
// Set up live chunk update listener (only in live mode)
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const plugin = control.plugins.get("minimap") as import("./index").WebPlugin;
|
|
||||||
if (!plugin) {
|
|
||||||
return () => { };
|
|
||||||
}
|
|
||||||
|
|
||||||
const handleChunkUpdate = (event: TileDataEvent) => {
|
const handleChunkUpdate = (event: TileDataEvent) => {
|
||||||
const currentState = currentStateRef.current;
|
const currentState = currentStateRef.current;
|
||||||
// Only process updates for the currently selected instance/surface/force
|
// Only process updates for the current surface/force
|
||||||
if (event.instance_id === currentState.selectedInstance
|
if (currentState.isReady
|
||||||
&& event.surface === currentState.selectedSurface
|
&& event.surface === currentState.selectedSurface
|
||||||
&& event.force === currentState.selectedForce
|
&& event.force === currentState.selectedForce
|
||||||
&& !currentState.isTimelapseMode) {
|
&& !currentState.isTimelapseMode) {
|
||||||
@@ -1963,8 +1942,8 @@ export default function CanvasMinimapPage() {
|
|||||||
|
|
||||||
const handleChartTagUpdate = (event: ChartTagDataEvent) => {
|
const handleChartTagUpdate = (event: ChartTagDataEvent) => {
|
||||||
const currentState = currentStateRef.current;
|
const currentState = currentStateRef.current;
|
||||||
// Only process updates for the currently selected instance/surface/force
|
// Only process updates for the current surface/force
|
||||||
if (event.instance_id === currentState.selectedInstance
|
if (currentState.isReady
|
||||||
&& event.tag_data.surface === currentState.selectedSurface
|
&& event.tag_data.surface === currentState.selectedSurface
|
||||||
&& event.tag_data.force === currentState.selectedForce) {
|
&& event.tag_data.force === currentState.selectedForce) {
|
||||||
|
|
||||||
@@ -2001,9 +1980,8 @@ export default function CanvasMinimapPage() {
|
|||||||
// will supply historical positions instead.
|
// will supply historical positions instead.
|
||||||
if (currentState.isTimelapseMode) { return; }
|
if (currentState.isTimelapseMode) { return; }
|
||||||
|
|
||||||
// Only process updates for the currently selected instance/surface
|
// Only process updates for the current surface
|
||||||
if (event.instance_id === currentState.selectedInstance
|
if (currentState.isReady && event.player_data.surface === currentState.selectedSurface) {
|
||||||
&& event.player_data.surface === currentState.selectedSurface) {
|
|
||||||
setPlayerPositions(prevPositions => {
|
setPlayerPositions(prevPositions => {
|
||||||
const newPositions = new Map(prevPositions);
|
const newPositions = new Map(prevPositions);
|
||||||
const playerKey = `${event.player_data.player_name}_${event.instance_id}`;
|
const playerKey = `${event.player_data.player_name}_${event.instance_id}`;
|
||||||
@@ -2016,17 +1994,17 @@ export default function CanvasMinimapPage() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Subscribe to update events through the plugin
|
// Subscribe to update events through the data source
|
||||||
plugin.onTileUpdate(handleChunkUpdate);
|
const unsubTile = dataSource.onTileUpdate(handleChunkUpdate);
|
||||||
plugin.onChartTagUpdate(handleChartTagUpdate);
|
const unsubTags = dataSource.onChartTagUpdate(handleChartTagUpdate);
|
||||||
plugin.onPlayerPositionUpdate(handlePlayerPositionUpdate);
|
const unsubPlayers = dataSource.onPlayerPositionUpdate(handlePlayerPositionUpdate);
|
||||||
|
|
||||||
return () => {
|
return () => {
|
||||||
plugin.offTileUpdate(handleChunkUpdate);
|
unsubTile();
|
||||||
plugin.offChartTagUpdate(handleChartTagUpdate);
|
unsubTags();
|
||||||
plugin.offPlayerPositionUpdate(handlePlayerPositionUpdate);
|
unsubPlayers();
|
||||||
};
|
};
|
||||||
}, [updateChunk, control]);
|
}, [dataSource, updateChunk]);
|
||||||
|
|
||||||
// Helper to draw recipe icon (placeholder)
|
// Helper to draw recipe icon (placeholder)
|
||||||
type IconSpace = "screen" | "world"; // screen = constant pixel size, world = scales with zoom
|
type IconSpace = "screen" | "world"; // screen = constant pixel size, world = scales with zoom
|
||||||
@@ -2069,16 +2047,10 @@ export default function CanvasMinimapPage() {
|
|||||||
// Function to load recipe tile
|
// Function to load recipe tile
|
||||||
const loadRecipeTile = async (tileX: number, tileY: number) => {
|
const loadRecipeTile = async (tileX: number, tileY: number) => {
|
||||||
const cs = currentStateRef.current;
|
const cs = currentStateRef.current;
|
||||||
if (!cs.selectedInstance) { return; }
|
if (!cs.isReady) { return; }
|
||||||
const resp = await control.send(new GetRawRecipeTileRequest(
|
const recipeData = await dataSource.getRecipeTileData(tileX, tileY, cs.isTimelapseMode ? cs.currentTick : null);
|
||||||
cs.selectedInstance, cs.selectedSurface, cs.selectedForce, tileX, tileY
|
if (!recipeData) { return; }
|
||||||
));
|
const parsed = parseRecipeTileBinary(tileX, tileY, recipeData, cs.isTimelapseMode ? cs.currentTick : null);
|
||||||
if (!resp.recipe_tile) { return; }
|
|
||||||
const binStr = atob(resp.recipe_tile);
|
|
||||||
const buf = new Uint8Array(binStr.length);
|
|
||||||
for (let i = 0; i < binStr.length; i++) { buf[i] = binStr.charCodeAt(i); }
|
|
||||||
|
|
||||||
const parsed = parseRecipeTileBinary(tileX, tileY, buf, cs.isTimelapseMode ? cs.currentTick : null);
|
|
||||||
|
|
||||||
// Apply parsed active recipes to cache
|
// Apply parsed active recipes to cache
|
||||||
for (const [coord, recName] of parsed.activeRecipes) {
|
for (const [coord, recName] of parsed.activeRecipes) {
|
||||||
@@ -2087,12 +2059,11 @@ export default function CanvasMinimapPage() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
// Live recipe update handler
|
// Live recipe update handler
|
||||||
const handleRecipeUpdate = (event: RecipeDataEvent) => {
|
const handleRecipeUpdate = useCallback((event: RecipeDataEvent) => {
|
||||||
const cs = currentStateRef.current;
|
const cs = currentStateRef.current;
|
||||||
const isWrongInstance = event.instance_id !== cs.selectedInstance;
|
|
||||||
const isWrongSurface = event.recipe_data.surface !== cs.selectedSurface;
|
const isWrongSurface = event.recipe_data.surface !== cs.selectedSurface;
|
||||||
const isWrongForce = event.recipe_data.force !== cs.selectedForce;
|
const isWrongForce = event.recipe_data.force !== cs.selectedForce;
|
||||||
if (isWrongInstance || isWrongSurface || isWrongForce) {
|
if (!cs.isReady || isWrongSurface || isWrongForce) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
// Handle recipe end events: remove icon if recipe interval finished
|
// Handle recipe end events: remove icon if recipe interval finished
|
||||||
@@ -2110,22 +2081,14 @@ export default function CanvasMinimapPage() {
|
|||||||
iconKey = `item-${event.recipe_data.recipe ?? "unknown"}`;
|
iconKey = `item-${event.recipe_data.recipe ?? "unknown"}`;
|
||||||
}
|
}
|
||||||
recipeCache.current.set(key, iconKey);
|
recipeCache.current.set(key, iconKey);
|
||||||
};
|
}, []);
|
||||||
|
|
||||||
// Subscribe to updates (tile, tag, recipe) once plugin is available
|
// Subscribe to recipe updates
|
||||||
useEffect(() => {
|
useEffect(() => dataSource.onRecipeUpdate(handleRecipeUpdate), [dataSource, handleRecipeUpdate]);
|
||||||
const plugin = control.plugins.get("minimap") as import("./index").WebPlugin;
|
|
||||||
if (!plugin) {
|
|
||||||
return () => { };
|
|
||||||
}
|
|
||||||
|
|
||||||
plugin.onRecipeUpdate(handleRecipeUpdate);
|
|
||||||
return () => { plugin.offRecipeUpdate(handleRecipeUpdate); };
|
|
||||||
}, [control]);
|
|
||||||
|
|
||||||
// Reload recipe overlay when timeline tick changes
|
// Reload recipe overlay when timeline tick changes
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (isTimelapseMode && currentTick !== null && showRecipes) {
|
if (isTimelapseMode && currentTick !== null && showRecipes && isReady) {
|
||||||
// Clear existing icons
|
// Clear existing icons
|
||||||
recipeCache.current.clear();
|
recipeCache.current.clear();
|
||||||
|
|
||||||
@@ -2139,16 +2102,16 @@ export default function CanvasMinimapPage() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}, [currentTick, isTimelapseMode, showRecipes]);
|
}, [currentTick, isTimelapseMode, showRecipes, activeViewKey, isReady]);
|
||||||
|
|
||||||
const updatePlayerPositionsForTick = async (tick: number) => {
|
const updatePlayerPositionsForTick = async (tick: number) => {
|
||||||
const buf = await fetchPlayerPathBuffer();
|
const loaded = await fetchPlayerPaths();
|
||||||
if (!buf) { setPlayerPositions(new Map()); return; }
|
if (!loaded) { setPlayerPositions(new Map()); return; }
|
||||||
const secTarget = Math.floor(tick / 60);
|
const secTarget = Math.floor(tick / 60);
|
||||||
const parsed = parsePositionsAtTick(buf, secTarget);
|
const parsed = parsePositionsAtTick(secTarget);
|
||||||
const map = new Map<string, PlayerData>();
|
const map = new Map<string, PlayerData>();
|
||||||
for (const p of parsed) {
|
for (const p of parsed) {
|
||||||
map.set(`${p.name}_${selectedInstance ?? 0}`, {
|
map.set(`${p.name}_${p.instanceId}`, {
|
||||||
player_name: p.name,
|
player_name: p.name,
|
||||||
surface: selectedSurface,
|
surface: selectedSurface,
|
||||||
x: p.x,
|
x: p.x,
|
||||||
@@ -2161,13 +2124,13 @@ export default function CanvasMinimapPage() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
// Function to parse positions at a specific tick using deduplicated cache
|
// Function to parse positions at a specific tick using deduplicated cache
|
||||||
const parsePositionsAtTick = (buf: Uint8Array, targetSec: number): ParsedPlayerPos[] => {
|
const parsePositionsAtTick = (targetSec: number): ParsedPlayerPosWithInstance[] => {
|
||||||
// Use deduplicated cached data instead of parsing from scratch
|
// Use deduplicated cached data instead of parsing from scratch
|
||||||
const result: ParsedPlayerPos[] = [];
|
const result: ParsedPlayerPosWithInstance[] = [];
|
||||||
|
|
||||||
for (const timeline of deduplicatedPlayerPositions.current.values()) {
|
for (const timeline of deduplicatedPlayerPositions.current.values()) {
|
||||||
// Find the most recent position for this player at or before targetSec
|
// Find the most recent position for this player at or before targetSec
|
||||||
let mostRecentPos: ParsedPlayerPos | null = null;
|
let mostRecentPos: ParsedPlayerPosWithInstance | null = null;
|
||||||
|
|
||||||
for (const pos of timeline) {
|
for (const pos of timeline) {
|
||||||
if (pos.sec <= targetSec) {
|
if (pos.sec <= targetSec) {
|
||||||
@@ -2199,15 +2162,15 @@ export default function CanvasMinimapPage() {
|
|||||||
<Card
|
<Card
|
||||||
title={
|
title={
|
||||||
<Space>
|
<Space>
|
||||||
<span>Factorio Instance Minimap</span>
|
<span>{title}</span>
|
||||||
{selectedInstance && (
|
{showInstanceSelector && selectedInstance && (
|
||||||
<Text type="secondary" style={{ fontSize: "14px" }}>
|
<Text type="secondary" style={{ fontSize: "14px" }}>
|
||||||
• {instances.get(selectedInstance)?.name || "Unknown Instance"}
|
• {instances.get(selectedInstance)?.name || "Unknown Instance"}
|
||||||
</Text>
|
</Text>
|
||||||
)}
|
)}
|
||||||
</Space>
|
</Space>
|
||||||
}
|
}
|
||||||
extra={
|
extra={showManageActions ? (
|
||||||
<Space>
|
<Space>
|
||||||
<Button
|
<Button
|
||||||
size="small"
|
size="small"
|
||||||
@@ -2242,7 +2205,7 @@ export default function CanvasMinimapPage() {
|
|||||||
</Tooltip>
|
</Tooltip>
|
||||||
</Dropdown>
|
</Dropdown>
|
||||||
</Space>
|
</Space>
|
||||||
}
|
) : undefined}
|
||||||
styles={{
|
styles={{
|
||||||
header: { padding: "16px 24px" },
|
header: { padding: "16px 24px" },
|
||||||
body: { padding: "16px 24px" },
|
body: { padding: "16px 24px" },
|
||||||
@@ -2257,32 +2220,34 @@ export default function CanvasMinimapPage() {
|
|||||||
}}>
|
}}>
|
||||||
<Row gutter={[24, 16]}>
|
<Row gutter={[24, 16]}>
|
||||||
{/* Instance Selection */}
|
{/* Instance Selection */}
|
||||||
<Col xs={24} md={8}>
|
{showInstanceSelector && (
|
||||||
<Space direction="vertical" style={{ width: "100%" }} size="small">
|
<Col xs={24} md={8}>
|
||||||
<Text strong style={{ fontSize: "12px", color: "#666" }}>INSTANCE</Text>
|
<Space direction="vertical" style={{ width: "100%" }} size="small">
|
||||||
<Select
|
<Text strong style={{ fontSize: "12px", color: "#666" }}>INSTANCE</Text>
|
||||||
style={{ width: "100%" }}
|
<Select
|
||||||
placeholder="Select instance"
|
style={{ width: "100%" }}
|
||||||
value={selectedInstance}
|
placeholder="Select instance"
|
||||||
onChange={(value) => {
|
value={selectedInstance}
|
||||||
setSelectedInstance(value);
|
onChange={(value) => {
|
||||||
// Return focus to canvas after selection
|
setSelectedInstance(value);
|
||||||
setTimeout(() => {
|
// Return focus to canvas after selection
|
||||||
if (canvasRef.current) {
|
setTimeout(() => {
|
||||||
canvasRef.current.focus();
|
if (canvasRef.current) {
|
||||||
}
|
canvasRef.current.focus();
|
||||||
}, 100);
|
}
|
||||||
}}
|
}, 100);
|
||||||
options={[...instances.values()].map(instance => ({
|
}}
|
||||||
value: instance.id,
|
options={[...instances.values()].map(instance => ({
|
||||||
label: instance.name,
|
value: instance.id,
|
||||||
}))}
|
label: instance.name,
|
||||||
suffixIcon={selectedInstance
|
}))}
|
||||||
? undefined
|
suffixIcon={selectedInstance
|
||||||
: <span style={{ color: "#ff4d4f" }}>Required</span>}
|
? undefined
|
||||||
/>
|
: <span style={{ color: "#ff4d4f" }}>Required</span>}
|
||||||
</Space>
|
/>
|
||||||
</Col>
|
</Space>
|
||||||
|
</Col>
|
||||||
|
)}
|
||||||
|
|
||||||
{/* Surface & Force Selection */}
|
{/* Surface & Force Selection */}
|
||||||
<Col xs={24} md={8}>
|
<Col xs={24} md={8}>
|
||||||
@@ -2302,7 +2267,7 @@ export default function CanvasMinimapPage() {
|
|||||||
}
|
}
|
||||||
}, 100);
|
}, 100);
|
||||||
}}
|
}}
|
||||||
disabled={!selectedInstance}
|
disabled={controlsDisabled}
|
||||||
>
|
>
|
||||||
{surfaceForceData.surfaces.map(surface => (
|
{surfaceForceData.surfaces.map(surface => (
|
||||||
<Select.Option key={surface} value={surface}>
|
<Select.Option key={surface} value={surface}>
|
||||||
@@ -2323,7 +2288,7 @@ export default function CanvasMinimapPage() {
|
|||||||
}
|
}
|
||||||
}, 100);
|
}, 100);
|
||||||
}}
|
}}
|
||||||
disabled={!selectedInstance}
|
disabled={controlsDisabled}
|
||||||
>
|
>
|
||||||
{surfaceForceData.forces.map(force => (
|
{surfaceForceData.forces.map(force => (
|
||||||
<Select.Option key={force} value={force}>
|
<Select.Option key={force} value={force}>
|
||||||
@@ -2360,7 +2325,7 @@ export default function CanvasMinimapPage() {
|
|||||||
onChange={(checked) => {
|
onChange={(checked) => {
|
||||||
toggleTimelapseMode(checked);
|
toggleTimelapseMode(checked);
|
||||||
}}
|
}}
|
||||||
disabled={!selectedInstance}
|
disabled={controlsDisabled}
|
||||||
/>
|
/>
|
||||||
<Text
|
<Text
|
||||||
type="secondary"
|
type="secondary"
|
||||||
@@ -2390,7 +2355,7 @@ export default function CanvasMinimapPage() {
|
|||||||
onChange={(checked) => {
|
onChange={(checked) => {
|
||||||
setShowChartTags(checked);
|
setShowChartTags(checked);
|
||||||
}}
|
}}
|
||||||
disabled={!selectedInstance}
|
disabled={controlsDisabled}
|
||||||
/>
|
/>
|
||||||
<Text
|
<Text
|
||||||
type="secondary"
|
type="secondary"
|
||||||
@@ -2422,7 +2387,7 @@ export default function CanvasMinimapPage() {
|
|||||||
onChange={(checked) => {
|
onChange={(checked) => {
|
||||||
setShowRecipes(checked);
|
setShowRecipes(checked);
|
||||||
}}
|
}}
|
||||||
disabled={!selectedInstance}
|
disabled={controlsDisabled}
|
||||||
/>
|
/>
|
||||||
<Text
|
<Text
|
||||||
type="secondary"
|
type="secondary"
|
||||||
@@ -2452,7 +2417,7 @@ export default function CanvasMinimapPage() {
|
|||||||
onChange={(checked) => {
|
onChange={(checked) => {
|
||||||
setShowPlayerPositions(checked);
|
setShowPlayerPositions(checked);
|
||||||
}}
|
}}
|
||||||
disabled={!selectedInstance}
|
disabled={controlsDisabled}
|
||||||
/>
|
/>
|
||||||
<Text
|
<Text
|
||||||
type="secondary"
|
type="secondary"
|
||||||
@@ -2473,7 +2438,7 @@ export default function CanvasMinimapPage() {
|
|||||||
</Col>
|
</Col>
|
||||||
</Row>
|
</Row>
|
||||||
</div>
|
</div>
|
||||||
{selectedInstance ? (
|
{isReady ? (
|
||||||
<div>
|
<div>
|
||||||
{isTimelapseMode && availableTicks.length > 0 && (
|
{isTimelapseMode && availableTicks.length > 0 && (
|
||||||
<div
|
<div
|
||||||
@@ -2602,8 +2567,12 @@ export default function CanvasMinimapPage() {
|
|||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<div style={{ textAlign: "center" }}>
|
<div style={{ textAlign: "center" }}>
|
||||||
<h3>No Instance Selected</h3>
|
<h3>{showInstanceSelector ? "No Instance Selected" : "Map Not Ready"}</h3>
|
||||||
<p>Select a running instance to view its minimap</p>
|
<p>
|
||||||
|
{showInstanceSelector
|
||||||
|
? "Select a running instance to view its minimap"
|
||||||
|
: "Waiting for map data to load"}
|
||||||
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -0,0 +1,191 @@
|
|||||||
|
import type { Control } from "@clusterio/web_ui";
|
||||||
|
import {
|
||||||
|
GetChartTagsRequest,
|
||||||
|
GetPlayerPathRequest,
|
||||||
|
GetRawRecipeTileRequest,
|
||||||
|
GetRawTileRequest,
|
||||||
|
type TileDataEvent,
|
||||||
|
type ChartTagDataEvent,
|
||||||
|
type RecipeDataEvent,
|
||||||
|
type PlayerPositionEvent,
|
||||||
|
} from "../../messages";
|
||||||
|
import type {
|
||||||
|
ChartTagDataWithInstance,
|
||||||
|
MinimapActiveView,
|
||||||
|
MinimapDataSource,
|
||||||
|
MinimapViewBounds,
|
||||||
|
} from "../minimap-data-source";
|
||||||
|
|
||||||
|
interface MinimapWebPlugin {
|
||||||
|
setInstanceSurfaceFilters?(filters: Array<{ instanceId: number; surface: string }> | null): Promise<void> | void;
|
||||||
|
setInstanceSurfaceFilter?(instanceId: number | null, surface: string | null): Promise<void> | void;
|
||||||
|
onTileUpdate(callback: (event: TileDataEvent) => void): void;
|
||||||
|
offTileUpdate(callback: (event: TileDataEvent) => void): void;
|
||||||
|
onChartTagUpdate(callback: (event: ChartTagDataEvent) => void): void;
|
||||||
|
offChartTagUpdate(callback: (event: ChartTagDataEvent) => void): void;
|
||||||
|
onRecipeUpdate(callback: (event: RecipeDataEvent) => void): void;
|
||||||
|
offRecipeUpdate(callback: (event: RecipeDataEvent) => void): void;
|
||||||
|
onPlayerPositionUpdate(callback: (event: PlayerPositionEvent) => void): void;
|
||||||
|
offPlayerPositionUpdate(callback: (event: PlayerPositionEvent) => void): void;
|
||||||
|
}
|
||||||
|
|
||||||
|
const decodeBase64ToBytes = (base64: string): Uint8Array => {
|
||||||
|
const binary = atob(base64);
|
||||||
|
const bytes = new Uint8Array(binary.length);
|
||||||
|
for (let i = 0; i < binary.length; i++) {
|
||||||
|
bytes[i] = binary.charCodeAt(i);
|
||||||
|
}
|
||||||
|
return bytes;
|
||||||
|
};
|
||||||
|
|
||||||
|
export class SingleInstanceDataSource implements MinimapDataSource {
|
||||||
|
private control: Control;
|
||||||
|
private plugin: MinimapWebPlugin | null = null;
|
||||||
|
private instanceId: number | null = null;
|
||||||
|
private surface = "nauvis";
|
||||||
|
private force = "player";
|
||||||
|
private activeInstances: number[] = [];
|
||||||
|
|
||||||
|
constructor(control: Control) {
|
||||||
|
this.control = control;
|
||||||
|
this.plugin = control.plugins.get("minimap") as MinimapWebPlugin | undefined ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
setInstance(instanceId: number | null): void {
|
||||||
|
this.instanceId = instanceId;
|
||||||
|
this.updateFilters();
|
||||||
|
}
|
||||||
|
|
||||||
|
setSurfaceForce(surface: string, force: string): void {
|
||||||
|
this.surface = surface;
|
||||||
|
this.force = force;
|
||||||
|
this.updateFilters();
|
||||||
|
}
|
||||||
|
|
||||||
|
setActiveView(_bounds: MinimapViewBounds): MinimapActiveView {
|
||||||
|
const nextActive = this.instanceId !== null ? [this.instanceId] : [];
|
||||||
|
const changed = nextActive.length !== this.activeInstances.length
|
||||||
|
|| nextActive.some((id, index) => id !== this.activeInstances[index]);
|
||||||
|
if (changed) {
|
||||||
|
this.activeInstances = nextActive;
|
||||||
|
}
|
||||||
|
return { changed, activeInstanceIds: [...this.activeInstances] };
|
||||||
|
}
|
||||||
|
|
||||||
|
isReady(): boolean {
|
||||||
|
return this.instanceId !== null;
|
||||||
|
}
|
||||||
|
|
||||||
|
async getTileData(tileX: number, tileY: number, tick?: number | null): Promise<Uint8Array | null> {
|
||||||
|
if (this.instanceId === null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const response = await this.control.send(new GetRawTileRequest(
|
||||||
|
this.instanceId,
|
||||||
|
this.surface,
|
||||||
|
this.force,
|
||||||
|
tileX,
|
||||||
|
tileY,
|
||||||
|
tick ?? undefined,
|
||||||
|
));
|
||||||
|
if (!response.tile_data) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return decodeBase64ToBytes(response.tile_data);
|
||||||
|
}
|
||||||
|
|
||||||
|
async getRecipeTileData(tileX: number, tileY: number, tick?: number | null): Promise<Uint8Array | null> {
|
||||||
|
if (this.instanceId === null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const response = await this.control.send(new GetRawRecipeTileRequest(
|
||||||
|
this.instanceId,
|
||||||
|
this.surface,
|
||||||
|
this.force,
|
||||||
|
tileX,
|
||||||
|
tileY,
|
||||||
|
tick ?? undefined,
|
||||||
|
));
|
||||||
|
if (!response.recipe_tile) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return decodeBase64ToBytes(response.recipe_tile);
|
||||||
|
}
|
||||||
|
|
||||||
|
async getChartTags(): Promise<ChartTagDataWithInstance[]> {
|
||||||
|
if (this.instanceId === null) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
const response = await this.control.send(new GetChartTagsRequest(
|
||||||
|
this.instanceId,
|
||||||
|
this.surface,
|
||||||
|
this.force,
|
||||||
|
));
|
||||||
|
return response.chart_tags.map(tag => ({
|
||||||
|
...tag,
|
||||||
|
instance_id: this.instanceId as number,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
async getPlayerPaths(): Promise<Array<{ instanceId: number; data: Uint8Array }>> {
|
||||||
|
if (this.instanceId === null) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
const response = await this.control.send(new GetPlayerPathRequest(
|
||||||
|
this.instanceId,
|
||||||
|
this.surface,
|
||||||
|
));
|
||||||
|
if (!response.positions) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
return [{ instanceId: this.instanceId, data: decodeBase64ToBytes(response.positions) }];
|
||||||
|
}
|
||||||
|
|
||||||
|
onTileUpdate(callback: (event: TileDataEvent) => void): () => void {
|
||||||
|
this.plugin?.onTileUpdate(callback);
|
||||||
|
return () => {
|
||||||
|
this.plugin?.offTileUpdate(callback);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
onChartTagUpdate(callback: (event: ChartTagDataEvent) => void): () => void {
|
||||||
|
this.plugin?.onChartTagUpdate(callback);
|
||||||
|
return () => {
|
||||||
|
this.plugin?.offChartTagUpdate(callback);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
onRecipeUpdate(callback: (event: RecipeDataEvent) => void): () => void {
|
||||||
|
this.plugin?.onRecipeUpdate(callback);
|
||||||
|
return () => {
|
||||||
|
this.plugin?.offRecipeUpdate(callback);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
onPlayerPositionUpdate(callback: (event: PlayerPositionEvent) => void): () => void {
|
||||||
|
this.plugin?.onPlayerPositionUpdate(callback);
|
||||||
|
return () => {
|
||||||
|
this.plugin?.offPlayerPositionUpdate(callback);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private updateFilters() {
|
||||||
|
if (!this.plugin) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (this.instanceId === null) {
|
||||||
|
if (this.plugin.setInstanceSurfaceFilters) {
|
||||||
|
this.plugin.setInstanceSurfaceFilters(null);
|
||||||
|
} else if (this.plugin.setInstanceSurfaceFilter) {
|
||||||
|
this.plugin.setInstanceSurfaceFilter(null, null);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const filters = [{ instanceId: this.instanceId, surface: this.surface }];
|
||||||
|
if (this.plugin.setInstanceSurfaceFilters) {
|
||||||
|
this.plugin.setInstanceSurfaceFilters(filters);
|
||||||
|
} else if (this.plugin.setInstanceSurfaceFilter) {
|
||||||
|
this.plugin.setInstanceSurfaceFilter(this.instanceId, this.surface);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,6 +2,20 @@ import React from "react";
|
|||||||
import { BaseWebPlugin } from "@clusterio/web_ui";
|
import { BaseWebPlugin } from "@clusterio/web_ui";
|
||||||
import * as lib from "@clusterio/lib";
|
import * as lib from "@clusterio/lib";
|
||||||
import CanvasMinimapPage from "./CanvasMinimapPage";
|
import CanvasMinimapPage from "./CanvasMinimapPage";
|
||||||
|
export { default as CanvasMinimapPage } from "./CanvasMinimapPage";
|
||||||
|
export { SingleInstanceDataSource } from "./dataSources/SingleInstanceDataSource";
|
||||||
|
export type {
|
||||||
|
ChartTagDataWithInstance,
|
||||||
|
MinimapActiveView,
|
||||||
|
MinimapDataSource,
|
||||||
|
MinimapViewBounds,
|
||||||
|
} from "./minimap-data-source";
|
||||||
|
export {
|
||||||
|
GetRawTileRequest,
|
||||||
|
GetRawRecipeTileRequest,
|
||||||
|
GetChartTagsRequest,
|
||||||
|
GetPlayerPathRequest,
|
||||||
|
} from "../messages";
|
||||||
import { TileDataEvent, ChartTagDataEvent, RecipeDataEvent, PlayerPositionEvent } from "../messages";
|
import { TileDataEvent, ChartTagDataEvent, RecipeDataEvent, PlayerPositionEvent } from "../messages";
|
||||||
|
|
||||||
export class WebPlugin extends BaseWebPlugin {
|
export class WebPlugin extends BaseWebPlugin {
|
||||||
@@ -38,9 +52,11 @@ export class WebPlugin extends BaseWebPlugin {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Update instance/surface filter used for subscriptions.
|
// Update instance/surface filters used for subscriptions.
|
||||||
async setInstanceSurfaceFilter(instanceId: number | null, surface: string | null) {
|
async setInstanceSurfaceFilters(filters: Array<{ instanceId: number; surface: string }> | null) {
|
||||||
const newFilters = (instanceId !== null && surface) ? [`${instanceId}:${surface}`] : undefined;
|
const newFilters = filters && filters.length > 0
|
||||||
|
? filters.map(filter => `${filter.instanceId}:${filter.surface}`)
|
||||||
|
: undefined;
|
||||||
|
|
||||||
// No change
|
// No change
|
||||||
const prev = this.currentFilters;
|
const prev = this.currentFilters;
|
||||||
@@ -72,6 +88,15 @@ export class WebPlugin extends BaseWebPlugin {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Update instance/surface filter used for subscriptions.
|
||||||
|
async setInstanceSurfaceFilter(instanceId: number | null, surface: string | null) {
|
||||||
|
await this.setInstanceSurfaceFilters(
|
||||||
|
instanceId !== null && surface
|
||||||
|
? [{ instanceId, surface }]
|
||||||
|
: null,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
private async updateSubscriptions() {
|
private async updateSubscriptions() {
|
||||||
if (!this.control.connector.connected) {
|
if (!this.control.connector.connected) {
|
||||||
return;
|
return;
|
||||||
|
|||||||
@@ -0,0 +1,38 @@
|
|||||||
|
import type {
|
||||||
|
ChartTagData,
|
||||||
|
ChartTagDataEvent,
|
||||||
|
PlayerPositionEvent,
|
||||||
|
RecipeDataEvent,
|
||||||
|
TileDataEvent,
|
||||||
|
} from "../messages";
|
||||||
|
|
||||||
|
export interface ChartTagDataWithInstance extends ChartTagData {
|
||||||
|
instance_id: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MinimapViewBounds {
|
||||||
|
worldLeft: number;
|
||||||
|
worldTop: number;
|
||||||
|
worldRight: number;
|
||||||
|
worldBottom: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MinimapActiveView {
|
||||||
|
changed: boolean;
|
||||||
|
activeInstanceIds: number[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MinimapDataSource {
|
||||||
|
setInstance?(instanceId: number | null): void;
|
||||||
|
setSurfaceForce(surface: string, force: string): void;
|
||||||
|
setActiveView(bounds: MinimapViewBounds): MinimapActiveView;
|
||||||
|
isReady(): boolean;
|
||||||
|
getTileData(tileX: number, tileY: number, tick?: number | null): Promise<Uint8Array | null>;
|
||||||
|
getRecipeTileData(tileX: number, tileY: number, tick?: number | null): Promise<Uint8Array | null>;
|
||||||
|
getChartTags(): Promise<ChartTagDataWithInstance[]>;
|
||||||
|
getPlayerPaths(): Promise<Array<{ instanceId: number; data: Uint8Array }>>;
|
||||||
|
onTileUpdate(callback: (event: TileDataEvent) => void): () => void;
|
||||||
|
onChartTagUpdate(callback: (event: ChartTagDataEvent) => void): () => void;
|
||||||
|
onRecipeUpdate(callback: (event: RecipeDataEvent) => void): () => void;
|
||||||
|
onPlayerPositionUpdate(callback: (event: PlayerPositionEvent) => void): () => void;
|
||||||
|
}
|
||||||
Reference in new issue
Block a user