# Question
Title: Reference a single 2d Rectangle in an array
What I am attempting to do probably has a very simple answer but I can't make heads or tails of it no matter how hard I try. Provided I'm a newb.

What I am trying to do is after I create a grid of rectangles, when the cursor moves into the grid, it changes the color of the rectangle the cursor is currently in (or highlights it), then changes back when the cursor leaves. Here's what I've coded so far:

```
namespace MapGenie
{
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;

        Rectangle[,] gameGrid;

        MouseState currentMouseState;
        MouseState previousMouseState;

        bool colorChange = false;

        Color color;
        Color previousColor;

    protected override void Initialize()
    {
        //Creates the array
        gameGrid = new Rectangle[10, 10];

        color = Color.Black;

        base.Initialize();
    }

    protected override void LoadContent()
    {
        spriteBatch = new SpriteBatch(GraphicsDevice);
        this.IsMouseVisible = true;

        int Gridsize = 20;

        //Creates the grid
        for(int x = 0;x <10;x++)
            for (int y = 0; y < 10; y++)
            {
                gameGrid[x, y] = new Rectangle(x * Gridsize, y * Gridsize, Gridsize, Gridsize);
            }
    }

    protected override void Update(GameTime gameTime)
    {
        currentMouseState = Mouse.GetState();
        var mousePoint = new Point(currentMouseState.X, currentMouseState.Y);
        previousMouseState = currentMouseState;

        //Checks each rectangle in the gameGrid array to see if cursor is there?
        foreach (Rectangle grid in gameGrid)
        {
            if (grid.Contains(mousePoint))
            {
                previousColor = color;
                color = Color.Blue;
                colorChange = true;
            }
            if (colorChange == true)
                color = previousColor;
        }

        base.Update(gameTime);
    }

    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.CornflowerBlue);

        spriteBatch.Begin();

        var t = new Texture2D(GraphicsDevice, 1, 1);
        t.SetData(new[] { Color.White });

        foreach (Rectangle grid in gameGrid)
            spriteBatch.Draw(t, grid, color);

        spriteBatch.End();

        base.Draw(gameTime);
    }
}
}

```

Before I added the else statement (Which I am also aware does not work, but I am working to fix that after asking this), the entire grid would turn blue. So, I am not sure if it is the right question or not, but how do you get just the one the cursor is in to change color?

# Answer
Alright, from what both of you brought to the table, I was able to modify the code to (in what I believe) make it more simple (and removes the need for excess variables).

```
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;

        Rectangle[,] gameGrid;

        MouseState MS;

        Color color;
        Color currentColor;
    }
        protected override void Initialize()
        {
            gameGrid = new Rectangle[10, 10];

            color = Color.Black;
            currentColor = Color.Blue;

            base.Initialize();
        }
//---Code Snip---

        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);

            spriteBatch.Begin();

            var t = new Texture2D(GraphicsDevice, 1, 1);
            t.SetData(new[] { Color.White });

            foreach (Rectangle grid in gameGrid)
            {
                //Creates a new point and checks to see if it is within the grid, if so, draws the selected color
                //on the rectangle it is currently within.  If not, then draws the normal color.
                if (grid.Contains(new Point(MS.X, MS.Y)))
                    spriteBatch.Draw(t, grid, currentColor);
                else
                    spriteBatch.Draw(t, grid, color);
            }

            spriteBatch.End();

            base.Draw(gameTime);
        }

```

Thanks for getting my creative juices flowing.
> 1 votes

# Answer
To get started remove the previousColor and colorChanged code.

Use these member variables instead:

```
Color color; //color of unselected rects
Color selectedColor; //color of selected rect
Rectangle currentRect; //current selected rectangle

```

In your Initialize method:

```
  color = Color.Black;
  selectedColor = Color.Blue;

```

change your update method to this:

```
  //Checks each rectangle in the gameGrid array to see if cursor is there?
  foreach (Rectangle grid in gameGrid)
  {
    if (grid.Contains(mousePoint))
    {
      currentRect = grid;
    }
  }

```

and your draw code to this:

```
  foreach (Rectangle grid in gameGrid)
  {
    if (grid == currentRect)
    {
      spriteBatch.Draw(t, grid, selectedColor);
    }
    else
    {
      spriteBatch.Draw(t, grid, color);
    }
  }

```

For the complete code go here: http://pastebin.com/ecS7bq3m

