three.js 05-03 之 ShapeGeometry 几何体

    本篇我们来介绍 ShapeGeometry 几何体。通过前两篇的介绍,我们会发现 PlaneGeometry 和 CircleGeometry 都只有有限的方法来定制他们的外观。如果我们想创建一个自定义的二维图形,那么就只能依靠今天要讲的 ShapeGeometry 了。

    为了使用 ShapeGeometry,我们首先需要通过 THREE.Shape 创建一个自定义的基本形状,然后把它作为参数传递给 ShapeGeometry 构造函数。因此,我们先来看看如何使用 THREE.Shape 创建自定义的基本形状,代码片段如下:

function drawShape() {
	var shape = new THREE.Shape();
	
	shape.moveTo(10, 10); // moveTo( x, y )
	shape.lineTo(10, 40); // lineTo( x, y ) - 线
	shape.bezierCurveTo(15, 25, 25, 25, 30, 40); // bezierCurveTo( cp1X, cp1Y, cp2X, cp2Y, x, y ) - 贝塞尔曲线
	shape.splineThru([
		new THREE.Vector2(32, 30),
		new THREE.Vector2(28, 20),
		new THREE.Vector2(30, 10)
	]); // splineThru ( vector2Array ) - 样条线
	shape.quadraticCurveTo(20, 15, 10, 10); // quadraticCurveTo( cpX, cpY, x, y ) - 二次曲线
	
	var hole = new THREE.Path(); // 添加“眼睛”孔洞1
	hole.absellipse(16, 24, 2, 3, 0, Math.PI * 2, false);
	shape.holes.push(hole);
	
	hole = new THREE.Path(); // 添加“眼睛”孔洞2
	hole.absellipse(23, 24, 2, 3, 0, Math.PI * 2, false);
	shape.holes.push(hole);
	
	hole = new THREE.Path(); // 添加“嘴巴”孔洞
	hole.absarc(20, 16, 2, 0, Math.PI, false);
	shape.holes.push(hole);
	
	return shape;
}
在这段代码里,你可以看到我们用线段(line)、曲线(curve)和样条线(spline)创建出图像的轮廓,然后用 THREE.Shape 类的 holes(孔洞)属性添加了几个洞(两只眼睛,一张嘴巴)。下表列出了 THREE.Shape 类用来创建图形的绘图函数:

函数名 描述
moveTo(x, y) 将绘图点移动到指定的 x、y 座标处
lineTo(x, y) 从当前位置(例如 moveTo 设定的位置)画一条线到指定的 x、y 座标处
quadricCurveTo(cpx, cpy, x, y)
(二次曲线)
此函数为二次曲线。你可以使用两种方法来画曲线:quadricCurveTo 或者 bezierCurveTo。这两种曲线的不同之处在于指定曲线曲率的方法不一样,如下图所示:

对于二次曲线,除了指定结束点(x, y)外,还需要额外指定一个点(cpx, cpy)来控制曲线的曲率(不用指定起始点,因为路径的当前位置就是起始点);
对于三次曲线,除了指定结束点(x, y)外,还需要额外指定两个点(cpx1, cpy1, cpx2, cpy2)来控制曲线的曲率。
bezierCurveTo(cpx1, cpy1, cpx2, cpy2, x, y)
(贝塞尔曲线)
此函数为三次曲线。相关说明参考上一行的二次曲线。
splineThru(vector2Array) 此函数沿着参数指定的座标集合绘制一条光滑的样条曲线。其参数为一个 THREE.Vector2 对象数组。
arc(x, y, radius, startAngle, endAngle, clockwise) 次函数绘制一个圆或者一段弧。x, y 用来指定圆心与当前位置的偏移量。radius 设定圆的大小。而 startAngle 及 endAngle 则用来定义圆弧要画多长。布尔属性 clockwise 决定这段弧是顺时针画还是逆时针画。
absArc(x, y, radius, startAngle, endAngle, clockwise) 参考 arc 函数。只不过其指定的圆心位置是绝对位置,而不是相对当前位置的偏移量。
ellipse(x, y, radiusX, radiusY, startAngle, endAngle, clockwise) 参考 arc 函数。只是椭圆可以分别指定 x 轴半径及 y 轴半径。
absEllipse(x, y, radiusX, radiusY, startAngle, endAngle, clockwise) 参考 ellipse 函数。只不过其指定的圆心位置是绝对位置,而不是相对当前位置的偏移量。
另外一个需要说明的是 THREE.Shape 对象属性 holes(孔洞)。通过向其添加 THREE.Shape 对象,你可以在图形中打几个孔洞(例如上面代码片段中所示的眼睛和嘴巴)。
在继续讨论之前,我们先给出一个完整的示例,代码如下:

