فهرست منبع

Merge branch 'newWebRtc' of http://192.168.0.115:3000/xushiting/Metaverse into newWebRtc

# Conflicts:
#	src/XMaterialComponent.js
xushiting 3 سال پیش
والد
کامیت
a79491d399
6فایلهای تغییر یافته به همراه638 افزوده شده و 529 حذف شده
  1. 3 3
      src/Signal.js
  2. 150 103
      src/XAvatar.js
  3. 90 101
      src/XAvatarManager.js
  4. 94 83
      src/XMaterialComponent.js
  5. 189 145
      src/XverseAvatar.js
  6. 112 94
      src/Xverse_Room.js

+ 3 - 3
src/Signal.js

@@ -38,11 +38,11 @@ export default class Signal {
         }
     }
     
-    handleSignal(updateData, i) {
+    handleSignal(data, reject) {
         if (!this.signalHandleActived) return;
 
         const time1 = Date.now()
-        const { signal, alreadyUpdateYUV } = updateData;
+        const { signal, alreadyUpdateYUV } = data;
         this.handleActionResponses(signal), this._room.handleSignalHook(signal);
 
         const time2 = Date.now();
@@ -92,7 +92,7 @@ export default class Signal {
                 if (!this._room.joined) {
                     const CodeError = getErrorByCode(signal.code),
                         error = new CodeError(signal.msg);
-                    i(error)
+                    reject(error)
                 }
                 logger.error("signal errcode: ", signal);
                 this._room.emit("error", signal);

+ 150 - 103
src/XAvatar.js

@@ -11,7 +11,7 @@ const castRayOffsetY = .01;
 const castRayTeleportationOffset = 10;
 
 export default class XAvatar {
-    constructor({id: e, avatarType: i, priority: o, avatarManager: s, assets: c, status: d}) {
+    constructor({id, avatarType, priority, avatarManager, assets, status}) {
         this.id = "-1",
         this.priority = 0,
         this.isRender = !1,
@@ -31,171 +31,202 @@ export default class XAvatar {
         this.isInLoadingQueue = !1,
         this._scene = void 0,
         this._transparent = 0,
-        this.hide = ()=>(this.isHide = !0,
-        this._hide(),
-        !this.isRender),
+
+        this.hide = ()=>{
+            this.isHide = !0
+            this._hide()
+            return !this.isRender
+        },
+
         this._show = ()=>{
-            var _;
-            this.isHide || (this.setIsPickable(!0),
-            this.bbComponent._attachmentObservers.forEach((b,k)=>{
-                k.setEnabled(!0)
-            }
-            ),
-            this.priority == 0 && (this.rootNode.setEnabled(!0),
-            this.isRender = !0,
-            this.avatarManager._updateBillboardStatus(this, BillboardStatus.SHOW),
-            this.component.accessories.forEach(b=>{
-                b.rootComponent.setEnabled(!0)
-            }
-            ),
-            (_ = this.controller) == null || _.playAnimation(this.controller.onPlay, this.controller.loop)),
-            this.component.accessories.forEach(b=>{
-                b.rootComponent.setEnabled(!0)
-            }
-            ))
-        }
-        ,
-        this.show = ()=>(this.isHide = !1,
-        this._show(),
-        !!this.isRender),
+            this.isHide || (
+                this.setIsPickable(!0),
+                this.bbComponent._attachmentObservers.forEach((b,k)=>{
+                    k.setEnabled(!0)
+                }),
+                this.priority == 0 && (
+                    this.rootNode.setEnabled(!0),
+                    this.isRender = !0,
+                    this.avatarManager._updateBillboardStatus(this, BillboardStatus.SHOW),
+                    this.component.accessories.forEach(b=>{
+                        b.rootComponent.setEnabled(!0)
+                    }),
+                    this.controller == null || this.controller.playAnimation(this.controller.onPlay, this.controller.loop)
+                ),
+                this.component.accessories.forEach(b=>{
+                    b.rootComponent.setEnabled(!0)
+                })
+            )
+        },
+
+        this.show = ()=>{
+            this.isHide = !1
+            this._show()
+            return !!this.isRender
+        },
+
         this.setAnimations = _=>{
             this.controller.animations = _
-        }
-        ,
-        this.attachToAvatar = (_,b=!1,k={
-            x: 0,
-            y: 0,
-            z: 0
-        },j=!1,$,_e)=>this.bbComponent.attachToAvatar(this, _, b, k, j, _e),
-        this.detachFromAvatar = (_,b=!1)=>this.bbComponent.detachFromAvatar(this, _, b),
-        this.getBbox = (_={})=>this.bbComponent.getBbox(this, _),
-        this.id = e,
-        this._avatarManager = s,
+        },
+        
+        this.attachToAvatar = ( _, b=!1, k={x:0,y:0,z:0}, j=!1, $, _e ) => {
+            this.bbComponent.attachToAvatar(this, _, b, k, j, _e)
+        },
+
+        this.detachFromAvatar = ( _, b=!1 )=>{
+            this.bbComponent.detachFromAvatar(this, _, b)
+        },
+        this.getBbox = (_={})=>{
+            this.bbComponent.getBbox(this, _)
+        },
+
+        this.id = id,
+        this._avatarManager = avatarManager,
         this._scene = this.avatarManager.scene,
-        this.clothesList = c,
-        this._avatarType = i,
-        this.priority = o || 0,
+        this.clothesList = assets,
+        this._avatarType = avatarType,
+        this.priority = priority || 0,
+        
         this.controller = new XAnimationController(this),
         this.component = new XAvatarComopnent,
         this.stateMachine = new XStateMachine(this._scene),
         this.bbComponent = new XAvatarBillboardComponent(this._scene),
-        this.rootNode = new BABYLON.TransformNode(e,this._avatarManager.scene),
-        this._avatarScale = d.avatarScale == null ? 1 : d.avatarScale,
-        this._avatarRotation = d.avatarRotation == null ? {
-            pitch: 0,
-            yaw: 0,
-            roll: 0
-        } : d.avatarRotation,
-        this._avatarPosition = d.avatarPosition == null ? {
-            x: 0,
-            y: 0,
-            z: 0
-        } : d.avatarPosition,
+        this.rootNode = new BABYLON.TransformNode(id, this._avatarManager.scene),
+
+        this._avatarScale = status.avatarScale == null ? 1 : status.avatarScale,
+        this._avatarRotation = status.avatarRotation == null ? { pitch: 0, yaw: 0, roll: 0 } : status.avatarRotation,
+        this._avatarPosition = status.avatarPosition == null ? { x: 0, y: 0, z: 0 } : status.avatarPosition,
         this._isRayCastEnable = avatarSetting.isRayCastEnable,
+        
         this.setPosition(this._avatarPosition, !0),
         this.setRotation(this._avatarRotation),
         this.setScale(this.scale),
         this._isRayCastEnable = avatarSetting.isRayCastEnable,
+
         this._scene.registerBeforeRender(()=>{
             this.tick()
-        }
-        )
+        })
     }
 
     tick() {
         this.cullingTick()
     }
+
     cullingTick() {
-        var e;
-        this.isCulling && ((e = this.rootNode) == null || e.getChildMeshes().forEach(i=>{
+        this.isCulling && (this.rootNode == null || this.rootNode.getChildMeshes().forEach(i=>{
             this.distToCam < 50 ? i.visibility = 0 : i.visibility = this._transparent
-        }
-        ))
+        }))
     }
+
     setTransParentThresh(e) {
         this._transparent = e
     }
+
     get isNameVisible() {
         return this.bbComponent.isNameVisible
     }
+
     get isBubbleVisible() {
         return this.bbComponent.isBubbleVisible
     }
+
     get isGiftButtonsVisible() {
         return this.bbComponent.isGiftButtonsVisible
     }
+
     get words() {
         return this.bbComponent.words
     }
+
     get nickName() {
         return this.bbComponent.nickName
     }
+
     get giftButtons() {
         return this.bbComponent.giftButtons
     }
+
     get bubble() {
         return this.bbComponent.bubble
     }
+
     get nameBoard() {
         return this.bbComponent.nameBoard
     }
+
     get avatarManager() {
         return this._avatarManager
     }
+
     set withinVisibleRange(e) {
         this.bbComponent.withinVisualRange = e
     }
+
     setNicknameStatus(e) {
         return this.bbComponent.setNicknameStatus(e)
     }
+
     setBubbleStatus(e) {
         return this.bbComponent.setBubbleStatus(e)
     }
+
     setButtonsStatus(e) {
         return this.bbComponent.setBubbleStatus(e)
     }
+
     setGiftButtonsVisible(e) {
         return this.bbComponent.setGiftButtonsVisible(e)
     }
+
     get avatarType() {
         return this._avatarType
     }
+
     attachBody(e) {
         return this.component.addBodyComp(this, e)
     }
+
     attachDecoration(e) {
         return this.component.addClothesComp(this, e)
     }
+    
     detachDecoration(e) {
         return this.component.clearClothesComp(e)
     }
+
     detachDecorationAll() {
         return this.component.clearAllClothesComps()
     }
+
     get skeleton() {
         return this.component.skeleton
     }
+
     get position() {
         return this._avatarPosition
     }
+
     get rotation() {
         return this._avatarRotation
     }
+
     get scale() {
         return this._avatarScale
     }
+
     _hide_culling() {
         this.bbComponent.updateBillboardStatus(this, BillboardStatus.HIDE),
         this.isCulling = !0
     }
+
     _show_culling() {
         this.isCulling && (this.rootNode && this.rootNode.getChildMeshes().forEach(e=>{
             e.visibility = 1
-        }
-        ),
+        }),
         this.bbComponent.updateBillboardStatus(this, BillboardStatus.SHOW),
         this.isCulling = !1)
     }
