Example #1
0
        public void Draw(Stopwatch time)
        {
            myApp.window.Clear(myStyle.BackgroundColor);

            if( myStyle.BackgroundImage != null )
            {
                ImagePart part= myStyle.BackgroundImage;
                myUIManager.Painter.Begin();
                if( myStyle.BackgroundDisplayMode == TextureDisplayMode.Stretch )
                    myUIManager.Painter.DrawImage(part.SourceTexture, new FloatRect(0f, 0f, myUIManager.ScreenSize.X, myUIManager.ScreenSize.Y), part.SourceRectangle);
                else
                {
                    // the image must be centered.
                    FloatRect destRect = new FloatRect(
                        0.5f*(myUIManager.ScreenSize.X - myStyle.BackgroundImage.Size.X),
                        0.5f * (myUIManager.ScreenSize.Y - myStyle.BackgroundImage.Size.Y),
                        myStyle.BackgroundImage.Size.X,
                        myStyle.BackgroundImage.Size.Y);
                    myUIManager.Painter.DrawImage(part.SourceTexture, destRect, part.SourceRectangle);
                }

                myUIManager.Painter.End();
            }

            myUIManager.Render();
        }
Example #2
0
        public FloatRect CalculateBoundingBox(float thrusterXScale = 0.3f)
        {
            var sprites = ServiceLocator.Instance.GetService<ISpriteManagerService>().Sprites;
            return Parts.Where(p=>p.SpriteId!=null).Aggregate(new FloatRect(), (box, part) =>
            {
                Sprite spr;
                if (!sprites.TryGetValue(part.SpriteId, out spr)) return box;

                var aabb = new FloatRect(-(spr.OriginX ?? spr.W / 2), -(spr.OriginY ?? spr.H / 2), spr.W, spr.H);

                var topleft = new Vector2(Math.Min(aabb.Left, aabb.Right), Math.Min(aabb.Top, aabb.Bottom));
                var bottomright = new Vector2(Math.Max(aabb.Left, aabb.Right), Math.Max(aabb.Top, aabb.Bottom));

                var matrix = part.Transform.Matrix;
                if (part is Thruster)
                {
                    matrix = Matrix.CreateScale(new Vector3(thrusterXScale, 1, 1)) * matrix;
                }

                Vector2.Transform(ref topleft, ref matrix, out topleft);
                Vector2.Transform(ref bottomright, ref matrix, out topleft);

                return new FloatRect(new Vector2(Math.Min(Math.Min(topleft.X, bottomright.X), box.Left), Math.Min(Math.Min(topleft.Y, bottomright.Y), box.Top)),
                    new Vector2(Math.Max(Math.Abs(topleft.X - bottomright.X), box.Width), Math.Max(Math.Abs(topleft.Y - bottomright.Y), box.Width)));
            });
        }
Example #3
0
        public void Draw(Texture2D texture, ref Matrix transform, FloatRect? sourceRectangle = null, Color? color=null, Vector3? normal = null)
        {
            Vertex3CTN vtx;
            vtx.Color = color ?? Color.White;
            vtx.Normal = normal ?? Vector3.Forward;
            FloatRect texRect = sourceRectangle ?? new FloatRect(texture.Bounds);

            Vector2 texCoordLT = texture.GetUV(texRect.Left, texRect.Top);
            Vector2 texCoordBR = texture.GetUV(texRect.Right, texRect.Bottom);

            vtx.Position = Vector3.Zero;
            vtx.TextureCoords = texCoordLT;
            _quadVertices[0] = vtx;
            vtx.Position = new Vector3(0, texRect.Height, 0);
            vtx.TextureCoords = new Vector2(texCoordLT.X, texCoordBR.Y);
            _quadVertices[1] = vtx;
            vtx.Position = new Vector3(texRect.Width, 0, 0);
            vtx.TextureCoords = new Vector2(texCoordBR.X, texCoordLT.Y);
            _quadVertices[2] = vtx;
            vtx.Position = new Vector3(texRect.Width, texRect.Height, 0);
            vtx.TextureCoords = texCoordBR;
            _quadVertices[3] = vtx;

            DrawVertices(texture, _quadVertices, _quadIndices, ref transform);
        }
        /// <summary>
        /// Set parameters :)
        /// </summary>
        /// <param name="parameter"></param>
        public override void SetParameter(ComponentParameter parameter)
        {
            var tileSize = IoCManager.Resolve<IMapManager>().TileSize;

            //base.SetParameter(parameter);
            switch (parameter.MemberName)
            {
                case "SizeX":
                    var width = parameter.GetValue<float>() / tileSize;
                    AABB = new FloatRect(AABB.Left + (AABB.Width - width) / 2f, AABB.Top, width, AABB.Height);
                    break;
                case "SizeY":
                    var height = parameter.GetValue<float>() / tileSize;
                    AABB = new FloatRect(AABB.Left, AABB.Top + (AABB.Height - height) / 2f, AABB.Width, height);
                    break;
                case "OffsetX":
                    var x = parameter.GetValue<float>() / tileSize;
                    AABB = new FloatRect(x - AABB.Width / 2f, AABB.Top, AABB.Width, AABB.Height);
                    break;
                case "OffsetY":
                    var y = parameter.GetValue<float>() / tileSize;
                    AABB = new FloatRect(AABB.Left, y - AABB.Height / 2f, AABB.Width, AABB.Height);
                    break;
            }
        }
Example #5
0
        public override bool Update(Vector2i mouseS, IMapManager currentMap)
        {
            if (currentMap == null) return false;

            spriteToDraw = GetDirectionalSprite(pManager.CurrentBaseSpriteKey);

            mouseScreen = mouseS;
            mouseWorld = CluwneLib.ScreenToWorld(mouseScreen);

            var bounds = spriteToDraw.GetLocalBounds();
            var spriteSize = CluwneLib.PixelToTile(new Vector2f(bounds.Width, bounds.Height));
            var spriteRectWorld = new FloatRect(mouseWorld.X - (spriteSize.X / 2f),
                                                 mouseWorld.Y - (spriteSize.Y / 2f),
                                                 spriteSize.X, spriteSize.Y);

            if (pManager.CurrentPermission.IsTile)
                return false;

            if (pManager.CollisionManager.IsColliding(spriteRectWorld))
                return false;

            //if (currentMap.IsSolidTile(mouseWorld)) return false;

            var rangeSquared = pManager.CurrentPermission.Range * pManager.CurrentPermission.Range;
            if (rangeSquared > 0)
                if (
                    (pManager.PlayerManager.ControlledEntity.GetComponent<TransformComponent>(ComponentFamily.Transform)
                         .Position - mouseWorld).LengthSquared() > rangeSquared) return false;

            currentTile = currentMap.GetTileRef(mouseWorld);

            return true;
        }
Example #6
0
        public Frame(RectangleShape borderRect, Color fillColor)
        {
            BorderRect = borderRect;
            BorderRect.FillColor = fillColor;

            BoundingRect = borderRect.GetGlobalBounds();
        }
Example #7
0
 public static void DrawRectangle(FloatRect rect, Color color) => drawInfos.Add(new DebugDrawInfo(new[]
 {
     new Vertex(new Vector2f(rect.Left, rect.Top), color),
     new Vertex(new Vector2f(rect.Left + rect.Width, rect.Top), color),
     new Vertex(new Vector2f(rect.Left + rect.Width, rect.Top + rect.Height), color),
     new Vertex(new Vector2f(rect.Left, rect.Top + rect.Height), color),
     new Vertex(new Vector2f(rect.Left, rect.Top), color)
 }, PrimitiveType.LinesStrip));
Example #8
0
        /// <summary>
        /// The FloatRects are relative to inside that Texture sent in
        /// </summary>
        public Backdrop(String[] bgText, FloatRect startSquare, FloatRect finalSquare)
        {
            backgroundString = bgText[0];
            waterString = bgText[1];

            topProps = new List<PropSprite>();
            lowProps = new List<PropSprite>();
        }
Example #9
0
        List<ChampItemPair> units; //ingroup

        #endregion Fields

        #region Constructors

        internal Pillar(FloatRect postion)
        {
            rect = postion;
            units = new List<ChampItemPair>();

            pillarSprite = new Sprite();
            unitSprite = new Sprite();
        }
Example #10
0
 public HWSurfaceInstance(ScriptEngine parent, Texture texture)
     : base(parent.Object.InstancePrototype)
 {
     _source = new FloatRect(_ox, _oy, texture.Size.X, texture.Size.Y);
     _ox += _source.Width + 1;
     if (_ox > _aw) { _ox = 0; _oy += _source.Height + 1; }
     Init();
 }
Example #11
0
 public QuadTreeNode(FloatRect range, int capacity, Vector2f minSize)
 {
     this.range = range;
     this.capacity = capacity;
     this.child = null;
     this.cubeList = new List<Cube>();
     this.minSize = minSize;
 }
Example #12
0
 public override void Update(float dt)
 {
     base.Update(dt);
     Hitbox = new FloatRect(
         MyEntity.Transform.Position.X - MyEntity.Transform.Origin.X,
         MyEntity.Transform.Position.Y - MyEntity.Transform.Origin.Y,
         Hitbox.Width,
         Hitbox.Height);
 }
Example #13
0
        public Player(FloatRect screenRect)
        {
            // setup player
            _shape = new CircleShape(30, 3);
            _shape.Position = new Vector2f(screenRect.Width/2 - (_shape.Radius), screenRect.Height - (_shape.Radius*2));
            _shape.FillColor = Color.Green;

            _bullets = new List<RectangleShape> ();
        }
