# Question
Title: What are good JS libraries for game dev?
If I decide to write a simple game both text and graphical (2d) what libraries would I use? (Assume we are using a HTML5 compatible browser)

The main things I can think of

* Rendering text on screen
* Animating sprites (using images/css)
* Input (capturing the arrow keys and getting relative mouse positions)
* Perhaps some preloading resource or dynamically loading resources and choosing order
* Sound (but I am unsure how important this will be to me at first). Perhaps with mixing and chaining sounds or looping forever until stop.
* Networking (low priority) to connect a user to another or to continuously GET data without multiple request (I know this exist but I don't know how easy it is to setup or use. But this isn't important to me. Its for the question).

# Answer
> 25 votes
**jQuery** and **MooTools** are awesome JavaScript libraries; I prefer jQuery myself. Either one will assist you in your JS game development if you use the DOM. If you go with Canvas rendering, I still think you should use one of those libraries, but you will need to learn the Canvas functions. Here is a tutorial which introduces you to canvas by creating a Breakout clone, so it might be exactly the kind of thing you're looking for (and it uses jQuery).

Animating sprites is a matter of changing an image src, or preloading several images and swapping them out, or in a canvas just drawing frames of an animation. The above libraries can help with any of these cases. The libraries also help with input (look into events such as onkeypress and onmousemove).

For preloading resources, I've seem some games that use a single "sprite sheet" image (here is the one for Google's Pacman game). I believe they basically create a DIV of one tile size, with the CSS background-image property set to the sprite sheet and the background-position property set to the offset of the tile on the sprite sheet. I haven't seen a library that will do this for you, but jQuery or MooTools can help you as far as dynamically creating the DIV and manipulating its CSS. Otherwise, preloading images is a matter of creating `<img>` tags of the images you want preloaded, and not adding them to the page (or adding them invisibly). Here's **a blog post** that has some code for a function using jQuery to preload images for you.

**SoundManager 2** seems to be the JS sound library to use; I know Vanthia uses it, and Google's Pacman used something similar (or at least the same technique, of using a hidden Flash file on the page to play sounds).

For networking, jQuery can handle AJAX for you, or if you want much more real-time networking (and have the server to do so), look into **JavaScript sockets**. I don't know if there's a stable library out there for it, but you might look into this or this. Essentially it uses a hidden Java or Flash file on the page so that you can do true socket communication with JavaScript, which is much quicker than AJAX polling and slightly more efficient than "AJAX Push". However, most likely, AJAX Push will be what you want, and **APE (Ajax Push Engine)** is probably the library to use.

Also, here is a Google tech talk about "Building a JavaScript-Based Game Engine for the Web". It looks neat.

# Answer
> 12 votes
When I evaluated JavaScript engines a little while ago my favorite was Crafty:

http://craftyjs.com/

There were a loooot of options I had to consider, and some others I liked were:

http://easeljs.com/

http://www.limejs.com/

http://code.google.com/p/casualjs/

(Incidentally, another option that looks pretty slick initially is http://impactjs.com/ but considering it costs money and the other options I looked at were open-source engines there were some glaring omissions, like the inability to attach display elements in a heirarchy.)

---

**UPDATE:** It's been almost 2 years since I posted that answer and the situation has changed slightly (this *is* a nascent area of technology.) Although Crafty is still a great choice, in the past year EaselJS has picked up a lot of momentum (especially considering Adobe hopped on the EaselJS train.) I'm gonna switch to that tool for future projects (also note that it has a new website)

# Answer
> 7 votes
The Effect Games engine (javascript) is fantastic for 2d, tile/sprite-based games. The website doesn't do a very good job of describing what's so great about it, but as soon as you dig into the excellent documentation you'll see how much has been covered for you:

* spriting
* collision detection
* level editing
* asset management
* audio
* input and control
* tileset creation and management
* layering
* animation
* performance (lock to a framerate)
* cross-browser support and abstractions
* hosting
* embedding
* HUD support

I really can't provide an exhaustive list as it's so fully featured. One thing that's missing is the ability to create in-game menus and UI (eg. equipment managers etc), but it's supposedly on the todo list.

# Answer
> 6 votes
I maintain a canvas 2D game engine called JawsJS - http://jawsjs.com/

Source @ https://github.com/ippa/jaws

cliffnotes:

* Readable, documented code
* 12+ bundled documented examples
* Useful constructors like Sprite(), SpriteSheet() and Animation()
* Game states - Separate sections of your game for better organized code
* Assets - Jaws will preload all your assets before the game starts
* Does not depend on any other javascript library
* Builds on lessons learned from years of developing Chingu, a Ruby game lib

# Answer
> 4 votes
Impact is going to be sick! Just take a look at the demo game, Biolab Disaster.

# Answer
> 4 votes
I've been doing some research in this area lately myself, so let me chip in my $0.02:

**PlayN** Is a cross platform library from Google, which compiles an object oriented game from Java to javascript/Flash/Android. It will handle JSON (AJAX), data models, and has sane semantics for updates and rendering. *Very* cool stuff.

**Processing** Is a simple to use library that is aimed at designers and artists. It's exceptionally simple to use and can give you great results. I've used the Java version for scientific modelling, and it is a delight to use. The 3D scenes will need WebGL, but the 2D scenes work without.

**Three.js** Has some great looking demos. It requires WebGL, but the result seem worth it. There are some exiting examples online too.

Here are some of the other items in my personal linkdumps that relate to WebGL:

# Answer
> 3 votes
Akihabara is a framework that I've seen come up in a number of places. A friend of mine also created a series of tutorials and documentation for the framework.

# Answer
> 3 votes
http://rocketpack.fi/ seems to have something coming up.

# Answer
> 2 votes
Another one I recently have been looking into with great interest is CreateJs. It is a collection of open source libraries to include...

Additional it EaslJs Plays well with Box2D JS

# Answer
> 1 votes
## Pixie Plugins

The creators of Contrasaurus have released a lot of their individual components!!!

They have code to do **matrix transformations**, **canvas abstractions** and many many more interesting things.

Their **code is great** and their libraries are really useful.

# Answer
> 1 votes
Impact JavaScript Game Engine for iOS looks promising. The link shows a demo, but it has not been released, yet.

# Answer
> 1 votes
Strange that Google Closure Library hasn't been mentioned. It has a huge API, allows more object oriented coding style and has the compiler.

I have used so far only the compiler but I am planning to study rest asap.

# Answer
> 1 votes
I usually use jawsjs because it's really easy to set it up and start developing a game in minutes. It has lots of really useful default classes (Tilemap, Viewport, Sprite, and others) that really help with game development.

# Answer
> 1 votes
You've got plenty of them actually, but it first mainly depends on which kind of game engine you're looking for. I can give you some references of the most noteworthy.

### 2D Game Engines

* Cocos2D tends to be a bit more fashionable at the moment. I saw Cocos2D questions popping up here and there on Stackoverflow recently.
* Impact, you can see a benchmark running on the official website.

### 3D Game Engines

Mozilla foundation has been working on a 3D game engine named Paladin. It's Mozilla that it can't really hurt I guess.

# Answer
> 0 votes
There is also gameQuery, a jQuery based game engine. Has decent documentation on their API, as well as, a few sound wrapper APIs they link to on their site.

http://gamequery.onaluf.org/

# Answer
> 0 votes
Mozilla Gaming has a list on its Resources pages. It links to Diggy, which is a DHTML game engine I built a while back. Live demo here!

# Answer
> 0 votes
Matrix.js is good if you want to get Flash style matrix transforms.

# Answer
> 0 votes
Tom here from Scirra, we are a 2 man team that have created Construct 2, the HTML5 game maker. (Free version available).

You might want to consider an engine like ours as it does a lot of the legwork for you. For example to do collisions in code yourself can be really tricky (think polygon collisions). Everything on your list is easily achievable with Construct 2.

---
Tags: html5, javascript
---


# Question
Title: Algorithm to select all cells inside rooms/regions
I have a 2d game map consisting of several 'rooms'

For example, here is a 2D map grid: (Brown cells = wall tiles)

If I click on a tile (that isn't brown), I would like to obtain an array of all the cells in the region that I clicked. (If the region is bounded by brown tiles, otherwise do nothing)

For example, there are two regions in the image above, both colored in grey. If I clicked cell (4,4) I would get a 4x5 array of cells starting at (3,3).

Does anyone know a good performance efficient algorithm for this? I need to account for non-square rooms ideally.

# Answer
> 6 votes
This is called *floodfill*. You can look it up on Wikipedia.

One way of implementing consists of having a list of visited squares `v` and pending squares `p`, and do something like

```
v = {}
p = {}
p <- (x, y)
while p is not empty
    (this_x, this_y) = p[0]
    remove p[0] from p
    if (this_x, this_y) is not in v, and (this_x, this_y) is not a wall
        v <- (this_x, this_y)
        // Add the adjacent squares...
        p <- (this_x + 1, this_y + 1)
        p <- (this_x + 1, this_y - 1)
        p <- (this_x - 1, this_y + 1)
        p <- (this_x - 1, this_y - 1)
    end
end

```

The squares in the room are those left in `v` when you finish.

There are also several ways to optimize this, but you should get the main idea.

# Answer
> 9 votes
A simple flood fill algorithm will suit you just fine.

Have it make a list of tiles as it progresses. If a neighboring tile is outside the bounds of your grid, then that entire region is not bounded by the brown tiles, and can be ignored.

---
Tags: algorithm, tiles, maps
---


# Question
Title: How do I render a filled and stroked path using OpenGL?
I want to render a 2-dimensional geometric path consisting of Bézier curves and straight lines. Paths can be concave.

What is the most efficient way to draw this using modern OpenGL? Can I do this with a vertex shader? How should I store the path segments?

# Answer
The easiest way is probably to use the NV\_path\_rendering extension: https://developer.nvidia.com/nv-path-rendering

If that won't work for you, you're going to essentially have to implement at least part of the functionality. The good news is that NV\_path\_rendering shows that it's possible; the bad news is that it's probably going to be a lot of effort, depending on your requirements.
> 3 votes

---
Tags: opengl, shaders, rendering, geometry, beziers
---


title: XNA Textures with background color

text:
# Question
Title: XNA Textures with background color
I am fairly new to XNA and I have questions in regards to textures.

Most of my of textures have a background color along with the overall image (white, black, or whatever). This is quite ugly as the users main character, ship, or bullets, ect, have this black or white background with it. Is there any function, tool, or anything that will enable me to crop the actual part of the image i want to use as the texture?

I am by no means good with and photo editors or anything graphic related.

I came up short with google, as most results led me no where.

All help is appreciated. Thank you.

# Answer
XNA Texture2D Content Pipeline compilation uses original alpha channel to remove backgrounds. you can set alpha chanels in your images using image procesing tools like Paint.NET, gimp or photoshop.

There is other way just to set specyfic color (example white) to be transpatent. In "Content" project where your textures are:

1. Right click texture you want to remove background
2. Select properties
3. From Properties select `Content Processor -> ColorKeyColor` and set it to color you want to be transparent (example `255;255;255;255` for white)
> 6 votes

---
Tags: xna, c#, textures
---


title: Drawing background is very costly/slow

text:
# Question
Title: Drawing background is very costly/slow
I'm creating a "simple" Tetris style game for a beginner project. My problem is when I added the background (tiled look consisting of a bunch of squares), the game got very slow. It has to have something to do with the way I am drawing the background but I am not sure of any way to improve it. I thought about using an image as the background, but I really want to be able to have the gameboard size customizable. Here is my code:

GameBoard

```
public class GameBoard
{
    private List<Square> Squares;

    public GameBoard()
    {
        Squares = new List<Square>();

        BuildBoard();
    }

    private void BuildBoard()
    {
        for (int x = 0; x < 40; x++)
        {
            for (int y = 0; y < 24; y++)
            {
                Squares.Add(new Square(new Point(x, y), new Color(50, 50, 0)));
            }
        }
    }

    public void Draw(SpriteBatch batch)
    {
        foreach (Square square in Squares)
            square.Draw(batch);
    }
}

```

Square

```
public class Square
{
    private const int HEIGHT = 20;
    private const int WIDTH = 20;

    public Point Position;
    public Rectangle Rectangle;
    public Color Color;

    public Square(Point Location, Color color)
    {
        Position = new Point(Location.X * 20, Location.Y * 20);
        Color = color;
        Rectangle = new Rectangle(Position.X, Position.Y, WIDTH, HEIGHT);
    }

    public void Move(int xMove, int yMove)
    {
        Position.X += xMove;
        Position.Y += yMove;
        Rectangle = new Rectangle(Position.X, Position.Y, WIDTH, HEIGHT);
    }

    public void MoveRight()
    {
        Position.X += 20;
        Rectangle = new Rectangle(Position.X, Position.Y, WIDTH, HEIGHT);
    }

    public void MoveLeft()
    {
        Position.X -= 20;
        Rectangle = new Rectangle(Position.X, Position.Y, WIDTH, HEIGHT);
    }

    public void MoveDown()
    {
        Position.Y += 20;
        Rectangle = new Rectangle(Position.X, Position.Y, WIDTH, HEIGHT);
    }

    public void Draw(SpriteBatch batch)
    {
        Texture2D squareTexture = new Texture2D(batch.GraphicsDevice, 1, 1);
        Texture2D borderTexture = new Texture2D(batch.GraphicsDevice, 1, 1);

        squareTexture.SetData(new[] { Color });
        borderTexture.SetData(new[] { Color.Black });

        batch.Draw(squareTexture, Rectangle, Color);
        batch.Draw(borderTexture, new Rectangle(Position.X, Position.Y, 2, HEIGHT), Color);
        batch.Draw(borderTexture, new Rectangle(Position.X, Position.Y, WIDTH, 2), Color);
        batch.Draw(borderTexture, new Rectangle(Position.X + 18, Position.Y, 2, HEIGHT), Color);
        batch.Draw(borderTexture, new Rectangle(Position.X, Position.Y + 18, WIDTH, 2), Color);
    }
}

```

Game1.cs

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

    GameBoard board;
    Shape shape;

    int downTicker;

    public Game1()
    {
        graphics = new GraphicsDeviceManager(this);
        Content.RootDirectory = "Content";
    }

    protected override void Initialize()
    {
        base.Initialize();
        this.TargetElapsedTime = TimeSpan.FromMilliseconds(50);
        downTicker = 0;
    }

    protected override void LoadContent()
    {
        spriteBatch = new SpriteBatch(GraphicsDevice);
        shape = new Shape(Color.Blue);
        board = new GameBoard();
    }

    protected override void UnloadContent()
    {
        spriteBatch.Dispose();
    }

    protected override void Update(GameTime gameTime)
    {
        if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
            this.Exit();
        downTicker++;

        Debug.WriteLine(TargetElapsedTime.Milliseconds);
        if (downTicker == 10)
        {
            //shape.MoveDown();
            downTicker = 0;
        }

        if (Keyboard.GetState().IsKeyDown(Keys.Right))
            shape.MoveRight();
        if (Keyboard.GetState().IsKeyDown(Keys.Left))
            shape.MoveLeft();
        if (Keyboard.GetState().IsKeyDown(Keys.Down))
            shape.MoveDown();

        base.Update(gameTime);
    }

    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.Black);
        spriteBatch.Begin();
        board.Draw(spriteBatch);
        shape.Draw(spriteBatch);
        spriteBatch.End();

        base.Draw(gameTime);
    }
}

