IOT3D.js 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534
  1. import * as THREE from 'three';
  2. import {FontLoader} from 'three/addons/loaders/FontLoader.js';
  3. import {CinematicCamera} from 'three/addons/cameras/CinematicCamera.js';
  4. import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
  5. import { EffectComposer } from 'three/addons/postprocessing/EffectComposer.js';
  6. import { RenderPass } from 'three/addons/postprocessing/RenderPass.js';
  7. import { ShaderPass } from 'three/addons/postprocessing/ShaderPass.js';
  8. import { OutlinePass } from 'three/addons/postprocessing/OutlinePass.js';
  9. import { CSS3DRenderer } from 'three/addons/renderers/CSS3DRenderer.js';
  10. import { CSS2DRenderer } from 'three/addons/renderers/CSS2DRenderer.js';
  11. import { Storage as _Storage } from 'three/libs/Storage.js';
  12. import {unzipSync} from 'three/libs/fflate.module.js';
  13. console.log('Three.js version:', THREE.REVISION);
  14. // --------------------- 折叠 -----------------------
  15. //region Description
  16. //endregion
  17. function IOT3D() {
  18. console.log("-------------- IOT3D --------------")
  19. window.iot3d = this
  20. window.THREE = THREE; // Used by APP Scripts.
  21. window.FontLoader = FontLoader; // Used by APP Scripts.
  22. // window.VRButton = VRButton; // Used by APP Scripts.
  23. window.OrbitControls = OrbitControls; // Used by APP Scripts.
  24. window.CinematicCamera = CinematicCamera; // Used by APP Scripts.
  25. window.EffectComposer = EffectComposer; // Used by APP Scripts.
  26. window.RenderPass = RenderPass; // Used by APP Scripts.
  27. window.ShaderPass = ShaderPass; // Used by APP Scripts.
  28. window.OutlinePass = OutlinePass; // Used by APP Scripts.
  29. this.loading_open = function (time){
  30. //1000为遮罩层显示时长,若不传则一直显示,须调用关闭方法
  31. $.mask_fullscreen(time);
  32. }
  33. this.loading_close = function (){
  34. //关闭遮罩层
  35. $.mask_close_all();
  36. }
  37. this.loading_text = function (text){
  38. //关闭遮罩层
  39. $.mask_text(text);
  40. }
  41. this.loading_html = function (html){
  42. //关闭遮罩层
  43. $.mask_html(html);
  44. }
  45. //
  46. var self;
  47. THREE.Cache.enabled = true; //这是一个全局属性,只需要设置一次,供内部使用FileLoader的所有加载器使用。
  48. // 项目
  49. // var IOT3D_Url = "https://iot3d.baozhida.cn"
  50. // var IOT3D_Url = "https://iot3d.baozhida.cn"
  51. // if(url.indexOf("127.0.0.1") != -1){
  52. // IOT3D_Url = "http://127.0.0.1:6210"
  53. // }else {
  54. // IOT3D_Url = "https://iot3d.baozhida.cn"
  55. // }
  56. var clock = new THREE.Clock();
  57. // 公共
  58. var dom_width = 500, dom_height = 500;
  59. var camera, scene, dom, renderer, rendererCss2, rendererCss3,controls;
  60. var events = {};
  61. window.parkId = 0; // 园区ID
  62. var project; // 项目配置
  63. /// =- 选取
  64. var raycaster, mouse, INTERSECTED = null;
  65. // 变量初始化
  66. self = this;
  67. dom_width = window.innerWidth;
  68. dom_height = window.innerHeight;
  69. self.width = dom_width;
  70. self.height = dom_width;
  71. // var vrButton = VRButton.createButton( renderer ); // eslint-disable-line no-undef
  72. // --------------------- 初始化 -----------------------
  73. //region Description
  74. // 舞台
  75. scene = new THREE.Scene();
  76. // 相机
  77. camera = new THREE.PerspectiveCamera(45, dom_width / dom_height, 0.1, 3000);
  78. camera.position.set(-10, 10, 30);
  79. camera.lookAt(scene.position);
  80. window.mixer = new THREE.AnimationMixer( scene ); // 动画
  81. // HTML dom
  82. dom = document.getElementById("iot3d");
  83. //渲染器
  84. renderer = new THREE.WebGLRenderer({antialias: true});
  85. renderer.setPixelRatio(window.devicePixelRatio); // TODO: Use setPixelRatio()
  86. // renderer.outputEncoding = THREE.sRGBEncoding;
  87. renderer.shadowMap.enabled = true;// 阴影
  88. renderer.setSize( dom_width, dom_height );
  89. renderer.setAnimationLoop( animate );
  90. dom.appendChild(renderer.domElement);
  91. // rendererCss3
  92. rendererCss3 = new CSS3DRenderer();
  93. rendererCss3.setSize( dom.innerWidth, dom.innerHeight );
  94. rendererCss3.domElement.style.position = 'absolute';
  95. rendererCss3.domElement.style.top = 0;
  96. dom.appendChild( rendererCss3.domElement );
  97. // rendererCss2
  98. rendererCss2 = new CSS2DRenderer();
  99. rendererCss2.setSize( dom.innerWidth, dom.innerHeight );
  100. rendererCss2.domElement.style.position = 'absolute';
  101. rendererCss2.domElement.style.top = '0px';
  102. dom.appendChild( rendererCss2.domElement );
  103. // 加载到 网页
  104. document.body.appendChild(dom);
  105. window.addEventListener('resize', function () {
  106. self.setSize(window.innerWidth, window.innerHeight);
  107. });
  108. /// =- 选取
  109. raycaster = new THREE.Raycaster();
  110. mouse = new THREE.Vector2();
  111. var selectedObjects = [],compose,renderPass,outlinePass;
  112. // 鼠标移动 -轨道控制
  113. // var AutomaticRotationPerspective = [1,2,20] //自动旋转视角 0 【关闭】 1【360度旋转[1,旋转速度{1~9,2},俯视角度{0~100,20}]】
  114. var AutomaticRotationPerspectiveInterval = undefined // 定时任务
  115. var AutomaticRotationPerspectiveTally = 0 // 计数
  116. // - 鼠标移动视角
  117. controls = new OrbitControls(camera, renderer.domElement);
  118. // controls.addEventListener('change', animate); // use if there is no animation loop
  119. controls.dampingFactor = 0.25;
  120. controls.minDistance = 5; // 最小距离
  121. controls.maxDistance = 1000;
  122. controls.screenSpacePanning = false; // 允许相机平移
  123. // 设置最大和最小角度
  124. controls.maxPolarAngle = Math.PI / 2; // 最大角度 (90度) - 可视化平面
  125. controls.minPolarAngle = 0; // 最小角度 (0度) - 直接向下
  126. controls.target.set(0, 0, -2.2); // 控件的焦点,.object围绕它运行。它可以随时手动更新以更改控件的焦点。
  127. // controls.position0.set(200, 200, 500 )
  128. controls.update();
  129. // 检查 鼠标是否有操作
  130. renderer.domElement.addEventListener( 'pointerdown', function () {
  131. if(AutomaticRotationPerspectiveInterval !== undefined){
  132. clearInterval(AutomaticRotationPerspectiveInterval); // 停止定时任务的执行
  133. }
  134. AutomaticRotationPerspectiveTally = 0
  135. AutomaticRotationPerspectiveInterval = undefined
  136. } );
  137. // 定时 开始触发 自动旋转视角
  138. setInterval(() => {
  139. if(project === undefined || project.autoangle === undefined || project.autoangle === "None") return; // 直接跳过
  140. if(AutomaticRotationPerspectiveInterval === undefined){
  141. AutomaticRotationPerspectiveTally += 1
  142. if(AutomaticRotationPerspectiveTally === 3){
  143. console.log("project.autoangle:",project.autoangle)
  144. switch (project.autoangle) {
  145. case "Angle360": // 360度旋转
  146. self.AroundRotation(scene,project.autoangle_speed,project.autoangle_angle)
  147. break;
  148. case "Regainstate": // 回到原始视角
  149. self.Focus(self.GetScene())
  150. break;
  151. }
  152. }
  153. }
  154. }, 1000); // 每秒
  155. // 数据订阅
  156. window.pubSub = {
  157. list: {},
  158. // 订阅
  159. subscribe: function(key, fn) {
  160. if (!this.list[key]) this.list[key] = [];
  161. this.list[key].push(fn);
  162. },
  163. //取消订阅
  164. unsubscribe: function(key, fn) {
  165. let fnList = this.list[key];
  166. if (!fnList) return false;
  167. if (!fn) { // 不传入指定的方法,清空所用 key 下的订阅
  168. fnList && (fnList.length = 0);
  169. } else {
  170. fnList.forEach((item, index) => {
  171. item === fn && fnList.splice(index, 1);
  172. });
  173. }
  174. },
  175. // 发布
  176. publish: function(key, ...args) {
  177. if(this.list[key] === undefined) return;
  178. for (let fn of this.list[key]) fn.call(this, ...args);
  179. }
  180. }
  181. // this.storage.get(fxx)
  182. //
  183. // function fxx(xxx) {
  184. // console.log("fxx-------------------------",xxx)
  185. // }
  186. // 测试
  187. this.Test = function (rotationSpeed = 0.001) {
  188. console.log("Test-------------------------")
  189. return
  190. }
  191. // 测试
  192. function cubeDr(a, x, y, z) {
  193. var cubeGeo = new THREE.BoxGeometry(a, a, a);
  194. var cubeMat = new THREE.MeshPhongMaterial({
  195. color: 0xfff000 * Math.random()
  196. });
  197. var cube = new THREE.Mesh(cubeGeo, cubeMat);
  198. cube.position.set(x, y, z);
  199. cube.castShadow = true;
  200. scene.add(cube);
  201. return cube;
  202. }
  203. //endregion
  204. // --------------------- 核心 -----------------------
  205. //region Description
  206. // 核心方法
  207. //region Description
  208. // 舞台
  209. this.GetScene = function () {
  210. return scene
  211. }
  212. // 相机
  213. this.GetCamera = function () {
  214. return camera
  215. }
  216. //渲染器
  217. this.GetRenderer = function () {
  218. return renderer
  219. }
  220. // 获取 UUID 模型
  221. this.GetModelByUuid = function (uuid) {
  222. return scene.getObjectByProperty('uuid', uuid, true);
  223. }
  224. // 获取 UUID 模型 内部函数
  225. this.Model = function (uuid,fun) {
  226. fun(scene.getObjectByProperty('uuid', uuid, true));
  227. }
  228. // 设置显示比例
  229. this.setPixelRatio = function (pixelRatio) {
  230. renderer.setPixelRatio(pixelRatio);
  231. };
  232. // 设置大小
  233. this.setSize = function (width, height) {
  234. dom_width = width;
  235. dom_height = height;
  236. if (camera) {
  237. camera.aspect = dom_width / dom_height;
  238. camera.updateProjectionMatrix();
  239. }
  240. renderer.setSize(width, height);
  241. if ( rendererCss3 !== null ) {
  242. rendererCss3.setSize( dom.offsetWidth, dom.offsetHeight );
  243. }
  244. if ( rendererCss2 !== null ) {
  245. rendererCss2.setSize( dom.offsetWidth, dom.offsetHeight );
  246. }
  247. self.width = dom_width;
  248. self.height = dom_width;
  249. };
  250. //endregion
  251. // 鼠标
  252. //region Description
  253. //更新视角中心点
  254. this.orbitControls_target = function (position) {
  255. console.log("更新视角中心点:", position)
  256. controls.target.set(position.x, position.y, position.z); // 控件的焦点,.object围绕它运行。它可以随时手动更新以更改控件的焦点。
  257. controls.update();
  258. }
  259. // 计算场景最远距离,并控制参数
  260. function orbitControls_maxDistance() {
  261. // 计算场景中的包围盒
  262. function calculateSceneBoundingBox(scene) {
  263. const box = new THREE.Box3();
  264. scene.traverse((object) => {
  265. if (object.isMesh) {
  266. // 更新包围盒以包含当前对象的包围盒
  267. const objectBox = new THREE.Box3().setFromObject(object);
  268. box.union(objectBox);
  269. }
  270. });
  271. return box;
  272. }
  273. // 计算场景的包围盒
  274. const boundingBox = calculateSceneBoundingBox(scene);
  275. // 获取包围盒的尺寸
  276. const size = new THREE.Vector3();
  277. boundingBox.getSize(size);
  278. // 获取包围盒的中心
  279. const center = new THREE.Vector3();
  280. boundingBox.getCenter(center);
  281. // 计算最大尺寸距离 (从中心到某个角的距离)
  282. const maxDistance = center.distanceTo(boundingBox.max);
  283. // console.log("从中心到最远角的距离:", maxDistance);
  284. controls.maxDistance = maxDistance * 10;
  285. }
  286. // 鼠标选择初始化
  287. var OutlinePass_selectedObjects_Map = new Map();
  288. function OutlinePass_inte(){
  289. // console.log("OutlinePass_inte")
  290. // 清空所有选项
  291. selectedObjects = []
  292. self.Model_Selected_Clear()
  293. camera.lookAt(scene.position);
  294. compose = new EffectComposer(renderer);
  295. renderPass = new RenderPass(scene, camera);
  296. outlinePass = new OutlinePass(new THREE.Vector2(window.innerWidth,window.innerHeight),scene,camera);
  297. outlinePass.renderToScreen = true;
  298. outlinePass.selectedObjects = selectedObjects;
  299. compose.addPass(renderPass);
  300. compose.addPass(outlinePass);
  301. // https://threejs.org/examples/?q=webgl_postprocessing_outline#webgl_postprocessing_outline
  302. outlinePass.renderToScreen = true;
  303. outlinePass.edgeStrength = 3 //粗 0.01, 10
  304. outlinePass.edgeGlow = 1 //发光 0.0, 1
  305. outlinePass.edgeThickness = 2 //光晕粗 1, 4
  306. outlinePass.pulsePeriod = 0 //闪烁 0.0, 5
  307. outlinePass.usePatternTexture = false //是否使用贴图
  308. let visibleEdgeColor = '#00a1fd'; // 选择颜色
  309. let hiddenEdgeColor = '#00a1fd'; //遮挡部分颜色
  310. outlinePass.visibleEdgeColor.set(visibleEdgeColor);
  311. outlinePass.hiddenEdgeColor.set(hiddenEdgeColor);
  312. // let light = new THREE.AmbientLight(0x333333);
  313. // scene.add(light);
  314. //
  315. // 这里没有 渲染会报错
  316. let light = new THREE.SpotLight(0xFFFFFF);
  317. light.position.set(0, 40, 30);
  318. light.castShadow = true;
  319. light.shadow.mapSize.height = 1;
  320. light.shadow.mapSize.width = 1;
  321. light.angle = 0;
  322. scene.add(light);
  323. // light = new THREE.HemisphereLight(0xffffff, 0x444444, 0.6);
  324. // light.position.set(0, 200, 0);
  325. // scene.add(light);
  326. // const light = new THREE.DirectionalLight( 0xffffff, 0.6 );
  327. // light.position.set( 1, 1, 1 );
  328. // light.castShadow = true;
  329. // light.shadow.mapSize.width = 1024;
  330. // light.shadow.mapSize.height = 1024;
  331. //
  332. // const d = 10;
  333. //
  334. // light.shadow.camera.left = - d;
  335. // light.shadow.camera.right = d;
  336. // light.shadow.camera.top = d;
  337. // light.shadow.camera.bottom = - d;
  338. // light.shadow.camera.far = 1000;
  339. //
  340. // scene.add( light );
  341. }
  342. // 刷新
  343. function OutlinePass_selectedObjects_Refresh() {
  344. if (outlinePass == undefined) return;
  345. selectedObjects = [];
  346. OutlinePass_selectedObjects_Map.forEach(function(value, key) {
  347. // console.log(key, value);
  348. selectedObjects.push( value );
  349. })
  350. if (INTERSECTED != null){
  351. if(!OutlinePass_selectedObjects_Map.has(INTERSECTED.uuid)){
  352. selectedObjects.push( INTERSECTED );
  353. }
  354. }
  355. // console.log("selectedObjects:",selectedObjects)
  356. outlinePass.selectedObjects = selectedObjects;
  357. // render()
  358. }
  359. // 选中配置 选择颜色 ,遮挡部分颜色
  360. this.Model_Selected_Config = function(visibleEdgeColor="#00ff18",hiddenEdgeColor="#ff0000") {
  361. outlinePass.visibleEdgeColor.set(visibleEdgeColor);
  362. outlinePass.hiddenEdgeColor.set(hiddenEdgeColor);
  363. }
  364. // 添加
  365. this.Model_Selected_Add = function(Model) {
  366. OutlinePass_selectedObjects_Map.set(Model.uuid, Model)
  367. OutlinePass_selectedObjects_Refresh()
  368. }
  369. // 删除
  370. this.Model_Selected_Del = function(Model) {
  371. OutlinePass_selectedObjects_Map.delete(Model.uuid)
  372. OutlinePass_selectedObjects_Refresh()
  373. }
  374. // 清空
  375. this.Model_Selected_Clear = function() {
  376. OutlinePass_selectedObjects_Map.clear()
  377. OutlinePass_selectedObjects_Refresh()
  378. }
  379. //endregion
  380. // ------------------------------ 运动 ---------------------------------------------
  381. // 聚焦物体 -
  382. var startMove_is = false
  383. // 聚焦物体 - V1
  384. // this.startFocus = function (ob,MoveTime=1) {
  385. //
  386. // if(startMove_is) {
  387. // console.log("任务还没结束,不能开始新任务!")
  388. // return;
  389. // }
  390. // startMove_is = true // 开始
  391. // // if(ob.type != "Group") {
  392. // // console.log("Group != ")
  393. // // startMove_is = false
  394. // // return;
  395. // // }
  396. // if(ob.children.length == 0) {
  397. // console.log("children.length == 0!")
  398. // startMove_is = false
  399. // return;
  400. // }
  401. // if(ob.children[0].type != "PerspectiveCamera") {
  402. // console.log("children[0].type != PerspectiveCamera")
  403. // startMove_is = false
  404. // return;
  405. // }
  406. // let MoveList = []
  407. // MoveList.push([camera.position.x,camera.position.y,camera.position.z])
  408. // // MoveList.push([ob.position.x,ob.position.y,ob.position.z])
  409. // // MoveList.push([ob.children[0].position.x + ob.position.x, ob.children[0].position.y + ob.position.y, ob.children[0].position.z + ob.position.z])
  410. // MoveList.push([ob.children[0].matrixWorld.elements[12], ob.children[0].matrixWorld.elements[13], ob.children[0].matrixWorld.elements[14]])
  411. // // MoveList.push([ob.matrixWorld.elements[12], ob.matrixWorld.elements[13], ob.matrixWorld.elements[14]])
  412. // console.log("MoveList:",MoveList)
  413. //
  414. // let MoveListCurve = []
  415. // for(var item of MoveList) {
  416. // MoveListCurve.push(new THREE.Vector3(item[0], item[1], item[2]))
  417. // }
  418. // let curve = new THREE.CatmullRomCurve3(MoveListCurve)
  419. //
  420. // var curveList = curve.getPoints(20 * MoveTime)
  421. // // console.log("curveList:",curveList)
  422. //
  423. // var testIndex = 0
  424. // var t = setInterval(function () {
  425. // if(!startMove_is) {
  426. // curveList = []
  427. // testIndex = 0
  428. //
  429. // clearTimeout(t) //停止 t 定时器
  430. // return
  431. // }
  432. // // 模仿管道的镜头推进
  433. // if (curveList.length !== 0) {
  434. // if (testIndex < curveList.length ) {
  435. //
  436. // const point = curveList[testIndex] //获取样条曲线指定点坐标,作为相机的位置
  437. // const pointBox = curveList[testIndex+2] //获取样条曲线指定点坐标
  438. //
  439. // camera.position.set(point.x, point.y , point.z)
  440. // camera.lookAt(ob.matrixWorld.elements[12], ob.matrixWorld.elements[13], ob.matrixWorld.elements[14])
  441. //
  442. // controls.target.set(ob.matrixWorld.elements[12], ob.matrixWorld.elements[13], ob.matrixWorld.elements[14]); // 控件的焦点,.object围绕它运行。它可以随时手动更新以更改控件的焦点。
  443. // controls.update();
  444. // // camera.lookAt(ob.position.x,ob.position.y,ob.position.z)
  445. // testIndex += 1
  446. // } else {
  447. // curveList = []
  448. // testIndex = 0
  449. //
  450. // clearTimeout(t) //停止 t 定时器
  451. // startMove_is = false
  452. //
  453. //
  454. // // 更新视角中心点
  455. // controls.target.set(ob.matrixWorld.elements[12], ob.matrixWorld.elements[13], ob.matrixWorld.elements[14]); // 控件的焦点,.object围绕它运行。它可以随时手动更新以更改控件的焦点。
  456. // controls.update();
  457. //
  458. // }
  459. // }
  460. //
  461. // render()
  462. // }, 50)
  463. //
  464. // return
  465. // }
  466. // 围绕旋转 ,围绕对象 , 旋转速度{1~9,2} , 俯视角度{0~100,20}
  467. this.AroundRotation = function (ob,anglespeed_ = 2,targetHeight = 20) {
  468. // 自动计算包围盒
  469. const box = new THREE.Box3().setFromObject(ob);
  470. const size = box.getSize(new THREE.Vector3());
  471. const center = box.getCenter(new THREE.Vector3());
  472. // const targetHeight = 20; // 俯视角度的高度
  473. const radius = Math.max(size.x, size.z) *1.2; // 基于包围盒计算半径
  474. let anglespeed = 0.001 * anglespeed_; // 旋转速度
  475. let angle = Math.atan2(camera.position.z - center.z, camera.position.x - center.x); // 当前相机角度
  476. // 设置相机位置的函数
  477. function updateCameraPosition() {
  478. camera.position.x = radius * Math.cos(angle);
  479. camera.position.z = radius * Math.sin(angle);
  480. camera.position.y = targetHeight; // 固定Y坐标高度
  481. camera.lookAt(center); // 始终朝向场景中心
  482. }
  483. // 定时循环
  484. AutomaticRotationPerspectiveInterval = setInterval(() => {
  485. angle += anglespeed; // 旋转速度
  486. updateCameraPosition();
  487. renderer.render(scene, camera);
  488. }, 1000 / 60); // 每秒60帧
  489. }
  490. // 聚焦物体 - V2
  491. this.Focus = function (ob) {
  492. // 计算物体的边界盒
  493. const box = new THREE.Box3().setFromObject(ob);
  494. const size = box.getSize(new THREE.Vector3());
  495. const distance = size.length() * 2.0; // 增加一些距离,以便能看得到
  496. // 按照目标物体的大小和 20 度俯视角度计算相机位置
  497. const pitchAngle = THREE.MathUtils.degToRad(20); // 转换为弧度 20
  498. // const yawAngle = THREE.MathUtils.degToRad(angle); // 旋转 90 度
  499. const yawAngle = ob.rotation._y
  500. const targetEnd = box.getCenter(new THREE.Vector3());
  501. const targetPosition = new THREE.Vector3(
  502. targetEnd.x + distance * Math.sin(yawAngle),
  503. targetEnd.y + distance * Math.sin(pitchAngle),
  504. targetEnd.z + distance * Math.cos(yawAngle)
  505. );
  506. let initialPosition = new THREE.Vector3();
  507. initialPosition.copy(camera.position); // 记录初始位置
  508. // 在动画开始前,确保相机在正确的初始位置
  509. // camera.position.copy(targetPosition);
  510. // controls.target.copy(target);
  511. // controls.update(); // 更新控件
  512. const targetStart = new THREE.Vector3(0, 0, 0); // 初始中心点
  513. // const targetEnd = new THREE.Vector3(1, 1, 1); // 目标中心点
  514. targetStart.x = controls.target.x
  515. targetStart.y = controls.target.y
  516. targetStart.z = controls.target.z
  517. // console.log("targetStart:",targetStart)
  518. // console.log("targetEnd:",targetEnd)
  519. // console.log("initialPosition:",initialPosition)
  520. // console.log("targetPosition:",targetPosition)
  521. const distancex = initialPosition.distanceTo(targetPosition);
  522. // console.log("运动距离:", distancex);
  523. if(startMove_is) {
  524. console.log("任务还没结束,不能开始新任务!")
  525. return;
  526. }
  527. startMove_is = true // 开始
  528. // 动画属性
  529. const animationDuration = distancex * 2; // 动画持续 2 秒
  530. let animationDurationTime = 0; // 动画开始时间
  531. var It = setInterval(function () {
  532. animationDurationTime += 1;
  533. const t = Math.min(animationDurationTime / animationDuration, 1); // 归一化
  534. // console.log("t:",animationDurationTime)
  535. // 插值计算新的相机位置
  536. camera.position.x = THREE.MathUtils.lerp(initialPosition.x, targetPosition.x, t);
  537. camera.position.y = THREE.MathUtils.lerp(initialPosition.y, targetPosition.y, t);
  538. camera.position.z = THREE.MathUtils.lerp(initialPosition.z, targetPosition.z, t);
  539. // 插值控制目标位置
  540. controls.target.x = THREE.MathUtils.lerp(targetStart.x, targetEnd.x, t);
  541. controls.target.y = THREE.MathUtils.lerp(targetStart.y, targetEnd.y, t);
  542. controls.target.z = THREE.MathUtils.lerp(targetStart.z, targetEnd.z, t);
  543. // 更新控件目标
  544. camera.lookAt(controls.target); // 始终看向目标
  545. controls.update(); // 更新控件以应用新位置和目标
  546. // render()
  547. if(animationDuration <= animationDurationTime || !startMove_is){
  548. startMove_is = false
  549. clearTimeout(It) //停止 t 定时器
  550. }
  551. }, 10)
  552. }
  553. // 聚焦物体运动 -
  554. // this.startFocusMotion = function (ob,MoveList,MoveTime=1) {
  555. // if(startMove_is) {
  556. // console.log("任务还没结束,不能开始新任务!")
  557. // return;
  558. // }
  559. // startMove_is = true // 开始
  560. //
  561. // console.log("MoveList:",MoveList)
  562. //
  563. // let MoveListCurve = []
  564. // for(var item of MoveList) {
  565. // MoveListCurve.push(new THREE.Vector3(item[0], item[1], item[2]))
  566. // }
  567. // let curve = new THREE.CatmullRomCurve3(MoveListCurve)
  568. //
  569. // var curveList = curve.getPoints(20 * MoveTime)
  570. // // console.log("curveList:",curveList)
  571. //
  572. // var testIndex = 0
  573. // var t = setInterval(function () {
  574. // if(!startMove_is) {
  575. // curveList = []
  576. // testIndex = 0
  577. //
  578. // clearTimeout(t) //停止 t 定时器
  579. // }
  580. // // 模仿管道的镜头推进
  581. // if (curveList.length !== 0) {
  582. // if (testIndex < curveList.length ) {
  583. //
  584. // const point = curveList[testIndex] //获取样条曲线指定点坐标,作为相机的位置
  585. //
  586. // camera.position.set(point.x, point.y , point.z)
  587. //
  588. // camera.lookAt(ob[0], ob[1], ob[2])
  589. // controls.target.set(ob[0], ob[1], ob[2]); // 控件的焦点,.object围绕它运行。它可以随时手动更新以更改控件的焦点。
  590. // controls.update();
  591. // // camera.lookAt(ob.position.x,ob.position.y,ob.position.z)
  592. // testIndex += 1
  593. // } else {
  594. // curveList = []
  595. // testIndex = 0
  596. //
  597. // clearTimeout(t) //停止 t 定时器
  598. // startMove_is = false
  599. //
  600. //
  601. // // 更新视角中心点
  602. // controls.target.set(ob[0], ob[1], ob[2]); // 控件的焦点,.object围绕它运行。它可以随时手动更新以更改控件的焦点。
  603. // controls.update();
  604. //
  605. // }
  606. // }
  607. //
  608. // render()
  609. // }, 50)
  610. //
  611. // return
  612. // }
  613. // 路径移动
  614. this.startMove = function (MoveList,MoveTime=1,orbitControls_target=[]) {
  615. if(startMove_is) {
  616. console.log("任务还没结束,不能开始新任务!")
  617. return;
  618. }
  619. startMove_is = true // 开始
  620. if(MoveList.length == 0) {
  621. console.log("数据异常!")
  622. startMove_is = false
  623. return;
  624. }
  625. if(MoveList[0].length != 3) {
  626. console.log("数据异常!")
  627. startMove_is = false
  628. return;
  629. }
  630. let MoveListCurve = []
  631. for(var item of MoveList) {
  632. MoveListCurve.push(new THREE.Vector3(item[0], item[1], item[2]))
  633. }
  634. let curve = new THREE.CatmullRomCurve3(MoveListCurve)
  635. var curveList = curve.getPoints(20 * MoveTime)
  636. // console.log("curveList:",curveList)
  637. var testIndex = 0
  638. var t = setInterval(function () {
  639. if(!startMove_is) {
  640. curveList = []
  641. testIndex = 0
  642. clearTimeout(t) //停止 t 定时器
  643. }
  644. // 模仿管道的镜头推进
  645. if (curveList.length !== 0) {
  646. if (testIndex < curveList.length - 2) {
  647. const point = curveList[testIndex] //获取样条曲线指定点坐标,作为相机的位置
  648. const pointBox = curveList[testIndex+2] //获取样条曲线指定点坐标
  649. camera.position.set(point.x, point.y , point.z)
  650. camera.lookAt(pointBox.x, pointBox.y , pointBox.z)
  651. testIndex += 1
  652. } else {
  653. curveList = []
  654. testIndex = 0
  655. clearTimeout(t) //停止 t 定时器
  656. startMove_is = false
  657. // 更新视角中心点
  658. if(orbitControls_target.length == 3){
  659. controls.target.set(orbitControls_target[0], orbitControls_target[1], orbitControls_target[2]); // 控件的焦点,.object围绕它运行。它可以随时手动更新以更改控件的焦点。
  660. controls.update();
  661. }
  662. }
  663. }
  664. // render()
  665. }, 50)
  666. return
  667. }
  668. // 停止移动
  669. this.stopMove = function () {
  670. startMove_is = false
  671. }
  672. // 渲染
  673. //region Description
  674. // ---------- 渲染 -----------
  675. // renderer.setAnimationLoop( render );
  676. var clock = new THREE.Clock(); // only used for animations
  677. // function render() {
  678. // // console.log("render")
  679. //
  680. // // 渲染方式
  681. // if(compose != undefined) {
  682. // if(selectedObjects.length > 0){
  683. // compose.render()
  684. // }else {
  685. // renderer.render(scene, camera);
  686. // }
  687. // }else {
  688. // renderer.render(scene, camera);
  689. // }
  690. //
  691. // if ( rendererCss2 !== null ) {
  692. // rendererCss2.render( scene, camera );
  693. // }
  694. // if ( rendererCss3 !== null ) {
  695. // rendererCss3.render( scene, camera );
  696. // }
  697. //
  698. // }
  699. // this.Render = function () {
  700. // render()
  701. // }
  702. // 渲染
  703. // let lastRender = performance.now();
  704. function animate() {
  705. // let timestamp = timestamp.now();
  706. // if (timestamp - lastRender < 1000 / 60) return; // 限制为 60fps
  707. // lastRender = timestamp;
  708. if(window.ScenePlane !== undefined){
  709. scene.add( window.ScenePlane );
  710. }
  711. // renderer.render(scene, camera);
  712. if(compose != undefined) {
  713. if(selectedObjects.length > 0){
  714. compose.render()
  715. }else {
  716. renderer.render(scene, camera);
  717. }
  718. }else {
  719. renderer.render(scene, camera);
  720. }
  721. if ( rendererCss2 !== null ) {
  722. rendererCss2.render( scene, camera );
  723. }
  724. if ( rendererCss3 !== null ) {
  725. rendererCss3.render( scene, camera );
  726. }
  727. // 更新控制器
  728. // controls.update(); // 仅在需要时调用,例如当你使相机移动时
  729. if(window.ScenePlane !== undefined){
  730. scene.remove( window.ScenePlane );
  731. }
  732. // Animations 动画
  733. if(window.mixer != null){
  734. window.mixer.update( clock.getDelta() );
  735. }
  736. // requestAnimationFrame(animate);
  737. }
  738. //endregion
  739. //endregion
  740. // --------------------- 鼠标事件 -----------------------
  741. //region Description
  742. var Model_onEvents = {
  743. mousemove:undefined,
  744. click:undefined,
  745. dblclick:undefined,
  746. mousedown:undefined,
  747. }
  748. // 递归寻找上级可触发
  749. function finde_parent_choice(Ob) {
  750. if (Ob.choice) {
  751. return {Ob:Ob,is:true}
  752. }
  753. if(Ob.parent.isScene) return null,false
  754. var Obf = finde_parent_choice(Ob.parent)
  755. if(Obf.is){
  756. return Obf
  757. }
  758. return {Ob:null,is:false}
  759. }
  760. // 移动
  761. dom.addEventListener('mousemove', onMouseMove, false);
  762. function onMouseMove(event) {
  763. // console.log("onMouseMove:",event)
  764. if (event.isPrimary === false) return;
  765. // 将鼠标位置归一化为设备坐标。x 和 y 方向的取值范围是 (-1 to +1)
  766. mouse.x = (event.clientX / dom_width) * 2 - 1;
  767. mouse.y = -(event.clientY / dom_height) * 2 + 1;
  768. raycaster.setFromCamera(mouse, camera);
  769. // 计算物体和射线的焦点
  770. var intersects = raycaster.intersectObjects(scene.children);
  771. // console.log("intersects:",intersects)
  772. if (intersects.length > 0){
  773. //
  774. for (let n = 0;intersects.length > n;n++) {
  775. let objectP = intersects[n].object
  776. // console.log("objectP:",objectP)
  777. if(objectP === undefined) break;
  778. let objectF = finde_parent_choice(objectP)
  779. // console.log("finde_parent_choice:",objectF)
  780. if (objectF.is) {
  781. if(INTERSECTED !== null && INTERSECTED.uuid === objectF.Ob.uuid) break;
  782. INTERSECTED = objectF.Ob;
  783. // console.log("移入:",INTERSECTED)
  784. if (Model_onEvents.mousemove !== undefined) Model_onEvents.mousemove(INTERSECTED)
  785. if(INTERSECTED.scriptsf !== undefined ){
  786. INTERSECTED.scriptsf.forEach(scriptf => {
  787. if(scriptf["onMouseMoveIn"] !== undefined){
  788. scriptf.onMouseMoveIn()
  789. }
  790. })
  791. }
  792. break;
  793. }
  794. // for (let xn = 0; 10 > xn; xn++) {
  795. // console.log(xn,"-objectP:",objectP)
  796. // if(objectP == null) break;
  797. // // if (objectP.type == "Object3D") {
  798. // if (INTERSECTED !== objectP) {
  799. // console.log("intersects[0].object:", intersects[0].object.parent)
  800. // if (objectP.choice === true) {
  801. // INTERSECTED = objectP;
  802. // if (Model_onEvents.mousemove !== undefined) Model_onEvents.mousemove(INTERSECTED)
  803. // break;
  804. // }
  805. // }
  806. // // }
  807. // objectP = objectP.parent
  808. // }
  809. }
  810. // console.log("onMouseMove:",INTERSECTED)
  811. }else {
  812. // console.log("移出:",INTERSECTED)
  813. if(INTERSECTED !== null && INTERSECTED.scriptsf !== undefined ){
  814. INTERSECTED.scriptsf.forEach(scriptf => {
  815. if(scriptf["onMouseMoveOut"] !== undefined){
  816. scriptf.onMouseMoveOut()
  817. }
  818. })
  819. }
  820. INTERSECTED = null;
  821. }
  822. OutlinePass_selectedObjects_Refresh()
  823. // render() // 可优化空间
  824. }
  825. this.Model_onMouseMove = function (fun) {
  826. Model_onEvents.mousemove = fun
  827. }
  828. //单击延时触发
  829. var clickTimeId,clickTimeIs = false;
  830. // 单击
  831. dom.addEventListener('click', onClick, false);
  832. function onClick(event) {
  833. // console.log("onClick:",INTERSECTED)
  834. if(INTERSECTED === null){return}
  835. // 取消上次延时未执行的方法
  836. clearTimeout(clickTimeId);
  837. const INTERSECTED_ = INTERSECTED
  838. //执行延时
  839. clickTimeId = setTimeout( function () {
  840. if (INTERSECTED_) {
  841. if(Model_onEvents.click != undefined) Model_onEvents.click(INTERSECTED)
  842. }
  843. // console.log("onClick:",INTERSECTED)
  844. if(INTERSECTED_.scriptsf !== undefined ){
  845. INTERSECTED_.scriptsf.forEach(scriptf => {
  846. if(scriptf["onClick"] !== undefined){
  847. scriptf.onClick()
  848. }
  849. })
  850. }
  851. // render()
  852. }, 250);
  853. }
  854. this.Model_onClick = function (fun) {
  855. Model_onEvents.click = fun
  856. }
  857. // 双击
  858. dom.addEventListener('dblclick', onDblclick, false);
  859. function onDblclick(event) {
  860. if(INTERSECTED === null){return}
  861. clearTimeout(clickTimeId); // 取消上次延时未执行的方法
  862. if (INTERSECTED) {
  863. if(Model_onEvents.dblclick != undefined) Model_onEvents.dblclick(INTERSECTED)
  864. }
  865. if(INTERSECTED.scriptsf !== undefined ){
  866. INTERSECTED.scriptsf.forEach(scriptf => {
  867. if(scriptf["onDblclick"] !== undefined){
  868. scriptf.onDblclick()
  869. }
  870. })
  871. }
  872. // render()
  873. }
  874. this.Model_onDblclick = function (fun) {
  875. Model_onEvents.dblclick = fun
  876. }
  877. // 右击---
  878. dom.addEventListener('contextmenu', onMousedown, false);
  879. function onMousedown(event) {
  880. if(clickTimeIs) return;
  881. clickTimeIs = true;
  882. setTimeout( function () {
  883. clickTimeIs = false;
  884. }, 2000); // 防止 反复触发退出
  885. if(Model_onEvents.mousedown != undefined) Model_onEvents.mousedown(INTERSECTED,event)
  886. onBackclick()
  887. // render()
  888. }
  889. this.Model_onMousedown = function (fun) {
  890. Model_onEvents.mousedown = fun
  891. }
  892. //
  893. // this.ondBlclick_Model = function (position) {
  894. // console.log("更新视角中心点:", position)
  895. // controls.target.set(position.x, position.y, position.z); // 控件的焦点,.object围绕它运行。它可以随时手动更新以更改控件的焦点。
  896. // controls.update();
  897. // }
  898. //endregion
  899. // --------------------- 项目 -----------------------
  900. //region Description
  901. // 本地调试模式
  902. this.LocalRun = function ( parkId = 0 ) {
  903. window.parkId = parkId
  904. new _Storage(function(result) {
  905. console.log(result);
  906. // scene = result.scene
  907. loadJson(result,"000000"+parkId)
  908. });
  909. }
  910. var loadProject_Map = []; //ProjectID 映射
  911. var Now_ProjectID = ""; // 当前 ProjectID
  912. this.load = function (){
  913. console.log("加载完毕")
  914. }
  915. // 加载项目
  916. this.LoadProject = function (ProjectID) {
  917. if(Now_ProjectID == ProjectID){ return }
  918. console.log('[' + /\d\d\:\d\d\:\d\d/.exec(new Date())[0] + ']', "加载 ProjectID:", ProjectID)
  919. // 是否加载与缓存过
  920. if (loadProject_Map[ProjectID] == undefined) {
  921. var httpRequest = new XMLHttpRequest();//第一步:建立所需的对象
  922. httpRequest.open('GET', './GetProject?T_ViewID=' + ProjectID, true);//第二步:打开连接 将请求参数写在url中 ps:"./Ptest.php?name=test&nameone=testone"
  923. httpRequest.send();//第三步:发送请求 将请求参数写在URL中
  924. httpRequest.onreadystatechange = function () {
  925. if (httpRequest.readyState == 4 && httpRequest.status == 200) {
  926. var json = JSON.parse(httpRequest.responseText);//获取到json字符串,还需解析
  927. console.log(json);
  928. if (json.Code != 200) {
  929. console.log("ProjectID 错误!", ProjectID)
  930. return "ProjectID 错误!"
  931. }
  932. var json = JSON.parse(json.Data.T_url);//获取到json字符串,还需解析
  933. console.log(json);
  934. window.parkList = json
  935. window.parkId = 0
  936. // 如果需要兼容低版本的浏览器,需要判断一下FileReader对象是否存在。
  937. if (window.FileReader) {
  938. blobLoad(ProjectID, window.parkList[window.parkId].T_url)
  939. } else {
  940. console.log('你的浏览器不支持读取文件');
  941. loadProject_Map[ProjectID] = src
  942. }
  943. }
  944. };
  945. } else {
  946. console.log('[' + /\d\d\:\d\d\:\d\d/.exec(new Date())[0] + ']', "缓存加载 ProjectID:", ProjectID)
  947. f_load(ProjectID)
  948. }
  949. }
  950. this.LoadLocal = function () {
  951. var httpRequest = new XMLHttpRequest();//第一步:建立所需的对象
  952. httpRequest.open('GET', './static/LocalProject/main.json', true);//第二步:打开连接 将请求参数写在url中 ps:"./Ptest.php?name=test&nameone=testone"
  953. httpRequest.responseType = 'json'; // 设置响应类型为 JSON
  954. httpRequest.onload = function() {
  955. if (httpRequest.status >= 200 && httpRequest.status < 300) {
  956. var jsonArray = httpRequest.response; // 直接获取 JSON 数组
  957. console.log("jsonArray:",jsonArray);
  958. window.parkList = jsonArray
  959. window.parkId = 0
  960. // 如果需要兼容低版本的浏览器,需要判断一下FileReader对象是否存在。
  961. if (window.FileReader) {
  962. blobLoad("00000", window.parkList[window.parkId].T_url)
  963. } else {
  964. console.log('你的浏览器不支持读取文件');
  965. loadProject_Map[ProjectID] = src
  966. }
  967. }
  968. };
  969. httpRequest.send();//第三步:发送请求 将请求参数写在URL中
  970. }
  971. // 解压并更新舞台
  972. function f_load(ProjectID) {
  973. console.log('[' + /\d\d\:\d\d\:\d\d/.exec(new Date())[0] + ']', "开始加载 file:", loadProject_Map[ProjectID])
  974. // 解压模型
  975. // var promise = fetch('../static/16635717199e4e03e8-8850-4152-9c08-9c203c882f7a.zip')
  976. var promise = fetch(loadProject_Map[ProjectID])
  977. .then((d) => d.arrayBuffer())
  978. promise = promise.then(function (data) {
  979. //响应的内容
  980. console.log("data:", data);
  981. const decompressed = unzipSync(new Uint8Array(data), {
  982. // You may optionally supply a filter for files. By default, all files in a
  983. // ZIP archive are extracted, but a filter can save resources by telling
  984. // the library not to decompress certain files
  985. filter(file) {
  986. // Don't decompress the massive image or any files larger than 10 MiB
  987. return file;
  988. }
  989. });
  990. console.log('[' + /\d\d\:\d\d\:\d\d/.exec(new Date())[0] + ']', "file:", decompressed['app.json'])
  991. var obj = JSON.parse(new TextDecoder().decode(decompressed['app.json']));
  992. loadJson(obj,ProjectID);// 加载场景
  993. // self.setSize(dom_width, dom_height);
  994. // orbitControls() // 鼠标移动 -轨道控制
  995. Now_ProjectID = ProjectID
  996. console.log('[' + /\d\d\:\d\d\:\d\d/.exec(new Date())[0] + ']', "JSON obj:", obj)
  997. }).catch(function (err) {
  998. console.log(err);
  999. })
  1000. }
  1001. // 导入 json
  1002. function loadJson(json,ProjectID) {
  1003. let loader = new THREE.ObjectLoader(); // 加载
  1004. console.log("loadJson:", json)
  1005. project = json.project;
  1006. // if (project.vr !== undefined) renderer.xr.enabled = project.vr;
  1007. // if (project.shadows !== undefined) renderer.shadowMap.enabled = project.shadows;
  1008. // if (project.shadowType !== undefined) renderer.shadowMap.type = project.shadowType;
  1009. // if (project.toneMapping !== undefined) renderer.toneMapping = project.toneMapping;
  1010. // if (project.toneMappingExposure !== undefined) renderer.toneMappingExposure = project.toneMappingExposure;
  1011. // if (project.physicallyCorrectLights !== undefined) renderer.physicallyCorrectLights = project.physicallyCorrectLights;
  1012. console.log("rendererCss2:", rendererCss2)
  1013. if ( rendererCss2 !== null ) {
  1014. rendererCss2.clean()
  1015. rendererCss3.clean()
  1016. }
  1017. scene = loader.parse(json.scene);
  1018. // camera = loader.parse(json.camera);
  1019. // console.log("json.camera:",json.camera)
  1020. // console.log("camera:",camera)
  1021. camera.position.x = json.camera.object.matrix[12]
  1022. camera.position.y = json.camera.object.matrix[13]
  1023. camera.position.z = json.camera.object.matrix[14]
  1024. // camera.aspect = dom_width / dom_height;
  1025. // camera.updateProjectionMatrix();
  1026. // renderer.setSize(dom_width, dom_height);
  1027. // 中心点
  1028. controls.target.set(0, 0, 0); // 控件的焦点,.object围绕它运行。它可以随时手动更新以更改控件的焦点。
  1029. controls.update();
  1030. //////--------------
  1031. // ScenePlane 场景平面
  1032. if ( project.sceneplane !== undefined ){
  1033. // console.log("sceneplane:",project.sceneplane)
  1034. switch ( project.sceneplane ) {
  1035. case 'None':
  1036. window.ScenePlane = undefined
  1037. break;
  1038. case 'Grass': //草地平面
  1039. const gt = new THREE.TextureLoader().load( './static/js/img/cd.jpg' );
  1040. const gg = new THREE.PlaneGeometry( 300, 300 );
  1041. const gm = new THREE.MeshPhongMaterial( { color: 0xffffff, map: gt } );
  1042. window.ScenePlane = new THREE.Mesh( gg, gm );
  1043. window.ScenePlane.rotation.x = - Math.PI / 2;
  1044. // window.ScenePlane.rotation.y = -0.1
  1045. window.ScenePlane.material.map.repeat.set( 64, 64 );
  1046. window.ScenePlane.material.map.wrapS = THREE.RepeatWrapping;
  1047. window.ScenePlane.material.map.wrapT = THREE.RepeatWrapping;
  1048. window.ScenePlane.material.map.colorSpace = THREE.SRGBColorSpace;
  1049. // note that because the ground does not cast a shadow, .castShadow is left false
  1050. window.ScenePlane.receiveShadow = true;
  1051. break;
  1052. }
  1053. }
  1054. //// ------------
  1055. events = {
  1056. init: [],
  1057. keydown: [],
  1058. keyup: [],
  1059. onMouseMoveIn: [], //鼠标移入
  1060. onMouseMoveOut: [], //鼠标移入
  1061. onClick: [], //鼠标单击
  1062. onDblclick: [], //鼠标双击
  1063. onBackclick: [], //鼠标右击 退后
  1064. renderer: [],
  1065. update: []
  1066. };
  1067. window.Getevents = function () {
  1068. return events
  1069. }
  1070. var scriptWrapParams = 'iot3d,renderer,scene,camera';
  1071. var scriptWrapResultObj = {};
  1072. for (var eventKey in events) {
  1073. scriptWrapParams += ',' + eventKey;
  1074. scriptWrapResultObj[eventKey] = eventKey;
  1075. }
  1076. var scriptWrapResult = JSON.stringify(scriptWrapResultObj).replace(/\"/g, '');
  1077. //执行代码
  1078. // 递归遍历 所有脚本 并添加
  1079. function traverseChildrenScript(object) {
  1080. if ( object.scripts !== undefined && object.scripts.length > 0 ) {
  1081. console.log("addObjectScript:",object.uuid,object.scripts)
  1082. object.scriptsf = []
  1083. var scripts = object.scripts;
  1084. for ( var i = 0; i < scripts.length; i ++ ) {
  1085. // 每个 script 代码
  1086. var script = scripts[i];
  1087. var functions = ( new Function( scriptWrapParams, script.source + '\nreturn ' + scriptWrapResult + ';' ).bind( object ) )( this, renderer, scene, camera );
  1088. // console.log("functions.name",functions)
  1089. object.scriptsf.push(functions)
  1090. for ( var name in functions ) {
  1091. // console.log("functions.name",name)
  1092. if ( functions[ name ] === undefined ) continue;
  1093. if ( events[ name ] === undefined ) {
  1094. console.warn( 'APP.Player: Event type not supported (', name, ')' );
  1095. continue;
  1096. }
  1097. if(name !== "update"){
  1098. events[ name ].push( functions[ name ].bind( object ) );
  1099. }else {
  1100. var subSN = SeekParameterNodes(object)
  1101. // console.log("subSN:",subSN)
  1102. // 订阅
  1103. pubSub.subscribe(subSN, data => {
  1104. // console.log("subSN:",subSN,data);
  1105. functions["update"].bind( object )( data )
  1106. })
  1107. }
  1108. }
  1109. }
  1110. }
  1111. // 遍历当前对象的所有子对象
  1112. object.children.forEach(child => {
  1113. traverseChildrenScript(child); // 递归调用
  1114. });
  1115. }
  1116. traverseChildrenScript(scene)
  1117. // console.log("events:", events)
  1118. dispatch(events.init, arguments);
  1119. console.log("加载完成 ProjectID:",ProjectID)
  1120. // 场景加载后 视角归为
  1121. self.setSize(window.innerWidth, window.innerHeight);
  1122. orbitControls_maxDistance() // 计算场景最远距离,并控制参数
  1123. OutlinePass_inte() // 鼠标选择初始化
  1124. };
  1125. // 文件缓存本地
  1126. function blobLoad(ProjectID, src) {
  1127. self.loading_open() //
  1128. console.log('[' + /\d\d\:\d\d\:\d\d/.exec(new Date())[0] + ']', "文件缓存本地 :", ProjectID)
  1129. // let self = this;
  1130. const req = new XMLHttpRequest();
  1131. req.open("GET", src, true);
  1132. req.responseType = "blob";
  1133. req.onload = function () {
  1134. // Onload is triggered even on 404
  1135. // so we need to check the status code
  1136. if (this.status === 200) {
  1137. const videoBlob = this.response;
  1138. console.log("videoBlob:", videoBlob)
  1139. const blobSrc = URL.createObjectURL(videoBlob); // IE10+
  1140. console.log("blobSrc:", blobSrc)
  1141. loadProject_Map[ProjectID] = blobSrc
  1142. console.log('[' + /\d\d\:\d\d\:\d\d/.exec(new Date())[0] + ']', "文件缓存本地完成 ProjectID:", ProjectID)
  1143. f_load(ProjectID)
  1144. }
  1145. self.loading_close()
  1146. };
  1147. //监听进度事件
  1148. req.addEventListener("progress", function (evt) {
  1149. if (evt.lengthComputable) {
  1150. var percentComplete = evt.loaded / evt.total;
  1151. //进度
  1152. console.log('[' + /\d\d\:\d\d\:\d\d/.exec(new Date())[0] + ']', "ProjectID:", ProjectID, " 进度:", (percentComplete * 100) + "%")
  1153. self.loading_text("模型加载中... "+parseInt(percentComplete * 100) + "%") // 替换内容
  1154. }
  1155. }, false);
  1156. req.onerror = function () {
  1157. // Error
  1158. console.log("blobLoad Error!", src)
  1159. loadProject_Map[ProjectID] = src
  1160. };
  1161. req.send();
  1162. }
  1163. //endregion
  1164. // --------------------- 脚本 -----------------------
  1165. //region Description
  1166. // var time, startTime;
  1167. // startTime = performance.now();
  1168. // // 创建一个每秒执行一次的定时循环
  1169. // setInterval(function() {
  1170. // // 在这里编写需要重复执行的代码
  1171. // time = performance.now();
  1172. // const rendertime = { time: time - startTime }
  1173. // // console.log("renderer:",rendertime)
  1174. // try {
  1175. // dispatch( events.renderer, rendertime);
  1176. // } catch ( e ) {
  1177. // console.error( ( e.message || e ), ( e.stack || '' ) );
  1178. // }
  1179. //
  1180. // }, 1000); // 1000 毫秒 = 1 秒
  1181. function dispatch( array, event ) {
  1182. for ( var i = 0, l = array.length; i < l; i ++ ) {
  1183. array[ i ]( event );
  1184. }
  1185. }
  1186. //
  1187. // function animate() {
  1188. //
  1189. // time = performance.now();
  1190. //
  1191. //
  1192. //
  1193. // prevTime = time;
  1194. //
  1195. // }
  1196. // this.play = function () {
  1197. //
  1198. // if ( renderer.xr.enabled ) dom.append( vrButton );
  1199. //
  1200. // startTime = prevTime = performance.now();
  1201. //
  1202. // document.addEventListener( 'keydown', oneyDown );
  1203. // document.addEventListener( 'keyup', onKeyUp );
  1204. // document.addEventListener( 'pointerup', onPointerUp );
  1205. // document.addEventListener( 'pointermove', onPointerMove );
  1206. //
  1207. // // dispatch( events.start, arguments );
  1208. //
  1209. // renderer.setAnimationLoop( animate );
  1210. //
  1211. // };
  1212. this.render = function ( time ) {
  1213. dispatch( events.update, { time: time * 1000, delta: 0 /* TODO */ } );
  1214. renderer.render( scene, camera );
  1215. };
  1216. this.dispose = function () {
  1217. renderer.dispose();
  1218. camera = undefined;
  1219. scene = undefined;
  1220. };
  1221. //
  1222. function onKeyDown( event ) {
  1223. dispatch( events.keydown, event );
  1224. }
  1225. function onKeyUp( event ) {
  1226. dispatch( events.keyup, event );
  1227. }
  1228. // function onPointerDown( event ) {
  1229. // dispatch( events.pointerdown, event );
  1230. //
  1231. // }
  1232. //
  1233. // function onPointerUp( event ) {
  1234. // dispatch( events.pointerup, event );
  1235. //
  1236. // }
  1237. //
  1238. function onBackclick( event ) {
  1239. dispatch( events.onBackclick, event );
  1240. }
  1241. function upDate( event ) {
  1242. try {
  1243. dispatch( events.update, event );
  1244. } catch ( e ) {
  1245. console.error( ( e.message || e ), ( e.stack || '' ) );
  1246. }
  1247. }
  1248. //endregion
  1249. // --------------------- 功能 -----------------------
  1250. //region Description
  1251. // this.BackgroundScene = function () {
  1252. // var urls = [
  1253. // './static/js/img/posx.jpg',
  1254. // './static/js/img/negx.jpg',
  1255. // './static/js/img/posy.jpg',
  1256. // './static/js/img/negy.jpg',
  1257. // './static/js/img/posz.jpg',
  1258. // './static/js/img/negz.jpg'
  1259. // ];
  1260. //
  1261. // var cubeLoader = new THREE.CubeTextureLoader();
  1262. // scene.background = cubeLoader.load(urls);
  1263. // setTimeout(function(){
  1264. // render()
  1265. // },3000);
  1266. //
  1267. // }
  1268. // 屏幕坐标与世界坐标
  1269. this.scene_3Dto2D = function (position) {
  1270. const worldVector = new THREE.Vector3(
  1271. position.x,
  1272. position.y,
  1273. position.z
  1274. );
  1275. const standardVec = worldVector.project(camera);
  1276. const centerX = dom_width / 2;
  1277. const centerY = dom_height / 2;
  1278. const screenX = Math.round(centerX * standardVec.x + centerX);
  1279. const screenY = Math.round(-centerY * standardVec.y + centerY);
  1280. console.log("screen:", screenX, screenY)
  1281. return screenX, screenY
  1282. }
  1283. //endregion
  1284. console.log("window.runmode:",window.runmode)
  1285. if(window.runmode === undefined) window.runmode = 2
  1286. // 开始 加载场景
  1287. if (window.runmode === 0){
  1288. this.LocalRun()// 本地调试模式
  1289. }else if(window.runmode === 1){
  1290. this.LoadProject(window.T_ViewID) // 在线
  1291. }else if(window.runmode === 2){
  1292. this.LoadLocal() // 离线
  1293. }
  1294. }
  1295. export {IOT3D};
  1296. new IOT3D();