# Question
Title: How do I draw anti-aliased holes in a bitmap
I have an artillery game (hobby-learning project) and when the projectile hits it leaves a hole in the ground. I want this hole to have antialiased edges. I'm using `System.Drawing` for this. I've tried with clipping paths, and drawing with a transparent color using `gfx.CompositingMode = CompositingMode.SourceCopy`, but it gives me the same result. If I draw a circle with a solid color it works fine, but I need a hole, a circle with 0 alpha values.

I have enabled these but they work only with solid colors:

```
gfx.CompositingQuality = CompositingQuality.HighQuality;
gfx.InterpolationMode = InterpolationMode.HighQualityBicubic;
gfx.SmoothingMode = SmoothingMode.AntiAlias;

```

In the two pictures consider black as being transparent.

This is what I have (zoomed in):

And what I need is something like this (made with photoshop):

This will be just a visual effect, in code for collision detection I still treat everything with alpha \> 128 as solid.

**Edit:** I'm usink OpenTK for this game. But for this question I think it doesn't really matter probably it is `gdi+` related.

# Answer
As you have noticed clipping or regions in GDI+ are not antialiased as they are both pixel based where a given pixel can either be completely included or excluded.

To do what you want in GDI+ you can apply an alpha mask to the image yourself. Basically you fill a rectangle of the size of the area affected with black color and then draw the hole with white using the high quality settings for Antialiasing and smoothing. Then you apply the resulting image as an alpha mask to the original image. (which means that you re-calculate the alpha value of the pixels involved based on the black/white image where completely white pixels will be transparent) To do this quickly you should use the fast pointer access to the pixel data via LockBits()..

Here is a GDI+ example. This will only work if the images are 32bppArgb format and both are the same size - if you only need to apply an alpha mask to a small portion of the original image I would suggest you adjust the code to do that.

```
public static void ApplyAlphaMask(Bitmap bmp, Bitmap alphaMaskImage)
{
  int width = bmp.Width;
  int height = bmp.Height;

  BitmapData dataAlphaMask = alphaMaskImage.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
  try
  {
    BitmapData data = bmp.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);
    try
    {
      unsafe //using pointer requires the unsafe keyword
      {
        byte* pData0Mask = (byte*)dataAlphaMask.Scan0;
        byte* pData0 = (byte*)data.Scan0;

        for (int x = 0; x < width; x++)
        {
          for (int y = 0; y < height; y++)
          {
            byte* pData = pData0 + (y * data.Stride) + (x * 4);
            byte* pDataMask = pData0Mask + (y * dataAlphaMask.Stride) + (x * 4);

            byte maskBlue = pDataMask[0];
            byte maskGreen = pDataMask[1];
            byte maskRed = pDataMask[2];

            //the closer the color is to black the more opaque it will be.
            byte alpha = (byte)(255 - (maskRed + maskBlue + maskGreen) / 3);

            //respect the original alpha value
            byte originalAlpha = pData[3];
            pData[3] = (byte)(((float)(alpha * originalAlpha)) / 255f);
          }
        }
      }
    }
    finally
    {
      bmp.UnlockBits(data);
    }
  }
  finally
  {
    alphaMaskImage.UnlockBits(dataAlphaMask);
  }
}

```
> 3 votes

