Esempio n. 1
0
 public Kid()
 {
     Animation = new AnimationSet(@"kid\kid.xml");
     Animation.Speed = 2;
     Animation.AutoAnimate("normal", 0);
     X = 2100;
     Y = 40;
 }
 public void Show()
 {
     if (anim4 != null)
     {
         anim4.Stop();
     }
     anim4 = (this).Fade(1, 200);
     anim4.Start();
 }
Esempio n. 3
0
 public Shim(AnimationSet animationSet, Position position, bool facingLeft, float parallaxX, float parallaxY)
 {
     AnimationSet   = animationSet;
     Position       = position;
     FacingLeft     = facingLeft;
     this.parallaxX = parallaxX;
     this.parallaxY = parallaxY;
     tag            = 0;
 }
Esempio n. 4
0
        private static AnimationSet <AnimationClip> LoadDanceCompiled([NotNull] string filePath, int motionNumber, int formationNumber, out int suggestedPosition)
        {
            AnimationClip dan = null, apa = null, apg = null, bpg = null;

            var danComp = $"{motionNumber:00}_dan";
            var apaComp = $"{formationNumber:00}_apa";
            var apgComp = $"{formationNumber:00}_apg";
            var bpgComp = $"{formationNumber:00}_bpg";

            var manager = new AssetsManager();

            manager.LoadFiles(filePath);

            foreach (var assetFile in manager.assetsFileList)
            {
                foreach (var obj in assetFile.Objects)
                {
                    if (obj.type != ClassIDType.AnimationClip)
                    {
                        continue;
                    }

                    var clip = obj as AnimationClip;

                    if (clip == null)
                    {
                        throw new ArgumentNullException(nameof(clip), "One animation clip is null.");
                    }

                    if (clip.m_Name.Contains(danComp))
                    {
                        dan = clip;
                    }
                    else if (clip.m_Name.Contains(apaComp))
                    {
                        apa = clip;
                    }
                    else if (clip.m_Name.Contains(apgComp))
                    {
                        apg = clip;
                    }
                    else if (clip.m_Name.Contains(bpgComp))
                    {
                        bpg = clip;
                    }

                    if (dan != null && apa != null && apg != null && bpg != null)
                    {
                        break;
                    }
                }
            }

            suggestedPosition = GetSuggestedDancePosition(manager);

            return(AnimationSet.Create(dan, apg, apa, bpg));
        }
Esempio n. 5
0
        public override AnimationSet LoadAnimation(string fileId)
        {
            AnimationSet animationSet = null;

            if (FitsExtension(fileId))
            {
            }
            return(animationSet);
        }
 public void Hide()
 {
     if (anim4 != null)
     {
         anim4.Stop();
     }
     anim4 = (this).Fade(0, 200);
     anim4.Start();
 }
 public PedAnimationManager(StreamedPed ped)
 {
     this.ped = ped;
     currentAnimation = PedAnimations.StandStill;
     animset = new AnimationSet("move_m@casual");
     animset2 = new AnimationSet("gun@ak47");
     lastRunToCoord = Vector3.Zero;
     lastWalkToCoord = Vector3.Zero;
     lastAnimationStarted = DateTime.Now;
 }
Esempio n. 8
0
        private AnimationSet AnimateGhostEllipse(double ellipseX, double ellipseY)
        {
            double width    = GhostCanvas.Width;
            double height   = GhostCanvas.Height;
            double ElRadius = GhostEllipse.Width / 2;

            AnimationSet anim = GhostShadow.Scale((float)1.5, (float)1.5, (float)ElRadius, (float)ElRadius, 100).Then().Scale(1, 1, (float)ElRadius, (float)ElRadius, 100).Then().Offset(offsetX: (float)((ellipseX * width) - ElRadius), offsetY: (float)((ellipseY * height) - ElRadius), duration: 800, easingType: EasingType.Quadratic);

            return(anim);
        }
 public RemotePlayerAnimationManager(RemotePlayer Player)
 {
     this.Player = Player;
     WalkAnimations = new AnimationSet("move_m@casual");
     CrouchAnimations = new AnimationSet("move_crouch");
     CurrentAnimation = (int)Shared.RemotePlayerAnimations.StandStill;
     LastRunToCord = Vector3.Zero;
     LastWalkToCord = Vector3.Zero;
     Initialized = true;
 }
        public AnimationComponent(AnimatedTexture animatedTexture)
        {
            _animatedTexture      = animatedTexture;
            _previousState        = AnimationState.None;
            _currentAnimationSet  = _animatedTexture.AnimationSets[AnimationState.IdleRight];
            _frameSelector.Width  = _animatedTexture.FrameWidth;
            _frameSelector.Height = _animatedTexture.FrameHeight;

            _frameTicksLeft = 0;
        }
Esempio n. 11
0
        private AnimationSet AnimateTinyEllipse(double ellipseX, double ellipseY)
        {
            double tinyWidth    = TinyCanvas.Width;
            double tinyHeight   = TinyCanvas.Height;
            double tinyElRadius = TinyEllipse.Width / 2;

            AnimationSet anim = TinyEllipse.Scale((float)1.5, (float)1.5, (float)tinyElRadius, (float)tinyElRadius, 100).Then().Scale(1, 1, (float)tinyElRadius, (float)tinyElRadius, 100).Then().Offset(offsetX: (float)((ellipseX * tinyWidth - tinyElRadius) * 0.9), offsetY: (float)((ellipseY * tinyHeight - tinyElRadius) * 0.9), duration: 800, easingType: EasingType.Quadratic);

            return(anim);
        }
Esempio n. 12
0
    public Baddie()
    {
        X = (int)(Utils.randomNumber() * 1300.0);
        Y = (int)(Utils.randomNumber() * 200.0);
        FramesPerShot = 20;

        Animation = new AnimationSet(@"baddie\baddie.xml");
        Animation.Speed = 2;
        Animation.AutoAnimate("normal", 0);
    }
Esempio n. 13
0
    public Baddie()
    {
        X             = (int)(Utils.randomNumber() * 1300.0);
        Y             = (int)(Utils.randomNumber() * 200.0);
        FramesPerShot = 20;

        Animation       = new AnimationSet(@"baddie\baddie.xml");
        Animation.Speed = 2;
        Animation.AutoAnimate("normal", 0);
    }
Esempio n. 14
0
        public static AABB AsAABB(this AnimationSet animationSet, Position position, bool facingLeft)
        {
            // TODO: Stop assuming a height, and get a real AABB from the heightmap (requires Heightmap cache its own AABB)
            var       heightmapView = new HeightmapView(animationSet.Heightmap, position, facingLeft);
            var       heightmapXZ   = heightmapView.Bounds;
            const int guessHeight   = 50;
            var       aabb          = new AABB(heightmapXZ.Left, heightmapXZ.Right - 1, position.Y, position.Y + guessHeight, heightmapXZ.Y, heightmapXZ.Y + heightmapXZ.Height - 1);

            return(aabb);
        }
 public PedAnimationManager(StreamedPed ped)
 {
     this.ped             = ped;
     currentAnimation     = PedAnimations.StandStill;
     animset              = new AnimationSet("move_m@casual");
     animset2             = new AnimationSet("gun@ak47");
     lastRunToCoord       = Vector3.Zero;
     lastWalkToCoord      = Vector3.Zero;
     lastAnimationStarted = DateTime.Now;
 }
Esempio n. 16
0
 public void ReplaceDamageAnimation(AnimationSet targetSet)
 {
     if (targetSet == null)
     {
         return;
     }
     clipOverrides["Leo_damage"]      = targetSet.rightClip;
     clipOverrides["Leo_damage_left"] = targetSet.leftClip;
     userAnimOverride.ApplyOverrides(clipOverrides);
 }
Esempio n. 17
0
        }   // end of PuckChassis PostCollisionTestUpdate()

        public override void SetLoopedAnimationWeights(AnimationSet anims, Movement movement, DesiredMovement desiredMovement)
        {
            float forward = movement.Speed / MaxSpeed;

            anims.IdleWeight      = 1.0f - forward;
            anims.ForwardWeight   = forward;
            anims.BackwardsWeight = 0.0f;
            anims.RightWeight     = 0.0f;
            anims.LeftWeight      = 0.0f;
        }   // end of SetLoopedAnimationWeights()
Esempio n. 18
0
        public override void OnStart()
        {
            mErrorInAnim  = this.CreateExitAnimation();
            mErrorXInAnim = (AnimationSet)AnimationUtils.LoadAnimation(this.Context, Resource.Animation.error_x_in);

            this.mErrorX = (ImageView)this.ContentView.FindViewById(Resource.Id.error_top_x);

            this.ContentView.StartAnimation(this.mErrorInAnim);
            this.mErrorX.StartAnimation(this.mErrorXInAnim);
        }
Esempio n. 19
0
 public Actor(QuickGameScene scene, TextureInfo texture)
 {
     Scene    = scene;
     Layer    = scene.SolidLayer;
     Position = new Rectangle();
     Sprite   = new Sprite(texture);
     scene.SolidLayer.AddObject(this);
     Animations = new AnimationSet(this);
     scene.AddObject(Animations);
 }
Esempio n. 20
0
 public RemotePlayerAnimationManager(RemotePlayer Player)
 {
     this.Player      = Player;
     WalkAnimations   = new AnimationSet("move_m@casual");
     CrouchAnimations = new AnimationSet("move_crouch");
     CurrentAnimation = (int)Shared.RemotePlayerAnimations.StandStill;
     LastRunToCord    = Vector3.Zero;
     LastWalkToCord   = Vector3.Zero;
     Initialized      = true;
 }
Esempio n. 21
0
 public CharacterPhysicsInfo(AnimationSet animationSet, object owner)
 {
     // TODO: BUG: This does not take into account facing direction!!
     // TODO: Consider putting this as configurable data on AnimationSet (eg: crates with different CP vs solid physics)
     this.startX             = animationSet.physicsStartX;
     this.endX               = animationSet.physicsEndX;
     this.height             = animationSet.physicsHeight;
     this.stairStepMaxHeight = CharacterPhysics.globalStairStepMaxHeight;
     this.owner              = owner;
 }
