Add image maps and pregeneration views to the studio

- List the pack's image maps with a preview over the area they cover
- Show the running pregeneration's chunk map, progress and pause
This commit is contained in:
piexel committed 2026-11-15 11:17:34 +01:00
1 parent 3532c16906
commit 98e296b666
149 files changed
+334 -29970

No files matched your search

@@ -8,6 +8,7 @@ import type {
BlockSource,
EditorState,
GraphEdit,
ImageMapDetails,
MapHover,
MapLabel,
MapTile,
@@ -18,6 +19,7 @@ import type {
PatternEntry,
PatternTile,
PickInspection,
PregenStatus,
ProfileFormState,
SavedStart,
SavedTile,
@@ -276,6 +278,36 @@ export class BridgeClient {
return decodePattern(await response.arrayBuffer())
}
pregen(signal?: AbortSignal): Promise<PregenStatus> {
return this.json('pregen', { signal })
}
/** The running pregeneration's chunks, one pixel each. */
async pregenMap(signal?: AbortSignal): Promise<Blob> {
const response = await this.fetch('pregen-map', { signal })
return response.blob()
}
/** Pauses the pregeneration, or resumes it when it is paused. */
async pregenPause(): Promise<void> {
await this.json('pregen-pause', { method: 'POST' })
}
/** The pack's image maps, listed like scene entries. */
imageMaps(): Promise<SceneEntry[]> {
return this.json('image-maps')
}
imageMap(key: string, signal?: AbortSignal): Promise<ImageMapDetails> {
return this.json(`image-map?${new URLSearchParams({ key })}`, { signal })
}
/** The image map painted over the world area it covers, {@code pixels} across its longer side. */
async imageMapPreview(key: string, pixels: number, signal?: AbortSignal): Promise<Blob> {
const response = await this.fetch(`image-map-preview?${new URLSearchParams({ key, size: String(pixels) })}`, { signal })
return response.blob()
}
/** The worlds saved on the server's disk. */
savedWorlds(): Promise<SavedWorldInfo[]> {
return this.json('saved-worlds')
+50
View File
@@ -194,6 +194,56 @@ export interface PatternTile {
export const NO_PATTERN_BLOCK = -1
/** How far the running pregeneration is; times are in milliseconds. */
export interface PregenProgress {
percent: number
generated: number
totalChunks: number
chunksPerSecond: number
overallChunksPerSecond: number
thirtySecondChunksPerSecond: number
sixtySecondChunksPerSecond: number
chunksRemaining: number
chunksInFlight: number
eta: number
elapsed: number
method: string
paused: boolean
failed: number
worldName: string
}
export type PregenPhase = 'INITIALIZING' | 'GENERATING' | 'PAUSED' | 'SAVING' | 'STOPPING' | 'COMPLETED' | 'ERROR'
export interface PregenSnapshot {
bounds: { minX: number; minZ: number; maxX: number; maxZ: number }
progress: PregenProgress
phase: PregenPhase
cached: boolean
usedMemoryBytes: number
memoryUsage: number
failure: string | null
}
/** The server's pregeneration; `snapshot` is null while none runs. */
export interface PregenStatus {
active: boolean
snapshot: PregenSnapshot | null
}
/** An image map of the pack and what it covers. */
export interface ImageMapDetails {
key: string
type: string
source: string
width: number
height: number
blocksPerPixel: number
/** The world area it covers: minimum X, minimum Z, maximum X, maximum Z. */
bounds: [number, number, number, number]
facts: string[]
}
/** A world saved on the server's disk, a dimension folder of region files. */
export interface SavedWorldInfo {
/** Its folder below the server's level folder. */
@@ -0,0 +1,109 @@
import { useEffect, useState } from 'react'
import type { BridgeClient } from '../bridge/BridgeClient'
import type { ImageMapDetails, SceneEntry } from '../bridge/types'
import { EntryBrowser } from './EntryBrowser'
import { Panel, SidebarPanel, ViewIsland } from './Sidebar'
const PREVIEW_PIXELS = 1024
const NUMBER = new Intl.NumberFormat('en-US')
interface ImageMapStudioProps {
title: string
client: BridgeClient
/** Changes when the pack reloads, so the maps are read again. */
packRevision: number
onSummary(summary: string | null): void
tell(message: string): void
}
/** The pack's image maps: the list on the left, the chosen one painted over the world area it covers in the middle, what it is on the right. */
export function ImageMapStudio({ title, client, packRevision, onSummary, tell }: ImageMapStudioProps): React.JSX.Element {
const entries = useImageMapEntries(client, packRevision, tell)
const [chosen, setChosen] = useState<string | null>(null)
const entry = entries.find((candidate) => candidate.key === chosen) ?? entries[0] ?? null
const { details, picture } = useImageMap(client, entry?.key ?? null, packRevision, tell)
useEffect(() => onSummary(entry === null ? null : entry.key), [entry, onSummary])
useEffect(() => () => onSummary(null), [onSummary])
return (
<>
<ViewIsland title={entry === null ? title : `${title} · ${entry.name}`}>
<div className="absolute inset-0 flex items-center justify-center overflow-auto bg-map-background p-4">
{picture !== null && <img src={picture} alt={entry?.name ?? title} className="max-h-full max-w-full object-contain [image-rendering:pixelated]" />}
{entry === null && <p className="text-[12px] text-secondary-text">This pack has no image maps. Put them in the pack's imageMaps folder.</p>}
</div>
</ViewIsland>
<SidebarPanel className="flex-1">
<EntryBrowser className="flex-1" title={title} entries={entries} current={entry?.key ?? null} onSelect={setChosen} />
</SidebarPanel>
<Panel className="w-[250px]">{details !== null && <Facts details={details} />}</Panel>
</>
)
}
function Facts({ details }: { details: ImageMapDetails }): React.JSX.Element {
const [minimumX, minimumZ, maximumX, maximumZ] = details.bounds
return (
<section className="px-4 pt-2.5 pb-2.5">
<h2 className="truncate text-[11px] font-semibold text-muted-foreground" title={details.key}>
{details.type}
</h2>
<p className="pt-1 text-[12px] leading-snug text-secondary-text">
Covers X {NUMBER.format(Math.round(minimumX))} to {NUMBER.format(Math.round(maximumX))}, Z {NUMBER.format(Math.round(minimumZ))} to {NUMBER.format(Math.round(maximumZ))}
</p>
{details.facts.map((fact) => (
<p key={fact} className="pt-1 text-[12px] leading-snug text-secondary-text">
{fact}
</p>
))}
</section>
)
}
function useImageMapEntries(client: BridgeClient, packRevision: number, tell: (message: string) => void): SceneEntry[] {
const [entries, setEntries] = useState<SceneEntry[]>([])
useEffect(() => {
let active = true
client
.imageMaps()
.then((found) => active && setEntries(found))
.catch((failure: Error) => active && tell(failure.message))
return () => {
active = false
}
}, [client, packRevision, tell])
return entries
}
function useImageMap(client: BridgeClient, key: string | null, packRevision: number, tell: (message: string) => void): { details: ImageMapDetails | null; picture: string | null } {
const [details, setDetails] = useState<ImageMapDetails | null>(null)
const [picture, setPicture] = useState<string | null>(null)
useEffect(() => {
setDetails(null)
setPicture(null)
if (key === null) {
return
}
const stop = new AbortController()
let url: string | null = null
client
.imageMap(key, stop.signal)
.then(setDetails)
.catch((failure: Error) => !stop.signal.aborted && tell(failure.message))
client
.imageMapPreview(key, PREVIEW_PIXELS, stop.signal)
.then((blob) => {
url = URL.createObjectURL(blob)
setPicture(url)
})
.catch((failure: Error) => !stop.signal.aborted && tell(failure.message))
return () => {
stop.abort()
if (url !== null) {
URL.revokeObjectURL(url)
}
}
}, [client, key, packRevision, tell])
return { details, picture }
}
+9 -1
View File
@@ -12,7 +12,9 @@ import { Legend } from './Legend'
import { MapCanvas, type CanvasPoint } from './MapCanvas'
import { PickInspector } from './PickInspector'
import { RegionPreviewList } from './RegionPreviewList'
import { ImageMapStudio } from './ImageMapStudio'
import { NoiseStudio } from './NoiseStudio'
import { PregenStudio } from './PregenStudio'
import { PatternStudio } from './PatternStudio'
import { SavedWorldStudio } from './SavedWorldStudio'
import { SceneStudio } from './SceneStudio'
@@ -235,6 +237,10 @@ export function MapStudio({ client, world, theme, onDisconnect }: MapStudioProps
<WorldStudio3D title={view.label} client={client} world={world} mapArea={area} packRevision={packRevision} onSummary={setSceneSummary} tell={tell} />
) : viewId === SAVED_WORLD.id ? (
<SavedWorldStudio title={view.label} client={client} world={world} onSummary={setSceneSummary} onProgress={setSceneProgress} tell={tell} />
) : viewId === PREGEN_VIEW_ID ? (
<PregenStudio title={view.label} client={client} onSummary={setSceneSummary} tell={tell} />
) : viewId === IMAGE_MAPS_VIEW_ID ? (
<ImageMapStudio title={view.label} client={client} packRevision={packRevision} onSummary={setSceneSummary} tell={tell} />
) : viewId === NOISE.id ? (
<NoiseStudio title={view.label} client={client} packRevision={packRevision} onSummary={setSceneSummary} tell={tell} />
) : (
@@ -347,7 +353,9 @@ const NOISE: ViewInfo = {
group: 'PACK',
groupLabel: 'Pack'
}
const APP_VIEW_IDS = new Set([WORLD_3D.id, SAVED_WORLD.id, NOISE.id])
const IMAGE_MAPS_VIEW_ID = 'imageMaps'
const PREGEN_VIEW_ID = 'pregen'
const APP_VIEW_IDS = new Set([WORLD_3D.id, SAVED_WORLD.id, NOISE.id, IMAGE_MAPS_VIEW_ID, PREGEN_VIEW_ID])
function withAppViews(serverViews: ViewInfo[]): ViewInfo[] {
const afterRegions = serverViews.findIndex((candidate) => candidate.id === 'regions') + 1
@@ -0,0 +1,131 @@
import { useEffect, useState } from 'react'
import { Button } from '@/components/ui/button'
import type { BridgeClient } from '../bridge/BridgeClient'
import type { PregenSnapshot } from '../bridge/types'
import { Panel, ViewIsland } from './Sidebar'
const POLL_MILLIS = 1000
const MILLIS_PER_SECOND = 1000
const SECONDS_PER_MINUTE = 60
const MINUTES_PER_HOUR = 60
const PERCENT = 100
const NUMBER = new Intl.NumberFormat('en-US')
const RATE = new Intl.NumberFormat('en-US', { maximumFractionDigits: 1 })
const PHASE_LABELS = {
INITIALIZING: 'Starting',
GENERATING: 'Generating',
PAUSED: 'Paused',
SAVING: 'Saving',
STOPPING: 'Stopping',
COMPLETED: 'Done',
ERROR: 'Failed'
} as const
interface PregenStudioProps {
title: string
client: BridgeClient
onSummary(summary: string | null): void
tell(message: string): void
}
/** The running pregeneration: its chunks as they are generated in the middle, its progress on the right. */
export function PregenStudio({ title, client, onSummary, tell }: PregenStudioProps): React.JSX.Element {
const { snapshot, picture } = usePregen(client, tell)
useEffect(() => onSummary(snapshot === null ? null : `${PHASE_LABELS[snapshot.phase]} · ${snapshot.progress.worldName}`), [snapshot, onSummary])
useEffect(() => () => onSummary(null), [onSummary])
return (
<>
<ViewIsland title={title}>
<div className="absolute inset-0 flex items-center justify-center bg-map-background p-4">
{picture !== null && <img src={picture} alt="Chunks of the pregeneration" className="max-h-full max-w-full object-contain [image-rendering:pixelated]" />}
{snapshot === null && <p className="text-[12px] text-secondary-text">No pregeneration is running. Start one with /iris pregen start.</p>}
</div>
</ViewIsland>
<Panel className="w-[250px]">{snapshot !== null && <Progress snapshot={snapshot} onPause={() => void client.pregenPause().catch((failure: Error) => tell(failure.message))} />}</Panel>
</>
)
}
function Progress({ snapshot, onPause }: { snapshot: PregenSnapshot; onPause(): void }): React.JSX.Element {
const { progress } = snapshot
const canPause = snapshot.phase === 'GENERATING' || snapshot.phase === 'PAUSED'
return (
<section className="flex flex-col gap-2 px-4 py-3 text-[12px]">
<h2 className="text-[11px] font-semibold text-muted-foreground">{PHASE_LABELS[snapshot.phase]}</h2>
<div className="h-1.5 overflow-hidden rounded-full bg-muted">
<div className="h-full bg-primary" style={{ width: `${Math.min(PERCENT, progress.percent)}%` }} />
</div>
<Row label="Done" value={`${RATE.format(progress.percent)}%`} />
<Row label="Chunks" value={`${NUMBER.format(progress.generated)} of ${NUMBER.format(progress.totalChunks)}`} />
<Row label="Remaining" value={NUMBER.format(progress.chunksRemaining)} />
<Row label="In flight" value={NUMBER.format(progress.chunksInFlight)} />
<Row label="Speed" value={`${RATE.format(progress.chunksPerSecond)} chunks/s`} />
<Row label="Average" value={`${RATE.format(progress.overallChunksPerSecond)} chunks/s`} />
<Row label="Elapsed" value={duration(progress.elapsed)} />
<Row label="Left" value={progress.eta < 0 ? 'unknown' : duration(progress.eta)} />
<Row label="Method" value={progress.method} />
{progress.failed > 0 && <Row label="Failed" value={NUMBER.format(progress.failed)} />}
{snapshot.failure !== null && <p className="text-destructive">{snapshot.failure}</p>}
{canPause && (
<Button variant="outline" size="sm" onClick={onPause}>
{snapshot.phase === 'PAUSED' ? 'Resume' : 'Pause'}
</Button>
)}
</section>
)
}
function Row({ label, value }: { label: string; value: string }): React.JSX.Element {
return (
<div className="flex justify-between gap-2">
<span className="text-secondary-text">{label}</span>
<span className="truncate tabular-nums">{value}</span>
</div>
)
}
function duration(millis: number): string {
const totalSeconds = Math.max(0, Math.round(millis / MILLIS_PER_SECOND))
const hours = Math.floor(totalSeconds / (SECONDS_PER_MINUTE * MINUTES_PER_HOUR))
const minutes = Math.floor(totalSeconds / SECONDS_PER_MINUTE) % MINUTES_PER_HOUR
const seconds = totalSeconds % SECONDS_PER_MINUTE
return hours > 0 ? `${hours}h ${minutes}m` : minutes > 0 ? `${minutes}m ${seconds}s` : `${seconds}s`
}
/** The pregeneration's status and map, read again every second while the view is shown. */
function usePregen(client: BridgeClient, tell: (message: string) => void): { snapshot: PregenSnapshot | null; picture: string | null } {
const [snapshot, setSnapshot] = useState<PregenSnapshot | null>(null)
const [picture, setPicture] = useState<string | null>(null)
useEffect(() => {
const stop = new AbortController()
let url: string | null = null
const show = (next: string | null): void => {
if (url !== null) {
URL.revokeObjectURL(url)
}
url = next
setPicture(next)
}
const refresh = async (): Promise<void> => {
try {
const status = await client.pregen(stop.signal)
setSnapshot(status.snapshot)
show(status.active ? URL.createObjectURL(await client.pregenMap(stop.signal)) : null)
} catch (failure) {
if (!stop.signal.aborted) {
tell(failure instanceof Error ? failure.message : String(failure))
}
}
}
void refresh()
const timer = window.setInterval(() => void refresh(), POLL_MILLIS)
return () => {
stop.abort()
window.clearInterval(timer)
show(null)
}
}, [client, tell])
return { snapshot, picture }
}
+3 -1
View File
@@ -29,7 +29,9 @@ const VIEW_ICONS: Record<string, IdeIconName> = {
'iris:decorant/decorators': 'decoration',
'iris:objects': 'views/objects',
'iris:objects/procedural': 'views/procedural',
noise: 'views/noise'
noise: 'views/noise',
imageMaps: 'grid',
pregen: 'lightning'
}
const FALLBACK_ICON: IdeIconName = 'blocks'
/** Inset, because the stripe scrolls and so clips anything drawn outside its buttons. */