# Answer
```
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
using System.Collections.Generic;

[assembly: CLSCompliant(true)]
namespace PtzControl {

    public partial class PtzUserControl : UserControl {

        #region Private Members

        /// <summary>
        /// Distance between zoom rectangles and the left and right side of the control.
        /// </summary>
        private const int _marginForZoomRectangles = 10;

        /// <summary>
        /// Distance between the upper portion and the lower portion (i.e the zoom portion).
        /// </summary>
        private const int _marginOuterToZoomRectangles = 7;

        /// <summary>
        /// Encapsulates outer circle.
        /// </summary>
        private Rectangle _outerRectangle;

        /// <summary>
        /// Encapsulates middle circle.
        /// </summary>
        private Rectangle _middleRectangle;

        /// <summary>
        /// Encapsulates inner circle.
        /// </summary>
        private Rectangle _innerRectangle;

        /// <summary>
        /// Holds the Zoom In region.
        /// </summary>
        private Rectangle _zoomInRectangle;

        /// <summary>
        /// Holds Zoom Out region.
        /// </summary>
        private Rectangle _zoomOutRectangle;

        /// <summary>
        /// Region between outer circle and the middle circle.
        /// </summary>
        private Region _outerCircleRegion;

        /// <summary>
        /// Region between the middle region and the inner region.
        /// </summary>
        private Region _middleCircleRegion;

        /// <summary>
        /// Inner circlular region.
        /// </summary>
        private Region _innerCircleRegion;

        /// <summary>
        /// Pan Up Button region in OuterCircle region.
        /// </summary>
        private Region _upButtonRegion;

        /// <summary>
        /// Pan Down Button region in OuterCircle region.
        /// </summary>
        private Region _downButtonRegion;

        /// <summary>
        /// Pan Left Button region in OuterCircle region.
        /// </summary>
        private Region _leftButtonRegion;

        /// <summary>
        /// Pan Right Button region in OuterCircle region.
        /// </summary>
        private Region _rightButtonRegion;

        /// <summary>
        /// Zoom In Button region.
        /// </summary>
        private Region _zoomInButtonRegion;

        /// <summary>
        /// Zoom Out Button region.
        /// </summary>
        private Region _zoomOutButtonRegion;

        /// <summary>
        /// Pen to draw direction angles, zoom in and zoom out lines.
        /// </summary>
        private Pen _penToDrawLines;

        /// <summary>
        /// Brush used to fill the control with the default color.
        /// </summary>
        private SolidBrush _defaultBrush;

        /// <summary>
        /// PtzControl to fill the control with the hover color.
        /// </summary>
        private SolidBrush _hoverBrush;

        /// <summary>
        /// Brush used to fill the inner circle.
        /// </summary>
        private SolidBrush _whiteBrush;

        /// <summary>
        /// Graphics object fills the regions on focus gain and relese condition using respective brushes
        /// (i.e hoveBrush ot defaultBrush).
        /// </summary>
        private Graphics _graphics;

        /// <summary>
        /// In the Mouse click event it is used to get where the house hasbeen clicked.
        /// It stores the current mouse position in context with the mouse region.
        /// </summary>
        private MouseLocation _currentMouseLocation;

        /// <summary>
        /// Holds the previous mouse location.
        /// </summary>
        private MouseLocation _previousMouseLocation;

        /// <summary>
        /// It used to create the regions.
        /// </summary>
        private readonly GraphicsPath _graphicsPathToSetRegins = new GraphicsPath();

        /// <summary>
        /// Virtical Line in the Zoom In Button Plus Sign.
        /// </summary>
        private readonly List<Point> _zoomInVirticleLine = new List<Point> {
                                new Point(_marginForZoomRectangles + 10, 80 + _marginOuterToZoomRectangles + 15),
                                new Point(_marginForZoomRectangles + 20, 80 + _marginOuterToZoomRectangles + 15)};

        /// <summary>
        /// Horizontal Line in the Zoom In Button Plus Sign.
        /// </summary>
        private readonly List<Point> _zoomInHorizontolLine = new List<Point> {
                                new Point(_marginForZoomRectangles + 15, 80 + _marginOuterToZoomRectangles + 10),
                                new Point(_marginForZoomRectangles + 15, 80 + _marginOuterToZoomRectangles + 20)};

        /// <summary>
        /// Horizontal Line in the Zoom Out Button Minus Sign.
        /// </summary>
        private readonly List<Point> _zoomOutLine = new List<Point> {
                                new Point(_marginForZoomRectangles + 30 + 1 + 10, 80 + _marginOuterToZoomRectangles + 15),
                                new Point(_marginForZoomRectangles + 30 + 1 + 20, 80 + _marginOuterToZoomRectangles + 15)};

        /// <summary>
        /// Points in angle on the Up button.
        /// </summary>
        private readonly List<Point> _upButtonAngle = new List<Point> {
                                new Point(40, 10), new Point(35, 15), new Point(40, 10), new Point(45, 15)};

        /// <summary>
        /// Points in angle on Left button.
        /// </summary>
        private readonly List<Point> _leftButtonAngle = new List<Point> {
                                new Point(10, 40), new Point(15, 35), new Point(10, 40), new Point(15, 45)};

        /// <summary>
        /// Points in andle on right button.
        /// </summary>
        private readonly List<Point> _rightButtonAngle = new List<Point> {
                                new Point(70, 40), new Point(65, 35), new Point(70, 40), new Point(65, 45)};

        /// <summary>
        /// Points in angle on down button.
        /// </summary>
        private readonly List<Point> _downButtonAngle = new List<Point> {
                                new Point(40, 70), new Point(35, 65), new Point(40, 70), new Point(45, 65)};

        #endregion

        #region Constructor

        /// <summary>
        /// Creates the regions and Initialises the graphics componants.
        /// **The initilization sequence must be maintained as the different componants are dependent of
        /// others, here regions are dependent of the rectangles and so rectangles have to be initialize before the
        /// regios.
        /// </summary>
        public PtzUserControl() {
            InitializeComponent();
            InitializeRectangles();
            InitializeRegions();
            InitializeGraphicsComponants();
        }

        #endregion

        #region Private Methods

        /// <summary>
        /// Initilizes all the rectangles that are used to drall the control.
        /// </summary>
        private void InitializeRectangles() {

            int _outerCircleDiameter = 80;
            int _middleCircleDiameter = 32;
            int _innerCircleDiameter = 12;
            int _zoomRectangleWidth = 30;
            int _marginBetweenOuterAndMiddleRectangle = (_outerCircleDiameter / 2 - _middleCircleDiameter / 2);
            int _marginBetweenMiddleAndInnerRectangle = _marginBetweenOuterAndMiddleRectangle +
                (_middleCircleDiameter / 2 - _innerCircleDiameter / 2);

            _outerRectangle = new Rectangle(0, 0, _outerCircleDiameter, _outerCircleDiameter);

            _middleRectangle = new Rectangle(_marginBetweenOuterAndMiddleRectangle,
                _marginBetweenOuterAndMiddleRectangle, _middleCircleDiameter, _middleCircleDiameter);

            _innerRectangle = new Rectangle(_marginBetweenMiddleAndInnerRectangle,
                _marginBetweenMiddleAndInnerRectangle, _innerCircleDiameter, _innerCircleDiameter);

            _zoomInRectangle = new Rectangle(_marginForZoomRectangles,
                _outerCircleDiameter + _marginOuterToZoomRectangles, _zoomRectangleWidth, _zoomRectangleWidth);

            _zoomOutRectangle = new Rectangle(_marginForZoomRectangles + _zoomRectangleWidth,
                _outerCircleDiameter + _marginOuterToZoomRectangles, _zoomRectangleWidth, _zoomRectangleWidth);
        }

        /// <summary>
        /// Initializes the graphics brushes and pen with proper colors.
        /// It sets the _currentMouseLocation to NoneLocation as initialy the mouse is not on any region.
        /// </summary>
        private void InitializeGraphicsComponants() {
            _currentMouseLocation = MouseLocation.NoneRegion;

            //  Default color is used to fill the control.
            Color _defaultColor = Color.FromArgb(120, 128, 128, 128);

            //  Hover color is used to fill the region when mouses hover on it.
            Color _hoverColor = Color.FromArgb(150, 64, 64, 64);

            //  Pen width used to draw line of this width.
            const byte _penWidth = 2;

            _graphics = CreateGraphics();
            _graphics.SmoothingMode = SmoothingMode.AntiAlias;

            _whiteBrush = new SolidBrush(Color.White);
            _defaultBrush = new SolidBrush(_defaultColor);
            _hoverBrush = new SolidBrush(_hoverColor);

            _penToDrawLines = new Pen(_defaultBrush) {
                Width = _penWidth,
                Color = Color.White,
                StartCap = LineCap.Round,
                EndCap = LineCap.Round
            };
        }

        /// <summary>
        /// Create the Inner circular region.
        /// </summary>
        private void CreateInnerRegion() {
            _innerCircleRegion = new Region();
            _graphicsPathToSetRegins.Reset();
            _graphicsPathToSetRegins.AddEllipse(_innerRectangle);
            _innerCircleRegion.Intersect(_graphicsPathToSetRegins);
        }

        /// <summary>
        /// Create the ZoomOut rectangular region.
        /// </summary>
        private void CreateZoomOutRegion() {
            _zoomOutButtonRegion = new Region();
            _zoomOutButtonRegion.MakeEmpty();
            _zoomOutButtonRegion.Union(_zoomOutRectangle);
        }

        /// <summary>
        /// Create ZoomIn rectangular region.
        /// </summary>
        private void CreateZoomInRegion() {
            _zoomInButtonRegion = new Region();
            _zoomInButtonRegion.MakeEmpty();
            _zoomInButtonRegion.Union(_zoomInRectangle);
        }

        /// <summary>
        /// Create Right button region.
        /// </summary>
        private void CreateRightButtonRegion() {
            _rightButtonRegion = new Region();
            _graphicsPathToSetRegins.Reset();
            _graphicsPathToSetRegins.AddPie(_outerRectangle, 315, 90);
            _rightButtonRegion.Intersect(_graphicsPathToSetRegins);
            _rightButtonRegion.Exclude(_middleCircleRegion);
            _rightButtonRegion.Exclude(_innerCircleRegion);
        }

        /// <summary>
        /// Create Up Button region.
        /// </summary>
        private void CreateUpButtonRegion() {
            _upButtonRegion = new Region();
            _graphicsPathToSetRegins.Reset();
            _graphicsPathToSetRegins.AddPie(_outerRectangle, 225, 90);
            _upButtonRegion.Intersect(_graphicsPathToSetRegins);
            _upButtonRegion.Exclude(_middleCircleRegion);
            _upButtonRegion.Exclude(_innerCircleRegion);
        }

        /// <summary>
        /// Create Left button region.
        /// </summary>
        private void CreateLeftButtonRegion() {
            _leftButtonRegion = new Region();
            _graphicsPathToSetRegins.Reset();
            _graphicsPathToSetRegins.AddPie(_outerRectangle, 135, 90);
            _leftButtonRegion.Intersect(_graphicsPathToSetRegins);
            _leftButtonRegion.Exclude(_middleCircleRegion);
            _leftButtonRegion.Exclude(_innerCircleRegion);
        }

        /// <summary>
        /// Create Down button region.
        /// </summary>
        private void CreateDownButtonRegin() {
            _downButtonRegion = new Region();
            _graphicsPathToSetRegins.Reset();
            _graphicsPathToSetRegins.AddPie(_outerRectangle, 45, 90);
            _downButtonRegion.Intersect(_graphicsPathToSetRegins);
            _downButtonRegion.Exclude(_middleCircleRegion);
            _downButtonRegion.Exclude(_innerCircleRegion);
        }

        /// <summary>
        /// Create Middle Circular button region.
        /// </summary>
        private void CreateMiddleRegion() {
            _middleCircleRegion = new Region();
            _graphicsPathToSetRegins.Reset();
            _middleCircleRegion.MakeEmpty();
            _graphicsPathToSetRegins.AddEllipse(_middleRectangle);
            _graphicsPathToSetRegins.AddEllipse(_innerRectangle);
            _middleCircleRegion.Union(_graphicsPathToSetRegins);
        }

        /// <summary>
        /// Create outer Circular region.
        /// This region include Complete outer circle excluding the middle and the inner circular regions.
        /// </summary>
        private void CreateOuterRegion() {
            _outerCircleRegion = new Region();
            _graphicsPathToSetRegins.Reset();
            _outerCircleRegion.MakeEmpty();
            _graphicsPathToSetRegins.AddEllipse(_outerRectangle);
            _graphicsPathToSetRegins.AddEllipse(_middleRectangle);
            _outerCircleRegion.Union(_graphicsPathToSetRegins);
        }

        /// <summary>
        /// Creates all the region of the control.
        /// </summary>
        private void InitializeRegions() {
            CreateInnerRegion();
            CreateOuterRegion();
            CreateMiddleRegion();
            CreateDownButtonRegin();
            CreateLeftButtonRegion();
            CreateUpButtonRegion();
            CreateRightButtonRegion();
            CreateZoomInRegion();
            CreateZoomOutRegion();
        }

        /// <summary>
        /// When mouse is over the outer circle then according to the current position of the
        /// mouse the proper button is repainted with hover Color.
        /// </summary>
        /// <param name="location">Point of mouse location.</param>
        private void CheckButtonsInOuterRegion(Point location) {
            if (_leftButtonRegion.IsVisible(location)) {
                SetFocusOnOuterCircleButtons(_leftButtonRegion, _leftButtonAngle, MouseLocation.LeftButtonRegion);
            } else if (_upButtonRegion.IsVisible(location)) {
                SetFocusOnOuterCircleButtons(_upButtonRegion, _upButtonAngle, MouseLocation.UpButtonRegion);
            } else if (_rightButtonRegion.IsVisible(location)) {
                SetFocusOnOuterCircleButtons(_rightButtonRegion, _rightButtonAngle, MouseLocation.RightButtonRegion);
            } else if (_downButtonRegion.IsVisible(location)) {
                SetFocusOnOuterCircleButtons(_downButtonRegion, _downButtonAngle, MouseLocation.DownButtonRegion);
            }
        }

        /// <summary>
        /// Repaints the button on outer circle buttons i.e Up, Right, Down and Left with hover brush.
        /// </summary>
        /// <param name="region">Region to fill with hover color.</param>
        /// <param name="angle">Line Angle of the respective region.</param>
        /// <param name="location">MouseLocation of the region.</param>
        private void SetFocusOnOuterCircleButtons(Region region, List<Point> angle, MouseLocation location) {
            if (_previousMouseLocation == location)
                return;
            _graphics.FillRegion(_hoverBrush, region);
            _graphics.DrawLine(_penToDrawLines, angle[0], angle[1]);
            _graphics.DrawLine(_penToDrawLines, angle[2], angle[3]);

            _currentMouseLocation = location;
        }

        /// <summary>
        /// Repaints the Middle Circle button if the mouse moves over it.
        /// </summary>
        private void SetFocusOnMiddleCircleButton() {
            _currentMouseLocation = MouseLocation.MiddleCircleRegion;
            if (_previousMouseLocation != MouseLocation.MiddleCircleRegion) {
                _graphics.FillRegion(_hoverBrush, _middleCircleRegion);
            }
        }

        /// <summary>
        /// Repaints the Zoom In button if the mouse moves over it.
        /// </summary>
        private void SetFocusOnZoomInButton() {
            if (_previousMouseLocation == MouseLocation.ZoomInButtonRegion)
                return;
            _graphics.FillRegion(_hoverBrush, _zoomInButtonRegion);
            _graphics.DrawLines(_penToDrawLines, _zoomInVirticleLine.ToArray());
            _graphics.DrawLines(_penToDrawLines, _zoomInHorizontolLine.ToArray());
            _currentMouseLocation = MouseLocation.ZoomInButtonRegion;
        }

        /// <summary>
        /// Repaints the Left Zoom Out if the mouse moves over it.
        /// </summary>
        private void SetFoucsOnZoomOutButton() {
            if (_previousMouseLocation == MouseLocation.ZoomOutButtonRegion)
                return;
            _graphics.FillRegion(_hoverBrush, _zoomOutButtonRegion);
            _graphics.DrawLines(_penToDrawLines, _zoomOutLine.ToArray());
            _currentMouseLocation = MouseLocation.ZoomOutButtonRegion;
        }

        /// <summary>
        /// Repaints the button on outer circle i.e Up, Right, Down and Left with default brush.
        /// with the default color.
        /// </summary>
        /// <param name="region">Region to repaint with the default color.</param>
        /// <param name="angle">MouseLocation of the region.</param>
        private void ReleseFocusFromOuterCircleButtons(Region region, List<Point> angle) {
            Invalidate(region);
            _graphics.FillRegion(_defaultBrush, region);
            _graphics.DrawLine(_penToDrawLines, angle[0], angle[1]);
            _graphics.DrawLine(_penToDrawLines, angle[2], angle[3]);
            //          _toolTip.Hide(this);
        }

        /// <summary>
        /// Repaints the Middle button region with default color.
        /// </summary>
        private void ReleseFocusFromMidleCircleButton() {
            Invalidate(_middleCircleRegion);
            _graphics.FillRegion(_defaultBrush, _middleCircleRegion);
            //          _toolTip.Hide(this);
        }

        /// <summary>
        /// Repaints the Zoom In button region with default color.
        /// </summary>
        private void ReleseFocusFromZoomInButton() {
            Invalidate(_zoomInButtonRegion);
            _graphics.FillRegion(_defaultBrush, _zoomInButtonRegion);
            _graphics.DrawLines(_penToDrawLines, _zoomInHorizontolLine.ToArray());
            _graphics.DrawLines(_penToDrawLines, _zoomInVirticleLine.ToArray());
            //          _toolTip.Hide(this);
        }

        /// <summary>
        /// Repaints the Zoom Out button region with default color.
        /// </summary>
        private void ReleseFocusFromZoomOutButton() {
            Invalidate(_zoomOutButtonRegion);
            _graphics.FillRegion(_defaultBrush, _zoomOutButtonRegion);
            _graphics.DrawLines(_penToDrawLines, _zoomOutLine.ToArray());
            //          _toolTip.Hide(this);
        }

        /// <summary>
        /// Creates the complete control.
        /// </summary>
        /// <param name="g">An Instane of Graphics use to draw all the region</param>
        private void FillControl(Graphics g) {
            g.FillEllipse(_defaultBrush, _outerRectangle);
            g.FillRegion(_defaultBrush, _zoomInButtonRegion);
            g.FillRegion(_defaultBrush, _zoomOutButtonRegion);
            g.FillEllipse(_whiteBrush, _innerRectangle);
            DrawAllLines(g);
        }

        /// <summary>
        /// Draws all the lines.
        /// </summary>
        /// <param name="g"></param>
        private void DrawAllLines(Graphics g) {
            g.DrawLine(_penToDrawLines, _upButtonAngle[0], _upButtonAngle[1]);
            g.DrawLine(_penToDrawLines, _upButtonAngle[2], _upButtonAngle[3]);

            g.DrawLine(_penToDrawLines, _downButtonAngle[0], _downButtonAngle[1]);
            g.DrawLine(_penToDrawLines, _downButtonAngle[2], _downButtonAngle[3]);

            g.DrawLine(_penToDrawLines, _leftButtonAngle[0], _leftButtonAngle[1]);
            g.DrawLine(_penToDrawLines, _leftButtonAngle[2], _leftButtonAngle[3]);

            g.DrawLine(_penToDrawLines, _rightButtonAngle[0], _rightButtonAngle[1]);
            g.DrawLine(_penToDrawLines, _rightButtonAngle[2], _rightButtonAngle[3]);

            g.DrawLines(_penToDrawLines, _zoomInHorizontolLine.ToArray());
            g.DrawLines(_penToDrawLines, _zoomInVirticleLine.ToArray());
            g.DrawLines(_penToDrawLines, _zoomOutLine.ToArray());
        }

        /// <summary>
        /// Releses the focus from the region pointed to by previousMouseLocation.
        /// </summary>
        private void ReleseFocusFromPreviousRegion() {
            switch (_previousMouseLocation) {
                case MouseLocation.UpButtonRegion:
                    ReleseFocusFromOuterCircleButtons(_upButtonRegion, _upButtonAngle);
                    break;
                case MouseLocation.RightButtonRegion:
                    ReleseFocusFromOuterCircleButtons(_rightButtonRegion, _rightButtonAngle);
                    break;
                case MouseLocation.LeftButtonRegion:
                    ReleseFocusFromOuterCircleButtons(_leftButtonRegion, _leftButtonAngle);
                    break;
                case MouseLocation.DownButtonRegion:
                    ReleseFocusFromOuterCircleButtons(_downButtonRegion, _downButtonAngle);
                    break;
                case MouseLocation.ZoomOutButtonRegion:
                    ReleseFocusFromZoomOutButton();
                    break;
                case MouseLocation.ZoomInButtonRegion:
                    ReleseFocusFromZoomInButton();
                    break;
                case MouseLocation.MiddleCircleRegion:
                    ReleseFocusFromMidleCircleButton();
                    break;
            }
        }

        #endregion

        #region Events

        /// <summary>
        /// Initializes the graphics objects and paints the control.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PtzControlPaint(object sender, PaintEventArgs e) {
            e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
            FillControl(e.Graphics);
        }

        /// <summary>
        /// Fills the region on which the mouse is hovering with _hoverBrush
        /// and as per the mouse location the current and the previous mouse
        /// location is managed.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PtzControlMouseMove(object sender, MouseEventArgs e) {
            //  Soters the current region in the previous location as when mouse mouse
            //  in other location the current location is set to the new locaiton and
            //  the previous location is presearved in the _previousMouseLocation.
            _previousMouseLocation = _currentMouseLocation;

            if (_outerCircleRegion.IsVisible(e.Location)) {
                CheckButtonsInOuterRegion(e.Location);
            } else if (_middleCircleRegion.IsVisible(e.Location)) {
                SetFocusOnMiddleCircleButton();
            } else if (_zoomInButtonRegion.IsVisible(e.Location)) {
                SetFocusOnZoomInButton();
            } else if (_zoomOutButtonRegion.IsVisible(e.Location)) {
                SetFoucsOnZoomOutButton();
            } else if (_innerCircleRegion.IsVisible(e.Location)) {
                _currentMouseLocation = MouseLocation.InnerCircleRegion;
            } else {
                _currentMouseLocation = MouseLocation.NoneRegion;
            }

            //  The focus relese is only allowed if the mouse mouve over other region
            //  from the current mouse location.
            //  by this mechnism the repainting of the region on the mouse is on is
            //  prevented as so avoids the flickering of the control.
            if (_previousMouseLocation != _currentMouseLocation) {
                ReleseFocusFromPreviousRegion();
            }
        }

        /// <summary>
        /// Detects the mouse is clicked.
        /// Strings used in this fuctions are for temporary purpose actual code in inserted for click events
        /// in respective click condition and fucntionality.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PtzControlClick(object sender, EventArgs e) {
            string msg = null;
            switch (_currentMouseLocation) {
                case MouseLocation.MiddleCircleRegion:
                    msg = "Middle Circle Button Clicked.";
                    break;
                case MouseLocation.InnerCircleRegion:
                    msg = "Inner Circle Button Clicked.";
                    break;
                case MouseLocation.UpButtonRegion:
                    msg = "Up Button Clicked.";
                    break;
                case MouseLocation.RightButtonRegion:
                    msg = "Right Button Clicked.";
                    break;
                case MouseLocation.DownButtonRegion:
                    msg = "Down Button Clicked.";
                    break;
                case MouseLocation.LeftButtonRegion:
                    msg = "Left Button Clicked.";
                    break;
                case MouseLocation.ZoomOutButtonRegion:
                    msg = "Zoom Out Button Clicked.";
                    break;
                case MouseLocation.ZoomInButtonRegion:
                    msg = "Zoom In Button Clicked";
                    break;
                case MouseLocation.NoneRegion:
                    msg = "PtzControl is Clicked.";
                    break;
            }
            Console.WriteLine(msg);
        }

        /// <summary>
        /// Repaints the region using the refresh method which inturn invokes the Paint event.
        /// which recreate the control.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PtzControlMouseLeave(object sender, EventArgs e) {
            _currentMouseLocation = MouseLocation.NoneRegion;
            Refresh();
        }

        #endregion
    }
}

```
> -5 votes

