示例#1
0
        public void ShapeFromTexture(string shape, float scale, Color color, out Texture2D outputTexture, out Vertices vertices)
        {
            Texture2D shapeTexture = _shapes[shape];

            uint[] data = new uint[shapeTexture.Width * shapeTexture.Height];
            shapeTexture.GetData(data);
            Vertices textureVertices = PolygonTools.CreatePolygon(data, shapeTexture.Width, false);
            AABB     vertsBounds     = textureVertices.GetCollisionBox();
            Vector2  origin          = vertsBounds.Center;

            textureVertices.Translate(-origin);
            int width  = (int)((vertsBounds.UpperBound.X - vertsBounds.LowerBound.X) * scale);
            int height = (int)((vertsBounds.UpperBound.Y - vertsBounds.LowerBound.Y) * scale);

            textureVertices = SimplifyTools.ReduceByDistance(textureVertices, 4f);
            Vector2 vertScale = ConvertUnits.ToSimUnits(Vector2.One) * scale;

            textureVertices.Scale(ref vertScale);
            vertices = new Vertices(textureVertices);
            RenderTarget2D renderTarget = new RenderTarget2D(_device, width + 2, height + 2, false, SurfaceFormat.Color,
                                                             DepthFormat.None, 8,
                                                             RenderTargetUsage.DiscardContents);
            SpriteBatch batch = new SpriteBatch(_device);

            _device.SetRenderTarget(renderTarget);
            _device.Clear(Color.Transparent);
            batch.Begin(SpriteSortMode.Immediate, null, SamplerState.LinearClamp, null, RasterizerState.CullNone);
            batch.Draw(shapeTexture, new Vector2(renderTarget.Width / 2, renderTarget.Height / 2), null, color, 0, origin, scale, SpriteEffects.None, 0f);
            batch.End();
            _device.SetRenderTarget(null);
            outputTexture = renderTarget as Texture2D;
        }
示例#2
0
        static private void CreateShape(SFML.Graphics.Texture texture, World world)
        {
            // Make collision Geo from bitmap
            // Get pixel data in array​
            byte[] bytes = texture.CopyToImage().Pixels;
            uint[] data  = new uint[texture.Size.X * texture.Size.Y];
            for (int i = 0; i < bytes.Length; i += 4)
            {
                data[i / 4] = BitConverter.ToUInt32(bytes, i);
            }

            Byte myByte = 1;

            List <Vertices> _list = PolygonTools.CreatePolygon(data, (int)texture.Size.X, 0.05f, myByte, true, true);
            Vertices        verts = new Vertices();
            Vector2         scale = ConvertUnits.ToSimUnits(new Vector2(1, 1));

            foreach (Vertices v in _list)
            {
                v.Scale(scale);
                //    v.Translate(ConvertUnits.ToSimUnits(new Vector2(-16, -16)));
                Body body = new Body(world);
                body.SleepingAllowed = false;
                body.UserData        = "wall";
                List <Fixture> fixtures = FixtureFactory.AttachCompoundPolygon(
                    FarseerPhysics.Common.Decomposition.Triangulate.ConvexPartition(SimplifyTools.DouglasPeuckerSimplify(v, 0.05f), TriangulationAlgorithm.Bayazit, false, 0.05f),
                    1, body);
            }
        }
示例#3
0
        public void findShadowHull(Texture2D texture)
        {
            //Create an array to hold the data from the texture
            uint[] data = new uint[texture.Width * texture.Height];

            //Transfer the texture data to the array
            texture.GetData(data);

            //Find the vertices that makes up the outline of the shape in the texture
            textureVertices = PolygonTools.CreatePolygon(data, texture.Width, false);

            //We simplify the vertices found in the texture.
            textureVertices = SimplifyTools.DouglasPeuckerSimplify(textureVertices, 0.5f);

            //Since it is a concave polygon, we need to partition it into several smaller convex polygons
            vertices = BayazitDecomposer.ConvexPartition(textureVertices);

            _scale = 1f;

            //scale the vertices from graphics space to sim space
            foreach (Vertices vertex in vertices)
            {
                Vector2[] verticesArray = vertex.ToArray();
                var       hull          = ShadowHull.CreateConvex(ref verticesArray);
                hulls.Add(hull);
                krypton.Hulls.Add(hull);
            }
        }
        public override void Initialize()
        {
            //Load texture that will represent the physics body
            Texture2D polygonTexture = CCApplication.SharedApplication.Content.Load <Texture2D>("box2d/Texture");

            //Create an array to hold the data from the texture
            uint[] data = new uint[polygonTexture.Width * polygonTexture.Height];

            //Transfer the texture data to the array
            polygonTexture.GetData(data);

            //Find the vertices that makes up the outline of the shape in the texture
            Vertices verts = PolygonTools.CreatePolygon(data, polygonTexture.Width);

            //For now we need to scale the vertices (result is in pixels, we use meters)
            Vector2 scale = new Vector2(0.07f, -0.07f);

            verts.Scale(ref scale);

            //We also need to move the polygon so that (0,0) is the center of the polygon.
            Vector2 centroid = -verts.GetCentroid();

            verts.Translate(ref centroid);

            //Create a single body with multiple fixtures
            Body compund = BodyFactory.CreateCompoundPolygon(World, BayazitDecomposer.ConvexPartition(verts), 1);

            compund.BodyType = BodyType.Dynamic;
            compund.Position = new Vector2(0, 20);

            base.Initialize();
        }