```

# Answer
> 5 votes
I believe the issue is that you're creating a pair of textures, for each draw, for each square:

```
Texture2D squareTexture = new Texture2D(batch.GraphicsDevice, 1, 1);
Texture2D borderTexture = new Texture2D(batch.GraphicsDevice, 1, 1);

squareTexture.SetData(new[] { Color });
borderTexture.SetData(new[] { Color.Black });

```

If you create these outside of the draw loop and keep them for the entire lifespan of the Square, your performance should improve greatly.

# Answer
> 0 votes
To extend on John McDonald's answer (i don't have comment permissions sorry). You should be able to ceate two textures in your `GameBoard` and pass them into each square that you generate, instead of the color property

Outside of the question but useful anyway:

In your `Square` constructor change the line:

```
Position = new Point(Location.X * 20, Location.Y * 20);

```

To:

```
Position = new Point(Location.X * WIDTH, Location.Y * HEIGHT);

```

---
Tags: 2d, xna-4.0
---


# Question
Title: Hello World with FlashDevelop, Flixel, AS3: uneffective SWF macro
I just started with FlashDevelop and Flixel, and I already have a question. I created this basic hello world:

```
package
{
    import org.flixel.*;
    [SWF(width = "640", height = "480", backgroundColor = "#000000")]; //Set the size and color of the Flash file

    public class HelloWorld extends FlxGame
    {
        //...
    }
}

```

When I run this "game", using Flash Player, I get a 800x600 window with a white background, even though I specified it's 640x480 with a black background. Am I doing anything wrong?

I am using Flex 4.6.0, and the target platform is Flash Player 10.1. I have the debugger version of Flash Player 11 installed (WIN 11,5,502,146 to be exact).

---

In the `.xml` file (found in the `obj` folder) I found the following:

```
<default-size>
    <width>800</width>
    <height>600</height>
</default-size>

```

Changing the size/color through the properties window of my FlashDevelop project **does** work fine...

It seems to ignore the `[SWF(...)]` macro entirely: what's going on?

# Answer
> 2 votes
Found it. It was the semicolon (`;`) after the `[SWF(...)]` that killed it. Got it rocking now :) I believe the FLEX compiler is to blame here, since tutorials also have this semicolon, they'll probably used the Flash IDE...

---
Tags: flash, actionscript-3, flixel, flex, flashdevelop
---


title: Background blur in 2D game?

text:
# Question
Title: Background blur in 2D game?
In an XNA 2D game, I am thinking about blurring the background slightly to increase the feeling of depth? I am already using parallax scrolling which works pretty well in terms of enhancing depth perception. However, some newer games e.g. Super Mario Bros. 2 on the Nintento 3DS additionally use a blurred background.

Admittedly, this is a pretty extreme example:

SMB2 on 3DS example http://www.zavvi.com/blog/wp-content/uploads/2012/08/MARIO2-580x347.jpg

For me, the blurring visually is not very pleasing but nevertheless somewhat enhances the feeling of depth. I was wondering if there are any studies or personal experiences out there on the subject?

At the moment, the blurring is created by a HLSL pixel-shader (or GLSL though Mojoshader with MonoGame) which is parameterized by the velocity of movement (the faster the more blurred).

# Answer
> 7 votes
There are a couple of options.

1. Blur the image itself (in Photoshop, GIMP, whatever).
2. Blur the image using a shader (probably not too hard)
3. Blur the image manually. (Blurring is really averaging of nearby pixels.)

I would personally favour reason #1, unless there's a very strong reason not to. If you need the original, unblurred image, then keep it alongside the blurred version.

Option #2 is probably a good learning experience if you've never written a shader before (I haven't), and the performance is probably not bad; the advantage is that you won't need to save the blurred version of the image alonside the original, and that you can modify the blur at runtime (eg. progressively blur more over time).

# Answer
> 1 votes
To me that screenshot looks like the background scene has been rendered as 3D and a depth of field effect has been applied, to simulate a camera lens.

Personally I don't mind the effect too much when the depth of field is fixed, but it gets more annoying when it won't focus on what you want it to in an FPS.

---
Tags: xna, 2d, xna-4.0
---


title: Make paid app free for specific user

text:
# Question
Title: Make paid app free for specific user
Is it possible for me as an developer/owner of my paid app (released on the Google Play market) to unlock its full version for specific user?

# Answer
> 3 votes
It's been discussed on the Google forums. Basically, there isn't a really easy option, but the options discussed in the thread are:

1. Buy gift cards and give the gift card codes to user to purchase your app. Issues: You'll lose money on this transaction and the user is not required to buy your app, potentially losing you even more.
2. Create a free version of the app that can accept an unlock code to be upgraded to the full version. Issues: If you don't already have something like this in place, it'll be a good deal of work to get implemented. The unlock codes would be single/limited use, so that would require a server for validation. That adds additional cost to this scenario.

The quickest and easiest of the two is to use the gift cards. But the most suitable for long term is the unlock codes. An additional benefit of the unlock codes is having the infrastructure in place for any future apps you develop. (Or maybe selling the library to other developers).

---
Tags: android, google-play
---


title: How to handle "weapon slots"?

text:
# Question
Title: How to handle "weapon slots"?
I'm working on implementing an RPG engine, and I'm trying to figure out the best way to implement equipment. The really tricky part is the hand slots.

It would be easy to give a character one hand slot for a weapon, and one off-hand slot for a shield. But defining it that way would make it impossible to dual-wield, or to wield two-handed weapons. Giving the character two generic "hand slots" would allow for dual wielding, two-handed weapons is where things get tricky.

The obvious way to equip a two-handed weapon is by filling both slots with the same object. But then I need special-case code for calculating stat bonuses (you can't simply sum all bonuses from all slots, because the weapon's values will get added twice) and for removal (you can't just clear the item from one slot). If I only put the object in one slot, then calculating bonuses becomes easy again, but there needs to be special-case code to check whether the "empty" offhand slot is really empty or not.

Obviously I'm not the first person to face something like this. Two-handed weapons have been around in RPGs for decades. Is there any elegant way to handle the logic involved?

# Answer
This is actually rather easy to do. Just get every item some bitmask to define how/where it can be equipped.

Some random example:

```
enum Slot {
    SLOT_NONE  = 0x0000,
    SLOT_LEFT  = 0x0001,
    SLOT_RIGHT = 0x0002,
    SLOT_TWOH  = 0x0004,
};

