import * as THREE from 'three'; //导入整个 three.js核心库 import {FBXLoader} from 'three/examples/jsm/loaders/FBXLoader'; import {OrbitControls} from 'three/examples/jsm/controls/OrbitControls'; //导入控制器模块,轨道控制器 import {CSS3DRenderer, CSS3DSprite} from 'three/examples/jsm/renderers/CSS3DRenderer.js'; import {GLTFLoader} from 'three/examples/jsm/loaders/GLTFLoader.js' // 用于模型边缘高亮 import {EffectComposer} from "three/examples/jsm/postprocessing/EffectComposer.js"; import {RenderPass} from "three/examples/jsm/postprocessing/RenderPass.js"; import {OutlinePass} from "three/examples/jsm/postprocessing/OutlinePass.js"; import {UnrealBloomPass} from "three/examples/jsm/postprocessing/UnrealBloomPass.js"; import * as TWEEN from '@tweenjs/tween.js'; import {getBottomMaterial} from './material.js'; // 定义一个 class类 class renderModel { constructor(selector) { this.container = document.querySelector(selector); // 相机 this.camera; // 场景 this.scene; //渲染器 this.renderer; // 控制器 this.controls; // 3d文字渲染器 this.css3DRenderer = null; // 3d文字控制器 this.css3dControls = null; // 模型 this.model; // 环境光 this.ambientLight; //模型平面 this.planeGeometry; this.outlineObjs = [] } outlineObj(selectedObjects) { // 创建一个EffectComposer(效果组合器)对象,然后在该对象上添加后期处理通道。 // 用于模型边缘高亮 let composer = new EffectComposer(this.renderer); composer.renderTarget1.texture.outputColorSpace = THREE.sRGBEncoding; composer.renderTarget2.texture.outputColorSpace = THREE.sRGBEncoding; composer.renderTarget1.texture.encoding = THREE.sRGBEncoding; composer.renderTarget2.texture.encoding = THREE.sRGBEncoding; // 新建一个场景通道 为了覆盖到原来的场景上 composer.addPass(new RenderPass(this.scene, this.camera)); // 物体边缘发光通道 let outlinePass = new OutlinePass( new THREE.Vector2(window.innerWidth, window.innerHeight), this.scene, this.camera, selectedObjects ); outlinePass.selectedObjects = selectedObjects; outlinePass.edgeStrength = 10.0; // 边框的亮度 outlinePass.edgeGlow = 0.5; // 光晕[0,1] outlinePass.usePatternTexture = false; // 是否使用父级的材质 outlinePass.edgeThickness = 1.0; // 边框宽度 outlinePass.downSampleRatio = 1; // 边框弯曲度 outlinePass.pulsePeriod = 5; // 呼吸闪烁的速度 outlinePass.visibleEdgeColor.set(parseInt(0x00ff00)); // 呼吸显示的颜色 outlinePass.hiddenEdgeColor = new THREE.Color(0, 0, 0); // 呼吸消失的颜色 outlinePass.clear = true; composer.addPass(outlinePass); // 自定义的着色器通道 作为参数 // effectFXAA = new ShaderPass(FXAAShader); // effectFXAA.uniforms.resolution.value.set( // 1 / window.innerWidth, // 1 / window.innerHeight // ); // effectFXAA.renderToScreen = true; // composer.addPass(effectFXAA); // // 发光效果 let unrealBloomPass = new UnrealBloomPass(); unrealBloomPass.strength = 0.1; unrealBloomPass.radius = 0; unrealBloomPass.threshold = 1; composer.addPass(unrealBloomPass); this.outlineObjs.push(composer) console.log(">>>>>>>>>>>>>>>>>>>>>") } // 初始化加载模型方法 init() { //初始化场景 this.initScene(); //初始化相机 this.initCamera(); //初始化渲染器 this.initRender(); // 创建灯光 this.createLight(); //初始化控制器,控制摄像头,控制器一定要在渲染器后 this.initControls(); this.setFBXModel(); //监听场景大小改变,跳转渲染尺寸 window.addEventListener('resize', this.onWindowResizes); //场景渲染 this.sceneAnimation(); } initGltfModel() { //初始化场景 this.initScene(); //初始化相机 this.initCamera(); //初始化渲染器 this.initRender(); // 创建灯光 this.createLight(); //初始化控制器,控制摄像头,控制器一定要在渲染器后 this.initControls(); this.setGlbModel(); //监听场景大小改变,跳转渲染尺寸 window.addEventListener('resize', this.onWindowResizes); //场景渲染 this.sceneAnimation(); } //创建场景 initScene() { this.scene = new THREE.Scene(); this.scene.background = new THREE.Color(0x000000); //底部平面 const geometry = new THREE.PlaneGeometry(1, 1); // 创建材质,可以设置贴图 const material = getBottomMaterial( '#ffffff', // 设置模型的颜色 require('@/assets/images/models/bg.png'), 1, 5 ); // 创建平面网格 const plane = new THREE.Mesh(geometry, material); plane.scale.set(1000, 1000, 1000); plane.position.y = 0; const plane2 = plane.clone(); plane2.material = getBottomMaterial( '#000000', // 设置模型的颜色 require('@/assets/images/models/bg.png'), 2, 5 ); this.scene.add(plane2); this.scene.add(plane); } // 创建相机 initCamera() { const {clientHeight, clientWidth} = this.container; this.camera = new THREE.PerspectiveCamera(18, clientWidth / clientHeight, 0.1, 10000); } // 创建渲染器 initRender() { this.renderer = new THREE.WebGLRenderer({ logarithmicDepthBuffer: true, antialias: true, // true/false表示是否开启反锯齿 alpha: true, // true/false 表示是否可以设置背景色透明 precision: 'mediump', // highp/mediump/lowp 表示着色精度选择 premultipliedAlpha: true // true/false 表示是否可以设置像素深度(用来度量图像的分辨率) // preserveDrawingBuffer: false, // true/false 表示是否保存绘图缓冲 // physicallyCorrectLights: true, // true/false 表示是否开启物理光照 }); //设置屏幕像素比 this.renderer.setPixelRatio(window.devicePixelRatio); //渲染的尺寸大小 const {clientHeight, clientWidth} = this.container; this.renderer.setSize(clientWidth, clientHeight); this.container.appendChild(this.renderer.domElement); // 创建一个CSS3渲染器CSS3DRenderer this.css3DRenderer = new CSS3DRenderer(); this.css3DRenderer.setSize(clientWidth, clientHeight); // HTML标签
外面父元素叠加到canvas画布上且重合 this.css3DRenderer.domElement.style.position = 'absolute'; this.css3DRenderer.domElement.style.top = '0px'; this.css3DRenderer.domElement.style.zIndex = '9999'; //设置.pointerEvents=none,解决HTML元素标签对threejs canvas画布鼠标事件的遮挡 this.css3DRenderer.domElement.style.pointerEvents = 'none'; this.css3DRenderer.domElement.style.className = 'css3DRenderer'; this.container.appendChild(this.css3DRenderer.domElement); } // 创建光源 createLight() { this.scene.add(new THREE.AmbientLight(0xffffff, 10)); } initControls() { this.controls = new OrbitControls(this.camera, this.renderer.domElement); // this.controls.enableDamping = true; // this.controls.screenSpacePanning = false; // this.controls.maxPolarAngle = Math.PI / 1.1; // this.controls.minPolarAngle = Math.PI / 2; // this.controls.minAzimuthAngle = 0; // this.controls.maxAzimuthAngle = 0; // this.controls.maxDistance = 2000; //标签控制器 this.css3dControls = new OrbitControls(this.camera, this.css3DRenderer.domElement); this.css3dControls.enablePan = false; this.css3dControls.enableDamping = true; this.controls.mouseButtons = { LEFT: THREE.MOUSE.PAN, MIDDLE: THREE.MOUSE.DOLLY, RIGHT: THREE.MOUSE.ROTATE }; } animate() { this.renderer.render(this.scene, this.camera); this.renderer.autoClear = true; this.controls.update(); this.css3DRenderer.render(this.scene, this.camera); TWEEN.update(); // this.outlineObjs.forEach(item => { // item.render(this.scene, this.camera) // }) // // 检查模型位置是否发生变化 // if (this.model) { // console.log('Model Position:', this.model.position); // console.log('Camera Position:', this.camera.position); // console.log('Controls Target:', this.controls.target); // } } // 使用动画器不断更新场景 sceneAnimation() { this.renderer.setAnimationLoop(this.animate.bind(this)); } flyTo(target, scale = 1, duration = 1000) { const targetPosition = new THREE.Vector3().copy(target.position); const targetFocus = new THREE.Vector3().copy(target.targetContent); // 移动相机位置 new TWEEN.Tween(this.camera.position) .to(targetPosition, target.time || 500) .easing(TWEEN.Easing.Quadratic.InOut) .onUpdate(() => { this.controls.update(); // 更新控制器 }) .start(); // 移动控制器目标 new TWEEN.Tween(this.controls.target) .to(targetFocus, target.time || 500) .easing(TWEEN.Easing.Quadratic.InOut) .onUpdate(() => { this.controls.update(); // 更新控制器 }) .start(); new TWEEN.Tween(this.model.scale).to({ x: scale, y: scale, z: scale }, duration).easing(TWEEN.Easing.Quadratic.InOut).start(); } tag3D(name) { // 创建div元素(作为标签) let div = document.createElement('div'); div.innerHTML = name; div.classList.add('tag3d'); //div元素包装为CSS3模型对象CSS3DObject let label = new CSS3DSprite(div); div.style.pointerEvents = 'none'; //避免HTML标签遮挡三维场景的鼠标事件 //缩放CSS3DObject模型对象 label.scale.set(0.15, 0.15, 0.15); //根据相机渲染范围控制HTML 3D标签尺寸 label.rotateY(Math.PI / 2); //控制HTML标签CSS3对象姿态角度 return label; //返回CSS3模型标签 } createDialog(html) { //div元素包装为CSS3模型对象CSS3DSprite const element = document.createElement('div'); element.className = 'customDialog'; element.appendChild(html); const dialog = new CSS3DSprite(element); element.style.pointerEvents = 'none'; //避免HTML标签遮挡三维场景的鼠标事件 // 设置HTML元素标签在three.js世界坐标中位置 // label.position.set(x, y, z); //缩放CSS3DSprite模型对象 dialog.scale.set(0.15, 0.15, 0.15); //根据相机渲染范围控制HTML 3D标签尺寸 dialog.rotateY(Math.PI / 2); //控制HTML标签CSS3对象姿态角度 return dialog; //返回CSS3模型标签 } /** * 设置加载模型居中 * {Object} object 模型对象 */ setModelPosition(object) { object.updateMatrixWorld(); // 获得包围盒得min和max const box = new THREE.Box3().setFromObject(object); // 返回包围盒的中心点 const center = box.getCenter(new THREE.Vector3()); object.position.x += object.position.x - center.x; object.position.y += object.position.y - center.y; object.position.z = 0; } setGlbModel() { var fbxLoader = new GLTFLoader(); fbxLoader.load('/models/model-road-pv.glb', object => { this.calcMeshCenter(object.scene); this.model = object.scene; object.scene.traverse(function (child) { if (child.isMesh) { child.material.emissive = child.material.color; child.material.emissiveMap = child.material.map; } }); // 设置相机位置 this.camera.position.set(-20, -652, 500); this.controls.target.set(-20, -20, 0); this.model.scale.set(1, 1, 1); // 设置相机坐标系 this.camera.lookAt(0, 0, 0); // 将模型添加到场景中去 this.scene.add(this.model); if (object.scene.type === 'Group') { console.log('这是一个Group'); // 遍历Group中的子对象 object.scene.children.forEach(child => { if (child.type === 'Mesh') { console.log('这是一个Mesh', child.name); // 检查并记录Mesh的名称 if (["solar_cell097.001", "solar_cell097.002", "solar_cell097.003", "solar_cell097.004","Line007"].includes(child.name)) { let selectedObjects = [child]; // this.outlineObj(selectedObjects); } } }); } else if (object.scene.type === 'Mesh') { console.log('这是一个单独的Mesh', object.scene.name); // 单独的Mesh对象 } else { console.log('未知类型的对象', object.scene.type); } window.addEventListener('click', event => { // raycaster.setFromCamera(mouse, this.camera); // const intersects = raycaster.intersectObjects(this.scene.children); const intersects = this.raycaster.intersectObjects(this.scene.children); if (intersects.length > 0) { const point = intersects[0].point; console.log(`Clicked at: (${point.x}, ${point.y}, ${point.z})`); } }); console.log('load') // this.initGUI(); }); } setFBXModel() { var fbxLoader = new FBXLoader(); fbxLoader.load('/models/model2.FBX', object => { this.calcMeshCenter(object); this.model = object; object.traverse(function (child) { if (child.isMesh) { child.material.emissive = child.material.color; child.material.emissiveMap = child.material.map; } }); // 设置相机位置 this.camera.position.set(-20, -652, 500); this.controls.target.set(-20, -20, 0); this.model.scale.set(1, 1, 1); // 设置相机坐标系 this.camera.lookAt(0, 0, 0); // 将模型添加到场景中去 this.scene.add(this.model); if (object.type === 'Group') { console.log('这是一个Group'); // 遍历Group中的子对象 object.children.forEach(child => { if (child.type === 'Mesh') { console.log('这是一个Mesh', child.name); // 检查并记录Mesh的名称 if (child.name === 'Line007') { let selectedObjects = [child]; this.outlineObj(selectedObjects); } } }); } else if (object.type === 'Mesh') { console.log('这是一个单独的Mesh', object.name); // 单独的Mesh对象 } else { console.log('未知类型的对象', object.type); } window.addEventListener('click', event => { // raycaster.setFromCamera(mouse, this.camera); // const intersects = raycaster.intersectObjects(this.scene.children); const intersects = this.raycaster.intersectObjects(this.scene.children); if (intersects.length > 0) { const point = intersects[0].point; console.log(`Clicked at: (${point.x}, ${point.y}, ${point.z})`); } }); }); } onWindowResizes() { if (!this.container) return false; const {clientHeight, clientWidth} = this.container; //调整屏幕大小 this.camera.aspect = clientWidth / clientHeight; // 摄像机宽高比例 this.camera.updateProjectionMatrix(); //相机更新矩阵,将3d内容投射到2d面上转换 this.renderer.setSize(clientWidth, clientHeight); } calcMeshCenter(group) { /** * 包围盒全自动计算:模型整体居中 */ var box3 = new THREE.Box3(); // 计算层级模型group的包围盒 // 模型group是加载一个三维模型返回的对象,包含多个网格模型 box3.expandByObject(group); // 计算一个层级模型对应包围盒的几何体中心在世界坐标中的位置 var center = new THREE.Vector3(); box3.getCenter(center); // 重新设置模型的位置,使之居中。 group.position.x = 0; group.position.y = 0; group.position.z = 17; } addDialog(html, labelName, position) { const {x, y, z} = position const label3D = this.tag3D(labelName); const dialog3D = this.createDialog(html); //设置标签名称 label3D.position.y += y; label3D.position.x += x; label3D.position.z += z; dialog3D.position.copy(label3D.position); dialog3D.position.z = z + 20; this.scene.add(label3D); this.scene.add(dialog3D); } } export default renderModel;