# Question
Title: semi 3d walls, should I use sprite sheet or render them 3d?
I'm going to develop a game and this is just a prototype of it's graphics.

Knowing that my primary target platform is iPhone, I'm wondering if it's better to create a spritesheet containing all possible angles from a wall or is it better to render them with 3d boxes?

here is sample spritesheet I was going to use:

# Answer
> 7 votes
If you're going to use a perspective camera like that, you're really not saving anything by using a sprite sheet. I mean I guess you could render all of the potential walls in one quarter of the screen and then do mirroring for the other 3 quadrants, but that assumes a stationary camera.

Why would you want to use a sprite sheet anyway? You're not really going to save on transparent drawing as the sprites themselves are going to have to be transparent.

Plus as a sprite sheet you're limiting yourself if you want to do any interesting camera effects like zooming, tilting, panning, etc.

# Answer
> 2 votes
You'll likely find that going full 3D is going to be a *lot* simpler than your proposed sprite sheet approach. For example, you'll get perspective for free instead of having to do a lot of tedious and complex calculations for each wall. It will also be considerably more lightweight on texture memory usage.

# Answer
> 2 votes
Did you have a look at cocos3d? It allows you to mix 3d content with regular cocos2d layers/nodes.

Since you're already using cocos2d, this might be the ideal choice for your task. AFAIK the import of 3D models for cocos3d is kinda limited at the moment and there are problems with exporting animated assets from blender. But for simple cube-like objects like your wall, this seems to be a perfect fit.

# Answer
> 1 votes
If going full 3d just for the walls is too much, I'd suggest 'hard coding' the 3d just for the walls.

One way of doing this, if you can create and change shapes in runtime: every wall is a 2d square. 4 vertices, vertex1\_bottom, vertex2\_bottom, vertex1\_top and vertex2\_top. Make bottom vertices move with the foreground and the other two vertices would be slightly displaced and move with a slightly larger velocity. This is the usual technique for parallax effect in older games (8/16 bit, for example) for the background, only here you would be using it in a different way.

The equations for the displacement and velocities are actually quite simple. If we put the coordinate system on the **center of the screen** (this is very important) all you have to do is scale the top vertices according to the bottom ones:

v1\_top = factor * v1\_bottom;

v2\_top = factor * v2\_bottom;

You might need to experiment with the factor. Basically, the higher this factor the closer to the camera the top of the walls will appear (a low value will probably work best).

I'm making this stuff as I write so there may be some conceptual problems. Let me know if you find any. Hope this helps :)

---
Tags: iphone, cocos2d
---


# Question
Title: Problem representing torque as a quaternion
Euler angles are much more intuitive to me than quaternions for representing 3-dimensional rotations. In fact, I barely understand quaternions at all. I use quaternions for rotation because people with more knowledge than me say they're better. (I'm familiar with the gimbal lock problem and axis-angle rotations, but that's getting away from the point.)

Given my nebulous understanding, what I'm trying to do might be really stupid. I want to rotate an object by applying an angular force (torque) which I'm representing as a quaternion plus a duration. To *move* the object, I do something like

```
abstract class PhysicsBody
    {
    protected Vector3 velocity = Vector3.Zero;

    public void ApplyForce(Vector3 force, float duration)
        {
        // mass and other concepts omitted for brevity
        this.velocity += force * duration;
        }
    }

```

and it works as expected. I figure rotation should work similarly, like so:

```
...

protected Quaternion orientation = Quaternion.Identity;

public void ApplyTorque(Quaternion torque, float duration)
    {
    this.orientation *= torque * duration;
    }

```

But of course it does not. If `duration` is less than 1, orientation does not change. If `duration` is greater than 1, things get weird and break after a few seconds.

I've experimented with renormalization, but I'm fumbling in the dark. What is the "correct" way to do this?

# Answer
> 4 votes
A torque has an axis and a magnitude, so in principle you can represent it as a quaternion. However, you have two problems. The first is that your parallel is wrong. torque :: force as orientation :: position, so you need to integrate it twice. Secondly, the way you're applying it is wrong.

Question: given a quaternion representing a rotation of a certain amount around a given axis, how do you derive the quaternion representing twice the rotation around the same axis?

The answer isn't "Multiply by two". You have to square the quaternion to apply the rotation twice. So scalar multiplication isn't what you're looking for.

You'll probably find that it's easiest to use axis-angle for the angular velocity and torque, and use quaternions only for the orientation. These links may also be helpful, but are too long to summarise here:

# Answer
> 4 votes
Torque and angular momentum should probably be represented as ordinary 3D vectors, not quaternions. Angular momentum vectors add according to the parallelogram rule, and torque is the time derivative of angular momentum, so you apply a torque to change angular momentum exactly the same way as applying an acceleration to change velocity.

Then you multiply the angular momentum by the inverse of the inertia tensor, to get an angular velocity, and integrate it to get a quaternion for the orientation by using the rule: dq/dt = 1/2 omega q, where q is the quaternion representing the current orientation of the body, and omega is the angular velocity vector. Omega has to be converted to a quat by placing 0 in the scalar (real) component, so you can multiply it by q using quaternion multiplication.

# Answer
> 1 votes
You might want to check out slerp, it is used for rotating 'more or less' with quaternions. Just use an empty quaternion, the base quaternion and 'slerp' more or less.

---
Tags: xna, physics, quaternion
---


# Question
Title: Setting up Payout on the Microsoft App Hub
I am a Windows Phone 7 developer from India. I want to set up the Payout option on the App Hub for the Paid apps I release.

What's the procedure? Do I have to physically mail the W-8 form to Microsoft? Any other things I should know about?

Can I release a paid app now and set up the payout later, in a month or so?

# Answer
Your best bet is to ask on the App Hub forms.

**I'm speaking from what i know about releasing xbox games.**

You can release a paid app and set up the payout later. You'll get any amount earned so far in your first payout.

Yes, physically mail the W-8 form.

For any other things to know, search the forums at http://forums.create.msdn.com/
> 2 votes

---
Tags: windows-phone-7, marketing
---


title: Situational awareness in path finding

text:
# Question
Title: Situational awareness in path finding
Assume you had to find the shortest path through a dungeon, where certain passages are only opened to you after certain items were collected, like locked doors and keys, for instance.

The normal gut reaction to the words "shortest path" would obviously be A\*. But A\* would fail in such an environment, since I see many problems defining a reliable heuristic and, additionally, it is very likely, that a node has to be visited multiple times, which is also not possible in conventional A\* and would also make the heuristic harder.

What I thought about is simply looking for a path from the start of the dungeon to the end, ignoring any blocked doors. After this path is found, for each of the doors blocking our way, an additional path looking for the appropriate key and back to the door would be sought and traversed before the door is even reached. The very same system would be used to handle a situation, where the path to a key needed to open a door is again blocked by another door, which needs to be opened first.

A big problem I see with my solution is that after all the paths including the ones for item acquisition are found, the total distance travelled by the agent might not be the smallest possible, since there might be other blocked doors that are farther from the goal but have their appropriate key much more easily available. A\* would have neglected these doors on the first pass where blocked doors are simply ignored.

I'm sure I'm not the first one to try to solve this and I would appreciate some input on the problem.

# Answer
The way to handle such a situation optimally using straightforward A\* is to expand the search space. That is, imagine that there exists a separate copy of the dungeon for each combination of items your character might be carrying.

In each copy of the dungeon, the doors which are passable are exactly those that can be passed using the corresponding set of items. The only way to pass from one dungeon copy to another is to stand on the location of an item and pick it up.

You can extend this trick to include other state changes, such as switches that can open and/or close doors. You could even allow the player to drop items, although this can get complicated since the state must then include the location of each dropped item, increasing the potential search space enormously.

A very useful optimization is to precalculate the shortest paths from each door (actually, each side of each door) and item to every other reachable door/item, *assuming that all doors are locked*. Once you have those paths, you can just treat each of them as a weighted edge in a graph connecting these *significant locations* to each other, and ignore all other locations.

For example, assume that your dungeon has ten doors and five keys. Then there will be 2 * 10 + 5 = 25 significant locations, and 2^5 = 32 possible item combinations, for a total of 25 * 32 = 800 nodes in the full search space. This is a very modest number, especially given that much of the search space is likely to be unreachable.
> 8 votes

# Answer
From a real-world viewpoint: If you were headed from A to B and found a door D in your way that was locked, you'd realise you have to find key D. So if your AI is as unknowing as the typical human is, that would involve scouting for the key, which is a set of tiny pathfinding steps in and of itself. On the other hand you might want your AI to know, before even attempting a path, that there is a locked door on that route, and in that case it will probably also know where to find the key.