```

When trying to equip a weapon into a specific slot, you can check/compare flags to do different things:

* If `itemSupportedSlots & slotType` is not equal 0, the item can be equipped in this slot.
* If `itemSupportedSlots & SLOT_TWOH` is not equal 0, the item is dual wield and equipping it automatically removes the item in the left hand.
* If the item goes into the left hand and there's a two-handed item in the right hand, the item in the right hand is removed.

Doing the slots with such flags makes it rather easy to define new slots, create special items that can fit either slot (e.g. multiple ring slots or the ability to wear a ring around the neck, etc.).
> 7 votes

# Answer
In Everquest (a 14 year old MMO), each item has a bitmask called "slots" and this allows for items to be designed to be fit in the primary weapon slot, off-hand, both, back slot, and so on. So for example, it allows for a weapon that can be used only in your right hand, a weapon that can only be used in your left hand, a shield that can only be used by your left hand, or a shield that can be used as a shield and as back armor (switch between the "details" and "raw" to see what the different views of the same item produce).

The advantage of this is that you don't need separate enumerations for clothing and weapons - they all share the same enum:

```
enum Slots {                // Lots left out
    Face =         0x00010,
    Back =         0x00100,
    Wrist_Left =   0x00200, // Perhaps you want watches only on the left wrist?
    Wrist_Right =  0x00400,
    Range =        0x00800, // This is usually for ranged weapons, like bows
    Primary =      0x02000, // Your right hand
    Secondary =    0x04000, // Your left hand
    Feet =         0x80000,
    Waist =       0x100000
}