---
Tags: c#, .net, antialiasing, opentk
---


# Question
Title: Is there a way to procedurally generate the history of a world?
I am somewhat intrigued by the diagram found here representing 1800 years of cultural history in an imaginary world some guy created.

This sort of thing would seem to have strong applications for game development, insofar as world design.

It looks like he did this diagram by hand. What I'm interested in is seeing if there is a way to create this sort of diagram programatically.

If you were tasked with generating diagrams in the style of the above from random values, how would you go about it? Are there any particular data structures or algorithms that you would consider?

# Answer
How accurate do you want to be? A good but complex choice would be simulating all that history:

1. Generate a random region list and adjacencies between these regions.
2. Generate random civilizations with characteristics such as population, belligerence, technology... and populate the regions.
3. Simulate as many years of history as you want, determining outcomes based on civilization characteristics.

E.g.: two adjacent belligerent civilizations have a higher probability of starting a war on each other, which leads to lower population over time. Merchant civilizations have higher resources, but are a great target for invasions. Highly populated ones will grow faster but also have more chances of hunger. Culturally-heterogeneous civs have a lower chance of internal wars (which could lead to breakups.) And so on... Outcomes would also modify the civilization characteristics: higher technology leads to better trading, stronger weapons, etc.

This allows for some procedural storytelling too: you can output not only a territory diagram, but also textual descriptions of history throught time. You can make this system as complex as you want.

---

**EDIT:** the challenge here is not a technical one, but adjusting the heuristics for realistic and interesting history generation. Take a closer look and think about the 3 aforementioned points... that's pretty much your technical explaination! Translate it to a loop (each iteration can represent as much time as you want, 1 year, half a year, 1 month...) and that's it. You'll have to work the inners (data structures, heuristics) and adapt it to your specific problem and needs. That's the hard part here and *nobody* can help you, since it's about imagination, trial and error.

There are no common data structures for this problem besides the ones you'll use for almost any problem: lists, queues, trees... and these will be tied for your specific implementation *(do I need a genealogic tree? a list of civilizations at war? a queue of tasks for each civ?)* Of course you need a list of civilizations too. The choices are obvious and pretty much common sense.