示例#5
0
        public override void Initialize()
        {
            Bitmap polygonTexture = Bitmap.FromFile("AltData/FarseerPhysics/Testbed/Content/Texture.png");

            uint[] data = new uint[polygonTexture.PixelWidth * polygonTexture.PixelHeight];

            BitmapData bitmapData = polygonTexture.LockBits(ImageLockMode.ReadOnly);

            byte[] src_buffer = bitmapData.Scan0;
            System.Buffer.BlockCopy(src_buffer, 0, data, 0, src_buffer.Length);
            polygonTexture.UnlockBits(bitmapData);

            Vertices verts = PolygonTools.CreatePolygon(data, polygonTexture.PixelWidth);

            Vector2 scale = new Vector2(0.07f, -0.07f);

            verts.Scale(ref scale);

            Vector2 centroid = -verts.GetCentroid();

            verts.Translate(ref centroid);

            Body compund = BodyFactory.CreateCompoundPolygon(World, Triangulate.ConvexPartition(verts, TriangulationAlgorithm.Bayazit), 1);

            compund.Position = new Vector2(-25, 30);

            Body b = compund.DeepClone();

            b.Position = new Vector2(20, 30);
            b.BodyType = BodyType.Dynamic;

            base.Initialize();
        }
示例#6
0
        public FSCompoundPolygonBody(World world, Subtexture subtexture, float density, Vector2 position = default(Vector2), BodyType bodyType = BodyType.Static)
            : base(world, subtexture, position, bodyType)
        {
            var data = new uint[subtexture.sourceRect.Width * subtexture.sourceRect.Height];

            subtexture.texture2D.GetData(0, subtexture.sourceRect, data, 0, data.Length);

            var verts = PolygonTools.CreatePolygon(data, subtexture.sourceRect.Width);

            verts = SimplifyTools.DouglasPeuckerSimplify(verts, 2);

            var decomposedVerts = Triangulate.ConvexPartition(verts, TriangulationAlgorithm.Bayazit);

            for (var i = 0; i < decomposedVerts.Count; i++)
            {
                var polygon = decomposedVerts[i];
                polygon.Translate(-subtexture.center);
            }

            // add the fixtures
            var fixtures = Farseer.FixtureFactory.attachCompoundPolygon(decomposedVerts, density, body);

            // fetch all the Vertices and save a copy in case we need to scale them later
            foreach (var fixture in fixtures)
            {
                _verts.Add(new Vertices((fixture.Shape as PolygonShape).Vertices));
            }
        }
示例#7
0
        public static List <Vertices> GetCompoundPolygonVertices(Texture2D _polygonTexture, float _scale, ref Vector2 origin)
        {
            uint[] data = new uint[_polygonTexture.Width * _polygonTexture.Height];
            _polygonTexture.GetData(data);

            Vertices textureVertices = PolygonTools.CreatePolygon(data, _polygonTexture.Width, false);

            Vector2 centroid = -textureVertices.GetCentroid();

            textureVertices.Translate(ref centroid);

            origin = -centroid;

            textureVertices = SimplifyTools.ReduceByDistance(textureVertices, 4f);

            List <Vertices> list = BayazitDecomposer.ConvexPartition(textureVertices);

            Vector2 vertScale = new Vector2(ConvertUnits.ToSimUnits(1)) * _scale;

            foreach (Vertices vertices in list)
            {
                vertices.Scale(ref vertScale);
            }

            return(list);
        }
