示例#1
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();
        }
示例#3
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()
示例#4
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();
        }
        /// <summary>
        /// Make a concave polygon into a convex one
        /// </summary>
        /// <param name="poly"></param>
        /// <returns></returns>
        public static IEnumerable <IPoly> MakeConvex(IPoly poly)
        {
            List <Vector3>         input  = poly.GetPoints().ToList();
            List <List <Vector3> > output = BayazitDecomposer.ConvexPartition(input);

            return(output.Select(x => poly.Clone(x.ToArray())));
        }
示例#6
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);
        }
    void OnDrawGizmos()
    {
        if (!Application.isPlaying || !show)
        {
            return;
        }

        Gizmos.color = Color.green;

        List <Vector2> worldColPoints = new List <Vector2>();

        foreach (Vector2 point in col.points)
        {
            Vector2 currentWorldPoint = this.transform.TransformPoint(point);
            worldColPoints.Add(currentWorldPoint);
        }

        List <Vector2> vertices = worldColPoints;

        List <List <Vector2> > listOfConvexPolygonPoints = BayazitDecomposer.ConvexPartition(vertices);

        foreach (List <Vector2> pointsOfIndivualConvexPolygon in listOfConvexPolygonPoints)
        {
            List <Vector2> currentPolygonVertices = pointsOfIndivualConvexPolygon;

            for (int i = 0; i < currentPolygonVertices.Count; i++)
            {
                Vector2 currentVertex = currentPolygonVertices[i];
                Vector2 nextVertex    = currentPolygonVertices[i + 1 >= currentPolygonVertices.Count ? 0 : i + 1];

                Gizmos.DrawLine(currentVertex, nextVertex);
            }
        }
    }
示例#8
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);
        }
示例#9
0
        private void CreateFixtures()
        {
            //Partition shape into convex pieces
            List <Vertices> verts;

            if (!Vertices.IsConvex())
            {
                verts = BayazitDecomposer.ConvexPartition(Vertices);
            }
            else
            {
                verts = new List <Vertices>();
                verts.Add(Vertices);
            }

            //Create fixtures for each piece
            foreach (Vertices v in verts)
            {
                PolygonShape shape = new PolygonShape(v, _density);
                Body.CreateFixture(shape);
            }

            //wake body up
            Body.Awake = true;
        }
示例#10
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();
        }
示例#11
0
        } // 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)
示例#12
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);
        }
        public override void LoadContent()
        {
            base.LoadContent();

            DebugView.AppendFlags(DebugViewFlags.Shape);

            World.Gravity = Vector2.Zero;

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

            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 = BayazitDecomposer.ConvexPartition(polygon);

#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;
            }
        }
示例#14
0
        public bool CheckIfFilled(Map.Map map, int layer, ObstacleCollection obstacles)
        {
            Simplify();
            var convexPolygons        = BayazitDecomposer.ConvexPartition(this);
            var blockPointsDictionary = new Dictionary <Block, List <Vector2> >();
            var blocks         = GetAssociatedBlocks(convexPolygons, map, layer, blockPointsDictionary);
            var layerObstacles = CreateLayerObstacles(layer, obstacles); //ToDo: Don't call this method every time, the result does not change...

            return(CheckLid(blocks, map, layer, layerObstacles, blockPointsDictionary));
        }
示例#15
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;
        }
示例#16
0
        public void Initialize(Map.Map map)
        {
            var collision = new CollisionMap(map);

            if (_world == null)
            {
                _world = new World(new Vector2(0, 0));
            }
            else
            {
                _world.Clear();
            }

            var obstacles       = collision.GetObstacles();
            var layer2Obstacles = obstacles.GetObstacles(2);

            foreach (var obstacle in layer2Obstacles)
            {
                var body = new Body(_world)
                {
                    BodyType = BodyType.Static
                };
                _json.SetName(body, "Building" + obstacle.Z);
                Shape   shape;
                Fixture fixture;
                switch (obstacle.Type)
                {
                case ObstacleType.Line:
                    var lineObstacle = (LineObstacle)obstacle;
                    shape   = new EdgeShape(lineObstacle.Start.ToMeters(), lineObstacle.End.ToMeters());
                    fixture = body.CreateFixture(shape);
                    _json.SetName(fixture, "Building" + obstacle.Z);
                    break;

                case ObstacleType.Polygon:
                    var polygonObstacle = (PolygonObstacle)obstacle;
                    var convexPolygons  = BayazitDecomposer.ConvexPartition(polygonObstacle.Vertices);
                    foreach (var convexPolygon in convexPolygons)
                    {
                        shape   = new PolygonShape(convexPolygon.ToMeters(), 1);
                        fixture = body.CreateFixture(shape);
                        _json.SetName(fixture, "Building" + obstacle.Z);
                    }
                    break;

                case ObstacleType.Rectangle:
                    var rectangleObstacle = (RectangleObstacle)obstacle;
                    shape   = new PolygonShape(rectangleObstacle.Vertices.ToMeters(), 1);
                    fixture = body.CreateFixture(shape);
                    _json.SetName(fixture, "Building" + obstacle.Z);
                    break;
                }
            }
        }