Simulation is a matter of chance/probability and you can make it a thousand different ways with random numbers. Think of any other game where simulation is involved like football managers, RPGs (after all, hitpoints/stats is just *combat simulation*), strategy games... It's just **characteristics** (so you'll need a way to store civilization characteristics and data) and random outcomes **statistically** based on them (so you'll have to randomly change the simulation state based on these characteristics.)

That's the essence of your algorithm: the hard to adjust heuristics: how to distribute characteristics at the beginning of the simulation for each civilization and how to statistically change the simulation state based on them.

**In short:** your algorithm is just a loop ranging the simulated time with any desired increment. Shorter increments lead to finer historic simulation, but will obviously take longer. Inside your loop there will be a bunch of heuristics like (roughly):

```
for each civilization
  if civ.isAtWar
    civ.population -= civ.population * 0.05;
    civ.wealth -= 1000.0;
    civ.belligerence += 1.0;
  if civ.population < 100
    civ.negotiatePeace()

```

After all this work (or during if you don't want to store the data) you must interpret all the simulation state into human-readable format like text, images or whatever you desire. This is trial and error too and very specific for your implementation.

**Specific to your question:** to generate a diagram like the one in your question you'll have to track world regions (top of the diagram, x axis, that's *point 1: generate region list* in my answer) and their civilizations (colors in the diagram, *point 2*) through time (y axis, the simulation loop in *point 3*.)

State machines are quite good at simulating broad topics (the code sample above is an approximation of a hard-coded state machine) - so you might start by implementing a simple state machine framework that is overall easy to tweak. Each civilisation would start off with one of these state machines and the simulation would run each state machine for each turn. Each state machine would need to be able to interact with other state machine: for example initiating a war would affect another civilisation's state machine, possibly with different outcomes based on their internal state - e.g. if they are in the 'famine' state they would likely want to negotiate peace, but a civilisation 'looking for trouble' would likely retaliate. Each state in the machine would have meaningful effects on the civilisation's metrics outlined above during each 'frame' (wealth, belligerence, populace, etc.). Most importantly you do not need to transition states on every frame - just when opportunity and/or random chance arises: this allows prolonged events (like war) to occur.
> 15 votes

# Answer
Yes, there is. Here's a dirt-simple history generator:

```
#!/usr/bin/env python
# to create a visualisation, run like this:
#    ./timeline.py --dot | dot -Tpng > filename.png
import sys
import random
from pprint import pprint
# Names is a newline separated list of nation names.
file = "names.txt"
names = open(file, "r").read().split("\n")
history = []
dot = False
if len(sys.argv) > 1 and sys.argv[1] == "--dot":
  dot = True

def wrap(str, wrap='"'):
  return wrap+str+wrap

def merge(states, names):
  number = random.randint(2,3)
  mergers = []
  if number < len(states):
    mergers = random.sample(states, number)
    new_name = random.choice(names)
    states = list(set(states).difference(set(mergers)))
    states.append(new_name)
    names.remove(new_name)
    if dot:
      for state in mergers:
        print '"%s" -> "%s"'%(state, new_name)
      print '{rank=same; %s }'%wrap(new_name)
    else:
      print "MERGE %s ==> '%s'"%( ", ".join(map(wrap,mergers)), new_name)
  return states, names

def split(states, names):
  number = random.randint(2,3)
  if number < len(names):
    splitter = random.choice(states)
    states.remove(splitter)
    new_states = random.sample(names, number)
    names = list(set(names).difference(set(new_states)))
    states = list(set(states).union(set(new_states)))
    if dot:
      for state in new_states:
        print '"%s" -> "%s"'%(splitter, state)
      print '{rank=same; %s }'%("; ".join(map(wrap, new_states)))
    else:
      print "SPLIT '%s' ==> %s"%(splitter, ", ".join(map(wrap,new_states)))
  return states, names

def revolt(states, names):
  old = random.choice(states)
  new = random.choice(names)
  names.remove(new)
  states.remove(old)
  states.append(new)
  if dot:
    print '"%s" -> "%s"'%(old, new)
    print '{rank=same; "%s"}'%new
  else:
    print "REVOLT '%s' ==> '%s'"%(old, new)
  return states, names

def conquest(states, names):
  if len(states) > 1:
    loser = random.choice(states)
    states.remove(loser)
    winner = random.choice(states)
    if dot:
      print '"%s" -> "%s" [label="conquered by"]'%(loser, winner)
    else:
      print "CONQUEST '%s' conquered '%s'"%(winner, loser)
  return states, names

#ignore empty names
names = [name for name in names if name] #yes, really.

origin = random.sample(names, random.randint(1,3))
names = list(set(names).difference(set(origin)))
history.append(origin) #random starting states

if dot:
  print "digraph g {"
  print "{rank=same; %s}"%("; ".join(map(wrap,origin)))
else:
  print("BEGIN %s"%(", ".join(map(wrap,history[0]))))

while names:
  func = random.choice([merge, split, revolt, conquest])
  states, names = func(history[-1], names)
  history.append(states)

if dot:
  print '{rank=same; %s}'%("; ".join(map(wrap,history[-1])))
  print "}"
else:
  print "END %s"%(", ".join(map(wrap,history[-1])))

```

Which produces output like this:

Adjust the heuristics to create different graphs.

The simplest way to do this would be to change the `func = random.choice([merge, split, revolt, conquest])` line to have more than one function of the same name. For example `func = random.choice([merge, split, revolt, conquest, merge, merge])` will lead to nations merging more often.
> 8 votes

---
Tags: architecture, algorithm
---


# Question
Title: Improving the efficiency of frustum culling
I've got some code which performs frustum culling. However, this defines the "frustum" way too broadly- when I have ~10 objects on screen, the code returns 42 objects to be rendered. I've tried taking "slices" through the frustum to attempt to increase the accuracy of the technique, but it doesn't seem to have made much impact. I also significantly reduced the far plane, so that the objects are barely at the edge. Here's my code (where `size` is the size in screen space- the resolution of the client area of the window I'm rendering into). Any suggestions?

```
    auto&& size = GetDimensions();
    D3DVIEWPORT9 vp = { 0, 0, size.x, size.y, 0, 1 };
    D3DCALL(device->SetViewport(&vp));
    static const int slices = 10;
    std::vector<Object*> result;
    for(int i = 0; i < slices; i++) {
        D3DXVECTOR3 WorldSpaceFrustumPoints[8] = {
            D3DXVECTOR3(0, size.y,      static_cast<float>(i) / slices),
            D3DXVECTOR3(size.x, 0,      static_cast<float>(i) / slices),
            D3DXVECTOR3(size.x, size.y, static_cast<float>(i) / slices),
            D3DXVECTOR3(0, 0,           static_cast<float>(i) / slices),
            D3DXVECTOR3(0, 0,           static_cast<float>(i + 1) / slices),
            D3DXVECTOR3(size.x, 0,      static_cast<float>(i + 1) / slices),
            D3DXVECTOR3(size.x, size.y, static_cast<float>(i + 1) / slices),
            D3DXVECTOR3(0, size.y,      static_cast<float>(i + 1) / slices)
        };

        D3DXMATRIXA16 Identity;
        D3DXMatrixIdentity(&Identity);
        D3DXVec3UnprojectArray(
            WorldSpaceFrustumPoints,
            sizeof(D3DXVECTOR3),
            WorldSpaceFrustumPoints,
            sizeof(D3DXVECTOR3),
            &vp,
            &Projection,
            &View,
            &Identity,
            8
        );
        Math::AABB Frustum;

        auto world_begin = std::begin(WorldSpaceFrustumPoints);
        auto world_end = std::end(WorldSpaceFrustumPoints);
        auto world_initial = WorldSpaceFrustumPoints[0];
        Frustum.BottomLeftClosest.x = std::accumulate(world_begin, world_end, world_initial, [](D3DXVECTOR3 lhs, D3DXVECTOR3 rhs) { return lhs.x < rhs.x ? lhs : rhs; }).x;
        Frustum.BottomLeftClosest.y = std::accumulate(world_begin, world_end, world_initial, [](D3DXVECTOR3 lhs, D3DXVECTOR3 rhs) { return lhs.y < rhs.y ? lhs : rhs; }).y;
        Frustum.BottomLeftClosest.z = std::accumulate(world_begin, world_end, world_initial, [](D3DXVECTOR3 lhs, D3DXVECTOR3 rhs) { return lhs.z < rhs.z ? lhs : rhs; }).z;
        Frustum.TopRightFurthest.x = std::accumulate(world_begin, world_end, world_initial, [](D3DXVECTOR3 lhs, D3DXVECTOR3 rhs) { return lhs.x > rhs.x ? lhs : rhs; }).x;
        Frustum.TopRightFurthest.y = std::accumulate(world_begin, world_end, world_initial, [](D3DXVECTOR3 lhs, D3DXVECTOR3 rhs) { return lhs.y > rhs.y ? lhs : rhs; }).y;
        Frustum.TopRightFurthest.z = std::accumulate(world_begin, world_end, world_initial, [](D3DXVECTOR3 lhs, D3DXVECTOR3 rhs) { return lhs.z > rhs.z ? lhs : rhs; }).z;
        auto slices_result = ObjectTree.collision(Frustum);
        result.insert(result.end(), slices_result.begin(), slices_result.end());
    }
    return result;

```

# Answer
You appear to be defining your frustum as a cuboid, when it's not that shape at all - it's more cone shaped - the near plane is much smaller than the far plane.

The standard way to test against the frustum is to test against all 6 frustum planes individually.

You can find some code and diagrams explaining it in more detail at http://www.chadvernon.com/blog/resources/directx9/frustum-culling/
> 5 votes

---
Tags: c++, directx
---


# Question
Title: How do I implement a score database in Android?
I making a 2D game for Android using OpenGL-ES technology. It is a space shooting game where the player shoots enemy ships.

I want to keep a track of score for the amount of enemy ships destroyed and a record of a local highscore. The score should be incremented whenever an enemy is destroyed. I also want a way of displaying both the current score and highscore on the game screen. I am not familiar with databases at all and I will appreciate a clear answer or a link to a good tutorial for my cause. Thanks.

# Answer
> 2 votes
Since it is local, your best bet would be to use the built in SQLite that is part of Android. Here is a link that I have used before and it explains how to use it pretty well.

http://www.vogella.de/articles/AndroidSQLite/article.html#overview\_sqlite

and also

http://www.androidhive.info/2011/11/android-sqlite-database-tutorial/

It can get fairly complex if you are new to it but once you get the main code down it will be pretty quick to save and get data

---
Tags: android, java, opengl-es, graphics-programming, databases
---


title: Where can I find a free SDK for C#?

text:
# Question
Title: Where can I find a free SDK for C#?
I need a free and recent SDK for use with C#. I will work first in 2D games with visual effects. Thanks for now. Can anyone help me?

# Answer
> 4 votes
Take your pick, all of these use C#. I recommend the first as I believe it to be the easiest one to get started with, especially for 2D graphics:

* Microsoft XNA \- Built on top of DirectX9. Very user friendly and game oriented.
* OpenTK \- An OpenGL C# wrapper.
* SlimDX \- A DirectX C# wrapper.
* SharpDX \- Another DirectX C# wrapper.

---
Tags: c#
---


# Question
Title: Are these non-standard applications of rendering practical in games?
I've recently got into 3D and I came up with a few different "tricky" rendering techniques. Unfortunately I don't have the time to work on this myself, but I'd like to know if these are known methods and if they can be used in practice.

## Hybrid rendering

Now I know that ray-tracing is still not fast enough for real-time rendering, at least on home computers. I also know that hybrid rendering (a combination of rasterization and ray-tracing) is a well known theory. However I had the following idea: one could separate a scene into "important" and "not important" objects. First you render the "not important" objects using traditional rasterization. In this pass you also render the "important" objects using a special shader that simply marks these parts on the image using a special color, or some stencil/depth buffer trickery. Then in the second pass you read back the results of the first pass and start ray tracing, but only from the pixels that were marked by the "important" object's shader. This would allow you to only ray-trace *exactly* what you need to. Could this be fast enough for real-time effects?

## Rendered physics

I'm specifically talking about bullet physics - intersection of a very small object (point/bullet) that travels across a straight line with other, relatively slow-moving, fairly constant objects. More specifically: hit detection. My idea is that you could render the scene from the point of view of the gun (or the bullet). Every object in the scene would draw a different color. You only need to render a 1x1 pixel window - the center of the screen (again, from the gun's point of view). Then you simply check that central pixel and the color tells you what you hit. This is pixel-perfect hit detection based on the *graphical* representation of objects, which is not common in games. Afaik traditional OpenGL "picking" is a similar method.

This could be extended in a few ways:

* For larger (non-bullet) objects you render a larger portion of the screen.
* If you put a special-colored plane in the middle of the scene (exactly where the bullet will be after the current frame) you get a method that works as the traditional slow-moving iterative physics test as well.
* You could simulate objects that the bullet can pass through (with decreased velocity) using alpha blending or some similar trick.

So are these techniques in use anywhere, and/or are they practical at all?

# Answer
> 6 votes
As far as I know, neither technique you described is used as presented in any modern game. The first technique has, if nothing else, some serious image quality concerns and the second (while similar to selection buffer picking) adds nothing to the table and suffers all the drawbacks of selection buffer picking.

It is difficult to say from these theoretical perspectives what the performance of these techniques would be and how they'd compare to alternatives. Much of it will depend on the complexity of the underlying scenes, the size of the desired render targets (as well as their bit depth), what other optimization can be made for a particular implementation, et cetera. I would be confident in saying that they'd probably be on-par with existing techniques -- certainly they won't be so much faster as to overwhelm their disadvantages. You're effectively trying to turn everything into an image processing problem and image processing is not all that fast, and generally has accuracy complexities.

I'll cover some of the major disadvantages for each proposal below:

---

**Hybrid rendering** \- what you are essentially describing here is a technique to reduce the cost of ray-tracing by reducing the amount of pixels you actually have to trace rays for. This is not dissimilar from simply reducing the resolution of the render surface, which can allow for ray-tracing computations to be done in real-time. So the technique is certainly feasible from that perspective.

However, it has some pretty serious drawbacks. First, you'd incur the readback cost for the render target to get it back on to the CPU (faster these days, but still less than ideal) and you'd have to iterate the entire render surface to look for pixels of the "special" colors anyway, and then perform a reverse transformation (so you'd probably want to readback the depth buffer as well) to find out where on the source "interesting" object the corresponding pixel was before you can start ray-tracing.

You could eliminate the readbacks by simply *not* rendering the important objects on the GPU, processing them only on the CPU using your raytracer into a separate buffer which is pre-filled with a transparency color. Then you can render that buffer over the GPU's framebuffer using an appropriate blend mode. While this would alleviate the readback issues, you'd still have what I think is the second (and larger) problem:

It probably won't look very good. You'd have a pretty big disparity in the visual fidelity of your important/non-important objects, plus you'd have lost most of the information you'd need to get some of the really cool things ray-tracing gives you, like local reflection for those non-important objects. Consequently this technique would probably only be useful for a highly stylized visual direction, and honestly there are probably better ways to achieve such a direction -- assuming it would even look good at all.

**Rendered physics** \- this is very similar to selection-buffer style picking, as has been noted. It also reminds me of hierarchical occlusion maps. The main difference is that you're concerning yourself with the rendering of only a single pixel (or very small set of pixels). You'd probably be best off doing this on the CPU, because the bandwidth overhead to set up and ship things to the GPU would probably be wasteful. It, again, is feasible, but has some drawbacks.

It's consumes a fair amount of resources for performing a single task -- detecting a "hit" -- that is useful only, really, to that task. Traditional methods of hit detection using geometrical computations rely on data that already exists for physics computations and are themselves reusable (for drawing tracers, or determining where and how sounds might play, et cetera). You're not really *gaining* anything by picking in this fashion.

The technique is pixel-perfect, sure, but that's only a real desirable advantage in 2D games. In 3D games, a pixel ends up being a relatively poor resolution unit of measure as objects get further from the camera. Also, once you move beyond a 1x1 pixel render surface you start having to include depth information and do math on the pixels in the render target (two colors are present, which object was closer? which object consumes more of the hitscan surface area? et cetera).

# Answer
> -1 votes
> Rendered physics

I believe this is a form of 'picking', and is commonly done.

---
Tags: 3d
---


# Question
Title: Creating smooth lighting transitions using tiles in HTML5/JavaScript game
I am trying to implement a lighting effect in an HTML5/JavaScript game using tile replacement. What I have now is kind of working, but the transitions do not look smooth/natural enough as the light source moves around. Here's where I am now:

1. Right now I have a background map that has a light/shadow spectrum PNG tilesheet applied to it - going from darkest tile to completely transparent. By default the darkest tile is drawn across the entire level on launch, covering all other layers etc.
2. I am using my predetermined tile sizes (40 x 40px) to calculate the position of each tile and store its x and y coordinates in an array.
3. I am then spawning a transparent 40 x 40px "grid block" entity at each position in the array
4. The engine I'm using (ImpactJS) then allows me to calculate the distance from my light source entity to every instance of this grid block entity.
5. I can then replace the tile underneath each of those grid block tiles with a tile of the appropriate transparency.

Currently I'm doing the calculation like this in each instance of the grid block entity that is spawned on the map:

```
var dist = this.distanceTo( ig.game.player );
var percentage = 100 * dist / 960;

if (percentage < 2) {
    // Spawns tile 64 of the shadow spectrum tilesheet at the specified position
    ig.game.backgroundMaps[2].setTile( this.pos.x, this.pos.y, 64 );
}
else if (percentage < 4) {
    ig.game.backgroundMaps[2].setTile( this.pos.x, this.pos.y, 63 );
}
else if (percentage < 6) {
    ig.game.backgroundMaps[2].setTile( this.pos.x, this.pos.y, 62 );
}
// etc...

```

The problem is that like I said, this type of calculation does not make the light source look very natural. Tile switching looks too sharp whereas ideally they would fade in and out smoothly using the spectrum tilesheet (I copied the tilesheet from another game that manages to do this, so I know it's not a problem with the tile shades. I'm just not sure how the other game is doing it). I'm thinking that perhaps my method of using percentages to switch out tiles could be replaced with a better/more dynamic proximity forumla of some sort that would allow for smoother transitions? Might anyone have any ideas for what I can do to improve the visuals here, or a better way of calculating proximity with the information I'm collecting about each tile?

(PS: I'm reposting this from Stack Overflow at someone's suggestion, sorry about the duplicate!)

# Answer
First of all, I'm sorry that I won't be able to help you with your specific platform, as I've never done this sort of work in HTML5. So I'll try to address this in a language agnostic way.

I don't think you'll be able to get smooth transitions if you're calculating light on a *tile per tile basis*. This is analogous to the differences between using flat shading, gouraud shading or phong shading:

What you're doing is similar to flat shading, i.e. you're assigning a different light **per tile** which results in the sharp transitions between tiles as demonstrated on the picture above.

In order to get better results you'll have to calculate your lights on a **per vertex** basis (i.e. gouraud). I don't know what are the capabilities of your engine, but the ideal case would be if each of your tiles was a quad and you had direct access to its vertices. Then you would be able to calculate the distance from the light for *each vertex* and store your shade color right inside the vertex. Finally, the rendering pipeline would automatically take care of interpolating the shades accross the tile's surfaces resulting in a smoother look (aka gouraud shading).

For even better results albeit a bit more expensive you could calculate the light on a **per pixel** (i.e. phong) basis inside the fragment shader. The basic approach works well if you have just a couple of lights to sample as seems to be the case from your example.

Finally, another alternative which might work very well is to render all of your lights (and your lights only) into a separate render target first, optionally blur the result, and blend it together with the rest of the scene at the end. Check this question for a few ideas on this.
> 5 votes

# Answer
You appear to be lighting with a linear attenuation (your light intensity is dropping off linearly). You may want to try using the inverse square law. Or a simple exponential fall off.

```
float maxLightDistance = 64;
float fallOff = 1.4f;
float intensity = Math.pow(distanceFromSource / maxLightDistance, fallOff);
int tileToUse = (int)intensity;
ig.game.backgroundMaps[2].setTile( this.pos.x, this.pos.y, tileToUse);

```

The above code also helps you get rid of the atrocious `if` `else if` thing you have going.

I use just a basic exponential fall off, and get results like this (I can post a better image later of a single light source, I just don't have one at the moment):

I should also mention that a program like Excel is great for things like this. You can test out formula changes pretty quickly and either graph them or use conditional rules for changing the color of a cell.
> 4 votes

---
Tags: javascript, lighting
---


# Question
Title: Clicking on clues and other objects in a 2D cluedo like game
I'm a java/android programmer, but I don't have any experience in game programming, I'm already reading proper books, like "Pro Android Games", but my concerns are more about the ideas behind game programming than the techniques themselves.

I'm working on a 2D game, something like Cluedo to let you understand the genre. I would like to know how should I act with the "scenes", for example, a room with a desk, TV, windows and a lamp. I need to make some items tappable and others not. Is it common to use one image (invisible to the user) with every different item a different color, then call the getColor() method on the image? Or use one image as background, and separate images for all the items? If the latter, how can I set the positioning? and should I use imageView or imageButton?

I'm sorry if those are really low quality questions, but as "outsider" ( I'm 23 and still finishing my university ) it's pretty hard learn alone.

# Answer
> 2 votes
I think you will find positioning the easier way to go. One background image then the item images on top of it. You can see where a user clicked and then test the item image dimensions to see if they clicked inside one of them and which one of them.

Hope this helps

---
Tags: 2d, android, java
---


# Question
Title: XNA 2D Board game - trouble with the cursor
I just have started making a simple 2D board game using XNA, but I got stuck at the movement of the cursor.

This is my problem:

I have a 10x10 table on with I should use a cursor to navigate. I simply made that table with the `spriteBatch.Draw()` function because I couldn't do it on another way.

So here is what I did with the cursor:

```
public override void LoadContent()
{
    ...
    mutato.Position = new Vector2(X, Y); //X=103, Y=107;
    mutato.Sebesseg = 45;
    ...
    mutato.Initialize(content.Load<Texture2D>("cursor"),mutato.Position,mutato.Sebesseg);
    ...
}

public override void HandleInput(InputState input)
{
    if (input == null)
        throw new ArgumentNullException("input");

    // Look up inputs for the active player profile.
    int playerIndex = (int)ControllingPlayer.Value;

    KeyboardState keyboardState = input.CurrentKeyboardStates[playerIndex];

    if (input.IsPauseGame(ControllingPlayer) || gamePadDisconnected)
    {
        ScreenManager.AddScreen(new PauseMenuScreen(), ControllingPlayer);
    }
    else
    {
        // Otherwise move the player position.
        if (keyboardState.IsKeyDown(Keys.Down))
        {
             Y = (int)mutato.Position.Y + mutato.Move;
        }
        if (keyboardState.IsKeyDown(Keys.Up))
        {
            Y = (int)mutato.Position.Y - mutato.Move;
        }
        if (keyboardState.IsKeyDown(Keys.Left))
        {
              X = (int)mutato.Position.X - mutato.Move;
        }
        if (keyboardState.IsKeyDown(Keys.Right))
        {
             X = (int)mutato.Position.X + mutato.Move;
        }
    }
}

public override void Draw(GameTime gameTime)
{
    mutato.Draw(spriteBatch);
}

```

Here's the cursor's (`mutato`) class:

```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace Battleship.Components
{
    class Cursor
    {
        public Texture2D Cursortexture;
        public Vector2 Position;
        public int Move;

        public void Initialize(Texture2D texture, Vector2 position,int move)
        {
            Cursortexture = texture;
            Position = position;
            Move = move;
        }

        public void Update()
        {
        }

        public void Draw(SpriteBatch spriteBatch)
        {
            spriteBatch.Draw(Cursortexture, Position, Color.White);
        }
    }
}

```

And here is a part of the `InputState` class where I think I should change something:

```
public bool IsNewKeyPress(Keys key, PlayerIndex? controllingPlayer,
                                       out PlayerIndex playerIndex)
{
     if (controllingPlayer.HasValue)
     {
           // Read input from the specified player.
           playerIndex = controllingPlayer.Value;

           int i = (int)playerIndex;

           return (CurrentKeyboardStates[i].IsKeyDown(key) &&
                   LastKeyboardStates[i].IsKeyUp(key));
     }
}

```

If I leave the movement operation like this it doesn't have any sense:

```
X = (int)mutato.Position.X - mutato.Move;

```

However if I modify it to this:

```
X = (int)mutato.Position.X--;

```

it moves smoothly. Instead of this I need to move the cursor by fields (45 pixels), but I don't have any idea how to manage it.

# Answer
> 2 votes
You can represent your board with fields as a 2D array of Rectangles. Each rectangle has a position on the screen.

Let's say your field looks like this:

```
Rectangle[,] field;

```

You would then index the field using the x and y coordinates:

```
Rectangle someField = field[x,y];

```

So far so good. Now the sprite you draw as your cursor can also be seen as a rectangle. So let's have it start at the lower right corner of your field. Note that we also store the indices of the fields.

```
int mouseIndexX = field.GetUpperBounds(0);
int mouseIndexY = field.GetUpperBounds(1);

Rectangle mouseRect = field[mouseIndexX, mouseIndexY ];

```

Now you have to update your mouse code to draw the mouse sprite at the place of mouseRect. The CursorTexture will completely overlap the field. You can use Rectangle.Inflate with negative numbers to draw a smaller cursor.

```
spriteBatch.Draw(CursorTexture, mouseRect, null, Color.White);

```

And now for movement, we want to hop the mouse cursor from field to field only if we detect a new keypress:

```
if(IsNewKeyPress(Keys.Left, ......)
{
    // This makes sure X stays between 0 and field.GetUpperBounds
    mouseIndexX = (mouseIndexX + field.GetUpperBounds(0) - 1) % field.GetUpperBounds(0);
    mouseRect = field[mouseIndexX, mouseIndexY ];
}

```

The same goes for Right, Up and Down.

I hope this helps. If you don't use a Rectangle\[,\] to store your fields on the board you must at least have some knowledge of their position and their width and height so you should be able to figure out the code to create the mouseRect.

---
Tags: xna, movement, puzzle, keyboard
---


title: Ideas for extending tic-tac-toe game?

text:
# Question
Title: Ideas for extending tic-tac-toe game?
I'm building a 3D tic-tac-toe game and this is what I've implemented so far:

* 3D renderer with texture mapping
* Playing against the computer
* Playing online (multiplayer)

Now I'm a little lost what I could add. Obviously, tic-tac-toe isn't that exciting or advanced, but I just miss something to salt it a little bit.

Therefore, could anyone please suggest some ideas that would be worth implementing?

Thanks!

# Answer
You could add more visual effects to the game to make it visually appealing (especially when a player wins. I personally don't like the classic "You won!" text, I prefer fireworks and fire all over the screen, but maybe that's just me)
> 4 votes

# Answer
Kind of a crazy second answer here ... you can always convert it into a full-fledged strategy game. Just turn tic-tac-toe pieces into, say, Orcs or something exotic, and start building it up from there ...

I know, it's weird, but you already have an established board with game mechanics. Start by adding pieces that modify the existing behavior (eg. enemy can't be placed diagonally adjacent to a certain type of unit, say) and build it from there.

You can slowly expand functionality, board-size, and rules for winning (eg. wiping out all enemy units).
> 10 votes

# Answer
Make it 3d. 3d Tic-Tac-Toe is played on three 3x3 grids. You can win on any single board, or across boards (eg. top-left square in every board; or top-left, center-middle, and bottom-right across the three boards.

Some win conditions:

```
x.. ... ...
.x. ... ...
..x ... ...

```

(Winning on a single board)

```
x.. x.. x..
... ... ...
... ... ...

```

(Same location across three levels)

```
x.. .x. ..x
... ... ...
... ... ...

```

(Same row across three levels)

```
x.. ... ...
... x.. ...
... ... x..

```

(Same column across three levels)

**Edit:** You could also make it a 4x4, connect-four style.
> 4 votes

# Answer
Some easy implementation that I find would extend the game is make a time mode. Each player has a second or two to make a move, the game continues if it's a tie, and maybe make the time less and less. So you will eventually get a winning player by the other player messing up.

And/Or make the previous moves invisible, the player would have to memorize the other player move, and if they select a square that has already been played they lose their turn. This would be great as most players would be focusing on offence (their own moves)
> 3 votes

# Answer
I've just gone through 20 pages of Google search sites to find a 4x4x4 online to play against the program I just wrote. Can't find what I want - just the same stuff over and over. So here's your NEW NEW NEW twist: First person to hit the same variant of the game from different 4 different sources in a row looses and has to go home.
> -2 votes

---
Tags: rendering
---


# Question
Title: Components in a client/server network game?
Behavior and logic are executed on the server. The clients are mostly for rendering, audio, and gathering input.

It looks as though most of the a components architecture benefits are only realized on the server.

Is it still beneficial to design the client with an component based architecture? Or is there a different approach that better fits a client.

# Answer
If you plan on running similar architectures, ie. c++ for both client and server instead of mixed mode, then there's a pretty good case for building objects on both sides from a common code base of components.

1) you can choose what component load is needed for client or server independently. eg server doesn't need to render, client doesn't need to AI. 2) proxies of shared components for your networking protocol become trivial. 3) actions can be done local on the client to avoid ping delays, but verified on the server with the exact same code. eg movement 4) you've already written the code, may as well use it twice.