+
     _hide() {
         !this.isHide || (this.setIsPickable(!1),
         this.bbComponent._attachmentObservers.forEach((e,i)=>{
@@ -212,25 +243,30 @@ export default class XAvatar {
         this.removeAvatarFromScene()),
         this.component.accessories.forEach(e=>{
             e.rootComponent.setEnabled(!1)
-        }
-        ))
+        }))
     }
+
     rotate(e, i, o) {
         return this.stateMachine.roll(this, e, i, o)
     }
+
     set isRayCastEnable(e) {
         this._isRayCastEnable = e
     }
+
     get isRayCastEnable() {
         return this._isRayCastEnable
     }
+
     getAvatarId() {
         return this.id
     }
+
     getAvaliableAnimations() {
         const e = avatarLoader.avaliableAnimation.get(this.avatarType);
         return e || []
     }
+
     // todo i用于控制是否接触地面。目前设默认为true,实时检测模型地面高度
     setPosition(e, i=!0) {
         this._avatarPosition = e;
@@ -263,6 +299,7 @@ export default class XAvatar {
         }
         return Promise.resolve(e)
     }
+
     setRotation(e) {
         if (this._avatarRotation = e,
         this.rootNode) {
@@ -275,6 +312,7 @@ export default class XAvatar {
             this.rootNode.rotation = o
         }
     }
+
     setAvatarVisible(e) {
         this.rootNode && (this.rootNode.setEnabled(e),
         this.rootNode.getChildMeshes().forEach(i=>{
@@ -282,11 +320,13 @@ export default class XAvatar {
         }
         ))
     }
+
     setScale(e) {
         this._avatarScale = e,
         this.rootNode && (this.rootNode.scaling = new BABYLON.Vector3(e,e,e)),
         this.bbComponent.bbox && this.getBbox()
     }
+
     _removeAvatarFromScene() {
         var e, i;
         this.isRender = !1,
@@ -295,19 +335,22 @@ export default class XAvatar {
         (i = this.avatarManager.sceneManager) == null || i.lightComponent.removeShadow(this),
         this.component.accessories.forEach(o=>{
             o.rootComponent.setEnabled(!1)
-        }
-        )
+        })
     }
+
     removeAvatarFromScene() {
         this._removeAvatarFromScene(),
         this._disposeBillBoard()
     }
+
     _disposeBillBoard() {
         this.bbComponent.disposeBillBoard(this)
     }
+
     addComponent(e, i, o, s) {
         return i === "pendant" ? this.component.attachPendant(this, e) : this.component.changeClothesComp(this, e, i, o, s)
     }
+
     removeComponent(e, i) {
         if (e === "pendant")
             i ? this.component.detachPendant(i) : this.component.accessories.forEach((o,s)=>{
@@ -320,6 +363,7 @@ export default class XAvatar {
             this.clothesList = this.clothesList.filter(s=>s.type != e))
         }
     }
+
     getComponentByType(e, i) {
         if (e === "pendant")
             if (i) {
@@ -330,6 +374,7 @@ export default class XAvatar {
         else
             return this.component.resourceIdList.find(o=>o.type == e)
     }
+
     _castRay(e) {
         return new Promise((i,o)=>{
             var et;
@@ -351,108 +396,109 @@ export default class XAvatar {
             _e = j.intersectsMeshes($),
             _e.length > 0)
                 return i(-(_e[0].distance - b))
-        }
-        )
+        })
     }
+
     setPickBoxScale(e) {
         return this.bbComponent.setPickBoxScale(e)
     }
+
     setIsPickable(e) {
         return this.bbComponent.setIsPickable(this, e)
     }
+
     createPickBoundingbox(e) {
         return this.bbComponent.createPickBoundingbox(this, e)
     }
+
     scaleBbox(e) {
         this.bbComponent.bbox && this.bbComponent.bbox.scale(e)
     }
+
     rotateTo(e, i, o) {
         return this.stateMachine.rotateTo(this, e, i, o)
     }
+
     faceTo(e, i) {
         return this.stateMachine.lookAt(this, e, i)
     }
+
     removeObserver() {
         this.stateMachine.disposeObsever()
     }
+
     moveHermite(e, i, o, s, c, d) {
         return this.stateMachine.moveToHermite(this, e, i, o, s, c, d)
     }
+
     moveCardinal(e, i, o, s, c, d, _=!1) {
         return this.stateMachine.moveToCardinal(this, e, i, o, s, c, d, _)
     }
+
     move(e, i, o, s, c, d=!1) {
         return this.stateMachine.moveTo(this, e, i, o, s, c, d)
     }
+
     initNameboard(e=1) {
         return this.bbComponent.initNameboard(this, e)
     }
+
     initBubble(e=1) {
         return this.bbComponent.initBubble(this, e)
     }
-    say(e, {id: i, isUser: o, background: s, font: c="Arial", fontsize: d=38, fontcolor: _="#ffffff", fontstyle: b="bold", linesize: k=22, linelimit: j, offsets: $={
-        x: 0,
-        y: 0,
-        z: 40
-    }, scale: _e=this._avatarScale, compensationZ: et=11.2, reregistAnyway: tt=!0}) {
+
+    say(e, {
+        id, isUser, background, 
+        font="Arial", fontsize=38, fontcolor="#ffffff", fontstyle="bold", linesize=22, linelimit, 
+        offsets={x: 0, y: 0, z: 40}, scale=this._avatarScale, compensationZ=11.2, reregistAnyway=!0
+    }) {
         return this.bbComponent.say(this, e, {
-            id: i,
-            isUser: o,
-            background: s,
-            font: c,
-            fontsize: d,
-            fontcolor: _,
-            fontstyle: b,
-            linesize: k,
-            linelimit: j,
-            offsets: $,
-            scale: _e,
-            compensationZ: et,
-            reregistAnyway: tt
+            id, isUser, background, 
+            font, fontsize, fontcolor, fontstyle, linesize, linelimit,
+            offsets, scale, compensationZ, reregistAnyway
         })
     }
+    
     silent() {
         return this.bbComponent.silent()
     }
-    setNickName(e, {id: i, isUser: o, background: s, font: c="Arial", fontsize: d=40, fontcolor: _="#ffffff", fontstyle: b="bold", linesize: k=22, linelimit: j, offsets: $={
-        x: 0,
-        y: 0,
-        z: 15
-    }, scale: _e=this._avatarScale, compensationZ: et=0, reregistAnyway: tt=!1}) {
+    
+    setNickName(e, {
+        id, isUser, background, 
+        font="Arial", fontsize=40, fontcolor="#ffffff", fontstyle="bold", linesize=22, linelimit, 
+        offsets={x: 0, y: 0, z: 15}, scale=this._avatarScale, compensationZ=0, reregistAnyway=!1
+    }) {
         return this.bbComponent.setNickName(this, e, {
-            id: i,
-            isUser: o,
-            background: s,
-            font: c,
-            fontsize: d,
-            fontcolor: _,
-            fontstyle: b,
-            linesize: k,
-            linelimit: j,
-            offsets: $,
-            scale: _e,
-            compensationZ: et,
-            reregistAnyway: tt
+            id, isUser, background,
+            font, fontsize, fontcolor, fontstyle, linesize, linelimit,
+            offsets, scale, compensationZ, reregistAnyway
         })
     }
+
     generateButtons(e=null, i=this._avatarScale, o=85) {
         return this.bbComponent.generateButtons(this, e, i, o)
     }
+
     clearButtons() {
         return this.bbComponent.clearButtons()
     }
+
     attachExtraProp(e, i, o, s) {
         return this.component.addDecoComp(this, e, i, o, s)
     }
+    
     showExtra(e) {
         return this.component.showExtra(e)
     }
+
     hideExtra(e) {
         return this.component.hideExtra(e)
     }
+
     disposeExtra() {
         return this.component.disposeExtra()
     }
+
     getSkeletonPositionByName(e) {
         var i;
         if (this.skeleton) {
@@ -467,6 +513,7 @@ export default class XAvatar {
             }
         }
     }
+
     shootTo(e, i, o=2, s=10, c={
         x: 0,
         y: 0,

+ 90 - 101
src/XAvatarManager.js

@@ -164,47 +164,35 @@ export default class XAvatarManager {
         this.characterMap.set(4, new Map),
         this.characterMap.set(5, new Map)
     }
-    loadAvatar({id: e, avatarType: t, priority: r, avatarManager: n, assets: o, status: a}) {
-        return new Promise((s,l)=>{
-            if (this.getAvatarById(e))
-                return l(new DuplicateAvatarIDError(`[Engine] cannot init avatar with the same id = ${e}`));
+    loadAvatar({id, avatarType, priority, avatarManager, assets, status}) {
+        return new Promise((resolve, reject)=>{
+            if (this.getAvatarById(id))
+                return reject(new DuplicateAvatarIDError(`[Engine] cannot init avatar with the same id = ${e}`));
             if (this.getAvatarNums() > this.maxAvatarNum)
-                return l(new ExceedMaxAvatarNumError(`[Engine] \u8D85\u51FA\u6700\u5927\u89D2\u8272\u9650\u5236 ${this.maxAvatarNum}`));
-            const u = new XAvatar({
-                id: e,
-                avatarType: t,
-                priority: r,
-                avatarManager: n,
-                assets: o,
-                status: a
-            });
-            this.registerAvatar(u);
-            if (r == 0)
-                this.setMainAvatar(u.id),
-                this.addAvatarToScene(u, 0).then(c=>(logger.debug(`[Engine] avatar ${u.id} has been added to scene`),
-                c ? (this._updateBillboardStatus(c, BillboardStatus.SHOW),
-                setTimeout(()=>{
-                    this.launchProcessLoadingLoop()
-                }
-                , this._delayTime),
-                s(c)) : (u.removeAvatarFromScene(),
-                l(new AvatarAssetLoadingError)))).catch(c=>(u.removeAvatarFromScene(),
-                l(new AvatarAssetLoadingError(c))));
-            else
-                return s(u)
+                return reject(new ExceedMaxAvatarNumError(`[Engine] \u8D85\u51FA\u6700\u5927\u89D2\u8272\u9650\u5236 ${this.maxAvatarNum}`));
 
-            // this.setMainAvatar(u.id),
-            // this.addAvatarToScene(u, 0).then(c=>(logger.debug(`[Engine] avatar ${u.id} has been added to scene`),
-            // c ? (this._updateBillboardStatus(c, BillboardStatus.SHOW),
-            // setTimeout(()=>{
-            //     this.launchProcessLoadingLoop()
-            // }
-            // , this._delayTime),
-            // s(c)) : (u.removeAvatarFromScene(),
-            // l(new AvatarAssetLoadingError)))).catch(c=>(u.removeAvatarFromScene(),
-            // l(new AvatarAssetLoadingError(c))));
-        }
-        )
+            const avatar = new XAvatar({ id, avatarType, priority, avatarManager, assets, status });
+            this.registerAvatar(avatar);
+
+            if (priority == 0)
+                this.setMainAvatar(avatar.id),
+                this.addAvatarToScene(avatar, 0).then(c=>(
+                    logger.debug(`[Engine] avatar ${avatar.id} has been added to scene`),
+                    c ? (
+                        this._updateBillboardStatus(c, BillboardStatus.SHOW),
+                        setTimeout(()=>{ this.launchProcessLoadingLoop() }, this._delayTime),
+                        resolve(c)
+                    ) : (
+                        avatar.removeAvatarFromScene(),
+                        reject(new AvatarAssetLoadingError)
+                    )
+                )).catch(c=>(
+                    avatar.removeAvatarFromScene(),
+                    reject(new AvatarAssetLoadingError(c))
+                ));
+            else
+                return resolve(avatar)
+        })
     }
     deleteAvatar(e) {
         return e.isRender ? (e.removeAvatarFromScene(),
@@ -632,79 +620,80 @@ export default class XAvatarManager {
     _getSourceKey(e, t) {
         return t && avatarSetting.lod[t] ? e + avatarSetting.lod[t].fileName.split(".")[0] : e
     }
-    addAvatarToScene(e, t) {
-        const r = Date.now();
-        return new Promise((n,o)=>{
-            this.loadBody(e.avatarType, e.avatarType, t).then(a=>{
-                // console.error(a.root._children[0]._scaling)
-                var s;
-                if (!a)
-                    return e.isInLoadingList = !1,
-                    o(new ContainerLoadingFailedError(`[Engine] avatar ${e.id} instanciates failed`));
-                if (e.attachBody(a),
-                a.animations.length > 0)
-                    return a.animations.forEach(l=>{
+    addAvatarToScene(xavatar, t) {
+        const startTime = Date.now();
+        return new Promise((resolve, reject)=>{
+            this.loadBody(xavatar.avatarType, xavatar.avatarType, t).then(modelData => {
+                if (!modelData) {
+                    xavatar.isInLoadingList = !1
+                    return reject(new ContainerLoadingFailedError(`[Engine] avatar ${xavatar.id} instanciates failed`));
+                }
+
+                xavatar.attachBody(modelData)
+                if (modelData.animations.length > 0) {
+                    modelData.animations.forEach(l=>{
                         l.stop()
+                    })
+                    xavatar.setAnimations(modelData.animations)
+                    xavatar.controller == null || xavatar.controller.playAnimation(xavatar.controller.onPlay, !0)
+                    xavatar.isRender = !0
+                    xavatar.isInLoadingList = !1
+                    xavatar.setAvatarVisible(!0)
+                    return resolve(xavatar);
+                }
+
+                this.loadAnimation(xavatar.avatarType, this._defaultAnims).then(l => {
+                    if (!l) {
+                        xavatar.removeAvatarFromScene()
+                        xavatar.isInLoadingList = !1
+                        return reject(new AvatarAnimationError);
                     }
-                    ),
-                    e.setAnimations(a.animations),
-                    (s = e.controller) == null || s.playAnimation(e.controller.onPlay, !0),
-                    e.isRender = !0,
-                    e.isInLoadingList = !1,
-                    e.setAvatarVisible(!0),
-                    n(e);
-                this.loadAnimation(e.avatarType, this._defaultAnims).then(l=>{
-                    if (!l)
-                        return e.removeAvatarFromScene(),
-                        e.isInLoadingList = !1,
-                        o(new AvatarAnimationError);
                     const u = [];
-                    e.clothesList.length > 0 && e.clothesList.forEach(c=>{
+                    xavatar.clothesList.length > 0 && xavatar.clothesList.forEach(c => {
                         u.push(this.loadDecoration(c.type, c.id, t))
-                    }
-                    ),
-                    Promise.all(u).then(c=>{
-                        var d, _, g, m;
+                    }),
+                    Promise.all(u).then(c => {
                         c.forEach(v=>{
-                            if (v && !v.isRender)
-                                e.attachDecoration(v);
-                            else
-                                return e.isInLoadingList = !1,
-                                e.removeAvatarFromScene(),
-                                o(new AvatarAssetLoadingError)
-                        }
-                        ),
-                        e.isRender = !0,
-                        (d = e.controller) == null || d.playAnimation(e.controller.onPlay, e.controller.loop),
-                        e.setAvatarVisible(!0);
+                            if (v && !v.isRender) {
+                                xavatar.attachDecoration(v);
+                            } else {
+                                xavatar.isInLoadingList = !1,
+                                xavatar.removeAvatarFromScene()
+                                return reject(new AvatarAssetLoadingError)
+                            }
+                        }),
+                        xavatar.isRender = !0,
+                        xavatar.controller == null || xavatar.controller.playAnimation(xavatar.controller.onPlay, xavatar.controller.loop),
+                        xavatar.setAvatarVisible(!0);
                         const h = avatarLoader.mshPath.get("meshes/ygb.glb")
                           , f = avatarLoader.matPath.get(avatarResources.ygb.mesh);
-                        h && f ? this.loadExtra(f, h).then(v=>{
-                            var y;
-                            e.isRender = !0,
-                            e.isInLoadingList = !1,
-                            e.distLevel = t,
-                            (y = this._sceneManager) == null || y.engineRunTimeStats.timeArray_addAvatarToScene.add(Date.now() - r),
-                            n(e)
+                        if(h && f) {
+                            this.loadExtra(f, h).then(v => {
+                                xavatar.isRender = !0,
+                                xavatar.isInLoadingList = !1,
+                                xavatar.distLevel = t,
+                                this._sceneManager == null || this._sceneManager.engineRunTimeStats.timeArray_addAvatarToScene.add(Date.now() - startTime),
+                                resolve(xavatar)
+                            })
+                        } else {
+                            xavatar.isRender = !0,
+                            xavatar.isInLoadingList = !1,
+                            xavatar.distLevel = t,
+                            this._sceneManager == null || this._sceneManager.engineRunTimeStats.timeArray_addAvatarToScene.add(Date.now() - startTime),
+                            resolve(xavatar)
                         }
-                        ) : (e.isRender = !0,
-                        e.isInLoadingList = !1,
-                        e.distLevel = t,
-                        (_ = this._sceneManager) == null || _.engineRunTimeStats.timeArray_addAvatarToScene.add(Date.now() - r),
-                        n(e)),
-                        (g = this._sceneManager) == null || g.lightComponent.setShadow(e),
-                        e.isInLoadingList = !1,
-                        e.distLevel = t,
-                        (m = this._sceneManager) == null || m.engineRunTimeStats.timeArray_addAvatarToScene.add(Date.now() - r),
-                        n(e)
+                        this._sceneManager == null || this._sceneManager.lightComponent.setShadow(xavatar),
+                        xavatar.isInLoadingList = !1,
+                        xavatar.distLevel = t,
+                        this._sceneManager == null || this._sceneManager.engineRunTimeStats.timeArray_addAvatarToScene.add(Date.now() - startTime),
+                        resolve(xavatar)
                     }
-                    ).catch(()=>o(new AvatarAssetLoadingError(`[Engine] avatar ${e.id} instanciates failed.`)))
+                    ).catch(()=>reject(new AvatarAssetLoadingError(`[Engine] avatar ${xavatar.id} instanciates failed.`)))
                 }
-                ).catch(()=>o(new AvatarAssetLoadingError(`[Engine] avatar ${e.id} instanciates failed.`)))
+                ).catch(()=>reject(new AvatarAssetLoadingError(`[Engine] avatar ${xavatar.id} instanciates failed.`)))
             }
-            ).catch(()=>o(new AvatarAssetLoadingError(`[Engine] avatar ${e.id} instanciates failed.`)))
-        }
-        )
+            ).catch(()=>reject(new AvatarAssetLoadingError(`[Engine] avatar ${xavatar.id} instanciates failed.`)))
+        })
     }
     loadExtra(e, t) {
         const r = avatarResources.ygb.name;

+ 94 - 83
src/XMaterialComponent.js

@@ -79,19 +79,14 @@ export default class XMaterialComponent {
             const height = e.height || 1280
             const focus = width / (2 * Math.tan(Math.PI * fov / 360));
             (lowModelShader = this._lowModelShader) == null || lowModelShader.setVector3("focal_width_height", new BABYLON.Vector3(focus,width,height))
-        }
-        );
+        });
 
-        E(this, "updateRawYUVData", (stream,width,height,fov=-1)=>{
-            var o, a;
+        E(this, "updateRawYUVData", (stream, width, height, fov=-1)=>{
             fov == -1 && (fov = this.yuvInfo.fov);
+
             if (this._isUpdateYUV == !0) {
-                //console.log('执行:updateRawYUVData')
-                const s = {
-                    width: width,
-                    height: height,
-                    fov: fov
-                }
+                console.log('执行:updateRawYUVData')
+                const yuvInfo = { width, height, fov }
                 const videosResOriArrayIndex = this._videoRawYUVTexArray.findId(width, height)
                 const currentVideoId = this._videoRawYUVTexArray.getCurrentVideoTexId();
 
@@ -100,48 +95,51 @@ export default class XMaterialComponent {
                     this.yuvInfo.width = width;
                     this.yuvInfo.height = height;
                     this.yuvInfo.fov = fov;
+
                     this._videoRawYUVTexArray.setCurrentVideoTexId(videosResOriArrayIndex);
-                    this._changeVideoRes(videosResOriArrayIndex);
-                    this._changePureVideoLowModelShaderCanvasSize(s);
-                    this._scenemanager.cameraComponent.cameraFovChange(s);
-                    this._scenemanager.yuvInfo = s;
+                    this._changeVideoRes(videosResOriArrayIndex);   // 设置texture_video
+                    this._changePureVideoLowModelShaderCanvasSize(yuvInfo); // 设置focal_width_height
+                    this._scenemanager.cameraComponent.cameraFovChange(yuvInfo);
+                    this._scenemanager.yuvInfo = yuvInfo;
                 }
 
                 let VideoTexture = this._videoRawYUVTexArray.getVideoYUVTex(videosResOriArrayIndex)
                 if(VideoTexture != null){
+                    // 更新视频流
                     VideoTexture.update(stream)
                     VideoTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE)
-                
                 }
+
+                //var o, a
                 //(o = this._videoRawYUVTexArray.getVideoYUVTex(videosResOriArrayIndex)) == null || o.update(stream),
                 //(a = this._videoRawYUVTexArray.getVideoYUVTex(videosResOriArrayIndex)) == null || a.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE)
             }
-        }
-        );
+        });
+
         E(this, "_changeVideoRes", e=>{
             this._lowModelShader.setTexture("texture_video", this._videoRawYUVTexArray.getVideoYUVTex(e))
-        }
-        );
+        });
 
-        E(this, "initDynamicData", (dynamicRange,width,height)=>new Promise((resolve,reject)=>{
-            this.setDynamicSize(dynamicRange).then(a=>{
-                if (a) {
-                    for (let s = 0; s < dynamicRange; ++s)
-                        (l=>{
-                            this.initDynamicTexture(l, width, height),
-                            this.initDynamicShaders(l).then(()=>{
-                                this._updatePanoShaderInput(l)
+        E(this, "initDynamicData", (dynamicRange,width,height)=>{
+            return new Promise((resolve,reject)=>{
+                this.setDynamicSize(dynamicRange).then(a=>{
+                    if (a) {
+                        for (let s = 0; s < dynamicRange; ++s)
+                            (l=>{
+                                this.initDynamicTexture(l, width, height),
+                                this.initDynamicShaders(l).then(()=>{
+                                    this._updatePanoShaderInput(l)
+                                }
+                                )
                             }
-                            )
-                        }
-                        )(s);
-                    resolve(!0)
-                } else
-                    reject(new XMaterialError(`[Engine] DynamicRoomSize (${dynamicRange}) is too small`))
-            }
-            )
-        }
-        ).catch(n=>logger.error(`[Engine] ${n}`)));
+                            )(s);
+                        resolve(!0)
+                    } else
+                        reject(new XMaterialError(`[Engine] DynamicRoomSize (${dynamicRange}) is too small`))
+                }
+                )
+            }).catch(n=>logger.error(`[Engine] ${n}`))
+        });
         
         E(this, "_initDefaultShader", ()=>{
             this._defaultShader == null && (this._defaultShader = new BABYLON.GridMaterial("GridShader",this.scene),
@@ -150,8 +148,8 @@ export default class XMaterialComponent {
             this._defaultShader.majorUnitFrequency = 1,
             this._defaultShader.mainColor = new BABYLON.Color3(.6,.6,.6),
             this._defaultShader.backFaceCulling = !1)
-        }
-        );
+        });
+
         E(this, "_initPureVideoShader", ()=>{
             if (this._lowModelShader == null) {
                 const e = new BABYLON.ShaderMaterial("PureVideoShader",this.scene,{
@@ -173,46 +171,49 @@ export default class XMaterialComponent {
                 e.backFaceCulling = !1,
                 this._lowModelShader = e
             }
-        }
-        );
+        });
+
         E(this, "setDynamicSize", e=>new Promise((t,r)=>{
             e >= 1 && e <= 100 ? (this._dynamic_size = e,
             t(!0)) : (this._dynamic_size = 1,
             t(!1))
-        }
-        ));
+        }));
+
         E(this, "_isInDynamicRange", e=>e < this._dynamic_size && e >= 0);
+
         E(this, "initDynamicTexture", (e,t,r)=>{
             this._isInDynamicRange(e) && (this._dynamic_textures[e] != null && (this._dynamic_textures[e].dispose(),
             this._dynamic_textures[e] = null),
             this._dynamic_textures[e] = new BABYLON.RawTexture(null,t,r * 1.5,BABYLON.Engine.TEXTUREFORMAT_LUMINANCE,this.scene,!1,!0,BABYLON.Texture.NEAREST_SAMPLINGMODE,BABYLON.Engine.TEXTURETYPE_UNSIGNED_BYTE),
             this._dynamic_textures[e].name = "Pano_Dynamic_" + e + "_" + Date.now())
-        }
-        );
-        E(this, "initDynamicShaders", e=>(logger.info("[Engine] Material init dynamic shader."),
-        new Promise((t,r)=>{
-            this._dynamic_shaders[e] != null && this._dynamic_shaders[e].dispose();
-            const n = new BABYLON.ShaderMaterial("Pano_Shader_" + e,this.scene,{
-                vertexSource: panoVertex,
-                fragmentSource: panoFragment
-            },{
-                attributes: ["uv", "position", "world0", "world1", "world2", "world3"],
-                uniforms: ["view", "projection", "worldViewProjection", "world"],
-                defines: ["#define SHADOWFULLFLOAT"]
-            });
-            n.setTexture("texture_pano", null),
-            n.setVector3("centre_pose", new BABYLON.Vector3(0,0,0)),
-            n.setFloat("isYUV", this._inputPanoYUV420 ? 1 : 0),
-            n.setTexture("shadowSampler", null),
-            n.setMatrix("lightSpaceMatrix", null),
-            n.setFloat("haveShadowLight", 0),
-            n.setFloat("fireworkLight", 0),
-            n.setVector3("fireworkLightPosition", new BABYLON.Vector3(0,0,0)),
-            n.backFaceCulling = !1,
-            this._dynamic_shaders[e] = n,
-            t(!0)
-        }
+        });
+
+        E(this, "initDynamicShaders", e=>(
+            logger.info("[Engine] Material init dynamic shader."),
+            new Promise((t,r)=>{
+                this._dynamic_shaders[e] != null && this._dynamic_shaders[e].dispose();
+                const n = new BABYLON.ShaderMaterial("Pano_Shader_" + e,this.scene,{
+                    vertexSource: panoVertex,
+                    fragmentSource: panoFragment
+                },{
+                    attributes: ["uv", "position", "world0", "world1", "world2", "world3"],
+                    uniforms: ["view", "projection", "worldViewProjection", "world"],
+                    defines: ["#define SHADOWFULLFLOAT"]
+                });
+                n.setTexture("texture_pano", null),
+                n.setVector3("centre_pose", new BABYLON.Vector3(0,0,0)),
+                n.setFloat("isYUV", this._inputPanoYUV420 ? 1 : 0),
+                n.setTexture("shadowSampler", null),
+                n.setMatrix("lightSpaceMatrix", null),
+                n.setFloat("haveShadowLight", 0),
+                n.setFloat("fireworkLight", 0),
+                n.setVector3("fireworkLightPosition", new BABYLON.Vector3(0,0,0)),
+                n.backFaceCulling = !1,
+                this._dynamic_shaders[e] = n,
+                t(!0)
+            }
         )));
+
         this._scenemanager = e,
         this.scene = e.Scene,
         this.engine = this.scene.getEngine(),
@@ -410,24 +411,34 @@ export default class XMaterialComponent {
             pointLight.intensity = 0
         }
     }
+
     _updatePanoShaderInput(e) {
-        var t, r, n, o, a, s, l, u, c, h;
-        if (this._isInDynamicRange(e))
-            if (this.scene.getLightByName("AvatarLight") ? ((t = this._dynamic_shaders[e]) == null || t.setFloat("haveShadowLight", 1),
-            (o = this._dynamic_shaders[e]) == null || o.setTexture("shadowSampler", (n = (r = this.scene.getLightByName("AvatarLight")) == null ? void 0 : r.getShadowGenerator()) == null ? void 0 : n.getShadowMapForRendering()),
-            (l = this._dynamic_shaders[e]) == null || l.setMatrix("lightSpaceMatrix", (s = (a = this.scene.getLightByName("AvatarLight")) == null ? void 0 : a.getShadowGenerator()) == null ? void 0 : s.getTransformMatrix())) : ((u = this._dynamic_shaders[e]) == null || u.setTexture("shadowSampler", null),
-            (c = this._dynamic_shaders[e]) == null || c.setMatrix("lightSpaceMatrix", new Matrix),
-            (h = this._dynamic_shaders[e]) == null || h.setFloat("haveShadowLight", 0)),
-            this.scene.getLightByName("fireworkLight"))
+        var n,s;
+        if (this._isInDynamicRange(e)) 
+        {
+            let shader = this._dynamic_shaders[e]
+            let avatarLight = this.scene.getLightByName("AvatarLight")
+
+            shader == null || (avatarLight ? (
+                shader.setFloat("haveShadowLight", 1),
+                shader.setTexture("shadowSampler", (n = avatarLight == null ? void 0 : avatarLight.getShadowGenerator()) == null ? void 0 : n.getShadowMapForRendering()),
+                shader.setMatrix("lightSpaceMatrix", (s = avatarLight == null ? void 0 : avatarLight.getShadowGenerator()) == null ? void 0 : s.getTransformMatrix())
+            ) : (
+                shader.setTexture("shadowSampler", null),
+                shader.setMatrix("lightSpaceMatrix", new Matrix),
+                shader.setFloat("haveShadowLight", 0)
+            ))
+
+            let fireworkLight = this.scene.getLightByName("fireworkLight")
+            if (fireworkLight) {
                 this.scene.registerBeforeRender(()=>{
-                    var f;
-                    this._dynamic_shaders[e].setFloat("fireworkLight", this.scene.getLightByName("fireworkLight").getScaledIntensity()),
-                    this._dynamic_shaders[e].setVector3("fireworkLightPosition", (f = this.scene.getLightByName("fireworkLight")) == null ? void 0 : f.position)
-                }
-                );
-            else {
-                const f = new BABYLON.PointLight("fireworkLight",new BABYLON.Vector3(0,0,0),this.scene);
+                    shader.setFloat("fireworkLight", fireworkLight.getScaledIntensity()),
+                    shader.setVector3("fireworkLightPosition", fireworkLight == null ? void 0 : fireworkLight.position)
+                });
+            } else {
+                const f = new BABYLON.PointLight("fireworkLight", new BABYLON.Vector3(0,0,0), this.scene);
                 f.intensity = 0
             }
+        }
     }
 }

+ 189 - 145
src/XverseAvatar.js

@@ -32,144 +32,142 @@ export default class XverseAvatar extends EventEmitter {
         E(this, "_lastAnimTraceId", "");
         E(this, "statusSyncQueue", new Queue);
         E(this, "extraInfo", {});
-        E(this, "setPosition", e=>{
-            var t;
-            !this._room.signal.isUpdatedYUV || (t = this.xAvatar) == null || t.setPosition(positionPrecisionProtect(e))
-        }
-        );
-        E(this, "setRotation", e=>{
-            var t;
-            !this._room.signal.isUpdatedYUV || (t = this.xAvatar) == null || t.setRotation(rotationPrecisionProtect(e))
-        }
-        );
+
+        E(this, "setPosition", pos => {
+            !this._room.signal.isUpdatedYUV || this.xAvatar == null || this.xAvatar.setPosition(positionPrecisionProtect(pos))
+        });
+
+        E(this, "setRotation", rota => {
+            !this._room.signal.isUpdatedYUV || this.xAvatar == null || this.xAvatar.setRotation(rotationPrecisionProtect(rota))
+        });
+
         E(this, "stopAnimation", ()=>{
-            var e, t;
-            (t = (e = this.xAvatar) == null ? void 0 : e.controller) == null || t.stopAnimation()
-        }
-        );
-        E(this, "_playAnimation", async(e,t=!0,r=!1)=>{
-            var o;
-            if (!this._room.signal.isUpdatedYUV)
-                return;
+            (this.xAvatar == null ? void 0 : this.xAvatar.controller) == null || this.xAvatar.controller.stopAnimation()
+        });
+
+        E(this, "_playAnimation", async(animationName, isLoop=!0, r=!1)=>{
+            if (!this._room.signal.isUpdatedYUV) return;
+
             if (this.state !== "idle" && !r)
                 return logger.debug("_playAnimation", "state is not idle"),
                 Promise.resolve("_playAnimation, state is not idle");
-            const n = Date.now();
+
+            const startTime = Date.now();
             try {
-                if (!((o = this.xAvatar) != null && o.controller))
-                    return Promise.reject(new InternalError(`[avatar: ${this.userId}] Play animation failed: ${e}, no controller`));
+                if (!(this.xAvatar != null && this.xAvatar.controller))
+                    return Promise.reject(new InternalError(`[avatar: ${this.userId}] Play animation failed: ${animationName}, no controller`));
                 this.isSelf && setTimeout(()=>{
                     logger.infoAndReportMeasurement({
-                        tag: e,
-                        startTime: n,
+                        tag: animationName,
+                        startTime,
                         value: 0,
                         metric: "playAnimationStart"
                     })
-                }
-                );
-                const a = util.uuid();
-                this._lastAnimTraceId = a,
-                await this.xAvatar.controller.playAnimation(e, t),
-                a === this._lastAnimTraceId && !this.isMoving && !t && e !== "Idle" && this.xAvatar.controller.playAnimation("Idle", t).catch(s=>{
+                });
+
+                const uuid = util.uuid();
+                this._lastAnimTraceId = uuid,
+                await this.xAvatar.controller.playAnimation(animationName, isLoop),
+                uuid === this._lastAnimTraceId && !this.isMoving && !isLoop && animationName !== "Idle" && this.xAvatar.controller.playAnimation("Idle", isLoop).catch(s=>{
                     logger.error(`[avatar: ${this.userId}] Play animation failed [force idle]`, s)
                 }
                 ),
                 this.isSelf && logger.infoAndReportMeasurement({
-                    tag: e,
-                    startTime: n,
+                    tag: animationName,
+                    startTime,
                     extra: {
-                        loop: t
+                        loop: isLoop
                     },
                     metric: "playAnimationEnd"
                 })
-            } catch (a) {
-                return logger.error(`[avatar: ${this.userId}] Play animation failed: ${e}`, a),
+            } catch (err) {
+                return logger.error(`[avatar: ${this.userId}] Play animation failed: ${animationName}`, err),
                 this.isSelf && logger.infoAndReportMeasurement({
-                    tag: e,
-                    startTime: n,
+                    tag: animationName,
+                    startTime,
                     metric: "playAnimationEnd",
-                    error: a,
+                    error: err,
                     extra: {
-                        loop: t
+                        loop: isLoop
                     }
                 }),
-                Promise.reject(a)
-            }
-        }
-        );
-        E(this, "changeComponents", async e=>{
-            const {mode: t, endAnimation: r=""} = e || {}
-              , n = JSON.parse(JSON.stringify(e.avatarComponents));
-            let o = avatarComponentsValidate(n, this._avatarModel);
-            return !ChangeComponentsMode[t] && !o && (o = new ParamError(`changeComponents failed, mode: ${t} is invalid`)),
-            o ? (logger.error(o),
-            Promise.reject(o)) : this._changeComponents({
-                avatarComponents: n,
-                mode: t,
-                endAnimation: r
-            }).then(()=>{
-                this.isSelf && t !== ChangeComponentsMode.Preview && this.avatarComponentsSync(this.avatarComponents)
+                Promise.reject(err)
             }
-            )
-        }
-        );
-        E(this, "_changeComponents", async e=>{
-            var o;
-            const {avatarComponents: t=[], mode: r} = e || {}
-              , n = Date.now();
+        });
+
+        E(this, "changeComponents", async data => {
+            const {mode, endAnimation=""} = data || {}
+              , avatarComponents = JSON.parse(JSON.stringify(data.avatarComponents));
+
+            let o = avatarComponentsValidate(avatarComponents, this._avatarModel);
+            !ChangeComponentsMode[mode] && !o && (o = new ParamError(`changeComponents failed, mode: ${mode} is invalid`))
+
+            return o ? (logger.error(o), Promise.reject(o)) 
+            : this._changeComponents({ avatarComponents, mode, endAnimation }).then(()=>{
+                this.isSelf && mode !== ChangeComponentsMode.Preview && this.avatarComponentsSync(this.avatarComponents)
+            })
+        });
+
+        E(this, "_changeComponents", async data=>{
+            const {avatarComponents=[], mode} = data || {}
+              , startTime = Date.now();
+
             try {
-                if (!this.xAvatar)
-                    return Promise.reject(new InternalError("changeComponents failed, without instance: xAvatar"));
-                const a = await avatarComponentsModify(this._avatarModel, t)
+                if (!this.xAvatar) return Promise.reject(new InternalError("changeComponents failed, without instance: xAvatar"));
+
+                const a = await avatarComponentsModify(this._avatarModel, avatarComponents)
                   , s = []
                   , l = await avatarComponentsParser(this._avatarModel, a, this.avatarComponents);
-                if (l.length === 0)
-                    return this.avatarComponents;
-                await this.beforeChangeComponentsHook(e);
+
+                if (l.length === 0) return this.avatarComponents;
+
+                await this.beforeChangeComponentsHook(data);
                 for (const u of l) {
-                    const {id: c, type: h, url: f, suitComb: d} = u;
-                    s.push((o = this.xAvatar) == null ? void 0 : o.addComponent(c, h, f, d))
+                    const {id, type, url, suitComb} = u;
+                    s.push(this.xAvatar == null ? void 0 : this.xAvatar.addComponent(id, type, url, suitComb))
                 }
-                return await Promise.all(s),
+
+                await Promise.all(s)
                 this.emit("componentsChanged", {
                     components: this.avatarComponents,
-                    mode: r
-                }),
+                    mode
+                })
                 this.isSelf && logger.infoAndReportMeasurement({
                     tag: "changeComponents",
-                    startTime: n,
+                    startTime,
                     metric: "changeComponents",
                     extra: {
-                        inputComponents: t,
+                        inputComponents: avatarComponents,
                         finalComponents: this.avatarComponents,
-                        mode: ChangeComponentsMode[r]
+                        mode: ChangeComponentsMode[mode]
                     }
-                }),
-                this.avatarComponents
-            } catch (a) {
-                return this.isSelf && logger.infoAndReportMeasurement({
+                })
+                return this.avatarComponents
+
+            } catch (error) {
+                this.isSelf && logger.infoAndReportMeasurement({
                     tag: "changeComponents",
-                    startTime: n,
+                    startTime,
                     metric: "changeComponents",
-                    error: a,
+                    error,
                     extra: {
-                        inputComponents: t,
+                        inputComponents: avatarComponents,
                         finalComponents: this.avatarComponents,
-                        mode: ChangeComponentsMode[r]
+                        mode: ChangeComponentsMode[mode]
                     }
-                }),
-                Promise.reject(a)
+                })
+                return Promise.reject(error)
             }
-        }
-        );
+        });
+
         E(this, "avatarComponentsSync", e=>{
             e = e.map(t=>({
                 type: t.type,
                 id: t.id
             })),
             this._room.actionsHandler.avatarComponentsSync(e)
-        }
-        );
+        });
+
         E(this, "hide", ()=>{
             var e;
             if ((e = this.xAvatar) != null && e.hide())
@@ -179,8 +177,8 @@ export default class XverseAvatar extends EventEmitter {
                 return logger.warn(t),
                 Promise.reject(t)
             }
-        }
-        );
+        });
+
         E(this, "show", ()=>{
             var e;
             if ((e = this.xAvatar) != null && e.show())
@@ -190,9 +188,10 @@ export default class XverseAvatar extends EventEmitter {
                 return logger.warn(t),
                 Promise.reject(t)
             }
-        }
-        );
+        });
+
         E(this, "sayTimer");