EDIT (Functastic's Comment):

> Okay I don't know C# and this is (obviously) untested, but to convert pixel coordinates to map coordinates it's just:
>
> ```
> pixelCoord -= renderOffset;
> Point mapCoord = new Point( Math.Floor(pixelCoord.x / cellWidth), Math.Floor(pixelCoord.y / cellHeight) );
>
> ```
>
> Where 'renderOffset' denotes the offset with which the map is rendered (basically its top left corner, in pixels).
> 0 votes

---
Tags: xna-4.0, grid
---


# Question
Title: Random Calculations for Strategy Based Games in Java
I am making a console based strategy game like Genghis Khan: Legend of the White Wolf, although it is in console. How can I implement the Random Calculation in there? First off, the game goes like this, for example you have 34 Soldiers and the enemy has 45 Archers. Say you attack the Archers, normally it is not good to subtract the number of archers from the number of Soldiers. How can I implement a random difference using Random Method? I made it this way though:

```
int result = 1+r.nextInt(20);
        for (int j = 1; j <= 1; j++) {
            System.out.println(result);
        }
}
attacker -= result;

```

Is that okay? How about for the Defender? Should I make another random result for the damage to them? Is there an easy coding here rather than this lengthy one I did?

# Answer
i made this dice roller. it may be of interest.

```
import java.util.Random;

public class DiceRoller {
    DiceRoller(final int sides) {
        this(1, sides, 0, 0);
    }

    DiceRoller(final int dice, final int sides) {
        this(dice, sides, 0, 0);
    }

    DiceRoller(final int dice, final int sides, final int netAdjustment, final int sidesAdjustment) {
        this.sides = sides;
        this.dice = dice;
        this.netAdjustment = netAdjustment;
        this.sidesAdjustment = sidesAdjustment;
    }

    int roll() {
        int sum=netAdjustment+sidesAdjustment*dice;
        for(int i=0;i<dice;i++)
            sum+=random.nextInt(sides)+1;
        return sum;
    }

    final Random random = new Random();
    final int dice;
    final int sides;
    final int netAdjustment;
    final int sidesAdjustment;
}

```
> 0 votes

# Answer
You could take the real difference, and then add/subtract a random amount or percentage from it.

Pardon the pseudocode, I barely know Java:

```
int difference = Math.abs(enemy.units - player.units);

int thirtyPercentDifference = Math.round(difference * 0.3f);
int randomNegative = (random.nextInt(1) == 1) ? 1 : -1;
int randomDifference = difference + (random.nextInt(thirtyPercentDifference) * randomNegative);

```

What the above code would do is take that actual difference and then add +/- 0-30% to it. You should be able to use `randomDifference` as your final result. Let's plug in the numbers in your example as see what we get.

```
//int difference = Math.abs(enemy.units - player.units);
abs(enemy.units - player.units) = abs(45 - 34) = 9

//int thirtyPercentDifference = Math.round(difference * 0.3f);
9 * 0.3f = 2.7f, rounded to nearest int = 3

//int randomNegative = (random.nextInt(1) == 1) ? 1 : -1;
Then we randomly get a number either 0 or 1, let's just say it is zero. In that case our randomNegative is -1.

//int randomDifference = difference + (random.nextInt(thirtyPercentDifference) * randomNegative);
9 + ((random number between 0 and 3) * -1) = A number between 6 and 9.

```

The full range of what we could have gotten is 6 - 12 with the above algorithm. And if you wanted it even more random you could randomize the percentage used in place of the hard-coded `0.3f`.
> 1 votes

---
Tags: java
---


# Question
Title: Most efficient 3d depth sorting for isometric 3d in AS3?
I am not using the built in 3d MovieClips, and I am storing the 3d location my way.

I have read a few different articles on sorting depths, but most of them seem in efficient.

I had a really efficient way to do it in AS2, but it was really hacky, and I am guessing there are more efficient ways that do not rely on possibly unreliable hacks.

**What is the most efficient way to sort display depths using AS3 with Z depths I already have?**

# Answer
> 13 votes
If you're talking a tile-based isometric game, you have a fixed number of different depths that are bounded between some known nearest and farthest depth. In that case, it's a perfect candidate for a pigeonhole sort, which has the best possible algorithmic complexity.

Just make an array where each index corresponds to a depth, and each element is a collection of entities at that depth. Sorting is just (in pseudo-code):

```
sort(entities)
    buckets = new Array(MaxDistance)

    for index in buckets
        buckets[index] = new Array
    end

    // distribute to buckets
    for entity in entities
        distance = calculateDistance(entity)
        buckets[distance].add(entity)
    end

    // flatten
    result = new Array
    for bucket in buckets
        for entity in bucket
            result.add(entity)
        end
    end
end

```

And that's from a completely unsorted collection. An even better option is to simply persist the buckets and keep the entity's bucket location updated when its depth changes.

# Answer
> 3 votes
```
private function positionOrthographic():void
{
 for each (var entity:Entity in entities)
 {
 entity.spriteView.x = entity.body.position.x;
 entity.spriteView.y = entity.body.position.y + entity.body.positionZ;

 var sortedEntities:Array = entities.concat();
 sortedEntities.sort(sortDepths, Array.DESCENDING | Array.NUMERIC);

 var numEntities:int = entities.length;

 for (var i:int = 0; i < numEntities; i++)
 {
  world.setChildIndex(sortedEntities[i].spriteView, i);
 }

}

 private function sortDepths(entity1:Entity, entity2:Entity):int
 {
     if (entity1.layer < entity2.layer) return 1;
  if (entity1.layer > entity2.layer) return -1;
  if (entity1.body.position.y > entity2.body.position.y)return -1;
  if (entity1.body.position.y < entity2.body.position.y)return 1;
  return 0;
 }

```

Important to note I'm using the y axis as depth into the scene here (would normally be Z). This is so I can share code between top-down and side-on games. Splits sorting into a separate function. No idea how efficient it is, other than I've never noticed any slowdown from using it. Supports layers, so e.g. HUD and floating text things can always appear on top, backgrounds always below, etc.

# Answer
> 2 votes
Since in most isometric games most of the stuff is static it doesn't really matter how inefficient it is (within reason of course), as there's only a few objects you need to insert in the right place into an array that can be presorted already. If you are resorting everything everytime you draw, it would, but it means your algorithm is wrong to begin with.
Rule #1 in optimization: try if there's a more efficient solution on the macro level, before you optimize the micro level. (well, okay that's #2, #1 would be don't optimize before it's a *measured* bottleneck)

# Answer
> 1 votes
I don't know about efficiency, but this is the method I've been using for a long time:

Pretty simple method: Just add the screen-Y and the Z to get a 'distance', and then keep them in a list sorted by this property.

```
// In the 'update' of each entity
entity.distance = entity.y + entity.z;

```

Then use:

```
allEntities:Array;
// ...

allEntities.sortOn("distance", Array.NUMERIC);

```

Finally, rather than using Flash's rendering, I always blit things myself when I'm very concerned about depth sorting:

```
canvas:BitmapData = new BitmapData(stage.stageWidth, stage.stageHeight);
for each (var e:Entity in allEntities) {
    // draw each entity in sorted order
    canvas.draw(e, e.transform.matrix);
}

```

**Caveat**: This opens up the can of worms which is doing your own blitting. But as I mentioned, I've always found it a road worth going down when trying to deal with depths in a precise way.

# Answer
> 0 votes
You can check this blog post for a good solution for isometric z-sorting in AS3. It is derived from an approach exposed by Jobe Makar in his book ‘ActionScript for Multiplayer Games and Virtual Worlds’.

Here's the core sorting routine:

```
// Sort by cell index
_aSortableItems.sort( sortByPos );
private function sortByPos( a:SortableItem, b:SortableItem ):int {
   if ( (a.uiRow * INC.WORLD_COLS + a.uiCol) < (b.uiRow * INC.WORLD_COLS + b.uiCol) ) {
      return( 1 );
   }
   else return( -1 );
}

// Sort by row and column
for ( var i:uint = 0; i < _aSortableItems.length; i++ ) {
   objItem = _aSortableItems[i];
   if ( (objNewItem.uiCol <= objItem.uiEndCol) && (objNewItem.uiRow <= objItem.uiEndRow) ) {
      _aSortableItems.splice( i, 0, objNewItem );
      bAdded = true;
      break;
   }
}
if ( !bAdded ) _aSortableItems.push( objNewItem );

```

# Answer
> 0 votes
I think Ollie's post is helpful however you do need to see the code in context (which he provides). I too went down this road once before for the as3isolib.v1, however I finally gave up and opted for the naive sort. It's a performance hog.

If you are blitting, (which the as3isolib.v2 is) you can do quite a bit more in terms of splitting your objects up into more easily sortable pieces, reducing the multi-dimensional sorting path. as3isolib.v2 currently reduces all sortable items in a simple linear sort.

---
Tags: 3d, actionscript-3, isometric
---


# Question
Title: Why isn't my sprite being drawn in the correct position in XNA?
Sorry if this has been asked before, but I can't seem to find it here. I'm trying to make an asteroids clone in XNA. I took the Game State Management project and am making new classes for things like the player and placing them in the GameplayScreen class. For some reason my ship isn't being draw correctly.

GameplayScreen's Draw method:

```
 public override void Draw(GameTime gameTime)
    {
        ScreenManager.GraphicsDevice.Clear(ClearOptions.Target,
                                           Color.CornflowerBlue, 0, 0);

        SpriteBatch spriteBatch = ScreenManager.SpriteBatch;

        spriteBatch.Begin();
        //draw fps
        if(showFPS)
            spriteBatch.DrawString(framerateFont, "FPS: " + frameRate, new Vector2(15, 15), Color.White);

        player.Draw(spriteBatch);

        spriteBatch.End();

        // If the game is transitioning on or off, fade it out to black.
        if (TransitionPosition > 0 || pauseAlpha > 0)
        {
            float alpha = MathHelper.Lerp(1f - TransitionAlpha, 1f, pauseAlpha / 2);

            ScreenManager.FadeBackBufferToBlack(alpha);
        }
    }

```

And my ship's drawing code:

```
 public PlayerShip(Game game)
    {
        this.game = game;
        Viewport view = game.GraphicsDevice.Viewport;
        center = new Vector2(view.Width / 2, view.Height /2);
        sourceRectangle = new Rectangle();
        Reset(center);
    }

    public void Reset(Vector2 position)
    {
        this.position = position;
    }

    public void LoadContent()
    {
        ship = game.Content.Load<Texture2D>("ship");
        sourceRectangle = new Rectangle(0, 0, ship.Width,
            ship.Height);
        origin = new Vector2(ship.Width / 2, ship.Height);
    }

    public void Update(GameTime gameTime)
    {
        HandleInput();

    }

    //handles all keyboard input by user. rotates ship based on current rotation.
    private void HandleInput()
    {
        input = Keyboard.GetState();
        float x = position.X;
        float y = position.Y;
        Matrix m = Matrix.CreateRotationZ(rotation);

        if (input.IsKeyDown(Keys.Right))
            rotation += turnFactor;
        else if (input.IsKeyDown(Keys.Left))
            rotation -= turnFactor;
        else if (input.IsKeyDown(Keys.Up))
        {
            x += m.M12 * directionFactor;
            y -= m.M11 * directionFactor;
        }
        else if (input.IsKeyDown(Keys.Down))
        {
            x -= m.M12 * directionFactor;
            y += m.M11 * directionFactor;
        }
        position.X = x;
        position.Y = y;
        Console.WriteLine("Y: {0} ", y);
        Console.WriteLine("X: {0} ", x);
    }

    public void Draw(SpriteBatch sb)
    {
        Vector2 origin = new Vector2(ship.Width / 2, ship.Height);
        sb.Draw(ship, ship.Bounds, null, Color.White, rotation, origin, SpriteEffects.None, 0f);
    }

```

I hooked the project up to a console window and it seems that the X and Y positions are updating correctly code wise, but not visually. It seems to update where it is rotationally, but going up or down doesn't draw correctly.

Image of what it's doing https://i.stack.imgur.com/M0ajO.jpg

# Answer
The problem is that when you're using the following version of `SpriteBatch.Draw`:

```
public void Draw (
     Texture2D texture,
     Rectangle destinationRectangle,         // Destination rectangle on _screen_
     Nullable<Rectangle> sourceRectangle,
     Color color,
     float rotation,
     Vector2 origin,
     SpriteEffects effects,
     float layerDepth
)

```

And calling it with the following parameters:

```
// Wrong version
sb.Draw(ship, ship.Bounds, null, Color.White, rotation, origin, SpriteEffects.None, 0f);

```

The second parameter is expecting the `destinationRectangle` where the sprite should be drawn on screen but you're passing it the sprite's `ship.Bounds` which is simply a `Rectangle` like `(0, 0, ship.Width, ship.Height)`. That's why the sprite is always stuck to the corner of the screen.

This is a simple fix. Just change that line to:

```
// Correct version
sb.Draw(ship, position, null, Color.White, rotation, origin, 1f, SpriteEffects.None, 0f);

```

And if everything else is correct, it should work. That's just another version of `SpriteBatch.Draw` that goes like this:

```
public void Draw (
     Texture2D texture,
     Vector2 position,
     Nullable<Rectangle> sourceRectangle,
     Color color,
     float rotation,
     Vector2 origin,
     float scale,
     SpriteEffects effects,
     float layerDepth
)

```
> 2 votes

---
Tags: xna, c#, 2d, xna-4.0, spritebatch
---


title: Detecting a click on a tile

text:
# Question
Title: Detecting a click on a tile
I'm making a simple tile-map system in LWJGL, and I'm trying to figure out how to detect if the mouse is clicking inside of a tile. So far no matter where I click it's always the same tile that is shown.

Code:

```
int blockWidth = 100;
int blockHeight = 100;

List<Tile> tiles = new ArrayList<Tile>();

private void addTiles(){
    for(int i = 0; i < ((Display.getHeight() / blockHeight) * (Display.getWidth() / blockWidth)); i++)
        tiles.add(new Tile(10,10,blockWidth,blockHeight, i));
}

//...

if(Mouse.isButtonDown(0)){
            System.out.println("Mouse clicked at (" + Mouse.getX() + ", " + Mouse.getY() + ")");
            for(Tile tile : tiles){
                if(tile.inBounds(Mouse.getX(), Mouse.getY())){
                    tile.highlight();
                    System.out.println("Box clicked at (" + Mouse.getX() + ", " + Mouse.getY() + ").");
                    break;
                }
            }
}

```

the inBounds method:

```
public boolean inBounds(int x, int y){
    Rectangle bounds = new Rectangle();
    bounds.setBounds(x, y, width, height);
    if(bounds.intersects(x,y,1,1)){
        System.out.println("Tile " + num + " clicked. X/Y val is (" + this.x + "," + this.y + ")");
        return true;
    }else{
        return false;
    }

}

```

# Answer
The `x` and `y` you use here:

```
bounds.setBounds(x, y, width, height);

```

are the parameters `x`, `y` that are being passed into the method.

I am assuming that there is also an `x` and `y` in your Tile class. So you either need to rename the parameters or use `this.` in front of your variables.

```
public boolean inBounds(int x, int y){
    Rectangle bounds = new Rectangle();
    bounds.setBounds(this.x, this.y, width, height); // change here
    if(bounds.intersects(x,y,1,1)){
        System.out.println("Tile " + num + " clicked. X/Y val is (" + this.x + "," + this.y + ")");
        return true;
    }else{
        return false;
    }
}

```
> 3 votes

# Answer
You can avoid the potentially O(N\*M) containemt checks by simply calculating the tile's array index in O(1) time:

```
int pixelCoordToIndex(int x, int y)
{
    return ((y / tileHeight) * numTilesX) + (x / tileWidth);
}

```

Your code is then reduced to:

```
System.out.println("Tile " + pixelCoordToIndex(x, y) + " clicked. X/Y val is (" + x + "," + y + ")");

```

This decouples the performance of containment checks from the map's extents, saving millions of unnecessary checks on moderately large maps.
> 4 votes

---
Tags: collision-detection, tiles, input, lwjgl, mouse
---


# Question
Title: Are OpenGL Textures more memory efficient than Android Bitmaps?
I have a custom application that deals with many Bitmaps tiles that are 256x256 images (png,jpg). I'm currently using the `View` 2d canvas and bring in all images as RGB\_565. Although I'm generally happy with the applications performance, I have features I'd like to add that will require even more map tiles (Bitmaps). I've been thinking about using opengl ES 2.0 but am fairly new to it.

* Would opengl Textures be more memory efficient than keeping Bitmaps around? I assume you can load a Bitmap into a Texture and then dispose of the Bitmap
* Is it an acceptable practice in opengl to dynamically load many different Textures at runtime?
* Do you need to cache Textures or does the GPU handle that for you?

# Answer
* Would opengl Textures be more memory efficient than keeping Bitmaps around? I assume you can load a Bitmap into a Texture and then dispose of the Bitmap

Maybe they are and maybe they're not. The one thing that OpenGL *would* give you is the ability to use compressed texture formats (usually one of the DXTn formats). If you don't care about an alpha channel (or if 1 bit alpha is enough) this can get you one-eighth of the storage requirements; if you do it can be one-quarter. Whether or not this is a win compared to your current PNG/JPG approach depends a lot on whether you're keeping uncompressed variants of your image file in memory too.

There is dependency on your driver supporting compressed textures too; if it doesn't it's game over. There's also a (slight, but depends on the texture) quality tradeoff involved here.

Brief summary here: http://developer.motorola.com/docstools/library/understanding-texture-compression/

* Is it an acceptable practice in opengl to dynamically load many different Textures at runtime?

That can be slow and it's one of the tradeoffs of using a 3D API for this. On the one hand you get to store textures in high-performance local video memory; on the other hand it can take a little time to get them there. Generally what you'd do (in this case - if storage wasn't a problem you'd just load everything up-front) is create a small handful of textures at the required size (256x256 in your case) then use glTexSubImage2D (or glCompressedTexSubImage2D for compressed textures) to update the data; that way the only hit you incur is disk I/O and bandwidth; otherwise OpenGL will be throwing away the old texture and completely re-specifying a new one each time.

With compression available respecifying a texture can be as little as 5 lines of code - fopen, fread, fclose, glBindTexture and glCompressedTexSubImage2D.

Of course you would also store the source textures on disk in the native compressed format so that they can be uploaded directly instead of having to go through any intermediate conversion steps (that will also be a huge saving in terms of performance on your current PNG/JPG usage, which would require the image files to be decompressed and converted to 5-6-5 first).

* Do you need to cache Textures or does the GPU handle that for you?

The GPU will do that for you. Just create a texture object using glGenTextures to give it a unique name, then glBindTexture that name in order to use it, and the GPU will manage everything else.

So - compressed textures, update existing textures rather than respecify, and you should see some improvements in both memory usage and performance.
> 6 votes

---
Tags: android, opengl-es
---


# Question
Title: With flash/flex games talking to backend, is it pull only or can the game server push?
With flash based games (or flex), is it a pull or request/response system or is it possible for the game server (say java based) to actually push out to its remote flash clients?

# Answer
> 2 votes
There are basically two different ways you can achieve "pushed" updates through flash. Using the Socket class is the most straightforward and gives you the most control. At this level, you can either exchange XML data or just read and write raw bytes. The only real downside is that some people might have trouble connecting depending on things like routers, firewalls and security software. There's also a tricky little bit about setting up a security policy server, which isn't made immediately obvious in the Socket API documentation.

The second method is to use a long polling HTTP request via the URLStream class. Essentially the client will make a regular HTTP request that stays open, then the server will push data down that connection as it becomes available, and the URLStream class allows you to process the data as it comes in. If the client needs to send any updates to the server, it can do so through regular HTTP requests, the tricky part is to ensure that something in that request reliably identifies the client so the server can apply the update properly (and securely).

---
Tags: java, flash
---


title: RPG Maker (Issue) RGSS_RTP STANDARD

text:
# Question
Title: RPG Maker (Issue) RGSS_RTP STANDARD
the issue i am having is rpg maker is installed onto my computer as well a rgss-rtp standard and when i go to run RPG maker it says RGSS-RTP STANDARD not installed? how can i get it to run?

# Answer
> 1 votes
If you have the complete installer for RPG Maker XP (of course, with RTP for RGSS1), you can install it there directly. Open your rpg maker xp installer and you can see the 'Install RTP' button. Click that and you are ready to go.

---
Tags: rpg-maker-xp
---


# Question
Title: What are the basics of 3D triangle/quad sorting?
I am really curious how any 3D engine or even the GPU sorts triangles and quads. Are they basically taking a "center" point of a particular triangle/quad/poly and then calculate a distance from a camera point?

How is the depth of a polygon calculated if not using a point distance algorithm? Keep in mind I am a complete noob regarding 3D.

# Answer
> 5 votes
For the most part, depth sorting does not occur at the triangle level. For opaque geometry - which is the majority of geometry drawn in a typical 3D application - depth sorting is usually done per pixel, using a depth buffer, also called a Z-buffer. It's a block of video memory that keeps track of the depth (distance into the screen) of each drawn pixel. When a new triangle is drawn, the GPU calculates the depth of each pixel in the triangle and compares it to the depth already stored in the depth buffer for that pixel. Only if the new pixel is closer does it get drawn (and the depth buffer updated). Thus, geometry that's behind other geometry gets culled away.

This image-space approach allows for interpenetrating geometry to be rendered correctly, and is a lot easier to parallelize (i.e. to make it fast) than an approach based on depth sorting at the triangle level.

Now, for transparent geometry it's another story. For transparent stuff the depth buffer doesn't help you, because you can't just cull away a transparent pixel that's behind another transparent pixel. In this case, the usual approach is to sort objects or individual triangles from back to front on the CPU, then the GPU will draw them in the correct order. The GPU doesn't have any built-in sorting capabilities that help with this case. Sorting by the depth of each triangle's centroid is a common and generally reasonable approximation, although it does not work in all cases.

Lastly, there are advanced techniques known collectively as "order-independent transparency" that allow you to do per-pixel depth sorting on the GPU for transparent geometry. These techniques can generate a visually correct image in cases where triangle sorting fails, but are very expensive in performance and memory.

---
Tags: 3d, rendering
---


# Question
Title: Xna GS 4 Animation Sample bone transforms not copying correctly
I have a person model that is animated and a suitcase model that is not. The person can pick up the suitcase and it should move to the location of the hand bone of the person model. Unfortunately the suitcase doesn't follow the animation correctly. it moves with the hand's animation but its position is under the ground and way too far to the right. I haven't scaled any of the models myself. Thank you. The source code (forgive the rough prototype code):

```
        Matrix[] tran = new Matrix[man.model.Bones.Count];// The absolute transforms from the animation player
        man.model.CopyAbsoluteBoneTransformsTo(tran);

        Vector3 suitcasePos, suitcaseScale, tempSuitcasePos = new Vector3();// Place holders for the Matrix Decompose
        Quaternion suitcaseRot = new Quaternion();

        // The transformation of the right hand bone is decomposed
        tran[man.model.Bones["HPF_RightHand"].Index].Decompose(out suitcaseScale, out suitcaseRot, out tempSuitcasePos);

        suitcasePos = new Vector3();
        suitcasePos.X = tempSuitcasePos.Z;// The axes are inverted for some reason
        suitcasePos.Y = -tempSuitcasePos.Y;
        suitcasePos.Z = -tempSuitcasePos.X;

        suitcase.Position = man.Position + suitcasePos;// The actual Suitcase properties
        suitcase.Rotation = man.Rotation + new Vector3(suitcaseRot.X, suitcaseRot.Y, suitcaseRot.Z);

```

I am also copying the bone transforms from the animation player in the Person class like so:

```
        // The transformations from the AnimationPlayer
        Matrix[] skinTrans = new Matrix[model.Bones.Count];
        skinTrans = player.GetBoneTransforms();

        // copy each transformation to its corresponding bone
        for (int i = 0; i < skinTrans.Length; i++)
        {
            model.Bones[i].Transform = skinTrans[i];
        }

```

EDIT:

Unfortunately I can't add screenshots, as this specific project has been lost to time. I still want to know why it didn't work, though.

# Answer
My initial guess was that CopyAbsoluteBoneTransforms gave you the bone's position in world coordinates instead of model coordinates, but that would only be true if you moved the model by modifying the transform of the root bone. (Not entirely sure how animation is done in XNA)

Something else to note is that you're taking the XYZ components of a quaternion and using them in a vector3 (that I'm assuming is a euler angle), which doesn't work as you would expect.
> 0 votes

