Exemplo n.º 1
0
        public void TestRemovingFeedbackReceivers()
        {
            FieldSize fieldsize = new FieldSize {
                Xmin = 0, Xmax = 4, Ymax = 2, Ymin = 0, Zmax = 4, Zmin = 0
            };
            IParticleGenerator particleGenerator        = new RandomParticleGenerator(new ContinuousUniform());
            IResampler         resampler                = new MultinomialResampler();
            INoiseGenerator    noiseGenerator           = new RandomNoiseGenerator(new ContinuousUniform());
            ISmoother          smoother                 = new MovingAverageSmoother(200);
            ParticleFilter     filter                   = new ParticleFilter(250, 0.1f, fieldsize, particleGenerator, resampler, noiseGenerator, smoother);
            Mock <IOrientationFeedbackReceiver> orifeed = new Mock <IOrientationFeedbackReceiver>();

            filter.RegisterReceiver(orifeed.Object);
            filter.RegisterReceiver(orifeed.Object);
            filter.UnregisterReceiver(orifeed.Object);
            filter.UnregisterReceiver(orifeed.Object);
            Mock <IPositionFeedbackReceiver> posfeed = new Mock <IPositionFeedbackReceiver>();

            filter.RegisterReceiver(posfeed.Object);
            filter.RegisterReceiver(posfeed.Object);
            filter.UnregisterReceiver(posfeed.Object);
            filter.UnregisterReceiver(posfeed.Object);
            filter.CalculatePose(10);
            posfeed.Verify(f => f.NotifyPositionFeedback(It.IsAny <FeedbackData <Vector3> >()), Times.Never);
            orifeed.Verify(f => f.NotifyOrientationFeedback(It.IsAny <FeedbackData <Vector3> >()), Times.Never);
        }
        public void SetUp()
        {
            this.rngsource = new Mock <IContinuousDistribution>();
            this.rngsource.SetupGet(foo => foo.Maximum).Returns(1);
            this.rngsource.SetupGet(foo => foo.Minimum).Returns(0);
            this.rngsource.Setup(foo => foo.Sample()).Returns(this.sample);

            this.rng = new RandomParticleGenerator(this.rngsource.Object);
        }
Exemplo n.º 3
0
    /// <summary>
    /// Initializes a new instance of the <see cref="ParticleFilterCoupler"/> class
    /// </summary>
    /// <param name="fieldSize">The preferred game field size</param>
    public ParticleFilterCoupler(FieldSize fieldSize)
    {
        int particleamount           = 300;
        IParticleGenerator prtclgen  = new RandomParticleGenerator(new ContinuousUniform());
        INoiseGenerator    noisegen  = new RandomNoiseGenerator(new ContinuousUniform());
        IResampler         resampler = new MultinomialResampler();
        ISmoother          smoother  = new MovingAverageSmoother(1000);

        this.localizer = new ParticleFilter(particleamount, 0.1f, fieldSize, prtclgen, resampler, noisegen, smoother);
    }
Exemplo n.º 4
0
        public Ship_Sprite(Texture2D texture, Vector2 location, SpriteBatch spriteBatch)
            : base(texture, location, spriteBatch)
        {
            particles[0] = GameContent.Assets.Images.particles[ParticleType.Circle];
            particles[1] = GameContent.Assets.Images.particles[ParticleType.Square];
            gen = new RandomParticleGenerator(SpriteBatch, particles);
            gen.TTLSettings = TimeToLiveSettings.AlphaLess100;
            gen.RandomProperties = new RandomParticleProperties() { ColorFactor = 0.985f, Tint = Color.White };
            gen.ParticlesToGenerate = 1;
            engine = new Glib.XNA.SpriteLib.ParticleEngine.ParticleEngine(gen);

            Vector2 toEngine = new Vector2(Position.X, Position.Y - Height / 2);
            toEngineLength = -toEngine.Length();
            toEngineAngle = toEngine.ToAngle();

            engine.Tracked = this;
        }