```
> 3 votes

---
Tags: rpg, logic
---


title: Should I learn Direct3D 9, 10 or 11?

text:
# Question
Title: Should I learn Direct3D 9, 10 or 11?
I'm just starting to get into 3D programming with Direct3D. What version of D3D should I pick up?

11 looks pretty neat, but 9 and 10 still seems to be pretty present. Given the current state of the game development industry, which version does it make more sense to start using?

# Answer
> 12 votes
That depends on whether or not you want to design an engine to produce a game to be done in three years, or one year or six months, and whether or not you're thinking of console ports. It'll be relatively easy to throw out a 360 port of your game from Direct3D9, but you'll need to do a lot more originating from D3D11. Remember that D3D11 locks out all XP users, if not necessarily all D3D9 hardware.

The most recent Steam survey suggests that about 16% of people still use Windows XP. Can you afford to cut them out? By the time your game is done, how will this have changed? Are you going to use features that depend on the higher level API? These are questions that you will need to answer yourself.

Direct3D 9 is pretty damn accessible and you can reach a lot of people with a D3D9 game, but it's days are numbered, especially on the PC. If you're not interested in targetting those people, then there's little point to it.

Oh, and don't bother with DX10. There's no reason at all to use it over DX11. Unless you want to use D2D/DirectWrite, which is not unreasonable.

Of course, it's worth mentioning that in DX11, there are no replacements for classes that, as a hobbyist myself, I found extremely useful in DX9. Such as ID3DXMesh, ID3DXSprite, ID3DXFont, have to compile ID3DXEffect from source, etc. Microsoft recommends DirectWrite to replace ID3DXFont, but of course, they forgot to actually make DX11 compatible with the new Direct2D/DirectWrite systems, which in my opinion was blindingly stupid.

# Answer
> 9 votes
tldr: Learn D3D11.

The difference between 10 and 11 is pretty small, in terms of the shape of the API. D3D11 allows you to use down-leveling to write code against the D3D11 API that will run all the way back to D3D9 class hardware (note that you will still require Vista or better however). So you may as well learn the newer API, which I feel is cleaner and more uniform anyhow.

However, if you don't have Vista or better, or you eventually want your own code to run on XP (to for example distribute your game to XP users), you're going to have to use D3D9. The XP market is probably shrinking, though, so I'd say go for 11 if you can.

# Answer
> 3 votes
If you're completely new to 3D programming, and especially if you're new to COM and Windows programming, I would strongly advice against learning DirectX now. In my experience, DirectX is an extremely powerful tool, but it has a very steep learning curve, which you must consider in addition to the learning curves of Windows programming, 3D programming and many others. If you start with DirectX, you might feel overwhelmed by all the details of making boilerplate code, so I advice against it.

Instead, I would recommend a simpler API that allows you to focus more on learning about 3D programming. XNA is quite nice, and since it lies on top of DirectX, once you move to DirectX, you'll have some ideas that will make the DirectX learning curve much easier to take on.

Now, if you have experience in 3D programming, such as with OpenGL, and you know how to do COM programming, I'd recommend DirectX 11. Anything but the latest version is obsolete, and any experience you get from it will be useful for a shorter span of time.

But then again, true experience comes from variety, so I'd recommend you learn both DirectX and OpenGL, and also XNA if you want, and as many APIs as you can. That way, you will have an abstract knowledge of how 3D programming works with different tools, and you will be able to use the right tool for each job.

# Answer
> 2 votes
I recommend DX11 or DX10. The difference is very small. You can just do more things with DX11 (hw tessalation, better gpgpu, output to multiple textures on pixel shader..). DirectX 9 has another architecture and is little outdated at the moment. If you are asking about current game dev industry: for curently developed pc games is DX9 dead.

But i have to say:
**Don't care about api**, once you really understand how graphics works, learning new api would take max one month. Even shorter time.

# Answer
> -5 votes
I heard that dx9 with win xp system is single core based system. It is old tech. I recommand you dx11.

---
Tags: directx
---


title: Keybindings in Unity

text:
# Question
Title: Keybindings in Unity
I need to know how to bind keys to actions through Javascript within Unity.

When I develop web applications, I normally use this:

```
var KeyBind = function() {
    if (document.addEventListener) {
        document.addEventListener("keydown", keyDownHandler, false);
        document.addEventListener("keydown", keyUpHandler, false);
    }
    else if (document.attachEvent) {
        document.attachEvent("onkeydown", function() {
            keyDownHandler(window.event);
        });
        document.attachEvent("onkeydown", function() {
            keyUpHandler(window.event);
        });
    }

    function keyDownHandler(e) {
        var key = e.which || e.keyCode;
        if (key == "27") {
            window.location="file:///D:/Users/pferris/Documents/Unnamed%20Site%202/HordeAttack.html";
        };
};

```

Does Unity use a similar method, or will I have to do something completely different?

I've been through the help section a bit, but nothing seemed very satisfactory.

# Answer
> 2 votes
A similar method would be from the Input class

http://docs.unity3d.com/Documentation/ScriptReference/Input.GetKeyDown.html

```
function Update () {
    if (Input.GetKeyDown (KeyCode.Space))
        print ("space key was pressed");
}

```

---
Tags: unity, software-engineering, keyboard
---


# Question
Title: How to position a sprite in a 2D animation skeleton?
Given two joints that define a bone, I would like to know how to decide where, between those two joints, I should draw the sprite. This should be a fairly simple thing to solve, but there is one thing that I am not sure about.

After I've determined the rotation of the sprite (which is the absolute angle the joints form with the x-axis), I also need to determine the origin point from where I need to start drawing the transformed image.

So how should I position the sprite between the two joints? Should I make the center of the image be the midpoint between the two joints, or should I make one the of the joints be the origin? Do these things matter that much (could the wrong positioning make the sprite move oddly during the animation)?

# Answer
My 2D animation skeleton looks like this:

The large hollow circles represent **constraints** that the nodes (filled circles) have to other nodes. For example, I make sure that the elbow stays within some given distance of the shoulder.

To actually **draw** a `sprite` between nodes `n1` and `n2`, this is the function call I use in Love2D:

```
love.graphics.draw(sprite.img -- image
    , n1.pos.x -- x coordinate
    , n1.pos.y -- y coordinate
    , (math.pi/2)-v.dir(n1.pos, n2.pos) -- orientation (radians)
    , (n2.pos - n1.pos):len() / len -- x scale
    , 1 -- y scale
    , sprite.orig.x -- x offset
    , sprite.orig.y -- y offset
)

```

Your framework likely has a similar function.

I use the two nodes' positions to figure out the rotation and scale that the sprite should have. The vector library I use implements these with simple trigonometric functions and Pythagoras' theorem, respectively.
> 2 votes

# Answer
It's quite simple, you calc

```
vec2 dir = vec2_end_joint - vec2_start_joint
angle = dir.Angle();
//set origin of sprite if required here.
sprite.draw(vec2_start_joint, angle, calculated_scale_if_required);

```

calculated\_scale\_if\_required - is sprite size and your dir.Magnitude ratio

Or you can use matrix multiplication, like glRotate glScale, to make direct kinematics calculations and use your bones hierarchy.
> 0 votes

# Answer
It sounds like for each bone you are currently defining the texture to be rendered - you might as well allow for more flexibility and include a texture origin offset in your bone structure as well (relative to either of the joints you choose). That way you can be sure the rendered texture will be consistently placed.
> 0 votes

---
Tags: 2d, animation, skeletal-animation
---


# Question
Title: How to determine mouse position outside stage, and center the cursor?
I was wondering if it is possible to have my flash game determine the position of the mouse, even when the cursor is not inside the stage.

My movie clip should move horizontally between `x = 100` and `500`, using `mouseX` for movement:

```
private var previousX : int;
private var mc : MovieClip;
//...
private function update(e:Event = null):void
{
    var deltaX : int = (mouseX - previousX) / 2;
    mc.x = Math.min(Math.max(mc.x + deltaX, 100), 500);
    previousX = mouseX;
}

```

The above code works fine, as long as the cursor is above my flash game. When the cursor is outside the stage, `mouseX` stops updating. I realise that `mouseX` is probably not what I'm looking for, so I was wondering if there was any other way of finding the cursors position.

I hoped there was a way to set the mouse position directly, so I could center it after every update, so it would almost never be able to leave the frame in the first place. Is that possible?

# Answer
There is only one way to determine it, for which you will need to make the behavior from mouse-move to click-and-drag. When mouse is clicked over the stage, and then moved outside, it's position (x,y) can be determined. Otherwise, i think it's not possible. I had a similar situation, where ultimately, we were forced to make the game full-screen.

Here is how to test it :

```
import flash.events.Event;

//CLICK AND DRAG ( DON'T DO A MOUSE UP )
stage.addEventListener(MouseEvent.MOUSE_MOVE,mv)

function mv(e:Event )
{
    trace(mouseX,mouseY);
}

```
> 2 votes

# Answer
You can't confine the system cursor to a region with Flash. What you can do is hide the system mouse-cursor using `Mouse.hide()` (only works when the cursor is over your game-area), then use a custom cursor instead. There's also an event called `Event.MOUSE_LEAVE` which will fire whenever the mouse leaves the stage area. You can't tell where the mouse will be on screen, but at least you know that it's no longer inside your game-area. Eg.

```
stage.addEventListener(Event.MOUSE_LEAVE, handleMouseLeave);

```

Here's a tutorial that explains the above in more detail.
> 3 votes

---
Tags: flash, actionscript-3, browser-based-games, mouse
---


# Question
Title: Is there any public in-game data mining/knowledge discovery repository?
I'm taking an Introduction to Data Mining course at the university and we have to work on a final project.

As you may already know, it's difficult to collect this kind of data manually (specially when you're not working for a company of have the proper contacts).

Is there any public collection of in-game data in order to apply data mining algorithms? The kind of data I'm looking for is the sort of data they used in this paper "Predicting Player Behavior in Tomb Raider Underworld".

Characteristics: playing time, number of deaths, causes of death, rewards, treasures. Other kind of in-game data (possible an MMORPG): race, level, equipment, guild, items usage, hp/mp rate, level-up mean time, hours played by day/week/month, log-in/log-off time, etc.

The kind of problems I'd like to tackle could be represented as questions like:

* What are the chances a player is likely to pass the game \[in X seconds\]?
* What are the best X guilds to be with in order to meet my expectations as a player and not end up being expelled?
* What is the best world area in order to level-up faster now while minimizing death possibilities?

# Answer
It's not precisely deep data, but check out what Valve Software makes available at http://store.steampowered.com/stats/

The Day of Defeat stats at http://www.dayofdefeat.com/stats/ might be the closest for what you're looking for. That said, none of the offerings have a lot of data.

You might also consider contacting Valve to see if they would share any additional data with you.
> 2 votes

# Answer
I suspect a lot of the information that you're after companies would consider commercially sensitive. The reason they gather all that data is to help them make more money by improving their games. Giving away that information to their competitors is probably not something they'd want.

If you look at the acknowledgements on the last page of that pdf you mentioned it's clear that the authors work for the game developer.

Your best option is probably to write your own game which collects the data you're interested in, although that will take a lot of time and effort to get what you're after.
> 1 votes

# Answer
i think mortal online released a map showing locations of player deaths some time back,

however why not think of it another way, give a few companies a call and tell them what you are doing and if they are willing to help, tell them anything you learn you will share with them, i'm sure some will be more than willing to pass some free work your way
> 1 votes

---
Tags: databases, data-mining
---


title: Calibration of a 6 DOF tracking device

text:
# Question
Title: Calibration of a 6 DOF tracking device
**Setting:** In our facility we have a 3D laboratory with 3 large displays (two edge-to-edge on orthogonal walls, one on the ground, also edge-to-edge). Its primary use-case is exploring 3D virtual environments. The control device is a Flystick, a 6 direction-of-freedom input device tracked by IR-cameras. One can query the stick's position in the room and its current orientation (rotation matrix).

**Goal:** I want to write a small tool which enables the user to use the stick as a pointing device to control the mouse cursor on the 3 screens.

**Challenge:** The stick does not have a pre-defined pointing direction. So even if I know its current rotation matrix I don't know which direction it is actually pointing at. That depends on its initial calibration (which may vary from application to application). So I need to figure out the stick's actual pointing direction on my own.

**Plan:** When starting my tool, I let the user point to the upper left corner of the first screen. Together with the current position of the stick I can calculate the pointing direction in the room's coordinate system. Now I transfere it into the stick's coordinate system by multiplying its inverse rotation matrix (at that moment) with that vector. This should give me the pointing direction in stick-space.

Now, if I want to determine the spot the user is pointing at for any other position & orientation, I need the stick's current position in room-space (check) and its pointing direction (also in room-space). To get that, I just need to apply the stick's current rotation matrix to the (stick-space) pointing vector which I determined during my calibration.

**Results:** So much for the plan. The calibration itself seem to work fine; and when only moving slightly from the screen corner the found pointing target seems to be reasonable. But when pointing for example on another screen, the results are totally wrong.

**It seems that the stick's pointing direction in room space is incorrect.**

Now the question is, is there a flaw in my approach? Did I miss something?

# Answer
> 0 votes
If you have the stick position and pointing direction, and if those are correct, one solution is to do a raycast.

Create a ray starting from your stick position (*O*) and expanding in its pointing direction (*D*), and test the intersections against your 3 planes. Check for instance this blog post for the math:

> We can \[...\] represent the path the ray takes as a parametric equation in t:
>
> We \[can write\] the plane equation in vector form as:
>
> The distance the ray has travelled when it hits the plane \[is\]:
>
> We can plug this value back into the ray equation to get the intersection point in 3D coordinates too.

The closest intersection (i.e. the smallest *t*) will determine which screen is touched, and your pointer position in room space.

You'll then have to transform that position from room space to this particular screen space. You can create a transformation matrix from screen space to room space, and use the inverse to transform your intersection point.

---
Tags: 3d, input, coordinates, transformation
---


# Question
Title: How to define a proper protocol for a turn-based combat system?
I'm working on the server side of a turn-based strategy game. The game has a really complex combat system, like:

> When you are hit, you summon a phoenix to attack the enemy that deals X damage, and the phoenix fly back to heal Y of your health.

Well, such skill does sounds interesting, but requires a great amount of work on the skill and combat system.

We did not use script on the server. We just split one skill into several skill effects. For instance, we have `DamageEffect`, `AddBuffEffect` and so on. However, we have a lot of skills like the phoenix stuff above, they can be triggered at a specific moment. And some of them even replace the main attack skill. So we designed several `SkillCondition`s for that. It worked, although not very well.

However, the question is: **For such a complex combat system, how to define the protocol between client and server?**

For example:

> A attacks B using skill X for 30 damage points. B uses the phoenix skill Y when he is hit that damage A for 20 points, and heals himself 10 points.

How can we express this to the client? We currently use a structure like this:

```
useSkillAction:
    skill: id_of_X
    source: id_of_A
    target: id_of_B
    subActions:
        damageAction:
            timing: onHit  // Timing means the the damageAction will trigger when the skill animation triggers a 'hit' event.
            character: id_of_B
            damage: 30
            subActions:
                propertyChangedAction:
                    timing: onFinished
                    character: id_of_B
                    property: health
                    value: health_of_B
                useSkillAction:
                    timing: onFinished
                    skill: id_of_Y
                    source: id_of_B
                    target: id_of_A
                    subActions:
                        damageAction:
                            timing: onHit
                            character: id_of_A
                            damage: 20
                            subActions:
                                propertyChangedAction:
                                    timing: onFinished
                                    character: id_of_A
                                    property: health
                                    value: health_of_A
                        healAction:
                            timing: onFlyBack??
                            character: id_of_B
                            damage: 10
                            subActions:
                                propertyChangedAction:
                                    timing: onFinished
                                    character: id_of_B
                                    property: health
                                    value: health_of_B

```

Well, I think you got the idea. For now, this structure can handle only simple skills. The solution currently have three problems:

1. For complex skills, like above, it's hard to describe the timing of phoenix fly back.
2. For the `onHit` timing in `damageAction`, that means **the server even knows that there's an animation trigger called 'hit'.**
3. It's hard to maintain.

Is there a better way to do this? Thanks anyway, for my broken English...

**EDIT**: As Petr suggested, I reduced the question to a simpler one:

**Is there a way to define the protocol so that server does not care about animation trigger stuffs like 'onHit'?** Because, generally speaking, server should only care about the logic.

# Answer
> 2 votes
It's hard to answer because the questions are pretty vague, since all the problems are not clearly specified. Basically you use the word 'hard', but not all things should be easy right? If the battle system is complex, then it's expected that it can be hard to maintain. Also 'hard' sometimes meas it's not wrong, just hard. If you feel it's wrong you should specifically show places which you think are.

As a pattern rule for similar complex sequences, you should try to minimize specifics and unify all actions as much as possible. I.e. you should eliminate `A_Something`, `B_Something`, `C_Something` and try to reduce it so some generic `Something` thus eliminating `switch`-like strictures for processing data. You can then define infinite sequences with simple structure like:

```
public class Action {
    // ...

    List<Action> subactions;
}

```

or even with a simple sequence `List<Action>`.

But again, this advice can be totally wrong, without more details. As suggest you to reduce this question to one, which troubles you most, and describe it carefully. Then you can create new questions if necessary.

As for updated question, it's still not very clear what is done on a server and what is on client. If client is a mere visualisation of a logic, it's necessary for a server to know such things as animation sequences, so it can tell a client how to animate battle. Can you clarify that aspect also? Also consider adding some client/server message processing code.

---
Tags: client-server, turn-based-strategy, combat, protocol
---


title: Horizontal scroll only part of the view

text:
# Question
Title: Horizontal scroll only part of the view
I would like to know the best way on how to implement horizontal scrolling to only part of the view and vertical scrolling to complete view. I was able to achieve horizontal and vertical scrolling to the complete view. If I have to use layers can you explain a bit more on how to achieve layers and draw shapes on those layers separately.

I tried using two different SurfaceViews it does not work. Here is my code for scrolling horizontally.

```
@Override public void onDrawFrame(GL10 unused) {

GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);

// Set the camera position (View matrix)
Matrix.setLookAtM(mVMatrix, 0, mXOffset, mYOffset, -3, mXOffset, mYOffset, 0f, 0.0f, 1.0f, 0.0f);

// Calculate the projection and view transformation
Matrix.multiplyMM(mMVPMatrix, 0, mProjMatrix, 0, mVMatrix, 0);

mGraph.draw(mMVPMatrix);

mLine.draw(mMVPMatrix);
msquare.draw(mMVPMatrix);

}