Esempio n. 22
0
        /// <summary>
        /// Explodes the specified view.
        /// </summary>
        /// <param name="view">The view.</param>
        /// <param name="duration">The duration of the explosion.</param>
        /// <param name="onHidden">The callback that is invoked when the view is no longer visible.</param>
        public void Explode(View view, long duration, Action onHidden)
        {
            const float vibrateAmount     = 0.05f;
            var         preDuration       = (long)(duration * 0.25f);
            var         explosionDuration = (long)(duration * 0.75f);
            var         startDelay        = (long)(duration * 0.15f);

            // get the bounds
            var r = new Rect();

            view.GetGlobalVisibleRect(r);
            var location = new int[2];

            GetLocationOnScreen(location);
            r.Offset(-location[0], -location[1]);
            r.Inset(-ExpansionLimit, -ExpansionLimit);

            var set = new AnimationSet(true);

            // vibrate
            var vibrate = new VibrateAnimation(view.Width * vibrateAmount, view.Height * vibrateAmount);

            vibrate.Duration = preDuration;
            set.AddAnimation(vibrate);

            // implode
            var alpha = new AlphaAnimation(1.0f, 0.0f);

            alpha.Duration    = preDuration;
            alpha.StartOffset = startDelay;
            set.AddAnimation(alpha);
            var scale = new ScaleAnimation(
                1.0f, 0.0f,
                1.0f, 0.0f,
                Dimension.RelativeToSelf, 0.5f,
                Dimension.RelativeToSelf, 0.5f);

            scale.Duration    = preDuration;
            scale.StartOffset = startDelay;
            set.AddAnimation(scale);

            // apply on complete
            set.AnimationEnd += delegate
            {
                view.Visibility = ViewStates.Invisible;
                if (onHidden != null)
                {
                    onHidden();
                }
            };
            view.StartAnimation(set);

            // explode
            Explode(Utils.CreateBitmapFromView(view), r, startDelay, explosionDuration);
        }
Esempio n. 23
0
        private static AnimationSet <CharacterImasMotionAsset> LoadDanceLegacy([NotNull] string filePath, int songPosition, out int suggestedPosition)
        {
            CharacterImasMotionAsset dan = null, apa = null, apg = null;

            var danComp = $"{songPosition:00}_dan.imo";
            var apaComp = $"{songPosition:00}_apa.imo";
            var apgComp = $"{songPosition:00}_apg.imo";

            var manager = new AssetsManager();

            manager.LoadFiles(filePath);

            var ser = new ScriptableObjectSerializer();

            foreach (var assetFile in manager.assetsFileList)
            {
                foreach (var obj in assetFile.Objects)
                {
                    if (obj.type != ClassIDType.MonoBehaviour)
                    {
                        continue;
                    }

                    var behaviour = obj as MonoBehaviour;

                    if (behaviour == null)
                    {
                        throw new ArgumentException("An object serialized as MonoBehaviour is actually not a MonoBehaviour.");
                    }

                    // Can't use EndsWith() here: some bundles have ".asset" postfixes (alstar_01.imo.unity3d: _apa.imo, _dan_imo.asset, _apg.imo.asset)
                    if (behaviour.m_Name.Contains(danComp))
                    {
                        dan = ser.Deserialize <CharacterImasMotionAsset>(behaviour);
                    }
                    else if (behaviour.m_Name.Contains(apaComp))
                    {
                        apa = ser.Deserialize <CharacterImasMotionAsset>(behaviour);
                    }
                    else if (behaviour.m_Name.Contains(apgComp))
                    {
                        apg = ser.Deserialize <CharacterImasMotionAsset>(behaviour);
                    }

                    if (dan != null && apa != null && apg != null)
                    {
                        break;
                    }
                }
            }

            suggestedPosition = GetSuggestedDancePosition(manager);

            return(AnimationSet.Create(dan, apa, apg));
        }
Esempio n. 24
0
        public static AnimationSet <CharacterImasMotionAsset> LoadCamera([NotNull] string filePath)
        {
            CharacterImasMotionAsset cam = null, apa = null, apg = null;

            const string defCamEnds         = "_cam.imo";
            const string apaCamEnds         = "_apa.imo";
            const string apgCamEnds         = "_apg.imo";
            const string apaPortraitCamEnds = "_tate_apa.imo";
            const string apgPortraitCamEnds = "_tate_apg.imo";

            var manager = new AssetsManager();

            manager.LoadFiles(filePath);

            var ser = new ScriptableObjectSerializer();

            foreach (var assetFile in manager.assetsFileList)
            {
                foreach (var obj in assetFile.Objects)
                {
                    if (obj.type != ClassIDType.MonoBehaviour)
                    {
                        continue;
                    }

                    var behaviour = obj as MonoBehaviour;

                    if (behaviour == null)
                    {
                        throw new ArgumentException("An object serialized as MonoBehaviour is actually not a MonoBehaviour.");
                    }

                    if (behaviour.m_Name.EndsWith(defCamEnds))
                    {
                        cam = ser.Deserialize <CharacterImasMotionAsset>(behaviour);
                    }
                    else if (behaviour.m_Name.EndsWith(apaCamEnds) && !behaviour.m_Name.EndsWith(apaPortraitCamEnds))
                    {
                        apa = ser.Deserialize <CharacterImasMotionAsset>(behaviour);
                    }
                    else if (behaviour.m_Name.EndsWith(apgCamEnds) && !behaviour.m_Name.EndsWith(apgPortraitCamEnds))
                    {
                        apg = ser.Deserialize <CharacterImasMotionAsset>(behaviour);
                    }

                    if (cam != null && apa != null && apg != null)
                    {
                        break;
                    }
                }
            }

            return(AnimationSet.Create(cam, apa, apg));
        }
Esempio n. 25
0
        private AnimationSet AnimateChaosEllipse(double ellipseX, double ellipseY)
        {
            double width    = ChaosCanvas.Width;
            double height   = ChaosCanvas.Height;
            double ElRadius = ChaosEllipse.Width / 2;

            // Animations are hardcoded at 1000 ms now - so the durations need to add up to that
            AnimationSet anim = ChaosShadow.Scale((float)1.5, (float)1.5, (float)ElRadius, (float)ElRadius, 100).Then().Scale(1, 1, (float)ElRadius, (float)ElRadius, 100).Then().Offset(offsetX: (float)((ellipseX * width) - ElRadius), offsetY: (float)((ellipseY * height) - ElRadius), duration: 800, easingType: EasingType.Quadratic);

            return(anim);
        }
Esempio n. 26
0
 public Animator(IScenePresence sp)
 {
     m_scenePresence = sp;
     IConfig animationConfig = sp.Scene.Config.Configs["Animations"];
     if (animationConfig != null)
     {
         SLOWFLY_DELAY = animationConfig.GetInt("SlowFlyDelay", SLOWFLY_DELAY);
         m_useSplatAnimation = animationConfig.GetBoolean("enableSplatAnimation", m_useSplatAnimation);
     }
     //This step makes sure that we don't waste almost 2.5! seconds on incoming agents
     m_animations = new AnimationSet(DefaultAnimations);
 }
Esempio n. 27
0
 public void ReplaceIdleAnimationSet(AnimationSet targetSet)
 {
     if (targetSet == null)
     {
         return;
     }
     clipOverrides["idle_up"]    = targetSet.upClip;
     clipOverrides["idle_down"]  = targetSet.downClip;
     clipOverrides["idle_left"]  = targetSet.leftClip;
     clipOverrides["idle_right"] = targetSet.rightClip;
     userAnimOverride.ApplyOverrides(clipOverrides);
 }
Esempio n. 28
0
        public static int GetDistanceSquaredToLocalPlayer(AnimationSet animationSet, Position position, bool facingLeft, IGameState gameState, int localPlayerBits)
        {
            int bestDistanceSquared = Int32.MaxValue;

            if (animationSet != null && animationSet.Heightmap != null) // Sound source has some (spatial) volume
            {
                var       heightmapView = new HeightmapView(animationSet.Heightmap, position, facingLeft);
                Rectangle heightmapXZ   = heightmapView.Bounds;

                // TODO: Stop assuming a height, and get a real AABB from the heightmap (requires Heightmap cache its own AABB)
                const int guessHeight   = 50;
                AABB      heightmapAABB = new AABB(heightmapXZ.Left, heightmapXZ.Right - 1,
                                                   position.Y, position.Y + guessHeight, heightmapXZ.Y, heightmapXZ.Y + heightmapXZ.Height - 1);


                for (int i = 0; i < gameState.MaxPlayers; i++) // For each possible player
                {
                    if (((1 << i) & localPlayerBits) != 0)     // This player is interactive locally
                    {
                        var playerPosition = gameState.GetPlayerPosition(i);
                        if (playerPosition != null)
                        {
                            int distanceSquared = heightmapAABB.DistanceSquaredTo(playerPosition.Value);
                            if (distanceSquared < bestDistanceSquared)
                            {
                                bestDistanceSquared = distanceSquared;
                            }
                        }
                    }
                }
            }
            else // Sound source is a point source
            {
                for (int i = 0; i < gameState.MaxPlayers; i++) // For each possible player
                {
                    if (((1 << i) & localPlayerBits) != 0) // This player is interactive locally
                    {
                        var playerPosition = gameState.GetPlayerPosition(i);
                        if (playerPosition != null)
                        {
                            int distanceSquared = Position.DistanceSquared(position, playerPosition.Value);
                            if (distanceSquared < bestDistanceSquared)
                            {
                                bestDistanceSquared = distanceSquared;
                            }
                        }
                    }
                }
            }

            return(bestDistanceSquared);
        }
    public static string[] getAnimationNames(int animation)
    {
        AnimationSet animationset = list.animationsets[animation];

        string[] names = new string[animationset.animations.Length];
        int      i     = 0;

        foreach (Animation a in animationset.animations)
        {
            names[i++] = a.name;
        }
        return(names);
    }
Esempio n. 30
0
        /// <summary>
        /// Initializes this component.
        /// </summary>
        /// <param name="animationSet">A set of the three animations (in, out and ping pong)
        /// to assign to this animator.</param>
        /// <param name="animationObserver">An observer that will be notified about animation
        /// events from this animator.</param>
        public void Init(AnimationSet <T, U, V> animationSet, IAnimationObserver animationObserver)
        {
            initializedFromInit = true;

            inAnimation       = animationSet.InAnimation;
            outAnimation      = animationSet.OutAnimation;
            pingPongAnimation = animationSet.PingPongAnimation;

            if (animationObserver != null)
            {
                this.animationObserver = animationObserver;
            }
        }
        public Animator(IScenePresence sp)
        {
            m_scenePresence = sp;
            IConfig animationConfig = sp.Scene.Config.Configs["Animations"];

            if (animationConfig != null)
            {
                SLOWFLY_DELAY       = animationConfig.GetInt("SlowFlyDelay", SLOWFLY_DELAY);
                m_useSplatAnimation = animationConfig.GetBoolean("enableSplatAnimation", m_useSplatAnimation);
            }
            //This step makes sure that we don't waste almost 2.5! seconds on incoming agents
            m_animations = new AnimationSet(DefaultAnimations);
        }
Esempio n. 32
0
        private void SplashPage_Loaded(object sender, RoutedEventArgs e)
        {
            PositionImage();

            Window.Current.SizeChanged += Current_SizeChanged;

            LogoEffectAnim            = LogoImage.Offset(0, -64, 250, 100);
            LogoEffectAnim.Completed += (_, s) =>
            {
                LoadingUI.Fade(1.0f, 250).Start();
            };
            LogoEffectAnim.Start();
        }