Exemplo n.º 5
0
        public void TestNoCrashWhenNoData()
        {
            FieldSize fieldsize = new FieldSize {
                Xmin = 0, Xmax = 4, Ymax = 2, Ymin = 0, Zmax = 4, Zmin = 0
            };
            IParticleGenerator particleGenerator = new RandomParticleGenerator(new ContinuousUniform());
            IResampler         resampler         = new MultinomialResampler();
            INoiseGenerator    noiseGenerator    = new RandomNoiseGenerator(new ContinuousUniform());
            ISmoother          smoother          = new MovingAverageSmoother(200);
            ParticleFilter     filter            = new ParticleFilter(250, 0.1f, fieldsize, particleGenerator, resampler, noiseGenerator, smoother);

            for (int i = 0; i < 10; i++)
            {
                filter.CalculatePose(i);
            }

            Assert.Pass();
        }
Exemplo n.º 6
0
        public void TestAddingDisplacementSource()
        {
            FieldSize fieldsize = new FieldSize {
                Xmin = 0, Xmax = 4, Ymax = 2, Ymin = 0, Zmax = 4, Zmin = 0
            };
            IParticleGenerator particleGenerator = new RandomParticleGenerator(new ContinuousUniform());
            IResampler         resampler         = new MultinomialResampler();
            INoiseGenerator    noiseGenerator    = new RandomNoiseGenerator(new ContinuousUniform());
            ISmoother          smoother          = new MovingAverageSmoother(200);
            ParticleFilter     filter            = new ParticleFilter(250, 0.1f, fieldsize, particleGenerator, resampler, noiseGenerator, smoother);

            Mock <IDisplacementSource> sourcemock = new Mock <IDisplacementSource>();

            sourcemock.SetReturnsDefault <Measurement <Vector3> >(new Measurement <Vector3>(new Vector3(), 0, new Normal(0.1)));
            sourcemock.Setup(foo => foo.GetDisplacement(It.IsAny <int>(), It.IsAny <int>())).Returns(() => new Measurement <Vector3>(new Vector3(), 0, new Normal(0.1)));
            filter.AddDisplacementSource(sourcemock.Object);

            filter.CalculatePose(1);
            filter.CalculatePose(2);
            sourcemock.Verify(foo => foo.GetDisplacement(1, 2));
        }
