webgl_rxdz_roam.vue 38 KB

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