mirror of
https://github.com/openfrontio/OpenFrontIO.git
synced 2026-06-27 02:44:36 +00:00
05e2bc9f0a
## Description: This reworks asset delivery and cacheability across the app and moves non-bundled public resources onto immutable, content-hashed URLs. Vite bundle outputs continue to live under `/assets/**` and remain content-hashed by Vite. Public resources that were previously fetched from stable paths in `resources/` now go through a custom hashed namespace under `/_assets/**`, backed by a generated asset manifest that is available to the server, browser, and worker runtime. In parallel, the root app shell is now cacheable shared HTML instead of request-time `no-store` HTML. Dynamic and live routes remain explicitly uncached. ## Why - Improve browser and Cloudflare cacheability for static assets. - Remove query-string and release-version cache busting for runtime-fetched assets. - Allow unchanged public assets to keep the same URL across releases. - Reduce avoidable work on `/` by serving a shared app shell instead of rendering HTML on every request. - Make cache behavior explicit instead of relying on mixed framework defaults and file-extension heuristics. ## What Changed ### 1. Content-hashed public asset pipeline - Added a build-time public asset manifest and hashing pipeline for non-Vite resources. - Production now emits hashed public assets under `/_assets/**`. - Added runtime manifest loading for Node so server-rendered paths resolve against built hashed files instead of rebuilding from source at runtime. - Emitted the runtime asset manifest as an ESM module for server consumption. Result: - `/assets/**` = Vite-managed hashed bundle outputs - `/_assets/**` = custom content-hashed public resources ### 2. Runtime asset URL migration - Added a shared `assetUrl(...)` resolution path. - Migrated runtime references away from query-string versioning and stable source paths. - Updated browser, worker, and server-side rendering paths to resolve through the asset manifest. - Moved map manifests, map binaries, thumbnails, sprites, sounds, fonts, flags, icons, screenshots, and other runtime-fetched resources onto hashed URLs. ### 3. Map and preview fixes - Fixed directory and per-file map asset resolution so map manifest and binary fetches resolve to the correct hashed URLs. - Updated preview metadata and map thumbnail paths to use the hashed asset namespace. - Fixed runtime manifest loading in prod after deployment. ### 4. Explicit cache policies - Added explicit immutable cache headers for: - `/assets/**` - `/_assets/**` - worker-prefixed equivalents under `/wN/...` - Added explicit `no-store` headers for live and dynamic APIs. - Removed the old `/api/env` bootstrap request and baked `gameEnv` into the HTML bootstrap instead. ### 5. Cacheable root app shell - Refactored the root HTML path to serve a shared app shell with: - `Cache-Control: public, max-age=0, s-maxage=300, stale-while-revalidate=86400` - `/` and the SPA fallback now serve shared cacheable HTML instead of request-time `no-store` rendering. - `/game/:id` remains dynamic and `no-store`, but now reuses the shared shell before injecting preview tags. ### 6. Matchmaking instance handling - Because the app shell is now cacheable, `INSTANCE_ID` was removed from shared HTML. - Added `/api/instance` as a temporary `no-store` runtime lookup used only by matchmaking. - This preserves correctness with the current random-per-boot `INSTANCE_ID` model while keeping `/` cacheable, but it is not the intended long-term design. ## Behavior Changes ### Asset URL contract Production URLs for non-Vite public resources now change from stable paths such as: - `/maps/...` - `/images/...` - `/manifest.json` to content-hashed paths under: - `/_assets/...` Examples: - `/_assets/maps/<map>/manifest.<hash>.json` - `/_assets/images/Favicon.<hash>.svg` ### Bootstrap/config - `/api/env` is removed. - `gameEnv` is now bootstrapped from HTML. ### HTML caching - `/` and the SPA fallback are now cacheable shared HTML. - `/game/:id` remains dynamic. ## Cache Matrix After This Branch - `/_assets/**`: `public, max-age=31536000, immutable` - `/assets/**`: `public, max-age=31536000, immutable` - live `/api/**`: explicit `no-store` - `/api/health`: explicit `no-store` - `/api/instance`: explicit `no-store` - `/game/:id`: explicit `no-store` - `/` and SPA fallback: `public, max-age=0, s-maxage=300, stale-while-revalidate=86400` ## Notes / Tradeoffs - `/api/instance` is a temporary compromise. It exists because `INSTANCE_ID` is currently random per boot, which is not safe to embed into cacheable shared HTML. - The current matchmaking flow still asks the client to provide `instance_id` during `matchmaking/join`. That is functional, but it is the wrong ownership boundary: instance selection should be handled by the matchmaking service, not by the browser. - The cleaner end-state would be: - make `matchmaking/join` stop requiring `instance_id` from the client, and let the matchmaking service select a healthy instance from worker check-ins - This branch makes the origin behavior edge-cache-friendly, but Cloudflare still needs matching cache rules if HTML itself should be cached at the edge. ## Validation Verified during development with: - `npx tsc --noEmit` - `node node_modules\\vite\\bin\\vite.js build` - `node node_modules\\vitest\\vitest.mjs run tests/server/RenderHtml.test.ts tests/server/NoStoreHeaders.test.ts tests/server/StaticAssetCache.test.ts tests/core/configuration/ConfigLoader.test.ts` Additional targeted tests added: - `tests/AssetUrls.test.ts` - `tests/core/game/FetchGameMapLoader.test.ts` - `tests/core/configuration/ConfigLoader.test.ts` - `tests/server/NoStoreHeaders.test.ts` - `tests/server/StaticAssetCache.test.ts` - `tests/server/RenderHtml.test.ts` ## Known Existing Warnings The production build still reports pre-existing warnings that are not addressed by this branch: - inconsistent JSON import attributes for `resources/countries.json` - inconsistent JSON import attributes for `resources/QuickChat.json` - large chunk warnings from Vite ## Rollout Notes - Cache rules should treat `/_assets/**` and `/assets/**` as immutable. - Cloudflare will still classify HTML as dynamic after deploy unless matching edge cache rules are configured for it. ## Follow-ups - Remove `/api/instance` by changing `matchmaking/join` so the server selects the target instance, or by making `INSTANCE_ID` deploy-stable if the current contract must remain. ## Please complete the following: - [ ] I have added screenshots for all UI updates - [ ] I process any text displayed to the user through translateText() and I've added it to the en.json file - [ ] I have added relevant tests to the test directory - [ ] I confirm I have thoroughly tested these changes and take full responsibility for any bugs introduced ## Please put your Discord username so you can be contacted if a bug or regression is found: DISCORD_USERNAME
285 lines
8.7 KiB
TypeScript
285 lines
8.7 KiB
TypeScript
import { colord, Colord } from "colord";
|
|
import { assetUrl } from "../../../core/AssetUrls";
|
|
import { Theme } from "../../../core/configuration/Config";
|
|
import { EventBus } from "../../../core/EventBus";
|
|
import { TransformHandler } from "../TransformHandler";
|
|
import { Layer } from "./Layer";
|
|
|
|
import { Cell, UnitType } from "../../../core/game/Game";
|
|
import { euclDistFN, isometricDistFN } from "../../../core/game/GameMap";
|
|
import { GameUpdateType } from "../../../core/game/GameUpdates";
|
|
import { GameView, UnitView } from "../../../core/game/GameView";
|
|
const cityIcon = assetUrl("images/buildings/cityAlt1.png");
|
|
const factoryIcon = assetUrl("images/buildings/factoryAlt1.png");
|
|
const shieldIcon = assetUrl("images/buildings/fortAlt3.png");
|
|
const anchorIcon = assetUrl("images/buildings/port1.png");
|
|
const missileSiloIcon = assetUrl("images/buildings/silo1.png");
|
|
const SAMMissileIcon = assetUrl("images/buildings/silo4.png");
|
|
|
|
const underConstructionColor = colord("rgb(150,150,150)");
|
|
|
|
// Base radius values and scaling factor for unit borders and territories
|
|
const BASE_BORDER_RADIUS = 16.5;
|
|
const BASE_TERRITORY_RADIUS = 13.5;
|
|
const RADIUS_SCALE_FACTOR = 0.5;
|
|
const ZOOM_THRESHOLD = 4.3; // below this zoom level, structures are not rendered
|
|
|
|
interface UnitRenderConfig {
|
|
icon: string;
|
|
borderRadius: number;
|
|
territoryRadius: number;
|
|
}
|
|
|
|
export class StructureLayer implements Layer {
|
|
private canvas: HTMLCanvasElement;
|
|
private context: CanvasRenderingContext2D;
|
|
private unitIcons: Map<string, HTMLImageElement> = new Map();
|
|
private theme: Theme;
|
|
private tempCanvas: HTMLCanvasElement;
|
|
private tempContext: CanvasRenderingContext2D;
|
|
|
|
// Configuration for supported unit types only
|
|
private readonly unitConfigs: Partial<Record<UnitType, UnitRenderConfig>> = {
|
|
[UnitType.Port]: {
|
|
icon: anchorIcon,
|
|
borderRadius: BASE_BORDER_RADIUS * RADIUS_SCALE_FACTOR,
|
|
territoryRadius: BASE_TERRITORY_RADIUS * RADIUS_SCALE_FACTOR,
|
|
},
|
|
[UnitType.City]: {
|
|
icon: cityIcon,
|
|
borderRadius: BASE_BORDER_RADIUS * RADIUS_SCALE_FACTOR,
|
|
territoryRadius: BASE_TERRITORY_RADIUS * RADIUS_SCALE_FACTOR,
|
|
},
|
|
[UnitType.Factory]: {
|
|
icon: factoryIcon,
|
|
borderRadius: BASE_BORDER_RADIUS * RADIUS_SCALE_FACTOR,
|
|
territoryRadius: BASE_TERRITORY_RADIUS * RADIUS_SCALE_FACTOR,
|
|
},
|
|
[UnitType.MissileSilo]: {
|
|
icon: missileSiloIcon,
|
|
borderRadius: BASE_BORDER_RADIUS * RADIUS_SCALE_FACTOR,
|
|
territoryRadius: BASE_TERRITORY_RADIUS * RADIUS_SCALE_FACTOR,
|
|
},
|
|
[UnitType.DefensePost]: {
|
|
icon: shieldIcon,
|
|
borderRadius: BASE_BORDER_RADIUS * RADIUS_SCALE_FACTOR,
|
|
territoryRadius: BASE_TERRITORY_RADIUS * RADIUS_SCALE_FACTOR,
|
|
},
|
|
[UnitType.SAMLauncher]: {
|
|
icon: SAMMissileIcon,
|
|
borderRadius: BASE_BORDER_RADIUS * RADIUS_SCALE_FACTOR,
|
|
territoryRadius: BASE_TERRITORY_RADIUS * RADIUS_SCALE_FACTOR,
|
|
},
|
|
};
|
|
|
|
constructor(
|
|
private game: GameView,
|
|
private eventBus: EventBus,
|
|
private transformHandler: TransformHandler,
|
|
) {
|
|
this.theme = game.config().theme();
|
|
this.tempCanvas = document.createElement("canvas");
|
|
const tempContext = this.tempCanvas.getContext("2d");
|
|
if (tempContext === null) throw new Error("2d context not supported");
|
|
this.tempContext = tempContext;
|
|
this.loadIconData();
|
|
}
|
|
|
|
private loadIcon(unitType: string, config: UnitRenderConfig) {
|
|
const image = new Image();
|
|
image.src = config.icon;
|
|
image.onload = () => {
|
|
this.unitIcons.set(unitType, image);
|
|
console.log(
|
|
`icon loaded: ${unitType}, size: ${image.width}x${image.height}`,
|
|
);
|
|
};
|
|
image.onerror = () => {
|
|
console.error(`Failed to load icon for ${unitType}: ${config.icon}`);
|
|
};
|
|
}
|
|
|
|
private loadIconData() {
|
|
Object.entries(this.unitConfigs).forEach(([unitType, config]) => {
|
|
this.loadIcon(unitType, config);
|
|
});
|
|
}
|
|
|
|
shouldTransform(): boolean {
|
|
return true;
|
|
}
|
|
|
|
tick() {
|
|
const updates = this.game.updatesSinceLastTick();
|
|
const unitUpdates = updates !== null ? updates[GameUpdateType.Unit] : [];
|
|
for (const u of unitUpdates) {
|
|
const unit = this.game.unit(u.id);
|
|
if (unit === undefined) continue;
|
|
this.handleUnitRendering(unit);
|
|
}
|
|
}
|
|
|
|
init() {
|
|
this.redraw();
|
|
}
|
|
|
|
redraw() {
|
|
console.log("structure layer redrawing");
|
|
this.canvas = document.createElement("canvas");
|
|
const context = this.canvas.getContext("2d", { alpha: true });
|
|
if (context === null) throw new Error("2d context not supported");
|
|
this.context = context;
|
|
|
|
// Enable smooth scaling
|
|
this.context.imageSmoothingEnabled = true;
|
|
this.context.imageSmoothingQuality = "high";
|
|
|
|
this.canvas.width = this.game.width() * 2;
|
|
this.canvas.height = this.game.height() * 2;
|
|
|
|
Promise.all(
|
|
Array.from(this.unitIcons.values()).map((img) =>
|
|
img.decode?.().catch((err) => {
|
|
console.warn("Failed to decode unit icon image:", err);
|
|
}),
|
|
),
|
|
).finally(() => {
|
|
this.game.units().forEach((u) => this.handleUnitRendering(u));
|
|
});
|
|
}
|
|
|
|
renderLayer(context: CanvasRenderingContext2D) {
|
|
if (
|
|
this.transformHandler.scale <= ZOOM_THRESHOLD ||
|
|
!this.game.config().userSettings()?.structureSprites()
|
|
) {
|
|
return;
|
|
}
|
|
context.drawImage(
|
|
this.canvas,
|
|
-this.game.width() / 2,
|
|
-this.game.height() / 2,
|
|
this.game.width(),
|
|
this.game.height(),
|
|
);
|
|
}
|
|
|
|
private isUnitTypeSupported(unitType: UnitType): boolean {
|
|
return unitType in this.unitConfigs;
|
|
}
|
|
|
|
private drawBorder(
|
|
unit: UnitView,
|
|
borderColor: Colord,
|
|
config: UnitRenderConfig,
|
|
) {
|
|
// Draw border and territory
|
|
for (const tile of this.game.bfs(
|
|
unit.tile(),
|
|
isometricDistFN(unit.tile(), config.borderRadius, true),
|
|
)) {
|
|
this.paintCell(
|
|
new Cell(this.game.x(tile), this.game.y(tile)),
|
|
borderColor,
|
|
255,
|
|
);
|
|
}
|
|
|
|
for (const tile of this.game.bfs(
|
|
unit.tile(),
|
|
isometricDistFN(unit.tile(), config.territoryRadius, true),
|
|
)) {
|
|
this.paintCell(
|
|
new Cell(this.game.x(tile), this.game.y(tile)),
|
|
unit.isUnderConstruction()
|
|
? underConstructionColor
|
|
: unit.owner().territoryColor(),
|
|
130,
|
|
);
|
|
}
|
|
}
|
|
|
|
private handleUnitRendering(unit: UnitView) {
|
|
const unitType = unit.type();
|
|
const iconType = unitType;
|
|
if (!this.isUnitTypeSupported(unitType)) return;
|
|
|
|
const config = this.unitConfigs[unitType];
|
|
let icon: HTMLImageElement | undefined;
|
|
let borderColor = unit.owner().borderColor();
|
|
|
|
// Handle cooldown states and special icons
|
|
if (unit.isUnderConstruction()) {
|
|
icon = this.unitIcons.get(iconType);
|
|
borderColor = underConstructionColor;
|
|
} else {
|
|
icon = this.unitIcons.get(iconType);
|
|
}
|
|
|
|
if (!config || !icon) return;
|
|
|
|
// Clear previous rendering
|
|
for (const tile of this.game.bfs(
|
|
unit.tile(),
|
|
euclDistFN(unit.tile(), config.borderRadius + 1, true),
|
|
)) {
|
|
this.clearCell(new Cell(this.game.x(tile), this.game.y(tile)));
|
|
}
|
|
|
|
if (!unit.isActive()) return;
|
|
|
|
this.drawBorder(unit, borderColor, config);
|
|
|
|
// Render icon at 1/2 scale for better quality
|
|
const scaledWidth = icon.width >> 1;
|
|
const scaledHeight = icon.height >> 1;
|
|
const startX = this.game.x(unit.tile()) - (scaledWidth >> 1);
|
|
const startY = this.game.y(unit.tile()) - (scaledHeight >> 1);
|
|
|
|
this.renderIcon(icon, startX, startY - 4, scaledWidth, scaledHeight, unit);
|
|
}
|
|
|
|
private renderIcon(
|
|
image: HTMLImageElement,
|
|
startX: number,
|
|
startY: number,
|
|
width: number,
|
|
height: number,
|
|
unit: UnitView,
|
|
) {
|
|
let color = unit.owner().borderColor();
|
|
if (unit.isUnderConstruction()) {
|
|
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
color = underConstructionColor;
|
|
}
|
|
|
|
// Make temp canvas at the final render size (2x scale)
|
|
this.tempCanvas.width = width * 2;
|
|
this.tempCanvas.height = height * 2;
|
|
|
|
// Enable smooth scaling
|
|
this.tempContext.imageSmoothingEnabled = true;
|
|
this.tempContext.imageSmoothingQuality = "high";
|
|
|
|
// Draw the image at final size with high quality scaling
|
|
this.tempContext.drawImage(image, 0, 0, width * 2, height * 2);
|
|
|
|
// Restore the alpha channel
|
|
this.tempContext.globalCompositeOperation = "destination-in";
|
|
this.tempContext.drawImage(image, 0, 0, width * 2, height * 2);
|
|
|
|
// Draw the final result to the main canvas
|
|
this.context.drawImage(this.tempCanvas, startX * 2, startY * 2);
|
|
}
|
|
|
|
paintCell(cell: Cell, color: Colord, alpha: number) {
|
|
this.clearCell(cell);
|
|
this.context.fillStyle = color.alpha(alpha / 255).toRgbString();
|
|
this.context.fillRect(cell.x * 2, cell.y * 2, 2, 2);
|
|
}
|
|
|
|
clearCell(cell: Cell) {
|
|
this.context.clearRect(cell.x * 2, cell.y * 2, 2, 2);
|
|
}
|
|
}
|