Either way, the issue is one of connectivity at two levels. At the "on-the-ground" level, you know you can always move safely within one undivided zone... undivided by locked doors, that is. This is where you can use your current A\* pathfinding implementation freely. (In a simplistic example, you could see a zone as a single room. You can't get to any other room without unlocking a door. In reality, it could be an entire region of your dungeon.) This is the foundation of your entity movement, but it's a bit like walking around with your eyes downcast, instead of surveying the area around you first -- you're likely to walk into a lamppost. Or in this case, a locked door. So your ground-level maps which your A\* runs on must restrict the player to movement only within the current zone.

Next, there is a higher level map, which is more topological than topographical in nature. It doesn't really care about the on-the-ground details of obstacles and so on, it only cares about the connectivity between zones. This topological map bears connections between even zones that currently have a locked door between them, since it shows the ideal connectivity of all zones in your dungeon. In it's edges -- each representing a door between zones -- it stores what key is yet needed, if any, to open that door, else it is considered open. So in searching this graph for shortest path, *it should limit that found path to only routes that are already open*, by checking the data in the edges as the search runs. Connectivity here does not imply openness, rather it implies potential openness.

When you want to move to a point that falls within a separate zone, you first search your higher level map to find a path. (A\* or any other shortest path algorithm may be used at this level.) Once you find a path, that higher level map should also provide info on which door you need to use to get from your current zone to the other zone. Now, in the local zone, you can do ground-level AI to navigate to that door. Once the door has been reached, your character can pass through that door/portal. He is now in zone B. If this is the target zone, he can use ground level navigation to go to the key. If it isn't, then you need to repeat step one until you reach the target zone.

There is the possibility that a key being sought is itself behind a locked door... and that the key to that door is likewise... and so on ad nauseum. This is essentially a dependency resolution problem, and there are a few ways to tackle this, one of which is Petri Nets. See this excellent paper.

PS. If you are creating your dungeon procedurally, then as you do so, you can store information on dependency ordering, provided you already know the starting position of the player.
> 5 votes

# Answer
> The normal gut reaction to the words "shortest path" would obviously be A\*. But A\* would fail in such an environment, since I see many problems defining a reliable heuristic and, additionally, it is very likely, that a node has to be visited multiple times, which is also not possible in conventional A\* and would also make the heuristic harder.

Firstly, an admissible heuristic doesn't have to be perfect. It just has to be an underestimate and it has to be better than nothing. Given that you're working with actual distances, it seems likely that A\* would at least be of some help, and even if the heuristic didn't improve the search much, it would probably still be better than a standard breadth-first search or similar.

Secondly, A\* can visit a node as many times as you like. Remember that A\* is not a path-finding algorithm but a search algorithm. It searches through states. In games we often equate a state with a position, because we don't care how you reached that state - just how short the path was to get there. However in a problem like this the state is a combination of the position plus any other relevant state such as keys held.

It is true, however, that these complications will move A\* from the realms of 'very efficient' to 'will succeed, but probably not in the timescale I require'. What is the timescale you require? In fact, why do you need to do this - do you really need the shortest path, or would any reasonable path suffice?

> What I thought about is simply looking for a path from the start of the dungeon to the end, ignoring any blocked doors. After this path is found, for each of the doors blocking our way, an additional path looking for the appropriate key and back to the door would be sought and traversed before the door is even reached.

It's easy to prove that such a system would be suboptimal. Where would you begin the additional path from? If from the start, then you've wasted your time plotting the original path to the door. If from the end, then placing a key near the start means the path traverses the map twice when once would suffice. If you try and calculate optimal merge points for the paths to and from the door and the original path, that will yield an optimal result but will be resource-intensive due to the number of permutations and difficulty forming a heuristic to simplify the search. If you add multiple keys into the problem then you have the Travelling Salesman problem which is not easy to efficiently solve.

What I would attempt, if it's possible to relax the 'shortest path' criterion, is this:

* Create a high-level graph which only contains important locations - key positions, door positions, positions within locked areas, and note the straight-line distances between them. If your map already divides up into rooms or other discrete locations, that's great.
* Use A\* to find a path through this graph, from the start to the end. The normal Cartesian distance heuristic should be sufficient to keep it manageable.
* Now, with this simplified path between these way points, use A\* again to plot a low level path from one way point to the next.
* Join these low level paths together to form your whole path.

Once I got that working, I'd consider some minor optimisations - eg. weighting the areas with keys in more leniently so that the low level pathing would be more likely to make small detours to collect keys.
> 2 votes

# Answer
with the information you provided I think you can use A\* with just a little modification. in a normal A\* algorithm, you mark every node as you pass over them to make sure you won't ever pass it again. That is the exact part that makes problem with the Items. The key change is to remember what was your items when you previously passed from a node. here is a sudo code explaining what I mean:

```
if (nodestoCheck.notempty())
    newNode = nodeToCheck.first;
    if (notpassed(newNode.pos, newNode.items))
        if (room(newNode).containItem)
            add NewNode + room(NewNode).items
        else
            do normal A* algorithm for new Node

```

with this algorithm you first start checking all nodes with no item. there is a high possibility that your first searching group end up blocked by some doors. but it'll find a key to that door before it search all the rooms. from that key you start a new search having that specific key. this time when you reach the door you may pass it. the same routine continues until you find your way out of dungeon. the only problem may be memory consumption whenever there are lots of doors and keys. although it won't be a problem for at least 10 or 15 keys.
> 0 votes

# Answer
Why don't you just use normal A\*, and model locked doors as impassable regions; once you pick up the key (walk on the key tile?), that changes that particular locked door into a passable region.

What this means is that your path-finder will go for the shortest *keyless route*, and if it finds keys along the way, it will incorporate that into its path *if that helps.*

That seems pretty reasonable to me. It's not perfect, but it's a simple solution to the problem.
> 0 votes

---
Tags: ai, path-finding
---


# Question
Title: Multi-tile agent path-finding algorithm?
Suppose we have a uniform rectanglular grid as shown below. The `a` is an agent, `o` is obstacle and `g` is goal. What are the options of handling multitile agents (e.g. dragons or tanks)?

```
.  .  .  .  o  .  .  .
.  .  .  .  o  .  g  .
.  a  a  .  .  .  .  .    <-- too tight
.  a  a  .  o  .  .  .
.  .  .  .  o  .  .  .
.  .  .  .  .  .  .  .    <-- should go through this gate
.  .  .  .  .  .  .  .
.  .  .  .  o  .  .  .

```

**Update:** Found this article on clearance-based pathfinding from Red Alert 3. It covers not only the clearance - size, but also a capability - ability of certain units to use certain terrains.

# Answer
The simplest approach I can think of is to designate one tile of the vehicle as the basis point which determines where the vehicle is, and for each potential position in a path, calculate whether the vehicle can fit in the space around that tile, and if not, reject that position as a possibility. Basically the check for whether a tile is passable or not changes to a check whether the given vehicle collides with anything while in this position or not.

For example, if you chose the top left of vehicle 'a' as the basis tile, when you evaluate a node you'd also check the one below it, the one to the right, and the one below and to the right. In this case the obstacle below the basis tile would collide and so this position would be rejected. (In fact, you'd not even get that far, as all positions 1 square to the left of the small gate would also be rejected.)
> 4 votes

# Answer
I would suggest something similar to dilation used in image processing.

Use your vehicle as a kernel to dilate your obstacles. Eg. your kernel could look like this (this would be a good kernel if your vehicle has it's "origin" at top-left):

```
1,1
1,1  <-- kernel "origin" is at 1,1

```

Basically you run through each "pixel" (or tile in your case) and render the kernel to a target whenever you encounter an obstacle. The kernel should be rendered with it's origin position at the position of the obstacle.

To illustrate, here's what will happen with a single obstacle:

```
[ source ]  ---->  [ target ]
. . .              o o .
. o .              o o .
. . .              . . .

```

Then, your grid dilated with this kernel would look like this:

```
.  .  .  o  o  .  .  .
.  .  .  o  o  .  .  .
.  .  .  o  o  .  .  .
.  .  .  o  o  .  .  .
.  .  .  o  o  .  .  .
.  .  .  .  .  .  .  .
.  .  .  o  o  .  .  .
.  .  .  o  o  .  .  .

```

Which would be the grid you want to perform your vehicle path-finding on.

**Update:** Updated above with some more information. Also this would actually work for different shaped vehicles but will get computationally expensive with a huge map and a large kernel (the smaller the kernel, the better).
> 2 votes

---
Tags: path-finding
---


title: Change flag if mousepress while on loop

text:
# Question
Title: Change flag if mousepress while on loop
I have this program that starts a loop when the key is pressed

The problem is that when i start the loop, i want to be able to stop it halfway with my mousepress.

The problem is that it doesn't register my mousepress until my loop is done.

How do I stop it halfway if the mouse was pressed in my loop? I tried a flag, if(mousePressed) but the flag doesnt change until the loop is done

# Answer
You have to register the function that handles the callback function to be executed when a button is mouse pressed during your display() loop. This has to be done before running the main loop, when you are initialising everything that GLUT requires.

```
glutMouseFunc (MouseButton);

```

Then you need to define the callback function itself, for example, something like this.

```
void MouseButton(int button, int state, int x, int y)
{
  // Respond to mouse button presses.
  // If button1 pressed, mark this state

  if (button == GLUT_LEFT_BUTTON)
    {
      g_bButton1Down = (state == GLUT_DOWN) ? TRUE : FALSE;
    }
}

```

Note that `g_bButton1Down` is the global variable that you have to check to see if the mouse button is being pressed or not inside your main display() GLUT loop.

Take a loop at the glutMouseFunc specifications.
> 2 votes

---
Tags: opengl, glut
---


# Question
Title: How do I create an installer for my XNA demo?
I have a demo coded in XNA3.1 using VS2008. I'd really love to be able to send this to anyone with a PC and let them install and run it without requiring them to have VS installed or the .Net framework etc.

I thought it would be the publish option but I'm a little confused by it. Can anyone shed some light on the matter?

Thank you in advance.

# Answer
***Take your pick***

There are a number of ways to create an installer for anything, including an XNA game.

## 1. Visual Studio Deployment Solution

This one's is fairly straightforward. If you have the Professional edition of Visual Studio, then you can add a Deployment project to your solution and whenever you compile this project, it will compile all necessary dependencies/assets for you and make you a nice installer at the end of it.

This link has most of the information that you would need to get started and contains information about redistributing the .NET framework and other related bits and pieces.

**Pros:**

* Integrated into Visual Studio
* Straightforward in getting a simple MSI installer built and ready to distribute

**Cons:**

* Not available in some versions of Visual Studio
* Difficult to get your installer to do something more complex than installing/repairing/uninstalling.

## 2. WiX

If you don't have the option of creating a Visual Studio Deployment project, due to a limited version of Visual Studio, there are a number of free alternatives available. WiX is one of these alternatives.

It stands for Windows Installer XML and can be integrated into Visual Studio, much like the VS Deployment projects. This also creates an msi installer after compilation. Be warned though, WiX has a steep learning curve, but it does allow for various complexities in your installer.

You can find out more about it here

**Pros:**

* 100% free.
* Powerful. If you want to do something ridiculously complex in your installer, just create a C# DLL, link it into your WiX project and run it as a Custom Action. (Almost) Anything is possible.
* Integrates into Visual Studio nicely, works very, very well with .NET projects.
* People on the WiX mailing list provide a lot of support.

**Cons:**

* Difficult to grasp and get started due to the steep learning curve.
* Errors are almost nonsensical when you start out and it takes a while to actually figure out what the real problem in your code is.
* Not enough tutorials on the subject. Most (in my opinion) are badly worded, badly structured and downright confusing.

## 3. NSIS

NSIS is a fully featured installer creation package. I'll admit, I've barely used it, but when I did it was a pleasant experience. There are a good amount of tutorials, it's completely scriptable, but I'd probably say it's not as powerful as WiX (if anyone feels this isn't the case, then feel free to correct me).

