objViewer.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  1. let texLoader = new THREE.TextureLoader;
  2. var emissiveTexture = null
  3. let camera, scene, renderer, stats, gui;
  4. const mouse = new THREE.Vector2();
  5. const raycaster = new THREE.Raycaster(); raycaster.linePrecision = 0;//不检测boxHelper
  6. const Transitions = {
  7. doubleClick: 0,
  8. helperOpa: 1,
  9. }
  10. let labelIndex = 0
  11. var Viewer = function (index, dom) {
  12. THREE.EventDispatcher.call(this)
  13. this.index = index;
  14. this.dom = dom
  15. this.camera = new THREE.PerspectiveCamera();
  16. this.camera.position.set(0, 0, 0.78);
  17. this.control = new THREE.OrbitControls(this.camera, this.dom)
  18. this.control.enableDamping = true;
  19. this.control.dampingFactor = 0.4;
  20. this.control.minDistance = 0.3;
  21. this.control.maxDistance = 2;
  22. this.control.enablePan = false;
  23. this.control.enableZoom = true;
  24. this.setRenderer()
  25. this.scene = new THREE.Scene;
  26. this.pointerDownPos
  27. this.textures = [];
  28. this.labels = []
  29. this.active = false;
  30. this.antialias = true;
  31. this.clickTime = new Date().getTime();
  32. this.updateClock = new THREE.Clock;
  33. this.init()
  34. }
  35. Viewer.prototype = Object.create(THREE.EventDispatcher.prototype)
  36. Viewer.constructor = Viewer
  37. Viewer.prototype.bindEvents = function () {
  38. this.renderer.domElement.addEventListener('pointerdown', this.onPointerDown.bind(this), false);
  39. this.renderer.domElement.addEventListener('pointerup', this.onPointerUp.bind(this), false);
  40. }
  41. Viewer.prototype.setRenderer = function () {
  42. try {
  43. this.renderer = new THREE.WebGLRenderer(
  44. {
  45. canvas: $(this.dom).find("canvas")[0],
  46. antialias: true,
  47. alpha: true
  48. }
  49. ),//许钟文 添加个抗锯齿,否则添加的线条锯齿严重,
  50. this.renderer.setClearAlpha(0);
  51. //this.renderer.autoClear = !0,
  52. this.renderer.setPixelRatio(window.devicePixelRatio ? window.devicePixelRatio : 1)
  53. // this.renderer.autoClear = false
  54. //this.emit(Events.ContextCreated)
  55. } catch (e) {
  56. console.error("Unable to create a WebGL rendering context")
  57. }
  58. }
  59. Viewer.prototype.update = function (deltaTime) {//绘制的时候同时更新
  60. //if(!this.active)return;
  61. this.setSize()
  62. this.control.update(deltaTime)
  63. transitions.update(deltaTime)
  64. var needsUpdate = 1;
  65. if (needsUpdate) {
  66. //this.renderer.autoClear = true
  67. this.renderer.render(this.scene, this.camera)
  68. }
  69. }
  70. Viewer.prototype.hasChanged = function () {//判断画面是否改变了,改变后需要更新一些东西
  71. var copy = function () {
  72. this.previousState = {
  73. projectionMatrix: this.camera.projectionMatrix.clone(),//worldMatrix在control时归零了所以不用了吧,用position和qua也一样
  74. position: this.camera.position.clone(),
  75. quaternion: this.camera.quaternion.clone(),
  76. //mouse: this.mouse.clone(),
  77. fov: this.camera.fov
  78. };
  79. }.bind(this)
  80. if (!this.previousState) {
  81. copy()
  82. return { cameraChanged: !0, changeSlightly: !1 };
  83. }
  84. var cameraChanged =
  85. !this.camera.projectionMatrix.equals(this.previousState.projectionMatrix) ||
  86. !this.camera.position.equals(this.previousState.position) ||
  87. !this.camera.quaternion.equals(this.previousState.quaternion)
  88. //var changed = cameraChanged //|| !this.mouse.equals(this.previousState.mouse)
  89. let changeSlightly
  90. if (cameraChanged) {
  91. changeSlightly = math.closeTo(this.camera.position, this.previousState.position, 1e-2) &&
  92. math.closeTo(this.camera.quaternion, this.previousState.quaternion, 1e-3)
  93. }
  94. copy()
  95. return { cameraChanged, changeSlightly };
  96. }
  97. Viewer.prototype.setSize = function () {
  98. var w, h, pixelRatio;
  99. return function () {
  100. if (w != this.dom.clientWidth || h != this.dom.clientHeight || pixelRatio != window.devicePixelRatio) {
  101. w = this.dom.clientWidth;
  102. h = this.dom.clientHeight;
  103. pixelRatio = window.devicePixelRatio;
  104. this.camera.aspect = w / h;
  105. this.camera.updateProjectionMatrix();
  106. this.renderer.setSize(w, h, false, pixelRatio);
  107. }
  108. }
  109. }()
  110. Viewer.prototype.init = function () {
  111. this.meshGroup = new THREE.Object3D();
  112. this.scene.add(this.meshGroup);
  113. this.meshGroup.name = "viewerMeshGroup";
  114. var buildScene = () => {
  115. this.animate()
  116. }
  117. this.loadOBJ(() => {
  118. this.bindEvents()
  119. //this.loadLabels()
  120. })
  121. buildScene()
  122. }
  123. Viewer.prototype.animate = function () {
  124. var deltaTime = Math.min(1, this.updateClock.getDelta());
  125. this.update(deltaTime)
  126. //bus.emit('player/position/change', {x:this.position.x, y:this.position.z, lon: this.cameraControls.controls.panorama.lon})
  127. let changed = this.hasChanged()
  128. if (changed.cameraChanged) {
  129. this.dispatchEvent({ type: 'view.changed', changeSlightly: changed.changeSlightly })
  130. let label_ = this.labels.filter(e => e.elem[0].style.display == 'block')
  131. label_.sort((a, b) => b.pos2d.z - a.pos2d.z)
  132. label_.forEach((e, index) => e.elem.css('z-index', index + 1000));
  133. }
  134. window.requestAnimationFrame(this.animate.bind(this));
  135. },
  136. Viewer.prototype.loadOBJ = function (done) {
  137. var startTime = new Date().getTime();
  138. window.objs = [];
  139. var group = new THREE.Object3D;
  140. this.meshGroup.add(group);
  141. function onProgress(xhr) {
  142. if (xhr.lengthComputable) {
  143. var percentComplete = xhr.loaded / xhr.total * 100;
  144. console.log('model ' + Math.round(percentComplete, 2) + '% downloaded');
  145. }
  146. }
  147. function onError() { }
  148. var MTLLoader = new THREE.MTLLoader();
  149. var OBJLoader = new THREE.OBJLoader()
  150. var loadModel = () => {
  151. var info = {//凳子
  152. path: 'model/',
  153. mtl: 'wl48-he.mtl',
  154. obj: 'wl48-he.obj',
  155. position: [0, 0],
  156. rotation: 0,
  157. height: 1
  158. };
  159. if (!info) {
  160. console.log("加载持续时间:" + (new Date().getTime() - startTime))
  161. return;
  162. }
  163. MTLLoader.setPath(info.path).load(info.mtl, (materials) => {
  164. materials.preload();
  165. OBJLoader.setMaterials(materials)
  166. .setPath(info.path)
  167. .load(info.obj, (object) => {
  168. group.add(object);
  169. object.traverse(function (child) {
  170. if (child.isMesh) {
  171. if (child.name == "WL48_ping") {
  172. let textrueLoader = new THREE.TextureLoader();
  173. emissiveTexture = textrueLoader.load("model/default.jpg");
  174. let step = 1
  175. setInterval(() => {
  176. if (window.showWenli) {
  177. if (child.material.emissiveIntensity > 0.5) {
  178. step = -1
  179. }
  180. if (child.material.emissiveIntensity < 0) {
  181. step = 1
  182. }
  183. child.material.emissiveIntensity += 0.01 * step;
  184. }
  185. else{
  186. child.material.emissiveMap = emissiveTexture;
  187. child.material.emissiveIntensity = 0;
  188. }
  189. }, 50);
  190. child.material.emissive = new THREE.Color(0xffffff);
  191. child.material.dispose();
  192. }
  193. /* if(child.geometry){
  194. child.geometry.computeBoundingBox();
  195. bound.union(child.geometry.boundingBox)
  196. } */
  197. }
  198. });
  199. this.model = object
  200. let s = 0.010
  201. object.scale.set(s, s, s)
  202. done && done()
  203. console.log("加载持续时间:" + (new Date().getTime() - startTime))
  204. setTimeout(() => {
  205. this.dispatchEvent({ type: 'hadLoaded' })
  206. });
  207. }, onProgress, onError);
  208. });
  209. }
  210. loadModel()
  211. var light1 = new THREE.AmbientLight(16777215);
  212. light1.intensity = 2.8;
  213. this.scene.add(light1)
  214. var light2 = new THREE.SpotLight(0xffffff, 1);
  215. light2.position.set(0, 0, 3)
  216. light2.intensity = 0.2;
  217. var light3 = new THREE.SpotLight(0xffffff, 1);
  218. light3.position.set(0, 0, -3)
  219. light3.intensity = 0.4;
  220. // let spotLightHelper = new THREE.SpotLightHelper(light2);
  221. // let spotLightHelper3 = new THREE.SpotLightHelper(light3);
  222. this.scene.add(light2)
  223. this.scene.add(light3)
  224. // this.scene.add( spotLightHelper );
  225. // this.scene.add( spotLightHelper3 );
  226. }
  227. Viewer.prototype.onPointerMove = function (event) {
  228. if (event.isPrimary === false) return;
  229. mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
  230. mouse.y = - (event.clientY / window.innerHeight) * 2 + 1;
  231. if (!this.pointerDownPos) this.checkIntersection();
  232. }
  233. Viewer.prototype.onPointerDown = function (event) {
  234. if (event.isPrimary === false) return;
  235. mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
  236. mouse.y = - (event.clientY / window.innerHeight) * 2 + 1;
  237. this.pointerDownPos = mouse.clone()
  238. }
  239. Viewer.prototype.onPointerUp = function (event) {
  240. if (event.isPrimary === false) return;
  241. this.dispatchEvent({ type: 'onPointerUp' })
  242. mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
  243. mouse.y = - (event.clientY / window.innerHeight) * 2 + 1;
  244. if (mouse.distanceTo(this.pointerDownPos) < 0.006) {//click
  245. this.checkIntersection()
  246. // if (this.intersects.length) {
  247. // console.log(this.intersects[0].point);
  248. // this.addLabel({ position: this.intersects[0].point })
  249. // }
  250. // var time = new Date().getTime();
  251. // if (time - this.clickTime < 300) {
  252. // if (this.intersects.length) {
  253. // console.log('doubleClick');
  254. // transitions.cancelById(0)
  255. // transitions.start(lerp.vector(this.control.target, this.intersects[0].point), 600, null, 0/* Delay */, easing.easeInOutQuad, null, Transitions.doubleClick);
  256. // }
  257. // }
  258. // this.clickTime = time;
  259. }
  260. this.pointerDownPos = null
  261. }
  262. Viewer.prototype.checkIntersection = function () {
  263. raycaster.setFromCamera(mouse, this.camera);
  264. const intersects = raycaster.intersectObject(this.model/* this.meshGroup */, true);
  265. this.intersects = intersects;
  266. }
  267. /* Viewer.prototype.adjustModelPos = function(){ //固定地板高度的情况下,调整模型的position.y
  268. this.meshGroup.updateMatrixWorld();
  269. this.model.updateMatrixWorld();
  270. var bound = this.model.bound.clone().applyMatrix4(this.model.matrixWorld)
  271. var center = bound.getCenter()
  272. //为了让最低点在地面上:
  273. this.meshGroup.position.y += floorY - bound.min.y
  274. //居中:
  275. this.meshGroup.position.x += 0 - center.x
  276. this.meshGroup.position.z += 0 - center.z
  277. } */
  278. Viewer.prototype.removeAllLabels = function (data) {
  279. this.labels.forEach(label => {
  280. label.dispose()
  281. label = null
  282. })
  283. this.labels = []
  284. }
  285. Viewer.prototype.loadLabelsFromData = function (data) {
  286. data.forEach(info => {
  287. info.position = new THREE.Vector3().fromArray(info.posInModel).applyMatrix4(this.model.matrixWorld)
  288. this.addLabel(info)
  289. })
  290. }
  291. Viewer.prototype.addLabel = function (o) {
  292. labelIndex++
  293. o.title = o.title || ('default' + labelIndex)
  294. o.shelterByModel = true
  295. let label = new Label2D(o)
  296. this.labels.push(label)
  297. }
  298. Viewer.prototype.removeLabel = function (label) {
  299. label.dispose()
  300. let index = this.labels.indexOf(label)
  301. index > -1 && this.labels.splice(index)
  302. label.li && label.li.remove()
  303. }
  304. Viewer.prototype.setAddLabelState = function (state) {
  305. this.addingLabel = !!state
  306. $('#addLabel').text(state ? '停止加标签' : '添加标签')
  307. }
  308. Viewer.prototype.exportLabelData = function () {
  309. let data = this.labels.map(label => {
  310. let inv = new THREE.Matrix4().getInverse(this.model.matrixWorld)
  311. let posInModel = label.position.clone().applyMatrix4(inv)
  312. let info = {
  313. title: label.title,
  314. posInModel: convertTool.toPrecision(posInModel.toArray(), 4),
  315. }
  316. return info
  317. })
  318. $('textarea').css('display', 'block').text(JSON.stringify(data))
  319. console.log(data)
  320. return data
  321. }
  322. Viewer.prototype.getCLabel = function () { //获取最接近中心的label
  323. let disSquairs = this.labels.filter(e => e.elem[0].style.display == 'block').map((label) => {
  324. return {
  325. label,
  326. disSquair: label.pos2d.x * label.pos2d.x + label.pos2d.y * label.pos2d.y
  327. }
  328. })
  329. disSquairs.sort((e1, e2) => { return e1.disSquair - e2.disSquair })
  330. return disSquairs[0] && disSquairs[0].label
  331. }
  332. //============
  333. var startTime = new Date().getTime();
  334. function dataURLtoBlob(dataurl) {//将base64转换blob
  335. var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
  336. bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
  337. while (n--) {
  338. u8arr[n] = bstr.charCodeAt(n);
  339. }
  340. return new Blob([u8arr], { type: mime });
  341. }
  342. /*
  343. MeshStandardMaterial(pbr)代替Phong
  344. 优点 : 能量守恒、更容易调节出真实感。 metalnessMap只用到一个通道,颜色信息整合到albedo贴图里,省数据。
  345. 缺点:可能,mtl里的值只能用到一部分, specular用不到。 (会降低对specular的控制)
  346. 另外不知道大部分模型用的是哪种模式,是否使用metalnessMap。
  347. aoMap r
  348. roughnessMap alphaMap g
  349. metalnessMap b
  350. normalMap ?
  351. bumpMap : 黑白?
  352. 主要是光滑度or粗糙度(可贴图) 还有 金属性(可贴图) 还有颜色(可贴图),透明度(in颜色贴图),法线贴图or凹凸贴图
  353. 贴图的属性 rotation offset repeat (当wrapS = THREE.RepeatWrapping,wrapT = THREE.RepeatWrapping)
  354. */