Example #14
0
        /// <summary>
        /// Draws a rectangle.
        /// </summary>
        /// <param name="sb"><see cref="ISpriteBatch"/> to draw to.</param>
        /// <param name="dest">Destination rectangle.</param>
        /// <param name="color">Color of the rectangle.</param>
        public static void Draw(ISpriteBatch sb, Rectangle dest, Color color)
        {
            var fDest = new FloatRect(dest.Left, dest.Top, dest.Width, dest.Height);

            using (var s = Shape.Rectangle(fDest, color))
            {
                sb.Draw(s);
            }
        }
Example #15
0
 private void OnColides(ColiderComponent colider, FloatRect overlap)
 {
     if(colider.MyEntity.HasComponent<Player>() &&
        StateManager.Instance.CurrentState is LevelState )
     {
         var levelState = StateManager.Instance.CurrentState as LevelState;
         levelState.CurrentLevel++;
     }
 }
Example #16
0
        internal override void draw(RenderWindow window)
        {
            //remember mPos is the middle this time
            FloatRect r = new FloatRect((int)(mPos.X - length / 2), (int)(mPos.Y - ylength / 2), (int)length, (int)ylength);

            sprite.Position = new Vector2f((mPos.X - (float)length / 2.0f),(mPos.Y - (float)ylength / 2.0f) );
            sprite.Color = color;
            sprite.Scale = new Vector2f((float)length / sprite.TextureRect.Width, (float)ylength / sprite.TextureRect.Height);
            window.Draw(sprite);
        }
Example #17
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="resManager">Gestor de recursos</param>
        /// <param name="worldBounds">Dimensiones de area de movimiento del PlayerShip</param>
        /// <param name="shootPool">Piscina que gestiona el reciclaje de las balas</param>
        public PlayerShip(ResourcesManager resManager, FloatRect worldBounds,ShootPlayerPool shootPool)
            : base() 
        {
            _sprite = new Sprite((Texture)resManager["Naves:NaveJugador"]);
            _worldBounds = worldBounds;

            // ubico el origen del sprite en el centro en vez de en la esquina superior derecha
            FloatRect bounds = _sprite.GetLocalBounds();
            _sprite.Origin = new SFML.System.Vector2f(bounds.Width / 2f, bounds.Height / 2f);

            _shootPool = shootPool;
        }
Example #18
0
 public static Entity LevelEnd(int x, int y)
 {
     var entity = new Entity();
     entity.Transform.Origin = new Vector2f(TILE_SIZE / 2f, TILE_SIZE / 2f);
     entity.Transform.Position = new Vector2f(x * TILE_SIZE, y * TILE_SIZE);
     var hitbox = new FloatRect(0, 0, TILE_SIZE, TILE_SIZE);
     var colider = new ColiderComponent(hitbox);
     var end = new LevelEnd();
     entity.AddComponent(colider);
     entity.AddComponent(end);
     return entity;
 }
Example #19
0
        public Corkscrew(float xIni, float yIni, float xEnd, float yEnd,
            FloatRect worldBounds)
        {
            _waypoints = new float[6, 4];

            _waypoints[0, 0] = xIni;
            _waypoints[0, 1] = yIni;
            _waypoints[0, 2] = 0;
            _waypoints[0, 3] = 1;

            _waypoints[1, 0] = worldBounds.Width * 0.45f;
            _waypoints[1, 1] = worldBounds.Height * .2f;
            _waypoints[1, 2] = 1;
            _waypoints[1, 3] = 2;

            _waypoints[2, 0] = worldBounds.Width * 0.125f;
            _waypoints[2, 1] = worldBounds.Height / 2;
            _waypoints[2, 2] = 1;
            _waypoints[2, 3] = 1;

            _waypoints[3, 0] = worldBounds.Width * 0.125f;
            _waypoints[3, 1] = worldBounds.Height * .75f;
            _waypoints[3, 2] = -1;
            _waypoints[3, 3] = 1;

            _waypoints[4, 0] = worldBounds.Width * 0.45f;
            _waypoints[4, 1] = worldBounds.Height * 0.6f;
            _waypoints[4, 2] = 1;
            _waypoints[4, 3] = -6;

            _waypoints[5, 0] = worldBounds.Width * 0.5f;
            _waypoints[5, 1] = worldBounds.Height * 0.48f;
            _waypoints[5, 2] = 0;
            _waypoints[5, 3] = -1;

            //_waypoints[5, 0] = xEnd;
            //_waypoints[5, 1] = yEnd + 70;
            //_waypoints[5, 2] = 0;
            //_waypoints[5, 3] = -1;

            //_waypoints[6, 0] = xEnd;
            //_waypoints[6, 1] = yEnd;
            //_waypoints[6, 2] = -0f;
            //_waypoints[6, 3] = -1;

            // calculo de coeficientes
            _coef = PolynomicUtilities.HermiteInterpolation(_waypoints);

            CalculateCurveLength();
        }
Example #20
0
 public SpawnButton(World parent, Vector2f pos, string tex, int val, bool add = true)
     : base(Rsc.Tex(tex), pos, parent, add)
 {
     _tex = tex;
     Val = val;
     new Entity(Rsc.Tex("rsc/Button.png"), pos, parent);
     {
         Layer = Layer - 1;
     }
     Bounds = new FloatRect(pos.X, pos.Y, 64, 64);
     DPDisp = new TextEntity(val.ToString(CultureInfo.InvariantCulture), pos + new Vector2f(4, 40), parent, Fonts.ExoRegular, 18, Colors.White, Colors.Black)
                  {Layer = Layer - 2};
     Scale /= 2;
 }
Example #21
0
        internal static new void LoadContent()
        {
            buffDmgAbilityTexture = GameBox.loadTexture("images/abilitys/buffDmgIcon");
            buffCDAbilityTexture = GameBox.loadTexture("images/abilitys/buffCDIcon");

            //beams
            buffDmgBeamTexture = GameBox.loadTexture("images/abilitys/buffDmg_beam"); ;
            buffDmgBeamRect = new FloatRect(0, 0, 4, 4);
            buffCDBeamTexture = GameBox.loadTexture("images/abilitys/buffCD_beam");
            buffCDBeamRect = new FloatRect(0, 0, 4, 4);

            bardBaseTexture = GameBox.loadTexture(SimpleModel.CLASS_PATH + "bardbase");
            bardWepAnimation = GameBox.loadTexture(SimpleModel.CLASS_PATH + "bardanim");
        }
Example #22
0
        public IEnumerable<Entity> EntitiesInRegion(FloatRect rect)
        {
            var min = new Vector2(rect.Left, rect.Top) / Program.PixelsPerMeter;
            var aabb = new AABB(min, min + (new Vector2(rect.Width, rect.Height) / Program.PixelsPerMeter));
            var result = new List<Entity>(256);

            World.QueryAABB(f =>
            {
                result.Add((Entity)f.Body.UserData);
                return true;
            }, ref aabb);

            return result.Distinct().OrderBy(e => e.Depth + e.DepthBias);
        }
Example #23
0
        public void DrawText(SpriteBatch batch, double x, double y, string text)
        {
            CheckUpdate();
            FloatRect dest = new FloatRect((float)x, (float)y, 0, (float)_height);

            for (var i = 0; i < text.Length; ++i)
            {
                IntRect src = _atlas.Sources[text[i]];
                dest.Width = src.Width;
                dest.Height = src.Height;
                batch.Add(_atlas.Texture, src, dest, _color);
                dest.Left += src.Width;
            }
        }