It's completely free and open source and you can find more information on it here.

**Pros:**

* 100% free.
* Scriptable installer, so you should be able to code some complex behaviour.
* Good amount of tutorials, good support.
* Doesn't make an MSI, but an EXE instead (MSI's can be bad)

**Cons:**

* Doesn't make an MSI, but an EXE instead (MSI's can be good)
* Fairly limited by the scope of the scripting commands

## 4. InstallShield and InstallAnywhere

I've never used InstallShield, but for completeness' sake, I thought I would mention it here. My only experience is from what people have told me, so I won't list out the pros and cons.

As far as I'm aware, it is pretty fully featured, however it is unable to handle a large amount of files (\> 1000). You do need to pay for it though. InstallAnywhere is a cross-platform version of InstallShield. More information here.

## 5. Other Solutions

I'll list the other solutions for deployment here if anyone has any others to add:

Advanced Installer \- The freeware version allows for basic deployment solutions. Thanks for this addition, pek.

## Conclusion

There are a whole host of options available to create an installer for your XNA game. Try out a couple, see what you get on with most. However, the *most important* thing regarding the creation of installers is ensuring that it works on a number of computers. If you're creating an MSI installer, testing is made much easier by running the msi from the command line using the following command:

```
msiexec /i [name of installer.msi] /L*v verbose_log.txt

```

This will write out a log of every single event that the installer is going through, which you can then diff from whatever diff tool you like.

In conclusion, see what fits you and your workflow best, testing is key, and whenever you're testing your installer, always, ALWAYS log the installations (most of the time installers never give you any useful information as to what went wrong).

This turned into something longer than I expected, and I am sorry. But I do hope it helps.

~Ray
> 14 votes

---
Tags: xna, software-engineering, publishing
---


# Question
Title: How does one write to another process's OpenGL/DirectX context?
I want to write a short of chat client that display the messages in-game (OpenGL/DirectX), but I really don't know how to handle this.

It is *easy* to write my client in my graphic context... but what about the other game-apps context?.

My primary target is Windows and Win 7, then mac, then Linux. But I would be happy to solve it for Windows.

By the way, it should try to be the most compatible with different DX versions and OGL versions.

# Answer
One of the most common ways to render into another application's GL or D3D rendering context is to *hook* the creation of the context or device objects in that application's process. This will let you gain access to the returned context or device pointer. You can then hook the actual rendering invocation methods (for example, `Present()` in D3D) and inject your own rendering before or after the rendering of the hooked process.

Google can provide a wealth of links on hooking/detouring/patching GL or D3D DLLs to enable this. For example:

Because you are patching the rendering API DLLs (essentially), you will have to do this different for D3D and OpenGL -- there is no way to do it in a uniform fashion for both APIs. You will probably need to write different code for Mac and Windows machines as well, even when utilizing OpenGL.

D3D9 on Windows supports hardware overlay surfaces in some scenarios, which can be much easier to use (I believe this is what some voice chat clients like Ventrilo use) if they do what you want. I don't know if OpenGL provides something similar -- it would likely be through an extension.
> 10 votes