示例#8
0
        public override void Initialize()
        {
            if (_world != null && Texture != null)
            {
                var data = new uint[Texture.Width * Texture.Height];
                Texture.GetData(data);
                var verts = PolygonTools.CreatePolygon(data, Texture.Width, true);
                var scale = ConvertUnits.ToSimUnits(new Vector2(1, 1));
                verts.Scale(ref scale);
                var list     = BayazitDecomposer.ConvexPartition(verts);
                var compound = BodyFactory.CreateCompoundPolygon(_world, list, 1);
                compound.BodyType = BodyType.Dynamic;
                Body             = compound;
                Body.Restitution = 1;

                SetStartPosition();

                var joint = new FixedPrismaticJoint(Body, Body.Position, new Vector2(1, 0));
                joint.LimitEnabled  = true;
                joint.LowerLimit    = -ConvertUnits.ToSimUnits((_screenBounds.Width - Texture.Width) / 2f);
                joint.UpperLimit    = ConvertUnits.ToSimUnits((_screenBounds.Width - Texture.Width) / 2f);
                joint.Enabled       = true;
                joint.MaxMotorForce = 70f;
                _world.AddJoint(joint);
            }

            base.Initialize();
        }
        } // PhysicTexture(setPos, setDensity, setDiffuseTexture, setCollisionTexture)

        #endregion

        #region CreateBody
        /// <summary> Creates the physics Body </summary>
        private void CreateBody()
        {
            uint[] data = new uint[collisionTexture.Width * collisionTexture.Height];
            collisionTexture.GetData(data);

            Vertices textureVertices = PolygonTools.CreatePolygon(data, collisionTexture.Width, true);

            Vector2 centroid = -textureVertices.GetCentroid();

            textureVertices.Translate(ref centroid);

            origin = -centroid;

            textureVertices = SimplifyTools.ReduceByDistance(textureVertices, 4f);

            Vector2         vertScale = new Vector2(ConvertUnits.ToSimUnits(1));
            List <Vertices> list      = BayazitDecomposer.ConvexPartition(textureVertices);

            list.ForEach(v => v.Scale(ref vertScale));

            size = list.SelectMany(v => v).CalculateSize();

            body          = BodyFactory.CreateCompoundPolygon(PhysicsGameScreen.World, list, density, BodyType.Static);//BodyType.Dynamic);
            body.Position = position;
            body.UserData = "physictexture";
            body.Friction = 10f;
        } // CreateBody(setPos, setDensity)
示例#10
0
        public static List <Fixture> TextureToPolygon(Texture2D texture, Vector2 scaling, BodyType bodyType, Vector2 position, float density)
        {
            uint[] data = new uint[texture.Width * texture.Height];
            texture.GetData(data);
            Vertices vertices      = PolygonTools.CreatePolygon(data, texture.Width, texture.Height, true);
            var      polygonOffset = new Vector2(-texture.Width / 2, -texture.Height / 2);

            vertices.Translate(ref polygonOffset);
            Vector2 scale = new Vector2(0.01f, 0.01f) * scaling;

            vertices.Scale(ref scale);

            List <Vertices> tempList = EarclipDecomposer.ConvexPartition(vertices);
            List <Vertices> toRemove = new List <Vertices>();

            foreach (Vertices item in tempList)
            {
                if (item.Count == 0)
                {
                    toRemove.Add(item);
                }
            }
            foreach (Vertices item in toRemove)
            {
                tempList.Remove(item);
            }

            List <Fixture> combine = FixtureFactory.CreateCompoundPolygon(Level.Physics, tempList, 1);

            combine[0].Body.BodyType = bodyType;
            combine[0].Body.Position = ToMeter(position);
            return(combine);
        }
示例#11
0
        private void CreateBody()
        {
            uint[] data = new uint[_textureBodyXna.Width * _textureBodyXna.Height];
            _textureBodyXna.GetData(data);

            Vertices textureVertices = PolygonTools.CreatePolygon(data, _textureBodyXna.Width, true);

            Vector2 centroid = -textureVertices.GetCentroid();

            textureVertices.Translate(ref centroid);


            Vector2         vertScale    = new Vector2(ConvertUnits.ToSimUnits(1));
            List <Vertices> triangulated = BayazitDecomposer.ConvexPartition(textureVertices);

            triangulated.ForEach(v => v.Scale(ref vertScale));

            _size   = _calcSize(triangulated.SelectMany(v => v));
            _origin = -centroid * vertScale;

            body = CreateBodyByList(triangulated);

            _parts = new Body[0];
            _infos.Values.ToList().ForEach(info => info.Effect.Dispose());
            _infos.Clear();

            foreach (Fixture fixture in body.FixtureList)
            {
                Guid id = Guid.NewGuid();

                fixture.UserData = id;
                _infos[id]       = new FixtureInfo(_effectXna.Clone(), fixture, _origin,
                                                   new Vector2(_diffuseTexture.Width, _diffuseTexture.Height)); //this.TextureSize
            }
        } // CreateBody()
示例#12
0
        public override void Initialize()
        {
            Texture2D polygonTexture = CCApplication.SharedApplication.Content.Load <Texture2D>("box2d/Texture");

            uint[] data = new uint[polygonTexture.Width * polygonTexture.Height];
            polygonTexture.GetData(data);

            Vertices verts = PolygonTools.CreatePolygon(data, polygonTexture.Width);

            Vector2 scale = new Vector2(0.07f, -0.07f);

            verts.Scale(ref scale);

            Vector2 centroid = -verts.GetCentroid();

            verts.Translate(ref centroid);

            Body compund = BodyFactory.CreateCompoundPolygon(World, BayazitDecomposer.ConvexPartition(verts), 1);

            compund.Position = new Vector2(-25, 30);

            Body b = compund.DeepClone();

            b.Position = new Vector2(20, 30);
            b.BodyType = BodyType.Dynamic;

            base.Initialize();
        }