+
         this._userId = e,
         this._room = r,
         this.isSelf = o || !1,
@@ -203,23 +202,27 @@ export default class XverseAvatar extends EventEmitter {
         this._room.modelManager.getAvatarModelList().then(s=>{
             const l = s.find(u=>u.id === n);
             l && (this._avatarModel = l)
-        }
-        )
+        })
     }
+
     get avatarId() {
         return this._avatarId
     }
+
     get isRender() {
         var e;
         return !!((e = this.xAvatar) != null && e.isRender)
     }
+
     get isHidden() {
         var e;
         return !!((e = this.xAvatar) != null && e.isHide)
     }
+
     get motionType() {
         return this._motionType
     }
+
     set motionType(e) {
         this._motionType = e
     }
@@ -227,113 +230,131 @@ export default class XverseAvatar extends EventEmitter {
         var e;
         return (e = this.xAvatar) == null ? void 0 : e.nickName
     }
+
     get words() {
         var e;
         return (e = this.xAvatar) == null ? void 0 : e.words
     }
+
     get isHost() {
         return this._isHost
     }
+
     get failed() {
         return this._failed
     }
+
     get scale() {
         var e;
         return (e = this.xAvatar) == null ? void 0 : e.scale
     }
+
     get animations() {
         var e;
         return !this.xAvatar || !this.xAvatar.controller ? [] : ((e = this.xAvatar) == null ? void 0 : e.getAvaliableAnimations()) || []
     }