Esempio n. 33
0
        public static AnimationSet getOutAnimation(Context context)
        {
            AnimationSet   _out  = new AnimationSet(context, null);
            AlphaAnimation alpha = new AlphaAnimation(1.0f, 0.0f);

            alpha.Duration = 150;
            ScaleAnimation scale = new ScaleAnimation(1.0f, 0.6f, 1.0f, 0.6f, Dimension.RelativeToSelf, 0.5f, Dimension.RelativeToSelf, 0.5f);

            scale.Duration = 150;
            _out.AddAnimation(alpha);
            _out.AddAnimation(scale);
            return(_out);
        }
Esempio n. 34
0
    void updateAnimationSet()
    {
        AnimationSet anim = animater.animationSet;

        if (anim != null)
        {
            renderer.material = anim.getTileset() == null? null : anim.getTileset().getMaterial();
        }
        else
        {
            renderer.material = defaultMaterial;
        }
    }
        public static void playClickAnim(View targetView)
        {
            float              SCALE_FACTOR  = 0.3f;
            AnimationSet       animSet       = new AnimationSet(true);
            TranslateAnimation translateAnim = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, -SCALE_FACTOR / 2, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, -SCALE_FACTOR / 2);

            animSet.addAnimation(translateAnim);
            ScaleAnimation anim = new ScaleAnimation(1f, 1f + SCALE_FACTOR, 1f, 1f + SCALE_FACTOR);

            animSet.addAnimation(anim);
            animSet.Interpolator = new AccelerateDecelerateInterpolator();
            animSet.Duration     = 150;
            targetView.startAnimation(animSet);
        }
Esempio n. 36
0
        public DummyEnemy(List<DrawableObjectAbstract> pipeline, Vector2 pos)
            : base(pipeline, new CharacterHealth(), new CharacterAmmo(), new CharacterWeapon(), "dummy", null, null, FRAMELENGTHMODIFIER, Vector2.Zero, pos, new Vector2(1.0f, 0.0f), 0.49f)
        {
            AI_ = new DummyAI(this);

            List<GameTexture> animationTextures = new List<GameTexture>();
            animationTextures.Add(TextureMap.getInstance().getTexture("basic_enemy_walk"));
            animations_ = new AnimationSet(animationTextures);
            movingToward_ = new Vector2(150.0f, 260.0f);
            lookingAt_ = new Vector2(250.0f, 60.0f);
            atLocation_ = false;
            collisionDetector_ = null;
            radius_ = RADIUS;
            Allegiance_ = 2;
            height_ = new Height(true, false);
            boundsPolygon_ = new CircularConvexPolygon(radius_, position_);

            AnimationInterface run = new LoopAnimation(TextureMap.getInstance().getTexture("basic_enemy_walk"), frameLengthModifier_, depth_, boundsPolygon_);
            AnimationInterface runTo = new LoopAnimation(TextureMap.getInstance().getTexture("basic_enemy_walk"), frameLengthModifier_, depth_, boundsPolygon_);
            AnimationInterface rest = new LoopAnimation(TextureMap.getInstance().getTexture("GreenPlayer_Blank"), frameLengthModifier_, depth_, boundsPolygon_);
            AnimationInterface rest2 = new LoopAnimation(TextureMap.getInstance().getTexture("basic_enemy_walk"), frameLengthModifier_, depth_, boundsPolygon_);
            AnimationInterface[] restAnims = new AnimationInterface[2];
            restAnims[0] = rest;
            restAnims[1] = rest2;
            AnimationInterface[] shoot = new AnimationInterface[1];
            shoot[0] = rest;

            List<string> levels = new List<string>();
            levels.Add("look");
            levels.Add("lower");

            Dictionary<string, Dictionary<string, CharacterActionInterface>> actions = new Dictionary<string, Dictionary<string, CharacterActionInterface>>();
            actions.Add("default", new Dictionary<string, CharacterActionInterface>());
            actions["default"].Add("move", new CharacterRunAction(this, run, 2.0f, "lower"));
            actions["default"].Add("moveTo", new CharacterRunToAction(this, runTo, 2.0f, "lower"));
            actions["default"].Add("rest", new CharacterStayStillAction(this, restAnims, levels, "lower", "lower"));
            actions["default"].Add("crouch", new NoAction("lower"));
            actions["default"].Add("cover", new NoAction("lower"));
            actions["default"].Add("shoot", new CharacterShootAction(this, shoot, "lower", 0));
            actions["default"].Add("look", new CharacterLookAction(this, "look"));
            actions["default"].Add("lookAt", new CharacterLookAtAction(this, "look"));
            actions["default"].Add("reload", new NoAction("lower"));
            actions["default"].Add("throw", new NoAction("lower"));
            actuator_ = new MultiLevelActuator(actions, levels, this, "default", "rest", "lower", "lower");

            currentDrawColor_ = Color.White;
            health_.update(15);

            Weapon_ = new DroneGun(pipeline_, this, new Vector2(GUNHANDLEX, GUNHANDLEY));
        }
Esempio n. 37
0
    public PC(int racei)
    {
        //TODO Clean
        X = 225;
        Y = 500;
        Race = (RaceUtils.Race)racei;
        switch (Race)
        {
            case RaceUtils.Race.Pirate:
                Anim = new AnimationSet(@"creatures\pc\pirate\anim.xml");
                Stats = new StatSet(@"creatures\pc\pirate\stat.xml");
                Size = 12;
                Name = "NANCY";
                break;
            case RaceUtils.Race.Dragon:
                Anim = new AnimationSet(@"creatures\pc\dragon\anim.xml");
                Stats = new StatSet(@"creatures\pc\dragon\stat.xml");
                Size = 16;
                Name = "ALESSIA";
                break;
            case RaceUtils.Race.Meximage:
                Anim = new AnimationSet(@"creatures\pc\meximage\anim.xml");
                Stats = new StatSet(@"creatures\pc\meximage\stat.xml");
                Size = 14;
                Name = "JESUS";
                break;
            case RaceUtils.Race.Ninja:
                Anim = new AnimationSet(@"creatures\pc\ninja\anim.xml");
                Stats = new StatSet(@"creatures\pc\ninja\stat.xml");
                Size = 12;
                Name = "BIP";
                break;

        }

        //fix!
        Anim.Speed = 9;
        HP = Stats.Vit();
        MP = Stats.Aff();
        FA = MaxFatigue;
    }
        public int AddAnimationSet(AnimationSet animationSet)
        {
            int id;
            if (animationFreeIds.Count > 0)
            {
                id = animationFreeIds[0];
                animationFreeIds.RemoveAt(0);
            }
            else
            {
                id = animationSets.Count;
            }

            animationSets.Add(id, animationSet);

            foreach (var pair in renderObjects)
            {
                RegisterAnimationSet(animationSet, id, pair.Value);
            }

            Render();
            return id;
        }
 /// <summary>
 /// Create a NonPlayableCharacter with the specified health, ammo, and weapon objects, plus the given name.
 /// Also, specify the AnimationSet, frameLengthModifier, velocity, position, direction,
 /// and depth of the character.
 /// </summary>
 /// <param name="pipeline">List of objects from which the object should be drawn.</param>
 /// <param name="health">CharacterStatusElement for health</param>
 /// <param name="ammo">CharacterStatusElement for ammo</param>
 /// <param name="weapon">CharacterStatusElement for the current weapon</param>
 /// <param name="name">The character's name</param>
 /// <param name="detector">Collision detector with which this object should register.</param>
 /// <param name="animations">AnimationSet containing all animations for this object</param>
 /// <param name="frameLengthModifier">Float representing the ratio of frames in an animation to movement along the screen</param>
 /// <param name="velocity">Vector of velocity, representing both direction of movement and magnitude</param>
 /// <param name="position">Position of object relative to the top left corner</param>
 /// <param name="direction">Vector representing the direction of the object</param>
 /// <param name="depth">Depth the object is to be drawn to</param>
 public NonPlayableCharacterAbstract(List<DrawableObjectAbstract> pipeline, CharacterHealth health, CharacterAmmo ammo, CharacterWeapon weapon, string name, CollisionDetectorInterface detector, AnimationSet animations, float frameLengthModifier, Vector2 velocity, Vector2 position, Vector2 direction, float depth)
     : base(pipeline, health, ammo, weapon, name, detector, animations, frameLengthModifier, velocity, position, direction, depth)
 {
 }
