webgl_decals

ThreeJS 官方案例学习(webgl_decals)

1.效果图

在这里插入图片描述

2.源码

<template>
	<div>
		<div id="container"></div>
	</div>
</template>
<script>
// 光线投射相关代码 https://threejs.org/docs/index.html#api/zh/core/Raycaster
import * as THREE from 'three';
// 导入控制器
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';
// 引入房间环境,创建一个室内环境
import { RoomEnvironment } from 'three/examples/jsm/environments/RoomEnvironment.js';
// 导入性能监视器
import Stats from 'three/examples/jsm/libs/stats.module.js';
// 导入gltf载入库、模型加载器
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader'
// 引入模型解压器
import { DRACOLoader } from 'three/examples/jsm/loaders/DRACOLoader'
// 引入贴花几何体
import { DecalGeometry } from 'three/examples/jsm/geometries/DecalGeometry.js';
//GUI界面
import { GUI } from 'three/examples/jsm/libs/lil-gui.module.min.js';
import gsap from 'gsap';
export default {
	data() {
		return {
			container: null, //界面需要渲染的容器
			scene: null,	// 场景对象
			camera: null, //相机对象
			renderer: null, //渲染器对象
			controller: null,	// 相机控件对象
			stats: null,// 性能监听器
			mixer: null,//动画混合器
			mesh: null,//导入的模型
			gui: null,//GUI界面
			clock: new THREE.Clock(),// 创建一个clock对象,用于跟踪时间
			raycaster: new THREE.Raycaster(),//光线投射,用于进行鼠标拾取(在三维空间中计算出鼠标移过了什么物体)
			params: null,
			intersection: {
				intersects: false,//是否存在相交的点
				point: new THREE.Vector3(),//相交部分的点(世界坐标)的坐标
				normal: new THREE.Vector3()//相交的面
			},
			mouse: new THREE.Vector2(),//创建鼠标位置。创建一个二维向量为后面 Raycaster 实例调用 .setFromCamera 方法做准备
			intersects: [],//物体和射线的焦点(光线投射与鼠标拾取时相交的物体数组)
			mouseHelper: null,//鼠标定位帮助器
			line: null,//鼠标定位帮助线条
			position: new THREE.Vector3(),//贴花投影器的位置
			orientation: new THREE.Euler(),//贴花投影器的朝向
			size: new THREE.Vector3(10, 10, 10),// 贴花投影器的尺寸
			decals: [],//点击时创建的贴花几何体集合
		};
	},
	mounted() {
		// gui参数(贴花参数)
		this.params = {
			minScale: 10,//最大缩放值
			maxScale: 20,//最小缩放值
			rotate: true,//贴花是否旋转
			clear: () => {
				this.removeDecals();
			}
		}
		this.init()
		this.animate()  //如果引入了模型并存在动画,可在模型引入成功后加载动画
		window.addEventListener("resize", this.onWindowSize)
		let moved = false;//判断是否移动状态
		// controller 控制器存在操作时(物体处于移动中时),moved置为true,不进行相关操作
		this.controller.addEventListener('change', () => { moved = true; });
		window.addEventListener("pointerdown", () => { moved = false })
		window.addEventListener("pointerup", (event) => {
			if (moved === false) {
				this.checkIntersection(event.clientX, event.clientY)
				if (this.intersection.intersects) this.shoot()
			}
		})

		window.addEventListener('pointermove', this.onPointerMove);
	},
	beforeUnmount() {
		console.log('beforeUnmount===============');
		// 组件销毁时置空
		this.container = null
		this.scene = null
		this.camera = null
		this.renderer = null
		this.controller = null
		this.stats = null
		this.mixer = null
		this.model = null//导入的模型
	},
	methods: {
		/**
		* @description 初始化
		 */
		init() {
			this.container = document.getElementById('container')
			this.setScene()
			this.setCamera()
			this.setRenderer()
			this.setController()
			this.addHelper()
			// this.setPMREMGenerator()
			this.setLight()
			this.setGltfLoader()
			this.addStatus()
		},
		/**
		 * @description 创建场景
		 */
		setScene() {
			// 创建场景对象Scene
			this.scene = new THREE.Scene()
			// 设置场景背景
			// this.scene.background = new THREE.Color(0xbfe3dd);
		},
		/**
		 * @description 创建相机
		*/
		setCamera() {
			// 第二参数就是 长度和宽度比 默认采用浏览器  返回以像素为单位的窗口的内部宽度和高度
			this.camera = new THREE.PerspectiveCamera(60, this.container.clientWidth / this.container.clientHeight, 1, 1000)
			// 设置相机位置
			this.camera.position.z = 120
			// 设置摄像头宽高比例
			this.camera.aspect = this.container.clientWidth / this.container.clientHeight;
			// 设置摄像头投影矩阵
			this.camera.updateProjectionMatrix();
			// 设置相机视线方向
			this.camera.lookAt(new THREE.Vector3(0, 0, 0))// 0, 0, 0 this.scene.position
			// 将相机加入场景
			this.scene.add(this.camera)
		},
		/**
		 * @description 创建渲染器
		 */
		setRenderer() {
			// 初始化渲染器
			this.renderer = new THREE.WebGLRenderer({
				antialias: true,// 设置抗锯齿
				// logarithmicDepthBuffer: true,  // 是否使用对数深度缓存
			})
			// 设置渲染器宽高
			this.renderer.setSize(this.container.clientWidth, this.container.clientHeight);
			// 设置渲染器的像素比
			this.renderer.setPixelRatio(window.devicePixelRatio);
			// 是否需要对对象排序
			this.renderer.sortObjects = false;
			// 将渲染器添加到页面
			this.container.appendChild(this.renderer.domElement);
		},
		/**
		 * @description 添加创建控制器
		 */
		setController() {
			this.controller = new OrbitControls(this.camera, this.renderer.domElement);
			// 控制缩放范围
			this.controller.minDistance = 50;
			this.controller.maxDistance = 200;
			//是否开启右键拖拽
			// this.controller.enablePan = false;
			// 阻尼(惯性)
			// this.controller.enableDamping = true; //启用阻尼(惯性)
			// this.controller.dampingFactor = 0.04; //阻尼惯性有多大
			// this.controller.autoRotate = true; //自动围绕目标旋转
			// this.controller.minAzimuthAngle = -Math.PI / 3; //能够水平旋转的角度下限。如果设置,其有效值范围为[-2 * Math.PI,2 * Math.PI],且旋转角度的上限和下限差值小于2 * Math.PI。默认值为无穷大。
			// this.controller.maxAzimuthAngle = Math.PI / 3;//水平旋转的角度上限,其有效值范围为[-2 * Math.PI,2 * Math.PI],默认值为无穷大
			// this.controller.minPolarAngle = 1; //能够垂直旋转的角度的下限,范围是0到Math.PI,其默认值为0。
			// this.controller.maxPolarAngle = Math.PI - 0.1; //能够垂直旋转的角度的上限,范围是0到Math.PI,其默认值为Math.PI。
			// 修改相机的lookAt是不会影响THREE.OrbitControls的target的
			// 由于设置了控制器,因此只能改变控制器的target以改变相机的lookAt方向
			// this.controller.target.set(0, 0.5, 0); //控制器的焦点
		},
		/**
		 * @description 创建辅助坐标轴
		 */
		addHelper() {
			// 模拟相机视锥体的辅助对象
			let helper = new THREE.CameraHelper(this.camera);
			// this.scene.add(helper);
			//创建辅助坐标轴、轴辅助 (每一个轴的长度)
			let axisHelper = new THREE.AxesHelper(150);  // 红线是X轴,绿线是Y轴,蓝线是Z轴
			// this.scene.add(axisHelper)
			// 坐标格辅助对象
			let gridHelper = new THREE.GridHelper(100, 30, 0x2C2C2C, 0x888888);
			// this.scene.add(gridHelper);

			this.mouseHelper = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 10), new THREE.MeshNormalMaterial());
			this.mouseHelper.visible = false;
			this.scene.add(this.mouseHelper);
		},
		/**
		 * @description 给场景添加环境光效果
		 */
		setPMREMGenerator() {
			// 预过滤的Mipmapped辐射环境贴图
			const pmremGenerator = new THREE.PMREMGenerator(this.renderer);
			this.scene.environment = pmremGenerator.fromScene(new RoomEnvironment(this.renderer), 0.04).texture;
		},
		/**
		 * @description 设置光源
		 */
		setLight() {
			// 环境光
			const ambientLight = new THREE.AmbientLight(0x666666);
			this.scene.add(ambientLight);
			// 平行光
			const dirLight1 = new THREE.DirectionalLight(0xffddcc, 3);
			dirLight1.position.set(1, 0.75, 0.5);
			this.scene.add(dirLight1);

			const dirLight2 = new THREE.DirectionalLight(0xccccff, 3);
			dirLight2.position.set(- 1, 0.75, - 0.5);
			this.scene.add(dirLight2);
		},
		/**
		 * @description 创建性能监听器
		*/
		addStatus() {
			// 创建一个性能监听器
			this.stats = new Stats();
			// 将性能监听器添加到容器中
			this.container.appendChild(this.stats.dom);
		},
		/**
		* @description 添加创建模型
		*/
		setGltfLoader() {
			let that = this
			// 实例化gltf载入库
			const loader = new GLTFLoader();
			// 实例化draco载入库
			const dracoLoader = new DRACOLoader();
			// 添加draco载入库
			dracoLoader.setDecoderPath("/draco/gltf/");
			// 添加draco载入库
			loader.setDRACOLoader(dracoLoader);

			//创建鼠标定位帮助线条
			const geometry = new THREE.BufferGeometry();
			geometry.setFromPoints([new THREE.Vector3(), new THREE.Vector3()]);
			this.line = new THREE.Line(geometry, new THREE.LineBasicMaterial());
			this.scene.add(this.line);


			// 添加模型
			const textureLoader = new THREE.TextureLoader()//纹理贴图加载器
			const map = textureLoader.load(require("../../../public/model/gltf/LeePerrySmith/Map-COL.jpg"));
			map.colorSpace = THREE.SRGBColorSpace;
			const specularMap = textureLoader.load('../../../public/models/gltf/LeePerrySmith/Map-SPEC.jpg');
			const normalMap = textureLoader.load('../../../public/models/gltf/LeePerrySmith/Infinite-Level_02_Tangent_SmoothUV.jpg');
			loader.load('/model/gltf/LeePerrySmith/LeePerrySmith.glb', (gltf) => {
				that.mesh = gltf.scene.children[0];
				that.mesh.material = new THREE.MeshPhongMaterial({
					specular: 0x111111,//材质的高光颜色
					map: map,//颜色贴图
					specularMap: specularMap,//镜面反射贴图
					// normalMap: normalMap,//法线贴图的纹理
					shininess: 25,//高亮的程度
				});
				that.scene.add(that.mesh)
				that.mesh.scale.set(10, 10, 10)
			}, undefined, (err => {
				console.error(err)
			}))


			const gui = new GUI();
			gui.add(this.params, 'minScale', 1, 30);
			gui.add(this.params, 'maxScale', 1, 30);
			gui.add(this.params, 'rotate');
			gui.add(this.params, 'clear');
			gui.open();
		},
		/**
		* @description pointermove 窗口事件
		*/
		onPointerMove(event) {
			if (event.isPrimary) {
				this.checkIntersection(event.clientX, event.clientY);
			}
		},
		/**
		* @description 计算物体和射线之间的焦点
		*/
		// 光线投射相关代码 https://threejs.org/docs/index.html#api/zh/core/Raycaster
		checkIntersection(x, y) {
			if (this.mesh === undefined) return
			// 将鼠标位置归一化为设备坐标。x 和 y 方向的取值范围是 (-1 to +1)
			this.mouse.x = (x / window.innerWidth) * 2 - 1;
			this.mouse.y = - (y / window.innerHeight) * 2 + 1;
			// 通过摄像机和鼠标位置更新射线
			this.raycaster.setFromCamera(this.mouse, this.camera);
			// 检测所有在射线与物体之间,包括或不包括后代的相交部分。返回结果时,相交部分将按距离进行排序,最近的位于第一个。
			// intersectObjec()第三个参数 - 结果的目标数组, 如果设置了这个值,则在每次调用之前必须清空这个数组(例如:array.length = 0;)
			this.raycaster.intersectObject(this.mesh, false, this.intersects);
			// 如果存在相交点
			if (this.intersects.length > 0) {
				const p = this.intersects[0].point//相交部分的点(世界坐标)
				this.mouseHelper.position.copy(p);
				this.intersection.point.copy(p);

				const n = this.intersects[0].face.normal.clone();//相交的面
				n.transformDirection(this.mesh.matrixWorld);
				n.multiplyScalar(10);
				n.add(this.intersects[0].point);

				this.intersection.normal.copy(this.intersects[0].face.normal);
				this.mouseHelper.lookAt(n);

				// 设置line焦点
				const positions = this.line.geometry.attributes.position;
				positions.setXYZ(0, p.x, p.y, p.z);
				positions.setXYZ(1, n.x, n.y, n.z);
				positions.needsUpdate = true;

				this.intersection.intersects = true;
				//intersectObjec() 清空数组
				this.intersects.length = 0;
			} else {
				this.intersection.intersects = false;
			}
		},
		/**
		* @description 创建贴花几何体
		*/
		shoot() {
			// 设置贴花几何体的位置、朝向、尺寸
			this.position.copy(this.intersection.point);
			this.orientation.copy(this.mouseHelper.rotation);
			if (this.params.rotate) this.orientation.z = Math.random() * 2 * Math.PI;
			const scale = this.params.minScale + Math.random() * (this.params.maxScale - this.params.minScale);
			this.size.set(scale, scale, scale);

			// 加载纹理贴图
			const textureLoader = new THREE.TextureLoader()//纹理贴图加载器
			const decalDiffuse = textureLoader.load('/textures/decal/decal-diffuse.png');
			decalDiffuse.colorSpace = THREE.SRGBColorSpace;
			const decalNormal = textureLoader.load('/textures/decal/decal-normal.jpg');

			// 设置贴花几何体材质
			const decalMaterial = new THREE.MeshPhongMaterial({
				specular: 0x444444,//材质的高光颜色
				map: decalDiffuse,//颜色贴图
				normalMap: decalNormal,//法线贴图的纹理
				normalScale: new THREE.Vector2(1, 1),//法线贴图对材质的影响程度
				shininess: 30,//高亮的程度
				transparent: true,//材质是否透明,存在map时为true
				depthTest: true,//是否在渲染此材质时启用深度测试
				depthWrite: false,//渲染此材质是否对深度缓冲区有任何影响
				polygonOffset: true,//是否使用多边形偏移
				polygonOffsetFactor: - 4,//多边形偏移系数
				wireframe: false,//渲染为平面多边形
			});
			const material = decalMaterial.clone();
			//设置随机颜色
			material.color.setHex(Math.random() * 0xffffff);
			// 引入贴花物体 DecalGeometry - 贴花几何体
			const m = new THREE.Mesh(new DecalGeometry(this.mesh, this.position, this.orientation, this.size), material);
			// 创建贴花几何体集合数组
			this.decals.push(m);
			// 在场景中添加贴花
			this.scene.add(m);
		},
		/**
		* @description 清除贴花几何体集合
		*/
		removeDecals() {
			this.decals.forEach((d) => {
				this.scene.remove(d);
			});
			this.decals.length = 0;
		},
		/**
		 * @description 监听屏幕的大小改变,修改渲染器的宽高,相机的比例
		*/
		// 窗口变化
		onWindowSize() {
			// 更新摄像头
			this.camera.aspect = this.container.clientWidth / this.container.clientHeight;
			// 更新摄像机的投影矩阵
			this.camera.updateProjectionMatrix();
			//更新渲染器
			this.renderer.setSize(this.container.clientWidth, this.container.clientHeight);
			// 设置渲染器的像素比
			this.renderer.setPixelRatio(window.devicePixelRatio)
		},
		/**
		* @description 动画执行函数
		*/
		animate() {
			const delta = this.clock.getDelta();
			// 引擎自动更新渲染器
			requestAnimationFrame(this.animate);
			//update()函数内会执行camera.lookAt(x, y, z)
			this.controller.update(delta);
			// 更新性能监听器
			this.stats.update();
			// 重新渲染场景
			this.renderer.render(this.scene, this.camera);
		},
	},
};
</script>
<style>
#container {
	position: absolute;
	width: 100%;
	height: 100%;
}
</style>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值