# Question
Title: How can I optimise a Minecraft-esque voxel world?
I found Minecraft's marvelous large worlds extremely slow to navigate, even with a quad core and meaty graphics card.

I assume Minecraft's slowness comes from:

* Java, as spatial partitioning and memory management are faster in native C++.
* Weak world partitioning.

I could be wrong on both assumptions. However, this got me thinking about the best way to manage large voxel worlds. As it is a true 3D world, where a block can exist in any part of the world, it is basically a big 3D array `[x][y][z]`, where each block in the world has a type (i.e `BlockType.Empty = 0`, `BlockType.Dirt = 1`, etc.)

I assume that to make this sort of world perform well, you would need to:

* Use a tree of some variety (oct/kd/bsp) to split all the cubes out; it seems like an oct/kd would be the better option, as you can just partition on a per cube level not a per triangle level.
* Use some algorithm to work out which blocks can currently be seen, as blocks closer to the user could obfuscate the blocks behind, making it pointless to render them.
* Keep the block object themselves lightweight, so it is quick to add and remove them from the trees.

I guess there is no *right* answer to this, but I would be interested to see peoples' opinions on the subject. **How would you improve performance in a large voxel-based world?**

# Answer
> 112 votes
With regards to Java vs C++, I've written a voxel engine in both (C++ version shown above). I've also been writing voxel engines since 2004 (when they were not vogue). :) I can say with little hesitation that C++ performance is far superior (but it is also more difficult to code). Its less about the computational speed, and more about memory management. Hands down, when you are allocating/deallocating as much data as whats in a voxel world, C(++) is the language to beat. **However**, you should think about your goal. If performance is your highest priority, go with C++. If you just want to write a game without bleeding-edge performance, Java is definitely acceptable (as evidenced by Minecraft). There are many trivial/edge cases, but in general you can expect Java to run about 1.75-2.0 times slower than (well written) C++. You can see a poorly optimized, older version of my engine in action here (EDIT: newer version here). While chunk generation might seem slow, keep in mind it is generating 3D voronoi diagrams volumetrically, calculating surface normals, lighting, AO, and shadows on the CPU with brute-force methods. I have tried out various techniques and I can get about 100x faster chunk generation using various caching and instancing techniques.

To answer the rest of your question, there are many things you can do to improve performance.

