Three.js 剖切模型功能封装
1.获取到需要剖切模型的包围盒,并计算每个包围盒的顶点位置,代码如下:
var Box = new THREE.Box3().setFromObject(mesh);
console.log(Box);
var point_max =new THREE.Vector3();
var point_max_right =new THREE.Vector3();
var point_max_behind =new THREE.Vector3();
var point_max_under =new THREE.Vector3();
var point_min =new THREE.Vector3();
var point_min_front =new THREE.Vector3();
var point_min_top =new THREE.Vector3();
var point_min_left =new THREE.Vector3();
point_max.set(Box.max.x,Box.max.y,Box.max.z);
point_max_right.set(Box.min.x,Box.max.y,Box.max.z);
point_max_under.set(Box.max.x,Box.max.y,Box.min.z);
point_max_behind.set(Box.max.x,Box.min.y,Box.max.z);
point_min.set(Box.min.x,Box.min.y,Box.min.z);
point_min_front.set(Box.min.x,Box.max.y,Box.min.z);
point_min_top.set(Box.min.x,Box.min.y,Box.max.z);
point_min_left.set(Box.max.x,Box.min.y,Box.min.z);
2.剖切面可视化,这里以前切面为例,别的切面以此类推,这里的clipping_box_mesh为全局变量。(部分读者不太清楚clipping_box_mesh变量存储的信息,这里解释一下clipping_box_mesh就是一个存储可视化剖切面mesh的全局索引数组方便我后续去拿到其中一个mesh去做一些改动,我这里用数组做收集当然读者也可以用Map;而Get_normal函数返回的是我后续将得到的三角面的法线,传入值是三个顶点:v1,v2,v3, 按照右手定理,得到的面法线 )代码如下:
//前切面可视化
var planeFront=new THREE.Geometry();
planeFront.name='front';
planeFront.vertices.push(point_max,point_max_right,point_min_front,point_max_under);
var planeFront_normal=Get_normal(point_max,point_min_front,,point_max_under);
var planeFront_face1=new THREE.Face3(0,1,2, planeFront_normal);
var planeFront_face2=new THREE.Face3(2,3,0, planeFront_normal);
planeFront.faces.push(planeFront_face1,planeFront_face2);
var planeFront_material=new THREE.MeshBasicMaterial({
color:0x00BFFF,
side:THREE.DoubleSide,
opacity: 0.2,
transparent: true
});
var planeFront_mesh= new THREE.Mesh(planeFront,planeFront_material);
clipping_box_mesh.push(planeFront_mesh);
scene.add(planeFront_mesh);
3.对应可视化切面的真实切面,以前切面为例,记得打开剖切的局部效果:
//对应前剖面
clipping_localPlane[0] = new THREE.Plane( new THREE.Vector3( 0, -1, 0 ),point_max.y );renderer.localClippingEnabled = true; //剖切局部效果
4.绑定需要切面的mesh,以及对各个可视化切面的自身的剖切。代码如下:
mesh.traverse(function (child) {
if (child.isMesh)
{
child.material.clippingPlanes=clipping_localPlane;
child.material.side=THREE.DoubleSide;
}
});
for(var i=0;i<clipping_box_mesh.length;i++){
var array_clipping=new Array();
for(var j=0;j<clipping_box_mesh.length;j++) {
if (i != j) {
array_clipping.push(clipping_localPlane[j])
}
}
clipping_box_mesh[i].material.clippingPlanes=array_clipping;
}
6.效果展示
更多推荐
所有评论(0)