Example #24
0
        public Tile(Game game, Vector2i mapPos, int scale, int tileID, bool solid = false)
        {
            this.game = game;
            this.tileID = tileID;
            this.solid = solid;
            this.mapPos = mapPos;

            Position = new Vector2f((mapPos.X * 16) * scale, (mapPos.Y * 16) * scale);

            sprite = new Sprite(TextureLoader.GetTile(tileID));
            sprite.Scale = new Vector2f(scale, scale);

            bounds = new FloatRect(Position, new Vector2f(16 * scale, 16 * scale));
        }
        public override bool Update(Vector2i mouseS, IMapManager currentMap)
        {
            if (currentMap == null) return false;

            spriteToDraw = GetDirectionalSprite(pManager.CurrentBaseSpriteKey);

            mouseScreen = mouseS;
            mouseWorld = CluwneLib.ScreenToWorld(mouseScreen);

            var bounds = spriteToDraw.GetLocalBounds();
            var spriteSize = CluwneLib.PixelToTile(new Vector2f(bounds.Width, bounds.Height));
            var spriteRectWorld = new FloatRect(mouseWorld.X - (spriteSize.X / 2f),
                                                 mouseWorld.Y - (spriteSize.Y / 2f),
                                                 spriteSize.X, spriteSize.Y);

            currentTile = currentMap.GetTileRef(mouseWorld);

            if (currentTile.Tile.TileDef.IsWall)
                return false;

            var rangeSquared = pManager.CurrentPermission.Range * pManager.CurrentPermission.Range;
            if (rangeSquared > 0)
                if (
                    (pManager.PlayerManager.ControlledEntity.GetComponent<TransformComponent>(ComponentFamily.Transform)
                         .Position - mouseWorld).LengthSquared() > rangeSquared)
                    return false;

            if (pManager.CurrentPermission.IsTile)
            {
                mouseWorld = new Vector2f(currentTile.X + 0.5f,
                                         currentTile.Y + 0.5f);
                mouseScreen = CluwneLib.WorldToScreen(mouseWorld).Round();
            }
            else
            {
                mouseWorld = new Vector2f(currentTile.X + 0.5f + pManager.CurrentTemplate.PlacementOffset.Key,
                                         currentTile.Y + 0.5f + pManager.CurrentTemplate.PlacementOffset.Value);
                mouseScreen = CluwneLib.WorldToScreen(mouseWorld).Round();

                spriteRectWorld = new FloatRect(mouseWorld.X - (bounds.Width/2f),
                                                 mouseWorld.Y - (bounds.Height/2f), bounds.Width,
                                                 bounds.Height);
                if (pManager.CollisionManager.IsColliding(spriteRectWorld))
                    return false;
                //Since walls also have collisions, this means we can't place objects on walls with this mode.
            }

            return true;
        }
        public ServerListOverlay()
        {
            servers = new List<Server>();
            refreshing = false;
            listOffset = 0;
            selectedIndex = -1;

            RefreshServerList();

            Input.MouseWheel += args =>
            {
                listOffset += args.Delta;

                if (listOffset >= servers.Count)
                    listOffset = servers.Count - 1;

                if (listOffset < 0)
                    listOffset = 0;

                return true;
            };

            Input.MouseButton[Mouse.Button.Left] = args =>
            {
                if (!args.Pressed)
                    return false;

                float boundingY = GameOptions.Height * (PaddingVertical * 3.0f) + 64.0f;
                float boundingX = GameOptions.Width * (PaddingHorizontal * 2.5f);
                float width = GameOptions.Width - boundingX * 2.0f;
                const float height = 64.0f * 6;

                FloatRect area = new FloatRect(boundingX, boundingY, width, height);
                if (!area.Contains(args.Position.X, args.Position.Y))
                {
                    selectedIndex = -1;
                    return false;
                }

                selectedIndex = (int)(args.Position.Y - boundingY) / 64 + listOffset;
                if (selectedIndex >= servers.Count)
                    selectedIndex = -1;

                if (SelectedServer != null)
                    JoinNext(SelectedServer.IpAddress);

                return false;
            };
        }
Example #27
0
 public static Entity Box(int x, int y)
 {
     var entity = new Entity();
     var texture = ResourceManager.Instance.Get<Texture>("rock" + Randomizer.Generator.Next(1, 3) + ".png");
     entity.Transform.Origin = new Vector2f(texture.Size.X / 2f, texture.Size.Y / 2f);
     entity.Transform.Position = new Vector2f(x * texture.Size.X, y * texture.Size.Y);
     var sprite = new SpriteComponent(texture);
     var hitbox = new FloatRect(0, 0, texture.Size.X, texture.Size.Y);
     var colider = new ColiderComponent(hitbox);
     var box = new Solid();
     entity.AddComponent(sprite);
     entity.AddComponent(colider);
     entity.AddComponent(box);
     return entity;
 }
Example #28
0
        public FastText(Font font, uint size)
        {
            textObject = new Text("Set Text Property", font, size);
            renderSprite = new Sprite();

            TextSize = size;
            TextAlignment = Alignment.TopLeft;

            Size = new Vector2f(50, 50);
            Anchor = AnchorPoints.None;
            Padding = new FloatRect(3, 3, 3, 3);
            BackgroundColor = Color.Transparent;

            renderContainer = new RenderTexture((uint)Size.X, (uint)Size.Y);
        }
Example #29
0
        public OpacityBox(FloatRect rect, int z = BaseDrawable.DEFAULT_Z, EDesactivatingSideType desactivatingSideType = DEFAULT_DESACTIVATING_SIDE_TYPE)
        {
            Rect = rect;
            Z = z;

            Sides = new Dictionary<State<string>, bool>()
            {
                { "Left", false },
                { "Top", false },
                { "Right", false },
                { "Bottom", false }
            };

            Desactivate(desactivatingSideType);
        }
Example #30
0
        public void Move(Direction d, FloatRect screenRect)
        {
            float dist = 10.5f;

            // Move players position only if its inside the screen
            switch (d) {
            case Direction.LEFT:
                if (_shape.Position.X >= dist)
                    _shape.Position = new Vector2f (_shape.Position.X - dist, _shape.Position.Y);
                break;
            case Direction.RIGHT:
                if (_shape.Position.X <= screenRect.Width - (_shape.Radius*2) - dist)
                    _shape.Position = new Vector2f (_shape.Position.X + dist, _shape.Position.Y);
                break;
            }
        }
Example #31
0
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        /// <summary>
        /// Draws the widget on the render target
        /// </summary>
        ///
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        public override void Draw(RenderTarget target, RenderStates states)
        {
            // Apply the transformation
            states.Transform *= Transform;

            // Remember the current transformation
            Transform oldTransform = states.Transform;

            // Check if the image is split
            if (m_SplitImage)
            {
                float scalingY = m_Size.Y / m_TextureBack_M.Size.Y;

                // Scale the image
                states.Transform.Scale(scalingY, scalingY);

                // Draw the left image of the loading bar
                target.Draw(m_TextureBack_L.sprite, states);
                target.Draw(m_TextureFront_L.sprite, states);

                // Check if the middle image may be drawn
                if ((scalingY * (m_TextureBack_L.Size.X + m_TextureBack_R.Size.X)) < m_Size.X)
                {
                    // Put the middle image on the correct position
                    states.Transform.Translate(m_TextureBack_L.Size.X, 0);

                    // Draw the middle image
                    target.Draw(m_TextureBack_M.sprite, states);
                    target.Draw(m_TextureFront_M.sprite, states);

                    // Put the right image on the correct position
                    states.Transform.Translate(m_TextureBack_M.sprite.GetGlobalBounds().Width, 0);

                    // Draw the right image
                    target.Draw(m_TextureBack_R.sprite, states);
                    target.Draw(m_TextureFront_R.sprite, states);
                }
                else // The loading bar isn't width enough, we will draw it at minimum size
                {
                    // Put the right image on the correct position
                    states.Transform.Translate(m_TextureBack_L.sprite.GetGlobalBounds().Width, 0);
                    states.Transform.Translate(m_TextureBack_L.Size.X, 0);

                    // Draw the right image
                    target.Draw(m_TextureBack_R.sprite, states);
                    target.Draw(m_TextureFront_R.sprite, states);
                }
            }
            else // The image is not split
            {
                // Scale the image
                states.Transform.Scale(m_Size.X / m_TextureBack_M.Size.X, m_Size.Y / m_TextureBack_M.Size.Y);

                // Draw the loading bar
                target.Draw(m_TextureBack_M.sprite, states);
                target.Draw(m_TextureFront_M.sprite, states);
            }

            // Check if there is a text to draw
            if (m_Text.DisplayedString.Length != 0)
            {
                // Reset the transformations
                states.Transform = oldTransform;

                // Get the current size of the text, so that we can recalculate the position
                FloatRect rect = m_Text.GetGlobalBounds();

                // Calculate the new position for the text
                rect.Left = (m_Size.X - rect.Width) * 0.5f - rect.Left;
                rect.Top  = (m_Size.Y - rect.Height) * 0.5f - rect.Top;

                // Set the new position
                states.Transform.Translate((float)System.Math.Floor(rect.Left + 0.5), (float)System.Math.Floor(rect.Top + 0.5));

                // Draw the text
                target.Draw(m_Text, states);
            }
        }
Example #32
0
        // If `ignoreSpace` is false, this will return tiles in chunks that don't even exist.
        // This is to make the tile count predictable.  Is this appropriate behavior?
        public IEnumerable <TileRef> GetTilesIntersecting(FloatRect area, bool ignoreSpace)
        {
            int chunkLeft   = (int)Math.Floor(area.Left / ChunkSize);
            int chunkTop    = (int)Math.Floor(area.Top / ChunkSize);
            int chunkRight  = (int)Math.Floor(area.Right() / ChunkSize);
            int chunkBottom = (int)Math.Floor(area.Bottom() / ChunkSize);

            for (int chunkY = chunkTop; chunkY <= chunkBottom; ++chunkY)
            {
                for (int chunkX = chunkLeft; chunkX <= chunkRight; ++chunkX)
                {
                    int xMin = 0;
                    int yMin = 0;
                    int xMax = 15;
                    int yMax = 15;

                    if (chunkX == chunkLeft)
                    {
                        xMin = Mod(Math.Floor(area.Left), ChunkSize);
                    }
                    if (chunkY == chunkTop)
                    {
                        yMin = Mod(Math.Floor(area.Top), ChunkSize);
                    }

                    if (chunkX == chunkRight)
                    {
                        xMax = Mod(Math.Floor(area.Right()), ChunkSize);
                    }
                    if (chunkY == chunkBottom)
                    {
                        yMax = Mod(Math.Floor(area.Bottom()), ChunkSize);
                    }

                    Chunk chunk;
                    if (!chunks.TryGetValue(new Vector2i(chunkX, chunkY), out chunk))
                    {
                        if (ignoreSpace)
                        {
                            continue;
                        }
                        else
                        {
                            for (int y = yMin; y <= yMax; ++y)
                            {
                                for (int x = xMin; x <= xMax; ++x)
                                {
                                    yield return(new TileRef(this,
                                                             chunkX * ChunkSize + x,
                                                             chunkY * ChunkSize + y));
                                }
                            }
                        }
                    }
                    else
                    {
                        for (int y = yMin; y <= yMax; ++y)
                        {
                            int i = y * ChunkSize + xMin;
                            for (int x = xMin; x <= xMax; ++x, ++i)
                            {
                                if (!ignoreSpace || chunk.Tiles[i].TileId != 0)
                                {
                                    yield return(new TileRef(this,
                                                             chunkX * ChunkSize + x,
                                                             chunkY * ChunkSize + y,
                                                             chunk, i));
                                }
                            }
                        }
                    }
                }
            }
        }