示例#13
0
        public void shapeFromTexture(Texture tex)
        {
            byte[] data;


            using (MemoryStream ms = new MemoryStream())
            {
                tex.bitmap.Save(ms, ImageFormat.Png);
                data = ms.ToArray();
                ms.Dispose();
            }

            uint[] bytes = new uint[data.Length];

            for (int i = 0; i < data.Length; i++)
            {
                bytes[i] = data[i];
            }

            Vertices verts = PolygonTools.CreatePolygon(bytes, tex.bitmap.Width, true);

            vertices.Clear();

            for (int i = 0; i < verts.Count; i++)
            {
                vertices.Add(new Vector((float)verts[i].X, (float)verts[i].Y));
            }
        }
示例#14
0
        public static Body ConvertToBody(this Texture2D me, Scene scene)
        {
            var polygonTexture = me;

            var data = new uint[polygonTexture.Width * polygonTexture.Height];

            polygonTexture.GetData(data);

            var verts = PolygonTools.CreatePolygon(data, polygonTexture.Width, true);

            //These 2 seem to work the best with tile maps
            verts = SimplifyTools.CollinearSimplify(verts);

            verts = SimplifyTools.DouglasPeuckerSimplify(verts, 0f);

            var list = BayazitDecomposer.ConvexPartition(verts);

            var vertScale = new Vector2(1f / ConvertUnits._displayUnitsToSimUnitsRatio);

            foreach (var vertices in list)
            {
                vertices.Scale(ref vertScale);
            }

            var body = BodyFactory.CreateCompoundPolygon(scene.World, list, 1);

            Debugging.Debug.WriteLine(
                "WARNING: In Texture2D.ConvertToBody, Body functions have not been implemented!");
            body.Friction = 0f;
            body.IsStatic = true;
            return(body);
        }
示例#15
0
        public override void Initialize()
        {
            Texture2D polygonTexture = GameInstance.Content.Load <Texture2D>("Texture");

            uint[] data = new uint[polygonTexture.Width * polygonTexture.Height];
            polygonTexture.GetData(data);

            Vertices verts = PolygonTools.CreatePolygon(data, polygonTexture.Width);

            Vector2 scale = new Vector2(0.07f, -0.07f);

            verts.Scale(ref scale);

            Vector2 centroid = -verts.GetCentroid();

            verts.Translate(ref centroid);

            Body compund = World.CreateCompoundPolygon(Triangulate.ConvexPartition(verts, TriangulationAlgorithm.Bayazit), 1);

            compund.Position = new Vector2(-25, 30);

            Body b = compund.DeepClone();

            b.Position = new Vector2(20, 30);
            b.BodyType = BodyType.Dynamic;

            base.Initialize();
        }
示例#16
0
        public CaveWall(GameWorld gameWorld, string textureName)
            : base(gameWorld, textureName)
        {
            // Read the texture data
            var textureData = new uint[Texture.Width * Texture.Height];

            Texture.GetData(textureData);

            // Detect an outline of the texture
            var outline = PolygonTools.CreatePolygon(textureData, Texture.Width);

            // Scale the outline so that it fits the size of my game world
            var scaleVector = ConvertUnits.ToSimUnits(2, 2);

            outline.Scale(scaleVector);

            // Simplify the outline to remove redundant points
            outline = SimplifyTools.CollinearSimplify(outline);

            // Decompose the outline into polygons
            var decomposed = BayazitDecomposer.ConvexPartition(outline);

            // Create the body for the game world
            Body = BodyFactory.CreateCompoundPolygon(World, decomposed, 1f);
        }
