gemercheung 3 years ago
parent
commit
4e30b63259
7 changed files with 357 additions and 361 deletions
  1. 147 136
      src/EngineProxy.js
  2. 9 9
      src/XAnimationController.js
  3. 28 22
      src/XAvatarLoader.js
  4. 17 15
      src/XSceneManager.js
  5. 75 78
      src/XStateMachine.js
  6. 4 3
      src/main.js
  7. 77 98
      src/开发笔记.txt

+ 147 - 136
src/EngineProxy.js

@@ -49,141 +49,36 @@ function getSceneManager(i, e) {
 
 export default class EngineProxy{
     constructor(xverseRoom) {
-        E(this, "_tvs", []);
-        E(this, "isRenderFirstFrame", !1);
-        E(this, "_idleTime", 0);
-        E(this, "renderTimer");
-        E(this, "lightManager");
-        E(this, "_checkSceneNotReadyCount", 0);
-        E(this, "_checkSceneDurationFrameNum", 0);
-        E(this, "_checkSceneFrameCount", 0);
-        E(this, "timeoutCircularArray", new CircularArray(120,!1,[]));
-        E(this, "frameCircularArray", new CircularArray(120,!1,[]));
-        E(this, "interFrameCircularArray", new CircularArray(120,!1,[]));
-        E(this, "drawCallCntCircularArray", new CircularArray(120,!1,[]));
-        E(this, "activeFacesCircularArray", new CircularArray(120,!1,[]));
-        E(this, "renderTimeCircularArray", new CircularArray(120,!1,[]));
-        E(this, "drawCallTimeCircularArray", new CircularArray(120,!1,[]));
-        E(this, "animationCircularArray", new CircularArray(120,!1,[]));
-        E(this, "meshSelectCircularArray", new CircularArray(120,!1,[]));
-        E(this, "renderTargetCircularArray", new CircularArray(120,!1,[]));
-        E(this, "regBeforeRenderCircularArray", new CircularArray(120,!1,[]));
-        E(this, "regAfterRenderCircularArray", new CircularArray(120,!1,[]));
-        E(this, "renderCnt", 0);
-        E(this, "renderErrorCount", 0);
-        E(this, "engineSloppyCnt", 0);
-        E(this, "systemStuckCnt", 0);
-        E(this, "frameRenderNumber", 0);
-        E(this, "_setFPS", (sceneManager,t=25)=>{
-            logger.info("Set fps to", t);
-            const r = t > 60 ? 60 : t < 24 ? 24 : t;
-            sceneManager.Engine.stopRenderLoop();
-            const n = 1e3 / r;
-            let o = Date.now()
-              , a = Date.now()
-              , s = n
-              , l = 1;
-            const u = ()=>{
-                var T;
-                const c = Date.now()
-                  , h = c - o
-                  , f = c - a;
-                a = c,
-                this.frameCircularArray.add(f),
-                h - s > n && (this.systemStuckCnt += 1);
-                const d = h / s;
-                l = .9 * l + .1 * d;
-                const _ = Date.now();
-                let g = 0
-                  , m = 0;
-                if (this.room.isUpdatedRawYUVData || this.room.isPano) {
-                    this.isRenderFirstFrame = !0
-                    if (this._checkSceneDurationFrameNum > 0)
-                    {
-                        this._checkSceneFrameCount++,
-                        this.room.sceneManager.isReadyToRender({}) && this._checkSceneDurationFrameNum--,
-                        this._checkSceneFrameCount > EngineProxy._CHECK_DURATION && (this._checkSceneDurationFrameNum = EngineProxy._CHECK_DURATION,
-                        this._checkSceneFrameCount = 0,
-                        this._checkSceneNotReadyCount++,
-                        (this._checkSceneNotReadyCount == 1 || this._checkSceneNotReadyCount % 100 == 0) && logger.error(`[SDK] Scene not ready, skip render. loop: ${this._checkSceneNotReadyCount}`),
-                        this._checkSceneNotReadyCount > 10 && (logger.error("[SDK] Scene not ready, reload later"),
-                        this.room.proxyEvents("renderError", {
-                            error: new Error("[SDK] Scene not ready, skip render and reload.")
-                        })),
-                        this.room.stats.assign({
-                            renderErrorCount: this._checkSceneNotReadyCount
-                        }),
-                        logger.infoAndReportMeasurement({
-                            value: 0,
-                            startTime: Date.now(),
-                            metric: "renderError",
-                            error: new Error("[SDK] Scene not ready, skip render and reload."),
-                            reportOptions: {
-                                sampleRate: .1
-                            }
-                        }));
-                    }
-                    else
-                    {
-                        try {
-                            sceneManager.render()
-                        } 
-                        catch (C) {
-                            this.renderErrorCount++,
-                            this.renderErrorCount > 10 && this.room.proxyEvents("renderError", {
-                                error: C
-                            }),
-                            this.room.stats.assign({
-                                renderErrorCount: this.renderErrorCount
-                            }),
-                            logger.infoAndReportMeasurement({
-                                value: 0,
-                                startTime: Date.now(),
-                                metric: "renderError",
-                                error: C,
-                                reportOptions: {
-                                    sampleRate: .1
-                                }
-                            })
-                        }
-                    }
-                    g = Date.now() - _,
-                    this.frameRenderNumber < 1e3 && this.frameRenderNumber++,
-                    this.room.networkController.rtcp.workers.UpdateYUV(),
-                    m = Date.now() - _ - g
-                }
-                this.isRenderFirstFrame || this.room.networkController.rtcp.workers.UpdateYUV();
-                const y = Date.now() - _;
-                o = c + y,
-                s = Math.min(Math.max((n - y) / l, 5), 200),
-                y > n && (s = 10,
-                this.engineSloppyCnt += 1),
-                this._idleTime = s;
-                const b = s;
-                if (s > 150 && console.log("lastGap is ", s, ", ratio is ", l, ", usedTimeMs is ", y, ", cpuRenderTime is ", g, ", cpuUpdateYUVTime is ", m),
-                this.timeoutCircularArray.add(b),
-                this.renderCnt % 25 == 0) {
-                    const C = this.frameCircularArray.getAvg()
-                      , A = this.timeoutCircularArray.getAvg()
-                      , S = this.frameCircularArray.getMax()
-                      , P = this.timeoutCircularArray.getMax();
-                    (T = this.room.stats) == null || T.assign({
-                        avgFrameTime: C,
-                        avgTimeoutTime: A,
-                        maxFrameTime: S,
-                        maxTimeoutTime: P,
-                        systemStuckCnt: this.systemStuckCnt
-                    })
-                }
-                this.renderTimer = window.setTimeout(u, s)
-            }
-            ;
-            this.renderTimer = window.setTimeout(u, n / l)
-        });
+        this._tvs = []
+        this.isRenderFirstFrame = !1
+        this._idleTime = 0
+        this.renderTimer
+        this.lightManager
+        this._checkSceneNotReadyCount = 0
+        this._checkSceneDurationFrameNum = 0
+        this._checkSceneFrameCount = 0
+        this.timeoutCircularArray = new CircularArray(120, !1, [])
+        this.frameCircularArray = new CircularArray(120, !1, [])
+        this.interFrameCircularArray = new CircularArray(120, !1, [])
+        this.drawCallCntCircularArray = new CircularArray(120, !1, [])
+        this.activeFacesCircularArray = new CircularArray(120, !1, [])
+        this.renderTimeCircularArray = new CircularArray(120, !1, [])
+        this.drawCallTimeCircularArray = new CircularArray(120, !1, [])
+        this.animationCircularArray = new CircularArray(120, !1, [])
+        this.meshSelectCircularArray = new CircularArray(120, !1, [])
+        this.renderTargetCircularArray = new CircularArray(120, !1, [])
+        this.regBeforeRenderCircularArray = new CircularArray(120, !1, [])
+        this.regAfterRenderCircularArray = new CircularArray(120, !1, [])
+        this.renderCnt = 0
+        this.renderErrorCount = 0
+        this.engineSloppyCnt = 0
+        this.systemStuckCnt = 0
+        this.frameRenderNumber = 0
 
-        E(this, "updateStats", ()=>{
-            var e;
-            (e = this.room.stats) == null || e.assign({
+        this.room = xverseRoom
+
+        this.updateStats = ()=>{
+            this.room.stats && this.room.stats.assign({
                 renderFrameTime: this.renderTimeCircularArray.getAvg(),
                 maxRenderFrameTime: this.renderTimeCircularArray.getMax(),
                 interFrameTime: this.interFrameCircularArray.getAvg(),
@@ -210,9 +105,125 @@ export default class EngineProxy{
                 maxTimeoutTime: this.timeoutCircularArray.getMax()
             })
         }
-        );
-        this.room = xverseRoom
     }
+
+    _setFPS(sceneManager, fps=25) {
+        logger.info("Set fps to", fps);
+        const protectFps = fps > 60 ? 60 : fps < 24 ? 24 : fps;
+        sceneManager.Engine.stopRenderLoop();
+        const mspf = 1e3 / protectFps; //毫秒每帧
+        let o = Date.now()
+            , a = Date.now()
+            , lastGap = mspf
+            , ratio = 1;
+
+        const updatePerGap = ()=>{
+            const c = Date.now()
+                , h = c - o
+                , f = c - a;
+
+            a = c
+            this.frameCircularArray.add(f)
+            h - lastGap > mspf && (this.systemStuckCnt += 1)
+
+            const d = h / lastGap;
+            ratio = .9 * ratio + .1 * d;
+            const _ = Date.now();
+            let cpuRenderTime = 0, cpuUpdateYUVTime = 0;
+            
+            if (this.room.isUpdatedRawYUVData || this.room.isPano) {
+                this.isRenderFirstFrame = !0
+                if (this._checkSceneDurationFrameNum > 0)
+                {
+                    this._checkSceneFrameCount++,
+                    this.room.sceneManager.isReadyToRender({}) && this._checkSceneDurationFrameNum--,
+                    this._checkSceneFrameCount > EngineProxy._CHECK_DURATION && (this._checkSceneDurationFrameNum = EngineProxy._CHECK_DURATION,
+                    this._checkSceneFrameCount = 0,
+                    this._checkSceneNotReadyCount++,
+
+                    (
+                        this._checkSceneNotReadyCount == 1 || 
+                        this._checkSceneNotReadyCount % 100 == 0
+                    ) && logger.error(`[SDK] Scene not ready, skip render. loop: ${this._checkSceneNotReadyCount}`),
+
+                    this._checkSceneNotReadyCount > 10 && (
+                        logger.error("[SDK] Scene not ready, reload later"),
+                        this.room.proxyEvents("renderError", {
+                            error: new Error("[SDK] Scene not ready, skip render and reload.")
+                        })
+                    ),
+                    this.room.stats.assign({
+                        renderErrorCount: this._checkSceneNotReadyCount
+                    }),
+                    logger.infoAndReportMeasurement({
+                        value: 0,
+                        startTime: Date.now(),
+                        metric: "renderError",
+                        error: new Error("[SDK] Scene not ready, skip render and reload."),
+                        reportOptions: {
+                            sampleRate: .1
+                        }
+                    }));
+                } else {
+                    try {
+                        sceneManager.render()
+                    } 
+                    catch (e) {
+                        this.renderErrorCount++,
+                        this.renderErrorCount > 10 && this.room.proxyEvents("renderError", {
+                            error: e
+                        }),
+                        this.room.stats.assign({
+                            renderErrorCount: this.renderErrorCount
+                        }),
+                        logger.infoAndReportMeasurement({
+                            value: 0,
+                            startTime: Date.now(),
+                            metric: "renderError",
+                            error: e,
+                            reportOptions: {
+                                sampleRate: .1
+                            }
+                        })
+                    }
+                }
+                cpuRenderTime = Date.now() - _,
+                this.frameRenderNumber < 1e3 && this.frameRenderNumber++,
+                this.room.networkController.rtcp.workers.UpdateYUV(),
+                cpuUpdateYUVTime = Date.now() - _ - cpuRenderTime
+            }
+            
+            this.isRenderFirstFrame || this.room.networkController.rtcp.workers.UpdateYUV();
+
+            const usedTimeMs = Date.now() - _;
+            o = c + usedTimeMs,
+            lastGap = Math.min(Math.max((mspf - usedTimeMs) / ratio, 5), 200),
+            usedTimeMs > mspf && (
+                lastGap = 10,
+                this.engineSloppyCnt += 1
+            ),
+            this._idleTime = lastGap;
+
+            lastGap > 150 && console.log("lastGap is ", lastGap, ", ratio is ", ratio, ", usedTimeMs is ", usedTimeMs, 
+                ", cpuRenderTime is ", cpuRenderTime, ", cpuUpdateYUVTime is ", cpuUpdateYUVTime)
+
+            const b = lastGap;
+            this.timeoutCircularArray.add(b)
+            
+            if (this.renderCnt % 25 == 0) {
+                this.room.stats && this.room.stats.assign({
+                    avgFrameTime: this.frameCircularArray.getAvg(),
+                    avgTimeoutTime: this.frameCircularArray.getMax(),
+                    maxFrameTime: this.frameCircularArray.getMax(),
+                    maxTimeoutTime: this.timeoutCircularArray.getMax(),
+                    systemStuckCnt: this.systemStuckCnt
+                })
+            }
+            this.renderTimer = window.setTimeout(updatePerGap, lastGap)
+        }
+        this.renderTimer = window.setTimeout(updatePerGap, mspf / ratio)
+    }
+
     async initEngine(e) {
         await this.updateBillboard();
         logger.info("engine version:", VERSION$1);

+ 9 - 9
src/XAnimationController.js

@@ -25,13 +25,13 @@ export default class XAnimationController {
         this._boneMap = new Map
     }
     
-    // s: :0 身体动画 :1 脸部动画
-    playAnimation = (animationName, isLoop, s=0, c, d, _)=>new Promise((resolve, reject)=>{
+    // aniType :0 身体动画 :1 脸部动画
+    playAnimation = (animationName, isLoop, aniType=0, c, d, _)=>new Promise((resolve, reject)=>{
         // zeg 传入i为任意动画名即可播放该动画,比如"GiftClap"
         // window.room.avatarManager.avatars.get(window.room.userId).playAnimation({"animationName": "GiftClap", "loop":true})
         if (
-            this._isPlaying(animationName, s) || 
-            (this._registerAnimInfo(animationName, isLoop, s, c, d, _), !this._isAnimate())
+            this._isPlaying(animationName, aniType) || 
+            (this._registerAnimInfo(animationName, isLoop, aniType, c, d, _), !this._isAnimate())
         ) 
         return resolve(null);
 
@@ -47,16 +47,16 @@ export default class XAnimationController {
                 return skeleton.dispose(),
                 reject(new AvatarAnimationError("mapping animation failed"));
 
-            this.enableSkLod && this.skeletonMask(skeleton, s)
-            this.detachAnimation(s)
-            s == 0 ? this.iBodyAnim.animGroup = skeleton : s == 1 && (this.iFaceAnim.animGroup = skeleton)
+            this.enableSkLod && this.skeletonMask(skeleton, aniType)
+            this.detachAnimation(aniType)
+            aniType == 0 ? this.iBodyAnim.animGroup = skeleton : aniType == 1 && (this.iFaceAnim.animGroup = skeleton)
 
-            if (!this._playAnimation(s)) 
+            if (!this._playAnimation(aniType)) 
             return reject(new AvatarAnimationError("[Engine] play animation failed, animtion resource does not match current character"));
             
             this._playEffect(),
             this.postObserver = skeleton.onAnimationEndObservable.addOnce(()=>(
-                this._postprocess(s),
+                this._postprocess(aniType),
                 resolve(null)
             ))
         })

+ 28 - 22
src/XAvatarLoader.js

@@ -227,47 +227,53 @@ export default class XAvatarLoader {
     _loadGltfFromUrl(e, i, o) {
         return BABYLON.SceneLoader.LoadAssetContainerAsync(o, i + ".gltf", e.Scene, null, ".gltf")
     }
-    _loadGlbFromBlob(e, i, o) {
-        return e.urlTransformer(o).then(s=>BABYLON.SceneLoader.LoadAssetContainerAsync("", s, e.Scene, null, ".glb").then(c=>{
-            if (c) {
-                if (this.containers.get(o))
-                    return c.dispose(),
-                    this.containers.get(o);
-                if (c.addAllToScene(),
-                this.enableShareTexture && c.textures.length > 0) {
+    _loadGlbFromBlob(sceneManager, i, aniModelPath) {
+        return sceneManager.urlTransformer(aniModelPath)
+        .then(path=>BABYLON.SceneLoader.LoadAssetContainerAsync("", path, sceneManager.Scene, null, ".glb")
+        .then(model => {
+            if (model) {
+                if (this.containers.get(aniModelPath))
+                    return model.dispose(),
+                    this.containers.get(aniModelPath);
+                if (model.addAllToScene(),
+                this.enableShareTexture && model.textures.length > 0) {
                     const d = [];
                     let _ = !1;
-                    c.meshes.forEach(b=>{
+                    model.meshes.forEach(b=>{
                         if (b.material) {
                             const k = b.material._albedoTexture;
                             if (k) {
                                 let j = k.name;
                                 j = j.replace(" (Base Color)", "").split(".")[0];
                                 const $ = this._sharedTex.get(j);
-                                $ ? (_ = !0,
-                                b.material._albedoTexture = $,
-                                d.push($),
-                                $._parentContainer = c,
-                                $.xReferenceCount++) : (this._sharedTex.set(j, k),
-                                c.textures[0].xReferenceCount = 1)
+                                $ ? (
+                                    _ = !0,
+                                    b.material._albedoTexture = $,
+                                    d.push($),
+                                    $._parentContainer = model,
+                                    $.xReferenceCount++
+                                ) : (
+                                    this._sharedTex.set(j, k),
+                                    model.textures[0].xReferenceCount = 1
+                                )
                             }
                         }
                     }
                     ),
-                    _ && (c.textures.forEach(b=>{
-                        e.Scene.removeTexture(b),
+                    _ && (model.textures.forEach(b=>{
+                        sceneManager.Scene.removeTexture(b),
                         b.dispose()
                     }
                     ),
-                    c.textures = d)
+                    model.textures = d)
                 }
-                return c.xReferenceCount = 0,
-                c.meshes.forEach(d=>{
+                return model.xReferenceCount = 0,
+                model.meshes.forEach(d=>{
                     d.setEnabled(!1)
                 }
                 ),
-                this.containers.set(o, c),
-                Promise.resolve(c)
+                this.containers.set(aniModelPath, model),
+                Promise.resolve(model)
             } else
                 return Promise.reject("glb file load failed")
         }

+ 17 - 15
src/XSceneManager.js

@@ -31,7 +31,7 @@ const getAlphaWidthMap = (i,e)=>{
 }
 
 export default class XSceneManager {
-    constructor(canvas, t) {
+    constructor(canvas, options) {
         this.cameraParam
         this.shaderMode
         this.panoInfo
@@ -48,7 +48,7 @@ export default class XSceneManager {
         this.engine = new BABYLON.Engine(canvas, !0, {
             preserveDrawingBuffer: !0,
             stencil: !0,
-            disableWebGL2Support: /iphone|ipad/gi.test(window.navigator.userAgent) || t.disableWebGL2
+            disableWebGL2Support: /iphone|ipad/gi.test(window.navigator.userAgent) || options.disableWebGL2
         }, !0),
         this.scene = new BABYLON.Scene(this.engine),
         this.canvas = canvas,
@@ -61,8 +61,8 @@ export default class XSceneManager {
         this.scene.cleanCachedTextureBuffer(),
         // this.scene.debugLayer.show({ embedMode: true, }),    // BABYLON调试工具栏
 
-        this.urlTransformer = t.urlTransformer || (s=>Promise.resolve(s)),
-        t.logger && defaultLog.setLogger(t.logger),
+        this.urlTransformer = options.urlTransformer || (s=>Promise.resolve(s)),
+        options.logger && defaultLog.setLogger(options.logger),
 
         this.gl = canvas.getContext("webgl2", { preserveDrawingBuffer: !0 }) 
         || canvas.getContext("webgl", { preserveDrawingBuffer: !0 }) 
@@ -70,16 +70,16 @@ export default class XSceneManager {
         this.gl.pixelStorei(this.gl.UNPACK_ALIGNMENT, 1),
 
         this._currentPanoId = 0,
-        t.forceKeepVertical && (this._forceKeepVertical = t.forceKeepVertical),
-        t.panoInfo && (this.panoInfo = t.panoInfo),
-        t.shaderMode && (this.shaderMode = t.shaderMode),
-        t.yuvInfo ? this._yuvInfo = t.yuvInfo : this._yuvInfo = {
-            width: t.videoResOriArray[0].width,
-            height: t.videoResOriArray[0].height,
+        options.forceKeepVertical && (this._forceKeepVertical = options.forceKeepVertical),
+        options.panoInfo && (this.panoInfo = options.panoInfo),
+        options.shaderMode && (this.shaderMode = options.shaderMode),
+        options.yuvInfo ? this._yuvInfo = options.yuvInfo : this._yuvInfo = {
+            width: options.videoResOriArray[0].width,
+            height: options.videoResOriArray[0].height,
             fov: 50
         },
-        t.cameraParam && (this.cameraParam = t.cameraParam),
-        t.nonlinearCanvasResize && (this._nonlinearCanvasResize = t.nonlinearCanvasResize),
+        options.cameraParam && (this.cameraParam = options.cameraParam),
+        options.nonlinearCanvasResize && (this._nonlinearCanvasResize = options.nonlinearCanvasResize),
 
         this._cameraManager = new XCameraComponent(this.canvas,this.scene,{
             cameraParam: this.cameraParam,
@@ -88,7 +88,7 @@ export default class XSceneManager {
         }),
         this._lowpolyManager = new XStaticMeshComponent(this),
         this._materialManager = new XMaterialComponent(this,{
-            videoResOriArray: t.videoResOriArray,
+            videoResOriArray: options.videoResOriArray,
             yuvInfo: this._yuvInfo,
             panoInfo: this.panoInfo,
             shaderMode: this.shaderMode
@@ -420,16 +420,18 @@ export default class XSceneManager {
     setIBL(e) {
         this._lightManager.setIBL(e)
     }
+    // 后处理bloom
     postprocessing() {
         const e = new BABYLON.DefaultRenderingPipeline("default",!0,this.scene);
         e.imageProcessingEnabled = !1,
-        e.bloomEnabled = !0,
+        // e.bloomEnabled = !0,
         e.bloomThreshold = 1,
         e.bloomWeight = 1,
         e.bloomKernel = 64,
         e.bloomScale = .1
     }
-    getGround(e) {
+    // 查询name中包含SM_Stage和以ground开头的meshes
+    getGround() {
         const t = this._lowpolyManager.getMeshes()
           , r = [];
         return t.forEach(n=>{

+ 75 - 78
src/XStateMachine.js

@@ -2,45 +2,39 @@ import Logger from "./Logger.js"
 
 const logger = new Logger('XStateMachine')
 export default class XStateMachine {
-    constructor(e) {
-        E(this, "state");
-        E(this, "isMoving");
-        E(this, "isRotating");
-        E(this, "_observer");
-        E(this, "_movingObserver");
-        E(this, "_scene");
-        this._scene = e
+    constructor(scene) {
+        this.state
+        this.isMoving
+        this.isRotating
+        this._observer
+        this._movingObserver
+        this._scene = scene
     }
-    rotateTo(e, t, r, n) {
-        return new Promise((o,a)=>{
-            var h;
-            const s = e.avatarManager.scene;
-            if (r && e.setRotation(r),
-            t == r)
-                return o();
-            e.priority === 0 && logger.info(`avatar ${e.id} starts to rotate from ${r} to ${t}`);
-            let l = 0;
+    rotateTo(avatar, t, r, aniName) {
+        return new Promise((resolve, reject)=>{
+            const scene = avatar.avatarManager.scene;
+            if (r && avatar.setRotation(r), t == r) return resolve();
+
+            avatar.priority === 0 && logger.info(`avatar ${avatar.id} starts to rotate from ${r} to ${t}`);
+
+            let lerpRatio = 0;
             const u = 1e3 / 25
-              , c = calcDistance3DAngle(t, e.rotation) / u;
-            this._movingObserver && s.onBeforeRenderObservable.remove(this._movingObserver),
-            (h = e.controller) == null || h.playAnimation(n || "Walking", !0),
-            this._movingObserver = s == null ? void 0 : s.onBeforeRenderObservable.add(()=>{
-                var f;
-                if (l < 1) {
-                    if (!e.rootNode)
-                        return e.setRotation(t),
-                        o();
-                    const d = BABYLON.Vector3.Lerp(e.rootNode.rotation, ue4Rotation2Xverse(t), l);
-                    e.setRotation(xverseRotation2Ue4(d)),
-                    l += u / (c * 1e3)
+              , c = calcDistance3DAngle(t, avatar.rotation) / u;
+
+            this._movingObserver && scene.onBeforeRenderObservable.remove(this._movingObserver),
+            avatar.controller && avatar.controller.playAnimation(aniName || "Walking", !0),
+            this._movingObserver = scene && scene.onBeforeRenderObservable.add(()=>{
+                if (lerpRatio < 1) {
+                    if (!avatar.rootNode) return avatar.setRotation(t), resolve();
+                    const d = BABYLON.Vector3.Lerp(avatar.rootNode.rotation, ue4Rotation2Xverse(t), lerpRatio);
+                    avatar.setRotation(xverseRotation2Ue4(d)),
+                    lerpRatio += u / (c * 1e3)
                 } else
-                    return s.onBeforeRenderObservable.remove(this._movingObserver),
-                    (f = e.controller) == null || f.playAnimation("Idle", !0),
-                    o()
-            }
-            )
-        }
-        )
+                    return scene.onBeforeRenderObservable.remove(this._movingObserver),
+                    avatar.controller && avatar.controller.playAnimation("Idle", !0),
+                    resolve()
+            })
+        })
     }
     _filterPathPoint(e) {
         let t = 0;
@@ -51,58 +45,61 @@ export default class XStateMachine {
             calcDistance3D(e[t], e[t + 1]) < r ? e.splice(t, 1) : t++;
         return e
     }
-    moveTo(e, t, r, n, o, a) {
-        return new Promise((s,l)=>{
-            var m;
-            const u = e.avatarManager.scene;
-            e.priority === 0 && logger.info(`avatar ${e.id} starts to move from ${t} to ${r}`);
-            let c = 0;
+    moveTo(avatar, t, r, n, aniName, a) {
+        return new Promise((resolve, reject)=>{
+            const scene = avatar.avatarManager.scene;
+            avatar.priority === 0 && logger.info(`avatar ${avatar.id} starts to move from ${t} to ${r}`);
+
+            let lerpRatio = 0;
             a ? a = a.concat(r) : a = [r],
             a = this._filterPathPoint(a);
             let h = t
               , f = a.shift();
-            if (!f)
-                return l("[Engine input path error]");
+            if (!f) return reject("[Engine input path error]");
             let d = calcDistance3D(h, f) / n;
             const _ = 1e3 / 25;
-            e.rootNode.lookAt(ue4Position2Xverse(f));
-            const g = xverseRotation2Ue4({
-                x: e.rootNode.rotation.x,
-                y: e.rootNode.rotation.y,
-                z: e.rootNode.rotation.z
+            avatar.rootNode.lookAt(ue4Position2Xverse(f));
+
+            const rotationUE4 = xverseRotation2Ue4({
+                x: avatar.rootNode.rotation.x,
+                y: avatar.rootNode.rotation.y,
+                z: avatar.rootNode.rotation.z
             });
-            g && (g.roll = 0,
-            g.pitch = 0,
-            e.setRotation(g)),
-            this._movingObserver && u.onBeforeRenderObservable.remove(this._movingObserver),
-            (m = e.controller) == null || m.playAnimation(o, !0),
-            this._movingObserver = u == null ? void 0 : u.onBeforeRenderObservable.add(()=>{
-                var v;
-                if (c < 1) {
-                    const y = BABYLON.Vector3.Lerp(ue4Position2Xverse(h), ue4Position2Xverse(f), c);
-                    if (e.setPosition(xversePosition2Ue4(y)),
-                    !e.rootNode)
-                        return e.setPosition(r),
-                        s();
-                    c += _ / (d * 1e3)
-                } else if (h = f,
-                f = a.shift(),
-                f) {
+            rotationUE4 && (
+                rotationUE4.roll = 0,
+                rotationUE4.pitch = 0,
+                avatar.setRotation(rotationUE4)
+            ),
+
+            this._movingObserver && scene.onBeforeRenderObservable.remove(this._movingObserver),
+            avatar.controller && avatar.controller.playAnimation(aniName, !0),
+            this._movingObserver = scene && scene.onBeforeRenderObservable.add(()=>{
+                if (lerpRatio < 1) 
+                {
+                    const y = BABYLON.Vector3.Lerp(ue4Position2Xverse(h), ue4Position2Xverse(f), lerpRatio);
+                    if (avatar.setPosition(xversePosition2Ue4(y)), !avatar.rootNode)
+                        return avatar.setPosition(r),
+                        resolve();
+                    lerpRatio += _ / (d * 1e3)
+                } else if (h = f, f = a.shift(), f) 
+                {
                     d = calcDistance3D(h, f) / n,
-                    e.rootNode.lookAt(ue4Position2Xverse(f));
-                    const y = xverseRotation2Ue4({
-                        x: e.rootNode.rotation.x,
-                        y: e.rootNode.rotation.y,
-                        z: e.rootNode.rotation.z
+                    avatar.rootNode.lookAt(ue4Position2Xverse(f));
+                    const rotationUE4 = xverseRotation2Ue4({
+                        x: avatar.rootNode.rotation.x,
+                        y: avatar.rootNode.rotation.y,
+                        z: avatar.rootNode.rotation.z
                     });
-                    y && (y.roll = 0,
-                    y.pitch = 0,
-                    e.setRotation(y)),
-                    c = 0
+                    rotationUE4 && (
+                        rotationUE4.roll = 0,
+                        rotationUE4.pitch = 0,
+                        avatar.setRotation(rotationUE4)
+                    ),
+                    lerpRatio = 0
                 } else
-                    return u.onBeforeRenderObservable.remove(this._movingObserver),
-                    (v = e.controller) == null || v.playAnimation("Idle", !0),
-                    s()
+                    return scene.onBeforeRenderObservable.remove(this._movingObserver),
+                    avatar.controller && avatar.controller.playAnimation("Idle", !0),
+                    resolve()
             }
             )
         }

+ 4 - 3
src/main.js

@@ -27,7 +27,7 @@ const l = async()=>{
     }
     let nickname = Math.random().toString(16).slice(2)
     try {
-
+ 
         let room = await xverse.joinRoom({
             canvas: document.getElementById('canvas'),
             skinId: '10089',
@@ -35,8 +35,9 @@ const l = async()=>{
             roomId: 'e629ef3e-022d-4e64-8654-703bb96410eb',
             userId: nickname,
             // wsServerUrl: 'wss://uat-eks.xverse.cn/ws',
-            wsServerUrl: "ws://localhost:6688/ws",
-            // wsServerUrl: "wss://meta-socket.4dage.com/ws",
+            // wsServerUrl: "ws://localhost:6688/ws",
+            wsServerUrl: "wss://meta-socket.4dage.com/ws",
+
             appId: "10016",
             token: " ",
             nickname: nickname,

+ 77 - 98
src/开发笔记.txt

@@ -1,110 +1,89 @@
 1. Logger不能用单例模式,里面的module对应的是类的名称
 2. BABYLON源码修改:
 
-          this._onBeforeRegisterBeforeRenderObserver = null,
-                this._onAfterRegisterBeforeRenderObserver = null,
-                this._RTT1Time = new Rr.a,
-                this._onBeforeRTT1Observer = null,
-                this._onAfterRTT1Observer = null,
-                this._registerAfterRenderTime = new Rr.a,
-                this._onBeforeRegisterAfterRenderObserver = null,
-                this._onAfterRegisterAfterRenderObserver = null,
-				
-				
-				
-				
-				
-				  this._onBeforeRegisterBeforeRenderObserver = e.onBeforeRunRegisterBeforeRenderObservable.add(function() {
-                    t._registerBeforeRenderTime.beginMonitoring()
-                }),
-                this._onAfterRegisterBeforeRenderObserver = e.onAfterRunRegisterBeforeRenderObservable.add(function() {
-                    t._registerBeforeRenderTime.endMonitoring()
-                }),
-                this._onBeforeRegisterAfterRenderObserver = e.onBeforeRunRegisterAfterRenderObservable.add(function() {
-                    t._registerAfterRenderTime.beginMonitoring()
-                }),
-                this._onAfterRegisterAfterRenderObserver = e.onAfterRunRegisterAfterRenderObservable.add(function() {
-                    t._registerAfterRenderTime.endMonitoring()
-                }),
-                this._onBeforeRTT1Observer = e.onBeforeRTT1Observable.add(function() {
-                    t._RTT1Time.beginMonitoring()
-                }),
-                this._onAfterRTT1Observer = e.onAfterRTT1Observable.add(function() {
-                    t._RTT1Time.endMonitoring()
-                })
-				
-				
-				
-				
-				
-				
-				
-				
-				 Object.defineProperty(e.prototype, "registerBeforeTimeCounter", {
-                get: function() {
-                    return this._registerBeforeRenderTime
-                },
-                enumerable: !1,
-                configurable: !0
-            }),
-            Object.defineProperty(e.prototype, "getRTT1TimeCounter", {
-                get: function() {
-                    return this._RTT1Time
-                },
-                enumerable: !1,
-                configurable: !0
-            }),
-            Object.defineProperty(e.prototype, "registerAfterTimeCounter", {
-                get: function() {
-                    return this._registerAfterRenderTime
-                },
-                enumerable: !1,
-                configurable: !0
-            }),
-			
-			
-			
-			
-			
-			
-			
-			        r.onBeforeRunRegisterBeforeRenderObservable = new Observable,
+        this._onBeforeRegisterBeforeRenderObserver = null,
+        this._onAfterRegisterBeforeRenderObserver = null,
+        this._RTT1Time = new Rr.a,
+        this._onBeforeRTT1Observer = null,
+        this._onAfterRTT1Observer = null,
+        this._registerAfterRenderTime = new Rr.a,
+        this._onBeforeRegisterAfterRenderObserver = null,
+        this._onAfterRegisterAfterRenderObserver = null,
+        
+
+        Object.defineProperty(e.prototype, "registerBeforeTimeCounter", {
+            get: function() {
+                return this._registerBeforeRenderTime
+            },
+            enumerable: !1,
+            configurable: !0
+        }),
+        Object.defineProperty(e.prototype, "getRTT1TimeCounter", {
+            get: function() {
+                return this._RTT1Time
+            },
+            enumerable: !1,
+            configurable: !0
+        }),
+        Object.defineProperty(e.prototype, "registerAfterTimeCounter", {
+            get: function() {
+                return this._registerAfterRenderTime
+            },
+            enumerable: !1,
+            configurable: !0
+        }),
+
+
+		r.onBeforeRunRegisterBeforeRenderObservable = new Observable,
         r.onAfterRunRegisterBeforeRenderObservable = new Observable,
         r.onBeforeRunRegisterAfterRenderObservable = new Observable,
         r.onAfterRunRegisterAfterRenderObservable = new Observable,
         r.onBeforeRTT1Observable = new Observable,
         r.onAfterRTT1Observable = new Observable,
 		
-		
-		
-		
-		
-		                    this.onBeforeRunRegisterBeforeRenderObservable.notifyObservers(this),
-                    this.onBeforeRenderObservable.notifyObservers(this),
-                    this.onAfterRunRegisterBeforeRenderObservable.notifyObservers(this),
-					
-					
-					
-					
-					
-					
-					
-					
-					                    this.onBeforeRunRegisterBeforeRenderObservable.clear(),
-                    this.onAfterRunRegisterBeforeRenderObservable.clear(),
-                    this.onBeforeRTT1Observable.clear(),
-                    this.onAfterRTT1Observable.clear(),
-                    this.onBeforeRunRegisterAfterRenderObservable.clear(),
-                    this.onAfterRunRegisterAfterRenderObservable.clear()
-					
-					
-					
-					
-					
-					
-					
-					
-					        this.scene.onBeforeRunRegisterBeforeRenderObservable.remove(this._onBeforeRegisterBeforeRenderObserver),
+
+
+
+
+
+        this._onBeforeRegisterBeforeRenderObserver = e.onBeforeRunRegisterBeforeRenderObservable.add(function() {
+            t._registerBeforeRenderTime.beginMonitoring()
+        }),
+        this._onAfterRegisterBeforeRenderObserver = e.onAfterRunRegisterBeforeRenderObservable.add(function() {
+            t._registerBeforeRenderTime.endMonitoring()
+        }),
+        this._onBeforeRegisterAfterRenderObserver = e.onBeforeRunRegisterAfterRenderObservable.add(function() {
+            t._registerAfterRenderTime.beginMonitoring()
+        }),
+        this._onAfterRegisterAfterRenderObserver = e.onAfterRunRegisterAfterRenderObservable.add(function() {
+            t._registerAfterRenderTime.endMonitoring()
+        }),
+        this._onBeforeRTT1Observer = e.onBeforeRTT1Observable.add(function() {
+            t._RTT1Time.beginMonitoring()
+        }),
+        this._onAfterRTT1Observer = e.onAfterRTT1Observable.add(function() {
+            t._RTT1Time.endMonitoring()
+        })
+
+
+        this.onBeforeRunRegisterBeforeRenderObservable.notifyObservers(this),
+        this.onBeforeRenderObservable.notifyObservers(this),
+        this.onAfterRunRegisterBeforeRenderObservable.notifyObservers(this),
+
+
+
+
+
+
+
+        this.onBeforeRunRegisterBeforeRenderObservable.clear(),
+        this.onAfterRunRegisterBeforeRenderObservable.clear(),
+        this.onBeforeRTT1Observable.clear(),
+        this.onAfterRTT1Observable.clear(),
+        this.onBeforeRunRegisterAfterRenderObservable.clear(),
+        this.onAfterRunRegisterAfterRenderObservable.clear()
+
+		this.scene.onBeforeRunRegisterBeforeRenderObservable.remove(this._onBeforeRegisterBeforeRenderObserver),
         this._onBeforeRegisterBeforeRenderObserver = null,
         this.scene.onAfterRunRegisterBeforeRenderObservable.remove(this._onAfterRegisterBeforeRenderObserver),
         this._onAfterRegisterBeforeRenderObserver = null,