title: How to go about GUI elements?

text:
# Question
Title: How to go about GUI elements?
Note: I plan on making my own GUI system. It will be good for learning, lightweight, only have bits I need, ties in with the game, etc.

I was thinking about how to do it. The elements I mean are:

* Radio buttons
* Enter text here boxes
* Buttons
* Sliders
* Checkboxes

I'm not looking as to how to make them, yet. But more of how they would go.

## Idea

I would have each state that needed stuff, so almost all, have a container of Elements. Each Element is-a GUI piece.

These each have position, a graphic, etc.

The bit I get more stuck on is the logic of them.

My idea for that, to allow for modularity and simplicity was to avoid a MainMenuStartButton; a OptionsOneBackButton, etc. and instead be able to do Slider slider1; or Button start;.

Instead, each would have a boost::function to a function in a GUI namespace, such like Gui::StartButtonClick, or GUI::ColourSliderHover.

I was just wondering whether this would be exceptionally slow or not.

And for that matter, is there any *easy, simple* way of doing GUI for games? No Qt, wxWidgets or anything.

# Answer
GUI isn't an easy or simple problem, especially when you get into games and their desire to have dynamic, interesting menus.

One "easy" thing you can do is try to use middleware. There's a question on that here.

If you're going to roll it yourself, there are a few things I would suggest.

* GUI elements generally have a "parent", either another GUI element or a "window", or something like that. Either by pointing up or having the parent point down means you can set state/position/etc on everything that's a child.
* You can build GUI elements by composition. A lot of widgets have labels (pretty much all of them), and it might make sense to make the concept of a label a component or a child of your other UI elements than copy/pasting the code or trying to inherit from a base class with label functionality.
* A lot of so-called specialized widgets are just buttons in disguise. Checkboxes are just buttons with states and special images. Radio buttons are just checkboxes that have meta-state (one and only one is active at any given time) with other radio buttons. Use this to your advantage. In one game I worked on, "checkboxes" were done with regular buttons entirely through scripting and art.
* For your first project, consider taking the more direct route. Yes, make your actionable events delegates and assign what you need on element creation (i.e. onMouseButtonDown, onMouseButtonUp, onHover etc), but consider just hard coding what you want to happen otherwise (i.e. hover color changes, button press sounds) until you get something functional. Once you're at that point, consider making that behavior data (i.e. have a variable on button for "press sound", or maybe consider having components that your UI elements use to define behavior that you just attach to them when you create them.
* delegates aren't that slow, you probably won't have so many widgets that it would be an issue, and menu code generally isn't that high impact anyway. I wouldn't worry too much about performance at this point in the game. Don't pick naive algorithms and profile once you get your code up and running.
> 14 votes

# Answer
There have been some really interesting breakthroughs in mainstream UI toolkits over the past few years. Game UIs have been evolving too, but at a somewhat slower pace. This is likely because developing a full-featured UI subsystem is a significant undertaking in itself, and it's difficult to justify the resource investment.

My personal favorite UI system is the Windows Presentation Foundation (WPF). It really takes the potential for UI differentiation to the next level. Here are some of its more interesting features:

1. Controls are "look-less" by default. A control's logic and visual appearance are generally decoupled. Every control ships with a default style and template, which describes its default visual appearance. For instance, a button may be represented as a rounded rectangle with an outer stroke, a solid color or gradient background, and a content presenter (to present the caption). Developers (or designers) can create custom styles templates which change the appearance and (to an extent) the behavior of a control. Styles can be used to override simple properties of a control, like foreground/background color, template, etc.; templates change the actual visual structure.
2. Styles and templates may include "Triggers". Triggers can listen for certain events or property values (or combinations of values) and conditionally alter aspects of a style or template. For instance, a button template would generally have a trigger on the "IsMouseOver" property for the purposes of changing the background color when the mouse hovers over the button.
3. There are a few different "levels" of UI elements ranging from lighter weight elements with minimal functionality to full-blown heavy-weight controls. This gives you some flexibility in how you structure your UI. The simplest of the UI element classes, `UIElement`, has no style or template and only supports the simplest of input events. For simple elements like status indicators, this functionality might be all you need. If you require more extensive input support, you can derive from `FrameworkElement` (which extends `UIElement`). Traditional widgets generally derive from `Control`, which extends `FrameworkElement` and adds custom style and template support (among other things).
4. WPF uses a retained, scalable, resolution-independent vector graphics model. On Windows, WPF applications are rendered and composed using Direct3D.
5. The introduction of WPF included a new declarative programming language called Xaml. Xaml, based on Xml, is the preferred language for declaring UI "scenes". It's actually pretty slick, and though it may appear similar at first glance, it's fundamentally different from existing languages like XUL (and much more powerful).
6. WPF has a *very* advanced text subsystem. It supports most if not all OpenType font features, bidirectional ClearType antialiasing, subpixel positioning, etc.

**"Ok, great, now how is this relevant to game development?"**

Back when WPF was still in development (and known as "Avalon"), I was taking a video game design course at Georgia Tech. My final project was a turn-based strategy game, and I wanted a very capable UI. WPF/Avalon seemed like a good route to go because it had a complete set of full-featured controls *and* it game me the capability to completely change the look and feel of those controls. The result was a game with a beautiful and crisp UI with the level of functionality that you normally only see in full-fledged applications.

Now, the problem with using WPF for games is that it's fairly heavy-weight and renders in its own "sandbox". By that, I mean there is no supported way of hosting WPF within a Direct3D or OpenGL game environment. It is possible to host Direct3D content within a WPF application, but you will be limited by the framerate of the WPF application, which is generally lower than you would want. For some types of games, like 2D strategy games (screenshot of my current WPF game project), it could still work great. For anything else, not so much. But you could still apply some of WPF's more compelling architectural concepts in developing your own UI framework.