Reasons against might be: 1) you're using an existing engine for the client. 2) different language on the server. 3) if you're heavily scripting then your choice of language might work better monolithic.
> 3 votes

---
Tags: networking, component-based, client-server
---


# Question
Title: Shader optimization - Cg/HLSL pseudo and via multiplication
HLSL/Cg do not allow texture fetching inside conditional blocks. To get around this I am first checking a variable and performing some computations, afterwards I set a float flag to `0.0` or `1.0`, depending on the computations. I'd like to trigger a texture fetch only if the flag is `1.0` or not `null`. I kind of hoped this would do the trick:

```
float4 TU0_atlas_colour=pseudoBool*tex2Dlod(TU0_texture, float4(tileCoord, 0, mipLevel));

```

I want to know if `pseudoBool` is `0`, will the texture fetch function still be called and produce overhead? I was hoping to prevent it from getting executed via this trick that usually works in plain C/C++.

# Answer
Firstly you can do texture fetching inside conditional blocks in HLSL. tex2Dlod() and tex2Dgrad() will work fine inside one. It's just tex2D() that won't compile, and you can work round that by computing ddx() and ddy() outside the conditional and using tex2Dgrad().

To reliably stop the texture fetch (or any other block of code) being executed in HLSL, use an `if` statement prefixed with the `[branch]` attribute. This requires shader model 3 or higher.

