main.js 8.1 KB

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