Esempio n. 40
0
        /// <summary>
        /// Compare the value (not "reference") of the given property. 
        /// Assumption: the caller has already checked if PhysActor exists
        /// if there are physics properties updated.
        /// If the value maintained here is different from that in SP data,
        /// synchronize the two: 
        /// (1) if the cached value has a timestamp newer than lastUpdateByLocalTS 
        /// overwrite the SP's property with the cached value (effectively 
        /// undoing the local write operation that just happened). 
        /// (2) otherwise, copy SP's data and update timestamp and syncID 
        /// as indicated by "lastUpdateByLocalTS" and "syncID".
        /// </summary>
        /// <param name="sp"></param>
        /// <param name="property"></param>
        /// <param name="lastUpdateByLocalTS"></param>
        /// <param name="syncID"></param>
        /// <returns>Return true if the property's value maintained in this 
        /// RegionSyncModule is replaced by SP's data.</returns>
        private bool CompareValue_UpdateByLocal(ScenePresence sp, SyncableProperties.Type property, long lastUpdateByLocalTS, string syncID)
        {
            //DebugLog.WarnFormat("[SYNC INFO PRESENCE] CompareValue_UpdateByLocal: Updating property {0} on sp {1}", property.ToString(), sp.UUID);
            // Check to see if this property is in the sync cache for this object.
            // If not, add it and initialize value to value in ScenePresence.
            bool ret = false;

            SyncedProperty syncedProperty;
            CurrentlySyncedProperties.TryGetValue(property, out syncedProperty);

            // If synced property is not in cache, add it now
            if (syncedProperty == null)
            {
                Object initValue = GetPropertyValue(sp, property);
                if (initValue != null)
                {
                    CurrentlySyncedProperties.Add(property, new SyncedProperty(property, initValue, lastUpdateByLocalTS, syncID));
                    ret = true;
                }
                return ret;
            }

            // First, check if the value maintained here is different from that in SP's.
            // If different, next check if the timestamp in SyncInfo is newer than lastUpdateByLocalTS;
            // if so (although ideally should not happen, but due to things likc clock not so perfectly
            // sync'ed, it might happen), overwrite SP's value with what's maintained
            // in SyncInfo; otherwise, copy SP's data to SyncInfo.
            Object value = GetPropertyValue(sp, property);

            // If both null, no update needed
            if (syncedProperty.LastUpdateValue == null && value == null)
                return false;

            switch (property)
            {
                default:
                    // If one is null and the other is not, or if the references are different, the property was changed.
                    // This will perform a value comparison for strings in C#. We could use String.Clone instead for string properties.
                    if ((value == null && syncedProperty.LastUpdateValue != null) ||
                        (value != null && syncedProperty.LastUpdateValue == null) ||
                        (!value.Equals(syncedProperty.LastUpdateValue)))
                    {
                        if (value != null)
                        {
                            // Some values, even if they are not 'equal', might be close enough to be equal.
                            // Note that the 'Equals()' above will most always return 'false' for lists and OSDMaps
                            //     since they are probably not the same object.
                            // Returning a 'false' here means the values don't need any updating (they are equal enough).
                            switch (property)
                            {
                                case SyncableProperties.Type.AvatarAppearance:
                                    String stringValue = OSDParser.SerializeJsonString((OSDMap)value);
                                    String lastStringValue = OSDParser.SerializeJsonString((OSDMap)syncedProperty.LastUpdateValue);
                                    if (stringValue == lastStringValue)
                                        return false;
                                    break;
                                case SyncableProperties.Type.Animations:
                                    if (syncedProperty.LastUpdateValue != null)
                                    {
                                        AnimationSet lastAnimations = new AnimationSet((OSDArray)syncedProperty.LastUpdateValue);

                                        // Get the home region for this presence (the client manager the presence is connected to).
                                        string cachedRealRegionName = (string)(CurrentlySyncedProperties[SyncableProperties.Type.RealRegion].LastUpdateValue);
                                        if (cachedRealRegionName != Scene.Name && sp.Animator.Animations.ToArray().Length == 0)
                                        {
                                            // If this is not the originating region for this presence and there is no additional
                                            //   animations being added, this simulator does not change the animation.
                                            // THIS IS A HORRIBLE KLUDGE. FIGURE OUT THE REAL SOLUTION!!
                                            // The problem is that animations are changed by every simulator (setting default
                                            //   sit and stand when parentID changes) and the updates conflict/override the real
                                            //   settings (like a scripted sit animation).
                                            // DebugLog.DebugFormat("{0} CompareValue_UpdateByLocal. Not home sim or no anim change. spID={1}, homeSim={2}, thisSim={3}, anims={4}",
                                            //                     LogHeader, sp.LocalId, cachedRealRegionName, Scene.Name, sp.Animator.Animations.ToArray().Length); // DEBUG DEBUG

                                            return false;
                                        }

                                        if (lastAnimations.Equals(sp.Animator.Animations))
                                        {
                                            // DebugLog.DebugFormat("{0} CompareValue_UpdateByLocal. Equal anims. spID={1}, sp.Anim={2}, lastAnim={3}",
                                            //                     LogHeader, sp.LocalId, sp.Animator.Animations, lastAnimations); // DEBUG DEBUG
                                            return false;
                                        }
                                        else
                                        {
                                            // If locally storing a new value of the animation, don't check for the time.
                                            // DebugLog.DebugFormat("{0} CompareValue_UpdateByLocal. Not equal anims. spID={1}, sp.Anim={2}, lastAnim={3}",
                                            //                     LogHeader, sp.LocalId, sp.Animator.Animations, lastAnimations); // DEBUG DEBUG
                                            syncedProperty.UpdateSyncInfoByLocal(lastUpdateByLocalTS, syncID, value);
                                            return true;
                                        }
                                    }
                                    break;
                                case SyncableProperties.Type.Velocity:
                                case SyncableProperties.Type.PA_Velocity:
                                case SyncableProperties.Type.PA_TargetVelocity:
                                case SyncableProperties.Type.RotationalVelocity:
                                case SyncableProperties.Type.AngularVelocity:
                                    {
                                        Vector3 partVal = (Vector3)value;
                                        Vector3 lastVal = (Vector3)syncedProperty.LastUpdateValue;
                                        // If velocity difference is small but not zero, don't update
                                        if (partVal.ApproxEquals(lastVal, VELOCITY_TOLERANCE) && !partVal.Equals(Vector3.Zero))
                                            return false;
                                        break;
                                    }
                                case SyncableProperties.Type.RotationOffset:
                                case SyncableProperties.Type.Orientation:
                                    {
                                        Quaternion partVal = (Quaternion)value;
                                        Quaternion lastVal = (Quaternion)syncedProperty.LastUpdateValue;
                                        if (partVal.ApproxEquals(lastVal, ROTATION_TOLERANCE))
                                            return false;
                                        break;
                                    }
                                case SyncableProperties.Type.OffsetPosition:
                                case SyncableProperties.Type.AbsolutePosition:
                                case SyncableProperties.Type.Position:
                                case SyncableProperties.Type.GroupPosition:
                                    {
                                        Vector3 partVal = (Vector3)value;
                                        Vector3 lastVal = (Vector3)syncedProperty.LastUpdateValue;
                                        if (partVal.ApproxEquals(lastVal, POSITION_TOLERANCE))
                                            return false;
                                        break;
                                    }
                            }
                        }

                        // If we get here, the values are not equal and we need to update the cached value if the
                        //     new value is timestamp newer.
                        if (lastUpdateByLocalTS >= syncedProperty.LastUpdateTimeStamp)
                        {
                            // DebugLog.DebugFormat("{0} CompareValue_UpdateByLocal (property={1}): TS >= lastTS (updating SyncInfo)", LogHeader, property);
                            syncedProperty.UpdateSyncInfoByLocal(lastUpdateByLocalTS, syncID, value);
                            return true;
                        }
                    }
                    break;
            }
            return false;
        }