+
     get position() {
         var e;
         return (e = this.xAvatar) == null ? void 0 : e.position
     }
+
     get rotation() {
         var e;
         return (e = this.xAvatar) == null ? void 0 : e.rotation
     }
+
     get pose() {
         return {
             position: this.position,
             angle: this.rotation
         }
     }
+
     get id() {
         return this.userId
     }
+
     get isMoving() {
         return this._isMoving
     }
+
     set isMoving(e) {
         this._isMoving = e,
         this.state = e ? "moving" : "idle"
     }
+
     get isRotating() {
         return this._isRotating
     }
+
     set isRotating(e) {
         this._isRotating = e,
         this.state = e ? "rotating" : "idle"
     }
+
     get withModel() {
         return this._withModel
     }
+
     get avatarComponents() {
         var e;
         return JSON.parse(JSON.stringify(((e = this.xAvatar) == null ? void 0 : e.clothesList) || []))
     }
+
     get userId() {
         return this._userId
     }
+
     get removeWhenDisconnected() {
         return this.extraInfo && this.extraInfo.removeWhenDisconnected !== void 0 ? this.extraInfo.removeWhenDisconnected : !0
     }
+
     setConnectionStatus(e) {
         this.disconnected !== e && (this.disconnected = e,
         e ? this.emit("disconnected") : this.emit("reconnected"),
         logger.warn(`avatar ${this.userId} status changed, disconnected:`, e))
     }
