diff --git a/studio/src/renderer/src/scene/surfacePick.test.ts b/studio/src/renderer/src/scene/surfacePick.test.ts new file mode 100644 index 000000000..d958b0e2d --- /dev/null +++ b/studio/src/renderer/src/scene/surfacePick.test.ts @@ -0,0 +1,34 @@ +import { Box3, BoxGeometry, Group, Mesh, MeshBasicMaterial, Ray, Vector3 } from 'three' +import { describe, expect, it } from 'vitest' +import type { ViewportContent } from '../studio/SceneViewport' +import { surfaceAlong } from './surfacePick' + +const REACH = 100 + +function boxContent(): ViewportContent { + const object = new Group() + object.add(new Mesh(new BoxGeometry(2, 2, 2), new MeshBasicMaterial())) + object.updateMatrixWorld(true) + return { object, bounds: new Box3(new Vector3(-1, -1, -1), new Vector3(1, 1, 1)) } +} + +function lookingDownTheDepth(x: number): Ray { + return new Ray(new Vector3(x, 0, 10), new Vector3(0, 0, -1)) +} + +describe('surface picking', () => { + it('finds the nearest face of the drawn meshes along the ray', () => { + expect(surfaceAlong(boxContent(), lookingDownTheDepth(0), REACH)!.toArray()).toEqual([0, 0, 1]) + }) + + it('finds nothing where the ray passes by or the surface lies beyond its reach', () => { + expect(surfaceAlong(boxContent(), lookingDownTheDepth(5), REACH)).toBeNull() + expect(surfaceAlong(boxContent(), lookingDownTheDepth(0), 5)).toBeNull() + }) + + it('asks the content when it knows its own surface', () => { + const known = new Vector3(1, 2, 3) + const content: ViewportContent = { ...boxContent(), surfaceAlong: () => known } + expect(surfaceAlong(content, lookingDownTheDepth(5), REACH)).toBe(known) + }) +}) diff --git a/studio/src/renderer/src/scene/surfacePick.ts b/studio/src/renderer/src/scene/surfacePick.ts new file mode 100644 index 000000000..afa89f73c --- /dev/null +++ b/studio/src/renderer/src/scene/surfacePick.ts @@ -0,0 +1,12 @@ +import { Raycaster, type Ray, type Vector3 } from 'three' +import type { ViewportContent } from '../studio/SceneViewport' + +/** Where the ray first meets what the content draws within {@code reach}, or null when it passes by. */ +export function surfaceAlong(content: ViewportContent, ray: Ray, reach: number): Vector3 | null { + if (content.surfaceAlong !== undefined) { + return content.surfaceAlong(ray) + } + const caster = new Raycaster(ray.origin, ray.direction, 0, reach) + const [nearest] = caster.intersectObject(content.object, true) + return nearest === undefined ? null : nearest.point +} diff --git a/studio/src/renderer/src/scene/terrainMesh.test.ts b/studio/src/renderer/src/scene/terrainMesh.test.ts index 667ad643c..5e9834d85 100644 --- a/studio/src/renderer/src/scene/terrainMesh.test.ts +++ b/studio/src/renderer/src/scene/terrainMesh.test.ts @@ -1,4 +1,4 @@ -import type { Mesh } from 'three' +import { Ray, Vector3, type Mesh } from 'three' import { describe, expect, it } from 'vitest' import { buildTerrainMesh, type TerrainSurface } from './terrainMesh' @@ -48,3 +48,27 @@ describe('terrain mesh', () => { expect(triangles(landWalls)).toBe(6 * 2) }) }) + +describe('terrain surface picking', () => { + const content = buildTerrainMesh(surface).content + const pick = (origin: Vector3, direction: Vector3): Vector3 | null => content.surfaceAlong!(new Ray(origin, direction.normalize())) + + it('finds where a slanted ray meets the water over the pond', () => { + const hit = pick(new Vector3(-7, WATER + 10, 3), new Vector3(1, -1, 0))! + expect(hit.x).toBeCloseTo(3, 3) + expect(hit.y).toBeCloseTo(WATER, 3) + expect(hit.z).toBeCloseTo(3, 3) + }) + + it('finds nothing over a hole, beside the field, or from below the ground', () => { + expect(pick(new Vector3(1, 30, 1), new Vector3(0, -1, 0))).toBeNull() + expect(pick(new Vector3(100, 30, 3), new Vector3(0, -1, 0))).toBeNull() + expect(pick(new Vector3(3, GROUND - 2, 3), new Vector3(0, 1, 0))).toBeNull() + }) + + it('meets the wall where a ray comes in from the side below the rim', () => { + const hit = pick(new Vector3(-10, GROUND - 1, 3), new Vector3(1, 0, 0))! + expect(hit.x).toBeCloseTo(0, 3) + expect(hit.y).toBeCloseTo(GROUND - 1, 3) + }) +}) diff --git a/studio/src/renderer/src/scene/terrainMesh.ts b/studio/src/renderer/src/scene/terrainMesh.ts index e69287dc2..2a1159930 100644 --- a/studio/src/renderer/src/scene/terrainMesh.ts +++ b/studio/src/renderer/src/scene/terrainMesh.ts @@ -1,4 +1,4 @@ -import { Box3, BufferAttribute, BufferGeometry, DoubleSide, Group, Mesh, MeshBasicMaterial, Vector3 } from 'three' +import { Box3, BufferAttribute, BufferGeometry, DoubleSide, Group, Mesh, MeshBasicMaterial, Vector3, type Ray } from 'three' import type { ViewportContent } from '../studio/SceneViewport' /** @@ -30,6 +30,8 @@ const WALL_DEPTH_BLOCKS = 8 const WALL_TOP_LIGHT = 0.55 const WALL_BASE_LIGHT = 0.25 const NO_VALUE = Number.NaN +const MARCH_STEPS_PER_CELL = 2 +const MARCH_REFINEMENTS = 16 /** * The surface as ground lit by its slopes, see-through water over it, and walls round the rim down to below the lowest @@ -47,8 +49,9 @@ export function buildTerrainMesh(surface: TerrainSurface): TerrainMesh { const group = new Group() group.add(new Mesh(ground, groundMaterial), new Mesh(landWalls, groundMaterial), new Mesh(water, waterMaterial), new Mesh(seaWalls, waterMaterial)) const geometries = [ground, water, landWalls, seaWalls] + const bounds = field.bounds(base) return { - content: { object: group, bounds: field.bounds(base) }, + content: { object: group, bounds, surfaceAlong: (ray) => field.surfaceAlong(ray, bounds) }, dispose: () => { geometries.forEach((geometry) => geometry.dispose()) groundMaterial.dispose() @@ -186,6 +189,72 @@ class HeightField { ) } + /** + * Where the ray first comes down onto the ground or the water over it, found by marching along it through the + * {@code bounds}, so a pick does not have to test every triangle. A ray that starts below the surface inside the + * bounds, or runs over holes and out of the field, finds nothing there. + */ + surfaceAlong(ray: Ray, bounds: Box3): Vector3 | null { + const start = bounds.containsPoint(ray.origin) ? ray.origin.clone() : ray.intersectBox(bounds, new Vector3()) + if (start === null) { + return null + } + const cell = Math.abs(this.surface.worldX(1) - this.surface.worldX(0)) || 1 + const step = cell / MARCH_STEPS_PER_CELL + const reach = bounds.getSize(new Vector3()).length() + const pointAt = (distance: number): Vector3 => ray.direction.clone().multiplyScalar(distance).add(start) + const isBelow = (point: Vector3): boolean => { + const top = this.topAt(point.x, point.z) + return top !== null && point.y <= top + } + if (isBelow(start)) { + return bounds.containsPoint(ray.origin) ? null : start + } + for (let distance = step; distance <= reach; distance += step) { + if (!isBelow(pointAt(distance))) { + continue + } + let above = distance - step + let below = distance + for (let refinement = 0; refinement < MARCH_REFINEMENTS; refinement++) { + const middle = (above + below) / 2 + if (isBelow(pointAt(middle))) { + below = middle + } else { + above = middle + } + } + return pointAt(below) + } + return null + } + + /** The height of the ground, or of the water over it, at a place in the field, blended between its four vertices. */ + private topAt(x: number, z: number): number | null { + const { columns, rows } = this.surface + if (columns < 2 || rows < 2) { + return null + } + const columnAt = (x - this.surface.worldX(0)) / ((this.surface.worldX(columns - 1) - this.surface.worldX(0)) / (columns - 1)) + const rowAt = (z - this.surface.worldZ(0)) / ((this.surface.worldZ(rows - 1) - this.surface.worldZ(0)) / (rows - 1)) + if (!(columnAt >= 0 && columnAt <= columns - 1 && rowAt >= 0 && rowAt <= rows - 1)) { + return null + } + const column = Math.min(Math.floor(columnAt), columns - 2) + const row = Math.min(Math.floor(rowAt), rows - 2) + const [alongColumn, alongRow] = [columnAt - column, rowAt - row] + const northWest = row * columns + column + const tops = [northWest, northWest + 1, northWest + columns, northWest + columns + 1].map((vertex) => + Number.isNaN(this.water[vertex]) ? this.ground[vertex] : Math.max(this.ground[vertex], this.water[vertex]) + ) + if (tops.some(Number.isNaN)) { + return null + } + const north = tops[0] + (tops[1] - tops[0]) * alongColumn + const south = tops[2] + (tops[3] - tops[2]) * alongColumn + return north + (south - north) * alongRow + } + /** The two triangles of each grid square whose four corners pass {@code wanted}. */ quadsWhere(wanted: (corners: [number, number, number, number]) => boolean): Uint32Array { const { columns, rows } = this.surface diff --git a/studio/src/renderer/src/studio/SceneViewport.tsx b/studio/src/renderer/src/studio/SceneViewport.tsx index aa11c8954..d206dd89f 100644 --- a/studio/src/renderer/src/studio/SceneViewport.tsx +++ b/studio/src/renderer/src/studio/SceneViewport.tsx @@ -1,6 +1,7 @@ import { useEffect, useRef } from 'react' -import { Box3, PerspectiveCamera, Scene, Sphere, Vector3, WebGLRenderer, type Object3D } from 'three' +import { Box3, MOUSE, PerspectiveCamera, Ray, Scene, Sphere, Vector3, WebGLRenderer, type Object3D } from 'three' import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js' +import { surfaceAlong } from '../scene/surfacePick' const FIELD_OF_VIEW_DEGREES = 45 // Looking down at the scene from the south east, as v3e's object view opens. @@ -14,6 +15,8 @@ const NEAR_CLIP_PER_ORBIT_DISTANCE = 0.01 export interface ViewportContent { object: Object3D bounds: Box3 + /** Where a ray first meets what is drawn, or null; without it the viewport casts the ray at the object's meshes. */ + surfaceAlong?(ray: Ray): Vector3 | null } interface SceneViewportProps { @@ -22,7 +25,7 @@ interface SceneViewportProps { framing?: unknown } -/** Something in 3D: drag to turn around it, right drag to move, scroll to come closer. Drawn only when it changes. */ +/** 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 { const host = useRef(null) const stage = useRef(null) @@ -59,6 +62,9 @@ class Stage { host.appendChild(this.renderer.domElement) this.controls = new OrbitControls(this.camera, this.renderer.domElement) 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.controls.addEventListener('change', () => { this.fitNearClipToOrbit() this.requestFrame() @@ -101,6 +107,22 @@ class Stage { this.requestFrame() } + // 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) { + return + } + const ray = new Ray(this.camera.getWorldPosition(new Vector3()), this.camera.getWorldDirection(new Vector3())) + const hit = surfaceAlong(this.shown, ray, this.camera.far) + if (hit === null) { + return + } + this.controls.target.copy(hit) + this.fitNearClipToOrbit() + this.requestFrame() + } + private fitNearClipToOrbit(): void { this.camera.near = Math.max(NEAREST_CLIP, this.camera.position.distanceTo(this.controls.target) * NEAR_CLIP_PER_ORBIT_DISTANCE) this.camera.updateProjectionMatrix()