Exemplo n.º 7
0
        /// <summary>
        /// Creates and initializes the main menu.
        /// </summary>
        /// <param name="sb">The <see cref="SpriteBatch"/> to render to.</param>
        public MainMenu(SpriteBatch sb)
            : base(sb, Color.Lime)
        {
            Name = "MainMenu";

            //TextureFactory: Creates textures at runtime
            TextureFactory factory = new TextureFactory(sb.GraphicsDevice);

            //Sprite: A simple bitmap image, with convenient methods and properties
            //Yet it has so many possibilities...
            //Here it is used as a mouse cursor
            //Star image courtesy of Wikimedia user Felipe Micaroni Lalli
            //Image obtained from http://commons.wikimedia.org/wiki/File:Star_Ouro.svg
            mouseCursor                   = new Sprite(GLibXNASampleGame.Instance.Content.Load <Texture2D>("Star"), Vector2.Zero, sb);
            mouseCursor.Scale             = new Vector2(.1f);
            mouseCursor.UseCenterAsOrigin = true;

            //OverlayImage overlays the second image onto the first (not in place)
            Texture2D imageOverlay = factory.CreateSquare(15, Color.DarkGray * 0.65F);

            TextureFactory.OverlayImage(imageOverlay, factory.CreateSquare(11, Color.Black * 0.75F), new Point(2, 2));
            TextureFactory.OverlayImage(imageOverlay, factory.CreateSquare(7, Color.DarkOrange * 0.85F), new Point(4, 4));
            TextureFactory.OverlayImage(imageOverlay, factory.CreateSquare(3, Color.DarkRed * 0.95F), new Point(6, 6));

            fadingImage          = new Sprite(imageOverlay, Vector2.Zero, sb);
            fadingImage.Position = new Vector2(15, 25);
            //The CreateFade method creates an array of textures, each one closer to the final texture than the last
            //It is used for fades
            Texture2D finalFadeImage = factory.CreateRectangle(fadingImage.Texture.Width, fadingImage.Texture.Height, Color.Red);

            TextureFactory.OverlayImage(finalFadeImage, factory.CreateHollowRectangle(fadingImage.Texture.Width - 4, fadingImage.Texture.Height - 4, Color.DarkRed), new Point(2, 2));
            fades = TextureFactory.CreateFade(fadingImage.Texture, finalFadeImage, 300);

            mouseBoundingBox = new Sprite(factory.CreateHollowCircle((mouseCursor.Width / 2).Round(), Color.Navy), mouseCursor.Position, sb)
            {
                UseCenterAsOrigin = true
            };

            //TextSprite: Displays text
            //Can be used for titles, descriptions, etc
            title = new TextSprite(sb, GLibXNASampleGame.Instance.Content.Load <SpriteFont>("Title"), "GlenLibrary XNA");
            //Extension method: GetCenterPosition: Returns the position required to center the object on the specified viewport
            title.Position = new Vector2(title.GetCenterPosition(sb.GraphicsDevice.Viewport).X, 15);
            //Fancy color constructor: Uses a Vector4 with RGBA values expressed as floats from 0 to 1, basically dark gray shadow with 128 alpha
            title.Shadow = new TextShadow(title, new Vector2(-2, 2), new Color(new Vector4(Color.DarkGray.ToVector3(), 0.5f)));

            AdditionalSprites.Add(title);


            desc         = new TextSprite(sb, GLibXNASampleGame.Instance.Content.Load <SpriteFont>("Subtitle"), "A general purpose XNA library", Color.Chocolate);
            desc.Color  *= 0.75f;
            desc.Color.A = 255;
            desc.X       = desc.GetCenterPosition(Graphics.Viewport).X;
            desc.Y       = title.Y + title.Height + 5;

            AdditionalSprites.Add(desc);

            //Add items to the buttons dictionary
            buttons.Add("Video Player", "VideoPlayer");
            buttons.Add("Multiplayer", "MultiPlayer");
            buttons.Add("Animated Sprite", "AnimatedScreen");

            #region Generation of buttons systematically
            float yCoord = desc.Y + desc.Height + 10;

            foreach (var element in buttons)
            {
                Sprite buttonSprite = new Sprite(GLibXNASampleGame.Instance.TextureCreator.CreateSquare(1, Color.Red), Vector2.Zero, sb);

                TextSprite button = new TextSprite(sb, GLibXNASampleGame.Instance.Content.Load <SpriteFont>("MenuItem"), element.Key);
                //Allows hovering (and therefore clicking) on a sprite
                button.IsHoverable = true;
                // These are the colors that are displayed at the various hovering states
                button.HoverColor    = Color.DarkCyan;
                button.NonHoverColor = Color.Black;
                // "Pressed" event handler lambda expression
                button.Pressed += (src, args) => GLibXNASampleGame.Instance.SetScreen(buttons[((TextSprite)src).Text]);
                // Setting width and height on a Sprite scales it
                buttonSprite.Width    = button.Width + 6;
                buttonSprite.Height   = button.Height + 4;
                buttonSprite.Position = new Vector2(buttonSprite.GetCenterPosition(sb.GraphicsDevice.Viewport).X, yCoord);
                // ParentSprite: Allows for a "button" behind a clickable TextSprite (or not clickable), all collision and position logic done with this sprite
                button.ParentSprite = buttonSprite;

                // Round to look better
                button.Scale.X = button.Scale.X.Round();
                button.Scale.Y = button.Scale.Y.Round();
                button.X       = button.X.Round();
                button.Y       = button.Y.Round();

                Sprites.Add(buttonSprite);
                AdditionalSprites.Add(button);

                yCoord += buttonSprite.Height;
                yCoord += 7.5f;
                yCoord  = yCoord.Round();
            }
            #endregion

            // ProgressBar: A dynamically generated progress bar, could be used to represent asset loading progress
            // Here it is just used for effects :-)
            progressBar = new ProgressBar(Vector2.Zero, _filledColors[0], _emptyColors[0], sb);
            //HeightScale: The progress bar shall be 7 pixels high
            progressBar.HeightScale = 7;
            progressBar.Denominator = Graphics.Viewport.Width - 20;
            progressBar.Value       = 0;
            progressBar.X           = progressBar.GetCenterPosition(sb.GraphicsDevice.Viewport).X;
            progressBar.Y           = Graphics.Viewport.Height - progressBar.Height - 5;
            Sprites.Add(progressBar);

            caption         = new TextSprite(sb, GLibXNASampleGame.Instance.Content.Load <SpriteFont>("Details"), "A caption!");
            caption.X       = caption.GetCenterPosition(Graphics.Viewport).X;
            caption.Y       = progressBar.Y - caption.Height - 2;
            caption.Visible = false;
            AdditionalSprites.Add(caption);

            // Random Particle Generator: A particle generator that uses a Random instance to set properties of the generated particles
            RandomParticleGenerator particlegen = new RandomParticleGenerator(sb, GLibXNASampleGame.Instance.Content.Load <Texture2D>("Star"));
            particlegen.MinimumParticleColorChangeRate = 0.925f;
            particlegen.MinimumTimeToLive   = TimeSpan.FromMilliseconds(400);
            particlegen.MaximumTimeToLive   = TimeSpan.FromMilliseconds(780);
            particlegen.ParticlesToGenerate = 1;
            particlegen.ScaleFactor         = 15;
            // TimeToLiveSettings: When to make a particle expire, binary flaggable enumerator
            particlegen.TTLSettings = TimeToLiveSettings.AlphaLess100 | TimeToLiveSettings.StrictTTL;

            // Particle engine: Generates particles using the specified particle generator
            mouseParticleGen = new ParticleEngine(particlegen);
            mouseParticleGen.FramesPerGeneration = 3;
            mouseParticleGen.Tracked             = mouseCursor;

            AdditionalSprites.Add(mouseParticleGen);
            AdditionalSprites.Add(mouseCursor);
            AdditionalSprites.Add(mouseBoundingBox);

            Sprites.Add(fadingImage);
        }