---
Tags: xna, c#, 3d, xna-4.0, animation
---


title: expand section of a texture 2D (zoom)

text:
# Question
Title: expand section of a texture 2D (zoom)
I have a texture2d loaded and wish at a certain moment to make a sort of zoom on the texture2d.

As you can see in the image i would like to expand my red square to the resolution of the black square. The aspect ratio is the same.

**update**

if it isn't clear, the question is how can i make that zoom?

# Answer
> 0 votes
In your draw method you have a destination rectangle and source rectangle, use them.

Source is related to your texture, it would be the red box.

Destination is related to your screen.

# Answer
> 2 votes
That can be done with transforms (like OpenGL does for example) to your viewport coordinates. It's just 2D geometry math.

Zoom is essentially a division. A 200x200 viewport with 2x zoom is actually 100x100 size in your texture (which will be expanded to fill the 200x200 viewport, effectively zooming.) After that, you just have to apply a translation to offset your zoomed area, which is a simple sum.

If you use the same zoom for both X and Y coordinates, you'll keep the aspect ratio the same. Here's some pseudocode for zooming into a full-screen texture (hence the `windowX`.)

```
backgroundX = windowX/zoom + translationX;
backgroundY = windowY/zoom + translationY;

```

Bear in mind you need some kind of interpolation (graphic cards can do it for you) because 1 pixel without zoom will be split into two half-pixels with 2x zoom (1px/2 = 0.5px size each fragment.) If you use nearest neighbor for interpolation, the zoomed image will be pixelated (which may be the effect you intend.)

I always implemented this myself on shaders. Here is a section of a shader of mine that zooms a texture applied to a full-screen quad, in case it helps:

```
uniform ivec2 resolution; // board size (for normalization)
uniform ivec3 camera;     // xy = offset, z = zoom

vec2 p = (gl_FragCoord.xy/resolution - vec2(0.5))/camera.z + camera.xy/(float)resolution;

```