Example #33
0
 // FloatRect
 public static float Bottom(this FloatRect rect) => rect.Top + rect.Height;
Example #34
0
 public static void AddRectangle(FloatRect rect, Color color)
 {
     AddRectangle(rect.Left, rect.Top, rect.Width, rect.Height, color);
 }
Example #35
0
        public bool Load(string xml)
        {
            // Открываем документ с картой в .xml разметке
            XmlDocument xDoc = new XmlDocument();

            try
            {
                xDoc.LoadXml(xml);
            }
            catch (Exception)
            {
                Console.WriteLine("Loading level failed.");
                return(false);
            }

            // Получаем информацию о карте (ширину, высоту карты и тайлов)
            XmlElement mapElement = (XmlElement)xDoc.GetElementsByTagName("map")[0];

            // Пример карты: <map version="1.0" orientation="orthogonal"
            // width="10" height="10" tilewidth="34" tileheight="34">
            width      = int.Parse(mapElement.GetAttribute("width"));
            height     = int.Parse(mapElement.GetAttribute("height"));
            tileWidth  = int.Parse(mapElement.GetAttribute("tilewidth"));
            tileHeight = int.Parse(mapElement.GetAttribute("tileheight"));

            // Получаем инфрмацию о свойствах карты
            XmlElement mapPropertiesElement = (XmlElement)mapElement.GetElementsByTagName("properties")[0];
            XmlElement mapPropertyElement   = (XmlElement)mapPropertiesElement.GetElementsByTagName("property").Item(0);

            while (mapPropertyElement != null)
            {
                string propertyName  = mapPropertyElement.GetAttribute("name");
                string propertyValue = mapPropertyElement.GetAttribute("value");

                properties.Add(propertyName, propertyValue);

                mapPropertyElement = (XmlElement)mapPropertyElement.NextSibling;
            }

            // Получаем информацию о наборе тайлов (firstgid)
            XmlElement tilesetElement = (XmlElement)mapElement.GetElementsByTagName("tileset")[0];

            firstTileID = int.Parse(tilesetElement.GetAttribute("firstgid"));

            // Получаем информацию о картинке (путь к файлу)
            XmlElement imageElement = (XmlElement)tilesetElement.GetElementsByTagName("image")[0];
            string     imagePath    = imageElement.GetAttribute("source");

            // Загружаем картинку
            Image image = new Image("Media/Maps/" + imagePath);

            // TODO: Проверку добавить
            //if (!img.loadFromFile(imagepath))
            //{
            //    std::cout << "Failed to load tile sheet." << std::endl;
            //    return false;
            //}

            image.CreateMaskFromColor(new Color(255, 255, 255));
            tilesetImage = new Texture(image);

            int columns = (int)tilesetImage.Size.X / tileWidth;
            int rows    = (int)tilesetImage.Size.Y / tileHeight;

            List <IntRect> subRects = new List <IntRect>();

            for (int y = 0; y < rows; y++)
            {
                for (int x = 0; x < columns; x++)
                {
                    IntRect rect = new IntRect();

                    rect.Top    = y * tileHeight;
                    rect.Height = tileHeight;
                    rect.Left   = x * tileWidth;
                    rect.Width  = tileWidth;

                    subRects.Add(rect);
                }
            }



            // Работа со слоями
            XmlElement layerElement = (XmlElement)mapElement.GetElementsByTagName("layer")[0];

            for (int i = 0; i < mapElement.GetElementsByTagName("layer").Count; i++)
            {
                Layer layer = new Layer();

                if (layerElement.HasAttribute("opacity"))
                {
                    float opacity = float.Parse(layerElement.GetAttribute("opacity"));
                    layer.opacity = (int)(255 * opacity);
                }
                else
                {
                    layer.opacity = 255;
                }

                XmlElement layerDataElement = (XmlElement)layerElement.GetElementsByTagName("data")[0];

                if (layerDataElement == null)
                {
                    Console.WriteLine("Bad map. No layer information found.");
                    return(false);
                }

                XmlElement tileElement = (XmlElement)layerDataElement.GetElementsByTagName("tile").Item(0);

                if (tileElement == null)
                {
                    Console.WriteLine("Bad map. No tile information found.");
                    return(false);
                }

                int x = 0;
                int y = 0;

                while (tileElement != null)
                {
                    int tileGID      = int.Parse(tileElement.GetAttribute("gid"));
                    int subRectToUse = tileGID - firstTileID;

                    // Устанавливаем TextureRect каждого тайла
                    if (subRectToUse >= 0)
                    {
                        Sprite sprite = new Sprite();
                        sprite.Texture     = tilesetImage;
                        sprite.TextureRect = subRects[subRectToUse];
                        sprite.Position    = new Vector2f(x * tileWidth, y * tileHeight);
                        sprite.Color       = new Color(255, 255, 255, (byte)layer.opacity);

                        layer.tiles.Add(sprite);
                    }

                    tileElement = (XmlElement)tileElement.NextSibling;

                    x++;
                    if (x >= width)
                    {
                        x = 0;
                        y++;
                        if (y >= height)
                        {
                            y = 0;
                        }
                    }
                }

                layers.Add(layer);

                layerElement = (XmlElement)mapElement.GetElementsByTagName("layer").Item(i + 1);
            }



            // Работа с объектами
            XmlElement objectGroupElement;

            // Если есть слои объектов
            if (xDoc.GetElementsByTagName("objectgroup").Count != 0)
            {
                objectGroupElement = (XmlElement)mapElement.GetElementsByTagName("objectgroup")[0];

                for (int i = 0; i < mapElement.GetElementsByTagName("objectgroup").Count; i++)
                {
                    // Контейнер <object>
                    XmlElement objectElement = (XmlElement)objectGroupElement.GetElementsByTagName("object")[0];

                    for (int j = 0; j < objectGroupElement.GetElementsByTagName("object").Count; j++)
                    {
                        // Получаем все данные - тип, имя, позиция, etc
                        string objectType = string.Empty;
                        if (objectElement.HasAttribute("type"))
                        {
                            objectType = objectElement.GetAttribute("type");
                        }
                        string objectName = string.Empty;
                        if (objectElement.HasAttribute("name"))
                        {
                            objectName = objectElement.GetAttribute("name");
                        }
                        float objectRotation = 0.0f;
                        if (objectElement.HasAttribute("rotation"))
                        {
                            objectRotation = float.Parse(objectElement.GetAttribute("rotation"));
                        }
                        int x = int.Parse(objectElement.GetAttribute("x"));
                        int y = int.Parse(objectElement.GetAttribute("y"));

                        int width, height;

                        Sprite sprite = new Sprite();
                        sprite.Texture     = tilesetImage;
                        sprite.TextureRect = new IntRect(0, 0, 0, 0);
                        sprite.Position    = new Vector2f(x, y);

                        if (objectElement.HasAttribute("width"))
                        {
                            width  = int.Parse(objectElement.GetAttribute("width"));
                            height = int.Parse(objectElement.GetAttribute("height"));
                        }
                        else
                        {
                            width              = subRects[int.Parse(objectElement.GetAttribute("gid")) - firstTileID].Width;
                            height             = subRects[int.Parse(objectElement.GetAttribute("gid")) - firstTileID].Height;
                            sprite.TextureRect = subRects[int.Parse(objectElement.GetAttribute("gid")) - firstTileID];
                        }

                        // Экземпляр объекта
                        GameObject obj = new GameObject();
                        obj.name     = objectName;
                        obj.type     = objectType;
                        obj.rotation = objectRotation;
                        obj.sprite   = sprite;

                        FloatRect objectRect = new FloatRect();
                        objectRect.Left   = x;
                        objectRect.Top    = y;
                        objectRect.Width  = width;
                        objectRect.Height = height;
                        obj.rect          = objectRect;

                        // "Переменные" объекта
                        XmlElement properties = (XmlElement)objectElement.GetElementsByTagName("properties")[0];
                        if (properties != null)
                        {
                            XmlElement prop = (XmlElement)properties.GetElementsByTagName("property")[0];
                            if (prop != null)
                            {
                                for (int k = 0; k < properties.GetElementsByTagName("property").Count; k++)
                                {
                                    string propertyName  = prop.GetAttribute("name");
                                    string propertyValue = prop.GetAttribute("value");

                                    obj.properties.Add(propertyName, propertyValue);

                                    prop = (XmlElement)properties.GetElementsByTagName("property").Item(k + 1);
                                }
                            }
                        }

                        objects.Add(obj);

                        objectElement = (XmlElement)objectGroupElement.GetElementsByTagName("object").Item(j + 1);
                    }

                    objectGroupElement = (XmlElement)mapElement.GetElementsByTagName("objectgroup").Item(i + 1);
                }
            }
            else
            {
                Console.WriteLine("No object layers found...");
            }

            return(true);
        }