There is also an open-source, unmanaged C++/Direct3D implementation of WPF called "WPF/G (WPF for Games)"\](http://wpfg.codeplex.com/) that is specifically designed for use in games on both Win32 and Windows Mobile. Active development appears to have ceased, but the last time I checked it out, it was a rather complete implementation. The text subsystem was the one area that was really lacking compared to Microsoft's WPF implementation, but that's less of an issue for games. I would imagine that integrating WPF/G with a Direct3D-based game engine would be relatively straightforward. Going this route could provide you with an extremely capable, resolution-independent UI framework with extensive support for UI customization.

Just to give you an idea of what a WPF-based game UI might look like, here's a screenshot from my pet project:
> 8 votes

# Answer
I would go for an immediate GUI, like this: http://code.google.com/p/nvidia-widgets/

The nVidia widgets are based on IMGUI (Immediate GUI) from MollyRocket.

I think that's about as simple as a GUI can ever get.

All depends on what your needs are.
> 2 votes

# Answer
In the game I'm working on, we have our own custom GUI framework. I've found it to be very simple, but still doing everything I want it to do. I don't know whether it's a "pattern" that many others use, but it works well for us.

Basically, all the buttons, checkboxes, etc. are subclasses of the class Element; and elements have Events. Then we have CompoundElements (which are themselves a subclass of Element), which contain other elements. In each cycle, three methods are called: processEvent(event), tick(time), and draw(surface). Each CompoundElement then calls those methods on its child Elements. In those calls (particularly the processEvent method), we fire off any relevant events.

All of this is in Python (a much slower language than C++), and it runs perfectly fine.
> 2 votes

# Answer
If you're going to need fairly sophisticated UIs, the best choice is probably to just embed a HTML renderer - you get all the common UI primitives you are used to, and you can trivially add complex UI to your game that will behave the way users expect, look great, and run fast (because browsers have pretty optimized rendering pipelines at this point).

There are a few libraries out there for embedding Webkit in games: Berkelium is the one I recommend, and I hear Awesomium is pretty good (used by EVE Online) and so is CEF (used by Steam). You can also try embedding Gecko - it's a lot harder to do but has some cool advantages as well. I'm currently using Berkelium for all my game UI (it replaced a combination of custom UI elements and native UI, and dramatically reduced the amount of code I had to write to get things running).
> 2 votes

# Answer
Make sure you actually need a sophisticated GUI system for your game. If you're making a computer RPG then obviously it will be a requirement; but for something like a racing game, don't overcomplicate things. Sometimes just rendering textures (custom button images) and having some "if" statements with hard-coded coordinates in your input function can get the job done. A game state machine (FSM) helps with this simple approach. Or, somewhere in the middle, forget the complicated hierarchy and scene graph approach and just have a "Button" class which packages the above-mentioned texture and input checks into simple function calls, but doesn't do anything complicated.

Nailing down your requirements is important. If you're unsure, just remind yourself YAGNI.
> 2 votes

# Answer
Here's one example (source code and all) of a GUI built for OpenGL, specifically for Slick2D called Thingle which is a port of Thinlet.

Another GUI for Slick2D was SUI that you might want to check out.

I'd follow these examples and go with an XML driven GUI. Although these projects are old/dead, you might be able to pick up some ideas from them.
> 1 votes

# Answer
I think one of the best ways to "figure it out" would be to have a look at how highly developed GUI frameworks work, such as Windows Forms in .NET.

For example, they are all Controls, which have a location, size, list of child controls, a reference to its parent, a `Text` property for whatever the control may use it for, as well as various overridable functions and predefined actions.

They all contain various events such as `Click`, `MouseOver` and `Resizing`.

For example, when a child control is changed, it sends a notification up the chain that its layout has changed, and all parents then call `PerformLayout()`.

As well, auto-sizing and auto-arranging are common features of these GUIs, allowing programmers to simply add controls and the parent controls adjust or arrange them automatically.
> 1 votes

# Answer
For interests sake I thought I would throw out Scaleform. Basically the artists can use illustrator, photoshop etc, then the UI designer uses Flash to layout all the interactivity. Then Scaleform transforms it into code for your engine (well thats my understanding of it as I have not used it). Crysis Warhead used this system for their lobby.
> 1 votes

---
Tags: c++, architecture, gui
---


title: 3D meshes for WPF (XAML)?

text:
# Question
Title: 3D meshes for WPF (XAML)?
I'm trying to make a WPF-3D game. WPF uses XAML.

I'm trying to find free 3D assets from the internet. :-)

What format of 3D models I should be looking for, direct XAML or 3D Studio format or what? I know that there are some 3D Studio format to XAML -converters, but I don't know if they really work...

# Answer
> 3 votes
I know that this does not really answer you question, but bear with me:

Why not (pretty much) every format?

Use the Open Asset Import Library (assimp).

There's examples of loaders using DirectX.

In addition to the Assimp Viewer shipped with the Assimp project.

That should get you started using all the formats Assimp supports.

It's probably possible to serialize the meshes as XAML - I bet there's code for that out there..

# Answer
> 2 votes
I would recommend avoiding XAML for 3D models if you can. In its typical Xml form, Xaml benefits from being human readable but suffers from slow load times. This is generally true for all plain text formats that require parsing and reflection. I suggest you look for libraries that can convert common 3D formats into WPF3D format at runtime. Alternatively, you could use Baml or a custom binary Xaml format. The latter is possible in .NET 4 due to the refined Xaml object model and extensible reader/writer facilities.

Loading and rendering 3D models in WPF should be relatively painless. Textures, on the other hand, may be more problematic. WPF3D's support for 3D surfaces/textures is relatively simple, and you may end up having to rework a lot of textures if you rely on free 3D assets from the Internet.

---
Tags: 3d-meshes
---


title: Patterns for racing AI behaviour

text:
# Question
Title: Patterns for racing AI behaviour
So let's say you've got a spline-based racing AI. Assume it can already handle the basics of braking and steering around the track.

How would you structure and implement collision avoidance, overtaking, drafting, blocking and other behaviours so your cars remain competitive but make interesting races?

Links to papers/implementations would be awesome.

# Answer
Have you seen Steering Behaviors For Autonomous Characters? I would consider a "CrowdPathFollowing" algorithm for staying on the track and avoiding collisions. You might be able to mix in a "Flow Field Following" behavior for drafting, passing and blocking - make the flow field follow the the player's past and projected path, but split around his current location.

```
      /-------------\
 ----<  [playerCar]  >-----
      \-------------/

```

That should cause the AI to tend to follow directly behind him and move directly in front to block, yet encourage clean passes.
> 7 votes

# Answer
There was a session partly about that at this year's AI Game Dev conference in Paris. You can find the slides and a summary here:

http://aigamedev.com/open/coverage/paris10-report/#session9
> 2 votes

# Answer
### Anti-Pattern: Opponents adapting their speed

Unfortunately I'm not able to give You patterns, but I would like to name an anti pattern. Please do not try to adapt the speed of the AI drivers to the one of the human player. The idea behind this is to create fair racing conditions for amateurs as well as pros and to abandon the need of multiple difficulty levels (and their implementation).

However, what sounds good on paper turns out to be awful in practice and the MotoGP series failed miserably at implementing this behavior. It ended up in the opponents driving at 5mp/h when you stood still for a couple of seconds and the impossibility to tell whether you've improved in the game (very bad feedback wise)
> 1 votes

---
Tags: collision-detection, ai, software-engineering
---


# Question
Title: Wave is being discontinued! Other good remote collaboration tools?
The news just came across the Google blog that Wave is going to go away in the not too distant future. Clicky for the story. This is a real shame for my team who has been making heavy use of Wave as a remote collaboration tool. Looks like we need a new platform. What tools does your remote team like to use to collaborate online?

# Answer
PyCon had a lot of success using Etherpad. Even though the main hosted service has been taken down, you can either run it yourself or use one of the many public sites. Chris Ball's openetherpad has worked well for me before.
> 2 votes

---
Tags: tools, productivity
---


# Question
Title: How do the Box2d and Bullet physics simulations work internally?
I've seen box2d and bullet ported into JavaScript, but neither of them attracted me, except for the source code. It all seemed quite simple, once I looked inside.

What are they doing within each of those libraries to get nice physics simulation? I can not find any explanation.

# Answer
> 11 votes
Rigid body physics is actually quite simple in concept - that is, the behaviors an engine is trying to create are not very complicated. That's probably why the libraries you looked at seem quite simple to you.

The trick is that making a sim that is *robust*, *stable*, and *fast*, even in the presence of things like floating-point error and low, variable framerates, is quite difficult and usually involves a great deal of tweaking and fiddling. Further complicating the issue is the fact that a lot of extremely smart people have made heroic efforts at finding better solutions, and have come up with beautiful and powerful but difficult-to-understand algorithms that have given the field a reputation for black magic.

In general, a physics engine is going to be concerned with three things (the order in which they do them in the internal loop varies):

1. Integration (approximating the Newtonian equations of motion),
2. Collision detection, and
3. Constraint solving (updating positions and velocities to satisfy nonpenetration or other user-specified constraints.)

For most of these, there are both simple but not-so-accurate algorithms and complex but more-accurate algorithms. To get you started:

1. For integration, most people use either Symplectic Euler or Verlet (which are actually equivalent. You can read up on numerical integration if you like, but the consensus seems to be that cheap first-order methods are fine.
2. You can find all the collision detection references you could want on the Real-Time Rendering resource page.
3. For constraint solving, the method of sequential impulses is very easy to understand. Erin Catto (the author of Box2D) gives a presentation at GDC every year - the slides are linked from the Box2D main page. The 2006 slides cover sequential impulses pretty well. You can also look into fancier methods like Featherstone or projected Gauss-Seidel.

There's an excellent introduction to simple methods and what can go wrong in the early chapters of the just-published book Game Physics Pearls.

# Answer
> 2 votes
http://en.wikipedia.org/wiki/Rigid\_body\_dynamics might be a good place to start. Different games will divide things up into different bodies, but in general you have a number of discrete rigid bodies linked by joints with specific properties. Each loop through the game you calculate the forces on each body and calculate its new parameters (position, velocity, etc). You also have to transmit forces from each body to the others it shares joints with and factor in global forces (gravity).

This doesn't cover things like liquid or cloth physics, those are all gibberish to me. There are differential equations involved and thats about the point where my eyes glaze over.

# Answer
> 0 votes
One important thing besides the physics equations is tracking all the objects, so that checking for collision detection and interactions is as fast as possible. Spatial Hashing is the technique that the Chipmunk physics engine uses.

---
Tags: box2d, software-engineering, bullet-physics
---


title: SoA Vectors on SPU

text:
# Question
Title: SoA Vectors on SPU
I've read a lot about the benefits of organizing data into 'Structs of Arrays' (SoA) instead of the typical 'Array of Structs' (AoS) to get better throughput when using SIMD instructions. While the 'why' makes total sense to me, I'm not sure *how much* to do this when working with things like vectors.

Vectors themselves can be tought of as a struct of a (fixed size) array of data, so you could convert an array of these into a struct of X, Y and Z arrays. Through this, you can work on 4 vectors at once as opposed to one at a time.

Now, for the specific reason I'm posting this on GameDev:

Does this make sense for working with vectors on the SPU? More specifically, does it make sense to DMA multiple arrays just for a single vector? Or would it be better to stick with DMAing the array of Vectors and unrolling them into the different components to work with?

I could see the benefit of cutting out the unrolling (if you did it 'AoS'), but it seems like you could quickly run out of DMA channels if you took this route and were working with multiple sets of vectors at once.

(Note: no professional experience with Cell yet, but have been toying around in OtherOS for a while)

# Answer
> 5 votes
One approach is to use an AoSoA (read: Array of Struct of Array) approach which is a hybrid of AoS and SoA. The idea is to store N structs worth of data in a contiguous chunk in SoA form, then the next N structs worth in SoA form.

Your AoS form for 16 vectors (labelled 0,1,2...F), swizzled at granularity of 4 structs is:

```
000111222333444555666777888999AAABBBCCCDDDEEEFFF
XYZXYZXYZXYZXYZXYZXYZXYZXYZXYZXYZXYZXYZXYZXYZXYZ

```

for SoA, this is:

```
0123456789ABCDEF
XXXXXXXXXXXXXXXX

0123456789ABCDEF
YYYYYYYYYYYYYYYY

0123456789ABCDEF
ZZZZZZZZZZZZZZZZ

```

for AoSoA, this becomes:

```
01230123012345674567456789AB89AB89ABCDEFCDEFCDEF
XXXXYYYYZZZZXXXXYYYYZZZZXXXXYYYYZZZZXXXXYYYYZZZZ

```

The AoSoA approach has the following benefits of AoS:

* Only a single DMA transfer is required to transfer a chunk of structs to SPU local memory.
* structs still have a chance of all data fitting in a cacheline.
* Block prefetching is still very easy.

The AoSoA approach also has these benefits of SoA form:

* You can load data from SPU local memory directly into 128-bit vector registers without having to swizzle your data.
* You can still operate on 4 structs at once.
* You can fully utilize the SIMD'ness of your vector processor if there is no basic branching (ie. no unused lanes in your vector arithmetic)

The AoSoA approach still has some of these drawbacks of SoA form:

* object management has to be done at swizzling granularity.
* random access writes of a full struct now needs to touch scattered memory.
* (these can turn out to be non-issues depending on how you organize/manage your structs and their lifetime)

BTW, these AoSoA concepts apply very well to SSE/AVX/LRBni, as well as GPUs which can be likened to very wide SIMD processors eg. 32/48/64 wide depending on the vendor/architecture.

# Answer
> 3 votes
SPUs are actually an interesting special case when it comes to vectorizing code. Instructions are divided into "arithmetic" and "load/store" families, and the two families run on separate pipelines. The SPU can issue one of each type per cycle.

Math code is obviously heavily bound by math instructions - so usually mathy loops on SPU will have lots and lots of open cycles on the load/store pipe. Since shuffles happen on the load/store pipe, you often have enough free load/store instructions to swizzle xyzxyzxyzxyz form into xxxxyyyyzzzz form without any overhead at all.

This technique is in use at Naughty Dog at least - see their SPU assembly presentations (part 1 and part 2) for details.

Unfortunately the compiler is often not smart enough to do this automatically - if you decide to go this route you'll need to either write assembly yourself or unroll your loops using intrinsics and check the assembler to make sure it's what you want. So if you are looking to write general cross-platform code that happens to run well on SPU, you may want to go with SoA or AoSoA (as jpaver suggests.)

# Answer
> 1 votes
As with any optimisations, profile! Readability comes first, and should only be sacrificed when profiling identifies a particular bottleneck and you have exhausted all your options for tuning the high level algorithm (the fastest way to do the work is to not have to do the work!) You should always reprofile following any low level optimisation to confirm that you really have made things faster rather than the opposite, especially with pipelines as quirky as the Cell's.

What techniques you use then will depend on the particulars of the bottleneck. In general, when working with vector types, a vector component you ignore in a result represents work wasted. Switching SoA / AoS does not make sense unless it allows you to do more useful work by filling such unused components (e.g. one dot product on PS3's PPU vs four dot products in parallel in the same amount of time). To address your question, spending time shuffling components around just to perform one operation on a single vector sounds like a pessimisation to me!

The flip side on SPUs is that the bulk of the cost of small DMA transfers is in setup; anything less than 128 bytes will take the same number of cycles to transfer, and anything less than about a kilobyte only a few cycles more. So don't worry about DMAing more data than you strictly need; reducing the number of sequential DMA transfers triggered, and performing work while DMA transfers are happening - and therefore unfolding loop prologues and epilogues to form software pipelines - is key to good SPU performance, and it is easiest to deal with corner cases by fetching extra data / discarding partially computed results than jumping through hoops to try to arrange for the exact amount of data that is necessary to be read and processed.

# Answer
> 0 votes
No, that would not make much sense in general as most vector opcodes operate on a vector as a whole and not on seperate components. So you can already multiply a vector in 1 instruction, whereas with splitting up the seperate components you'd spend 4 instructions on it. So since you basically do a lot of operations in general on part of a struct you're better of packing them in an array, but you hardly ever do things only on one component of a vector, or wildly different on each component so breaking them out wouldn't work.
Of course, if you do find a situation where you have to do something to only the (say) x components of vectors it might work, however the penalty of swizzling everything back when you need the actual vector wouldn't be cheap so you could wonder if you shouldn't use vectors to begin with but just an array of floats that happen to allow for vector opcodes to do their specific calculations.

---
Tags: software-engineering, algorithm, playstation3
---


# Question
Title: How to calculate the exit speed of ball bouncing off a solid surface
Hey all, I am working on a simple game to include some rigid body dynamics, involving placing (moving & rotating) some springs to bounce a falling ball into a target area.

My problem is correctly calculating the exit velocity of the ball after it hits the spring surface (Vexit, Ve for short)

**Assume the following:**
Initial ball velocity vector at point of impact is known (Vimpact, Vi for short)
Surface orientation vector is known (Vsurface, Vs for short)
Bounce coefficient (Bc for short) of ball after hitting surface is constant (*for example |Ve| = 1.2 x |Vi|*)

**My algorithm is as follows:**
-get surface normal vector, ***Vn***
-get ***Vi*** inverse (reversing both x,y components to get reversed direction vector)
-get normalised Vi inverse, call this ***Vin***
-get angle between Vin & Vn, by arccos(Vin . Vn). Let this be ***angle A***
-rotate Vin by (2A) degrees to get normalised exit vector ***Ven***
-***Ve*** = Ven . Bc

Now as far as I can tell, this would work well. However, I am unable to know on ***whether to perform the rotation step in clock-wise, or anti-clock-wise motion***; since the angle i get is always positive

What do you all think of this algorithm anyways?
Can anyone help me out on how to figure out the rotation direction?
Anyone have a better (faster,simpler,more accurate, etc) algorithm to use?

Thanks a lot!

# Answer
I think you're over-thinking this, you can achieve reflection, as it can be calculated by doing:

Ve = Vi - 2 * (Vi *dot* Vn) * Vn

(Where *dot* refers to the dot product)

Then you can simply scale Ve by your Bc to get the final result.

Reference: http://mathworld.wolfram.com/Reflection.html
> 9 votes

# Answer
You don't need the arccos or the angle. You just want to invert the normal velocity.

Start by taking the component of the ball's velocity in the normal direction (perpendicular)

```
Vp = Dot(Vn, Vi) * Vn

```

compute the tangential velocity

```
Vt = Vi - Vp

```

and then invert the normal velocity while keeping the tangential velocity

```
Ve = Vt - Vp

```

This can simplify to

```
Ve = Vi - 2*Vp

```

This assumes that your Vn is normalized (i.e. Dot(Vn, Vn) == 1).

It should be easy to change this to support restitution other than 1 (that is, different bounciness.)
> 2 votes

---
Tags: 2d, mathematics, physics
---


# Question
Title: Good way to implement really basic physics in Flash?
I'm making a somewhat simple side-scroller in Flash. The way I'm currently doing the really basic physics(you don't fall through floors/can't walk through walls) is that I have a big symbol of all the walls/floor/ceiling and use some complex hit testing against that.

Basically, if you are moving down when you hit, move you up til you're out, moving left move right, etc. If you're moving diagonally you'll move diagonally out and then move over the direction that didn't get you out until you hit something or get lined up. Then I move you down one so you're touching the floor since I have you fall down 20 pixels if you're in the air, and that make it slow since it has to do 20 hit tests every frame. Here's the code I use:

```
    public function onEnterFrame(e:Event){
            hitTests = 0;
            trace("x:"+x+", y: "+y);
            if(!game.main.Paused) {
                if(!HitTest.complexHitTestObject(this, room.main.currentRoom.edge, 1)) {
                    hitTests++;
                    movementY += 10;
//                    trace("movY: "+(movementY-20)+" > "+movementY);
                }
                if(game.main.Ahit) {
                    movementX -= 5;
                }
                if(game.main.Dhit) {
                    movementX += 5;
                }
                x += movementX;
                y += movementY;
//                trace((y-movementY)+" + "+movementY+" = "+y);
                if(HitTest.complexHitTestObject(this, room.main.currentRoom.edge, 1)) {
                    hitTests++;
                    dynamicXnum = 0;
                    dynamicYnum = 0;
                    free4floor = true;
                    while(HitTest.complexHitTestObject(this, room.main.currentRoom.edge, 1)) {
                        hitTests++;
                        if(movementX == 0 && movementY == 0) {
                            break;
                            xlast = undefined;
                        }
                        if(movementX > 0) {
                            x--;
                            dynamicXnum--;
                        }
                        if(movementX  0 || free4floor) {
                            y--;
                            dynamicYnum--;
                            free4floor = false;
                        }
                        if(movementY  0) {
                                y--;
                                dynamicYnum--;
                            }
                            else {
                                break;
                            }
                        }
                    }
                    if(xlast == false) {
                        while(!HitTest.complexHitTestObject(this, room.main.currentRoom.edge, 1) && dynamicXnum != 0) {
                            hitTests++;
                            if(dynamicXnum  0) {
                                x--;
                                dynamicXnum--;
                            }
                            else {
                                break;
                            }
                        }
                        if(movementX > 0)
                            x--;
                        if(movementX  0 || movementX != 0)
                            y++;
                        movementY = 0;
                    }
                }
                if(movementX >= 5) {
                    movementX -= 5;
                }
                else if(movementX  maxHitTests)
                maxHitTests = hitTests;
            trace("end: x:"+x+", y: "+y);
            trace("hts: "+hitTests)
            trace("mhts: "+maxHitTests);
            }
        }

```

This is working okay for now, and you can see a demo of it here, but there are a couple of problems.

For one, it can get a little slow, but this isn't that big of a problem, since it's pretty rare, and it's not that slow. Mainly, it's that when I get around to animating the little dude, and even now sometimes when it messes up a bit, it will get more than five pixels in the wall. Then when I try to move out, it won't make it out in one frame, and it will force him through the wall the wrong way, making him fall into infinity...does anyone know how to fix this? Should I totally redo how I do it? Should I have some kind of variable for which way he came from? If so, how should I do it?

# Answer
Have you thought about using a good API to help you with your flash development?

Take a look at Flixel and Box2D.
> 1 votes

# Answer
Also, if you really want to understand... I highly recommend MetaNet's tutorial series:

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

(This tutorial includes an example -- with source from N! N had excellent and speedy physics.)

They go over way MORE than what you need, but DO go over what you need rather well.
> 2 votes

# Answer
Honestly Box2D is a great physics library for flash and is very incorporable into existing projects.
> 2 votes

# Answer
It's hard to comment on speed since we don't know what's happening in HitTest.complexHitTestObject. I would say though that if you have a point that represent the player's feet, you can just move that point straight up in a while loop until you hit the air. I would have 2 "detector" points, one on the bottom left corner of the character, one on the bottom right, and test the leading point against terrain and move the character back until they are out of terrain (as you are doing). If you are using the built-in hitTest methods be aware that they are not that fast, but may well be the only way to get the effect you want.
> 0 votes

---
Tags: flash, physics
---


title: Rendering SVG art directly in XNA

text:
# Question
Title: Rendering SVG art directly in XNA
Suppose I have a bunch of 2D art in some vectorized format such as SVG. Is there an easy-ish way to render that directly without having to implement a full SVG renderer myself?

Of course I could rasterize it off-line (e.g. in the content pipeline) for different resolutions/zoom levels, but I would like to maintain the crisp visuals at continuous zoom levels that vector graphics offer.

# Answer
A good question. I was experimenting with this at one point - I couldn't find a easy, pre-built solution. But let me point you to some of the resources I found when attempting to implement it myself:

---

First of all there's an article from GPU Gems 3: Rendering Vector Art on the GPU (and the associated Loop-Blinn paper).

The hardest part is that, while drawing quadratic curves are easy, cubic curves (like those found in your typical SVG) are considerably harder. The article goes into detail on this, but you'll need to bring your maths hat.

The alternative to rendering cubic curves is to convert the cubic curves to quadratic ones. Also a non-trivial problem.

Once you can render vector curves on the GPU, it's a simple matter of parsing the SVG in your content pipeline and turning it into a mesh that you can render. **Parsing SVG is easy**, by the way.

Another, potentially easier alternative is to forego curves all together and simply triangulate a linear approximation of your SVG.

Both these solutions require triangulation - here's a reasonable triangulator suited to XNA.

---

As a completely different alternative, you can use a "distance field" to render sprites with nearly-vector-like sharp edges.

Here is a paper from Valve from SIGGRAPH 2007 on how to do this: Improved Alpha-Tested Magniﬁcation for Vector Textures and Special Effects (PDF)

The basic method here is very easy to implement. The difficulty comes when trying to make it support sharp corners (something only touched on in the paper). This method also has some pretty severe limitations for anything but drawing simple shapes. It's best suited to UI text and decals (like Valve is using it for).

---

Now that I've said all that - I have to say that, in my experience, all the effort here is not worth it!

Unless your *gameplay* is going to be based primarily around ***extreme*** vector zooming effects like the very cool Masagin demo, you can get away with pre-rendering your SVG and simply using bitmap techniques (easier, better supported, etc).

(One of the first techniques that comes to mind is mipmapping (wiki) high-resolution versions of your sprites, to give you resolution independence up until your maximum sprite size.)

This blog post is probably a good place to get started adding SVG rendering support to your XNA content pipeline.
> 27 votes

---
Tags: xna, 2d, graphics, art, vector-art
---


# Question
Title: In general how often and when should I optimize my code?
In 'normal' business programming optimization step is often left until really needed. Meaning you should not optmize until it is really needed.

Remember what Donald Knuth said "We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil"

When is the time to optimize to make sure I am not wasting effort. Should I do it a method level? Class level? Module level?

Also what should my measurement of optimization? Ticks? Frame Rate? Total Time?

# Answer
Where I've worked, we always use multiple levels of profiling; if you see a problem, you just move down the list a bit more until you figure out what's going on:

* The "human profiler", aka **just play the game**; does it feel slow or "hitch" occasionally? Noticing jerky animations? (As a developer, note that you'll be more sensitive to some kinds of performance issues and oblivious to others. Plan extra testing accordingly.)
* Turn on the **FPS display**, which is a sliding-window 5 second average FPS. Very little overhead to calculate and display.
* Turn on the **profile bars**, which are just a series of quads (ROYGBIV colors) that represent different parts of the frame (e.g. vblank, preframe, update, collision, render, postframe) using a simple "stopwatch" timer around each section of code. To emphasize what we want, we set one screen width worth of bar to be representative of a 60Hz target frame, so it's really easy to see if you're e.g. 50% under budget (only a half-bar) or 50% over (the bar wraps and becomes one and a half bars). It's also pretty easy to tell what's generally eating most of the frame: red = render, yellow = update, etc...
* Build a special **instrumented build** that inserts "stopwatch" like code around each and every function. (Note that you may take a massive performance, dcache, and icache hit when doing this, so it's definitely intrusive. But if you lack a proper sampling profiler or decent support on the CPU, this is an acceptable option. You can also be clever about recording a minimum of data on function enter/exit and rebuilding calltraces later.) When we built ours, we mimicked much of gprof's output format.
* Best of all, run a **sampling profiler**; VTune and CodeAnalyst are available for x86 and x64, you've got various simulation or emulation environments that might give you data here.

(There's a fun story from a past year's GDC of a graphics programmer who took four pictures of himself -- happy, indifferent, annoyed, and angry -- and displayed an appropriate picture in the corner of the internal builds based on the framerate. The content creators quickly learned not to turn on complicated shaders for *all* of their objects and environments: they'd make the programmer angry. Behold the power of feedback.)

Note you can also do fun things like graph the "profile bars" continuously, so you can see spike patterns ("we're losing a frame every 7 frames") or the like.

To answer your question directly, though: in my experience, while it's tempting (and often rewarding -- I usually learn something) to rewrite single functions/modules to optimize number of instructions or icache or dcache performance, and we do actually *need* to do this sometimes when we've got a particularly obnoxious performance problem, the vast majority of the performance issues we deal with on a regular basis come down to **design**. For example:

* Should we cache in RAM or reload from disk the "attack" state animation frames for the player? How about for each enemy? We don't have RAM to do them all, but disk loads are expensive! You can see the hitching if 5 or 6 different enemies pop in at once! (Okay, how about staggering spawning?)
* Are we doing a single type of operation across all particles, or all operations across a single particle? (This is an icache/dcache tradeoff, and the answer isn't always clear.) How about pulling apart all the particles and storing the positions together (the famous "struct of arrays") vs keeping all particle data in one place ("array of structs").

You hear it until it becomes obnoxious in any university-level computer science courses, but: it really is all about the data structures and algorithms. Spending some time on algorithm and data flow design is going to get you more bang for the buck in general. (Make sure you've read the excellent Pitfalls of Object Oriented Programming slides from a Sony Developer Services fellow for some insight here.) This doesn't "feel" like optimization; it's mostly time spent with a whiteboard or UML tool or creating many prototypes, rather than making current code run faster. But it's generally much more worthwhile.

And another useful heuristic: if you're close to your engine's "core", it may be worth some extra effort and experimentation to optimize (e.g. vectorize those matrix multiplies!). The further from core, the less you should be worrying about that unless one of your profiling tools tells you otherwise.
> 18 votes

# Answer
1. Use the right data structures and algorithms up front.
2. Don't micro-optimize until you profile and know exactly where your hot spots are.
3. Don't worry about being clever. The compiler already does all the little tricks you're thinking of ("Oh! I need to multiply by four! I'll shift left two!")
4. Pay attention to cache misses.
> 6 votes

# Answer
Also remember however "premature pessimization". While there's no need to go hardcore on every line of code, there's justification for realizing you are actually working on a game, which has real-time performance implications.
While everyone tells you to measure and optimize the hot-spots, that technique won't show you performance that is lost in hidden places. For example, if every '+' operation in your code would take twice as long as it should, it won't show up as a hot-spot and thus you will never optimize it or even realize, however since it's being used allover the place it might cost you a lot of performance. You'd be surprised how many of those cycles trickle away without ever being detected. So be aware of what you do.
Apart from that, I tend to profile regularly to get an idea of what's there, and how much time is left per frame. To me time per frame is the most logical as it tells me directly where I'm at with framerate goals. Also try to find out where peaks are and what causes them - I prefer a stable framerate over a high framerate with spikes.
> 5 votes

# Answer
Once a game is ready to be released (either final or a beta), or it is noticeably slow, that's probably the best time to profile your app. Of course, you can always run the profiler at any point; but yes, premature optimization is the root of all evil. Unfounded optimization, too; you need actual data to show that some code is slow, before you should go try to "optimize" it. A profiler does that for you.

If you don't know about a profiler, learn it! Here's a good blog post demonstrating the usefulness of a profiler.

> Most of game code optimization comes down to reducing the CPU cycles that you need for each frame. One way to do this is to just optimize every routine as you write it, and make sure it's as fast as possible. However, there is a common saying that 90% of the CPU cycles are spent in 10% of the code. This means that directing all of your optimization work to these bottleneck routines will have 10x the effect of optimizating everything uniformly. So how do you identify these routines? Profiling makes it easy.

Otherwise, if your small game is running at 200 FPS even though it has an inefficient algorithm in it, do you really have a reason to optimize? You should have a good idea of your target machine's specs, and make sure the game runs well on that machine, but anything beyond that is (arguably) wasted time that could be better spent coding or polishing the game.
> 3 votes

# Answer
I find it useful to build profiling in. Even if you're not actively optimising it's good to have an idea on what is limiting your performance at any given time. Many games have some kind of overlayable HUD which displays a simple graphical chart (usually just a coloured bar) showing how long various parts of the game loop are taking each frame.

It would be a bad idea to leave performance analysis and optimisation to too late a late stage. If you've already built the game and you're 200% over your CPU budget and you can't find that through optimisation, you're screwed.

You need to know what the budgets are for graphics, physics, etc., as you write. You can't do that if you have no idea what your performance is going to be, and you can't guess at that without know both what your performance is, and how much slack there might be.

So build in some performance stats from day one.

As to when to tackle stuff - again, probably best not to leave it too late, lest you have to refactor half your engine. On the other hand, don't get too wrapped up in optimising stuff to squeeze out every cycle if you think you might change the algorithm entirely tomorrow, or if you haven't put real game data through it.

Pick off the low hanging fruit as you go along, tackle the big stuff periodically, and you should be fine.
> 2 votes

# Answer
If look at Knuth's quote in its context he goes on to explain, that **we should** optimize but with tools, like a profiler.

You should constantly profile and memory profile your application after the very basic architecture gets laid.

Profiling will not just help you increase the speed, it will help you find bugs. If your program suddenly drastically changes speed, this is usually because of a bug. If your not profiling it might go unnoticed.

The trick to optimizing is to do it by design. Don't wait till the last minute. Make sure the design of your program gives you the performance you need without really on nasty inner loop tricks.
> 2 votes

# Answer
For my project, I usually apply some VERY needed optimizations in my base engine. For example I always like to implement a good solid SIMD implementation using SSE2 and 3DNow! This ensures my floating point math is on cue with where I want it to be. Another good practice is to make a habit out of optimizations as you code instead of going back. Most of the time these little practices are just as time consuming as what you were coding anyway. Before coding a feature, make sure you research the most efficient way to do it.

Bottom line, in my opinion, its HARDER to make your code more efficient after it already suck.
> 1 votes

# Answer
I would say the easiest way would be using your common sense - if something looks like it's running slow, then have a look at it. See if it is a bottleneck.
Use a profiler to have a look at the speed functions are taking and how often they're being called.
There's absolutely no point optimizing or spending time trying to optimize something that doesn't need it.
> 0 votes

# Answer
If your code is running slow, then run a profiler and see what exactly is causing it to run slower. Or you could be proactive and already have a profiler running *before* you start to notice performance problems.

You will want to optimize when your framerate drops to a point that the game starts to suffer. Your most likely culprit will be your CPU being used up too much (100%).
> 0 votes

# Answer
You should optimize your code... as often as you need to.

What I've done in the past is just continuously run the game with profiling turned on (at the very least a framerate counter on screen at all times). If the game is getting slow (below your target framerate on your min spec machine, for example), turn on the profiler and see if any hot spots show up.

Sometimes it isn't the code. A lot of the problems I've run into the past have been gpu-oriented (granted, this was on the iPhone). Fillrate issues, too many draw calls, not batching enough geometry, inefficient shaders...

Other than inefficient algorithms for hard problems (i.e. pathfinding, physics), I've very rarely run into issues where the code itself was the culprit. And those hard problems should be things you spend a lot of your effort on getting the algorithm right and not worrying about smaller things.
> 0 votes

# Answer
For me is the best follow good prepared data model. And optimalization-before main step forward. I mean before start implementing something big new. Other reason for optimalization is when I'm loosing control on resources , App needs lot of CPU load/GPU load or memory and i don't know why :) or it's too much.
> 0 votes

---
Tags: optimization
---


title: MMO Performance

text:
# Question
Title: MMO Performance
To give a bit of background, I'm developing an MMO in the web browser. Crazy? Yes, but it certainly isn't impossible. The server sends updates to the client by means of long-polling JSONp tags which are opened in advance and marked for updates to be sent at a certain timestamp.

The problem is that you simply can't pump too much information into a browser. At some point, there's a barrier as to both the speed and quantity of information that you can send, so I'm looking to implement some type of system that would allow the server to send periodic updates of remote users' positions rather than "realtime" updates. Is there any reliable way of doing this without shooting myself in the foot?

I've read about a heuristics technique that analyzes the motion of a player over time to generate a function which could be used to simulate the player's pathfinding "technique". This would then be used to interpolate the position of the remote player between updates. Any thoughts on this or another technique I could use?

# Answer
Optimizing mmo network performance does indeed come down to movement prediction. Luckily there are a few different strategies you can use in your MMO with regards to movement, and some of them are much easier to predict than others.

If at all possible don't worry about where players ARE, worry about where they are going. Let's say your game has some sort of point and click interface where a player picks where they are going. This makes perfect sense for a mouse-driven MMO. In this case you do not have to update periodically with their current location. Instead, you just need to tell every client where each player is heading and when they expect to get there (and maybe some pathing info if you need it). You can then animate it entirely on the client. If a player changes their mind you can then send updated info to the clients. there may be a bit of rubber banding, but without direct player control it won't be noticeable. This approach can even be used in crazy physics environments, as much of Eve's motion is predicted on the client using complicated math.

If it's absolutely vital that your players must have direct movement control, you're then going to need fps-style movement prediction. This is probably overkill for any sort of web-based MMO (are your players really using controllers or wasd to move?), but you will need it if collision is important. In this case you end up doing a much more complicated version of the above, where the client will attempt to determine where a player is heading based on the position and velocity of a player that is sent down over the network. But the prediction errors here will feel much worse, especially in a laggy environment. Stay away from this method if at all possible.
> 3 votes

# Answer
Motion prediction is used by pretty much every online game these days, but it usually operates with an expected sync cycle of 100ms or less. Are you sure you can keep that kind of data rate without maxing out the browser? If you search for "motion prediction" you can find a lot of information, but assuming this is a 2D game the concept is simple enough (store a moving buffer of the last X positions, extrapolate next position). There is some complexity when you start dealing with how to move players that are out of sync from where the server thinks they should be (read: rubberbanding), but you can probably just ignore that for now.
> 5 votes

# Answer
I have no experience in this domain, but I've seen something that may be useful. If you know, or anyone else knows about this feel free to elaborate on it. A buddy of mine pointed me to this when I was talking about creating a multiplayer web-based game.

http://www.ape-project.org/
> 1 votes

# Answer
> I'm looking to implement some type of system that would allow the server to send periodic updates of remote users' positions rather than "realtime" updates.

Pretty much all MMOs do this; it's not limited to those that want to run in the browser.

It's quite simple to get a basic scheme up and running:

* The server has an interest list for every player, consisting of other players and NPCs.
* If someone moves too far from the player, they're removed from the list, and if they move within range, they're added to it.
* If a player moves, an update about that is sent just to the players who have this guy on their interest list. It doesn't have to be sent immediately - it can just be flagged up in the interest list as needing an update, so that it is sent in the next periodic update message
* These updates can be skipped if one was already sent too recently. Your definition of 'too recently' can be based upon distance, or on a more complex scheme which evaluates how good a predicted position is likely to be (see below).
* Clients linearly interpolate positions, predicting a character's path, and smoothly blend between the prediction and the reported position to correct errors, meaning updates don't have to be real-time to appear fairly accurate.
> 1 votes

# Answer
I think that the interpolation idea will not be useful to you. If your game is supposed to have realtime interaction between players, any delays in transmitting player actions would seriously damage the realtime aspect. If the game does not have realtime interaction, the periodic transmissions should be sufficient for any important events in the game.
> 0 votes

# Answer
## JavaScript Sockets!

There are several implementations but they all use either Flash or Java, which your page communicates with via a JavaScript library (since both Flash and Java can interact with JavaScript on the page). You can literally make C-like socket calls to establish a connection, send/receive data, and close a connection (and whatever else you do with sockets).

Here are a couple:

I highly recommend taking this approach. However, it would also require a different server technology; which is a good thing, but it is a change and depending on how advanced your server is, that could mean a lot of lost time...

Oh, and there's also WebSockets coming soon. So if you use one of the above libraries and adapt your server to use socket communication, then you can just swap in WebSockets as it becomes more accepted!
> 0 votes

---
Tags: mmo, performance
---


title: Expected OpenGL performance

text:
# Question
Title: Expected OpenGL performance
I'm benchmarking some simple code for drawing using OpenGL.

In the following code, the number of indices being drawn is 4,644 (or 1,548 triangles per frame = @60fps 92,880 Triangles per second).

```
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, screenSize.width, screenSize.height, 0, 0, 1);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glDisable(GL_DEPTH_TEST);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glEnable(GL_TEXTURE_2D);

glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(venomGLAttribute), ,drawingTexturedList.attrib[0].color);
glVertexPointer(2, GL_SHORT, sizeof(venomGLAttribute), &drawingTexturedList.attrib[0].pos[0]);
glTexCoordPointer(2, GL_FLOAT, sizeof(venomGLAttribute), &drawingTexturedList.attrib[0].UV[0]);
glDrawElements(GL_TRIANGLES, drawingTexturedList[cnt].currentIndice /*4644*/, GL_UNSIGNED_INT, drawingTexturedList[cnt].Indices);

```

This takes 100% of one of my CPU's. If I take out the call to glDrawElements but still perform all the other steps (geometry preperation, gl\*Pointer setup) I see my CPU stay at ~3%.

Is this expected behaviour? The machine I'm running on has a GeForce 8800GTX and a Dual Core @ 2.66Ghz.

Using fps as a measurement (which isn't perfect I realise) and using gDEBugger to confirm my findings, rendering 27,904 triangles a frame in a single call to glDrawElements brings my frame rate down to ~35fps (or 977,640 triangles a second).

Is there a better way to pack my data than I'm doing or perhaps a better way to send the data than glDrawElements? I don't think using a VBO will help as the data being sent changes every frame.

Any idea's would be appreciated!

# Answer
> 3 votes
Yes, it's somewhat to be expected (although your throughput is really low).

You're using about the worst method of drawing with vertex arrays: drawing indexed with client-side vertex data requires the GL implementation to:

* parse all the indices to find the min/max on each draw
* transfer all the vertex data from min to max on each draw.

Note that if you remove the draw, the GL will not do any of it, and it *will* be real fast.

if you don't want to use VBOs (they still help in that the GL can figure out easier how much to transfer), you can use glDrawRangeElements, which specifies the range of indices that the GL will transfer (ie the first of the 2 bullets).

Also, are the indices changing each frame too ? If they don't, you can store them in an index buffer. (but be careful: at that point, if you don't use glDrawRangeElements, the GL usually has to bring the index buffer back from the device, find min/max, and transfer vertex data. That's even worse than your current state)

# Answer
> 0 votes
Have you tried simply reducing the size of the array, and seeing if it makes a difference? I have a feeling you are getting a false positive; by taking out the ONLY draw call, I think you are affecting OpenGL more significantly and I'm pretty sure if you replace it with an easier call you'll still see 100% CPU.

If that is the case, then you need to make sure you are sleeping in each iteration of the game loop, or enable vsync. If you don't sleep and just have a tight draw loop then you will naturally take up 100% of one CPU, but if you just add a sleep(0) call it should reduce to ~0% CPU.

Or I could be totally wrong; if that's the case, I apologize in advance.

---
Tags: opengl, performance
---


# Question
Title: Is there a plugin to integrate Face FX with Blender?
Is there a plugin to integrate Face FX with Blender? I only see plugins for Maya, Max, SoftImage, and MotionBuilder on the Face FX website.

# Answer
Well, I haven't used FaceFX myself, but I do recall FaceFX uses Ogre for its editor/viewer (here is a forum post about it), and there is an excellent Ogre exporter for Blender available here (for versions 2.4.x I believe). So you could export from blender into Ogre's format, then load that into FaceFX. It's not a plugin or direct integration, but I suspect that's as good as it's going to get unless the FaceFX devs decide make a plugin (maybe contact them about it?).
> 2 votes

# Answer
you can get facefx data out to fbx format, and it looks like you might be able to find an fbx importer for blender. that is probably your best bet.
> 2 votes

---
Tags: 3d, blender
---


title: Resource Managers - Are they any good?

text:
# Question
Title: Resource Managers - Are they any good?
I've seen many a time in source code, things like this \[well, this is more of a pseudo C++ idea of mine\]

```
typedef shared_ptr<Resource> ResourcePtr;// for ease
ResourcePtr sound1 = resourceManager.Get<SoundResource>("boom.ogg");
sound1->Play();
ResourcePtr sprite = resourceManager.Get<Image>("sprite.png");

```

I was just wondering how useful a class like this was, something that:

* Loaded media files
* Stored them in memory
* Did this at the start of a level - loading screen.
* Cleaned up

Rather than having a system of:

* Resources are held by entities only, or loose.
* Responsible for own load into memory.

The first is a 'manager' as such; something I feel indicates it's wrong to use. However, it allows for something like a vector of resource names to be passed, rather than having to scramble around finding everything that needs to be loaded.

# Answer
A good resource manager is key to how well - and how flexible - your game 'engine' is going to be.

Not only does it solve a lot of problems with low level resource management, but it also helps to ensure that resources are loaded only once, and then reused if they are already loaded.

If the resource system is abstracted well, the underlying details can wary between file system, physfs storage, sql even...

You just request a resource, and it's given to you.

No need to worry about resource IDs and stuff like that.

Duplicate resource conflict handling, etc.

Let the resource manager sort that out.

Depending on how you design it - if C++ then make friends with your scenemanaging class(es) to ensure that ownership is properly handled.

Resource pool ?

No problem.

Forgetting to release resources?

No problem.

Same interface to resources no matter where they are: memory, disk, archive, network.

No problem.

Do you want streaming?

Threading?

Let your resource management hub take care of that.

And you can rest assured that it will inform you when the resources are ready to be used.

Ogre 3D has a very flexible resource management system, but I am sure there are others 'out there'.
> 21 votes

# Answer
I recently wrote a resource manager which works pretty well for my case. Main features:

* Resources are requested by string ID, for example, `ResourceManager::instance().getTexture("textures/player.png")`. The texture ID is currently mapped straight to a file on disk, which is convenient during development, but this will later be replaced by lookup in some archive.
* The resource manager holds on to a map of IDs to resources, so it won't reload a resource that has already been loaded.
* The above call does not return a `Texture` object, but rather a `Resource<Texture>` object; the caller is expected to store the `Resource<Texture>` object and not the actual texture. The `Resource<Texture>` acts like a smart pointer to a `Texture`; its `operator*()` returns the `Texture` object itself. The advantage is that the actual texture can be reloaded, or unloaded, without the need of updating all clients.
* The resource manager checks periodically whether files on disk have changed, and reloads them if necessary. This allows me to modify textures or shaders and see the result without even restarting the game.
* Resources can be dependent on each other. Most, if not all, resources depend on a `File` resource, which is the file they were loaded from. If, for example, a model depends on a texture, the model will be reloaded whenever the texture's file changes on disk.
* When a resource cannot be found, or fails to load, a default resource is silently substituted. This allows me to use resources that I haven't yet created, without crashing the game. (Planned feature: indicate "essential" resources such as GPGPU shaders, without which the game cannot properly run at all.)
* Reference counting, and unloading of unused resources, can be added easily. Since my game is pretty small, I haven't had a need for this yet.

I think that this feature list shows that, yes, resource managers can be good!
> 15 votes

# Answer
One of the reasons for having a resource manager is the sharing of resources. For example, when you call `resourceManager.Get("sprite.png")`, if "sprite.png" is already loaded, the resource manager can simply return a pointer to the already loaded sprite resource rather than creating a new image and reloading it from disk.

A resource manager can also cache resources, so that although the last reference to a resource has been dropped, the resource manager can choose to keep it in memory in case it gets loaded again in the near future. The resource manager would be programmed to automatically handle all memory management with your resources.

Finally, I think a very useful feature is the in-game reloading of resources. Since the resource manager holds handles to all the games resources, you can build in a function which causes all the resources to be reloaded from disk and updating the game in real-time, which is extremely useful for artists/designers who work with your game.
> 2 votes

# Answer
Another benefit is, besides caching and reference counting is that it can handle dependencies (model a needs texture b? I'll get it for ya!) and load order issues (model a needs to know what shader b requires? Let me load shader b before loading the model!)
> 1 votes

---
Tags: architecture, assets
---


# Question
Title: Using The Box2D Polygon "Set()" function?
I'm using the Box2D physics engine. And there's a type of shape for box2D called b2PolygonShape.

In this class, you can create polygons. There is also a Set() function that takes an array of points and a vertex count.

Box2D has an example like this:

```
// This defines a triangle in CCW order.

b2Vec2 vertices[3];

vertices[0].Set(0.0f, 0.0f);

vertices[1].Set(1.0f, 0.0f);

vertices[2].Set(0.0f, 1.0f);

int32 count = 3;

b2PolygonShape polygon;

polygon.Set(vertices, count);

```

This works. Yet when I tried to practice and mess with this function, I did this:

```
  b2Vec2 vertices[4];

  vertices[0].Set(0, 0);
  vertices[1].Set(0,10);
  vertices[2].Set(10,10);
  vertices[3].Set(10,0);

  int32 count = 4;

  b2PolygonShape polygon;

  polygon.Set(vertices, count);

```

When I compiled and ran this, it crashed after the Set() function. Wouldn't this create a square?

Also in the console I got this:

```
Assertion failed: s > 0.0f

```

What did I do wrong?

# Answer
> 10 votes
That's because the four vertices you provided are in clockwise order and Box2D assumes they're in counter-clockwise, like in your first example. So it should work fine if you change it to:

```
  b2Vec2 vertices[4];

  vertices[0].Set(0, 0);
  vertices[1].Set(10,0);
  vertices[2].Set(10,10);
  vertices[3].Set(0,10);

  int32 count = 4;

  b2PolygonShape polygon;

  polygon.Set(vertices, count);

```

And by the way, if you're just creating a box-shaped polygon, you can use the convenience function

```
void b2PolygonShape::SetAsBox(float32 hx, float32 hy, const b2Vec2& center, float32 angle)

```

# Answer
> 0 votes
You could determine the winding of the polygon, and then reverse it if it is anti-clockwise.

One common method is to calculate the area of the polygon using the algorithm below. It will return a +ve number for clockwise winding, and a -ve number for anticlockwise winding.

Here is a Python example:

```
def poly_area(verts):
    """
    Return area of a simple (ie. non-self-intersecting) polygon.
    Will be negative for counterclockwise winding.
    """
    accum = 0.0
    for i in range(len(verts)):
        j = (i + 1) % len(verts)
        accum += verts[j][0] * verts[i][1] - verts[i][0] * verts[j][1]
    return accum / 2

```

---
Tags: 2d, physics, box2d
---


# Question
Title: Does PS3 have a program similar to the "Xbox 360 Creator Club"?
Wondering if the PS3 has a way for game developers to make free / affordable games available to their consumer base? Is the only way to get your game on the PS3 to go through an approval process which may cost money?

# Answer
> 3 votes
No, there is nothing equivalent to XNA on the Xbox 360.

There is LittleBigPlanet though, depending on how complex your game needs to be ;)

# Answer
> 3 votes
No, there is no Creators Club equivalent for PS3, however Sony does have PS3/PSP Minis. There's a \[rather large\] outlay for a devkit though. More details can be found in the Minis Guidelines available on the License Enquiry Page

# Answer
> 0 votes
If you somehow have a PS3 that hasn't been updated in a while you could use OtherOS to run some stuff under Linux. The GPU is disabled though, so nothing needing a lot of horsepower unfortunately.

---
Tags: xbox360, publishing, playstation3
---


# Question
Title: MeshTextureCoords element in DirectX .x file
What is the significance of `MeshTextureCoords` element in a .x Mesh file?

# Answer
Don't they kind of make it obvious? The name 'MeshTextureCoords' makes me think of Texture Coords of a Mesh.
> 1 votes

# Answer
I'm going to go way out on a limb here, and suggest that they specify texture coordinates for the mesh.
> 0 votes

---
Tags: directx, 3d-meshes
---


title: Frustum Culling with VBOs

text:
# Question
Title: Frustum Culling with VBOs
I have terrain being rendered in my project using VBOs in OpenGL. I would like to apply some Frustum Culling but have no idea how to access each polygon as its drawn to check if it is in view. I think this is where octrees come into play but I have no idea how this is really done. Does anyone know a good tutorial on how to do this specific thing or have some pseudocode for me?

Thanks in advanced!

# Answer
More information on how you are storing the terrain data would be helpful here. Are you storing it chunks? Are you constantly rebuilding the VBOs? Is all of the terrain in one VBO and you are rendering pieces of it at a time?

Trying to cull per polygon is probably going to introduce more overhead than it saves. The larger a chunk of terrain you can test at once, the quicker the culling will be, with the obvious trade-off of accuracy. In the end, you will need to do some profiling to figure out what the optimal point of that trade-off is, so creating a system that allows you to dynamically change how your terrain is broken up will be very helpful.
> 3 votes

# Answer
A GPU *can already* cull the polygons on a per-polygon basis, but this happens at rasterization/setup time which happens *after* vertex shading (using Vertex/Geometry/Hull/Domain shaders). This means that the GPU can still end up shading polygon vertices that will end up getting culled. If this happens, the GPU will have done a lot of work for nothing and is therefore a waste of GPU cycles.

For this reason, we try not waste GPU cycles by culling invisible geometry on the CPU side (or GPU side using DX10+ features such as DrawIndirect and/or predicated rendering) in batches of polygons by simply not calling draw for those batches.

Typically that batch of polygons can be represented by a sphere or box that surrounds all those polygons. This bounding sphere/box is then tested against the frustum and if it touches the frustum, the draw call is invoked for those polygons. If not, the draw call is skipped. An octree is simply another way of determining which batches of geometry are visible, except it organizes that data in a hierarchical fashion. Octrees are not necessarily suitable for all geometry.

Some fairly good references that explain the sphere/frustum technique follow:
> 1 votes

---
Tags: c++, opengl, optimization
---


# Question
Title: What are the most common splines you will find in game development?
List here the most common splines found in game development, how many points the method needs to interpolate a curve, and how can you build a data type that allows you to get an interpolation of the curve points. Examples: Bezier curves, B-Splines, Cubic Splines, etc.

P.S.: I'm putting this as a community wiki so we can list all kinds of spline interpolation.

# Answer
The most simple case is a linear interpolation for a straight line:

(x0, y0) * ------------------------ * (x1, y1)

Say t is between \[0, 1\]:

```
function lerp((x0, y0), (x1, y1), t):
    return (x0+(x1-x0)*t, y0+(y1-y0)*t)

```
> 4 votes

# Answer
Catmull-Rom splines (a type of cubic hermite spline) can be quite useful, if you've got a set of points that you want to create a smooth path between (without defining any additional control points), such as camera paths

For all the maths, see:

http://en.wikipedia.org/wiki/Cubic\_Hermite\_spline

If you're using D3DX, there's some handy functions for dealing with them (D3DXVec3CatmullRom)
> 4 votes

# Answer
**Edit:** Sorry, as Jason points out in the comment, the following answer is not about splines but about two-dimensional linear (or *bilinear*) interpolation. I am choosing not to delete it in case someone might find it informative.

---

I've created a simple 3D terrain and then wanted my character to walk across the terrain. So, to find the character's height at any point on the terrain, I used bilinear interpolation.

Here is the Java code I use for the bilinear interpolation:

```
/**
 * Interpolates the value of a point in a two dimensional surface using bilinear spline interpolation.
 * The value is calculated using the position of the point and the values of the 4 surrounding points.
 * Note that the returned value can be more or less than any of the values of the surrounding points.
 *
 * @param p A 2x2 array containing the heights of the 4 surrounding points
 * @param x The horizontal position, between 0 and 1
 * @param y The vertical position, between 0 and 1
 * @return the interpolated height
 */
private static float bilinearInterpolate (float[][] p, float x, float y) {
    return p[0][0]*(1.0f-x)*(1.0f-y) + p[1][0]*x*(1.0f-y) + p[0][1]*(1.0f-x)*y + p[1][1]*x*y;
}

/**
 * Finds a 2-dimensional array of the heights of the four points that
 * surround (x,y).
 *
 * Uses the member variable "verts", an 2D array of Vertex objects which have
 * a member "height" that is the specific vertex's height.
 */
private float[][] nearestFour(float x, float y) {
    int xf = (int) Math.floor(x);
    int yf = (int) Math.floor(y);

    if(xf < 0 || yf < 0 || xf > verts[0].length-2 || yf > verts.length-2) {
        // TODO do something better than just return 0s
        return new float[][]{
                {0.0f, 0.0f},
                {0.0f, 0.0f}
            };
    } else {
        return new float[][]{
                {verts[yf][xf].height, verts[yf][xf+1].height},
                {verts[yf+1][xf].height, verts[yf+1][xf+1].height},
            };
    }
}

```

Note that bicubic interpolation might present smoother or more realistic interpolation across distant points; but I choose to go with bilinear because I have a dense grid, in an attempt to optimize (perhaps prematurely).
> 0 votes

---
Tags: mathematics, splines
---


# Question
Title: What coordinate system to use to handle 2D UI?
Following on from the aspect ratios question, I'm interested to hear what other people are using when working on 2D UI systems (most likely their own home-grown solutions). Specifically, how do you handle coordinate systems. To my mind there are three options:

1. Hard-coded co-ordinates (e.g.: 0 -\> 720, 0 -\> 576)
2. Normalised co-ordinates (0.0 -\> 1.0, 0.0 -\> 1.0), mapped into real coordinates before rendering
3. Virtual co-ordinates (e.g.: 0 -\> 1600, 0 -\> 1000), mapped into real coordinates before rendering

Hard-coded is obviously only useful if you're on a fixed platform and know what your screen space coordinates are in advance, or if you're prepared to author screen layouts for every possible set of screen dimensions.

Normalised co-ordinates are nice, but suffer from ambiguity when the aspect ratio of the screen isn't fixed (e.g. 0.75 maps to a different physical co-ordinate when running in widescreen than it does in 4:3). Also, for the authors, it's really counterintuitive to declare a UI element to be (0.2 x 0.2), only to find it's not actually square when rendered.

Virtual co-ordinates are unambiguous, but suffer from the same problems as normalised co-ordinates at the remapping stage: a tiny decimal discrepancy can result in off-by-one errors meaning that UI elements which should tile now have a seam between them.

Similarly, when you do have a fixed resolution screen, both normalised and virtual coordinates mean that it's very difficult to guarantee a 1:1 mapping between your artist's finely crafted pixels in the UI image, and pixels on screen, meaning you run the risk of nasty scaling artefacts (assuming you're rendering as textured quads on screen).

We've gone with the virtual co-ordinate approach, specifically to avoid ambiguity about aspect ratios. So when rendering to a 16:10 screen, the UI space is (0,0) -\> (1600,1000), but when rendering to 4:3, the usable UI space is actually (133,0) -\> (1467,0).

Are there any better solutions that I'm just not aware of? Are there any good strategies for minimising the problems these 3 approachs have?

# Answer
I think I agree that normalised co-ordinates don't really map well to UI stuff.

What I typically do for 2D layouts, is basically your "virtual" co-ordinate space, but I pick a space which maps 1:1 with my prefered target resolution (1280x720, for example). It's not fixed, but it's intuitive to deal with and I know that in 90% of cases it'll look just right. Obviously it's important not to get complacent, and to actually *check* different resolutions often.

For crispness when remapping resolutions, I'd borrow some tips from font-rendering, and provide hinting information. So make sure that things which need to be continuous are tagged in some way, while also performing rounding to exact pixels where crisp alignment is necessary.

Perhaps also consider making things more relative. So rather than everything being "position object 1 at absolute X,Y", you could specify "position bottom left of object 2 at some offset from bottom right of object 1". It's easier then to rescale and/or move things about, without losing important relationships.
> 5 votes

# Answer
CEGUI's coordinate system seems really well thought out. It's unified coordinate system blends absolute positioning with relative positioning. You can specify locations like:

* in the middle of the screen
`UDim(0.5,0)`
* five pixels to the left of the right edge
`UDim(1.0,-5)`
* two widgets in the middle but separated by 10 pixels
`HA_RIGHT,UDim(0.5,-5) HA_LEFT,UDim(0.5,5)`
> 5 votes

# Answer
If in doubt, why not go with the CSS box model, or a simplification of it?

You can specify positions in percentages or pixels. You might position containers with percentages but position the items within them by pixels, for example.
> 2 votes

# Answer
I like using virtual coordinates, but based around a common target resolution (preferably one of the highest resolutions that you expect the game to be run at.

These days, a good choice may be 1920x1080.

All artwork and screen mock-ups can be created at that resolution, and it makes it easy to measure positions/distances in pixels.

If running at a different aspect ratio to the virtual coordinates, you can choose how to fit it to the screen (letterboxing, cropping the sides, or a bit of both)

When coding, I find 'thinking in pixels' much easier than thinking in normalised coordinates! - I want the text to be '50 (virtual) pixels in height' rather than '0.0463 units high'
> 1 votes

# Answer
It totally depends on what type of GUI you have, but often games have things anchored along the edges of the screen and in corners, and then they might have a box in the middle of the screen for a modal dialog or something.

If that's the case for you, then might I suggest using a scheme where you specify an anchor and an offset (x,y)? This would be similar to Java's BorderLayout (but maybe with the four corners, four middles of edges, and one center of screen). So for example, you could specify an offset of (0,0) from the top-left corner; then the element would be anchored exactly in the corner of the screen. And then no matter what resolution, aspect ratio, etc., you would have the health indicator in the corner of the screen. But then if you anchor an element to the top right corner, the element would naturally be anchored relative to its top right point (instead of top left), so again it would be automatically anchored to the corner of the screen no matter the resolution.

I definitely recommend against normalized 0.0-1.0 coordinates; these could vary based on floating-point accuracy. GUIs should be mapped to pixels, unless you have a 3D GUI.
> 0 votes

# Answer
A lot depends on the kind of game and the situation. For quick-and-dirty prototypes, I prefer to plan out the UI on graph paper, write down a list of numeric coordinates for a fixed window size, and hardcode everything -- it's easier and faster for me. But for a "real" project where you'd want resizable windows or alternate screen resolutions, that would obviously not be ideal, and some kind of solution that allows for scaling in both directions would be better.
> 0 votes

---
Tags: rendering, gui
---


# Question
Title: Audio Design and XAudio2 Performance Issues
I have a very basic understanding of audio and was hoping I could get some help to resolve a problem with the audio design in my engine. Let me give you a run-down of how I've currently got it fitting together.

I have an AudioManager that handles setting up and tear down of the XAudio2 interface as well as the master voice, and various submix voices that I can use to group sounds. I have a ResourceManager that can be used to load audio files into the required buffers ready for XAudio2 consumption. During my game, I call a method on my AudioManager to play a sound - this obtains the necessary Audio Voice and links it to the right buffer and begins playback.

The first problem I am having is that when there is a lot going on, and a lot of sounds are played at once, I get performance issues - framerates drop, and there is audio stuttering. I currently don't limit the number of concurrent sounds that can be played - can you give me any other advice on a better design, or solutions to limit impact on performance?

The second problem I am having is that if multiples of the same sound are played at the same time, it sounds like the volume has been turned up on that particular sound. I assumed this is to do with wave amplification and tried implementing a Volume Limiter effect on my submix voices. This works to a degree, and I can eliminate any distortion, but the increased volume effect is still noticeable. Can anyone suggest decent values to use for the volume limiter effects, or any other solutions to the problem?

# Answer
> 2 votes
How many sounds do you have playing? In my experience games will use somewhere between 32-\>256 audio channels. To solve your problem you need to work out your audio budget (the amount of processing / memory you will be giving to the audio system) and then prioritise sounds being played.

The methods to prioritise can include :

a) Volume - the lowest being the least important.

b) Priority - a value you set yourself based on the importance of the sound and the likely hood that the user will notice the sound dropping out. Background music, for example, should be set to never be dropped. A random cricket sound for ambience should be high on the list.

c) Grouping - If you have gunshot sounds for example, once they have hit a hard limit (say 15) you would stop adding new gunshot sounds as they wouldn't add to the overall mix.

For your second problem there are two things you can do. One, you need to balance your game audio. This is a fine and somewhat black art that people can spend a lot of time doing in games. The first step is to make sure all your sounds are normalised (http://en.wikipedia.org/wiki/Audio\_normalization). The next is to play through the game adjusting volumes on the fly to get the mix right. Building in some simple debug audio functionality (a remote application that can connect and adjust the mix of the application is ideal) can make this a lot easier.

Why are you playing multiple sounds of the same type? If it necessary you can attempt to a audio compressor (link in comment). Now I don't know if XAudio has one built in, but if not they are fairly simple to implement. This gives you an increase in dynamic range - i.e if there are a lot of sounds and it is getting very loud the compressor will bring the entire mix down in an attempt to fit it in.

# Answer
> 1 votes
It sounds like you know the main answer to the first issue - you need to limit the number of voices. The AudioManager will need some sort of prioritization scheme that drops low priority sounds in favor of the high priority ones.

And that ties into the second question. Are you playing the two instances of the same sound at exactly the same time? Why? - they won't be distinguishable except for the increased volume Or are they slightly offset - like maybe 2 near-simultaneous gunshots - in which case, what's wrong with 2 events sounding louder than one event? That's realistic. It seems to me that you either actually do want the increased volume, or you want the AudioManager to filter out the duplicates to avoid overloading the voice hardware with needless work.

---
Tags: c++, architecture, directx, audio
---


title: Upgrade OpenGL version on Windows?

text:
# Question
Title: Upgrade OpenGL version on Windows?
How do I update the version of OpenGL on Windows so that I can use anything newer than the Version 1.1 header file that is included in the Platform SDK? Even version 7.0A of the SDK for Windows 7 only includes GL.h and GLU.h for version 1.1 of OpenGL. I've installed the NVidia driver for my board that includes OpenGL 4.1 support, but I don't see header files included in this package.

# Answer
> 14 votes
You can download glext.h from the OpenGL website, which has extensions for OpenGL.
Or, download a function pointer handling library like GLee, which solves the problem as well as making it easier to access them; no more functor declarations.

To quote the OpenGL site:

> Microsoft will never update gl.h and opengl32.lib that comes with their compiler. It hasn't been updated since 1995. Basically, the solution is to use glext.h and wglext.h (wglext.h is for Windows only) which define all the GL 1.2, 1.3, 1.4, 1.5, 2.0, 2.1 and above tokens and functions. Keep reading.
> ...
> Download glext.h and wglext.h from The Extensions Registry.

# Answer
> 5 votes
Take a look at this OpenGL getting started page:

http://www.opengl.org/wiki/Getting\_started#OpenGL\_2.0.2B\_and\_extensions1

You'll see that The Communist Duck is right: it's just a matter of downloading a header or two from the extension registry:

http://www.opengl.org/registry/

However, as he also said, it might be easier for you to download an extension handler which does all the gritty work for you, like GLee - or GLEW:

GLee : http://elf-stone.com/glee.php

GLEW : http://glew.sourceforge.net/

# Answer
> 2 votes
You can directly download updated header files and drivers from this page here for Windows. There is even a little how-to-install at the top of the page.

Swiftless OpenGL Drivers Page

I hope this helps!

---
Tags: c++, opengl
---


# Question
Title: What should every graphics programmer write
I've seen this question on SO, but here i want it to focus on GFX.

So in your opinion what applications/features should every aspiring GFX programmer write/change to get better?

Community wiki since there is no "right answer".

LE: Not referring to actual games, but to graphical features for example changing something in an engine (e.g how it loads objects), making a compositor, so on and so forth.

# Answer
My answer is always the same: if you haven't written one before, write a raytracer.

You'll have to deal with optimization structures, numerical precision, and all sorts of other issues, but you'll also work directly with the mathematics of light in a way that you rarely do when dealing with all the hacks and approximations that make up a production real-time renderer.

Strip away all the edifice of loading systems, buzzwords-of-the-week, deferred-this or forward-that, and you're left, finally, with light traveling through a medium. In the end, that's all there is to graphics.
> 22 votes

# Answer
It may be of little practical use these days, but writing at a software renderer, at least a basic one (maybe just some spinning textured cubes), is a worthwhile exercise.

Understanding how to transform, project, clip, depth-sort, rasterize, and texture map polygons yourself will give you a much better understanding of what 3D hardware and rendering APIs are doing
> 7 votes

# Answer
While not rendering code, I think writing a BSP compiler and accompanying traversal code is a nice exercise in vector maths.
Secondly, a deferred renderer. Not because it's the end-all answer to rendering, but it'll give you insight in another approach to rendering.
> 6 votes

# Answer
Learn the mechanics and skills of writing good shaders. While not 100% necessary in all cases, it's a valuable skill to know.
> 2 votes

---
Tags: graphics, software-engineering, graphics-programming
---


title: Clickable hex grid in c#.net

text:
# Question
Title: Clickable hex grid in c#.net
I want to create a Windows Form-based adventure game where the player clicks a hex on a static map to bring up their next encounter. I have the map already and plan to scan it and convert it to a .bmp file. My problem is that I'm not sure how to tie the map image in with the game code. Unless I'm mistaken, I think I need to use some kind of imagemap control. If that's the case, do I need to plot each hex individually, or is there a way to plot the whole map in bulk? I found this article, but I'm not sure if it's relevant to what I want to do or not. I'm just looking for general information or links to relevant articles. Thanks.

# Answer
I really like Amit's Game Programming Information, and it has a whole section on hexagon grids. Perhaps you'd find any of those links to be informative?

Here is the list of links he gives:

>

I apologize if this isn't helpful. Windows Form isn't the ideal platform to develop a game, but I assume you would have one image per grid square and give it an OnClick event. There would be the issue of overlapping corners though... (the transparent corners of the square image that the grid image is on). In a traditional game you would use the above information to figure out how to translate click coordinates (screen space) to the hexagonal grid coordinates (which your link details nicely), and then handle it appropriately.
> 15 votes

---
Tags: software-engineering, c#
---


# Question
Title: Where are the requirements documents for console game software?
I hear that the console game platforms have strict requirements for their games. For example I just read an answer that stated loading screens must have an animation on them so that the game doesn't appear to be frozen -- this makes sense, of course! I think a lot of the guidelines in these books would probably be great information.

Are these documents protected in some way or is there someplace on the internet where I can read them? I would love to read through all the guidelines for good design that the console manufacturers have put in place to give console players a good experience, and probably to adhere to them in my own games (at least those which are not console-specific, obviously).

So, **where can I find these fabled console video game design guidebooks?**

# Answer
> 11 votes
While I can't link you to the actual documents used by "proper" published console games (and, really, unless that's what you're doing, you don't need them), but here are the two documents used for XNA games that go up on Xbox Live Indie Games:

Additionally here is the MSDN page on Xbox 360 Programming Considerations.

# Answer
> 1 votes
I highly doubt that you are going to find these documents unless they have been leaked out somewhere (torrents?). Unfortunately, I believe the only way you'll be able to (legitimately) get these documents is by purchasing the SDK for the specific platform you are interested in (Xbox, Playstation, Wii, etc.).

# Answer
> 0 votes
If the ability to develop a console game - of course, excluding homebrew PS3 Linux/DS/Wii and XBLA with XNA - has a requirement of a well respected developer or company and money to even get a devkit for the platform, I doubt the requirements to create the game are available publicly.
You could, of course, try buying an SDK and seeing if there's any kind of idea there. But you need to be a well referenced developer.
Or, like people get most things nowadays, try the torrent/P2P/file sharing websites.

# Answer
> 0 votes
Both the 360 TCRs and the PS3 cert lists are available on the developer networks. You need to be a registered studio to get access. I've read the Xbox ones enough times that I might be able to answer some suitably generic questions without being in breach of the NDA.

# Answer
> 0 votes
Mind you, a lot of the requirements are fairly nitpicky whereas others are relatively pointless. A good example would be your example of 'a screen must be animating so the game doesn't appear hung' is one of them. Now you're in the situation where games animate the loading screen on their own thread while loading. If the loading thread crashes the screen keeps animating, leading to the false impression that the game didn't crash.

# Answer
> 0 votes
The actual TCRs (what Microsoft calls their set of requirements) are protected under NDA, so you're not going to be able to find them unless you're a "certified" ("approved"? I'm not sure what terminology they use) developer. I personally always err on the side of caution when it comes to NDAs, so I'm even reluctant to provide non-specific information on the requirements. But like you said, while some of them might be nitpicky most of them are common sense rules that exist to provide a friendly and consistent experience to the end-user, and are guidelines you should be following even if you weren't developing a console title.

---
Tags: architecture, books, console
---


# Question
Title: Other than the ESA are there other sources for demographic data?
I'm pretty interested in seeing demographic data as I find them good targeting tools. But other than the ESA reports (free) and NPD numbers (paid) does anyone know any other sources for such data?

# Answer
Here is a website that has very interesting demographics regarding MMORPG's in the US. http://www.nickyee.com/daedalus/gateway\_intro.html

This is from the same site but it has a bit more general data. Just keep clicking the small "Next Page" link at the bottom for more statistics including Good vs Evil, Choosing a Race, and etc. http://www.nickyee.com/daedalus/archives/001558.php

Here is a slide show on demographics for teen and adult gameplay in 2009 http://www.pewinternet.org/Presentations/2009/11--Cheats-for-Video-Game-Marketers.aspx

This is another site that has demographic data on game developers which is useful for those developing an SDK or engine. You can also submit a survey to help improve these statistics. http://archives.igda.org/diversity/report.php

If you are looking for specific demographics you could also try picking up the phone book and calling major players in the game development realm. For example, I am sure Microsoft will have no problem giving you demographics on its specific users. Hope this helps.
> 2 votes

# Answer
These look pretty nice, though I'm not sure:
Free Demographics
US Census Bureau

EDIT: Also, free.
> 1 votes

# Answer
Not free, but you might want to talk to EEDAR.
> 1 votes

---
Tags: game-design, marketing, demographics
---