示例#17
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));
        }
示例#18
0
        public override void HandleInput(InputHelper input, GameTime gameTime)
        {
            Keys[] pressedKeys = input.KeyboardState.GetPressedKeys();

            if (pressedKeys.Any(x => x == Keys.Up))
            {
                this.MoveVertical(gamePad2, -step);

                //this.gamePad2.Position = new Vector2((float)(this.gamePad2.Position.X), Math.Max(this.gamePad2.Position.Y - step, MinTop));
            }
            else if (pressedKeys.Any(x => x == Keys.Down))
            {
                //this.gamePad2.Position = new Vector2((float)(this.gamePad2.Position.X), Math.Min(this.gamePad2.Position.Y + step, MaxTop));

                this.MoveVertical(gamePad2, +step);
            }

            if (pressedKeys.Any(x => x == Keys.W))
            {
                this.MoveVertical(gamePad1, -step);
            }
            else if (pressedKeys.Any(x => x == Keys.S))
            {
                this.MoveVertical(gamePad1, +step);

                //this.gamePad1.Position = new Vector2((float)(this.gamePad1.Position.X), Math.Min(this.gamePad1.Position.Y + step, MaxTop));
            }

            if (pressedKeys.Any(x => x == Keys.Enter) && !geometryAdded)
            {
                geometryAdded = true;

                var verts = new Vertices {
                    new Vector2(-2, -2), new Vector2(-2, 2), new Vector2(2, 2), new Vector2(2, -2)
                };
                var geo = BodyFactory.CreateCompoundPolygon(World, BayazitDecomposer.ConvexPartition(verts), 1f, new Vector2(-3));

                geo.IsStatic    = true;
                geo.Restitution = 1f;
                geo.Friction    = 0f;

                var sprite = new Sprite(ScreenManager.Assets.TextureFromShape(geo.FixtureList[0].Shape, MaterialType.Dots, Color.SandyBrown, 0.8f));

                dymanicShit.Add(new BodySprite {
                    Body = geo, Sprite = sprite
                });
            }

            base.HandleInput(input, gameTime);
        }
示例#19
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>());
            }
        }
示例#20
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
        }
示例#21
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);
            }
        }
示例#22
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;
        }
        private List <Vector2[]> ProcessVertices(PolygonCollider2D collider, Vertices v, List <Vector2[]> list, ref PolygonParameters p, ref int pathIndex)
        {
            Vector2 offset          = p.Offset;
            float   flipXMultiplier = (spriteRenderer.flipX ? -1.0f : 1.0f);
            float   flipYMultiplier = (spriteRenderer.flipY ? -1.0f : 1.0f);

            if (p.DistanceThreshold > 1)
            {
                v = SimplifyTools.DouglasPeuckerSimplify(v, p.DistanceThreshold);
            }

            if (p.Decompose)
            {
                List <List <Vector2> > points = BayazitDecomposer.ConvexPartition(v);
                for (int j = 0; j < points.Count; j++)
                {
                    List <Vector2> v2 = points[j];
                    for (int i = 0; i < v2.Count; i++)
                    {
                        float xValue = (2.0f * (((v2[i].x - offset.x) + 0.5f) / p.Rect.width));
                        float yValue = (2.0f * (((v2[i].y - offset.y) + 0.5f) / p.Rect.height));
                        v2[i] = new Vector2(xValue * p.XMultiplier * Scale * flipXMultiplier, yValue * p.YMultiplier * Scale * flipYMultiplier);
                    }
                    Vector2[] arr = v2.ToArray();
                    collider.pathCount = pathIndex + 1;
                    collider.SetPath(pathIndex++, arr);
                    list.Add(arr);
                }
            }
            else
            {
                collider.pathCount = pathIndex + 1;
                for (int i = 0; i < v.Count; i++)
                {
                    float xValue = (2.0f * (((v[i].x - offset.x) + 0.5f) / p.Rect.width));
                    float yValue = (2.0f * (((v[i].y - offset.y) + 0.5f) / p.Rect.height));
                    v[i] = new Vector2(xValue * p.XMultiplier * Scale * flipXMultiplier, yValue * p.YMultiplier * Scale * flipYMultiplier);
                }
                Vector2[] arr = v.ToArray();
                collider.SetPath(pathIndex++, arr);
                list.Add(arr);
            }

            return(list);
        }