Exemplo n.º 8
0
        public void TestRealMarkerSensorData()
        {
            List <Measurement <Vector3> > oridata = new List <Measurement <Vector3> >();
            List <Measurement <Vector3> > posdata = new List <Measurement <Vector3> >();

            using (StreamReader sr = new StreamReader(TestContext.CurrentContext.TestDirectory + @"\RealMarkerOriData_Expected_9_10_3.dat"))
            {
                string line = sr.ReadLine();
                while (line != null)
                {
                    string[] unparsed = line.Split(',');
                    oridata.Add(new Measurement <Vector3>(
                                    VectorMath.Normalize(new Vector3(float.Parse(unparsed[0]), float.Parse(unparsed[1]), float.Parse(unparsed[2]))),
                                    0,
                                    new Normal(0.1)));
                    line = sr.ReadLine();
                }
            }

            using (StreamReader sr = new StreamReader(TestContext.CurrentContext.TestDirectory + @"\RealMarkerPosData_Expected_060_150_1.dat"))
            {
                string line = sr.ReadLine();
                while (line != null)
                {
                    string[] unparsed = line.Split(',');
                    posdata.Add(new Measurement <Vector3>(
                                    new Vector3(float.Parse(unparsed[0]), float.Parse(unparsed[1]), float.Parse(unparsed[2])),
                                    0,
                                    new Normal(0.01)));
                    line = sr.ReadLine();
                }
            }

            FieldSize fieldsize = new FieldSize {
                Xmin = 0, Xmax = 4, Ymax = 2, Ymin = 0, Zmax = 4, Zmin = 0
            };
            IParticleGenerator particleGenerator = new RandomParticleGenerator(new ContinuousUniform());
            IResampler         resampler         = new MultinomialResampler();
            INoiseGenerator    noiseGenerator    = new RandomNoiseGenerator(new ContinuousUniform());
            ISmoother          smoother          = new MovingAverageSmoother(200);
            ParticleFilter     filter            = new ParticleFilter(250, 0.1f, fieldsize, particleGenerator, resampler, noiseGenerator, smoother);

            int poscount = 0;
            Mock <IPositionSource> possource = new Mock <IPositionSource>();

            possource.Setup(foo => foo.GetPositionsClosestTo(It.IsAny <long>(), It.IsAny <long>())).
            Returns(() => new List <Measurement <Vector3> > {
                posdata[poscount]
            }).
            Callback(() => poscount++);
            filter.AddPositionSource(possource.Object);

            int oricount = 0;
            Mock <IOrientationSource> orisource = new Mock <IOrientationSource>();

            orisource.Setup(foo => foo.GetOrientationClosestTo(It.IsAny <long>(), It.IsAny <long>())).
            Returns(() => new List <Measurement <Vector3> > {
                oridata[oricount]
            }).
            Callback(() => oricount++);
            filter.AddOrientationSource(orisource.Object);

            this.writetofile = false;
            StringBuilder res     = new StringBuilder();
            List <Pose>   results = new List <Pose>();
            long          i       = 0;

            while ((poscount < posdata.Count / 10) && (oricount < oridata.Count / 10))
            {
                Pose pose = filter.CalculatePose(i);
                if (this.writetofile)
                {
                    res.AppendFormat($"{pose.Position.X},{pose.Position.Y},{pose.Position.Z},{pose.Orientation.X},{pose.Orientation.Y},{pose.Orientation.Z}" + Environment.NewLine);
                }

                i += 33;
                results.Add(pose);
            }

            if (this.writetofile)
            {
                File.WriteAllText(TestContext.CurrentContext.TestDirectory + @"\RealMarkerResults.dat", res.ToString());
            }

            int startindex = 30;

            Pose[] resultarray = new Pose[results.Count - startindex];
            results.CopyTo(startindex, resultarray, 0, resultarray.Length);

            Assert.AreEqual(posdata.GetRange(startindex, resultarray.Length).Select(m => m.Data.X).Average(), resultarray.Select(p => p.Position.X).Average(), 0.1);
            Assert.AreEqual(posdata.GetRange(startindex, resultarray.Length).Select(m => m.Data.Y).Average(), resultarray.Select(p => p.Position.Y).Average(), 0.1);
            Assert.AreEqual(posdata.GetRange(startindex, resultarray.Length).Select(m => m.Data.Z).Average(), resultarray.Select(p => p.Position.Z).Average(), 0.1);
            Assert.AreEqual(oridata.GetRange(startindex, resultarray.Length).Select(m => m.Data.X).Average(), resultarray.Select(p => p.Orientation.X).Average(), 0.1);
            Assert.AreEqual(oridata.GetRange(startindex, resultarray.Length).Select(m => m.Data.Y).Average(), resultarray.Select(p => p.Orientation.Y).Average(), 0.1);
            Assert.AreEqual(oridata.GetRange(startindex, resultarray.Length).Select(m => m.Data.Z).Average(), resultarray.Select(p => p.Orientation.Z).Average(), 0.1);
        }