-    setScale(e) {
-        var t;
-        (t = this.xAvatar) == null || t.setScale(e > 0 ? e : 1)
+
+    setScale(scaleNum) {
+        this.xAvatar == null || this.xAvatar.setScale(scaleNum > 0 ? scaleNum : 1)
     }
-    async playAnimation(e) {
-        const {animationName: t, loop: r, extra: n} = e || {};
+
+    async playAnimation(aniData) {
+        const {animationName, loop: isLoop, extra} = aniData || {};
         if (this.isSelf) {
             if (this.isMoving)
                 try {
                     await this.stopMoving()
-                } catch (a) {
-                    return logger.error(`stopMoving error before playAnimation ${t}`, a),
-                    Promise.reject(`stopMoving error before playAnimation ${t}`)
+                } catch (err) {
+                    return logger.error(`stopMoving error before playAnimation ${animationName}`, err),
+                    Promise.reject(`stopMoving error before playAnimation ${animationName}`)
                 }
-            const o = {
+            const data = {
                 info: {
                     userId: this.userId,
-                    animation: t,
-                    loop: r,
-                    extra: encodeURIComponent(n || "")
+                    animation: animationName,
+                    loop: isLoop,
+                    extra: encodeURIComponent(extra || "")
                 },
                 broadcastType: CoreBroadcastType.PlayAnimation
             };
-            this._room.avatarManager.broadcast.broadcast({
-                data: o
-            })
+            this._room.avatarManager.broadcast.broadcast({ data })
         }
         return this.emit("animationStart", {
-            animationName: t,
-            extra: safeDecodeURIComponent(n || "")
+            animationName,
+            extra: safeDecodeURIComponent(extra || "")
         }),
-        this._playAnimation(t, r).then(()=>{
+        this._playAnimation(animationName, isLoop).then(()=>{
             this.emit("animationEnd", {
-                animationName: t,
-                extra: safeDecodeURIComponent(n || "")
+                animationName,
+                extra: safeDecodeURIComponent(extra || "")
             })
-        }
-        )
+        })
     }
+
     async beforeChangeComponentsHook(e) {}
+
     turnTo(e) {
         if (this._room.viewMode === "observer") {
             this._room.sceneManager.cameraComponent.MainCamera.setTarget(ue4Position2Xverse(e.point));
@@ -343,9 +364,9 @@ export default class XverseAvatar extends EventEmitter {
             this.emit("viewChanged", {
                 extra: (e == null ? void 0 : e.extra) || ""
             })
-        }
-        )
+        })
     }
+
     async moveTo(e) {
         const {point: t, extra: r=""} = e || {};
         if (!this.position)
@@ -362,15 +383,19 @@ export default class XverseAvatar extends EventEmitter {
             extra: r
         })
     }