You can also of course also make two separate shaders and switch between them from the calling code, but that isn't as flexible. Where it's possible it will be quicker though.

Also note that unless the branch is skipping over significantly more lines of code than a single texture read you will probably lose performance and not gain it. If in doubt test with both `[branch]` and `[flatten]` and compare performance between the two. Without either attribute the compiler will guess at which option is best.
> 6 votes

---
Tags: shaders, hlsl, cg
---


title: Dirty 2D map rendering

text:
# Question
Title: Dirty 2D map rendering
I keep hearing people talk about "dirty rendering" when it comes to map rendering for HTML5. I've Googled and searched the GameDev about it but there isn't much about it.

* What exactly is it?
* How to implement it properly?

# Answer
This means that when the background is drawn, not all of it is redrawn every frame. **When something on the map moves, the area it used to occupy gets marked as dirty**. Then when drawing, you know you only need to redraw that portion of the background. This is beneficial because then you only need to redraw the areas that weren't shown before.

So this is really only beneficial when you don't have many things moving around, otherwise your spending more time figuring out what new areas to draw than if you just redrew the entire background. This isn't too common anymore as the platform is usually fast enough to redraw everything without issue. Since this is really just an optimization feature, I'd ignore it for now, and come back to it if you find that performance is lacking.
> 12 votes

# Answer
Rendering in most games takes place within a loop (the game loop) and in each iteration of the game loop the **entire** backbuffer is cleared (in this case your canvas) and redrawn from scratch.

The term *dirty rendering* is referring to a technique where instead of clearing the entire canvas every frame, you only clear it on demand (i.e. only **when** something changed in the scene) and possibly only a portion of it (i.e. only the portion **where** something changed).