Now `p` holds my texture coordinate (in \[0..1\] range, that's why I need the texture resolution) for the fragment at `gl_FragCoord` in screen. If you're not drawing a full-screen quad, you have to replace `gl_FragCoord` with your texture coordinate (passed as a uniform or with `glTexCoord` in fixed-pipeline OpenGL.)

I substract 0.5 from the fragment coordinate to center the zoom direction on screen (otherwise you would zoom into the bottom-left corner.) You don't need this, since you could also add `resolution/2` to your camera offset in your application, but I prefer using the center of the screen as the origin (for convenience.)

---
Tags: xna, xna-4.0
---


# Question
Title: How do MMO servers communicate with players who are behind a NAT?
I'm now planning to develop a real-time mmo in the future using udp as the transmission protocol since it has lesser overheads than tcp... I understand that between the client and the server, they have to do 2 basic things, the client needs to send server updates such as character positions..movements..hitting a monster..etc, and the server needs to update all the clients connected to render the changes on their screen...

For the client updating the server, I'll most probably do it by sending fast UDP packets to the server, but however for the server to update client, the server will send UDP packets to client containing the updates, however what if a client is behind a NAT? How do the server "push" udp packets to clients connected to a NAT-based network?

I plan to write the server in Java, I've also read about NAT hole-punching with various techniques like STUN..TURN..ICE.. however I can't seem to find a good framework/solution for it..

I also wonder how MMOs today like Maple Story..WOW..League of Legends implemented it..

# Answer
> 13 votes
A static MMO server (that is, one which is not located behind a NAT device itself) can simply send packets to users who are behind a NAT device exactly the same way that (for example) web sites send packets to them -- just ignore the possibility of a NAT device and send replies to the IP+port that's visible on incoming packets from the users; NAT devices rewrite packets that pass through them so that two-way communication with servers is possible that way.

As an MMO server (like any other kind of publicly available internet server), you don't have to think about NAT at all.

# Answer
> 2 votes
There's no guarantee that a firewall (whether NATing or not) will let UDP packets through at all, so your client and server should be prepared to communicate over TCP if necessary. Typically, the client will create a TCP connection to the server, and thereafter both will talk back and forth over that connection.

For setups where *no* direct connections are permitted through the firewall, you may want to also support tunneling the TCP connection through a SOCKS proxy. In particular, it may be a good idea to query the system default proxy settings and use them if a direct connection fails.

It's perfectly feasible to use the same message format for both UDP and TCP. There are some features that you'll only need for one protocol or the other; you can either have two variants of your message format, one for each protocol, or just include all the necessary features in both:

* UDP includes the packet length in the header; with TCP, you need to have some way to tell where one message ends and the next begins. (Of course, this may be useful with UDP too, if you want to be able to pack multiple messages into one packet.)
* TCP guarantees sequential transmission; UDP packets may be lost or arrive out of order, so you need sequence numbers of some kind (and probably some retransmission mechanism). Of course, TCP connections may break for various reasons, in which case knowing where to restart after reconnection can be useful.

To minimize the additional latency when communicating over TCP, it may be useful to disable Nagle's algorithm using the `TCP_NODELAY` flag. Instead, you may want to implement your own transmission buffering, collecting several small messages into one packet whenever possible (which is a good idea with UDP too).

*Edit: Rewrote the second paragraph per comments below.*

---
Tags: java, networking, mmo, udp
---


# Question
Title: (Why) Should I choose Unity 3 or Cocos2d (or something third) for my app?
My colleague and me made an HTML 5 iPad game ( http://braille.gandzo.com/ ) and we would like to upgrade it, and our framweork is not enoguh, for what we want. Some of the things we would change are: graphics update, animations/"effects", multi-player, achievements and so on. The game would stay 2d. Now, as far as I understand, both Unity and Cocos would be good for this task, with Unity having the advantage of being multi-platform.

What I want to know is are there unknown qualites/"flaws" to these two programs which would influence my decision (maybe even by choosing something else). Examples that come to mind are "Unity is too complicated/has too much unneeded options/hoops because it's made with 3d in mind" or "Cocos is significantly more suited for 2d games".

# Answer
> 1 votes
I think your examples pretty much answer it.

I (being an experienced Unity user) would use Unity (this is not my advice to you). The people who prefer unity over corona for 2d are generally experienced unity users. Take that into consideration. Unity, as you have heard, is a platform designed for 3d. There are a lot of features specific to 3d, e.g. if you want physics for a 2d game you need to lock the x rotation axis and lock the z translation axis.

Unity fortunately has a ton of extensions that make it great for 2d, so us experienced unity users, or users who plan on using more than just the 2d aspects, should choose unity given a 2d game to develop.

To sum it up, if you don't plan on using the 3d aspects of unity, go with corona. It's built for the task and doesn't have an extra layer of complexity for features you don't need. If you do plan on doing 3d and don't mind a slightly larger learning curve so you only have to learn one environment, go with unity.

---
Tags: unity, multiplayer, cocos2d-iphone, html5, cocos2d
---


# Question
Title: Can you embed a Unity3d mobile project into an existing native mobile app?
I am creating an application for both Android and iPhone that will have a few mini games in it. I would like to create the non game section in native Android and iPhone. My question is, is it possible to have a native app that will incorporate the Unity mini game I am creating all inside one apk and ios project?

# Answer
That's been asked a ton of times at http://answers.unity3d.com

Where there is a demand there is usually a supply

The Native Toolkit plugin from prime31 http://prime31.com/unity/docs/#nativeToolkitDoc

An excerpt from their product description:

> The NativeToolkit Plugin is your bridge for communicating between Unity and iOS. It is designed to make displaying view controllers as simple as possible. A single call to activateUIWithController will load the specified view controller and it will search for iPad specific nib files to load as well. This allows you to easily create menus, pause screens, inventory screens or any other UI your game needs via drag and drop in Interface Builder.
> 4 votes

---
Tags: android, iphone, unity, ios
---


# Question
Title: What is a convincing Berserker enemy AI finite state machine for a Roguelike
I'm looking for a way to create a convincing Berserker enemy in a Roguelike I've been creating for some time. You may assume a game like NetHack for this when considering what kinds of actions can be taken and text messages that can be alerted.

I ask this for two reasons:

1. I've been trying to solve this problem for over a year and have failed. Examples to follow.
2. I see a general lack of examples on this SE that show what a mapping of an entity's states, in total, looks like. It would be helpful to the community to have such an example.

**What I need:**

When I say Berserker I mean an enemy that can swing into a blind rage and attack other entities that it is in conflict with with violence and bloodlust. Not simply switching to attacking targets randomly, as is done in many RPGs. To this end, feel free to assume the addition of any status effects or buffs you wish. Just make sure you detail the pertinent information for those states.

A berserk entity needs to express his rage in a way that isn't simply a status change with some strength increases. This is a very shallow solution to the problem. The entity doesn't end up feeling like a Berserker at all.

**What I've Tried:**

I've tried 3 different ideas over the last year. And none of them satisfy. A solution to the problem could be all new, or a 'fix' for one of these. I am mainly including them to get the juices flowing.

1. The first thing I tried was a simple Berserk state that increased the strength of the entity, randomized its target (from list of enemies), had him shout obscenities, so on. Once in this state, the enemy would remain in it until death.
2. The next thing I attempted was really a modification of the above. The enemy felt very flat, and there was no way to calm him or knock him out of his rage which seemed unrealistic. I added the ability to calm (with a spell and other effects) and also added a condition that would return the enemy to a normal state, from which he could transition to others such as fleeing. This created more depth, but made the Berserker state seem even more shallow and less destructive.
3. From here I scrapped it all and aimed for something more emergent. Essentially a buff that the enemy could cast on itself based on a transition state. Once cast, this would change the enemies behavior (for targeting) and increase their damage while randomly issuing insults from the enemy. Then, he could enter any other states and stay enraged. So he might flee, but still taunt. He might heal, but still be enraged and deal lots of damage. This is better, but the underlying issue still remains. He doesn't really seem berserked, just pissed. Mainly because you typically encounter the enemy alone, and not with other enemies the berserker doesn't like, so the randomization aspect is down played.

How else can I make the guy seem Berserked, and not just pissed/foul-mouthed?

---

I realize this is a borderline list question. So I impose these requirements: It must be a very detailed complete answer that shows all the states and conditions for transitioning. And it must be more than a guess. You should test this in your own roguelike, or it should otherwise be obvious why this is a probable 'best' solution at getting the idea of Berserk status across.

I also won't take offense if this is closed. I realized it dances the edge.

# Answer
> 7 votes
## Berserker-psychology

* He is pissed/aggressive. (Therefore, he needs a **reason** and a **target** to be pissed.)
* When he's pissed, he gets more dangerous (Also, if he isn't pissed anymore, he's back to normal.)

## Trigger - The reason he goes berserk

* He gets insulted
* He gets hurt (or more interestingly, he gets hurt a certain critical amount)

## Effect

* He gets stronger
* He gets faster
* He gets more health
* He starts shouting insults
* He starts **following** the person who dealt the damage

## Player-Defense

* Player can kill the berserk
* Environmental damage kills the berserk (lead him into a trap)
* Player can **slow** the berserk
* Other NPC/Player/Enemy hurts the berserk critical -\> berserk follows now the new target
* Over time the berserk calms down (if he does not get hit again)

## How this would play

The player meets the enemy. *a)* Player deals multiple-times small damage (the enemy fights back, but does not go berserk), *b)* Player deals big damage, the enemy loses a lot of health, but goes berserk. The player must now flee. While fleeing he can *a)* deal further damage, *b)* slow the berserk. If *a)* the enemy stays berserk or dies. If *b)* the enemy calms down (slowing him, does not deal critical damage). When he's calmed down, you can attack him again critically. Maybe he dies now :-)

**Note:** If you don't agree with my statement, that the berserk does attack the target that hurt him, you could change that so, that the berserk attacks the **nearest** character. This would be interesting, if he got attacked from a distance. (For a sword-fighter it would be the same.)

# Answer
> 7 votes
I suppose the answer depends on just what you think of as a "berserker".

The historical Berserkers were shock troops who focused their attention on engaging and slaying their opponents with little regard to anything else, including their own safety or that of others on their side. Different sources disagree on just how indiscriminate they were in their killing: some describe them as willfully slaying anyone and everyone around them, while others merely describe them as fearless warriors. Here's a fairly middle-of-the-road quote from the *Ynglinga saga*, via Wikipedia:

> "His (Odin's) men rushed forwards without armour, were as mad as dogs or wolves, bit their shields, and were strong as bears or wild oxen, and killed people at a blow, but neither fire nor iron told upon them. This was called *Berserkergang*."

So, my conception of a berserker would be something like this:

* Completely **fearless**, probably oblivious to pain. Willing to engage enemies of any level.
* Highly **focused** on fighting, to the exclusion of anything else going on around them.
* **Not *completely* indiscriminate** in killing, but probably willing to attack friendlies (perhaps without even noticing) if they get in his way. Might also attack friendlies if there are no enemies around, but should still prefer enemy targets if there are any.
* Disdainful of subtle or cautious tactics: **charge the enemy** and **hack them to bits** is the name of the game here. Prefers mêlée combat, but might use sufficiently powerful ranged weapons (like guns, preferably on full auto and fired while running towards the enemy) if available.
* Unnaturally **strong** and **tough** — maybe not Superman-level tough, but they should definitely get *some* attack and defense bonuses, and perhaps a slight speed boost.

So, how would I translate these traits into game AI behavior? Well, here are a few ideas:

* This should be kind of a no-brainer, but a berserker *should never run away*, even if he's down to a single hit point and bleeding. Just turn that code off. Ditto for any other "defensive" tactics.
* Prioritize tactical options in this order: 1. Attack. 2. Move towards target. 3. Everything else. In particular, berserkers should not stop to pick up items if there are enemies in sight, even if the items are, say, better weapons than they currently have. (However, switching from bare hands to an already held mêlée weapon *might* be reasonably prioritized even over attacking.)
* If both attacking *and* chasing after the target can ever be valid tactical options at the same time, consider giving your berserkers the ability to do both at the same time (an attack "in passing"), even if your creatures can't normally do that (possibly with an accuracy penalty to compensate). That way, your berserkers won't have to slow down their charge to take attacks of opportunity.
* Target selection: I'd suggest just picking the nearest visible enemy (regardless of level) and having the berserker chase him, at least unless another enemy comes significantly closer (say, half the distance to current target). Keep chasing the target even if you temporarily lose line of sight, as long as the target doesn't get too far away. This should give some feeling of single-mindedness. Once the target is in mêlée range, attack him.
* Pathfinding: If there are friendlies between the berserker and his target, consider letting him just attack them and hack his way through. It's up to you how eager to do that you'll make him — at least he should do it if there's no other path to the target, but you might even consider making him ignore friendlies entirely in pathfinding.
* The above probably works best if you also make the (non-berserker) friendlies try to flee out of the square that the berserker will be next moving into (and maybe the next square or two in his path, too). Of course, if there's too much crowding, they might not be able to flee in time...
* If there are no enemy targets around, consider letting the berserker attack nearby (adjacent, or maybe one or two squares away) friendlies instead. Of course, said friendlies should try to flee. On any turn where the berserker has no enemy target and doesn't make an attack, make him move around randomly and give him a random per-turn chance of calming down and reverting to normal state.
* Weapon choice: As I noted above, real berserkers were big on mêlée combat. Don't use ranged weapons, unless they're particularly common and powerful in your game (e.g. guns in a modern setting). If you do let your berserkers use ranged or area-effect weapons, let them fire them *while* chasing their target (see "in passing" attacks above). Obviously, collateral damage should be ignored (by the berserker — making *other* enemies scramble to stay out of the line between you and a berserker with a gun would be a very nice touch).
* And, of course, the berserker should have appropriate attack, defense and speed buffs. They should probably also be immune to any fatigue or fear effects. If blinded or confused, just have them make random attacks in the hope of hitting something.

You noted that you want berserking to be a state that can sometimes be entered by normal enemies (with a propensity to it). Thus, you'll need to decide what will trigger it. IRL, traditionally described triggers include combat, heavy exertion and stress. Some potential triggers for a game might include:

* seeing enemies,
* attacking,
* being attacked,
* being seriously wounded,
* seeing others in combat,
* seeing others get killed, or
* seeing traces of combat (bloodstains, dead bodies).

None of those should probably IMO be an automatic trigger; rather, there should be a random chance for each such event to trigger the berserk state, with the odds perhaps varying based on individual propensity and the severity of the event. Also, combinations of several triggers might make berserking more likely: for example, the presence of a visible enemy might be a precondition for any of the other events to trigger berserking, while low hit points might increase the odds for the other triggers.

Also, you might consider introducing a "rage meter" instead of just a simple on/off berserk state. For example, a newly triggered berserk might start at, say, rage = 1, with attacking and being attacked increasing the meter, and not seeing any enemies decreasing it. At low rage, a berserk would simply be fearless and buffed, but would generally avoid attacking friendlies, while increased rage would increase the buffs but also make the berserker's attacks less and less discriminate. When the rage meter goes down to zero, the berserker calms down and goes back to normal.

As for the obscene shouts, I'd mostly get rid of them: I see a berserker as being too focused on attacking to bother with any silly taunts. I suppose you could have him shout something when the berserk state is triggered, and maybe roar or make a simple war cry when closing to mêlée range, but that would seem enough for me.

---

Edit: After re-reading what I wrote above, I guess that real gist of what I'm trying to say is this: don't focus too much on the berserker AI itself. In the end, it's likely to turn out pretty simple, probably much simpler than your normal enemy AI. Instead, **focus on how the other enemies will behave** when they see a berserker nearby — that's where the really interesting dynamics will arise.

---
Tags: ai, roguelikes, fsm
---


# Question
Title: NxWheelShape Tilt with Vision(Havok) Engine and PhysX 2.8.x
A vehicle I am working on has front wheels that can tilt(lean) left and right as well as turn left and right. The turning was pretty easy, but there seems to be nothing on how to set a WheelShapes tilt and I'm wondering if anyone here has experience with this and can point me in the right direction?

I see there is a SetRotationMatrix() but it also says that it bypasses physics module and will lead to unpredictable results so I was looking into a Vision Engine function that allows me to set a Rotation Delta by passing in a yaw, pitch and roll but that doesn't affect the WheelShape itself, only the 3D Wheel Model and I don't think thats what i want anyway.

I only mention the Vision Engine in case anyone is familiar with both but the PhysX stuff is mostly untouched by the engine. Any suggestions?

# Answer
So I got it figured out. Turns out that some of the other coders had to multiply a couple matrices to get the wheels to stand up in the first place so the work I was doing was working, just resetting the wheels back to flat and then tilting. I just multiplied my new matrix with the original and voila =-)
> 1 votes

---
Tags: c++, physics, physx
---


title: Quake d_draw.s versus d_draw16.s

text:
# Question
Title: Quake d_draw.s versus d_draw16.s
I decided to write my first Quake source port, but I'm a bit confused.

There are 2 rasterization code files: d\_draw.s and d\_draw16.s.

The first is, as John Carmack said, horizontal 8-bpp span-drawing code. The second is the same, but with 16-pixel subdivision.

Which is more preferable for full-color 320x200 source port?

Do they both feature non-power-of-2 texture distortion?

GL code is not an option, because the target system doesn't feature 3D API.

# Answer
> 1 votes
According to here

> For maximum speed, perspective correction is performed only every 16 pixels. This is normally fine, but it is possible to see texture ripples in surfaces that are viewed at sharp angles. For more precise texture mapping, set the console variable d\_subdiv16 to 0. Doing this will result in somewhat slower performance, however, and the difference in visual quality will not normally be noticeable.

So I'm assuming for maximum visual quality you want d\_draw and not d\_draw16.

---
Tags: software-rendering
---


title: Transfer my UDK 2 project to UDK 3?

text:
# Question
Title: Transfer my UDK 2 project to UDK 3?
Is it possible to export my UDK 2 project to UDK 3 ? What kinds of things aren't transferable?

# Answer
> 5 votes
The answer to your question is given over here

http://udn.epicgames.com/Three/DevelopmentKitFAQ.html

> Q: Can previous Unreal Engine 3 projects be imported?
>
> A: Yes, users can open Unreal Engine 3 packages made with previous UDK releases in more recent UDK Betas with iOS support.

So if you have made some projects in UDK 2 it will work in udk 3 with some changes to the project file in the kismet and basically some code changes.

# Answer
> 2 votes
True, the Unreal Development Kit only exists for Unreal Engine 3.

All of them support kismet.

You can load almost all content from an older version of UDK to a newer version with the exception of certain deprecated content such as the pre-Scaleform ui solution. Other things such as the old Terrain system were replaced with newer systems (Landscape) and thus need to be converted with in-engine utilities.

Also certain other things, like material editor nodes, may have become obsolete but are still in the engine, so you may need to go through and swap out old nodes (specifically certain depth nodes) for the newer ones.

Also Shader Model 2 support was deprecated so you could see some issues with left over fallback materials.

The bigger the leap forward the more work may need to be done to upgrade.

---
Tags: udk
---


# Question
Title: OpenGL & SDL textures... game shuts down
I'm going to create a game in C++ with SDL & openGL but adding textures won't work. the code is in some different classes. here's the main file

```
//==============================================================================
#include "ZOMBOX.h"

//==============================================================================
ZOMBOX::ZOMBOX() {

    isRunning = true;
}

//------------------------------------------------------------------------------
int ZOMBOX::Execute() {
    Init();

    bool mainloop = false;

    SDL_Event event;

    //Create an texture
    unsigned int Ball_texture = 0;
    //Load the image into the texture using the function
    Ball_texture = loadTexture("Smile.png");
    std::cout << "OpenGL is running\n";

    while(isRunning) {
        while(SDL_PollEvent(&event)) {
            Event(&event);
        }
        if(mainloop == false){
            std::cout << "Main loop has started\n";
            mainloop = true;
        }
        Logic();
        Render();
        }

    //Clear();

    SDL_Quit();

    return 0;
}

//==============================================================================
int main(int argc, char* argv[]) {
    ZOMBOX theApp;

    return theApp.Execute();
}

//==============================================================================

```

Ok, now the rendering;

//============================================================================== #include "ZOMBOX.h"

```
//==============================================================================
void ZOMBOX::Render() {

    extern float ballX;
    extern float ballY;
    extern float ballWH;
    extern int vellX;
    extern int vellY;
    extern unsigned int Ball_texture;
    Ball_texture = loadTexture("Smile.png");

    //RENDERING to the screen
    //Enable textures when we are going to blend an texture
    glClear(GL_COLOR_BUFFER_BIT);
    glPushMatrix(); //Start rendering phase
    glOrtho(0,800,600,0,-1,1); //Set the matrix
    glColor4ub(0,0,0,255); //White color
    glEnable(GL_TEXTURE_2D);
    glBindTexture(GL_TEXTURE_2D, Ball_texture);

    glBegin(GL_QUADS); //Start drawing the pad
    //We set the corners of the texture using glTexCoord2d
    glTexCoord2d(0,0); glVertex2f(ballX,ballY); //Upper-left corner
    glTexCoord2d(1,0); glVertex2f(ballX+ballWH,ballY); //Upper-right corner
    glTexCoord2d(1,1); glVertex2f(ballX+ballWH,ballY+ballWH); //Down-right corner
    glTexCoord2d(0,1); glVertex2f(ballX,ballY+ballWH); //Down-left corner
    glEnd(); //End drawing
    //Disable textures when we are done using them
    glDisable(GL_TEXTURE_2D);

    glPopMatrix(); //End rendering phase
    SDL_GL_SwapBuffers();

    SDL_Delay(1);
}

//==============================================================================

```

i know the comments are not right but i understand it...

now the texture; here's the fault i think