Example #36
0
        public void Update()
        {
            var equipped = false;

            for (var i = 0; i < Options.EquipmentSlots.Count; i++)
            {
                if (Globals.Me.MyEquipment[i] == mMySlot)
                {
                    equipped = true;

                    break;
                }
            }

            var item = ItemBase.Get(Globals.Me.Inventory[mMySlot].ItemId);

            if (Globals.Me.Inventory[mMySlot].ItemId != mCurrentItemId ||
                Globals.Me.Inventory[mMySlot].Quantity != mCurrentAmt ||
                equipped != mIsEquipped ||
                item == null && mTexLoaded != "" ||
                item != null && mTexLoaded != item.Icon ||
                mIconCd != Globals.Me.ItemOnCd(mMySlot) ||
                Globals.Me.ItemOnCd(mMySlot))
            {
                mCurrentItemId          = Globals.Me.Inventory[mMySlot].ItemId;
                mCurrentAmt             = Globals.Me.Inventory[mMySlot].Quantity;
                mIsEquipped             = equipped;
                EquipPanel.IsHidden     = !mIsEquipped;
                EquipLabel.IsHidden     = !mIsEquipped;
                mCooldownLabel.IsHidden = true;
                if (item != null)
                {
                    var itemTex = Globals.ContentManager.GetTexture(GameContentManager.TextureType.Item, item.Icon);
                    if (itemTex != null)
                    {
                        Pnl.Texture = itemTex;
                        if (Globals.Me.ItemOnCd(mMySlot))
                        {
                            Pnl.RenderColor = new Color(100, 255, 255, 255);
                        }
                        else
                        {
                            Pnl.RenderColor = new Color(255, 255, 255, 255);
                        }
                    }
                    else
                    {
                        if (Pnl.Texture != null)
                        {
                            Pnl.Texture = null;
                        }
                    }

                    mTexLoaded = item.Icon;
                    mIconCd    = Globals.Me.ItemOnCd(mMySlot);
                    if (mIconCd)
                    {
                        mCooldownLabel.IsHidden = false;
                        var secondsRemaining = (float)Globals.Me.ItemCdRemainder(mMySlot) / 1000f;
                        if (secondsRemaining > 10f)
                        {
                            mCooldownLabel.Text = Strings.Inventory.cooldown.ToString(secondsRemaining.ToString("N0"));
                        }
                        else
                        {
                            mCooldownLabel.Text = Strings.Inventory.cooldown.ToString(
                                secondsRemaining.ToString("N1").Replace(".", Strings.Numbers.dec)
                                );
                        }
                    }
                }
                else
                {
                    if (Pnl.Texture != null)
                    {
                        Pnl.Texture = null;
                    }

                    mTexLoaded = "";
                }

                if (mDescWindow != null)
                {
                    mDescWindow.Dispose();
                    mDescWindow = null;
                    pnl_HoverEnter(null, null);
                }
            }

            if (!IsDragging)
            {
                if (mMouseOver)
                {
                    if (!Globals.InputManager.MouseButtonDown(GameInput.MouseButtons.Left))
                    {
                        mCanDrag = true;
                        mMouseX  = -1;
                        mMouseY  = -1;
                        if (Globals.System.GetTimeMs() < mClickTime)
                        {
                            Globals.Me.TryUseItem(mMySlot);
                            mClickTime = 0;
                        }
                    }
                    else
                    {
                        if (mCanDrag && Draggable.Active == null)
                        {
                            if (mMouseX == -1 || mMouseY == -1)
                            {
                                mMouseX = InputHandler.MousePosition.X - Pnl.LocalPosToCanvas(new Point(0, 0)).X;
                                mMouseY = InputHandler.MousePosition.Y - Pnl.LocalPosToCanvas(new Point(0, 0)).Y;
                            }
                            else
                            {
                                var xdiff = mMouseX -
                                            (InputHandler.MousePosition.X - Pnl.LocalPosToCanvas(new Point(0, 0)).X);

                                var ydiff = mMouseY -
                                            (InputHandler.MousePosition.Y - Pnl.LocalPosToCanvas(new Point(0, 0)).Y);

                                if (Math.Sqrt(Math.Pow(xdiff, 2) + Math.Pow(ydiff, 2)) > 5)
                                {
                                    IsDragging = true;
                                    mDragIcon  = new Draggable(
                                        Pnl.LocalPosToCanvas(new Point(0, 0)).X + mMouseX,
                                        Pnl.LocalPosToCanvas(new Point(0, 0)).X + mMouseY, Pnl.Texture
                                        );
                                }
                            }
                        }
                    }
                }
            }
            else
            {
                if (mDragIcon.Update())
                {
                    //Drug the item and now we stopped
                    IsDragging = false;
                    var dragRect = new FloatRect(
                        mDragIcon.X - (Container.Padding.Left + Container.Padding.Right) / 2,
                        mDragIcon.Y - (Container.Padding.Top + Container.Padding.Bottom) / 2,
                        (Container.Padding.Left + Container.Padding.Right) / 2 + Pnl.Width,
                        (Container.Padding.Top + Container.Padding.Bottom) / 2 + Pnl.Height
                        );

                    float bestIntersect      = 0;
                    var   bestIntersectIndex = -1;

                    //So we picked up an item and then dropped it. Lets see where we dropped it to.
                    //Check inventory first.
                    if (mInventoryWindow.RenderBounds().IntersectsWith(dragRect))
                    {
                        for (var i = 0; i < Options.MaxInvItems; i++)
                        {
                            if (mInventoryWindow.Items[i].RenderBounds().IntersectsWith(dragRect))
                            {
                                if (FloatRect.Intersect(mInventoryWindow.Items[i].RenderBounds(), dragRect).Width *
                                    FloatRect.Intersect(mInventoryWindow.Items[i].RenderBounds(), dragRect).Height >
                                    bestIntersect)
                                {
                                    bestIntersect =
                                        FloatRect.Intersect(mInventoryWindow.Items[i].RenderBounds(), dragRect).Width *
                                        FloatRect.Intersect(mInventoryWindow.Items[i].RenderBounds(), dragRect).Height;

                                    bestIntersectIndex = i;
                                }
                            }
                        }

                        if (bestIntersectIndex > -1)
                        {
                            if (mMySlot != bestIntersectIndex)
                            {
                                //Try to swap....
                                PacketSender.SendSwapInvItems(bestIntersectIndex, mMySlot);
                                Globals.Me.SwapItems(bestIntersectIndex, mMySlot);
                            }
                        }
                    }
                    else if (Interface.GameUi.Hotbar.RenderBounds().IntersectsWith(dragRect))
                    {
                        for (var i = 0; i < Options.MaxHotbar; i++)
                        {
                            if (Interface.GameUi.Hotbar.Items[i].RenderBounds().IntersectsWith(dragRect))
                            {
                                if (FloatRect.Intersect(
                                        Interface.GameUi.Hotbar.Items[i].RenderBounds(), dragRect
                                        )
                                    .Width *
                                    FloatRect.Intersect(Interface.GameUi.Hotbar.Items[i].RenderBounds(), dragRect)
                                    .Height >
                                    bestIntersect)
                                {
                                    bestIntersect =
                                        FloatRect.Intersect(Interface.GameUi.Hotbar.Items[i].RenderBounds(), dragRect)
                                        .Width *
                                        FloatRect.Intersect(Interface.GameUi.Hotbar.Items[i].RenderBounds(), dragRect)
                                        .Height;

                                    bestIntersectIndex = i;
                                }
                            }
                        }

                        if (bestIntersectIndex > -1)
                        {
                            Globals.Me.AddToHotbar((byte)bestIntersectIndex, 0, mMySlot);
                        }
                    }

                    mDragIcon.Dispose();
                }
            }
        }
Example #37
0
 public QuadNode(FloatRect bounds)
 {
     Bounds  = bounds;
     Nodes   = new ReadOnlyCollection <QuadNode>(_nodes);
     Objects = new ReadOnlyCollection <T>(quadObjects);
 }
Example #38
0
        public void update()
        {
            View      calcView = Controller.Window.GetView();
            FloatRect overlap, calcPort = new FloatRect(calcView.Center.X - Controller.Window.Size.X / 2, calcView.Center.Y - Controller.Window.Size.Y / 2,
                                                        Controller.Window.Size.X, Controller.Window.Size.Y);

            Console.WriteLine(calcPort);

            //move the sprite if the view is moving off of it
            calcPort.Intersects(bgRects[4], out overlap);

            if (overlap.Height == calcPort.Height)
            {
                bgMoved[1] = false;
                bgMoved[3] = false;
            }
            if (overlap.Width == calcPort.Width)
            {
                bgMoved[0] = false;
                bgMoved[2] = false;
            }

            if (overlap.Left <= bgRects[4].Left && !bgMoved[0])
            {
                gameReference.bgMoveCallBack(Globals.moveDirection.left);
            }

            if (overlap.Top <= bgRects[4].Top && !bgMoved[3])
            {
                gameReference.bgMoveCallBack(Globals.moveDirection.up);
            }


            if (overlap.Left + calcPort.Width > bgRects[4].Left + bgRects[4].Width && !bgMoved[2])
            {
                gameReference.bgMoveCallBack(Globals.moveDirection.right);
            }

            if (overlap.Top + calcPort.Height > bgRects[4].Top + bgRects[4].Height && !bgMoved[1])
            {
                gameReference.bgMoveCallBack(Globals.moveDirection.down);
            }

            bool doRepos = true;

            //draw only if it would actually be seen
            for (int i = 0; i < bgRects.Length; i++)
            {
                if (calcPort.Intersects(bgRects[i]))
                {
                    bgDraw[i] = true;
                    doRepos   = false;
                }
                else
                {
                    bgDraw[i] = false;
                }
            }
            if (doRepos)
            {
                reposition(gameReference.myShip.GlobalCenter);
            }
        }
