webgl_rxdz_roam.vue 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934
  1. <template src="./webgl_rxdz_roam.html">
  2. </template>
  3. <script>
  4. import * as THREE from 'three';
  5. import Stats from 'three/addons/libs/stats.module.js';
  6. import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
  7. import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
  8. import TWEEN from 'three/addons/libs/tween.module.js';
  9. var requestId = "";
  10. const util = require('@/utils/util.js').default;
  11. // import util from '@/utils/util.js';
  12. // const config = require('@/services/urlConfig.js');
  13. // import requestConfig from '@/static/lib/requestConfig.js';
  14. import viewShell from'@/components/newBottomCom/viewShell/viewShell.vue';
  15. import viewMask from'@/components/newBottomCom/viewMask/viewMask.vue';
  16. // import { RGBELoader } from '@/webgl/jsm/loaders/RGBELoader.js';
  17. import screenshot from '@/mixins/screenshot.js';
  18. import floorMethod from '@/mixins/floorMethod.js';
  19. import loadModel from '@/mixins/loadModel.js';
  20. import wallMethod from '@/mixins/wallMethod.js';
  21. import commonPageMethod from '@/mixins/commonPageMethod.js';
  22. // import commonPageMethod from '@/common/commonPageMethod.js';
  23. // const app = getApp(); //获取应用实例
  24. export default {
  25. components:{viewShell,viewMask},
  26. mixins:[screenshot,loadModel,floorMethod,wallMethod,commonPageMethod],
  27. /**
  28. * 页面的初始数据
  29. */
  30. data() {
  31. return {
  32. pvCurPageName: "room_show",
  33. locusBehaviorName: "房间展示",
  34. pvCurPageParams: null,
  35. houseId: "",
  36. pvId: 'p_2cmina_23080402',
  37. canvas:null,
  38. navbar: {
  39. showCapsule: 1,
  40. title: '客厅',
  41. titleColor: '#000',
  42. navPadding: 0,
  43. navPaddingBg:'transparent',
  44. navBarColor: 'transparent',
  45. navBackColor: 'transparent',
  46. haveCallback: true, // 如果是 true 会接手 navbarBackClk
  47. fromShare: false,
  48. fromProject: 0,
  49. shareToken: "",
  50. pageName: this.pvCurPageName,
  51. },
  52. id:'',// 户型编号
  53. spaceList:[], // 空间列表
  54. gltfSpaces:[], // 场景中地板模型数组
  55. gltfSpaceRoofs:[],
  56. curSpaceObj:null, // 当前选中的空间
  57. // curSpaceIndex:-1, // 当前选中的空间索引
  58. spaceId:null,
  59. wallIds:[], // 空间墙体id
  60. // wallList:[], // 墙体数据
  61. gltfWalls:[], // 场景中墙体模型数组
  62. loader:null,
  63. scene:null,
  64. // sky:null,
  65. camera:null,
  66. controlStarPosition : { x:0, y:0, z:0}, //控制器初始位置
  67. cameraStarPosition : { x:0, y:20, z:0} ,//摄像头初始位置
  68. cameraLastPosition: null, //摄像头上一次移动到的位置
  69. controlLastPosition: null, //观察点上一次移动到的位置
  70. canvasHeight:408, //canvas视图的高度-计算得出
  71. chooseMesh:null,//标记鼠标拾取到的mesh
  72. shottingImg: [],
  73. progress:1, //进度条
  74. myLoadingStatus:false,
  75. // textGeoList:[],
  76. repeatFlag:false, //重复点击
  77. // skyPlan: null, // 天空盒子
  78. instancedMeshList: [],
  79. screenshotResolve:null,
  80. actors:[],
  81. showDownView:true,//默认显示下载按钮
  82. currentActor:null,
  83. circleGroup:null,//圆形地标
  84. isIOS:false,
  85. defaulIndex:null, //默认视角的序号
  86. // aiImagesList:[
  87. // // "https://dm.static.elab-plus.com/miniProgram/plus_IM01.png",
  88. // // "https://dm.static.elab-plus.com/miniProgram/plus_IM02.png",
  89. // // "https://dm.static.elab-plus.com/miniProgram/plus_IM03.png",
  90. // // "https://dm.static.elab-plus.com/miniProgram/plus_IM04.png",
  91. // ]
  92. }
  93. },
  94. beforeDestroy() {
  95. cancelAnimationFrame(requestId, this.canvas)
  96. this.worker && this.worker.terminate()
  97. if (this.renderer instanceof THREE.WebGLRenderer) {
  98. // 遍历场景中的所有子对象,找到类型为Mesh的对象并移除
  99. let deleList = this.scene.children.filter(object=>{
  100. if (object instanceof THREE.Mesh) {
  101. return object
  102. }
  103. })
  104. if(deleList && deleList.length>0){
  105. this.scene.remove(...deleList);
  106. }
  107. this.scene.traverse(function(object) {
  108. if (object instanceof THREE.Mesh) {
  109. if(object.geometry && typeof(object.geometry.dispose)=='function'){
  110. object.geometry.dispose();
  111. }
  112. if(object.material && typeof(object.material.dispose)=='function'){
  113. object.material.dispose();
  114. }
  115. if(object.texture && typeof(object.texture.dispose)=='function'){
  116. object.texture.dispose();
  117. }
  118. }
  119. });
  120. this.renderer.clear();
  121. this.renderer.dispose();
  122. this.renderer.forceContextLoss();
  123. this.renderer.context = null;
  124. this.renderer.domElement = null;
  125. this.renderer = null;;
  126. this.clearHandle()
  127. }
  128. TWEEN && TWEEN.removeAll();//清除所有的tween;
  129. console.warn("***beforeDestroy-webgl_rxdz_roam***");
  130. },
  131. mounted(options) {
  132. var that = this;
  133. // alert("JavaScript 堆大小限制: "+performance.memory.jsHeapSizeLimit
  134. // +"\n已使用的 JavaScript 堆大小: "+performance.memory.usedJSHeapSize
  135. // +"\nJavaScript 堆的总大小: "+performance.memory.totalJSHeapSize);
  136. console.warn("***webgl_rxdz_roam-options***",this.$route.query)
  137. this.isIOS = !!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
  138. // alert("***mounted-webgl_rxdz_roam***"+this.curHouseObj)
  139. let screenWidth = window.screen.width;
  140. let screenHeight = window.screen.height;
  141. if(window.innerWidth && window.screen.width){
  142. screenWidth = Math.min(window.innerWidth,window.screen.width)
  143. }
  144. if(window.innerHeight && window.screen.height){
  145. screenHeight = Math.min(window.innerHeight,window.screen.height)
  146. }
  147. let unit = screenWidth / 750;//单位rpm 对应 px 的值
  148. this.canvasHeight = screenHeight - (600 * unit) + (40 * unit);
  149. this.houseId = this.$route.query.houseId?this.$route.query.houseId:'';
  150. this.spaceId = this.$route.query.spaceId?this.$route.query.spaceId:'';
  151. let container = this.$refs.webgl;
  152. let canvas3d = this.canvas = this.$refs.glcanvas;
  153. //uniapp 兼容写法,因为uni的页面对象的Vue 实例是$vm
  154. let camera = null, renderer = null;
  155. let needRender = false; //是否需要渲染 false表示不需要渲染;true 表示需要渲染
  156. let loader = this.loader = new GLTFLoader();
  157. let scene = this.scene = new THREE.Scene();
  158. let raycaster = null;
  159. let mouse = new THREE.Vector2();
  160. let chooseMesh = this.chooseMesh;//标记鼠标拾取到的mesh
  161. let isUserContorl = true;//是否进入漫游状态-默认是
  162. //漫游时变量
  163. let onPointerDownMouseX = 0, onPointerDownMouseY = 0,
  164. lon = 0;
  165. let fingerCount = 0; //触摸时的手指数目
  166. let startTime = 0; //非漫游时的移动变量
  167. let tweenCameraAnma = false; //表示当前是否处在动画过程中
  168. let controls = null,boundary=null;
  169. let stats;
  170. init();
  171. // this.$refs.myLoading.showLoading("加载中...1%")
  172. this.$store.state.loadingMsg="加载中...1%";
  173. // this.myLoadingStatus = true;
  174. this.progress = 1;
  175. this.clearEvent = clearEvent;
  176. this.attendEvent = attendEvent;
  177. // this.meshRoam = meshRoam;
  178. this.tweenCameraAnmaChange = tweenCameraAnmaChange;
  179. this.switchActor = switchActor;
  180. this.starRender = starRender;//对外暴露启动渲染的方法
  181. this.stopRender = stopRender;//对外暴露停止渲染的方法
  182. this.positionCamer = positionCamer;
  183. if(this.curHouseObj && this.curHouseObj.id){
  184. this.setHouseDetail(this.curHouseObj);
  185. }
  186. function init() {
  187. scene.background = new THREE.Color("#FFFFFF");
  188. // scene.environment = new THREE.Color("#F2F2F2");
  189. // 创建一个HDR贴图加载器
  190. // const rgbeloader = new RGBELoader();
  191. // // 加载HDR贴图
  192. // rgbeloader.load('https://dm.static.elab-plus.com/miniProgram/environment.hdr', (texture) => {
  193. // // 将HDR贴图设置为场景的环境贴图
  194. // texture.mapping = THREE.EquirectangularReflectionMapping;
  195. // scene.environment = texture;
  196. // })
  197. // 创建相机位置
  198. camera = new THREE.PerspectiveCamera(90, screenWidth / that.canvasHeight, 0.1, 10000 );
  199. // camera.up.set(0, 1, 0);//俯视状态,将相机的up向量设置为z轴负方向 {x:0,y:1,z:0}
  200. // camera.position.set(that.cameraStarPosition.x, that.cameraStarPosition.y, that.cameraStarPosition.z);
  201. scene.add(camera);
  202. that.camera = camera;
  203. // 环境光会均匀的照亮场景中的所有物体
  204. const ambientLight = new THREE.AmbientLight(0xFFEFE0, 3.5);
  205. scene.add(ambientLight);
  206. //平行光
  207. const light = new THREE.DirectionalLight(0xFFF8E5, 2.5);
  208. light.position.set(5, 7, 3); //default; light shining from top
  209. if(!that.isIOS){
  210. light.castShadow = true; // default false
  211. // 默认情况下光投影相机区域是一个长宽高为10x10x500的长方体区域,光源投射方向为通过坐标原点
  212. light.shadow.camera.left = -100; // 这个区域内产生阴影
  213. light.shadow.camera.right = 100; // 这个区域内产生阴影
  214. light.shadow.camera.top = 100; // 这个区域内产生阴影
  215. light.shadow.camera.bottom = -100; // 这个区域内产生阴影
  216. light.shadow.mapSize.width = 1024; // 影响阴影的清晰度
  217. light.shadow.mapSize.height = 1024; // 影响阴影的清晰度
  218. }
  219. scene.add(light);
  220. //antialias 这个值得设置为false,不然IOS上截图会失效
  221. renderer = that.renderer = new THREE.WebGLRenderer( {
  222. canvas:canvas3d,
  223. alpha: true,
  224. antialias:true,
  225. preserveDrawingBuffer: true,
  226. });
  227. if(!that.isIOS){
  228. renderer.shadowMap.enabled = true;//产生阴影
  229. renderer.shadowMap.type = THREE.PCFSoftShadowMap; // 阴影属性
  230. }
  231. renderer.outputEncoding = THREE.sRGBEncoding;
  232. renderer.outputColorSpace = THREE.SRGBColorSpace;
  233. // renderer.toneMappingExposure = 0.1;//色调映射的曝光级别。默认是1
  234. renderer.toneMapping = THREE.NoToneMapping;//色调映射
  235. renderer.physicallyCorrectLights = true;//关键参数,模拟物理光照影响,必须设置为true
  236. renderer.setPixelRatio(window.devicePixelRatio);
  237. renderer.setSize(screenWidth, that.canvasHeight);
  238. container.appendChild( renderer.domElement );
  239. controls = new OrbitControls( camera, renderer.domElement );
  240. controls.enableDamping = true;//启动缓动
  241. controls.minDistance = 0.0001;
  242. controls.maxDistance = 10;
  243. controls.minPolarAngle = 0;// 默认0
  244. controls.maxPolarAngle = Math.PI / 2; // 默认Math.PI,即可以向下旋转到的视角。
  245. // controls.target.set( that.controlStarPosition.x, that.controlStarPosition.y, that.controlStarPosition.z);
  246. controls.enableZoom = true;//启用摄像机的缩放
  247. controls.enablePan = true;//禁用摄像机平移
  248. controls.enableRotate = true;//启用摄像机水平或垂直旋转
  249. // controls.zoomToCursor = true;
  250. // controls.target.copy(camera.position);
  251. // controls.update();
  252. // 监听相机移动事件-限制只能在当前空间范围内移动
  253. controls.addEventListener('change', () => {
  254. // 检查相机位置是否超出边界框
  255. if (boundary && !boundary.containsPoint(camera.position)) {
  256. let clampedPosition = new THREE.Vector3( );
  257. boundary.clampPoint(camera.position,clampedPosition);
  258. if(clampedPosition){
  259. camera.position.copy(clampedPosition);
  260. // controls.target.copy(clampedPosition);
  261. }
  262. }
  263. });
  264. // controls.target = new THREE.Vector3( );;
  265. // camera.lookAt(that.controlStarPosition.x,that.controlStarPosition.y,that.controlStarPosition.z);
  266. raycaster = new THREE.Raycaster();
  267. // stats = new Stats();
  268. // container.appendChild(stats.dom);
  269. // stats.domElement.style.top = '100px';
  270. attendEvent();//注册监听事件
  271. starRender(); //启动渲染
  272. }
  273. function tweenCameraAnmaChange (value) {
  274. tweenCameraAnma = value
  275. }
  276. function attendEvent () {
  277. renderer.domElement.addEventListener('touchstart', onPointerStart, false);
  278. renderer.domElement.addEventListener('touchmove', onPointerMove, false);
  279. renderer.domElement.addEventListener('touchend', onPointerUp, false);
  280. }
  281. //取消事件监听-避免二次进入时触发多次事件
  282. function clearEvent(){
  283. console.warn("**clearEvent****")
  284. renderer && renderer.domElement && renderer.domElement.removeEventListener('touchstart', onPointerStart);
  285. renderer && renderer.domElement && renderer.domElement.removeEventListener('touchmove', onPointerMove );
  286. renderer && renderer.domElement && renderer.domElement.removeEventListener('touchend', onPointerUp );
  287. }
  288. // 手指移动开始
  289. function onPointerStart(event){
  290. startTime = (new Date()).getTime();
  291. fingerCount = event.touches.length;//手指个数
  292. console.log('开始触摸事件:',lon,fingerCount,camera.position.y)
  293. if (fingerCount === 1) {
  294. // 只有一个手指时记录当前点的坐标作为平移起始点
  295. onPointerDownMouseX = event.changedTouches[0].clientX;
  296. onPointerDownMouseY = event.changedTouches[0].clientY;
  297. }
  298. }
  299. //持续触摸中
  300. function onPointerMove( event ) {
  301. fingerCount = event.touches.length;//手指个数
  302. }
  303. //触摸结束
  304. function onPointerUp(event) {
  305. fingerCount = event.touches.length;//手指个数
  306. console.warn("***触摸结束***",fingerCount,startTime)
  307. if(fingerCount==0){
  308. let now = new Date().getTime()
  309. if (Math.abs(event.changedTouches[0].clientX - onPointerDownMouseX) < 10
  310. && Math.abs(event.changedTouches[0].clientY - onPointerDownMouseY) < 10
  311. && (now - startTime) < 300 ){
  312. checkIntersection(event);
  313. }
  314. }
  315. }
  316. //射线检测handle
  317. function checkIntersection(event) {
  318. let x = (event.changedTouches[0].clientX / screenWidth) * 2 - 1;
  319. let y = -(event.changedTouches[0].clientY / that.canvasHeight) * 2 + 1;
  320. mouse.x = x;
  321. mouse.y = y;
  322. //更新射线
  323. raycaster.setFromCamera(mouse, camera);
  324. let intersects = raycaster.intersectObjects(scene.children,true);
  325. console.warn("***checkIntersection***",intersects.length)
  326. if (intersects.length > 0) {
  327. //找到最近的那个网格模型物体
  328. let mesh = intersects.find((it) => {
  329. if(it.object && it.object.isMesh == true
  330. && it.object.parent && it.object.parent.name == 'actor'
  331. && it.object.parent.visible == true){
  332. return true;
  333. }
  334. });
  335. //拾取到了视角,就不继续拾取了
  336. if(mesh){
  337. moveActor(mesh.object.parent);
  338. return false;
  339. }
  340. mesh = intersects.find((it) => {
  341. if(it.object && it.object.isInstancedMesh
  342. && (it.object.name == '地板' || it.object.name == '花园') && it.object.visible == true){
  343. return true;
  344. }
  345. });
  346. //拾取到了地板
  347. if(mesh){
  348. let floor = mesh.object;
  349. let index = mesh.instanceId;//射线相交是的实例序号
  350. let spaceId = that.gltfSpaces[index].spaceId;//获取选中实例的空间id
  351. if(floor.name == "花园"){//花园
  352. return false;
  353. let selectMesh = that.gltfSpaces.find(it=>{return it.spaceType==14 && it.instancedMeshIndexList[0].instancedAtIndex==index})
  354. spaceId = selectMesh.spaceId;
  355. }else{//室内
  356. // floor.name = "地板";
  357. let selectMesh = that.gltfSpaces.find(it=>{return it.spaceType!=14 && it.instancedMeshIndexList[0].instancedAtIndex==index})
  358. spaceId = selectMesh.spaceId;
  359. }
  360. // let spaceId = that.gltfSpaces[index].spaceId;//获取选中实例的空间id
  361. console.warn("***checkIntersection-地板***",floor,index,spaceId,that.spaceId)
  362. //当前拾取到的是本空间的底部-意味着用户点击了地板
  363. if(floor && spaceId == that.spaceId){
  364. moveCarmer(mesh.point);
  365. return false;
  366. }
  367. }
  368. }
  369. }
  370. //自动切换视角
  371. function switchActor (toIndex=null) {
  372. if(!that.currentActor){
  373. this.$message.warning("没有当前视角!");
  374. return false;
  375. }
  376. if(!that.actors || that.actors.length==0){
  377. this.$message.warning("没有视角!");
  378. return false;
  379. }
  380. if(toIndex!=null){//存在要去往的视角
  381. moveActor(that.actors[toIndex]);
  382. }else{
  383. let index = that.currentActor.userIndex;//当前视角的序号
  384. let nextIndex = (index + 1) % that.actors.length;
  385. //移动到对应的视角去
  386. moveActor(that.actors[nextIndex]);
  387. that.defaulIndex = nextIndex;//更新下默认视角
  388. }
  389. }
  390. //移动到选中的位置-地板
  391. function moveCarmer (point) {
  392. //还在动画中,不能点击切换
  393. if(tweenCameraAnma == true){
  394. return false;
  395. }
  396. let _x = point.x - camera.position.x;//x轴移动的距离
  397. let _z = point.z - camera.position.z;//z轴移动的距离
  398. let cameraNewPosition = {x:camera.position.x + _x,y:1.5,z:camera.position.z + _z};
  399. let targetNewPosition = {x:controls.target.x + _x,y:1.5,z:controls.target.z + _z};
  400. let oldUp = {x:0,y:1,z:0};
  401. let newUp = {x:0,y:1,z:0};
  402. moveTip(cameraNewPosition)
  403. // console.warn("**moveCarmer***",lon,JSON.stringify(cameraNewPosition),JSON.stringify(targetNewPosition))
  404. tweenCamera(camera.position,controls.target,cameraNewPosition,targetNewPosition,oldUp,newUp,2000);
  405. setTimeout(()=> {
  406. that.circleGroup.visible = false;
  407. }, 2000);
  408. }
  409. //创建地标
  410. function creatMoveTip(position){
  411. if(!that.circleGroup){
  412. that.circleGroup = new THREE.Group();
  413. let geometry = new THREE.CircleGeometry( 0.2, 32 );
  414. let material = new THREE.MeshBasicMaterial( { transparent: true } );
  415. let circle = new THREE.Mesh( geometry, material );
  416. circle.position.set(position.x,0.01,position.z);
  417. circle.rotation.x = -Math.PI / 2;
  418. // let geometry1 = new THREE.CircleGeometry( 0.4, 32 );
  419. // let circle2 = new THREE.Mesh( geometry1, material );
  420. // circle2.position.set(position.x,0.01,position.z);
  421. // 使用贴图
  422. const textureLoader = new THREE.TextureLoader();
  423. textureLoader.load('https://dm.static.elab-plus.com/miniProgram/circlemap1.png', function(texture) {
  424. material.map = texture; // 将贴图应用于材质的map属性
  425. material.needsUpdate = true; // 更新材质
  426. });
  427. that.circleGroup.add(circle);
  428. scene.add(that.circleGroup);
  429. that.circleGroup.visible = false;
  430. }
  431. }
  432. //移动地标
  433. function moveTip(position){
  434. if(!that.circleGroup){
  435. that.circleGroup = new THREE.Group();
  436. let geometry = new THREE.CircleGeometry( 0.2, 32 );
  437. let material = new THREE.MeshBasicMaterial( { color: 0xffffff } );
  438. let circle = new THREE.Mesh( geometry, material );
  439. circle.position.set(position.x,0.01,position.z);
  440. circle.rotation.x = -Math.PI / 2;
  441. // let geometry1 = new THREE.CircleGeometry( 0.4, 32 );
  442. // let circle2 = new THREE.Mesh( geometry1, material );
  443. // circle2.position.set(position.x,0.01,position.z);
  444. that.circleGroup.add(circle);
  445. scene.add(that.circleGroup);
  446. }else{
  447. that.circleGroup.visible = true;
  448. that.circleGroup.children[0].position.set(position.x,0.01,position.z);
  449. }
  450. }
  451. //移动视角点位
  452. function moveActor (obj) {
  453. clearEvent();//注销事件监听
  454. // console.warn("***moveActor***",obj)
  455. that.currentActor = obj;//记录下当前的视角对象 mesh网格模型
  456. let cameraNewPosition = obj.position;
  457. let targetNewPosition = obj.targetNewPosition;
  458. let oldUp = {x:0,y:1,z:0}; //俯视
  459. let newUp = {x:0,y:1,z:0}; //正视
  460. // moveTip(cameraNewPosition);
  461. // console.warn("**moveActor***",JSON.stringify(cameraNewPosition),JSON.stringify(targetNewPosition))
  462. tweenCamera(camera.position,controls.target,cameraNewPosition,targetNewPosition,oldUp,newUp,2000);
  463. lon = 0;
  464. setTimeout(()=> {
  465. attendEvent()
  466. // that.circleGroup.visible = false;
  467. }, 2000);
  468. }
  469. //初始化点位视角
  470. function initActor(){
  471. if(!chooseMesh){
  472. console.error("[drawActor],没有选中的空间数据")
  473. return false;
  474. }
  475. let spaceObj = chooseMesh;//获取选中的空间模型的相关数据
  476. if(!spaceObj.actors){
  477. return false;
  478. }
  479. let defaulIndex = spaceObj.actors.findIndex(it=>it.isSelected==true);
  480. if(defaulIndex == -1){
  481. defaulIndex = 0;
  482. }
  483. that.defaulIndex = defaulIndex;//记录下默认视角
  484. that.actors = [];
  485. spaceObj.actors.forEach((actor,index)=>{
  486. // let model = gltf.scene; // 获取模型
  487. // let cloneModel = model.clone(true);//赋值模型,准备复用
  488. // cloneModel.children.map((v,i)=>{
  489. // if(v.material){
  490. // v.material = model.children[i].material.clone()
  491. // }
  492. // })
  493. // let cube = cloneModel;
  494. let cube = {};
  495. cube.name = "actor";
  496. cube.userType = "mesh";
  497. //新的摄像机的位置-新的摄像机角度是倾斜角度,所以z值需要计算,高度设置为模型高度的2倍
  498. let _actorLoaction = actor.actorLocation.split(',');//x y z
  499. let _actorTransform = actor.actorTransform.split(',');//旋转角度,取第三个值
  500. let _hd = THREE.MathUtils.degToRad(parseInt(_actorTransform[2]));//将度转化为弧度。
  501. let _hdY = THREE.MathUtils.degToRad(parseInt(_actorTransform[1]));//Y轴方向上将度转化为弧度。
  502. // if(parseInt(_actorLoaction[1])==0){//X轴
  503. // _actorLoaction[1] = spaceObj.centerX;
  504. // }
  505. // if(parseInt(_actorLoaction[0])==0){//Y轴
  506. // _actorLoaction[0] = spaceObj.centerY;
  507. // }
  508. let X_C = parseInt(_actorLoaction[0]);//X轴偏移量
  509. let Y_C = -parseInt(_actorLoaction[1]);//Y轴偏移量-取反,UE里面的Y轴方向跟Three.js相反
  510. let px = spaceObj.centerX + X_C;
  511. let py = -spaceObj.centerY + Y_C;//UE里面的centerY值跟Three.js Y轴相反;获得真实的坐标值
  512. let position = {
  513. x:(parseInt(px))/100,
  514. y:1.5,
  515. z:(parseInt(py))/100,//模型Y轴坐标系正负值跟webglZ轴是相反的
  516. }
  517. //新的观察点的位置-取模型的中心点坐标,加上高度,由于模型都是贴地的,所以高度设置为1.5
  518. let targetNewPosition = {
  519. x:position.x + Math.sin(_hd),
  520. y:1.5 + Math.tan(_hdY),
  521. z:(position.z - Math.cos(_hd)),
  522. }
  523. cube.position = position;
  524. cube.userIndex = index;
  525. cube.actorEum = index;
  526. cube.targetNewPosition = targetNewPosition;
  527. // console.warn("*actors*",cube,defaulIndex)
  528. that.actors.push(cube);//添加视角
  529. if(index == defaulIndex){//隐藏当前视角
  530. that.currentActor = cube;//记录下当前的视角对象 mesh网格模型
  531. let param = {
  532. type: 'CLK', //埋点类型
  533. clkId: 'clk_2cmina_23080411', //点击ID
  534. clkName: 'visualangle_clk', //点击前往的页面名称
  535. clkParams: {
  536. locusName: "预制视角",
  537. type:that.actors[index].actorEum
  538. }
  539. };
  540. util.trackRequest(param);
  541. }
  542. })
  543. }
  544. //计算当前选中空间的平视时的观察点和摄像机的放置点位
  545. function roamPositionHandle(lon=''){
  546. if(!chooseMesh){
  547. console.error("[roamPositionHandle],没有选中的空间数据")
  548. return false;
  549. }
  550. let spaceObj = chooseMesh;//获取选中的空间模型的相关数据
  551. //获取视角
  552. let defaultActor = null;
  553. if(spaceObj.actors && spaceObj.actors.length>0){
  554. defaultActor = spaceObj.actors.find(it=>it.isSelected==true);
  555. if(!defaultActor){
  556. defaultActor = spaceObj.actors[0];
  557. }
  558. }
  559. let _actorLoaction = defaultActor.actorLocation.split(',');//x y z
  560. let _actorTransform = defaultActor.actorTransform.split(',');//旋转角度,取第三个值
  561. let _hd = THREE.MathUtils.degToRad(parseInt(_actorTransform[2]) + lon);//将度转化为弧度。
  562. let _hdY = THREE.MathUtils.degToRad(parseInt(_actorTransform[1]));//Y轴方向上将度转化为弧度。
  563. // if(parseInt(_actorLoaction[1])==0){//X轴
  564. // _actorLoaction[1] = spaceObj.centerX;
  565. // }
  566. // if(parseInt(_actorLoaction[0])==0){//Y轴
  567. // _actorLoaction[0] = spaceObj.centerY;
  568. // }
  569. let X_C = parseInt(_actorLoaction[0]);//X轴偏移量-UE原因
  570. let Y_C = -parseInt(_actorLoaction[1]);//Y轴偏移量-取反,UE里面的Y轴方向跟Three.js相反
  571. let px = spaceObj.centerX + X_C;
  572. let py = -spaceObj.centerY + Y_C;
  573. //新的摄像机的位置-新的摄像机角度是倾斜角度,所以z值需要计算,高度设置为模型高度的2倍
  574. let cameraNewPosition = {
  575. x:(parseInt(px))/100,
  576. y:1.5,
  577. z:(parseInt(py))/100,//模型Y轴坐标系正负值跟webglZ轴是相反的
  578. }
  579. if(cameraNewPosition){
  580. let minX = 0,maxX = 0,minY = 0,maxY = 0;//0.1 是模型墙壁厚度
  581. minX = (spaceObj.centerX - (spaceObj.spaceWidth/2))/100 + 0.1;
  582. maxX = (spaceObj.centerX + (spaceObj.spaceWidth/2))/100 - 0.1;
  583. maxY = ((-spaceObj.centerY + (spaceObj.spaceHeight/2))/100 - 0.1);
  584. minY = ((-spaceObj.centerY - (spaceObj.spaceHeight/2))/100 + 0.1);
  585. //新的坐标轴不在房间范围内,则不能移动
  586. if(cameraNewPosition.x<minX || cameraNewPosition.x>maxX
  587. ||cameraNewPosition.z<minY || cameraNewPosition.z>maxY){//不在房间范围
  588. let _x = ((spaceObj.spaceWidth/2) - 15)*defaultActor.presentX + spaceObj.centerX;
  589. let _z = ((spaceObj.spaceHeight/2) - 15)*defaultActor.presentY + (-spaceObj.centerY);
  590. cameraNewPosition.x = _x/100;
  591. cameraNewPosition.z = _z/100;
  592. console.warn("**roamPositionHandle-观察点不在空间范围-强制修正观察点位置****",JSON.stringify(cameraNewPosition))
  593. }
  594. }
  595. //新的观察点的位置-取模型的中心点坐标,加上高度,由于模型都是贴地的,所以高度设置为1.5
  596. let targetNewPosition = {
  597. x:cameraNewPosition.x + Math.sin(_hd),
  598. y:1.5 + Math.tan(_hdY),
  599. z:(cameraNewPosition.z - Math.cos(_hd)),
  600. }
  601. let lookPosition = {
  602. x:cameraNewPosition.x + (Math.sin(_hd)*0.01),
  603. y:1.5 + Math.tan(_hdY),
  604. z:(cameraNewPosition.z - (Math.cos(_hd))*0.01),
  605. }
  606. return {cameraNewPosition,targetNewPosition,lookPosition}
  607. }
  608. //直接定位到摄像头位置
  609. function positionCamer(mesh=null){
  610. if(mesh){//如果传入了模型,则取模型
  611. chooseMesh = mesh;
  612. }
  613. if(!chooseMesh){
  614. console.error("[positionCamer],没有选中的空间数据")
  615. return false;
  616. }
  617. if(!chooseMesh.actors || chooseMesh.actors.length==0){
  618. chooseMesh.actors = [{
  619. actorLocation:chooseMesh.actorLocation,
  620. actorTransform:chooseMesh.actorTransform,
  621. isSelected:true,
  622. presentX:chooseMesh.presentX,
  623. presentY:chooseMesh.presentY,
  624. }]
  625. }
  626. boundary = new THREE.Box3(
  627. new THREE.Vector3(chooseMesh.centerX/100 - chooseMesh.spaceWidth/100/2 + 0.1, 0, -chooseMesh.centerY/100 - chooseMesh.spaceHeight/100/2 + 0.1), // 边界框的最小点
  628. new THREE.Vector3(chooseMesh.centerX/100 + chooseMesh.spaceWidth/100/2 - 0.1, 2.7, -chooseMesh.centerY/100 + chooseMesh.spaceHeight/100/2 - 0.1) // 边界框的最大点
  629. );
  630. initActor();//初始化视角
  631. let data = roamPositionHandle();
  632. let cameraNewPosition = data.cameraNewPosition;
  633. let targetNewPosition = data.targetNewPosition;
  634. let lookPosition = data.lookPosition;
  635. creatMoveTip(cameraNewPosition);//创建移动的地标
  636. camera.position.set(cameraNewPosition.x, cameraNewPosition.y, cameraNewPosition.z);
  637. controls.target.set(lookPosition.x,lookPosition.y,lookPosition.z);
  638. // controls.target.set(cameraNewPosition.x,cameraNewPosition.y,cameraNewPosition.z);
  639. // controls.target.copy(camera.position);
  640. camera.lookAt(targetNewPosition.x,targetNewPosition.y,targetNewPosition.z);
  641. }
  642. // oldP 相机原来的位置
  643. // oldT target原来的位置
  644. // newP 相机新的位置
  645. // newT target新的位置
  646. function tweenCamera(oldP, oldT, newP, newT, oldUp, newUp, time=1000) {
  647. if(JSON.stringify(oldP) == JSON.stringify(newP) && JSON.stringify(oldT) == JSON.stringify(newT)){
  648. that.repeatFlag = false;//放开限制,可以再次点击
  649. return false;
  650. }
  651. if (!chooseMesh) {
  652. that.repeatFlag = false;//放开限制,可以再次点击
  653. return false;
  654. }
  655. tweenCameraAnma = true;
  656. var tween = new TWEEN.Tween({
  657. x1: oldP.x, // 相机x
  658. y1: oldP.y, // 相机y
  659. z1: oldP.z, // 相机z
  660. x2: oldT.x, // 控制点的中心点x
  661. y2: oldT.y, // 控制点的中心点y
  662. z2: oldT.z, // 控制点的中心点z
  663. x3: oldUp.x, // 控制点的中心点x
  664. y3: oldUp.y, // 控制点的中心点y
  665. z3: oldUp.z // 控制点的中心点z
  666. })
  667. .to({
  668. x1: newP.x,
  669. y1: newP.y,
  670. z1: newP.z,
  671. x2: newT.x,
  672. y2: newT.y,
  673. z2: newT.z,
  674. x3: newUp.x, // up向量
  675. y3: newUp.y, // 控制点的中心点y
  676. z3: newUp.z // 控制点的中心点z
  677. }, time)
  678. .easing(TWEEN.Easing.Quadratic.InOut)
  679. .onUpdate((object)=> {
  680. camera.position.x = object.x1;
  681. camera.position.y = object.y1;
  682. camera.position.z = object.z1;
  683. // let newTarget = new THREE.Vector3(object.x3,object.y3,object.z3);
  684. // camera.up.copy(newTarget);
  685. camera.lookAt(object.x2,object.y2,object.z2);
  686. // controls.target.x = object.x2;
  687. // controls.target.y = object.y2;
  688. // controls.target.z = object.z2;
  689. // controls.update();
  690. }).onComplete(()=>{
  691. controls.target.x = newT.x;
  692. controls.target.y = newT.y;
  693. controls.target.z = newT.z;
  694. //修正最后的视角
  695. // let up = new THREE.Vector3(newUp.x,newUp.y,newUp.z);
  696. // camera.up.copy(up);
  697. camera.lookAt(newT.x,newT.y,newT.z);
  698. tweenCameraAnma = false;
  699. that.repeatFlag = false;//放开限制,可以再次点击
  700. })
  701. // 开始动画
  702. tween.start();
  703. }
  704. function stopRender () {
  705. needRender = false;
  706. }
  707. function starRender () {
  708. if(needRender==true){//如果已经在渲染中了,则不能再次开启,避免渲染过多
  709. false;
  710. }
  711. needRender = true;
  712. render();//开始渲染
  713. }
  714. function render() {
  715. if(needRender==false){
  716. return false;
  717. }
  718. TWEEN && TWEEN.update();
  719. // stats.update();
  720. renderer.render(scene, camera);//单次渲染
  721. requestId = requestAnimationFrame(render, canvas3d);
  722. if (that.screenshotResolve) {
  723. stopRender();
  724. that.screenshotResolve()
  725. that.screenshotResolve = null;//释放Promise
  726. }
  727. }
  728. },
  729. computed: {
  730. curHouseObj() {
  731. return this.$store.state.curHouseObj;
  732. },
  733. wallList() {
  734. return this.$store.state.wallList;
  735. },
  736. },
  737. watch: {
  738. curHouseObj: {
  739. handler(val) {
  740. if (val) {
  741. // setTimeout(()=> {
  742. // if(this.renderer){
  743. // this.setHouseDetail(val);
  744. // }
  745. // }, 1000);
  746. }
  747. },
  748. immediate: true,
  749. }
  750. },
  751. methods: {
  752. navbarBackClk() {
  753. if(!this.$refs.viewMask){
  754. this.$router.go(-1);
  755. return false
  756. }
  757. if (this.$refs.viewMask.showAIImage) {
  758. this.$refs.viewMask.showOrHideWebGl();//隐藏显示的AI生图
  759. // if(this.currentActor.userIndex!=this.defaulIndex){//当前不是默认视角了
  760. this.switchActor(this.defaulIndex);//切换到默认视角
  761. // }
  762. } else {
  763. this.$router.go(-1);
  764. }
  765. },
  766. switchActor(){},
  767. positionCamer(){},
  768. clearHandle(){
  769. this.clearEvent();
  770. },
  771. save(){
  772. this.$refs.viewMask.save();//下载
  773. },
  774. /**
  775. * 设置户型详情信息
  776. * @param {Object} data 户型详情
  777. */
  778. setHouseDetail(data){
  779. if(data){
  780. this.id = this.curHouseObj.id;
  781. this.spaceId = this.$route.query.spaceId?this.$route.query.spaceId:'';
  782. console.warn("***curHouseObj***",this.curHouseObj)
  783. // 加载户型
  784. this.loadSpace();
  785. }else{
  786. this.curHouseObj = {}
  787. }
  788. },
  789. // 绘制空间-即地板
  790. async loadSpace(){
  791. this.spaceList = [];
  792. this.wallIds = [];
  793. if(!this.curHouseObj || !this.spaceId){//减少重复请求
  794. alert("数据错误")
  795. console.warn("***数据错误***")
  796. return false
  797. }
  798. if(this.curHouseObj){
  799. const spaceDetail = this.curHouseObj;
  800. const spaceList = JSON.parse(spaceDetail.houseJson);
  801. // 交换centerX, centerY;上一页面已经处理过了,这里不在需要处理
  802. for (let index = 0; index < spaceList.length; index++) {
  803. var element = spaceList[index];
  804. // const centerX = JSON.parse(JSON.stringify(element.centerX))
  805. if(!element.actors || element.actors.length==0){
  806. element.actors = [{
  807. actorLocation:element.actorLocation,
  808. actorTransform:element.actorTransform,
  809. isSelected:true,
  810. }]
  811. }
  812. element.actors.forEach(actor=>{
  813. let _actorLoaction = actor.actorLocation.split(',');//x y z
  814. let X_C = parseInt(_actorLoaction[0]);//X轴偏移量-UE原因
  815. let Y_C = -parseInt(_actorLoaction[1]);//Y轴偏移量-取反,UE里面的Y轴方向跟Three.js相反
  816. let _x = element.centerX + X_C;
  817. let _z = -element.centerY + Y_C;//centerY 要取反,因为UE里面是反向的
  818. // let _x = parseInt(_actorLoaction[1]) || element.centerX;//观察点 X轴坐标
  819. // let _z = parseInt(_actorLoaction[0]) || element.centerY;//观察点 Z轴坐标
  820. let _presentX = (_x - element.centerX)/((element.spaceWidth/2) - 10);//10是墙壁厚度-单位cm
  821. let _presentY = (_z + element.centerY)/((element.spaceHeight/2) - 10);
  822. //注意如果一开始就设置大超过空间大小,则处理成贴近空间边界
  823. actor.presentX = Math.abs(_presentX)>1 ? (_presentX>1?1:-1) : _presentX;//观察点跟空间中心原点的距离比例
  824. actor.presentY = Math.abs(_presentY)>1 ? (_presentY>1?1:-1) : _presentY;
  825. })
  826. element.wallMoveValue = "[0,0,0,0]"
  827. this.spaceList.push(element);
  828. this.wallIds.push(element.wallId);
  829. if(element.spaceId == this.spaceId){ // 默认选中空间
  830. this.curSpaceObj = element;
  831. }
  832. }
  833. if(!this.curSpaceObj && this.spaceList.length > 0){
  834. this.curSpaceObj = this.spaceList[0];
  835. }
  836. }
  837. let curSpaceArea = parseFloat((this.curSpaceObj.spaceWidth * this.curSpaceObj.spaceHeight) / 10000).toFixed(1);
  838. this.navbar.title = this.curSpaceObj.spaceName + " " + curSpaceArea + "㎡"
  839. console.log("该户型空间数据:", this.spaceList);
  840. console.log("当前选中的空间:", this.curSpaceObj);
  841. this.positionCamer(this.curSpaceObj);
  842. this.loaderSpaceArr(this.spaceList);//绘制地板
  843. // 获取墙体数据并且绘制墙体
  844. this.getHouseTypeSpaceWalls();
  845. },
  846. // 获取墙体数据
  847. async getHouseTypeSpaceWalls(){
  848. let wallList = [];
  849. if(this.wallList){
  850. wallList = this.wallList;
  851. }else{
  852. let data = {id:this.wallIds}
  853. const res = await requestConfig('getHouseTypeSpaceWalls', data, true);
  854. // console.log("墙体数据:", res.list)
  855. if(res.success){
  856. wallList = this.wallList = res.list;
  857. }
  858. }
  859. let wallArr = []
  860. for (let index = 0; index < wallList.length; index++) {//每个空间对应一个数据
  861. let element = JSON.parse(wallList[index].wallJson);
  862. let space = this.spaceList.find(space=>space.spaceId==element.spaceId);
  863. this.computeWallHandleOld(space,element);//提前计算
  864. for (let i = 0; i < element.wallData.length; i ++) {//对应空间里面的4个方向的墙壁数据
  865. let wallData = element.wallData[i];
  866. //对应方向的墙壁的墙体模型数据列表,每一面墙可能有多个模型
  867. for (let j = 0; j < wallData.wallModelData.length; j ++) {
  868. let wallModelData = wallData.wallModelData[j];
  869. wallArr.push({spaceId:element.spaceId, wallModelData:wallModelData, wallDirection:wallData.wallDirection})
  870. // console.log("wallModelData", element,wallData.wallDirection, wallModelData.wallType );
  871. }
  872. }
  873. }
  874. this.loadSpaceObjWalls(wallArr, wallList);
  875. this.getOverallArrangementDetailsList();//
  876. },
  877. // 加载单个空间墙体资源
  878. async loadSpaceObjWalls(wallArr, wallList){
  879. // 加载远程墙体模型资源
  880. let startTime = new Date().getTime();
  881. // console.log("wallArr:", wallArr)
  882. let promise_list = [];
  883. let realWallArr = this.preWallData(wallArr);
  884. let arrLength = realWallArr.length;
  885. realWallArr && realWallArr.forEach((item,index) => {
  886. promise_list.push(
  887. new Promise((resolve, reject) => {
  888. this.loadWallModels(item, wallList, arrLength , resolve);
  889. })
  890. )
  891. });
  892. Promise.all(promise_list).then(()=>{
  893. let endTime = new Date().getTime();
  894. console.log("墙体模型全部加载完成,时间:",endTime - startTime);
  895. // 设置空间数组的墙体信息
  896. // this.setSpaceListWallInfo();
  897. this.$nextTick(()=>{
  898. // this.moveMeshCenter(this.curSpaceObj);
  899. this.progress = 100;
  900. // this.$refs.myLoading.showLoading("加载中..." + this.progress + '%')
  901. this.$nextTick(()=>{
  902. this.myLoadingStatus = false;
  903. // this.$refs.myLoading.hideLoading();
  904. // this.meshRoam(this.curSpaceObj);//开始漫游,必须先选中模型
  905. })
  906. })
  907. })
  908. },
  909. }
  910. }
  911. </script>
  912. <style lang="scss" scoped>
  913. @import "./webgl_rxdz_roam.scss";
  914. /* @import "@/common/css/common.css"; */
  915. </style>