This process of marking only a portion of your canvas to be redrawn is what is what *dirty* is referring to (i.e. *that portion of the canvas is dirty and needs to be redrawn but everything else is still clean and shouldn't be touched*).

I have no idea if there's some special way for you to implement this in HTML5, but I found this resource which might give you some ideas.
> 6 votes

---
Tags: javascript, html5, html-canvas
---


# Question
Title: Is there an easy and automatic way of converting a Windows XNA project into a Monotouch Monogame project?
I have just started with XNA development on Windows. But as I'm a fan of iOS I had to try porting my test code over to Monotouch on the Mac. I used these instructions: http://www.facepuncher.com/blogs/10parameters/?p=42 But this is so much (manual) work! And it really doesn't answer open topics like: why would I copy all the XNB files and in addition all the resources, like PNGs?

Is there maybe a tool that automatically converts a Windows XNA project into a Monotouch iOS project or at least creates the correct folder structure?

# Answer
> 1 votes
I don't believe there is a magical "Port it!" button that will do everything for you, however ExEn does a pretty good job of getting rid of most of the manual work, while maintaining most of your current code.

# Answer
> 0 votes
Although this video targets MonoDroid, it's still a good reference and can answer most of your questions: http://www.youtube.com/watch?v=hF0sm5KGPPM

---
Tags: xna, monotouch, monogame
---


# Question
Title: How to spawn a character at certain point and walk to a set point
I am making a game where I have a background image of a neighborhood. Each location has a different number of customers that are generated to walk on sidewalks. They all walk to a specific location (like a stand or cart that sells stuff), after they get to location I want them to interact with the cart. However, if another customer is already in a sale interaction then the others get in line in order of arrival. After the transaction the customers walk off screen. Any information on how I can do this and what game engine would be needed? Any one have any idea where I should go for this. I already have my game done up through Eclipse/Java without any game engine.

# Answer
> 1 votes
What you are looking for is a Queue, check the destination, and if there is already somebody there, add the person to the queue, and then query the queue to figure out where to stand (you can use vectors to figure out where exactly to stand in the line)

Best I could give you is C++ code, so see if this works...

```
function addPerson(int x, int y, Location placeToGo)
{
    new Person(x,y,placeToGo);
}

Person::Person(int newx, int newy, Location placeToGo)
{
    x = newx;
    y = newy;
    wantToGoTo = placeToGo;
    PathFind myPath = NULL;
    if(placeToGo.queue.isEmpty() == false)
    {
        Person inFrontOfMe = placeToGo.queue.queryEnd();
        placeToGo.queue.add(this);
        myPath = new PathFind(inFrontOfMe.location);
    }
    else
    {
        myPath = new PathFind(placeToGo);
    }
}

```

If anybody knows what to do better, please feel free to edit this!

# Answer
> 1 votes
Use the number of customers in line to offset the destination. For example, say the line is below the stand at `(200,200)`, customers are spaces 25 pixels, and there are three customers in line. The back of the line will be at `(200,200+(3*25))`, or `(200,275)`.

Use the distance formula to check and see if the customer is in range.

```
xdist = backOfLine.x-cust.x;
ydist = backOfLine.y-cust.y;
dist = Math.sqrt(xdist*xdist+ydist*ydist);

```

If the distance is small enough, then the customer is in range to "see" the booth. To actually move the customer, find the unit components of the distance, and then multiply by your desired speed.

```
uxdist = xdist/dist; //these are our unit components
uydist = ydist/dist; //with a hypotenuse of 1
uxdist *= speed;
uydist *= speed;

```

Then just move by uxdist and uydist each frame. This will get them to the line. Once distance is around zero, he reached the line and gets assigned a queue number and stops. When a customer in front is served, he moves up in the queue, walks to the spot designated for that queue, and stops. Let's say for example, he is third in line. A signal is sent that the line is moving, and so he moves up as second in line. His destination becomes `booth.y+(25*queueLocation)`. He walks until he reaches that destination, and then stops, and the system resets. It repeats this process until the signal is sent while the customer is first in line. This means he is done. He picks a random direction, and walks off.

---
Tags: android, java, sprites, path-finding
---


# Question
Title: Is there a standard way to store 3D meshes to easily communicate between libraries?
In a 3D game lots of different systems need to know about geometry data, however the only way they seem to be able to agree to on in representing it by an array of triangles.

Can anyone recommend a good geometry manipulation library that will allow me to easily integrate the drawing library(OpenGL), the physics engine(Bullet), Serialization(Several 3D file formats) and my own code(objective-c++). Focus on the a representation between the drawing library and the physics engine. Also if the library can triangulate a mesh definition that would be very helpful. My code can work around what exists already.

# Answer
There isn't really a standard format -- and there really shouldn't be, because you're asking about several widely different domains and applications of geometry data and *efficient* representations will differ for each.

That said, there are formats designed to facilitate content interchange. The most popular are Collada and FBX. This doesn't completely address your concerns though -- both formats are quite verbose and not actually well-suited to being used *directly* in memory, as a result. You'd probably want to condition them into some custom format your game can load most efficiently (the "array of triangles" you mentioned).

You generally want physics and render data to be different -- perhaps sourced from the same place, but there's no reason your physics meshes need to have colors and texture coordinates, for example. It's wasteful.
> 5 votes

# Answer
For a library I suggest you have a look at Assimp. It's a library for working with various mesh formats so you can just dump it in and get a full mesh importer with little in the way of work. It also allows you to load in a standardized format and output a custom one.

The problem is what format you store your meshes in will vary depending on your program and what features you need, what formats you are using internally. You are normally going to need some post-processing for things like converting filenames of images referenced by meshes. How are you going to link custom shaders and so on.

There are some standardized formats that you can use but they will tend to be over engineered for most realtime rendering and are more for use in the content creation pipeline. COLLADA is the main example (as the other post mentioned), it's found use from Sony with the PS3. Bullet Physics (and the Physics Abstraction Layer) apparently includes support for Collada. On the down side COLLADA is XML, so it requires parsing and needs to support a huge list of features making even a basic implementation quite a bit of work (for example it supports multiple coordinate systems, so if you want to support custom content you will have to take that into account, plain image textures have multiple levels of linages since the same format needs to support more advanced things like multiple textures and so on). With that said, in the past games often add support for importing the native formats of a 3d modelling program such as 3ds which wouldn't be too different so the overhead isn't that great. Although might be to much for mobile phones and some game console systems.

idGames such as the Doom 3 mesh format (MD5) is simply a plain text ASCII file. There are multiple files, one for geometry and another for animation. You could also have a separate one for physics as that will generally use lower polygon geometry.

Personally I would recommend using a binary format as your final mesh format. You can make a format that can be loaded into memory as basically a single block of memory and just requires some updating of pointers. The only potential problem is big endian vs little endian but just standardize on one and convert on the other.

Rather than using triangles it might be better to use an indexed vertex array of triangle strips for storage as it should save a bit of storage space (and ram when loaded into memory) but it does require some conversion to the format.
> 1 votes

---
Tags: asset-management
---


title: Multiplayer game over internet

text:
# Question
Title: Multiplayer game over internet
How to construct my multilayer mode for my Delphi game? For LAN I use UDP server/client. But for internet I think UDP is useless.

I have in mind something like:

1. The host create SQL database and store the game data.
2. The clients connect via TCP/IP and sent requests in that database to get current state of the game.

Or is there a better option for internet multiplayer?

# Answer
When it comes to making a multiplayer FPS, this is a pretty amazing resource: https://github.com/id-Software

That is the full source code to every one of id's games up through Doom 3.

There is no reason to go with a different implementation of how it works over a LAN vs over the internet. UDP is definitely the way to go, I don't know of any FPS that didn't use that protocol for it's network play. You can probably make TCP work, but ultimately UDP will allow you to better handle interruptions. Transacting through a database is going to introduce far more latency then will be acceptable in an action game, you need to have the server delivering updates directly to the clients.

For a lot more information in general, check out this collection of articles: http://gafferongames.com/networking-for-game-programmers/
> 9 votes

# Answer
UDP is okay, you have exactly the same problems as you would have on a LAN but with the bonus that you can do NAT Hole punching

TCP/IP is easier to use (no packet losses and everything comes in the expected order) so go with that if you think it is easier for you.

For the "how does it work", it is a correct start but you seems to have forgotten the "server" or some of its work namely to act as a buffer between the database and the client:

Client negotiates a login (server checks database for login, pass, playerID etc) Server loads up the new player from database to memory and sends That off to the client.

Every change will primarily affect the memory (I use a class Player that holds all the data of a character for example) and only rarely the server will save off the memory to the database (for example, the minimum required is when a player quits the game).

I use the same technique for items, they get checked out too by the server and 'saved' in the player class. Every time the item changes owner (I give you an apple) I reflect that instantly and then I save off the new state to the database, this way it is fast and secure and fast(I can send back information before even touching the database).

Another thing is of course the need to add another 'layer' for lag compensating. This doesn't need to be something extremely complicated but some data (like positions) should not be updated directly when the client gets information from the server but saved off in another variable and the client position can then use some sort of lag compensation like interpolation or dead reckoning

Good luck and as a side note, what's the game about?
> 2 votes

---
Tags: multiplayer, sql, delphi
---


# Question
Title: Modifying SAT Code To Obtain Penertration Vector
> **Possible Duplicate:**
> SAT, How Do I Find The Penetration Vector?

Hi how could I modify my SAT code and visual debug it to find the penetration vector of the two Entities so I can separate them.

Code: http://ideone.com/ef7A3

# Answer
There we go: http://www.codezealot.org/archives/55#sat-mtv
> 0 votes

---
Tags: c++, collision-detection, separating-axis-theorem
---


# Question
Title: Attributes and Behaviours in game object design
Recently I have read interesting slides about game object design written by Marcin Chady Theory and Practice of the Game Object Component Architecture. I have prototyped quick sample that utilize all Attributes\Behaviour idea with some sample data.

Now I have faced a little problem when I added a RenderingSystem to my prototype application. I have created an object with RenderBehaviour which listens for messages (OnMessage function) like MovedObject in order to mark them as invalid and in OnUpdate pass I am inserting a new renderable object to rederer queue. I have noticed that rendering updates should be the last thing made in single frame and this causes RenderBehaviour to depend on any other Behaviour that changes object position (i.ex. PhysicsSystem and PhysicsBehaviour).

I am not even sure if I am doing this the way it should be. Do you have any clues that might put me on the right track?

# Answer
As a rule of thumb there is no right or wrong way of doing the rendering, it all depends on your architecture and game.

Rendering is usually done outside of the component based system, despite this you will either reference your models from a renderable system where the updates on position will be done or the models will fetch the latest animations frame and position themselves before each draw.

Usually I simply duplicate data (position, skeleton, animation) and sync it when needed.
> 1 votes

---
Tags: architecture, component-based, behavior
---


# Question
Title: How to pause and resume a game in XNA using the same key?
I'm attempting to implement a really simple game state system, this is my first game - trying to make a Tetris clone. I'd consider myself a novice programmer at best. I've been testing it out by drawing different textures to the screen depending on the current state.

The 'Not Playing' state seems to work fine, I press Space and it changes to 'Playing', but when I press 'P' to pause or resume the game nothing happens. I tried checking current and previous keyboard states thinking it was happening to fast for me to see, but again nothing seemed to happen. If I change either the pause or resume, so they're both different, it works as intended.

I'm clearly missing something obvious, or completely lacking some know-how in regards to how update and/or the keyboard states work.

Here's what I have in my Update method at the moment:

```
    protected override void Update(GameTime gameTime)
    {
        KeyboardState CurrentKeyboardState = Keyboard.GetState();

        // Allows the game to exit
        if (CurrentKeyboardState.IsKeyDown(Keys.Escape))
            this.Exit();

        // TODO: Add your update logic here

        if (CurrentGameState == GameStates.NotPlaying)
        {
            if (CurrentKeyboardState.IsKeyDown(Keys.Space))
                CurrentGameState = GameStates.Playing;
        }

        if (CurrentGameState == GameStates.Playing)
        {
            if (CurrentKeyboardState.IsKeyDown(Keys.P))
                CurrentGameState = GameStates.Paused;
        }

        if (CurrentGameState == GameStates.Paused)
        {
            if (CurrentKeyboardState.IsKeyDown(Keys.P))
                CurrentGameState = GameStates.Playing;
        }

        base.Update(gameTime);
    }

```

# Answer
When playing and you hit the P key your if(CurrentGameState == GameStates.Playing) block is executed, changing the state to paused. Then the if(CurrentGameState == GameStates.Paused) block that follows also runs (because you just changed the state to paused above and the P key state hasn't changed), changing the game state back to playing. This is why you never experience the paused state.

At the very least, I'd make the code for each state exclusive within the update method, either by using a switch statement or the following:

```
if (CurrentGameState == GameStates.NotPlaying)
{
  // do stuff
}
else if (CurrentGameState == GameStates.Playing)
{
  // do stuff
}
else if (CurrentGameState == GameStates.Paused)
{
  // do stuff
}

```
> 4 votes

# Answer
As others have mentioned: Immediately after you set the gamestate to paused, it enters the following if-block and sets the state back to playing.

Sure, the simple fix is to include an `else` between the two states, but that will cause yet an other problem because `IsKeyDown` will return `true` in sequential updates, and since updates happen 40+ times per second, you will temporarily unpause for one frame, then pause the very next, and back and forth until the key is released.

The real solution is to detect the moment when the key is released (or pressed if you want to do it backwards). This can be done by storing the previous keyboard state, and comparing that to the current keyboard state. Something like:

```
if (LastKeyboardState.IsKeyDown(Keys.P) && !CurrentKeyboardState.IsKeyDown(Keys.P))
{
    // The 'P' key has just been released
    // This will only fire ONCE when the 'P' key is released
}

```

I would recommend making a wrapper class for the keyboard that handles this for you, but that is up to you.
> 3 votes

# Answer
Since there are many ways to skin a cat, Here's another:

```
bool gamePaused = false;
KeyboardState currentKB, previousKB;
protected override void Update(GameTime gameTime)
{
    previousKB = currentKB;
    currentKB = Keyboard.GetState();

    if (currentKB.IsKeyDown(Keys.Escape)) Exit();
    if (currentKB.IsKeyUp(Keys.P) && previousKB.IsKeyDown(Keys.P)) gamePaused = !gamePaused;

    if (gamePaused) return;

    //do update stuff here

    base.Update(gameTime);
}

```
> 2 votes

# Answer
There is a simple explanation here.
> 2 votes

# Answer
Look closely at the logic you have to pause and unpause:

```
if (CurrentGameState == GameStates.Playing)
{
    if (CurrentKeyboardState.IsKeyDown(Keys.P))
        CurrentGameState = GameStates.Paused;
}

if (CurrentGameState == GameStates.Paused)
{
    if (CurrentKeyboardState.IsKeyDown(Keys.P))
        CurrentGameState = GameStates.Playing;
}

```

If your game is playing and you have pressed `P` this frame, the first set `if` statements' conditions will be true. This will change `CurrentGameState` to `Paused` which will then make the second set of conditions true, chaning it back to `Playing`.

You'll probably just need to set up a series of conditionals that exclusively check the game state at the beginning of the frame. Either by using a `switch` statement instead of a series of `if`s or at least putting subsequent `if`s within `else` blocks:

```
if (CurrentGameState == GameStates.Playing)
{
    if (CurrentKeyboardState.IsKeyDown(Keys.P))
        CurrentGameState = GameStates.Paused;
}
else if (CurrentGameState == GameStates.Paused)
{
    if (CurrentKeyboardState.IsKeyDown(Keys.P))
        CurrentGameState = GameStates.Playing;
}

```
> 1 votes

---
Tags: xna, c#, xna-4.0, state, keyboard
---


title: How to create a mini-map in XNA 3?

text:
# Question
Title: How to create a mini-map in XNA 3?
simple map

The map i would like to create is like this one, but simpler , what i want to have is a geographical map indicate high /low and a point that show where am i and points indicate enemies

Thank you

# Answer
If you want that minimap for 3D game

1. If your environment is created from heightmap then use heightmap as minimap
2. Or just move camera up, to face down the ground, change projection to orthographic, and render it as depth map.

If you want to know just how to draw minimap, you can use SetData on Texture2D, to create texture and then pass it to spriteBatch.Draw
> 1 votes

---
Tags: xna, maps
---


# Question
Title: How can I create tiles that scale to multiple resolutions?
I am trying to create a multiplayer version of the popular Flash game N in Java. However, I'm not sure how to create a tileset that will scale up. Are the tiles for N pre-drawn or are they defined with mathamatical formulas in code?

I do see how they would scale up in Flash if they were pre-rendered. So if anyone has any ideas how I should go about creating the tileset, or how they are created in the game please let me know.

You can check out the game here.

# Answer
The creator of N actually put together a few tutorials explaining a little of the technology they used.

Tutorial A is about the collision detection used (separating axis theorem) but may be useful to you.

http://www.metanetsoftware.com/technique/tutorialA.html

Tutorial B explains more about the tile shapes used and from the looks of it, they are just a tileset. Some sample source code can be found at the bottom of the page.

http://www.metanetsoftware.com/technique/tutorialB.html
> 5 votes

# Answer
If you want to create tilesets that scale to many resolutions, you can look into creating your tiles from a vector graphics format (like SVG, which you did tag your original question with) rather than a raster format like PNG, et cetera.

You can, at load time (or possibly as a build step if you have a fixed set of known resolutions), load the vector graphics data, create geometry for it using your rendering API, and render out the tileset to a texture which then you can then use in your game as you would any normal tileset -- this way you save yourself the cost of re-rendering a bunch of tile geometry that likely never changes.

This *also* has the advantage of allowing you to use both pre-defined tiles in SVG and tiles that you design mathematically via some formula or script for procedurally generating them -- the script or formula just needs to produce the same style of point/triangle/whatever data that you're feeding to the tileset pre-renderer from SVG. Or, if you'd like to do just eschew pre-defined tiles entirely you can build them all procedurally.

As Byte56 commented, even though you are attempting to create a game in the style of another, you don't have to do things *exactly the same way* that game did, so long as it looks and functions similarly enough for your needs, any technique is appropriate.

There are a few questions on SO about rendering SVG (more if you hit up your favorite search engine).
> 1 votes

---
Tags: java, flash, tiles, svg
---


title: Problem with Assimp 3D model loader

text:
# Question
Title: Problem with Assimp 3D model loader
In my game I have model loading functions for Assimp model loading library. I can load the model and render it, but the model displays incorrectly. The models load in as if they were using a seperate projection matrix. I have looked over my code over and over again, but I probably keep on missing the obvious reason why this is happening.

Here is an image of my game:

It's simply a 6 sided cube, but it's off big time!

Here are my code snippets for rendering the cube to the screen:

```
void C_MediaLoader::display(void)
{
    float tmp;

    glTranslatef(0,0,0);
    // rotate it around the y axis
    glRotatef(angle,0.f,0.f,1.f);
    glColor4f(1,1,1,1);

    // scale the whole asset to fit into our view frustum
    tmp = scene_max.x-scene_min.x;
    tmp = aisgl_max(scene_max.y - scene_min.y,tmp);
    tmp = aisgl_max(scene_max.z - scene_min.z,tmp);
    tmp = (1.f / tmp);
    glScalef(tmp/5, tmp/5, tmp/5);

    // center the model
    //glTranslatef( -scene_center.x, -scene_center.y, -scene_center.z );
    // if the display list has not been made yet, create a new one and
    // fill it with scene contents
    if(scene_list == 0) {
        scene_list = glGenLists(1);
        glNewList(scene_list, GL_COMPILE);
            // now begin at the root node of the imported data and traverse
            // the scenegraph by multiplying subsequent local transforms
            // together on GL's matrix stack.
        recursive_render(scene, scene->mRootNode);
        glEndList();
    }
    glCallList(scene_list);
}

void C_MediaLoader::recursive_render (const struct aiScene *sc, const struct aiNode* nd)
{
    unsigned int i;
    unsigned int n = 0, t;
    struct aiMatrix4x4 m = nd->mTransformation;

    // update transform
    aiTransposeMatrix4(&m);
    glPushMatrix();
    glMultMatrixf((float*)&m);

    // draw all meshes assigned to this node
    for (; n < nd->mNumMeshes; ++n) {
        const struct aiMesh* mesh = scene->mMeshes[nd->mMeshes[n]];

        apply_material(sc->mMaterials[mesh->mMaterialIndex]);

        if(mesh->mNormals == NULL) {
            glDisable(GL_LIGHTING);
        } else {
            glEnable(GL_LIGHTING);
        }

        for (t = 0; t < mesh->mNumFaces; ++t) {
            const struct aiFace* face = &mesh->mFaces[t];
            GLenum face_mode;

            switch(face->mNumIndices) {
                case 1: face_mode = GL_POINTS; break;
                case 2: face_mode = GL_LINES; break;
                case 3: face_mode = GL_TRIANGLES; break;
                default: face_mode = GL_POLYGON; break;
            }

            glBegin(face_mode);

            for(i = 0; i < face->mNumIndices; i++) {
                int index = face->mIndices[i];

                if(mesh->mColors[0] != NULL)
                    glColor4fv((GLfloat*)&mesh->mColors[0][index]);

                if(mesh->mNormals != NULL)
                    glNormal3fv(&mesh->mNormals[index].x);

                glVertex3fv(&mesh->mVertices[index].x);
            }

            glEnd();
        }
    }
    // draw all children
    for (n = 0; n < nd->mNumChildren; ++n) {
        recursive_render(sc, nd->mChildren[n]);
    }
    glPopMatrix();
}

```

Sorry there is so much code to look through, but I really cannot find the problem, and I would love to have help.

# Answer
Turns out this was an issue with my perspective, I was able to solve my problem by setting the `gluPerspective` correctly:

```
void C_MediaLoader::display(void)
{
    glLoadIdentity();
    gluPerspective(45, 640/480,
        1.0, 1000.0);  /* Znear and Zfar */

    // remainder code is the same as before...
}

```

Thanks for everyone's help!
> 6 votes

---
Tags: c++, opengl, models, matrix, assimp
---