```
//==============================================================================
#include "ZOMBOX.h"
//==============================================================================
//Function for loading an image into an texture
GLuint ZOMBOX::loadTexture( const std::string &fileName )
{
    SDL_Surface* image = IMG_Load( fileName.c_str() );

    SDL_DisplayFormatAlpha(image);

    unsigned object(0);

    glGenTextures(1, &object);

    glBindTexture(GL_TEXTURE_2D, object);

    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image->w, image->h, 0, GL_RGBA, GL_UNSIGNED_BYTE, image->pixels);

    //Free surface
    SDL_FreeSurface(image);

return object;
}
//==============================================================================

```

I use variables you cant see but that's no problem thus they are not nessecary(i think).

Sorry for my bad English im just a dutch highschool student.

# Answer
> 5 votes
In addition to the comments above, your conversion of an SDL\_Surface to an OpenGL texture is incorrect. You're missing two important issues:

1. Ensure that the image dimensions are a power of two. (64, 128, 256, 512, etc)
2. Ensure that your SDL\_Surface is in the pixel format that you're telling OpenGL that it's using (GL\_RGBA, GL\_UNSIGNED\_BYTE, in your case). This one could easily be the cause of crashes, if your image isn't actually stored as a 32-bit image.
3. I also tell OpenGL to automatically generate mipmaps. No need to do that part, but I've included it here for completeness.

Here's the code I use for doing this texture setup. Basic idea: create a new SDL\_Surface of the correct size and pixel format, copy the original surface into it, create the OpenGL texture from the correctly-formatted copy, and then clean up.

Source code:

```
static int power_of_two(int input)
{
    int value = 1;

    while ( value < input ) {
        value <<= 1;
    }
    return value;
}

int ConvertSDLSurfaceToTexture( SDL_Surface *source )
{
    SDL_Rect    area;
    uint32_t saved_flags;
    uint8_t  saved_alpha;

    SDL_SetAlpha(source, 0, SDL_ALPHA_OPAQUE);

    m_width = (float)source->w;
    m_height = (float)source->h;

    int w = power_of_two(source->w);
    int h = power_of_two(source->h);

    SDL_Surface *image = SDL_CreateRGBSurface(
                                          SDL_SWSURFACE,
                                          w, h,
                                          32,
#if SDL_BYTEORDER == SDL_LIL_ENDIAN /* OpenGL RGBA masks */
                                          0x000000FF,
                                          0x0000FF00,
                                          0x00FF0000,
                                          0xFF000000
#else
                                          0xFF000000,
                                          0x00FF0000,
                                          0x0000FF00,
                                          0x000000FF
#endif
                                          );
    assert(image != NULL);

    saved_flags = source->flags&(SDL_SRCALPHA|SDL_RLEACCELOK);
    saved_alpha = source->format->alpha;
    if ( (saved_flags & SDL_SRCALPHA) == SDL_SRCALPHA ) {
        SDL_SetAlpha(source, 0, 0);
    }

    /* Copy the surface into the GL texture image */
    area.x = 0;
    area.y = 0;
    area.w = source->w;
    area.h = source->h;
    SDL_BlitSurface(source, &area, image, &area);

    /* Restore the alpha blending attributes */
    if ( (saved_flags & SDL_SRCALPHA) == SDL_SRCALPHA ) {
        SDL_SetAlpha(source, saved_flags, saved_alpha);
    }

    /* Create an OpenGL texture for the image */
    GLuint t;
    glGenTextures(1, &t);

    glBindTexture(GL_TEXTURE_2D, m_texture);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE);
    glTexImage2D(GL_TEXTURE_2D,
                 0,
                 GL_RGBA,
                 w, h,
                 0,
                 GL_RGBA,
                 GL_UNSIGNED_INT_8_8_8_8_REV,
                 image->pixels);

    SDL_FreeSurface(image); /* done with this copy of the input surface */

    return t;
}

```

# Answer
> 2 votes
Are there any errors when loading the image? Try to verify that the image loads properly.

After this:

```
SDL_Surface* image = IMG_Load( fileName.c_str() );

```

Add this:

```
if(!image) {
    printf("IMG_Load: %s\n", IMG_GetError());
    // handle error
}

```

# Answer
> 1 votes
You load the texture every time you Render().
It should be this way:

1. You start the program
2. Load the texture (before the while-loop)
3. Render the texture (in the while-loop)
4. Unload the texture (after the while-loop)
5. Close the program

---
Tags: opengl, 2d, textures, sdl
---


title: How do I generate coins in a pattern?

text:
# Question
Title: How do I generate coins in a pattern?
In my game you collect coins (surprise!). At the moment I generate them like this:

* Find a random position given a rectangle (eg. the screen size) and generate a coin
* Possible positions are left and right of this coin for our next coin
    + If both are available, choose at random
    + If a coin exists in one position, use the other
    + If neither are available skip this step
* Do the same for up and down positions of the new coin
* Repeat this sequence for all available coins

This works fine but I would like to create custom shapes with my coins like arrows, stars etc. This got me thinking into how I could achieve this. One way I thought of was to use a small texture where each coloured pixel represented the position of a coin. So that a picture like this:

Can be used to generate an array of coin position coordinates in any framework supporting textures. I'm pretty sure this can be done, but was wondering if anyone has tried this or something totally different for generating coins or any other objects in a game. Ideally the game would involve several different textures and choose them at random, and combine this with the random scattering textures from simple algorithms such as the one I have above.

# Answer
> 2 votes
In one of my projects, as I was starting out, I wanted to make something right away and not get bogged down with technicalities. I was using Java and ImageIcons, so when it came to loading level data, I simply drew the level in Paint at one pixel per tile and parsed that into my array.

It was a hacky solution with zero thought involved, but in the end worked out quite well. Bitmaps are very easy to edit, and the different channels can work as layers easily. Most languages tend to have relatively simple methods for reading pixels as well. For complex maps with very varied tiles, it wouldn't work very well, but I don't think that is the case for you.

---
Tags: textures, procedural-generation
---


title: Making classes available to others

text:
# Question
Title: Making classes available to others
I'm currently working on a 2D game engine in XNA, and I am very interested in architecture, and how best to let my game objects communicate.

I know a lot of people use a Singleton design but I believe that this is more of a "counter-architecture" way of doing things, as every class will have access to the Singleton.

I was comtemplating using a Service-type architecture to allow for my Input, Sound, etc Manager classes to be available, but this is essentially the same problem as the Singleton as all the Classes are available to 'whoever' wants them.

I could of course pass references to the objects when they are needed, but this is bloated.

I wonder if making the 'Services' only allow certain objects to subscribe would be possible?

So is there a better way to make your classes available?

Or am I searching for an answer that doesn't have a question?

# Answer
> 8 votes
When you're writing a game, you're better off *writing a game* than worrying too much about having the perfect architecture. There's nothing really wrong with having singletons and global variables in a game. Far better to have *less* and *more flexible* code than for it to be perfect.

I personally find that Singleton is a pattern to be avoided. Most of the time you should be using a static class or member instead of a singleton. See, for example, the `Mouse` and `Keyboard` and `MediaPlayer` classes in XNA. These are all simply static classes which are globally accessible.

I would query your need for a "sound manager", seeing as `SoundEffect`s are stand-alone. And `ContentManager` is already the only thing you need to "manage" them.

You don't really need to write a services architecture, because XNA already provides one (see `Game.Services`).

If it seems like it would help, there's no reason why you can't just add a `public static MyGame theGame` member to your `Game` class and effectively turn it into a singleton. For the simple reason that there is never *reasonably* going to be more than one instance of your game class. Then you can make its members public (`Content` and `Services` already are) and access them globally, if it makes sense. This is simple. You can always change it to something more complicated later!

Making only your `Game` class a globally accessible also keeps the global access point localised to one place in the code, making it easier to locate when you want to "un-globalify" something later.

What I would **very much avoid** is making true *Singleton* classes that can only be instanced once. For example: don't make a map class that you can only create one instance of: what if you want to add background loading of the next map later? (Or the player class - for multiplayer, and so on).

The best example of this "global but not singleton" in XNA is `ContentManager`. You've got `Game.Content` which is effectively global. But you can also create more instances of `ContentManager`, which can be owned by whatever you like (levels, screens, whatever) and will operate independently.

# Answer
> 10 votes
```
I could of course pass references to the objects when they are needed, but this is bloated.

```

No, that's completely how it should be done. If you find doing this untenable, then your design is broken.

Passing references makes for the easiest, most obvious control and encapsulation. Global data is bad, whether you want to call it a "Singleton" or a static Manager. You shouldn't even *need* an InputManager or a SoundManager.

# Answer
> 1 votes
My advice is that a good programmer isn't dogmatic. Passing things by reference is good, singletons are also good. A good programmer uses every weapon in his arsenal, they don't rely on using a single tool, a hammer can't solve every problem.

For instance I would say it is a bad design to be passing around the same reference to a single object everywhere.

Singletons aren't counter-architecture, they're part of the GOF patterns and it is an extremely useful pattern. As all architecture, they have a proper time and place, architecture for its own sake is a common mistake. A singleton is appropriate when there should only ever be one instance of that class in your application and that instance is referenced everywhere.

You want to restrict access to singletons? A good design is not just about classes, its also about appropriate packaging. By using the internal C# access modifier you can limit use of a singleton to within a particular package/assembly.

# Answer
> 0 votes
The major difference between the singleton approach and the service locator approach is that the components are more loosely coupled. If Foo accesses Bar as a singleton, any changes to Bar affect Foo indirectly.

With a service locator you can communicate through an interface though, IBar say. You can change Bar all you want as long as it fulfills the IBar contract. If you decide that the class Baz should now fulfill the IBar contract, you can just swap it out. With the singleton, you can't do that so easily.

# Answer
> 0 votes
This is a problem throughout all of software development, and there are several common solutions.

Fortunately, you don't really need to pick one - XNA already has a built-in service locator!

# Answer
> -6 votes
I think you can use mutiple inhertence for your need and have some game object like these :

```
class KeyboardReader
{
    protected :
    static KeyBoard* keyboard;
};

class MouseReader
{
    protected:
    static Mouse* mouse;
}

class gamecontroller:public KeyboardReader, public MouseReader
{

}

```

---
Tags: xna, c#, architecture
---


# Question
Title: BoundingBox created from mesh to origin, making it bigger
I'm working on a level-based survival game and I want to design my scenes in Maya and export them as a single model (with multiple meshes) into XNA.

My problem is that when I try to create Bounding Boxes(for Collision purposes) for each of the meshes, the are calculated from origin to the far-end of the current mesh, so to speak.

I'm thinking that it might have something to do with the position each mesh brings from Maya and that it's interpreted wrongly... or something.

Here's the code for when I create the boxes:

```
private static BoundingBox CreateBoundingBox(Model model, ModelMesh mesh)
    {

        Matrix[] boneTransforms = new Matrix[model.Bones.Count];
        model.CopyAbsoluteBoneTransformsTo(boneTransforms);

        BoundingBox result = new BoundingBox();

        foreach (ModelMeshPart meshPart in mesh.MeshParts)
        {
            BoundingBox? meshPartBoundingBox = GetBoundingBox(meshPart, boneTransforms[mesh.ParentBone.Index]);
            if (meshPartBoundingBox != null)
                result = BoundingBox.CreateMerged(result, meshPartBoundingBox.Value);
        }
        result = new BoundingBox(result.Min, result.Max);
        return result;
    }
    private static BoundingBox? GetBoundingBox(ModelMeshPart meshPart, Matrix transform)
    {
        if (meshPart.VertexBuffer == null)
            return null;

        Vector3[] positions = VertexElementExtractor.GetVertexElement(meshPart, VertexElementUsage.Position);
        if (positions == null)
            return null;

        Vector3[] transformedPositions = new Vector3[positions.Length];
        Vector3.Transform(positions, ref transform, transformedPositions);

        for (int i = 0; i < transformedPositions.Length; i++)
        {
            Console.WriteLine(" " + transformedPositions[i]);
        }
        return BoundingBox.CreateFromPoints(transformedPositions);
    }

public static class VertexElementExtractor
{
    public static Vector3[] GetVertexElement(ModelMeshPart meshPart, VertexElementUsage usage)
    {
        VertexDeclaration vd = meshPart.VertexBuffer.VertexDeclaration;
        VertexElement[] elements = vd.GetVertexElements();

        Func<VertexElement, bool> elementPredicate = ve => ve.VertexElementUsage == usage && ve.VertexElementFormat == VertexElementFormat.Vector3;
        if (!elements.Any(elementPredicate))
            return null;

        VertexElement element = elements.First(elementPredicate);

        Vector3[] vertexData = new Vector3[meshPart.NumVertices];
        meshPart.VertexBuffer.GetData((meshPart.VertexOffset * vd.VertexStride) + element.Offset,
            vertexData, 0, vertexData.Length, vd.VertexStride);

        return vertexData;
    }
}

```

Here's a link to the picture of the mesh(The model holds six meshes, but I'm only rendering one and it's bounding box to make it clearer: http://www.gsodergren.se/portfolio/wp-content/uploads/2011/10/Screen-shot-2011-10-24-at-1.16.37-AM.png The mesh that I'm refering to is the Cubelike one. The cylinder is a completely different model and not part of any bounding box calculation.

I've double- (and tripple-)-checked that this mesh corresponds to this bounding box.

Any thoughts on what I'm doing wrong?

# Answer
> 6 votes
I have found the solution to this problem of yours.

Instead of doing just the following in CreateBoundingBox:

```
BoundingBox result = new BoundingBox();

```

do this:

```
BoundingBox result = new BoundingBox();
result.Min = new Vector3(float.MaxValue, float.MaxValue, float.MaxValue);
result.Max = new Vector3(float.MinValue, float.MinValue, float.MinValue);

```

When you create a new BoundingBox, the Min value is set to 0,0,0. Then later where you merge the boundingbox with result, one of the values (x,y,z) stays 0, depending on the mesh's position. This causes the box to stretch to 0,0,0 when you draw the bounding box.

So setting the Max to the minimum possible, and Min to the maximum possible, the situation is avoided.

In my tests it did fix the issue.

# Answer
> 2 votes
My insights on your situation:

1. Your bounding box isn't bigger. It's exactly the right size to encompass those meshes, except it's offset by a certain amount along two axes. In fact, it's drawing from the exact centre of that cylinder. This very unlikely to be a coincidence, and in fact it's probably telling you exactly what the problem is.
2. It's not necessarily the bounding box code that's doing something wrong. The meshes or bounding box could be using the wrong coordinates, or either one could be drawn incorrectly.
3. You made no mention of walking through what your code does in the debugger. This will tell you where the problem is.
    * What are the bounding box and mesh values after you've calculated them?
    * Are they correct? If not, there's your problem.
    * If they're fine, you're drawing them wrong.

I'm not going to diagnose the problem in your code since that's a lot of different logic to look through that I can't run.

---
Tags: xna, 3d-meshes, bounding-boxes
---


title: UDK requirements

text:
# Question
Title: UDK requirements
I've made a small game with UDK (Unreal Development Kit, release of December 2011 UDK Beta) and used frontend to package my game;

When I install the game on the user's computer (the OS of the user is Windows XP SP3 32 bit or Windows 7 SP1 32 bit without .NET Framework), the installer program follows the steps below:

1. install .NET Framework 4 (full installation)
2. run UE3Redist.exe (this program installs DirectX & Microsoft Visual C++ 2010 Redistributable Package for x86 and x64)
3. copy the required files

I tried to not install the .NET Framework 4 but it gives this error:

```
*
--------------------------
TestGame.exe - .NET Framework Initialization Error
---------------------------
To run this application, you first must install one of the following versions of
the .NET Framework: v4.0.30319 Contact your application publisher for instructions
about obtaining the appropriate version of the .NET Framework.
*

```
1. Why is the .NET Framework required?
2. If I want to build my custom setup for my game, do I need to install the .NET Framework 4? (I read UDK System Requirements.)

# Answer
> 2 votes
I made a game with UDK, and after packed with FrontEnd and installed on other computer, it required things that you have mentioned. I installed all of the things needed and afterwords uninstalled .NET 4, and my game worked just fine. I presume that .NET is required for some system tasks within your game, like saving/loading game data such as checkpoint, scores and similar, which I didn't have in my game. This, of course my not be the case, I will inspect more, but since my game worked, I believe that .NET is something that only UDK installer requires. Will try to pack with some other installers and see what happens.

Also, I made two games with Unity, and it didn't require any external packages.

---
Tags: udk
---


# Question
Title: Is it possible to reuse the same window in multiple games?
In particular, I'm thinking about C# and XNA, and obviously on Windows. Let's say I have the main game which is a normal XNA game, but at some point I would like to momentarily switch to a mini-game that was also implemented in XNA but is completely independent of my game.

Is there any way I can switch to and back between the two games, while reusing the same windows handle? And preferably keeping the old state in memory, although I could also implement this persistence writing to a file.

And when going back to the initial game, is there any way I could access the value returned by the mini-game's main method? For instance, 1 or 0 depending on whether the player cleared the mini-game or not.

---

Andrew Russell wrote:

> You should build your mini game and your main game into separate classes within the same program. Each of those classes should have Update, Draw, Initialize, etc methods. You should then have some kind of master controller to call those methods to have only one game active at a time (this could also simply be in your main game class).

Thanks for the answer. Your suggestion is what I'd do in a normal game situation - one where I'd be the one creating all of the mini games and their content.

But this is not a game, but rather a game maker tool for creating graphic adventures, and it is the end user that might feel the need to plug in external mini-games in response to certain game events.

The older internal engine that I'm trying to replace was done in Flash, and solved this problem simply by loading an SWF inside of the main SWF. It worked okay for most cases. I'm trying to do something similar but with XNA now.

But following your train or thought, perhaps I could create a separate assembly containing a base class or common interface for all mini games, and compile it as a dll. Then the user would reference that library, implement the interface and compile into his own library which could be loaded by the engine at runtime and executed as a separate state inside the main game. Am I missing some hidden implications?

# Answer
**No.** There's no official way to do this in the API.

If you were *insane*, you could *perhaps* use reflection to get at the underlying DirectX objects, and then trick them into reusing a window and triggering a content reload at the right time. (Only one device context can be attached to a window at a time, basically)

You could let them have separate windows. Although that could introduce issues, especially if they both need to be full-screen.

---

You should build your mini game and your main game into separate classes within the same program. Each of those classes should have Update, Draw, Initialize, etc methods. You should then have some kind of master controller to call those methods to have only one game active at a time (this could also simply be in your main game class).

You can use separate content managers for each game/mini-game, allowing you to unload the content for each of them once they're done.

Consider looking at the Game State Management sample.

---

To answer your edit:

Yes. A kind of plugin system like this should work just fine.

Be aware that, once loaded into a process, you won't be able to *unload* the plugin DLL without unloading the whole process - although you can unload its resources in the usual way. (Note for anyone else coming across this: You can unload when using AppDomains, but I am reasonably sure that this won't play nicely with XNA.)
> 6 votes

---
Tags: xna, c#, windows
---


# Question
Title: How can I get a set of raw samples from an audio file in XNA 4.0?
In particular, I'd like to know how to get a set of audio samples that are compatible with the XNA's Sound API classes, such as the `DynamicSoundEffectInstance` class.

I've used the `DynamicSoundEffectInstance` class for synthesizer work in XNA before. But now instead of synthesizing my sounds, I'd like to read audio samples directly out of audio files - basically I want to do my own mixing and sequencing of samples into a single `DynamicSoundEffectInstance` object. I've had subtle timing problems when trying to do sequencing on XNA before using regular timers and `Play()` calls, so I need more control.

Clearly, XNA already knows how to load sounds, for instance, using the content pipeline and the `SoundEffect` class. Is the underlying format used by the `SoundEffect` class the same as the one used by the `DynamicSoundEffectInstance` class - signed 16 bit interleaved PCM?

In short, how do I reach the point where I can play an audio file using the `DynamicSoundEffectInstance` class?

# Answer
Take a look at this tutorial. This shows you how to read and play a WAV file with DSEI (with streaming, too).

The same technique can be used for audio in other formats, but you will have to bring your own converter. Google may be able to help if you need to support other formats.

XNA's `SoundEffect` can use PCM that are (I think) in the same format as DSEI. But it can also accept compressed sound effects in some Microsoft proprietary format. However there does not appear to be any way to access its PCM data directly.
> 1 votes

---
Tags: xna, xna-4.0, audio
---


# Question
Title: Handling lost graphics device XNA 4.0 in winforms
I'm trying to put in a new feature into my level editor. Part of the feature is to bring up a form when a user places a new tile onto the map, but once the form is brought up the XNA embedded screen throws up a big red X. I think this is due to the embedded screen losing focus to the form and then crashing.

This is where the form is initialized

```
 public Form1()
   {
    InitializeComponent();

    //Node Editor

    tileDisplay1.OnInitialize += new EventHandler(tileDisplay1_OnInitialize);
    tileDisplay1.OnDraw += new EventHandler(tileDisplay1_OnDraw);

    Microsoft.Xna.Framework.Input.Keys[] allKeys = (Microsoft.Xna.Framework.Input.Keys[])
     Enum.GetValues(typeof(Microsoft.Xna.Framework.Input.Keys));

    foreach (var key in allKeys)
    KeyboardInput.AddKey(key);

     KeyboardInput.KeyRelease += new KeyHandler(KeyboardInput_KeyRelease);
     MouseInput.MouseMove += new MouseMoveHandler(MouseInput_MouseMove);
     MouseInput.MouseDown += new MouseClickHandler(MouseInput_MouseDown);
     MouseInput.MouseUp += new MouseClickHandler(MouseInput_MouseUp);

     Application.Idle += delegate { tileDisplay1.Invalidate(); };

     saveFileDialog1.Filter = "Map File|*.map";

     Mouse.WindowHandle = tileDisplay1.Handle;

   }

```