示例#24
0
        public void loadConvexHulls()
        {
            //World.Gravity = Vector2.Zero;
            //load texture that will represent the physics body
            _polygonTexture = Content.Load <Texture2D>("Tiles/Exit");

            //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
            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.CollinearSimplify(textureVertices, 1f);

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

            //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;
        }
示例#25
0
        public FarseerObject(FarseerWorld world, Texture2D texture, float density = 1, BodyType BodyType = BodyType.Dynamic, float colapseDistance = 4)
        {
            //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
            Vertices textureVertices = PolygonTools.CreatePolygon(data, texture.Width);

            //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 - new Vector2(texture.Width / 2, texture.Height / 2);;

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

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

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

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

            //Create a single body with multiple fixtures
            body                     = BodyFactory.CreateCompoundPolygon(world.World, list, density, BodyType);
            body.BodyType            = BodyType;
            body.CollisionCategories = Category.All;
            body.CollidesWith        = Category.All;
            body.Enabled             = false;
        }
示例#26
0
/*
 *      private void world_OnBroadPhaseCollision(ref FixtureProxy proxyA, ref FixtureProxy proxyB)
 *      {
 *          // Get the collided entities
 *          Entity entityA = proxyA.Fixture.Body.UserData as Entity;
 *          Entity entityB = proxyB.Fixture.Body.UserData as Entity;
 *          if (entityA == null || entityB == null)
 *          {
 *              // fail in debug builds
 *              Debug.Assert(entityA != null && entityB != null);
 *              return;
 *          }
 *          entityA.CollideWith(entityB);
 *      }
 */
        private Body BodyFromTexture(Texture2D texture, float density)
        {
            //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
            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.
            Vector2 centroid = -textureVertices.GetCentroid();

            textureVertices.Translate(ref centroid);

            //2. To draw the texture the correct place.
            Vector2 _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);

            //scale the vertices from graphics space to sim space
            Vector2 vertScale = new Vector2(WorldConversions.ConvertFromPixels(1));

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

            //Create a single body with multiple fixtures
            Body body = BodyFactory.CreateCompoundPolygon(
                CurrentLevel.PhysicsWorld, list, density, BodyType.Dynamic);

            return(body);
        }
示例#27
0
        public List <Fixture> CreateFixture(Body body)
        {
            var             vertices  = new Vertices(Verts);
            List <Vertices> vertsList = BayazitDecomposer.ConvexPartition(vertices);

            List <Fixture> fixtureList = new List <Fixture>();

            Vector2 mainCentroid = vertices.GetCentroid();

            foreach (Vertices v in vertsList)
            {
                PolygonShape shape   = new PolygonShape(v, Density);
                Fixture      fixture = new Fixture(body, shape, RotationOffset);
                fixture.IsSensor            = IsSensor;
                fixture.CollisionGroup      = CollisionGroup;
                fixture.CollisionCategories = (Category)CollisionCategories;
                fixture.CollidesWith        = (Category)CollidesWith;
                fixtureList.Add(fixture);
            }
            return(fixtureList);
        }
