Appearance
画廊编辑
一、数据持久化
1.1 zustand
zustand是一个全局状态仓库,组件里按需订阅,改了就自动更新,没有Provider、没有样板代码。
1.2 依赖安装
sh
pnpm add zustand1.3 默认画廊场景定义
1.3.1 structuredClone
structuredClone是浏览器 /Node.js内置的深拷贝API,用来完整复制一个对象(包括嵌套结构、Date、Map、Set、ArrayBuffer等)。
1.3.2 src/store/defaultGallery.ts
ts
import type { GalleryScene } from './types'
/** 内置默认场景:空墙段,仅地面范围 */
export const defaultGalleryScene: GalleryScene = {
space: {
floor: {
width: 20,
depth: 20,
},
wallSegments: [],
},
exhibits: [],
}
export function getDefaultGalleryScene(): GalleryScene {
return structuredClone(defaultGalleryScene)
}1.4 类型定义
src/store/types.ts
ts
/** 与 Three.js 世界坐标一致的向量(Y 向上) */
export interface Vec3 {
x: number
y: number
z: number
}
/**
* 墙段:在 XZ 平面上由两点确定的一条墙,供左侧 2D 绘制与右侧 3D 挤出共用。
* 单位与场景一致(如米),后续画墙工具只改 start/end。
*/
export interface WallSegment {
id: string
start: { x: number; z: number }
end: { x: number; z: number }
/** 墙高 */
height: number
/** 墙厚(XZ 法线方向宽度,挤出时用) */
thickness: number
}
/** 展厅空间:地面范围 + 2D 画墙得到的墙段列表 */
export interface GallerySpace {
floor: {
width: number
depth: number
}
wallSegments: WallSegment[]
}
/** 展品:模型或贴图至少一种,后续加载逻辑再约束 */
export interface Exhibit {
id: string
modelUrl?: string
artUrl?: string
position: Vec3
rotation: Vec3
scale?: number
}
/** 画廊场景根数据:可序列化、持久化 */
export interface GalleryScene {
space: GallerySpace
exhibits: Exhibit[]
}1.5 store创建
ts
import { create, type StateCreator } from 'zustand'
import { persist } from 'zustand/middleware'
import { getDefaultGalleryScene } from './defaultGallery'
import type { GalleryScene } from './types'
export type {
GalleryScene,
Exhibit,
GallerySpace,
WallSegment,
Vec3,
} from './types'
export interface GalleryState {
data: GalleryScene
}
export interface GalleryActions {
setData: (data: GalleryScene) => void
reset: () => void
}
const stateCreator: StateCreator<GalleryState & GalleryActions> = (set) => ({
data: getDefaultGalleryScene(),
setData(data) {
set({ data })
},
reset() {
set({ data: getDefaultGalleryScene() })
},
})
export const useGalleryStore = create<GalleryState & GalleryActions>()(
persist(stateCreator, {
/** 与「仅墙段」数据模型对齐,避免旧版 persist 结构冲突 */
name: 'gallery-editor-v2',
partialize: (state) => ({ data: state.data }),
}),
)二、场景调整
2.1 2D场景调整
2.1.1 src/components/Main/init-2d.ts
ts
import * as THREE from "three";
export type Init2DResult = {
scene: THREE.Scene;
dispose: () => void;
};
/**
* @description 在指定容器内初始化一个 2D 场景(相机 / 光照 / 渲染器都是独立的)。
* 该场景仅用于展示 2D 内容(例如平面图),不适合展示 3D 模型。
* 返回 scene 供外部挂载内容;dispose 用于销毁场景。
* @param dom 容器元素,场景会被渲染到该元素内
* @returns Init2DResult
* @example
* const { scene, dispose } = init2D(dom);
* // 在 scene 上挂载 2D 内容
* // ...
* // 卸载组件时调用 dispose 销毁场景
* dispose();
*/
export function init2D(dom: HTMLElement): Init2DResult {
const scene = new THREE.Scene();
const axesHelper = new THREE.AxesHelper(500);
scene.add(axesHelper);
const directionalLight = new THREE.DirectionalLight(0xffffff);
directionalLight.position.set(500, 400, 300);
scene.add(directionalLight);
const ambientLight = new THREE.AmbientLight(0xffffff);
scene.add(ambientLight);
const camera = new THREE.PerspectiveCamera(60, 1, 1, 10000);
camera.position.set(500, 500, 500);
camera.lookAt(0, 0, 0);
const renderer = new THREE.WebGLRenderer({
antialias: true,
});
renderer.setClearColor("lightblue");
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();
dom.append(renderer.domElement);
const resizeObserver = new ResizeObserver(() => {
resize();
});
resizeObserver.observe(dom);
let rafId = 0;
let stopped = false;
function render() {
if (stopped) {
return;
}
renderer.render(scene, camera);
rafId = requestAnimationFrame(render);
}
render();
function dispose() {
stopped = true;
cancelAnimationFrame(rafId);
resizeObserver.disconnect();
renderer.dispose();
dom.innerHTML = "";
}
return {
scene,
dispose,
};
}2.2 3D场景调整
2.2.1 src/components/Main/init-3d.ts
ts
import * as THREE from "three";
export type Init3DResult = {
scene: THREE.Scene;
dispose: () => void;
};
/**
* @description 在指定容器内初始化一个 3D 场景(相机 / 光照 / 渲染器都是独立的)。
* 该场景用于展示 3D 内容(例如模型),不适合展示 2D 内容。
* 返回 scene 供外部挂载内容;dispose 用于销毁场景。
* @param dom 容器元素,场景会被渲染到该元素内
* @example
* const { scene, dispose } = init3D(dom);
* // 在 scene 上挂载 3D 内容
* // ...
* // 卸载组件时调用 dispose 销毁场景
* dispose();
* @returns Init3DResult
*/
export function init3D(dom: HTMLElement): Init3DResult {
const scene = new THREE.Scene();
const axesHelper = new THREE.AxesHelper(500);
scene.add(axesHelper);
const directionalLight = new THREE.DirectionalLight(0xffffff);
directionalLight.position.set(500, 400, 300);
scene.add(directionalLight);
const ambientLight = new THREE.AmbientLight(0xffffff);
scene.add(ambientLight);
const camera = new THREE.PerspectiveCamera(60, 1, 1, 10000);
camera.position.set(500, 500, 500);
camera.lookAt(0, 0, 0);
const renderer = new THREE.WebGLRenderer({
antialias: true,
});
renderer.setClearColor("lightyellow");
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();
dom.append(renderer.domElement);
const resizeObserver = new ResizeObserver(() => {
resize();
});
resizeObserver.observe(dom);
let rafId = 0;
let stopped = false;
function render() {
if (stopped) {
return;
}
renderer.render(scene, camera);
rafId = requestAnimationFrame(render);
}
render();
function dispose() {
stopped = true;
cancelAnimationFrame(rafId);
resizeObserver.disconnect();
renderer.dispose();
dom.innerHTML = "";
}
return {
scene,
dispose,
};
}2.3 src/components/Main/GalleryView.tsx
tsx
import React from "react";
import { Segmented, Typography } from "antd";
import { useGalleryStore } from "../../store";
import { init2D } from "./init-2d";
import { init3D } from "./init-3d";
const { Text, Title } = Typography;
function GalleryView() {
React.useEffect(() => {
const dom = document.getElementById("threejs-3d-container")!;
const { dispose } = init3D(dom);
return dispose;
}, []);
React.useEffect(() => {
const dom = document.getElementById("threejs-2d-container")!;
const { dispose } = init2D(dom);
return dispose;
}, []);
React.useEffect(() => {
const { data } = useGalleryStore.getState();
console.log("[gallery] scene", data);
}, []);
const [curMode, setCurMode] = React.useState<"2d" | "3d">("2d");
return (
<div className="gallery-view">
<div id="threejs-2d-container" style={{ display: curMode === "2d" ? "block" : "none" }} />
<div id="threejs-3d-container" style={{ display: curMode === "3d" ? "block" : "none" }} />
{curMode === "2d" ? (
<div className="gallery-2d-hud">
<Title level={5} className="gallery-2d-hud-title">
平面绘制(画墙)
</Title>
<Text type="secondary">下一阶段在此接入画墙交互</Text>
</div>
) : (
<div className="gallery-3d-hud">
<Title level={5} className="gallery-3d-hud-title">
三维预览
</Title>
<Text type="secondary">后续根据墙段生成墙体模型</Text>
</div>
)}
<div className="mode-change-btns">
<Segmented
options={[
{ label: "2D", value: "2d" },
{ label: "3D", value: "3d" },
]}
value={curMode}
onChange={(value) => setCurMode(value as "2d" | "3d")}
/>
</div>
</div>
);
}
export default GalleryView;2.4 样式调整
diff
body {
margin: 0;
}
.gallery-editor-layout {
min-height: 100vh;
.app-header {
display: flex;
align-items: center;
padding: 0 24px;
background: #fff;
border-bottom: 1px solid #000;
.header-content {
display: flex;
align-items: center;
justify-content: space-between;
width: 100%;
}
.header-title {
margin: 0;
font-size: 18px;
font-weight: 500;
}
}
.app-sider {
background: #fff;
border-right: 1px solid #000;
.ant-menu {
margin-top: 16px;
}
}
.app-content {
position: relative;
min-height: calc(100vh - 64px);
background: #fff;
}
.main-content {
position: relative;
height: 100%;
min-height: calc(100vh - 64px);
display: flex;
flex-direction: column;
+ .gallery-view {
+ position: relative;
+ flex: 1;
+ min-height: 0;
+ }
#threejs-3d-container,
#threejs-2d-container {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
width: 100%;
height: 100%;
+ canvas {
+ display: block;
+ width: 100% !important;
+ height: 100% !important;
+ }
}
+ .gallery-2d-hud,
+ .gallery-3d-hud {
+ position: absolute;
+ z-index: 12;
+ top: 16px;
+ left: 16px;
+ max-width: min(360px, 90vw);
+ padding: 10px 12px;
+ background: #fff;
+ border: 1px solid rgba(0, 0, 0, 0.15);
+ border-radius: 6px;
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ align-items: flex-start;
+ }
+
+ .gallery-2d-hud-title,
+ .gallery-3d-hud-title {
+ margin: 0 !important;
+ }
.mode-change-btns {
position: absolute;
z-index: 10;
bottom: 20px;
left: 20px;
}
+ @media (prefers-color-scheme: dark) {
+ .gallery-2d-hud,
+ .gallery-3d-hud {
+ background: #f5f5f5;
+ border-color: rgba(255, 255, 255, 0.12);
+ }
+ }
.character-view {
flex: 1;
display: flex;
flex-direction: column;
min-height: 0;
padding: 20px 24px 24px;
box-sizing: border-box;
background: linear-gradient(180deg, #fafbfc 0%, #f0f2f5 100%);
}
.character-view-header {
flex-shrink: 0;
margin-bottom: 16px;
}
.character-view-title {
margin: 0 0 6px;
font-size: 16px;
font-weight: 600;
color: rgba(0, 0, 0, 0.88);
letter-spacing: 0.02em;
}
.character-view-desc {
margin: 0;
font-size: 13px;
color: rgba(0, 0, 0, 0.45);
line-height: 1.5;
}
.character-split {
flex: 1;
display: flex;
gap: 20px;
min-height: 0;
align-items: stretch;
}
.character-panel {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
padding: 0;
margin: 0;
border: 1px solid rgba(0, 0, 0, 0.08);
border-radius: 12px;
background: #fff;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.04);
cursor: pointer;
text-align: left;
font: inherit;
color: inherit;
overflow: hidden;
outline: none;
transition:
border-color 0.2s ease,
box-shadow 0.2s ease,
transform 0.15s ease;
&:focus-visible {
box-shadow:
0 0 0 2px #fff,
0 0 0 4px rgba(22, 119, 255, 0.45);
}
&:hover {
border-color: rgba(22, 119, 255, 0.35);
box-shadow: 0 4px 14px rgba(22, 119, 255, 0.08);
}
.character-panel-head {
flex-shrink: 0;
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
padding: 12px 16px;
background: linear-gradient(180deg, #fafafa 0%, #fff 100%);
border-bottom: 1px solid rgba(0, 0, 0, 0.06);
}
.character-panel-name {
font-size: 15px;
font-weight: 600;
color: rgba(0, 0, 0, 0.85);
}
.character-panel-badge {
font-size: 12px;
font-weight: 500;
color: #1677ff;
padding: 2px 10px;
border-radius: 999px;
background: rgba(22, 119, 255, 0.1);
border: 1px solid rgba(22, 119, 255, 0.2);
}
.character-panel-viewport {
flex: 1;
min-height: 280px;
position: relative;
background: #f0f2f5;
canvas {
display: block;
width: 100% !important;
height: 100% !important;
}
}
.character-panel--active {
border-color: #1677ff;
box-shadow:
0 0 0 1px rgba(22, 119, 255, 0.2),
0 6px 20px rgba(22, 119, 255, 0.12);
&:hover {
border-color: #1677ff;
}
.character-panel-head {
background: linear-gradient(180deg, #e6f4ff 0%, #fff 100%);
border-bottom-color: rgba(22, 119, 255, 0.15);
}
}
}
}
}三、绘制地面与墙段
3.1 Store同步场景
3.1.1 src/components/Main/gallery-sync.ts
ts
import * as THREE from 'three'
import type { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js'
import type { GalleryScene } from '../../store/types'
export type Sync3DOptions = {
/** 首次进入或需要复位视角时为 true */
resetCamera?: boolean
}
const ROOT_NAME = 'gallery-root'
/**
* @description 释放 Object3D 及其子节点的几何体和材质资源。
* 仅释放几何体和材质,纹理资源由材质统一管理,通常无需单独释放。
* 仅释放几何体和材质,不会从场景中移除节点;若需要移除节点,请在外部调用 scene.remove(obj)。
* @param obj 要释放资源的 Object3D 节点
*/
function disposeObjectResources(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()
}
}
})
}
/**
* @description 移除场景中已存在的 gallery 根节点,并释放其几何体和材质资源。
* @param scene 场景实例
* @returns void
*/
function removeGalleryRoot(scene: THREE.Scene): void {
const existing = scene.getObjectByName(ROOT_NAME)
if (existing) {
disposeObjectResources(existing)
scene.remove(existing)
}
}
/**
* @description 同步 3D 视图的场景内容(地面 + 墙段),并可选复位相机。
* @param scene 场景实例
* @param camera 相机实例
* @param data 画廊场景数据
* @param controls 轨道控制器实例,可选
* @param options 同步选项,可选
* @returns void
*/
export function syncGalleryScene3D(
scene: THREE.Scene,
camera: THREE.PerspectiveCamera,
data: GalleryScene,
controls: OrbitControls | null,
options?: Sync3DOptions,
): void {
removeGalleryRoot(scene)
const root = new THREE.Group()
root.name = ROOT_NAME
const { floor, wallSegments } = data.space
const cx = floor.width / 2
const cz = floor.depth / 2
const maxDim = Math.max(floor.width, floor.depth, 1)
const floorGeom = new THREE.PlaneGeometry(floor.width, floor.depth)
const floorMat = new THREE.MeshStandardMaterial({
color: 0xd9d9d9,
side: THREE.DoubleSide,
})
const floorMesh = new THREE.Mesh(floorGeom, floorMat)
floorMesh.rotation.x = -Math.PI / 2
floorMesh.position.set(cx, 0, cz)
root.add(floorMesh)
const wallMat = new THREE.MeshStandardMaterial({ color: 0xf5f5f5 })
for (const wall of wallSegments) {
const dx = wall.end.x - wall.start.x
const dz = wall.end.z - wall.start.z
const len = Math.hypot(dx, dz)
if (len < 1e-6) {
continue
}
const hx = (wall.start.x + wall.end.x) / 2
const hz = (wall.start.z + wall.end.z) / 2
const angle = Math.atan2(dx, dz)
const geom = new THREE.BoxGeometry(wall.thickness, wall.height, len)
const mesh = new THREE.Mesh(geom, wallMat)
mesh.position.set(hx, wall.height / 2, hz)
mesh.rotation.y = angle
mesh.name = wall.id
root.add(mesh)
}
scene.add(root)
if (controls) {
controls.target.set(cx, 0, cz)
}
if (options?.resetCamera) {
camera.position.set(cx + maxDim * 0.75, maxDim * 0.65, cz + maxDim * 0.75)
camera.lookAt(cx, 0, cz)
}
controls?.update()
}
/**
* @description 同步 2D 视图的场景内容(地面 + 墙段),并调整相机位置和投影矩阵。
* @param scene 场景实例
* @param camera 相机实例
* @param viewportW 视口宽度
* @param viewportH 视口高度
* @param data 画廊场景数据
* @returns void
*/
export function syncGalleryScene2D(
scene: THREE.Scene,
camera: THREE.PerspectiveCamera,
viewportW: number,
viewportH: number,
data: GalleryScene,
): void {
removeGalleryRoot(scene)
const root = new THREE.Group()
root.name = ROOT_NAME
const { floor, wallSegments } = data.space
const cx = floor.width / 2
const cz = floor.depth / 2
const grid = new THREE.GridHelper(
Math.max(floor.width, floor.depth),
Math.max(4, Math.round(Math.max(floor.width, floor.depth))),
0xbbbbbb,
0xdddddd,
)
grid.position.set(cx, 0, cz)
root.add(grid)
const outlinePts = [
new THREE.Vector3(0, 0.02, 0),
new THREE.Vector3(floor.width, 0.02, 0),
new THREE.Vector3(floor.width, 0.02, floor.depth),
new THREE.Vector3(0, 0.02, floor.depth),
new THREE.Vector3(0, 0.02, 0),
]
const outlineGeom = new THREE.BufferGeometry().setFromPoints(outlinePts)
const outline = new THREE.Line(
outlineGeom,
new THREE.LineBasicMaterial({ color: 0x667eea }),
)
root.add(outline)
const wallLineMat = new THREE.LineBasicMaterial({ color: 0x262626 })
for (const wall of wallSegments) {
const pts = [
new THREE.Vector3(wall.start.x, 0.04, wall.start.z),
new THREE.Vector3(wall.end.x, 0.04, wall.end.z),
]
const g = new THREE.BufferGeometry().setFromPoints(pts)
const line = new THREE.Line(g, wallLineMat)
line.name = wall.id
root.add(line)
}
scene.add(root)
const maxDim = Math.max(floor.width, floor.depth)
const dist = maxDim * 1.15
camera.position.set(cx, dist, cz)
camera.lookAt(cx, 0, cz)
const w = Math.max(1, viewportW)
const h = Math.max(1, viewportH)
camera.aspect = w / h
camera.updateProjectionMatrix()
}3.1.2 src/components/Main/init-2d.ts
- 新增回调函数
3.1.3 src/components/Main/init-3d.ts
code diff
3.1.4 src/components/Main/GalleryView.tsx
- 修改画廊页
四、拖拽面墙
4.1 交互逻辑
- 在 2D 平面画布上拖拽生成墙段:射线与地面(y=0)求交,松手写入 onCommit。
- 预览线挂在 scene 根下,与
gallery-root分离,避免被同步逻辑删掉。
4.2 src/components/Main/plan-wall-draw.ts
ts
import * as THREE from 'three'
const PREVIEW_NAME = 'wall-draw-preview'
/**
* @description 移除场景中已存在的墙段绘制预览线,并释放其几何体和材质资源。
* @param scene 场景实例
* @returns void
*/
function removePreview(scene: THREE.Scene): void {
const obj = scene.getObjectByName(PREVIEW_NAME)
if (!obj) {
return
}
scene.remove(obj)
const line = obj as THREE.Line
line.geometry.dispose()
;(line.material as THREE.Material).dispose()
}
export type AttachPlanWallDrawOptions = {
dom: HTMLElement
camera: THREE.Camera
scene: THREE.Scene
getFloorBounds: () => { width: number; depth: number }
onCommit: (start: { x: number; z: number }, end: { x: number; z: number }) => void
/** 最小墙长(世界单位),过短视为误触 */
minLength?: number
}
/**
* 在 2D 平面画布上拖拽生成墙段:射线与地面(y=0)求交,松手写入 onCommit。
* 预览线挂在 scene 根下,与 `gallery-root` 分离,避免被同步逻辑删掉。
*/
/**
* @description 在 2D 平面画布上拖拽生成墙段:射线与地面(y=0)求交,松手写入 onCommit。
* 预览线挂在 scene 根下,与 `gallery-root` 分离,避免被同步逻辑删掉。
* @param opts 配置项
* @returns 卸载函数,调用后移除事件监听和预览线
* @example
* const detach = attachPlanWallDrawing({
* dom,
* camera,
* scene,
* getFloorBounds: () => ({ width: 10, depth: 8 }),
* onCommit: (start, end) => {
* console.log('新墙段:', start, end)
* },
* })
* // 卸载时调用 detach()
* detach()
*/
export function attachPlanWallDrawing(opts: AttachPlanWallDrawOptions): () => void {
const { dom, camera, scene, getFloorBounds, onCommit, minLength = 0.12 } = opts
const el = dom.querySelector('canvas')
if (!(el instanceof HTMLCanvasElement)) {
return () => {}
}
const canvas = el
const plane = new THREE.Plane(new THREE.Vector3(0, 1, 0), 0)
const raycaster = new THREE.Raycaster()
const hit = new THREE.Vector3()
const ndc = new THREE.Vector2()
let dragStart: THREE.Vector3 | null = null
function clampOnFloor(v: THREE.Vector3): THREE.Vector3 {
const { width, depth } = getFloorBounds()
v.x = Math.min(width, Math.max(0, v.x))
v.z = Math.min(depth, Math.max(0, v.z))
v.y = 0.06
return v
}
function pointerToFloor(e: PointerEvent): THREE.Vector3 | null {
const rect = canvas.getBoundingClientRect()
const rw = Math.max(1, rect.width)
const rh = Math.max(1, rect.height)
ndc.x = ((e.clientX - rect.left) / rw) * 2 - 1
ndc.y = -((e.clientY - rect.top) / rh) * 2 + 1
raycaster.setFromCamera(ndc, camera)
const out = raycaster.ray.intersectPlane(plane, hit)
if (!out) {
return null
}
return clampOnFloor(hit.clone())
}
function showPreview(a: THREE.Vector3, b: THREE.Vector3): void {
removePreview(scene)
const geom = new THREE.BufferGeometry().setFromPoints([a.clone(), b.clone()])
const mat = new THREE.LineBasicMaterial({ color: 0xf5222d })
const line = new THREE.Line(geom, mat)
line.name = PREVIEW_NAME
scene.add(line)
}
function onDown(e: PointerEvent): void {
if (e.button !== 0) {
return
}
const p = pointerToFloor(e)
if (!p) {
return
}
dragStart = p.clone()
canvas.setPointerCapture(e.pointerId)
}
function onMove(e: PointerEvent): void {
if (!dragStart) {
return
}
const p = pointerToFloor(e)
if (!p) {
return
}
showPreview(dragStart, p)
}
function finish(e: PointerEvent): void {
if (!dragStart) {
return
}
try {
canvas.releasePointerCapture(e.pointerId)
} catch {
/* 未捕获时忽略 */
}
const start = dragStart
dragStart = null
const p = pointerToFloor(e)
removePreview(scene)
if (!p) {
return
}
const dx = p.x - start.x
const dz = p.z - start.z
if (Math.hypot(dx, dz) < minLength) {
return
}
onCommit(
{ x: start.x, z: start.z },
{ x: p.x, z: p.z },
)
}
canvas.addEventListener('pointerdown', onDown)
canvas.addEventListener('pointermove', onMove)
canvas.addEventListener('pointerup', finish)
canvas.addEventListener('pointercancel', finish)
return () => {
canvas.removeEventListener('pointerdown', onDown)
canvas.removeEventListener('pointermove', onMove)
canvas.removeEventListener('pointerup', finish)
canvas.removeEventListener('pointercancel', finish)
removePreview(scene)
dragStart = null
}
}4.3 src/store/index.ts
- 调整
store
添加一个墙段到画廊场景数据中,生成唯一 ID 并使用默认高度和厚度(如果未提供)。
4.4 src/components/Main/gallery-sync.ts
- 2D 中点击选中墙段、高亮显示,并按 Backspace 删除;store 增加 removeWallSegment 与选中状态。
五、shift轴对齐
5.1 功能简介
Shift拖拽时墙段角度对齐到90°(轴对齐);- 选中墙时在
2D HUD用antd编辑墙高与墙厚。
5.2 src/components/Main/snap-wall.ts
Math.hypot()函数返回所有参数的平方和的平方根,即
ts
/**
* @description 将墙段的终点坐标 snap 到与起点坐标的水平或垂直轴上。
* 将墙终点吸附到相对起点的最近轴向(90°),与 3D 墙 Box 的 rotation.y = atan2(dx,dz) 一致。
* @param start 墙段起点坐标
* @param end 墙段终点坐标
* @returns snap 后的终点坐标
*/
export function snapWallEndToAxis(
start: { x: number; z: number },
end: { x: number; z: number },
): { x: number; z: number } {
const dx = end.x - start.x
const dz = end.z - start.z
const len = Math.hypot(dx, dz)
if (len < 1e-9) {
return { ...end }
}
let theta = Math.atan2(dx, dz)
const quarter = Math.PI / 2
theta = Math.round(theta / quarter) * quarter
return {
x: start.x + len * Math.sin(theta),
z: start.z + len * Math.cos(theta),
}
}5.3 src/components/Main/plan-wall-draw.ts
- 根据起点坐标、原始终点坐标和
shift键状态,计算墙段终点的最终坐标。
- 若按下 shift 键,则将终点坐标 snap 到与起点坐标的水平或垂直轴上。
- 若未按下 shift 键,则返回原始终点坐标。
- 终点坐标会被限制在地面范围内(0 <= x <= width, 0 <= z <= depth)。
- y 坐标固定为 0.06,表示墙段高度。
5.4 src/components/Main/GalleryView.tsx
- 按住
Shift吸附水平 / 垂直
5.5 src/store/index.ts
updateWallSegment更新指定墙段的属性,支持更新起点、终点、厚度和高度。
六、状态同步与属性共用
6.1 src/App.scss
- 样式调整
6.2 src/components/Main/gallery-3d-pick.ts
ts
import * as THREE from 'three'
export type AttachGallery3dWallPickOptions = {
dom: HTMLElement
scene: THREE.Scene
camera: THREE.PerspectiveCamera
setSelectedWallId: (id: string | null) => void
}
/**
* @description 在 3D 视图中点击墙段或地面,选中墙段或取消选中。
* @param opts 配置选项
* @returns 解绑函数
* @example
* const detach = attachGallery3dWallPick({
* dom: document.getElementById('canvas-container'),
* scene: threeScene,
* camera: threeCamera,
* setSelectedWallId: (id) => {
* console.log('Selected wall ID:', id)
* },
* })
* // 调用 detach() 可解绑事件监听
*/
export function attachGallery3dWallPick(
opts: AttachGallery3dWallPickOptions,
): () => void {
const { dom, scene, camera, setSelectedWallId } = opts
const el = dom.querySelector('canvas')
if (!(el instanceof HTMLCanvasElement)) {
return () => {}
}
const canvas = el
const raycaster = new THREE.Raycaster()
const ndc = new THREE.Vector2()
function onClick(ev: MouseEvent): void {
if (ev.button !== 0) {
return
}
const rect = canvas.getBoundingClientRect()
const rw = Math.max(1, rect.width)
const rh = Math.max(1, rect.height)
ndc.x = ((ev.clientX - rect.left) / rw) * 2 - 1
ndc.y = -((ev.clientY - rect.top) / rh) * 2 + 1
raycaster.setFromCamera(ndc, camera)
const root = scene.getObjectByName('gallery-root')
if (!root) {
return
}
const hits = raycaster.intersectObjects(root.children, true)
const wallHit = hits.find(
(h) =>
(h.object as THREE.Mesh).isMesh === true &&
h.object.userData.isWallSegment === true &&
typeof h.object.name === 'string' &&
h.object.name.length > 0,
)
if (wallHit) {
setSelectedWallId(wallHit.object.name)
return
}
const floorHit = hits.find(
(h) =>
(h.object as THREE.Mesh).isMesh === true &&
h.object.userData.isGalleryFloor === true,
)
if (floorHit) {
setSelectedWallId(null)
}
}
canvas.addEventListener('click', onClick)
return () => {
canvas.removeEventListener('click', onClick)
}
}6.3 src/components/Main/gallery-sync.ts
- 添加与2D平面共用的选中态
6.4 src/components/Main/GalleryView.tsx
七、2D平面控制
7.1 功能简介
- 实现
2D平面下拖动墙段两端控制点以调整长度与走向 - 与
Shift轴对齐吸附复用现有逻辑。
7.2 src/components/Main/plan-wall-handles.ts
- 实现
syncPlanWallHandles方法,用于在2D平面视图中显示选中墙段的端点蓝色拖拽手柄。 - 实现
attachPlanWallHandleDrag方法,用于在2D平面视图中拖拽选中墙段的端点手柄,实时更新墙段的起点或终点坐标。
ts
import * as THREE from 'three'
import type { WallSegment } from '../../store/types'
import { snapWallEndToAxis } from './snap-wall'
const HANDLES_GROUP = 'plan-wall-handles'
function disposeHandlesGroup(group: THREE.Object3D): void {
group.traverse((child) => {
const m = child as THREE.Mesh
if (m.isMesh) {
m.geometry?.dispose()
const mat = m.material
if (Array.isArray(mat)) {
mat.forEach((x) => x.dispose())
} else {
mat?.dispose()
}
}
})
}
/**
* @description 在 2D 平面视图中显示选中墙段的端点蓝色拖拽手柄。
* @param scene 场景实例
* @param selectedWallId 当前选中墙段的 ID,若为 null 则不显示手柄。
* @param walls 墙段数据列表,用于查找选中墙段的起点和终点坐标。
* @returns void
* @example
* syncPlanWallHandles(scene, selectedWallId, walls)
* // 在 2D 平面视图中显示选中墙段的端点蓝色拖拽手柄。
*/
export function syncPlanWallHandles(
scene: THREE.Scene,
selectedWallId: string | null,
walls: WallSegment[],
): void {
const existing = scene.getObjectByName(HANDLES_GROUP)
if (existing) {
disposeHandlesGroup(existing)
scene.remove(existing)
}
if (!selectedWallId) {
return
}
const wall = walls.find((w) => w.id === selectedWallId)
if (!wall) {
return
}
const group = new THREE.Group()
group.name = HANDLES_GROUP
for (const kind of ['start', 'end'] as const) {
const pos = kind === 'start' ? wall.start : wall.end
const geom = new THREE.SphereGeometry(0.22, 14, 14)
const mat = new THREE.MeshBasicMaterial({ color: 0x1677ff })
const mesh = new THREE.Mesh(geom, mat)
mesh.position.set(pos.x, 0.14, pos.z)
mesh.userData.isWallEndpointHandle = true
mesh.userData.handleKind = kind
mesh.userData.wallId = wall.id
group.add(mesh)
}
scene.add(group)
}
export type AttachPlanWallHandleDragOptions = {
dom: HTMLElement
scene: THREE.Scene
camera: THREE.Camera
getFloorBounds: () => { width: number; depth: number }
getWall: (id: string) => WallSegment | undefined
updateWallSegment: (
id: string,
patch: Partial<Pick<WallSegment, 'start' | 'end'>>,
) => void
minLength?: number
}
type DragState = {
wallId: string
kind: 'start' | 'end'
fixed: { x: number; z: number }
mesh: THREE.Mesh
pointerId: number
last: { x: number; z: number }
}
/**
* @description 在 2D 平面视图中拖拽选中墙段的端点手柄,实时更新墙段的起点或终点坐标。
* @param opts 配置选项,包括 DOM 元素、场景、相机、获取地面边界和墙段数据的函数,以及更新墙段的回调函数。
* @returns 返回一个函数,用于移除事件监听器和清理拖拽状态。
* @example
* const detach = attachPlanWallHandleDrag({
* dom: document.getElementById('canvas-container'),
* scene,
* camera,
* getFloorBounds: () => ({ width: 10, depth: 10 }),
* getWall: (id) => walls.find(w => w.id === id),
* updateWallSegment: (id, patch) => { ... },
* })
* // 调用 detach() 可移除事件监听器和清理拖拽状态。
*/
export function attachPlanWallHandleDrag(
opts: AttachPlanWallHandleDragOptions,
): () => void {
const {
dom,
scene,
camera,
getFloorBounds,
getWall,
updateWallSegment,
minLength = 0.12,
} = opts
const el = dom.querySelector('canvas')
if (!(el instanceof HTMLCanvasElement)) {
return () => {}
}
const canvas = el
const plane = new THREE.Plane(new THREE.Vector3(0, 1, 0), 0)
const raycaster = new THREE.Raycaster()
const hit = new THREE.Vector3()
const ndc = new THREE.Vector2()
let drag: DragState | null = null
function clampOnFloor(x: number, z: number): { x: number; z: number } {
const { width, depth } = getFloorBounds()
return {
x: Math.min(width, Math.max(0, x)),
z: Math.min(depth, Math.max(0, z)),
}
}
function ndcFromPointer(e: PointerEvent): void {
const rect = canvas.getBoundingClientRect()
const rw = Math.max(1, rect.width)
const rh = Math.max(1, rect.height)
ndc.x = ((e.clientX - rect.left) / rw) * 2 - 1
ndc.y = -((e.clientY - rect.top) / rh) * 2 + 1
}
function pickHandle(
e: PointerEvent,
): { mesh: THREE.Mesh; wallId: string; kind: 'start' | 'end' } | null {
ndcFromPointer(e)
raycaster.setFromCamera(ndc, camera)
const group = scene.getObjectByName(HANDLES_GROUP)
if (!group || group.children.length === 0) {
return null
}
const hits = raycaster.intersectObjects(group.children as THREE.Object3D[], false)
const h = hits[0]
if (!h || !(h.object instanceof THREE.Mesh)) {
return null
}
const mesh = h.object
if (
mesh.userData.isWallEndpointHandle !== true ||
(mesh.userData.handleKind !== 'start' &&
mesh.userData.handleKind !== 'end') ||
typeof mesh.userData.wallId !== 'string'
) {
return null
}
return {
mesh,
wallId: mesh.userData.wallId,
kind: mesh.userData.handleKind,
}
}
function adjustMoving(
fixed: { x: number; z: number },
raw: { x: number; z: number },
shift: boolean,
): { x: number; z: number } {
const o = shift ? snapWallEndToAxis(fixed, raw) : raw
return clampOnFloor(o.x, o.z)
}
function onDownCapture(e: PointerEvent): void {
if (e.button !== 0) {
return
}
const picked = pickHandle(e)
if (!picked) {
return
}
const wall = getWall(picked.wallId)
if (!wall) {
return
}
const fixed =
picked.kind === 'start'
? { x: wall.end.x, z: wall.end.z }
: { x: wall.start.x, z: wall.start.z }
const cur =
picked.kind === 'start'
? { x: wall.start.x, z: wall.start.z }
: { x: wall.end.x, z: wall.end.z }
drag = {
wallId: picked.wallId,
kind: picked.kind,
fixed,
mesh: picked.mesh,
pointerId: e.pointerId,
last: cur,
}
e.stopImmediatePropagation()
canvas.setPointerCapture(e.pointerId)
}
function onMove(e: PointerEvent): void {
if (!drag || e.pointerId !== drag.pointerId) {
return
}
ndcFromPointer(e)
raycaster.setFromCamera(ndc, camera)
const out = raycaster.ray.intersectPlane(plane, hit)
if (!out) {
return
}
const raw = clampOnFloor(hit.x, hit.z)
const moved = adjustMoving(drag.fixed, raw, e.shiftKey)
drag.last = moved
drag.mesh.position.set(moved.x, 0.14, moved.z)
}
function finish(e: PointerEvent): void {
if (!drag || e.pointerId !== drag.pointerId) {
return
}
try {
canvas.releasePointerCapture(e.pointerId)
} catch {
/* ignore */
}
const { wallId, kind, fixed, last, mesh: handleMesh } = drag
drag = null
const newStart =
kind === 'start' ? { x: last.x, z: last.z } : { x: fixed.x, z: fixed.z }
const newEnd =
kind === 'end' ? { x: last.x, z: last.z } : { x: fixed.x, z: fixed.z }
const dx = newEnd.x - newStart.x
const dz = newEnd.z - newStart.z
if (Math.hypot(dx, dz) < minLength) {
const wall = getWall(wallId)
if (wall) {
const pos = kind === 'start' ? wall.start : wall.end
handleMesh.position.set(pos.x, 0.14, pos.z)
}
return
}
updateWallSegment(wallId, { start: newStart, end: newEnd })
}
canvas.addEventListener('pointerdown', onDownCapture, true)
canvas.addEventListener('pointermove', onMove)
canvas.addEventListener('pointerup', finish)
canvas.addEventListener('pointercancel', finish)
return () => {
canvas.removeEventListener('pointerdown', onDownCapture, true)
canvas.removeEventListener('pointermove', onMove)
canvas.removeEventListener('pointerup', finish)
canvas.removeEventListener('pointercancel', finish)
drag = null
}
}7.3 src/components/Main/GalleryView.tsx
- 接入
attachPlanWallHandleDrag和syncPlanWallHandles方法
八、实现展品(占位方块)阶段
8.1 src/components/Main/gallery-3d-pick.ts
- 修改
attachGallery3dWallPick方法
8.2 src/components/Main/gallery-sync.ts
- 同步选项修改
8.3 src/components/Main/GalleryView.tsx
8.4 src/components/Main/plan-wall-draw.ts
pickExhibitId根据鼠标点击位置拾取展品ID,若点击位置未命中展品则返回null。