Esempio n. 41
0
        // Received a list of animations for this avatar. Check to see if animation list has
        //   changed and update the scene presence.
        // Doing any updates to the Animator causes events to be sent out so don't change willy nilly.
        // Changes to the animation set must be done through sp.Animator so the proper side
        //   effects happen and updates are sent out.
        private void UpdateAvatarAnimations(ScenePresence sp, OSDArray pPackedAnimations)
        {
            AnimationSet newSet = new AnimationSet(pPackedAnimations);
            AnimationSet currentSet = sp.Animator.Animations;
            if (!newSet.Equals(currentSet))
            {
                // DebugLog.DebugFormat("{0} UpdateAvatarAnimations. spID={1},CurrAnims={2},NewAnims={3}",
                //                          LogHeader, sp.LocalId, currentSet, newSet); // DEBUG DEBUG

                // If something changed, stuff the new values in the existing animation collection.
                sp.Animator.Animations.FromOSDArray(pPackedAnimations);
            }
            // Doesn't matter if it changed or not. If someone sends us an animation update, tell any connected client.
            sp.Animator.SendAnimPack();
        }
        public ActuatedMainPlayer(List<DrawableObjectAbstract> pipeline, CollisionDetectorInterface detector, Vector2 position, Vector2 direction)
            : base(pipeline, new CharacterHealth(), new CharacterAmmo(), new CharacterWeapon(), "Woger Ru", detector, null, 8.0f, Vector2.Zero, position, direction, 0.5f)
        {
            /*
            boundsPolygonHigh_ = new ConvexPolygon(BOUNDSPOINTSHIGH, Vector2.Zero);
            boundsPolygonHigh_.rotate(direction_, position_);

            boundsPolygonLow_ = new ConvexPolygon(BOUNDSPOINTSLOW, Vector2.Zero);
            boundsPolygonLow_.rotate(direction_, position_);

            boundsPolygonLowCrouch_ = new ConvexPolygon(BOUNDSPOINTSLOWCROUCH, Vector2.Zero);
            boundsPolygonLowCrouch_.rotate(direction_, position_);
            */
            Allegiance_ = 1;

            List<string> levels = new List<string>();
            levels.Add("transition");
            levels.Add("turning");
            levels.Add("lower");
            levels.Add("upper");

            List<Vector2> boundsPointsLow = BOUNDSPOINTSLOW;
            List<Vector2> boundsPointsHigh = BOUNDSPOINTSHIGH;

            AnimationInterface[] restAnimations = new AnimationInterface[8];
            restAnimations[0] = new LoopAnimation(TextureMap.fetchTexture("GreenPlayer_Blank"), frameLengthModifier_, depth_ - 0.02f, boundsPointsLow);
            restAnimations[1] = restAnimations[0];
            restAnimations[2] = restAnimations[0];
            restAnimations[3] = restAnimations[0];
            restAnimations[4] = new LoopAnimation(TextureMap.fetchTexture("GreenPlayer_Walk_Stand"), frameLengthModifier_, depth_ - 0.01f, boundsPointsLow);
            restAnimations[5] = restAnimations[4];
            restAnimations[6] = new LoopAnimation(TextureMap.fetchTexture("GreenPlayer_UpperBody_Pistol_Stand"), frameLengthModifier_, depth_, boundsPointsHigh);
            restAnimations[7] = new LoopAnimation(TextureMap.fetchTexture("GreenPlayer_UpperBody_Rifle_Stand"), frameLengthModifier_, depth_, boundsPointsHigh);

            AnimationInterface[] crouchRestAnimations = new AnimationInterface[8];
            crouchRestAnimations[0] = new LoopAnimation(TextureMap.fetchTexture("GreenPlayer_Blank"), frameLengthModifier_, depth_ - 0.02f, BOUNDSPOINTSLOWCROUCH);
            crouchRestAnimations[1] = crouchRestAnimations[0];
            crouchRestAnimations[2] = crouchRestAnimations[0];
            crouchRestAnimations[3] = crouchRestAnimations[0];
            crouchRestAnimations[4] = new LoopAnimation(TextureMap.fetchTexture("GreenPlayer_Crouch_Stationary"), frameLengthModifier_, depth_ - 0.01f, BOUNDSPOINTSLOWCROUCH);
            crouchRestAnimations[5] = crouchRestAnimations[4];
            crouchRestAnimations[6] = new LoopAnimation(TextureMap.fetchTexture("GreenPlayer_Pistol_Crouch"), frameLengthModifier_, depth_, BOUNDSPOINTSLOWCROUCH);
            crouchRestAnimations[7] = new LoopAnimation(TextureMap.fetchTexture("GreenPlayer_Rifle_Crouch"), frameLengthModifier_, depth_, BOUNDSPOINTSLOWCROUCH);

            AnimationInterface runAnimation = new LoopAnimation(TextureMap.fetchTexture("GreenPlayer_Walk_Stand"), frameLengthModifier_, depth_ - 0.01f, boundsPointsLow);
            AnimationInterface runToAnimation = new LoopAnimation(TextureMap.fetchTexture("GreenPlayer_Walk_Stand"), frameLengthModifier_, depth_ - 0.01f, boundsPointsLow);
            AnimationInterface coverAnimation = new LoopAnimation(TextureMap.fetchTexture("GreenPlayer_Walk_Stand"), frameLengthModifier_, depth_ - 0.01f, boundsPointsLow);
            AnimationInterface crouchAnimation = new LoopAnimation(TextureMap.fetchTexture("GreenPlayer_Walk_Stand"), frameLengthModifier_, depth_ - 0.01f, boundsPointsLow);

            AnimationInterface crouchedRunAnimation = new LoopAnimation(TextureMap.fetchTexture("GreenPlayer_Walk_Crouch"), frameLengthModifier_, depth_ - 0.01f, BOUNDSPOINTSLOWCROUCH);
            AnimationInterface crouchedRunToAnimation = new LoopAnimation(TextureMap.fetchTexture("GreenPlayer_Walk_Crouch"), frameLengthModifier_, depth_ - 0.01f, BOUNDSPOINTSLOWCROUCH);
            AnimationInterface crouchedCoverAnimation = new LoopAnimation(TextureMap.fetchTexture("GreenPlayer_Walk_Crouch"), frameLengthModifier_, depth_ - 0.01f, BOUNDSPOINTSLOWCROUCH);
            AnimationInterface crouchedCrouchAnimation = new LoopAnimation(TextureMap.fetchTexture("GreenPlayer_Walk_Crouch"), frameLengthModifier_, depth_ - 0.01f, BOUNDSPOINTSLOWCROUCH);

            AnimationInterface[] shootAnimations = new AnimationInterface[2];
            shootAnimations[0] = new NonLoopAnimation(TextureMap.fetchTexture("GreenPlayer_UpperBody_Pistol_Stand"), frameLengthModifier_, depth_, boundsPointsHigh);
            shootAnimations[1] = new NonLoopAnimation(TextureMap.fetchTexture("GreenPlayer_UpperBody_Rifle_Stand"), frameLengthModifier_, depth_, boundsPointsHigh);
            AnimationInterface[] throwGrenadeAnimations = new AnimationInterface[2];
            throwGrenadeAnimations[0] = new NonLoopAnimation(TextureMap.fetchTexture("GreenPlayer_Throw_Stand_Pistol"), frameLengthModifier_, depth_, boundsPointsHigh);
            throwGrenadeAnimations[1] = new NonLoopAnimation(TextureMap.fetchTexture("GreenPlayer_Throw_Stand_Rifle"), frameLengthModifier_, depth_, boundsPointsHigh);
            AnimationInterface[] reloadAnimations = new AnimationInterface[2];
            reloadAnimations[0] = new NonLoopAnimation(TextureMap.fetchTexture("GreenPlayer_Reload_Stand_Pistol"), frameLengthModifier_, depth_, boundsPointsHigh);
            reloadAnimations[1] = new NonLoopAnimation(TextureMap.fetchTexture("GreenPlayer_Reload_Stand_Rifle"), frameLengthModifier_, depth_, boundsPointsHigh);

            AnimationInterface[] crouchedShootAnimations = new AnimationInterface[2];
            crouchedShootAnimations[0] = new NonLoopAnimation(TextureMap.fetchTexture("GreenPlayer_Pistol_Crouch"), frameLengthModifier_, depth_, boundsPointsHigh);
            crouchedShootAnimations[1] = new NonLoopAnimation(TextureMap.fetchTexture("GreenPlayer_Rifle_Crouch"), frameLengthModifier_, depth_, boundsPointsHigh);
            AnimationInterface[] crouchedThrowGrenadeAnimations = new AnimationInterface[2];
            crouchedThrowGrenadeAnimations[0] = new NonLoopAnimation(TextureMap.fetchTexture("GreenPlayer_Throw_Crouch_Pistol"), frameLengthModifier_, depth_, boundsPointsHigh);
            crouchedThrowGrenadeAnimations[1] = new NonLoopAnimation(TextureMap.fetchTexture("GreenPlayer_Throw_Crouch_Rifle"), frameLengthModifier_, depth_, boundsPointsHigh);
            AnimationInterface[] crouchedReloadAnimations = new AnimationInterface[2];
            crouchedReloadAnimations[0] = new NonLoopAnimation(TextureMap.fetchTexture("GreenPlayer_Reload_Crouch_Pistol"), frameLengthModifier_, depth_, boundsPointsHigh);
            crouchedReloadAnimations[1] = new NonLoopAnimation(TextureMap.fetchTexture("GreenPlayer_Reload_Crouch_Rifle"), frameLengthModifier_, depth_, boundsPointsHigh);

            /*
            AnimationInterface run = new LoopAnimation(TextureMap.getInstance().getTexture("GreenPlayer_Walk_Stand"), frameLengthModifier_, depth_);
            AnimationInterface runTo = new LoopAnimation(TextureMap.getInstance().getTexture("GreenPlayer_Walk_Stand"), frameLengthModifier_, depth_);
            AnimationInterface rest = new LoopAnimation(TextureMap.getInstance().getTexture("GreenPlayer_Walk_Stand"), frameLengthModifier_, depth_);
            AnimationInterface crouch = new LoopAnimation(TextureMap.getInstance().getTexture("GreenPlayer_Stand_Rifle_Walk"), frameLengthModifier_, depth_);
            AnimationInterface cover = new LoopAnimation(TextureMap.getInstance().getTexture("GreenPlayer_Stand_Rifle_Walk"), frameLengthModifier_, depth_);
            AnimationInterface crouch_run = new LoopAnimation(TextureMap.getInstance().getTexture("GreenPlayer_Crouch_Rifle_Walk"), frameLengthModifier_, depth_);
            AnimationInterface crouch_runTo = new LoopAnimation(TextureMap.getInstance().getTexture("GreenPlayer_Crouch_Rifle_Walk"), frameLengthModifier_, depth_);
            AnimationInterface crouch_rest = new LoopAnimation(TextureMap.getInstance().getTexture("GreenPlayer_Crouch_Rifle"), frameLengthModifier_, depth_);
            AnimationInterface crouch_crouch = new LoopAnimation(TextureMap.getInstance().getTexture("GreenPlayer_Crouch_Rifle"), frameLengthModifier_, depth_);
            AnimationInterface crouch_cover = new LoopAnimation(TextureMap.getInstance().getTexture("GreenPlayer_Crouch_Rifle_Walk"), frameLengthModifier_, depth_);
            AnimationInterface cover_run = new LoopAnimation(TextureMap.getInstance().getTexture("GreenPlayer_Crouch_Rifle_Walk"), frameLengthModifier_, depth_);
            AnimationInterface cover_runTo = new LoopAnimation(TextureMap.getInstance().getTexture("GreenPlayer_Crouch_Rifle_Walk"), frameLengthModifier_, depth_);
            AnimationInterface cover_rest = new LoopAnimation(TextureMap.getInstance().getTexture("GreenPlayer_Crouch_Rifle"), frameLengthModifier_, depth_);
            AnimationInterface cover_crouch = new LoopAnimation(TextureMap.getInstance().getTexture("GreenPlayer_Crouch_Rifle"), frameLengthModifier_, depth_);
            AnimationInterface cover_cover = new LoopAnimation(TextureMap.getInstance().getTexture("GreenPlayer_Crouch_Rifle_Walk"), frameLengthModifier_, depth_);
            AnimationInterface cover_shoot = new NonLoopAnimation(TextureMap.fetchTexture("GreenPlayer_StandToShoot_Rifle"), 1.0f, depth_);
            */
            Dictionary<string, Dictionary<string, CharacterActionInterface>> actions = new Dictionary<string, Dictionary<string, CharacterActionInterface>>();
            //actions.Add("default", new Dictionary<string, CharacterActionInterface>());
            //actions["default"].Add("move", new CharacterRunAction(this, run, 3.0f));
            //actions["default"].Add("moveTo", new CharacterRunToAction(this, runTo, 3.0f));
            //actions["default"].Add("rest", new CharacterStayStillAction(this, rest));
            actions.Add("crouch", new Dictionary<string, CharacterActionInterface>());
            actions["crouch"].Add("move", new CharacterRunAction(this, crouchedRunAnimation, SPEED, "lower"));
            actions["crouch"].Add("moveTo", new CharacterRunToAction(this, crouchedRunToAnimation, SPEED, "lower"));
            actions["crouch"].Add("rest", new CharacterStayStillAction(this, crouchRestAnimations, levels, "upper", "lower"));
            actions["crouch"].Add("crouch", new CrouchAction(this, crouchedCrouchAnimation, "stand", new Height(true, true), "transition"));
            actions["crouch"].Add("cover", new AttachToCoverAction(this, crouchedCoverAnimation, "cover", new Height(true, false), SPEED, "lower"));
            actions["crouch"].Add("shoot", new CharacterShootAction(this, crouchedShootAnimations, "upper", 0));
            actions["crouch"].Add("throw", new ThrowGrenadeAction(this, crouchedThrowGrenadeAnimations, new Vector2(40.5f, 7.5f), "upper", 4, 10));
            actions["crouch"].Add("look", new CharacterLookAction(this, "turning"));
            actions["crouch"].Add("lookAt", new CharacterLookAtAction(this, "turning"));
            actions["crouch"].Add("reload", new CharacterReloadAction(this, crouchedReloadAnimations, "upper"));
            actions.Add("stand", new Dictionary<string, CharacterActionInterface>());
            actions["stand"].Add("move", new CharacterRunAction(this, runAnimation, SPEED, "lower"));
            actions["stand"].Add("moveTo", new CharacterRunToAction(this, runToAnimation, SPEED, "lower"));
            actions["stand"].Add("rest", new CharacterStayStillAction(this, restAnimations, levels, "upper", "lower"));
            actions["stand"].Add("crouch", new CrouchAction(this, crouchAnimation, "crouch", new Height(true, false), "transition"));
            actions["stand"].Add("cover", new AttachToCoverAction(this, coverAnimation, "cover", new Height(true, false), SPEED, "lower"));
            actions["stand"].Add("shoot", new CharacterShootAction(this, shootAnimations, "upper", 0));
            actions["stand"].Add("throw", new ThrowGrenadeAction(this, throwGrenadeAnimations, new Vector2(30.5f, 7.5f), "upper", 4, 10));
            actions["stand"].Add("look", new CharacterLookAction(this, "turning"));
            actions["stand"].Add("lookAt", new CharacterLookAtAction(this, "turning"));
            actions["stand"].Add("reload", new CharacterReloadAction(this, reloadAnimations, "upper"));
            actions.Add("cover", new Dictionary<string, CharacterActionInterface>());
            actions["cover"].Add("move", new CharacterCoverMoveAction(this, crouchedRunAnimation, SPEED, "lower"));
            actions["cover"].Add("moveTo", new CharacterCoverMoveToAction(this, crouchedRunToAnimation, SPEED, "lower"));
            actions["cover"].Add("rest", new CharacterStayStillAction(this, crouchRestAnimations, levels, "upper", "lower"));
            actions["cover"].Add("crouch", new CrouchAction(this, crouchedCrouchAnimation, "stand", new Height(true, true), "transition"));
            actions["cover"].Add("cover", new DetachFromCoverAction(this, crouchedCoverAnimation, "stand", new Height(true, true), SPEED, "lower"));
            actions["cover"].Add("shoot", new CharacterCoverShootAction(this, crouchedShootAnimations, 0, "upper"));
            actions["cover"].Add("throw", new ThrowGrenadeAction(this, crouchedThrowGrenadeAnimations, new Vector2(40.5f, 7.5f), "upper", 4, 10));
            actions["cover"].Add("look", new CharacterLookAction(this, "turning"));
            actions["cover"].Add("lookAt", new CharacterLookAtAction(this, "turning"));
            actions["cover"].Add("reload", new CharacterReloadAction(this, crouchedReloadAnimations, "upper"));

            actuator_ = new MultiLevelActuator(actions, levels, this, "stand", "rest", "lower", "upper");

            List<GameTexture> anims = new List<GameTexture>();
            anims.Add(TextureMap.getInstance().getTexture("PlayerWalk"));
            animations_ = new AnimationSet(anims);
            if (RADIUS < RADIUSCROUCH)
            {
                radius_ = RADIUSCROUCH;
            }
            else
            {
                radius_ = RADIUS;
            };
            //collisionDetector_ = new SeparatingAxisCollisionDetector();
            collisionDetector_ = detector;
            if (collisionDetector_ != null)
            {
                collisionDetector_.register(this);
            }

            // Give the player his currently active weapon
            Weapon_ = new Pistol(pipeline, this, new Vector2(60f - 37.5f, 33.5f - 37.5f));
            //Weapon_.update();
            //Weapon_ = new Pistol(pipeline, this, new Vector2(60f - 37.5f, 33.5f - 37.5f));

            // Add the other weapons to the character's inventory
            //Inventory_.Weapons_.Enqueue(new MachineGun(pipeline, this, new Vector2(42f - 37.5f, 47f - 37.5f)));
            //Inventory_.Weapons_.Enqueue(new Shotgun(pipeline, this, new Vector2(42f - 37.5f, 47f - 37.5f)));

            height_ = new Height(true, true);
        }
 private void RegisterAnimationSet(AnimationSet animationSet, int id, IRenderObject renderObject)
 {
     AnimationController animationController = renderObject.AnimationController;
     animationController.RegisterAnimationSet(animationSet);
     animationController.SetTrackAnimationSet(id, animationSet);
     animationController.SetTrackWeight(id, 1);
     animationController.SetTrackSpeed(id, 0);
     animationController.SetTrackPosition(id, 0);
     animationController.SetTrackPriority(id, TrackPriority.High);
 }