Exemplo n.º 9
0
        public Ship(Texture2D texture, Vector2 location, SpriteBatch spriteBatch)
            : base(texture, location, spriteBatch)
        {
            StateManager.Options.ScreenResolutionChanged += new EventHandler<ViewportEventArgs>(Options_ScreenResolutionChanged);
            _healthBar = new ProgressBar(new Vector2(X, Y), Color.DarkGreen, Color.Red, spriteBatch);
            _healthBar.WidthScale = 1;
            _healthBar.HeightScale = 10;
            Moved += new EventHandler(Ship_Moved);
            _shipID = Guid.NewGuid();
            _initHealth = 100;
            _healthBar.X -= (_healthBar.Width / 2);
            _healthBar.Y -= (_healthBar.Height / 1.5f);

            _isDead = false;

            Explosion = GameContent.Assets.Images.SpriteSheets[SpriteSheetType.Explosion];
            _explosionSheet = new SpriteSheet(GameContent.Assets.Images.SpriteSheets[SpriteSheetType.Explosion], new Rectangle(0, 0, 50, 50), this.Position, spriteBatch, 8, 9);

            _explosionSheet.IsAnimated = true;
            _explosionSheet.Scale = new Vector2(1.5f);
            _explosionSheet.RestartAnimation = false;
            _currentHealth = _initHealth;

            ExplosionSFX = GameContent.Assets.Sound[SoundEffectType.EnemyExplodes];
            FriendlyName = ShipType.ToFriendlyString();

            particles[0] = GameContent.Assets.Images.particles[ParticleType.Circle];
            particles[1] = GameContent.Assets.Images.particles[ParticleType.Square];
            gen = new RandomParticleGenerator(SpriteBatch, particles);
            gen.TTLSettings = TimeToLiveSettings.AlphaLess100;
            gen.RandomProperties = new RandomParticleProperties() { ColorFactor = 0.985f, Tint = Color.White };
            gen.ParticlesToGenerate = 1;
            engine = new Glib.XNA.SpriteLib.ParticleEngine.ParticleEngine(gen);

            Vector2 toEngine = new Vector2(Position.X, Position.Y - texture.Height / 2);
            toEngineLength = -toEngine.Length();
            toEngineAngle = toEngine.ToAngle();

            engine.PositionOffset = new Vector2(0, texture.Height / 2);

            engine.Tracked = this;
        }