ソースを参照

新增3D模型本地缓存方法

zhangmingyan 7 ヶ月 前
コミット
13e9aaa26a
2 ファイル変更365 行追加123 行削除
  1. 126 0
      src/DButil.js
  2. 239 123
      src/uwb-sample.js

+ 126 - 0
src/DButil.js

@@ -0,0 +1,126 @@
+const DB_NAME = 'mesh';
+const DB_VERSION = 1; // Use a long long for this value (don't use a float)
+const DB_STORE_NAME = 'model_glb';
+
+export class DBUtil {
+    async get(url, onProgress) {
+        this.db = await this.initDataBase();
+        let getRequest = this.db
+            .transaction([DB_STORE_NAME], "readwrite").objectStore(DB_STORE_NAME).get(url);
+        let that = this;
+        return new Promise((resolve, reject) => {
+            getRequest.onsuccess = function (event) {
+                let modelFile = event.target.result;
+                // 假如已经有缓存了 直接用缓存
+                if (modelFile) {
+                    if (onProgress) {
+                        onProgress(100);
+                    }
+                    resolve(modelFile.blob)
+                } else {
+                    // 假如没有缓存 请求新的模型存入
+                    that.put(url, onProgress).then((blob) => {
+                        resolve(blob)
+                    }).catch(() => {
+                        reject()
+                    });
+                }
+            };
+            getRequest.onerror = function (event) {
+                console.log('error', event)
+                reject()
+            }
+        })
+    }
+    async put(url, onProgress) {
+        const response = await fetch(url);
+
+        if (response.status !== 200) {
+            throw new Error('Request failed');
+        }
+
+        const contentLength = response.headers.get('Content-Length');
+        console.log(contentLength)
+        const totalBytes = parseInt(contentLength, 10);
+        let downloadedBytes = 0;
+
+        const readableStream = response.body;
+
+        const { readable, writable } = new TransformStream();
+
+        const writer = writable.getWriter();
+
+        const reader = readableStream.getReader();
+
+        const pump = async () => {
+            const { done, value } = await reader.read();
+
+            if (done) {
+                writer.close();
+                return;
+            }
+
+            writer.write(value);
+
+            downloadedBytes += value.length;
+
+            if (onProgress) {
+                const progress = (downloadedBytes / totalBytes) * 100;
+                console.log(progress.toFixed(2))
+                onProgress(progress.toFixed(2));
+            }
+
+            return pump();
+        };
+        await pump();
+
+        let blob = null;
+        try {
+                    blob = await new Response(readable).arrayBuffer();
+                } catch (e) {
+                    console.log('请求arrayBuffer失败,用blob方式')
+                    blob = await new Response(readable).blob();
+                }
+
+        let obj = {
+            ssn: url
+        }
+        obj.blob = new Blob([blob])
+        const inputRequest = this.db
+                    .transaction([DB_STORE_NAME], "readwrite")
+                    .objectStore(DB_STORE_NAME)
+                    .add(obj);
+
+        return new Promise((resolve, reject) => {
+            inputRequest.onsuccess = function() {
+                console.log('glb数据添加成功');
+                resolve(obj.blob);
+            };
+            inputRequest.onerror = function(evt) {
+                console.log('glb数据添加失败', evt);
+                reject();
+            };
+        });
+    }
+    initDataBase() {
+        if (!window.indexedDB) {
+            console.log("Your browser doesn't support a stable version of IndexedDB.")
+            return;
+        }
+        let request = indexedDB.open(DB_NAME, DB_VERSION);
+        return new Promise((resolve, reject) => {
+            request.onerror = function () {
+                console.log("error: create db error");
+                reject()
+            };
+            request.onupgradeneeded = function (evt) {
+                evt.currentTarget.result.createObjectStore(
+                    DB_STORE_NAME, {keyPath: 'ssn'});
+            };
+            request.onsuccess = function (evt) {
+                console.log("onsuccess: create db success ");
+                resolve(evt.target.result)
+            };
+        })
+    }
+}

+ 239 - 123
src/uwb-sample.js

@@ -6,6 +6,7 @@ import fetchAndCombine from "../public/loader/loader";
 import { UWB } from "../public/plugin/uwb/index.js";
 import { FXAAShader } from "../public/shader/FAAXShader.js"
 import '../public/libs/tools.js'
+import {DBUtil} from "../src/DButil";
 
 // 定义一个函数,接受元素ID和一个回调函数作为参数,用于处理点击事件
 window.waterMap = {}