示例#17
0
        public override void LoadContent()
        {
            base.LoadContent();

            DebugView.AppendFlags(DebugViewFlags.Shape);

            World.Gravity = Vector2.Zero;

            _border          = new Border(World, ScreenManager, Camera);
            _breakableBodies = new List <BreakableBody>();

            Texture2D alphabet = ScreenManager.Content.Load <Texture2D>("Samples/alphabet");

            uint[] data = new uint[alphabet.Width * alphabet.Height];
            alphabet.GetData(data);

            List <Vertices> list = PolygonTools.CreatePolygon(data, alphabet.Width, 3.5f, 20, true, true);

            for (int i = 0; i < list.Count; i++)
            {
                list[i].Scale(new Vector2(1f, -1f)); // flip Vert
            }
            float yOffset = -5f;
            float xOffset = -14f;

            for (int i = 0; i < list.Count; i++)
            {
                if (i == 9)
                {
                    yOffset = 0f;
                    xOffset = -14f;
                }
                if (i == 18)
                {
                    yOffset = 5f;
                    xOffset = -12.25f;
                }
                Vertices polygon  = list[i];
                Vector2  centroid = -polygon.GetCentroid();
                polygon.Translate(ref centroid);
                polygon = SimplifyTools.CollinearSimplify(polygon);
                polygon = SimplifyTools.ReduceByDistance(polygon, 4);
                List <Vertices> triangulated = Triangulate.ConvexPartition(polygon, TriangulationAlgorithm.Bayazit);

                Vector2 vertScale = new Vector2(13.916667f, 23.25f) / new Vector2(alphabet.Width, alphabet.Height);
                foreach (Vertices vertices in triangulated)
                {
                    vertices.Scale(ref vertScale);
                }

                var breakableBody = new BreakableBody(World, triangulated, 1);
                breakableBody.MainBody.Position = new Vector2(xOffset, yOffset);
                breakableBody.Strength          = 100;
                _breakableBodies.Add(breakableBody);

                xOffset += 3.5f;
            }
        }
        public override void LoadContent()
        {
            base.LoadContent();

            DebugView.AppendFlags(DebugViewFlags.Shape);

            World.Gravity = Vector2.Zero;

            _border = new Border(World, ScreenManager, Camera);

            Texture2D alphabet = ScreenManager.Content.Load <Texture2D>("Samples/alphabet");

            uint[] data = new uint[alphabet.Width * alphabet.Height];
            alphabet.GetData(data);

            List <Vertices> list = PolygonTools.CreatePolygon(data, alphabet.Width, 3.5f, 20, true, true);

            float yOffset = -5f;
            float xOffset = -14f;

            for (int i = 0; i < list.Count; i++)
            {
                if (i == 9)
                {
                    yOffset = 0f;
                    xOffset = -14f;
                }
                if (i == 18)
                {
                    yOffset = 5f;
                    xOffset = -12.25f;
                }
                Vertices polygon  = list[i];
                Vector2  centroid = -polygon.GetCentroid();
                polygon.Translate(ref centroid);
                polygon = SimplifyTools.CollinearSimplify(polygon);
                polygon = SimplifyTools.ReduceByDistance(polygon, 4);
                List <Vertices> triangulated = Triangulate.ConvexPartition(polygon, TriangulationAlgorithm.Bayazit);

#if WINDOWS_PHONE
                const float scale = 0.6f;
#else
                const float scale = 1f;
#endif
                Vector2 vertScale = new Vector2(ConvertUnits.ToSimUnits(1)) * scale;
                foreach (Vertices vertices in triangulated)
                {
                    vertices.Scale(ref vertScale);
                }

                BreakableBody breakableBody = new BreakableBody(triangulated, World, 1);
                breakableBody.MainBody.Position = new Vector2(xOffset, yOffset);
                breakableBody.Strength          = 100;
                World.AddBreakableBody(breakableBody);

                xOffset += 3.5f;
            }
        }
示例#19
0
        public static MPTanks.Engine.Serialization.GameObjectBodySpecifierJSON BuildBody(uint[] imageData, int width, Vector2 objSize)
        {
            var vertices  = PolygonTools.CreatePolygon(imageData, width, true);
            var imgHeight = imageData.Length / width;
            var scale     = new Vector2(objSize.X / width, objSize.Y / imgHeight);

            vertices.Scale(scale);
            var decomposed = Triangulate.ConvexPartition(vertices, TriangulationAlgorithm.Seidel);

            var result   = new Engine.Serialization.GameObjectBodySpecifierJSON();
            var fixtures = new List <Engine.Serialization.GameObjectBodySpecifierJSON.FixtureSpecifierJSON>();

            foreach (var fixture in decomposed)
            {
                var fx       = new Engine.Serialization.GameObjectBodySpecifierJSON.FixtureSpecifierJSON();
                var vertList = new List <Engine.Serialization.JSONVector>();
                var holeList = new List <Engine.Serialization.GameObjectBodySpecifierJSON.FixtureSpecifierJSON.HolesSpecifierJSON>();
                foreach (var vert in fixture)
                {
                    vertList.Add(new Engine.Serialization.JSONVector
                    {
                        X = vert.X - (objSize.X / 2),
                        Y = vert.Y - (objSize.Y / 2)
                    });
                }

                if (fixture.Holes != null)
                {
                    foreach (var h in fixture.Holes)
                    {
                        var hole  = new Engine.Serialization.GameObjectBodySpecifierJSON.FixtureSpecifierJSON.HolesSpecifierJSON();
                        var vList = new List <Engine.Serialization.JSONVector>();
                        foreach (var v in h)
                        {
                            vList.Add(new Engine.Serialization.JSONVector
                            {
                                X = v.X - (objSize.X / 2),
                                Y = v.Y - (objSize.Y / 2)
                            });
                        }
                        hole.Vertices = vList.ToArray();

                        holeList.Add(hole);
                    }
                }

                fx.Vertices = vertList.ToArray();
                fx.Holes    = holeList.ToArray();
                fixtures.Add(fx);
            }

            result.Fixtures = fixtures.ToArray();
            result.Size     = new Engine.Serialization.JSONVector {
                X = objSize.X, Y = objSize.Y
            };
            return(result);
        }
