main.js 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. import * as THREE from "../js/three.module.js"
  2. import initTinyUSDZ from "../js/tinyusdz.js"
  3. import { OrbitControls } from "../js/OrbitControls.js"
  4. const urlAll = window.location.href.split("?m=")[1]
  5. // console.log(123456,urlAll);
  6. // const USDZ_FILEPATH = `https://4dkankan.oss-cn-shenzhen.aliyuncs.com/sxz/${urlAll}.usdz`;
  7. // const USDZ_FILEPATH = `https://us-test.4dkankan.com/20241202dome/Shuiyueguanyin.usdz`;
  8. const USDZ_FILEPATH = `https://3d-usdz.4dkankan.com/sxz/${urlAll}.usdz`
  9. document.addEventListener("DOMContentLoaded", async () => {
  10. const loadingBar = document.getElementById("loading") // 获取加载条元素
  11. loadingBar.style.display = "block" // 显示加载条
  12. const usd_res = await fetch(USDZ_FILEPATH)
  13. const totalBytes = parseInt(usd_res.headers.get("Content-Length"), 10) // 获取总字节数
  14. const reader = usd_res.body.getReader() // 获取读取器
  15. const chunks = [] // 存储数据块
  16. let receivedLength = 0 // 已接收字节数
  17. let timeOut = -1
  18. // 更新加载条的函数
  19. const updateLoadingBar = (loaded) => {
  20. let percentage = (loaded / totalBytes) * 100
  21. if (percentage >= 100) {
  22. percentage = 100
  23. // 隐藏加载条
  24. clearTimeout(timeOut)
  25. timeOut = setTimeout(() => {
  26. const loadingBoxDom = document.querySelector(".loadingBox")
  27. loadingBoxDom.style.opacity = 0
  28. loadingBoxDom.style.pointerEvents = "none"
  29. }, 300)
  30. }
  31. loadingBar.style.width = `${percentage}%` // 更新加载条宽度
  32. }
  33. // 读取数据流
  34. while (true) {
  35. const { done, value } = await reader.read() // 读取数据
  36. if (done) break // 如果读取完成,退出循环
  37. chunks.push(value) // 存储数据块
  38. receivedLength += value.length // 更新已接收字节数
  39. updateLoadingBar(receivedLength) // 更新加载条
  40. }
  41. const usd_data = new Uint8Array(receivedLength) // 创建最终数据数组
  42. let position = 0
  43. for (const chunk of chunks) {
  44. usd_data.set(chunk, position) // 将数据块写入最终数组
  45. position += chunk.length // 更新位置
  46. }
  47. // const usd_binary = new Uint8Array(usd_data);
  48. // 加载 TinyUSDZ
  49. initTinyUSDZ().then(function (TinyUSDZLoader) {
  50. const usd = new TinyUSDZLoader.TinyUSDZLoader(usd_data)
  51. // console.log(usd.numMeshes());
  52. // 隐藏加载条
  53. loadingBar.style.display = "none"
  54. const scene = new THREE.Scene()
  55. const camera = new THREE.PerspectiveCamera(
  56. 75,
  57. window.innerWidth / window.innerHeight,
  58. 0.1,
  59. 1000
  60. )
  61. const renderer = new THREE.WebGLRenderer({
  62. alpha: true, // 关键配置,设置背景透明
  63. antialias: true, // 可选抗锯齿
  64. })
  65. renderer.setClearColor(0x000000, 0) // 第二个参数为透明度(0表示完全透明)
  66. renderer.setSize(window.innerWidth, window.innerHeight)
  67. renderer.setAnimationLoop(animate)
  68. // 设置输出颜色空间为线性SRGB
  69. renderer.outputColorSpace = THREE.LinearSRGBColorSpace
  70. document.body.appendChild(renderer.domElement)
  71. // First mesh only
  72. const mesh = usd.getMesh(0)
  73. //console.log("usd", usd)
  74. //console.log("mesh", mesh);
  75. //const geometry = new THREE.BoxGeometry( 1, 1, 1 );
  76. const geometry = new THREE.BufferGeometry()
  77. geometry.setAttribute(
  78. "position",
  79. new THREE.BufferAttribute(mesh.points, 3)
  80. )
  81. // TODO: set normal from mesh
  82. if (mesh.hasOwnProperty("texcoords")) {
  83. // console.log(mesh.texcoords);
  84. geometry.setAttribute("uv", new THREE.BufferAttribute(mesh.texcoords, 2))
  85. }
  86. const usdMaterial = usd.getMaterial(mesh.materialId)
  87. //console.log("usdMat", usdMaterial);
  88. //if (usdMaterial.aaa) {
  89. // console.log("aaa");
  90. //}
  91. var material
  92. if (usdMaterial.hasOwnProperty("diffuseColorTextureId")) {
  93. const diffTex = usd.getTexture(usdMaterial.diffuseColorTextureId)
  94. const img = usd.getImage(diffTex.textureImageId)
  95. // console.log(img);
  96. // assume RGBA for now.
  97. let image8Array = new Uint8ClampedArray(img.data)
  98. let imgData = new ImageData(image8Array, img.width, img.height)
  99. const texture = new THREE.DataTexture(imgData, img.width, img.height)
  100. texture.flipY = true
  101. texture.needsUpdate = true
  102. material = new THREE.MeshBasicMaterial({
  103. map: texture,
  104. })
  105. } else {
  106. material = new THREE.MeshNormalMaterial()
  107. }
  108. // Assume triangulated indices.
  109. geometry.setIndex(
  110. new THREE.Uint32BufferAttribute(mesh.faceVertexIndices, 1)
  111. )
  112. geometry.computeVertexNormals()
  113. //const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  114. const cube = new THREE.Mesh(geometry, material)
  115. // 缩放模型
  116. cube.scale.set(2, 2, 2)
  117. cube.updateMatrixWorld(true) // 强制更新世界矩阵[3](@ref)
  118. // 计算包围盒
  119. const box = new THREE.Box3().setFromObject(cube)
  120. const center = new THREE.Vector3()
  121. box.getCenter(center)
  122. // 居中模型
  123. cube.position.sub(center)
  124. // 计算尺寸并调整相机
  125. const size = box.getSize(new THREE.Vector3()).length()
  126. camera.near = size / 100
  127. camera.far = size * 100
  128. camera.updateProjectionMatrix()
  129. camera.position.set(size * 0.5, size * 0.5, size * 0.5)
  130. camera.lookAt(0, 0, 0)
  131. scene.add(cube)
  132. const controls = new OrbitControls(camera, renderer.domElement)
  133. controls.enablePan = true // 禁用右键平移功能
  134. controls.enableZoom = true // 必须禁用轨道控制器的默认缩放[1](@ref)
  135. controls.enableDamping = true
  136. controls.dampingFactor = 0.25
  137. controls.screenSpacePanning = false
  138. controls.minPolarAngle = Math.PI / 180 * 1 // 1 度(约 0.01745 弧度)
  139. controls.maxPolarAngle = Math.PI - Math.PI / 180 * 1 // 179 度(约 3.124 弧度)
  140. // 兼容鼠标滚轮与触摸屏双指缩放
  141. // 兼容鼠标滚轮与触摸屏双指缩放
  142. // const handleZoom = (delta) => {
  143. // // console.log('--------',delta);
  144. // cube.updateMatrixWorld(true);
  145. // // 计算包围盒
  146. // const box = new THREE.Box3().setFromObject(cube);
  147. // const center = new THREE.Vector3();
  148. // box.getCenter(center);
  149. // // 居中模型
  150. // cube.position.sub(center);
  151. // cube.scale.multiplyScalar(delta);
  152. // cube.scale.clampScalar(0.5, 4); // 限制缩放范围0.5-3倍[1,6](@ref)
  153. // };
  154. // 鼠标滚轮事件
  155. // window.addEventListener(
  156. // "wheel",
  157. // (e) => {
  158. // e.preventDefault();
  159. // const zoomFactor = e.deltaY > 0 ? 0.95 : 1.05;
  160. // handleZoom(zoomFactor);
  161. // },
  162. // { passive: false }
  163. // );
  164. // 触摸屏双指缩放
  165. // let initialDistance = 0;
  166. // window.addEventListener("touchstart", (e) => {
  167. // if (e.touches.length === 2) {
  168. // initialDistance = Math.hypot(
  169. // e.touches[0].pageX - e.touches[1].pageX,
  170. // e.touches[0].pageY - e.touches[1].pageY
  171. // );
  172. // }
  173. // });
  174. // window.addEventListener("touchmove", (e) => {
  175. // if (e.touches.length === 2) {
  176. // const currentDistance = Math.hypot(
  177. // e.touches[0].pageX - e.touches[1].pageX,
  178. // e.touches[0].pageY - e.touches[1].pageY
  179. // );
  180. // const zoomFactor = currentDistance > initialDistance ? 1.01 : 0.99;
  181. // handleZoom(zoomFactor);
  182. // initialDistance = currentDistance;
  183. // }
  184. // });
  185. function animate() {
  186. //cube.rotation.x += 0.01;
  187. // cube.rotation.y += 0.02;
  188. controls.update()
  189. renderer.render(scene, camera)
  190. }
  191. window.addEventListener("resize", () => {
  192. camera.aspect = window.innerWidth / window.innerHeight
  193. camera.updateProjectionMatrix()
  194. renderer.setSize(window.innerWidth, window.innerHeight)
  195. })
  196. })
  197. })