IOT3D-.js 44 KB

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