示例#28
0
        public static PhysicsObject createFromTexture(Texture2D texture, float density = 1f)
        {
            int width  = texture.Width;
            int height = texture.Height;

            uint[] data = new uint[texture.Width * texture.Height];
            texture.GetData <uint>(data);

            PhysicsObject obj = new PhysicsObject();

            for (int i = 0; i < Main.objects.Length; i++)
            {
                if (Main.objects[i].active == false)
                {
                    Main.objects[i] = obj;
                    obj.whoAmI      = i;
                    break;
                }
            }
            Vertices verts    = PolygonTools.CreatePolygon(data, width, false);
            Vector2  centroid = -verts.GetCentroid();

            obj.origin = Vector2.Zero;// centroid / 2;
            verts      = SimplifyTools.ReduceByDistance(verts, 4f);
            List <Vertices> list   = BayazitDecomposer.ConvexPartition(verts);
            Vector2         vScale = new Vector2(ConvertUnits.ToSimUnits(1));

            foreach (Vertices v in list)
            {
                v.Scale(ref vScale);
            }
            obj.body          = BodyFactory.CreateCompoundPolygon(Main.physicsWorld, list, 1f);
            obj.shape         = 3;
            obj.active        = true;
            obj.dwidth        = width;
            obj.dheight       = height;
            obj.body.BodyType = BodyType.Dynamic;
            Debug.print("New texture body with " + verts.Count + " vertices successfully added");
            return(obj);
        }
        /// <summary>
        /// Updates data for convex decomposition of the polygon.
        /// </summary>
        private void UpdateConvexDecomposition()
        {
            if (vertices.Count <= 3)
            {
                return;
            }

            Debug.Assert(Polygon.Vertices.IsSimple(), "Polygon must be simple (no crossing edges)");

            // compute convex decomposition
            List <Vertices> decomposition = BayazitDecomposer.ConvexPartition(new Vertices(Polygon.Vertices));

            // update convex decomposition lines
            convexDecompositionLines.Clear();
            foreach (Vertices decompositionVertices in decomposition)
            {
                PointF[] convexLines = new PointF[decompositionVertices.Count];
                for (int i = 0; i < decompositionVertices.Count; ++i)
                {
                    convexLines[i] = new PointF(decompositionVertices[i].X, decompositionVertices[i].Y);
                }
                convexDecompositionLines.Add(convexLines);
            }
        }
示例#30
0
        /// <summary>
        /// Builds convex polygons out of the currently loaded 2D Shape Editor project.
        /// Note: Currently simply triangulates everything instead.
        /// </summary>
        /// <returns>A list of convex polygons.</returns>
        private List <Polygon> BuildConvexPolygons()
        {
            List <Polygon> polygons = new List <Polygon>();

            // for each shape in the project:
            foreach (Shape shape in project.shapes)
            {
                List <Vector2> vertices = new List <Vector2>();

                // iterate through all segments of the shape:
                foreach (Segment segment in shape.segments)
                {
                    // linear segment:
                    if (segment.type == SegmentType.Linear)
                    {
                        vertices.Add(new Vector2(segment.position.x * project.extrudeScale.x, segment.position.y * -1.0f * project.extrudeScale.y) / 8.0f);
                    }

                    // bezier segment:
                    else
                    {
                        foreach (Edge edge in GetBezierEdges(segment, GetNextSegment(shape, segment)))
                        {
                            vertices.Add(new Vector2(edge.Vertex1.Position.x * project.extrudeScale.x, edge.Vertex1.Position.y * -1.0f * project.extrudeScale.y) / 8.0f);
                        }
                    }
                }

                // in project v1 we use the horizontal and vertical flags to keep track of the correct winding order.
                Vector2[] inputVertices = vertices.ToArray();
                if (project.flipHorizontally && !project.flipVertically)
                {
                    inputVertices = ReverseWindingOrder(inputVertices);
                }
                if (!project.flipHorizontally && project.flipVertically)
                {
                    inputVertices = ReverseWindingOrder(inputVertices);
                }

                // create convex polygons:
                inputVertices = ReverseWindingOrder(inputVertices);
                List <Vector2[]> convexPolygonsVertices = BayazitDecomposer.ConvexPartition(inputVertices);

                foreach (Vector2[] polyVertices in convexPolygonsVertices)
                {
                    List <Vertex> vertexList = new List <Vertex>();
                    foreach (Vector2 vert in polyVertices)
                    {
                        vertexList.Add(new Vertex(vert, Vector3.zero, Vector2.zero));
                    }

                    polygons.Add(new Polygon(vertexList.ToArray(), null, false, false));
                }

                switch (extrudeMode)
                {
                case ExtrudeMode.CreatePolygon:
                    // we make a brush for every polgon.
                    desiredBrushCount = polygons.Count;
                    break;

                // we need another brush for every revolve step.
                case ExtrudeMode.RevolveShape:
                    desiredBrushCount = polygons.Count * project.revolveSteps;
                    break;

                case ExtrudeMode.ExtrudeShape:
                    // we make a brush for every polgon.
                    desiredBrushCount = polygons.Count;
                    break;

                case ExtrudeMode.ExtrudePoint:
                    // we make a brush for every polgon.
                    desiredBrushCount = polygons.Count;
                    break;

                case ExtrudeMode.ExtrudeBevel:
                    // we make a brush for every polgon.
                    desiredBrushCount = polygons.Count;
                    break;
                }
            }

            return(polygons);
        }