示例#20
0
        public override void LoadContent()
        {
            base.LoadContent();

            World.Gravity = Vector2.Zero;

            _border = new Border(World, this, ScreenManager.GraphicsDevice.Viewport);

            //load texture that will represent the physics body
            _polygonTexture = ScreenManager.Content.Load <Texture2D>("Samples/object");

            //Create an array to hold the data from the texture
            uint[] data = new uint[_polygonTexture.Width * _polygonTexture.Height];

            //Transfer the texture data to the array
            _polygonTexture.GetData(data);

            //Find the vertices that makes up the outline of the shape in the texture
            Vertices textureVertices = PolygonTools.CreatePolygon(data, _polygonTexture.Width, false);

            //The tool return vertices as they were found in the texture.
            //We need to find the real center (centroid) of the vertices for 2 reasons:

            //1. To translate the vertices so the polygon is centered around the centroid.
            Vector2 centroid = -textureVertices.GetCentroid();

            textureVertices.Translate(ref centroid);

            //2. To draw the texture the correct place.
            _origin = -centroid;

            //We simplify the vertices found in the texture.
            textureVertices = SimplifyTools.ReduceByDistance(textureVertices, 4f);

            //Since it is a concave polygon, we need to partition it into several smaller convex polygons
            List <Vertices> list = BayazitDecomposer.ConvexPartition(textureVertices);

            //Adjust the scale of the object for WP7's lower resolution
#if WINDOWS_PHONE
            _scale = 0.6f;
#else
            _scale = 1f;
#endif

            //scale the vertices from graphics space to sim space
            Vector2 vertScale = new Vector2(ConvertUnits.ToSimUnits(1)) * _scale;
            foreach (Vertices vertices in list)
            {
                vertices.Scale(ref vertScale);
            }

            //Create a single body with multiple fixtures
            _compound          = BodyFactory.CreateCompoundPolygon(World, list, 1f, BodyType.Dynamic);
            _compound.BodyType = BodyType.Dynamic;
        }
示例#21
0
        public override void LoadContent()
        {
            base.LoadContent();

            World.Gravity = Vector2.Zero;

            _border = new Border(World, ScreenManager, Camera);

            //load texture that will represent the physics body
            _polygonTexture = ScreenManager.Content.Load <Texture2D>("Samples/object");

            //Create an array to hold the data from the texture
            uint[] data = new uint[_polygonTexture.Width * _polygonTexture.Height];

            //Transfer the texture data to the array
            _polygonTexture.GetData(data);

            //Find the vertices that makes up the outline of the shape in the texture
            Vertices textureVertices = PolygonTools.CreatePolygon(data, _polygonTexture.Width, false);

            //The tool return vertices as they were found in the texture.
            //We need to find the real center (centroid) of the vertices for 2 reasons:

            //1. To translate the vertices so the polygon is centered around the centroid.
            Vector2 centroid = -textureVertices.GetCentroid();

            textureVertices.Translate(ref centroid);

            //2. To draw the texture the correct place.
            _origin = -centroid;
            var aabb = textureVertices.GetAABB();

            _polygonSize = new Vector2(aabb.Width, aabb.Height);

            //We simplify the vertices found in the texture.
            textureVertices = SimplifyTools.ReduceByDistance(textureVertices, 4f);

            //Since it is a concave polygon, we need to partition it into several smaller convex polygons
            List <Vertices> list = Triangulate.ConvexPartition(textureVertices, TriangulationAlgorithm.Bayazit);

            //scale the vertices from graphics space to sim space
            Vector2 vertScale = new Vector2(1f / 24f);

            _polygonSize *= vertScale;
            foreach (Vertices vertices in list)
            {
                vertices.Scale(new Vector2(1f, -1f));
                vertices.Translate(new Vector2(0f, 30f));
                vertices.Scale(vertScale);
            }

            //Create a single body with multiple fixtures
            _compound          = World.CreateCompoundPolygon(list, 1f, Vector2.Zero, 0, BodyType.Dynamic);
            _compound.BodyType = BodyType.Dynamic;
        }
示例#22
0
        public static PhysicsFrame GetVerticesForTextureData(uint[] textureData, int textureWidth)
        {
            Vertices textureVertices = PolygonTools.CreatePolygon(textureData, textureWidth, false);
            Vector2  offset          = -textureVertices.GetCentroid();

            textureVertices.Translate(ref offset);
            SimplifyTools.MergeParallelEdges(textureVertices, 0);
            List <Vertices> convexVertices = BayazitDecomposer.ConvexPartition(textureVertices);

            ConvertUnits.ScaleToSimUnits(ref convexVertices);
            return(new PhysicsFrame(convexVertices, -offset));
        }
示例#23
0
        static List <Vertices> ToVertices(Texture2D texture, out Vector2 origin)
        {
            //Create an array to hold the data from the texture
            uint[] data = new uint[texture.Width * texture.Height];

            //Transfer the texture data to the array
            texture.GetData(data);

            Vertices textureVertices = PolygonTools.CreatePolygon(data, texture.Width, false);

            //The tool return vertices as they were found in the texture.
            //We need to find the real center (centroid) of the vertices for 2 reasons:

            //1. To translate the vertices so the polygon is centered around the centroid.
            var centroid = -textureVertices.GetCentroid();

            textureVertices.Translate(ref centroid);

            //2. To draw the texture the correct place.
            origin = -centroid;

            //We simplify the vertices found in the texture.
            textureVertices = SimplifyTools.ReduceByDistance(textureVertices, 5f);

            //Since it is a concave polygon, we need to partition it into several smaller convex polygons
            //List<Vertices> list = BayazitDecomposer.ConvexPartition(textureVertices);
            try
            {
                List <Vertices> list = BayazitDecomposer.ConvexPartition(textureVertices);


                //Now we need to scale the vertices (result is in pixels, we use meters)
                //At the same time we flip the y-axis.
                var scale = new Vector2(0.015f, 0.015f);

                foreach (Vertices vertices in list)
                {
                    vertices.Scale(ref scale);

                    //When we flip the y-axis, the orientation can change.
                    //We need to remember that FPE works with CCW polygons only.
                    vertices.ForceCounterClockWise();
                }
                return(list);
            }
            catch
            {
                return(new List <Vertices>());
            }
        }