# Answer
For the most part, it's not possible to write to a graphics context that isn't your own computer (there's... *sort of* ways to do this, but they're all really silly, and technically still not performing the rendering on the remote PC). In terms of your specific question, making a chat client, you should just send the text of the message (along with other useful information, like who said what and when) to the other clients (ideally, you'd send it to a server, which would pass it on to the clients, and possible perform some other actions, but...). Then, each client would handle rendering the text to their own graphics context. This solves the problem of dealing with multiple OSes and multiple rendering systems, too (again, sort of...)

TL;DL, just send the text, don't try to render something on another computer.
> 0 votes

---
Tags: opengl, directx, windows, linux, macos
---


# Question
Title: Is an entity/component system appropriate for this geometry handling system?
I'm working on a Component/Entity-System based game engine atm. And I have this little dilemma. I have simple geometrical structures which might be downloaded or created in game at some point. These structures are used to create models that are used in OpenGL and OpenGL ES and then for some collision processing. During dev and Beta I am quite ok with maintaining data copies for the physics and the display. But I started thinking about the future of this engine as I already invested some spare time over a year and a half in it. Now I would like to duplicate a few routines into OpenCL kernels and use the power of GPUs for the server side of my engine (and be ready for OpenCL enabled mobile hardware/software).

The structures are of variable size and moving or stationary structures can be deformed or broken... ATM the storage is very inefficient.

I thought of using a few mega arrays of GLfloat (Compatible with OpenCL) which would contain my structures depending on their size and pass only the transformations needed each frame. My Components would then point to these arrays.

Is it the right approach? If not, how to store the structure data to get it loaded only when needed to GPU memory and maintain the Component structure.

Do I even need a system and components to display and manipulate the structures?

---

**Note:** This is not a homework. It is more a question of interest to get a little multiplayer side project running as nicely as possible.

---

**Note:** I can't create an OpenCL tag so if someone else could and add it to the question it would be appreciated.

# Answer
> 1 votes
I don't think you need an entity system for this at all; entity systems work well for gameplay-related code, where they are influencing behavior or properties in some fashion and can allow for rapid iteration in a very large way.

It sounds like your geometry packaging system (for lack of a better term) doesn't need that kind of wide flexibility, and in fact you wouldn't want to allow it since that could destabilize performance.

I would instead implement the system on its own, distinct from any kind of entity system, taking your requirements into account (which appear to be efficient storage of the shape data for both transport and utilizing in OpenCL for deformation computations, et cetera).

Once the system is in place, you can *expose* it to your gameplay objects via a component that acts as a proxy for the geometry package. Such a component would essentially be a dumb wrapper around a reference to one of these geometry packages that is itself managed by the geometry packaging system. This will let your entity system refer to and take advantage of that system without complicating that system's own design with the flexibility of the entity system.

(Incidentally, I think this is how one should generally approach interfacing physics and rendering systems with entity systems as well.)

---
Tags: c++, opengl, component-based, entity-system
---


# Question
Title: What is an efficient way to deal with large, scrolling background images?
In my mobile game you basically you just fly up (infinite height) and collect stars.

I have many quite large background images, scaled down so that their width is the same as the device width. Then they are appended after each other during rendering.

Since I implemented these backgrounds, my game runs poorly. I've got about 20 background images with a size of 800x480 each; without backgrounds the game is quite smooth.

Does anyone have an idea how to implement this many backgrounds without making the game slow down?

The images are used as a 2DTexture. If I leave the clouds out of the image and "just" display the blue part, the app still slows down. Showing some code is a bit difficult, because I got many many classes which will do the loading, rendering and display stuff. Basically its done as Google does it in there "spriteMethodTest" example here: http://code.google.com/p/apps-for-android/source/browse/trunk/SpriteMethodTest

2 of these image set.

First: http://picbox.im/view/b7c8c86abb-01.png

Second: http ://picbox.im/view/3a8162314a-02.png

# Answer
> 2 votes
What I'd recommend is to go with a smaller tile system, as suggested in the comments. I would separate the clouds from the stars and create a bunch of tileable star tiles, maybe 48x48 or 96x96 (or whatever suits you).

Then I would create a bunch of cloud tiles (can vary in size), using alpha / transparency so the clouds will overlay and blend with the stars smoothly.

This could all be in one texture file if your device supports textures that size.

Then randomly pick stars from the star tile list to fill a star tile array. The choose random clouds and random positions to fill a cloud tile array. Fill in new tiles at the bottom in both tile arrays after scrolling.

One advantage of this is you could implement a parallax scrolling effect easily if you scroll the clouds faster than the stars. And it will take less memory if that's an issue. Plus it will be fairly fast in rendering if done properly and only set the texture / material once at the start of the tilemap render loop.

# Answer
> 0 votes
If your images are glued together on both x and y axis you will have up to 4 images drawn at the same time. I had a similar problem and solved it with loads of small images loaded as textures and displayed when needed.

You can also load the image and then by simply dividing it into smaller textures/tiles you can already get some improvements. Try also enabling clipping.

I am not sure about the underlying functions we used for the memory management and display as the game engine was not written by me.

---
Tags: opengl, android
---


title: How do I store Items in MySQL?

text:
# Question
Title: How do I store Items in MySQL?
I'm working to my first game containing items (built a small one before, strategy type but not very complicated). I was thinking something like this for the db design since it will be almost the same items in each shop. I'm thinking of connecting the shop to user items (not sure if you understand what i'm thinking of):

```
shopname
  shopNameId, shopName
shopCategory
 shopCategoryId, shopNameId shopCategoryName,
shopItems
 shopItemId, armourId, oneHandedWeaponId, twohandedWeapoinId,

```

this would be for the shop..now;

```
oneHandedWeapons
 oneHandedWeaponId, weaponName, weaponMinAtk, weaponMaxAtk, ...

```

otherAttributes,

```
oneHandedExtendedAttributes
 oneHandedExtendId, oneHandedWeaponId, ... otherAttritubes,

```

and again for other item types. This npc's will be the only place from where they can buy items.

Now when a user bought a new item from one of the shops i should insert the id of that item in the inventory table no? I was thinking on a structure like this for a stash based on 10 slots.

```
userStash
userStashId, userId, slot1, slot2, slot3, slot4, slot6, slot7, slot8, slot9, slot10

```

now on each on slot i can insert the id of that item.

Now my questions:

1. Is it ok how i did this?
2. Do you see any problems?
3. Do you have any advice?
4. Can you give me another ideea / another example how should I do this part?

# Answer
While this proposed implementation is workable, it's not very scalable -- and scalability should be one reason you consider using something MySQL. You don't *need* a "database" to store items and shop/vendor data for a game, especially not a simple single player game. Simply storing the data in flat files (text, or XML, or some binary format you invent) would work just as well and would likely be much easier to implement and maintain. You should not use a database like MySQL unless you need something a database offers that no other solution does. I don't believe you do.

That said, some specific critiques:

* `shopCategory` is designed such that every category is unique to a shop. The "swords" in shop A are not the same category as "swords" in shop B. This is probably not desirable as it will likely introduce complexity that isn't needed; it also creates data bloat. Categories probably don't need to be tied to a shop.
* `shopItems` implies that there is one item set per shop (although there appears to be no relation between shops and the item set), and that an item set contains exactly one of each fixed class of weapon. It is impossible for a shop to see two different kinds of two-handed weapons.
* Which begs the question, if the weapon class if fixed in table design, why is there a 'category' table at all?
* The user "stash" table implies a fixed upper limit to player storage, which would be very difficult to change in the future. This is a bad idea.

This sounds like your first foray into both games with item systems and database design, which is another reason I would recommend you avoid a database entirely. The system you want to model has multiple many-to-many relationships, which aren't immediately obvious how to capture to the DB neophyte.

What you need is an intermediate table. Let's say you have a table defining a shop:

```
Shop
------------------
shopID   | integer
shopName | text

```

and one defining every item in the game:

```
Item
------------------
itemID   | integer
itemName | text
itemType | integer
...

```

You can have a third table defining the (many-to-many) relationship between shops and the items they carry; each entry in this table represents a specific instance of a specific kind of item (from the items table) for a specific shop (from the shops table).

```
ShopInventory
-------------
shopId | integer (the shop ID that owns this item)
itemId | integer (the ID of the item)

```

So if Bob's Shop is shop ID 23, and it has 4 copies of Awesome Longsword (item 2) and two copies of Potion of Hangover Resistance (item 73), the ShopInventory table might look like:

```
shopId | itemId
---------------
23     | 2
23     | 2
23     | 2
23     | 2
23     | 73
23     | 73
... etc ...

```

This is a really, really cursory overview of many-to-many relationships and how you might implement them -- they are really needed to do the kind of model you're talking about well, so I would strongly encourage you to research DB design a lot more if you really want to use a DB for your items. But I would encourage you *more* to simply not bother with a database at all. Store your data in text files or XML files while you figure out how to best design you item/inventory/shop systems.

Worry about databases later.

**EDIT:** Definitely read through the comments to this answer if you're actually interested in the database implementation bit, because my initial example was quite cursory and a number of users have pointed out a number of simple but important improvements that could be made to it.
> 12 votes

# Answer
1 No... At least not how I would have done it. It might be exactly what you need, but I don't really see the logics.

2 Yes a few. For example:

* Your user stash violates 1NF principles: Should not have multiple columns for storing the same data domain (but it's not the most important thing).
* Your shopItems is not efficient if each item isn't composed exactly of an armor, a one handed weapon and a two-handed weapon. Which is not the case presuming on handed weapons are not always 2 handed and the other way round.

3 You should probably change your data structure or use a more dynamic storage system (XML, JSON...) where you could do a few things that are not practical with SQL.

```
<shop id="45u2y">
  <items>
    <item id="broad2">
    ...
  </item>
</shop>

<items>
  <item id="broad2">
    <name lang="en">Broad Sword</name>
    <transform id="twoHanded"><dmg type="cut">3d6+2</dmg><slot id="hand"/><slot id="hand"/></transform>
    <transform id="oneHanded"><dmg type="cut">2d6</dmg><slot id="hand"/></transform>
  </item>
</item>

```

4 If I had to use SQL I would probably do something like that:

```
shopItems
 shopItemId, shopItemStatus

items
 itemId, itemName, itemCathegory

itemsTransformators
 itemId, transformatorId, transformatorType, transformatorCondition

```

Etc... In this case I really believe SQL is not the best bet. I would definitely use a custom storage system, XML or if really needed another type of DB. ex: eXistDB http://exist.sourceforge.net/
> 3 votes

---
Tags: architecture, databases
---


# Question
Title: How can I implement fixed joints in a 2D physics system?
I'm developing a simple, 2D physics system to complement an entity/component game object framework. So far, I have implemented some basic, tutorial-level physics. An entity that is affected by physics must have two components:

* Transform (translation, rotation, scale; may have parent transform)
* Rigidbody (mass, list of forces)

The physics engine currently uses Verlet integration to move entities - that is, velocity is derived from the current and previous positions of an entity, and is not explicitly stated anywhere.

I would now like to start implementing some joints, starting with the basics and perhaps expanding as I grow more familiar with the concepts.

The first joint I attempted to implement was extremely simple - the fixed joint, whereby two entities are 'fixed' together and their transforms may not change relative to each other. My approach was to make one entity an immovable child of the other - that is, to set the transform of A as a local transform relative to B and disable movement of A by passing all accumulated forces of the rigidbody of A to the parent, B. Already this seems hackish and inflexible and has issues with gravity (B ends up with two gravity forces acting on it) - I'm clearly heading in the wrong direction.

I have searched for some literature on the subject but have only found either very basic tutorials that only cover what I've already done, or articles with advanced mathematical formulae that are difficult to follow or relate to simulation in any meaningful way.

This leads to two questions:

1. How are fixed joints normally implemented?
2. Are there any good 2D physics simulation tutorials aimed at those without a degree in physics or mathematics?

# Answer
This article ("Advanced Character Physics" by Thomas Jakobsen, with a PDF mirror here that preserves images) discusses solving fixed distance constraints (which sound to me like your fixed joints) between particles by relaxation -- specifically you want the section "Solving several concurrent constraints by relaxation" on page 2, I think -- treating the constraints as infinitely stiff springs. I found this article approachable enough years ago when I was implementing something similar, so hopefully it will have what you need.

A relevant passage:

> One may think of this process as inserting infinitely stiff springs between the particle and the penetration surface – springs that are exactly so strong and suitably damped that instantly they will attain their rest length zero. We now extend the experiment to model a stick of length 100. We do this by setting up two individual particles (with positions x1 and x2) and then require them to be a distance of 100 apart. Expressed mathematically, we get the following bilateral (equality) constraint: **|x2 - x1| = 100**.
>
> Although the particles might be correctly placed initially, after one integration step the separation distance between them might have become invalid. In order to obtain the correct distance once again, we move the particles by projecting them onto the set of solutions described by \[the above equality constraint\]. This is done by pushing the particles directly away from each other or by pulling them closer together (depending on whether the erroneous distance is too small or too large).

This page appears to have source code of a concrete example, although I'm not sure of its quality.
> 4 votes

---
Tags: physics, rigid-body-dynamics
---


# Question
Title: Chunking/caching large levels in a singleplayer game
Does it make sense to try to offload a large nonlinear level into file-based chunks, and load those on demand? We've implemented level chunking to improve rendering performance, but still all level objects are persistent in RAM.

If yes, then how do we keep the illusion of a living/changing world? Since the level is not linear, but rather like a world in itself, we cannot just pretend that whatever one's gone through is gone forever.

Is it a better idea to make the levels complex enough, but also optimized enough to be always persistent in memory, but implement micro/macro jump points which allow one to jump to a totally distant point (i.e. a whole new level), thus forgetting about the world consistency, and the illusion of a changing world. Also, this would allow us to follow a slightly linear story in a seemingly non-linear world. It would be possible to just apply a new state to the existing state of a "distant" level, if we are to bring the player back to it.

# Answer
> 6 votes
Creating chunks are really a good idea but you need to use it wisely. there are many big titles that use the same idea to give the illusion of very large world. for example you I can mention Spore or Oblivion.

First let's talk about spore since in it's galactic phase you can easily see how the things work:

there are many planets in the galaxy but not all of them are in memory in same time. whenever you get near one planet game automatically loads a texture for that planet from hard disk. Then if you get close enough you may enter planet and make some changes. while you are inside a planet almost all the data about outer space is deallocated. And you may make any change in that planet you like. then you can return to space view. this time game reloads data for other planets and saves the changes you made in that planet. for example if you created a mountain there, all mesh and texture changes are again saved in files. there are also some events which are saved in files. like when you put the device that help creatures evolve in planets. these events remain active until you get really far away from planet triggering them. but still they are saved and when you get close enough system will check if they need to be triggered based on game clock.

In oblivion thing are a little different, although the base idea is the same. when you walk in wild, the game is constantly loading and unloading areas. if you tried playing oblivion on PS3 this process produced some minor lags in transition area (or at least I heard they did). there are also some areas that completely stop Game and you see a loading screen like when you enter caves you houses. using this method they easily reduced complexity and memory usage in cities. just think of how many houses there is in a city and how much memory they would consume if they wanted to load them. also note that if they wanted to use the same loading and unloading system whenever you get near houses they needed almost all of hdd bandwidth, and it could damage hdd.

to conclude my answer I suggest you use same method in you game for wide areas. you also have to save any changes that player made in an area while unloading it. This method gives a very pleasant experience of a exploring a real world to players. But for areas that there are many objects and you think you may need most of storage bandwidth for data transmission just use a traditional method with a loading screen.

---
Tags: optimization, levels, level-of-detail, space-partitioning
---


title: C# 2D Game Design/Architecture Question

text:
# Question
Title: C# 2D Game Design/Architecture Question
I am developing a 2D game for windows phone using C# and XNA. I have a list of screens managed by an engine. each screen has a list of components like 'camera', 'skyBackground', 'landBackground', 'units' and so on. All those components inherit from an interface 'IComponent' which has the following:

```
public interface IComponent
{
    void Initialize();

    void Update();

    void Draw(Camera camera, Color tint);

    BoundingBox BoundingBox { get; }
}

```

This has it advantages and disadvantages. It unifies all game objects so i can treat them the same, but creates some harmless but still annoying issues like having plenty of empty initialize functions, or a camera with an empty draw method, or a UI class that doesn't need the camera as a passed in parameter to draw in the 'Draw' function but takes it anyways and so on.

I then thought of creating a number of interfaces like 'IUpdate', 'IInitialize', 'IDraw', 'IBoundingBox' and having my screens store a list of 'object' rather than a list of 'IComponents', and then in the update method i would do as follows:

```
foreach object obj in objects
    if(obj is IUpdate)
        ((IUpdate)obj).Update();

```

But I don't know how the 'is' command works behind the scenes, maybe its a costly feature which shouldn't be called each frame for all objects in each loop.

So am not sure what to do here, should I accept a unified interface with the few currently harmless kinks it introduces or use my 2nd idea? or maybe you could suggest another alternative?

Thanks a lot

# Answer
> 5 votes
You never know how costly a feature is until it's in your code and tested running, realizing that you don't know is a great thing.

I think that your main problem is that you've packed your idea of what a "component" is with way too much functionality. I think that you want to reduce the responsibilities of component to the bare minimum, maybe just engine maintenance and debug helpers.

From there you could add more interfaces for updating and rendering and so on to appropriate classes, and when those objects are created add them to separate lists of components that are known to use those interfaces. One way you could do that would be for the class to have an initializer that requests that it be placed on the rendering list, for example, or that it needs an update.

Your engine, then, maintains those lists and knows that anyone on that list needs to be called and you don't have to check each object each frame.

It may help to make a large scale block diagram of how your system will fit together logically, if interactions appear to be really complicated then that's an indication that your blocks need redesigning. With diagrams and logic you will avoid getting stuck in the implementation details before you even know what it is you are implementing.

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


# Question
Title: UDK - problem packaging/publishing the game
I have set up all the config files to my game classes and am able to launch the game to test everything.

Although when I package the game, it still runs the UT deathmatch game?

What other lines in the config files should be changed to make it default to my game and default map once published/packaged?

# Answer
This is documented here on the UDN:

http://udn.epicgames.com/Three/DevelopmentKitProgramming.html#Configuring,%20Compiling%20and%20Testing

> You can also change the default game type to use when none is specified in UDKGame.ini in the \[Engine.GameInfo\] section. Change DefaultGame and DefaultServerGame to =MyMod.SuperFunGame. Make sure your gametype implements SetGameType() so it can prevent the gametype from being overridden.

I should mention there's a bit more info here:

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

> To propagate this change or any other ini change into your packaged mod, you'll need to also modify the defaults in DefaultGame.ini.
> 1 votes

---
Tags: udk, unreal, distribution
---


# Question
Title: Why is my Diamond-Square implementation producing blocky, banded results?
Do you know why my diamond square algorithm is giving me this such "ragged" results? I used to render it in a way that concealed the roughness (basically asigning color ranges instead of fractional values as now), but when made it work for the first time, months ago, it used to work fine!

I want to tear my hair out!

# Answer
Diamond Square typically returns very rough results when a basic implementation of it is used. The solution to this is to modify how Diamond Square is creating your values. I'm unsure what you are trying to use it for, but one of the most common is for procedurally generated mountains.

**Option 1:**

At each step of the Diamond Square process, that is each time the square gets smaller, reduce the amount of new offset you are going to introduce. This will create a more realistic looking mountainous region that is less craggy and more long slopes with variations, if you are trying for that.

This reduction in offset could also come along with randomness along a scale and not just flat. Meaning that it is possible to still have crags, but they are rarer.

**Option 2:**

If you are intending to create a more weathered looking landscape, and not sharp crags, it would be wise to pass the result from Diamond Square into a Cellular Automata engine that smooths based on neighboring values. One that works well for me is to check if all 8 neighbors are the same height or higher. If 6 or more are, then do nothing, otherwise lower the height by one. Repeat as needed. More repetitions means a smoother landscape. Eventually it will become flat like Florida.

These are by no means the only options. But they are relatively simple ones you should be able to accomplish with a limited understanding of Diamond Square.
> 5 votes

# Answer
Your image reminds me of loading a bitmap with the wrong bit or color depth. When you are outputting (and inputting if you are using your own code for display) make sure you are using the correct number of bits, colors and compression. Even if you think you are doing it correctly try outputting a simple test image to ensure this isn't the source of the issue.
> 0 votes

---
Tags: algorithm, rendering
---


# Question
Title: How to optimize primitives in SecondLife/Opensim?
SecondLife/Opensim uses Primitives to construct models. How it works in details is explained here.

Now I have many triangles which link together. Is there any way to make them into one prim, thus reducing the number of prims?

# Answer
> 1 votes
No. A "prim" is a primative object, and is the base building blocks for building 3d content.

You cannot combine shapes into a single prim.

However you can use prims efficiently by using clever textures instead of details, or by using fewer larger prims to create your objects.

---
Tags: models, triangulation
---


# Question
Title: What are the advantages and disadvantages of both writing a wrapper, and not writing a wrapper?
I am going to use Ogre3D as the rendering engine for our 3D software. I am not sure if I need to use the engine as it is, or if I need to write a wrapper for the parts I want to use. What are the advantages and disadvantages of both writing a wrapper, and not writing a wrapper?

# Answer
> 5 votes
Ogre3D is already a wrapper/abstraction for OpenGL/DirectX. Adding another wrapper on top of that might be overkill, unless you will write a completely other rendering engine that will replace the functionality you used from Ogre. It's hard to judge, since I don't know how much of the Ogre API you're going to use.

Ogre3D already works for Linux/PC/Mac/iOS and apparently Google Native Client (which will probably also work on Android).

Generally there are situations where a wrapper might be a good idea (Gajet makes some good points) but in your current situation I'd rather invest some time to get Ogre3D running on all your target platforms. Maybe you'll have to write some additional code to achieve that, but I think it's probably less than writing a wrapper that works with different engines. And if you happen to be able to port Ogre3D to another platform, it would be a great service to the community.

**Edit:** Apparently Ogre3D has already been ported to Android. Here's a thread abut porting Ogre to Android.

# Answer
> 3 votes
writing a wrapper will help you in some ways:

1. you can change engine whenever you like, you'll just have to change your wrapper's implementation. this is especially useful if you think you might someday change your target platform.
2. when you write a wrapper your whole game code will share similar coding style. for example you know all functions start will small letters or all classes star with capital letters or any other coding style that you think of.

but there are also some drawbacks:

1. you may restrict engine functionalities, by your wrapper. that's just possible if you don't want to copy all the features engine provide with exactly same structures.
2. it always takes time to write something. both from programmers and computer. there are also many potential bugs you might introduce and whenever you need a new feature from engine you need to first write a wrapper to make that feature available in your code. it may decrease production speed alot.

---
Tags: architecture, ogre
---


title: Ogre3D Fog with overlays

text:
# Question
Title: Ogre3D Fog with overlays
I'm building a game with Ogre3d, I've got fog working properly with: `scenemanager->setFog(Ogre::FOG_LINEAR, Ogre::ColourValue( 0.23f, 0.725f, 1.0f ), 0, 18, 20 );`

However I'm currently implementing a GUI system (libRocket) which is rendered on top of everything else, and this removes the fog, does anyone know how to fix this? (I'm using the default libRocket rendering system for ogre as included in the samples, but this problem also appears when using a semi-transparent overlay).

# Answer
I use Mogr3D, but I have built my own UI rendering system. Probably libRocket does the same,

Try to do some tests by using the Overlay objects, if I'm correct they do not remove the fog from the SceneManager.

Does libRocket use .material files or vertex scripts that might remove the fog there?

Have you tried adding the fog AFTER adding the UI stuff ?
> 1 votes

---
Tags: ogre
---


title: 3ds envelope underlap?

text:
# Question
Title: 3ds envelope underlap?
I'm rigging up a man in 3DS Max 2012, but I'm having some envelope problems. I have this man, but I can't ever seem to catch those nodes along his inner thigh so they protrude, as you can see in the picture.

I've tried adjusting the numbers in `Radial Scale`, `Parent Overlap`, `Child Overlap`, `Strength`, and `Falloff`, and even the `Exclude` command to exclude the other limb but all with no success.

How can I somehow make these stray thigh vertexes conform into their thigh envelope?

# Answer
> 3 votes
You should not be using the envelopes, it is no precise enough, open the Weight Table, select the vertex that is giving problems, like the one in you image. Give it a a 0.0 weight for all the bones, Select the Thigh Bone and set the weight to 1.0

This should solve your problem.

---
Tags: 3dsmax
---


# Question
Title: Implementing a large scale (planet-like) level in XNA 4.0
What is the best way to implement continuous level throughout the game, using XNA? Imagine that I have a level with the size of a whole city (like in MMORPGs) however, the game will currently be mainly single-player. I'd like to be able to split this huge planet into parts which load asynchronously as I enter them. However, I also have other questions, such as, what happens with the part that I've come from. Its state should be stored on the disk, right? Then, what if I need to make some changes to that part, when the player comes back. Obviously, other characters should have done something rather than standing still. What's the best way to grab the state as I stored it, and modify it a bit, based on certain parameters, before I load it and let my player return.

# Answer
In world of warcraft, the adjacent "tiles", which are pretty large, are loaded as a low poly model This is done so you (as a player) do not see the "end of the world". Then, once you know where the player is going, you have a Loading engine start to load the assets of the "tile" the player is going, asynchronously

Unload the once from the "tile" the player is moving from,

This "in short" is how Blizzard does it

Hope you can make something of it.
> 1 votes

---
Tags: xna, levels, storage
---


# Question
Title: Is it worth supporting iOS 3.x or iPhone 3G devices anymore when developing a game?
Is it still worth it for a game developer to try and support older devices: iPhone 3G and earlier or to support older OS: iOS 3.x and earlier? Or is it recommended to make use of OpenGL ES 2.0 supported be the iPhone 3GS and above? Do you know what percentage of users still use those earlier version of devices/operating systems?

# Answer
> 4 votes
Really... It depends on your goals and resources.

For an indie, a rule of thumb is: if it takes more than your spare time to support then no. The iPhone 3G is a legacy device.

Apple still services it when they come for repair, but there are no iOS updates and users don't expect all apps to be available on it.

With iOS 5 the iPhone 3G will be left behind. It can't run 4.3 and users using it will have the opportunity to get a new one discounted by their carrier. You can't be sure the hardware will be supported when iOS 6 is released, so is it worth to add support for just one year or less?

If you don't support the device, the impact it will have on you will depend on the kind of game you produce. If you have great graphics people will understand. Otherwise it will be harder to mitigate the response from iPhone 3G users.

At my previous employer we had to support all versions as long as the SDK allowed it. But the maintenance cost was not huge as we had our own framework and all games used it. So keeping it compatible with all iOS/Android versions was not an issue. But we didn't use OpenGL ES 2 to avoid issues with older hardware and other OSes.

But for an indie developer its more a question of time and $. I would really advise to get the game out there and patch it later if you can to allow other users to get it.

If you aim for budget users, if you have some sort of social game, then I would say: use OpenGL ES 1 support the oldest devices you can.

I remember hearing there have been Around 35M iPhones 3G sold... You could try to extrapolate the sales from this chart for what is worth: http://fr.wikipedia.org/wiki/Fichier:IPhone\_sales\_per\_quarter\_simple.svg

I don't think there are precise numbers freely circulating. But you should not waist your time if you really don't need to support the older devices. Simply add support if its free or close to free in your case.

# Answer
> 7 votes
No.

When iOS 4 was introduced, the app store introduced a new rule: "You can't upload binaries which deploy for iOS 2.x". This sent a clear message that Apple doesn't want to have users nor developers trailing in firmware updates. Since today (depending on where you live on the globe) Apple is expected to announce iOS 5, the app store will likely disallow uploading binaries which can be deployed on 3.x.

But this is speculation. Think better that by the time you finish your game iOS 3.x devices will likely not be in use any more, or represent such a fraction of the whole market that it is economically not sensible to develop for them. There are similar questions/answers here with more information and links to statistics.

**UPDATE**: Well, my speculation was wrong. Apple has not banned 3.x development, the latest Xcode still allows deployment of 3.x and I haven't seen any new notes about deployment versions when uploading to itunes connect, so at least I will try to keep providing 3.x compatibility for the apps I have which support it. As a reminder, only original iphones and 1st generation ipod touches are unable to upgrade to 4.x.

**UPDATE 2013**: Looks like Apple dislikes old hardware, the recent Xcode versions don't work on lesser than Mountain Lion machines and they don't support building binaries for armv6, meaning devices which can't upgrade to iOS 4.x. It is still possible to download Xcode 4.4 manually from Apple's developer file section, the last supporting 1st generation devices. Grab it while it lasts if you want to support old hardware!

# Answer
> 2 votes
No, for two reasons.

1) While there are a lot of "old" (pre-OGLES 2.0) devices out there, they account for only 5-6% of the market share of people actually playing/downloading your app, depending on who you ask. Here's an example of a company announcing the drop in support for older devices: http://www.ngmoco.com/we-rule/blog/2011/08/11/support-for-earlier-generation-devices/

Keep in mind that that particular example is a free-to-play game, so it probably has a *larger* percentage of older device users (think hand me downs to kids and that kind of thing) than people who have newer/faster/shiner devices. This, however, is speculation.

2) It's hard to test. Unless you have an iPhone 3G or a newer device with its near-original OS installed (like an iPad 1 with 3.2.x installed), you can't be sure that the newer features you may want to use (like GameCenter) are going to fall back gracefully. You can accomplish it by using weak-linking, but Apple doesn't test it for you. If you don't set it up properly, what will happen on the devices using an older OS is that it will just crash.