Esempio n. 44
0
    public void CreateAnimation(string name, int firstFrame, int lastFrame, double animationSpeed)
    {
        AnimationSet ani = new AnimationSet(ref mMaterial, firstFrame, lastFrame, mNumCols, mNumRows, animationSpeed);

        mAniSets[name] = ani;
    }
Esempio n. 45
0
 public ScenePresenceAnimator(ScenePresence sp)
 {
     m_scenePresence = sp;
     //This step makes sure that we don't waste almost 2.5! seconds on incoming agents
     m_animations = new AnimationSet(sp.Scene.DefaultAnimations);
 }
Esempio n. 46
0
        /// <summary>
        /// Call this to initialize a Behaviour with data supplied in a file.
        /// </summary>
        /// <param name="fileName">The file to load from.</param>
        public override void LoadContent(String fileName)
        {
            base.LoadContent(fileName);

            SpriteRenderDefinition def = GameObjectManager.pInstance.pContentManager.Load<SpriteRenderDefinition>(fileName);

            mSpriteFileName = def.mSpriteFileName;
            mTexture = GameObjectManager.pInstance.pContentManager.Load<Texture2D>(mSpriteFileName);

            if (def.mScreenStretchPercentage != null)
            {
                System.Diagnostics.Debug.Assert(def.mAnimationSets == null, "mScreenStretchPercentage is not yet supported for animated sprites.");

                if (def.mScreenStretchPercentage.X >= 0)
                {
                    System.Diagnostics.Debug.Assert(def.mScreenStretchPercentage.X >= 0 && def.mScreenStretchPercentage.X <= 1.0f, "Percentage should be expressed as floating point value from 0 - 1");
                    Single width = CameraManager.pInstance.pScreenViewRect.pDimensions.X;
                    Single initialPercent = mTexture.Width / width;
                    mParentGOH.pScaleX = def.mScreenStretchPercentage.X / initialPercent;
                }
                if (def.mScreenStretchPercentage.Y >= 0)
                {
                    System.Diagnostics.Debug.Assert(def.mScreenStretchPercentage.Y >= 0 && def.mScreenStretchPercentage.Y <= 1.0f, "Percentage should be expressed as floating point value from 0 - 1");
                    Single height = CameraManager.pInstance.pScreenViewRect.pDimensions.Y;
                    Single initialPercent = mTexture.Height / height;
                    mParentGOH.pScaleY = def.mScreenStretchPercentage.Y / initialPercent;
                }
            }

            mAttachmentPoints = new Dictionary<string, SpriteRenderDefinition.AtachmentPoint>();
            if (def.mAttachmentPoints != null)
            {
                for (Int32 i = 0; i < def.mAttachmentPoints.Count; i++)
                {
                    mAttachmentPoints.Add(def.mAttachmentPoints[i].mName, def.mAttachmentPoints[i]);
                }
            }
            mHasShadow = def.mHasShadow;
            Single colHeight = mTexture.Height;
            if (def.mFrameHeight > 0)
            {
                colHeight = def.mFrameHeight;
            }

            if (def.mAnimationSets != null)
            {
                mIsAnimated = true;

                if (def.mFrameHeight == 0)
                {
                    System.Diagnostics.Debug.Assert(false, "Sprite has animations but a frame height of 0.  FrameHeight must be > 0.");

                    def.mFrameHeight = 1;
                }

                mFrameHeight = def.mFrameHeight;

                mAnimations = new List<AnimationSet>();

                for (int i = 0; i < def.mAnimationSets.Count; i++)
                {
                    AnimationSet temp = new AnimationSet();
                    temp.Reset();
                    temp.mNumFrames = def.mAnimationSets[i].mNumFrames;
                    temp.mTicksPerFrame = def.mAnimationSets[i].mTicksPerFrame;
                    temp.mName = def.mAnimationSets[i].mName;
                    temp.mStartingFrame = def.mAnimationSets[i].mStartingFrame;
                    temp.mLooping = def.mAnimationSets[i].mLooping;
                    temp.mRemoveGameObjectOnComplete = def.mAnimationSets[i].mRemoveGameObjectOnComplete;
                    temp.mAnimationComplete = false;
                    temp.mFrameOverrides = def.mAnimationSets[i].mFrameOverrides;
                    mAnimations.Add(temp);
                }
            }
            else
            {
                mIsAnimated     = false;
            }

            Reset();

            mOnAnimationCompleteMsg = new OnAnimationCompleteMessage();
            mGetMotionTrailHistoryMsg = new MotionTrail.GetMotionTrailHistoryMessage();
        }
Esempio n. 47
0
        private void ValidateAssets()
        {
            if (m_asset.Type == (sbyte)CustomAssetType.AnimationSet)
            {
                AnimationSet animSet = new AnimationSet(m_asset.Data);

                bool allOk = animSet.Validate(x => {
                    int perms = m_Scene.InventoryService.GetAssetPermissions(ourClient.AgentId, x);
                    int required = (int)(PermissionMask.Transfer | PermissionMask.Copy);
                    if ((perms & required) != required)
                        return false;
                    return true;
                    });

                if (!allOk)
                    m_asset.Data = animSet.ToBytes();
            }

            if (m_asset.Type == (sbyte)AssetType.Clothing ||
                m_asset.Type == (sbyte)AssetType.Bodypart)
            {
                string content = System.Text.Encoding.ASCII.GetString(m_asset.Data);
                string[] lines = content.Split(new char[] {'\n'});

                List<string> validated = new List<string>();

                Dictionary<int, UUID> allowed = ExtractTexturesFromOldData();

                int textures = 0;

                foreach (string line in lines)
                {
                    try
                    {
                        if (line.StartsWith("textures "))
                        {
                            textures = Convert.ToInt32(line.Substring(9));
                            validated.Add(line);
                        }
                        else if (textures > 0)
                        {
                            string[] parts = line.Split(new char[] {' '});

                            UUID tx = new UUID(parts[1]);
                            int id = Convert.ToInt32(parts[0]);

                            if (defaultIDs.Contains(tx) || tx == UUID.Zero ||
                                (allowed.ContainsKey(id) && allowed[id] == tx))
                            {
                                validated.Add(parts[0] + " " + tx.ToString());
                            }
                            else
                            {
                                int perms = m_Scene.InventoryService.GetAssetPermissions(ourClient.AgentId, tx);
                                int full = (int)(PermissionMask.Modify | PermissionMask.Transfer | PermissionMask.Copy);

                                if ((perms & full) != full)
                                {
                                    m_log.ErrorFormat("[ASSET UPLOADER]: REJECTED update with texture {0} from {1} because they do not own the texture", tx, ourClient.AgentId);
                                    validated.Add(parts[0] + " " + UUID.Zero.ToString());
                                }
                                else
                                {
                                    validated.Add(line);
                                }
                            }
                            textures--;
                        }
                        else
                        {
                            validated.Add(line);
                        }
                    }
                    catch
                    {
                        // If it's malformed, skip it
                    }
                }

                string final = String.Join("\n", validated.ToArray());

                m_asset.Data = System.Text.Encoding.ASCII.GetBytes(final);
            }
        }
Esempio n. 48
0
 /// <summary>
 /// Sets the current animation based off of it's name.
 /// </summary>
 /// <param name="setName">The name of the animation to set the sprite to.</param>
 public void SetAnimation(string setName)
 {
     if (CurrentAnimation.name != setName)
     {
         foreach (AnimationSet a in AnimationSets)
         {
             if (a.name == setName)
             {
                 CurrentAnimation = a;
                 CurrentFrame = Point.Zero;
             }
         }
     }
 }
Esempio n. 49
0
 public void Close()
 {
     m_animations = null;
     m_scenePresence = null;
 }
