0
点赞
收藏
分享

微信扫一扫

Three.js获取物体交并集创建新的几何图形


Three.js获取物体交并集创建新的几何图形_并集

THREE.js 终于有个靠谱的CSG运算库了
网上大量的使用 ​​​threeBSP​​​库的文章但是这个库已经不维护多年 其使用的​​THREE.Geometry​​​早已被删除改用​​THREE.BufferGeometry​​无法在新版本中使用

目前有几个可用的库有以下几个

  • ​​THREE-CSGMesh​​
  • ​​csg.js​​
  • ​​OctreeCSG​​

展示最近开源的库 ​​OctreeCSG​​ 的用法

步骤

  1. 根据Mesh生成八叉树结构
  2. 结构之间进行并集/补集操作
  3. 将八叉树结构转换成THREE.BufferGeomerty
  • 不限于两两运算可以数组运算

引入文件 目前为止像threeBSP这几个库都有一个共同点没发布npm需要手动引入文件

Three.js获取物体交并集创建新的几何图形_three.js_02


下载源文件放到项目中

import OctreeCSG from "../OctreeCSG/OctreeCSG";

简单封装一个函数

type csgOperationsType = "union" | "subtract" | "intersect";

/**
* @description: 构造立体几何
* @param {THREE.Mesh} mesh1
* @param {THREE.Mesh} mesh2
* @param {csgOperationsType} operation "union" | "subtract" | "intersect"
* @return {THREE.BufferGeometry}
*/
function ConstructiveSolidGeometry(
mesh1: THREE.Mesh,
mesh2: THREE.Mesh,
operation: csgOperationsType
) {
const mesh1Octree = OctreeCSG.fromMesh(mesh1);
const mesh2Octree = OctreeCSG.fromMesh(mesh2);
const resultOctree = OctreeCSG[operation](
mesh1Octree.clone(),
mesh2Octree.clone(),
false
);
const resultGeom = OctreeCSG.toGeometry(resultOctree);
return resultGeom;THREE.BufferGeometry
}

使用

const box = new THREE.Mesh(
new THREE.BoxGeometry(1, 1, 1),
new THREE.MeshLambertMaterial({ color: 0xff11ff })
);
;
const yellowBox = new THREE.Mesh(
new THREE.BoxGeometry(1, 1, 1),
new THREE.MeshLambertMaterial({ color: 0xffff00 })
);
yellowBox.position.set(0.5,-0.5,0.5);
scene.add(box,yellowBox)

据两个盒子生成新的几何体

const unionMesh = new THREE.Mesh(
ConstructiveSolidGeometry(box, yellowBox, "union"),
new THREE.MeshStandardMaterial({
color: 0xffaa44,
})
);
unionMesh.position.set(-2, 0, 2);
scene.add(unionMesh);


举报

相关推荐

0 条评论