```

# Answer
> 1 votes
Turns Out My Emulator wasn't working fine but the answer is just have a new Model Matrix created for the buttons without the x offset value in the model matrix.

---
Tags: android, opengl-es2, side-scroller
---


title: Using OpenGL GLEW within Unity

text:
# Question
Title: Using OpenGL GLEW within Unity
**Edit:-**

How do I implement GLEW (or OpenGL extension libraries) within Unity?

**Original Question:-**

I've recently been looking into some really nice features of OpenGL 3.2 that I want to take advantage of in the development of a tech demo. One example being Geometry Shaders and Tessellation: now I know that OSX 10.8 already implements OpenGL 3.2 but not all of the functionality has been exposed, that is where GLEW comes in.

GLEW is a C/C++ extension... I have very limited C/C++ knowledge, would anyone be able to run through (in layman's terms) how to get GLEW working along side my C# Unity project.

# Answer
Unity is a higher level rendering engine which doesn't necessarily even use OpenGL for its rendering. (The default on Windows is DirectX, as far as I know.) But even if it did, extensions aren't usually things you can just 'switch on' and have it affect the rest of the system - the system usually has to be built in such a way as to make use of the extensions. So really you need to check which features Unity supports, without reference to OpenGL specifically.
> 5 votes

---
Tags: opengl, unity
---


# Question
Title: How do I simulate a crowd in the stadium stands?
I'm working on a mobile sports game with Unity. I'm wondering how I could create an efficient effect of an audience in the stadium.

I know that with more than 15 characters in my games (with 1800 faces and 20 bones) the game slows down, so I guess that even with a small number of bones, using 3D characters for even the first row of seats isn't feasible... Would you have some tips on how to do this another way?

I have also tried to "paint" them, and add a blur effect, but the result is not very good...

# Answer
> 4 votes
If it's for mobile devices, as in phones, then making the public as individual characters (even really low poly ones) is out of the question. Not only will it bog down the limited resources of the device, but no one will notice such detail on such a small screen.

My best bet would be an animated texture. Or multiple animated textures, where you have one for "idle" (not much happening in public, just small isolated motions), one for "cheering" (all public moves wildly), etc. And then you display then accordingly on a plane which represents the public's geometry.

Now, in order to obtain the animated texture you could do a bunch of repeated textures on plains, have them animate (like raise them a bit for crowd standing up, move some around for crowd fussing about, etc) and then create pre-rendered textures out of these.

Or I guess you could use some actual public footage which you can tile about and create animated textures out of that.

# Answer
> 2 votes
**Fake it**.

In a mobile game, this is an unimportant detail. Most of the screen will be dedicated to the action. This is my suggestion:

If the player is playing:

* Crowd should appear a few meters away from the playable part of the field (to account for out of bounds space), camera should not be able to move directly up to them in this situation.
* Crowd will drawn either using a single plane or a layered group of 2 - 5 planes (geometry consists of 2 to 40 triangles).
* Crowd animations are handled through a set of animated textures which should consist of only a few (no more than maybe 10) low resolution images per animation. These animations can be tiled on the planes to reduce image size and memory usage at the expense of the CPU or GPU.
* Animations should change based on a crowd state enum that is set after player events (such as scoring, missing a shot, or bad over all performance) animations can include things like happy idle, angry idle, celebrate, rage, rage quit.

(Optionally) When an important player event is triggered:

* If player is to do some sort of action that deserves special attention, the camera may move to the crowd (move should be quick fade out and in so that the player cannot see the swap between a fake crowd and a character model crowd).
* When camera moves to the crowd, it actually moves to a separate part of the game (not near the field more like a room). The only things to be drawn in this scene are the area surrounding (like bleachers and a skybox) the character model crowd, and the character models for people in the crowd (which should be limited based on your hardware, preferably no more than 10 at most).
* Since the full crowd is only drawn when the game is at a standstill (player is paused during the animation) the game logic only needs to update and draw the full crowd until animation is complete. After animation is complete the full crowd moves to an inactive state and is not updated or drawn again until another important player event is triggered.

*To summarise*: Fake the crowd with a simple 2D sprite until the player does something important (scores an amazing goal, injures another player, or whatever important events happen in your game). By only showing a 2D sprite during active game play, the overhead of an in-game crowd is reduced. As long as you show a more detailed 3D version of the crowd during an event, you can trick the player into thinking the crowd is full 3D at all times. Make sure not to draw or update the full crowd and the actual game at the same time, else any performance gains from faking it will be lost.

---
Tags: 3d, unity, performance, mobile
---


title: Rotating 3d plane to XY plane

text:
# Question
Title: Rotating 3d plane to XY plane
I have a triangle in 3d space and would like to create a grid over the triangle, such as in the image below.

The purpose of this is to store information about each block of the grid. In order to store this grid in a 2D array, my idea was to rotate the triangle until it is in the XY plane. After rotation the above triangle would look like the image below.

What I have tried to do is find the angle between the triangle's normal and the z-axis, then rotate each vertex by this amount.

```
    public double getAngle(Vector3 normal, Vector3 axis) {
        double dot = normal.dotProduct(axis);
        double angle = Math.acos(dot / (normal.getMagnitude() * axis.getMagnitude()));
        System.out.println("angle = " + Math.toDegrees(angle));
        return angle;
    }

    public static void main(String args[]) {
        Vector3 pointA = new Vector3(0,0,0);
        Vector3 pointB = new Vector3(5,5,5);
        Vector3 pointC = new Vector3(-5,5,5);
        Triangle tri = new Triangle(new Vector3[]{pointA, pointB, pointC});
        Vector3 normal = tri.normal();
        normal.normalize();
        Vector3 zAxis = new Vector3(0, 0, 1);
        Matrix4x4 rot = Matrix4x4.getRotationMatrix(0, 0, patch.getAngle(normal, zAxis));
        for(int i = 0; i < tri.vertices.length; i++) {
            tri.vertices[i] = rot.multiply(tri.vertices[i]);
        }
    }

```

The result of this code would be:

```
Triangle's normal: (0.0, -50.0, 50.0)
Normalized normal: (0.0, -0.7071067811865475, 0.7071067811865475)
Vertices after rotation:
   (0.0, 0.0, 0.0)
   (4.440892098500626E-16, 7.0710678118654755, 5.0)
   (-7.0710678118654755, 4.440892098500626E-16, 5.0)

```

This is not quite right, though. I am expecting all z-coordinates to be the same so that I can ignore them and store the grid in a 2d array. Is there something else I need to do to rotate the triangle appropriately, or is there a simpler way to store this grid? If needed, the code for my rotation matrix is below:

```
private static Matrix4x4 getRotationMatrix(double x, double y, double z, boolean inverse) {
    double sign = (inverse) ? -1 : 1;
    Matrix4x4 rotateX = new Matrix4x4(new double[][]{
            {1, 0,             0,            0},
            {0, Math.cos(sign * x), -Math.sin(sign * x), 0},
            {0, Math.sin(sign * x),  Math.cos(sign * x), 0},
            {0, 0,             0,            1}
    });
    Matrix4x4 rotateY = new Matrix4x4(new double[][]{
            { Math.cos(sign * y), 0, Math.sin(sign * y), 0},
            { 0,            1, 0,            0},
            {-Math.sin(sign * y), 0, Math.cos(sign * y), 0},
            { 0,            0, 0,            1}
    });
    Matrix4x4 rotateZ = new Matrix4x4(new double[][]{
            {Math.cos(sign * z), -Math.sin(sign * z), 0, 0},
            {Math.sin(sign * z),  Math.cos(sign * z), 0, 0},
            {0,             0,            1, 0},
            {0,             0,            0, 1}
    });
    Matrix4x4 rotation = rotateZ.multiply(rotateY).multiply(rotateX);
    return rotation;
}

```

# Answer
> 3 votes
The rotation-axis is not the z-axis, it is the cross product of the normal of the triangle and the z-axis:

```
rot_axis = normalize(cross(axis_z, triangle_normal))

```

the rot\_angle that you already calculated:

```
rot_angle = acos(dot(axis_z, triangle_normal))

```

Now we have the Axis-Angle of the rotation. You can convert it to a matrix using Matrix4x4::CreateFromAxisAngle

---
Tags: java, matrix, rotation
---


# Question
Title: Can't get normals to work correctly with lighting in OpenGL
I'm trying to light up a simple 2d triangle with my cursor as a diffuse light source but can't seem to set the normal correctly for the lighting to look right. The function that calculates the normal (m3dFindNormal) comes from the OpenGL Superbible (math3d.h) which takes 3 points on a plane and determines the cross product of 2 vectors from those points. Since this doesn't return a normal of length 1 I then call m3dNormalizeVector3 to get a normal vector of length 1. I then set the normal for the triangle using glNormal to that vector and draw the triangle. Using this code the triangle never lights up at all but when I comment out the glNormal call it lights up on the vertices so something must be wrong with the normal.

```
glShadeModel(GL_SMOOTH);
GLfloat diffuseLight[] = {0.9f, 0.9f, 0.9f, 1.0f};
glEnable(GL_LIGHTING);
glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuseLight);
GLfloat lightPos[] = { x, y, 1.0f, 1.0f }; //x and y are the cursor's position
glLightfv(GL_LIGHT0, GL_POSITION, lightPos);
glEnable(GL_LIGHT0);
glEnable(GL_COLOR_MATERIAL);
glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
glColor3f(0.75f, 0.75f, 0.75f);
glBegin(GL_TRIANGLES);
    M3DVector3f vPoints[3] = {{ SCREEN_WIDTH / 2 - 40, SCREEN_HEIGHT / 2 + 40, 0},
                              { SCREEN_WIDTH / 2 + 40, SCREEN_HEIGHT / 2 + 40, 0},
                              { SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2, 0}};
    m3dFindNormal(vNormal, vPoints[0], vPoints[1], vPoints[2]);
    m3dNormalizeVector3( vNormal );
    glNormal3fv(vNormal);
    glVertex3fv( vPoints[0] );
    glVertex3fv( vPoints[1] );
    glVertex3fv( vPoints[2] );