@@ -508,134 +509,249 @@ function getsqlData(sdkInstance, uwbInstance, bAddModel) {
         })
       }
 
-      var fbxLoader3 = new THREE.GLTFLoader();
-      fbxLoader3.setDRACOLoader(dracoLoader);
-      if (!fbxLoader3Loaded) {
-
-        fbxLoader3.load("../models/mesh3Draco.gltf", function (fbx) {
-          console.log('1loadzmg211111111111111111111')
-          let benchIdList = window.store.getters['benchList/getBenchList'].map(m => m.id);
-          //fbxLoader3Loaded = true;
-          let result = g_PosArrayResult;
-          for (var item of result) {
-            let x = item.x;
-            let y = item.y;
-            let z = item.z;
-            let ang_x = 0.0;
-            let ang_y = 0.0;
-            let ang_z = 0.0;
-            let benchType = item.bench_type
-            //if (item.use_fix_pos == 1) {
-            if (true) {
-              x = JSON.parse(JSON.stringify(item.fix_pos_x));
-              y = JSON.parse(JSON.stringify(item.fix_pos_y));
-              z = JSON.parse(JSON.stringify(item.fix_pos_z));
-              ang_x = JSON.parse(JSON.stringify(item.fix_angle_x));
-              ang_y = JSON.parse(JSON.stringify(item.fix_angle_y));
-              ang_z = JSON.parse(JSON.stringify(item.fix_angle_z));
-            }
-            else {
-            }
-
-            var distance = 10000.0;
-
-            var xSubTmp = x;
-            var ySubTmp = y;
-            var zSubTmp = z;
-            var ang_xSubTmp = ang_x;
-            var ang_ySubTmp = ang_y;
-            var ang_zSubTmp = ang_z;
-
-            if (g_PosArrayResult) {
-              var iCount = 0;
-              for (var itemSub of g_PosArrayResult) {
-
-                iCount++;
-                var xSub = itemSub.x;
-                var ySub = itemSub.y;
-                var zSub = itemSub.z;
-                var ang_xSub = 0.0;
-                var ang_ySub = 0.0;
-                var ang_zSub = 0.0;
-                xSub = itemSub.fix_pos_x;
-                ySub = itemSub.fix_pos_y;
-                zSub = itemSub.fix_pos_z;
-                ang_xSub = itemSub.fix_angle_x;
-                ang_ySub = itemSub.fix_angle_y;
-                ang_zSub = itemSub.fix_angle_z;
-                var disTmp = Math.sqrt(Math.pow(x - xSub, 2) + Math.pow(y - ySub, 2) + Math.pow(z - zSub, 2))
-                if (disTmp < distance) {
-                  distance = disTmp;
-                  xSubTmp = xSub;
-                  ySubTmp = ySub;
-                  zSubTmp = zSub;
-                  ang_xSubTmp = ang_xSub;
-                  ang_ySubTmp = ang_ySub;
-                  ang_zSubTmp = ang_zSub;
-                }
+      // var fbxLoader3 = new THREE.GLTFLoader();
+      // fbxLoader3.setDRACOLoader(dracoLoader);
+
+      new DBUtil().get('../models/mesh3Draco.gltf',(progress) => {
+          console.log(progress)
+      }).then((blob) => {
+          console.log('getModel获取成功', blob);
+          var fbxLoader3 = new THREE.GLTFLoader();
+          fbxLoader3.setDRACOLoader(dracoLoader);
+          let url = URL.createObjectURL(new Blob([blob]));
+          fbxLoader3.load(url, function (gltf) {
+            console.log("================================================")
+            console.log(gltf)
+            let benchIdList = window.store.getters['benchList/getBenchList'].map(m => m.id);
+            let result = g_PosArrayResult;
+            for (var item of result) {
+              let x = item.x;
+              let y = item.y;
+              let z = item.z;
+              let ang_x = 0.0;
+              let ang_y = 0.0;
+              let ang_z = 0.0;
+              let benchType = item.bench_type
+              if (true) {
+                x = JSON.parse(JSON.stringify(item.fix_pos_x));
+                y = JSON.parse(JSON.stringify(item.fix_pos_y));
+                z = JSON.parse(JSON.stringify(item.fix_pos_z));
+                ang_x = JSON.parse(JSON.stringify(item.fix_angle_x));
+                ang_y = JSON.parse(JSON.stringify(item.fix_angle_y));
+                ang_z = JSON.parse(JSON.stringify(item.fix_angle_z));
               }
-            }
-
-
-            x = xSubTmp;
-            y = ySubTmp;
-            z = zSubTmp;
-            ang_x = ang_xSubTmp;
-            ang_y = ang_ySubTmp;
-            ang_z = ang_zSubTmp;
-            x = JSON.parse(JSON.stringify(xSubTmp));
-            y = JSON.parse(JSON.stringify(ySubTmp));
-            z = JSON.parse(JSON.stringify(zSubTmp));
-            ang_x = JSON.parse(JSON.stringify(ang_xSubTmp));
-            ang_y = JSON.parse(JSON.stringify(ang_ySubTmp));
-            ang_z = JSON.parse(JSON.stringify(ang_zSubTmp));
-
-            let card_id = item.card_id;
-            let bench_id = item.bench_id;
-            let bench_img = item.bench_img;
-            let show_remote_button = item.show_remote_button;
-            if (benchType == 3) {
-              console.log("控制台查看加载gltf文件返回的对象结构", fbx);
-              var childMesh = fbx.scene.children[0].children[0];
-              // var childMesh = fbx.scene.children[0];
-              let childMeshTmp = new THREE.Mesh(childMesh.geometry, childMesh.material)
-              let scale = 0.1;
-              childMeshTmp.scale.set(scale, scale, scale)
-              //fbx.scene.children[0].scale.set(5, 5, 5)
-              //fbx.scene.children[0].position.set(8.7, -1.6, 5.4)
-              childMeshTmp.position.set(x, y, z)
-              var Euler = new THREE.Euler(Math.PI * ang_x, Math.PI * ang_y, Math.PI * ang_z);
-              //var Euler = new THREE.Euler( Math.PI*1.5, Math.PI*0, Math.PI*0);
-              var quaternion = new THREE.Quaternion();
-              childMeshTmp.quaternion.copy(quaternion.setFromEuler(Euler))
-              var customData = {
-                benchId: bench_id,
-                benchFlag: true,
-                bShowRemoteButton: show_remote_button == 1 ? true : false,
-                benchImg: bench_img,
-              };
-              childMeshTmp.userData = customData;
-              if (benchIdList.indexOf(Number(bench_id)) > 0) {
-                if (!window.benchMeshMap[bench_id]) {
-                  window.benchMeshMap[bench_id] = childMeshTmp;
-                  sdkInstance.sceneRenderer.scene.add(childMeshTmp)
-                }
-                else {
-                  let deleteChildMesh = window.benchMeshMap[bench_id];
-                  sdkInstance.sceneRenderer.scene.remove(deleteChildMesh)
-                  deleteChildMesh.geometry.dispose(); // 清理几何体
-                  deleteChildMesh.material.dispose(); // 清理材质
-                  deleteChildMesh = null; // 置空指向该3D模型的变量
-                  window.benchMeshMap[bench_id] = childMeshTmp;
-                  sdkInstance.sceneRenderer.scene.add(childMeshTmp);
+              var distance = 10000.0;
+              var xSubTmp = x;
+              var ySubTmp = y;
+              var zSubTmp = z;
+              var ang_xSubTmp = ang_x;
+              var ang_ySubTmp = ang_y;
+              var ang_zSubTmp = ang_z;
+
+              if (g_PosArrayResult) {
+                var iCount = 0;
+                for (var itemSub of g_PosArrayResult) {
+                  iCount++;
+                  var xSub = itemSub.x;
+                  var ySub = itemSub.y;
+                  var zSub = itemSub.z;
+                  var ang_xSub = 0.0;
+                  var ang_ySub = 0.0;
+                  var ang_zSub = 0.0;
+                  xSub = itemSub.fix_pos_x;
+                  ySub = itemSub.fix_pos_y;
+                  zSub = itemSub.fix_pos_z;
+                  ang_xSub = itemSub.fix_angle_x;
+                  ang_ySub = itemSub.fix_angle_y;
+                  ang_zSub = itemSub.fix_angle_z;
+                  var disTmp = Math.sqrt(Math.pow(x - xSub, 2) + Math.pow(y - ySub, 2) + Math.pow(z - zSub, 2))
+                  if (disTmp < distance) {
+                    distance = disTmp;
+                    xSubTmp = xSub;
+                    ySubTmp = ySub;
+                    zSubTmp = zSub;
+                    ang_xSubTmp = ang_xSub;
+                    ang_ySubTmp = ang_ySub;
+                    ang_zSubTmp = ang_zSub;
+                  }
                 }
               }
+              x = xSubTmp;
+              y = ySubTmp;
+              z = zSubTmp;
+              ang_x = ang_xSubTmp;
+              ang_y = ang_ySubTmp;
+              ang_z = ang_zSubTmp;
+              x = JSON.parse(JSON.stringify(xSubTmp));
+              y = JSON.parse(JSON.stringify(ySubTmp));
+              z = JSON.parse(JSON.stringify(zSubTmp));
+              ang_x = JSON.parse(JSON.stringify(ang_xSubTmp));
+              ang_y = JSON.parse(JSON.stringify(ang_ySubTmp));
+              ang_z = JSON.parse(JSON.stringify(ang_zSubTmp));
+
+              let card_id = item.card_id;
+              let bench_id = item.bench_id;
+              let bench_img = item.bench_img;
+              let show_remote_button = item.show_remote_button;
+              if (benchType == 3) {
+                console.log("控制台查看加载gltf文件返回的对象结构", gltf);
+                var childMesh = gltf.scene.children[0].children[0];
+                // var childMesh = fbx.scene.children[0];
+                let childMeshTmp = new THREE.Mesh(childMesh.geometry, childMesh.material)
+                let scale = 0.1;
+                childMeshTmp.scale.set(scale, scale, scale)
+                childMeshTmp.position.set(x, y, z)
+                var Euler = new THREE.Euler(Math.PI * ang_x, Math.PI * ang_y, Math.PI * ang_z);
+                var quaternion = new THREE.Quaternion();
+                childMeshTmp.quaternion.copy(quaternion.setFromEuler(Euler))
+                var customData = {
+                  benchId: bench_id,
+                  benchFlag: true,
+                  bShowRemoteButton: show_remote_button == 1 ? true : false,
+                  benchImg: bench_img,
+                };
+                childMeshTmp.userData = customData;
+                if (benchIdList.indexOf(Number(bench_id)) > 0) {
+                  if (!window.benchMeshMap[bench_id]) {
+                    window.benchMeshMap[bench_id] = childMeshTmp;
+                    sdkInstance.sceneRenderer.scene.add(childMeshTmp)
+                  }
+                  else {
+                    let deleteChildMesh = window.benchMeshMap[bench_id];
+                    sdkInstance.sceneRenderer.scene.remove(deleteChildMesh)
+                    deleteChildMesh.geometry.dispose(); // 清理几何体
+                    deleteChildMesh.material.dispose(); // 清理材质
+                    deleteChildMesh = null; // 置空指向该3D模型的变量
+                    window.benchMeshMap[bench_id] = childMeshTmp;
+                    sdkInstance.sceneRenderer.scene.add(childMeshTmp);
+                  }
+                }
 
-            }
+              }
 
-          };
-        })
-      }
+            };
+            //   model.add(gltf.scene);
+          }, function ( xhr ) {
+              console.log( ( xhr.loaded / xhr.total * 100 ) + '% loaded' );
+          })
+      })
+
+      // if (!fbxLoader3Loaded) {
+      //   fbxLoader3.load("../models/mesh3Draco.gltf", function (fbx) {
+      //     console.log('1loadzmg211111111111111111111')
+      //     let benchIdList = window.store.getters['benchList/getBenchList'].map(m => m.id);
+      //     let result = g_PosArrayResult;
+      //     for (var item of result) {
+      //       let x = item.x;
+      //       let y = item.y;
+      //       let z = item.z;
+      //       let ang_x = 0.0;
+      //       let ang_y = 0.0;
+      //       let ang_z = 0.0;
+      //       let benchType = item.bench_type
+      //       if (true) {
+      //         x = JSON.parse(JSON.stringify(item.fix_pos_x));
+      //         y = JSON.parse(JSON.stringify(item.fix_pos_y));
+      //         z = JSON.parse(JSON.stringify(item.fix_pos_z));
+      //         ang_x = JSON.parse(JSON.stringify(item.fix_angle_x));
+      //         ang_y = JSON.parse(JSON.stringify(item.fix_angle_y));
+      //         ang_z = JSON.parse(JSON.stringify(item.fix_angle_z));
+      //       }
+      //       var distance = 10000.0;
+      //       var xSubTmp = x;
+      //       var ySubTmp = y;
+      //       var zSubTmp = z;
+      //       var ang_xSubTmp = ang_x;
+      //       var ang_ySubTmp = ang_y;
+      //       var ang_zSubTmp = ang_z;
+
+      //       if (g_PosArrayResult) {
+      //         var iCount = 0;
+      //         for (var itemSub of g_PosArrayResult) {
+      //           iCount++;
+      //           var xSub = itemSub.x;
+      //           var ySub = itemSub.y;
+      //           var zSub = itemSub.z;
+      //           var ang_xSub = 0.0;
+      //           var ang_ySub = 0.0;
+      //           var ang_zSub = 0.0;
+      //           xSub = itemSub.fix_pos_x;
+      //           ySub = itemSub.fix_pos_y;
+      //           zSub = itemSub.fix_pos_z;
+      //           ang_xSub = itemSub.fix_angle_x;
+      //           ang_ySub = itemSub.fix_angle_y;
+      //           ang_zSub = itemSub.fix_angle_z;
+      //           var disTmp = Math.sqrt(Math.pow(x - xSub, 2) + Math.pow(y - ySub, 2) + Math.pow(z - zSub, 2))
+      //           if (disTmp < distance) {
+      //             distance = disTmp;
+      //             xSubTmp = xSub;
+      //             ySubTmp = ySub;
+      //             zSubTmp = zSub;
+      //             ang_xSubTmp = ang_xSub;
+      //             ang_ySubTmp = ang_ySub;
+      //             ang_zSubTmp = ang_zSub;
+      //           }
+      //         }
+      //       }
+      //       x = xSubTmp;
+      //       y = ySubTmp;
+      //       z = zSubTmp;
+      //       ang_x = ang_xSubTmp;
+      //       ang_y = ang_ySubTmp;
+      //       ang_z = ang_zSubTmp;
+      //       x = JSON.parse(JSON.stringify(xSubTmp));
+      //       y = JSON.parse(JSON.stringify(ySubTmp));
+      //       z = JSON.parse(JSON.stringify(zSubTmp));
+      //       ang_x = JSON.parse(JSON.stringify(ang_xSubTmp));
+      //       ang_y = JSON.parse(JSON.stringify(ang_ySubTmp));
+      //       ang_z = JSON.parse(JSON.stringify(ang_zSubTmp));
+
+      //       let card_id = item.card_id;
+      //       let bench_id = item.bench_id;
+      //       let bench_img = item.bench_img;
+      //       let show_remote_button = item.show_remote_button;
+      //       if (benchType == 3) {
+      //         console.log("控制台查看加载gltf文件返回的对象结构", fbx);
+      //         var childMesh = fbx.scene.children[0].children[0];
+      //         // var childMesh = fbx.scene.children[0];
+      //         let childMeshTmp = new THREE.Mesh(childMesh.geometry, childMesh.material)
+      //         let scale = 0.1;
+      //         childMeshTmp.scale.set(scale, scale, scale)
+      //         //fbx.scene.children[0].scale.set(5, 5, 5)
+      //         //fbx.scene.children[0].position.set(8.7, -1.6, 5.4)
+      //         childMeshTmp.position.set(x, y, z)
+      //         var Euler = new THREE.Euler(Math.PI * ang_x, Math.PI * ang_y, Math.PI * ang_z);
+      //         //var Euler = new THREE.Euler( Math.PI*1.5, Math.PI*0, Math.PI*0);
+      //         var quaternion = new THREE.Quaternion();
+      //         childMeshTmp.quaternion.copy(quaternion.setFromEuler(Euler))
+      //         var customData = {
+      //           benchId: bench_id,
+      //           benchFlag: true,
+      //           bShowRemoteButton: show_remote_button == 1 ? true : false,
+      //           benchImg: bench_img,
+      //         };
+      //         childMeshTmp.userData = customData;
+      //         if (benchIdList.indexOf(Number(bench_id)) > 0) {
+      //           if (!window.benchMeshMap[bench_id]) {
+      //             window.benchMeshMap[bench_id] = childMeshTmp;
+      //             sdkInstance.sceneRenderer.scene.add(childMeshTmp)
+      //           }
+      //           else {
+      //             let deleteChildMesh = window.benchMeshMap[bench_id];
+      //             sdkInstance.sceneRenderer.scene.remove(deleteChildMesh)
+      //             deleteChildMesh.geometry.dispose(); // 清理几何体
+      //             deleteChildMesh.material.dispose(); // 清理材质
+      //             deleteChildMesh = null; // 置空指向该3D模型的变量
+      //             window.benchMeshMap[bench_id] = childMeshTmp;
+      //             sdkInstance.sceneRenderer.scene.add(childMeshTmp);
+      //           }
+      //         }
+
+      //       }
+
+      //     };
+      //   })
+      // }
     });
   }