Esempio n. 50
0
        /// <summary>
        /// The workhorse of the animation processor. It loops through all 
        /// animations, all tracks, and all keyframes, and converts to the format
        /// expected by the runtime animation classes.
        /// </summary>
        /// <param name="input">The NodeContent to process. Comes from the base ModelProcessor.</param>
        /// <param name="output">The ModelContent that was produced. You don't typically change this.</param>
        /// <param name="context">The build context (logger, etc).</param>
        /// <returns>An allocated AnimationSet with the animations to include.</returns>
        public virtual AnimationSet BuildAnimationSet(NodeContent input, ref ModelContent output, 
        ContentProcessorContext context)
        {
            AnimationSet ret = new AnimationSet();
              if (!DoAnimations)
              {
            context.Logger.LogImportantMessage("DoAnimation is set to false for {0}; not generating animations.", input.Name);
            return ret;
              }

              //  go from name to index
              Dictionary<string, ModelBoneContent> nameToIndex = new Dictionary<string, ModelBoneContent>();
              foreach (ModelBoneContent mbc in output.Bones)
            nameToIndex.Add(GetBoneName(mbc), mbc);

              AnimationContentDictionary adict = MergeAnimatedBones(input);
              if (adict == null || adict.Count == 0)
              {
            context.Logger.LogWarning("http://kwxport.sourceforge.net/", input.Identity,
            "Model processed with AnimationProcessor has no animations.");
            return ret;
              }

              foreach (AnimationContent ac in adict.Values)
              {
            if (!IncludeAnimation(ac))
            {
              context.Logger.LogImportantMessage(String.Format("Not including animation named {0}.", ac.Name));
              continue;
            }
            context.Logger.LogImportantMessage(
            "Processing animation {0} duration {1} sample rate {2} reduction tolerance {3}.",
            ac.Name, ac.Duration, SampleRate, Tolerance);
            AnimationChannelDictionary acdict = ac.Channels;
            AnimationTrackDictionary tracks = new AnimationTrackDictionary();
            TimeSpan longestUniqueDuration = new TimeSpan(0);
            foreach (string name in acdict.Keys)
            {
              if (!IncludeTrack(name))
              {
            context.Logger.LogImportantMessage(String.Format("Not including track named {0}.", name));
            continue;
              }

              int ix = 0;
              AnimationChannel achan = acdict[name];
              int bix = nameToIndex[name].Index;
              context.Logger.LogMessage("Processing bone {0}:{1}.", name, bix);
              AnimationTrack at;
              if (tracks.TryGetValue(bix, out at))
              {
            throw new System.ArgumentException(
                String.Format("Bone index {0} is used by multiple animations in the same clip (name {1}).",
                bix, name));
              }

              //  Sample at given frame rate from 0 .. Duration
              List<Keyframe> kfl = new List<Keyframe>();
              int nFrames = (int)Math.Floor(ac.Duration.TotalSeconds * SampleRate + 0.5);
              for (int i = 0; i < nFrames; ++i)
              {
            Keyframe k = SampleChannel(achan, i / SampleRate, ref ix);
            kfl.Add(k);
              }

              //  Run keyframe elimitation
              Keyframe[] frames = kfl.ToArray();
              int nReduced = 0;
              if (tolerance_ > 0)
            nReduced = ReduceKeyframes(frames, tolerance_);
              if (nReduced > 0)
            context.Logger.LogMessage("Reduced '{2}' from {0} to {1} frames.",
                frames.Length, frames.Length - nReduced, name);

              //  Create an AnimationTrack
              at = new AnimationTrack(bix, frames);
              Debug.Assert(name != null);
              at.Name = name;
              tracks.Add(bix, at);
            }
            if (ShouldTrimAnimation(ac))
            {
              TrimAnimationTracks(ac.Name, tracks, context);
            }

            Animation a = new Animation(ac.Name, tracks, SampleRate);
            ret.AddAnimation(a);
              }

              //  build the special "identity" and "bind pose" animations
              AnimationTrackDictionary atd_id = new AnimationTrackDictionary();
              AnimationTrackDictionary atd_bind = new AnimationTrackDictionary();
              foreach (KeyValuePair<string, ModelBoneContent> nip in nameToIndex)
              {
            if (!IncludeTrack(nip.Key))
              continue;
            Keyframe[] frames_id = new Keyframe[2];
            frames_id[0] = new Keyframe();
            frames_id[1] = new Keyframe();
            AnimationTrack at_id = new AnimationTrack(nip.Value.Index, frames_id);
            at_id.Name = nip.Key;
            atd_id.Add(nip.Value.Index, at_id);

            Keyframe[] frames_bind = new Keyframe[2];
            Matrix mat = nip.Value.Transform;
            frames_bind[0] = Keyframe.CreateFromMatrix(mat);
            frames_bind[1] = new Keyframe();
            frames_bind[1].CopyFrom(frames_bind[0]);
            AnimationTrack at_bind = new AnimationTrack(nip.Value.Index, frames_bind);
            at_bind.Name = nip.Key;
            atd_bind.Add(nip.Value.Index, at_bind);
              }
              ret.AddAnimation(new Animation("$id$", atd_id, 1.0f));
              ret.AddAnimation(new Animation("$bind$", atd_bind, 1.0f));

              return ret;
        }
Esempio n. 51
0
    public void SetSequence(string name)
    {
        if (CurrentAnimSet != null && name == CurrentAnimSet.Name)
            return;

        LastUpdateTime = -9999;

        if (FrameSets.ContainsKey(name))
            CurrentAnimSet = FrameSets[name];
        else if (FrameSets.ContainsKey("Idle"))
            CurrentAnimSet = FrameSets["Idle"];
        else
        {
            CurrentAnimSet = null;
            return;
        }

        CurrentSequence = CurrentAnimSet.Name;

        CurrentFrame = -1;
    }
Esempio n. 52
0
 public void Clear()
 {
     CurrentAnimSet = null;
     CurrentSequence = string.Empty;
 }