<!DOCTYPE html>
<html>
<head>
    <title>示例 05.03 - ShapeGeometry</title>
	<script src="../build/three.js"></script>
	<script src="../build/js/controls/OrbitControls.js"></script>
	<script src="../build/js/libs/stats.min.js"></script>
	<script src="../build/js/libs/dat.gui.min.js"></script>
	<script src="../jquery/jquery-3.2.1.min.js"></script>
    <style>
        body {
            /* 设置 margin 为 0,并且 overflow 为 hidden,来完成页面样式 */
            margin: 0;
            overflow: hidden;
        }
		/* 统计对象的样式 */
		#Stats-output {
			position: absolute;
			left: 0px;
			top: 0px;
		}
    </style>
</head>
<body>

<!-- 用于 WebGL 输出的 Div -->
<div id="webgl-output"></div>
<!-- 用于统计 FPS 输出的 Div -->
<div id="stats-output"></div>

<!-- 运行 Three.js 示例的 Javascript 代码 -->
<script type="text/javascript">

	var scene;
	var camera;
	var render;
	var webglRender;
	//var canvasRender;
	var controls;
	var stats;
	var guiParams;
	
	var ground;
	//var cube;
	//var sphere;
	var plane;
	
	var meshMaterial;
	
	var ambientLight;
	var spotLight;
	//var cameraHelper;

    $(function() {
		stats = initStats();
		scene = new THREE.Scene();
		
		webglRender = new THREE.WebGLRenderer( {antialias: true, alpha: true} ); // antialias 抗锯齿
		webglRender.setSize(window.innerWidth, window.innerHeight);
		webglRender.setClearColor(0xeeeeee, 1.0);
		webglRender.shadowMap.enabled = true; // 允许阴影投射
		render = webglRender;
		
		camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 30, 1000); // 2147483647
		camera.position.set(-45.5, 68.2, 90.9);
		
		var target = new THREE.Vector3(10, 0 , 0);
		controls = new THREE.OrbitControls(camera, render.domElement);
		controls.target = target;
		camera.lookAt(target);
		
		$('#webgl-output')[0].appendChild(render.domElement);
		window.addEventListener('resize', onWindowResize, false);
		
		ambientLight = new THREE.AmbientLight(0x0c0c0c);
		scene.add(ambientLight);
		
		spotLight = new THREE.SpotLight(0xffffff);
        spotLight.position.set(0, 30, 60);
        spotLight.castShadow = true;
        scene.add(spotLight);
		//cameraHelper = new THREE.CameraHelper(spotLight.shadow.camera);
		//scene.add(cameraHelper);
		
		// 加入一个地面
		var groundGeometry = new THREE.PlaneGeometry(100, 100, 4, 4);
		var groundMaterial = new THREE.MeshBasicMaterial({color: 0x777777});
		ground = new THREE.Mesh(groundGeometry, groundMaterial);
		ground.rotation.set(-0.5 * Math.PI, 0, 0); // 沿着 X轴旋转-90°
		scene.add(ground);
		
		// 定义 shape
		var shape = drawShape();

		// 材质
        meshMaterial = [
			new THREE.MeshNormalMaterial({side: THREE.DoubleSide}),
			new THREE.MeshBasicMaterial({wireframe: true})
		];
		
		/** 用来保存那些需要修改的变量 */
		guiParams = new function() {
			this.rotationSpeed = 0.02;
			
			this.addMesh = function() {
				createMesh(shape);
			};
			this.addPoints = function() {
				createLine(shape, false);
			};
			this.addSpacedPoints = function() {
				createLine(shape, true);
			};
		}
		/** 定义 dat.GUI 对象,并绑定 guiParams 的几个属性 */
		var gui = new dat.GUI();
		gui.add(guiParams, 'addMesh');
		gui.add(guiParams, 'addPoints');
		gui.add(guiParams, 'addSpacedPoints');
		
		guiParams.addMesh();
		
		renderScene();
    });
	
	/** 渲染场景 */
	function renderScene() {
		stats.update();
		rotateMesh(); // 旋转物体
		
		requestAnimationFrame(renderScene);
		render.render(scene, camera);
	}
	
	/** 初始化 stats 统计对象 */
	function initStats() {
		stats = new Stats();
		stats.setMode(0); // 0 为监测 FPS;1 为监测渲染时间
		$('#stats-output').append(stats.domElement);
		return stats;
	}
	
	/** 当浏览器窗口大小变化时触发 */
	function onWindowResize() {
		camera.aspect = window.innerWidth / window.innerHeight;
		camera.updateProjectionMatrix();
		render.setSize(window.innerWidth, window.innerHeight);
	}
	
	/** 旋转物体 */
	var step = 0;
	function rotateMesh() {
		step += guiParams.rotationSpeed;
		scene.traverse(function(mesh) {
			if ((mesh instanceof THREE.Mesh || mesh instanceof THREE.Line) && mesh != ground) {
				//mesh.rotation.x = step;
				mesh.rotation.y = step;
				//mesh.rotation.z = step;
			}
		});
	}
	
	function drawShape() {
		var shape = new THREE.Shape();
		
		shape.moveTo(10, 10); // moveTo( x, y )
		shape.lineTo(10, 40); // lineTo( x, y ) - 线
		shape.bezierCurveTo(15, 25, 25, 25, 30, 40); // bezierCurveTo( cp1X, cp1Y, cp2X, cp2Y, x, y ) - 贝塞尔曲线
		shape.splineThru([
			new THREE.Vector2(32, 30),
			new THREE.Vector2(28, 20),
			new THREE.Vector2(30, 10)
		]); // splineThru ( vector2Array ) - 样条线
		shape.quadraticCurveTo(20, 15, 10, 10); // quadraticCurveTo( cpX, cpY, x, y ) - 二次曲线
		
		var hole = new THREE.Path(); // 添加“眼睛”孔洞1
		hole.absellipse(16, 24, 2, 3, 0, Math.PI * 2, false);
		shape.holes.push(hole);
		
		hole = new THREE.Path(); // 添加“眼睛”孔洞2
		hole.absellipse(23, 24, 2, 3, 0, Math.PI * 2, false);
		shape.holes.push(hole);
		
		hole = new THREE.Path(); // 添加“嘴巴”孔洞
		hole.absarc(20, 16, 2, 0, Math.PI, false);
		shape.holes.push(hole);
		
		return shape;
	}
	
	function createMesh(shape) {
		scene.remove(plane);
		
		var shapeGeometry = new THREE.ShapeGeometry(shape);
		plane = new THREE.SceneUtils.createMultiMaterialObject(shapeGeometry, meshMaterial);
		plane.castShadow = true;
		plane.position.set(0, 0, 0);
		scene.add(plane);
	}

	/** 从已有的 shape 中进行分段再得出新形状 */
	function createLine(shape, spaced) {
		scene.remove(plane);
		
		var newPoints;
		var shapeGeometry;
		if (spaced) {
			newPoints = shape.getSpacedPoints(3); // 把整个 shape 路径当做一个整体进行分段并得到一个点集
		} else {
			newPoints = shape.getPoints(10); // 分别把 shape 中的每一段路径进行分段(此处为 10 段)并得到一个点集
		}
		shapeGeometry = new THREE.Geometry();
		newPoints.forEach(function(vec2){
			shapeGeometry.vertices.push(new THREE.Vector3(vec2.x, vec2.y, 0));
		});
		
		plane = new THREE.Line(shapeGeometry, new THREE.LineBasicMaterial({color: 0xff3333,linewidth: 2}));
		plane.castShadow = true;
		plane.position.set(0, 0, 0);
		scene.add(plane);
	}