+
     async stopMoving() {
         return this._room.actionsHandler.stopMoving()
     }
+
     rotateTo(e) {
         return this._room.actionsHandler.rotateTo(e)
     }
+
     setRayCast(e) {
         this.xAvatar && (this.xAvatar.isRayCastEnable = e)
     }
+
     say(e, t) {
         if (this.sayTimer && window.clearTimeout(this.sayTimer),
         !this.xAvatar) {
@@ -386,6 +411,7 @@ export default class XverseAvatar extends EventEmitter {
         }
         , t))
     }
+
     silent() {
         var e;
         if (!this.xAvatar) {
@@ -394,15 +420,18 @@ export default class XverseAvatar extends EventEmitter {
         }
         (e = this.xAvatar) == null || e.silent()
     }
+
     setMotionType({type: e=MotionType.Walk}) {
         return this.motionType === e ? Promise.resolve() : this._room.actionsHandler.setMotionType(e).then(()=>{
             this._motionType = e
         }
         )
     }
+
     setNickname(e) {
         return this._room.actionsHandler.setNickName(encodeURIComponent(e))
     }
+
     _setNickname(e) {
         var r, n;
         if (!e)
@@ -416,16 +445,19 @@ export default class XverseAvatar extends EventEmitter {
             scale: this.xAvatar.scale
         }))
     }
