main.js 7.5 KB

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