index.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  1. let camera, scene, renderer;
  2. const shadowHasAlpha = false //阴影是否考虑光透过透明材质
  3. const planeGeo = new THREE.PlaneBufferGeometry(1, 1)
  4. const raycaster = new THREE.Raycaster(); raycaster.linePrecision = 0;//不检测boxHelper
  5. const mouse = new THREE.Vector2();
  6. let needUpdateShadow, needsUpdateScene
  7. var BlurShader = {
  8. uniforms: {
  9. "map": { value: null },
  10. "blurRadius": { value: new THREE.Vector2(1.0 / 512.0, 1.0 / 512.0) },
  11. 'opacity': { value: 0 }
  12. },
  13. vertexShader: [
  14. "varying vec2 vUv;",
  15. "void main() {",
  16. " vUv = uv;",
  17. " gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  18. "}"
  19. ].join("\n"),
  20. fragmentShader: [
  21. "uniform sampler2D map;",
  22. "uniform vec2 resolution;",
  23. "uniform float blurRadius;",
  24. "uniform float opacity;",
  25. "varying vec2 vUv;",
  26. "void main() {",
  27. " vec2 offset = blurRadius / resolution; ",
  28. " vec4 sum = vec4( 0.0 );",
  29. " sum += texture2D( map, vec2( vUv.x - 4.0 * offset.x, vUv.y ) ) * 0.051;",
  30. " sum += texture2D( map, vec2( vUv.x - 3.0 * offset.x, vUv.y ) ) * 0.0918;",
  31. " sum += texture2D( map, vec2( vUv.x - 2.0 * offset.x, vUv.y ) ) * 0.12245;",
  32. " sum += texture2D( map, vec2( vUv.x - 1.0 * offset.x, vUv.y ) ) * 0.1531;",
  33. " sum += texture2D( map, vec2( vUv.x, vUv.y ) ) * 0.1633;",
  34. " sum += texture2D( map, vec2( vUv.x + 1.0 * offset.x, vUv.y ) ) * 0.1531;",
  35. " sum += texture2D( map, vec2( vUv.x + 2.0 * offset.x, vUv.y ) ) * 0.12245;",
  36. " sum += texture2D( map, vec2( vUv.x + 3.0 * offset.x, vUv.y ) ) * 0.0918;",
  37. " sum += texture2D( map, vec2( vUv.x + 4.0 * offset.x, vUv.y ) ) * 0.051;",
  38. " sum += texture2D( map, vec2( vUv.x , vUv.y - 4.0 * offset.y ) ) * 0.051;",
  39. " sum += texture2D( map, vec2( vUv.x , vUv.y - 3.0 * offset.y) ) * 0.0918;",
  40. " sum += texture2D( map, vec2( vUv.x , vUv.y - 2.0 * offset.y) ) * 0.12245;",
  41. " sum += texture2D( map, vec2( vUv.x , vUv.y - 1.0 * offset.y ) ) * 0.1531;",
  42. " sum += texture2D( map, vec2( vUv.x , vUv.y ) ) * 0.1633;",
  43. " sum += texture2D( map, vec2( vUv.x , vUv.y + 1.0 * offset.y ) ) * 0.1531;",
  44. " sum += texture2D( map, vec2( vUv.x , vUv.y + 2.0 * offset.y ) ) * 0.12245;",
  45. " sum += texture2D( map, vec2( vUv.x , vUv.y + 3.0 * offset.y ) ) * 0.0918;",
  46. " sum += texture2D( map, vec2( vUv.x , vUv.y + 4.0 * offset.y ) ) * 0.051;",
  47. " gl_FragColor = sum / 2.0 ;",
  48. " gl_FragColor.a *= opacity;",
  49. "}"
  50. ].join("\n")
  51. };
  52. var Viewer = function (index, dom) {
  53. this.index = index;
  54. this.dom = dom
  55. this.camera = new THREE.PerspectiveCamera(setting.vfov);
  56. this.camera.position.set(0, 1, -1.5);
  57. this.control = new PanoramaControls(this.camera, this.dom)
  58. this.control.latMin = this.control.latMax = 0
  59. //this.control.target.set(0,-1,0)
  60. this.setRenderer()
  61. this.scene = new THREE.Scene;
  62. this.scene.background = common.loadTexture("background.jpg")
  63. this.pointerDownPos
  64. this.active = false;
  65. this.antialias = true;
  66. this.clickTime = new Date().getTime();
  67. this.updateClock = new THREE.Clock;
  68. this.cardGroup = new THREE.Object3D();
  69. this.scene.add(this.cardGroup);
  70. this.cardGroup.name = "cardGroup";
  71. this.autoMove = true
  72. this.bindEvents()
  73. this.preLoadCards()
  74. this.animate()
  75. }
  76. /*
  77. 同一时间,视线范围不能同时出现两张卡。也就是分布要根据视角范围变化,但是如果浏览器变宽导致的出现两张卡不算。
  78. */
  79. Viewer.prototype.preLoadCards = function () {
  80. let i = 10
  81. while (i-- > 0) {
  82. this.addCard(true)
  83. }
  84. let add = () => {
  85. if (document.hidden) return
  86. this.addCard()
  87. setTimeout(add, 40000 * Math.random() * this.getDensity()) //当前视野中密度越小 添加越频繁
  88. }
  89. add()
  90. document.addEventListener('visibilitychange', (e) => {
  91. if (!document.hidden) add()
  92. console.log('document.hidden', document.hidden)
  93. })
  94. }
  95. Viewer.prototype.getDensity = function () {
  96. let frustumMatrix = new THREE.Matrix4
  97. frustumMatrix.multiplyMatrices(this.camera.projectionMatrix, this.camera.matrixWorldInverse)
  98. let frustum = new THREE.Frustum();
  99. frustum.setFromProjectionMatrix(frustumMatrix)
  100. let count = this.cardGroup.children.filter(card => {
  101. return frustum.containsPoint(card.position)
  102. }).length
  103. let density = count / (this.renderer.domElement.width * this.renderer.domElement.height) * 1000
  104. return density
  105. }
  106. Viewer.prototype.addCard = function (around) {
  107. let cardIndex = Math.floor(cardNames.length * Math.random())
  108. common.loadTexture("assets/" + cardNames[cardIndex], (map) => {
  109. console.log('------',map);
  110. /* let card = new THREE.Mesh(planeGeo, new THREE.MeshBasicMaterial({
  111. map,
  112. transparent:true, opacity:0,side:2
  113. })) */
  114. let card = new THREE.Mesh(planeGeo, new THREE.ShaderMaterial({
  115. uniforms: {
  116. map: { value: map },
  117. resolution: { value: new THREE.Vector2(this.renderer.domElement.width, this.renderer.domElement.height) },
  118. blurRadius: { value: 0 },//像素
  119. opacity: { value: 0 }
  120. },
  121. vertexShader: BlurShader.vertexShader,
  122. fragmentShader: BlurShader.fragmentShader,
  123. transparent: true, side: 2
  124. }))
  125. Object.defineProperty(card.material, 'opacity', {
  126. get: function () {
  127. return card.material.uniforms.opacity.value
  128. },
  129. set: function (e) {
  130. card.material.uniforms.opacity.value = e
  131. card.material.uniforms.blurRadius.value = math.linearClamp(e, [0, 0.4], [40, 0])
  132. }
  133. })
  134. let direction, far = setting.cards.far
  135. if (around) {//在四周所有方向都可生成,在一开始时需要
  136. let n = 0.6//范围0-1 越大越可能接近相机
  137. far = far * (1 - n * Math.random()) //靠近一点
  138. direction = new THREE.Vector3(0, 0, -1).applyEuler(new THREE.Euler(0, Math.PI * 2 * Math.random(), 0))
  139. } else {//仅在相机前方生成,因为相机往这个方向移动,最前方空缺
  140. direction = new THREE.Vector3(0, 0, -1).applyQuaternion(this.camera.quaternion).applyEuler(new THREE.Euler(0, this.camera.hfov * (Math.random() - 0.5), 0))
  141. }
  142. let h = (Math.random() * 2 - 1) * setting.cards.highest * 0.8 // *0.8是因为靠近后就会飞出视线
  143. card.position.copy(this.camera.position).add(direction.add(new THREE.Vector3(0, h, 0)).multiplyScalar(far))
  144. card.scale.set(map.image.width / 500, map.image.height / 500, 1)
  145. this.cardGroup.add(card)
  146. card.transition = transitions.start(lerp.property(card.material, 'opacity', 1, (e) => {
  147. //console.log(e, card.uuid)
  148. }), setting.cards.fadeInDur);
  149. })
  150. }
  151. Viewer.prototype.removeCards = function () {//移除超过bound的卡
  152. let needRemove = this.cardGroup.children.filter(card => {
  153. if (card.disToCam > setting.cards.far) {
  154. card.material.dispose()
  155. transitions.cancel(card.transition)
  156. //console.log('remove一张卡')
  157. return true
  158. }
  159. })
  160. needRemove.forEach(card => card.parent.remove(card))
  161. //needRemove.length>0 && console.log('当前存在卡数', this.cardGroup.children.length)
  162. }
  163. Viewer.prototype.update = function (deltaTime) {//绘制的时候同时更新
  164. this.setSize()
  165. this.control.update(deltaTime)
  166. transitions.update(deltaTime)
  167. if (this.autoMove) {
  168. let direction = new THREE.Vector3(0, 0, -1).applyQuaternion(this.camera.quaternion)
  169. let moveSpeed = 0.8
  170. this.camera.position.add(direction.multiplyScalar(deltaTime * moveSpeed))
  171. }
  172. this.cardGroup.children.forEach(card => {
  173. card.quaternion.copy(this.camera.quaternion)
  174. let dis = card.position.clone().setY(0).distanceTo(this.camera.position.clone().setY(0))
  175. if (!card.transition.running) {
  176. card.material.opacity = math.linearClamp(dis, [setting.cards.near, setting.cards.beginFadeNear], [0, 1])
  177. }
  178. card.disToCam = dis
  179. })
  180. this.removeCards()
  181. var needsUpdate = 1;
  182. if (needsUpdate) {
  183. this.renderer.autoClear = true
  184. this.renderer.render(this.scene, this.camera)
  185. }
  186. }
  187. Viewer.prototype.bindEvents = function () {
  188. this.renderer.domElement.addEventListener('pointermove', this.onPointerMove.bind(this), false);
  189. this.renderer.domElement.addEventListener('pointerdown', this.onPointerDown.bind(this), false);
  190. this.renderer.domElement.addEventListener('pointerup', this.onPointerUp.bind(this), false);
  191. }
  192. Viewer.prototype.setRenderer = function () {
  193. try {
  194. this.renderer = new THREE.WebGLRenderer({ canvas: $(this.dom).find("canvas")[0], antialias: true }),
  195. this.renderer.setPixelRatio(window.devicePixelRatio ? window.devicePixelRatio : 1),
  196. this.renderer.autoClear = false
  197. this.renderer.setClearColor(0xffffff, 1)
  198. console.log("ContextCreated")
  199. //this.emit(Events.ContextCreated)
  200. } catch (e) {
  201. console.error("Unable to create a WebGL rendering context")
  202. }
  203. }
  204. Viewer.prototype.hasChanged = function () {//判断画面是否改变了,改变后需要更新一些东西
  205. var copy = function () {
  206. this.previousState = {
  207. projectionMatrix: this.camera.projectionMatrix.clone(),//worldMatrix在control时归零了所以不用了吧,用position和qua也一样
  208. position: this.camera.position.clone(),
  209. quaternion: this.camera.quaternion.clone(),
  210. //mouse: this.mouse.clone(),
  211. fov: this.camera.fov
  212. };
  213. }.bind(this)
  214. if (!this.previousState) {
  215. copy()
  216. return { cameraChanged: !0, changed: !0 };
  217. }
  218. var cameraChanged =
  219. !this.camera.projectionMatrix.equals(this.previousState.projectionMatrix) ||
  220. !this.camera.position.equals(this.previousState.position) ||
  221. !this.camera.quaternion.equals(this.previousState.quaternion)
  222. var changed = cameraChanged //|| !this.mouse.equals(this.previousState.mouse)
  223. copy()
  224. return { cameraChanged, changed };
  225. }
  226. Viewer.prototype.setSize = function () {
  227. var w, h, pixelRatio;
  228. return function () {
  229. if (w != this.dom.clientWidth || h != this.dom.clientHeight || pixelRatio != window.devicePixelRatio) {
  230. w = this.dom.clientWidth;
  231. h = this.dom.clientHeight;
  232. pixelRatio = window.devicePixelRatio;
  233. this.camera.aspect = w / h;
  234. this.camera.updateProjectionMatrix();
  235. this.renderer.setSize(w, h, false, pixelRatio);
  236. this.camera.hfov = cameraLight.getHFOVForCamera(this.camera, true)
  237. this.cardGroup.children.forEach(card =>
  238. card.material.uniforms.resolution.value.set(w, h)
  239. )
  240. }
  241. }
  242. }()
  243. Viewer.prototype.animate = function () {
  244. var deltaTime = Math.min(1, this.updateClock.getDelta());
  245. this.update(deltaTime)
  246. //bus.emit('player/position/change', {x:this.position.x, y:this.position.z, lon: this.cameraControls.controls.panorama.lon})
  247. window.requestAnimationFrame(this.animate.bind(this));
  248. },
  249. Viewer.prototype.onPointerMove = function (event) {
  250. if (event.isPrimary === false) return;
  251. mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
  252. mouse.y = - (event.clientY / window.innerHeight) * 2 + 1;
  253. if (!this.pointerDownPos) this.checkIntersection();
  254. }
  255. Viewer.prototype.onPointerDown = function (event) {
  256. if (event.isPrimary === false) return;
  257. mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
  258. mouse.y = - (event.clientY / window.innerHeight) * 2 + 1;
  259. this.pointerDownPos = mouse.clone()
  260. this.pointerDownTime = Date.now()
  261. }
  262. Viewer.prototype.onPointerUp = function (event) {
  263. if (event.isPrimary === false) return;
  264. mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
  265. mouse.y = - (event.clientY / window.innerHeight) * 2 + 1;
  266. let now = Date.now()
  267. if (mouse.distanceTo(this.pointerDownPos) < 0.006 && now - this.pointerDownTime < 1000) {//click
  268. //doubleClick
  269. /* var time = new Date().getTime();
  270. if(time - this.clickTime < 300){
  271. if(this.intersects.length){
  272. console.log('doubleClick');
  273. transitions.cancelById(0)
  274. transitions.start(lerp.vector(this.control.target, this.intersects[0].point), 600, null, 0 , easing.easeInOutQuad, null, Transitions.doubleClick);
  275. }
  276. } */
  277. if (this.hoveredObject) {
  278. this.dispatchEvent({ type: 'clickObject', imgName: this.hoveredObject.material.uniforms.map.value.image.src.split('/').pop() })
  279. }
  280. }
  281. this.pointerDownPos = null
  282. }
  283. Viewer.prototype.checkIntersection = function () {
  284. raycaster.setFromCamera(mouse, this.camera);
  285. raycaster.near = 2
  286. const intersects = raycaster.intersectObject(this.cardGroup, true);
  287. var recover = () => {
  288. if (this.hoveredObject) {
  289. }
  290. }
  291. if (intersects.length > 0) {
  292. const hoveredObject = intersects[0].object;
  293. if (this.hoveredObject != hoveredObject) {
  294. recover()
  295. this.dispatchEvent({ type: "hoverObject", imgName: hoveredObject.material.uniforms.map.value.image.src.split('/').pop() })
  296. this.hoveredObject = hoveredObject;
  297. this.dom.style.cursor = 'pointer'
  298. }
  299. } else {
  300. recover()
  301. this.dispatchEvent({ type: "mouseoutObject" })
  302. this.dom.style.cursor = ''
  303. this.hoveredObject = null
  304. }
  305. this.intersects = intersects;
  306. }
  307. Viewer.prototype.setAutoMove = function (state) {//设置相机飞行状态
  308. this.autoMove = !!state
  309. }
  310. Object.assign(Viewer.prototype, THREE.EventDispatcher.prototype);
  311. //============
  312. var startTime = new Date().getTime();
  313. var viewer = new Viewer(0, $("#player")[0])