+
     _move(e) {
         var s;
         const {start: t, end: r, walkSpeed: n, moveAnimation: o="Walking", inter: a=[]} = e || {};
         return (s = this.xAvatar) == null ? void 0 : s.move(t, r, n, o, a)
     }
+
     setPickBoxScale(e=1) {
         return this.xAvatar ? (this.xAvatar.setPickBoxScale(e),
         !0) : (logger.error("setPickBoxScale failed, without instance: xAvatar"),
         !1)
     }
+
     transfer(e) {
         const {player: t, camera: r, areaName: n, attitude: o, pathName: a} = e;
         return this._room.actionsHandler.transfer({
@@ -438,39 +470,51 @@ export default class XverseAvatar extends EventEmitter {
             tag: "transfer"
         })
     }
+
     avatarLoadedHook() {}
     avatarStartMovingHook() {}
     avatarStopMovingHook() {}
+
     async statusSync(e) {
-        var t, r, n;
         try {
-            if ((t = e.event) != null && t.rotateEvent) {
-                const {angle: o, speed: a} = e.event.rotateEvent
-                  , s = this.motionType === MotionType.Run ? "Running" : "Walking";
-                this.rotation && (this.rotation.yaw = this.rotation.yaw % 360,
-                o.yaw - this.rotation.yaw > 180 && (o.yaw = 180 - o.yaw),
-                this.isRotating = !0,
-                await this.xAvatar.rotateTo(o, this.rotation, s).then(()=>{
-                    this._playAnimation("Idle", !0),
-                    this.isRotating = !1
-                }
-                ))
+            // 旋转
+            if (e.event != null && e.event.rotateEvent) 
+            {
+                const {angle, speed} = e.event.rotateEvent
+                  , moveAnimation = this.motionType === MotionType.Run ? "Running" : "Walking";
+
+                this.rotation && (
+                    this.rotation.yaw = this.rotation.yaw % 360,
+                    angle.yaw - this.rotation.yaw > 180 && (angle.yaw = 180 - angle.yaw),
+                    this.isRotating = true,
+
+                    await this.xAvatar.rotateTo(angle, this.rotation, moveAnimation).then(()=>{
+                        this._playAnimation("Idle", true),
+                        this.isRotating = false
+                    })
+                )
             }
-            if (e.event && (((r = e.event) == null ? void 0 : r.points.length) || 0) > 1 && !this.isSelf) {
-                this.isMoving = !0,
+
+            // 行走
+            if (e.event && ((e.event == null ? void 0 : e.event.points.length) || 0) > 1 && !this.isSelf)
+            {
+                this.isMoving = true,
                 e.playerState.attitude && (this._motionType = e.playerState.attitude);
-                const o = this.motionType === MotionType.Run ? "Running" : "Walking"
-                  , a = this._room.skin.routeList.find(l=>l.areaName === this._room.currentState.areaName)
-                  , s = ((a == null ? void 0 : a.step) || 7.5) * 30 * (25 / 30);
-                this.position && await this._move({
-                    start: this.position,
-                    end: e.event.points[e.event.points.length - 1],
-                    walkSpeed: s,
-                    moveAnimation: o,
-                    inter: (n = e.event) == null ? void 0 : n.points.slice(0, -1)
-                }).then(()=>{
-                    this.isMoving = !1
-                }
+
+                const moveAnimation = this.motionType === MotionType.Run ? "Running" : "Walking"
+                  , skinRoute = this._room.skin.routeList.find(l => l.areaName === this._room.currentState.areaName)
+                  , walkSpeed = ((skinRoute == null ? void 0 : skinRoute.step) || 7.5) * 30 * (25 / 30);
+
+                this.position && (
+                    await this._move({
+                        start: this.position,
+                        end: e.event.points[e.event.points.length - 1],
+                        walkSpeed,
+                        moveAnimation: moveAnimation,
+                        inter: e.event == null ? void 0 : e.event.points.slice(0, -1)
+                    }).then(()=>{
+                        this.isMoving = false
+                    })
                 )
             }
         } catch {

تفاوت فایلی نمایش داده نمی شود زیرا این فایل بسیار بزرگ است
+ 112 - 94
src/Xverse_Room.js