SKILL.md
只读
名称
threejs-geometry
描述
Three.js 几何体创建 - 内置形状、BufferGeometry、自定义几何体、实例化。适用于创建 3D 形状、处理顶点、构建自定义网格,或通过实例化渲染进行性能优化。
Three.js 几何体(Geometry)
快速开始
import * as THREE from "three";
// 内置几何体
const box = new THREE.BoxGeometry(1, 1, 1);
const sphere = new THREE.SphereGeometry(0.5, 32, 32);
const plane = new THREE.PlaneGeometry(10, 10);
// 创建网格
const material = new THREE.MeshStandardMaterial({ color: 0x00ff00 });
const mesh = new THREE.Mesh(box, material);
scene.add(mesh);
内置几何体
基础形状
// 立方体 (Box) - width, height, depth, widthSegments, heightSegments, depthSegments
new THREE.BoxGeometry(1, 1, 1, 1, 1, 1);
// 球体 (Sphere) - radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength
new THREE.SphereGeometry(1, 32, 32);
new THREE.SphereGeometry(1, 32, 32, 0, Math.PI * 2, 0, Math.PI); // 完整球体
new THREE.SphereGeometry(1, 32, 32, 0, Math.PI); // 半球体
// 平面 (Plane) - width, height, widthSegments, heightSegments
new THREE.PlaneGeometry(10, 10, 1, 1);
// 圆形 (Circle) - radius, segments, thetaStart, thetaLength
new THREE.CircleGeometry(1, 32);
new THREE.CircleGeometry(1, 32, 0, Math.PI); // 半圆
// 圆柱体 (Cylinder) - radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded
new THREE.CylinderGeometry(1, 1, 2, 32, 1, false);
new THREE.CylinderGeometry(0, 1, 2, 32); // 圆锥体
new THREE.CylinderGeometry(1, 1, 2, 6); // 六角柱
// 圆锥体 (Cone) - radius, height, radialSegments, heightSegments, openEnded
new THREE.ConeGeometry(1, 2, 32, 1, false);
// 圆环体 (Torus) - radius, tube, radialSegments, tubularSegments, arc
new THREE.TorusGeometry(1, 0.4, 16, 100);
// 扭结圆环体 (TorusKnot) - radius, tube, tubularSegments, radialSegments, p, q
new THREE.TorusKnotGeometry(1, 0.4, 100, 16, 2, 3);
// 环形 (Ring) - innerRadius, outerRadius, thetaSegments, phiSegments
new THREE.RingGeometry(0.5, 1, 32, 1);
进阶形状
// 胶囊体 (Capsule) - radius, length, capSegments, radialSegments
new THREE.CapsuleGeometry(0.5, 1, 4, 8);
// 十二面体 (Dodecahedron) - radius, detail
new THREE.DodecahedronGeometry(1, 0);
// 二十面体 (Icosahedron) - radius, detail(0 = 20 个面,数值越高越平滑)
new THREE.IcosahedronGeometry(1, 0);
// 八面体 (Octahedron) - radius, detail
new THREE.OctahedronGeometry(1, 0);
// 四面体 (Tetrahedron) - radius, detail
new THREE.TetrahedronGeometry(1, 0);
// 多面体 (Polyhedron) - vertices, indices, radius, detail
const vertices = [1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1];
const indices = [2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1];
new THREE.PolyhedronGeometry(vertices, indices, 1, 0);
基于路径的形状
// 旋转成型 (Lathe) - points[], segments, phiStart, phiLength
const points = [
new THREE.Vector2(0, 0),
new THREE.Vector2(0.5, 0),
new THREE.Vector2(0.5, 1),
new THREE.Vector2(0, 1),
];
new THREE.LatheGeometry(points, 32);
// 挤压成型 (Extrude) - shape, options
const shape = new THREE.Shape();
shape.moveTo(0, 0);
shape.lineTo(1, 0);
shape.lineTo(1, 1);
shape.lineTo(0, 1);
shape.lineTo(0, 0);
const extrudeSettings = {
steps: 2,
depth: 1,
bevelEnabled: true,
bevelThickness: 0.1,
bevelSize: 0.1,
bevelSegments: 3,
};
new THREE.ExtrudeGeometry(shape, extrudeSettings);
// 管道 (Tube) - path, tubularSegments, radius, radialSegments, closed
const curve = new THREE.CatmullRomCurve3([
new THREE.Vector3(-1, 0, 0),
new THREE.Vector3(0, 1, 0),
new THREE.Vector3(1, 0, 0),
]);
new THREE.TubeGeometry(curve, 64, 0.2, 8, false);
文本几何体
import { FontLoader } from "three/examples/jsm/loaders/FontLoader.js";
import { TextGeometry } from "three/examples/jsm/geometries/TextGeometry.js";
const loader = new FontLoader();
loader.load("fonts/helvetiker_regular.typeface.json", (font) => {
const geometry = new TextGeometry("Hello", {
font: font,
size: 1,
depth: 0.2, // 旧版本中为 'height'
curveSegments: 12,
bevelEnabled: true,
bevelThickness: 0.03,
bevelSize: 0.02,
bevelSegments: 5,
});
// 文本居中
geometry.computeBoundingBox();
geometry.center();
const mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);
});
BufferGeometry
所有几何体的基类。将数据存储为类型化数组(Typed Arrays),以便提高 GPU 执行效率。
自定义 BufferGeometry
const geometry = new THREE.BufferGeometry();
// 顶点数据(每个顶点 3 个浮点数:x, y, z)
const vertices = new Float32Array([
-1,
-1,
0, // 顶点 0
1,
-1,
0, // 顶点 1
1,
1,
0, // 顶点 2
-1,
1,
0, // 顶点 3
]);
geometry.setAttribute("position", new THREE.BufferAttribute(vertices, 3));
// 索引数据(用于索引几何体 - 复用顶点)
const indices = new Uint16Array([
0,
1,
2, // 三角形 1
0,
2,
3, // 三角形 2
]);
geometry.setIndex(new THREE.BufferAttribute(indices, 1));
// 法线数据(计算光照所需)
const normals = new Float32Array([0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1]);
geometry.setAttribute("normal", new THREE.BufferAttribute(normals, 3));
// UV 数据(用于贴图)
const uvs = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
geometry.setAttribute("uv", new THREE.BufferAttribute(uvs, 2));
// 颜色数据(逐顶点颜色)
const colors = new Float32Array([
1,
0,
0, // 红色
0,
1,
0, // 绿色
0,
0,
1, // 蓝色
1,
1,
0, // 黄色
]);
geometry.setAttribute("color", new THREE.BufferAttribute(colors, 3));
// 搭配使用:material.vertexColors = true
BufferAttribute 类型
// 常见的属性类型
new THREE.BufferAttribute(array, itemSize);
// 类型化数组选项
new Float32Array(count * itemSize); // 位置、法线、UV
new Uint16Array(count); // 索引(最多 65535 个顶点)
new Uint32Array(count); // 索引(大型网格)
new Uint8Array(count * itemSize); // 颜色(0-255 范围)
// 项目大小 (Item Size)
// 位置 (Position): 3 (x, y, z)
// 法线 (Normal): 3 (x, y, z)
// UV: 2 (u, v)
// 颜色 (Color): 3 (r, g, b) 或 4 (r, g, b, a)
// 索引 (Index): 1
修改 BufferGeometry
const positions = geometry.attributes.position;
// 修改顶点
positions.setXYZ(index, x, y, z);
// 读取顶点
const x = positions.getX(index);
const y = positions.getY(index);
const z = positions.getZ(index);
// 标记需要更新到 GPU
positions.needsUpdate = true;
// 修改位置后重新计算法线
geometry.computeVertexNormals();
// 修改后重新计算包围盒/包围球
geometry.computeBoundingBox();
geometry.computeBoundingSphere();
交错缓冲区 Interleaved Buffers(高级)
// 适用于大型网格的更高效内存布局
const interleavedBuffer = new THREE.InterleavedBuffer(
new Float32Array([
// pos.x, pos.y, pos.z, uv.u, uv.v(每个顶点重复)
-1, -1, 0, 0, 0, 1, -1, 0, 1, 0, 1, 1, 0, 1, 1, -1, 1, 0, 0, 1,
]),
5, // 步长 stride(每个顶点的浮点数数量)
);
geometry.setAttribute(
"position",
new THREE.InterleavedBufferAttribute(interleavedBuffer, 3, 0),
); // 大小为 3,偏移量为 0
geometry.setAttribute(
"uv",
new THREE.InterleavedBufferAttribute(interleavedBuffer, 2, 3),
); // 大小为 2,偏移量为 3
EdgesGeometry 与 WireframeGeometry
// 边缘线(仅硬边缘)
const edges = new THREE.EdgesGeometry(boxGeometry, 15); // 15 = 阈值角度
const edgeMesh = new THREE.LineSegments(
edges,
new THREE.LineBasicMaterial({ color: 0xffffff }),
);
// 线框(所有三角形)
const wireframe = new THREE.WireframeGeometry(boxGeometry);
const wireMesh = new THREE.LineSegments(
wireframe,
new THREE.LineBasicMaterial({ color: 0xffffff }),
);
点云 (Points)
// 创建点云
const geometry = new THREE.BufferGeometry();
const positions = new Float32Array(1000 * 3);
for (let i = 0; i < 1000; i++) {
positions[i * 3] = (Math.random() - 0.5) * 10;
positions[i * 3 + 1] = (Math.random() - 0.5) * 10;
positions[i * 3 + 2] = (Math.random() - 0.5) * 10;
}
geometry.setAttribute("position", new THREE.BufferAttribute(positions, 3));
const material = new THREE.PointsMaterial({
size: 0.1,
sizeAttenuation: true, // 尺寸随距离增加而衰减
color: 0xffffff,
});
const points = new THREE.Points(geometry, material);
scene.add(points);
线条 (Lines)
// 线段 (Line)(连续连接的点)
const points = [
new THREE.Vector3(-1, 0, 0),
new THREE.Vector3(0, 1, 0),
new THREE.Vector3(1, 0, 0),
];
const geometry = new THREE.BufferGeometry().setFromPoints(points);
const line = new THREE.Line(
geometry,
new THREE.LineBasicMaterial({ color: 0xff0000 }),
);
// 闭合线条 (LineLoop)
const loop = new THREE.LineLoop(geometry, material);
// 独立线段 (LineSegments)(每两个点成一条线)
const segmentsGeometry = new THREE.BufferGeometry();
segmentsGeometry.setAttribute(
"position",
new THREE.BufferAttribute(
new Float32Array([
-1,
0,
0,
0,
1,
0, // 线段 1
0,
1,
0,
1,
0,
0, // 线段 2
]),
3,
),
);
const segments = new THREE.LineSegments(segmentsGeometry, material);
实例化网格 (InstancedMesh)
高效渲染同一几何体的多个副本。
const geometry = new THREE.BoxGeometry(1, 1, 1);
const material = new THREE.MeshStandardMaterial({ color: 0x00ff00 });
const count = 1000;
const instancedMesh = new THREE.InstancedMesh(geometry, material, count);
// 为每个实例设置变换矩阵
const dummy = new THREE.Object3D();
const matrix = new THREE.Matrix4();
for (let i = 0; i < count; i++) {
dummy.position.set(
(Math.random() - 0.5) * 20,
(Math.random() - 0.5) * 20,
(Math.random() - 0.5) * 20,
);
dummy.rotation.set(Math.random() * Math.PI, Math.random() * Math.PI, 0);
dummy.scale.setScalar(0.5 + Math.random());
dummy.updateMatrix();
instancedMesh.setMatrixAt(i, dummy.matrix);
}
// 标记需要更新到 GPU
instancedMesh.instanceMatrix.needsUpdate = true;
// 可选:设置单个实例的颜色
instancedMesh.instanceColor = new THREE.InstancedBufferAttribute(
new Float32Array(count * 3),
3,
);
for (let i = 0; i < count; i++) {
instancedMesh.setColorAt(
i,
new THREE.Color(Math.random(), Math.random(), Math.random()),
);
}
instancedMesh.instanceColor.needsUpdate = true;
scene.add(instancedMesh);
运行时更新实例
// 更新单个实例
const matrix = new THREE.Matrix4();
instancedMesh.getMatrixAt(index, matrix);
// 修改矩阵...
instancedMesh.setMatrixAt(index, matrix);
instancedMesh.instanceMatrix.needsUpdate = true;
// InstancedMesh 的光线投射 (Raycasting)
const intersects = raycaster.intersectObject(instancedMesh);
if (intersects.length > 0) {
const instanceId = intersects[0].instanceId;
}
InstancedBufferGeometry(高级)
用于除变换/颜色之外的自定义单实例属性(per-instance attributes)。
const geometry = new THREE.InstancedBufferGeometry();
geometry.copy(new THREE.BoxGeometry(1, 1, 1));
// 添加自定义逐实例属性
const offsets = new Float32Array(count * 3);
for (let i = 0; i < count; i++) {
offsets[i * 3] = Math.random() * 10;
offsets[i * 3 + 1] = Math.random() * 10;
offsets[i * 3 + 2] = Math.random() * 10;
}
geometry.setAttribute("offset", new THREE.InstancedBufferAttribute(offsets, 3));
// 在 着色器 (Shader) 中使用
// attribute vec3 offset;
// vec3 transformed = position + offset;
几何体实用工具 (Geometry Utilities)
import * as BufferGeometryUtils from "three/examples/jsm/utils/BufferGeometryUtils.js";
// 合并几何体(属性必须完全一致)
const merged = BufferGeometryUtils.mergeGeometries([geo1, geo2, geo3]);
// 带分组的合并(适用于多重材质)
const merged = BufferGeometryUtils.mergeGeometries([geo1, geo2], true);
// 计算切线(法线贴图所需)
BufferGeometryUtils.computeTangents(geometry);
// 交错交织属性以获得更好的性能
const interleaved = BufferGeometryUtils.interleaveAttributes([
geometry.attributes.position,
geometry.attributes.normal,
geometry.attributes.uv,
]);
常用模式
几何体居中
geometry.computeBoundingBox();
geometry.center(); // 移动顶点使几何体中心位于原点
缩放至合适尺寸
geometry.computeBoundingBox();
const size = new THREE.Vector3();
geometry.boundingBox.getSize(size);
const maxDim = Math.max(size.x, size.y, size.z);
geometry.scale(1 / maxDim, 1 / maxDim, 1 / maxDim);
克隆与变换
const clone = geometry.clone();
clone.rotateX(Math.PI / 2);
clone.translate(0, 1, 0);
clone.scale(2, 2, 2);
变形目标 (Morph Targets)
// 基础几何体
const geometry = new THREE.BoxGeometry(1, 1, 1, 4, 4, 4);
// 创建变形目标
const morphPositions = geometry.attributes.position.array.slice();
for (let i = 0; i < morphPositions.length; i += 3) {
morphPositions[i] *= 2; // X 轴缩放
morphPositions[i + 1] *= 0.5; // Y 轴压缩
}
geometry.morphAttributes.position = [
new THREE.BufferAttribute(new Float32Array(morphPositions), 3),
];
const mesh = new THREE.Mesh(geometry, material);
mesh.morphTargetInfluences[0] = 0.5; // 50% 混合
性能建议
- 使用索引几何体:通过索引复用顶点
- 合并静态网格:使用
mergeGeometries减少绘制调用 (Draw Calls) - 使用 InstancedMesh:渲染大量相同物体
- 选择合适的细化分段数:分段越多越平滑,但性能开销越大
- 释放不用的几何体内存:
geometry.dispose()
// 常见用途的推荐分段数设置
new THREE.SphereGeometry(1, 32, 32); // 良好画质
new THREE.SphereGeometry(1, 64, 64); // 高画质
new THREE.SphereGeometry(1, 16, 16); // 性能优先模式
// 使用完毕后销毁释放内存
geometry.dispose();
另请参阅
threejs-fundamentals- 场景设置与 Object3Dthreejs-materials- 网格材质类型threejs-shaders- 自定义顶点操作






