Appearance
展厅
一、TransformControls
1.1 功能简介
- 为选中的展品在
3D视图中添加TransformControls(拖拽结束后写入 store),并扩展init-3d以暴露renderer.domElement。
1.2 src/components/Main/exhibit-transform-3d.ts
ts
import * as THREE from "three";
import type { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";
import { TransformControls } from "three/examples/jsm/controls/TransformControls.js";
export function findExhibitMesh(
scene: THREE.Scene,
id: string,
): THREE.Object3D | null {
const root = scene.getObjectByName("gallery-root");
if (!root) {
return null;
}
let found: THREE.Object3D | null = null;
root.traverse((o) => {
if (found) {
return;
}
if (o.name === id && o.userData.isGalleryExhibit === true) {
found = o;
}
});
return found;
}
export type ExhibitTransformBinding = {
controls: TransformControls;
dispose: () => void;
};
/**
* 展品 3D 变换手柄:平移;拖拽结束时写回 store。
* Three.js r180+:与 Orbit 互斥用 mouseDown/mouseUp;场景内添加的是 getHelper()。
*/
export function bindExhibitTransformControls(
camera: THREE.PerspectiveCamera,
domElement: HTMLElement,
orbit: OrbitControls,
scene: THREE.Scene,
onCommit: (
id: string,
position: { x: number; y: number; z: number },
rotation: { x: number; y: number; z: number },
) => void,
): ExhibitTransformBinding {
const tc = new TransformControls(camera, domElement);
tc.setMode("translate");
tc.size = 0.85;
const helper = tc.getHelper();
scene.add(helper);
tc.addEventListener("mouseDown", () => {
orbit.enabled = false;
});
tc.addEventListener("mouseUp", () => {
orbit.enabled = true;
if (tc.object) {
const o = tc.object;
onCommit(
o.name,
{ x: o.position.x, y: o.position.y, z: o.position.z },
{ x: o.rotation.x, y: o.rotation.y, z: o.rotation.z },
);
}
});
return {
controls: tc,
dispose: () => {
tc.detach();
scene.remove(helper);
tc.dispose();
},
};
}1.3 src/components/Main/GalleryView.tsx
- 接入
TransformControls
1.4 src/components/Main/init-3d.ts
- 扩展
init3D
二、加入内置数据
2.1 功能简介
- 加入内置数据,可以点击直接创建画廊的。
2.2 src/components/Main/exhibit-transform-3d.ts
- 新增
setMode方法,用于设置变换手柄的模式(平移或旋转);可选mode形式:"translate"表示平移,"rotate"表示旋转。 - 新增
consumeSuppressClick方法,消费一次「忽略紧随其后的画布click」,用于防止gizmo松手时误触地面取消选中。
2.3 src/components/Main/gallery-3d-pick.ts
- 新增
shouldSuppressClick方法,为true时跳过本次click(如TransformControls刚结束拖拽)
2.4 src/store/presetGalleries.ts
- 画廊预设数据与创建函数
ts
import type { Exhibit, GalleryScene, WallSegment } from './types'
export type GalleryPreset = {
id: string
name: string
description: string
createScene: () => GalleryScene
}
/**
* @description 创建一个墙段对象。
* @param id 墙段的唯一标识符。
* @param start 墙段的起点坐标,包含 x 和 z 坐标。
* @param end 墙段的终点坐标,包含 x 和 z 坐标。
* @param height 墙段的高度,默认为 3。
* @param thickness 墙段的厚度,默认为 0.2。
* @returns 返回一个 WallSegment 对象。
* @example
* const wallSegment = wall('wall1', { x: 0, z: 0 }, { x: 5, z: 0 }, 3, 0.2)
* // 创建一个墙段对象,id 为 'wall1',起点为 (0, 0),终点为 (5, 0),高度为 3,厚度为 0.2。
*/
function wall(
id: string,
start: { x: number; z: number },
end: { x: number; z: number },
height = 3,
thickness = 0.2,
): WallSegment {
return { id, start, end, height, thickness }
}
/**
* @description 创建一个展品对象。
* @param id 展品的唯一标识符。
* @param x 展品在 X 轴上的位置。
* @param y 展品在 Y 轴上的位置。
* @param z 展品在 Z 轴上的位置。
* @param rotationY 展品绕 Y 轴的旋转角度,默认为 0。
* @param scale 展品的缩放比例,默认为 1。
* @returns 返回一个 Exhibit 对象。
* @example
* const exhibit = exhibit('exhibit1', 1, 0.5, 2, Math.PI / 4, 1.5)
* // 创建一个展品对象,id 为 'exhibit1',位置为 (1, 0.5, 2),绕 Y 轴旋转 π/4 弧度,缩放比例为 1.5。
*/
function exhibit(
id: string,
x: number,
y: number,
z: number,
rotationY = 0,
scale = 1,
): Exhibit {
return {
id,
position: { x, y, z },
rotation: { x: 0, y: rotationY, z: 0 },
scale,
}
}
/**
* @description 创建一个矩形的墙段列表,按顺时针方向排列。
* @param prefix 墙段 ID 的前缀,用于生成每个墙段的唯一 ID。
* @param width 矩形的宽度。
* @param depth 矩形的深度。
* @returns 返回一个包含四个墙段的数组,按顺时针方向排列。
* @example
* const walls = rectPerimeter('room1', 10, 5)
* // 创建一个矩形墙段列表,宽度为 10,深度为 5,墙段 ID 分别为 'room1-s'、'room1-e'、'room1-n'、'room1-w'。
*/
function rectPerimeter(
prefix: string,
width: number,
depth: number,
): WallSegment[] {
return [
wall(`${prefix}-s`, { x: 0, z: 0 }, { x: width, z: 0 }),
wall(`${prefix}-e`, { x: width, z: 0 }, { x: width, z: depth }),
wall(`${prefix}-n`, { x: width, z: depth }, { x: 0, z: depth }),
wall(`${prefix}-w`, { x: 0, z: depth }, { x: 0, z: 0 }),
]
}
/**
* @description 预设的展厅场景列表,每个预设包含唯一 ID、名称、描述和创建场景的函数。
* @type {GalleryPreset[]}
* @example
* const preset = galleryPresets[0]
* // 获取第一个预设的展厅场景。
* const scene = preset.createScene()
* // 创建该预设的展厅场景数据。
*/
const presets: GalleryPreset[] = [
{
id: 'empty',
name: '空展厅',
description: '20×20 空地,无墙无展品',
createScene: () => ({
space: {
floor: { width: 20, depth: 20 },
wallSegments: [],
},
exhibits: [],
}),
},
{
id: 'single-room',
name: '单厅展厅',
description: '18×14 矩形封闭空间 + 5 件展品',
createScene: () => {
const w = 18
const d = 14
return {
space: {
floor: { width: w, depth: d },
wallSegments: rectPerimeter('sr', w, d),
},
exhibits: [
exhibit('sr-e1', w / 2, 0.6, d * 0.35, 0),
exhibit('sr-e2', w * 0.28, 0.6, d * 0.62, Math.PI / 6),
exhibit('sr-e3', w * 0.72, 0.6, d * 0.62, -Math.PI / 6),
exhibit('sr-e4', w * 0.35, 0.6, d * 0.82, Math.PI / 4),
exhibit('sr-e5', w * 0.65, 0.6, d * 0.82, -Math.PI / 4),
],
}
},
},
{
id: 'cross-four',
name: '十字四厅',
description: '24×24 外圈 + 十字内墙,四象限各一展品',
createScene: () => {
const w = 24
const d = 24
const cx = w / 2
const cz = d / 2
const gap = 2.2
return {
space: {
floor: { width: w, depth: d },
wallSegments: [
...rectPerimeter('cf-o', w, d),
wall('cf-v1', { x: cx, z: gap }, { x: cx, z: cz - gap }),
wall('cf-v2', { x: cx, z: cz + gap }, { x: cx, z: d - gap }),
wall('cf-h1', { x: gap, z: cz }, { x: cx - gap, z: cz }),
wall('cf-h2', { x: cx + gap, z: cz }, { x: w - gap, z: cz }),
],
},
exhibits: [
exhibit('cf-e1', cx * 0.5, 0.6, cz * 0.5),
exhibit('cf-e2', cx * 1.5, 0.6, cz * 0.5, -Math.PI / 2),
exhibit('cf-e3', cx * 0.5, 0.6, cz * 1.5, Math.PI / 2),
exhibit('cf-e4', cx * 1.5, 0.6, cz * 1.5, Math.PI),
],
}
},
},
{
id: 'corridor',
name: '走廊展厅',
description: '28×9 长走廊,两侧展墙与 6 件展品',
createScene: () => {
const w = 28
const d = 9
const door = 2.4
const mid = w / 2
return {
space: {
floor: { width: w, depth: d },
wallSegments: [
wall('co-s', { x: 0, z: 0 }, { x: w, z: 0 }),
wall('co-n', { x: 0, z: d }, { x: w, z: d }),
wall('co-w1', { x: 0, z: 0 }, { x: 0, z: mid - door / 2 }),
wall('co-w2', { x: 0, z: mid + door / 2 }, { x: 0, z: d }),
wall('co-e1', { x: w, z: 0 }, { x: w, z: mid - door / 2 }),
wall('co-e2', { x: w, z: mid + door / 2 }, { x: w, z: d }),
wall('co-p1', { x: w * 0.33, z: d * 0.5 }, { x: w * 0.33, z: d }),
wall('co-p2', { x: w * 0.66, z: 0 }, { x: w * 0.66, z: d * 0.5 }),
],
},
exhibits: [
exhibit('co-e1', w * 0.15, 0.6, d * 0.35),
exhibit('co-e2', w * 0.28, 0.6, d * 0.68, Math.PI / 8),
exhibit('co-e3', w * 0.42, 0.6, d * 0.32, -Math.PI / 8),
exhibit('co-e4', w * 0.58, 0.6, d * 0.68, Math.PI / 10),
exhibit('co-e5', w * 0.72, 0.6, d * 0.32),
exhibit('co-e6', w * 0.85, 0.6, d * 0.65, -Math.PI / 6),
],
}
},
},
]
export const galleryPresets: readonly GalleryPreset[] = presets
/**
* @description 根据预设 ID 获取对应的展厅预设对象。
* @param id 要获取的预设 ID。
* @returns 返回对应的 GalleryPreset 对象,如果未找到则返回 undefined。
* @example
* const preset = getGalleryPreset('single-room')
* // 获取 ID 为 'single-room' 的展厅预设对象。
*/
export function getGalleryPreset(id: string): GalleryPreset | undefined {
return galleryPresets.find((p) => p.id === id)
}
/**
* @description 根据预设 ID 创建对应的展厅场景数据。
* @param id 要创建场景的预设 ID。
* @returns 返回对应的 GalleryScene 对象,如果未找到预设则返回 null。
* @example
* const scene = createPresetScene('cross-four')
* // 创建 ID 为 'cross-four' 的展厅场景数据。
*/
export function createPresetScene(id: string): GalleryScene | null {
const preset = getGalleryPreset(id)
if (!preset) {
return null
}
return structuredClone(preset.createScene())
}2.5 src/store/index.ts
- 新增
loadPreset,加载内置模板
2.6 src/components/Main/GalleryPresetPicker.tsx
- 开发内置模板组件
- 展厅预设选择器组件,显示内置模板列表,允许用户一键加载预设场景。
tsx
import { Button, Popconfirm, Space, Typography } from 'antd'
import { galleryPresets, useGalleryStore } from '../../store'
const { Text } = Typography
type GalleryPresetPickerProps = {
onLoaded?: () => void
}
function GalleryPresetPicker({ onLoaded }: GalleryPresetPickerProps) {
const loadPreset = useGalleryStore((s) => s.loadPreset)
return (
<div className="gallery-preset-picker">
<Text strong style={{ fontSize: 12 }}>
内置模板
</Text>
<Text type="secondary" style={{ fontSize: 12, lineHeight: 1.4 }}>
一键生成示例画廊(会替换当前场景)
</Text>
<Space wrap size={[6, 6]}>
{galleryPresets.map((preset) => (
<Popconfirm
key={preset.id}
title={`加载「${preset.name}」?`}
description={preset.description}
okText="加载"
cancelText="取消"
onConfirm={() => {
if (loadPreset(preset.id)) {
onLoaded?.()
}
}}
>
<Button size="small">{preset.name}</Button>
</Popconfirm>
))}
</Space>
</div>
)
}
export default GalleryPresetPicker2.7 src/components/Main/plan-wall-draw.ts
- 加入
getExhibit函数传入,获取展品信息的回调函数,用于在拖拽展品时获取其位置。 - 加入
updateExhibit函数传入,更新展品位置的回调函数,用于在拖拽展品时更新其位置。
2.7 src/components/Main/GalleryView.tsx
- 空白处拖拽画墙(Shift 轴对齐);点击墙线或橙色环选中展品;拖拽橙色环在平面上移动展品;拖拽蓝点改墙;
三、预览模式
3.1 功能简介
- 实现预览模式,让人物在场景里面行走
3.2 src/components/Header/index.tsx
Header组件支持传入onPreview函数支持预览功能
3.3 src/components/Main/gallery-walk-collision.ts
ts
import * as THREE from 'three'
const _box = new THREE.Box3()
const _min = new THREE.Vector3()
const _max = new THREE.Vector3()
/**
* @description 收集场景根节点下所有墙段与展品的世界坐标包围盒,作为行走碰撞检测的障碍物。
* @param root 场景根节点(通常为 gallery-root 分组)
* @returns THREE.Box3[] 障碍物包围盒列表
* @example
* collectGalleryObstacles(root)
* // 返回 root 下所有墙段和展品的包围盒。
*/
export function collectGalleryObstacles(root: THREE.Object3D): THREE.Box3[] {
const boxes: THREE.Box3[] = []
root.updateMatrixWorld(true)
root.traverse((obj) => {
const mesh = obj as THREE.Mesh
if (!mesh.isMesh) {
return
}
if (
mesh.userData.isWallSegment !== true &&
mesh.userData.isGalleryExhibit !== true
) {
return
}
_box.setFromObject(mesh)
boxes.push(_box.clone())
})
return boxes
}
/**
* @description 判断以 (x, z) 为中心、指定半径的站立区域是否在地面范围内且不与任何障碍物相交。
* @param x 待检测位置的 X 坐标
* @param z 待检测位置的 Z 坐标
* @param radius 角色碰撞半径
* @param floor 地面尺寸,包含 width 与 depth
* @param obstacles 障碍物包围盒列表,由 collectGalleryObstacles 生成
* @returns boolean 可站立返回 true,越界或与障碍物相交返回 false
* @example
* isPositionFree(2, 3, 0.3, floor, obstacles)
* // 判断 (2, 3) 处半径为 0.3 的区域是否可站立。
*/
export function isPositionFree(
x: number,
z: number,
radius: number,
floor: { width: number; depth: number },
obstacles: THREE.Box3[],
): boolean {
const margin = radius + 0.08
if (
x < margin ||
x > floor.width - margin ||
z < margin ||
z > floor.depth - margin
) {
return false
}
_min.set(x - radius, 0, z - radius)
_max.set(x + radius, 2.2, z + radius)
_box.setFromPoints([_min, _max])
for (const o of obstacles) {
if (_box.intersectsBox(o)) {
return false
}
}
return true
}
/**
* @description 按位移增量尝试移动角色,支持沿 X/Z 轴滑动以避免贴墙时被完全卡住,并限制在地面范围内。
* @param pos 角色当前位置
* @param delta 期望的位移增量
* @param radius 角色碰撞半径
* @param floor 地面尺寸,包含 width 与 depth
* @param obstacles 障碍物包围盒列表,由 collectGalleryObstacles 生成
* @returns THREE.Vector3 移动后的新位置(未能移动时返回当前位置的副本)
* @example
* tryMoveXZ(pos, new THREE.Vector3(0.1, 0, 0), 0.3, floor, obstacles)
* // 尝试沿 X 轴移动,被阻挡时尝试沿单轴滑动。
*/
export function tryMoveXZ(
pos: THREE.Vector3,
delta: THREE.Vector3,
radius: number,
floor: { width: number; depth: number },
obstacles: THREE.Box3[],
): THREE.Vector3 {
const margin = radius + 0.08
const minX = margin
const maxX = floor.width - margin
const minZ = margin
const maxZ = floor.depth - margin
const canStand = (x: number, z: number): boolean =>
isPositionFree(x, z, radius, floor, obstacles)
const nx = THREE.MathUtils.clamp(pos.x + delta.x, minX, maxX)
const nz = THREE.MathUtils.clamp(pos.z + delta.z, minZ, maxZ)
if (canStand(nx, nz)) {
return new THREE.Vector3(nx, pos.y, nz)
}
if (canStand(nx, pos.z)) {
return new THREE.Vector3(nx, pos.y, pos.z)
}
if (canStand(pos.x, nz)) {
return new THREE.Vector3(pos.x, pos.y, nz)
}
return pos.clone()
}
/**
* @description 在地面中心附近按环状扩散的方式寻找可站立的出生点,找不到时回退到地面中心。
* @param floor 地面尺寸,包含 width 与 depth
* @param obstacles 障碍物包围盒列表,由 collectGalleryObstacles 生成
* @param radius 角色碰撞半径
* @returns THREE.Vector3 出生点坐标,Y 轴固定为 0
* @example
* findSpawnPosition(floor, obstacles, 0.3)
* // 返回地面中心附近一个不与墙段、展品重叠的出生点。
*/
export function findSpawnPosition(
floor: { width: number; depth: number },
obstacles: THREE.Box3[],
radius: number,
): THREE.Vector3 {
const cx = floor.width / 2
const cz = floor.depth / 2
const candidates: [number, number][] = [[cx, cz]]
for (let ring = 1; ring <= 6; ring += 1) {
const step = 0.65 * ring
candidates.push(
[cx + step, cz],
[cx - step, cz],
[cx, cz + step],
[cx, cz - step],
[cx + step, cz + step],
[cx - step, cz - step],
)
}
for (const [x, z] of candidates) {
if (isPositionFree(x, z, radius, floor, obstacles)) {
return new THREE.Vector3(x, 0, z)
}
}
return new THREE.Vector3(cx, 0, cz)
}3.4 src/components/Main/init-gallery-walk.ts
ts
import * as THREE from 'three'
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js'
import type { GalleryScene } from '../../store/types'
import { syncGalleryScene3D } from './gallery-sync'
import {
collectGalleryObstacles,
findSpawnPosition,
tryMoveXZ,
} from './gallery-walk-collision'
const PLAYER_RADIUS = 0.32
const WALK_SPEED = 4.2
const CAM_DISTANCE = 4.8
const CAM_HEIGHT = 2.15
const LOOK_HEIGHT = 1.25
const TARGET_MODEL_HEIGHT = 1.65
/** Mixamo / 常见 GLB 默认朝 -Z,与移动方向 (+Z) 相差 180° */
const MODEL_YAW_OFFSET = Math.PI
export type InitGalleryWalkOptions = {
getSceneData: () => GalleryScene
characterModelUrl: string
onExit: () => void
}
export type GalleryWalkApi = {
dispose: () => void
}
/**
* @description 按候选名称关键字(忽略大小写、包含匹配)在动画列表中查找片段,全部未命中时回退到第一个片段。
* @param clips 动画片段列表
* @param names 候选动画名称关键字,按数组顺序优先匹配
* @returns THREE.AnimationClip | undefined 匹配到的动画片段;列表为空时返回 undefined
* @example
* findClip(gltf.animations, ['Idle', 'idle', 'Stand'])
* // 优先返回名称包含 Idle 的动画片段。
*/
function findClip(
clips: THREE.AnimationClip[],
names: string[],
): THREE.AnimationClip | undefined {
for (const name of names) {
const lower = name.toLowerCase()
const hit = clips.find((c) => c.name.toLowerCase().includes(lower))
if (hit) {
return hit
}
}
return clips[0]
}
/**
* @description 在指定容器内初始化第一人称漫游:构建灯光与展厅场景、加载角色模型与动画、绑定键鼠控制,并启动渲染循环。
* @param dom 承载渲染画布的容器元素
* @param options 初始化选项
* @param options.getSceneData 获取当前展厅数据的回调,用于构建 3D 场景与碰撞障碍物
* @param options.characterModelUrl 角色 GLB 模型地址
* @param options.onExit 退出漫游时的回调(按 Esc 触发)
* @returns GalleryWalkApi 控制器,调用其 dispose 可释放监听、动画与渲染资源
* @example
* const walk = initGalleryWalk(container, { getSceneData, characterModelUrl, onExit })
* // 退出漫游时调用 walk.dispose() 清理资源。
*/
export function initGalleryWalk(
dom: HTMLElement,
options: InitGalleryWalkOptions,
): GalleryWalkApi {
const { getSceneData, characterModelUrl, onExit } = options
const scene = new THREE.Scene()
scene.background = new THREE.Color(0xe8f4fc)
const hemi = new THREE.HemisphereLight(0xffffff, 0x8a9aaa, 0.55)
scene.add(hemi)
const dir = new THREE.DirectionalLight(0xffffff, 1.15)
dir.position.set(24, 40, 18)
scene.add(dir)
const ambient = new THREE.AmbientLight(0xffffff, 0.35)
scene.add(ambient)
const camera = new THREE.PerspectiveCamera(60, 1, 0.08, 500)
const renderer = new THREE.WebGLRenderer({ antialias: true })
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2))
renderer.setClearColor(0xe8f4fc)
dom.appendChild(renderer.domElement)
const galleryData = getSceneData()
syncGalleryScene3D(scene, camera, galleryData, null, {
selectedWallId: null,
selectedExhibitId: null,
})
const galleryRoot = scene.getObjectByName('gallery-root')
const obstacles = galleryRoot
? collectGalleryObstacles(galleryRoot)
: []
const floor = galleryData.space.floor
const spawn = findSpawnPosition(floor, obstacles, PLAYER_RADIUS)
const player = new THREE.Group()
player.position.copy(spawn)
scene.add(player)
const keys = {
forward: false,
backward: false,
left: false,
right: false,
}
let pointerLocked = false
let isMoving = false
let stopped = false
const clock = new THREE.Clock()
const loader = new GLTFLoader()
let mixer: THREE.AnimationMixer | null = null
let idleAction: THREE.AnimationAction | null = null
let walkAction: THREE.AnimationAction | null = null
const yAxis = new THREE.Vector3(0, 1, 0)
const moveDelta = new THREE.Vector3()
const forward = new THREE.Vector3()
const right = new THREE.Vector3()
function resize() {
const w = Math.max(1, dom.clientWidth)
const h = Math.max(1, dom.clientHeight)
renderer.setSize(w, h)
camera.aspect = w / h
camera.updateProjectionMatrix()
}
resize()
const resizeObserver = new ResizeObserver(resize)
resizeObserver.observe(dom)
function updateCamera() {
const yaw = player.rotation.y
const px = player.position.x - Math.sin(yaw) * CAM_DISTANCE
const pz = player.position.z - Math.cos(yaw) * CAM_DISTANCE
camera.position.set(px, player.position.y + CAM_HEIGHT, pz)
camera.lookAt(
player.position.x,
player.position.y + LOOK_HEIGHT,
player.position.z,
)
}
updateCamera()
function setMoving(moving: boolean) {
if (moving === isMoving) {
return
}
isMoving = moving
if (!mixer || !idleAction || !walkAction) {
return
}
if (moving) {
idleAction.fadeOut(0.2)
walkAction.reset().fadeIn(0.2).play()
} else {
walkAction.fadeOut(0.2)
idleAction.reset().fadeIn(0.2).play()
}
}
function onKeyDown(e: KeyboardEvent) {
switch (e.code) {
case 'KeyW':
case 'ArrowUp':
keys.forward = true
break
case 'KeyS':
case 'ArrowDown':
keys.backward = true
break
case 'KeyA':
case 'ArrowLeft':
keys.left = true
break
case 'KeyD':
case 'ArrowRight':
keys.right = true
break
case 'Escape':
if (document.pointerLockElement === dom) {
document.exitPointerLock()
}
onExit()
break
default:
break
}
}
function onKeyUp(e: KeyboardEvent) {
switch (e.code) {
case 'KeyW':
case 'ArrowUp':
keys.forward = false
break
case 'KeyS':
case 'ArrowDown':
keys.backward = false
break
case 'KeyA':
case 'ArrowLeft':
keys.left = false
break
case 'KeyD':
case 'ArrowRight':
keys.right = false
break
default:
break
}
}
function onMouseMove(e: MouseEvent) {
if (!pointerLocked) {
return
}
player.rotation.y -= e.movementX * 0.0022
}
function onPointerLockChange() {
pointerLocked = document.pointerLockElement === dom
}
function onCanvasClick() {
if (document.pointerLockElement !== dom) {
dom.requestPointerLock()
}
}
dom.addEventListener('click', onCanvasClick)
document.addEventListener('keydown', onKeyDown)
document.addEventListener('keyup', onKeyUp)
document.addEventListener('mousemove', onMouseMove)
document.addEventListener('pointerlockchange', onPointerLockChange)
void loader.loadAsync(characterModelUrl).then((gltf) => {
const model = gltf.scene
model.traverse((child) => {
const mesh = child as THREE.Mesh
if (mesh.isMesh) {
mesh.castShadow = true
mesh.receiveShadow = true
}
})
const box = new THREE.Box3().setFromObject(model)
const size = box.getSize(new THREE.Vector3())
const scale = TARGET_MODEL_HEIGHT / Math.max(size.y, 0.01)
model.scale.setScalar(scale)
box.setFromObject(model)
model.position.y = -box.min.y
model.rotation.y = MODEL_YAW_OFFSET
player.add(model)
if (gltf.animations.length > 0) {
mixer = new THREE.AnimationMixer(model)
const idleClip = findClip(gltf.animations, ['Idle', 'idle', 'Stand'])
const walkClip = findClip(gltf.animations, [
'Walk',
'walk',
'Run',
'run',
])
if (idleClip) {
idleAction = mixer.clipAction(idleClip)
idleAction.play()
}
if (walkClip && walkClip !== idleClip) {
walkAction = mixer.clipAction(walkClip)
} else if (gltf.animations[1]) {
walkAction = mixer.clipAction(gltf.animations[1])
}
}
})
let rafId = 0
function tick() {
if (stopped) {
return
}
rafId = requestAnimationFrame(tick)
const dt = Math.min(clock.getDelta(), 0.05)
moveDelta.set(0, 0, 0)
if (keys.forward || keys.backward || keys.left || keys.right) {
forward.set(0, 0, 1).applyAxisAngle(yAxis, player.rotation.y)
right.set(1, 0, 0).applyAxisAngle(yAxis, player.rotation.y)
if (keys.forward) {
moveDelta.add(forward)
}
if (keys.backward) {
moveDelta.sub(forward)
}
if (keys.left) {
moveDelta.sub(right)
}
if (keys.right) {
moveDelta.add(right)
}
if (moveDelta.lengthSq() > 0) {
moveDelta.normalize().multiplyScalar(WALK_SPEED * dt)
const next = tryMoveXZ(
player.position,
moveDelta,
PLAYER_RADIUS,
floor,
obstacles,
)
player.position.copy(next)
}
}
const moving =
keys.forward || keys.backward || keys.left || keys.right
setMoving(moving)
mixer?.update(dt)
updateCamera()
renderer.render(scene, camera)
}
tick()
function dispose() {
stopped = true
cancelAnimationFrame(rafId)
dom.removeEventListener('click', onCanvasClick)
document.removeEventListener('keydown', onKeyDown)
document.removeEventListener('keyup', onKeyUp)
document.removeEventListener('mousemove', onMouseMove)
document.removeEventListener('pointerlockchange', onPointerLockChange)
if (document.pointerLockElement === dom) {
document.exitPointerLock()
}
resizeObserver.disconnect()
mixer?.stopAllAction()
renderer.dispose()
dom.innerHTML = ''
}
return { dispose }
}3.5 src/store/characterModels.ts
迁移模型
ts
export const CHARACTER_MODELS = {
michelle: '/glb/Michelle.glb',
soldier: '/glb/Soldier.glb',
} as const
export type CharacterModelKey = keyof typeof CHARACTER_MODELS
export const DEFAULT_CHARACTER_MODEL: CharacterModelKey = 'michelle'3.6 src/store/index.ts
- 新增
setCharacterModelKey方法设置行走预览使用的角色模型,选择结果会随persist持久化。
3.7 src/components/Main/init-character-3d.ts
- 新增
dispose方法,用于停止渲染循环并释放控制器、尺寸监听、渲染器及画布节点,避免内存泄漏。
3.8 src/components/Main/GalleryPreview.tsx
- 实现
GalleryPreview画廊预览组件
tsx
import { useEffect, useRef } from 'react'
import { Button, Typography } from 'antd'
import {
CHARACTER_MODELS,
useGalleryStore,
type CharacterModelKey,
} from '../../store'
import { initGalleryWalk } from './init-gallery-walk'
const { Text } = Typography
type GalleryPreviewProps = {
onClose: () => void
}
function GalleryPreview({ onClose }: GalleryPreviewProps) {
const containerRef = useRef<HTMLDivElement>(null)
const characterKey = useGalleryStore(
(s) => s.characterModelKey,
) as CharacterModelKey
useEffect(() => {
const el = containerRef.current
if (!el) {
return
}
const walk = initGalleryWalk(el, {
getSceneData: () => useGalleryStore.getState().data,
characterModelUrl: CHARACTER_MODELS[characterKey],
onExit: onClose,
})
return () => walk.dispose()
}, [characterKey, onClose])
return (
<div className="gallery-preview" role="dialog" aria-label="画廊行走预览">
<div ref={containerRef} className="gallery-preview-canvas" />
<div className="gallery-preview-hud">
<Text className="gallery-preview-title">行走预览</Text>
<Text type="secondary" className="gallery-preview-hint">
点击画面锁定鼠标 · WASD / 方向键移动 · Esc 退出
</Text>
<Button size="small" onClick={onClose}>
退出预览
</Button>
</div>
<div className="gallery-preview-crosshair" aria-hidden />
</div>
)
}
export default GalleryPreview3.9 src/components/Main/CharacterView.tsx
3.10 src/App.tsx
- 接入
GalleryPreview组件
3.11 src/App.scss
- 样式调整
四、场景的导入导出
4.1 src/store/scene-io.ts
serializeGalleryScene:将展厅数据序列化为带版本号的JSON字符串,用于导出或下载。parseGallerySceneJson:校验并解析导入的JSON文本,兼容带版本号包裹({ version, scene })与裸场景两种结构,校验不通过时返回null。downloadGalleryScene:将展厅数据序列化后通过浏览器下载为JSON文件。
ts
import type { GalleryScene } from './types'
const SCENE_VERSION = 1
/** 导出文件的顶层结构,携带版本号便于后续做数据迁移 */
export type GallerySceneFile = {
version: number
scene: GalleryScene
}
/**
* @description 将展厅数据序列化为带版本号的 JSON 字符串,用于导出或下载。
* @param data 展厅场景数据
* @returns string 格式化(2 空格缩进)后的 JSON 文本
* @example
* serializeGalleryScene(scene)
* // 返回 { "version": 1, "scene": { ... } } 形式的 JSON 字符串。
*/
export function serializeGalleryScene(data: GalleryScene): string {
const payload: GallerySceneFile = {
version: SCENE_VERSION,
scene: data,
}
return JSON.stringify(payload, null, 2)
}
/**
* @description 类型守卫:判断未知值是否为包含数值型 x/y/z 的向量对象。
* @param v 待校验的值
* @returns boolean 是合法向量返回 true
* @example
* isVec3({ x: 1, y: 0, z: 2 }) // true
* isVec3({ x: 1, y: '0' }) // false
*/
function isVec3(v: unknown): v is { x: number; y: number; z: number } {
if (!v || typeof v !== 'object') {
return false
}
const o = v as Record<string, unknown>
return (
typeof o.x === 'number' &&
typeof o.y === 'number' &&
typeof o.z === 'number'
)
}
/**
* @description 校验未知值是否为合法墙段:需要 id、start/end 的 x/z 坐标以及 height、thickness 均为数值。
* @param v 待校验的值
* @returns boolean 是合法墙段返回 true
* @example
* isWallSegment({ id: 'w1', start: { x: 0, z: 0 }, end: { x: 2, z: 0 }, height: 2.8, thickness: 0.12 })
* // 返回 true。
*/
function isWallSegment(v: unknown): unknown | boolean {
if (!v || typeof v !== 'object') {
return false
}
const w = v as Record<string, unknown>
return (
typeof w.id === 'string' &&
w.start &&
typeof (w.start as { x: unknown }).x === 'number' &&
typeof (w.start as { z: unknown }).z === 'number' &&
w.end &&
typeof (w.end as { x: unknown }).x === 'number' &&
typeof (w.end as { z: unknown }).z === 'number' &&
typeof w.height === 'number' &&
typeof w.thickness === 'number'
)
}
/**
* @description 校验未知值是否为合法展品:需要 id、数值型 position/rotation,scale 可省略但存在时必须是数值。
* @param v 待校验的值
* @returns boolean 是合法展品返回 true
* @example
* isExhibit({ id: 'e1', position: { x: 1, y: 0.6, z: 1 }, rotation: { x: 0, y: 0, z: 0 } })
* // 返回 true。
*/
function isExhibit(v: unknown): boolean {
if (!v || typeof v !== 'object') {
return false
}
const e = v as Record<string, unknown>
return (
typeof e.id === 'string' &&
isVec3(e.position) &&
isVec3(e.rotation) &&
(e.scale === undefined || typeof e.scale === 'number')
)
}
/**
* @description 校验并解析导入的 JSON 文本,兼容带版本号包裹({ version, scene })与裸场景两种结构,校验不通过时返回 null。
* @param text 待解析的 JSON 字符串
* @returns GalleryScene | null 校验通过时返回场景数据的深拷贝,否则返回 null
* @example
* parseGallerySceneJson(jsonText)
* // 解析成功返回 GalleryScene,格式非法或版本不匹配返回 null。
*/
export function parseGallerySceneJson(text: string): GalleryScene | null {
try {
const raw = JSON.parse(text) as unknown
let scene: unknown
if (
raw &&
typeof raw === 'object' &&
'scene' in raw &&
(raw as GallerySceneFile).version === SCENE_VERSION
) {
scene = (raw as GallerySceneFile).scene
} else if (raw && typeof raw === 'object' && 'space' in raw) {
scene = raw
} else {
return null
}
const s = scene as GalleryScene
if (
!s.space?.floor ||
typeof s.space.floor.width !== 'number' ||
typeof s.space.floor.depth !== 'number' ||
!Array.isArray(s.space.wallSegments) ||
!Array.isArray(s.exhibits)
) {
return null
}
if (!s.space.wallSegments.every(isWallSegment)) {
return null
}
if (!s.exhibits.every(isExhibit)) {
return null
}
return structuredClone(s)
} catch {
return null
}
}
/**
* @description 将展厅数据序列化后通过浏览器下载为 JSON 文件。
* @param data 展厅场景数据
* @param filename 下载文件名,省略时按当天日期生成 gallery-scene-YYYY-MM-DD.json
* @returns void
* @example
* downloadGalleryScene(scene, 'my-gallery.json')
* // 触发浏览器下载该场景的 JSON 文件。
*/
export function downloadGalleryScene(data: GalleryScene, filename?: string): void {
const blob = new Blob([serializeGalleryScene(data)], {
type: 'application/json',
})
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download =
filename ?? `gallery-scene-${new Date().toISOString().slice(0, 10)}.json`
a.click()
URL.revokeObjectURL(url)
}4.2 src/components/Main/exhibit-models.ts
subscribeExhibitModels:订阅展品模型加载状态变化,加载完成或失败时回调,用于触发视图刷新。preloadExhibitModel:预加载展品模型并写入模板缓存;空地址、已缓存或加载中的地址会被跳过,加载失败仅告警不影响占位显示。invalidateExhibitModel:从模板缓存中移除指定模型,使下次构建展品节点时重新走占位与预加载流程。createExhibitObject3D:构建展品3D节点:有modelUrl且已缓存则克隆模板并用GLB呈现,否则返回占位方块并触发预加载。disposeExhibitObject:释放展品节点占用的GPU资源(含GLB克隆实例的几何体与材质),但不影响模板缓存。
ts
import * as THREE from 'three'
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js'
import type { Exhibit } from '../../store/types'
const TARGET_HEIGHT = 1.15
const loader = new GLTFLoader()
/** 已加载完成的模板缓存,key 为模型地址,value 为归一化后的根节点 */
const templateCache = new Map<string, THREE.Group>()
/** 正在加载中的模型地址,用于避免重复请求 */
const loading = new Set<string>()
/** 模型加载状态变化的订阅者集合 */
const listeners = new Set<() => void>()
/**
* @description 模型加载状态发生变化时,逐个通知所有订阅者触发重渲染。
* @returns void
* @example
* notify()
* // 在模型加载完成或失败后通知订阅者。
*/
function notify() {
for (const fn of listeners) {
fn()
}
}
/**
* @description 订阅展品模型加载状态变化,加载完成或失败时回调,用于触发视图刷新。
* @param listener 状态变化时执行的回调
* @returns () => void 取消订阅函数
* @example
* const unsubscribe = subscribeExhibitModels(rerender)
* // 组件卸载时调用 unsubscribe() 取消订阅。
*/
export function subscribeExhibitModels(listener: () => void): () => void {
listeners.add(listener)
return () => listeners.delete(listener)
}
/**
* @description 将原始 GLB 场景归一化为模板:按目标高度等比缩放、底部贴地,并包一层可复用的 Group。
* @param scene GLTF 加载得到的原始场景根节点
* @returns THREE.Group 归一化后的模板根节点
* @example
* templateCache.set(url, prepareTemplate(gltf.scene))
* // 缓存归一化后的模板供后续 clone 使用。
*/
function prepareTemplate(scene: THREE.Object3D): THREE.Group {
const root = new THREE.Group()
const box = new THREE.Box3().setFromObject(scene)
const size = box.getSize(new THREE.Vector3())
const scale = TARGET_HEIGHT / Math.max(size.y, 0.01)
scene.scale.setScalar(scale)
box.setFromObject(scene)
scene.position.y = -box.min.y
root.add(scene)
return root
}
/**
* @description 预加载展品模型并写入模板缓存;空地址、已缓存或加载中的地址会被跳过,加载失败仅告警不影响占位显示。
* @param url 展品模型资源地址
* @returns void
* @example
* preloadExhibitModel('/models/vase.glb')
* // 后台加载模型,完成后通过 subscribeExhibitModels 的回调通知刷新。
*/
export function preloadExhibitModel(url: string): void {
if (!url || templateCache.has(url) || loading.has(url)) {
return
}
loading.add(url)
void loader
.loadAsync(url)
.then((gltf) => {
templateCache.set(url, prepareTemplate(gltf.scene))
})
.catch((err) => {
console.warn('[exhibit-models] 加载失败', url, err)
})
.finally(() => {
loading.delete(url)
notify()
})
}
/**
* @description 从模板缓存中移除指定模型,使下次构建展品节点时重新走占位与预加载流程。
* @param url 展品模型资源地址
* @returns void
* @example
* invalidateExhibitModel('/models/vase.glb')
* // 模型地址变更后清理旧缓存。
*/
export function invalidateExhibitModel(url: string): void {
templateCache.delete(url)
}
/**
* @description 创建展品占位方块,模型未加载完成时用于保持展品可见,并按选中态着色。
* @param isSelected 是否为选中态
* @returns THREE.Mesh 占位方块网格
* @example
* const mesh = createPlaceholder(true)
* // 创建一个橙色(选中态)的占位方块。
*/
function createPlaceholder(isSelected: boolean): THREE.Mesh {
const geom = new THREE.BoxGeometry(0.5, 1.2, 0.5)
const mat = new THREE.MeshStandardMaterial({
color: isSelected ? 0xfa8c16 : 0xd48806,
roughness: 0.55,
metalness: 0.08,
})
return new THREE.Mesh(geom, mat)
}
/**
* @description 递归遍历展品节点,通过自发光(emissive)表现选中态,未选中时清除发光。
* @param root 展品根节点
* @param selected 是否为选中态
* @returns void
* @example
* applySelection(model, true)
* // 让模型整体呈现选中高亮。
*/
function applySelection(root: THREE.Object3D, selected: boolean): void {
root.traverse((child) => {
const mesh = child as THREE.Mesh
if (!mesh.isMesh) {
return
}
const mats = Array.isArray(mesh.material)
? mesh.material
: [mesh.material]
for (const m of mats) {
if (m instanceof THREE.MeshStandardMaterial) {
m.emissive.setHex(selected ? 0x331a00 : 0x000000)
m.emissiveIntensity = selected ? 0.4 : 0
}
}
})
}
/**
* @description 构建展品 3D 节点:有 modelUrl 且已缓存则克隆模板并用 GLB 呈现,否则返回占位方块并触发预加载。
* @param ex 展品数据,包含位置、旋转、缩放与可选的模型地址
* @param isSelected 是否为选中态,影响高亮与占位色
* @returns THREE.Object3D 可直接加入场景的展品节点,userData 标记 isGalleryExhibit 与 usesGltf
* @example
* createExhibitObject3D(exhibit, true)
* // 返回已定位、已应用选中态的展品节点。
*/
export function createExhibitObject3D(
ex: Exhibit,
isSelected: boolean,
): THREE.Object3D {
const userScale = ex.scale ?? 1
if (ex.modelUrl && templateCache.has(ex.modelUrl)) {
const model = templateCache.get(ex.modelUrl)!.clone(true)
model.scale.multiplyScalar(userScale)
model.position.set(ex.position.x, ex.position.y, ex.position.z)
model.rotation.set(ex.rotation.x, ex.rotation.y, ex.rotation.z)
model.name = ex.id
model.userData.isGalleryExhibit = true
model.userData.usesGltf = true
applySelection(model, isSelected)
return model
}
if (ex.modelUrl) {
preloadExhibitModel(ex.modelUrl)
}
const mesh = createPlaceholder(isSelected)
mesh.scale.setScalar(userScale)
mesh.position.set(ex.position.x, ex.position.y, ex.position.z)
mesh.rotation.set(ex.rotation.x, ex.rotation.y, ex.rotation.z)
mesh.name = ex.id
mesh.userData.isGalleryExhibit = true
mesh.userData.usesGltf = false
return mesh
}
/**
* @description 释放展品节点占用的 GPU 资源(含 GLB 克隆实例的几何体与材质),但不影响模板缓存。
* @param obj 要释放的展品节点
* @returns void
* @example
* disposeExhibitObject(mesh)
* // 从场景移除展品后释放其几何体与材质。
*/
export function disposeExhibitObject(obj: THREE.Object3D): void {
obj.traverse((child) => {
const mesh = child as THREE.Mesh
if (mesh.isMesh) {
mesh.geometry?.dispose()
const m = mesh.material
if (Array.isArray(m)) {
m.forEach((mat) => mat.dispose())
} else {
m?.dispose()
}
}
})
}4.3 src/store/history.ts
cloneGalleryScene:深拷贝场景数据,生成互不共享引用的历史快照,避免后续编辑污染已入栈的记录。appendHistory:将一次场景快照追加到撤销历史末尾;超过MAX_HISTORY时从头部丢弃最早的快照。MAX_HISTORY:撤销历史最多保留的快照数量,超出后丢弃最早的快照
ts
import type { GalleryScene } from './types'
/** 撤销历史最多保留的快照数量,超出后丢弃最早的快照 */
export const MAX_HISTORY = 40
/**
* @description 深拷贝场景数据,生成互不共享引用的历史快照,避免后续编辑污染已入栈的记录。
* @param data 待拷贝的当前场景数据
* @returns GalleryScene 与原对象完全独立的场景副本
* @example
* const snapshot = cloneGalleryScene(data)
* // snapshot 与 data 不再共享嵌套引用,可直接压入撤销栈。
*/
export function cloneGalleryScene(data: GalleryScene): GalleryScene {
return structuredClone(data)
}
/**
* @description 将一次场景快照追加到撤销历史末尾;超过 MAX_HISTORY 时从头部丢弃最早的快照。
* @param past 已有的撤销历史快照列表(从旧到新),不会被原地修改
* @param snapshot 本次要记录的场景快照,入栈前会自动深拷贝
* @returns GalleryScene[] 追加后的新历史数组,长度不超过 MAX_HISTORY
* @example
* const past = appendHistory(get().historyPast, get().data)
* // 每次修改场景前调用,撤销时从 past 末尾取回上一状态。
*/
export function appendHistory(
past: GalleryScene[],
snapshot: GalleryScene,
): GalleryScene[] {
const next = [...past, cloneGalleryScene(snapshot)]
if (next.length > MAX_HISTORY) {
next.shift()
}
return next
}4.4 src/store/index.ts
store新增撤销栈historyPast和重做栈historyFuture- 新增
importScene方法:导入外部场景数据并替换当前场景,同时清空选中态;原场景会入栈以便撤销。 - 新增
pushHistorySnapshot方法:手动把当前场景压入撤销栈并清空重做栈,但不改动 data。 - 新增
undo方法:撤销一步:从撤销栈弹出最近快照作为当前场景,当前场景(深拷贝)转入重做栈,并清空选中态。 - 新增
redo方法:重做一步:从重做栈取出最近一条作为当前场景,当前场景入撤销栈,并清空选中态。 setData修改:整体替换场景数据,替换前入栈历史快照并清空重做栈。reset修改:重置为默认空场景并清空选中态;重置前的状态会入栈,可通过 undo 恢复。loadPreset修改:加载内置模板并替换当前场景,同时清空选中态;原场景会入栈以便撤销。addWallSegment修改:新增墙段:自动生成 id,入栈历史快照并清空重做栈。removeWallSegment修改:删除指定墙段,入栈历史快照并清空重做栈;若被删墙段正处于选中态则同步取消选中。addExhibit修改:新增展品:自动生成 id,缺省属性用默认值补齐,入栈历史快照并清空重做栈。removeExhibit修改:删除指定展品,入栈历史快照并清空重做栈;若被删展品正处于选中态则同步取消选中。
4.5 src/components/Main/GallerySceneTools.tsx
- 负责场景数据的序列化落地与历史栈操作。
tsx
import { useRef } from 'react'
import { Button, message, Space, Typography } from 'antd'
import {
downloadGalleryScene,
parseGallerySceneJson,
useGalleryStore,
} from '../../store'
const { Text } = Typography
type GallerySceneToolsProps = {
onSceneReplaced?: () => void
}
function GallerySceneTools({ onSceneReplaced }: GallerySceneToolsProps) {
const fileRef = useRef<HTMLInputElement>(null)
const data = useGalleryStore((s) => s.data)
const historyPast = useGalleryStore((s) => s.historyPast)
const historyFuture = useGalleryStore((s) => s.historyFuture)
const importScene = useGalleryStore((s) => s.importScene)
const undo = useGalleryStore((s) => s.undo)
const redo = useGalleryStore((s) => s.redo)
function onExport() {
downloadGalleryScene(data)
message.success('场景已导出')
}
function onImportClick() {
fileRef.current?.click()
}
function onFileChange(e: React.ChangeEvent<HTMLInputElement>) {
const file = e.target.files?.[0]
e.target.value = ''
if (!file) {
return
}
const reader = new FileReader()
reader.onload = () => {
const text = reader.result
if (typeof text !== 'string') {
message.error('无法读取文件')
return
}
const scene = parseGallerySceneJson(text)
if (!scene) {
message.error('不是有效的画廊场景 JSON')
return
}
importScene(scene)
onSceneReplaced?.()
message.success('场景已导入')
}
reader.readAsText(file)
}
return (
<div className="gallery-scene-tools">
<Text strong style={{ fontSize: 12 }}>
场景文件
</Text>
<Space wrap size={[6, 6]}>
<Button size="small" onClick={onExport}>
导出 JSON
</Button>
<Button size="small" onClick={onImportClick}>
导入 JSON
</Button>
<Button size="small" disabled={historyPast.length === 0} onClick={undo}>
撤销
</Button>
<Button size="small" disabled={historyFuture.length === 0} onClick={redo}>
重做
</Button>
</Space>
<input
ref={fileRef}
type="file"
accept="application/json,.json"
hidden
onChange={onFileChange}
/>
</div>
)
}
export default GallerySceneTools4.6
- 样式调整