modelUnpack.vue 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225
  1. <template>
  2. <div
  3. class="modelBox"
  4. v-loading="modelLoading"
  5. element-loading-text="模型加载中...请稍等..."
  6. :element-loading-spinner="loadingSvg"
  7. element-loading-svg-view-box="-10, -10, 50, 50"
  8. element-loading-background="rgba(0, 0, 0, 0.5)"
  9. >
  10. <div class="l">
  11. <div
  12. ref="threeCanvas"
  13. class="threeCanvas"
  14. style="width: 100%; height: 100%"
  15. ></div>
  16. </div>
  17. <div class="r" :style="`opacity: ${splitOpacity / 100}`">
  18. <div
  19. ref="threeToushi"
  20. class="threeToushi"
  21. style="width: 100%; height: 100%"
  22. ></div>
  23. </div>
  24. <div class="bjSelectBox">
  25. <el-select
  26. v-model="bj"
  27. placeholder="完整展示"
  28. style="width: 300px"
  29. clearable
  30. filterable
  31. @change="bjChange"
  32. >
  33. <el-option
  34. v-for="item in bjList"
  35. :key="item.id"
  36. :label="item.name"
  37. :value="item.uuid"
  38. >
  39. <span
  40. :style="
  41. item.warnType ? `color: ${selectWarnType[item.warnType]}` : ''
  42. "
  43. >{{ item.name }}</span
  44. >
  45. </el-option>
  46. </el-select>
  47. </div>
  48. <div class="sliderBarBox">
  49. <el-slider
  50. v-model="splitOpacity"
  51. :min="0"
  52. :max="75"
  53. size="small"
  54. :format-tooltip="sliderFormatTooltip"
  55. />
  56. </div>
  57. <div class="alertBox" v-if="yujingList?.length || baojingList?.length">
  58. <el-alert title="" type="warning" v-if="yujingList.length">
  59. <template #default>
  60. <div class="alertItem">
  61. {{ yujingList.length }}条部件预警信息:
  62. <span v-for="item in yujingList" :key="item.uuid">
  63. <span
  64. class="name"
  65. @click="
  66. () => {
  67. bj = item.uuid;
  68. bjChange(item.uuid);
  69. }
  70. "
  71. >[{{ item.name }}]</span
  72. >
  73. :
  74. <span class="desc">{{ item.desc }}</span>
  75. </span>
  76. </div>
  77. </template>
  78. </el-alert>
  79. <el-alert title="" type="error" v-if="baojingList.length">
  80. <template #default>
  81. <div class="alertItem">
  82. {{ baojingList.length }}条部件预警信息:
  83. <span v-for="item in baojingList" :key="item.uuid">
  84. <span
  85. class="name"
  86. @click="
  87. () => {
  88. bj = item.uuid;
  89. bjChange(item.uuid);
  90. }
  91. "
  92. >[{{ item.name }}]</span
  93. >
  94. :
  95. <span class="desc">{{ item.desc }}</span>
  96. </span>
  97. </div>
  98. </template>
  99. </el-alert>
  100. </div>
  101. </div>
  102. </template>
  103. <script>
  104. // import * as THREE from "../Three/Three.js";
  105. // import { TEngine } from "../threeTool/ThreeEngine";
  106. // import { allBaseObject } from "../threeTool/ThreeBaseObject";
  107. // import { allLights } from "../threeTool/ThreeLights";
  108. // import { getColor } from "../threeTool/ThreeColor";
  109. // import { ThreeAxes } from "../threeTool/ThreeAxes";
  110. // import { GLTFLoader } from "../Three/examples/jsm/loaders/GLTFLoader";
  111. // import { RGBELoader } from "three/examples/jsm/loaders/RGBELoader";
  112. import * as THREE from "three";
  113. import {
  114. WebGLRenderer,
  115. Scene,
  116. PerspectiveCamera,
  117. Vector3,
  118. MOUSE,
  119. Raycaster,
  120. Vector2,
  121. } from "three";
  122. import { OrbitControls } from "three/addons/controls/OrbitControls.js";
  123. import { TransformControls } from "three/examples/jsm/controls/TransformControls";
  124. import {
  125. CSS3DRenderer,
  126. CSS3DObject,
  127. } from "three/examples/jsm/renderers/CSS3DRenderer";
  128. import { EffectComposer } from "three/examples/jsm/postprocessing/EffectComposer.js";
  129. import { RenderPass } from "three/examples/jsm/postprocessing/RenderPass.js";
  130. import { OutlinePass } from "three/examples/jsm/postprocessing/OutlinePass.js";
  131. import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader";
  132. import { DRACOLoader } from "three/examples/jsm/loaders/DRACOLoader";
  133. import { OBJLoader } from "three/examples/jsm/loaders/OBJLoader";
  134. import { FBXLoader } from "three/examples/jsm/loaders/FBXLoader";
  135. import { TDSLoader } from "three/examples/jsm/loaders/TDSLoader";
  136. import { MTLLoader } from "three-obj-mtl-loader";
  137. import { Color } from "../Three/Three.js";
  138. import WebGL from "../threeTool/WebGL";
  139. import axios from "axios";
  140. THREE.Cache.enabled = true;
  141. export default {
  142. name: "ThreeScene",
  143. props: {
  144. modelUnpackType: {
  145. type: String,
  146. default: () => {
  147. return "";
  148. },
  149. },
  150. showModelMsg: {
  151. type: Boolean,
  152. default: true,
  153. },
  154. },
  155. data() {
  156. return {
  157. selectWarnType: {
  158. warn: "#e6a23c",
  159. error: "#f56c6c",
  160. },
  161. yujingList: [],
  162. baopjingList: [],
  163. splitOpacity: 25,
  164. modelLoading: false,
  165. loadingSvg: `<path class="path" d="
  166. M 30 15
  167. L 28 17
  168. M 25.61 25.61
  169. A 15 15, 0, 0, 1, 15 30
  170. A 15 15, 0, 1, 1, 27.99 7.5
  171. L 15 15
  172. " style="stroke-width: 4px; fill: rgba(0, 0, 0, 0)"/>`,
  173. modelUnpackMap: {
  174. fengji: "fengji",
  175. guangfu: "gfSolo",
  176. dixing: "dixing",
  177. },
  178. ThreeEngine: null,
  179. scene: null,
  180. camera: null,
  181. renderer: null,
  182. scene_Toushi: null,
  183. camera_Toushi: null,
  184. renderer_Toushi: null,
  185. composer: null,
  186. outlinePass: null,
  187. loader: null,
  188. baseWidth: 0,
  189. baseHeight: 0,
  190. orbitControls: null,
  191. css3DRenderer: null,
  192. orbitControls_Toushi: null,
  193. css3DRenderer_Toushi: null,
  194. animationId: null,
  195. basicModel: null,
  196. bj: "",
  197. bjList: [],
  198. modleMap: {
  199. fengji: {
  200. dizuo13: {
  201. name: "底座",
  202. },
  203. tadiyiceng14: {
  204. name: "塔底一层",
  205. },
  206. zhuzhou15: {
  207. name: "主轴",
  208. },
  209. zhengliuzhao16: {
  210. name: "整流罩",
  211. },
  212. jicangzhao0117: {
  213. name: "机舱罩01",
  214. },
  215. pati18: {
  216. name: "爬梯",
  217. },
  218. tadierceng19: {
  219. name: "塔底二层",
  220. },
  221. tadisanceng20: {
  222. name: "塔底三层",
  223. },
  224. miehuoqi21: {
  225. name: "灭火器",
  226. },
  227. chilunxiang22: {
  228. name: "齿轮箱",
  229. },
  230. diaoji23: {
  231. name: "吊机",
  232. },
  233. qita24: {
  234. name: "其他",
  235. },
  236. jicanggui25: {
  237. name: "机舱柜",
  238. },
  239. dianji26: {
  240. name: "电机",
  241. },
  242. lianzhouqi27: {
  243. name: "联轴器",
  244. },
  245. men28: {
  246. name: "门",
  247. },
  248. xiangbian29: {
  249. name: "箱变",
  250. },
  251. tatong0230: {
  252. name: "塔筒02",
  253. },
  254. tatong0331: {
  255. name: "塔筒03",
  256. },
  257. pianhangxitong32: {
  258. name: "偏航系统",
  259. },
  260. tajia33: {
  261. name: "塔架",
  262. },
  263. tatong0136: {
  264. name: "塔筒01",
  265. },
  266. dianlanxian37: {
  267. name: "电缆线",
  268. },
  269. yeyazhan38: {
  270. name: "液压站",
  271. },
  272. bianjiangxitong39: {
  273. name: "变桨系统",
  274. },
  275. shanye0240: {
  276. name: "扇叶02",
  277. },
  278. shanye0141: {
  279. name: "扇叶01",
  280. },
  281. shanye0342: {
  282. name: "扇叶03",
  283. },
  284. jicangzhao0243: {
  285. name: "机舱罩02",
  286. },
  287. },
  288. },
  289. };
  290. },
  291. created() {
  292. // this.test();
  293. },
  294. mounted() {},
  295. methods: {
  296. init() {
  297. this.$nextTick(async () => {
  298. await this.initLoader();
  299. await this.initThree({
  300. dom: this.$refs.threeCanvas,
  301. dom_Toushi: this.$refs.threeToushi,
  302. showGridHelper: true,
  303. });
  304. await this.addModel({
  305. fileType: "glb",
  306. fileName: this.modelUnpackMap[this.modelUnpackType],
  307. });
  308. });
  309. },
  310. sliderFormatTooltip(value) {
  311. return `透视透明度: ${value}% `;
  312. },
  313. async test() {
  314. const res = await axios.get(
  315. `https://nomads.ncep.noaa.gov/cgi-bin/filter_gfs_0p50.pl`,
  316. {
  317. file: "gfs.t18z.pgrb2full.0p50.f000",
  318. leftlon: 0,
  319. rightlon: 360,
  320. toplat: 90,
  321. bottomlat: -90,
  322. dir: `/gfs.20250827/18/atmos`,
  323. "lev_PV=1e-06_(Km^2/kg/s)_surface": "on",
  324. var_TMP: "on",
  325. }
  326. );
  327. console.log(1111111111, res);
  328. return;
  329. // 获取 gfs 文件列表
  330. const rootRes = await axios.get("/nomads");
  331. const gfsList = this.extractDOM(rootRes.data, "body p");
  332. const firstGfsName = gfsList[1].querySelector("a").innerHTML;
  333. // 获取首个文件内的日期列表
  334. const dateRes = await axios.get(`/nomads?dir=/${firstGfsName}`);
  335. const gfsFileDateList = this.extractDOM(dateRes.data, "body td a");
  336. const firstDate = gfsFileDateList[0].innerHTML;
  337. // 获取 gfs 文件详情
  338. const gfsRes = await axios.get(
  339. `/nomads?dir=/${firstGfsName}/${firstDate}/atmos`
  340. );
  341. const gfsDetailPage = this.extractDOM(gfsRes.data, "body form p");
  342. // 获取 gfs 模型列表
  343. const gfsModelList = gfsDetailPage[1].querySelectorAll("option");
  344. let model = [];
  345. for (let i = 0; i < gfsModelList.length; i++) {
  346. model.push(gfsModelList[i].innerHTML.replace(/\n/g, ""));
  347. }
  348. // 获取级别
  349. const levelsList = gfsDetailPage[4];
  350. const levelInputList = levelsList.querySelectorAll("input");
  351. let lvl = [];
  352. for (let i = 0; i < levelInputList.length; i++) {
  353. const ipt = levelInputList[i];
  354. const lvlStr = ipt
  355. .getAttribute("name")
  356. .replace(/^lev_/, "")
  357. .replace(/\\/g, "");
  358. lvl.push(lvlStr);
  359. }
  360. lvl.shift();
  361. // 获取变量
  362. const variablesList = gfsDetailPage[5];
  363. const varInputList = variablesList.querySelectorAll("input");
  364. let variables = [];
  365. for (let i = 0; i < varInputList.length; i++) {
  366. const ipt = varInputList[i];
  367. const varStr = ipt
  368. .getAttribute("name")
  369. .replace(/^var_/, "")
  370. .replace(/\\/g, "");
  371. variables.push(varStr);
  372. }
  373. variables.shift();
  374. },
  375. // 提取DOM元素函数
  376. extractDOM(htmlString, selector) {
  377. if (!htmlString.trim()) {
  378. showMessage("请输入HTML字符串", "error");
  379. return;
  380. }
  381. if (!selector.trim()) {
  382. showMessage("请输入CSS选择器", "error");
  383. return;
  384. }
  385. try {
  386. // 使用DOMParser解析HTML字符串
  387. const parser = new DOMParser();
  388. const doc = parser.parseFromString(htmlString, "text/html");
  389. // 使用选择器查找元素
  390. const element = doc.querySelectorAll(selector);
  391. if (element) {
  392. // 输出元素的outerHTML
  393. return element;
  394. } else {
  395. console.log("未匹配到元素:", selector);
  396. }
  397. } catch (error) {
  398. console.log("解析HTML时出错: ", error.message);
  399. }
  400. },
  401. enableFallbackOutline() {
  402. console.log("启用备用描边方案 (EdgesGeometry)");
  403. let yujingList = [];
  404. let baojingList = [];
  405. this.basicModel.children.forEach((bj) => {
  406. if (bj.name === "变桨系统" || bj.name === "齿轮箱") {
  407. bj.name === "变桨系统"
  408. ? yujingList.push({ name: bj.name, uuid: bj.uuid, desc: "三相电流不平衡度超过10%且持续120秒" })
  409. : bj.name === "齿轮箱"
  410. ? baojingList.push({
  411. name: bj.name,
  412. uuid: bj.uuid,
  413. desc: "齿箱油温功率超限",
  414. })
  415. : "";
  416. bj.traverse((child) => {
  417. if (child.isMesh) {
  418. // 移除可能存在的旧描边
  419. if (child.userData.outline) {
  420. child.remove(child.userData.outline);
  421. }
  422. // 创建边缘几何体
  423. const edges = new THREE.EdgesGeometry(child.geometry, 15); // 角度阈值
  424. const lineMaterial = new THREE.LineBasicMaterial({
  425. color: this.getColor(
  426. this.selectWarnType[bj.name === "齿轮箱" ? "error" : "warn"]
  427. ),
  428. linewidth: 2,
  429. });
  430. const outline = new THREE.LineSegments(edges, lineMaterial);
  431. // 添加到网格
  432. child.add(outline);
  433. child.userData.outline = outline;
  434. child.userData.outline.visible = false;
  435. // 确保描边随父级变换
  436. outline.matrixAutoUpdate = false;
  437. }
  438. });
  439. }
  440. });
  441. this.yujingList = yujingList;
  442. this.baojingList = baojingList;
  443. // this.basicModel.traverse((child) => {
  444. // if (child.isMesh) {
  445. // // 移除可能存在的旧描边
  446. // if (child.userData.outline) {
  447. // child.remove(child.userData.outline);
  448. // }
  449. // // 创建边缘几何体
  450. // const edges = new THREE.EdgesGeometry(child.geometry, 15); // 角度阈值
  451. // const lineMaterial = new THREE.LineBasicMaterial({
  452. // color: this.getColor("red"),
  453. // linewidth: 2,
  454. // });
  455. // const outline = new THREE.LineSegments(edges, lineMaterial);
  456. // // 添加到网格
  457. // child.add(outline);
  458. // child.userData.outline = outline;
  459. // child.userData.outline.visible = false;
  460. // // 确保描边随父级变换
  461. // outline.matrixAutoUpdate = false;
  462. // }
  463. // });
  464. },
  465. showOutlineForSelected(selectedPart) {
  466. // 隐藏所有描边
  467. this.basicModel.traverse((child) => {
  468. if (child.userData.outline) {
  469. child.userData.outline.visible = false;
  470. }
  471. });
  472. // 显示选中部件的描边
  473. selectedPart.traverse((child) => {
  474. if (child.userData.outline) {
  475. child.userData.outline.visible = true;
  476. }
  477. });
  478. },
  479. hideOutline(part) {
  480. part.traverse((child) => {
  481. if (child.userData.outline) {
  482. child.userData.outline.visible = false;
  483. }
  484. });
  485. },
  486. showOutline(part) {
  487. part.traverse((child) => {
  488. if (child.userData.outline) {
  489. child.userData.outline.visible = true;
  490. }
  491. });
  492. },
  493. bjChange(uuid) {
  494. let modelBjList = this.scene.children.find((modelEle) => {
  495. return !modelEle.isLight && !modelEle.isLineSegments;
  496. });
  497. if (uuid) {
  498. modelBjList.children.forEach((ele) => {
  499. if (ele.uuid === uuid) {
  500. this.focusOnPart(ele);
  501. ele.visible = true;
  502. // 显示选中部件的描边,隐藏其他的
  503. this.showOutlineForSelected(ele);
  504. } else {
  505. ele.visible = false;
  506. this.hideOutline(ele);
  507. }
  508. });
  509. } else {
  510. this.focusOnPart(this.basicModel);
  511. modelBjList.children.forEach((ele) => {
  512. ele.visible = true;
  513. });
  514. }
  515. },
  516. calcFixBeiLv(value) {
  517. return 4 * value;
  518. switch (value) {
  519. case 1:
  520. return 96;
  521. case 2:
  522. return 92.4;
  523. case 3:
  524. return 88.75;
  525. case 4:
  526. return 85.25;
  527. case 5:
  528. return 81.75;
  529. case 6:
  530. return 78.4;
  531. case 7:
  532. return 75.5;
  533. default:
  534. return 4 * value;
  535. }
  536. },
  537. initThree(options) {
  538. this.$nextTick(() => {
  539. const parentDom = getComputedStyle(
  540. document.querySelector(".el-drawer__body"),
  541. null
  542. );
  543. this.baseWidth = parentDom.width ? parseInt(parentDom.width) : 0;
  544. this.baseHeight = parentDom.height ? parseInt(parentDom.height) : 0;
  545. // 创建3D场景对象Scene
  546. const scene = new THREE.Scene();
  547. scene.background = this.getColor("#93bcd3");
  548. const scene_Toushi = new THREE.Scene();
  549. scene_Toushi.background = this.getColor("#93bcd3");
  550. // 相机
  551. const camera = new PerspectiveCamera(
  552. // 视野角度(fov)
  553. options?.cameraOptions?.fov || 75,
  554. // 长宽比(aspect ratio)
  555. options?.cameraOptions?.aspectRatio ||
  556. this.baseWidth / this.baseHeight,
  557. // 近截面(near)
  558. options?.cameraOptions?.near || 0.1,
  559. // 远截面(far)
  560. options?.cameraOptions?.far || 1000
  561. );
  562. const camera_Toushi = new PerspectiveCamera(
  563. // 视野角度(fov)
  564. options?.cameraOptions?.fov || 75,
  565. // 长宽比(aspect ratio)
  566. options?.cameraOptions?.aspectRatio ||
  567. this.baseWidth / this.baseHeight,
  568. // 近截面(near)
  569. options?.cameraOptions?.near || 0.1,
  570. // 远截面(far)
  571. options?.cameraOptions?.far || 1000
  572. );
  573. // 设置摄像机位置和朝向
  574. camera.position.set(80, 100, 200); // 调整摄像机位置
  575. camera.lookAt(new THREE.Vector3(0, 0, 0)); // 设置摄像机朝向场景中心
  576. camera_Toushi.position.set(80, 100, 200); // 调整摄像机位置
  577. camera_Toushi.lookAt(new THREE.Vector3(0, 0, 0)); // 设置摄像机朝向场景中心
  578. // 渲染器
  579. const renderer = new WebGLRenderer({
  580. antialias: true, // 开启抗锯齿
  581. });
  582. const renderer_Toushi = new WebGLRenderer({
  583. antialias: true, // 开启抗锯齿
  584. });
  585. // 添加灯光
  586. const ambientLight = new THREE.AmbientLight(0xffffff, 5);
  587. scene.add(ambientLight);
  588. const directionalLight1 = new THREE.DirectionalLight(0xffffff, 3);
  589. directionalLight1.position.set(0, 0, 1);
  590. scene.add(directionalLight1);
  591. const directionalLight2 = new THREE.DirectionalLight(0xffffff, 3);
  592. directionalLight2.position.set(0, 0, -1);
  593. scene.add(directionalLight2);
  594. const directionalLight3 = new THREE.DirectionalLight(0xffffff, 3);
  595. directionalLight3.position.set(1, 0, 0);
  596. scene.add(directionalLight3);
  597. const directionalLight4 = new THREE.DirectionalLight(0xffffff, 3);
  598. directionalLight4.position.set(-1, 0, 0);
  599. scene.add(directionalLight4);
  600. const directionalLight5 = new THREE.DirectionalLight(0xffffff, 3);
  601. directionalLight5.position.set(0, 1, 0);
  602. scene.add(directionalLight5);
  603. const directionalLight6 = new THREE.DirectionalLight(0xffffff, 3);
  604. directionalLight6.position.set(0, -1, 0);
  605. scene.add(directionalLight6);
  606. const ambientLight_Toushi = new THREE.AmbientLight(0xffffff, 5);
  607. scene_Toushi.add(ambientLight_Toushi);
  608. const directionalLight1_Toushi = new THREE.DirectionalLight(
  609. 0xffffff,
  610. 3
  611. );
  612. directionalLight1_Toushi.position.set(0, 0, 1);
  613. scene_Toushi.add(directionalLight1_Toushi);
  614. const directionalLight2_Toushi = new THREE.DirectionalLight(
  615. 0xffffff,
  616. 3
  617. );
  618. directionalLight2_Toushi.position.set(0, 0, -1);
  619. scene_Toushi.add(directionalLight2_Toushi);
  620. const directionalLight3_Toushi = new THREE.DirectionalLight(
  621. 0xffffff,
  622. 3
  623. );
  624. directionalLight3_Toushi.position.set(1, 0, 0);
  625. scene_Toushi.add(directionalLight3_Toushi);
  626. const directionalLight4_Toushi = new THREE.DirectionalLight(
  627. 0xffffff,
  628. 3
  629. );
  630. directionalLight4_Toushi.position.set(-1, 0, 0);
  631. scene_Toushi.add(directionalLight4_Toushi);
  632. const directionalLight5_Toushi = new THREE.DirectionalLight(
  633. 0xffffff,
  634. 3
  635. );
  636. directionalLight5_Toushi.position.set(0, 1, 0);
  637. scene_Toushi.add(directionalLight5_Toushi);
  638. const directionalLight6_Toushi = new THREE.DirectionalLight(
  639. 0xffffff,
  640. 3
  641. );
  642. directionalLight6_Toushi.position.set(0, -1, 0);
  643. scene_Toushi.add(directionalLight6_Toushi);
  644. // renderer.setSize(window.innerWidth, window.innerHeight);
  645. const rendererBox = getComputedStyle(options.dom, null);
  646. const renderSizeWidth = parseFloat(rendererBox.width);
  647. const renderSizeHeight = parseFloat(rendererBox.height);
  648. renderer.setSize(renderSizeWidth, renderSizeHeight);
  649. const rendererBox_Toushi = getComputedStyle(options.dom_Toushi, null);
  650. const renderSizeWidth_Toushi = parseFloat(rendererBox_Toushi.width);
  651. const renderSizeHeight_Toushi = parseFloat(rendererBox_Toushi.height);
  652. renderer_Toushi.setSize(
  653. renderSizeWidth_Toushi,
  654. renderSizeHeight_Toushi
  655. );
  656. options?.dom?.appendChild(renderer.domElement);
  657. options?.dom_Toushi?.appendChild(renderer_Toushi.domElement);
  658. const css3DRenderer = new CSS3DRenderer();
  659. css3DRenderer.setSize(renderSizeWidth, renderSizeHeight);
  660. css3DRenderer.render(scene, camera);
  661. css3DRenderer.domElement.style.position = "absolute";
  662. css3DRenderer.domElement.style.top = 0;
  663. css3DRenderer.domElement.style.pointerEvents = "none";
  664. options.dom.appendChild(css3DRenderer.domElement);
  665. const css3DRenderer_Toushi = new CSS3DRenderer();
  666. css3DRenderer_Toushi.setSize(
  667. renderSizeWidth_Toushi,
  668. renderSizeHeight_Toushi
  669. );
  670. css3DRenderer_Toushi.render(scene_Toushi, camera_Toushi);
  671. css3DRenderer_Toushi.domElement.style.position = "absolute";
  672. css3DRenderer_Toushi.domElement.style.top = 0;
  673. css3DRenderer_Toushi.domElement.style.pointerEvents = "none";
  674. options.dom_Toushi.appendChild(css3DRenderer_Toushi.domElement);
  675. // 设置鼠标功能键(轨道控制器)
  676. const orbitControls = new OrbitControls(camera, renderer.domElement);
  677. // 移动带阻尼
  678. orbitControls.enableDamping = options.enableDamping || false;
  679. // 设置阻尼系数
  680. orbitControls.dampingFactor = options.dampingFactor || 0;
  681. // 自动旋转
  682. orbitControls.autoRotate = options.autoRotate || false;
  683. orbitControls.mouseButtons = {
  684. LEFT: MOUSE.ROTATE, // 左键无功能
  685. MIDDLE: MOUSE.PAN, // 中键移动
  686. RIGHT: null, // 右键旋转
  687. };
  688. orbitControls.addEventListener("change", () => {
  689. // 复制位置
  690. camera_Toushi.position.copy(camera.position);
  691. // 复制旋转
  692. camera_Toushi.rotation.copy(camera.rotation);
  693. // 复制up向量
  694. camera_Toushi.up.copy(camera.up);
  695. camera_Toushi.updateMatrixWorld();
  696. orbitControls_Toushi.target.copy(orbitControls.target);
  697. // orbitControls.update();
  698. // orbitControls_Toushi.update();
  699. });
  700. const orbitControls_Toushi = new OrbitControls(
  701. camera_Toushi,
  702. renderer_Toushi.domElement
  703. );
  704. // 移动带阻尼
  705. orbitControls_Toushi.enableDamping = options.enableDamping || false;
  706. // 设置阻尼系数
  707. orbitControls_Toushi.dampingFactor = options.dampingFactor || 0;
  708. // 自动旋转
  709. orbitControls_Toushi.autoRotate = options.autoRotate || false;
  710. orbitControls_Toushi.mouseButtons = {
  711. LEFT: MOUSE.ROTATE, // 左键无功能
  712. MIDDLE: MOUSE.PAN, // 中键移动
  713. RIGHT: null, // 右键旋转
  714. };
  715. orbitControls_Toushi.addEventListener("change", () => {
  716. // 复制位置
  717. camera.position.copy(camera_Toushi.position);
  718. // 复制旋转
  719. camera.rotation.copy(camera_Toushi.rotation);
  720. // 复制up向量
  721. camera.up.copy(camera_Toushi.up);
  722. camera.updateMatrixWorld();
  723. orbitControls.target.copy(orbitControls_Toushi.target);
  724. // orbitControls_Toushi.update();
  725. // orbitControls.update();
  726. });
  727. if (options.showGridHelper) {
  728. // 底图网格 (总长宽,分多少个网格,颜色,轴线颜色,和网格颜色 #e6e8ed)
  729. const gridHelper = new THREE.GridHelper(
  730. 2000,
  731. 100,
  732. this.getColor("#dedede"),
  733. this.getColor("#dedede")
  734. );
  735. gridHelper.name = "网格地板";
  736. gridHelper.disalbedDelete = true;
  737. scene.add(gridHelper);
  738. const gridHelper_Toushi = new THREE.GridHelper(
  739. 2000,
  740. 100,
  741. this.getColor("#dedede"),
  742. this.getColor("#dedede")
  743. );
  744. gridHelper_Toushi.name = "网格地板透视";
  745. gridHelper_Toushi.disalbedDelete = true;
  746. scene_Toushi.add(gridHelper_Toushi);
  747. }
  748. // 渲染循环
  749. const animate = () => {
  750. requestAnimationFrame(animate);
  751. orbitControls.update();
  752. css3DRenderer.render(scene, camera);
  753. renderer.render(scene, camera);
  754. };
  755. const animate_Toushi = () => {
  756. requestAnimationFrame(animate_Toushi);
  757. orbitControls_Toushi.update();
  758. css3DRenderer_Toushi.render(scene_Toushi, camera_Toushi);
  759. renderer_Toushi.render(scene_Toushi, camera_Toushi);
  760. };
  761. this.scene = scene;
  762. this.camera = camera;
  763. this.renderer = renderer;
  764. this.orbitControls = orbitControls;
  765. this.css3DRenderer = css3DRenderer;
  766. this.scene_Toushi = scene_Toushi;
  767. this.camera_Toushi = camera_Toushi;
  768. this.renderer_Toushi = renderer_Toushi;
  769. this.orbitControls_Toushi = orbitControls_Toushi;
  770. this.css3DRenderer_Toushi = css3DRenderer_Toushi;
  771. if (WebGL.isWebGLAvailable()) {
  772. animate();
  773. animate_Toushi();
  774. // 窗口调整大小时更新渲染器
  775. window.addEventListener("resize", () => {
  776. renderer.setSize(window.innerWidth, window.innerHeight);
  777. camera.aspect = window.innerWidth / window.innerHeight;
  778. camera.updateProjectionMatrix();
  779. renderer_Toushi.setSize(window.innerWidth, window.innerHeight);
  780. camera_Toushi.aspect = window.innerWidth / window.innerHeight;
  781. camera_Toushi.updateProjectionMatrix();
  782. // 修复:更新 composer 尺寸
  783. composer.setSize(window.innerWidth, window.innerHeight);
  784. });
  785. } else {
  786. const warning = WebGL.getWebGLErrorMessage();
  787. options?.dom?.appendChild(warning);
  788. dom_Toushi?.appendChild(warning);
  789. }
  790. });
  791. },
  792. // 初始化模型加载器
  793. initLoader() {
  794. this.loader = {
  795. glb: new GLTFLoader(),
  796. gltf: new GLTFLoader(),
  797. obj: new OBJLoader(),
  798. fbx: new FBXLoader(),
  799. "3ds": new TDSLoader(),
  800. };
  801. },
  802. // 获取颜色
  803. getColor(colorHex) {
  804. return new Color(colorHex);
  805. },
  806. // 添加模型
  807. addModel({ fileType = "glb", fileName }) {
  808. this.modelLoading = true;
  809. const loader = this.loader[fileType];
  810. loader.setResourcePath(`./static/model/${fileName}/`);
  811. loader.load(`./static/model/${fileName}/model.${fileType}`, (result) => {
  812. if (fileType === "fbx") {
  813. this.basicModel = this.formatModel(result);
  814. } else if (fileType === "glb") {
  815. this.basicModel = this.formatModel(result.scene);
  816. }
  817. this.basicModel.isCurrentAddModel = true;
  818. let bjList = [];
  819. this.basicModel.children.forEach((bj) => {
  820. if (
  821. bj.name.indexOf("Particle_View") === -1 &&
  822. bj.name !== "34" &&
  823. bj.name !== "_35" &&
  824. this.modleMap?.[fileName]?.[bj.name]
  825. ) {
  826. bj.name = this.modleMap?.[fileName]?.[bj.name]?.name || bj.name;
  827. const warnType =
  828. bj.name === "齿轮箱"
  829. ? "error"
  830. : bj.name === "变桨系统"
  831. ? "warn"
  832. : "";
  833. bjList.push({
  834. id: bj.id,
  835. uuid: bj.uuid,
  836. name: bj.name,
  837. warnType,
  838. });
  839. }
  840. });
  841. this.bjList = bjList;
  842. this.collectMaterialInfo(this.basicModel);
  843. this.scene.add(this.basicModel);
  844. this.scene_Toushi.add(this.basicModel.clone());
  845. this.modelLoading = false;
  846. this.enableFallbackOutline();
  847. });
  848. },
  849. // 调整视角到选中部件
  850. focusOnPart(part) {
  851. const box = new THREE.Box3().setFromObject(part);
  852. const size = box.getSize(new THREE.Vector3());
  853. const center = box.getCenter(new THREE.Vector3());
  854. const speed = 0.5;
  855. // 计算最佳相机距离
  856. const maxDim = Math.max(size.x, size.y, size.z);
  857. const cameraDistance = maxDim * parseFloat(speed);
  858. // 计算相机位置
  859. const direction = this.orbitControls.target
  860. .clone()
  861. .sub(this.camera.position)
  862. .normalize();
  863. const cameraPosition = center
  864. .clone()
  865. .sub(direction.multiplyScalar(cameraDistance));
  866. // 是否启用平滑过渡
  867. const smooth = true;
  868. if (smooth) {
  869. // 平滑过渡到新位置
  870. this.animateCamera(
  871. this.camera.position,
  872. cameraPosition,
  873. this.orbitControls.target,
  874. center,
  875. speed
  876. );
  877. setTimeout(() => {
  878. // 复制位置
  879. this.camera_Toushi.position.copy(this.camera.position);
  880. // 复制旋转
  881. this.camera_Toushi.rotation.copy(this.camera.rotation);
  882. // 复制up向量
  883. this.camera_Toushi.up.copy(this.camera.up);
  884. this.camera_Toushi.updateMatrixWorld();
  885. this.orbitControls_Toushi.target.copy(this.orbitControls.target);
  886. this.orbitControls.update();
  887. this.orbitControls_Toushi.update();
  888. }, 1000);
  889. } else {
  890. // 直接设置新位置
  891. this.camera.position.copy(cameraPosition);
  892. this.orbitControls.target.copy(center);
  893. this.orbitControls.update();
  894. }
  895. },
  896. // 平滑移动相机
  897. animateCamera(fromPosition, toPosition1, fromTarget, toTarget, speed) {
  898. const that = this;
  899. const duration = 1000; // 动画持续时间(ms)
  900. const startTime = Date.now();
  901. const toPosition = toPosition1;
  902. toPosition.x *= 1.03;
  903. toPosition.y *= 1.01;
  904. toPosition.z *= 1.03;
  905. // 缓动函数
  906. let easeInOutCubic = (t) => {
  907. return t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2;
  908. };
  909. function update() {
  910. const elapsed = Date.now() - startTime;
  911. const progress = Math.min(elapsed / duration, 1);
  912. // 使用缓动函数
  913. const easeProgress = easeInOutCubic(progress);
  914. // 插值计算相机位置和目标位置
  915. that.camera.position.lerpVectors(
  916. fromPosition,
  917. toPosition,
  918. easeProgress
  919. );
  920. that.orbitControls.target.lerpVectors(
  921. fromTarget,
  922. toTarget,
  923. easeProgress
  924. );
  925. that.orbitControls.update();
  926. if (progress < 1) {
  927. requestAnimationFrame(update);
  928. }
  929. }
  930. update();
  931. },
  932. formatModel(model) {
  933. console.log("model", model);
  934. this.renderer.outputColorSpace = THREE.SRGBColorSpace;
  935. const camera = this.camera;
  936. // model.traverse((child) => {
  937. // if (child.material) {
  938. // child.material.emissive = child.material.color;
  939. // child.material.emissiveMap = child.material.map;
  940. // }
  941. // });
  942. // model.children.forEach((item, index) => {
  943. // item.castShadow = true;
  944. // item.receiveShadow = true;
  945. // });
  946. const baseBoxSize = new THREE.Vector3(100, 100, 100);
  947. // 计算模型的包围盒(bounding box)
  948. const boundingBox = new THREE.Box3().setFromObject(model);
  949. const modelSize = new THREE.Vector3();
  950. boundingBox.getSize(modelSize);
  951. // 计算模型的最大尺寸
  952. const maxModelSize = Math.max(modelSize.x, modelSize.y, modelSize.z);
  953. // 计算缩放比例,使模型尺寸不超过基准盒子的尺寸
  954. const scaleFactor = baseBoxSize.clone().divideScalar(maxModelSize);
  955. // 将模型等比例缩放到适应基准盒子大小
  956. model.scale.set(scaleFactor.x, scaleFactor.y, scaleFactor.z);
  957. camera.position.z = 200;
  958. return model;
  959. },
  960. collectMaterialInfo(model) {
  961. if (!model) return;
  962. const info = [];
  963. const originalMaterials = new Map();
  964. let materialCount = 0;
  965. model.traverse((node) => {
  966. if (node.isMesh && node.material) {
  967. materialCount++;
  968. const materials = Array.isArray(node.material)
  969. ? node.material
  970. : [node.material];
  971. materials.forEach((material, index) => {
  972. if (material.name === "Mesh_225") {
  973. }
  974. info.push(`材质 ${materialCount}-${index + 1}: ${material.type}`);
  975. info.push(` 名称: ${material.name || "未命名"}`);
  976. info.push(
  977. ` 颜色: ${material.color ? material.color.getHexString() : "无"}`
  978. );
  979. info.push(` 贴图: ${material.map ? "有" : "无"}`);
  980. info.push(` 自发光贴图: ${material.emissiveMap ? "有" : "无"}`);
  981. info.push(
  982. ` 金属粗糙度贴图: ${material.metalnessMap ? "有" : "无"}`
  983. );
  984. info.push(` 法线贴图: ${material.normalMap ? "有" : "无"}`);
  985. info.push("---");
  986. // 保存原始材质引用
  987. originalMaterials.set(node.uuid + "-" + index, material);
  988. });
  989. }
  990. });
  991. // console.log(333, info);
  992. },
  993. overrideMaterials() {
  994. if (!model) return;
  995. model.traverse((node) => {
  996. if (node.isMesh) {
  997. // 创建新的基本材质
  998. const newMaterial = new THREE.MeshStandardMaterial({
  999. color: 0x4488ff,
  1000. metalness: metalness.value,
  1001. roughness: roughness.value,
  1002. emissive: new THREE.Color(0x888888).multiplyScalar(
  1003. emissiveIntensity.value
  1004. ),
  1005. wireframe: wireframe.value,
  1006. });
  1007. node.material = newMaterial;
  1008. }
  1009. });
  1010. },
  1011. },
  1012. watch: {
  1013. showModelMsg: {
  1014. handler(val) {
  1015. if (val) {
  1016. this.init();
  1017. }
  1018. },
  1019. immediate: true,
  1020. },
  1021. },
  1022. };
  1023. </script>
  1024. <style lang="less" scoped>
  1025. .modelBox {
  1026. width: 100%;
  1027. height: 100%;
  1028. position: relative;
  1029. display: flex;
  1030. justify-content: flex-start;
  1031. align-items: center;
  1032. .l,
  1033. .r {
  1034. width: 100%;
  1035. height: 100%;
  1036. position: absolute;
  1037. left: 0;
  1038. top: 0;
  1039. overflow: hidden;
  1040. }
  1041. .r {
  1042. pointer-events: none;
  1043. }
  1044. .threeToushi {
  1045. z-index: 10;
  1046. position: absolute;
  1047. left: 0;
  1048. top: 0;
  1049. }
  1050. .bjSelectBox {
  1051. position: absolute;
  1052. left: 5px;
  1053. top: 25px;
  1054. }
  1055. .sliderBarBox {
  1056. width: 100%;
  1057. position: absolute;
  1058. left: 5px;
  1059. top: 5px;
  1060. width: calc(100% - 10px);
  1061. }
  1062. .alertBox {
  1063. width: calc(100% - 24px);
  1064. margin: 0 12px;
  1065. position: absolute;
  1066. left: 0;
  1067. bottom: 12px;
  1068. .el-alert {
  1069. margin-bottom: 4px;
  1070. &:last-child {
  1071. margin-bottom: 0;
  1072. }
  1073. }
  1074. .alertItem {
  1075. .name {
  1076. color: #1890ff;
  1077. cursor: pointer;
  1078. &:hover {
  1079. color: #409eff;
  1080. text-decoration: underline;
  1081. }
  1082. }
  1083. .desc {
  1084. font-weight: 700;
  1085. }
  1086. }
  1087. }
  1088. }
  1089. </style>