glEnd();

```

I know the light works because things light up when I move the cursor around but they light up at the wrong times. Anyone know what I'm doing wrong?

# Answer
> 3 votes
This was calculating a normal vector of {0,0,-1.0f} instead of {0,0,1.0f} and my light was placed on the positive z-axis. Simply changing the light position to be placed at {x,y,-1.0f} instead of {x,y,1.0f} fixed the problem.

---
Tags: opengl, lighting, normals
---


# Question
Title: How was the Castle Crashers game for X-box made?
The graphics and animations for Castle Crashers were definitely made with Adobe Flash. But as far as I know X-box doesn't directly support Flash and Adobe Air technology. I love flash for 2D game development and I wonder how to do the trick. And an additional question: are there easy-to-use libraries for adding gamepad support to Adobe Air app.

# Answer
So it looks as though the game was designed and made in flash and then the guys at Newgrounds wrote a custom parser and renderer in c++ to run on the xbox (source: http://www.newgrounds.com/bbs/topic/1034102). However, to do this in general, it is possible to render the vector graphics from the flash files in a 3D renderer (After parsing and triangulation/etc of course). This is not something that would necessarily be easy for one person to do, but it is not impossible and it should be able to be done with XNA with enough dedication.
> 1 votes

---
Tags: flash, xbox360, xbox-controller, flash-develop
---


title: Storing items in external data files

text:
# Question
Title: Storing items in external data files
My project, in its current state, keeps all of the info for each inventory item in script files. That means, inventory items and their properties are part of the codebase. This works well, but I'm advancing quickly through development and I fear that this system is going to pose some problems later on. Normally, data (item properties) are not stored in the code, but in some sort of database.

I was thinking about storing item properties in external (text for now) data files, that would get parsed when the game loads. I'd mark each item with a string ID (for easier referencing in other places - **GetItemWithID("FOOD\_FISH")** makes more sense than **GetItemWithID(5)**). Then, I'd build some sort of class that would take care of item-driven events (such as what happens when an item is consumed). Then I'd map each function implemented by the manager to some interpretable string counterpart (in an item's data file I'd have the string "RestoreHealth(50)" - this would be mapped by the manager to the function RestoreHealth (the param would get passed too)).

Is this an even remotely good idea? How would you do it?

Another thing that I'm thinking of, since I'm building a tool to make inventory item creation easier, is to develop something that simply generates appropriate C# code for an underlying database of user-readable and editable item properties.

E.g. it takes in

```
FOOD_FISH
Name:Fish
Value:50
OnConsume:
RestoreHealth(40)

```

and generates

```
FoodFish = new InventoryItem();
//Properties set here.

```

**LATER EDIT:**

After Byte56's reply, I came up with a kind of format that's easy enough to parse.

```
[ID:IT_FO_TROUT]
[Name:Trout]
[Description:A raw trout.]
[Value:10]

[3DModel:null]
[InventoryIcon:trout]

[Tag:Consumable]
[Tag:Food]
[Tag:Stackable]

[OnConsume:RestoreHealth(15)]
[OnConsume:RestoreFatigue(15)]

```

Since on the project there will be people with no programming experience working remotely, using external files + custom item generators seems to be the best way to go. Should've figured it out earlier.

# Answer
Yes, storing the items in external files is a good idea. I created something very close to what you're talking about. It's an item/entity lexicon. Items, materials and entities are all stored in this "database". The script files get read on load and store every item available in game.

You can see kind of an example of what the entity files look like here.

The format of the script is up to you. You may want to use XML or some other common script, or you can make your own like I did or what it looks like you've started to do.

When the items are read in, they go into an item blueprint class. This class has all the required information for generating a new item. It also allows each item some variation. As you can see in my other answer, I define ranges of acceptable values. When the item is created it will choose a random value from within the range defined, giving each item a slightly different quality/value/whatever.

All those blueprints are stored in a `HashMap`, a `Dictionary` for C#. The ID is the key and the value is the blueprint. I also have the keys in a `HashMap` that's referenced by the item name. This makes it easier for me if I want to create a specific item, and I don't remember the name. For example I have an apple defined:

```
MATERIAL:"Apple" {
        description="An apple, a tasty fruit"
        commonName="Apple"
        pluralCommonName="Apples"
        tags=Fruit,Edible
        basetype=CulinaryFruit
        qualityrange=0.2:1.0
        itemtextureindex=10
        value=15
        density=20.0
        entityBaseAttributes="Small Physics Item","Slow Decay"

        HarvestItems{
                HarvestItem{
                        material="Apple seed"
                        TimeToCollect=200:500
                        WeightedChance=1
                        MinConditionToProduce=0.3
                        OverrideQuality=1.0:1.0
                }
                HarvestItem{
                        material="Apple core"
                        TimeToCollect=200:500
                        WeightedChance=1
                        MinConditionToProduce=0.3
                }
        }
}

```

Where `Apple seed` and `Apple core` are also items defined in the script. So if I want to create an apple somewhere, I have a method that takes the information above and generates the properties of an entity. Including some predefined standards like "Small Physics Item" and "Slow Decay" which add attributes to the entity being generated.

It's a pretty flexible system that allows me to quickly generate new items. And it's easy to use, because I don't actually even need to know the IDs of anything, I can reference them by name. I also have an entity named "Apple Tree" that has a `ProduceItems` attribute that generates `Apple`.

All in all, yes, it's a good idea to put your items in scripts. And with a little work, you can create some very complex behaviors and items with your item scripts.
> 3 votes

---
Tags: c#, rpg, data-structure
---


# Question
Title: OpenGL GL_TRIANGLE_STRIP creating grid with degenerate triangles / for one draw call
I need to create a grid ready for GL\_TRIANGLE\_STRIP rendering with **One** drawcall - so i need to degenerate the triangles.

I am almost there but missing last row/column and can't figure out why.

My **grid** is just a :

* Position ( self explanatory )
* Size ( the x,y size )
* Resolution ( the spacing between each vertex in x,y )

Here is the method used to create verts/indices and return them:

```
int iCols = vSize.x / vResolution.x;
int iRows = vSize.y / vResolution.y;

// Create Vertices
for(int y = 0; y <= iRows; y ++)
{
    for(int x = 0; x <= iCols; x ++)
    {
        float startu  = (float)x / (float)vSize.x;
        float startv  = (float)y / (float)vSize.y;

        tControlVertex.Color    = vColor;
        tControlVertex.Position = CVector3(x * vResolution.x,y * vResolution.y,0);
        tControlVertex.TexCoord = CVector2(startu, startv - 1.0 );

        vMeshVertices.push_back(tControlVertex);
    }
}

// Create Indices
rIndices.clear();

for (int r = 0; r < iRows - 1; r++)
{
    rIndices.push_back(r*iCols);

    for (int c = 0; c < iCols; c++)
    {
        rIndices.push_back(r*iCols+c);
        rIndices.push_back((r+1)*iCols+c);
    }
    rIndices.push_back((r + 1) * iCols + (iCols - 1));
}

```

And to visualise that, few examples first.

1) Size 512x512 Resolution 64x64, so it should be made of 8 x 8 quads, but i get 7x7 only

2) Size 512x512 Resolution 128x128, so it should be made of 4 x 4 quads, but i get 3x3 only

3) Size 128x128 Resolution 8x8 so it should be made of 16 x 16 quads but i get 15x15 only

So as you can see, i am missing the Last Row and Last Column somewhere. Where am I going wrong?

# Answer
> 0 votes
Ok, i have solved this. I think we're all getting old, that's why we couldn't spot it.

Here is the code:

```
    // Create Vertices
// Notice <= to create exactly as many vertices in X and Y as required
for(int y = 0; y <= iRows ; y++)
{
    for(int x = 0; x <= iCols; x++)
    {
        float u  = (float)x / (float)vSize.x;
        float v  = (float)y / (float)vSize.y;

        tControlVertex.Color    = vColor;
        tControlVertex.Position = CVector3(x * vResolution.x, y * vResolution.y,0);
        tControlVertex.TexCoord = CVector2(u, v - 1.0 );

        vMeshVertices.push_back(tControlVertex);
    }

}

// Create Indices
rIndices.clear();

// Create Indices with degenerate triangles ( stitching )
// Notice < iRows, <= iCols
for (int y = 0; y < iRows; y++)
{
    // Degenerate first triangle in this column
    rIndices.push_back((unsigned short)((y + 0) * (iCols+1) + 0));

    for (int x = 0; x < iCols + 1; x++)
    {
        // Vertex in actual row
        rIndices.push_back((unsigned short)((y + 0) * (iCols+1) + x));

        // Vertex row below
        rIndices.push_back((unsigned short)((y + 1) * (iCols+1) + x));
    }

    // Degenerate last triangle in this column
    rIndices.push_back((unsigned short)((y + 0) * (iCols+1) + iCols+1));
}

```

And the results are:

512x512 with Resolution of 64x64 ( called stepping ) produces 8\*64 x 8\*64 = 512x512.

Thanks CiscoIPPhone for looking into this.

# Answer
> 2 votes
If iCols is 10, then 11 horizontal vertices are created:

```
for(int x = 0; x <= iCols; x ++)

```

When creating the last column of indices you do:

```
rIndices.push_back((r + 1) * iCols + (iCols - 1));

```

We can ignore the first part to just concentrate on a single row:

```
rIndices.push_back(iCols - 1);

```

(iCols - 1) would be 9, so it's not going to address the last vertex (10). I think to fix the problem with columns you should remove the -1.

To fix the problem with the amount of rows change

```
(int r = 0; r < iRows - 1; r++)

```

to

```
(int r = 0; r < iRows; r++)

```

Because the difference between y \<= iRows; and r \< iRows - 1 is two, but there should only be one more vertical vertex than there are rows.

---
Tags: opengl-es, opengl-es2
---


title: Depth Stencil buffer mandatory?

text:
# Question
Title: Depth Stencil buffer mandatory?
If I disable depth and stencil buffering, do I have to create and set the depth stencil buffer?

# Answer
You do not, calling `ID3D11DeviceContext::OMSetRenderTargets` with the DepthStencilView parameter being a null pointer is perfectly valid, and you can still draw fine:

No Z-Buffer used http://dl.dropbox.com/u/21007284/tris.png

Obviously though, whatever you drew last will be drawn on top of everything else, regardless of its actual Z position - the colorful triangle in the image is behind the white one, but was drawn last.
> 4 votes

---
Tags: directx11
---


# Question
Title: How to implement input-texture limited alphablending of 2 textures with HLSL?
I try to implement a HLSL shader the does the normal Alphablend with premultiplied colors (just as XNA4 does) but depending on some existing colors. One can think of adding a glow to a 2D terrain where the glow should only be applied to the not fully transparent parts of the terrain.

My current code is:

```
sampler TextureSampler1 : register(s1); // Addition (Terrain-only particles)
sampler TextureSampler2 : register(s2); // Existing (Terrain)

