& {
+ showCloseButton?: boolean
+}) {
+ return (
+
+
+
+ {children}
+ {showCloseButton && (
+
+
+ Close
+
+ )}
+
+
+ )
+}
+
+function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+
+ )
+}
+
+function DialogFooter({
+ className,
+ showCloseButton = false,
+ children,
+ ...props
+}: React.ComponentProps<"div"> & {
+ showCloseButton?: boolean
+}) {
+ return (
+
+ {children}
+ {showCloseButton && (
+
+
+
+ )}
+
+ )
+}
+
+function DialogTitle({
+ className,
+ ...props
+}: React.ComponentProps) {
+ return (
+
+ )
+}
+
+function DialogDescription({
+ className,
+ ...props
+}: React.ComponentProps) {
+ return (
+
+ )
+}
+
+export {
+ Dialog,
+ DialogClose,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogOverlay,
+ DialogPortal,
+ DialogTitle,
+ DialogTrigger,
+}
diff --git a/studio/src/renderer/src/components/ui/input.tsx b/studio/src/renderer/src/components/ui/input.tsx
new file mode 100644
index 000000000..1e3b93289
--- /dev/null
+++ b/studio/src/renderer/src/components/ui/input.tsx
@@ -0,0 +1,20 @@
+import * as React from "react"
+import { cn } from "@/lib/utils"
+
+function Input({ className, type, ...props }: React.ComponentProps<"input">) {
+ return (
+
+ )
+}
+
+export { Input }
diff --git a/studio/src/renderer/src/components/ui/kbd.tsx b/studio/src/renderer/src/components/ui/kbd.tsx
new file mode 100644
index 000000000..95601b25b
--- /dev/null
+++ b/studio/src/renderer/src/components/ui/kbd.tsx
@@ -0,0 +1,28 @@
+import { cn } from "@/lib/utils"
+
+function Kbd({ className, ...props }: React.ComponentProps<"kbd">) {
+ return (
+
+ )
+}
+
+function KbdGroup({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+
+ )
+}
+
+export { Kbd, KbdGroup }
diff --git a/studio/src/renderer/src/components/ui/scroll-area.tsx b/studio/src/renderer/src/components/ui/scroll-area.tsx
new file mode 100644
index 000000000..b699a24ff
--- /dev/null
+++ b/studio/src/renderer/src/components/ui/scroll-area.tsx
@@ -0,0 +1,57 @@
+"use client"
+
+import * as React from "react"
+import { cn } from "@/lib/utils"
+import { ScrollArea as ScrollAreaPrimitive } from "radix-ui"
+
+function ScrollArea({
+ className,
+ children,
+ ...props
+}: React.ComponentProps) {
+ return (
+
+
+ {children}
+
+
+
+
+ )
+}
+
+function ScrollBar({
+ className,
+ orientation = "vertical",
+ ...props
+}: React.ComponentProps) {
+ return (
+
+
+
+ )
+}
+
+export { ScrollArea, ScrollBar }
diff --git a/studio/src/renderer/src/components/ui/separator.tsx b/studio/src/renderer/src/components/ui/separator.tsx
new file mode 100644
index 000000000..056d875a1
--- /dev/null
+++ b/studio/src/renderer/src/components/ui/separator.tsx
@@ -0,0 +1,25 @@
+import * as React from "react"
+import { cn } from "@/lib/utils"
+import { Separator as SeparatorPrimitive } from "radix-ui"
+
+function Separator({
+ className,
+ orientation = "horizontal",
+ decorative = true,
+ ...props
+}: React.ComponentProps) {
+ return (
+
+ )
+}
+
+export { Separator }
diff --git a/studio/src/renderer/src/components/ui/toggle-group.tsx b/studio/src/renderer/src/components/ui/toggle-group.tsx
new file mode 100644
index 000000000..54d3d9019
--- /dev/null
+++ b/studio/src/renderer/src/components/ui/toggle-group.tsx
@@ -0,0 +1,69 @@
+import * as React from "react"
+import { type VariantProps } from "class-variance-authority"
+import { ToggleGroup as ToggleGroupPrimitive } from "radix-ui"
+
+import { cn } from "@/lib/utils"
+import { toggleVariants } from "@/components/ui/toggle"
+
+const ToggleGroupContext = React.createContext>({
+ size: "default",
+ variant: "default",
+})
+
+function ToggleGroup({
+ className,
+ variant,
+ size,
+ children,
+ ...props
+}: React.ComponentProps &
+ VariantProps) {
+ return (
+
+
+ {children}
+
+
+ )
+}
+
+function ToggleGroupItem({
+ className,
+ children,
+ variant,
+ size,
+ ...props
+}: React.ComponentProps &
+ VariantProps) {
+ const context = React.useContext(ToggleGroupContext)
+
+ return (
+
+ {children}
+
+ )
+}
+
+export { ToggleGroup, ToggleGroupItem }
diff --git a/studio/src/renderer/src/components/ui/toggle.tsx b/studio/src/renderer/src/components/ui/toggle.tsx
new file mode 100644
index 000000000..137c38510
--- /dev/null
+++ b/studio/src/renderer/src/components/ui/toggle.tsx
@@ -0,0 +1,44 @@
+import * as React from "react"
+import { cva, type VariantProps } from "class-variance-authority"
+import { cn } from "@/lib/utils"
+import { Toggle as TogglePrimitive } from "radix-ui"
+
+const toggleVariants = cva(
+ "inline-flex items-center justify-center gap-2 rounded-md text-sm font-medium whitespace-nowrap transition-[color,box-shadow] outline-none hover:bg-muted hover:text-muted-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 data-[state=on]:bg-accent data-[state=on]:text-accent-foreground dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
+ {
+ variants: {
+ variant: {
+ default: "bg-transparent",
+ outline:
+ "border border-input bg-transparent shadow-xs hover:bg-accent hover:text-accent-foreground",
+ },
+ size: {
+ default: "h-9 min-w-9 px-2",
+ sm: "h-8 min-w-8 px-1.5",
+ lg: "h-10 min-w-10 px-2.5",
+ },
+ },
+ defaultVariants: {
+ variant: "default",
+ size: "default",
+ },
+ }
+)
+
+function Toggle({
+ className,
+ variant,
+ size,
+ ...props
+}: React.ComponentProps &
+ VariantProps) {
+ return (
+
+ )
+}
+
+export { Toggle, toggleVariants }
diff --git a/studio/src/renderer/src/components/ui/tooltip.tsx b/studio/src/renderer/src/components/ui/tooltip.tsx
new file mode 100644
index 000000000..ccc8fd335
--- /dev/null
+++ b/studio/src/renderer/src/components/ui/tooltip.tsx
@@ -0,0 +1,55 @@
+"use client"
+
+import * as React from "react"
+import { cn } from "@/lib/utils"
+import { Tooltip as TooltipPrimitive } from "radix-ui"
+
+function TooltipProvider({
+ delayDuration = 0,
+ ...props
+}: React.ComponentProps) {
+ return (
+
+ )
+}
+
+function Tooltip({
+ ...props
+}: React.ComponentProps) {
+ return
+}
+
+function TooltipTrigger({
+ ...props
+}: React.ComponentProps) {
+ return
+}
+
+function TooltipContent({
+ className,
+ sideOffset = 6,
+ children,
+ ...props
+}: React.ComponentProps) {
+ return (
+
+
+ {children}
+
+
+ )
+}
+
+export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider }
diff --git a/studio/src/renderer/src/css.d.ts b/studio/src/renderer/src/css.d.ts
new file mode 100644
index 000000000..5894ae0b6
--- /dev/null
+++ b/studio/src/renderer/src/css.d.ts
@@ -0,0 +1 @@
+declare module '*.css'
diff --git a/studio/src/renderer/src/editor/EditHistory.test.ts b/studio/src/renderer/src/editor/EditHistory.test.ts
new file mode 100644
index 000000000..a0852bf6e
--- /dev/null
+++ b/studio/src/renderer/src/editor/EditHistory.test.ts
@@ -0,0 +1,35 @@
+import { describe, expect, it } from 'vitest'
+import { EditHistory } from './EditHistory'
+
+describe('EditHistory', () => {
+ it('undoes back to the text before an edit and redoes forward again', () => {
+ const history = new EditHistory()
+ history.edited('a')
+
+ expect(history.nextUndo()).toBe('a')
+ history.undone('b')
+ expect(history.canUndo).toBe(false)
+ expect(history.nextRedo()).toBe('b')
+ history.redone('a')
+ expect(history.nextUndo()).toBe('a')
+ })
+
+ it('forgets what could be redone once a new edit is made', () => {
+ const history = new EditHistory()
+ history.edited('a')
+ history.undone('b')
+
+ history.edited('a')
+
+ expect(history.canRedo).toBe(false)
+ })
+
+ it('keeps the history as it was when an undo is never written', () => {
+ const history = new EditHistory()
+ history.edited('a')
+
+ history.nextUndo()
+
+ expect(history.canUndo).toBe(true)
+ })
+})
diff --git a/studio/src/renderer/src/editor/EditHistory.ts b/studio/src/renderer/src/editor/EditHistory.ts
new file mode 100644
index 000000000..b1b002caa
--- /dev/null
+++ b/studio/src/renderer/src/editor/EditHistory.ts
@@ -0,0 +1,45 @@
+const KEPT_STEPS = 100
+
+/**
+ * The texts a file had before each edit, so undoing writes an earlier text back whole. A step is only taken once its
+ * write succeeded, so a refused undo leaves the history as it was.
+ */
+export class EditHistory {
+ private readonly undos: string[] = []
+ private readonly redos: string[] = []
+
+ get canUndo(): boolean {
+ return this.undos.length > 0
+ }
+
+ get canRedo(): boolean {
+ return this.redos.length > 0
+ }
+
+ edited(before: string): void {
+ this.undos.push(before)
+ if (this.undos.length > KEPT_STEPS) {
+ this.undos.shift()
+ }
+ this.redos.length = 0
+ }
+
+ /** The text undoing writes, if there is one. */
+ nextUndo(): string | undefined {
+ return this.undos.at(-1)
+ }
+
+ undone(before: string): void {
+ this.undos.pop()
+ this.redos.push(before)
+ }
+
+ nextRedo(): string | undefined {
+ return this.redos.at(-1)
+ }
+
+ redone(before: string): void {
+ this.redos.pop()
+ this.undos.push(before)
+ }
+}
diff --git a/studio/src/renderer/src/editor/curves.test.ts b/studio/src/renderer/src/editor/curves.test.ts
new file mode 100644
index 000000000..8e00a484b
--- /dev/null
+++ b/studio/src/renderer/src/editor/curves.test.ts
@@ -0,0 +1,84 @@
+import { describe, expect, it } from 'vitest'
+import { canBecomeCurve, curveAt, curveFrom, isCurve, keyframesFrom, samplesOf, shapeFrom, withAddedKeyframe, withKeyframe, withoutKeyframe, withSetting, withShape } from './curves'
+
+describe('isCurve', () => {
+ it('holds only for keyframes and named shapes', () => {
+ expect(isCurve([[0, 1.3], [1, 0.2]])).toBe(true)
+ expect(isCurve({ shape: 'power', exponent: 3 })).toBe(true)
+ expect(isCurve([15, 20])).toBe(false)
+ expect(isCurve(4)).toBe(false)
+ expect(isCurve({ min: 3, max: 8 })).toBe(false)
+ expect(isCurve({ shape: 'zigzag' })).toBe(false)
+ })
+})
+
+describe('samplesOf', () => {
+ it('runs from the start of the curve to its end', () => {
+ expect(samplesOf([[0, 1.3], [1, 0.2]], 3)).toEqual([1.3, 0.75, 0.2].map((expected) => expect.closeTo(expected, 9)))
+ })
+
+ it('has none for a value that is no curve', () => {
+ expect(samplesOf(4, 3)).toBeNull()
+ })
+
+ it('follows a named curve between its from and to', () => {
+ expect(curveAt({ shape: 'power', exponent: 2, from: 10, to: 20 }, 0.5)).toBeCloseTo(12.5, 9)
+ expect(curveAt({ shape: 'linear' }, 0.25)).toBeCloseTo(0.25, 9)
+ })
+
+ it('holds the first and last values beyond the keyframes', () => {
+ expect(curveAt([[0.2, 5], [0.8, 9]], 0)).toBe(5)
+ expect(curveAt([[0.2, 5], [0.8, 9]], 1)).toBe(9)
+ })
+})
+
+describe('curveFrom', () => {
+ it('makes a number a flat curve and a range a rising one', () => {
+ expect(curveFrom(4)).toEqual([[0, 4], [1, 4]])
+ expect(curveFrom([15, 20])).toEqual([[0, 15], [1, 20]])
+ expect(curveFrom({ min: 3, max: 8 })).toEqual([[0, 3], [1, 8]])
+ })
+
+ it('leaves what is not a number or range alone', () => {
+ expect(curveFrom('wood')).toBeNull()
+ expect(canBecomeCurve([[0, 1], [1, 2]])).toBe(false)
+ expect(canBecomeCurve(4)).toBe(true)
+ })
+})
+
+describe('changing how a curve is written', () => {
+ it('turns keyframes into a linear shape between their ends, and back into sampled keyframes', () => {
+ const shape = shapeFrom([[1, 8], [0, 2]])
+
+ expect(shape).toEqual({ shape: 'linear', from: 2, to: 8 })
+ expect(keyframesFrom(shape).map(([t, value]) => [t, value])).toEqual([[0, 2], [0.25, 3.5], [0.5, 5], [0.75, 6.5], [1, 8]])
+ })
+
+ it('sets a shape setting, or leaves it out so the default applies', () => {
+ expect(withSetting({ shape: 'power', exponent: 3 }, 'exponent', 4)).toEqual({ shape: 'power', exponent: 4 })
+ expect(withSetting({ shape: 'power', exponent: 3 }, 'exponent', undefined)).toEqual({ shape: 'power' })
+ })
+
+ it('keeps from and to when the shape changes, but not the old shape settings', () => {
+ expect(withShape({ shape: 'power', exponent: 3, from: 1, to: 4 }, 'sine')).toEqual({ shape: 'sine', from: 1, to: 4 })
+ })
+})
+
+describe('editing keyframes', () => {
+ const keys: [number, number][] = [[0, 1], [1, 3]]
+
+ it('adds a keyframe halfway across the widest gap, on the curve', () => {
+ expect(withAddedKeyframe(keys)).toEqual([[0, 1], [0.5, 2], [1, 3]])
+ expect(withAddedKeyframe([[0, 1], [0.25, 1], [1, 3]])[2]).toEqual([0.625, expect.closeTo(1 + (2 * 0.375) / 0.75, 9)])
+ })
+
+ it('gives a lone keyframe a partner at the other end', () => {
+ expect(withAddedKeyframe([[0, 4]])).toEqual([[0, 4], [1, 4]])
+ })
+
+ it('sets and removes a keyframe but never removes the last one', () => {
+ expect(withKeyframe(keys, 1, [0.9, 5])).toEqual([[0, 1], [0.9, 5]])
+ expect(withoutKeyframe(keys, 0)).toEqual([[1, 3]])
+ expect(withoutKeyframe([[1, 3]], 0)).toEqual([[1, 3]])
+ })
+})
diff --git a/studio/src/renderer/src/editor/curves.ts b/studio/src/renderer/src/editor/curves.ts
new file mode 100644
index 000000000..5cf2a1fc9
--- /dev/null
+++ b/studio/src/renderer/src/editor/curves.ts
@@ -0,0 +1,217 @@
+/** One keyframe of a curve: where it is from 0 to 1, and the value there. */
+export type Keyframe = [number, number]
+
+export interface ShapeParameter {
+ name: string
+ fallback: number
+}
+
+/** A named curve (ProceduralValue.CurveShape): from 0 at t = 0 toward 1, stretched between a value's from and to. */
+export interface CurveShape {
+ key: string
+ parameters: ShapeParameter[]
+ at(t: number, parameter: (name: string) => number): number
+}
+
+const DEFAULT_FROM = 0
+const DEFAULT_TO = 1
+const KEYFRAME_SIZE = 2
+const RANGE_SIZE = 2
+const NARROWEST_BELL = 1e-6
+const SHAPE_STOPS = 5
+const FIRST_STOP = 0
+const LAST_STOP = 1
+
+export const CURVE_SHAPES: CurveShape[] = [
+ { key: 'linear', parameters: [], at: (t) => t },
+ { key: 'smooth', parameters: [], at: (t) => t * t * (3 - 2 * t) },
+ { key: 'power', parameters: [{ name: 'exponent', fallback: 2 }], at: (t, p) => Math.pow(t, p('exponent')) },
+ {
+ key: 'sigmoid',
+ parameters: [
+ { name: 'steepness', fallback: 10 },
+ { name: 'mid', fallback: 0.5 }
+ ],
+ at: (t, p) => 1 / (1 + Math.exp(-p('steepness') * (t - p('mid'))))
+ },
+ {
+ key: 'bell',
+ parameters: [
+ { name: 'mid', fallback: 0.5 },
+ { name: 'width', fallback: 0.15 }
+ ],
+ at: (t, p) => Math.exp(-0.5 * Math.pow((t - p('mid')) / Math.max(NARROWEST_BELL, p('width')), 2))
+ },
+ {
+ key: 'periodic',
+ parameters: [
+ { name: 'periods', fallback: 4 },
+ { name: 'sharpness', fallback: 8 }
+ ],
+ at: (t, p) => Math.pow(Math.max(0, Math.sin(2 * Math.PI * t * p('periods'))), p('sharpness'))
+ },
+ { key: 'sine', parameters: [{ name: 'periods', fallback: 1 }], at: (t, p) => 0.5 + 0.5 * Math.sin(2 * Math.PI * t * p('periods')) }
+]
+
+export function shapeNamed(key: unknown): CurveShape | undefined {
+ return typeof key === 'string' ? CURVE_SHAPES.find((shape) => shape.key === key.toLowerCase()) : undefined
+}
+
+function isObject(value: unknown): value is Record {
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
+}
+
+function isKeyframe(value: unknown): value is Keyframe {
+ return Array.isArray(value) && value.length === KEYFRAME_SIZE && value.every((part) => typeof part === 'number')
+}
+
+/** Whether {@code value} is keyframes [[t, value], ...], which a range [min, max] and a number are not. */
+export function isKeyframes(value: unknown): value is Keyframe[] {
+ return Array.isArray(value) && value.length > 0 && value.every(isKeyframe)
+}
+
+/** Whether {@code value} is a named curve {"shape": ...} the studio knows. */
+export function isShape(value: unknown): value is Record {
+ return isObject(value) && shapeNamed(value.shape) !== undefined
+}
+
+/** Whether {@code value} is a curve, as opposed to a number or a [min, max] range. */
+export function isCurve(value: unknown): boolean {
+ return isKeyframes(value) || isShape(value)
+}
+
+/** Whether {@code value} is a number or a range, which {@link curveFrom} makes a curve. */
+export function canBecomeCurve(value: unknown): boolean {
+ return typeof value === 'number' || rangeOf(value) !== null
+}
+
+function rangeOf(value: unknown): [number, number] | null {
+ if (Array.isArray(value) && value.length === RANGE_SIZE && value.every((part) => typeof part === 'number')) {
+ return [value[0], value[1]]
+ }
+ if (isObject(value) && typeof value.min === 'number' && typeof value.max === 'number') {
+ return [value.min, value.max]
+ }
+ return null
+}
+
+/** A number as a curve that stays at it, a range as a curve rising from its low end to its high end; null for anything else. */
+export function curveFrom(value: unknown): Keyframe[] | null {
+ if (typeof value === 'number') {
+ return [
+ [0, value],
+ [1, value]
+ ]
+ }
+ const range = rangeOf(value)
+ return range === null
+ ? null
+ : [
+ [0, range[0]],
+ [1, range[1]]
+ ]
+}
+
+function numberOf(written: unknown, fallback: number): number {
+ return typeof written === 'number' ? written : fallback
+}
+
+/** The value of a curve at {@code t}, from 0 to 1; NaN for a value that is no curve. */
+export function curveAt(value: unknown, t: number): number {
+ if (isKeyframes(value)) {
+ return keyframesAt(sortedKeyframes(value), t)
+ }
+ if (!isShape(value)) {
+ return Number.NaN
+ }
+ const shape = shapeNamed(value.shape)!
+ const from = numberOf(value.from, DEFAULT_FROM)
+ const to = numberOf(value.to, DEFAULT_TO)
+ const parameter = (name: string): number => numberOf(value[name], shape.parameters.find((candidate) => candidate.name === name)!.fallback)
+ return from + (to - from) * shape.at(Math.max(0, Math.min(1, t)), parameter)
+}
+
+export function sortedKeyframes(keys: Keyframe[]): Keyframe[] {
+ return [...keys].sort((a, b) => a[0] - b[0])
+}
+
+function keyframesAt(keys: Keyframe[], t: number): number {
+ if (t <= keys[0][0]) {
+ return keys[0][1]
+ }
+ for (let index = 1; index < keys.length; index++) {
+ if (t <= keys[index][0]) {
+ const span = keys[index][0] - keys[index - 1][0]
+ const blend = span <= 0 ? 1 : (t - keys[index - 1][0]) / span
+ return keys[index - 1][1] + (keys[index][1] - keys[index - 1][1]) * blend
+ }
+ }
+ return keys[keys.length - 1][1]
+}
+
+/** {@code count} values of the curve, from its start to its end; null for a value that is no curve. */
+export function samplesOf(value: unknown, count: number): number[] | null {
+ if (!isCurve(value)) {
+ return null
+ }
+ return Array.from({ length: count }, (_, index) => curveAt(value, count === 1 ? 0 : index / (count - 1)))
+}
+
+/** The curve as keyframes, such as to move a named curve's shape by hand: its values at evenly spaced points. */
+export function keyframesFrom(value: unknown): Keyframe[] {
+ if (isKeyframes(value)) {
+ return value
+ }
+ const stops = Array.from({ length: SHAPE_STOPS }, (_, index) => FIRST_STOP + ((LAST_STOP - FIRST_STOP) * index) / (SHAPE_STOPS - 1))
+ return stops.map((t): Keyframe => [t, curveAt(value, t)])
+}
+
+/** A linear named curve between the first and last keyframes' values, or the shape itself. */
+export function shapeFrom(value: unknown): Record {
+ if (isShape(value)) {
+ return value
+ }
+ const keys = isKeyframes(value) ? sortedKeyframes(value) : []
+ return { shape: 'linear', from: keys.length > 0 ? keys[0][1] : DEFAULT_FROM, to: keys.length > 0 ? keys[keys.length - 1][1] : DEFAULT_TO }
+}
+
+/** The shape with {@code key}, keeping its from and to; the other settings of the old shape do not carry over. */
+export function withShape(shape: Record, key: string): Record {
+ return { shape: key, from: numberOf(shape.from, DEFAULT_FROM), to: numberOf(shape.to, DEFAULT_TO) }
+}
+
+/** The shape with {@code name} set to {@code number}, or left out when it is undefined so the shape's own default applies. */
+export function withSetting(shape: Record, name: string, number: number | undefined): Record {
+ const { [name]: _replaced, ...others } = shape
+ return number === undefined ? others : { ...others, [name]: number }
+}
+
+/** The keyframes with the one at {@code index} (as listed) set to {@code keyframe}. */
+export function withKeyframe(keys: Keyframe[], index: number, keyframe: Keyframe): Keyframe[] {
+ return keys.map((existing, position) => (position === index ? keyframe : existing))
+}
+
+/** The keyframes without the one at {@code index}; the last one stays, since a curve needs a keyframe. */
+export function withoutKeyframe(keys: Keyframe[], index: number): Keyframe[] {
+ return keys.length <= 1 ? keys : keys.filter((_, position) => position !== index)
+}
+
+/** The keyframes with one more halfway across the widest gap, on the curve as it is; a lone keyframe gets one at the other end. */
+export function withAddedKeyframe(keys: Keyframe[]): Keyframe[] {
+ const sorted = sortedKeyframes(keys)
+ if (sorted.length === 1) {
+ const t = sorted[0][0] === LAST_STOP ? FIRST_STOP : LAST_STOP
+ return sortedKeyframes([...sorted, [t, sorted[0][1]]])
+ }
+ let widest = 0
+ let before = 0
+ for (let index = 1; index < sorted.length; index++) {
+ const gap = sorted[index][0] - sorted[index - 1][0]
+ if (gap > widest) {
+ widest = gap
+ before = index - 1
+ }
+ }
+ const t = sorted[before][0] + widest / 2
+ return sortedKeyframes([...sorted, [t, keyframesAt(sorted, t)]])
+}
diff --git a/studio/src/renderer/src/editor/entryKeys.test.ts b/studio/src/renderer/src/editor/entryKeys.test.ts
new file mode 100644
index 000000000..7e57836b8
--- /dev/null
+++ b/studio/src/renderer/src/editor/entryKeys.test.ts
@@ -0,0 +1,32 @@
+import { describe, expect, it } from 'vitest'
+import { folderPrefixOf, refusalOfNewKey } from './entryKeys'
+
+describe('refusalOfNewKey', () => {
+ it('accepts a free, plain key', () => {
+ expect(refusalOfNewKey('trees/oak-2', ['trees/oak'])).toBeNull()
+ })
+
+ it('refuses a key that is taken', () => {
+ expect(refusalOfNewKey('trees/oak', ['trees/oak'])).toBe('trees/oak already exists')
+ })
+
+ it('refuses a blank name', () => {
+ expect(refusalOfNewKey(' ', [])).toBe('Give it a name')
+ })
+
+ it('refuses keys that could leave the folder or are not plain', () => {
+ for (const key of ['Trees/Oak', 'trees//oak', '/oak', 'oak/', '../oak', 'trees/../oak', 'oak.json', 'trees\\oak']) {
+ expect(refusalOfNewKey(key, []), key).toMatch(/^Use lower case/)
+ }
+ })
+})
+
+describe('folderPrefixOf', () => {
+ it('keeps the folders of a key with their closing slash', () => {
+ expect(folderPrefixOf('trees/oak/tall')).toBe('trees/oak/')
+ })
+
+ it('is empty for a key in no folder', () => {
+ expect(folderPrefixOf('oak')).toBe('')
+ })
+})
diff --git a/studio/src/renderer/src/editor/entryKeys.ts b/studio/src/renderer/src/editor/entryKeys.ts
new file mode 100644
index 000000000..e16123e5f
--- /dev/null
+++ b/studio/src/renderer/src/editor/entryKeys.ts
@@ -0,0 +1,18 @@
+const FOLDER_SEPARATOR = '/'
+const KEY = /^[a-z0-9_-]+(\/[a-z0-9_-]+)*$/
+
+/** Why `key` can't name a new entry beside the `existing` ones, or null when it can; the server checks the same. */
+export function refusalOfNewKey(key: string, existing: readonly string[]): string | null {
+ if (key.trim() === '') {
+ return 'Give it a name'
+ }
+ if (!KEY.test(key)) {
+ return 'Use lower case letters, digits, - and _, with / between folders'
+ }
+ return existing.includes(key) ? `${key} already exists` : null
+}
+
+/** The folder of `key` as a start for naming a new entry in it, such as `trees/`; empty for an entry in no folder. */
+export function folderPrefixOf(key: string): string {
+ return key.slice(0, key.lastIndexOf(FOLDER_SEPARATOR) + 1)
+}
diff --git a/studio/src/renderer/src/editor/jsonValues.ts b/studio/src/renderer/src/editor/jsonValues.ts
new file mode 100644
index 000000000..418f01b2d
--- /dev/null
+++ b/studio/src/renderer/src/editor/jsonValues.ts
@@ -0,0 +1,22 @@
+import type { JsonPath } from '../bridge/types'
+
+/** The value at {@code path} in a parsed file; undefined where nothing is written. */
+export function valueAt(root: unknown, path: JsonPath): unknown {
+ let current = root
+ for (const step of path) {
+ if (current === null || typeof current !== 'object') {
+ return undefined
+ }
+ current = (current as Record)[step]
+ }
+ return current
+}
+
+/** The file parsed, or undefined when it is not JSON (the editor then shows why instead). */
+export function parsedText(text: string): unknown {
+ try {
+ return JSON.parse(text)
+ } catch {
+ return undefined
+ }
+}
diff --git a/studio/src/renderer/src/editor/nodeLayout.test.ts b/studio/src/renderer/src/editor/nodeLayout.test.ts
new file mode 100644
index 000000000..78e4d8f97
--- /dev/null
+++ b/studio/src/renderer/src/editor/nodeLayout.test.ts
@@ -0,0 +1,68 @@
+import { describe, expect, it } from 'vitest'
+import type { GraphNode, JsonPath } from '../bridge/types'
+import { NO_PART } from '../bridge/types'
+import { isWithin, layoutNodes, nodeDrawingPart, NODE_WIDTH } from './nodeLayout'
+
+function node(path: JsonPath, children: GraphNode[] = []): GraphNode {
+ return {
+ kind: 'Stem',
+ title: 'Stem',
+ path,
+ partId: NO_PART,
+ roles: [],
+ settings: [],
+ children: children.map((child) => ({ wire: '', node: child })),
+ childList: null,
+ movable: true,
+ duplicable: true,
+ additions: []
+ }
+}
+
+describe('layoutNodes', () => {
+ it('sets a parent level with the middle of its children, a column to their left', () => {
+ const layout = layoutNodes([node([], [node(['parts', 0]), node(['parts', 1]), node(['parts', 2])])])
+ const [first, , last, parent] = layout.nodes
+
+ expect(parent.y).toBe((first.y + last.y) / 2)
+ expect(first.x - parent.x).toBeGreaterThan(NODE_WIDTH)
+ expect(layout.wires).toHaveLength(3)
+ })
+
+ it('lays the next root out under the tree before it', () => {
+ const layout = layoutNodes([node([], [node(['parts', 0])]), node(['materials', 0])])
+ const material = layout.nodes.find((placed) => placed.id === JSON.stringify(['materials', 0]))!
+
+ expect(material.x).toBe(0)
+ expect(material.y).toBeGreaterThan(Math.max(...layout.nodes.filter((placed) => placed !== material).map((placed) => placed.y)))
+ })
+})
+
+describe('nodeDrawingPart', () => {
+ const drawing = (path: JsonPath, partId: number, children: GraphNode[] = []): GraphNode => ({ ...node(path, children), partId })
+
+ it('finds the node that draws the part, whichever tree and depth it is in', () => {
+ const roots = [drawing([], 0, [drawing(['parts', 0], 1)]), drawing(['materials', 0], NO_PART, [drawing(['materials', 0, 'parts', 0], 2)])]
+
+ expect(nodeDrawingPart(roots, 1)?.path).toEqual(['parts', 0])
+ expect(nodeDrawingPart(roots, 2)?.path).toEqual(['materials', 0, 'parts', 0])
+ })
+
+ it('takes the outer node when a node and the one it copies draw the same part', () => {
+ const roots = [drawing([], 3, [drawing(['branches', 'part'], 3)])]
+
+ expect(nodeDrawingPart(roots, 3)?.path).toEqual([])
+ })
+
+ it('finds none for a part no node draws', () => {
+ expect(nodeDrawingPart([drawing([], 0)], 5)).toBeNull()
+ })
+})
+
+describe('isWithin', () => {
+ it('holds for the path itself and what sits inside it, not for a sibling', () => {
+ expect(isWithin(['parts', 0, 'children', 1], ['parts', 0])).toBe(true)
+ expect(isWithin(['parts', 0], ['parts', 0])).toBe(true)
+ expect(isWithin(['parts', 1], ['parts', 0])).toBe(false)
+ })
+})
diff --git a/studio/src/renderer/src/editor/nodeLayout.ts b/studio/src/renderer/src/editor/nodeLayout.ts
new file mode 100644
index 000000000..4f300a441
--- /dev/null
+++ b/studio/src/renderer/src/editor/nodeLayout.ts
@@ -0,0 +1,108 @@
+import type { GraphNode, JsonPath } from '../bridge/types'
+
+export const NODE_WIDTH = 168
+export const NODE_HEIGHT = 46
+const COLUMN_GAP = 64
+const ROW_GAP = 10
+const TREE_GAP = 26
+
+/** A node where the canvas draws it, by its top left corner; `id` tells it from every other node of the file. */
+export interface PlacedNode {
+ id: string
+ node: GraphNode
+ x: number
+ y: number
+}
+
+export interface PlacedWire {
+ from: PlacedNode
+ to: PlacedNode
+ label: string
+}
+
+export interface NodeLayout {
+ nodes: PlacedNode[]
+ wires: PlacedWire[]
+ width: number
+ height: number
+}
+
+export function idOf(path: JsonPath): string {
+ return JSON.stringify(path)
+}
+
+/** The node at {@code path} among the trees of {@code roots}, or null when there is none, such as after it was deleted. */
+export function nodeWithPath(roots: GraphNode[], path: JsonPath): GraphNode | null {
+ const id = idOf(path)
+ for (const root of roots) {
+ if (idOf(root.path) === id) {
+ return root
+ }
+ const found = nodeWithPath(
+ root.children.map((link) => link.node),
+ path
+ )
+ if (found !== null) {
+ return found
+ }
+ }
+ return null
+}
+
+/** The first node, going down each tree in turn, that draws {@code part}, or null when none does. */
+export function nodeDrawingPart(roots: GraphNode[], part: number): GraphNode | null {
+ for (const root of roots) {
+ if (root.partId === part) {
+ return root
+ }
+ const found = nodeDrawingPart(
+ root.children.map((link) => link.node),
+ part
+ )
+ if (found !== null) {
+ return found
+ }
+ }
+ return null
+}
+
+/** Whether {@code path} is {@code ancestor} or sits inside it. */
+export function isWithin(path: JsonPath, ancestor: JsonPath): boolean {
+ return ancestor.length <= path.length && ancestor.every((step, index) => path[index] === step)
+}
+
+/**
+ * Lays each root's tree out from left to right, a column per generation, one tree under the other. Leaves take a row
+ * each and a parent sits level with the middle of its children, so wires never cross.
+ */
+export function layoutNodes(roots: GraphNode[]): NodeLayout {
+ const nodes: PlacedNode[] = []
+ const wires: PlacedWire[] = []
+ let nextTop = 0
+ let width = 0
+
+ const place = (node: GraphNode, depth: number): PlacedNode => {
+ const x = depth * (NODE_WIDTH + COLUMN_GAP)
+ width = Math.max(width, x + NODE_WIDTH)
+ const children = node.children.map((link) => ({ label: link.wire, placed: place(link.node, depth + 1) }))
+ const y = children.length === 0 ? takeRow() : (children[0].placed.y + children[children.length - 1].placed.y) / 2
+ const placed: PlacedNode = { id: idOf(node.path), node, x, y }
+ nodes.push(placed)
+ for (const child of children) {
+ wires.push({ from: placed, to: child.placed, label: child.label })
+ }
+ return placed
+ }
+
+ const takeRow = (): number => {
+ const top = nextTop
+ nextTop += NODE_HEIGHT + ROW_GAP
+ return top
+ }
+
+ for (const root of roots) {
+ place(root, 0)
+ nextTop += TREE_GAP
+ }
+ return { nodes, wires, width, height: Math.max(0, nextTop - ROW_GAP - TREE_GAP) }
+}
diff --git a/studio/src/renderer/src/editor/settingFolds.test.ts b/studio/src/renderer/src/editor/settingFolds.test.ts
new file mode 100644
index 000000000..90b180090
--- /dev/null
+++ b/studio/src/renderer/src/editor/settingFolds.test.ts
@@ -0,0 +1,79 @@
+import { describe, expect, it } from 'vitest'
+import type { NodeSettings, SettingOption, SettingsType, ValueKind } from '../bridge/types'
+import { foldedSections, idOfFold, visibleFolds } from './settingFolds'
+
+function option(name: string, kind: ValueKind): SettingOption {
+ return { name, description: '', required: false, minimum: null, maximum: null, minItems: null, defaultValue: null, kind }
+}
+
+const text: ValueKind = { kind: 'text', format: 'PLAIN' }
+const any: ValueKind = { kind: 'any' }
+
+const types: Record = {
+ Material: {
+ description: '',
+ options: [
+ option('role', text),
+ option('block', { kind: 'reference', reference: 'BLOCK', format: 'BLOCK_ID' }),
+ option('offset', { kind: 'object', type: 'Offset' }),
+ option('rules', { kind: 'list', element: { kind: 'object', type: 'Rule' }, unique: false }),
+ option('parts', { kind: 'list', element: { kind: 'object', type: 'Rule' }, unique: false })
+ ]
+ },
+ Offset: { description: '', options: [option('x', any), option('y', any)] },
+ Rule: { description: '', options: [option('chance', any), option('face', text)] }
+}
+
+const material: NodeSettings = { title: 'Material', path: ['materials', 0], type: 'Material', shownAsNodes: ['parts'] }
+const file = {
+ materials: [
+ {
+ role: 'wood',
+ block: 'minecraft:birch_wood',
+ offset: { x: 2, y: [[0, 1], [1, 0]] },
+ rules: [{ chance: 0.5 }, { face: 'top' }]
+ }
+ ]
+}
+
+describe('foldedSections', () => {
+ it('folds an object setting into a section, and a list of objects into a section of items', () => {
+ const folds = foldedSections(material, types, file)
+
+ expect(folds.map((fold) => fold.title)).toEqual(['Material', 'offset', 'rules', '1', '2'])
+ expect(folds.map((fold) => fold.kind)).toEqual(['own', 'group', 'list', 'item', 'item'])
+ expect(folds.map((fold) => fold.depth)).toEqual([0, 1, 1, 2, 2])
+ expect(folds[4].path).toEqual(['materials', 0, 'rules', 1])
+ expect(folds[2].holder).toEqual({ object: ['materials', 0], key: 'rules' })
+ })
+
+ it('leaves the folded settings and the ones shown as nodes out of the fields of the section that holds them', () => {
+ const [own] = foldedSections(material, types, file)
+
+ expect(own.options.map((setting) => setting.name)).toEqual(['role', 'block'])
+ })
+
+ it('sums a section up by what it holds, a curve as curve and the default namespace left off', () => {
+ const folds = foldedSections(material, types, file)
+
+ expect(folds[0].summary).toBe('role wood · block birch_wood · rules 2')
+ expect(folds[1].summary).toBe('x 2 · y curve')
+ expect(folds[2].summary).toBe('2 items')
+ })
+
+ it('keeps a setting that is not written as an object a field', () => {
+ const [own, ...inside] = foldedSections(material, types, { materials: [{ role: 'wood' }] })
+
+ expect(inside).toEqual([])
+ expect(own.options.map((setting) => setting.name)).toEqual(['role', 'block', 'offset', 'rules'])
+ })
+})
+
+describe('visibleFolds', () => {
+ it('hides what is inside a fold that is folded', () => {
+ const folds = foldedSections(material, types, file)
+
+ expect(visibleFolds(folds, new Set()).map((fold) => fold.title)).toEqual(['Material', 'offset', 'rules'])
+ expect(visibleFolds(folds, new Set([idOfFold(folds[2])])).map((fold) => fold.title)).toEqual(['Material', 'offset', 'rules', '1', '2'])
+ })
+})
diff --git a/studio/src/renderer/src/editor/settingFolds.ts b/studio/src/renderer/src/editor/settingFolds.ts
new file mode 100644
index 000000000..f6a9dc943
--- /dev/null
+++ b/studio/src/renderer/src/editor/settingFolds.ts
@@ -0,0 +1,128 @@
+import type { JsonPath, NodeSettings, SettingOption, SettingsType } from '../bridge/types'
+import { isCurve } from './curves'
+import { isWithin } from './nodeLayout'
+import { textOf } from './settingText'
+import { valueAt } from './jsonValues'
+
+const SUMMARY_SETTINGS = 3
+const SUMMARY_SEPARATOR = ' · '
+const DEFAULT_NAMESPACE = 'minecraft:'
+
+/**
+ * What a section is: a node's own settings, a setting written as an object, a setting written as a list of objects, or
+ * one element of such a list. All but the first fold.
+ */
+export type FoldKind = 'own' | 'group' | 'list' | 'item'
+
+/** One object of the file whose settings the inspector shows, below the ones that hold it. */
+export interface SettingsFold {
+ title: string
+ path: JsonPath
+ type: string
+ kind: FoldKind
+ /** 0 for a node's own sections, one more for each object it is inside. */
+ depth: number
+ /** A short reading of what it holds, shown while it is folded. */
+ summary: string
+ /** The object and member that hold a group or list, to unset it; null for the rest. */
+ holder: { object: JsonPath; key: string } | null
+ /** The settings written plainly in it, as fields; those that are folds of their own are not among them. */
+ options: SettingOption[]
+}
+
+function isObject(value: unknown): value is Record {
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
+}
+
+function isObjects(value: unknown): value is Record[] {
+ return Array.isArray(value) && value.every(isObject)
+}
+
+export function idOfFold(fold: SettingsFold): string {
+ return JSON.stringify(fold.path)
+}
+
+/**
+ * The sections of one object of a node and the objects inside it, in file order, each followed by those inside it. A
+ * setting that is itself an object whose type the schema describes is a section of its own one level deeper, and so is
+ * each element of a list of objects; one that is not written stays a field.
+ */
+export function foldedSections(section: NodeSettings, types: Record, values: unknown): SettingsFold[] {
+ const folds: SettingsFold[] = []
+ addFold(folds, types, values, { title: section.title, path: section.path, type: section.type, kind: 'own', depth: 0, holder: null }, new Set(section.shownAsNodes))
+ return folds
+}
+
+type FoldHead = Pick
+
+function addFold(into: SettingsFold[], types: Record, values: unknown, head: FoldHead, shownAsNodes: Set): void {
+ const options: SettingOption[] = []
+ const inside: SettingsFold[] = []
+ const summary: string[] = []
+ for (const option of types[head.type]?.options ?? []) {
+ if (shownAsNodes.has(option.name)) {
+ continue
+ }
+ const path = [...head.path, option.name]
+ const value = valueAt(values, path)
+ const holder = { object: head.path, key: option.name }
+ const objectType = option.kind.kind === 'object' ? option.kind.type : null
+ const itemType = option.kind.kind === 'list' && option.kind.element.kind === 'object' ? option.kind.element.type : null
+ if (objectType !== null && isObject(value) && types[objectType] !== undefined) {
+ addFold(inside, types, values, { title: option.name, path, type: objectType, kind: 'group', depth: head.depth + 1, holder }, new Set())
+ continue
+ }
+ if (itemType !== null && isObjects(value) && types[itemType] !== undefined) {
+ addList(inside, types, values, { option, path, itemType, count: value.length, depth: head.depth + 1, holder })
+ summary.push(`${option.name} ${value.length}`)
+ continue
+ }
+ options.push(option)
+ if (value !== undefined) {
+ summary.push(`${option.name} ${shortText(option, value)}`)
+ }
+ }
+ into.push({ ...head, summary: summary.slice(0, SUMMARY_SETTINGS).join(SUMMARY_SEPARATOR), options })
+ into.push(...inside)
+}
+
+interface ListFold {
+ option: SettingOption
+ path: JsonPath
+ itemType: string
+ count: number
+ depth: number
+ holder: { object: JsonPath; key: string }
+}
+
+function addList(into: SettingsFold[], types: Record, values: unknown, list: ListFold): void {
+ into.push({
+ title: list.option.name,
+ path: list.path,
+ type: list.itemType,
+ kind: 'list',
+ depth: list.depth,
+ summary: `${list.count} ${list.count === 1 ? 'item' : 'items'}`,
+ holder: list.holder,
+ options: []
+ })
+ for (let index = 0; index < list.count; index++) {
+ addFold(
+ into,
+ types,
+ values,
+ { title: String(index + 1), path: [...list.path, index], type: list.itemType, kind: 'item', depth: list.depth + 1, holder: null },
+ new Set()
+ )
+ }
+}
+
+function shortText(option: SettingOption, value: unknown): string {
+ return isCurve(value) ? 'curve' : textOf(option.kind, value).replaceAll(DEFAULT_NAMESPACE, '')
+}
+
+/** The folds shown while the ones in {@code open} are unfolded: a fold inside another that is folded is hidden. */
+export function visibleFolds(folds: SettingsFold[], open: ReadonlySet): SettingsFold[] {
+ const foldable = folds.filter((fold) => fold.kind !== 'own')
+ return folds.filter((fold) => !foldable.some((outer) => outer !== fold && !open.has(idOfFold(outer)) && outer.path.length < fold.path.length && isWithin(fold.path, outer.path)))
+}
diff --git a/studio/src/renderer/src/editor/settingText.test.ts b/studio/src/renderer/src/editor/settingText.test.ts
new file mode 100644
index 000000000..9b21e067c
--- /dev/null
+++ b/studio/src/renderer/src/editor/settingText.test.ts
@@ -0,0 +1,27 @@
+import { describe, expect, it } from 'vitest'
+import type { ValueKind } from '../bridge/types'
+import { literalOf, textOf } from './settingText'
+
+const roles: ValueKind = { kind: 'list', element: { kind: 'text', format: 'PLAIN' }, unique: false }
+
+describe('string lists', () => {
+ it('read as commas and are written back quoted', () => {
+ expect(textOf(roles, ['wood', 'leaves'])).toBe('wood, leaves')
+ expect(literalOf(roles, 'wood, leaves, ')).toBe('["wood","leaves"]')
+ expect(literalOf(roles, ',')).toBe('[]')
+ })
+
+ it('keep a list typed as JSON, and show a list of anything else as JSON', () => {
+ expect(literalOf(roles, '["a", "b"]')).toBe('["a", "b"]')
+ expect(textOf(roles, [1, 2])).toBe('[1,2]')
+ })
+})
+
+describe('text', () => {
+ it('shows a string as it is and writes it quoted', () => {
+ const text: ValueKind = { kind: 'text', format: 'PLAIN' }
+
+ expect(textOf(text, 'wood')).toBe('wood')
+ expect(literalOf(text, 'wood "a"')).toBe('"wood \\"a\\""')
+ })
+})
diff --git a/studio/src/renderer/src/editor/settingText.ts b/studio/src/renderer/src/editor/settingText.ts
new file mode 100644
index 000000000..d02ebe432
--- /dev/null
+++ b/studio/src/renderer/src/editor/settingText.ts
@@ -0,0 +1,48 @@
+import type { ValueKind } from '../bridge/types'
+
+export const NOT_SET = ''
+export const LIST_SEPARATOR = ', '
+
+/** Whether {@code kind} is a string naming something, typed as text. */
+export function isText(kind: ValueKind): boolean {
+ return kind.kind === 'text' || kind.kind === 'reference' || kind.kind === 'resource'
+}
+
+/** Whether {@code kind} is a list of strings, such as the roles a decoration goes on, which is typed as {@code a, b}. */
+export function isStringList(kind: ValueKind): boolean {
+ return kind.kind === 'list' && isText(kind.element)
+}
+
+function isStrings(value: unknown): value is string[] {
+ return Array.isArray(value) && value.every((element) => typeof element === 'string')
+}
+
+/** What the field shows for the value the file holds. */
+export function textOf(kind: ValueKind, value: unknown): string {
+ if (value === undefined) {
+ return NOT_SET
+ }
+ if (isText(kind) && typeof value === 'string') {
+ return value
+ }
+ return isStringList(kind) && isStrings(value) ? value.join(LIST_SEPARATOR) : JSON.stringify(value)
+}
+
+/** The strings a list is typed as, each trimmed, and none left empty. */
+export function itemsOf(draft: string): string[] {
+ return draft
+ .split(',')
+ .map((item) => item.trim())
+ .filter((item) => item !== '')
+}
+
+/** What the field holds as JSON to write; a list typed as {@code a, b} is written as an array unless it already is one. */
+export function literalOf(kind: ValueKind, draft: string): string {
+ if (isText(kind)) {
+ return JSON.stringify(draft)
+ }
+ if (isStringList(kind) && !draft.trim().startsWith('[')) {
+ return JSON.stringify(itemsOf(draft))
+ }
+ return draft.trim()
+}
diff --git a/studio/src/renderer/src/editor/suggestionStore.test.ts b/studio/src/renderer/src/editor/suggestionStore.test.ts
new file mode 100644
index 000000000..a61887c83
--- /dev/null
+++ b/studio/src/renderer/src/editor/suggestionStore.test.ts
@@ -0,0 +1,25 @@
+import { describe, expect, it, vi } from 'vitest'
+import { SuggestionStore } from './suggestionStore'
+
+describe('SuggestionStore', () => {
+ it('asks once for a list however often it is read', async () => {
+ const fetch = vi.fn().mockResolvedValue(['minecraft:stone'])
+ const store = new SuggestionStore(fetch)
+
+ await store.load({ from: 'reference', reference: 'BLOCK' })
+ const again = await store.load({ from: 'reference', reference: 'BLOCK' })
+
+ expect(again).toEqual(['minecraft:stone'])
+ expect(fetch).toHaveBeenCalledTimes(1)
+ expect(fetch).toHaveBeenCalledWith({ reference: 'BLOCK' })
+ })
+
+ it('asks again after a list could not be read', async () => {
+ const fetch = vi.fn().mockRejectedValueOnce(new Error('down')).mockResolvedValue(['birch'])
+ const store = new SuggestionStore(fetch)
+
+ await expect(store.load({ from: 'resource', resource: 'iris:object' })).rejects.toThrow('down')
+ await expect(store.load({ from: 'resource', resource: 'iris:object' })).resolves.toEqual(['birch'])
+ expect(fetch).toHaveBeenLastCalledWith({ resource: 'iris:object' })
+ })
+})
diff --git a/studio/src/renderer/src/editor/suggestionStore.ts b/studio/src/renderer/src/editor/suggestionStore.ts
new file mode 100644
index 000000000..de6b89aa8
--- /dev/null
+++ b/studio/src/renderer/src/editor/suggestionStore.ts
@@ -0,0 +1,23 @@
+import { sourceKey, type ListedSource } from './suggestions'
+
+/** What the server lists for the suggestions of a source that names platform or pack entries. */
+export type SuggestionFetch = (of: { reference: string } | { resource: string }) => Promise
+
+/** The suggestion lists, each asked for once; a list that could not be read is asked for again next time. */
+export class SuggestionStore {
+ private readonly lists = new Map>()
+
+ constructor(private readonly fetch: SuggestionFetch) {}
+
+ load(source: ListedSource): Promise {
+ const key = sourceKey(source)
+ const known = this.lists.get(key)
+ if (known !== undefined) {
+ return known
+ }
+ const asked = this.fetch(source.from === 'reference' ? { reference: source.reference } : { resource: source.resource })
+ this.lists.set(key, asked)
+ asked.catch(() => this.lists.delete(key))
+ return asked
+ }
+}
diff --git a/studio/src/renderer/src/editor/suggestions.test.ts b/studio/src/renderer/src/editor/suggestions.test.ts
new file mode 100644
index 000000000..a2ae79600
--- /dev/null
+++ b/studio/src/renderer/src/editor/suggestions.test.ts
@@ -0,0 +1,82 @@
+import { describe, expect, it } from 'vitest'
+import type { GraphNode, SettingOption } from '../bridge/types'
+import { NO_PART } from '../bridge/types'
+import { completed, matching, rolesOf, suggestionSourceOf, wordBeingTyped } from './suggestions'
+
+function option(name: string, kind: SettingOption['kind']): SettingOption {
+ return { name, description: '', required: false, minimum: null, maximum: null, minItems: null, defaultValue: null, kind }
+}
+
+function node(roles: string[], children: GraphNode[] = []): GraphNode {
+ return {
+ kind: 'Stem',
+ title: 'Stem',
+ path: [],
+ partId: NO_PART,
+ roles,
+ settings: [],
+ children: children.map((child) => ({ wire: '', node: child })),
+ childList: null,
+ movable: false,
+ duplicable: false,
+ additions: []
+ }
+}
+
+describe('suggestionSourceOf', () => {
+ it('names the registry of a reference, the kind of a resource and the roles of the object', () => {
+ expect(suggestionSourceOf('Material', option('block', { kind: 'reference', reference: 'BLOCK', format: 'BLOCK_ID' }))).toEqual({ from: 'reference', reference: 'BLOCK' })
+ expect(suggestionSourceOf('Part', option('skin', { kind: 'resource', resource: 'iris:object' }))).toEqual({ from: 'resource', resource: 'iris:object' })
+ })
+
+ it('takes the roles for the settings that name one', () => {
+ const on = option('on', { kind: 'list', element: { kind: 'text', format: 'PLAIN' }, unique: false })
+
+ expect(suggestionSourceOf('art.arcane.iris.engine.procedural.part.ProceduralDecoration', on)).toEqual({ from: 'roles' })
+ expect(suggestionSourceOf('art.arcane.iris.engine.procedural.part.ProceduralDecoration', option('at', { kind: 'text', format: 'PLAIN' }))).toBeNull()
+ })
+
+ it('takes the elements of a list of references, and nothing for free text', () => {
+ expect(suggestionSourceOf('Rule', option('blocks', { kind: 'list', element: { kind: 'reference', reference: 'BLOCK', format: 'BLOCK_ID' }, unique: false }))).toEqual({ from: 'reference', reference: 'BLOCK' })
+ expect(suggestionSourceOf('Rule', option('note', { kind: 'text', format: 'PLAIN' }))).toBeNull()
+ })
+})
+
+describe('rolesOf', () => {
+ it('lists each role of the whole tree once, sorted', () => {
+ expect(rolesOf([node(['wood', 'leaves'], [node(['wood', 'bark'])]), node(['moss'])])).toEqual(['bark', 'leaves', 'moss', 'wood'])
+ })
+})
+
+describe('matching', () => {
+ const blocks = ['minecraft:oak_log', 'minecraft:birch_log', 'minecraft:oak_leaves', 'minecraft:stone']
+
+ it('puts what starts with the typed text before what holds it', () => {
+ expect(matching(blocks, 'minecraft:oak')).toEqual(['minecraft:oak_log', 'minecraft:oak_leaves'])
+ expect(matching(blocks, 'oak')).toEqual(['minecraft:oak_log', 'minecraft:oak_leaves'])
+ expect(matching(['a_log', 'log'], 'log')).toEqual([])
+ expect(matching(['a_log', 'logs'], 'log')).toEqual(['logs', 'a_log'])
+ })
+
+ it('suggests nothing for nothing typed or a choice that is already typed out', () => {
+ expect(matching(blocks, '')).toEqual([])
+ expect(matching(blocks, 'MINECRAFT:STONE')).toEqual([])
+ })
+
+ it('shows only the first few', () => {
+ expect(matching(Array.from({ length: 30 }, (_, index) => `block_${index}`), 'block')).toHaveLength(8)
+ })
+})
+
+describe('the word being typed', () => {
+ it('is the whole text, or for a list the item after the last comma', () => {
+ expect(wordBeingTyped('oak', false)).toEqual({ start: 0, typed: 'oak' })
+ expect(wordBeingTyped('wood, lea', true)).toEqual({ start: 6, typed: 'lea' })
+ expect(wordBeingTyped('wood, ', true)).toEqual({ start: 6, typed: '' })
+ })
+
+ it('is replaced by the choice, a list ready for its next item', () => {
+ expect(completed('minecraft:oa', 'minecraft:oak_log', false)).toBe('minecraft:oak_log')
+ expect(completed('wood, lea', 'leaves', true)).toBe('wood, leaves, ')
+ })
+})
diff --git a/studio/src/renderer/src/editor/suggestions.ts b/studio/src/renderer/src/editor/suggestions.ts
new file mode 100644
index 000000000..cd71ead34
--- /dev/null
+++ b/studio/src/renderer/src/editor/suggestions.ts
@@ -0,0 +1,79 @@
+import type { GraphNode, SettingOption, ValueKind } from '../bridge/types'
+import { LIST_SEPARATOR } from './settingText'
+
+/** What an option may be typed as: the entries of a platform registry, the keys of the pack's resources of a kind, or the roles of the object. */
+export type SuggestionSource = { from: 'reference'; reference: string } | { from: 'resource'; resource: string } | { from: 'roles' }
+
+/** Settings that name a role of the object being edited, by the schema type and option (ProceduralPart, ProceduralMaterial and ProceduralDecoration). */
+const ROLE_OPTIONS: ReadonlySet = new Set([
+ 'art.arcane.iris.engine.procedural.part.ProceduralPart.role',
+ 'art.arcane.iris.engine.procedural.part.ProceduralMaterial.role',
+ 'art.arcane.iris.engine.procedural.part.ProceduralDecoration.on'
+])
+
+/** A source the server lists, as opposed to the roles, which the studio reads from the nodes. */
+export type ListedSource = Exclude
+
+const MOST_SHOWN = 8
+
+/** Where the suggestions for {@code option} of the schema type {@code type} come from; null when it is typed freely. */
+export function suggestionSourceOf(type: string, option: SettingOption): SuggestionSource | null {
+ if (ROLE_OPTIONS.has(`${type}.${option.name}`)) {
+ return { from: 'roles' }
+ }
+ const kind: ValueKind = option.kind.kind === 'list' ? option.kind.element : option.kind
+ if (kind.kind === 'reference') {
+ return { from: 'reference', reference: kind.reference }
+ }
+ return kind.kind === 'resource' ? { from: 'resource', resource: kind.resource } : null
+}
+
+export function sourceKey(source: ListedSource): string {
+ return source.from === 'reference' ? `reference:${source.reference}` : `resource:${source.resource}`
+}
+
+/** Every role the nodes place or decorate, once each and sorted. */
+export function rolesOf(roots: GraphNode[]): string[] {
+ const roles = new Set()
+ const visit = (node: GraphNode): void => {
+ node.roles.forEach((role) => roles.add(role))
+ node.children.forEach((link) => visit(link.node))
+ }
+ roots.forEach(visit)
+ return [...roles].sort()
+}
+
+/** The word being typed: from where it starts in {@code draft}, with what is typed of it. For a list that is the item after the last comma. */
+export function wordBeingTyped(draft: string, isList: boolean): { start: number; typed: string } {
+ const start = isList ? draft.lastIndexOf(',') + 1 : 0
+ const typed = draft.slice(start)
+ return { start: start + (typed.length - typed.trimStart().length), typed: typed.trim() }
+}
+
+/** The choices that hold what is typed, those that start with it first; none while nothing is typed or it is already a choice. */
+export function matching(choices: readonly string[], typed: string): string[] {
+ const wanted = typed.toLowerCase()
+ if (wanted === '') {
+ return []
+ }
+ const starting: string[] = []
+ const containing: string[] = []
+ for (const choice of choices) {
+ const lower = choice.toLowerCase()
+ if (lower === wanted) {
+ return []
+ }
+ if (lower.startsWith(wanted)) {
+ starting.push(choice)
+ } else if (lower.includes(wanted)) {
+ containing.push(choice)
+ }
+ }
+ return [...starting, ...containing].slice(0, MOST_SHOWN)
+}
+
+/** The draft with the word being typed replaced by {@code choice}; a list gets its separator ready for the next item. */
+export function completed(draft: string, choice: string, isList: boolean): string {
+ const { start } = wordBeingTyped(draft, isList)
+ return draft.slice(0, start) + choice + (isList ? LIST_SEPARATOR : '')
+}
diff --git a/studio/src/renderer/src/editor/useNodeEditor.ts b/studio/src/renderer/src/editor/useNodeEditor.ts
new file mode 100644
index 000000000..e0bd74f82
--- /dev/null
+++ b/studio/src/renderer/src/editor/useNodeEditor.ts
@@ -0,0 +1,122 @@
+import { useCallback, useEffect, useRef, useState } from 'react'
+import { BridgeError, STATUS_CONFLICT, type BridgeClient } from '../bridge/BridgeClient'
+import type { EditorState, GraphEdit } from '../bridge/types'
+import { EditHistory } from './EditHistory'
+
+export interface NodeEditor {
+ /** The entry's file as it is now; null while it is read. */
+ state: EditorState | null
+ saving: boolean
+ canUndo: boolean
+ canRedo: boolean
+ edit(edit: GraphEdit): void
+ undo(): void
+ redo(): void
+}
+
+/**
+ * Reads an entry's file as nodes and edits it. Edits are sent one after another, each on the text the one before left,
+ * so quick edits never refuse each other; one refused because the file changed elsewhere reads the file again.
+ */
+export function useNodeEditor(client: BridgeClient, viewId: string, key: string | null, packRevision: number, tell: (message: string) => void): NodeEditor {
+ const [state, setState] = useState(null)
+ const [saving, setSaving] = useState(false)
+ const [, setHistoryChanges] = useState(0)
+ const history = useRef(new EditHistory())
+ const shown = useRef(null)
+ const queue = useRef>(Promise.resolve())
+ const entry = useRef({ viewId, key })
+
+ const run = useCallback(
+ (task: (current: EditorState | null) => Promise): void => {
+ const asked = entry.current
+ queue.current = queue.current.then(async () => {
+ if (entry.current !== asked) {
+ return
+ }
+ setSaving(true)
+ try {
+ const next = await task(shown.current)
+ if (entry.current === asked && next !== null) {
+ shown.current = next
+ setState(next)
+ }
+ } catch (failure) {
+ if (entry.current !== asked) {
+ return
+ }
+ tell((failure as Error).message)
+ if (failure instanceof BridgeError && failure.status === STATUS_CONFLICT && asked.key !== null) {
+ const reread = await client.sceneFile(asked.viewId, asked.key).catch(() => null)
+ if (reread !== null && entry.current === asked) {
+ shown.current = reread
+ setState(reread)
+ }
+ }
+ } finally {
+ setSaving(false)
+ setHistoryChanges((changes) => changes + 1)
+ }
+ })
+ },
+ [client, tell]
+ )
+
+ useEffect(() => {
+ entry.current = { viewId, key }
+ history.current = new EditHistory()
+ shown.current = null
+ setState(null)
+ }, [viewId, key])
+
+ useEffect(() => {
+ if (key !== null) {
+ run(() => client.sceneFile(viewId, key))
+ }
+ }, [client, viewId, key, packRevision, run])
+
+ const edit = useCallback(
+ (change: GraphEdit) =>
+ run(async (current) => {
+ if (current === null || key === null) {
+ return null
+ }
+ const next = await client.sceneEdit(viewId, key, current.revision, change)
+ if (next.text !== current.text) {
+ history.current.edited(current.text)
+ }
+ return next
+ }),
+ [client, viewId, key, run]
+ )
+
+ const undo = useCallback(
+ () =>
+ run(async (current) => {
+ const earlier = history.current.nextUndo()
+ if (current === null || key === null || earlier === undefined) {
+ return null
+ }
+ const next = await client.sceneWrite(viewId, key, current.revision, earlier)
+ history.current.undone(current.text)
+ return next
+ }),
+ [client, viewId, key, run]
+ )
+
+ const redo = useCallback(
+ () =>
+ run(async (current) => {
+ const later = history.current.nextRedo()
+ if (current === null || key === null || later === undefined) {
+ return null
+ }
+ const next = await client.sceneWrite(viewId, key, current.revision, later)
+ history.current.redone(current.text)
+ return next
+ }),
+ [client, viewId, key, run]
+ )
+
+ return { state, saving, canUndo: history.current.canUndo, canRedo: history.current.canRedo, edit, undo, redo }
+}
diff --git a/studio/src/renderer/src/env.d.ts b/studio/src/renderer/src/env.d.ts
new file mode 100644
index 000000000..3ab813db9
--- /dev/null
+++ b/studio/src/renderer/src/env.d.ts
@@ -0,0 +1,10 @@
+///
+import type { StudioHost } from '../../shared/bridge'
+
+declare global {
+ interface Window {
+ studio: StudioHost
+ }
+}
+
+export {}
diff --git a/studio/src/renderer/src/icons/LICENSE-APACHE-2.0.txt b/studio/src/renderer/src/icons/LICENSE-APACHE-2.0.txt
new file mode 100644
index 000000000..d64569567
--- /dev/null
+++ b/studio/src/renderer/src/icons/LICENSE-APACHE-2.0.txt
@@ -0,0 +1,202 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/studio/src/renderer/src/icons/NOTICE.txt b/studio/src/renderer/src/icons/NOTICE.txt
new file mode 100644
index 000000000..e3d07cdd4
--- /dev/null
+++ b/studio/src/renderer/src/icons/NOTICE.txt
@@ -0,0 +1,6 @@
+The icons in this folder and its subfolders come from the IntelliJ Platform (https://github.com/JetBrains/intellij-community),
+platform/icons/src/expui, Copyright 2000-2023 JetBrains s.r.o. and contributors,
+used under the Apache License 2.0 (LICENSE-APACHE-2.0.txt).
+memory.svg is profileMemory.svg with its profiling badge removed.
+theme.svg, blocks.svg, borders.svg, shading.svg, mob.svg, actualZoom.svg, decoration.svg, and in views/ biomes.svg, regions.svg,
+world-3d.svg, saved-world.svg, noise.svg and objects.svg are the studio's own, drawn to match.
diff --git a/studio/src/renderer/src/icons/actualZoom.svg b/studio/src/renderer/src/icons/actualZoom.svg
new file mode 100644
index 000000000..08981f5e8
--- /dev/null
+++ b/studio/src/renderer/src/icons/actualZoom.svg
@@ -0,0 +1,5 @@
+
diff --git a/studio/src/renderer/src/icons/actualZoom_dark.svg b/studio/src/renderer/src/icons/actualZoom_dark.svg
new file mode 100644
index 000000000..0cc5f18b6
--- /dev/null
+++ b/studio/src/renderer/src/icons/actualZoom_dark.svg
@@ -0,0 +1,5 @@
+
diff --git a/studio/src/renderer/src/icons/add.svg b/studio/src/renderer/src/icons/add.svg
new file mode 100644
index 000000000..57eaaf561
--- /dev/null
+++ b/studio/src/renderer/src/icons/add.svg
@@ -0,0 +1,4 @@
+
+
diff --git a/studio/src/renderer/src/icons/add_dark.svg b/studio/src/renderer/src/icons/add_dark.svg
new file mode 100644
index 000000000..397e9321b
--- /dev/null
+++ b/studio/src/renderer/src/icons/add_dark.svg
@@ -0,0 +1,4 @@
+
+
diff --git a/studio/src/renderer/src/icons/blocks.svg b/studio/src/renderer/src/icons/blocks.svg
new file mode 100644
index 000000000..aa609f646
--- /dev/null
+++ b/studio/src/renderer/src/icons/blocks.svg
@@ -0,0 +1,4 @@
+
diff --git a/studio/src/renderer/src/icons/blocks_dark.svg b/studio/src/renderer/src/icons/blocks_dark.svg
new file mode 100644
index 000000000..d215432f4
--- /dev/null
+++ b/studio/src/renderer/src/icons/blocks_dark.svg
@@ -0,0 +1,4 @@
+
diff --git a/studio/src/renderer/src/icons/borders.svg b/studio/src/renderer/src/icons/borders.svg
new file mode 100644
index 000000000..4fe3957a7
--- /dev/null
+++ b/studio/src/renderer/src/icons/borders.svg
@@ -0,0 +1,3 @@
+
diff --git a/studio/src/renderer/src/icons/borders_dark.svg b/studio/src/renderer/src/icons/borders_dark.svg
new file mode 100644
index 000000000..2f7ce7863
--- /dev/null
+++ b/studio/src/renderer/src/icons/borders_dark.svg
@@ -0,0 +1,3 @@
+
diff --git a/studio/src/renderer/src/icons/checked.svg b/studio/src/renderer/src/icons/checked.svg
new file mode 100644
index 000000000..863bbc418
--- /dev/null
+++ b/studio/src/renderer/src/icons/checked.svg
@@ -0,0 +1,4 @@
+
+
diff --git a/studio/src/renderer/src/icons/checked_dark.svg b/studio/src/renderer/src/icons/checked_dark.svg
new file mode 100644
index 000000000..3e1d9ecc3
--- /dev/null
+++ b/studio/src/renderer/src/icons/checked_dark.svg
@@ -0,0 +1,4 @@
+
+
diff --git a/studio/src/renderer/src/icons/chevronLeft.svg b/studio/src/renderer/src/icons/chevronLeft.svg
new file mode 100644
index 000000000..c6c4fa041
--- /dev/null
+++ b/studio/src/renderer/src/icons/chevronLeft.svg
@@ -0,0 +1,4 @@
+
+
diff --git a/studio/src/renderer/src/icons/chevronLeft_dark.svg b/studio/src/renderer/src/icons/chevronLeft_dark.svg
new file mode 100644
index 000000000..d4284d234
--- /dev/null
+++ b/studio/src/renderer/src/icons/chevronLeft_dark.svg
@@ -0,0 +1,4 @@
+
+
diff --git a/studio/src/renderer/src/icons/chevronRight.svg b/studio/src/renderer/src/icons/chevronRight.svg
new file mode 100644
index 000000000..5120ed891
--- /dev/null
+++ b/studio/src/renderer/src/icons/chevronRight.svg
@@ -0,0 +1,4 @@
+
+
diff --git a/studio/src/renderer/src/icons/chevronRight_dark.svg b/studio/src/renderer/src/icons/chevronRight_dark.svg
new file mode 100644
index 000000000..838142106
--- /dev/null
+++ b/studio/src/renderer/src/icons/chevronRight_dark.svg
@@ -0,0 +1,4 @@
+
+
diff --git a/studio/src/renderer/src/icons/closeSmall.svg b/studio/src/renderer/src/icons/closeSmall.svg
new file mode 100644
index 000000000..c375b9331
--- /dev/null
+++ b/studio/src/renderer/src/icons/closeSmall.svg
@@ -0,0 +1,4 @@
+
+
diff --git a/studio/src/renderer/src/icons/closeSmall_dark.svg b/studio/src/renderer/src/icons/closeSmall_dark.svg
new file mode 100644
index 000000000..237d6d45d
--- /dev/null
+++ b/studio/src/renderer/src/icons/closeSmall_dark.svg
@@ -0,0 +1,4 @@
+
+
diff --git a/studio/src/renderer/src/icons/decoration.svg b/studio/src/renderer/src/icons/decoration.svg
new file mode 100644
index 000000000..fb2a026ea
--- /dev/null
+++ b/studio/src/renderer/src/icons/decoration.svg
@@ -0,0 +1,5 @@
+
diff --git a/studio/src/renderer/src/icons/decoration_dark.svg b/studio/src/renderer/src/icons/decoration_dark.svg
new file mode 100644
index 000000000..0e0b87790
--- /dev/null
+++ b/studio/src/renderer/src/icons/decoration_dark.svg
@@ -0,0 +1,5 @@
+
diff --git a/studio/src/renderer/src/icons/delete.svg b/studio/src/renderer/src/icons/delete.svg
new file mode 100644
index 000000000..a858096ac
--- /dev/null
+++ b/studio/src/renderer/src/icons/delete.svg
@@ -0,0 +1,4 @@
+
+
diff --git a/studio/src/renderer/src/icons/delete_dark.svg b/studio/src/renderer/src/icons/delete_dark.svg
new file mode 100644
index 000000000..03ff9f241
--- /dev/null
+++ b/studio/src/renderer/src/icons/delete_dark.svg
@@ -0,0 +1,4 @@
+
+
diff --git a/studio/src/renderer/src/icons/exit.svg b/studio/src/renderer/src/icons/exit.svg
new file mode 100644
index 000000000..8ff96d714
--- /dev/null
+++ b/studio/src/renderer/src/icons/exit.svg
@@ -0,0 +1,5 @@
+
+
diff --git a/studio/src/renderer/src/icons/exit_dark.svg b/studio/src/renderer/src/icons/exit_dark.svg
new file mode 100644
index 000000000..e4cdd4abf
--- /dev/null
+++ b/studio/src/renderer/src/icons/exit_dark.svg
@@ -0,0 +1,12 @@
+
+
diff --git a/studio/src/renderer/src/icons/grid.svg b/studio/src/renderer/src/icons/grid.svg
new file mode 100644
index 000000000..8b28efaf4
--- /dev/null
+++ b/studio/src/renderer/src/icons/grid.svg
@@ -0,0 +1,7 @@
+
+
diff --git a/studio/src/renderer/src/icons/grid_dark.svg b/studio/src/renderer/src/icons/grid_dark.svg
new file mode 100644
index 000000000..98f561847
--- /dev/null
+++ b/studio/src/renderer/src/icons/grid_dark.svg
@@ -0,0 +1,7 @@
+
+
diff --git a/studio/src/renderer/src/icons/groups.svg b/studio/src/renderer/src/icons/groups.svg
new file mode 100644
index 000000000..d4ab80fbb
--- /dev/null
+++ b/studio/src/renderer/src/icons/groups.svg
@@ -0,0 +1,7 @@
+
+
diff --git a/studio/src/renderer/src/icons/groups_dark.svg b/studio/src/renderer/src/icons/groups_dark.svg
new file mode 100644
index 000000000..2769c3ce0
--- /dev/null
+++ b/studio/src/renderer/src/icons/groups_dark.svg
@@ -0,0 +1,7 @@
+
+
diff --git a/studio/src/renderer/src/icons/help.svg b/studio/src/renderer/src/icons/help.svg
new file mode 100644
index 000000000..203346d24
--- /dev/null
+++ b/studio/src/renderer/src/icons/help.svg
@@ -0,0 +1,5 @@
+
+
diff --git a/studio/src/renderer/src/icons/help_dark.svg b/studio/src/renderer/src/icons/help_dark.svg
new file mode 100644
index 000000000..d571baabe
--- /dev/null
+++ b/studio/src/renderer/src/icons/help_dark.svg
@@ -0,0 +1,5 @@
+
+
diff --git a/studio/src/renderer/src/icons/lightning.svg b/studio/src/renderer/src/icons/lightning.svg
new file mode 100644
index 000000000..4ac384edd
--- /dev/null
+++ b/studio/src/renderer/src/icons/lightning.svg
@@ -0,0 +1,4 @@
+
+
diff --git a/studio/src/renderer/src/icons/lightning_dark.svg b/studio/src/renderer/src/icons/lightning_dark.svg
new file mode 100644
index 000000000..251f75413
--- /dev/null
+++ b/studio/src/renderer/src/icons/lightning_dark.svg
@@ -0,0 +1,4 @@
+
+
diff --git a/studio/src/renderer/src/icons/locate.svg b/studio/src/renderer/src/icons/locate.svg
new file mode 100644
index 000000000..2343fa2e3
--- /dev/null
+++ b/studio/src/renderer/src/icons/locate.svg
@@ -0,0 +1,4 @@
+
+
diff --git a/studio/src/renderer/src/icons/locate_dark.svg b/studio/src/renderer/src/icons/locate_dark.svg
new file mode 100644
index 000000000..a2ba607aa
--- /dev/null
+++ b/studio/src/renderer/src/icons/locate_dark.svg
@@ -0,0 +1,4 @@
+
+
diff --git a/studio/src/renderer/src/icons/locked.svg b/studio/src/renderer/src/icons/locked.svg
new file mode 100644
index 000000000..666daddf5
--- /dev/null
+++ b/studio/src/renderer/src/icons/locked.svg
@@ -0,0 +1,4 @@
+
+
diff --git a/studio/src/renderer/src/icons/locked_dark.svg b/studio/src/renderer/src/icons/locked_dark.svg
new file mode 100644
index 000000000..9658ca553
--- /dev/null
+++ b/studio/src/renderer/src/icons/locked_dark.svg
@@ -0,0 +1,4 @@
+
+
diff --git a/studio/src/renderer/src/icons/memory.svg b/studio/src/renderer/src/icons/memory.svg
new file mode 100644
index 000000000..6af68790d
--- /dev/null
+++ b/studio/src/renderer/src/icons/memory.svg
@@ -0,0 +1,7 @@
+
+
+
diff --git a/studio/src/renderer/src/icons/memory_dark.svg b/studio/src/renderer/src/icons/memory_dark.svg
new file mode 100644
index 000000000..92038e383
--- /dev/null
+++ b/studio/src/renderer/src/icons/memory_dark.svg
@@ -0,0 +1,7 @@
+
+
+
diff --git a/studio/src/renderer/src/icons/mob.svg b/studio/src/renderer/src/icons/mob.svg
new file mode 100644
index 000000000..bcd9e1a0e
--- /dev/null
+++ b/studio/src/renderer/src/icons/mob.svg
@@ -0,0 +1,6 @@
+
diff --git a/studio/src/renderer/src/icons/mob_dark.svg b/studio/src/renderer/src/icons/mob_dark.svg
new file mode 100644
index 000000000..f1b911136
--- /dev/null
+++ b/studio/src/renderer/src/icons/mob_dark.svg
@@ -0,0 +1,6 @@
+
diff --git a/studio/src/renderer/src/icons/redo.svg b/studio/src/renderer/src/icons/redo.svg
new file mode 100644
index 000000000..862b8f574
--- /dev/null
+++ b/studio/src/renderer/src/icons/redo.svg
@@ -0,0 +1,4 @@
+
+
diff --git a/studio/src/renderer/src/icons/redo_dark.svg b/studio/src/renderer/src/icons/redo_dark.svg
new file mode 100644
index 000000000..a39093042
--- /dev/null
+++ b/studio/src/renderer/src/icons/redo_dark.svg
@@ -0,0 +1,4 @@
+
+
diff --git a/studio/src/renderer/src/icons/refresh.svg b/studio/src/renderer/src/icons/refresh.svg
new file mode 100644
index 000000000..7a4c73dfd
--- /dev/null
+++ b/studio/src/renderer/src/icons/refresh.svg
@@ -0,0 +1,7 @@
+
+
diff --git a/studio/src/renderer/src/icons/refresh_dark.svg b/studio/src/renderer/src/icons/refresh_dark.svg
new file mode 100644
index 000000000..3362992af
--- /dev/null
+++ b/studio/src/renderer/src/icons/refresh_dark.svg
@@ -0,0 +1,7 @@
+
+
diff --git a/studio/src/renderer/src/icons/reset.svg b/studio/src/renderer/src/icons/reset.svg
new file mode 100644
index 000000000..de5d2b170
--- /dev/null
+++ b/studio/src/renderer/src/icons/reset.svg
@@ -0,0 +1,4 @@
+
+
diff --git a/studio/src/renderer/src/icons/reset_dark.svg b/studio/src/renderer/src/icons/reset_dark.svg
new file mode 100644
index 000000000..28d58e10e
--- /dev/null
+++ b/studio/src/renderer/src/icons/reset_dark.svg
@@ -0,0 +1,4 @@
+
+
diff --git a/studio/src/renderer/src/icons/search.svg b/studio/src/renderer/src/icons/search.svg
new file mode 100644
index 000000000..021b0c394
--- /dev/null
+++ b/studio/src/renderer/src/icons/search.svg
@@ -0,0 +1,5 @@
+
+
diff --git a/studio/src/renderer/src/icons/search_dark.svg b/studio/src/renderer/src/icons/search_dark.svg
new file mode 100644
index 000000000..d5a82d9c1
--- /dev/null
+++ b/studio/src/renderer/src/icons/search_dark.svg
@@ -0,0 +1,5 @@
+
+
diff --git a/studio/src/renderer/src/icons/settings.svg b/studio/src/renderer/src/icons/settings.svg
new file mode 100644
index 000000000..c30de8209
--- /dev/null
+++ b/studio/src/renderer/src/icons/settings.svg
@@ -0,0 +1,4 @@
+
+
diff --git a/studio/src/renderer/src/icons/settings_dark.svg b/studio/src/renderer/src/icons/settings_dark.svg
new file mode 100644
index 000000000..62f328167
--- /dev/null
+++ b/studio/src/renderer/src/icons/settings_dark.svg
@@ -0,0 +1,4 @@
+
+
diff --git a/studio/src/renderer/src/icons/shading.svg b/studio/src/renderer/src/icons/shading.svg
new file mode 100644
index 000000000..c545e1d8b
--- /dev/null
+++ b/studio/src/renderer/src/icons/shading.svg
@@ -0,0 +1,4 @@
+
diff --git a/studio/src/renderer/src/icons/shading_dark.svg b/studio/src/renderer/src/icons/shading_dark.svg
new file mode 100644
index 000000000..cc2b121d0
--- /dev/null
+++ b/studio/src/renderer/src/icons/shading_dark.svg
@@ -0,0 +1,4 @@
+
diff --git a/studio/src/renderer/src/icons/stopWatch.svg b/studio/src/renderer/src/icons/stopWatch.svg
new file mode 100644
index 000000000..33f0d5917
--- /dev/null
+++ b/studio/src/renderer/src/icons/stopWatch.svg
@@ -0,0 +1,6 @@
+
+
diff --git a/studio/src/renderer/src/icons/stopWatch_dark.svg b/studio/src/renderer/src/icons/stopWatch_dark.svg
new file mode 100644
index 000000000..10bec586b
--- /dev/null
+++ b/studio/src/renderer/src/icons/stopWatch_dark.svg
@@ -0,0 +1,6 @@
+
+
diff --git a/studio/src/renderer/src/icons/symlink.svg b/studio/src/renderer/src/icons/symlink.svg
new file mode 100644
index 000000000..4c2ccbb21
--- /dev/null
+++ b/studio/src/renderer/src/icons/symlink.svg
@@ -0,0 +1,4 @@
+
+
diff --git a/studio/src/renderer/src/icons/symlink_dark.svg b/studio/src/renderer/src/icons/symlink_dark.svg
new file mode 100644
index 000000000..fcc2390a9
--- /dev/null
+++ b/studio/src/renderer/src/icons/symlink_dark.svg
@@ -0,0 +1,4 @@
+
+
diff --git a/studio/src/renderer/src/icons/theme.svg b/studio/src/renderer/src/icons/theme.svg
new file mode 100644
index 000000000..3f4ab8713
--- /dev/null
+++ b/studio/src/renderer/src/icons/theme.svg
@@ -0,0 +1,4 @@
+
diff --git a/studio/src/renderer/src/icons/theme_dark.svg b/studio/src/renderer/src/icons/theme_dark.svg
new file mode 100644
index 000000000..375b1b72c
--- /dev/null
+++ b/studio/src/renderer/src/icons/theme_dark.svg
@@ -0,0 +1,4 @@
+
diff --git a/studio/src/renderer/src/icons/undo.svg b/studio/src/renderer/src/icons/undo.svg
new file mode 100644
index 000000000..7a98c7583
--- /dev/null
+++ b/studio/src/renderer/src/icons/undo.svg
@@ -0,0 +1,4 @@
+
+
diff --git a/studio/src/renderer/src/icons/undo_dark.svg b/studio/src/renderer/src/icons/undo_dark.svg
new file mode 100644
index 000000000..2fa3c0d42
--- /dev/null
+++ b/studio/src/renderer/src/icons/undo_dark.svg
@@ -0,0 +1,4 @@
+
+
diff --git a/studio/src/renderer/src/icons/views/biomes.svg b/studio/src/renderer/src/icons/views/biomes.svg
new file mode 100644
index 000000000..78c98d754
--- /dev/null
+++ b/studio/src/renderer/src/icons/views/biomes.svg
@@ -0,0 +1,8 @@
+
diff --git a/studio/src/renderer/src/icons/views/biomes_dark.svg b/studio/src/renderer/src/icons/views/biomes_dark.svg
new file mode 100644
index 000000000..731013503
--- /dev/null
+++ b/studio/src/renderer/src/icons/views/biomes_dark.svg
@@ -0,0 +1,8 @@
+
diff --git a/studio/src/renderer/src/icons/views/noise.svg b/studio/src/renderer/src/icons/views/noise.svg
new file mode 100644
index 000000000..e735984cf
--- /dev/null
+++ b/studio/src/renderer/src/icons/views/noise.svg
@@ -0,0 +1,3 @@
+
diff --git a/studio/src/renderer/src/icons/views/noise_dark.svg b/studio/src/renderer/src/icons/views/noise_dark.svg
new file mode 100644
index 000000000..187dd72f4
--- /dev/null
+++ b/studio/src/renderer/src/icons/views/noise_dark.svg
@@ -0,0 +1,3 @@
+
diff --git a/studio/src/renderer/src/icons/views/objects.svg b/studio/src/renderer/src/icons/views/objects.svg
new file mode 100644
index 000000000..6297b050c
--- /dev/null
+++ b/studio/src/renderer/src/icons/views/objects.svg
@@ -0,0 +1,4 @@
+
diff --git a/studio/src/renderer/src/icons/views/objects_dark.svg b/studio/src/renderer/src/icons/views/objects_dark.svg
new file mode 100644
index 000000000..4e3d96e86
--- /dev/null
+++ b/studio/src/renderer/src/icons/views/objects_dark.svg
@@ -0,0 +1,4 @@
+
diff --git a/studio/src/renderer/src/icons/views/palettes.svg b/studio/src/renderer/src/icons/views/palettes.svg
new file mode 100644
index 000000000..67e265433
--- /dev/null
+++ b/studio/src/renderer/src/icons/views/palettes.svg
@@ -0,0 +1,6 @@
+
+
diff --git a/studio/src/renderer/src/icons/views/palettes_dark.svg b/studio/src/renderer/src/icons/views/palettes_dark.svg
new file mode 100644
index 000000000..8d120c93e
--- /dev/null
+++ b/studio/src/renderer/src/icons/views/palettes_dark.svg
@@ -0,0 +1,6 @@
+
+
diff --git a/studio/src/renderer/src/icons/views/procedural.svg b/studio/src/renderer/src/icons/views/procedural.svg
new file mode 100644
index 000000000..5ad2cdb16
--- /dev/null
+++ b/studio/src/renderer/src/icons/views/procedural.svg
@@ -0,0 +1,7 @@
+
+
diff --git a/studio/src/renderer/src/icons/views/procedural_dark.svg b/studio/src/renderer/src/icons/views/procedural_dark.svg
new file mode 100644
index 000000000..3c5f7ed0d
--- /dev/null
+++ b/studio/src/renderer/src/icons/views/procedural_dark.svg
@@ -0,0 +1,7 @@
+
+
diff --git a/studio/src/renderer/src/icons/views/regions.svg b/studio/src/renderer/src/icons/views/regions.svg
new file mode 100644
index 000000000..f2848a5ee
--- /dev/null
+++ b/studio/src/renderer/src/icons/views/regions.svg
@@ -0,0 +1,4 @@
+
diff --git a/studio/src/renderer/src/icons/views/regions_dark.svg b/studio/src/renderer/src/icons/views/regions_dark.svg
new file mode 100644
index 000000000..f28c07a18
--- /dev/null
+++ b/studio/src/renderer/src/icons/views/regions_dark.svg
@@ -0,0 +1,4 @@
+
diff --git a/studio/src/renderer/src/icons/views/saved-world.svg b/studio/src/renderer/src/icons/views/saved-world.svg
new file mode 100644
index 000000000..ba35672af
--- /dev/null
+++ b/studio/src/renderer/src/icons/views/saved-world.svg
@@ -0,0 +1,4 @@
+
diff --git a/studio/src/renderer/src/icons/views/saved-world_dark.svg b/studio/src/renderer/src/icons/views/saved-world_dark.svg
new file mode 100644
index 000000000..f9880f87b
--- /dev/null
+++ b/studio/src/renderer/src/icons/views/saved-world_dark.svg
@@ -0,0 +1,4 @@
+
diff --git a/studio/src/renderer/src/icons/views/world-3d.svg b/studio/src/renderer/src/icons/views/world-3d.svg
new file mode 100644
index 000000000..233fbbd78
--- /dev/null
+++ b/studio/src/renderer/src/icons/views/world-3d.svg
@@ -0,0 +1,4 @@
+
diff --git a/studio/src/renderer/src/icons/views/world-3d_dark.svg b/studio/src/renderer/src/icons/views/world-3d_dark.svg
new file mode 100644
index 000000000..46f0ee93d
--- /dev/null
+++ b/studio/src/renderer/src/icons/views/world-3d_dark.svg
@@ -0,0 +1,4 @@
+
diff --git a/studio/src/renderer/src/icons/web.svg b/studio/src/renderer/src/icons/web.svg
new file mode 100644
index 000000000..897fab392
--- /dev/null
+++ b/studio/src/renderer/src/icons/web.svg
@@ -0,0 +1,4 @@
+
+
diff --git a/studio/src/renderer/src/icons/web_dark.svg b/studio/src/renderer/src/icons/web_dark.svg
new file mode 100644
index 000000000..0ca6194ab
--- /dev/null
+++ b/studio/src/renderer/src/icons/web_dark.svg
@@ -0,0 +1,4 @@
+
+
diff --git a/studio/src/renderer/src/lib/utils.ts b/studio/src/renderer/src/lib/utils.ts
new file mode 100644
index 000000000..b057456de
--- /dev/null
+++ b/studio/src/renderer/src/lib/utils.ts
@@ -0,0 +1,6 @@
+import { clsx, type ClassValue } from 'clsx'
+import { twMerge } from 'tailwind-merge'
+
+export function cn(...inputs: ClassValue[]): string {
+ return twMerge(clsx(inputs))
+}
diff --git a/studio/src/renderer/src/main.tsx b/studio/src/renderer/src/main.tsx
new file mode 100644
index 000000000..3ea6345e0
--- /dev/null
+++ b/studio/src/renderer/src/main.tsx
@@ -0,0 +1,13 @@
+import { StrictMode } from 'react'
+import { createRoot } from 'react-dom/client'
+import { TooltipProvider } from '@/components/ui/tooltip'
+import { App } from './App'
+import './styles.css'
+
+createRoot(document.getElementById('root')!).render(
+
+
+
+
+
+)
diff --git a/studio/src/renderer/src/map/MapController.ts b/studio/src/renderer/src/map/MapController.ts
new file mode 100644
index 000000000..fc7050740
--- /dev/null
+++ b/studio/src/renderer/src/map/MapController.ts
@@ -0,0 +1,386 @@
+import type { BridgeClient, WorldRect } from '../bridge/BridgeClient'
+import { gridIndex } from '../bridge/tileDecoding'
+import { NO_LABEL, type BlockSource, type MapLabel, type MapTile, type Marker, type PickDisplay, type WorldInfo } from '../bridge/types'
+import { countShares, type PlacedTile, type Share } from './census'
+import { blockArt, type BlockArt } from '../scene/blockArt'
+import { hasBlocksAt, mapTileSource, type TileLayer } from './mapTileSource'
+import { drawPlayerArrow } from './playerArrow'
+import { drawVisibleTiles } from './tileDrawing'
+import type { Highlight, TileStyle } from './tileStyle'
+import { TileStore } from './TileStore'
+import {
+ clampBlocksPerPixel,
+ DEFAULT_BLOCKS_PER_PIXEL,
+ renderBlocksPerPixel,
+ screenToWorldX,
+ screenToWorldZ,
+ worldToScreenX,
+ worldToScreenZ,
+ type TileAddress,
+ type Viewport
+} from './viewport'
+
+export interface MapStatus {
+ blocksPerPixel: number
+ widthBlocks: number
+ heightBlocks: number
+ tilesReady: number
+ tilesTotal: number
+ cursorX: number
+ cursorZ: number
+}
+
+export interface MapListener {
+ onStatus(status: MapStatus): void
+ onShares(shares: Share[]): void
+ /** The world area on screen, reported with the shares: a few times a second while it moves, and once at rest. */
+ onArea(area: WorldRect): void
+ onError(message: string): void
+}
+
+/** The views whose spots a noise picks, so they can draw that noise. */
+const PICK_NOISE_VIEWS = new Set(['biomes', 'regions'])
+
+/** What the map shows at a spot, read from the tiles already drawn. */
+export interface SpotSubjects {
+ subject: Highlight | null
+ region: Highlight | null
+}
+
+export interface MapToggles {
+ shading: boolean
+ regionBorders: boolean
+ grid: boolean
+ /** Colour the map by the block on top of each column, where it is zoomed in far enough. */
+ blocks: boolean
+}
+
+const BLOCK_SOURCE: BlockSource = 'generated'
+
+const CENSUS_INTERVAL_MILLIS = 250
+const CHUNK_BLOCKS = 16
+const REGION_BLOCKS = 512
+const SMALLEST_GRID_GAP_PIXELS = 8
+const CHUNK_LINE = 'rgba(255, 255, 255, 0.14)'
+const REGION_LINE = 'rgba(255, 255, 255, 0.38)'
+const ENTITY_FILL = '#f75464'
+const MARKER_OUTLINE = '#ffffff'
+const ENTITY_RADIUS_PIXELS = 3
+
+/**
+ * The 2D map on a canvas: which tiles to fetch for the view, drawing them in the current style, and the grid and
+ * markers on top. Kept outside React, as it redraws on every drag and wheel step.
+ */
+export class MapController {
+ private readonly context: CanvasRenderingContext2D
+ private readonly art: BlockArt
+ private readonly store: TileStore
+ private readonly view: Viewport = { centerX: 0, centerZ: 0, blocksPerPixel: DEFAULT_BLOCKS_PER_PIXEL, width: 1, height: 1 }
+ private layer: TileLayer
+ private toggles: MapToggles = { shading: true, regionBorders: false, grid: false, blocks: false }
+ private pickDisplay: PickDisplay = 'picks'
+ private highlight: Highlight | null = null
+ private players: Marker[] = []
+ private entities: Marker[] = []
+ private cursor: { x: number; y: number } | null = null
+ private frameRequested = false
+ private lastCensusMillis = 0
+ private censusTimer: number | undefined
+ private closed = false
+
+ constructor(
+ private readonly canvas: HTMLCanvasElement,
+ client: BridgeClient,
+ private readonly world: WorldInfo,
+ view: string,
+ private readonly listener: MapListener
+ ) {
+ this.context = canvas.getContext('2d')!
+ this.layer = { view, preview: null, heights: this.needsHeights(this.toggles), pickNoise: false, blocks: null, revision: 0 }
+ this.art = blockArt(client, false)
+ this.store = new TileStore(mapTileSource(client, world.tileSize, this.art), () => this.redraw(), (message) => listener.onError(message))
+ }
+
+ close(): void {
+ this.closed = true
+ this.art.dispose()
+ window.clearTimeout(this.censusTimer)
+ this.store.clear()
+ }
+
+ resize(width: number, height: number): void {
+ const ratio = window.devicePixelRatio
+ this.canvas.width = Math.round(width * ratio)
+ this.canvas.height = Math.round(height * ratio)
+ this.view.width = width
+ this.view.height = height
+ this.redraw()
+ }
+
+ /** Shows a view; the region view previews {@code preview} everywhere when it is not null. */
+ setView(view: string, preview: string | null = null): void {
+ this.layer = {
+ ...this.layer,
+ view,
+ preview: view === 'regions' ? preview : null,
+ pickNoise: this.needsPickNoise(view, this.pickDisplay)
+ }
+ this.redraw()
+ }
+
+ setPickDisplay(display: PickDisplay): void {
+ this.pickDisplay = display
+ this.layer = { ...this.layer, pickNoise: this.needsPickNoise(this.layer.view, display) }
+ this.redraw()
+ }
+
+ // Tiles only carry their pick noise while it is drawn, so drawing the picks alone costs nothing extra.
+ private needsPickNoise(view: string, display: PickDisplay): boolean {
+ return display !== 'picks' && PICK_NOISE_VIEWS.has(view)
+ }
+
+ setToggles(toggles: MapToggles): void {
+ this.toggles = toggles
+ this.layer = { ...this.layer, heights: this.needsHeights(toggles), blocks: toggles.blocks ? BLOCK_SOURCE : null }
+ this.redraw()
+ }
+
+ /** Whether the map is zoomed in far enough for its tiles to carry blocks. */
+ showsBlocks(): boolean {
+ return hasBlocksAt(this.renderScale())
+ }
+
+ // Heights are the costly part of a tile, so they are only asked for when something draws with them: the relief, and
+ // the sea over the blocks.
+ private needsHeights(toggles: MapToggles): boolean {
+ return toggles.shading || toggles.blocks
+ }
+
+ setHighlight(highlight: Highlight | null): void {
+ this.highlight = highlight
+ this.redraw()
+ }
+
+ setMarkers(players: Marker[], entities: Marker[]): void {
+ this.players = players
+ this.entities = entities
+ this.redraw()
+ }
+
+ setCursor(cursor: { x: number; y: number } | null): void {
+ this.cursor = cursor
+ this.reportStatus()
+ }
+
+ /** Draws everything again from the server, after the pack changed. */
+ refresh(): void {
+ this.store.clear()
+ this.layer = { ...this.layer, revision: this.layer.revision + 1 }
+ this.redraw()
+ }
+
+ panBy(screenDeltaX: number, screenDeltaZ: number): void {
+ this.view.centerX -= screenDeltaX * this.view.blocksPerPixel
+ this.view.centerZ -= screenDeltaZ * this.view.blocksPerPixel
+ this.redraw()
+ }
+
+ centerOn(worldX: number, worldZ: number): void {
+ this.view.centerX = worldX
+ this.view.centerZ = worldZ
+ this.redraw()
+ }
+
+ /** Zooms by {@code factor} (above 1 zooms in) keeping the world spot under the screen point where it is. */
+ zoomAt(factor: number, screenX = this.view.width / 2, screenZ = this.view.height / 2): void {
+ const worldX = screenToWorldX(this.view, screenX)
+ const worldZ = screenToWorldZ(this.view, screenZ)
+ this.view.blocksPerPixel = clampBlocksPerPixel(this.view.blocksPerPixel / factor)
+ this.view.centerX = worldX - (screenX - this.view.width / 2) * this.view.blocksPerPixel
+ this.view.centerZ = worldZ - (screenZ - this.view.height / 2) * this.view.blocksPerPixel
+ this.redraw()
+ }
+
+ resetZoom(): void {
+ this.view.blocksPerPixel = DEFAULT_BLOCKS_PER_PIXEL
+ this.redraw()
+ }
+
+ worldAt(screenX: number, screenZ: number): { x: number; z: number } {
+ return { x: screenToWorldX(this.view, screenX), z: screenToWorldZ(this.view, screenZ) }
+ }
+
+ /** The biome or region and the region at a screen point, from the tile drawn there; nulls before it arrived. */
+ subjectsAt(screenX: number, screenZ: number): SpotSubjects {
+ const worldX = screenToWorldX(this.view, screenX)
+ const worldZ = screenToWorldZ(this.view, screenZ)
+ const scale = this.renderScale()
+ const span = this.world.tileSize * scale
+ const address = { tileX: Math.floor(worldX / span), tileZ: Math.floor(worldZ / span), blocksPerPixel: scale }
+ const tile = this.store.get(address, this.layer)
+ if (tile === null) {
+ return { subject: null, region: null }
+ }
+ const pixelX = Math.min(tile.size - 1, Math.floor((worldX - address.tileX * span) / scale))
+ const pixelZ = Math.min(tile.size - 1, Math.floor((worldZ - address.tileZ * span) / scale))
+ const cell = gridIndex(tile, pixelX, pixelZ)
+ const region = labelAt(tile.labels, tile.regions[cell])
+ return { subject: labelAt(tile.labels, tile.subjects[cell]), region }
+ }
+
+ private renderScale(): number {
+ return renderBlocksPerPixel(this.view.blocksPerPixel, window.devicePixelRatio)
+ }
+
+ private style(): TileStyle {
+ return {
+ byBlock: this.toggles.blocks,
+ shading: this.toggles.shading,
+ regionBorders: this.toggles.regionBorders,
+ highlight: this.highlight,
+ seaLevel: this.world.fluidHeight,
+ pickDisplay: this.pickDisplay
+ }
+ }
+
+ private redraw(): void {
+ if (this.frameRequested || this.closed) {
+ return
+ }
+ this.frameRequested = true
+ requestAnimationFrame(() => {
+ this.frameRequested = false
+ if (!this.closed) {
+ this.draw()
+ }
+ })
+ }
+
+ private draw(): void {
+ const ratio = window.devicePixelRatio
+ const context = this.context
+ context.setTransform(ratio, 0, 0, ratio, 0, 0)
+ context.fillStyle = getComputedStyle(this.canvas).getPropertyValue('--map-background') || '#16171a'
+ context.fillRect(0, 0, this.view.width, this.view.height)
+
+ const style = this.style()
+ const drawn = drawVisibleTiles(context, this.view, this.renderScale(), this.world.tileSize, (address) =>
+ this.store.picture(address, this.layer, style)
+ )
+ this.store.want(drawn.wanted, this.layer)
+ if (this.toggles.grid) {
+ this.drawGrid()
+ }
+ this.drawMarkers()
+ this.reportStatus(drawn.ready, drawn.tiles.length)
+ this.scheduleCensus(drawn.tiles)
+ }
+
+ private drawGrid(): void {
+ this.drawLines(CHUNK_BLOCKS, CHUNK_LINE, 1)
+ this.drawLines(REGION_BLOCKS, REGION_LINE, 1.5)
+ }
+
+ private drawLines(gapBlocks: number, color: string, width: number): void {
+ if (gapBlocks / this.view.blocksPerPixel < SMALLEST_GRID_GAP_PIXELS) {
+ return
+ }
+ const context = this.context
+ context.strokeStyle = color
+ context.lineWidth = width
+ context.beginPath()
+ const firstX = Math.ceil(screenToWorldX(this.view, 0) / gapBlocks) * gapBlocks
+ for (let worldX = firstX; worldX <= screenToWorldX(this.view, this.view.width); worldX += gapBlocks) {
+ const screenX = Math.round(worldToScreenX(this.view, worldX)) + 0.5
+ context.moveTo(screenX, 0)
+ context.lineTo(screenX, this.view.height)
+ }
+ const firstZ = Math.ceil(screenToWorldZ(this.view, 0) / gapBlocks) * gapBlocks
+ for (let worldZ = firstZ; worldZ <= screenToWorldZ(this.view, this.view.height); worldZ += gapBlocks) {
+ const screenZ = Math.round(worldToScreenZ(this.view, worldZ)) + 0.5
+ context.moveTo(0, screenZ)
+ context.lineTo(this.view.width, screenZ)
+ }
+ context.stroke()
+ }
+
+ private drawMarkers(): void {
+ for (const entity of this.entities) {
+ this.drawEntity(entity)
+ }
+ for (const player of this.players) {
+ drawPlayerArrow(this.context, worldToScreenX(this.view, player.worldX), worldToScreenZ(this.view, player.worldZ), player.yaw, player.label)
+ }
+ }
+
+ private drawEntity(entity: Marker): void {
+ const context = this.context
+ context.beginPath()
+ context.arc(worldToScreenX(this.view, entity.worldX), worldToScreenZ(this.view, entity.worldZ), ENTITY_RADIUS_PIXELS, 0, Math.PI * 2)
+ context.fillStyle = ENTITY_FILL
+ context.fill()
+ context.lineWidth = 2
+ context.strokeStyle = MARKER_OUTLINE
+ context.stroke()
+ }
+
+ private lastReady = 0
+ private lastTotal = 0
+
+ private reportStatus(ready = this.lastReady, total = this.lastTotal): void {
+ this.lastReady = ready
+ this.lastTotal = total
+ const cursor = this.cursor === null ? { x: this.view.width / 2, y: this.view.height / 2 } : this.cursor
+ this.listener.onStatus({
+ blocksPerPixel: this.view.blocksPerPixel,
+ widthBlocks: Math.round(this.view.width * this.view.blocksPerPixel),
+ heightBlocks: Math.round(this.view.height * this.view.blocksPerPixel),
+ tilesReady: ready,
+ tilesTotal: total,
+ cursorX: Math.floor(screenToWorldX(this.view, cursor.x)),
+ cursorZ: Math.floor(screenToWorldZ(this.view, cursor.y))
+ })
+ }
+
+ // Counting what is on screen is cheap but not free, so it runs at most a few times a second and once more at rest.
+ private scheduleCensus(tiles: TileAddress[]): void {
+ window.clearTimeout(this.censusTimer)
+ const wait = Math.max(0, this.lastCensusMillis + CENSUS_INTERVAL_MILLIS - performance.now())
+ this.censusTimer = window.setTimeout(() => {
+ this.lastCensusMillis = performance.now()
+ this.listener.onShares(this.census(tiles))
+ this.listener.onArea(this.screenArea())
+ }, wait)
+ }
+
+ private screenArea(): WorldRect {
+ return {
+ minX: screenToWorldX(this.view, 0),
+ minZ: screenToWorldZ(this.view, 0),
+ maxX: screenToWorldX(this.view, this.view.width),
+ maxZ: screenToWorldZ(this.view, this.view.height)
+ }
+ }
+
+ private census(tiles: TileAddress[]): Share[] {
+ const placed: PlacedTile[] = []
+ for (const address of tiles) {
+ const tile = this.store.get(address, this.layer)
+ if (tile !== null) {
+ const span = this.world.tileSize * address.blocksPerPixel
+ placed.push({ tile, worldX: address.tileX * span, worldZ: address.tileZ * span })
+ }
+ }
+ const screen = this.screenArea()
+ const area = { minimumX: screen.minX, minimumZ: screen.minZ, maximumX: screen.maxX, maximumZ: screen.maxZ }
+ return countShares(placed, area)
+ }
+}
+
+function labelAt(labels: MapLabel[], index: number): Highlight | null {
+ if (index === NO_LABEL) {
+ return null
+ }
+ const label = labels[index]
+ return { kind: label.kind, key: label.key, name: label.name }
+}
diff --git a/studio/src/renderer/src/map/TileStore.ts b/studio/src/renderer/src/map/TileStore.ts
new file mode 100644
index 000000000..89a920bf3
--- /dev/null
+++ b/studio/src/renderer/src/map/TileStore.ts
@@ -0,0 +1,200 @@
+import { BridgeError } from '../bridge/BridgeClient'
+import type { TileAddress } from './viewport'
+
+/** What a store's tiles are, where they come from, and how one is drawn in a style. */
+export interface TileSource {
+ /** Tells layers apart; a layer that changes on hotload carries its revision here, so older tiles are not used again. */
+ layerKey(layer: Layer): string
+ fetch(address: TileAddress, layer: Layer, signal: AbortSignal): Promise
+ bytesOf(tile: Tile): number
+ /** Only for sources whose tiles are drawn as pictures. */
+ styleKey?(style: Style): string
+ pixels?(tile: Tile, style: Style): ImageData
+}
+
+interface StoredTile {
+ tile: Tile
+ address: TileAddress
+ layerKey: string
+ bytes: number
+ lastUsed: number
+ picture: HTMLCanvasElement | null
+ pictureStyle: string
+}
+
+// Drawing a few hundred tiles at once only queues them on the server; a handful in flight keeps it busy.
+const MAXIMUM_IN_FLIGHT = 6
+// A 3D view holds a couple of hundred tiles of blocks, half a megabyte each, and turning back should not sample them again.
+const CACHE_BYTES = 1024 * 1024 * 1024
+
+/**
+ * Tiles fetched from the bridge as a view needs them, kept within a memory budget, and drawn as the current style
+ * asks. A tile that leaves the view before it arrives is not fetched.
+ */
+export class TileStore {
+ private readonly tiles = new Map>()
+ private readonly inFlight = new Map()
+ /** Asked for again only after a refresh, which changes every key, so a broken tile is not fetched on every frame. */
+ private readonly failed = new Set()
+ private wanted: { key: string; address: TileAddress; layer: Layer }[] = []
+ private storedBytes = 0
+ private useClock = 0
+ private changes = 0
+
+ constructor(
+ private readonly source: TileSource,
+ private readonly onChange: () => void,
+ private readonly onError: (message: string) => void
+ ) {}
+
+ key(address: TileAddress, layer: Layer): string {
+ return `${this.source.layerKey(layer)}/${address.blocksPerPixel}/${address.tileX}/${address.tileZ}`
+ }
+
+ /** The tile if it has arrived, marked as just used. */
+ get(address: TileAddress, layer: Layer): Tile | null {
+ const stored = this.tiles.get(this.key(address, layer))
+ if (stored === undefined) {
+ return null
+ }
+ stored.lastUsed = ++this.useClock
+ return stored.tile
+ }
+
+ /** Whether the tile has arrived; unlike {@link get}, asking does not count as using it. */
+ has(address: TileAddress, layer: Layer): boolean {
+ return this.tiles.has(this.key(address, layer))
+ }
+
+ /** Where the layer's tiles that have arrived lie; asking does not count as using them. */
+ addressesOf(layer: Layer): TileAddress[] {
+ const layerKey = this.source.layerKey(layer)
+ return [...this.tiles.values()].filter((stored) => stored.layerKey === layerKey).map((stored) => stored.address)
+ }
+
+ /** Changes whenever a tile arrives or is let go, so what is worked out from the stored tiles is worked out again. */
+ get version(): number {
+ return this.changes
+ }
+
+ /** The tile drawn in {@code style}; restyled only when the style changed since it was last drawn. */
+ picture(address: TileAddress, layer: Layer, style: Style): HTMLCanvasElement | null {
+ const stored = this.tiles.get(this.key(address, layer))
+ if (stored === undefined || this.source.styleKey === undefined || this.source.pixels === undefined) {
+ return null
+ }
+ stored.lastUsed = ++this.useClock
+ const wantedStyle = this.source.styleKey(style)
+ if (stored.picture === null || stored.pictureStyle !== wantedStyle) {
+ stored.picture = stored.picture ?? document.createElement('canvas')
+ paint(stored.picture, this.source.pixels(stored.tile, style))
+ stored.pictureStyle = wantedStyle
+ }
+ return stored.picture
+ }
+
+ /** Fetches the tiles the view shows, in the order given, and gives up on the ones it no longer shows. */
+ want(addresses: TileAddress[], layer: Layer): void {
+ this.wantEach(addresses.map((address) => ({ address, layer })))
+ }
+
+ /** As {@link want}, each tile of its own layer. */
+ wantEach(tiles: { address: TileAddress; layer: Layer }[]): void {
+ this.wanted = tiles
+ .map(({ address, layer }) => ({ key: this.key(address, layer), address, layer }))
+ .filter((entry) => !this.tiles.has(entry.key) && !this.failed.has(entry.key))
+ const stillWanted = new Set(this.wanted.map((entry) => entry.key))
+ for (const [key, request] of this.inFlight) {
+ if (!stillWanted.has(key)) {
+ request.controller.abort()
+ this.inFlight.delete(key)
+ }
+ }
+ this.startRequests()
+ }
+
+ /** How many of the wanted tiles are still on their way. */
+ pending(): number {
+ return this.wanted.length
+ }
+
+ clear(): void {
+ for (const request of this.inFlight.values()) {
+ request.controller.abort()
+ }
+ this.inFlight.clear()
+ this.failed.clear()
+ this.tiles.clear()
+ this.wanted = []
+ this.storedBytes = 0
+ this.changes++
+ }
+
+ // Each layer has its own requests in flight, so tiles of a slow layer, which take a minute, never hold up a quick one's.
+ private startRequests(): void {
+ const inFlightByLayer = new Map()
+ for (const { layerKey } of this.inFlight.values()) {
+ inFlightByLayer.set(layerKey, (inFlightByLayer.get(layerKey) ?? 0) + 1)
+ }
+ for (const entry of this.wanted) {
+ const layerKey = this.source.layerKey(entry.layer)
+ const inFlight = inFlightByLayer.get(layerKey) ?? 0
+ if (this.inFlight.has(entry.key) || inFlight >= MAXIMUM_IN_FLIGHT) {
+ continue
+ }
+ inFlightByLayer.set(layerKey, inFlight + 1)
+ this.fetchTile(entry.key, layerKey, entry.address, entry.layer)
+ }
+ }
+
+ private fetchTile(key: string, layerKey: string, address: TileAddress, layer: Layer): void {
+ const controller = new AbortController()
+ this.inFlight.set(key, { controller, layerKey })
+ this.source
+ .fetch(address, layer, controller.signal)
+ .then((tile) => this.store(key, address, layer, tile))
+ .catch((error: unknown) => {
+ if (!controller.signal.aborted) {
+ this.failed.add(key)
+ this.onError(error instanceof BridgeError ? error.message : 'The server did not answer')
+ }
+ })
+ .finally(() => {
+ if (this.inFlight.get(key)?.controller === controller) {
+ this.inFlight.delete(key)
+ }
+ this.wanted = this.wanted.filter((entry) => entry.key !== key)
+ this.startRequests()
+ this.onChange()
+ })
+ }
+
+ private store(key: string, address: TileAddress, layer: Layer, tile: Tile): void {
+ const bytes = this.source.bytesOf(tile)
+ this.tiles.set(key, { tile, address, layerKey: this.source.layerKey(layer), bytes, lastUsed: ++this.useClock, picture: null, pictureStyle: '' })
+ this.storedBytes += bytes
+ this.changes++
+ this.evictOldest()
+ }
+
+ private evictOldest(): void {
+ if (this.storedBytes <= CACHE_BYTES) {
+ return
+ }
+ const byAge = [...this.tiles.entries()].sort((first, second) => first[1].lastUsed - second[1].lastUsed)
+ for (const [key, stored] of byAge) {
+ if (this.storedBytes <= CACHE_BYTES * 0.8) {
+ return
+ }
+ this.tiles.delete(key)
+ this.storedBytes -= stored.bytes
+ this.changes++
+ }
+ }
+}
+
+function paint(canvas: HTMLCanvasElement, pixels: ImageData): void {
+ canvas.width = pixels.width
+ canvas.height = pixels.height
+ canvas.getContext('2d')!.putImageData(pixels, 0, 0)
+}
diff --git a/studio/src/renderer/src/map/TiledView.ts b/studio/src/renderer/src/map/TiledView.ts
new file mode 100644
index 000000000..faedff9dc
--- /dev/null
+++ b/studio/src/renderer/src/map/TiledView.ts
@@ -0,0 +1,188 @@
+import { drawVisibleTiles } from './tileDrawing'
+import { TileStore, type TileSource } from './TileStore'
+import {
+ MAXIMUM_BLOCKS_PER_PIXEL,
+ MINIMUM_VIEW_BLOCKS_PER_PIXEL,
+ renderBlocksPerPixel,
+ screenToWorldX,
+ screenToWorldZ,
+ type TileAddress,
+ type Viewport
+} from './viewport'
+
+export interface TiledViewOptions {
+ source: TileSource
+ tileSize: number
+ defaultBlocksPerPixel: number
+ /** The finest scale tiles are asked for at; closer views magnify them. */
+ finestRenderBlocksPerPixel: number
+ /** How far the view may zoom out. */
+ coarsestBlocksPerPixel?: number
+ onFrame(frame: TiledFrame): void
+ onError(message: string): void
+}
+
+export interface TiledFrame {
+ blocksPerPixel: number
+ tilesReady: number
+ tilesTotal: number
+ /** The world spot under the cursor, or under the middle when the cursor is away. */
+ cursorX: number
+ cursorZ: number
+}
+
+/** A tile and the pixel of it at a world spot. */
+export interface TileSpot {
+ tile: Tile
+ pixelX: number
+ pixelZ: number
+}
+
+/** Where a view looks and the scale its tiles are drawn at. */
+export interface TiledFraming {
+ centerX: number
+ centerZ: number
+ renderScale: number
+}
+
+/**
+ * A pan and zoom view of tiles on a canvas, fetched as the view moves and drawn in the current style. Kept outside
+ * React, as it redraws on every drag and wheel step.
+ */
+export class TiledView {
+ private readonly context: CanvasRenderingContext2D
+ private readonly store: TileStore
+ private readonly view: Viewport
+ private layer: Layer | null = null
+ private style: Style | null = null
+ private cursor: { x: number; y: number } | null = null
+ private drawn = { tilesReady: 0, tilesTotal: 0 }
+ private frameRequested = false
+ private closed = false
+
+ constructor(
+ private readonly canvas: HTMLCanvasElement,
+ private readonly options: TiledViewOptions
+ ) {
+ this.context = canvas.getContext('2d')!
+ this.view = { centerX: 0, centerZ: 0, blocksPerPixel: options.defaultBlocksPerPixel, width: 1, height: 1 }
+ this.store = new TileStore(options.source, () => this.redraw(), options.onError)
+ }
+
+ close(): void {
+ this.closed = true
+ this.store.clear()
+ }
+
+ resize(width: number, height: number): void {
+ const ratio = window.devicePixelRatio
+ this.canvas.width = Math.round(width * ratio)
+ this.canvas.height = Math.round(height * ratio)
+ this.view.width = width
+ this.view.height = height
+ this.redraw()
+ }
+
+ show(layer: Layer | null, style: Style): void {
+ this.layer = layer
+ this.style = style
+ this.redraw()
+ }
+
+ panBy(screenDeltaX: number, screenDeltaZ: number): void {
+ this.view.centerX -= screenDeltaX * this.view.blocksPerPixel
+ this.view.centerZ -= screenDeltaZ * this.view.blocksPerPixel
+ this.redraw()
+ }
+
+ /** Zooms by {@code factor} (above 1 zooms in) keeping the spot under the screen point where it is. */
+ zoomAt(factor: number, screenX = this.view.width / 2, screenZ = this.view.height / 2): void {
+ const worldX = screenToWorldX(this.view, screenX)
+ const worldZ = screenToWorldZ(this.view, screenZ)
+ const coarsest = this.options.coarsestBlocksPerPixel ?? MAXIMUM_BLOCKS_PER_PIXEL
+ this.view.blocksPerPixel = Math.min(coarsest, Math.max(MINIMUM_VIEW_BLOCKS_PER_PIXEL, this.view.blocksPerPixel / factor))
+ this.view.centerX = worldX - (screenX - this.view.width / 2) * this.view.blocksPerPixel
+ this.view.centerZ = worldZ - (screenZ - this.view.height / 2) * this.view.blocksPerPixel
+ this.redraw()
+ }
+
+ resetView(): void {
+ this.view.centerX = 0
+ this.view.centerZ = 0
+ this.view.blocksPerPixel = this.options.defaultBlocksPerPixel
+ this.redraw()
+ }
+
+ setCursor(cursor: { x: number; y: number } | null): void {
+ this.cursor = cursor
+ this.reportFrame()
+ }
+
+ framing(): TiledFraming {
+ return { centerX: this.view.centerX, centerZ: this.view.centerZ, renderScale: this.renderScale() }
+ }
+
+ /** The tile drawn at a world spot at the current scale and its pixel there; null before it arrived. */
+ spotAt(worldX: number, worldZ: number): TileSpot | null {
+ if (this.layer === null) {
+ return null
+ }
+ const scale = this.renderScale()
+ const span = this.options.tileSize * scale
+ const address: TileAddress = { tileX: Math.floor(worldX / span), tileZ: Math.floor(worldZ / span), blocksPerPixel: scale }
+ const tile = this.store.get(address, this.layer)
+ if (tile === null) {
+ return null
+ }
+ const last = this.options.tileSize - 1
+ const pixelX = Math.min(last, Math.floor((worldX - address.tileX * span) / scale))
+ const pixelZ = Math.min(last, Math.floor((worldZ - address.tileZ * span) / scale))
+ return { tile, pixelX, pixelZ }
+ }
+
+ private renderScale(): number {
+ return renderBlocksPerPixel(this.view.blocksPerPixel, window.devicePixelRatio, this.options.finestRenderBlocksPerPixel)
+ }
+
+ private redraw(): void {
+ if (this.frameRequested || this.closed) {
+ return
+ }
+ this.frameRequested = true
+ requestAnimationFrame(() => {
+ this.frameRequested = false
+ if (!this.closed) {
+ this.draw()
+ }
+ })
+ }
+
+ private draw(): void {
+ const ratio = window.devicePixelRatio
+ const context = this.context
+ context.setTransform(ratio, 0, 0, ratio, 0, 0)
+ context.fillStyle = getComputedStyle(this.canvas).getPropertyValue('--map-background') || '#16171a'
+ context.fillRect(0, 0, this.view.width, this.view.height)
+ const layer = this.layer
+ const style = this.style
+ if (layer === null || style === null) {
+ this.drawn = { tilesReady: 0, tilesTotal: 0 }
+ this.reportFrame()
+ return
+ }
+ const drawn = drawVisibleTiles(context, this.view, this.renderScale(), this.options.tileSize, (address) => this.store.picture(address, layer, style))
+ this.store.want(drawn.wanted, layer)
+ this.drawn = { tilesReady: drawn.ready, tilesTotal: drawn.tiles.length }
+ this.reportFrame()
+ }
+
+ private reportFrame(): void {
+ const cursor = this.cursor ?? { x: this.view.width / 2, y: this.view.height / 2 }
+ this.options.onFrame({
+ blocksPerPixel: this.view.blocksPerPixel,
+ ...this.drawn,
+ cursorX: screenToWorldX(this.view, cursor.x),
+ cursorZ: screenToWorldZ(this.view, cursor.y)
+ })
+ }
+}
diff --git a/studio/src/renderer/src/map/census.ts b/studio/src/renderer/src/map/census.ts
new file mode 100644
index 000000000..7a00c1a7b
--- /dev/null
+++ b/studio/src/renderer/src/map/census.ts
@@ -0,0 +1,85 @@
+import { gridIndex } from '../bridge/tileDecoding'
+import { NO_LABEL, type MapTile } from '../bridge/types'
+import { bandIndexOf, HEIGHT_BANDS } from './heightColors'
+import type { Highlight } from './tileStyle'
+
+/** How much of the screen one biome, region or height band covers. */
+export interface Share {
+ subject: Highlight
+ color: number
+ fraction: number
+}
+
+/** A loaded tile and where its top left pixel lies in the world. */
+export interface PlacedTile {
+ tile: MapTile
+ worldX: number
+ worldZ: number
+}
+
+export interface WorldArea {
+ minimumX: number
+ minimumZ: number
+ maximumX: number
+ maximumZ: number
+}
+
+// Enough samples that a share is right to a fraction of a percent, few enough to count every frame the map settles.
+const MAXIMUM_COUNTED_PIXELS = 250_000
+
+/**
+ * The shares of what the tiles show inside {@code area}, largest first: their subjects, which are biomes or regions.
+ */
+export function countShares(tiles: PlacedTile[], area: WorldArea): Share[] {
+ const counts = new Map()
+ const totalPixels = tiles.reduce((sum, placed) => sum + placed.tile.size * placed.tile.size, 0)
+ const stride = Math.max(1, Math.ceil(Math.sqrt(totalPixels / MAXIMUM_COUNTED_PIXELS)))
+ let counted = 0
+ for (const { tile, worldX, worldZ } of tiles) {
+ const scale = tile.blocksPerPixel
+ const firstX = Math.max(0, Math.ceil((area.minimumX - worldX) / scale))
+ const endX = Math.min(tile.size, Math.ceil((area.maximumX - worldX) / scale))
+ const firstZ = Math.max(0, Math.ceil((area.minimumZ - worldZ) / scale))
+ const endZ = Math.min(tile.size, Math.ceil((area.maximumZ - worldZ) / scale))
+ for (let pixelZ = firstZ; pixelZ < endZ; pixelZ += stride) {
+ for (let pixelX = firstX; pixelX < endX; pixelX += stride) {
+ const subject = subjectAt(tile, gridIndex(tile, pixelX, pixelZ))
+ if (subject === null) {
+ continue
+ }
+ const id = `${subject.subject.kind}:${subject.subject.key}`
+ const entry = counts.get(id) ?? { ...subject, count: 0 }
+ entry.count++
+ counts.set(id, entry)
+ counted++
+ }
+ }
+ }
+ return [...counts.values()]
+ .map((entry) => ({ subject: entry.subject, color: entry.color, fraction: entry.count / Math.max(1, counted) }))
+ .sort((first, second) => second.fraction - first.fraction)
+}
+
+/** The shares of the height bands the {@code heights} fall in, highest band first. */
+export function heightBandShares(heights: readonly number[], seaLevel: number): Share[] {
+ const counts = new Map()
+ for (const height of heights) {
+ const band = bandIndexOf(height, seaLevel)
+ counts.set(band, (counts.get(band) ?? 0) + 1)
+ }
+ return [...counts]
+ .sort(([firstBand], [secondBand]) => secondBand - firstBand)
+ .map(([band, count]) => {
+ const { key, name, color } = HEIGHT_BANDS[band]
+ return { subject: { kind: 'HEIGHT', key, name }, color, fraction: count / heights.length }
+ })
+}
+
+function subjectAt(tile: MapTile, cell: number): { subject: Highlight; color: number } | null {
+ const index = tile.subjects[cell]
+ if (index === NO_LABEL) {
+ return null
+ }
+ const label = tile.labels[index]
+ return { subject: { kind: label.kind, key: label.key, name: label.name }, color: label.color }
+}
diff --git a/studio/src/renderer/src/map/heightColors.ts b/studio/src/renderer/src/map/heightColors.ts
new file mode 100644
index 000000000..de14ad17e
--- /dev/null
+++ b/studio/src/renderer/src/map/heightColors.ts
@@ -0,0 +1,76 @@
+/** The height scale of the map, from deep water to snowy peaks, measured from sea level (v3e HeightColors). */
+
+export const DEEPEST_BELOW_SEA_BLOCKS = 90
+export const HIGHEST_ABOVE_SEA_BLOCKS = 300
+const DEPTH_BLOCKS = [0, 10, 40, DEEPEST_BELOW_SEA_BLOCKS]
+const DEPTH_COLORS = [0x7db8d8, 0x4c8dba, 0x2a5e8f, 0x15304f]
+const ABOVE_SEA_BLOCKS = [0, 8, 30, 70, 130, 200, HIGHEST_ABOVE_SEA_BLOCKS]
+const LAND_COLORS = [0x7fa35a, 0x5e8c44, 0x8fa65a, 0xc2ae78, 0x8e7663, 0xa9a6a2, 0xf4f4f4]
+// Where each band ends, in blocks above sea; they follow the colour stops, merging the deepest two.
+const BAND_TOPS_ABOVE_SEA = [-40, -10, 0, 8, 30, 70, 130, 200, 300, Number.POSITIVE_INFINITY]
+
+/** A stretch of heights between two of the scale's stops, for telling how much ground lies at each height. */
+export interface HeightBand {
+ /** The band's place from the deepest, as text that sorts the same way. */
+ key: string
+ name: string
+ color: number
+}
+
+export function heightColor(height: number, seaLevel: number): number {
+ if (height <= seaLevel) {
+ return along(DEPTH_BLOCKS, DEPTH_COLORS, seaLevel - height)
+ }
+ return along(ABOVE_SEA_BLOCKS, LAND_COLORS, height - seaLevel)
+}
+
+export const HEIGHT_BANDS: readonly HeightBand[] = createBands()
+
+export function bandIndexOf(height: number, seaLevel: number): number {
+ const aboveSea = height - seaLevel
+ const index = BAND_TOPS_ABOVE_SEA.findIndex((top) => aboveSea <= top)
+ return index < 0 ? BAND_TOPS_ABOVE_SEA.length - 1 : index
+}
+
+function createBands(): HeightBand[] {
+ const bands: HeightBand[] = []
+ let bottom = -DEEPEST_BELOW_SEA_BLOCKS
+ BAND_TOPS_ABOVE_SEA.forEach((top, band) => {
+ const colorHeight = Number.isFinite(top) ? (bottom + top) / 2 : bottom
+ bands.push({ key: String(band).padStart(2, '0'), name: bandName(band, bottom, top), color: heightColor(colorHeight, 0) })
+ bottom = top
+ })
+ return bands
+}
+
+function bandName(band: number, bottom: number, top: number): string {
+ if (band === 0) {
+ return `${Math.round(-top)}+ below sea`
+ }
+ if (!Number.isFinite(top)) {
+ return `${Math.round(bottom)}+ above sea`
+ }
+ if (top <= 0) {
+ return `${Math.round(-top)}–${Math.round(-bottom)} below sea`
+ }
+ return `${Math.round(bottom)}–${Math.round(top)} above sea`
+}
+
+function along(stops: number[], colors: number[], blocks: number): number {
+ if (blocks <= stops[0]) {
+ return colors[0]
+ }
+ for (let stop = 1; stop < stops.length; stop++) {
+ if (blocks <= stops[stop]) {
+ return blend(colors[stop - 1], colors[stop], (blocks - stops[stop - 1]) / (stops[stop] - stops[stop - 1]))
+ }
+ }
+ return colors[colors.length - 1]
+}
+
+export function blend(first: number, second: number, amount: number): number {
+ const red = Math.round(((first >> 16) & 0xff) * (1 - amount) + ((second >> 16) & 0xff) * amount)
+ const green = Math.round(((first >> 8) & 0xff) * (1 - amount) + ((second >> 8) & 0xff) * amount)
+ const blue = Math.round((first & 0xff) * (1 - amount) + (second & 0xff) * amount)
+ return (red << 16) | (green << 8) | blue
+}
diff --git a/studio/src/renderer/src/map/map.test.ts b/studio/src/renderer/src/map/map.test.ts
new file mode 100644
index 000000000..4ad7b8a0c
--- /dev/null
+++ b/studio/src/renderer/src/map/map.test.ts
@@ -0,0 +1,323 @@
+import { describe, expect, it } from 'vitest'
+import { decodeTile, gridIndex } from '../bridge/tileDecoding'
+import type { MapLabel, MapTile, TileBlocks } from '../bridge/types'
+import { countShares, heightBandShares } from './census'
+import { bandIndexOf, HEIGHT_BANDS, heightColor } from './heightColors'
+import { arrowCorners } from './playerArrow'
+import { stylePixels, type TileStyle } from './tileStyle'
+import { coarserTile, previewsFor, renderBlocksPerPixel, screenToWorldX, visibleTiles, worldToScreenX, type Viewport } from './viewport'
+
+const PLAINS: MapLabel = { kind: 'BIOME', key: 'plains', name: 'Plains', color: 0x00ff00 }
+const DESERT: MapLabel = { kind: 'BIOME', key: 'desert', name: 'Desert', color: 0xffff00 }
+const WARM: MapLabel = { kind: 'REGION', key: 'warm', name: 'Warm', color: 0xff0000 }
+const FLAT: TileStyle = { byBlock: false, shading: false, regionBorders: false, highlight: null, seaLevel: 63, pickDisplay: 'picks' }
+
+/** A tile whose left half is plains and right half desert, all in one region, at height 70. */
+function splitTile(size = 4): MapTile {
+ const cells = (size + 2) ** 2
+ const subjects = new Int16Array(cells)
+ for (let cell = 0; cell < cells; cell++) {
+ subjects[cell] = cell % (size + 2) <= size / 2 ? 0 : 1
+ }
+ return {
+ size,
+ blocksPerPixel: 1,
+ subjectKind: 'BIOME',
+ labels: [PLAINS, DESERT, WARM],
+ subjects,
+ regions: new Int16Array(cells).fill(2),
+ heights: new Float32Array(cells).fill(70),
+ pickNoise: null,
+ blocks: null
+ }
+}
+
+/** A tile as the bridge sends it: u32 header length, JSON header, aligned grids. */
+function encode(size: number, withHeights: boolean, withPickNoise = false): ArrayBuffer {
+ const header = new TextEncoder().encode(
+ JSON.stringify({ size, blocksPerPixel: 2, subjectKind: 'BIOME', labels: [PLAINS], heights: withHeights, pickNoise: withPickNoise })
+ )
+ const cells = (size + 2) ** 2
+ const align = (bytes: number): number => Math.ceil(bytes / 4) * 4
+ const subjectsAt = align(4 + header.length)
+ const regionsAt = align(subjectsAt + cells * 2)
+ const heightsAt = align(regionsAt + cells * 2)
+ const pickNoiseAt = heightsAt + (withHeights ? cells * 4 : 0)
+ const buffer = new ArrayBuffer(pickNoiseAt + (withPickNoise ? cells * 4 : 0))
+ new DataView(buffer).setUint32(0, header.length, true)
+ new Uint8Array(buffer, 4).set(header)
+ new Int16Array(buffer, subjectsAt, cells).fill(0)
+ new Int16Array(buffer, regionsAt, cells).fill(-1)
+ if (withHeights) {
+ new Float32Array(buffer, heightsAt, cells).fill(81.5)
+ }
+ if (withPickNoise) {
+ new Float32Array(buffer, pickNoiseAt, cells).fill(0.25)
+ }
+ return buffer
+}
+
+function nothingRaised(cells: number): Pick {
+ return { raisedStart: new Int32Array(cells + 1), raisedY: new Int16Array(0), raised: new Int16Array(0), voxels: null, runs: null, models: [] }
+}
+
+/** A tile of one pixel with its blocks as the bridge sends them: ground, cover and the raised blocks' counts, heights and blocks. */
+function encodeBlocks(raisedCounts: number[], raisedY: number[], raised: number[]): ArrayBuffer {
+ const size = 1
+ const cells = (size + 2) ** 2
+ const header = new TextEncoder().encode(
+ JSON.stringify({ size, blocksPerPixel: 1, subjectKind: 'BIOME', labels: [PLAINS], heights: false, pickNoise: false, blocks: ['stone', 'leaves', 'log'], raised: raised.length })
+ )
+ const align = (bytes: number): number => Math.ceil(bytes / 4) * 4
+ const grid = align(cells * 2)
+ const groundAt = align(4 + header.length) + grid * 2
+ const raisedYAt = groundAt + grid * 3
+ const raisedAt = align(raisedYAt + raised.length * 2)
+ const buffer = new ArrayBuffer(raisedAt + align(raised.length * 2))
+ new DataView(buffer).setUint32(0, header.length, true)
+ new Uint8Array(buffer, 4).set(header)
+ new Int16Array(buffer, groundAt + grid, cells).fill(-1)
+ new Int16Array(buffer, groundAt + grid * 2, cells).set(raisedCounts)
+ new Int16Array(buffer, raisedYAt, raised.length).set(raisedY)
+ new Int16Array(buffer, raisedAt, raised.length).set(raised)
+ return buffer
+}
+
+describe('tile decoding', () => {
+ it('reads the raised blocks of each cell after the cover grid', () => {
+ const blocks = decodeTile(encodeBlocks([0, 0, 0, 0, 2, 0, 0, 1, 0], [70, 69, 66], [1, 2, 1])).blocks!
+
+ expect([...blocks.raisedStart]).toEqual([0, 0, 0, 0, 0, 2, 2, 2, 3, 3])
+ expect([...blocks.raisedY]).toEqual([70, 69, 66])
+ expect([...blocks.raised]).toEqual([1, 2, 1])
+ expect(blocks.cover[4]).toBe(-1)
+ })
+
+ it('reads the header and views each grid where the bridge put it', () => {
+ const tile = decodeTile(encode(3, true))
+
+ expect(tile.size).toBe(3)
+ expect(tile.blocksPerPixel).toBe(2)
+ expect(tile.labels[0].key).toBe('plains')
+ expect(tile.subjects.length).toBe(25)
+ expect(tile.regions[0]).toBe(-1)
+ expect(tile.heights?.[24]).toBe(81.5)
+ })
+
+ it('has no heights when the header says so', () => {
+ expect(decodeTile(encode(3, false)).heights).toBeNull()
+ })
+
+ it('reads the pick noise after the heights, or in their place without them', () => {
+ expect(decodeTile(encode(3, true, true)).pickNoise?.[24]).toBe(0.25)
+ expect(decodeTile(encode(3, false, true)).pickNoise?.[0]).toBe(0.25)
+ expect(decodeTile(encode(3, true)).pickNoise).toBeNull()
+ })
+})
+
+describe('pick noise', () => {
+ function noisyTile(noise: number): MapTile {
+ const tile = splitTile()
+ return { ...tile, pickNoise: new Float32Array(tile.subjects.length).fill(noise) }
+ }
+
+ it('draws the bare noise from dark to white', () => {
+ const pixels = stylePixels(noisyTile(1), { ...FLAT, pickDisplay: 'noise' })
+
+ expect([pixels[0], pixels[1], pixels[2]]).toEqual([255, 255, 255])
+ })
+
+ it('draws the picks darker where their noise is lower', () => {
+ const pixels = stylePixels(noisyTile(0), { ...FLAT, pickDisplay: 'both' })
+
+ expect(pixels[1]).toBe(Math.floor(255 * 0.3))
+ })
+
+ it('leaves a spot nothing picked in its own colour', () => {
+ const pixels = stylePixels(noisyTile(Number.NaN), { ...FLAT, pickDisplay: 'noise' })
+
+ expect([pixels[0], pixels[1], pixels[2]]).toEqual([0, 255, 0])
+ })
+})
+
+describe('height colours', () => {
+ it('runs from deep water to snow and stays at the ends beyond them', () => {
+ expect(heightColor(63, 63)).toBe(0x7db8d8)
+ expect(heightColor(-1000, 63)).toBe(0x15304f)
+ expect(heightColor(1000, 63)).toBe(0xf4f4f4)
+ })
+
+ it('puts each height in the band the legend names', () => {
+ expect(HEIGHT_BANDS[bandIndexOf(63, 63)].name).toBe('0–10 below sea')
+ expect(HEIGHT_BANDS[bandIndexOf(64, 63)].name).toBe('0–8 above sea')
+ expect(HEIGHT_BANDS[bandIndexOf(500, 63)].name).toBe('300+ above sea')
+ expect(HEIGHT_BANDS[bandIndexOf(-500, 63)].name).toBe('40+ below sea')
+ })
+})
+
+describe('tile style', () => {
+ const pixel = (pixels: Uint8ClampedArray, size: number, x: number, z: number): number => {
+ const at = (z * size + x) * 4
+ return (pixels[at] << 16) | (pixels[at + 1] << 8) | pixels[at + 2]
+ }
+
+ it('paints each pixel in its label colour', () => {
+ const pixels = stylePixels(splitTile(), FLAT)
+
+ expect(pixel(pixels, 4, 0, 0)).toBe(PLAINS.color)
+ expect(pixel(pixels, 4, 3, 3)).toBe(DESERT.color)
+ })
+
+ it('paints each pixel in the colour of what stands on its ground, or of the ground itself', () => {
+ const tile = splitTile()
+ const cells = tile.subjects.length
+ const cover = new Int16Array(cells).fill(-1)
+ cover[gridIndex(tile, 3, 3)] = 1
+ const blocks = { ...nothingRaised(cells), names: ['stone', 'poppy'], ground: new Int16Array(cells).fill(0), cover, colors: [0x808080, 0xff0000], looks: [], covers: [] }
+ const pixels = stylePixels({ ...tile, blocks }, { ...FLAT, byBlock: true })
+
+ expect(pixel(pixels, 4, 0, 0)).toBe(0x808080)
+ expect(pixel(pixels, 4, 3, 3)).toBe(0xff0000)
+ })
+
+ it('paints a column with blocks raised over its ground in the colour of the highest', () => {
+ const tile = splitTile()
+ const cells = tile.subjects.length
+ const raisedStart = new Int32Array(cells + 1)
+ raisedStart.fill(2, gridIndex(tile, 3, 3) + 1)
+ const blocks = {
+ names: ['stone', 'leaves', 'log'],
+ ground: new Int16Array(cells).fill(0),
+ cover: new Int16Array(cells).fill(-1),
+ raisedStart,
+ raisedY: Int16Array.of(70, 69),
+ raised: Int16Array.of(1, 2),
+ voxels: null,
+ runs: null,
+ colors: [0x808080, 0x00ff00, 0x654321],
+ looks: [],
+ covers: [],
+ models: []
+ }
+ const pixels = stylePixels({ ...tile, blocks }, { ...FLAT, byBlock: true })
+
+ expect(pixel(pixels, 4, 0, 0)).toBe(0x808080)
+ expect(pixel(pixels, 4, 3, 3)).toBe(0x00ff00)
+ })
+
+ it('keeps the label colours of a tile without blocks', () => {
+ expect(pixel(stylePixels(splitTile(), { ...FLAT, byBlock: true }), 4, 0, 0)).toBe(PLAINS.color)
+ })
+
+ it('dims everything but the highlight, and tints the highlight edge', () => {
+ const pixels = stylePixels(splitTile(), { ...FLAT, highlight: { kind: 'BIOME', key: 'plains', name: 'Plains' } })
+
+ expect(pixel(pixels, 4, 3, 3)).not.toBe(DESERT.color)
+ expect(pixel(pixels, 4, 0, 1)).toBe(PLAINS.color)
+ expect(pixel(pixels, 4, 1, 1)).not.toBe(PLAINS.color)
+ })
+
+ it('leaves flat ground almost as it is when shading', () => {
+ const pixels = stylePixels(splitTile(), { ...FLAT, shading: true })
+ const green = (pixel(pixels, 4, 0, 0) >> 8) & 0xff
+
+ expect(green).toBeGreaterThan(200)
+ })
+})
+
+describe('viewport', () => {
+ const view: Viewport = { centerX: 100, centerZ: -50, blocksPerPixel: 2, width: 800, height: 600 }
+
+ it('maps screen and world both ways', () => {
+ expect(screenToWorldX(view, 400)).toBe(100)
+ expect(worldToScreenX(view, screenToWorldX(view, 123))).toBe(123)
+ })
+
+ it('draws tiles at the power of two nearest a device pixel, never finer than a block', () => {
+ expect(renderBlocksPerPixel(4, 1)).toBe(4)
+ expect(renderBlocksPerPixel(4, 2)).toBe(2)
+ expect(renderBlocksPerPixel(0.25, 1)).toBe(1)
+ expect(renderBlocksPerPixel(5.5, 1)).toBe(4)
+ })
+
+ it('covers the screen, starting from the middle', () => {
+ const tiles = visibleTiles(view, 2, 128)
+
+ // 1600 × 1200 blocks around (100, -50) in tiles of 256 blocks: x -3 to 3, z -3 to 2.
+ expect(tiles.length).toBe(7 * 6)
+ expect(tiles[0]).toEqual({ tileX: 0, tileZ: -1, blocksPerPixel: 2 })
+ })
+
+ it('finds the coarser tile that covers a tile', () => {
+ expect(coarserTile({ tileX: -3, tileZ: 5, blocksPerPixel: 2 }, 2)).toEqual({ tileX: -1, tileZ: 1, blocksPerPixel: 8 })
+ })
+
+ it('previews four blank tiles with one tile a level out, never past the coarsest scale', () => {
+ const blank = [
+ { tileX: 0, tileZ: 0, blocksPerPixel: 2 },
+ { tileX: 1, tileZ: 0, blocksPerPixel: 2 },
+ { tileX: 0, tileZ: 1, blocksPerPixel: 2 },
+ { tileX: -1, tileZ: 0, blocksPerPixel: 2 },
+ { tileX: 0, tileZ: 0, blocksPerPixel: 4096 }
+ ]
+
+ expect(previewsFor(blank)).toEqual([
+ { tileX: 0, tileZ: 0, blocksPerPixel: 4 },
+ { tileX: -1, tileZ: 0, blocksPerPixel: 4 }
+ ])
+ })
+})
+
+describe('census', () => {
+ it('shares the visible pixels between the labels', () => {
+ const tile = splitTile(4)
+ const shares = countShares([{ tile, worldX: 0, worldZ: 0 }], { minimumX: 0, minimumZ: 0, maximumX: 4, maximumZ: 4 })
+
+ expect(shares.map((share) => share.subject.key).sort()).toEqual(['desert', 'plains'])
+ expect(shares[0].fraction).toBeCloseTo(0.5)
+ expect(gridIndex(tile, -1, -1)).toBe(0)
+ })
+
+ it('counts only the part of a tile inside the area, largest share first', () => {
+ const shares = countShares([{ tile: splitTile(4), worldX: 0, worldZ: 0 }], { minimumX: 0, minimumZ: 0, maximumX: 3, maximumZ: 4 })
+
+ expect(shares.map((share) => share.subject.key)).toEqual(['plains', 'desert'])
+ expect(shares[0].fraction).toBeCloseTo(2 / 3)
+ })
+
+ it('shares spot heights between their bands, highest band first', () => {
+ const shares = heightBandShares([64, 64, 64, 500, 30], 63)
+
+ expect(shares.map((share) => share.subject.name)).toEqual(['300+ above sea', '0–8 above sea', '10–40 below sea'])
+ expect(shares.map((share) => share.fraction)).toEqual([0.2, 0.6, 0.2])
+ expect(shares[1].color).toBe(HEIGHT_BANDS[bandIndexOf(64, 63)].color)
+ })
+
+ it('has no shares for no heights', () => {
+ expect(heightBandShares([], 63)).toEqual([])
+ })
+})
+
+describe('player arrow', () => {
+ const tipAt = (yaw: number) => arrowCorners(yaw, 10, 7, 3)[0]
+
+ it('points the tip south, down the map, at yaw 0', () => {
+ expect(tipAt(0).x).toBeCloseTo(0)
+ expect(tipAt(0).z).toBeCloseTo(10)
+ })
+
+ it('points west at 90, north at 180 and east at 270', () => {
+ expect(tipAt(90).x).toBeCloseTo(-10)
+ expect(tipAt(90).z).toBeCloseTo(0)
+ expect(tipAt(180).z).toBeCloseTo(-10)
+ expect(tipAt(270).x).toBeCloseTo(10)
+ })
+
+ it('keeps its shape while turning', () => {
+ const [tip, right, notch, left] = arrowCorners(37, 10, 7, 3)
+
+ expect(Math.hypot(tip.x, tip.z)).toBeCloseTo(10)
+ expect(Math.hypot(right.x - left.x, right.z - left.z)).toBeCloseTo(14)
+ expect(Math.hypot(notch.x, notch.z)).toBeCloseTo(7)
+ })
+})
diff --git a/studio/src/renderer/src/map/mapTileSource.ts b/studio/src/renderer/src/map/mapTileSource.ts
new file mode 100644
index 000000000..d887cb1f0
--- /dev/null
+++ b/studio/src/renderer/src/map/mapTileSource.ts
@@ -0,0 +1,61 @@
+import type { BridgeClient } from '../bridge/BridgeClient'
+import type { BlockSource, MapTile } from '../bridge/types'
+import type { BlockArt } from '../scene/blockArt'
+import { stylePixels, styleKey, type TileStyle } from './tileStyle'
+import type { TileSource } from './TileStore'
+
+/** What one map tile request needs besides where the tile is. */
+export interface TileLayer {
+ view: string
+ /** The region the region view previews everywhere, or null for the world as it is. */
+ preview: string | null
+ heights: boolean
+ pickNoise: boolean
+ /** Where the tiles' blocks come from, or null for tiles without them. */
+ blocks: BlockSource | null
+ /** Whether tiles with blocks also carry the ground's shape in 3D, to draw it as blocks and runs of blocks. */
+ shape?: boolean
+ /** Bumped when the pack is hotloaded, so older tiles are not used again. */
+ revision: number
+}
+
+/**
+ * The coarsest tiles the map asks for blocks; coarser ones come without. Every chunk under a tile is generated for its
+ * blocks, so a map zoomed out over a few screens would keep the server busy for minutes.
+ */
+const MAP_MOST_BLOCKS_PER_PIXEL = 1
+const TEXTURED_BLOCKS_PER_PIXEL = 1
+
+function voxelBytesOf(tile: MapTile): number {
+ const voxels = tile.blocks?.voxels
+ return voxels === null || voxels === undefined ? 0 : voxels.x.byteLength * 3 + voxels.y.byteLength * 2
+}
+
+/** Whether the map's tiles this coarse carry blocks. */
+export function hasBlocksAt(blocksPerPixel: number): boolean {
+ return blocksPerPixel <= MAP_MOST_BLOCKS_PER_PIXEL
+}
+
+/**
+ * The world map's tiles: the engine's streams, drawn in the map's styles, their blocks painted with {@code art}.
+ *
+ * @param mostBlocksPerPixel the coarsest tiles that carry blocks; at most the 8 the server generates them for
+ */
+export function mapTileSource(client: BridgeClient, tileSize: number, art: BlockArt, mostBlocksPerPixel = MAP_MOST_BLOCKS_PER_PIXEL): TileSource {
+ return {
+ layerKey: (layer) => [layer.revision, layer.view, layer.preview ?? '', layer.heights, layer.pickNoise, layer.blocks ?? '', layer.shape === true].join('/'),
+ fetch: async (address, layer, signal) => {
+ const blocks = layer.blocks !== null && address.blocksPerPixel <= mostBlocksPerPixel ? layer.blocks : null
+ const tile = await client.tile({ ...layer, ...address, size: tileSize, blocks }, signal)
+ if (tile.blocks !== null) {
+ // Runs show each block's sides in the colours of its pictures, so their looks are read too.
+ await art.paint(tile.blocks, address.blocksPerPixel === TEXTURED_BLOCKS_PER_PIXEL || tile.blocks.runs !== null)
+ }
+ return tile
+ },
+ bytesOf: (tile) =>
+ tile.subjects.byteLength * 2 + (tile.heights?.byteLength ?? 0) + (tile.pickNoise?.byteLength ?? 0) + (tile.blocks?.ground.byteLength ?? 0) * 2 + (tile.blocks?.raisedStart.byteLength ?? 0) + (tile.blocks?.raised.byteLength ?? 0) * 2 + voxelBytesOf(tile) + tile.size * tile.size * 4,
+ styleKey,
+ pixels: (tile, style) => new ImageData(stylePixels(tile, style), tile.size, tile.size)
+ }
+}
diff --git a/studio/src/renderer/src/map/playerArrow.ts b/studio/src/renderer/src/map/playerArrow.ts
new file mode 100644
index 000000000..cb9f4bb99
--- /dev/null
+++ b/studio/src/renderer/src/map/playerArrow.ts
@@ -0,0 +1,85 @@
+export interface ScreenPoint {
+ x: number
+ z: number
+}
+
+const MINECRAFT_YAW_TO_SCREEN_DEGREES = 180
+const ARROW_HALF_LENGTH_PIXELS = 9.5
+const ARROW_HALF_WIDTH_PIXELS = 7.5
+const ARROW_NOTCH_PIXELS = 3.5
+const ARROW_EDGE_WIDTH_PIXELS = 1.75
+const ARROW_OUTLINE_WIDTH_PIXELS = 1
+const ARROW_SHADOW_OFFSET_PIXELS = 1.5
+const ARROW_REACH_PIXELS = ARROW_HALF_LENGTH_PIXELS + ARROW_EDGE_WIDTH_PIXELS + ARROW_OUTLINE_WIDTH_PIXELS
+const ARROW_FILL = '#3574f0'
+const ARROW_EDGE = '#ffffff'
+const ARROW_OUTLINE = 'rgba(0, 0, 0, 0.59)'
+const ARROW_SHADOW = 'rgba(0, 0, 0, 0.35)'
+const LABEL_GAP_PIXELS = 5
+const LABEL_HEIGHT_PIXELS = 18
+const LABEL_PADDING_X_PIXELS = 7
+const LABEL_FONT = '600 12px Inter, "Segoe UI", system-ui, sans-serif'
+const LABEL_BACKGROUND = 'rgba(30, 31, 34, 0.86)'
+const LABEL_BORDER = 'rgba(255, 255, 255, 0.22)'
+const LABEL_TEXT = '#ffffff'
+
+/**
+ * The corners of a player's arrow around the origin: tip, right wing, notch, left wing. Minecraft's yaw 0 faces
+ * south and 90 west, which on the map is down and left, so the heading is (-sin, cos) in (x, z).
+ */
+export function arrowCorners(yawDegrees: number, halfLength: number, halfWidth: number, notch: number): ScreenPoint[] {
+ const turn = ((yawDegrees + MINECRAFT_YAW_TO_SCREEN_DEGREES) * Math.PI) / 180
+ const sine = Math.sin(turn)
+ const cosine = Math.cos(turn)
+ const upright: ScreenPoint[] = [
+ { x: 0, z: -halfLength },
+ { x: halfWidth, z: halfLength },
+ { x: 0, z: halfLength - notch },
+ { x: -halfWidth, z: halfLength }
+ ]
+ return upright.map((corner) => ({ x: corner.x * cosine - corner.z * sine, z: corner.x * sine + corner.z * cosine }))
+}
+
+/** A blue arrow with a white edge, dark outline and shadow pointing where the player looks, and their name in a pill above. */
+export function drawPlayerArrow(context: CanvasRenderingContext2D, x: number, z: number, yawDegrees: number, name: string): void {
+ const corners = arrowCorners(yawDegrees, ARROW_HALF_LENGTH_PIXELS, ARROW_HALF_WIDTH_PIXELS, ARROW_NOTCH_PIXELS)
+ context.save()
+ context.lineJoin = 'round'
+ context.fillStyle = ARROW_SHADOW
+ context.fill(arrowPath(corners, x, z + ARROW_SHADOW_OFFSET_PIXELS))
+ const arrow = arrowPath(corners, x, z)
+ // Strokes are centred on the outline, so each ring is drawn twice its width and the next one covers its inner half.
+ context.lineWidth = (ARROW_EDGE_WIDTH_PIXELS + ARROW_OUTLINE_WIDTH_PIXELS) * 2
+ context.strokeStyle = ARROW_OUTLINE
+ context.stroke(arrow)
+ context.lineWidth = ARROW_EDGE_WIDTH_PIXELS * 2
+ context.strokeStyle = ARROW_EDGE
+ context.stroke(arrow)
+ context.fillStyle = ARROW_FILL
+ context.fill(arrow)
+ drawNamePill(context, name, x, z - ARROW_REACH_PIXELS - LABEL_GAP_PIXELS)
+ context.restore()
+}
+
+function arrowPath(corners: ScreenPoint[], x: number, z: number): Path2D {
+ const path = new Path2D()
+ corners.forEach((corner, index) => (index === 0 ? path.moveTo(x + corner.x, z + corner.z) : path.lineTo(x + corner.x, z + corner.z)))
+ path.closePath()
+ return path
+}
+
+function drawNamePill(context: CanvasRenderingContext2D, name: string, centerX: number, bottom: number): void {
+ context.font = LABEL_FONT
+ context.textAlign = 'center'
+ context.textBaseline = 'middle'
+ const width = context.measureText(name).width + LABEL_PADDING_X_PIXELS * 2
+ const pill = new Path2D()
+ pill.roundRect(centerX - width / 2, bottom - LABEL_HEIGHT_PIXELS, width, LABEL_HEIGHT_PIXELS, LABEL_HEIGHT_PIXELS / 2)
+ context.fillStyle = LABEL_BACKGROUND
+ context.fill(pill)
+ context.lineWidth = 1
+ context.strokeStyle = LABEL_BORDER
+ context.stroke(pill)
+ context.fillStyle = LABEL_TEXT
+ context.fillText(name, centerX, bottom - LABEL_HEIGHT_PIXELS / 2)
+}
diff --git a/studio/src/renderer/src/map/tileDrawing.ts b/studio/src/renderer/src/map/tileDrawing.ts
new file mode 100644
index 000000000..ac3b9545a
--- /dev/null
+++ b/studio/src/renderer/src/map/tileDrawing.ts
@@ -0,0 +1,82 @@
+import { coarserTile, previewsFor, visibleTiles, worldToScreenX, worldToScreenZ, type TileAddress, type Viewport } from './viewport'
+
+// While a tile is on its way, a coarser one already drawn stands in, up to this many zoom levels out.
+const COARSER_FALLBACK_LEVELS = 6
+
+export interface DrawnTiles {
+ /** Every tile the view covers, nearest the centre first. */
+ tiles: TileAddress[]
+ ready: number
+ /** What to fetch, in order: a coarser preview for each blank stretch first, then the tiles themselves. */
+ wanted: TileAddress[]
+}
+
+/**
+ * Draws the tiles covering the view at {@code renderScale}, from {@code pictureOf}; where one hasn't arrived, the part
+ * of a coarser one that covers it.
+ */
+export function drawVisibleTiles(
+ context: CanvasRenderingContext2D,
+ view: Viewport,
+ renderScale: number,
+ tileSize: number,
+ pictureOf: (address: TileAddress) => HTMLCanvasElement | null
+): DrawnTiles {
+ const tiles = visibleTiles(view, renderScale, tileSize)
+ context.imageSmoothingEnabled = view.blocksPerPixel > renderScale
+ let ready = 0
+ const blank: TileAddress[] = []
+ for (const address of tiles) {
+ const picture = pictureOf(address)
+ if (picture !== null) {
+ drawTile(context, view, tileSize, picture, address, 0, 0, picture.width)
+ ready++
+ } else if (!drawFallback(context, view, tileSize, address, pictureOf)) {
+ blank.push(address)
+ }
+ }
+ return { tiles, ready, wanted: [...previewsFor(blank), ...tiles] }
+}
+
+/** Draws the part of a tile picture from (sourceX, sourceZ), {@code sourceSize} pixels wide, over {@code address}. */
+function drawTile(
+ context: CanvasRenderingContext2D,
+ view: Viewport,
+ tileSize: number,
+ picture: HTMLCanvasElement,
+ address: TileAddress,
+ sourceX: number,
+ sourceZ: number,
+ sourceSize: number
+): void {
+ const span = tileSize * address.blocksPerPixel
+ const left = Math.round(worldToScreenX(view, address.tileX * span))
+ const top = Math.round(worldToScreenZ(view, address.tileZ * span))
+ const right = Math.round(worldToScreenX(view, (address.tileX + 1) * span))
+ const bottom = Math.round(worldToScreenZ(view, (address.tileZ + 1) * span))
+ context.drawImage(picture, sourceX, sourceZ, sourceSize, sourceSize, left, top, right - left, bottom - top)
+}
+
+/** Draws the part of a coarser tile that covers {@code address}; false when no coarser tile has arrived either. */
+function drawFallback(
+ context: CanvasRenderingContext2D,
+ view: Viewport,
+ tileSize: number,
+ address: TileAddress,
+ pictureOf: (address: TileAddress) => HTMLCanvasElement | null
+): boolean {
+ for (let levels = 1; levels <= COARSER_FALLBACK_LEVELS; levels++) {
+ const coarser = coarserTile(address, levels)
+ const picture = pictureOf(coarser)
+ if (picture === null) {
+ continue
+ }
+ const factor = 2 ** levels
+ const sourceSize = picture.width / factor
+ const sourceX = (address.tileX - coarser.tileX * factor) * sourceSize
+ const sourceZ = (address.tileZ - coarser.tileZ * factor) * sourceSize
+ drawTile(context, view, tileSize, picture, address, sourceX, sourceZ, sourceSize)
+ return true
+ }
+ return false
+}
diff --git a/studio/src/renderer/src/map/tileStyle.ts b/studio/src/renderer/src/map/tileStyle.ts
new file mode 100644
index 000000000..229f4a60a
--- /dev/null
+++ b/studio/src/renderer/src/map/tileStyle.ts
@@ -0,0 +1,193 @@
+import { gridIndex } from '../bridge/tileDecoding'
+import { NO_BLOCK, NO_LABEL, type MapTile, type PickDisplay, type TileBlocks } from '../bridge/types'
+import { WATER_SURFACE_COLOR } from '../scene/waterTint'
+import { blend } from './heightColors'
+
+const WATER_OVER_GROUND = 0.65
+
+/** What a highlight picks out: a biome or region by key, or a height band in the 3D world's legend. */
+export interface Highlight {
+ kind: 'BIOME' | 'REGION' | 'HEIGHT'
+ key: string
+ name: string
+}
+
+export interface TileStyle {
+ /** Colour by the block on top of each column instead of by label, where the tile carries its blocks. */
+ byBlock: boolean
+ shading: boolean
+ regionBorders: boolean
+ highlight: Highlight | null
+ seaLevel: number
+ /** How tiles that carry their pick noise draw it. */
+ pickDisplay: PickDisplay
+}
+
+export function styleKey(style: TileStyle): string {
+ const highlight = style.highlight === null ? '' : `${style.highlight.kind}:${style.highlight.key}`
+ return `${style.byBlock}|${style.shading}|${style.regionBorders}|${highlight}|${style.seaLevel}|${style.pickDisplay}`
+}
+
+const UNKNOWN_SUBJECT = 0x5a5c62
+const SHADING_EXAGGERATION = 2
+const LIGHT_X = -0.5
+const LIGHT_Y = 0.7
+const LIGHT_Z = -0.5
+const LIGHT_LENGTH = Math.sqrt(LIGHT_X * LIGHT_X + LIGHT_Y * LIGHT_Y + LIGHT_Z * LIGHT_Z)
+const AMBIENT_LIGHT = 0.35
+const DIRECT_LIGHT = 0.75
+const DARKEST_SHADE = 0.25
+const BRIGHTEST_SHADE = 1.15
+// Water lies flat over the seafloor, so only a hint of the relief beneath shows through.
+const UNDERWATER_RELIEF = 0.15
+const DIM_TARGET = 0x1e1f22
+const DIM_AMOUNT = 0.72
+const DIM_DESATURATION = 0.6
+const HIGHLIGHT_EDGE = 0xffffff
+// A solid outline turns biomes that are scattered pixel by pixel into white noise, so the edge only tints.
+const HIGHLIGHT_EDGE_STRENGTH = 0.55
+const REGION_BORDER = 0x101114
+const REGION_BORDER_STRENGTH = 0.6
+const NOISE_LOW = 0x050505
+const NOISE_HIGH = 0xffffff
+// Picks drawn by their noise keep some colour where the noise is low, so they still read as the pick.
+const DARKEST_PICK_SHADE = 0.3
+
+/** The tile's pixels as RGBA, as {@code style} draws them (v3e MapTile.styledPixels). */
+export function stylePixels(tile: MapTile, style: TileStyle): Uint8ClampedArray {
+ const { size } = tile
+ const pixels = new Uint8ClampedArray(size * size * 4)
+ const colors = tile.labels.map((label) => label.color)
+ const blocks = style.byBlock ? tile.blocks : null
+ const heights = blocks === null || tile.heights === null ? tile.heights : heightsSeenFromAbove(tile.heights, blocks)
+ const pickNoise = style.pickDisplay === 'picks' || blocks !== null ? null : tile.pickNoise
+ // The bare noise is read by its brightness, which relief shading would mix up.
+ const shading = style.shading && heights !== null && !(pickNoise !== null && style.pickDisplay === 'noise')
+ const highlighted = highlightCells(tile, style)
+ for (let pixelZ = 0; pixelZ < size; pixelZ++) {
+ for (let pixelX = 0; pixelX < size; pixelX++) {
+ const cell = gridIndex(tile, pixelX, pixelZ)
+ let color = blocks === null ? labelColor(colors, tile.subjects[cell]) : blockColor(blocks, cell, heights, style.seaLevel)
+ if (pickNoise !== null) {
+ color = byNoise(color, pickNoise[cell], style.pickDisplay)
+ }
+ if (shading) {
+ color = shade(tile, heights, cell, color, style.seaLevel)
+ }
+ if (highlighted !== null) {
+ color = highlight(tile, highlighted, cell, color)
+ }
+ if (style.regionBorders && isRegionEdge(tile, cell)) {
+ color = blend(color, REGION_BORDER, REGION_BORDER_STRENGTH)
+ }
+ const at = (pixelZ * size + pixelX) * 4
+ pixels[at] = (color >> 16) & 0xff
+ pixels[at + 1] = (color >> 8) & 0xff
+ pixels[at + 2] = color & 0xff
+ pixels[at + 3] = 0xff
+ }
+ }
+ return pixels
+}
+
+function labelColor(colors: number[], index: number): number {
+ return index === NO_LABEL ? UNKNOWN_SUBJECT : colors[index]
+}
+
+// Seen from above, the highest block raised over the ground hides it, and what stands on the ground hides the ground;
+// what lies under the sea shows through its water.
+function blockColor(blocks: TileBlocks, cell: number, heights: Float32Array | null, seaLevel: number): number {
+ const top = blockSeenFromAbove(blocks, cell)
+ const color = top === NO_BLOCK ? UNKNOWN_SUBJECT : blocks.colors[top]
+ return heights !== null && heights[cell] < seaLevel ? blend(color, WATER_SURFACE_COLOR, WATER_OVER_GROUND) : color
+}
+
+function blockSeenFromAbove(blocks: TileBlocks, cell: number): number {
+ const highestRaised = blocks.raisedStart[cell]
+ if (highestRaised < blocks.raisedStart[cell + 1]) {
+ return blocks.raised[highestRaised]
+ }
+ return blocks.cover[cell] === NO_BLOCK ? blocks.ground[cell] : blocks.cover[cell]
+}
+
+// The ground's heights with each column's highest raised block in place of its ground, so trees stand out in relief.
+function heightsSeenFromAbove(groundHeights: Float32Array, blocks: TileBlocks): Float32Array {
+ const heights = Float32Array.from(groundHeights)
+ for (let cell = 0; cell < heights.length; cell++) {
+ const highestRaised = blocks.raisedStart[cell]
+ if (highestRaised < blocks.raisedStart[cell + 1]) {
+ heights[cell] = blocks.raisedY[highestRaised]
+ }
+ }
+ return heights
+}
+
+// Where nothing picked the spot, as on an image map, it keeps its colour.
+function byNoise(color: number, noise: number, display: PickDisplay): number {
+ if (Number.isNaN(noise)) {
+ return color
+ }
+ const value = Math.min(1, Math.max(0, noise))
+ return display === 'noise' ? blend(NOISE_LOW, NOISE_HIGH, value) : scale(color, DARKEST_PICK_SHADE + (1 - DARKEST_PICK_SHADE) * value)
+}
+
+// Lit from the north west like a relief map, so slopes read as hills and valleys at a glance.
+function shade(tile: MapTile, heights: Float32Array, cell: number, color: number, seaLevel: number): number {
+ const row = tile.size + 2
+ const slopeX = (heights[cell + 1] - heights[cell - 1]) / (2 * tile.blocksPerPixel)
+ const slopeZ = (heights[cell + row] - heights[cell - row]) / (2 * tile.blocksPerPixel)
+ const normalX = -slopeX * SHADING_EXAGGERATION
+ const normalZ = -slopeZ * SHADING_EXAGGERATION
+ const normalLength = Math.sqrt(normalX * normalX + 1 + normalZ * normalZ)
+ const light = (normalX * LIGHT_X + LIGHT_Y + normalZ * LIGHT_Z) / (normalLength * LIGHT_LENGTH)
+ let factor = Math.min(BRIGHTEST_SHADE, Math.max(DARKEST_SHADE, AMBIENT_LIGHT + DIRECT_LIGHT * light))
+ if (heights[cell] <= seaLevel) {
+ factor = 1 - (1 - factor) * UNDERWATER_RELIEF
+ }
+ return scale(color, factor)
+}
+
+/** Which cells the highlight covers, as one flag per grid cell; null when nothing is highlighted. */
+function highlightCells(tile: MapTile, style: TileStyle): Uint8Array | null {
+ const target = style.highlight
+ if (target === null) {
+ return null
+ }
+ const cells = new Uint8Array(tile.subjects.length)
+ // Every view knows its regions, so a region can be highlighted in a biome view too.
+ const grid = target.kind === tile.subjectKind ? tile.subjects : target.kind === 'REGION' ? tile.regions : null
+ const index = tile.labels.findIndex((label) => label.kind === target.kind && label.key === target.key)
+ if (grid !== null && index >= 0) {
+ grid.forEach((label, cell) => {
+ cells[cell] = label === index ? 1 : 0
+ })
+ }
+ return cells
+}
+
+function highlight(tile: MapTile, highlighted: Uint8Array, cell: number, color: number): number {
+ if (highlighted[cell] === 0) {
+ return dim(color)
+ }
+ const row = tile.size + 2
+ const edge = highlighted[cell + 1] === 0 || highlighted[cell - 1] === 0 || highlighted[cell + row] === 0 || highlighted[cell - row] === 0
+ return edge ? blend(color, HIGHLIGHT_EDGE, HIGHLIGHT_EDGE_STRENGTH) : color
+}
+
+function isRegionEdge(tile: MapTile, cell: number): boolean {
+ const region = tile.regions[cell]
+ return tile.regions[cell + 1] !== region || tile.regions[cell + tile.size + 2] !== region
+}
+
+function dim(color: number): number {
+ const gray = Math.floor((((color >> 16) & 0xff) + ((color >> 8) & 0xff) + (color & 0xff)) / 3)
+ const desaturated = blend(color, (gray << 16) | (gray << 8) | gray, DIM_DESATURATION)
+ return blend(desaturated, DIM_TARGET, DIM_AMOUNT)
+}
+
+function scale(color: number, factor: number): number {
+ const red = Math.min(255, Math.floor(((color >> 16) & 0xff) * factor))
+ const green = Math.min(255, Math.floor(((color >> 8) & 0xff) * factor))
+ const blue = Math.min(255, Math.floor((color & 0xff) * factor))
+ return (red << 16) | (green << 8) | blue
+}
diff --git a/studio/src/renderer/src/map/viewport.ts b/studio/src/renderer/src/map/viewport.ts
new file mode 100644
index 000000000..c243ff9ac
--- /dev/null
+++ b/studio/src/renderer/src/map/viewport.ts
@@ -0,0 +1,97 @@
+/** Where the map looks and how far it is zoomed; screen sizes are CSS pixels. */
+export interface Viewport {
+ centerX: number
+ centerZ: number
+ blocksPerPixel: number
+ width: number
+ height: number
+}
+
+export interface TileAddress {
+ tileX: number
+ tileZ: number
+ blocksPerPixel: number
+}
+
+export const MINIMUM_VIEW_BLOCKS_PER_PIXEL = 1 / 8
+export const MAXIMUM_BLOCKS_PER_PIXEL = 4096
+export const DEFAULT_BLOCKS_PER_PIXEL = 4
+// Iris has nothing finer than a block, so closer views magnify the block-sized tiles.
+const MINIMUM_RENDER_BLOCKS_PER_PIXEL = 1
+
+export function clampBlocksPerPixel(blocksPerPixel: number): number {
+ return Math.min(MAXIMUM_BLOCKS_PER_PIXEL, Math.max(MINIMUM_VIEW_BLOCKS_PER_PIXEL, blocksPerPixel))
+}
+
+export function screenToWorldX(view: Viewport, screenX: number): number {
+ return view.centerX + (screenX - view.width / 2) * view.blocksPerPixel
+}
+
+export function screenToWorldZ(view: Viewport, screenZ: number): number {
+ return view.centerZ + (screenZ - view.height / 2) * view.blocksPerPixel
+}
+
+export function worldToScreenX(view: Viewport, worldX: number): number {
+ return (worldX - view.centerX) / view.blocksPerPixel + view.width / 2
+}
+
+export function worldToScreenZ(view: Viewport, worldZ: number): number {
+ return (worldZ - view.centerZ) / view.blocksPerPixel + view.height / 2
+}
+
+/**
+ * The scale tiles are drawn at for a view: the nearest power of two to one tile pixel per device pixel, so tiles stay
+ * sharp on dense screens and every zoom between two levels reuses the same tiles.
+ */
+export function renderBlocksPerPixel(
+ viewBlocksPerPixel: number,
+ devicePixelRatio: number,
+ finestBlocksPerPixel = MINIMUM_RENDER_BLOCKS_PER_PIXEL
+): number {
+ const level = 2 ** Math.round(Math.log2(viewBlocksPerPixel / devicePixelRatio))
+ return Math.min(MAXIMUM_BLOCKS_PER_PIXEL, Math.max(finestBlocksPerPixel, level))
+}
+
+/** The tiles covering the view, nearest the centre first so the middle of the screen fills in first. */
+export function visibleTiles(view: Viewport, renderScale: number, tileSize: number): TileAddress[] {
+ const span = tileSize * renderScale
+ const firstX = Math.floor(screenToWorldX(view, 0) / span)
+ const lastX = Math.floor(screenToWorldX(view, view.width) / span)
+ const firstZ = Math.floor(screenToWorldZ(view, 0) / span)
+ const lastZ = Math.floor(screenToWorldZ(view, view.height) / span)
+ const middleX = view.centerX / span - 0.5
+ const middleZ = view.centerZ / span - 0.5
+ const tiles: TileAddress[] = []
+ for (let tileZ = firstZ; tileZ <= lastZ; tileZ++) {
+ for (let tileX = firstX; tileX <= lastX; tileX++) {
+ tiles.push({ tileX, tileZ, blocksPerPixel: renderScale })
+ }
+ }
+ const distance = (tile: TileAddress): number => (tile.tileX - middleX) ** 2 + (tile.tileZ - middleZ) ** 2
+ return tiles.sort((first, second) => distance(first) - distance(second))
+}
+
+/**
+ * One tile a level out for each group of blank tiles, in their order: a quarter of the pixels, so the screen fills
+ * about four times sooner and sharpens as the tiles themselves arrive.
+ */
+export function previewsFor(blankTiles: TileAddress[]): TileAddress[] {
+ const previews = new Map()
+ for (const tile of blankTiles) {
+ const preview = coarserTile(tile, 1)
+ if (preview.blocksPerPixel <= MAXIMUM_BLOCKS_PER_PIXEL) {
+ previews.set(`${preview.tileX}/${preview.tileZ}/${preview.blocksPerPixel}`, preview)
+ }
+ }
+ return [...previews.values()]
+}
+
+/** The coarser tile that covers {@code tile}, {@code levels} zoom levels out. */
+export function coarserTile(tile: TileAddress, levels: number): TileAddress {
+ const factor = 2 ** levels
+ return {
+ tileX: Math.floor(tile.tileX / factor),
+ tileZ: Math.floor(tile.tileZ / factor),
+ blocksPerPixel: tile.blocksPerPixel * factor
+ }
+}
diff --git a/studio/src/renderer/src/noise/noise.test.ts b/studio/src/renderer/src/noise/noise.test.ts
new file mode 100644
index 000000000..f86197394
--- /dev/null
+++ b/studio/src/renderer/src/noise/noise.test.ts
@@ -0,0 +1,60 @@
+import { describe, expect, it } from 'vitest'
+import type { NoiseSource } from '../bridge/types'
+import { heightColor } from '../map/heightColors'
+import { INVALID_NOISE_COLOR, noiseScale } from './noiseScale'
+import { NoiseTerrain } from './noiseTerrain'
+
+const UNIT_NOISE: NoiseSource = { id: 'style:SIMPLEX', name: 'Simplex', category: 'Simplex', usesSeed: true, blockRange: null }
+const BLOCK_NOISE: NoiseSource = { id: 'world:overlay', name: 'Overlay noise', category: 'Pack generators', usesSeed: false, blockRange: { lowest: -20, highest: 40 } }
+
+describe('noise scale', () => {
+ it('spans the palette for noise of 0 to 1 and takes its end colours past it', () => {
+ const terrain = noiseScale('terrain', UNIT_NOISE)
+ expect([terrain.minimum, terrain.maximum]).toEqual([0, 1])
+ expect(terrain.colorOf(0)).toBe(0x071a2f)
+ expect(terrain.colorOf(1)).toBe(0xf4f1de)
+ expect(terrain.colorOf(7)).toBe(0xf4f1de)
+ expect(noiseScale('signed', UNIT_NOISE).minimum).toBe(-1)
+ })
+
+ it('spans the block range for noise in blocks, coloured as heights above the fluid', () => {
+ const height = noiseScale('height', BLOCK_NOISE)
+ expect([height.minimum, height.maximum]).toEqual([-20, 40])
+ expect(height.colorOf(-20)).toBe(heightColor(-20, 0))
+ expect(height.colorOf(40)).toBe(heightColor(40, 0))
+ })
+
+ it('marks a value the noise could not give', () => {
+ expect(noiseScale('grayscale', UNIT_NOISE).colorOf(Number.NaN)).toBe(INVALID_NOISE_COLOR)
+ })
+})
+
+describe('noise terrain', () => {
+ const tile = (values: number[]) => ({ size: 2, values: Float32Array.from(values) })
+ const place = { level: 1, tileX: 1, tileZ: -2 }
+
+ it('raises noise of 0 to 1 to the relief, without water', () => {
+ const terrain = new NoiseTerrain(tile([0, 0.5, 1, Number.NaN]), place, UNIT_NOISE, noiseScale('terrain', UNIT_NOISE), 64)
+ expect([terrain.groundAt(0, 0), terrain.groundAt(1, 0), terrain.groundAt(0, 1), terrain.groundAt(1, 1)]).toEqual([0, 32, 64, null])
+ expect(terrain.waterAt(0, 0)).toBeNull()
+ })
+
+ it('places its columns where the tile lies, as wide as its level', () => {
+ const terrain = new NoiseTerrain(tile([0, 0, 0, 0]), place, UNIT_NOISE, noiseScale('terrain', UNIT_NOISE), 64)
+ expect([terrain.originX, terrain.originZ, terrain.blocksPerColumn]).toEqual([256, -512, 2])
+ })
+
+ it('stands noise in blocks at its own height, under water below the fluid', () => {
+ const terrain = new NoiseTerrain(tile([-5, 12, 0, 3]), place, BLOCK_NOISE, noiseScale('height', BLOCK_NOISE), 64)
+ expect(terrain.groundAt(0, 0)).toBe(-5)
+ expect(terrain.waterAt(0, 0)).toBe(0)
+ expect(terrain.waterAt(1, 0)).toBeNull()
+ })
+
+ it('fills each column up to the block its noise reaches into', () => {
+ const terrain = new NoiseTerrain(tile([-0.5, 12.9, 0.4, 3]), place, BLOCK_NOISE, noiseScale('height', BLOCK_NOISE), 64)
+ expect([terrain.groundAt(0, 0), terrain.groundAt(1, 0), terrain.groundAt(0, 1)]).toEqual([-1, 12, 0])
+ expect(terrain.waterAt(0, 0)).toBe(0)
+ expect(terrain.waterAt(0, 1)).toBeNull()
+ })
+})
diff --git a/studio/src/renderer/src/noise/noiseScale.ts b/studio/src/renderer/src/noise/noiseScale.ts
new file mode 100644
index 000000000..4c5026bef
--- /dev/null
+++ b/studio/src/renderer/src/noise/noiseScale.ts
@@ -0,0 +1,81 @@
+import type { NoiseSource } from '../bridge/types'
+import { DEEPEST_BELOW_SEA_BLOCKS, heightColor, HIGHEST_ABOVE_SEA_BLOCKS } from '../map/heightColors'
+
+export type NoisePaletteId = 'terrain' | 'signed' | 'grayscale' | 'height' | 'green'
+
+interface NoisePalette {
+ id: NoisePaletteId
+ label: string
+ minimum: number
+ maximum: number
+ /** Colours from the minimum to the maximum, evenly spaced; null for the map's height colours. */
+ stops: number[] | null
+}
+
+/** v3e's noise palettes, each with the values it spans when the noise is not measured in blocks. */
+export const NOISE_PALETTES: readonly NoisePalette[] = [
+ { id: 'terrain', label: 'Terrain', minimum: 0, maximum: 1, stops: [0x071a2f, 0x155e75, 0x2a9d8f, 0xe9c46a, 0xf4f1de] },
+ { id: 'signed', label: 'Signed', minimum: -1, maximum: 1, stops: [0x173b66, 0x4f86c6, 0xe7edf3, 0xe89555, 0x9d3b35] },
+ { id: 'grayscale', label: 'Grayscale', minimum: 0, maximum: 1, stops: [0x050505, 0xffffff] },
+ { id: 'height', label: 'Height', minimum: 0, maximum: 1, stops: null },
+ { id: 'green', label: 'Green', minimum: 0, maximum: 1, stops: [0x2a3330, 0x5fd3a8] }
+]
+
+/** The colour of a value the noise couldn't give, so it stands out from every palette. */
+export const INVALID_NOISE_COLOR = 0xff2daa
+const LOOKUP_SIZE = 256
+
+/** How values become colours: the span the palette covers, and the colour of a value. */
+export interface NoiseScale {
+ minimum: number
+ maximum: number
+ /** Over and under the span take the end colours. */
+ colorOf(value: number): number
+ /** The colour a fraction of the way along the span, for the legend. */
+ colorAlong(fraction: number): number
+}
+
+/**
+ * The scale for a palette and a source: noise of 0 to 1 spans the palette's own range; noise in blocks spans its block
+ * range, and the height palette then colours it as the map colours heights above the fluid.
+ */
+export function noiseScale(paletteId: NoisePaletteId, source: NoiseSource | null): NoiseScale {
+ const palette = NOISE_PALETTES.find((candidate) => candidate.id === paletteId)!
+ const blocks = source?.blockRange ?? null
+ const minimum = blocks?.lowest ?? palette.minimum
+ const maximum = blocks?.highest ?? palette.maximum
+ const colorAlong = paletteColors(palette, blocks === null ? null : [blocks.lowest, blocks.highest])
+ const span = maximum - minimum
+ return {
+ minimum,
+ maximum,
+ colorAlong,
+ colorOf: (value) => (Number.isFinite(value) ? colorAlong(span <= 0 ? 0.5 : (value - minimum) / span) : INVALID_NOISE_COLOR)
+ }
+}
+
+function paletteColors(palette: NoisePalette, blockSpan: [number, number] | null): (fraction: number) => number {
+ if (palette.stops === null) {
+ const [lowest, highest] = blockSpan ?? [-DEEPEST_BELOW_SEA_BLOCKS, HIGHEST_ABOVE_SEA_BLOCKS]
+ return (fraction) => heightColor(lowest + (highest - lowest) * clampUnit(fraction), 0)
+ }
+ const lookup = lookupOf(palette.stops)
+ return (fraction) => lookup[Math.round(clampUnit(fraction) * (LOOKUP_SIZE - 1))]
+}
+
+function lookupOf(stops: number[]): number[] {
+ return Array.from({ length: LOOKUP_SIZE }, (_, index) => {
+ const position = (index / (LOOKUP_SIZE - 1)) * (stops.length - 1)
+ const lower = Math.min(stops.length - 2, Math.floor(position))
+ return mix(stops[lower], stops[lower + 1], position - lower)
+ })
+}
+
+function mix(from: number, to: number, fraction: number): number {
+ const channel = (shift: number): number => Math.round(((from >>> shift) & 0xff) + (((to >>> shift) & 0xff) - ((from >>> shift) & 0xff)) * fraction)
+ return (channel(16) << 16) | (channel(8) << 8) | channel(0)
+}
+
+function clampUnit(fraction: number): number {
+ return Math.min(1, Math.max(0, fraction))
+}
diff --git a/studio/src/renderer/src/noise/noiseTerrain.ts b/studio/src/renderer/src/noise/noiseTerrain.ts
new file mode 100644
index 000000000..b4d969c5f
--- /dev/null
+++ b/studio/src/renderer/src/noise/noiseTerrain.ts
@@ -0,0 +1,62 @@
+import type { NoiseSource, NoiseTile } from '../bridge/types'
+import type { TerrainSurface } from '../scene/terrainMesh'
+import { blocksPerColumn, originXOf, originZOf, type TerrainTile } from '../scene/terrainTiles'
+import type { NoiseScale } from './noiseScale'
+
+// The fluid of noise measured in blocks lies at its zero, as the world adds the overlay above its fluid height.
+const FLUID_BLOCKS = 0
+
+/**
+ * One tile of noise as terrain (v3e's 3D noise): noise measured in blocks stands at its own height with water at the
+ * fluid; other noise rises from its scale's minimum to {@code reliefBlocks} at its maximum, with no water.
+ */
+export class NoiseTerrain implements TerrainSurface {
+ readonly columns: number
+ readonly rows: number
+ readonly originX: number
+ readonly originZ: number
+ readonly blocksPerColumn: number
+
+ constructor(
+ private readonly tile: NoiseTile,
+ place: TerrainTile,
+ private readonly source: NoiseSource,
+ private readonly scale: NoiseScale,
+ private readonly reliefBlocks: number
+ ) {
+ this.columns = tile.size
+ this.rows = tile.size
+ this.originX = originXOf(place)
+ this.originZ = originZOf(place)
+ this.blocksPerColumn = blocksPerColumn(place.level)
+ }
+
+ groundAt(column: number, row: number): number | null {
+ const value = this.valueAt(column, row)
+ return Number.isFinite(value) ? Math.floor(this.heightOf(value)) : null
+ }
+
+ waterAt(column: number, row: number): number | null {
+ if (this.source.blockRange === null) {
+ return null
+ }
+ const ground = this.groundAt(column, row)
+ return ground !== null && ground < FLUID_BLOCKS ? FLUID_BLOCKS : null
+ }
+
+ colorAt(column: number, row: number): number {
+ return this.scale.colorOf(this.valueAt(column, row))
+ }
+
+ private heightOf(value: number): number {
+ if (this.source.blockRange !== null) {
+ return value
+ }
+ const span = this.scale.maximum - this.scale.minimum
+ return ((value - this.scale.minimum) / span) * this.reliefBlocks
+ }
+
+ private valueAt(column: number, row: number): number {
+ return this.tile.values[row * this.tile.size + column]
+ }
+}
diff --git a/studio/src/renderer/src/noise/noiseTiles.ts b/studio/src/renderer/src/noise/noiseTiles.ts
new file mode 100644
index 000000000..9465a0106
--- /dev/null
+++ b/studio/src/renderer/src/noise/noiseTiles.ts
@@ -0,0 +1,77 @@
+import type { BridgeClient } from '../bridge/BridgeClient'
+import type { NoiseTile } from '../bridge/types'
+import { TiledView, type TiledFrame } from '../map/TiledView'
+import type { TileSource } from '../map/TileStore'
+import type { NoiseScale } from './noiseScale'
+
+/** Which noise the tiles hold. */
+export interface NoiseLayer {
+ sourceId: string
+ /** A 64 bit seed, as text so no digit is lost. */
+ seed: string
+ /** Bumped when the pack is hotloaded, so older tiles are not used again. */
+ revision: number
+}
+
+export interface NoiseStyle {
+ /** Tells styles apart, so a tile is recoloured only when its style changed. */
+ key: string
+ scale: NoiseScale
+}
+
+export type NoiseView = TiledView
+
+export interface NoiseStatus extends TiledFrame {
+ /** The noise at the cursor, or null before its tile arrived. */
+ value: number | null
+}
+
+export interface NoiseListener {
+ onStatus(status: NoiseStatus): void
+ onError(message: string): void
+}
+
+export const NOISE_TILE_PIXELS = 128
+const DEFAULT_NOISE_BLOCKS_PER_PIXEL = 1
+// Noise has detail finer than a block, so it is drawn finer than the world map's one block per pixel.
+const FINEST_NOISE_BLOCKS_PER_PIXEL = 1 / 16
+
+export function createNoiseView(canvas: HTMLCanvasElement, client: BridgeClient, listener: NoiseListener): NoiseView {
+ const view: NoiseView = new TiledView(canvas, {
+ source: noiseTileSource(client),
+ tileSize: NOISE_TILE_PIXELS,
+ defaultBlocksPerPixel: DEFAULT_NOISE_BLOCKS_PER_PIXEL,
+ finestRenderBlocksPerPixel: FINEST_NOISE_BLOCKS_PER_PIXEL,
+ onFrame: (frame) => listener.onStatus({ ...frame, value: valueAt(view, frame.cursorX, frame.cursorZ) }),
+ onError: (message) => listener.onError(message)
+ })
+ return view
+}
+
+function valueAt(view: NoiseView, worldX: number, worldZ: number): number | null {
+ const spot = view.spotAt(worldX, worldZ)
+ return spot === null ? null : spot.tile.values[spot.pixelZ * spot.tile.size + spot.pixelX]
+}
+
+export function noiseTileSource(client: BridgeClient): TileSource {
+ return {
+ layerKey: (layer) => `${layer.revision}/${layer.sourceId}/${layer.seed}`,
+ fetch: (address, layer, signal) =>
+ client.noiseTile(layer.sourceId, layer.seed, address.tileX, address.tileZ, address.blocksPerPixel, NOISE_TILE_PIXELS, signal),
+ bytesOf: (tile) => tile.values.byteLength + tile.size * tile.size * 4,
+ styleKey: (style) => style.key,
+ pixels: (tile, style) => noisePixels(tile, style.scale)
+ }
+}
+
+function noisePixels(tile: NoiseTile, scale: NoiseScale): ImageData {
+ const pixels = new ImageData(tile.size, tile.size)
+ for (let index = 0; index < tile.values.length; index++) {
+ const color = scale.colorOf(tile.values[index])
+ pixels.data[index * 4] = (color >> 16) & 0xff
+ pixels.data[index * 4 + 1] = (color >> 8) & 0xff
+ pixels.data[index * 4 + 2] = color & 0xff
+ pixels.data[index * 4 + 3] = 0xff
+ }
+ return pixels
+}
diff --git a/studio/src/renderer/src/pattern/patternTiles.ts b/studio/src/renderer/src/pattern/patternTiles.ts
new file mode 100644
index 000000000..896a603aa
--- /dev/null
+++ b/studio/src/renderer/src/pattern/patternTiles.ts
@@ -0,0 +1,152 @@
+import type { BridgeClient } from '../bridge/BridgeClient'
+import { NO_PATTERN_BLOCK, type PatternTile } from '../bridge/types'
+import { TiledView, type TiledFrame } from '../map/TiledView'
+import type { TileSource } from '../map/TileStore'
+import type { TileAddress } from '../map/viewport'
+import type { BlockColors } from '../scene/blockColors'
+
+/** Which entry, at which depth, the tiles lay out. */
+export interface PatternLayer {
+ viewId: string
+ key: string
+ depth: number
+ /** Bumped when the pack is hotloaded, so older tiles are not used again. */
+ revision: number
+}
+
+/** A pattern tile with what it needs to be drawn: each block's colour, and its texture once a block spans pixels. */
+export interface PatternPicture {
+ pattern: PatternTile
+ colors: number[]
+ /** Per block, its top texture; empty while a block is a pixel or smaller. */
+ textures: (ImageData | null)[]
+ /** How many pixels across a column is drawn; 1 when it is a pixel or smaller. */
+ pixelsPerColumn: number
+}
+
+/** Patterns have one look; the style only satisfies the tile store. */
+export type PatternStyle = 'blocks'
+export type PatternView = TiledView
+
+/** What is under the cursor: a block, nothing placed there, or not known before its tile arrived. */
+export type PatternSpot = { kind: 'block'; block: string } | { kind: 'none' } | { kind: 'unknown' }
+
+export interface PatternStatus extends TiledFrame {
+ spot: PatternSpot
+}
+
+/** The blocks a tile placed, each with the state it is drawn as, and whether it left some columns without a block. */
+export interface PatternBlocks {
+ drawnAs: Map
+ someNone: boolean
+}
+
+export interface PatternListener {
+ onStatus(status: PatternStatus): void
+ /** What a tile of the layer showed, for the legend. */
+ onBlocks(layer: PatternLayer, blocks: PatternBlocks): void
+ onError(message: string): void
+}
+
+export const PATTERN_TILE_PIXELS = 128
+const DEFAULT_PATTERN_BLOCKS_PER_PIXEL = 1
+// A block texture is 16 pixels across; drawing a block that wide shows it whole.
+const FINEST_PATTERN_BLOCKS_PER_PIXEL = 1 / 16
+// The bridge lays out a column at most every 64 blocks; views stop a level short so their previews stay within it.
+const COARSEST_PATTERN_BLOCKS_PER_PIXEL = 32
+const NO_COLOR = 0x000000
+const OPAQUE = 0xff
+const OPAQUE_ENOUGH_ALPHA = 128
+
+export function createPatternView(canvas: HTMLCanvasElement, client: BridgeClient, blockColors: BlockColors, listener: PatternListener): PatternView {
+ const view: PatternView = new TiledView(canvas, {
+ source: patternTileSource(client, blockColors, listener),
+ tileSize: PATTERN_TILE_PIXELS,
+ defaultBlocksPerPixel: DEFAULT_PATTERN_BLOCKS_PER_PIXEL,
+ finestRenderBlocksPerPixel: FINEST_PATTERN_BLOCKS_PER_PIXEL,
+ coarsestBlocksPerPixel: COARSEST_PATTERN_BLOCKS_PER_PIXEL,
+ onFrame: (frame) => listener.onStatus({ ...frame, spot: spotAt(view, frame.cursorX, frame.cursorZ) }),
+ onError: (message) => listener.onError(message)
+ })
+ return view
+}
+
+function spotAt(view: PatternView, worldX: number, worldZ: number): PatternSpot {
+ const spot = view.spotAt(worldX, worldZ)
+ if (spot === null) {
+ return { kind: 'unknown' }
+ }
+ const { pattern, pixelsPerColumn } = spot.tile
+ const column = Math.floor(spot.pixelX / pixelsPerColumn)
+ const row = Math.floor(spot.pixelZ / pixelsPerColumn)
+ const pick = pattern.picks[row * pattern.columns + column]
+ return pick === NO_PATTERN_BLOCK ? { kind: 'none' } : { kind: 'block', block: pattern.blocks[pick] }
+}
+
+function patternTileSource(client: BridgeClient, blockColors: BlockColors, listener: PatternListener): TileSource {
+ return {
+ layerKey: (layer) => `${layer.revision}/${layer.viewId}/${layer.key}/${layer.depth}`,
+ fetch: async (address, layer, signal) => {
+ const picture = await fetchPicture(client, blockColors, address, layer, signal)
+ listener.onBlocks(layer, {
+ drawnAs: new Map(picture.pattern.blocks.map((block, index) => [block, picture.pattern.drawnAs[index]])),
+ someNone: picture.pattern.picks.includes(NO_PATTERN_BLOCK)
+ })
+ return picture
+ },
+ bytesOf: (picture) => picture.pattern.picks.byteLength + PATTERN_TILE_PIXELS * PATTERN_TILE_PIXELS * 4,
+ styleKey: (style) => style,
+ pixels: (picture) => patternPixels(picture)
+ }
+}
+
+/**
+ * A tile a pixel per column where a column is a pixel or more, and otherwise a column per block, each drawn a few
+ * pixels wide in its texture.
+ */
+async function fetchPicture(client: BridgeClient, blockColors: BlockColors, address: TileAddress, layer: PatternLayer, signal: AbortSignal): Promise {
+ const blocksPerColumn = Math.max(1, address.blocksPerPixel)
+ const pixelsPerColumn = Math.round(blocksPerColumn / address.blocksPerPixel)
+ const columns = PATTERN_TILE_PIXELS / pixelsPerColumn
+ const pattern = await client.pattern({ ...layer, tileX: address.tileX, tileZ: address.tileZ, blocksPerColumn, columns }, signal)
+ const colors = await Promise.all(pattern.drawnAs.map((block) => blockColors.colorOf(block)))
+ const textures = pixelsPerColumn > 1 ? await Promise.all(pattern.drawnAs.map((block) => blockColors.topTexture(block))) : []
+ return { pattern, colors, textures, pixelsPerColumn }
+}
+
+function patternPixels(picture: PatternPicture): ImageData {
+ const pixels = new ImageData(PATTERN_TILE_PIXELS, PATTERN_TILE_PIXELS)
+ const { pattern, pixelsPerColumn } = picture
+ for (let pixelZ = 0; pixelZ < PATTERN_TILE_PIXELS; pixelZ++) {
+ for (let pixelX = 0; pixelX < PATTERN_TILE_PIXELS; pixelX++) {
+ const pick = pattern.picks[Math.floor(pixelZ / pixelsPerColumn) * pattern.columns + Math.floor(pixelX / pixelsPerColumn)]
+ if (pick !== NO_PATTERN_BLOCK) {
+ writePixel(pixels, (pixelZ * PATTERN_TILE_PIXELS + pixelX) * 4, picture, pick, pixelX % pixelsPerColumn, pixelZ % pixelsPerColumn)
+ }
+ }
+ }
+ return pixels
+}
+
+/**
+ * The block's texture at a spot within its column, and its colour where it has no texture or the texture is see
+ * through, such as between leaves, so a palette reads as solid ground.
+ */
+function writePixel(pixels: ImageData, offset: number, picture: PatternPicture, pick: number, insideX: number, insideZ: number): void {
+ const texture = picture.textures[pick] ?? null
+ if (texture !== null) {
+ const textureX = Math.floor((insideX * texture.width) / picture.pixelsPerColumn)
+ const textureZ = Math.floor((insideZ * texture.height) / picture.pixelsPerColumn)
+ const from = (textureZ * texture.width + textureX) * 4
+ if (texture.data[from + 3] >= OPAQUE_ENOUGH_ALPHA) {
+ pixels.data.set(texture.data.subarray(from, from + 3), offset)
+ pixels.data[offset + 3] = OPAQUE
+ return
+ }
+ }
+ const color = picture.colors[pick] ?? NO_COLOR
+ pixels.data[offset] = (color >> 16) & 0xff
+ pixels.data[offset + 1] = (color >> 8) & 0xff
+ pixels.data[offset + 2] = color & 0xff
+ pixels.data[offset + 3] = OPAQUE
+}
diff --git a/studio/src/renderer/src/scene/BridgeAssets.ts b/studio/src/renderer/src/scene/BridgeAssets.ts
new file mode 100644
index 000000000..e6fc40d6d
--- /dev/null
+++ b/studio/src/renderer/src/scene/BridgeAssets.ts
@@ -0,0 +1,44 @@
+import { BridgeError, STATUS_UNAVAILABLE, type BridgeClient } from '../bridge/BridgeClient'
+import type { AssetSource } from './blockModels'
+import type { ImageSource } from './textureAtlas'
+
+const RETRY_MILLIS = 2000
+const LONGEST_WAIT_MILLIS = 10 * 60 * 1000
+
+/**
+ * The Minecraft client's assets through the bridge. The server fetches the client the first time anyone asks, so
+ * until it has it every request waits, telling {@code onWaiting} why.
+ */
+export class BridgeAssets implements AssetSource, ImageSource {
+ constructor(
+ private readonly client: BridgeClient,
+ private readonly onWaiting: (reason: string | null) => void
+ ) {}
+
+ async json(path: string): Promise {
+ const response = await this.fetch(path)
+ return response === null ? null : response.json()
+ }
+
+ async image(path: string): Promise {
+ const response = await this.fetch(path)
+ return response === null ? null : createImageBitmap(await response.blob())
+ }
+
+ private async fetch(path: string): Promise {
+ const giveUpAt = Date.now() + LONGEST_WAIT_MILLIS
+ for (;;) {
+ try {
+ const response = await this.client.asset(path)
+ this.onWaiting(null)
+ return response
+ } catch (error) {
+ if (!(error instanceof BridgeError) || error.status !== STATUS_UNAVAILABLE || Date.now() > giveUpAt) {
+ throw error
+ }
+ this.onWaiting(error.message)
+ await new Promise((resume) => window.setTimeout(resume, RETRY_MILLIS))
+ }
+ }
+ }
+}
diff --git a/studio/src/renderer/src/scene/bakeTiming.test.ts b/studio/src/renderer/src/scene/bakeTiming.test.ts
new file mode 100644
index 000000000..7c1e4c283
--- /dev/null
+++ b/studio/src/renderer/src/scene/bakeTiming.test.ts
@@ -0,0 +1,81 @@
+import { describe, expect, it } from 'vitest'
+import type { BakeRun } from '../bridge/types'
+import { BAKE_RUN_COUNT, bakeWeightOf, formatMillis, measureBake, medianRun, meterFill, runMillis, slowestStageIndex } from './bakeTiming'
+
+const NANOS_PER_MILLI = 1_000_000
+
+function runOf(...stageMillis: number[]): BakeRun {
+ return { variantCount: 4, stages: stageMillis.map((millis, index) => ({ label: `Stage ${index}`, nanos: millis * NANOS_PER_MILLI })) }
+}
+
+describe('bake timing', () => {
+ it('adds the stages of a run up to its time in milliseconds', () => {
+ expect(runMillis(runOf(2, 3, 5))).toBe(10)
+ })
+
+ it('keeps the run in the middle by time, not the fastest, the slowest or the first', () => {
+ const slowFirstRun = runOf(900)
+ const median = runOf(40)
+ const runs = [slowFirstRun, runOf(10), runOf(300), median, runOf(25)]
+ expect(medianRun(runs)).toBe(median)
+ expect(runs[0]).toBe(slowFirstRun)
+ })
+
+ it('times five runs one after the other and keeps the median', async () => {
+ const times = [90, 10, 50, 30, 70]
+ let asked = 0
+ const median = await measureBake(async () => runOf(times[asked++]), () => true)
+ expect(asked).toBe(BAKE_RUN_COUNT)
+ expect(median === null ? null : runMillis(median)).toBe(50)
+ })
+
+ it('stops asking once another entry is opened', async () => {
+ let asked = 0
+ const median = await measureBake(
+ async () => runOf(asked++),
+ () => asked < 2
+ )
+ expect(median).toBeNull()
+ expect(asked).toBe(2)
+ })
+
+ it('drops the result of runs that finished after the entry was left', async () => {
+ let wanted = true
+ const median = await measureBake(
+ async () => {
+ wanted = false
+ return runOf(1)
+ },
+ () => wanted
+ )
+ expect(median).toBeNull()
+ })
+
+ it('rates a bake against a server tick of 50 ms', () => {
+ expect(bakeWeightOf(0.4).label).toBe('Light')
+ expect(bakeWeightOf(49.9).label).toBe('Light')
+ expect(bakeWeightOf(50).label).toBe('Moderate')
+ expect(bakeWeightOf(500).label).toBe('Heavy')
+ expect(bakeWeightOf(60_000).label).toBe('Heavy')
+ })
+
+ it('fills the meter on a logarithmic scale, a third for each weight', () => {
+ expect(meterFill(0)).toBe(0)
+ expect(meterFill(50)).toBeCloseTo(1 / 3)
+ expect(meterFill(500)).toBeCloseTo(2 / 3)
+ expect(meterFill(5000)).toBeCloseTo(1)
+ expect(meterFill(1_000_000)).toBeCloseTo(1)
+ expect(meterFill(Math.sqrt(50))).toBeCloseTo(1 / 6)
+ })
+
+ it('formats times with the digits they need', () => {
+ expect(formatMillis(2.34)).toBe('2.3 ms')
+ expect(formatMillis(48.6)).toBe('49 ms')
+ expect(formatMillis(1250)).toBe('1.3 s')
+ })
+
+ it('points at the slowest stage, the first when none took time', () => {
+ expect(slowestStageIndex(runOf(1, 9, 4))).toBe(1)
+ expect(slowestStageIndex(runOf(0, 0))).toBe(0)
+ })
+})
diff --git a/studio/src/renderer/src/scene/bakeTiming.ts b/studio/src/renderer/src/scene/bakeTiming.ts
new file mode 100644
index 000000000..0c38f7ade
--- /dev/null
+++ b/studio/src/renderer/src/scene/bakeTiming.ts
@@ -0,0 +1,87 @@
+import type { BakeRun } from '../bridge/types'
+
+const NANOS_PER_MILLI = 1_000_000
+const SECOND_IN_MILLIS = 1000
+const FINE_MILLIS_DIGITS_BELOW = 10
+
+/** How many times a bake is timed; the run in the middle is the one shown. */
+export const BAKE_RUN_COUNT = 5
+
+/** How long a bake stalls the chunk that first places it, against a server tick of 50 ms (v3 BakeWeight). */
+export interface BakeWeight {
+ label: string
+ /** Where the weight starts, in milliseconds. */
+ fromMillis: number
+ /** Where the meter is full within the weight, in milliseconds. */
+ meterFullAtMillis: number
+ /** The text colour class of the weight. */
+ textClass: string
+ /** The fill colour class of the weight. */
+ fillClass: string
+}
+
+export const BAKE_WEIGHTS: readonly BakeWeight[] = [
+ { label: 'Light', fromMillis: 1, meterFullAtMillis: 50, textClass: 'text-success', fillClass: 'bg-success' },
+ { label: 'Moderate', fromMillis: 50, meterFullAtMillis: 500, textClass: 'text-warning', fillClass: 'bg-warning' },
+ { label: 'Heavy', fromMillis: 500, meterFullAtMillis: 5000, textClass: 'text-destructive', fillClass: 'bg-destructive' }
+]
+
+export function bakeWeightIndex(millis: number): number {
+ const index = BAKE_WEIGHTS.findIndex((weight) => millis < weight.meterFullAtMillis)
+ return index < 0 ? BAKE_WEIGHTS.length - 1 : index
+}
+
+export function bakeWeightOf(millis: number): BakeWeight {
+ return BAKE_WEIGHTS[bakeWeightIndex(millis)]
+}
+
+/** How full the meter is, from 0 to 1: each weight takes an equal share, filled on a logarithmic scale since bakes span thousands of times. */
+export function meterFill(millis: number): number {
+ const index = bakeWeightIndex(millis)
+ const weight = BAKE_WEIGHTS[index]
+ const clamped = Math.min(Math.max(millis, weight.fromMillis), weight.meterFullAtMillis)
+ const withinWeight = Math.log(clamped / weight.fromMillis) / Math.log(weight.meterFullAtMillis / weight.fromMillis)
+ return (index + withinWeight) / BAKE_WEIGHTS.length
+}
+
+export function runMillis(run: BakeRun): number {
+ return run.stages.reduce((total, stage) => total + stage.nanos, 0) / NANOS_PER_MILLI
+}
+
+/** The run in the middle by total time. The first run is slow while the JIT compiles the baker, and the garbage collector or chunk generation can slow any other, so neither ends up in the middle. */
+export function medianRun(runs: readonly BakeRun[]): BakeRun {
+ const byTime = [...runs].sort((first, second) => runMillis(first) - runMillis(second))
+ return byTime[Math.floor(byTime.length / 2)]
+}
+
+/**
+ * Times a bake {@link BAKE_RUN_COUNT} times, one run after the other, and keeps the median; null once {@code stillWanted}
+ * says another entry was opened.
+ */
+export async function measureBake(bakeOnce: () => Promise, stillWanted: () => boolean): Promise {
+ const runs: BakeRun[] = []
+ while (runs.length < BAKE_RUN_COUNT) {
+ if (!stillWanted()) {
+ return null
+ }
+ runs.push(await bakeOnce())
+ }
+ return stillWanted() ? medianRun(runs) : null
+}
+
+export function formatMillis(millis: number): string {
+ if (millis >= SECOND_IN_MILLIS) {
+ return `${(millis / SECOND_IN_MILLIS).toFixed(1)} s`
+ }
+ return `${millis.toFixed(millis < FINE_MILLIS_DIGITS_BELOW ? 1 : 0)} ms`
+}
+
+/** Where light turns to heavy, as the tooltip tells it. */
+export function weightScale(): string {
+ return `Light under ${formatMillis(BAKE_WEIGHTS[1].fromMillis)}, heavy from ${formatMillis(BAKE_WEIGHTS[2].fromMillis)}`
+}
+
+/** The index of the stage that took longest; the first when none took any time. */
+export function slowestStageIndex(run: BakeRun): number {
+ return run.stages.reduce((slowest, stage, index) => (stage.nanos > run.stages[slowest].nanos ? index : slowest), 0)
+}
diff --git a/studio/src/renderer/src/scene/blockArt.ts b/studio/src/renderer/src/scene/blockArt.ts
new file mode 100644
index 000000000..f9b2948dd
--- /dev/null
+++ b/studio/src/renderer/src/scene/blockArt.ts
@@ -0,0 +1,57 @@
+import type { BridgeClient } from '../bridge/BridgeClient'
+import { NO_BLOCK, type TileBlocks } from '../bridge/types'
+import { BlockColors } from './blockColors'
+import { BlockLooks } from './blockLooks'
+import { BlockModels } from './blockModels'
+import { BridgeAssets } from './BridgeAssets'
+import { TerrainAtlas } from './terrainAtlas'
+
+/** What a tile's blocks are drawn with: each block's colour from above, and its textures where columns show them. */
+export interface BlockArt {
+ /** The atlas the looks' pictures lie in; null for art that only colours. */
+ readonly atlas: TerrainAtlas | null
+ /** Fills in the colours of the tile's blocks, and their looks when {@code textured}. */
+ paint(blocks: TileBlocks, textured: boolean): Promise
+ dispose(): void
+}
+
+// Only these have their whole model's pictures placed, so the ground's blocks take no room in the atlas for faces a column never shows.
+function namesStandingOnGround(blocks: TileBlocks): string[] {
+ const standing = new Set(blocks.cover)
+ standing.delete(NO_BLOCK)
+ return [...standing].map((index) => blocks.names[index])
+}
+
+// A tile drawn block by block places the whole models of the blocks it shows.
+function namesSeenOneByOne(blocks: TileBlocks): string[] {
+ if (blocks.voxels === null) {
+ return []
+ }
+ return [...new Set(blocks.voxels.blocks)].map((index) => blocks.names[index])
+}
+
+/** Block art read from the Minecraft client's assets through the bridge; {@code textured} art can also show textures. */
+export function blockArt(client: BridgeClient, textured: boolean): BlockArt {
+ const images = new BridgeAssets(client, () => {})
+ const models = new BlockModels(images)
+ const colors = new BlockColors(models, images)
+ const atlas = textured ? new TerrainAtlas(images) : null
+ const looks = atlas === null ? null : new BlockLooks(models, atlas)
+ return {
+ atlas,
+ paint: async (blocks, withLooks) => {
+ const shownLooks = withLooks ? looks : null
+ const [colorOf, lookOf, coverOf, modelOf] = await Promise.all([
+ colors.colorsOf(blocks.names),
+ shownLooks?.looksOf(blocks.names) ?? null,
+ shownLooks?.coversOf(namesStandingOnGround(blocks)) ?? null,
+ shownLooks?.coversOf(namesSeenOneByOne(blocks)) ?? null
+ ])
+ blocks.colors = blocks.names.map((name) => colorOf.get(name)!)
+ blocks.looks = lookOf === null ? [] : blocks.names.map((name) => lookOf.get(name) ?? null)
+ blocks.covers = coverOf === null ? [] : blocks.names.map((name) => coverOf.get(name) ?? null)
+ blocks.models = modelOf === null ? [] : blocks.names.map((name) => modelOf.get(name) ?? null)
+ },
+ dispose: () => atlas?.dispose()
+ }
+}
diff --git a/studio/src/renderer/src/scene/blockColors.ts b/studio/src/renderer/src/scene/blockColors.ts
new file mode 100644
index 000000000..e8c3fbae1
--- /dev/null
+++ b/studio/src/renderer/src/scene/blockColors.ts
@@ -0,0 +1,100 @@
+import { blockTint } from './blockTints'
+import { parseState, type BlockModels } from './blockModels'
+import { texturePath, type ImageSource } from './textureAtlas'
+
+const UNKNOWN_BLOCK_COLOR = 0x7f7f7f
+const OPAQUE_ENOUGH_ALPHA = 128
+const NO_TINT = 0xffffff
+
+/** Each block seen from above: its top face's texture tinted as the client tints it, and that texture's average colour, read once. */
+export class BlockColors {
+ private readonly textures = new Map>()
+ private readonly colors = new Map>()
+
+ constructor(
+ private readonly models: BlockModels,
+ private readonly images: ImageSource
+ ) {}
+
+ /** The first frame of the block's top face texture, tinted; null when the block has no model or texture. */
+ topTexture(block: string): Promise {
+ let texture = this.textures.get(block)
+ if (texture === undefined) {
+ texture = this.readTopTexture(block).catch(() => null)
+ this.textures.set(block, texture)
+ }
+ return texture
+ }
+
+ colorOf(block: string): Promise {
+ let color = this.colors.get(block)
+ if (color === undefined) {
+ color = this.topTexture(block).then((texture) => (texture === null ? UNKNOWN_BLOCK_COLOR : averageColor(texture)))
+ this.colors.set(block, color)
+ }
+ return color
+ }
+
+ /** Every block's colour, by name. */
+ async colorsOf(blocks: Iterable): Promise