Esempio n. 53
0
        public static Animation Process(XmlNode input, double version, ContentProcessorContext context)
        {
            Animation animation = new Animation();
            string innerText = SGDEProcessor.GetInnerText(input).Trim();
            if (ContentTagManager.TagMatches("ANIMATION_GLOBAL", innerText, version))
            {
                animation.BuiltIn = false;
                animation.ID = int.Parse(ContentTagManager.GetXMLAtt("GENERAL_ID", version, input).Value);
            }
            else if (ContentTagManager.TagMatches("ANIMATION_LOCAL", innerText, version))
            {
                animation.BuiltIn = true;

                #region Local

                animation.Sets = new List<AnimationSet>();
                int index = 0;
                foreach (XmlNode element in input)
                {
                    if (ContentTagManager.TagMatches("ANIMATION_LOCAL_SET", element.Name, version))
                    {
                        #region AnimationSet

                        AnimationSet set = new AnimationSet();
                        set.Index = index++;
                        XmlAttribute at = ContentTagManager.GetXMLAtt("ANIMATION_LOCAL_DEFAULT", version, element);
                        if (at != null)
                        {
                            set.Default = bool.Parse(at.Value);
                        }
                        at = ContentTagManager.GetXMLAtt("ANIMATION_LOCAL_FPS", version, element);
                        if (at != null)
                        {
                            set.FPS = float.Parse(at.Value);
                        }
                        at = ContentTagManager.GetXMLAtt("GENERAL_DEVELOPER_ID", version, element);
                        if (at != null)
                        {
                            set.DevID(at, set);
                        }
                        int fcount = 0;
                        //This happens twice, first gets the frame count...
                        foreach (XmlNode frame in element)
                        {
                            if (ContentTagManager.TagMatches("ANIMATION_LOCAL_FRAME", frame.Name, version))
                            {
                                at = ContentTagManager.GetXMLAtt("ANIMATION_LOCAL_FRAME_FRAMECOUNT", version, frame);
                                if (at != null)
                                {
                                    int c = int.Parse(at.Value);
                                    if (c < 1)
                                    {
                                        context.Logger.LogWarning(null, null, Messages.Animation_FPSTooLow, c);
                                    }
                                    else
                                    {
                                        fcount += c;
                                    }
                                }
                                else
                                {
                                    fcount++;
                                }
                            }
                        }
                        //...second actually processes them.
                        set.Frames = new List<AnimationFrame>(fcount);
                        Rectangle? region = null;
                        foreach (XmlNode frame in element)
                        {
                            if (ContentTagManager.TagMatches("ANIMATION_LOCAL_FRAME", frame.Name, version))
                            {
                                #region Frame

                                AnimationFrame aframe = null;
                                at = ContentTagManager.GetXMLAtt("ANIMATION_LOCAL_FRAME_CONTINUE", version, frame);
                                if (at != null)
                                {
                                    bool value = bool.Parse(at.Value);
                                    if (value)
                                    {
                                        if (set.Frames.Count == 0)
                                        {
                                            context.Logger.LogWarning(null, null, Messages.Animation_ContinueAnimationOnFirstFrame);
                                        }
                                        else
                                        {
                                            aframe = new AnimationFrame(set.Frames[set.Frames.Count - 1]);
                                        }
                                    }
                                }
                                else
                                {
                                    aframe = new AnimationFrame();
                                }
                                at = ContentTagManager.GetXMLAtt("ANIMATION_LOCAL_FRAME_FRAMECOUNT", version, frame);
                                if (at != null)
                                {
                                    int c = int.Parse(at.Value);
                                    if (c >= 1)
                                    {
                                        while (c-- > 0)
                                        {
                                            set.Frames.Add(aframe); //If one changes, they all change
                                        }
                                    }
                                    else
                                    {
                                        set.Frames.Add(aframe);
                                    }
                                }
                                else
                                {
                                    set.Frames.Add(aframe);
                                }
                                at = ContentTagManager.GetXMLAtt("ANIMATION_LOCAL_FRAME_EFFECT", version, frame);
                                if (at != null)
                                {
                                    aframe.Effect = Utils.ParseEnum<Microsoft.Xna.Framework.Graphics.SpriteEffects>(at.Value, Microsoft.Xna.Framework.Graphics.SpriteEffects.None, context.Logger);

                                    if (aframe.Effect != Microsoft.Xna.Framework.Graphics.SpriteEffects.None)
                                    {
                                        aframe.Used |= SGDE.Content.Readers.AnimationReader.EffectUsed;
                                    }
                                    else
                                    {
                                        aframe.Used &= (byte)((~SGDE.Content.Readers.AnimationReader.EffectUsed) & 0xFF);
                                    }
                                }
                                at = ContentTagManager.GetXMLAtt("ANIMATION_LOCAL_FRAME_COLOR", version, frame);
                                if (at != null)
                                {
                                    try
                                    {
                                        /* Bug causes this not to be set properly. Try 0xFF008000 for example. Supposed to be A:255, R:0, G:128, B:0. Instead green is 255.
                                        Microsoft.Xna.Framework.Graphics.PackedVector.Byte4 packedVector = new Microsoft.Xna.Framework.Graphics.PackedVector.Byte4(); //Preperation
                                        packedVector.PackedValue = Convert.ToUInt32(at.Value, 16); //Keep it clean
                                        aframe.Color = new Color(packedVector.ToVector4()); //Build it
                                         */
                                        Color col = new Color(); //Build
                                        col.PackedValue = Convert.ToUInt32(at.Value, 16); //Keep it clean
                                        aframe.Color = col;
                                        aframe.Used |= SGDE.Content.Readers.AnimationReader.ColorUsed;
                                    }
                                    catch
                                    {
                                        context.Logger.LogWarning(null, null, Messages.Animation_InvalidColor, at.Value);
                                    }
                                }
                                at = ContentTagManager.GetXMLAtt("ANIMATION_LOCAL_FRAME_FRAME", version, frame);
                                if (at != null)
                                {
                                    string[] values = at.Value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                                    if (values.Length != 4)
                                    {
                                        context.Logger.LogWarning(null, null, Messages.Animation_InvalidRegion);
                                    }
                                    else
                                    {
                                        int[] ivals = new int[4];
                                        bool error = false;
                                        for (int i = 0; i < 4; i++)
                                        {
                                            try
                                            {
                                                ivals[i] = int.Parse(values[i].Trim());
                                            }
                                            catch
                                            {
                                                error = true;
                                                context.Logger.LogWarning(null, null, Messages.CannotParseValue);
                                            }
                                        }
                                        if (region.HasValue)
                                        {
                                            if (ivals[2] != region.Value.Width || ivals[3] != region.Value.Height)
                                            {
                                                error = true;
                                                context.Logger.LogWarning(null, null, Messages.Animation_RegionMustRemainSame);
                                            }
                                        }
                                        if (!error)
                                        {
                                            aframe.Region = new Rectangle(ivals[0], ivals[1], ivals[2], ivals[3]);
                                            aframe.Used |= SGDE.Content.Readers.AnimationReader.RegionUsed;
                                            if (!region.HasValue)
                                            {
                                                region = new Rectangle(0, 0, aframe.Region.Width, aframe.Region.Height); //Only care about height and width
                                            }
                                        }
                                    }
                                }
                                at = ContentTagManager.GetXMLAtt("ANIMATION_LOCAL_FRAME_ORIGIN", version, frame);
                                if (at != null)
                                {
                                    string[] values = at.Value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                                    if (values.Length != 2)
                                    {
                                        context.Logger.LogWarning(null, null, Messages.Animation_InvalidOrigin);
                                    }
                                    else
                                    {
                                        float[] fvals = new float[2];
                                        bool error = false;
                                        for (int i = 0; i < 2; i++)
                                        {
                                            try
                                            {
                                                fvals[i] = float.Parse(values[i].Trim());
                                            }
                                            catch
                                            {
                                                error = true;
                                                context.Logger.LogWarning(null, null, Messages.CannotParseValue);
                                            }
                                        }
                                        if (!error)
                                        {
                                            aframe.Origin = new Vector2(fvals[0], fvals[1]);
                                            if (aframe.Origin.X != 0 || aframe.Origin.Y != 0)
                                            {
                                                aframe.Used |= SGDE.Content.Readers.AnimationReader.OriginUsed;
                                            }
                                            else
                                            {
                                                aframe.Used &= (byte)((~SGDE.Content.Readers.AnimationReader.OriginUsed) & 0xFF);
                                            }
                                        }
                                    }
                                }
                                at = ContentTagManager.GetXMLAtt("ANIMATION_LOCAL_FRAME_SCALE", version, frame);
                                if (at != null)
                                {
                                    string[] values = at.Value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                                    if (values.Length != 2)
                                    {
                                        context.Logger.LogWarning(null, null, Messages.Animation_InvalidScale);
                                    }
                                    else
                                    {
                                        float[] fvals = new float[2];
                                        bool error = false;
                                        for (int i = 0; i < 2; i++)
                                        {
                                            try
                                            {
                                                fvals[i] = float.Parse(values[i].Trim());
                                            }
                                            catch
                                            {
                                                error = true;
                                                context.Logger.LogWarning(null, null, Messages.CannotParseValue);
                                            }
                                        }
                                        if (!error)
                                        {
                                            aframe.Scale = new Vector2(fvals[0], fvals[1]);
                                            if (aframe.Scale.X != 1 || aframe.Scale.Y != 1)
                                            {
                                                aframe.Used |= SGDE.Content.Readers.AnimationReader.ScaleUsed;
                                            }
                                            else
                                            {
                                                aframe.Used &= (byte)((~SGDE.Content.Readers.AnimationReader.ScaleUsed) & 0xFF);
                                            }
                                        }
                                    }
                                }
                                at = ContentTagManager.GetXMLAtt("ANIMATION_LOCAL_FRAME_ROTATION", version, frame);
                                if (at != null)
                                {
                                    bool radian = false;
                                    string value = at.Value;
                                    at = ContentTagManager.GetXMLAtt("ANIMATION_LOCAL_FRAME_ROTATION_FORMAT", version, frame);
                                    if (at != null)
                                    {
                                        if (ContentTagManager.TagMatches("ANIMATION_LOCAL_FRAME_ROTATION_FORMAT_RADIAN", at.Value, version))
                                        {
                                            radian = true;
                                        }
                                        else if (ContentTagManager.TagMatches("ANIMATION_LOCAL_FRAME_ROTATION_FORMAT_DEGREE", at.Value, version))
                                        {
                                            radian = false;
                                        }
                                        else
                                        {
                                            context.Logger.LogWarning(null, null, Messages.Animation_UnknownRotationFormat, at.Value);
                                        }
                                    }
                                    if (radian)
                                    {
                                        double radianVal;
                                        try
                                        {
                                            radianVal = double.Parse(value.Trim());
                                            radianVal %= (2 * Math.PI);
                                            if (radianVal != 0)
                                            {
                                                aframe.Used |= SGDE.Content.Readers.AnimationReader.RotationUsed;
                                                aframe.Rotation = (float)radianVal;
                                            }
                                            else if (aframe.Rotation != 0)
                                            {
                                                aframe.Used &= (byte)((~SGDE.Content.Readers.AnimationReader.RotationUsed) & 0xFF);
                                            }
                                        }
                                        catch
                                        {
                                            XmlAttribute tempnode = frame.OwnerDocument.CreateAttribute(ContentTagManager.GetTagValue("ANIMATION_LOCAL_FRAME_ROTATION", version));
                                            //Replace "Pi" with "Math.PI" for easier execution
                                            int nindex = value.IndexOf("PI", StringComparison.OrdinalIgnoreCase);
                                            if (nindex >= 0)
                                            {
                                                string piValue = value.Substring(nindex, 2);
                                                value = value.Replace(piValue, CodeProcessor.AbsReference("Math.PI"));
                                            }
                                            tempnode.Value = value;

                                            SGDeContent.DataTypes.Code.Code code = CodeProcessor.Process(tempnode, version, context);
                                            if (code.Constant)
                                            {
                                                radianVal = Convert.ToDouble(code.ConstantValue);
                                                if (radianVal != 0)
                                                {
                                                    aframe.Used |= SGDE.Content.Readers.AnimationReader.RotationUsed;
                                                    aframe.Rotation = (float)radianVal;
                                                }
                                                else if (aframe.Rotation != 0)
                                                {
                                                    aframe.Used &= (byte)((~SGDE.Content.Readers.AnimationReader.RotationUsed) & 0xFF);
                                                }
                                            }
                                            else
                                            {
                                                context.Logger.LogWarning(null, null, Messages.Animation_InvalidRadian);
                                            }
                                        }
                                    }
                                    else
                                    {
                                        try
                                        {
                                            double degree = double.Parse(value.Trim());
                                            degree %= 360;
                                            if (degree != 0)
                                            {
                                                aframe.Used |= SGDE.Content.Readers.AnimationReader.RotationUsed;
                                                aframe.Rotation = (float)((degree * Math.PI) / 180.0); //Could use MathHelper but want higher precision first
                                            }
                                            else if (aframe.Rotation != 0)
                                            {
                                                aframe.Used &= (byte)((~SGDE.Content.Readers.AnimationReader.RotationUsed) & 0xFF);
                                            }
                                        }
                                        catch
                                        {
                                            context.Logger.LogWarning(null, null, Messages.Animation_InvalidDegree);
                                        }
                                    }
                                }
                                set.Used |= aframe.Used;

                                #endregion
                            }
                        }
                        if (set.Frames.Count > 0)
                        {
                            animation.Sets.Add(set);
                        }

                        #endregion
                    }
                }

                #endregion
            }
            else
            {
                throw new InvalidContentException(string.Format(Messages.Animation_UnknownType, innerText));
            }
            return animation;
        }
Esempio n. 54
0
        /// <summary>
        /// Capability originating call to update the asset of an item in an agent's inventory
        /// </summary>
        /// <param name="remoteClient"></param>
        /// <param name="itemID"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public virtual UUID CapsUpdateInventoryItemAsset(IClientAPI remoteClient, UUID itemID, byte[] data)
        {
            InventoryItemBase item = new InventoryItemBase(itemID, remoteClient.AgentId);
            item = m_Scene.InventoryService.GetItem(item);

            if (item.Owner != remoteClient.AgentId)
                return UUID.Zero;

            if (item != null)
            {
                if ((InventoryType)item.InvType == InventoryType.Notecard)
                {
                    if (!m_Scene.Permissions.CanEditNotecard(itemID, UUID.Zero, remoteClient.AgentId))
                    {
                        remoteClient.SendAgentAlertMessage("Insufficient permissions to edit notecard", false);
                        return UUID.Zero;
                    }

                    remoteClient.SendAlertMessage("Notecard saved");
                }
                else if ((InventoryType)item.InvType == InventoryType.LSL)
                {
                    if (!m_Scene.Permissions.CanEditScript(itemID, UUID.Zero, remoteClient.AgentId))
                    {
                        remoteClient.SendAgentAlertMessage("Insufficient permissions to edit script", false);
                        return UUID.Zero;
                    }

                    remoteClient.SendAlertMessage("Script saved");
                }
                else if ((CustomInventoryType)item.InvType == CustomInventoryType.AnimationSet)
                {
                    AnimationSet animSet = new AnimationSet(data);
                    if (!animSet.Validate(x => {
                        int perms = m_Scene.InventoryService.GetAssetPermissions(remoteClient.AgentId, x);
                        int required = (int)(PermissionMask.Transfer | PermissionMask.Copy);
                        if ((perms & required) != required)
                            return false;
                        return true;
                    }))
                    {
                        data = animSet.ToBytes();
                    }
                }

                AssetBase asset =
                    CreateAsset(item.Name, item.Description, (sbyte)item.AssetType, data, remoteClient.AgentId.ToString());
                item.AssetID = asset.FullID;
                m_Scene.AssetService.Store(asset);

                m_Scene.InventoryService.UpdateItem(item);

                // remoteClient.SendInventoryItemCreateUpdate(item);
                return (asset.FullID);
            }
            else
            {
                m_log.ErrorFormat(
                    "[INVENTORY ACCESS MODULE]: Could not find item {0} for caps inventory update",
                    itemID);
            }

            return UUID.Zero;
        }