Example #39
0
        private void CheckWallCollision()
        {
            bool      ballWallColision = false;
            FloatRect myBounds         = GetGlobalBounds();

            Vector2u screenBounds = Engine.Get.Window.Size;

            if (myBounds.Left <= 0.0f)
            {
                Forward          = new Vector2f(-Forward.X, Forward.Y);
                Position         = new Vector2f(myBounds.Width * 0.5f, Position.Y);
                ballWallColision = true;
            }
            else if ((myBounds.Left + myBounds.Width * 0.5f) >= screenBounds.X)
            {
                Forward          = new Vector2f(-Forward.X, Forward.Y);
                Position         = new Vector2f(screenBounds.X - myBounds.Width * 0.5f, Position.Y);
                ballWallColision = true;
            }
            else if (myBounds.Top <= 0.0f)
            {
                Forward          = new Vector2f(Forward.X, -Forward.Y);
                Position         = new Vector2f(Position.X, myBounds.Height * 0.5f);
                ballWallColision = true;
            }
            else if (myBounds.Top >= screenBounds.Y)
            {
                var pad = Engine.Get.Scene.GetFirst <Pad> ();
                if (pad.ballList.Count == 1)
                {
                    MyGame.Get.HUD.NumLifes -= 1; // restamos vidas
                    // CAMBIAR EL ESTADO A WAITTING FOR BALL
                    MyGame.Get.ChangeStateToWaitingForBall();
                }


                Engine.Get.Scene.GetAll <Ball> ().Remove(this); // la borramos de la lista de la pla
                pad.ballList.Remove(this);                      // la borramos de la lita del juego

                Destroy();
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Eliminamos bola");
                Console.ResetColor();
            }

            // SONIDOS DE LA PELOTA CON LAS PAREDES
            if (ballWallColision == true)
            {
                Random alea = new Random();
                switch (alea.Next(1, 4))
                {
                case 1:
                    ballSFX = new Sound(sfBall_01);
                    break;

                case 2:
                    ballSFX = new Sound(sfBall_02);
                    break;

                case 3:
                    ballSFX = new Sound(sfBall_03);
                    break;
                }
                ballSFX.Play();
            }
        }
Example #40
0
        public static Vector2f GetSize(Text T)
        {
            FloatRect B = T.GetLocalBounds();

            return(new Vector2f(B.Width, B.Height));
        }
Example #41
0
        public void Update()
        {
            var n = mMySide;

            if (Globals.Trade[n, mMySlot].ItemId != mCurrentItemId)
            {
                mCurrentItemId = Globals.Trade[n, mMySlot].ItemId;
                var item = ItemBase.Get(Globals.Trade[n, mMySlot].ItemId);
                if (item != null)
                {
                    var itemTex = Globals.ContentManager.GetTexture(GameContentManager.TextureType.Item, item.Icon);
                    if (itemTex != null)
                    {
                        Pnl.Texture = itemTex;
                    }
                    else
                    {
                        if (Pnl.Texture != null)
                        {
                            Pnl.Texture = null;
                        }
                    }
                }
                else
                {
                    if (Pnl.Texture != null)
                    {
                        Pnl.Texture = null;
                    }
                }
            }

            if (!IsDragging)
            {
                if (mMouseOver)
                {
                    if (!Globals.InputManager.MouseButtonDown(GameInput.MouseButtons.Left))
                    {
                        if (n == 0)
                        {
                            mCanDrag = true;
                        } //Only be able to drag your trade box

                        mMouseX = -1;
                        mMouseY = -1;
                        if (Globals.System.GetTimeMs() < mClickTime)
                        {
                            //Globals.Me.TryUseItem(_mySlot);
                            mClickTime = 0;
                        }
                    }
                    else
                    {
                        if (mCanDrag && Draggable.Active == null)
                        {
                            if (mMouseX == -1 || mMouseY == -1)
                            {
                                mMouseX = InputHandler.MousePosition.X - Pnl.LocalPosToCanvas(new Point(0, 0)).X;
                                mMouseY = InputHandler.MousePosition.Y - Pnl.LocalPosToCanvas(new Point(0, 0)).Y;
                            }
                            else
                            {
                                var xdiff = mMouseX -
                                            (InputHandler.MousePosition.X - Pnl.LocalPosToCanvas(new Point(0, 0)).X);

                                var ydiff = mMouseY -
                                            (InputHandler.MousePosition.Y - Pnl.LocalPosToCanvas(new Point(0, 0)).Y);

                                if (Math.Sqrt(Math.Pow(xdiff, 2) + Math.Pow(ydiff, 2)) > 5)
                                {
                                    IsDragging = true;
                                    mDragIcon  = new Draggable(
                                        Pnl.LocalPosToCanvas(new Point(0, 0)).X + mMouseX,
                                        Pnl.LocalPosToCanvas(new Point(0, 0)).X + mMouseY, Pnl.Texture
                                        );
                                }
                            }
                        }
                    }
                }
            }
            else
            {
                if (mDragIcon.Update())
                {
                    //Drug the item and now we stopped
                    IsDragging = false;
                    var dragRect = new FloatRect(
                        mDragIcon.X - sItemXPadding / 2, mDragIcon.Y - sItemYPadding / 2, sItemXPadding / 2 + 32,
                        sItemYPadding / 2 + 32
                        );

                    float bestIntersect      = 0;
                    var   bestIntersectIndex = -1;

                    //So we picked up an item and then dropped it. Lets see where we dropped it to.
                    //Check inventory first.
                    if (mTradeWindow.RenderBounds().IntersectsWith(dragRect))
                    {
                        for (var i = 0; i < Options.MaxInvItems; i++)
                        {
                            if (mTradeWindow.TradeSegment[n].Items[i].RenderBounds().IntersectsWith(dragRect))
                            {
                                if (FloatRect.Intersect(mTradeWindow.TradeSegment[n].Items[i].RenderBounds(), dragRect)
                                    .Width *
                                    FloatRect.Intersect(mTradeWindow.TradeSegment[n].Items[i].RenderBounds(), dragRect)
                                    .Height >
                                    bestIntersect)
                                {
                                    bestIntersect =
                                        FloatRect.Intersect(
                                            mTradeWindow.TradeSegment[n].Items[i].RenderBounds(), dragRect
                                            )
                                        .Width *
                                        FloatRect.Intersect(
                                            mTradeWindow.TradeSegment[n].Items[i].RenderBounds(), dragRect
                                            )
                                        .Height;

                                    bestIntersectIndex = i;
                                }
                            }
                        }

                        if (bestIntersectIndex > -1)
                        {
                            if (mMySlot != bestIntersectIndex)
                            {
                                //Trade
                                //PacketSender.SendTradeConfirm(bestIntersectIndex);
                            }
                        }
                    }

                    mDragIcon.Dispose();
                }
            }
        }
Example #42
0
 public IEnumerable <TileRef> GetWallsIntersecting(FloatRect area)
 {
     return(GetTilesIntersecting(area, true).Where(t => t.Tile.TileDef.IsWall));
 }
Example #43
0
        private static void UpdateView()
        {
            if (Globals.Me == null)
            {
                CurrentView = new FloatRect(0, 0, Renderer.GetScreenWidth(), Renderer.GetScreenHeight());
                Renderer.SetView(CurrentView);

                return;
            }

            var map = MapInstance.Get(Globals.Me.CurrentMap);
            if (Globals.GameState == GameStates.InGame && map != null)
            {
                var en = Globals.Me;
                var x = map.GetX() - Options.MapWidth * Options.TileWidth;
                var y = map.GetY() - Options.MapHeight * Options.TileHeight;
                var x1 = map.GetX() + Options.MapWidth * Options.TileWidth * 2;
                var y1 = map.GetY() + Options.MapHeight * Options.TileHeight * 2;
                if (map.CameraHolds[(int) Directions.Up])
                {
                    y += Options.MapHeight * Options.TileHeight;
                }

                if (map.CameraHolds[(int) Directions.Left])
                {
                    x += Options.MapWidth * Options.TileWidth;
                }

                if (map.CameraHolds[(int) Directions.Right])
                {
                    x1 -= Options.MapWidth * Options.TileWidth;
                }

                if (map.CameraHolds[(int) Directions.Down])
                {
                    y1 -= Options.MapHeight * Options.TileHeight;
                }

                var w = x1 - x;
                var h = y1 - y;
                var restrictView = new FloatRect(x, y, w, h);
                CurrentView = new FloatRect(
                    (int) Math.Ceiling(en.GetCenterPos().X - Renderer.GetScreenWidth() / 2f),
                    (int) Math.Ceiling(en.GetCenterPos().Y - Renderer.GetScreenHeight() / 2f),
                    Renderer.GetScreenWidth(), Renderer.GetScreenHeight()
                );

                if (restrictView.Width >= CurrentView.Width)
                {
                    if (CurrentView.Left < restrictView.Left)
                    {
                        CurrentView.X = restrictView.Left;
                    }

                    if (CurrentView.Left + CurrentView.Width > restrictView.Left + restrictView.Width)
                    {
                        CurrentView.X -=
                            CurrentView.Left + CurrentView.Width - (restrictView.Left + restrictView.Width);
                    }
                }

                if (restrictView.Height >= CurrentView.Height)
                {
                    if (CurrentView.Top < restrictView.Top)
                    {
                        CurrentView.Y = restrictView.Top;
                    }

                    if (CurrentView.Top + CurrentView.Height > restrictView.Top + restrictView.Height)
                    {
                        CurrentView.Y -=
                            CurrentView.Top + CurrentView.Height - (restrictView.Top + restrictView.Height);
                    }
                }
            }
            else
            {
                CurrentView = new FloatRect(0, 0, Renderer.GetScreenWidth(), Renderer.GetScreenHeight());
            }

            Renderer.SetView(CurrentView);
        }
        public static Vector2f GetSpriteOrigin(Sprite sprite, float xPercent = .5f, float yPercent = .5f)
        {
            FloatRect rect = sprite.GetLocalBounds();

            return(new Vector2f(rect.Left + (rect.Width * xPercent), rect.Top + (rect.Height * yPercent)));
        }
        public static Vector2f GetTextOrigin(Text textobj, float xPercent = .5f, float yPercent = .5f)
        {
            FloatRect rect = textobj.GetLocalBounds();

            return(new Vector2f(rect.Left + (rect.Width * xPercent), rect.Top + (rect.Height * yPercent)));
        }
