objViewer.js 15 KB

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