overlay.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613
  1. var MathLight = {};
  2. MathLight.RADIANS_PER_DEGREE = Math.PI / 180;
  3. MathLight.DEGREES_PER_RADIAN = 180 / Math.PI;
  4. var initOverlay = function(THREE) {
  5. var _planeGeometry = new THREE.PlaneGeometry(settings.overlay.width,settings.overlay.height,1,1)
  6. var _boxGeometry = new THREE.BoxBufferGeometry(settings.overlay.width,settings.overlay.height,settings.overlay.depth)
  7. //ie的mesh 加了polygonOffset也是会重叠。所以去掉前面的face: (但是突然ie又播放不了videoTexture)
  8. var newIndex = [..._boxGeometry.index.array]
  9. newIndex.splice(4 * 6, 6)
  10. _boxGeometry.setIndex(new THREE.BufferAttribute(new Uint16Array(newIndex),1))
  11. var _boxMat = new THREE.MeshBasicMaterial({
  12. //MeshStandardMaterial
  13. color: "#eeeeee",
  14. transparent: !0,
  15. opacity: 0.8
  16. })
  17. var overlayGroup = new THREE.Object3D;
  18. player.model.add(overlayGroup);
  19. overlayGroup.name = "overlayGroup"
  20. player.overlayGroup = overlayGroup;
  21. var Overlay = function(info) {
  22. THREE.Object3D.call(this);
  23. this.sid = info.sid;
  24. if (info.media)
  25. this.preDeal(info)
  26. this.build(info);
  27. this.name = "overlay_" + this.sid;
  28. }
  29. Overlay.prototype = Object.create(THREE.Object3D.prototype);
  30. Overlay.prototype.build = function(info) {
  31. if( info.media.includes('text') && !info.words)return;
  32. var plane = new THREE.Mesh(_planeGeometry,new THREE.MeshBasicMaterial({
  33. //MeshStandardMaterial
  34. color: "#00c8af",
  35. opacity: 0.4,
  36. transparent: !0,
  37. polygonOffset: true,
  38. //是否开启多边形偏移 //ie不开启时blank也不会闪烁
  39. polygonOffsetFactor: -0.9,
  40. //多边形偏移因子
  41. polygonOffsetUnits: -4.0,
  42. //多边形偏移单位
  43. }))
  44. plane.renderOrder = 3
  45. this.add(plane);
  46. this.plane = plane;
  47. if (info.hasBox) {
  48. this.addBox(true)
  49. }
  50. overlayGroup.add(this);
  51. if (info.media) {
  52. if (info.media.includes('video')) {
  53. //var id = "video"+ this.sid id="${ id }"
  54. var video = $(`<video controls="controls" loop autoplay x5-playsinline="" webkit-playsinline="true" playsinline="true" controlslist="nodownload"></video>`)[0]
  55. video.setAttribute("crossOrigin", 'Anonymous')
  56. //要在src设置好前解决跨域
  57. $(video).on('contextmenu', function() {
  58. return false;
  59. });
  60. //禁止右键点击出
  61. video.src = manage.dealURL(info.file);
  62. info.media = video;
  63. info.type = "video"
  64. /* video.addEventListener('loadeddata', ()=>{
  65. console.log(this.sid + " loaded!!!")
  66. }) */
  67. video.oncanplaythrough = function() {
  68. plane.material.map.needsUpdate = !0
  69. if(video.shouldPlay){
  70. video.play()
  71. }
  72. }
  73. video.volume = 0
  74. video.muted = true
  75. }else if(info.media.includes('photo')){
  76. /* var img = new Image();
  77. img.src = manage.dealURL(info.file) //"https://4dkk.4dage.com/images/images"+Config.projectNum+"/overlay"+this.sid+".jpg?m="+new Date().getTime()
  78. info.media = img
  79. */
  80. info.type = "photo"
  81. }else if(info.media.includes('text')){
  82. info.type = "text";
  83. var fontSize = 40;
  84. var lineHeight = fontSize * 2.1;//fontSize + 行间距
  85. var texWidthRitio = 0.86
  86. var canvas = document.createElement('canvas');
  87. var context = canvas.getContext('2d');
  88. canvas.width = 1024;
  89. context.font = `${fontSize}px 微软雅黑`;
  90. var result = []
  91. info.words.forEach((words)=>{
  92. if(!words){result.push("");return;}
  93. result = result.concat ( breakLinesForCanvas(
  94. words,
  95. //'使用很寻常的二分查找,如果某一个位置之前的文字宽度小于等于设定的宽度,并且它之后一个字之前的文字宽度大于设定的宽度,那么这个位置就是文本的换行点。上面只是找到一个换行点,对于输入的一段文本,需要循环查找,直到不存在这样的换行点为止, 完整的代码如下',
  96. context, canvas.width * texWidthRitio ) )
  97. })
  98. canvas.height = (result.length + 1 ) * lineHeight
  99. var context = canvas.getContext('2d');//不知为什么要再获取一次context才行
  100. context.font = `${fontSize}px 微软雅黑`;
  101. /* context.fillStyle = '#fff';
  102. context.fillRect(0,0,canvas.width,canvas.height); */
  103. context.fillStyle = '#f5c772';
  104. result.forEach(function(line, index) {
  105. context.fillText(line, canvas.width * (1-texWidthRitio)/ 2, lineHeight * (index + 1));
  106. });
  107. var url = canvas.toDataURL()
  108. var img = new Image();
  109. img.src = url;
  110. info.media = img;
  111. info.lineCount = result.length
  112. }
  113. plane.material.opacity = 1;
  114. plane.material.color = new THREE.Color(1,1,1)
  115. }
  116. if (info.width == void 0)
  117. info.width = settings.overlay.width;
  118. if (info.height == void 0)
  119. info.height = settings.overlay.height;
  120. this.setFromInfo(info)
  121. this.fileSrc = info.file
  122. }
  123. Overlay.prototype.computeMapRepeat = function(info){//使得文字不变形
  124. clearInterval(this.mapInterval);
  125. var map = this.plane.material.map;
  126. var tw = map.image.width, th = map.image.height,
  127. w = this.width, h = this.height;
  128. var ratio = (h / w) / (th / tw); //显示的部分占据整个图高度的比例
  129. map.repeat.y = ratio
  130. if(th / tw > h / w){
  131. //如果贴图设置成不repeat(缺点是会有一段白屏期)
  132. /* map.offset.y = 1 - ratio;//向下移动 1-ratio个高度, 使图片的顶部显示在plane的最上方;之后滚动时正常repeat在 1-ratio到0之间变化 , 为了连续变化,改成 1 到 -ratio
  133. this.mapInterval = setInterval(()=>{
  134. map.offset.y -= 0.003;
  135. if(map.offset.y < -ratio )map.offset.y = 1
  136. },20) */
  137. //如果贴图设置成 repeat(缺点是 可能衔接时的缝隙比较窄)
  138. map.wrapS = map.wrapT = THREE.RepeatWrapping;
  139. map.offset.y = 1 - ratio;//向下移动 1-ratio个高度, 使图片的顶部显示在plane的最上方;之后滚动时正常repeat在 1-ratio到0之间变化 , 为了连续变化,改成 1 到 -ratio
  140. this.mapInterval = setInterval(()=>{
  141. map.offset.y -= 0.013 / info.lineCount ;
  142. //if(map.offset.y < -ratio )map.offset.y = 1
  143. },20)
  144. }else{//如果图可以完全展示
  145. map.offset.y = (1 - ratio) / 2;//居中
  146. map.wrapS = map.wrapT = THREE.ClampToEdgeWrapping;
  147. }
  148. map.needsUpdate = true;
  149. }
  150. Overlay.prototype.setFromInfo = function(info) {
  151. //1 恢复到编辑之前 2 初始加载
  152. var plane = this.plane;
  153. var transformAtPanos = {}
  154. for(var i in info.transformAtPanos){
  155. transformAtPanos[i] = {
  156. width : info.transformAtPanos[i].width,
  157. height : info.transformAtPanos[i].height,
  158. pos : info.transformAtPanos[i].pos.clone(),
  159. qua : info.transformAtPanos[i].qua.clone(),
  160. }
  161. }
  162. this.transformAtPanos = transformAtPanos
  163. //在每个漫游点独立设置的position。
  164. //var curPanoTransform = player.currentPano && this.transformAtPanos[player.currentPano.id] || {}
  165. var curPanoTransform = this.transformAtPanos[ getTransformSid()] || {}
  166. info.depth && this.scale.setZ(info.depth / settings.overlay.depth)
  167. this.posCustom = info.pos ? info.pos.clone() : this.position.clone();
  168. //没有单独设置position的漫游点使用的position
  169. this.position.copy(curPanoTransform.pos || this.posCustom)
  170. this.quaCustom = info.qua ? info.qua.clone() : this.quaternion.clone()
  171. this.quaternion.copy(curPanoTransform.qua || this.quaCustom);
  172. this.widthCustom = info.width
  173. this.heightCustom = info.height
  174. this.width = curPanoTransform.width || this.widthCustom
  175. this.height = curPanoTransform.height || this.heightCustom
  176. var a = this.getScaleBySize(this.width, this.height)
  177. this.scale.setX(a.x)
  178. this.scale.setY(a.y)
  179. if (info.type) {
  180. if (!plane.material.map) {
  181. if (info.type == "video") {
  182. plane.material.map = new THREE.VideoTexture(info.media);
  183. this.hasRequestLoad = true
  184. plane.material.map.wrapS = plane.material.map.wrapT = THREE.ClampToEdgeWrapping;
  185. plane.material.map.minFilter = THREE.LinearFilter;
  186. plane.material.map.magFilter = THREE.LinearFilter;
  187. plane.material.map.generateMipmaps = true;
  188. } else {
  189. this._loadDones = []
  190. /* plane.material.map = Texture.load(info.file,()=>{
  191. if(this._loadDones){
  192. this._loadDones.forEach(e=>e())
  193. this._loadDones = null
  194. }
  195. }) */
  196. }
  197. /* plane.material.map.wrapS = plane.material.map.wrapT = THREE.ClampToEdgeWrapping;
  198. plane.material.map.minFilter = THREE.LinearFilter;
  199. plane.material.map.magFilter = THREE.LinearFilter;
  200. plane.material.map.generateMipmaps = true; */
  201. } else
  202. plane.material.map.image = info.media;
  203. this.file = info.file;
  204. }
  205. this.overlayType = info.type;
  206. if (!!this.hasBox != !!info.hasBox) {
  207. this.addBox(!this.hasBox);
  208. }
  209. this.updateMatrixWorld()
  210. this.getVisiblePanos()
  211. {//gif
  212. if(this.animation){
  213. GifTexDeal.remove(this.animation)
  214. }
  215. this.animateInfo = CloneObject(info.animateInfo)
  216. if(this.animateInfo && plane.material.map){
  217. this.animation = GifTexDeal.addAnimation(plane.material.map, this, this.animateInfo, this.sid )
  218. this.visible && this.inSight() && GifTexDeal.start(this.animation)
  219. }
  220. }
  221. }
  222. Overlay.prototype.addBox = function(state) {
  223. if (state == !!this.hasBox) {
  224. return;
  225. }
  226. if (state) {
  227. var box = new THREE.Mesh(_boxGeometry,_boxMat)
  228. box.position.set(0, 0, settings.overlay.depth / 2);
  229. box.renderOrder = 3
  230. this.plane.position.set(0, 0, settings.overlay.depth);
  231. this.add(box);
  232. this.box = box;
  233. } else {
  234. this.plane.position.set(0, 0, 0);
  235. this.remove(this.box);
  236. this.box = null;
  237. }
  238. this.hasBox = state
  239. }
  240. Overlay.prototype.getSizeByScale = function() {
  241. return {
  242. width: settings.overlay.width * this.scale.x,
  243. height: settings.overlay.height * this.scale.y
  244. }
  245. }
  246. Overlay.prototype.getScaleBySize = function(width, height) {
  247. return {
  248. x: width / settings.overlay.width,
  249. y: height / settings.overlay.height,
  250. }
  251. }
  252. Overlay.prototype.preDeal = function(info) {
  253. info.pos = new THREE.Vector3().fromArray(info.pos)
  254. info.qua = new THREE.Quaternion().fromArray(info.qua)
  255. info.width = parseFloat(info.width)
  256. info.height = parseFloat(info.height)
  257. info.depth = parseFloat(info.depth)
  258. info.hasBox = parseInt(info.hasBox)
  259. info.pos.x = parseFloat(info.pos.x)
  260. info.pos.y = parseFloat(info.pos.y)
  261. info.pos.z = parseFloat(info.pos.z)
  262. info.qua.x = parseFloat(info.qua.x)
  263. info.qua.y = parseFloat(info.qua.y)
  264. info.qua.z = parseFloat(info.qua.z)
  265. info.qua.w = parseFloat(info.qua.w)
  266. if (!info.transformAtPanos)
  267. info.transformAtPanos = {}
  268. for (let i in info.transformAtPanos) {
  269. info.transformAtPanos[i].pos = new THREE.Vector3().fromArray(info.transformAtPanos[i].pos)
  270. info.transformAtPanos[i].qua = new THREE.Quaternion().fromArray(info.transformAtPanos[i].qua)
  271. }
  272. if(info.media.includes("text")){
  273. /*
  274. 只有http能加载
  275. */
  276. $.ajax({
  277. url: "/api/web/list",
  278. type: 'POST',
  279. dataType: "json",
  280. cache: false,
  281. contentType: 'application/json;charset=UTF-8',
  282. data : JSON.stringify({"pageNum":1,"pageSize":1000} ),
  283. success: (data)=>{
  284. console.log(data)
  285. var words = [];
  286. data.data.list.forEach((item,index)=>{
  287. /* words += item.nickName; words += " "
  288. words += item.createTime; words += "\n\n"
  289. words += item.msg; words += "\n"
  290. words += "————————\n\n" */
  291. words.push(item.nickName + " " + item.createTime);
  292. //words.push("");
  293. words.push(item.msg);
  294. words.push("————————————————");
  295. words.push("");
  296. })
  297. console.log(words)
  298. info.words = words
  299. this.build(info)
  300. },
  301. error: function (msg) {
  302. console.log(msg)
  303. }
  304. });
  305. }
  306. }
  307. Overlay.prototype.getVisiblePanos = function() {
  308. this.visiblePanos = common.getVisiblePano(this.plane.getWorldPosition(), {
  309. model: null
  310. });
  311. }
  312. Overlay.prototype.updateVisibles = function(panos) {
  313. if(settings.isEdit && EditOverlay.editPlane == this){
  314. return true
  315. }
  316. this.visible = !!panos.find(pano=>this.visiblePanos.includes(pano))
  317. if (!this.visible && this.overlayType == 'video')
  318. this.videoControl('stop')
  319. }
  320. Overlay.updateVisibles = function(panos) {
  321. if (panos === true) {
  322. player.overlayGroup.children.forEach(e=>e.visible = true)
  323. } else {
  324. player.overlayGroup.children.forEach(e=>e.updateVisibles && e.updateVisibles(panos))
  325. }
  326. }
  327. Overlay.prototype.videoControl = function(state){
  328. if(this.overlayType != "video")return
  329. var video = this.plane.material.map.image
  330. if(!state || state == 'stop'){
  331. video.paused || video.pause()
  332. if(state == 'stop'){
  333. video.currentTime = 0;
  334. }
  335. video.shouldPlay = false
  336. //console.log("pause")
  337. }else if(state){
  338. video.paused && video.play()
  339. video.shouldPlay = true
  340. //console.log("play")
  341. }
  342. }
  343. Overlay.prototype.inSight = function(){
  344. if(player.mode == 'panorama'){
  345. var position = this.plane.getWorldPosition()
  346. var pos2d = math.getPos2d(position, player.camera, $("#player")[0])
  347. if(pos2d.trueSide && pos2d.inSight){
  348. return true
  349. }else{
  350. var cornerPoint = [
  351. new THREE.Vector3(-settings.overlay.width/2, settings.overlay.height/2, 0),
  352. new THREE.Vector3(settings.overlay.width/2, settings.overlay.height/2, 0),
  353. new THREE.Vector3(settings.overlay.width/2, -settings.overlay.height/2, 0),
  354. new THREE.Vector3(-settings.overlay.width/2, -settings.overlay.height/2, 0),
  355. ];
  356. for(var i=0;i<4;i++){
  357. cornerPoint[i].applyMatrix4(this.plane.matrixWorld);
  358. var pos2d = math.getPos2d(cornerPoint[i], player.camera, $("#player")[0])
  359. if(pos2d.trueSide && pos2d.inSight){
  360. return true
  361. }
  362. }
  363. }
  364. }else{
  365. return true
  366. }
  367. }
  368. Overlay.prototype.addToLoadQueue = function() {
  369. if (this.overlayType == 'photo') {
  370. Overlay.loadQueue.includes(this) || Overlay.loadQueue.push(this)
  371. }
  372. }
  373. Overlay.prototype.requestDownload = function() {
  374. if (this.hasRequestLoad || this.overlayType != 'photo')
  375. return
  376. console.log('overlay beginDownload : ' + this.sid)
  377. var plane = this.plane;
  378. plane.material.map = Texture.load(this.file, ()=>{
  379. if (this._loadDones) {
  380. this._loadDones.forEach(e=>e())
  381. this._loadDones = null
  382. }
  383. setTimeout(Overlay.loadNext, 50)
  384. plane.material.opacity = 1;
  385. console.log('overlay loaded: ' + this.sid)
  386. if(this.animateInfo){
  387. this.animation = GifTexDeal.addAnimation(plane.material.map, this, this.animateInfo, this.sid )
  388. this.visible && this.inSight() && GifTexDeal.start(this.animation)
  389. }
  390. plane.material.needsUpdate = true
  391. })
  392. plane.material.map.wrapS = plane.material.map.wrapT = THREE.ClampToEdgeWrapping;
  393. plane.material.map.minFilter = THREE.LinearFilter;
  394. plane.material.map.magFilter = THREE.LinearFilter;
  395. plane.material.map.generateMipmaps = true;
  396. this.hasRequestLoad = true
  397. }
  398. Overlay.loadQueue = []; //等待下载的overlay,目前只针对photo
  399. Overlay.maxLoadingCount = 3; //同时正在load图片的数量
  400. Overlay.loadNext = ()=>{//继续requestDownload loadQueue中前排的item
  401. var loadings = player.overlayGroup.children.filter(e=>e.hasRequestLoad && e._loadDones)//开始下载了但是没加载好的
  402. Overlay.loadQueue.slice(0, Overlay.maxLoadingCount - loadings.length).forEach(e=>e.requestDownload())
  403. Overlay.loadQueue.splice(0, Overlay.maxLoadingCount - loadings.length)
  404. }
  405. Overlay.getNeedLoad = function() {//计算获取loadQueue,每次都重新计算,覆盖旧的
  406. if (!player || !player.domElement || !player.mode)
  407. return;
  408. if (player.mode != 'panorama') {
  409. if (!Overlay.loadWhenOutside)
  410. return;
  411. if (Overlay.loadQueue.length == 0) {
  412. Overlay.loadQueue = player.overlayGroup.children.filter(e=>!e.hasRequestLoad).slice(0, 5);
  413. }
  414. return;
  415. }
  416. Overlay.loadWhenOutside = true
  417. var overlays = player.overlayGroup.children.filter(e=>!e.hasRequestLoad && e.visiblePanos.includes(player.currentPano))
  418. //var maxAngle = THREE.Math.degToRad( cameraLight.getHFOVFromVFOV(70, player.domElement.clientWidth, app.player.domElement.clientHeight) / 2);
  419. var cameraDir = player.getDirection()
  420. /* var maxCount = 5;
  421. if(overlays.length>maxCount){
  422. for(var i=0;i<overlays.length;i++){
  423. //角度为可见范围
  424. var v1 = cameraDir.clone().setY(0);
  425. var v2 = overlays[i].plane.getWorldPosition().sub(player.position).setY(0)
  426. if(v1.angleTo(v2) <= maxAngle){
  427. Overlay.loadQueue.push(overlays[i])
  428. if(Overlay.loadQueue.length>=10) break;
  429. }
  430. }
  431. if(Overlay.loadQueue.length<Overlay.maxLoadingCount){
  432. Overlay.loadQueue.push()
  433. }
  434. }else{ */
  435. Overlay.loadQueue = overlays
  436. //}
  437. var request = [(overlay)=>{
  438. return true
  439. }
  440. ];
  441. var rank = [(overlay)=>{
  442. var dis = overlay.plane.getWorldPosition().distanceTo(player.position);
  443. return -dis
  444. }
  445. , (overlay)=>{
  446. var tagDir = overlay.plane.getWorldPosition().sub(player.position)
  447. var angle = tagDir.angleTo(cameraDir)
  448. return -angle * 20
  449. }
  450. ]
  451. var result = common.sortByScore(Overlay.loadQueue, request, rank);
  452. Overlay.loadQueue = result ? result.slice(0, 5).map(e=>e.item) : player.overlayGroup.children.filter(e=>!e.hasRequestLoad).slice(0, 2);
  453. }
  454. Overlay.load = ()=>{//开始下载图片
  455. Overlay.getNeedLoad()
  456. Overlay.loadNext()
  457. var unloads = player.overlayGroup.children.filter(e=>!e.hasRequestLoad)
  458. if (unloads.length) {
  459. setTimeout(Overlay.load, 200)
  460. } else {
  461. Overlay.allRequestLoad = true
  462. console.log('allRequestLoad')
  463. }
  464. }
  465. function findBreakPoint(text, width, context) {
  466. var min = 0;
  467. var max = text.length - 1;
  468. while (min <= max) {
  469. var middle = Math.floor((min + max) / 2);
  470. var middleWidth = context.measureText(text.substr(0, middle)).width;
  471. var oneCharWiderThanMiddleWidth = context.measureText(text.substr(0, middle + 1)).width;
  472. if (middleWidth <= width && oneCharWiderThanMiddleWidth > width) {
  473. return middle;
  474. }
  475. if (middleWidth < width) {
  476. min = middle + 1;
  477. } else {
  478. max = middle - 1;
  479. }
  480. }
  481. return -1;
  482. }
  483. function breakLinesForCanvas(text, context, width, font) {
  484. var result = [];
  485. var breakPoint = 0;
  486. if (font) {
  487. context.font = font;
  488. }
  489. while ((breakPoint = findBreakPoint(text, width, context)) !== -1) {
  490. result.push(text.substr(0, breakPoint));
  491. text = text.substr(breakPoint);
  492. }
  493. if (text) {
  494. result.push(text);
  495. }
  496. return result;
  497. }
  498. window.Overlay = Overlay;
  499. }