Example #46
0
 public static bool InBounds(FloatRect bounds, Vector2f point)
 {
     return(point.X >= bounds.Left && point.Y >= bounds.Top && point.X <= bounds.Width && point.Y <= bounds.Height);
 }
Example #47
0
        public override void Draw()
        {
            WorldPos.Reset();
            if (MapInstance.Get(CurrentMap) == null || !Globals.GridMaps.Contains(CurrentMap))
            {
                return;
            }


            var         map           = MapInstance.Get(CurrentMap);
            var         srcRectangle  = new FloatRect();
            var         destRectangle = new FloatRect();
            GameTexture srcTexture    = null;
            var         height        = 0;
            var         width         = 0;
            var         d             = 0;

            switch (Graphic.Type)
            {
            case EventGraphicType.Sprite:     //Sprite
                var entityTex = Globals.ContentManager.GetTexture(
                    GameContentManager.TextureType.Entity, Graphic.Filename
                    );

                if (entityTex != null)
                {
                    srcTexture = entityTex;
                    height     = srcTexture.GetHeight() / Options.Instance.Sprites.Directions;
                    width      = srcTexture.GetWidth() / Options.Instance.Sprites.NormalFrames;
                    d          = Graphic.Y;
                    if (!DirectionFix)
                    {
                        switch (Dir)
                        {
                        case 0:
                            d = 3;

                            break;

                        case 1:
                            d = 0;

                            break;

                        case 2:
                            d = 1;

                            break;

                        case 3:
                            d = 2;

                            break;
                        }
                    }

                    var frame = Graphic.X;
                    if (WalkingAnim)
                    {
                        frame = WalkFrame;
                    }

                    if (Options.AnimatedSprites.Contains(Graphic.Filename.ToLower()))
                    {
                        srcRectangle = new FloatRect(
                            AnimationFrame * (int)entityTex.GetWidth() / Options.Instance.Sprites.NormalFrames, d * (int)entityTex.GetHeight() / Options.Instance.Sprites.Directions,
                            (int)entityTex.GetWidth() / Options.Instance.Sprites.NormalFrames, (int)entityTex.GetHeight() / Options.Instance.Sprites.Directions
                            );
                    }
                    else
                    {
                        srcRectangle = new FloatRect(
                            frame * (int)srcTexture.GetWidth() / Options.Instance.Sprites.NormalFrames, d * (int)srcTexture.GetHeight() / Options.Instance.Sprites.Directions,
                            (int)srcTexture.GetWidth() / Options.Instance.Sprites.NormalFrames, (int)srcTexture.GetHeight() / Options.Instance.Sprites.Directions
                            );
                    }
                }

                break;

            case EventGraphicType.Tileset:     //Tile
                if (mCachedTilesetName != Graphic.Filename)
                {
                    mCachedTilesetName = Graphic.Filename;
                    mCachedTileset     = Globals.ContentManager.GetTexture(
                        GameContentManager.TextureType.Tileset, Graphic.Filename
                        );
                }

                var tileset = mCachedTileset;
                if (tileset != null)
                {
                    srcTexture   = tileset;
                    width        = (Graphic.Width + 1) * Options.TileWidth;
                    height       = (Graphic.Height + 1) * Options.TileHeight;
                    srcRectangle = new FloatRect(
                        Graphic.X * Options.TileWidth, Graphic.Y * Options.TileHeight,
                        (Graphic.Width + 1) * Options.TileWidth, (Graphic.Height + 1) * Options.TileHeight
                        );
                }

                break;
            }

            destRectangle.X = map.GetX() + X * Options.TileWidth + OffsetX;
            if (height > Options.TileHeight)
            {
                destRectangle.Y = map.GetY() + Y * Options.TileHeight + OffsetY - (height - Options.TileHeight);
            }
            else
            {
                destRectangle.Y = map.GetY() + Y * Options.TileHeight + OffsetY;
            }

            if (width > Options.TileWidth)
            {
                destRectangle.X -= (width - Options.TileWidth) / 2;
            }

            destRectangle.X      = (int)Math.Ceiling(destRectangle.X);
            destRectangle.Y      = (int)Math.Ceiling(destRectangle.Y);
            destRectangle.Width  = srcRectangle.Width;
            destRectangle.Height = srcRectangle.Height;
            WorldPos             = destRectangle;
            if (srcTexture != null)
            {
                Graphics.DrawGameTexture(srcTexture, srcRectangle, destRectangle, Intersect.Color.White);
            }
        }
Example #48
0
        public override void DrawIn(RenderWindow window, ref FloatRect boundsView)
        {
            animationWater.Visit(this);

            base.DrawIn(window, ref boundsView);
        }
Example #49
0
        private bool CheckWallBounce(Vector2f destination, ref WorldBorder windowBorder, FloatRect borderBounds)
        {
            if (!(destination.Y - (_boundingBox.GetGlobalBounds().Height / 2f) <=
                  borderBounds.Top + windowBorder.Border.OutlineThickness) &&
                !(destination.Y + (_boundingBox.GetGlobalBounds().Height / 2f) >=
                  borderBounds.Height - windowBorder.Border.OutlineThickness))
            {
                return(false);
            }

            SetVelocity(new Vector2f(_velocity.X, -_velocity.Y)); // invert Y axis velocity
            return(true);
        }
Example #50
0
 public RoundRectRenderer(FloatRect rect, FloatRectCorners radii, float tens)
 {
     rectangle = rect;
     corners   = radii;
     tension   = tens;
 }
Example #51
0
        public void UpdateGUIPosition()
        {
            _imgMainBg.Position = new Vector2i(
                (int)((CluwneLib.Screen.Size.X / 2f) - (_imgMainBg.ClientArea.Width / 2f)),
                (int)((CluwneLib.Screen.Size.Y / 2f) - (_imgMainBg.ClientArea.Height / 2f)));
            _imgMainBg.Update(0);

            _recStatus = new FloatRect(_imgMainBg.Position.X + 10, _imgMainBg.Position.Y + 63, 785, 21);

            _imgStatus.Position = new Vector2i((int)_recStatus.Left,
                                               (int)_recStatus.Top);
            _imgStatus.Update(0);

            _lblServer.Position = new Vector2i((int)_recStatus.Left + 5,
                                               (int)_recStatus.Top + 2);
            _lblServer.Update(0);

            _lblServerInfo.Position = new Vector2i(_lblServer.ClientArea.Right(),
                                                   _lblServer.ClientArea.Top);
            _lblServerInfo.Update(0);

            _lblMode.Position = new Vector2i(_lblServerInfo.ClientArea.Right() + (int)_lastLblSpacing,
                                             _lblServerInfo.ClientArea.Top);
            _lblMode.Update(0);

            _lblModeInfo.Position = new Vector2i(_lblMode.ClientArea.Right(),
                                                 _lblMode.ClientArea.Top);
            _lblModeInfo.Update(0);

            _lblPlayers.Position = new Vector2i(_lblModeInfo.ClientArea.Right() + (int)_lastLblSpacing,
                                                _lblModeInfo.ClientArea.Top);
            _lblPlayers.Update(0);

            _lblPlayersInfo.Position = new Vector2i(_lblPlayers.ClientArea.Right(),
                                                    _lblPlayers.ClientArea.Top);
            _lblPlayersInfo.Update(0);

            _lblPort.Position = new Vector2i(_lblPlayersInfo.ClientArea.Right() + (int)_lastLblSpacing,
                                             _lblPlayersInfo.ClientArea.Top);
            _lblPort.Update(0);

            _lblPortInfo.Position = new Vector2i(_lblPort.ClientArea.Right(),
                                                 _lblPort.ClientArea.Top);
            _lblPortInfo.Update(0);

            _tabs.Position = _imgMainBg.Position + new Vector2i(5, 90);
            _tabs.Update(0);

            _lobbyChat.Position = new Vector2i(_imgMainBg.ClientArea.Left + 12,
                                               _imgMainBg.ClientArea.Bottom() - _lobbyChat.ClientArea.Height - 12); //Wish the chat box wasnt such shit. Then i wouldnt have to do this here.
            _lobbyChat.Update(0);

            _imgChatBg.Position = new Vector2i(_lobbyChat.ClientArea.Left - 6,
                                               _lobbyChat.ClientArea.Top - 9);
            _imgChatBg.Update(0);

            _btnReady.Position = new Vector2i(_lobbyChat.ClientArea.Right() - _btnReady.ClientArea.Width - 5,
                                              _lobbyChat.ClientArea.Top - _btnReady.ClientArea.Height - 8);
            _btnReady.Update(0);

            _btnBack.Position = new Vector2i(_lobbyChat.ClientArea.Left - _btnBack.ClientArea.Width - 20,
                                             _lobbyChat.ClientArea.Bottom() - _btnBack.ClientArea.Height);
            _btnBack.Update(0);
        }