float4 main(float4 color : COLOR0, float2 texCoord : TEXCOORD0) : COLOR0
{
    // Look up color from partly transparent existing texture (premultipied colors)
    float4 existing = tex2D(TextureSampler2, texCoord);

    // For transparent pixels -> Color stays the same
    if ((existing.r + existing.g + existing.b + existing.a) == 0) return existing;

    // Look up color from partly transparent addition-texture (e.g. glow) (using premultipied colors) that should be added to existing color
    float4 addition = tex2D(TextureSampler1, texCoord);

    // Rescale light that is added by existing alpha
    addition.rgb *= existing.a;

    // Use this color to blend
    existing.rgb *= (1 - addition.a) + addition.rgb;

    return existing;
}

```

However, there still seems to be a problem with the alpha channel. Any ideas?

# Answer
> 1 votes
Your line:

```
existing.rgb *= (1 - addition.a) + addition.rgb;

```

does

```
existing.rgb = existing.rgb * ((1 - addition.a) + addition.rgb);

```

what you probably wanted is

```
existing.rgb = existing.rgb * (1 - addition.a) + addition.rgb;

```

# Answer
> 0 votes
Interestingly, the following code works. But why?

```
float4 main(float4 color : COLOR0, float2 texCoord : TEXCOORD0) : COLOR0
{
    // Look up color from partly transparent existing texture (premultipied colors)
    float4 existing = tex2D(TextureSampler2, texCoord);

    // For transparent pixels -> Color stays the same
    if ((existing.r + existing.g + existing.b + existing.a) == 0) return existing;

    // Look up color from partly transparent addition-texture (e.g. glow) (premultipied colors) that should be added to existing color
    float4 addition = tex2D(TextureSampler1, texCoord);

    float4 output;

    // Keep light blocking properties
    output.a = existing.a;
    // Rescale light that is added by existing alpha
    addition.rgb = addition.rgb * existing.a;
    // Use this color to blend
    output.rgb = existing.rgb * (1 - addition.a) + addition.rgb;

    return output;
}

```

---
Tags: xna, shaders, hlsl, fragment-shader
---


# Question
Title: Filtering (e.g. Gauss blur) on seamless textures but without border artifacts?
I am looking for a way to apply (Photoshop, Gimp etc.) filters to seamless textures without the usual border artifacts. The kernel of the Photoshop Gauss filter for example does not wrap around the image (which in non-seamless cases is surely also not wanted) but shows severe artifacts at the borders. Is there any way around this?

# Answer
> 7 votes
Just fake the wrapping (I assume we're talking about working in Photoshop/Gimp and not doing it at runtime in a game):

* Depending on your editor there might be an easier way to do this.
* Double the size of the canvas while keeping the original image in the center (i.e. don't scale it).
* Copy/tile the actual texture to fill the (still blank) space outside the original image.
* Apply the filter.
* Downsize the canvas again to the original size, keeping the image aligned to the center.

# Answer
> 0 votes
Here's what I do: Duplicate your image into two layers, then on one of the layers use Filter\>Other\>Offset half the width and height. Apply your Gauss filter to each layer, offset the layer by half again, and *use the eraser on the top layer* to blend them together.

Edit: Make sure you use the Wrap Around option in the Offset filter.

On the top left is my original image. Top right is the top layer after applying an offset and then using Gaussian Blur. Bottom left shows the re-offset top layer with the erased area highlighted in red. On the bottom right is the final image.

---
Tags: 2d, graphics, image, gimp
---


# Question
Title: How long would it take to learn c# if I know c++?
I already know c++, having worked through Accelerated C++ reading all the chapters and doing all the problems, with a bit of college coursework in C++ as well.

From what I read, I seem to have learned the harder of the two languages first. My question is, how fast could I pick up C#? I'm looking for a job and an awful lot of companies want experience with .Net framework and/or C#.

Are we talking another few months, or could I reasonably start programming in C# within a week? I've got experience picking up new languages quickly, and I'm familiar with C, a little Java, Haskell, and Prolog.

# Answer
> 0 votes
This would probably be more suited for programmers.stackexchange.com I guess, but basically it's just some added knowledge, based on what you're supposed to do (like GUI programming in Windows Forms or WPF. Overall, I'd say you should be able to get the required basics in a few hours, especially if you've worked with STL classes such as `std::string` in the past. There are some added concepts and language constructs (especially if you plan on using LINQ as well), but overall I'd say you should be able to understand and train most generic concepts in a few weeks or just a few days (depending on how fast you learn, what you learn, etc.). Getting some simple UI program to run should be doable within a few hours though.

---
Tags: c++, c#
---


# Question
Title: Heightmap VS actual model of environment
I've been looking at 3D environments for games and I would like to know (case by case) which would be the best fit for development. The types in question are between **heightmaps** or a **model of an environment** (created in Maya, Max, etc). And when I say "environment," I mean "the ground the player walks on (street, hill, valley, etc).

Here are the scenarios based off of actual games:

1. **Red Dead Redemption** \- massive open world
2. **Gears of War** \- smaller/confined world and linear navigation; urban + natural
3. **MW3** \- small world; urban-oriented

Which is the best fit for developing the ground for each of these games?

*Keep in mind that these games have varying degrees of slopes.*

**Update**

1. This is not a coding problem. This is a design problem.
2. I'm not asking how the above games were codes. I'm asking about the environment "style of whether it would be best to use a height map or model the environment (terrain) entirely within a 3D editor.

# Answer
Most games (I guess all you listed) combine both approaches to reduce the amount of data to process and render.

Using one huge model is very costly, because you'll always have to draw everything (or do lots of culling calculations).

Due to this, the probably most often used approach is drawing the raw map using one or more heightmaps (to improve performance, you'd most likely split this into "cells").

In addition, these cells are decorated with more detailed and modeled objects, such as rocks, cliffs, bridges, houses, etc.

When drawing, you can then restrict yourself to only draw the heightmap of the current (or neighboring) cells as well as all their objects. Recent and popular examples would be games such as Skyrim or Far Cry 3.

This approach will be less attractive if you plan on doing things like indoor maps. Brush based drawing, e.g. as done by Valve's Source engine are more suited for something like this. Overall they'll still do the same thing: Use the rough drawing (brushes here) to create the map, objects to decorate it.

So in short: Always try to get your general map layout done with some simple method. Keep this simple, because this will be fast and allow you to cull other elements (e.g. using depth buffers, cell hierarchy, etc.). Then add the details.
> 0 votes

---
Tags: 3d, game-design, models, heightmap
---


title: How to create 2D textures from footage?

text:
# Question
Title: How to create 2D textures from footage?
I am new to game development but I heard, that already in the 80s with Prince of Persia, indie developers where capable to create textures from footage. I am developing a game and so far I get an illustrator to draw things I need.

I'd like to explore the opportunity of taking some video footage of complex movements and create some basic textures from it (as I guess Jordan Mechner did), so to then "feed" them to a more digital artist to draw "over" them in order to make them cartoonish and coherent with the style of the pre-existing in the game.

Anyone of you could also explore the answer for mobile game development? Any crazy mobile developer that did so already for a 2D game? :)

# Answer
The technique is called rotoscoping. It does lead to very fluid movement. Yes, you could use it for any game platform (in theory), but to get the full benefit of the style it's best used with a *lot* of frames.
> 1 votes

---
Tags: textures, animation, mobile, video
---


title: Proper vertex buffer use

text:
# Question
Title: Proper vertex buffer use
How're you supposed to use vertex buffers?

Say you have 500 distinct **deformable** shapes/models in the world (ie you want to be able to change/delete vertices from the models somewhat arbitraily as the game progresses). The requires you refresh the vertex buffers in the frames the model has become dirty, *at least*.

So how should you handle your vertex buffer, assuming D3D11 interfaces (so vertex buffers are **your only option** to draw anything):

* Store model vertices in CPU RAM. Create one vertex buffer at program start. For each model, copy the vertices into the single vertex buffer, render
* Create 500 vertex buffers, update each when necessary, render.

# Answer
> 2 votes
At the bottom of this article, there are references to how to make dynamic vertex buffers.

http://msdn.microsoft.com/en-us/library/windows/desktop/ff476899(v=vs.85).aspx

This particular solution is "supposed" to dynamically "optimize" itself based on how frequently you are updating the vertices, etc. In other words, just let the DirectX API manage it for you.

I have had a similar problem rendering chained deformations where one object's deformation affects another, and so on, until it becomes cyclical.

In this case, maintaining the original vertex points is completely useless.

However, if your deformable objects retain somewhat of their original shape, you may be able to rely completely on geometry shaders, or other types as you need, and not have to update the vertices.

Without knowing your particular scenario, and the extent of the deformations, relative interval of the deformations, a specific architecture is pretty much impossible to recommend.

HTH.

---
Tags: directx11, vertex
---


# Question
Title: Vector3 vs. Vector2 - performance, usage?
I'm currently playing around with XNA, and creating a simple 2D platformer. I was thinking of adding multiple layers to make it a little bit of challenge.

In stead of having a `Vector2` for my positions, I now use a `Vector3`, solely to use it's `Z` as layer depth. However, since you can't use operators between `Vector2` and `Vector3` for some unknown reason **\[1\]**, I ended up changing all other `Vector2`s in my game, such as *acceleration*, *speed* and *offset*, so I can do things like `position += offset` without errors.

I also changed my rotation variable from `float` to `Vector3`, and I use the `Z` value to rotate my textures. I'm planning to use the `X` and `Y` to scale-flip my textures, so you get the Super Paper Mario effect.

However, after changing all these `Vector2`s in `Vector3`s, I felt a little bad about it. How does this effect the performance of games? I know I shouldn't have to worry about performance in my little platformer game, but I'm just curious about it.

Is there any notable performance between `Vector2`s and `Vector3`s, for example when adding or multiplying them, or when calling `Normalize`, `Transform`, or `Distance`?

---

**\[1\]** Just a side question, why are there no operators for calculations between Vector3 and Vector2?

# Answer
> Is there any notable performance between `Vector2`s and `Vector3`s, for example when adding or multiplying them, or when calling `Normalize`, `Transform`, or `Distance`?

Yes, you have one more coordinate so you will use more CPU cycles.

But it is very unlikely that it will ever give you any trouble. XNA 4 is using SIMD extensions for vector math (EDIT: **on Windows Phone only**), so the implementation is very optimal (on that platform). Except if you're doing very heavy computing, it is very unlikely to ever cause you trouble. You do need `Vector3`s for your positions because you're now doing 3D (or 2.5D...), so please don't do any premature optimization. This is **97% evil**1.

> Just a side question, why are there no operators for calculations between Vector3 and Vector2?

Because it makes no sense, mathematically. What would you expect to come out from such calculations? For instance what should happen if you try to add a `Vector3` and a `Vector2`:

\[*x1, y1, z1*\] + \[*x2, y2*\] = \[*x1 + x2, y1 + y2, z1*\] **or** \[*x1, y1 + x2, z1 + y2*\] ?

In this case, you'll typically need to determine by yourself what you want as a third coordinate for the `Vector2`, and where you wish to add it. For instance this solves the ambiguity:

\[*x1, y1, z1*\] + \[*x2, y2,* **0**\] = \[*x1 + x2, y1 + y2, z1*\]

---

Now it's possible that some parts of your gameplay work only in 2D. If there are cases where you only need 2D coordinates, and if the computing *does* get really heavy (e.g. 2D physics), you can stick to `Vector2`s in that specific part of the code to save some precious cycles. You can then easily switch between 2D and 3D coordinates when you need to (e.g. get a scene position from a 2D physics position, or the other way around):

E.g. from `Vector2` to `Vector3` using this constructor:

```
Vector2 v2;
Vector3 v3(v2, someDepthValue);

