zhouenguang 3 năm trước cách đây
mục cha
commit
2b980b9dfb
5 tập tin đã thay đổi với 132 bổ sung127 xóa
  1. 9 9
      src/XAnimationController.js
  2. 28 22
      src/XAvatarLoader.js
  3. 17 15
      src/XSceneManager.js
  4. 75 78
      src/XStateMachine.js
  5. 3 3
      src/main.js

+ 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()
             }
             )
         }

+ 3 - 3
src/main.js

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