objViewer.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  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. let delayNeedUpdated
  124. Viewer.prototype.animate = function () {
  125. var deltaTime = Math.min(1, this.updateClock.getDelta());
  126. this.update(deltaTime)
  127. //bus.emit('player/position/change', {x:this.position.x, y:this.position.z, lon: this.cameraControls.controls.panorama.lon})
  128. let changed = this.hasChanged()
  129. if (changed.cameraChanged) {
  130. this.dispatchEvent({ type: 'view.changed'/* , changeSlightly: changed.changeSlightly */ })
  131. delayNeedUpdated = true
  132. if (!transitions.funcs.some(function (e) { return e.name === 'cameraFly' })) {
  133. convertTool.intervalTool.isWaiting('delayUpdate', () => { //延时update,防止卡顿
  134. if (delayNeedUpdated) {
  135. delayNeedUpdated = false
  136. this.dispatchEvent({ type: 'delayUpdate' })
  137. return true
  138. }
  139. }, 200)
  140. }
  141. let label_ = this.labels.filter(e => e.elem[0].style.display == 'block')
  142. label_.sort((a, b) => b.pos2d.z - a.pos2d.z)
  143. label_.forEach((e, index) => e.elem.css('z-index', index + 1000));
  144. }
  145. window.requestAnimationFrame(this.animate.bind(this));
  146. },
  147. Viewer.prototype.loadOBJ = function (done) {
  148. var startTime = new Date().getTime();
  149. window.objs = [];
  150. var group = new THREE.Object3D;
  151. this.meshGroup.add(group);
  152. function onProgress(xhr) {
  153. if (xhr.lengthComputable) {
  154. var percentComplete = xhr.loaded / xhr.total * 100;
  155. console.log('model ' + Math.round(percentComplete, 2) + '% downloaded');
  156. }
  157. }
  158. function onError() { }
  159. var MTLLoader = new THREE.MTLLoader();
  160. var OBJLoader = new THREE.OBJLoader()
  161. var loadModel = () => {
  162. var info = {//凳子
  163. path: 'model/',
  164. mtl: 'wl48-he.mtl',
  165. obj: 'wl48-he.obj',
  166. position: [0, 0],
  167. rotation: 0,
  168. height: 1
  169. };
  170. if (!info) {
  171. console.log("加载持续时间:" + (new Date().getTime() - startTime))
  172. return;
  173. }
  174. MTLLoader.setPath(info.path).load(info.mtl, (materials) => {
  175. materials.preload();
  176. OBJLoader.setMaterials(materials)
  177. .setPath(info.path)
  178. .load(info.obj, (object) => {
  179. group.add(object);
  180. object.traverse(function (child) {
  181. if (child.isMesh) {
  182. if (child.name == "WL48_ping") {
  183. let textrueLoader = new THREE.TextureLoader();
  184. emissiveTexture = textrueLoader.load("model/default.jpg");
  185. let step = 1
  186. setInterval(() => {
  187. if (window.showWenli) {
  188. if (child.material.emissiveIntensity > 0.5) {
  189. step = -1
  190. }
  191. if (child.material.emissiveIntensity < 0) {
  192. step = 1
  193. }
  194. child.material.emissiveIntensity += 0.01 * step;
  195. }
  196. else {
  197. child.material.emissiveMap = emissiveTexture;
  198. child.material.emissiveIntensity = 0;
  199. }
  200. }, 50);
  201. child.material.emissive = new THREE.Color(0xffffff);
  202. child.material.dispose();
  203. }
  204. /* if(child.geometry){
  205. child.geometry.computeBoundingBox();
  206. bound.union(child.geometry.boundingBox)
  207. } */
  208. }
  209. });
  210. this.model = object
  211. let s = 0.010
  212. object.scale.set(s, s, s)
  213. done && done()
  214. console.log("加载持续时间:" + (new Date().getTime() - startTime))
  215. setTimeout(() => {
  216. this.dispatchEvent({ type: 'hadLoaded' })
  217. });
  218. }, onProgress, onError);
  219. });
  220. }
  221. loadModel()
  222. var light1 = new THREE.AmbientLight(16777215);
  223. light1.intensity = 2.8;
  224. this.scene.add(light1)
  225. var light2 = new THREE.SpotLight(0xffffff, 1);
  226. light2.position.set(0, 0, 3)
  227. light2.intensity = 0.2;
  228. var light3 = new THREE.SpotLight(0xffffff, 1);
  229. light3.position.set(0, 0, -3)
  230. light3.intensity = 0.4;
  231. // let spotLightHelper = new THREE.SpotLightHelper(light2);
  232. // let spotLightHelper3 = new THREE.SpotLightHelper(light3);
  233. this.scene.add(light2)
  234. this.scene.add(light3)
  235. // this.scene.add( spotLightHelper );
  236. // this.scene.add( spotLightHelper3 );
  237. }
  238. Viewer.prototype.onPointerMove = function (event) {
  239. if (event.isPrimary === false) return;
  240. mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
  241. mouse.y = - (event.clientY / window.innerHeight) * 2 + 1;
  242. if (!this.pointerDownPos) this.checkIntersection();
  243. }
  244. Viewer.prototype.onPointerDown = function (event) {
  245. if (event.isPrimary === false) return;
  246. mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
  247. mouse.y = - (event.clientY / window.innerHeight) * 2 + 1;
  248. this.pointerDownPos = mouse.clone()
  249. //console.log('onPointerDown')
  250. }
  251. Viewer.prototype.onPointerUp = function (event) {
  252. if (event.isPrimary === false) return;
  253. this.dispatchEvent({ type: 'onPointerUp' })
  254. mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
  255. mouse.y = - (event.clientY / window.innerHeight) * 2 + 1;
  256. if (this.pointerDownPos && mouse.distanceTo(this.pointerDownPos) < 0.006) {//click
  257. this.checkIntersection()
  258. // if (this.intersects.length) {
  259. // console.log(this.intersects[0].point);
  260. // this.addLabel({ position: this.intersects[0].point })
  261. // }
  262. // var time = new Date().getTime();
  263. // if (time - this.clickTime < 300) {
  264. // if (this.intersects.length) {
  265. // console.log('doubleClick');
  266. // transitions.cancelById(0)
  267. // transitions.start(lerp.vector(this.control.target, this.intersects[0].point), 600, null, 0/* Delay */, easing.easeInOutQuad, null, Transitions.doubleClick);
  268. // }
  269. // }
  270. // this.clickTime = time;
  271. }
  272. this.pointerDownPos = null
  273. //console.log('onPointerUp')
  274. }
  275. Viewer.prototype.checkIntersection = function () {
  276. raycaster.setFromCamera(mouse, this.camera);
  277. const intersects = raycaster.intersectObject(this.model/* this.meshGroup */, true);
  278. this.intersects = intersects;
  279. }
  280. /* Viewer.prototype.adjustModelPos = function(){ //固定地板高度的情况下,调整模型的position.y
  281. this.meshGroup.updateMatrixWorld();
  282. this.model.updateMatrixWorld();
  283. var bound = this.model.bound.clone().applyMatrix4(this.model.matrixWorld)
  284. var center = bound.getCenter()
  285. //为了让最低点在地面上:
  286. this.meshGroup.position.y += floorY - bound.min.y
  287. //居中:
  288. this.meshGroup.position.x += 0 - center.x
  289. this.meshGroup.position.z += 0 - center.z
  290. } */
  291. Viewer.prototype.removeAllLabels = function (data) {
  292. this.labels.forEach(label => {
  293. label.dispose()
  294. label = null
  295. })
  296. this.labels = []
  297. }
  298. Viewer.prototype.loadLabelsFromData = function (data) {
  299. data.forEach(info => {
  300. info.position = new THREE.Vector3().fromArray(info.posInModel).applyMatrix4(this.model.matrixWorld)
  301. this.addLabel(info)
  302. })
  303. }
  304. Viewer.prototype.addLabel = function (o) {
  305. labelIndex++
  306. o.title = o.title || ('default' + labelIndex)
  307. o.shelterByModel = true
  308. let label = new Label2D(o)
  309. this.labels.push(label)
  310. }
  311. Viewer.prototype.removeLabel = function (label) {
  312. label.dispose()
  313. let index = this.labels.indexOf(label)
  314. index > -1 && this.labels.splice(index)
  315. label.li && label.li.remove()
  316. }
  317. Viewer.prototype.setAddLabelState = function (state) {
  318. this.addingLabel = !!state
  319. $('#addLabel').text(state ? '停止加标签' : '添加标签')
  320. }
  321. Viewer.prototype.exportLabelData = function () {
  322. let data = this.labels.map(label => {
  323. let inv = new THREE.Matrix4().getInverse(this.model.matrixWorld)
  324. let posInModel = label.position.clone().applyMatrix4(inv)
  325. let info = {
  326. title: label.title,
  327. posInModel: convertTool.toPrecision(posInModel.toArray(), 4),
  328. }
  329. return info
  330. })
  331. $('textarea').css('display', 'block').text(JSON.stringify(data))
  332. console.log(data)
  333. return data
  334. }
  335. Viewer.prototype.getCLabel = function () { //获取最接近中心的label
  336. let disSquairs = this.labels.filter(e => e.elem[0].style.display == 'block').map((label) => {
  337. return {
  338. label,
  339. disSquair: label.pos2d.x * label.pos2d.x + label.pos2d.y * label.pos2d.y
  340. }
  341. })
  342. disSquairs.sort((e1, e2) => { return e1.disSquair - e2.disSquair })
  343. return disSquairs[0] && disSquairs[0].label
  344. }
  345. //============
  346. var startTime = new Date().getTime();
  347. function dataURLtoBlob(dataurl) {//将base64转换blob
  348. var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
  349. bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
  350. while (n--) {
  351. u8arr[n] = bstr.charCodeAt(n);
  352. }
  353. return new Blob([u8arr], { type: mime });
  354. }
  355. /*
  356. MeshStandardMaterial(pbr)代替Phong
  357. 优点 : 能量守恒、更容易调节出真实感。 metalnessMap只用到一个通道,颜色信息整合到albedo贴图里,省数据。
  358. 缺点:可能,mtl里的值只能用到一部分, specular用不到。 (会降低对specular的控制)
  359. 另外不知道大部分模型用的是哪种模式,是否使用metalnessMap。
  360. aoMap r
  361. roughnessMap alphaMap g
  362. metalnessMap b
  363. normalMap ?
  364. bumpMap : 黑白?
  365. 主要是光滑度or粗糙度(可贴图) 还有 金属性(可贴图) 还有颜色(可贴图),透明度(in颜色贴图),法线贴图or凹凸贴图
  366. 贴图的属性 rotation offset repeat (当wrapS = THREE.RepeatWrapping,wrapT = THREE.RepeatWrapping)
  367. */