</script>
</body>
</html>
这个示例的效果如下所示:


    在这个例子中,右上角有三个按钮,分别是 addMesh、addPoints、addSpacedPoints。其中 addMesh 的功能比较好理解,就是通过传入 shape 参数构造一个 THREE.ShapeGeometry 几何对象,有了这个几何对象后,就可以创建 THREE.Mesh 网格对象了。
    需要特别说明的是另外两个按钮的功能,这两个按钮的功能都类似。主要用到了 THREE.Shape 对象的两个辅助函数 getPoints(divisions) 和 getSpacedPoints(divisions)。下表给出了相关描述:
函数 描述
getPoints( divisions ) 此函数将图形转换成一个点集。参数 divisions(分段数)定义返回点的数目,它会分别应用到 shape 路径的每一个部分。
getSpacedPoints( divisions ) 此函数也是将图形转换成一个点集。参数 divisions(分段数)定义返回点的数目,它会一次性应用到 shape 的整个路径上。
    通过上面两个辅助函数获得新的点集后,我们再通过以下核心代码来创建线段:
shapeGeometry = new THREE.Geometry();
newPoints.forEach(function(vec2){
	shapeGeometry.vertices.push(new THREE.Vector3(vec2.x, vec2.y, 0));
});

plane = new THREE.Line(shapeGeometry, new THREE.LineBasicMaterial({color: 0xff3333,linewidth: 2}));

未完待续···

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章