This is where the draw event is fired off

```
void tileDisplay1_OnDraw(object sender, EventArgs e)
        {
            Logic();
            Render();

            KeyboardInput.Update();
            MouseInput.Update();

            foreach (var actor in Actor.Actors)
                actor.Update();
        }

```

This is where the form is being called

```
     private void Logic()
    {
               if (colIndex == 8 && AssociateBox.SelectedIndex == 0)
                {
                    currentCollisionLayer.SetCellIndex(collideCellX, collideCellY,form.spawnNumber.ToString());

                    if(form.spawnNumber == "12")
                    {
                       camdetails.ShowDialog();
                    }
                }
    }

```

# Answer
> 2 votes
The "Big Red X" from the WinForms sample comes up when your draw/update code throws an exception. Rather than simply ignoring it, the WinForms sample catches the exception, switches to displaying the Big Red X, and stops calling your draw/update code.

**This is the equivalent of a regular XNA programming exiting with an "Unhandled Exception" error.**

Simply resetting the graphics device and attempting to continue is the wrong solution.

What you need to do is figure out where the exception is being thrown, and stop it percolating up past your draw/update code. Try setting "break on exception" in Visual Studio. Or wrap your draw/update code in a try-catch block and adding a breakpoint.

# Answer
> 1 votes
I recommend reviewing the XNA AppHub sample on WinForms that is located here: http://create.msdn.com/en-US/education/catalog/sample/winforms\_series\_1

They create a `GraphicsDeviceService` derived from `IGraphicsDeviceService`. The `GraphicsDeviceService` updates `PresentationParameters` and calls `graphicsDevices.Reset(parameters);` any time the `GraphicsDevice` needs it, which is anytime the window or form resizes.

From the code you've posted I'm guessing that `camDetails.ShowDialog();` or something inside of `SetCellIndex` could be the cause.

As a quick test you might try this right before you call `Logic();`:

```
graphicsDeviceService.ResetDevice(ClientSize.Width, ClientSize.Height);

```

Try calling that from your `Systems.Windows.Forms.Control`

---
Tags: xna
---


# Question
Title: Can I use SpriteBatch when drawing sprites on a rotating 3D plane
I'd like to have my plane of sprites rotate similarly as in this game (YouTube Video). So basically, everything is drawn in 2D, but the 2D plane is then "rotated in 3D" (or camera is rotated). When rotated, sprites further away should look like they are further away.

Question:

Can I use SpriteBatch with this? IIRC SpriteBatch uses Orthographic view matrix, so probably not? If I can, how? If not, how would you suggest I draw the sprites?

PS. I am really bad at explaining problems so feel free to ask any questions.

# Answer
**Yes!**

Let's have a look at how SpriteBatch works:

`SpriteBatch` draws sprites onto a 2D plane. So if you had wanted to rotate your sprites so that they come "off" this 2D plane, then you'd probably have to find another solution. But, looking at your video, it looks like you want to rotate the entire 2D plane.

`SpriteBatch`'s normal mode of operation uses a built-in orthographic projection matrix into client space. It also lets you pass in an optional global transformation matrix. You could use this global transformation to get your effect, but you'd also have to "pre-undo" the projection matrix that comes afterwards, and the maths is annoying.

But fear not - `SpriteBatch` has another mode of operation, where it can use any `Effect`, using that effect's vertex shader and transformation matrices. `BasicEffect` will do nicely here. Take a look at this article to get the basic principles.

Simply set `BasicEffect.Projection` matrix to a suitable perspective projection. And then set `BasicEffect.World` matrix so that your plane of sprites appears in the correct location (and the right way up!).

Take a look at this article as well. It describes the process in more detail.
> 5 votes

# Answer
> Can I use SpriteBatch when drawing sprites with 3D rotation

I'm afraid not.

You can however render the sprites you want to rotate together to a `RenderTarget2D`. Then skin a quad with the previously mentioned RenderTarget.

This describes the skin and draw a quad part.

Edit: watched the video on my phone :).

Anyways to achieve a similar effect you just need 1 quad and one render target. Draw you whole scene to a rendertarget and apply it to a single quad. you can then either move your camera or quad, whichever you find more convenient.
> 0 votes

# Answer
"Technically", no. SpriteBatch exists for 2D sprites.

However, you can supply transformation matrices to the SpriteBatch, and unless I'm mistaken this allows you to skew and stretch your sprite to your heart's content. You would, of course, have to manually calculate everything, but you could fake 3D by clever transformation of 2D.
> 0 votes

---
Tags: xna, 2d, 3d, rotation, spritebatch
---


title: Implementing IVertexType Interface

text:
# Question
Title: Implementing IVertexType Interface
In XNA, I have created a new VertexType, called it VertexPositionTextureLight which inherts the IVertexType Interface, but apparently I need to implement the member of VertexDeclartion which I cleary have:

```
struct VertexPositionTextureLight : IVertexType  {
    Vector3 position;
    Vector2 textureCoordinates;
    float light;

    public readonly static VertexDeclaration VertexDeclaration = new VertexDeclaration(new VertexElement(0, VertexElementFormat.Vector3, VertexElementUsage.Position, 0), new VertexElement(sizeof(float) * 3, VertexElementFormat.Vector2, VertexElementUsage.TextureCoordinate, 0), new VertexElement(sizeof(float) * 5, VertexElementFormat.Single, VertexElementUsage.TextureCoordinate, 1));

    public VertexPositionTextureLight(Vector3 position, Vector3 normal, Vector2 textureCoordinate, float light)  {
        // TODO: Use normal data
        this.position = position;
        this.textureCoordinates = textureCoordinate;
        this.light = light;
    }
}

```

I used to use this struct without inheriting the interface but since I need to call the device.DrawUserIndexedPrimitives that function wants the struct to inherit IVertexType.

# Answer
> 3 votes
You should have this line also:

```
   VertexDeclaration IVertexType.VertexDeclaration
   {
       get { return VertexPositionTextureLight.VertexDeclaration; }
   }

```

It should work fine after that.

---
Tags: xna, c#, shaders, interface, vertex
---


# Question
Title: How to manage the lifetime of Ogre3D objects?
I haven't found tutorials that are concerned about deleting scenenodes and entities. I assume that the scenemanager will take ownership of them when they are attached (am I right?). However, I can imagine many situations where I would like to deterministically and selectively terminate objects, for example if I were to use OGRE to display a huge open-world level, I would like to dynamically load and unload parts of the world. How can I do this while also telling the scenemanager that his pointer is no longer valid?

# Answer
Despite the facts that is not recommended to delete entities and scenenodes yourself, did you take a look at the Ogre SceneManager documention ?

---

In this document you can find the following functions to remove & destroy entities:

---

And you can find the following function to remove & destroy Scene Nodes:

---

Anyway don't forget you need to detach entities from the sceneNode first to avoid problems...

---

Finally **I do really recommend you to take a look at the Scene Manager FAQ**. This document presents the different ways to manage the scene nodes using BSP, Octree or Portal Connected Zone etc. This is probably better way to achieve what you want to to without having to manage the scene nodes yourself.
> 5 votes

---
Tags: c++, ogre, resource-management
---


title: Incorrect Model Position (XNA)

text:
# Question
Title: Incorrect Model Position (XNA)
I am new at XNA, i have started it about a week earlier but i have 3d experience in WPF.

Scenario: I have a room in which i have a object(for now it is a cube). The objects are generated in Max 2011 in the designers computer which i import into mine using fbx importer.

Problem: 1. The model are not positioned as per the max files, and also there are losses in the models.

In Max: https://i.stack.imgur.com/uID39.jpg
In XNA: https://i.stack.imgur.com/q02DY.png

Could anyone suggest me how to resolve this problem?

2. Is there a dynamic way to get the camera position information from the "FBX" file that i exported from 3Ds Max?

# Answer
> 1 votes
The model is imported with the proper transforms to set it up the way it is in max. You must account for those transforms in your c# code like this:

```
//in the fields declaration
Matrix[] modelTransforms;

//in the loadContent method after loading the model
modelTransforms = new Matrix[model.Bones.Count];
model.CopyAbsoluteTransformsTo(modelTransforms);

//in your draw method
effect.World = modelTransforms[mesh.ParentBone.Index];//where 'mesh' iterates through all objects in the model.

```

The camera position is not imported with the fbx. Your best shot there is to right click the 'Move Gizmo' in max and record the position of it (remember to set Z = -Y & Y = Z due to the zup/yup swap) then in c# camera setup:

```
Matrix view = Matrix.CreateLookAt(recordedPosition, Vector3.Zero, Vector3.Up);

```

now the camera is set the same as max.

# Answer
> 1 votes
I don't believe there is a built in way to get the camera position from an embedded camera in an FBX file imported to the Model class. You would probably need to write your own content importer that imports the FBX file to a class of your own (you can probably reuse a lot of the FBX importer so it shouldn't be too much work).

As for the position, XNA is right handed so make sure you export using a right handed coordinate system.

# Answer
> 0 votes
It's possible, your model is exported with some transformation. I don't use Max, but you should try to find something like Freeze transformation (so your Rotation, Transformation and Scale are all default).

---
Tags: xna
---


# Question
Title: Best way to separate display and game logic (threads)
What is the best way to separate render and game logic threads?

I'd like to make logic-heavy game (ai, machine learning, and network) in which world updates 50-60 times per second.

I want to separate rendering so it will not waste logic's thread power.

I'm planning to use c++ with boost.

# Answer
Threading in games has pretty much the same issues you'll find in any other application. Think in terms of parallelization: you have some interrelated task that must be run concurrently without interfering with each other's work.

The drawing stage should not be affected by any other computation, so the gamestate must remain stable while drawing, i.e., these tasks must be synchronized. Drawing should not start until the whole gamestate step has finished. Gamesate-changing tasks must run sequentially with drawing code (update-draw-update-draw-...) while you can still concurrently run code that doesn't immediately change gamestate (e.g. pathfinding for the next frame.) You can also keep local copies of the whole gamestate (if it's not too big) or parts of it, computing them but only updating the gamestate upon synchronization with the drawing code (after the drawing for the current frame had ended.)
> 3 votes

---
Tags: c++, rendering, multithreading, logic
---