示例#24
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="tex">Texture of shape</param>
        /// <param name="pos">Postion in physics units</param>
        /// <param name="isStatic">True for static</param>
        /// <param name="world">World</param>
        public Shape(Texture2D tex, Vector2 pos, bool isStatic, bool colliedsWithPlayerLaser, World world)
        {
            this.tex = tex;
            this.pos = pos;

            uint[] data = new uint[tex.Width * tex.Height];

            tex.GetData(data);

            Vertices verts = PolygonTools.CreatePolygon(data, tex.Width);

            // How do we work out what the correct scale factor is? - Trial and error
            Vector2 scale = new Vector2(0.015f, 0.015f); // was 0.025f

            verts.Scale(ref scale);

            Vector2 centroid = -verts.GetCentroid();

            // orgin = centroid; // just a little test
            verts.Translate(ref centroid);

            var decomposedVertices = BayazitDecomposer.ConvexPartition(verts);

            shapeBody = BodyFactory.CreateCompoundPolygon(world, decomposedVertices, 1);
            if (this.isStatic)
            {
                shapeBody.BodyType = BodyType.Static;
            }
            else
            {
                shapeBody.BodyType = BodyType.Dynamic;
            }
            if (isStatic == true)
            {
                shapeBody.BodyType = BodyType.Static;
            }
            shapeBody.Position = pos / 64;
            shapeBody.BodyId   = 3;
            if (colliedsWithPlayerLaser)
            {
                shapeBody.CollisionCategories = Category.Cat4;
            }
            else
            {
                shapeBody.CollisionCategories = Category.Cat8;
            }
            shapeBody.CollidesWith = Category.All ^ Category.Cat2;
            orgin = new Vector2(tex.Width / 2, tex.Height / 2); // this seems to work well
        }
示例#25
0
        public static TexVertOutput TexToVert(World world, Texture2D texture, float mass, bool useCentroid, float scale)
        {
            Vertices      verts;
            TexVertOutput output = new TexVertOutput();

            //  Creates an array for every pixel in the texture
            uint[] data = new uint[texture.Width * texture.Height];

            texture.GetData(data);

            verts = PolygonTools.CreatePolygon(data, texture.Width, false);

            Vector2 centroid = Vector2.Zero;

            //  Origin needs to be altered so it uses the origin of the verts
            //  rather than the texture's centre.
            if (useCentroid)
            {
                centroid = -verts.GetCentroid();
                verts.Translate(ref centroid);
            }
            else
            {
                centroid = ConvertUnits.ToSimUnits(new Vector2(texture.Width, texture.Height) * 0.5f);
            }


            float   simScale = ConvertUnits.ToSimUnits(scale);
            Vector2 Scale    = new Vector2(simScale, simScale);

            verts.Scale(ref Scale);

            verts = SimplifyTools.ReduceByDistance(verts, ConvertUnits.ToSimUnits(4f));

            Body body = BodyFactory.CreateCompoundPolygon(world, EarclipDecomposer.ConvexPartition(verts), mass);

            body.BodyType = BodyType.Dynamic;

            if (!useCentroid)
            {
                body.LocalCenter = centroid;
            }

            output.Body   = body;
            output.Origin = ConvertUnits.ToDisplayUnits(centroid);

            return(output);
        }
示例#26
0
        public void findShadowHull(Texture2D texture)
        {
            //Create an array to hold the data from the texture
            uint[] data = new uint[texture.Width * texture.Height];

            //Transfer the texture data to the array
            texture.GetData(data);

            //Find the vertices that makes up the outline of the shape in the texture
            textureVertices = PolygonTools.CreatePolygon(data, texture.Width, false);

            //The tool return vertices as they were found in the texture.
            //We need to find the real center (centroid) of the vertices for 2 reasons:

            //1. To translate the vertices so the polygon is centered around the centroid.
            Vector2 centroid = -textureVertices.GetCentroid();

            textureVertices.Translate(ref centroid);

            //2. To draw the texture the correct place.
            _origin = -centroid;

            //We simplify the vertices found in the texture.
            textureVertices = SimplifyTools.CollinearSimplify(textureVertices, 0f);

            //Since it is a concave polygon, we need to partition it into several smaller convex polygons
            list = BayazitDecomposer.ConvexPartition(textureVertices);

            //Adjust the scale of the object for WP7's lower resolution
            //Adjust the scale of the object for WP7's lower resolution
            #if WINDOWS_PHONE
            _scale = 0.6f;
            #else
            _scale = 1f;
            #endif

            //scale the vertices from graphics space to sim space
            Vector2 vertScale = new Vector2(ConvertUnits.ToSimUnits(1)) * _scale;
            foreach (Vertices vertices in list)
            {
                vertices.Scale(ref vertScale);
                Vector2[] verticesArray = vertices.ToArray();
                var       hull          = ShadowHull.CreateConvex(ref verticesArray);
                hulls.Add(hull);
                krypton.Hulls.Add(hull);
            }
        }
