IOT3D.js 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526
  1. import * as THREE from '../build/three.module.js';
  2. import {unzipSync} from './libs/fflate.module.js';
  3. import {FontLoader} from './jsm/loaders/FontLoader.js';
  4. import {CinematicCamera} from './jsm/cameras/CinematicCamera.js';
  5. import { OrbitControls } from './jsm/controls/OrbitControls.js';
  6. import { EffectComposer } from './jsm/postprocessing/EffectComposer.js';
  7. import { RenderPass } from './jsm/postprocessing/RenderPass.js';
  8. import { ShaderPass } from './jsm/postprocessing/ShaderPass.js';
  9. import { OutlinePass } from './jsm/postprocessing/OutlinePass.js';
  10. import { CSS3DRenderer } from './jsm/renderers/CSS3DRenderer.js';
  11. import { CSS2DRenderer } from './jsm/renderers/CSS2DRenderer.js';
  12. import { Storage as _Storage } from './libs/Storage.js';
  13. // --------------------- 折叠 -----------------------
  14. //region Description
  15. //endregion
  16. // iot3d = new IOT3D("iot3d",false); // 创建应用 (div_id,运行模式)
  17. function IOT3D(iot3d,runmode = 1) {
  18. window.iot3d = this
  19. window.runmode = runmode
  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.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.send();//第三步:发送请求 将请求参数写在URL中
  954. httpRequest.onreadystatechange = function () {
  955. if (httpRequest.readyState == 4 && httpRequest.status == 200) {
  956. var json = JSON.parse(httpRequest.responseText);//获取到json字符串,还需解析
  957. console.log(json);
  958. window.parkList = json
  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. }
  970. // 解压并更新舞台
  971. function f_load(ProjectID) {
  972. console.log('[' + /\d\d\:\d\d\:\d\d/.exec(new Date())[0] + ']', "开始加载 file:", loadProject_Map[ProjectID])
  973. // 解压模型
  974. // var promise = fetch('../static/16635717199e4e03e8-8850-4152-9c08-9c203c882f7a.zip')
  975. var promise = fetch(loadProject_Map[ProjectID])
  976. .then((d) => d.arrayBuffer())
  977. promise = promise.then(function (data) {
  978. //响应的内容
  979. console.log("data:", data);
  980. const decompressed = unzipSync(new Uint8Array(data), {
  981. // You may optionally supply a filter for files. By default, all files in a
  982. // ZIP archive are extracted, but a filter can save resources by telling
  983. // the library not to decompress certain files
  984. filter(file) {
  985. // Don't decompress the massive image or any files larger than 10 MiB
  986. return file;
  987. }
  988. });
  989. console.log('[' + /\d\d\:\d\d\:\d\d/.exec(new Date())[0] + ']', "file:", decompressed['app.json'])
  990. var obj = JSON.parse(new TextDecoder().decode(decompressed['app.json']));
  991. loadJson(obj,ProjectID);// 加载场景
  992. // self.setSize(dom_width, dom_height);
  993. // orbitControls() // 鼠标移动 -轨道控制
  994. Now_ProjectID = ProjectID
  995. console.log('[' + /\d\d\:\d\d\:\d\d/.exec(new Date())[0] + ']', "JSON obj:", obj)
  996. }).catch(function (err) {
  997. console.log(err);
  998. })
  999. }
  1000. // 导入 json
  1001. function loadJson(json,ProjectID) {
  1002. let loader = new THREE.ObjectLoader(); // 加载
  1003. console.log("loadJson:", json)
  1004. project = json.project;
  1005. // if (project.vr !== undefined) renderer.xr.enabled = project.vr;
  1006. // if (project.shadows !== undefined) renderer.shadowMap.enabled = project.shadows;
  1007. // if (project.shadowType !== undefined) renderer.shadowMap.type = project.shadowType;
  1008. // if (project.toneMapping !== undefined) renderer.toneMapping = project.toneMapping;
  1009. // if (project.toneMappingExposure !== undefined) renderer.toneMappingExposure = project.toneMappingExposure;
  1010. // if (project.physicallyCorrectLights !== undefined) renderer.physicallyCorrectLights = project.physicallyCorrectLights;
  1011. rendererCss2.clean()
  1012. rendererCss3.clean()
  1013. scene = loader.parse(json.scene);
  1014. // camera = loader.parse(json.camera);
  1015. // console.log("json.camera:",json.camera)
  1016. // console.log("camera:",camera)
  1017. camera.position.x = json.camera.object.matrix[12]
  1018. camera.position.y = json.camera.object.matrix[13]
  1019. camera.position.z = json.camera.object.matrix[14]
  1020. // camera.aspect = dom_width / dom_height;
  1021. // camera.updateProjectionMatrix();
  1022. // renderer.setSize(dom_width, dom_height);
  1023. // 中心点
  1024. controls.target.set(0, 0, 0); // 控件的焦点,.object围绕它运行。它可以随时手动更新以更改控件的焦点。
  1025. controls.update();
  1026. //////--------------
  1027. // ScenePlane 场景平面
  1028. if ( project.sceneplane !== undefined ){
  1029. // console.log("sceneplane:",project.sceneplane)
  1030. switch ( project.sceneplane ) {
  1031. case 'None':
  1032. window.ScenePlane = undefined
  1033. break;
  1034. case 'Grass': //草地平面
  1035. const gt = new THREE.TextureLoader().load( './static/js/img/cd.jpg' );
  1036. const gg = new THREE.PlaneGeometry( 300, 300 );
  1037. const gm = new THREE.MeshPhongMaterial( { color: 0xffffff, map: gt } );
  1038. window.ScenePlane = new THREE.Mesh( gg, gm );
  1039. window.ScenePlane.rotation.x = - Math.PI / 2;
  1040. // window.ScenePlane.rotation.y = -0.1
  1041. window.ScenePlane.material.map.repeat.set( 64, 64 );
  1042. window.ScenePlane.material.map.wrapS = THREE.RepeatWrapping;
  1043. window.ScenePlane.material.map.wrapT = THREE.RepeatWrapping;
  1044. window.ScenePlane.material.map.colorSpace = THREE.SRGBColorSpace;
  1045. // note that because the ground does not cast a shadow, .castShadow is left false
  1046. window.ScenePlane.receiveShadow = true;
  1047. break;
  1048. }
  1049. }
  1050. //// ------------
  1051. events = {
  1052. init: [],
  1053. keydown: [],
  1054. keyup: [],
  1055. onMouseMoveIn: [], //鼠标移入
  1056. onMouseMoveOut: [], //鼠标移入
  1057. onClick: [], //鼠标单击
  1058. onDblclick: [], //鼠标双击
  1059. onBackclick: [], //鼠标右击 退后
  1060. renderer: [],
  1061. update: []
  1062. };
  1063. window.Getevents = function () {
  1064. return events
  1065. }
  1066. var scriptWrapParams = 'iot3d,renderer,scene,camera';
  1067. var scriptWrapResultObj = {};
  1068. for (var eventKey in events) {
  1069. scriptWrapParams += ',' + eventKey;
  1070. scriptWrapResultObj[eventKey] = eventKey;
  1071. }
  1072. var scriptWrapResult = JSON.stringify(scriptWrapResultObj).replace(/\"/g, '');
  1073. //执行代码
  1074. // 递归遍历 所有脚本 并添加
  1075. function traverseChildrenScript(object) {
  1076. if ( object.scripts !== undefined && object.scripts.length > 0 ) {
  1077. console.log("addObjectScript:",object.uuid,object.scripts)
  1078. object.scriptsf = []
  1079. var scripts = object.scripts;
  1080. for ( var i = 0; i < scripts.length; i ++ ) {
  1081. // 每个 script 代码
  1082. var script = scripts[i];
  1083. var functions = ( new Function( scriptWrapParams, script.source + '\nreturn ' + scriptWrapResult + ';' ).bind( object ) )( this, renderer, scene, camera );
  1084. // console.log("functions.name",functions)
  1085. object.scriptsf.push(functions)
  1086. for ( var name in functions ) {
  1087. // console.log("functions.name",name)
  1088. if ( functions[ name ] === undefined ) continue;
  1089. if ( events[ name ] === undefined ) {
  1090. console.warn( 'APP.Player: Event type not supported (', name, ')' );
  1091. continue;
  1092. }
  1093. if(name !== "update"){
  1094. events[ name ].push( functions[ name ].bind( object ) );
  1095. }else {
  1096. var subSN = SeekParameterNodes(object)
  1097. // console.log("subSN:",subSN)
  1098. // 订阅
  1099. pubSub.subscribe(subSN, data => {
  1100. // console.log("subSN:",subSN,data);
  1101. functions["update"].bind( object )( data )
  1102. })
  1103. }
  1104. }
  1105. }
  1106. }
  1107. // 遍历当前对象的所有子对象
  1108. object.children.forEach(child => {
  1109. traverseChildrenScript(child); // 递归调用
  1110. });
  1111. }
  1112. traverseChildrenScript(scene)
  1113. // console.log("events:", events)
  1114. dispatch(events.init, arguments);
  1115. console.log("加载完成 ProjectID:",ProjectID)
  1116. // 场景加载后 视角归为
  1117. self.setSize(window.innerWidth, window.innerHeight);
  1118. orbitControls_maxDistance() // 计算场景最远距离,并控制参数
  1119. OutlinePass_inte() // 鼠标选择初始化
  1120. };
  1121. // 文件缓存本地
  1122. function blobLoad(ProjectID, src) {
  1123. self.loading_open() //
  1124. console.log('[' + /\d\d\:\d\d\:\d\d/.exec(new Date())[0] + ']', "文件缓存本地 :", ProjectID)
  1125. // let self = this;
  1126. const req = new XMLHttpRequest();
  1127. req.open("GET", src, true);
  1128. req.responseType = "blob";
  1129. req.onload = function () {
  1130. // Onload is triggered even on 404
  1131. // so we need to check the status code
  1132. if (this.status === 200) {
  1133. const videoBlob = this.response;
  1134. console.log("videoBlob:", videoBlob)
  1135. const blobSrc = URL.createObjectURL(videoBlob); // IE10+
  1136. console.log("blobSrc:", blobSrc)
  1137. loadProject_Map[ProjectID] = blobSrc
  1138. console.log('[' + /\d\d\:\d\d\:\d\d/.exec(new Date())[0] + ']', "文件缓存本地完成 ProjectID:", ProjectID)
  1139. f_load(ProjectID)
  1140. }
  1141. self.loading_close()
  1142. };
  1143. //监听进度事件
  1144. req.addEventListener("progress", function (evt) {
  1145. if (evt.lengthComputable) {
  1146. var percentComplete = evt.loaded / evt.total;
  1147. //进度
  1148. console.log('[' + /\d\d\:\d\d\:\d\d/.exec(new Date())[0] + ']', "ProjectID:", ProjectID, " 进度:", (percentComplete * 100) + "%")
  1149. self.loading_text("模型加载中... "+parseInt(percentComplete * 100) + "%") // 替换内容
  1150. }
  1151. }, false);
  1152. req.onerror = function () {
  1153. // Error
  1154. console.log("blobLoad Error!", src)
  1155. loadProject_Map[ProjectID] = src
  1156. };
  1157. req.send();
  1158. }
  1159. //endregion
  1160. // --------------------- 脚本 -----------------------
  1161. //region Description
  1162. // var time, startTime;
  1163. // startTime = performance.now();
  1164. // // 创建一个每秒执行一次的定时循环
  1165. // setInterval(function() {
  1166. // // 在这里编写需要重复执行的代码
  1167. // time = performance.now();
  1168. // const rendertime = { time: time - startTime }
  1169. // // console.log("renderer:",rendertime)
  1170. // try {
  1171. // dispatch( events.renderer, rendertime);
  1172. // } catch ( e ) {
  1173. // console.error( ( e.message || e ), ( e.stack || '' ) );
  1174. // }
  1175. //
  1176. // }, 1000); // 1000 毫秒 = 1 秒
  1177. function dispatch( array, event ) {
  1178. for ( var i = 0, l = array.length; i < l; i ++ ) {
  1179. array[ i ]( event );
  1180. }
  1181. }
  1182. //
  1183. // function animate() {
  1184. //
  1185. // time = performance.now();
  1186. //
  1187. //
  1188. //
  1189. // prevTime = time;
  1190. //
  1191. // }
  1192. // this.play = function () {
  1193. //
  1194. // if ( renderer.xr.enabled ) dom.append( vrButton );
  1195. //
  1196. // startTime = prevTime = performance.now();
  1197. //
  1198. // document.addEventListener( 'keydown', oneyDown );
  1199. // document.addEventListener( 'keyup', onKeyUp );
  1200. // document.addEventListener( 'pointerup', onPointerUp );
  1201. // document.addEventListener( 'pointermove', onPointerMove );
  1202. //
  1203. // // dispatch( events.start, arguments );
  1204. //
  1205. // renderer.setAnimationLoop( animate );
  1206. //
  1207. // };
  1208. this.render = function ( time ) {
  1209. dispatch( events.update, { time: time * 1000, delta: 0 /* TODO */ } );
  1210. renderer.render( scene, camera );
  1211. };
  1212. this.dispose = function () {
  1213. renderer.dispose();
  1214. camera = undefined;
  1215. scene = undefined;
  1216. };
  1217. //
  1218. function onKeyDown( event ) {
  1219. dispatch( events.keydown, event );
  1220. }
  1221. function onKeyUp( event ) {
  1222. dispatch( events.keyup, event );
  1223. }
  1224. // function onPointerDown( event ) {
  1225. // dispatch( events.pointerdown, event );
  1226. //
  1227. // }
  1228. //
  1229. // function onPointerUp( event ) {
  1230. // dispatch( events.pointerup, event );
  1231. //
  1232. // }
  1233. //
  1234. function onBackclick( event ) {
  1235. dispatch( events.onBackclick, event );
  1236. }
  1237. function upDate( event ) {
  1238. try {
  1239. dispatch( events.update, event );
  1240. } catch ( e ) {
  1241. console.error( ( e.message || e ), ( e.stack || '' ) );
  1242. }
  1243. }
  1244. //endregion
  1245. // --------------------- 功能 -----------------------
  1246. //region Description
  1247. // this.BackgroundScene = function () {
  1248. // var urls = [
  1249. // './static/js/img/posx.jpg',
  1250. // './static/js/img/negx.jpg',
  1251. // './static/js/img/posy.jpg',
  1252. // './static/js/img/negy.jpg',
  1253. // './static/js/img/posz.jpg',
  1254. // './static/js/img/negz.jpg'
  1255. // ];
  1256. //
  1257. // var cubeLoader = new THREE.CubeTextureLoader();
  1258. // scene.background = cubeLoader.load(urls);
  1259. // setTimeout(function(){
  1260. // render()
  1261. // },3000);
  1262. //
  1263. // }
  1264. // 屏幕坐标与世界坐标
  1265. this.scene_3Dto2D = function (position) {
  1266. const worldVector = new THREE.Vector3(
  1267. position.x,
  1268. position.y,
  1269. position.z
  1270. );
  1271. const standardVec = worldVector.project(camera);
  1272. const centerX = dom_width / 2;
  1273. const centerY = dom_height / 2;
  1274. const screenX = Math.round(centerX * standardVec.x + centerX);
  1275. const screenY = Math.round(-centerY * standardVec.y + centerY);
  1276. console.log("screen:", screenX, screenY)
  1277. return screenX, screenY
  1278. }
  1279. //endregion
  1280. // 开始 加载场景
  1281. if (runmode === 0){
  1282. this.LocalRun()// 本地调试模式
  1283. }else if(runmode === 1){
  1284. this.LoadProject(window.T_ViewID) // 在线
  1285. }else if(runmode === 2){
  1286. this.LoadLocal() // 离线
  1287. }
  1288. }
  1289. export {IOT3D};