```

Or from `Vector3` to `Vector2` using that constructor;

```
Vector3 v3;
Vector2 v2(v3.X, v3.Y);

```

---

1In Donald Knuth's words:

> Programmers waste enormous amounts of time thinking about, or worrying about, the speed of noncritical parts of their programs, and these attempts at efficiency actually have a strong negative impact when debugging and maintenance are considered. We should forget about small efficiencies, say about 97% of the time: **premature optimization is the root of all evil**. Yet we *should* not pass up our opportunities in that critical 3%.
> 13 votes

# Answer
You're trying to optimize prematurely. Most of the operations you mentioned ( normalize, transform, distance ) are pretty much identical to what vector2D does, if you can look at their code you will notice that they are practically the same. The only difference is that vector3D has a third axis. Performance wise it should be trivial compared to a Vector2D.

As for your side question:
Because you can't multiply matrixes/row-vectors/column-vectors that both have different sizes.
> 3 votes

# Answer
One of the biggest performance effects of using `Vector3` unnecessarily, instead of `Vector2`, is the 50% increase in size and **the effect that has on cache**.

That unnecessary extra data needs to be loaded into the CPU cache from main memory. This is *sloooow*.

In addition, by loading in this unnecessary data, you increase the chance that you are pushing out *useful* data that then immediately has to be loaded *back into* cache.

In a modestly tight loop, the cache effects will overwhelm any CPU effects of doing extra operations.

Also, it's faster to add the elements directly (due to various quirks of .NET). So if you're micro-optimising you won't be using the vector operations anyway. So if you only need to add the first two elements of a vector, you could do this:

```
v1.X += v2.X; v1.Y += v2.Y;

```

But these kinds of performance considerations are only really applicable to things like particle engines, physics engines, and so on. So don't worry too much!
> 1 votes

---
Tags: xna, xna-4.0, performance, vector
---


# Question
Title: What are the rest of the blending functions used for?
In general, I know of five ways to make use of blending functions (these are for OpenGL, but replace `glBlendFunc()` with `SetRenderState(D3DRS_SRCBLEND)` and `SetRenderState(D3DRS_DESTBLEND)` for DirectX):

`glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)`: Alpha blending (not premultiplied)

`glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA)`: Alpha blending (premultiplied)

`glBlendFunc(GL_ONE, GL_ONE)`: Additive blending

`glBlendFunc(GL_ZERO, GL_SRC_COLOR)`: Multiplicative blending

`glBlendFunc(GL_DST_COLOR, GL_SRC_COLOR)`: 2x Multiplicative blending (somewhat obscure)

But there are so many other values you can use when setting your blending function, and not only I've never seen them in use, but also have no idea what they could be used for. In particular, I don't see what `GL_DST_ALPHA` could be used for.

What the rest of the blending functions used for?

# Answer
> 5 votes
You have to stop thinking of blend equations (and *any* graphics mechanism or tool) as "what it looks like." Blend equations are not "additive", "multiplicative" or anything of the sort. The blend equations *do math*; that's all they do.

The question is how you *use* that math to achieve a desired visual effect. The limits are your imagination. If you can't see how these could be used, then it's a problem with your vision, not the tool.

Destination alpha, for example, can be used for various effects. Certain objects in a scene can lay down alpha, and later, you can use this alpha in a blend equation as a key to whether you show some overlaying effect. Thus, this overlay is visible only on certain objects, and only to various degrees based on that alpha.

---
Tags: xna, opengl, graphics, directx, blending
---


title: How to store data in a data-driven RPG

text:
# Question
Title: How to store data in a data-driven RPG
> **Possible Duplicate:**
> Would it be better to use XML/JSON/Text or a database to store game content?

I'm working on a 2D data-driven RPG. I intend for it to be modabble; my intention is to expose all the major game data (eg. monster stats, item stats, pet stats) through some interface to allow tweaking by end-users with a tool.

First, my basic assumption is that there will be a "lot" of data (perhaps on the order of magnitude of megabytes). I have a few requirements that I'm trying to figure out.

* How to efficiently store and load the data. For example, a SQLite DB would be faster than reading text files on startup.
* How to make it version-control friendly (text-files wins here).
* How to maintain data integrity. If it's just a text-file, you can put invalid values in it.
* If possible, I would like to allow users to make their own tools to crunch my data.

Since maintaining version-control friendly data is important, I think having one or more text files with data in it will win. I can probably try to get people to use my tools to edit the data, and put lots of integrity checks in the actual code (eg. `if totalHealth < 0, throw`).

Are there better approaches to achieve these four goals?

I would also like input on the file format (eg. YAML vs. XML vs. JSON vs. whatever)

# Answer
> For example, a SQLite DB would be faster than reading text files on startup.

That's an interesting assumption. Opening it might be faster, depending on the size of the text file. But *reading* it is another matter altogether. If all your startup code does is open the file and read a couple of entries out, then it would be faster. But if you're reading the entire thing into memory, then a DB is going to be slower than the text file.

Not unless you write your own parser, or use a bad parser framework.

And of course, once it's in memory, finding the data for monster X will be faster than an SQLite DB. Assuming you use an appropriate data structure.

This is the only requirement that would suggest using an SQLite DB, so you probably shouldn't use that.

Lastly, remember that SQL databases are designed and optimized for complex searching for stuff. If all you're searching for in your DB is a monster by name or something, you're really using an over-designed tool for the job.

> How to maintain data integrity. If it's just a text-file, you can put invalid values in it.

If you are going to allow your users to directly modify game data *without* forcing them to use a specific tool, then you're going to have to accept that users can do the wrong thing. With great power, comes great opportunity to *abuse* that power.

So your options are to "force" users to use a specific tool (which would require some form of encryption on your data file. It won't stop dedicated hackers, but the hoi polloi will be warded off), or to do integrity testing at load time. Or you could split the difference.

Let users edit text files however they please, but you introduce a "build mod" step between the text and your game. They have to run some command line tool that converts their text files into your game data. That's where integrity testing goes. You could also optimize your data in such cases, if text parsing is really that big of a turn-off for you. Of course, this makes it a bit more difficult to use, thus slightly slowing down turnaround time between editing the game data and seeing a change.

> If possible, I would like to allow users to make their own tools to crunch my data.

That's a lot less viable for SQLite DBs. Especially if you add integrity check expressions. And it becomes much harder if those integrity expressions require functions that only your code exposes; that last part makes it impossible for someone to use their own SQLite tool without linking to a library of yours for the interface.

> I would also like input on the file format (eg. YAML vs. XML vs. JSON vs. whatever)

That's dealer's choice. However, XML has one significant advantage (beyond being the most prevalent and de facto lingua franca of textual data storage): XML schemas can do integrity testing for you, for simple cases. There are even schema-guided editors that can help prevent users from doing the wrong thing at edit time.

I'd use whatever is easier for you as a developer. Pick the syntax you like best; there will be tools for reading it. Personally, I'd use Lua, as I would also be using Lua for scripting, so I would have it handy.
> 4 votes

---
Tags: architecture, data-driven
---


title: Weird shader compiler error

text:
# Question
Title: Weird shader compiler error
I am trying to draw a full screen quad without a vertex buffer. SV\_VertexID should do the trick, although I get a weird error in my shader on the following line:

```
PS_IN VS(uint VertexID : SV_VertexID)// << this is the line that causes trouble
{
    PS_IN output = (PS_IN)0;

    float4 pos = float4( (VertexID << 1) & 2, VertexID & 2 ,0,1);
    output.pos = mul(pos, wvp );

    float4 t = mul(pos, texTransform);
    output.tex = float2(t.x,t.y);

    return output;
}

```

The error message:

```
invalid type used for 'SV_VertexID' input semantics, must be integral

```

This is how I compile the shader:

```
fxc.exe /Tvs_4_0_level_9_3 /EVS /Fo Texture_VS.fxo Texture.fx

```

I dont understand why, as the type is integral. Why do I get this compiler error?

# Answer
> 2 votes
Do you do a `#define uint float` or similar anywhere?

That code compiled for me as vs\_5\_0 once I added appropriate definitions of PS\_IN etc. Are you compiling it as a pixel shader or something?

http://msdn.microsoft.com/en-us/library/windows/desktop/bb509647%28v=vs.85%29.aspx

> Other system values (SV\_VertexID, SV\_InstanceID, SV\_IsFrontFace) can only be input into the first active shader in the pipeline that can interpret the particular value; after that the shader function must pass the values to subsequent stages.

---
Tags: directx, directx11
---