1. Caching. Wherever you can, you should compute data once. For example, I bake the lighting into the scene. It could use dynamic lighting (in screen space, as a post-process), but baking in the lighting means that I don't have to pass in the normals for the triangles, which means....
2. Pass as little data to the video card as possible. One thing people tend to forget is that the more data you pass to the GPU, the more time it takes. I pass in a single color and a vertex position. If I want to do day/night cycles, I can just do color grading, or I can recompute the scene as the sun gradually changes.
3. Since passing data to the GPU is so expensive, it is possible to write an engine in software which is faster in some respects. The advantage of software is that it can do all kinds of data manipulation / memory access that simply is not possible on a GPU.
4. Play with the batch size. If you are using a GPU, performance can vary dramatically based on how big each vertex array you pass is. Accordingly, play around with the size of the chunks (if you use chunks). I've found that 64x64x64 chunks work pretty well. No matter what, keep your chunks cubic (no rectangular prisms). This will make coding and various operations (like transformations) easier, and in some cases, more performant. If you only store one value for the length of every dimension, keep in mind thats two less registers that get swapped around during compute.
5. Consider display lists (for OpenGL). Even though they are the "old" way, they can be faster. You must bake a display list into a variable...if you call display list creation operations in realtime, it will be ungodly slow. How is a display list faster? It only updates the state, vs per-vertex attributes. This means I can pass up to six faces, then one color (vs a color for each vertex of the voxel). If you are using GL\_QUADS and cubic voxels, this could save up to 20 bytes (160 bits) per voxel! (15 bytes with no alpha, although usually you want to keep things 4-byte aligned.)
6. I use a brute-force method of rendering "chunks", or pages of data, which is a common technique. Unlike octrees, it is much easier/faster to read/process the data, although much less memory friendly (however, these days you can get 64 gigabytes of memory for $200-$300)...not that the average user has that. Obviously, you cannot allocate one huge array for the whole world (a 1024x1024x1024 set of voxels is 4 gigabytes of memory, assuming a 32-bit int is used per voxel). So you alloc/dealloc many small array, based on their proximity to the viewer. You can also alloc the data, get the necessary display list, then dump the data to save memory. I think the ideal combo might be to use a hybrid approach of octrees and arrays -- store the data in an array when doing procedural generation of the world, lighting, etc, then keep the octree around for collision detection and other less expensive tasks.
7. Render near to far...a pixel clipped is time saved. The gpu will toss a pixel if it does not pass the depth buffer test.
8. Render only chunks/pages in the viewport (self explanatory). Even if the gpu knows how to clips polgyons outside of the viewport, passing this data still takes time. I don't know what the most efficient structure for this would be ("shamefully," I have never written a BSP tree), but even a simple raycast on a per chunk basis might improve performance, and obviously testing against the viewing frustum would save time.
9. Obvious info, but for the newbies: remove every single polygon that is not on the surface -- i.e. if a voxel consists of six faces, remove the faces that never get rendered (are touching another voxel).
10. As a general rule of everything you do in programming: CACHE LOCALITY! If you can keep things cache-local (even for a small amount of time, it will make an enormous difference. This means keeping your data congruent (in the same memory region), and not switching areas of memory to process too often. So, ideally, work on one chunk per thread, and keep that memory exclusive to the thread. This does not just apply to the CPU cache. Think of the cache hierarchy like this (slowest to fastest): network (cloud/database/etc) -\> hard drive (get a SSD if you don't already have one), ram (get tripple channel or greater RAM if you don't already have it), CPU Cache(s), registers. Try to keep your data on the latter end, and not swap it more than you have to.
11. Threading. Do it. Voxel worlds are well suited for threading, as each part can be calculated (mostly) independently of others...I saw literally a near-4x improvement (on a 4 core, 8 thread Core i7) in procedural world generation when I wrote the routines for threading.
12. Do not use char/byte data types. Or shorts. Your average consumer will have a modern AMD or Intel processor (as will you, probably). These processors do not have 8 bit registers. They calculate bytes by putting them into a 32 bit slot, then converting them back (maybe) in memory. Your compiler may do all sorts of voodoo, but using a 32 or 64 bit number is going to give you the most predictable (and fastest) results. Likewise, a "bool" value does not take 1 bit; the compiler will often use a full 32 bits for a bool. It may be tempting to do certain types of compression on your data. For example, you could store 8 voxels as a single number (2^8 = 256 combinations) if they were all the same type/color. However, you have to think about the ramifications of this - it might save a good deal of memory, but it can also hinder performance, even with a small decompression time, because even that small amount of extra time scales cubically with the size of your world. Imagine calculating a raycast; for every step of the raycast, you would have to run the decompression algorithm (unless you come up with a smart way of generalizing the calculation for 8 voxels in one ray step).
13. As Jose Chavez mentions, the flyweight design pattern can be useful. Just as you would use a bitmap to represent a tile in a 2D game, you can build your world out of several 3D tile (or block) types. The downside to this is repetition of textures, but you can ameliorate this by using variance textures that fit together. As a rule of thumb, you want to utilize instancing wherever you can.
14. Avoid vertex and pixel processing in the shader when outputting the geometry. In a voxel engine you will inevitably have many triangles, so even a simple pixel shader can reduce your render time greatly. Its better to render to a buffer, then do you pixel shader as a post-process. If you can't do that, try to do calculations in your vertex shader. Other calculations should be baked into the vertex data where possible. Additional passes become very expensive if you must re-render all the geometry (such as shadow mapping or environment mapping). Sometimes it is better to give up a dynamic scene in favor of richer details. If your game has modifiable scenes (i.e. destructible terrain) you can always recompute the scene as things are destroyed. The recompilation is not expensive and should take under a second. You can also do things to delay the user and calculate a recomputed environment behind the scenes (i.e. chip away at a block until you are ready to exchange it with new geometry).
15. Unwind your loops and keep arrays flat! Don't do this:

```
for (i = 0; i < chunkLength; i++) {
 for (j = 0; j < chunkLength; j++) {
  for (k = 0; k < chunkLength; k++) {
   MyData[i][j][k] = newVal;
  }
 }
}
//Instead, do this:
for (i = 0; i < chunkLengthCubed; i++) {
 //figure out x, y, z index of chunk using modulus and div operators on i
 //myData should have chunkLengthCubed number of indices, obviously
 myData[i] = newVal;
}

```

**EDIT: Through more extensive testing, I have found this can be wrong. Use the case that works best for your scenario. Generally, arrays should be flat, but using multi-index loops can often be faster depending on the case**

**EDIT 2: when using multi-index loops, best to loop int the z, y, x order rather than the other way around. Your compiler might optimize this, but I would be surprised if it did. This maximizes efficiency in memory access and locality.**

```
for (k < 0; k < volumePitch; k++) {
    for (j = 0; j < volumePitch; j++) {
        for (i = 0; i < volumePitch; i++) {
            myIndex = k*volumePitch*volumePitch + j*volumePitch + i;
        }
    }
}

```
16. Sometimes you have to make assumptions, generalizations, and sacrifices. The best one you can make is to assume that most of your world is completely static, and only changes every couple thousand frames. For the animated parts of the world, those can be done in a separate pass. Also assume most of your world is completely opaque. Transparent objects can be rendered in a separate pass. Assume that textures only vary every x units, or that objects can only be placed in x increments. Assume a fixed world size...as tempting as an infinite world is, it can lead to unpredictable system requirements. For example, to simplify the voronoi pattern generation in the rocks above, I assumed that every voronoi center point lied in a uniform grid, with a slight offset (in other words, implied geometric hashing). Assume a world that does not wrap (has edges). This can simplify many complexities introduced by a wrapping coordinate system, at minimal cost to user experience.

You can read more about my implementations at my site

# Answer
> 7 votes
There are a lot of things that Minecraft could be doing more efficiently. For example, Minecraft loads entire vertical pillars of about 16x16 tiles and renders them. I feel that it is very inefficient to send and render that many tiles needlessly. But I don't feel like choice of language is an important one.

Java can be quite fast but for something this data-oriented, C++ does have a large advantage with significantly less overhead for accessing arrays and working within bytes. On the flip side, it is much easier to perform threading across all platforms in Java. Unless you plan to utilize OpenMP or OpenCL, you won't find that convenience in C++.

My ideal system would be a slightly more complex hierarchy.

**Tile** is a single unit, likely around 4 bytes to keep information such as material type and lighting.

**Segment** would be a 32x32x32 block of tiles.

1. Flags would be set for each of the six sides, if that entire side is solid blocks. That would allow the renderer to occlude segments behind that segment. Minecraft currently does not appear to perform occlusion testing. But there was mention of having hardware occlusion culling available which can be costly but better than rendering massive amounts of polygons on low-end cards.
2. Segments would only be loaded into memory during activity (players, NPCs, water physics, tree growth, etcetera). Otherwise they would be sent directly still compressed from disk to clients.

**Sectors** would be a 16x16x8 block of segments.

1. Sectors would track the highest segment for each vertical column so that segments higher than that can quickly be determined empty.
2. It would also track the bottom occluded segment, so that every segment that needs to be rendered from the surface could be quickly grabbed.
3. Sectors would also track the next time each segment needs to be updated (water physics, tree growth, etcetera). This way loading in each sector would be enough to keep the world alive and only loading in segments long enough to complete their tasks.
4. All entity positions would be tracked relative to the Sector. This would prevent the floating-point errors present in Minecraft when travelling very far from the map center.

**World** would be an infinite map of sectors.

1. The world would be responsible for managing sectors and their next updates.
2. The world would preemptively send segments to players along their potential paths. Minecraft reactively sends segments that the client requests, inciting a delay.

# Answer
> 5 votes
Minecraft is pretty quick, even on my 2-core. Java does not seem to be a limiting factor, here, although there is a bit of server lag. Local games seem to do better, so I'm going to assume some inefficiencies, there.

As to your question, Notch (Minecraft author) has blogged at some length about the technology. In particular, the world is stored in "chunks" (you sometimes see these, especially when one is missing as the world hasn't filled in, yet.), so the first optimization is to decide if a chunk can be seen or not.

Within a chunk, as you have guessed, the app has to decide if a block can be seen or not, based on whether or not is is obscured by other blocks.

Note, too, that there are block FACES, which can be assumed not-seen, by virtue of either being obscured (i.e., another block covers the face) or by which direction the camera is pointing (if the camera faces North, you can't see the North face of ANY blocks!)

Common techniques would also include not keeping separate block objects but, rather, a "chunk" of block types, with a single prototype block for each one, along with some minimal set of data to describe how this block may be custom. For example, there aren't any custom granite blocks (that I know), but water has data to tell how deep it is along each side-face, from which one can calculate its direction of flow.

Your question isn't clear if you're looking to optimize render speed, data size or what. Clarification there would be helpful.

# Answer
> 4 votes
Here's just a few words of general info and advice, which I can give as an, um, overly experienced Minecraft modder (which may at least partly give you some guidance.)

The reason Minecraft is slow has a LOT to do with some questionable, low-level design decisions-- for example, every time a block is referenced by positioning, the game validates the coordinates with about 7 if statements to ensure it's not out of bounds. Furthermore, there's no way to grab a 'chunk' (a 16x16x256 unit of blocks the game works with) then reference blocks in it directly, in order to bypass cache lookups and, erm, silly validation issues (iow, each block reference also involves a chunk lookup, among other things.) In my mod, I created a way to grab and change the array of blocks directly, which boosted massive dungeon generation from unplayably laggy to unnoticeably fast.

EDIT: Removed claim that declaring variables at a different scope resulted in performance gains, this doesn't actually appear to be the case. I believe at the time that I conflated this result with something else I was experimenting with (specifically, removing casts between doubles and floats in explosion related code by consolidating to doubles... understandably, this had a huge impact!)

Also, though it's not the area I spend a lot of time in, most of the performance choke in Minecraft is an issue with the rendering (about 75% of game time is dedicated to it on my system). Obviously you don't care so much if the concern is supporting more players in multiplayer (server doesn't render anything), but it matters to the extent of everyone's machines being able to even play.

So whatever language you choose, try to get very intimate with the implementation/low level details, because even one little detail in a project such as this could make all the difference (one example for me in C++ was "Can the compiler statically inline function pointers?" Yes it can! Made an incredible difference in one of the projects I was working on, since I had less code and the advantage of inlining.)

I really dislike that answer because it makes high-level design difficult, but it's the painful truth if performance is a concern. Hope you found this helpful!

Also, Gavin's answer covers some details I didn't want to reiterate (and much more! He's clearly more knowledgeable on the subject than I am), and I agree with him for the most part. I'll have to experiment with his comment regarding processors and shorter variable sizes, I've never heard of that-- I'd like to prove to myself that it's true!

# Answer
> 2 votes
The thing is to think about how you would first of all load the data. If you stream your map data into memory when needed, there is abivously a natural limit to what you can render, this is already a rendering performance upgrade.

What you do with this data is then up to you. For GFX performance, you can then use Clipping to clip hidden objects, objects that are too small to be visible, etc.

If you are then just looking for Graphics Performance techniques I'm sure you can find mountains of stuff on the net.

# Answer
> 1 votes
Something to look at is the Flyweight design pattern. I believe most of the answers here reference this design pattern in one way or another.

While I don't know the exact method Minecraft is using to minimize memory for each block type, this is a possible avenue to use in your game. The idea is to have only one object, like a prototype object, that holds information about all the blocks. The only difference would be the location of each block.

But even location can be minimized: if you know a block of land is of one type, why not store the dimensions of that land as one giant block, with one set of location data?

Obviously the only way to know is to start implementing your own, and do some memory tests for performance. Let us know how it goes!

---
Tags: procedural-generation, optimization, terrain, voxels, space-partitioning
---


# Question
Title: how should I network my turn based game?
I'm writing a very basic turn based strategy game which allows a player to select units and attack enemy units on their turn. The game is written in Java using the slick2d library and I plan to use kyronet for the networking api.

I want the game to be networked, but I do not know how I should go about it. My current idea is to connect two users together, and the first one to join the game becomes the game host, while the other becomes the client.

However after reading http://gafferongames.com/networking-for-game-programmers/what-every-programmer-needs-to-know-about-game-networking/ it seems my game would be suited to a peer to peer lockstep model. Would that make programming the networking side much easier?

Any suggestions on how I should structure my networking would be greatly appreciated

# Answer
If it's just a basic turn based strategy game you could utilize Java's Remote Method Invocation (RMI) API. It basically lets you call methods on remote machines without having to worry about the networking part. For example, your client could call "makeTurn(player)" on the server while the server calls "madeTurn(player, whatKindOfTurn)" on the client. I hope you get the idea. There are tons of resources about RMI.

You could also go the Kryonet / Socket way, as you will probably learn more about networking if you go that route, but it will also significantly slow down your development process.

Hope that helped.
> 1 votes

# Answer
Unless you are strictly limiting your networking to a pair of computers you own and control, peer-to-peer is difficult to get to work - there are too many routers, firewalls, and antivirus tools out there, interfering with add-hoc networks.

The usual solution is to use a public server, and communicate with it using HTTP requests. The server would typically store game state and do most of the work of validating network communications from untrusted sources (that's the only kind of source there is)
> 1 votes

---
Tags: java, networking, slick, turn-based
---


# Question
Title: Do I need to use the Kinect SDK to develop for Xbox?
I was wondering if I need to use the Kinect SDK from Microsoft to develop games for the Xbox 360. I know there are other libraries such as OpenNI and OpenGL, but can I develop games using Kinect for those? Also where would I get a License to develop for the 360?

# Answer
> 2 votes
The question explicitly asks how to write Kinect games for the 360. My understanding is that XNA on the 360 doesn't support the Kinect. It seems you can possibly use it on Windows, but as I've never tried I can't confirm (but a quick internet search seems to confirm you can).

Unless you're an authorised 360 developer (think have a publisher that's an approved XBox 360 developer or some sort of track record making games that would help get your foot in the door talking to MS) you're not going to get access to the full blown XDK that allows C++ based development and access to the Kinect device. There are no other alternatives for 360 development.

# Answer
> 3 votes
The Xbox360's primary development tool is C# and Microsoft's XNA framework.

You will need a copy of Visual C# (Express is usable forever once you get a free registration key):

http://www.microsoft.com/visualstudio/en-us/products/2010-editions/visual-csharp-express

And the XNA SDK:

http://www.microsoft.com/en-us/download/details.aspx?id=23714

Here are some good sites to check out to get started:

http://create.msdn.com/en-US/

http://www.riemers.net/

You can get the App Hub membership here:

http://create.msdn.com/en-us/home/membership

The membership allows you to upload 10 Xbox360 games and test your games on your console, among some other benefits.

---
Tags: xna, c#, legal, xbox360, kinect
---


# Question
Title: How to integrate the game editor with the engine?
What I am trying to figure out is what is the best way to integrate the editor(level, effects, model, etc...) in the most effective way?

Now the first thing I thought would be to create the game engine(\*) extremely modular. For example I took the example of game states. You could have multiple game states that all have their own update() and draw() methods among others. Each game state class would inherit from a base GameState class. This allows for a more modular approach and a useful one at that.

Now would the most efficient approach be to implement the editor along with the modular engine, or create two different designs for both the game, and editor? I thought to take the game state example and extend it to window states, and well could be used for a lot more systems. Is there a better implementation of this design(game state) for use in other systems used in the engine?

\*: Now I know the term game engine is sorta irrelevant, and misused in many situations. What I am referring to as the "game engine" is the combination of the systems that the game must interact with for short.

Also this is more of a theory / design question than an implementation. Even though both mix, I'd rather like to have a more general idea on how the editor is built in an efficient way and still using the same engine code as what the game uses.

P.S If you need more clarification or extra bits just leave a comment.

# Answer
> 5 votes
I think your question is more about design, but usually you don't want to design something that can't be implemented, so implementation shows up every now and then.

As for the editor, I think it depends on what the run-time game engine library can support. Does it support some kind of general application architecture (e.g. event system, exception handling, GUI, etc...) or is it more focused on running a particular type of game that it was made for? If it supports such an architecture, I think one would implement the editor similar to a game. If it didn't, the editor could be a stand alone program using some established framework.

You might want to check out Game Engine Architecture, by Jason Gregory. In this book, the author points out that UnrealEd is an example of an editor built using the engine that it supports and that such a design has pros and cons. (pro: everything is native, so it's easy to hit 'play' and jump right into the game from the editor. con: if your engine isn't stable/in development, the usage of the editor can be affected.)

Below is a picture of an engine's architecture from the same book, for an example. To integrate an editor, you would probably want to add a generic GUI to the Frontend. You might also want an application Event system (that can be turned off/on) that sits somewhere between the HID and the Frontend. You could probably get a decent amount of functionality out of just that, but there might be an Editor/Generic Application - Specific Subsystems bubble next to the game one and other preexisting bubbles might be extended, as needed.

---
Tags: c++, architecture, editors
---


# Question
Title: Load individual sprite from a sprite sheet and make it a FlxSprite
I'm using flixel and flixer power tools which contains a FlxButtonPlus class that allows me to load 2 FlxSprite as each button state, the problem is that FlxSprite requires a Class a its source but I would like to have a single spritesheet for all my buttons and call each one from there, rather than having a bunch of pngs for every button and every state.

Any idea on how to do that?

# Answer
You can have one (or a few) PNG sprite sheet and use it for multiple different sprites. You'll need to create the sprite object and use `loadGraphic(graphic,true)` to load the sprite sheet. "animated" must be true; if it's false the entire image will be one static frame. "graphic" is the embedded PNG of type `Class`

You'll have to put them all in one horizontal row and each frame will need to be the same width and height as all the others. Ideally frames should be square, but you can specify rectangular frames. Then you can use `frame = value` where value is the index of the frame you want to use for static images.

You can also do `addAnimation("name", [1, 2, 3], 29)` to create named animations that you can play back with `play("name")`. That said, it is probably a good idea to still do separate sprite sheets for animated sprites.
> 1 votes

---
Tags: flash, flixel
---


# Question
Title: Positioning a sprite in XNA: Use ClientBounds or BackBuffer?
I'm reading a book called "*Learning XNA 4.0*" written by *Aaron Reed*. Throughout most of the chapters, whenever he calculates the position of a sprite to use in his call to `SpriteBatch.Draw`, he uses `Window.ClientBounds.Width` and `Window.ClientBounds.Height`. But then all of a sudden, on page *108*, he uses `PresentationParameters.BackBufferWidth` and `PresentationParameters.BackBufferHeight` instead.

I think I understand what the Back Buffer and the Client Bounds are and the difference between those two (or perhaps not?). But I'm mighty confused about when I should use one or the other when it comes to positioning sprites. The author uses for the most part Client Bounds both for checking whenever a moving sprite is of the screen and to find a spawn point for new sprites. However, he seems to make two exceptions from this pattern in his book. The first time is when he wants some animated sprites to "move in" and cross the screen from one side to another (page *108* as mentioned). The second and last time is when he positions a texture to work as a button in the lower right corner of a Windows Phone 7 screen (page *379*).

Anyone got an idea?

I shall provide some context if it is of any help. Here's how he usually calls `SpriteBatch.Draw` (code example from where he positions a sprite in the middle of the screen \[page *35*\]):

```
spriteBatch.Draw(texture,
   new Vector2(
   (Window.ClientBounds.Width / 2) - (texture.Width / 2),
   (Window.ClientBounds.Height / 2) - (texture.Height / 2)),
   null,
   Color.White,
   0,
   Vector2.Zero,
   1,
   SpriteEffects.None,
   0);

```

And here is the first case of four possible in a switch statement that will set the position of soon to be spawned moving sprites, this position will later be used in the `SpriteBatch.Draw` call (page *108*):

```
// Randomly choose which side of the screen to place enemy,
// then randomly create a position along that side of the screen
// and randomly choose a speed for the enemy
switch (((Game1)Game).rnd.Next(4))
{
   case 0: // LEFT to RIGHT
      position = new Vector2(
         -frameSize.X, ((Game1)Game).rnd.Next(0,
         Game.GraphicsDevice.PresentationParameters.BackBufferHeight
         - frameSize.Y));

      speed = new Vector2(((Game1)Game).rnd.Next(
         enemyMinSpeed,
         enemyMaxSpeed), 0);
   break;

```

# Answer
> 2 votes
Neither.

Use `GraphicsDevice.Viewport`, as that is the region that `SpriteBatch` actually uses to do its drawing.

See also this answer for when you should use each of the available options.

---
Tags: xna, sprites
---


# Question
Title: Is there a command line ATI texture compression tool?
Is there a command line tool that can convert PNG and JPG files to ATITC compressed textures?

I have my own export pipeline that converts all textures to PVRTC, ATITC, and DXT, so I have no use for a GUI-based tool like the Compressonator. Also, I'm running on Linux (although Wine might be able to handle simple conversion tools).

# Answer
> 3 votes
Compressonator can be used through the command line.

```
TheCompressonator <-command> [options]
Commands:
  help     - display help
  convert  - convert image type to another, or compress
  diff     - compare textures
  plugins  - get list of plugins and their options

```

# Answer
> 1 votes
For future reference: ImgTec has both a texture compression utility and a texture compression library (which works under both Linux and Windows). They support some compressed texture formats, like DXT and PVRTC.

Rolling out your own command-line tool is easy as pie using the library. I'm currently adding PVRTC support for my XNA pipeline (the processor is made with Managed-C++) and haven't found any problems yet.

# Answer
> 1 votes
I managed to get the compressonator to run under Ubuntu 12.04 by first running

```
winetricks vcrun2005

```

then copying the installed compressonator files to ~/.wine/drive\_c and running it from there with

```
wine TheCompressonator.exe

```

# Answer
> 1 votes
**Andreno SDK** provides a windows library to compress your texture without Compressonator. You can build your **own tool** to convert PNG, BMP, TGA or JPEG to ATITC on windows platform.

Otherwise, Unity3D which is running on OS X and windows generates ATITC for mobile assets, but i don't find the internal tool which does it (No wine too).

NB: our build system can compress to ETC, PVR and DXT on Win, OSX and Linux but for ATITC we zip all src images, send them to a server and use ATI Compressonator to compress them and download them when it's done.

NB 2: use PVRTextTool for PVR, it is faster or better than textureTool (Apple's one).

---
Tags: tools, textures, compression
---


# Question
Title: Implement Fast Inverse Square Root in Javascript?
The Fast Inverse Square Root from Quake III seems to use a floating-point trick. As I understand, floating-point representation can have some different implementations.

So is it possible to implement the Fast Inverse Square Root in Javascript?

Would it return the same result?

```
float Q_rsqrt(float number) {

  long i;
  float x2, y;
  const float threehalfs = 1.5F;

  x2 = number * 0.5F;
  y = number;
  i = * ( long * ) &y;
  i = 0x5f3759df - ( i >> 1 );
  y = * ( float * ) &i;
  y = y * ( threehalfs - ( x2 * y * y ) );

  return y;

}

```

# Answer
> 16 votes
The trick depends on *reinterpreting the bits of a floating-point number as an integer* and back again, which is possible in JavaScript by using the Typed Arrays facility, to create a raw byte buffer with multiple numeric views onto it.

Here is a literal conversion of the code you gave; note that it is not exactly the same, as all arithmetic operations in JavaScript are 64-bit floating point, not 32-bit, so the input will necessarily be converted. Also, like the original code, this is *platform-dependent* in that it will give nonsense results if the processor architecture uses a different byte order; if you must do things like this, I recommend that your application first execute a test case to determine that integers and floats have the byte representations you expect.

```
const bytes = new ArrayBuffer(Float32Array.BYTES_PER_ELEMENT);
const floatView = new Float32Array(bytes);
const intView = new Uint32Array(bytes);
const threehalfs = 1.5;

function Q_rsqrt(number) {
  const x2 = number * 0.5;
  floatView[0] = number;
  intView[0] = 0x5f3759df - ( intView[0] >> 1 );
  let y = floatView[0];
  y = y * ( threehalfs - ( x2 * y * y ) );

  return y;
}

```

I've confirmed by eyeballing a graph that this gives reasonable numeric results. However, it is not obvious that this will improve performance at all, since we are doing more high-level JavaScript operations. I have run benchmarks on the browsers I have handy and found that `Q_rsqrt(number)` takes 50% to 80% of the time taken by `1/sqrt(number)` (Chrome, Firefox, and Safari on macOS, as of April 2018). Here is my complete test setup:

```
const {sqrt, min, max} = Math;

const bytes = new ArrayBuffer(Float32Array.BYTES_PER_ELEMENT);
const floatView = new Float32Array(bytes);
const intView = new Uint32Array(bytes);
const threehalfs = 1.5;

function Q_rsqrt(number) {
  const x2 = number * 0.5;
  floatView[0] = number;
  intView[0] = 0x5f3759df - ( intView[0] >> 1 );
  let y = floatView[0];
  y = y * ( threehalfs - ( x2 * y * y ) );

  return y;
}

// benchmark
const junk = new Float32Array(1);
function time(f) {
  const t0 = Date.now();
  f();
  const t1 = Date.now();
  return t1 - t0;
}
const timenat = time(() => {
  for (let i = 0; i < 5000000; i++) junk[0] = 1/sqrt(i)
});
const timeq = time(() => {
  for (let i = 0; i < 5000000; i++) junk[0] = Q_rsqrt(i);
});
document.getElementById("info").textContent =
  "Native square root: " + timenat + " ms\n" +
  "Q_rsqrt: " + timeq + " ms\n" +
  "Ratio Q/N: " + timeq/timenat;

// plot results
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
function plot(f) {
  ctx.beginPath();
  const mid = canvas.height / 2;
  for (let i = 0; i < canvas.width; i++) {
    const x_f = i / canvas.width * 10;
    const y_f = f(x_f);
    const y_px = min(canvas.height - 1, max(0, mid - y_f * mid / 5));
    ctx[i == 0 ? "moveTo" : "lineTo"](i, y_px);
  }
  ctx.stroke();
  ctx.closePath();
}
ctx.strokeStyle = "black";
plot(x => 1/sqrt(x));
ctx.strokeStyle = "yellow";
plot(x => Q_rsqrt(x));
```

```
<pre id="info"></pre>
<canvas width="300" height="300" id="canvas"
        style="border: 1px solid black;"></canvas>
```

---
Tags: javascript
---


# Question
Title: How do I convert sin, cos and tan into an int in Java?
How would you be able to change `Math.sin`, `Math.cos` and `Math.tan` into an `int`? This is because I heard that it is useful to have those Math resources in movement, gravity, etc. in gaming. Also, as a little inside question, does anyone know if there is a method where you can square or cube a number instead of doing: (Pseudo Example) `9 * 9 * 9` ?

# Answer
> 5 votes
You can convert any `float` or `double` to an `int` with a cast. For example:

```
int integerResult = (int)Math.sin(variable);

```

However, this really does not make sense. Since the result of `Math.sin()` will always be from -1 to 1, this cast will always make the result 0 or -1 or 1. From the sound of your question you're not very sure about how to use these. I would strongly recommend you brush up on your math skills before attempting anything too complicated with your programming. You can, of course, use these in floating point format instead of as an integer.

Your second question. `9 * 9 * 9` is equivalent to 9 cubed. You could make your own method for the clearest intent:

```
int cube(int input) {
    //return the input cubed
    return input*input*input;
}

```

Or use the built in function `Math.pow()` like so:

```
float nineCubed = Math.pow(9,3);

```

You can see check the java doc to see what functions Java has built in for math.

Finally, you can check out some of these math resources:

What math should all game programmers know?

Linear algebra for game developers part 1

---
Tags: java, mathematics
---


title: Space & Sound? Defying Physics?

text:
# Question
Title: Space & Sound? Defying Physics?
Why are there sound effects in **space shooter** games like *asteroid* and such?

There is no medium in space for sound to travel by. Yet we get hear gun shots & explosion.

I am not talking about the background music/sound.

# Answer
> 7 votes
Seems strange to pick apart on just the fact that you could hear sound. There's a good deal of things that many space games do that doesn't relate to reality:

* Respawn
* Infinite fuel
* Infinite power
* Maximum velocity even with sustained acceleration
* Faster than light travel
* The stresses of extreme acceleration are ignored
* and so on.

The point is to remove these constraints because it's not supposed to be a simulation. It's supposed to be a fun game. It's not fun to obey the laws of reality.

Secondly, many people are not as educated as you or I. They know things make sound, so they expect things to make sound. When they don't, it's something wrong with the game and it's less entertaining.

# Answer
> 3 votes
First off, this trope is hardly specific to games; it is extremely common in movies and TV shows too (refer here http://tvtropes.org/pmwiki/pmwiki.php/Main/SpaceIsNoisy )

The reason is pretty simple: those sound effects are cool, and a completely silent game would be boring.

# Answer
> 3 votes
**Because it's a game.**

You can do stuff like that in games. When's the last time you saw someone do a double jump in real life? Or heal fully from half a dozen bullet wounds in the space of ten seconds? Or be shot to within an inch of death, only to touch a medkit and be perfectly healthy again?

It's not realistic. It doesn't have to be. It's a game. You can do unrealistic things.

**It just has to be fun.**

# Answer
> 1 votes
You can hear the sounds of explosions and gunshots because they make the game much more interesting. An alternative approach could be to only play the sounds that originate from one's own spaceship.

Space games without any combat sound effects can be nice too, if you have a nice playlist of music to make up for it. In my opinion, the MMO Eve Online did this quite well.

---
Tags: sound, spaces
---


# Question
Title: How to manage drawing loop when changing render targets
I'm managing my game state by having a base `GameScreen` class with a `Draw` method.

I then have (basically) a stack of `GameScreen`s that I render.
I render the bottom one first, as screens above might not completely cover the ones below.

I now have a problem where one `GameScreen` changes render targets while doing its rendering. Anything the previous screens have drawn to the backbuffer is lost (as XNA emulates what happens on the xbox). I don't want to just set the backbuffer to preserve its contents as I want this to work on the xbox as well as PC.

---

How should I manage this problem?

A few ideas I've had:

1. Render every `GameScreen` to its own render target, then render them all to the backbuffer.
2. Create some kind of RenderAction queue where a game screen (and anything else I guess) could queue something to be rendered to the back buffer. They'd render whatever they wanted to any render target as normal, but if they wanted to render to the backbuffer they'd stick that in a queue which would get processed once all rendertarget rendering was done.
3. Abstract away from render targets and backbuffers and have some way of representing the way graphics flows and transforms between render targets and have something manage/work out the correct rendering order (and render targets) given what rendering process needs as input and what it produces as output.

I think each of my ideas have pros and cons and there are probably several other ways of approaching this general problem so I'm interested in finding out what solutions are out there.

# Answer
> 2 votes
I believe (haven't tested it) that if you split your Draw call into PrepareDraw and Draw calls, you can have the GameScreen that changes render targets do that in PrepareDraw and then all GameScreens draw to the backbuffer in the Draw call.

```
List<GameScreen> screens;
foreach (var screen in screens)
  screen.PrepareDraw(...);
foreach (var screen in screens)
  screen.Draw(...);

```

# Answer
> 0 votes
You should be able to first draw to screen, then to a render target and then to the screen again in the same draw loop without losing data. Once that works you should be fine by letting each GameScreen handle whether they need an RT or not themselves. Keep them as 'black box' as possible.

Maybe you're forgetting to fetch the texture from the render target before switching them out? Also note that you can't re-use a render target in the same frame.

*What tech are you using btw? Maybe there is a difference between XNA/DirectX and what you're using*

---
Tags: xna, rendering, rendertargets
---


# Question
Title: How can I make my main character move in a parabolic arc when jumping?
I'm entering Android game development, and I already have a computer version of a game I want to publish. The thing is, I want to make this as good as it can be. With that said, I need a physics engine, really to only do one thing: make a parabolic movement of my main character as he's jumping in the air. Currently, my computer version simply makes the guy move up at a 45 degree angle, and as soon as it hits the ceiling, down at a 45 degree angle. I need a physics engine/library that would accomplish that, it has to be in java since that's my best language, it has to be 2D, and it has to be able to work on Android. Which physics engine/library could accomplish all of that?

# Answer
You don't need a physics engine for this because the calculations required are extremely simple! All you have to do is to apply some gravity to your player's vertical velocity, and he will automatically follow an arc when jumping.

For a detailed explanation of how it works, including a demo that runs in the browser, read the following answer:

https://gamedev.stackexchange.com/a/29618/11686

But I'll transcribe the two most important points to this answer. This is all the physics you need to add to your game:

```
float positionX, positionY;     // Position of the character
float velocityX, velocityY;     // Velocity of the character
float gravity = 0.5f;           // How strong is gravity

void Update(float time)
{
    velocityY += gravity * time;        // Apply gravity to vertical velocity
    positionX += velocityX * time;      // Apply horizontal velocity to X position
    positionY += velocityY * time;      // Apply vertical velocity to X position
}

```

And this is how you initiate a jump, i.e. apply a vertical impulse to the player to get him off the floor, and let gravity take care of bringing him down:

```
void OnJumpKeyPressed()
{
    velocityY = -12.0f;   // Give a vertical boost to the players velocity to start jump
}

```
> 10 votes

# Answer
I would start by looking at libgdx. There are three main advantages for you as I see it:

1. It comes with Box2d integrated
2. It comes with a 2D scene graph (in case you've never used a scene graph, this can greatly simplify setting up 2D levels and sprites, handling input, etc)
3. It runs on the desktop and Android. In Eclipse, it's just a matter of selecting a project and pressing 'Run', and this is a tremendous boost over waiting for the emulator.

The project is in active development, so some of the documentation is out of date. I would recommend starting with these tutorials on Scene2d to get started. There's like 10 or more sections, but you probably only need the first few:

http://steigert.blogspot.com/2012/02/1-libgdx-tutorial-introduction.html
> 4 votes

# Answer
If you know Box2D, a 2D physics engine written in C++, then you know the Java version of that engine, JBox2D. There is an Android project based on JBox2D, I'd suggest you to take a look at it. http://code.google.com/p/androidbox2d/
> 3 votes

---
Tags: java, android, physics, physics-engine
---


# Question
Title: Best practices in managing character states
While in development of a character, I feel like I'm digging myself deeper into a hole every time I add more functionality to him, creating more bugs and it seems like my code is tripping over itself all over the place.

What are the best practices when managing character states for a character that has a large selection of abilities and actions that they can perform, without their abilities interrupting each other and creating a mess overall?

# Answer
If a character can only perform one action at a time, then you can use the State pattern to represent that action.

Basically this means that your character contains an object which handles the current state of the character, or specifically in this case, the current action. Typically you derive all your states from a standard base class or interface, which in a game might only have 1 method on it, an Update() function.

Add the action object when the action begins, call Update() once per frame or as often as you need to update the state, and remove the object when the action is complete.
> 8 votes

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


# Question
Title: XNA Skinning Sample - exporting from Blender recognize only first animation clip
**(and sorry for my English)** I'm using animation components from XNA Skinning Sample. It works great but when I export a model from Blender, it does not recognize any other animation clips than the first one. So I have three animation clips, but XNA recognize only one. Also, when I looked up on Xml file of the model in Debug\Content\obj directory, there is only one animation clip, but when I check code directly from .fbx file, it seems to be alright.

Link to my model files: https://skydrive.live.com/redir?resid=8480AF53198F0CF3!139

BIG Thanks in forward!

# Answer
This is because XNA 4.0 does not support more than one take per fbx file, the simplest solution is to export the model and armature first, then export one animation at a time with only the armature per fbx and merge the result in the content pipeline. Shawn Hargreaves did a post on this with code.
> 1 votes

---
Tags: xna, c#, animation, blender, skinning
---


# Question
Title: What web technology could I use which would support a decision tree?
I am a big game development fan but I haven't done any commercial work in the past. I have been asked by a non-profit to look at developing a game similar to the award-winning www.playspent.org

They want the following features:

* support 5 scenarios
* mobile isn't important but compatibility with older browsers would be a big bonus
* they want it to be visual and audible
* bonus is to have it easily modifiable
* support 4 languages

I don't have much knowledge of Flash and would rather avoid using it as a solution. I started breaking down the problem into segments that I will need to examine, they are as follows:

* ability to read the game flow from a file that they can produce (xml, etc.)
* db design to store decision tree
* language challenge
* browser compatibility

I am leaning towards an Google app engine/GWT solution but I am not sure what technology is best for this.

I am really hoping to get your opinion/recommendation on my approach and on what technology is best. A special thanks (and beer if you live in Toronto) will be awarded to anyone who can help give me a ballpark estimate on how much such a game should go for. I know it's tough to estimate but any rough figure will help (how much would you charge for building something like playspent.org?)

Thanks in advance

# Answer
> 6 votes
Decision trees have (IMO) very little (if nothing) to do with the platform - it's completely separate from presentation.

Instead, it's a programming thing.

You setup a data structure that represents the tree, and write code to modify the state of game entities. Then (and only then) does other code decide how to display the state of those entities.

Consider that decision trees are present in games from text-only telnet/ssh interactions, all the way up to complex MMO environments.

In fact that is one way to imagine how to develop such a thing. Imagine your game only had text to display, and you wanted to implement decision trees. Imagine how you would write that, and then consider how it would be used with a game using visual graphics.

---
Tags: java, game-design, game-industry
---


# Question
Title: How can I keep track of a battle log on a web game?
Recently I started working on a Web turn-based PvP RPG game. Now I'm working on the battle system but I encountered some issues:

**How can I keep track of everything that happens in the battle?** It should keep track of the characters on the field, inventory, the damage done etc.

I first thought I would simply put it in the (MySQL) database, but I think it will be too much. Especially if several people are in a battle. I thought of puting this in sessions or cookies but I don't think thats reliable.

Does anyone have an idea how I can do this?

# Answer
> 6 votes
> I first thought I would simply put it in the (MySQL) database

Sounds good!

> but I think it will be too much.

Then you don't know the limits yet.

Seriously, just throw everything in a database. Don't care about performance too much at this stage, if it becomes an issue you can fix it later.

Here's an abstract view of what your database could look like:

```
Character
-- id (int, key)
-- name (string)
-- health (int)

InventoryItem
-- id (int, key)
-- character_id (int)
-- name (string)

Battle
-- id (int, key)
-- name (string)
-- location_id (int)

BattleParticipants
-- id (int, key)
-- battle_id (int)
-- character_id (int)

```

This employs something called database normalization, where each unique piece of data is stored once and only once.

Now, if you want to get the names of the participants in a battle, you can use an inner join to combine the data tables. This should explain that:

http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-joins.html

---
Tags: javascript, rpg, databases, php, online
---


# Question
Title: Best way to handle realtime melee AI in authoritative network environment
So i've been working on a multiplayer game for a bit; it's a co-op action RPG with real-time combat. If you've seen or played TERA, I'd say it's comparable to that, but not an MMO, heh. I'm currently handling the AI units authoritatively, the server calculates their pathing, movement, and pursue/attack logic, and syncs the movement to the clients 15x per second, and the state changes when they happen.

When I emulate 200ms ping, though, the client can perceive being out of range to an AI's attack, but still take the hit, because on the server he hadn't moved that far yet. This also plays hell with my real-time blocking.

I don't really want to allow the clients to be allowed to say "that was out of range" or "I blocked that", but I'm not really sure how else to handle it.

# Answer
> 2 votes
I can't really give a good answer (no experience in this particular field), but merely a line-of-thought that could inspire you:

Why should the AI be able to "instantly" hit the player within the server, while the player's attempt to block and attack must be sent over a 200ms asynchronous message-delay?

Maybe you could let the AI also queue messages asynchronously to itself (or other parts of your system) and use the same path of code that is used when the Player sends in some "I attack the AI-player" message?

Unquestionable, this makes the AI code more complex, as you can't be sure anymore whether your attempt to damage the player will work right now - instead you have to attack the player when he "might be a target in 200ms". But it seems like a "natural solution" to the problem to me.

(Again disclaimer: I haven't been in your shoes yet, so this might be utterly stupid and complicated ;))

# Answer
> 0 votes
Authoritative clients are a problem even when trust is strangely not an issue, like you imply in your question. And they are a problem just because of de-sync issues like those you are facing.

You can't split authoritativeness about related things between disagreeing processes: you need to have a single machine decide the real position of all entities and determine collision detection, and all other machines can at most "predict" it for display reasons.

# Answer
> 0 votes
Instead of having only the server calculating the movement, it might be better to have both the server **and** the client do this independently. The player sees the AI movements as soon as they happen (or delayed by a small amount to simulate the current average network latency), and can react accordingly. Hit and block animations are shown based on the clients calculations. The server then verifies the client's results against his own, and corrects movements and scoring if neccessary. These corrections are then integrated back into the client's AI movements instead of just overriding them to minimize jerkiness.

This can be seen as the client predicting the state of the AI or even the whole game world, only to be corrected by the server should discrepancies arise.

The multiplayer in Halo 2 was realized in this way.

---
Tags: networking, multiplayer
---


title: Continuous integration: Do I need it?

text:
# Question
Title: Continuous integration: Do I need it?
Does it make a sense to use a build server in small (2-3 developer) game development team? I like the idea of continuous integration, and the team members are not in the same place, so it might not be a bad idea.

# Answer
The main benefits of CI are:

* Constantly checking if the code is broken
* Making an "official" build which ships to the customer.
* Running the tests after you make a build and passing the build if all tests pass

I just completed a small game in a one-month cycle that shipped. We didn't use CI; even if we did, we would not have needed those above two benefits because:

* Our code-base was interpreted (Ruby) code
* We coordinated and integrated often
* We didn't have automated tests.

Your situation may vary. If you don't need any or all of these benefits, it's not worth the additional overhead to:

* Setup the CI machine
* Maintain it when things go bad
* Figure out why things work locally but not on the CI machine.
> 4 votes

# Answer
It makes sense to use whatever tool gives you more benefit than it costs to use.

In the small team I am working in, one person suggested that we have a CI server, but upon discussing it, it seemed that it would take a significant degree of effort to get it working with the tools we use. In our situation, we couldn't spare that amount of time so we chose not to use one.

The best answer for you will depend on how quickly you can set one up, and how much benefit you think you'd get from it. Personally I think most of these systems are only worthwhile for big projects with large numbers of developers, but you may think differently, based on your own experiences and on how much benefit you expect to see compared to the difficulty of setting it up and maintaining it.
> 1 votes

---
Tags: server
---


# Question
Title: RevoluteJoint Stop Rotating when Some Physics Body Collide in Andengine + Box2d?
I am making a Game from andengine + box2d in Which i am using RevoluteJoint in that case i am facing some problem that when physics body or Sprite Collide with this Revolute joint body then Revolute body stop rotating then after some time it start rotating I am using below code for this :

```
     this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(movingFace, movingBody, true, true));

         final RevoluteJointDef revoluteJointDef = new RevoluteJointDef();
         revoluteJointDef.initialize(anchorBody, movingBody, anchorBody.getWorldCenter());
         revoluteJointDef.enableMotor = true;
         revoluteJointDef.motorSpeed = 100;
         revoluteJointDef.maxMotorTorque = 200;

         this.mPhysicsWorld.createJoint(revoluteJointDef);

```

**EDIT** Here is a screenshot:

# Answer
> 3 votes
What is happening is that when the triangle hits an object the torque required for the motor to continue exceeds the `maxMotorTorque` you have set, this effectively stops the motor dead for a while.

The solution is to increase `maxMotorTorque` high enough so that the motor continues even on collision for your specific game.

Quote from Box2D manual about the joint motor:

> A joint motor allows you to specify the joint speed (the time derivative of the angle). The speed can be negative or positive. A motor can have infinite force, but this is usually not desirable. Recall the eternal question:
>
> "What happens when an irresistible force meets an immovable object?"
>
> I can tell you it's not pretty. So you can provide a maximum torque for the joint motor. The joint motor will maintain the specified speed unless the required torque exceeds the specified maximum. When the maximum torque is exceeded, the joint will slow down and can even reverse.

---
Tags: game-design, box2d, andengine
---


title: Vector reflect problem

text:
# Question
Title: Vector reflect problem
I'm testing some vector reflection and I want to check what happens when a ball collides with a paddle.

So if I have:

```
Vector2 velocity = new Vector2(-5, 2);
position_ball += velocity;

if (position_ball.X < 10)
{
    Vector2 v = new Vector2(1,0); // or Vector2.UnitX
    velocity = Vector2.Reflect(velocity, v);
}

```

then, correctly, velocity is (5,2) after `Reflect`, but if I do:

```
if (position_ball.X < 10)
{
  Vector2 v = new Vector2(1,1);
  velocity = Vector2.Reflect(velocity, v);
}

```

then velocity is (1,8) and not (5, -2) that is the solution of reflection equation R = V - 2 * (V . N)

Why is that?

# Answer
The reflection equation is `R = V - 2 * (V . N) * N` This formula also assumes that N is a normal vector, which it isn't in your case `new Vector2(1,1).Length() == 1.414...`

Try this instead:

```
if (position_ball.X < 10)
{
  Vector2 v = new Vector2(1,1);
  v.Normalize();
  velocity = Vector2.Reflect(velocity, v);
}

```

The reflection of \[-5,2\] will actually be \[-2,5\] (or \[1,8\] if not normalized) and not \[5,-2\] as you assumed:

```
R = V - 2 * (V.N) * N
N = [1,1] * 2^-0.5
V = [-5,2]

```

Since Nx = Ny in this particular case we can refer to either of them as Nc

```
R = V - 2 * (v.N) * N
  = V - 2 * (Vx*Nc + Vy*Nc) * N
  = V - 2*Nc(Vx+Vy) * N
  = V - 2*Nc(-5+2) * N
  = V - 2*Nc(-3) * N
  = V + 6*Nc * N
  = V + [6*Nx*Nx, 6*Ny*Ny]
  = V + [6*Nx^2, 6*Ny^2]
  = [6*Nx^2-5, 6*Ny^2+2]
  = [6*(2^-1)-5, 6*(2^-1)+2]
  = [-2, 5]

```

`(N^a)^b = N^(a*b)` which is used in the above proof `(2^-0.5)^2 = 2^-1`
> 6 votes

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


# Question
Title: Cocos2D: Change animation based on joystick direction
I'm trying to get my figure to look in the right directions, based on the input of the joystick. So if I tilt left it looks left and the left animation is used, if I used right, it looks right and right animation is used, if up, then up, down, down and so on. I just get animation for front and back. Also if I press up I see the back of the figure correctly, but it won't go back into the original state when I don't press up anymore.

```
-(void)applyJoystick:(SneakyJoystick *)aJoystick forTimeDelta:(float)
deltaTime {
    CGPoint scaledVelocity = ccpMult(aJoystick.velocity, 128.0f);
    CGPoint oldPosition = [self position];
    CGPoint newPosition =
    ccp(oldPosition.x + scaledVelocity.x * deltaTime,
    oldPosition.y + scaledVelocity.y * deltaTime);
    [self setPosition:newPosition];
    id action = nil;
   int extra = 50;
if ((int) aJoystick.degrees > 180 - extra && aJoystick.degrees < 180 + extra) {
action = [CCAnimate actionWithAnimation:walkingAnimLeft restoreOriginalFrame:NO];

} else if ((int) aJoystick.degrees > 360 - extra && aJoystick.degrees < 360 + extra) {
    action = [CCAnimate actionWithAnimation:walkingAnimRight restoreOriginalFrame:NO];
}

else if ((int) aJoystick.degrees > 90 - extra && aJoystick.degrees < 90 + extra) {
    action = [CCAnimate actionWithAnimation:walkingAnimBack restoreOriginalFrame:NO];

}
 else if ((int) aJoystick.degrees > 270 - extra && aJoystick.degrees < 270 + extra) {
action = [CCAnimate actionWithAnimation:walkingAnimFront restoreOriginalFrame:NO];
}

if (action != nil) {
[self runAction:action];
        }
    }
}

```

# Answer
> 0 votes
My approach was more or less the right one. But the direction cue had to go somewhere completely different, and also had to be changed a little. It is now in

```
-(void)updateStateWithDeltaTime:(ccTime)deltaTime
andListOfGameObjects:(CCArray*)listOfGameObjects {
 if (joystick.degrees > 60 && joystick.degrees < 120) {
        if (self.characterState != kStateWalkingBack)
            [self changeState:kStateWalkingBack];

    } else if (joystick.degrees > 211 && joystick.degrees < 300) {
        if (self.characterState != kStateWalkingFront)
            [self changeState:kStateWalkingFront];

    } else if (joystick.degrees > 301 && joystick.degrees < 360){
    if (self.characterState != kStateWalkingRight)
            [self changeState:kStateWalkingRight];

    } else if (joystick.degrees > 121 && joystick.degrees < 210) {
        if (self.characterState != kStateWalkingLeft)
            [self changeState:kStateWalkingLeft];
    }
        [self applyJoystick:joystick
               forTimeDelta:deltaTime];
    }
}

```

If someone has further questions about this, don't hesitate to ask :)

---
Tags: cocos2d, joystick
---


# Question
Title: Is there a way to export all the images of my tweening effect in Flash?
i'm using Flash to create the animation of my character in 2D (i'm just beginning). Is it possible to make a tween effect of a character, and then **automatically export all the images/frames**?

So far, it's a bit fastidious : i create my tweening effect, then i put a keyframe for each frame i want to copy and paste, then i select the movieclips and shapes and copy and paste them into another flash document, i position those clips at the exact same location as the previous image, then i erase the previous image and export the image... For 30 frames! Is there any faster way?

Thanks

# Answer
Take a look at the Grapefrukt Exporter library.
> 2 votes

---
Tags: 2d, flash, image, tweening
---


# Question
Title: Extremely simple online multiplayer game
I am considering creating a simple multiplayer game, which focuses on physics and can accommodate up to 30 players per session. Very simple graphics, but smart physics (pushing, weight and gravity, balance) is required. After some research I found a good java script (framework ??) called box2d.js I found the demo to be excellent. this is is kind of physics am looking for in my game. Now, what other frameworks will I need? Node.js?? Prototype.js?? (btw, I found the latest versoin of protoype.js to be released in 2010...?? is this still supported? Should I avoid using it?) What bout HTML 5 and Canvas? would I need them? websockets?

Am a beginner in web programming + game programming world. but I will learn fast, am computer science graduate. (but no much web expeience but know essentionals javascript, html, css..). I just need a guiding path to build my game. Thanks

# Answer
> 4 votes
Stop thinking in terms of frameworks and start thinking about what you want your *game* to do.

Does slapping a sticker on the box (okay, website) that says "Runs on Node.js!" or "Built for Box2D!" help sell more copies? Nope. Most users won't know and won't care.

You rattle off a lot of technologies, but it seems to me you're just excited to be building a game. You don't have a plan yet. Start with that.

Start simple. First, estimate how long it will take you to build a game like Tetris in JavaScript. 30 minutes? Longer? Write it down.

Build your simple Tetris clone. Ask questions if you get stuck. Now look at your estimate again. How off were you? By what margin?

You can now go either way:

* Keep building increasingly complex games, until you end up with a game that feels your own. (programmer)
* Keep expanding upon your simple game's design, how you can tweak it until it's the best Tetris ever. (designer)

As for your actual question: Box2D is a very good physics framework, but it's going to be impossible to get clients to sync up if you don't know anything about physics, networking or game programming in general.

---
Tags: javascript, multiplayer, mmo, node.js
---


# Question
Title: How can I select an audio output device in directshow
I was wondering how I can select the output device for audio in directshow. I am able to get available audio output devices in directshow. But how can I make one of these to be audio output device. Its always going for the default audio device. I want to be able to output audio on my choice of device. I have been struggling through google but couldn't find anything useful. All I could get was this link but it doesn't really solve my problem.

Any help will be really helpful for me.

# Answer
> 1 votes
I've not tried it, but a quick MSDN browsing makes me think you could try that:

1. Enumerate the available devices using an `IMMDeviceEnumerator`, and let your user pick one. You should have a look at this MSDN page for a head start.
2. Use the `GUID` of the selected device for your call to `DirectSoundCreate`. Reference here.

# Answer
> 1 votes
I may be misunderstanding what you are trying to do but I'm guessing you want to do something like change the output device from speakers to headphones or something? I don't believe that you can change the output device via code and I think that is something that can only be changed in the playback devices in the windows sound and volume control.

---
Tags: audio
---


# Question
Title: Corona SDK: Animation takes a long time to play after "prepare" step
First off, I'm using the current publicly available build, version 2011.704

I'm building a platformer, and have a character that runs along and jumps when the screen is tapped. While jumping, the animation code has him assume a svelte jumping pose, and upon the detection of a collision with the ground, he returns to running. All of this happens.

The problem is that there is this strange gap of time, about 1/2 a second by the feel of it, where my character sits on the first frame of the run animation after landing, before it actually starts playing. This leads me to believe that the problem is somewhere between the "prepare" step of loading up a sprite set's animation sequence and the "play" step. Thanks in advance for any help :).

My code for when my character lands is as follows:

```
local function collisionHandler ( event )
    if (event.object1.myName == "character") and (event.object2.type == "terrain") then
        inAir = false
        characterInstance:prepare( "run" ) -- TODO: time between prepare and play is curiously long...
        characterInstance:play()
    end
end

```

# Answer
> 1 votes
Aha! Figured it out! The problem has to do with the collision event being thrown multiple times as things balance out physics wise (as it should be). My collision handler being what it was, the "prepare" step would keep getting called, setting the animation to the first frame, until the collision events stopped firing.

My fix was to write a little state machine for the character that guards against resetting the state if the program requests a state that is already active, thus preventing the animation from continuously being set to the first frame.

It looks like this:

```
characterInstance.stateMachine = {
    currentState = "State not set",
    ["set"] = function ( newState )
                        if characterInstance.stateMachine.currentState ~= newState then
                            characterInstance.stateMachine[newState]()
                        end
                    end,
    ["running"] = function ()
                        characterInstance:prepare( "run" )
                        characterInstance:play()
                        characterInstance.stateMachine.currentState = "running"
                    end,
    ["jumping"] = function ()
                        characterInstance:prepare( "jump" )
                        characterInstance:play()
                        characterInstance.stateMachine.currentState = "jumping"
                    end,
    ["attacking"] = function ()
                        characterInstance:prepare( "attack" )
                        characterInstance:play()
                        characterInstance.stateMachine.currentState = "attacking"
                    end
}

```

An example of setting the state: `characterInstance.stateMachine["set"]( "jumping" )`

---
Tags: iphone, animation, corona-sdk
---


title: Simple 2D Flight Physics with Box2D

text:
# Question
Title: Simple 2D Flight Physics with Box2D
I'm trying to build a simple side scroller with an airplane being the player. As such, I want to build simple flight controls with simple but realistic-feeling physics. I'm making use of cocos2D and Box2D. I have a basic system working, but just can't get the physics feeling correct.

I am applying force to the plane (which is a `b2CircleShape`) based on the user's input. So, basically, if the user pushes up, `body_->ApplyForce(b2Vec2(10,30), body_->GetPosition())` is called. Similarly, for down -30 is used.

This works and the plane flys along with up/down causing it to dive or climb. But it just doesn't feel right. There is no slowdown on climbs, nor speed up during dives. My simple solution is far to simple.

How can I get a better feel for a plane climbing/diving?

Thanks!

# Answer
**Iterative empirical testing**. Add some test sliders to your GUI that control the force applied for the upward and downward directions.

Other than that, consider changing the way force is applied. Add gravity into the mix, when the plane is horizontal its lift offsets gravity. The lift decreases with change in pitch. Your force is always forward, when pointing down it's in addition to gravity, when you're pointing up gravity is subtracted from the force.

Basically, think about how to make it more realistic if you want it to feel more realistic.
> 2 votes

# Answer
**Tilt the nose when up/down forces are applied**, and cause the plane to rise or fall more the farther the nose tilts. So the longer you hold the key, the faster the plane rises or falls. Cap it, though, to avoid nosedives.

This should be a tradeoff with airspeed, with forward airspeed decreasing as the plane's nose moves away from a horizontal position. You may want to apply this only to upwards turns so that going down doesn't increase your airspeed.
> 0 votes

---
Tags: physics, box2d, cocos2d-iphone
---


# Question
Title: Creating a good looking interface for a Java CCG?
I would like to create a Java collectible card game. I have the logic down pat, but I am having some trouble with the interface. I would like to make it look nice. Rather than using the standard java SWING components, I would like to create something like this. What is necessary to create something like that?

# Answer
> 2 votes
**Time and artistic skills**. No way around that. You can however, make it a little easier. You can use a library specifically designed for implementing GUIs.

Without knowing what you're using to render your game, I can only assume you haven't done any graphics yet. Nifty GUI is one that comes to mind that is almost library agnostic. It uses OpenGL and Java but it works with more OpenGL libraries than most other GUI libraries, including: jme, jogl2, lwjgl and it's own custom renderer.

---
Tags: java, interface
---


# Question
Title: Why should I consider using the Source Engine?
I've always been a Valve fan, but now that I have the opportuninty to choose a game engine for a project I'm not sure I want to choose the Source Engine after watching this wikipedia entry. My options essentially boiled down to an open source stack (Horde3D + Zoidcom + Spark + SFML + CEGUI, and well, not OSS but PhysX too), UDK and the Source Engine.

My question is (because I really have no experience with it) what would be the **technical reasons** (not license or other) for any developer to choose the Source Engine over any other open source or commercial option ?, is the Source Engine really worth it as a game development tool or has it time already passed and it is obsolete against other solutions?.

Thanks

---

Edit: Precised my question a little more , I'm looking for technical reasons to choose the Source Engine.

# Answer
> 5 votes
Well, by far and away your biggest question should be: is my game going to be commercial? If so, then you will have to obtain a Source engine license, which is going to be (in most cases) substantially more costly than other engines, especially options like Unity. From the jist of your post I assume you aren't going to be commercial, though.

If your game is not going to be commercial, you can use the Source engine for free, but then you will have limited access to the engine and be at the mercy of the SDK tools. Valve has not done a great job (I am putting this lightly) at maintaining the SDK lately and the tools remain in a near-broken state.

Personally, speaking as someone who has worked on multiple Source SDK mods since 2005, I would stay as far away from source as possible. The tools are simply far too outdated and unkempt at this point. They have literally gotten worse as time has passed; for example the demo smoother tool (used to edit the camera movement in a demo to get good footage for movies such as trailers), has actually become harder to use from the Episode 1 SDK to the Orange Box SDK. It has more bugs and more crashes. The other tools can have the same said of them, OBSDK's Hammer (the level editing tool) now has multiple render bugs that did not exist in previous SDK versions, etc... it simply feels as if they do not care about their free tools anymore. It's a shame, as mods are a huge part of why Valve is what they are today. I do not know if their commercial tools fare the same (I would hope not!), but given what I have experienced with the free SDK there is no way I would ever consider purchasing/using the source engine for a commercial game.

As for other free engines, Ogre3D and Irrlicht are worth looking into as well. Also the Torque engine from Garage Games has just recently re-launched with a much lower price, $100 for their 3D engine, down from what used to be around $2000 iirc.

# Answer
> 2 votes
There are a handful of things the source engine gets you.

1. It "just works". None of this trying to ham fist tech together like in your OSS solution.
2. Lots of tech focused on realistic humans. Ragdolls are good, IK (for proper foot placement) is good. Pathfinding is there (I think). Physics is pretty polished. And you get their facial animation tool which lets you do passable cinematics in-game along with gestures (partial additive animations). NPCs have things like "interest points" that they'll occasionally look at when wandering about, or event-based reactions to things (for example, saying something if you throw a physics object at them or if you're at low health).
3. It's not Unreal. You're working in C++ as a programmer instead of UnrealScript.

But there are some problems with it.

1. I don't think they've solved the lighting for dynamic objects (last I checked dynamic objects were vertex lit using a single sample point at the origin), meaning that it can clash pretty bad with the nice-looking lightmapped static environment.
2. Not as modern occlusion solutions. Unless they've changed it since I've used it, you still have to do Quake-3-style manual portal placement and sometimes hint brushes. Hope you like making most of your level out of brushes.
3. It's not Unreal. The artists' tools aren't going to be as polished. Techniques learned here probably aren't as useful to the job market as a whole as more studios use Unreal.

# Answer
> 2 votes
The Source Engine is an interesting toolset. It is not for everyone. Mostly it is for the mod crowd, and for those that wish to make a commercially released game. The interface hasn't changed much in years. That could be looked at as a good or a bad thing, depending on the user. Compared to UDK, it is a breath of fresh air. It is half way between UDK, CryEngine, and Unity. UDK has a convoluted import process that is un-necessarily complicated. If you don't want to deal with programming in Unity, you have to purchase quite a few plugins to get to the level of a AAA quality game. Source is not as dependant on programming. CryEngine has a propietary format, and currently only provides support for Maya, and 3DS Max. If you do not use those packages, you will hit a brick wall in your development. To see what progress has been made with this issue visit http://www.crydev.net/newspage.php?news=89611

For all of you that want an all inclusive package that does it all, Source is a viable alternative. Source doesn't have those strange import issues. There are tools for artificial intelligence, spawn points, hurt zones, heads up display creation, skyboxes with parallax effects, audio zones, ragdoll physics, vehicle physics, rope effects, cloth dynamics, facial animation, body animation, particles, and destructible objects. Source is also compatible with many 3D content applications, not just the most popular packages.

A powerful combination is the Source Engine, and Blender. Blender can be downloaded at http://www.blender.org/download/get-blender/

# Answer
> -2 votes
The source engine is more a professionnal engine, I would recommend to use it if you have a project within a company, but if you are doing something "through" the help of internet, my answer is that you can't beat open source: its use is more widespread and their usage is more commonly "standard" in its design, while professionnal engines usually have been made with a goal in mind, which were half life 2 and all other mods alike, and thus, those requirements with their deadlines made it more difficult to use, even if the result is awesome.

It really depends how do you work and what do you want to do; I'm not much experience, but as I see it, even an indie would use open source rather than pro engines.

Open source softwares always have to shine in ease of use, whatever is the result, because that's the only thing that makes a software better than another: OSS and internet are brothers for life, but they can't beat the voodoo magics of proprietary top-notch last-generation software.

---
Tags: source-engine
---


title: Small adventure game

text:
# Question
Title: Small adventure game
I'm making a small adventure game where the player can walk through Dungeons and meet scary characters:

The whole thing is 20 java classes and I'm making this a standalone frame while it could very well be an applet I don't want to make another applet since I might want to recode this in C/C++ if the game or game engine turns out a success. The engine is the most interesting part of the game, it controls players and computer-controlled characters such as Zombies, Reptile Warriors, Trolls, Necromancers, and other Persons. These persons can sleep or walk around in the game and also pick up and move things. I didn't add many things so I suppose that is the next thing to do is to add things that can get used now that I already added many different types of walking persons.

What do you think I should add and do with things in the game? The things I have so far is:

```
package adventure;
/**
 * The data type for things. Subclasses will be create that takes part of the story
*/
public class Thing {

    /**
     * The name of the Thing.
     */
  public String name;

    /**
     * @param name The name of the Thing.
     */
  Thing( String name ) {
    this.name = name;
  }

}

public class Scroll extends Thing
{
  Scroll (String name)
  {
    super(name);
  }
}

class Key extends Thing
{
  Key (String name)
  {
    super(name);
  }
}

```

The key is the way to win the game if you figure our that you should give it to a certain person and the scroll can protect you from necromancers and trolls. If I make this game more Dungeons and Dragons-inspired, do you think will be any good? Any other ideas that you think I could use here?

The Threadwhich steps time forward and wakes up persons is called simulation. Do you think I could do something more advanced with this class?

```
package adventure;
class Simulation extends Thread
{

  private PriorityQueue Eventqueue;

  Simulation()
  {
    Eventqueue = new PriorityQueue();
    start();
  }

  public void wakeMeAfter(Wakeable SleepingObject, double time)
  {
    Eventqueue.enqueue(SleepingObject, System.currentTimeMillis()+time);
  }

  public void run()
  {
    while(true)
    {
      try
      {
    sleep(5); //Sov i en halv sekund

    if (Eventqueue.getFirstTime() <= System.currentTimeMillis())
    {
      ((Wakeable)Eventqueue.getFirst()).wakeup();
      Eventqueue.dequeue();
    }

      }
      catch (InterruptedException e )
    {

    }

    }
  }

}

```

And here is the class that makes up the actual world:

```
package adventure;
import java.awt.*;
import java.net.URL;
/**
 * Subklass to World that builds up the Dungeon World.
 */

public class DungeonWorld extends World {

    /**
     *
     * @param a Reference to adventure game.
     *
     */
  public DungeonWorld(Adventure a) {
    super ( a );

    // Create all places
    createPlace( "Himlen" );
    createPlace( "Stairs3" );
    createPlace( "IPLab" );
    createPlace( "Dungeon3" );
    createPlace( "Stairs5" );
    createPlace( "C2M2" );
    createPlace( "SANS" );
    createPlace( "Macsal" );
    createPlace( "Stairs4" );
    createPlace( "Dungeon2" );
    createPlace( "Datorsalen" );
    createPlace( "Dungeon");//, "Ljushallen.gif" );
    createPlace( "Cola-automaten", "ColaAutomat.gif" );
    createPlace( "Stairs2" );
    createPlace( "Fable1" );
    createPlace( "Dungeon1" );
    createPlace( "Kulverten" );

    // Create all connections between places
    connect( "Stairs3", "Stairs5", "Down", "Up" );
    connect( "Dungeon3", "SANS", "Down", "Up" );
    connect( "Dungeon3", "IPLab", "West", "East" );
    connect( "IPLab", "Stairs3", "West", "East" );
    connect( "Stairs5", "Stairs4", "Down", "Up" );
    connect( "Macsal", "Stairs5", "South", "Norr" );
    connect( "C2M2", "Stairs5", "West", "East" );
    connect( "SANS", "C2M2", "West", "East" );
    connect( "Stairs4", "Dungeon", "Down", "Up" );
    connect( "Datorsalen", "Stairs4", "South", "Noth" );
    connect( "Dungeon2", "Stairs4", "West", "East" );
    connect( "Dungeon", "Stairs2", "Down", "Up" );
    connect( "Dungeon", "Cola-automaten", "South", "North" );
    connect( "Stairs2", "Kulverten", "Down", "Up" );
    connect( "Stairs2", "Fable1", "East", "West" );
    connect( "Fable1", "Dungeon1", "South", "North" );

    // Add things

    // --- Add new things here ---

    getPlace("Cola-automaten").addThing(new CocaCola("Ljummen cola"));
    getPlace("Cola-automaten").addThing(new CocaCola("Avslagen Cola"));
    getPlace("Cola-automaten").addThing(new CocaCola("Iskall Cola"));
    getPlace("Cola-automaten").addThing(new CocaCola("Cola Light"));
    getPlace("Cola-automaten").addThing(new CocaCola("Cuba Cola"));

    getPlace("Stairs4").addThing(new Scroll("Scroll"));
    getPlace("Dungeon3").addThing(new Key("Key"));
    Simulation sim = new Simulation();

    // Load images to be used as appearance-parameter for persons
    Image studAppearance = owner.loadPicture( "Person.gif" );
    Image asseAppearance = owner.loadPicture( "Asse.gif" );
    Image trollAppearance = owner.loadPicture( "Loke.gif" );
    Image necromancerAppearance = owner.loadPicture( "Necromancer.gif" );
    Image skeletonAppearance = owner.loadPicture( "Reptilewarrior.gif" );
    Image reptileAppearance = owner.loadPicture( "Skeleton.gif" );
    Image zombieAppearance = owner.loadPicture( "Zombie.gif" );
    // --- Add new persons here ---
    new WalkingPerson(sim, this, "Peter", studAppearance);
    new WalkingPerson(sim, this, "Zombie", zombieAppearance );
    new WalkingPerson(sim, this, "Zombie", zombieAppearance );
    new WalkingPerson(sim, this, "Skeleton", skeletonAppearance );
    new WalkingPerson(sim, this, "John", studAppearance );
    new WalkingPerson(sim, this, "Skeleton", skeletonAppearance );
    new WalkingPerson(sim, this, "Skeleton", skeletonAppearance );
    new WalkingPerson(sim, this, "Skeleton", skeletonAppearance );
    new WalkingPerson(sim, this, "Sean", studAppearance );
    new WalkingPerson(sim, this, "Reptile", reptileAppearance );

    new LabAssistant(sim, this, "Kate", asseAppearance);
    new LabAssistant(sim, this, "Jenna", asseAppearance);

    new Troll(sim, this, "Troll", trollAppearance);

    new Necromancer(sim, this, "Necromancer", necromancerAppearance);

  }

    /**
     *
     * The place where persons are placed by default
     *
     *@return The default place.
     *
     */
  public Place defaultPlace() {
    return getPlace( "Datorsalen" );
  }

  private void connect( String p1, String p2, String door1, String door2) {
    Place place1 = getPlace( p1 );
    Place place2 = getPlace( p2 );

    place1.addExit( door1, place2 );
    place2.addExit( door2, place1 );
  }

}

```

Thanks

# Answer
> 12 votes
I noticed that English isn't your first language. That's okay, it's my second language too. ;)

What I would advise is to keep everything about your game in English.

1. It's easier to port English to Danish than in reverse.
2. Somebody else can extend your code if she knows English.
3. You can outsource translations and resource creation to somebody else (who may or may not speak Danish)
4. It helps when you're asking questions on StackExchange if you don't have to mix native terms with English terms.

You've said that you might want to rebuild it in C++ later. What I think is stopping you from doing that right now is that your *data* is coupled with your *code*.

Your data is the most important thing about your game. It can be roughly defined as:

* Your sprites.
* Your object properties.
* Your rooms.
* Your map that connects the rooms.

Take a look at data-driven programming. This is a way to define your data outside of your code, so you can write any number of implementations for it.

So, instead of saying this:

```
connect( "Stairs3", "Stairs5", "Down", "Up" );
connect( "Dungeon3", "SANS", "Down", "Up" );
connect( "Dungeon3", "IPLab", "West", "East" );

```

Why not have a datafile that looks sort of like this:

```
[Stairs3] VERTICAL [Stairs5]
[Dungeon3] VERTICAL [SANS]
[Dungeon3] HORIZONTAL [IPLab]

```

As for your objects:

```
<Dispenser name="Cola-automaten">
    <Item type="Cola">Avslagen Cola</Item>
    <Item type="Cola">Iskall Cola</Item>
    <Item type="Cola">Cola Light</Item>
    <Item type="Cola">Cuba Cola</Item>
</Dispenser>

```

Now you can parse this XML and turn it into the Java code you have right now. With a distinct advantage: you can add a new type of cola without changing a single line of code!

Ultimately, your game is nothing more than a state machine for your data. And if your data is decoupled from your game code, then you can write any number of implementations in any number of languages you want.

Finally, let me close with a practical example: Angry Birds is available for iPhone, Android, BlackBerry *and* Google Chrome. How do they do that? Well, they take their datafiles (sprites, physics settings, level design) and write a game implementation for each platform. This is expensive in terms of time and money, but it works quite well for them.

---
Tags: java, 2d, adventure-games
---


title: OpenGL Tessellation makes point

text:
# Question
Title: OpenGL Tessellation makes point
A little problem with my tessellation shader. I try to implement a simple tessellation shader but it only makes points.

Here's my vertex shader :

```
out vec4 ecPosition;
out vec3 ecNormal;
void main( void )
{
    vec4 position = gl_Vertex;

    gl_Position = gl_ModelViewProjectionMatrix * position;
    ecPosition  = gl_ModelViewMatrix * position;
    ecNormal    = normalize(gl_NormalMatrix * gl_Normal);
}

```

My tessellation control shader :

```
layout(vertices = 3) out;
out vec4 ecPosition3[];
in vec3 ecNormal[];
in vec4 ecPosition[];
out vec3 myNormal[];
void main()
{
    gl_out[gl_InvocationID].gl_Position =  gl_in[gl_InvocationID].gl_Position;
    myNormal[gl_InvocationID] = ecNormal[gl_InvocationID];
    ecPosition3[gl_InvocationID] = ecPosition[gl_InvocationID];
    gl_TessLevelOuter[0] = float(4.0);
    gl_TessLevelOuter[1] = float(4.0);
    gl_TessLevelOuter[2] = float(4.0);
    gl_TessLevelInner[0] = float(4.0);
}

```

And my Tessellation Evaluation shader:

```
layout(triangles, equal_spacing, ccw) in;
in vec3 myNormal[];
in vec4 ecPosition3[];
out vec3 ecNormal;
out vec4 ecPosition;

void main()
{
    float u = gl_TessCoord.x;
    float v = gl_TessCoord.y;
    float w = gl_TessCoord.z;
    vec3 position = vec4(gl_in[0].gl_Position.xyz * u +
                 gl_in[1].gl_Position.xyz * v +
                 gl_in[2].gl_Position.xyz * w );
    vec3 position2 = vec4(ecPosition3[0].xyz * u +
                  ecPosition3[1].xyz * v +
                  ecPosition3[2].xyz * w );
    vec3 normal = myNormal[0] * u +
              myNormal[1] * v +
              myNormal[2] * w );
    ecNormal = normal;
    gl_Position = vec4(position, 1.0);
    ecPosition = vec4(position2, 1.0);
}

```

A screenshot:

# Answer
You're only emitting one vertex. ;)

Here's how you should rewrite your geometry shader:

```
layout(vertices = 3) out;
out vec4 ecPosition3[];
in vec3 ecNormal[];
in vec4 ecPosition[];
out vec3 myNormal[];
void main()
{
    for (int p = 0; p < gl_in.length(); p++)
    {
        gl_Position =  gl_in[p].gl_Position;
        myNormal = ecNormal[p];
        ecPosition3 = ecPosition[p];
        gl_TessLevelOuter[0] = float(4.0);
        gl_TessLevelOuter[1] = float(4.0);
        gl_TessLevelOuter[2] = float(4.0);
        gl_TessLevelInner[0] = float(4.0);

        EmitVertex();
    }

    EndPrimitive();
}

```

Note: this may still not be exactly what you want, but at least you'll be getting triangles as output.
> 1 votes

---
Tags: opengl, shaders, glsl, tessellation
---


# Question
Title: Storing and sending English word list using trie data structure
I was planning on making a word based game something like Scramble or Boggle. I searched on the internet and found that one of the best way to store the Word List is by using a trie.

**My question**: Is there a way I can pre-make and populate a trie data structure and send it to the user rather than sending him the whole word list and then creating the trie data structure at run-time?

# Answer
You could create and serialize the trie offline, then push/pull the resulting string to/from the client for unserialization.

There is probably no need to roll your own code for (un)serialization. I don't have a lot of experience with modern Flash and ActionScript, but this seems to be a way to do it: http://en.wikipedia.org/wiki/Action\_Message\_Format
> 3 votes

# Answer
The best way to store a dictionary like the one you have in mind is with a red-black tree.

It has an unfortunate downside though, it is incredibly complex to comprehend and implement. Luckily somebody has already done the leg-work for you: link

As to how you want to send this dictionary to the players, well that depends.

* Does it have to be quick to transfer?
* Does it have to be secure?
* Do the users get to make changes?
* What happens when a word isn't in the dictionary?

My suggestion would be: make a textfile for your dictionary and send it to each player when the game starts. Later on you can make it faster by compressing it to a binary format and more secure by encrypting it with a certificate.

**EDIT:**

Here's an example of a binary file:

```
0x54 0x52 0x45 0x45 0x02
0x00 0x48 0x65 0x6C 0x6C
0x6F 0x00 0x01 0x41 0x70
0x70 0x6C 0x65 0x00

```

That looks like garbage, doesn't it? Now, let's look at it in a hex editor:

```
TREE.
.Hell
o..Ap
ple.

```

Still doesn't look like much, so let's break it down.

First, we have the header:

```
TREE - 0x54 0x52 0x45 0x45 0x02

```

A header is not required, but very much advised! It tells you about what type of file this is, what kind of data is in it and how much data it contains.

The `0x02` at the end there tells us this tree will contain 2 items.

Next, we get an index:

```
0x00 - index for dictionary item

```

This tells us item 0 is coming up.

```
Hello - 0x48 0x65 0x6C 0x6C 0x6F 0x00

```

This is our first dictionary item: "Hello". The `0x00` at the end tells us we've reached the end of this string.

Now we get another index:

```
 0x01

```

Item 1 is coming up!

```
 Apple - 0x41 0x70 0x70 0x6C 0x00

```

And now have our second item: "Apple". Now we can build a tree:

```
 Tree
 [0] = "Hello"
 [1] = "Apple"

```

Hope that helps!
> 1 votes

---
Tags: flash, data-structure
---


# Question
Title: Handling game states like Braid's timeshift or Shooter's Killcam
me as very unexperienced game developer, I wondered how I could achieve something like re-winding the time in my game or jump back to a special moment (killcam) and replay it for the user.

# Answer
> 3 votes
The only way you can achieve this is if your game is completely deterministic. In mathematical terms, that means that if you have the function:

```
y = x^2

```

Then you can always get a value for `x` if you have a value for `y`:

```
x = square_root(y)

```

For every time `t`, you must be able to generate a world state. If you have something like a bullet being fired from a gun, then you want to be able to rewind its position from impact back to when it left the barrel. There are two ways to achieve this:

* Record the position of the bullet every x frames. When replaying, interpolate between those frame positions.
* Have a function for bullet position that takes a time `t`. Have this function be completely deterministic and rewind it from `t1` (impact) to `t0` (departure). This is called integration in mathematics.

Now, this second method is obviously the best, but it's also the hardest. Because in a game, not everything can be broken down to functions:

* Players mash on keys and move with mouses.
* Networking delays can mean physics run at a different framerate.
* Some functions can not be integrated (see: N-body problem).

Most likely you'll end up with a combination of the two: integration for bullet position and interpolated recordings for player positions.

---
Tags: game-mechanics, state, time-travel
---