Example #52
0
        public void Update()
        {
            var spell = SpellBase.Get(Globals.Me.Spells[mYindex].SpellId);

            if (!IsDragging &&
                (mTexLoaded != "" && spell == null ||
                 spell != null && mTexLoaded != spell.Icon ||
                 mCurrentSpellId != Globals.Me.Spells[mYindex].SpellId ||
                 mIconCd !=
                 Globals.Me.GetSpellCooldown(Globals.Me.Spells[mYindex].SpellId) > Globals.System.GetTimeMs() ||
                 Globals.Me.GetSpellCooldown(Globals.Me.Spells[mYindex].SpellId) > Globals.System.GetTimeMs()))
            {
                mCooldownLabel.IsHidden = true;
                if (spell != null)
                {
                    var spellTex = Globals.ContentManager.GetTexture(GameContentManager.TextureType.Spell, spell.Icon);
                    if (spellTex != null)
                    {
                        Pnl.Texture = spellTex;
                        if (Globals.Me.GetSpellCooldown(Globals.Me.Spells[mYindex].SpellId) >
                            Globals.System.GetTimeMs())
                        {
                            Pnl.RenderColor = new Color(100, 255, 255, 255);
                        }
                        else
                        {
                            Pnl.RenderColor = new Color(255, 255, 255, 255);
                        }
                    }
                    else
                    {
                        if (Pnl.Texture != null)
                        {
                            Pnl.Texture = null;
                        }
                    }

                    mTexLoaded      = spell.Icon;
                    mCurrentSpellId = Globals.Me.Spells[mYindex].SpellId;
                    mIconCd         = Globals.Me.GetSpellCooldown(Globals.Me.Spells[mYindex].SpellId) >
                                      Globals.System.GetTimeMs();

                    if (mIconCd)
                    {
                        mCooldownLabel.IsHidden = false;
                        var secondsRemaining =
                            (float)(Globals.Me.GetSpellCooldown(Globals.Me.Spells[mYindex].SpellId) -
                                    Globals.System.GetTimeMs()) /
                            1000f;

                        if (secondsRemaining > 10f)
                        {
                            mCooldownLabel.Text = Strings.Spells.cooldown.ToString(secondsRemaining.ToString("N0"));
                        }
                        else
                        {
                            mCooldownLabel.Text = Strings.Spells.cooldown.ToString(
                                secondsRemaining.ToString("N1").Replace(".", Strings.Numbers.dec)
                                );
                        }
                    }
                }
                else
                {
                    if (Pnl.Texture != null)
                    {
                        Pnl.Texture = null;
                    }

                    mTexLoaded = "";
                }
            }

            if (!IsDragging)
            {
                if (mMouseOver)
                {
                    if (!Globals.InputManager.MouseButtonDown(GameInput.MouseButtons.Left))
                    {
                        mCanDrag = true;
                        mMouseX  = -1;
                        mMouseY  = -1;
                        if (Globals.System.GetTimeMs() < mClickTime)
                        {
                            Globals.Me.TryUseSpell(mYindex);
                            mClickTime = 0;
                        }
                    }
                    else
                    {
                        if (mCanDrag && Draggable.Active == null)
                        {
                            if (mMouseX == -1 || mMouseY == -1)
                            {
                                mMouseX = InputHandler.MousePosition.X - Pnl.LocalPosToCanvas(new Point(0, 0)).X;
                                mMouseY = InputHandler.MousePosition.Y - Pnl.LocalPosToCanvas(new Point(0, 0)).Y;
                            }
                            else
                            {
                                var xdiff = mMouseX -
                                            (InputHandler.MousePosition.X - Pnl.LocalPosToCanvas(new Point(0, 0)).X);

                                var ydiff = mMouseY -
                                            (InputHandler.MousePosition.Y - Pnl.LocalPosToCanvas(new Point(0, 0)).Y);

                                if (Math.Sqrt(Math.Pow(xdiff, 2) + Math.Pow(ydiff, 2)) > 5)
                                {
                                    IsDragging = true;
                                    mDragIcon  = new Draggable(
                                        Pnl.LocalPosToCanvas(new Point(0, 0)).X + mMouseX,
                                        Pnl.LocalPosToCanvas(new Point(0, 0)).X + mMouseY, Pnl.Texture
                                        );

                                    mTexLoaded = "";
                                }
                            }
                        }
                    }
                }
            }
            else
            {
                if (mDragIcon.Update())
                {
                    //Drug the item and now we stopped
                    IsDragging = false;
                    var dragRect = new FloatRect(
                        mDragIcon.X - (Container.Padding.Left + Container.Padding.Right) / 2,
                        mDragIcon.Y - (Container.Padding.Top + Container.Padding.Bottom) / 2,
                        (Container.Padding.Left + Container.Padding.Right) / 2 + Pnl.Width,
                        (Container.Padding.Top + Container.Padding.Bottom) / 2 + Pnl.Height
                        );

                    float bestIntersect      = 0;
                    var   bestIntersectIndex = -1;

                    //So we picked up an item and then dropped it. Lets see where we dropped it to.
                    //Check spell first.
                    if (mSpellWindow.RenderBounds().IntersectsWith(dragRect))
                    {
                        for (var i = 0; i < Options.MaxInvItems; i++)
                        {
                            if (i < mSpellWindow.Items.Count &&
                                mSpellWindow.Items[i].RenderBounds().IntersectsWith(dragRect))
                            {
                                if (FloatRect.Intersect(mSpellWindow.Items[i].RenderBounds(), dragRect).Width *
                                    FloatRect.Intersect(mSpellWindow.Items[i].RenderBounds(), dragRect).Height >
                                    bestIntersect)
                                {
                                    bestIntersect =
                                        FloatRect.Intersect(mSpellWindow.Items[i].RenderBounds(), dragRect).Width *
                                        FloatRect.Intersect(mSpellWindow.Items[i].RenderBounds(), dragRect).Height;

                                    bestIntersectIndex = i;
                                }
                            }
                        }

                        if (bestIntersectIndex > -1)
                        {
                            if (mYindex != bestIntersectIndex)
                            {
                                //Try to swap....
                                PacketSender.SendSwapSpells(bestIntersectIndex, mYindex);
                                Globals.Me.SwapSpells(bestIntersectIndex, mYindex);
                            }
                        }
                    }
                    else if (Interface.GameUi.Hotbar.RenderBounds().IntersectsWith(dragRect))
                    {
                        for (var i = 0; i < Options.MaxHotbar; i++)
                        {
                            if (Interface.GameUi.Hotbar.Items[i].RenderBounds().IntersectsWith(dragRect))
                            {
                                if (FloatRect.Intersect(
                                        Interface.GameUi.Hotbar.Items[i].RenderBounds(), dragRect
                                        )
                                    .Width *
                                    FloatRect.Intersect(Interface.GameUi.Hotbar.Items[i].RenderBounds(), dragRect)
                                    .Height >
                                    bestIntersect)
                                {
                                    bestIntersect =
                                        FloatRect.Intersect(Interface.GameUi.Hotbar.Items[i].RenderBounds(), dragRect)
                                        .Width *
                                        FloatRect.Intersect(Interface.GameUi.Hotbar.Items[i].RenderBounds(), dragRect)
                                        .Height;

                                    bestIntersectIndex = i;
                                }
                            }
                        }

                        if (bestIntersectIndex > -1)
                        {
                            Globals.Me.AddToHotbar((byte)bestIntersectIndex, 1, mYindex);
                        }
                    }

                    mDragIcon.Dispose();
                }
            }
        }
Example #53
0
 public static bool Encloses(this FloatRect outer, FloatRect inner)
 => (outer.Left <= inner.Left) &&
 (inner.Right() <= outer.Right()) &&
 (outer.Top <= inner.Top) &&
 (inner.Bottom() <= outer.Bottom());
Example #54
0
 public static bool IsEmpty(this FloatRect rect) => rect.Left == 0 && rect.Top == 0 && rect.Width == 0 && rect.Height == 0;
 public PatternChangedEventArgs(FloatRect oldP, FloatRect newP)
 {
     NewPattern = newP;
     OldPattern = oldP;
 }
Example #56
0
 public static float Right(this FloatRect rect) => rect.Left + rect.Width;
 public AccelerationArea(FloatRect rect, Vector2f acceleration)
 {
     Area         = rect;
     Acceleration = acceleration;
 }
Example #58
0
 public HitboxComponent()
 {
     Family = ComponentFamily.Hitbox;
     AABB   = new FloatRect();
 }
Example #59
0
        private static void myResizeHandler(object sender, SizeEventArgs e)
        {
            FloatRect visibleArea = new FloatRect(new Vector2f(0, 0), new Vector2f(e.Width, e.Height));

            window.SetView(new View(visibleArea));
        }
 public void SetTextureRect(FloatRect textureRect)
 {
     m_textureRect = textureRect;
     UpdateQuad();
 }