---
Tags: iphone, opengl-es, ios
---


# Question
Title: How should I track players' real-time positions in an MMO?
How do you keep track of the positions of the players in a MMORPG? I read that you can use either a database or you can store the coordinates in files. I tried using a database but it was slow. How can files be used to keep track of players positions?

# Answer
> How can files be used to keep track of players positions?

You write the player position to the file. For example, if you identify every player with a unique number (or a GUID), you could use that as the file name. In the file, simply write the position data out in a format you can parse later. For example, `467239.txt` might contain `20, 3, 19` if player #467239 is at that (*x, y, z*) location.

This is not that different from what you would do with a database, however -- a database should not be "slow" at this operation, it should be very fast (probably faster than files, because you have more disk IO overhead or IO locking contention -- if you stored multiple positions per file -- in a filesystem-based approach).

Perhaps you were trying to use the DB or filesystem to store the player position *at runtime*? **You should not do this at all**.

At runtime, in your server, player positions should be kept in-memory and updated there, as you would do with any other kind of game. Periodically they can be saved to disk or other persistent storage -- for example, when the player rests, saves, or logs out.

But writing every players position to storage every update is unnecessary and extremely inefficient; it will never be fast enough to handle anything resembling "massive" player scales.
> 23 votes

# Answer
The Position **must** be in RAM while in use. (ex: player's character is in the world) You cannot use the DB as operating memory. Well you can, but this will be terrible.

You should save the positions regularly, but not every time they change.

I would also avoid saving all positions at the same time. If you want to maintain persistence in case of a server crash you should save the position as often as possible but on the game's spare time. Simply do this by batches.

Save 30 positions while spare time is available.

As for the clients. They should receive (relevant) game state updates through a connection to your server software. **Not from the DB**... That would be impractical, slow, bad, evil and the force would be disturbed.
> 13 votes

# Answer
I have a separate thread I queue to to save to files every 500 or so game ticks. Otherwise, you should store everything in RAM.
> 4 votes

# Answer
What I do in my server, is to store the players direction (vector) and last position, if the player has a speed, I do calculate the players new position every 2 seconds.

The client has its own position position of course and sends it new direction (vector) to the server.

The server is authoritative about the position and sends a position packet if the client moved a certain distance since last check (this may lead to rubber band effect is client is out of sync).

All this happens in memory of course.
> 4 votes

---
Tags: multiplayer, mmo, databases
---


title: How to decide who wins a race?

text:
# Question
Title: How to decide who wins a race?
I'im thinking of building a text-based browser game. A racing game.like F1 or rally. users can set-up a car. thinks like tyres, fuel, driver,brakes. every attribute gets a value.

the part where i am stuck is the race.

i think a race exist out of corners, straight parts, hills,...

i have no idea how i can come to a solution who wins the race and what the lap times would be.

idea i have: a race has for all attributes of a car the best value. the car with the best values of that race, normally wins.

anyone with some idea's?

# Answer
When you watch a race, it unfolds sequentially, until by the end there is a history of that race that you could tell someone as a story. Some research like watching races with your buddies might show off what the most exciting parts are, or how the story tends to divide itself up.

In the "race" part of the game, you could randomise a story like this, having the story unfold as the player passively watches, periodically spitting out sentences describing the major events in the race (), with a dramatic pause between each (picture moving ellipsis .....) and use those events as the build up to who wins or who doesn't. You'd need to use a stack to track the positions of the various drivers as you make each statement.

So for example

* "They're at the line up. Mansell has pole position...."
* "And they're away! Senna's moving quickly, he outskirts Prost..."
* "Berger..."
* "and Patrese!..."
* "Oh! Patrese swerves out of the way and Häkkinen is into the boundary! What a start we're off to!..."

You could break this up into early race, mid race, and end race, keeping each section brief (maybe 10-15 lines?) so that things don't get too boring. This way, you are rewarding the player with a suspenseful race after all the effort they've put in setting up their car and driver. Also cool to see the name of your driver mixing it up with the other drivers when the commentator focuses on him/her. You could even have simple sound effects for many of the events as they happen, like tyres screeching, revving hard, or gearing down... just to add some life to the text output.

All these events are templates of course, which you will probably create and store in a long text file that you load at runtime, and you can then mix and match them in different ways to create the race experience as commentated. Some events rely on others, such as where one of the drivers crashes due to another one's reckless action.

Of course, kitting out the cars in the first place would be part of who wins and who loses on which tracks, meaning it has an effect on what story events are generated as the race proceeds. Crappy tyres? Expect a blowout on a hard corner. Ferrari engine? Expect superb acceleration. Cars with good traction and suspension win on curvy tracks, cars with best top speed win on long-straight tracks. Or you could do it by track section if you wanted more detail, i.e. straights, long bends, and esses.

PS. You could even do a sci-fi or fantasy themed race. Perhaps more fun? Just my two cents.
> 3 votes

---
Tags: logic, php, text-based
---


# Question
Title: Deciding Which Platforms to Support -- Silveright (+Android?)
My "usual" stack for game dev is to create (in-browser) Silverlight games. I've decided I want to branch into iPhone or Android, and decided to go droid because it's cheaper (considering I don't have a Mac).

Having now all the requisite software and hardware, **how do I decide which games to code on both platforms and which to not?**

In an ideal world, it would only cost me 5-10% more (time/effort) to port it to Android having developed it for SL. But I know the worst case is 100%+ (i.e. rewrite), and that it'll be somewhere in the middle.

Considering everything will likely be free (although it might be worth it to release the SL one free and offer a $5 paid one on Android, not sure), what are factors to look at?

# Answer
> 4 votes
Answering your question "how do I decide which games to code on both platforms and which to not?" That will be up to you. Though you will want to look at a not so graphic/physic base games to port over. (High poly count equals a very slow game in android).
Try something simple, and see if it's harder or easier than you thought.

---
Tags: cross-platform
---


# Question
Title: How to tie a bullet release with a firing animation
Lets say you have an animation that you want to happen when firing a bullet. How would you get the bullet to show up at the end of the animation. The only thing I can figure out is to know the time length of the animation, and delay setting the bullets position and setting it active until that amount of time has passed. I was just wondering if this is the best approach, how does everyone else handle this?

EDIT: I think i'm having trouble wording the question properly.

# Answer
Fundamentally you're on the right track - you need to know how long an animation lasts to do this sort of thing. Animations are more than just a collection of frames, there is all sorts of other information around them that you need. E.g. how many frames are there, does the animation loop, how quickly does it play back (e.g. 10 animation frames per second or 25, or 60?). Every animation can be defined in terms of a few pieces of data, which some generalised animation code can look at and play back. You should be encapsulating the animation part in its own bit of code, which is aware of nothing except these animation definitions and how to display the individual image frames. That is, have an animation object which you can load, start playing, stop playing, and tell to render at a particular location on screen.

A flexible approach is to use a sort of animation definition to encapsulate this sort of information. So rather than just saying "animation X is all of these frames, just play through them", you get something a bit more complex.

E.g. with some sort of mocked up data format

```
animations =
{
  { name="walk", files="walk*.png", frameCount="12", loop="true" },
  { name="fire" files="fire*.png" frameCount="6",
       events = {
           { name="bulletLeavesGun", frame="4", param1="43", param2="30" }
       }
  }
}

```

So your code says something like:

```
currentAnimation = animations.Get("fire");
currentAnimation.Play();

```

How you detect events can either be with the animation code calling you back (i.e. when it detects a new event because the animation has played to a certain frame, it calls your game code to tell it about the new event), or by polling the animation like so:

```
List<Event> events = currentAnimation.EventsSinceLastCheck();
foreach (AnimationEvent event in events)
{
    if (event.name == "bulletLeavesGun")
    {
        Vector2 bulletPosition = new Vector2(event.param1, event.param2);
        Vector2 actualBulletPosition = new Vector2(
                 character.x + bulletPosition.x,
                 character.y + bulletPosition.y);
        CreateBulletAt(actualBulletPosition);
    }
}

```

Points to note:

* Animation code should exist separately from game code. You really don't want your gameplay code too tightly tied to the nuts and bolts of animation playback.
* The animation code knows whether or not to loop based on the animation definition
* The animation code knows when the animation is done, and can call back to some other code to say 'hey, the animation called "fire" just finished, what do you want to do now?'
* The animation code doesn't know anything about events other than that they have a name and some arbitrary data associated with them (param1 and param2)
* The animation code knows what frame it's currently on, and when it changes to a new frame, it can check and say 'oh, I'm on frame 4 now, that means this event called "fire" has just happened, add that to my list of recent events so I can tell anyone who asks about it'.

If you don't need the bullet firing to happen within the animation, but only once it has finished, you can get away with a much less complex system without the notion of events. But you'll still want a system where animations play back on their own, know how long they are, and can call back to the game code when an animation completes.
> 8 votes

# Answer
In some way, you'll have to wait until the animation is done and create the bullet at that point.

Just setting a timer will work, if you're sure that your animation rate is fixed. As a minor variation, you could have code internal to the bullet that makes it wait invisibly for a moment before appearing and moving.

Depending on your development platform, you may have some sort of animation update function or callback that will let you respond the exact moment the animation reaches the desired point. This is how I'd do it with Flixel, for example.
> 3 votes

# Answer
Straight forward answer: Assuming you have an animation that you want to play when the player hits the 'fire' button, and then have a bullet come out after it's done playing. Ideally, you should avoid hard-coding the animation time, and fire the bullet when the animation completes (using a callback function or something, depending on your platform). I can't think of any other method to do this that isn't overly complex.

Alternate Game Design answer: Unless there's a really, *really* good reason to do so, I would avoid having a delay from pressing the 'fire' button and having the bullet appear. Unless the animation is really, really short (one or two frames, max, basically a muzzle flash), it's going to make the fire button response feel slow, and it will just get annoying to a typical player. Even if you do decide to go with using an animation before the bullets come out (turn based RPGs and tactical games would be acceptable reasons to do this), I'd think about including a "turn off animations" option somewhere, to allow the game to move faster if the player wants.
> 2 votes

# Answer
As MrCranky says ; keep animation and logics separated.

But most importantly, **logics must remain the master** part.

* When the fire button is pressed you should trigger the draw "**action**" in your character's state (logics).
* This action should trigger the drawing *animation* with all the parameters (time to live etc).
* Once the draw **action** is finished you can trigger the fire **action** (could fire once or more depending on the weapon)
* This action can generate bullets and trigger the fire *animation*.

Keep in mind that controlling the UI from the logics is the only way to ensure you will be able to keep, reuse and share your logics later (new renderer, new game, server version without a renderer...)
> 2 votes

# Answer
First off, I'd use an event system (observer pattern?) to decouple pieces of the code. This isn't just for the animation, but certainly applies there. Then the animation code can simply say dispatchEvent(event) and some other part of the code listens for that event, without either part of the code needing to know about each other.

Now the animation code needs to actually have a reference to the event dispatcher (easily done with dependency injection) and you need to have some XML or JSON that actually defines your animations. Something like:

```
{
  animation: {
    name: shoot,
    length: 12,
    spritesheet: shoot.png
    event: {
      frame: 4,
      name: bulletLeavesGun,
    },
  },
}

```

Read in the data when loading the animation, and have the animation code dispatch the event when it's on that frame during playback.
> 1 votes

---
Tags: 2d, animation, release, timing
---


# Question
Title: How should I go about abstracting away the graphics device?
I would like to be able to move my game from using a XNA graphics device to possibly an OpenGL device in the future. So I'd like to have a somewhat abstract interface to submit polygons to. Its ok if it does not fully hide the directx pipeline. I simply want something that takes in a bunch of vertices and draws them.

I was wondering if anyone has done this and/or if you guys had any advice for me.

# Answer
> 3 votes
When you're dealing with vertex buffers, it gets real tricky with doing cross-platform or cross-API code, especially if you want to use the best approach particular to each API. I would look at some open-source cross platform engines such as OGRE to see how they do things at the lowest level- don't try to implement more complex ideas right away, like quadtree heightmap generation or cube mapping.

A good first step is to start porting your XNA code to DirectX 9 first. XNA really just hides many things of DX9 behind the scenes, and you will just have to learn how to work with unmanaged code. When you have the basics down of loading and reading resources in DX9, you can begin wrapping it around more general functions.

You have one benefit with OpenGL, though. It handles resources in a more managed way (just imagine all of them are in a managed pool). With DX9 you have to handle lost devices to take care of your resources.

# Answer
> 3 votes
*(In the interests of disclosure: (1) I have not completed my implementation yet, so I cannot say with certainty how well it worked, (2) I only do graphics programming as a hobby, I write my engine and tools because I enjoy writing engines and tools, I don't know how well any of this would apply to a commerical project.)*

I find this question very interesting as I have been working for the last couple of days on the same thing, and it certainly isn't for the feint-hearted (or people who like tidy code and lots of refactoring ;))

It all depends on where you aim; as Patrick Hughes commented so many of the types and concepts are very implementation specific that it is difficult to keep something satisfactorily generic and of use. That said, if too much is done in the plug-in the purpose of the abstraction is negated.

Take for example, a mirror or video screen in the game world, say you implemented this by rendering your scene using a special viewport to a texture on the GPU which was then provided to the shader of your mirror or screen with some post-processing. This I would say is an ideal task for the engine, pertaining to a collection of low level objects with specific configurations, with some knowledge of the scene at large - but if your layer is dealing only with complete game objects such as models, you'd have to implement all that logic once for every API your layer supported.

The very nature of an abstraction means you shall lose functionality the further away from the API you move, how generic your methods and objects depends on the requirements of your application (or probably more accurately, what specific features of your chosen API you want to use and interact with explicitly).

My recent attempt had one purpose, and that was to in some way 'protect' the work I put into an engine, by ensuring it would not be tied to a specific API, so I could go cross-platform, or support different grades of graphics cards. I chose a level slightly below that of XNA, and set some rules for the composition of my wrapper, such as, there shall be no internal caches - all objects shall be passed back through the layer (though they are hidden). I used namespaces and split up the projects so I could force myself to conform to these by omitting references to parts that other parts of the code should not see.

As I wanted to put all the interesting and tricky bits in an engine where they could be reused, I opted for a low level wrapper. I have a 'template' for a 'Renderer' (which abstracts the device) defined by an abstract class, which has methods to create a number of objects representing common paradigms such as Vertex/Index Buffers, Textures, Shader Programs, etc. Each of these implementing an appropriate interface.

The quick and dirty diagram below indicating whereabouts I intended my wrapper to sit:

An example excerpt from my 'template':

```
public enum ElementFormat
{
    Vector4 = 4 * 4,
    Vector3 = 3 * 4,
    Vector2 = 2 * 4,
    Byte4   = 4 * 1,
    Int     = 1 * 4
}

[Serializable]
public class VertexElement
{
    public string Semantic;
    public ElementFormat Format;
    public int Index;
}
public interface IVertexBuffer
{
    VertexElement[] VertexDefinition { get; set; }
    void SetData(byte[] data, int destStartPosition);
    void GetData(byte[] data, int lengthDataToGet);
}

public abstract class Renderer
{

    /// <summary>
    /// Creates a new index buffer on the GPU, initialising to the supplied data.
    /// </summary>
    /// <param name="length">Length in bytes of the new buffer</param>
    /// <param name="data">Data to initialise to</param>
    /// <param name="dynamic">Buffer is accessible by the CPU. If no data is supplied this is assumed to be true</param>
    /// <returns>A handle to the new buffer</returns>
    public abstract IVertexBuffer CreateVertexBuffer(byte[] data, bool dynamic);
    public abstract IVertexBuffer CreateVertexBuffer(int length);
}

```

The actual object that is returned by CreateVertexBuffer() is defined within the wrapper, and the engine has no knowledge of it.

```
    public class Dx11VertexBuffer : IVertexBuffer
    {
        internal SlimDX.Direct3D11.Buffer DxBuffer;
        internal SlimDX.Direct3D11.VertexBufferBinding DxBinding;
        internal SlimDX.Direct3D11.InputElement[] DxVertexDefinition;
        internal int DxVertexStride = 0;
        internal DirectX_11_64_Renderer Parent;

        public void SetData(byte[] data, int destStartPosition)
        {
            Parent.UpdateBufferData(DxBuffer, data, destStartPosition);
        }

        private VertexElement[] vertexdefinitioncopy;

        public VertexElement[] VertexDefinition
        {
            get
            {
                return vertexdefinitioncopy;
            }
            set
            {
                vertexdefinitioncopy = value;
                Parent.SetVertexFormat(this, vertexdefinitioncopy);
            }
        }

    }

```

My wrapper abstracts away some detail, for example DirectX has a single type of Resource Buffer with various bindings for things such as vertices, indices, textures, shader constants, etc, whereas I specify multiple explicit types - the ones I intend to use.

There are of course serious caveats with this design:

1. It is closely modelled on DirectX - other implementations will have to bend their APIs to a degree.
2. It leaks - if there are some (desired) concepts that some APIs implement and others do not, the only option is to expand the template to accommodate them, and have the others break; the engine can work out what is available and what not and use workarounds if available.

I pursued the design for a number of reasons, that I would say are important to keep in mind when thinking about designing something such as this:

1. Unless you work for Pixar, there are really only two APIs - DirectX and OpenGL (and if you work for Pixar, there are still only three)
2. And both of these use very similar concepts (makes sense, afterall they operate on the exact same hardware!) - look at the 'SlimDx Pipeline' vs. the 'OpenTK Pipeline'.
3. Most people use Windows, so optimizing for DirectX is never going to be a bad call. (I am writing this with a view to three implementations - OpenGL, DirectX 9 and DirectX 11)

In addition to that of course, is that I am building this as a tool for my personal use, designed only for the methods of the engine I build on top of it, meaning backwards compatibility or leaks are not as big a concern as they would be if it were public or operated at the same level as the engine - full vertical control gives you much more flexibility.

I would be interested to know how you get on, good luck!

# Answer
> 1 votes
Here's how I did it: its not practical for me to post the full solution here, but here is an outline:

```
// this class interacts with the Windows O/S
class Window { } ;

// This class contains the "contract" that each
// of the subsequently defined Graphics Windows
// MUST implement.  Provides basic service such as
// initialization, and rendering a SCENE* object
class IGraphicsWindow : public Window
{
    virtual bool init( int width, int height ) PURE ;
    virtual void render( Scene * scene ) PURE ;

    // ... MORE METHODS (not shown) ...
} ;

```

(a SCENE object contains a collection of Models and vertices.. it is required to be able to render a Scene object)

```
// each implements all methods required by IGraphicsWindow..
class D3D9Window : public IGraphicsWindow {} ;
class D3D11Window : public IGraphicsWindow {} ;
class OpenGLWindow : public IGraphicsWindow {} ;

// Then, you work with an IGraphicsWindow interface
IGraphicsWindow* window = new D3D11Window() ; // using d3d11 thru
// an IGraphicsWindow interface.

```

Its a lot more complicated than that. Handling vertex buffers is completely different, so I defined:

```
class VertexBuffer abstract
{
public:
  virtual void drawTris() PURE ;
  virtual void drawLines() PURE ;
  virtual void drawPoints() PURE ;
} ;

```

And then:

```
template<typename T> class D3D11VertexBuffer : public VertexBuffer { } ;
template<typename T> class D3D9VertexBuffer : public VertexBuffer { } ;

```

`D3D9Window` uses `D3D9VertexBuffer`s, and `D3D11Window` uses `D3D11VertexBuffer`

So really, its hard and requires **a lot** of maintenance and upkeep (DING!!).

# Answer
> 0 votes
You might not have to change anything in your own code actually! The XNA API, apart from the HLSL shaders themselves, has very few ties with DirectX.

There are multiple projects reimplementing the XNA API on top of Mono with OpenGL, and making good progress. Here are a couple:

* MonoGame supports 2D rendering (3D is on the way), for instance Terraria has been shown to run **unmodified** with Mono on Linux using MonoGame's DLLs. It also supports mobile deployments (iOS & Android through MonoTouch and MonoDroid)
* ExEn is more centered on mobile but has started funding for OS X and 3D support.

---
Tags: xna, architecture
---


title: Examples of Android Joystick Controls?

text:
# Question
Title: Examples of Android Joystick Controls?
I can't seem to find any well executed code examples for Android joystick controls.

Whatever it may be, algorithms, pseudo code, actual code examples, strategies, or anything to assist with the design and implementation of Android joystick controls; I can't seem to find anything decent on the net.

**What are some well executed examples?**

More specifically,

* Pseudo Code
* Current Examples
* Idea/Design
* Functionality Description
* Controller Hints Related Directly to Android Architecture

What kind of classes will I have making this? Will there be only one? How would this be implemented to the game architecture? All things I am thinking about.

Cheers!

**UPDATE**

* I've found this on the subject Joystick Example1, though I am still looking for different examples/resources.
* Answered my own question with a link to the code of the above video. It's a fantastic start to Android Joystick Controls.

# Answer
> 0 votes
Anarchy Joystick Widget

The link above is code for implementing a Joystick. You can see this code in action with this video.

---
Tags: android, control, touch
---


# Question
Title: In XNA, is there an issue with copying/pasting the using statements to each .cs file?
When I'm working on a project in XNA I copy the using statements from file to file. However, on tutorials I've seen for various games, they show files that only have specific using statements used. Do the other statements cause problems in the event the program doesn't need it?

I want to avoid any future problems.

# Answer
Extra using statements will very rarely cause problems, and when they do they will be because you have introduced an ambiguous name into the scope (for example, `using` two namespaces with both define a `Vector` type, and then trying to write `Vector myVector = new Vector()` will be ambiguous). The compiler will tell you of these name clashes, and fail to compile your code.

If you run afoul of this, you can either fully-qualify the name reference (`MyNamespace.Vector` verus `SomeOtherNamespace.Vector`) or remove the unused `using` directives.

Note that if you are using Visual Studio, there is an option in the right-click menu while in the text editor for a source file to "remove unused usings." You can also have them sorted via a similar menu command.
> 7 votes

# Answer
is not used to cause problems.

the greatest problem is class or struct name collision.

if you have this:

```
 using System.Drawing;
 usign Microsoft.Xna.Framework.Graphics;

```

these namespaces both contains a Color struct, and you will have to use doing:

```
 System.Drawing.Color Foreground;

 Microsoft.Xna.Framework.Graphics XnaColor = Microsoft.Xna.Framework.Graphics.Color.Red;

```

anyway you can delete unused using statements clicking with right mouse button over the using states and selecting the appropiate option.
> 2 votes

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


# Question
Title: Should I batch up debug primitives for rendering in modern OpenGL?
I've recently started porting some old rendering demos I did to modern OpenGL. I had a debug drawing class in my old code which used immediate mode glBegin(), glEnd() etc. for rendering debug objects such as triangles, cubes and spheres etc.

Originally I replaced the code in these functions with code to generate the VAO and VBOs (for position and colour), bind them, assign the vertex data, render, then disable and delete the VBOs and VAO. Is there anything wrong with this?

I've been thinking about modifying the class so that every time it gets a draw primitive call it generates the VAO and VBOs and assigns the vertex data but doesn't actually do the rendering until after all the other rendering has been completed. Then it renders all the debug prims that have been stored at once.

I'm not sure of the benefits of either way of doing this and was just wondering what people thought.

# Answer
If you are doing debug drawing, then performance really shouldn't be your highest concern. Getting it working is far more important. After all, you won't be using this stuff in release builds, so what does it matter?

However, if you are interested in one way to do it, this page on buffer object streaming suggests ways to improve performance for manually-generated vertex data. Pay particular attention to the "Buffer Update" method.
> 7 votes

# Answer
Whether you want to use immediate mode or VBOs, it depends on the complexity of the scene. I've seen some examples where tangent/normal lines are drawn using immediate mode.

There is nothing wrong with using VBOs for debugging. However, keep in mind that, generally speaking, batching will give you performance benefits no matter which approach you use, so always look to use it whenever possible. You can still benefit a lot from batching in immediate mode (maybe even more), because it will greatly reduce the number of state changes. If batched properly, you will only ever need one GlBegin() and GlEnd(), and all similar data is tightly grouped together. The only difference is that you'll be batching state calls instead of vertex data.
> 1 votes

---
Tags: opengl
---