main.js 7.8 KB

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