Pick procedural parts by clicking blocks in the studio scene view

Authors could not tell which part of a procedural object placed a block. A click on a block in the Procedural view now finds its part and chooses the node that draws it; choosing a node lights up its blocks and draws everything else faintly. SceneView gains hasParts and parts (BlockParts), served as scene-parts, aligned with the scene's blocks. No pins moved: the trace bakes with its own builder and generation is untouched, ProceduralObjectsGoldenTest digests are unchanged.

v3: ff0190384
This commit is contained in:
piexel committed 2026-11-10 12:44:27 +01:00
1 parent a8aaa3c3cf
commit 8136fa857f
24 files changed
+719 -48

No files matched your search

@@ -174,6 +174,12 @@ export class BridgeClient {
return decodeScene(await response.arrayBuffer())
}
/** The part that placed each block of {@link scene}, in the same order, or NO_PART; baked again on the server to find out. */
async sceneParts(viewId: string, key: string, variant: number, signal?: AbortSignal): Promise<Int32Array> {
const response = await this.fetch(`scene-parts?${new URLSearchParams({ view: viewId, key, variant: String(variant) })}`, { signal })
return new Int32Array(await response.arrayBuffer())
}
/** The pattern views the pack's modules show, such as its palettes. */
patternViews(): Promise<ModuleViewInfo[]> {
return this.json('patterns')
+2 -1
View File
@@ -33,10 +33,11 @@ export interface SceneEntry {
variants: number
}
/** A scene view as the server lists it; `editable` when its entries can be edited as nodes, `baked` when their bake can be timed. */
/** A scene view as the server lists it; `editable` when its entries can be edited as nodes, `baked` when their bake can be timed, `parts` when a block can be traced to the part that placed it. */
export interface SceneViewInfo extends ModuleViewInfo {
editable: boolean
baked: boolean
parts: boolean
}
/** One timed bake of a scene entry (IrisApi BakeRun): a time per step, added up over every variant. */
@@ -1,7 +1,7 @@
import { describe, expect, it } from 'vitest'
import type { GraphNode, JsonPath } from '../bridge/types'
import { NO_PART } from '../bridge/types'
import { isWithin, layoutNodes, NODE_WIDTH } from './nodeLayout'
import { isWithin, layoutNodes, nodeDrawingPart, NODE_WIDTH } from './nodeLayout'
function node(path: JsonPath, children: GraphNode[] = []): GraphNode {
return {
@@ -38,6 +38,27 @@ describe('layoutNodes', () => {
})
})
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)
@@ -49,6 +49,23 @@ export function nodeWithPath(roots: GraphNode[], path: JsonPath): GraphNode | nu
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)
@@ -0,0 +1,43 @@
import { Vector3 } from 'three'
import { describe, expect, it } from 'vitest'
import { BlockIndex, blockAtHit, NO_BLOCK } from './blockPick'
import type { BlockScene } from './sceneDecoding'
// Three blocks in a row along x, from -1 to 1, and one above the middle one.
const SCENE: BlockScene = {
palette: ['minecraft:stone'],
blocks: new Int32Array([-1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0]),
min: [-1, 0, 0],
max: [2, 2, 1]
}
describe('BlockIndex', () => {
it('finds each block by position, in the scene order', () => {
const index = new BlockIndex(SCENE)
expect([index.at(-1, 0, 0), index.at(0, 0, 0), index.at(1, 0, 0), index.at(0, 1, 0)]).toEqual([0, 1, 2, 3])
})
it('finds nothing where the scene has no block, inside its bounds or beyond', () => {
const index = new BlockIndex(SCENE)
expect(index.at(1, 1, 0)).toBe(NO_BLOCK)
expect(index.at(5, 0, 0)).toBe(NO_BLOCK)
expect(index.at(0, -1, 0)).toBe(NO_BLOCK)
})
})
describe('blockAtHit', () => {
const index = new BlockIndex(SCENE)
it('takes the block a ray goes into, whichever way it faces', () => {
expect(blockAtHit(index, new Vector3(2, 0.5, 0.5), new Vector3(-1, 0, 0))).toBe(2)
expect(blockAtHit(index, new Vector3(-1, 0.5, 0.5), new Vector3(1, 0, 0))).toBe(0)
expect(blockAtHit(index, new Vector3(0.5, 2, 0.5), new Vector3(0, -1, 0))).toBe(3)
expect(blockAtHit(index, new Vector3(0.5, 0, 0.5), new Vector3(0, 1, 0))).toBe(1)
})
it('finds no block in the open', () => {
expect(blockAtHit(index, new Vector3(5.5, 0.5, 0.5), new Vector3(-1, 0, 0))).toBe(NO_BLOCK)
})
})
@@ -0,0 +1,38 @@
import type { Vector3 } from 'three'
import { INTS_PER_BLOCK, type BlockScene } from './sceneDecoding'
/** How far past a hit surface along the ray a point is taken to tell which block the surface belongs to, in blocks. */
const SURFACE_NUDGE = 1e-3
export const NO_BLOCK = -1
/** The blocks of a scene by position. */
export class BlockIndex {
private readonly indexes = new Map<number, number>()
private readonly sizeY: number
private readonly sizeZ: number
constructor(private readonly scene: BlockScene) {
;[this.sizeY, this.sizeZ] = [scene.max[1] - scene.min[1], scene.max[2] - scene.min[2]]
const blocks = scene.blocks
for (let offset = 0; offset < blocks.length; offset += INTS_PER_BLOCK) {
this.indexes.set(this.keyOf(blocks[offset], blocks[offset + 1], blocks[offset + 2]), offset / INTS_PER_BLOCK)
}
}
/** The place of the block at x, y and z among the scene's blocks, or NO_BLOCK. */
at(x: number, y: number, z: number): number {
const inside = [x, y, z].every((value, axis) => value >= this.scene.min[axis] && value < this.scene.max[axis])
return inside ? (this.indexes.get(this.keyOf(x, y, z)) ?? NO_BLOCK) : NO_BLOCK
}
private keyOf(x: number, y: number, z: number): number {
const [localX, localY, localZ] = [x - this.scene.min[0], y - this.scene.min[1], z - this.scene.min[2]]
return (localX * this.sizeY + localY) * this.sizeZ + localZ
}
}
/** The block whose surface a ray met at {@code point}: the one the ray goes into. NO_BLOCK when that spot holds none. */
export function blockAtHit(index: BlockIndex, point: Vector3, direction: Vector3): number {
const inside = point.clone().addScaledVector(direction, SURFACE_NUDGE)
return index.at(Math.floor(inside.x), Math.floor(inside.y), Math.floor(inside.z))
}
@@ -0,0 +1,20 @@
import { describe, expect, it } from 'vitest'
import { NO_PART } from '../bridge/types'
import { blocksInPart, blocksOutsidePart } from './partFocus'
const PARTS = Int32Array.of(2, NO_PART, 0, 2, 2)
describe('part focus', () => {
it('marks every block outside the chosen part, the ones no part placed too', () => {
expect(blocksOutsidePart(PARTS, 2)).toEqual(Uint8Array.of(0, 1, 1, 0, 0))
})
it('marks nothing when no part is chosen', () => {
expect(blocksOutsidePart(PARTS, NO_PART)).toBeNull()
})
it('counts the blocks of a part, none for a part that placed nothing', () => {
expect(blocksInPart(PARTS, 2)).toBe(3)
expect(blocksInPart(PARTS, 7)).toBe(0)
})
})
@@ -0,0 +1,14 @@
import { NO_PART } from '../bridge/types'
/** Which blocks are not of {@code part}, one 1 per block in the scene's order; null when no part is chosen. */
export function blocksOutsidePart(parts: Int32Array, part: number): Uint8Array | null {
if (part === NO_PART) {
return null
}
return Uint8Array.from(parts, (blockPart) => (blockPart === part ? 0 : 1))
}
/** How many blocks {@code part} placed. */
export function blocksInPart(parts: Int32Array, part: number): number {
return parts.reduce((count, blockPart) => count + (blockPart === part ? 1 : 0), 0)
}
+54 -15
View File
@@ -1,4 +1,4 @@
import { Box3, BufferAttribute, BufferGeometry, Mesh, MeshBasicMaterial } from 'three'
import { Box3, BufferAttribute, BufferGeometry, Group, Mesh, MeshBasicMaterial } from 'three'
import type { ViewportContent } from '../studio/SceneViewport'
import { cubeModel, parseState, type BlockModels, type BlockModel, type Direction, type Quad } from './blockModels'
import { blockTint } from './blockTints'
@@ -15,6 +15,8 @@ export interface SceneMesh {
}
const CUTOUT_ALPHA = 0.1
/** How much of a faint block shows, from 0 for none to 1 for all. */
const FAINT_OPACITY = 0.12
/** The light Minecraft gives each side of a block without shadows: the top brightest, the bottom darkest. */
const FACE_LIGHT: Record<Direction, number> = { up: 1, down: 0.5, north: 0.8, south: 0.8, west: 0.6, east: 0.6 }
@@ -40,11 +42,26 @@ interface PaletteEntry {
shown: boolean
}
interface PlacedQuad {
quad: Quad
entry: PaletteEntry
x: number
y: number
z: number
}
/**
* One geometry for the whole scene, its faces against solid neighbours left out, textured from one atlas. With
* `farLeavesOnly` and far leaves in the scene, nothing but them is drawn.
* `farLeavesOnly` and far leaves in the scene, nothing but them is drawn. Blocks `faint` flags, one per block in the
* scene's order, are drawn through a faint geometry of their own that hides nothing behind it.
*/
export async function buildSceneMesh(scene: BlockScene, models: BlockModels, images: ImageSource, farLeavesOnly = false): Promise<SceneMesh> {
export async function buildSceneMesh(
scene: BlockScene,
models: BlockModels,
images: ImageSource,
farLeavesOnly = false,
faint: Uint8Array | null = null
): Promise<SceneMesh> {
const singlingOutFarLeaves = farLeavesOnly && countFarLeaves(scene) > 0
const resolved = await Promise.all(scene.palette.map((state) => models.model(state)))
const unknownStates = scene.palette.filter((_, index) => resolved[index] === null)
@@ -59,15 +76,30 @@ export async function buildSceneMesh(scene: BlockScene, models: BlockModels, ima
const solid = shown && model.fullCube && model.quads.every((quad) => atlas.cell(quad.texture).solid)
return { model, name: state.name, properties: state.properties, solid, shown }
})
const geometry = geometryOf(scene, palette, atlas)
const material = new MeshBasicMaterial({ map: atlas.texture, vertexColors: true, alphaTest: CUTOUT_ALPHA })
const bounds = new Box3().setFromBufferAttribute(geometry.getAttribute('position') as BufferAttribute)
const { solid: solidQuads, faint: faintQuads } = visibleQuads(scene, palette, faint)
const solidGeometry = geometryOf(solidQuads, atlas)
const faintGeometry = geometryOf(faintQuads, atlas)
const solidMaterial = new MeshBasicMaterial({ map: atlas.texture, vertexColors: true, alphaTest: CUTOUT_ALPHA })
const faintMaterial = new MeshBasicMaterial({ map: atlas.texture, vertexColors: true, alphaTest: CUTOUT_ALPHA * FAINT_OPACITY, transparent: true, opacity: FAINT_OPACITY, depthWrite: false })
const object = new Group()
const bounds = new Box3()
for (const [quads, geometry, material] of [
[solidQuads, solidGeometry, solidMaterial],
[faintQuads, faintGeometry, faintMaterial]
] as const) {
if (quads.length > 0) {
object.add(new Mesh(geometry, material))
bounds.union(new Box3().setFromBufferAttribute(geometry.getAttribute('position') as BufferAttribute))
}
}
return {
content: { object: new Mesh(geometry, material), bounds },
content: { object, bounds },
unknownStates,
dispose: () => {
geometry.dispose()
material.dispose()
solidGeometry.dispose()
faintGeometry.dispose()
solidMaterial.dispose()
faintMaterial.dispose()
atlas.dispose()
}
}
@@ -84,9 +116,10 @@ function drawnModel(model: BlockModel | null): BlockModel {
return model
}
function geometryOf(scene: BlockScene, palette: PaletteEntry[], atlas: TextureAtlas): BufferGeometry {
const solids = new SolidBlocks(scene, palette)
const visible: { quad: Quad; entry: PaletteEntry; x: number; y: number; z: number }[] = []
// A faint block hides no face of a neighbour, so what stands behind it is drawn whole.
function visibleQuads(scene: BlockScene, palette: PaletteEntry[], faint: Uint8Array | null): { solid: PlacedQuad[]; faint: PlacedQuad[] } {
const solids = new SolidBlocks(scene, palette, faint)
const quads = { solid: [] as PlacedQuad[], faint: [] as PlacedQuad[] }
const blocks = scene.blocks
for (let offset = 0; offset < blocks.length; offset += INTS_PER_BLOCK) {
const [x, y, z, paletteIndex] = [blocks[offset], blocks[offset + 1], blocks[offset + 2], blocks[offset + 3]]
@@ -94,13 +127,18 @@ function geometryOf(scene: BlockScene, palette: PaletteEntry[], atlas: TextureAt
if (!entry.shown) {
continue
}
const drawnIn = faint !== null && faint[offset / INTS_PER_BLOCK] === 1 ? quads.faint : quads.solid
for (const quad of entry.model.quads) {
if (quad.cullFace !== null && solids.besides(x, y, z, quad.cullFace)) {
continue
}
visible.push({ quad, entry, x, y, z })
drawnIn.push({ quad, entry, x, y, z })
}
}
return quads
}
function geometryOf(visible: PlacedQuad[], atlas: TextureAtlas): BufferGeometry {
const positions = new Float32Array(visible.length * CORNERS_PER_QUAD * 3)
const uvs = new Float32Array(visible.length * CORNERS_PER_QUAD * 2)
const colors = new Float32Array(visible.length * CORNERS_PER_QUAD * 3)
@@ -136,12 +174,13 @@ class SolidBlocks {
private readonly sizeY: number
private readonly sizeZ: number
constructor(private readonly scene: BlockScene, palette: PaletteEntry[]) {
constructor(private readonly scene: BlockScene, palette: PaletteEntry[], faint: Uint8Array | null) {
;[this.sizeX, this.sizeY, this.sizeZ] = [0, 1, 2].map((axis) => scene.max[axis] - scene.min[axis])
this.solid = new Uint8Array(this.sizeX * this.sizeY * this.sizeZ)
const blocks = scene.blocks
for (let offset = 0; offset < blocks.length; offset += INTS_PER_BLOCK) {
if (palette[blocks[offset + 3]].solid) {
const isFaint = faint !== null && faint[offset / INTS_PER_BLOCK] === 1
if (palette[blocks[offset + 3]].solid && !isFaint) {
this.solid[this.indexOf(blocks[offset], blocks[offset + 1], blocks[offset + 2])] = 1
}
}
+108 -22
View File
@@ -1,23 +1,25 @@
import { ChevronLeft, ChevronRight } from 'lucide-react'
import { useEffect, useMemo, useState } from 'react'
import { useEffect, useMemo, useRef, useState } from 'react'
import { Button } from '@/components/ui/button'
import { ScrollArea } from '@/components/ui/scroll-area'
import { cn } from '@/lib/utils'
import type { BridgeClient } from '../bridge/BridgeClient'
import type { JsonPath, SceneEntry, SceneViewInfo } from '../bridge/types'
import { NO_PART, type JsonPath, type SceneEntry, type SceneViewInfo } from '../bridge/types'
import { parsedText } from '../editor/jsonValues'
import { nodeWithPath } from '../editor/nodeLayout'
import { nodeDrawingPart, nodeWithPath } from '../editor/nodeLayout'
import { useNodeEditor } from '../editor/useNodeEditor'
import { BlockIndex, blockAtHit, NO_BLOCK } from '../scene/blockPick'
import { BlockModels } from '../scene/blockModels'
import { BridgeAssets } from '../scene/BridgeAssets'
import { countFarLeaves } from '../scene/farLeaves'
import { blocksInPart, blocksOutsidePart } from '../scene/partFocus'
import { INTS_PER_BLOCK, type BlockScene } from '../scene/sceneDecoding'
import { buildSceneMesh, type SceneMesh } from '../scene/sceneMesh'
import { BakeMeter, useBakeTiming } from './BakeMeter'
import { EntryBrowser } from './EntryBrowser'
import { NodeInspector } from './NodeInspector'
import { NodePane } from './NodePane'
import { SceneViewport } from './SceneViewport'
import { SceneViewport, type PickedSurface } from './SceneViewport'
const NUMBER = new Intl.NumberFormat('en-US')
const DEFAULT_NAMESPACE_PREFIX = 'minecraft:'
@@ -46,7 +48,6 @@ export function SceneStudio({ client, view, packRevision, onSummary, tell }: Sce
const entry = entries.find((candidate) => candidate.key === chosen?.key) ?? entries[0] ?? null
const variant = entry !== null && chosen?.key === entry.key ? Math.min(chosen.variant, entry.variants - 1) : 0
const [farLeavesOnly, setFarLeavesOnly] = useState(false)
const { scene, shown, building } = useSceneMesh(client, view.id, entry, variant, packRevision, models, images, farLeavesOnly, tell)
const chooseVariant = (next: number): void => {
if (entry !== null) {
setChosen({ key: entry.key, variant: (next + entry.variants) % entry.variants })
@@ -60,9 +61,40 @@ export function SceneStudio({ client, view, packRevision, onSummary, tell }: Sce
const selected = editor.state?.roots != null && selectedPath !== null ? nodeWithPath(editor.state.roots, selectedPath) : null
const values = useMemo(() => (editor.state === null ? undefined : parsedText(editor.state.text)), [editor.state])
useEffect(() => onSummary(entry === null || scene === null ? null : summaryOf(entry, scene)), [entry, scene, onSummary])
const [pickedPart, setPickedPart] = useState(NO_PART)
const highlightedPart = view.parts ? (selected?.partId ?? pickedPart) : NO_PART
const { scene, shown, sceneParts, building } = useSceneMesh(client, view, entry, variant, packRevision, models, images, farLeavesOnly, highlightedPart, tell)
const shownScene = shown?.scene ?? null
const blockIndex = useMemo(() => (shownScene === null ? null : new BlockIndex(shownScene)), [shownScene])
const shownParts = partsOf(sceneParts, shownScene)
const pickPart = (picked: PickedSurface): void => {
const choose = (part: number): void => {
setPickedPart(part)
setSelectedPath(part === NO_PART || editor.state?.roots == null ? null : (nodeDrawingPart(editor.state.roots, part)?.path ?? null))
}
const block = picked === null || blockIndex === null ? NO_BLOCK : blockAtHit(blockIndex, picked.point, picked.direction)
if (block === NO_BLOCK) {
choose(NO_PART)
} else if (shownParts === null) {
tell('Still finding which part placed each block')
} else if (shownParts[block] === NO_PART) {
choose(NO_PART)
tell('That block belongs to no part')
} else {
choose(shownParts[block])
}
}
const summaryParts = partsOf(sceneParts, scene)
useEffect(
() => onSummary(entry === null || scene === null ? null : summaryOf(entry, scene, summaryParts === null ? '' : partNote(summaryParts, highlightedPart))),
[entry, scene, summaryParts, highlightedPart, onSummary]
)
useEffect(() => () => onSummary(null), [onSummary])
useEffect(() => setSelectedPath(null), [entry?.key])
useEffect(() => {
setSelectedPath(null)
setPickedPart(NO_PART)
}, [entry?.key])
return (
<>
@@ -73,9 +105,18 @@ export function SceneStudio({ client, view, packRevision, onSummary, tell }: Sce
shown={shown}
status={building && entry !== null ? (waiting ?? `Building ${entry.name}`) : null}
onVariant={chooseVariant}
onPick={view.parts ? pickPart : undefined}
/>
{view.editable && entry !== null && (
<NodePane editor={editor} entryKey={entry.key} selected={selected} onSelect={(node) => setSelectedPath(node?.path ?? null)} />
<NodePane
editor={editor}
entryKey={entry.key}
selected={selected}
onSelect={(node) => {
setSelectedPath(node?.path ?? null)
setPickedPart(NO_PART)
}}
/>
)}
</div>
<aside className={cn('flex shrink-0 flex-col border-l bg-card', view.editable ? 'w-[300px]' : 'w-[250px]')}>
@@ -98,12 +139,14 @@ interface SceneAreaProps {
/** What is being built, or null when nothing is. */
status: string | null
onVariant(variant: number): void
/** Called when a block is clicked; absent when the scene has no parts to pick. */
onPick?(picked: PickedSurface): void
}
function SceneArea({ entry, variant, shown, status, onVariant }: SceneAreaProps): React.JSX.Element {
function SceneArea({ entry, variant, shown, status, onVariant, onPick }: SceneAreaProps): React.JSX.Element {
return (
<div className="relative min-h-0 flex-[11]">
<SceneViewport content={shown?.mesh.content ?? null} framing={shown?.scene} />
<SceneViewport content={shown?.mesh.content ?? null} framing={shown?.scene} onPick={onPick} />
{entry !== null && entry.variants > 1 && (
<div className="absolute top-3 left-3 flex items-center gap-1 rounded-md border border-overlay-border bg-card/90 p-1 text-[12px] tabular-nums">
<Button variant="ghost" size="icon-sm" title="Previous variant" onClick={() => onVariant(variant - 1)}>
@@ -126,10 +169,19 @@ function SceneArea({ entry, variant, shown, status, onVariant }: SceneAreaProps)
)
}
function summaryOf(entry: SceneEntry, scene: BlockScene): string {
function summaryOf(entry: SceneEntry, scene: BlockScene, partNote: string): string {
const [width, height, depth] = [0, 1, 2].map((axis) => scene.max[axis] - scene.min[axis])
const blocks = scene.blocks.length / INTS_PER_BLOCK
return `${entry.key} · ${NUMBER.format(blocks)} blocks · ${width} × ${height} × ${depth}`
return `${entry.key} · ${NUMBER.format(blocks)} blocks${partNote} · ${width} × ${height} × ${depth}`
}
// A part that only carves has no blocks of its own, which is why nothing lights up.
function partNote(parts: Int32Array, part: number): string {
if (part === NO_PART) {
return ''
}
const blocks = blocksInPart(parts, part)
return blocks === 0 ? ' · part has no blocks here' : ` · part has ${NUMBER.format(blocks)}`
}
function useSceneEntries(client: BridgeClient, viewId: string, packRevision: number, tell: (message: string) => void): SceneEntry[] {
@@ -152,25 +204,42 @@ interface ShownScene {
mesh: SceneMesh
}
/** The part of each block of {@code scene}, when the parts were read for that scene. */
interface SceneParts {
scene: BlockScene
parts: Int32Array
}
function partsOf(sceneParts: SceneParts | null, scene: BlockScene | null): Int32Array | null {
return sceneParts !== null && sceneParts.scene === scene ? sceneParts.parts : null
}
/**
* The chosen entry's scene, and its mesh, with only the far leaves drawn when asked; a newer choice abandons an older
* one, and a replaced mesh is freed. Asking for the far leaves builds the mesh again from the scene already read.
* The chosen entry's scene, and its mesh, with only the far leaves drawn when asked and every block outside the
* highlighted part drawn faintly; a newer choice abandons an older one, and a replaced mesh is freed. Asking for the
* far leaves or another part builds the mesh again from the scene already read. A view with parts also reads which
* part placed each block, once the scene is in.
*/
function useSceneMesh(
client: BridgeClient,
viewId: string,
view: SceneViewInfo,
entry: SceneEntry | null,
variant: number,
packRevision: number,
models: BlockModels,
images: BridgeAssets,
farLeavesOnly: boolean,
highlightedPart: number,
tell: (message: string) => void
): { scene: BlockScene | null; shown: ShownScene | null; building: boolean } {
): { scene: BlockScene | null; shown: ShownScene | null; sceneParts: SceneParts | null; building: boolean } {
const [scene, setScene] = useState<BlockScene | null>(null)
const [sceneParts, setSceneParts] = useState<SceneParts | null>(null)
const [shown, setShown] = useState<ShownScene | null>(null)
const [building, setBuilding] = useState(false)
const unknownStatesTold = useRef<BlockScene | null>(null)
const key = entry?.key ?? null
const viewId = view.id
const hasParts = view.parts
useEffect(() => {
if (key === null) {
@@ -180,7 +249,18 @@ function useSceneMesh(
setBuilding(true)
client
.scene(viewId, key, variant, stop.signal)
.then((found) => !stop.signal.aborted && setScene(found))
.then((found) => {
if (stop.signal.aborted) {
return
}
setScene(found)
if (hasParts) {
client
.sceneParts(viewId, key, variant, stop.signal)
.then((parts) => !stop.signal.aborted && setSceneParts({ scene: found, parts }))
.catch((failure: Error) => !stop.signal.aborted && tell(failure.message))
}
})
.catch((failure: Error) => {
if (stop.signal.aborted) {
return
@@ -189,7 +269,12 @@ function useSceneMesh(
setBuilding(false)
})
return () => stop.abort()
}, [client, viewId, key, variant, packRevision, tell])
}, [client, viewId, hasParts, key, variant, packRevision, tell])
const faint = useMemo(() => {
const parts = partsOf(sceneParts, scene)
return parts === null ? null : blocksOutsidePart(parts, highlightedPart)
}, [sceneParts, scene, highlightedPart])
useEffect(() => {
if (scene === null) {
@@ -197,25 +282,26 @@ function useSceneMesh(
}
const stop = new AbortController()
setBuilding(true)
buildSceneMesh(scene, models, images, farLeavesOnly)
buildSceneMesh(scene, models, images, farLeavesOnly, faint)
.then((built) => {
if (stop.signal.aborted) {
disposeMesh(built)
return
}
setShown({ scene, mesh: built })
if (!farLeavesOnly && built.unknownStates.length > 0) {
if (!farLeavesOnly && built.unknownStates.length > 0 && unknownStatesTold.current !== scene) {
unknownStatesTold.current = scene
tell(`No model for ${built.unknownStates.length === 1 ? built.unknownStates[0] : `${built.unknownStates.length} block states`}`)
}
})
.catch((failure: Error) => !stop.signal.aborted && tell(failure.message))
.finally(() => !stop.signal.aborted && setBuilding(false))
return () => stop.abort()
}, [scene, farLeavesOnly, models, images, tell])
}, [scene, farLeavesOnly, faint, models, images, tell])
useEffect(() => () => disposeMesh(shown?.mesh ?? null), [shown])
return { scene, shown, building }
return { scene, shown, sceneParts, building }
}
function disposeMesh(mesh: SceneMesh | null): void {
@@ -1,5 +1,5 @@
import { useEffect, useRef } from 'react'
import { Box3, MOUSE, PerspectiveCamera, Ray, Scene, Sphere, Vector3, WebGLRenderer, type Object3D } from 'three'
import { Box3, MOUSE, PerspectiveCamera, Ray, Raycaster, Scene, Sphere, Vector2, Vector3, WebGLRenderer, type Object3D } from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js'
import type { SightView } from '../scene/cameraSight'
import { surfaceAlong } from '../scene/surfacePick'
@@ -14,6 +14,13 @@ const NEAR_CLIP_PER_ORBIT_DISTANCE = 0.01
// The far plane keeps up with zooming out, so ground reaching to the horizon stays in view.
const FAR_CLIP_PER_ORBIT_DISTANCE = 20
// A press that moves further than this between pressing and releasing is a drag, not a click.
const CLICK_SLOP_PIXELS = 4
function turnsView(event: PointerEvent): boolean {
return event.button === 0 && !event.shiftKey && !event.ctrlKey && !event.metaKey
}
/** The camera of a viewport, for content that draws only what the camera looks at. */
export interface CameraLink {
/** Where the camera is and how it looks now. */
@@ -34,14 +41,19 @@ export interface ViewportContent {
follow?(camera: CameraLink): () => void
}
/** Where a click met the content, and the way it was looking; null when the click met nothing. */
export type PickedSurface = { point: Vector3; direction: Vector3 } | null
interface SceneViewportProps {
content: ViewportContent | null
/** Changes when the camera should frame the content again; the same content keeps the camera where it is. */
framing?: unknown
/** Called when the content is clicked, not dragged. */
onPick?(picked: PickedSurface): void
}
/** Something in 3D: drag to turn around what is in the middle, right drag to move, scroll to come closer to the cursor. Drawn only when it changes. */
export function SceneViewport({ content, framing }: SceneViewportProps): React.JSX.Element {
export function SceneViewport({ content, framing, onPick }: SceneViewportProps): React.JSX.Element {
const host = useRef<HTMLDivElement>(null)
const stage = useRef<Stage | null>(null)
@@ -56,6 +68,7 @@ export function SceneViewport({ content, framing }: SceneViewportProps): React.J
useEffect(() => stage.current?.show(content), [content])
useEffect(() => stage.current?.frameShown(), [framing])
useEffect(() => stage.current?.onPick(onPick ?? null), [onPick])
return <div ref={host} className="absolute inset-0 bg-map-background" />
}
@@ -73,6 +86,8 @@ class Stage {
private framed = false
private framedFar = this.camera.far
private frameRequested = false
private pickListener: ((picked: PickedSurface) => void) | null = null
private pressedAt: { x: number; y: number } | null = null
constructor(private readonly host: HTMLDivElement) {
this.renderer.setPixelRatio(window.devicePixelRatio)
@@ -82,7 +97,11 @@ class Stage {
this.controls.enableDamping = true
this.controls.zoomToCursor = true
this.controls.mouseButtons = { LEFT: MOUSE.ROTATE, MIDDLE: MOUSE.PAN, RIGHT: MOUSE.PAN }
this.renderer.domElement.addEventListener('pointerdown', (event) => this.pivotOnSurfaceInMiddle(event))
this.renderer.domElement.addEventListener('pointerdown', (event) => {
this.pressedAt = turnsView(event) ? { x: event.clientX, y: event.clientY } : null
this.pivotOnSurfaceInMiddle(event)
})
this.renderer.domElement.addEventListener('pointerup', (event) => this.pickIfClicked(event))
this.controls.addEventListener('change', () => {
this.fitClipToOrbit()
this.notifyMoved()
@@ -154,10 +173,32 @@ class Stage {
this.requestFrame()
}
onPick(listener: ((picked: PickedSurface) => void) | null): void {
this.pickListener = listener
}
// A press that stays where it was is a click; one that moved turned the view.
private pickIfClicked(event: PointerEvent): void {
const pressed = this.pressedAt
this.pressedAt = null
if (pressed === null || this.shown === null || this.pickListener === null) {
return
}
if (Math.hypot(event.clientX - pressed.x, event.clientY - pressed.y) > CLICK_SLOP_PIXELS) {
return
}
const bounds = this.renderer.domElement.getBoundingClientRect()
const pointer = new Vector2(((event.clientX - bounds.left) / bounds.width) * 2 - 1, -((event.clientY - bounds.top) / bounds.height) * 2 + 1)
const caster = new Raycaster()
this.camera.updateMatrixWorld()
caster.setFromCamera(pointer, this.camera)
const point = surfaceAlong(this.shown, caster.ray, this.camera.far)
this.pickListener(point === null ? null : { point, direction: caster.ray.direction.clone() })
}
// The pivot slides along the line of sight, so the picture stays put while turning now goes around what is there.
private pivotOnSurfaceInMiddle(event: PointerEvent): void {
const turns = event.button === 0 && !event.shiftKey && !event.ctrlKey && !event.metaKey
if (!turns || this.shown === null) {
if (!turnsView(event) || this.shown === null) {
return
}
const ray = new Ray(this.camera.getWorldPosition(new Vector3()), this.camera.getWorldDirection(new Vector3()))