示例#27
0
        public PhysicObj(World world, Texture2D texture, Vector2 scale, float density)
            : base(texture, 0, scale, Vector2.Zero)
        {
            this.texture = texture;
            this.scale   = scale;
            scale       /= MULTIPLER;

            uint[] data = new uint[texture.Width * texture.Height];

            texture.GetData(data);

            Vertices textureVertices = PolygonTools.CreatePolygon(data, texture.Width, false);

            Vector2 centroid = -textureVertices.GetCentroid();

            textureVertices.Translate(ref centroid);

            origin = -centroid;

            textureVertices = SimplifyTools.ReduceByDistance(textureVertices, 4f);

            List <Vertices> list = BayazitDecomposer.ConvexPartition(textureVertices);

            float minX = float.PositiveInfinity;
            float maxX = float.NegativeInfinity;

            foreach (Vertices vertices in list)
            {
                vertices.Scale(ref scale);
                foreach (Vector2 vec in vertices)
                {
                    if (vec.X < minX)
                    {
                        minX = vec.X;
                    }
                    if (maxX < vec.X)
                    {
                        maxX = vec.X;
                    }
                }
            }

            body          = BodyFactory.CreateCompoundPolygon(world, list, density, BodyType.Dynamic);
            body.BodyType = BodyType.Dynamic;
        }
示例#28
0
        public void AddShadowForObject(Texture2D texture, Vector2 position)
        {
            uint[] data = new uint[texture.Width * texture.Height];
            texture.GetData <uint>(data);

            foreach (var poly in EarclipDecomposer.ConvexPartition(PolygonTools.CreatePolygon(data, texture.Width)))
            {
                if (poly.Count >= 3)
                {
                    var array = poly.ToArray();

                    var hull = ShadowHull.CreateConvex(ref array);
                    hull.Position = position;

                    _krypton.Hulls.Add(hull);
                }
            }
        }
示例#29
0
        private void CreatePolygon(Texture2D a_texture, World a_world)
        {
            //Create an array to hold the data from the texture
            uint[] data = new uint[a_texture.Width * a_texture.Height];

            //Transfer the texture data to the array
            a_texture.GetData(data);

            //Find the vertices that makes up the outline of the shape in the texture
            Vertices textureVertices = PolygonTools.CreatePolygon(data, a_texture.Width, false);

            //The tool return vertices as they were found in the texture.
            //We need to find the real center (centroid) of the vertices for 2 reasons:

            //1. To translate the vertices so the polygon is centered around the centroid.
            Vector2 centroid = -textureVertices.GetCentroid();

            textureVertices.Translate(ref centroid);

            //2. To draw the texture the correct place.
            _origin = -centroid;

            //We simplify the vertices found in the texture.
            textureVertices = SimplifyTools.ReduceByDistance(textureVertices, 4f);

            //Since it is a concave polygon, we need to partition it into several smaller convex polygons
            List <Vertices> list = Triangulate.ConvexPartition(textureVertices, TriangulationAlgorithm.Bayazit);


            //Adjust the scale of the object for WP7's lower resolution
            _scale = new Vector2(1f, 1f);

            //scale the vertices from graphics space to sim space
            Vector2 vertScale = new Vector2(ConvertUnits.ToSimUnits(1)) * _scale;

            foreach (Vertices vertices in list)
            {
                vertices.Scale(ref vertScale);
            }

            //Create a single body with multiple fixtures
            _body          = BodyFactory.CreateCompoundPolygon(a_world, list, 1f, BodyType.Dynamic);
            _body.BodyType = BodyType.Dynamic;
        }
示例#30
0
        private static Body createBody(Sprite sprite, World world)
        {
            uint[] texData = new uint[sprite.Texture.Width * sprite.Texture.Height];

            sprite.Texture.GetData(texData);

            //Find the vertices that makes up the outline of the shape in the texture
            Vertices verts = PolygonTools.CreatePolygon(texData, sprite.Texture.Width, false);

            //For now we need to scale the vertices (result is in pixels, we use meters)
            Vector2 scale = new Vector2(ConvertUnits.ToSimUnits(1));

            verts.Scale(ref scale);

            //Since it is a concave polygon, we need to partition it into several smaller convex polygons
            List <Vertices> vertexList = Triangulate.ConvexPartition(verts, TriangulationAlgorithm.Bayazit);

            return(BodyFactory.CreateCompoundPolygon(world, vertexList, 1f));
        }