# Question
Title: iPhone/OpenGL-ES partially texture mapping an object
I only have a basic understanding of OpenGL, so I'm probably showing my ignorance here.

I'm looking for a great iPhone/OpenGL-ES example of applying a texture (preferably from a texture atlas, but not really a requirement) to specific parts of some arbitrary object/model.

I have a game where 3D tiles "flip" to reveal some other texture on the backside of the tile. I created the model in Blender and exported it to an Objective-C header. The tile isn't a simple "cube", but it is relatively cube-shaped. Everything works great when I use a single texture that simply wraps the entire model. But I'm struggling to figure out how I can restrict that texture to just specific parts of the model.

To complicate things even more, I ultimately want to texture it with three different images. The top will have "image x", the sides of the tile will have "image y", and the back will have "image z".

Thanks!

# Answer
> 4 votes
You're doomed.

The iPhone only has 2 multitexturing units, so you can't use 3 textures at the same time. This leaves you with the following options :

* Make a single texture with your 3 images on it. If the combination of textures is not a compile-time constant, either recompute the new texture each time you need it, or pre-compute every possibility.
* Split your cube into 3 meshes, display each independently with its own texture
* Hybrid approach : Split your cube in 2, first half with 1 texture, second half with multitexturing.

Hope this helps.

---
Tags: iphone, textures, opengl-es
---


# Question
Title: Is there any algorithm for creating 3D lightning?
Is there any algorithm for generating lightning?
Lets say, you input the starting and ending coordinates (x,y,z) and out comes an array of coordinates to show where the lightning goes.
It doesn't have to be scientifically accurate but as long it looks random and unpredictable

EDIT: I found this, but can't figure out how to put this in to C/++ code. There is a 2D example provided but I want 3D :O

EDIT2: The output might be something like this:

```
struct coord3 { int x, y, z; };

struct line
{
    unsigned char lumo;
    coord3 start;
    coord3 end;
};

line* lightning = new line[n]; // each element of the array would be a line that
                               // needs to be drawn for the lightning so the
                               // lightning can "fork" and can have different
                               // brightnesses

```

# Answer
> 2 votes
If you need a set begin and endpoint then you'll have to generate the points inbetween. Start by randomly cutting the line (begin - end) in a number of segments. For each point generate a random amplitude within a given range and scale it (or scale your random range) so the points closer to the beginning and end can't displace as much. Next for each segment endpoint do a random to see if a fork should be created there, give it a random number of segments and repeat the same process for the fork. Forks can have a fixed endpoint as well if you want. Nodes should have a random value to decide how long they should be kept the same. This way you'll get lightning going from a to b with some points staying in place a few frames longer, some a few frames shorter and some random forking.

# Answer
> 1 votes
Why not try a random walk? You could also have a small random chance of branching at each step.

Ah, you wanted ending coordinates too. Then just weight your directional probability based on how many steps you are from the ending point. The fewer steps remaining, the more chance of going toward the desired endpoint.

# Answer
> 0 votes
I'd personally try with L-System. I wouldn't be surprised if there are examples you could find with google.

---
Tags: 3d, coordinates
---


# Question
Title: what are the essential things to be looked upon in game design
I've made a couple of games now.

Starting from basic hobbyist projects like snake , I advanced into platform based games, board games, turn based games. While doing the latter of these projects I had to spent a lot of time redesigning certain concepts, sometimes even throwing away certain logic. So always I've felt the time wasted could have been avoided or at least reduced, if I had properly planned each and every stage of my game.

Though i can try to do it on paperwork or by a word file with bulleted points. I think there ought to be some other way of game design.

Do help me with suggestions and other game design patterns being followed, either as an indie-game developer or as a game company. I can learn from both. I am not looking for game design e-books, since there is already a thread for that. I would like to get suggestions and game design patters. Thank you.

# Answer
> 11 votes
The time spent eliminating false paths is not wasted. It's time well spent, learning about what the right design is for your particular game. If you're willing to throw that out, that puts you WAY ahead of the game compared to most novice designers.

Think of it this way. When you first set out to make a new game, you either know EXACTLY what mechanics work to make it the best game possible, or you don't. If you do know, it means you're making a clone of an existing game, because the only way we have so far to "prove" that a set of mechanics is good is to actually play the darned thing and see for ourselves. If you don't know, then by definition you're going to get it wrong sometimes. It's like the adage from science: "hey, if we knew what we were doing, it wouldn't be 'research'!"

Beyond that, the best I can offer is that you get a better feel for what will and won't work through experience. Keep making games. Every time you follow your instincts, whether you're right or wrong, your instincts learn from the process and get a little bit better.

But if you're looking for shortcuts to the process... I don't think there are any. If it helps, all creative fields are like that. You don't become a master painter without spending decades painting. Authors have a saying that you should prepare to throw away your first million words and chalk it up to practice. So, it sounds like you're on the right track to being a master game designer; just make sure that each time you throw out a feature, you sit back and reflect to understand why, so that you get that much better at it in the future.

# Answer
> 0 votes
Just a list of things I find that helps me:

1. Play more games
2. Research related topics on your game from developer blogs and gamasutra.
3. Participate in discussions be it online or local, about your design or other games (I find this helps me collate my thoughts as well as get good feedback). Double edged though as it could lead to prolonging the design phase as well.
4. Write down your design, reread a couple of times.
5. Know your target player

---
Tags: game-design, methodology, design-patterns
---


# Question
Title: Which SceneGraph is optimal to begin with for small game programming?
I am a Java web application developer (mostly server side) since 7 years who recently got interested in game development (i dont know why, maybe i am bored). Today I was looking for frameworks. I read about a few scene graphs and took a look at jMonkeyEngine. It was recommended here and here.

My first goal was to create a simple plane and a sphere which could be moved around using the keyboard. Well, as I mentioned I am a web developer and never programmed anything else so I started with the tutorials of jMonkey. But I wasn't able to get them working. I took a look at the wiki but I noticed that the documentation seems to be very poor, at least compared to what I am used to. I then took a look at a few other scene graph's (also for C++) but they also seem to have an outdated, incomplete poor documentation.

Can someone recommend me a scene graph which is well documented with working samples? Or is there something like the "ultimate guide" to get into this topic? Do I first need to know how to develop my own scene graph to get it working or is it possible to just understand the abstract principles and use it from a higher point of view?

Somehow I have the feeling I need to understand the deep insides of a scene graph to use it well (like it's the case for ORM tools in web dev, you can't use them well if you don't understand databases)

I'm sorry if this question is too 'noobish', but I just want to get on my feet and do my first steps.

# Answer
> 5 votes
A scene graph is a tool. It's not really a suitable tool for when you're just starting out in game development.

I think what you are after is not a *scene graph* but just a framework of some kind.

Normally I'd recommend XNA because it's *really* good (powerful, modern, well documented, beginner-friendly). But it is C# and I can see you are a Java man. If you'd prefer to stick with Java, perhaps a good place to start would be the Java ports of the old NeHe OpenGL Tutorials (this is not a framework - but it is a set of tutorials for how to do (at a low level) the kind of things a framework does for you - load and render models, load textures, etc).

In the first few lessons you will learn about transformation matrices, which is basically what scene graphs are all about (in the common case).

To describe a scene graph briefly: Say you have a windmill model - it is defined in its own space. You *translate* it to where you want it to appear in your *world space*. That windmill would have a child object for its rotating blades - so you you would apply a *rotation* transformation to the blades, and it would also inherit its parent's translation to place the blades correctly in the world.

When you're starting out, making small games, you don't need to worry so much about having this big complicated data structure. Usually you'll just have a couple of models that you'll apply transformation matrices to directly.

(Scene graphs are also used for performance-related things like sorting by material, culling, etc - all unnecessary for the beginner and for most small games.)

# Answer
> 9 votes
Scene graph have slightly lost their spot as a must-have. Mostly because a scene-graph centric engine is so tied up in the idea of a scenegraph that it confuses itself. Fact is that various parts of an engine need a different view of the world, whereas a scenegraph centric engine tends to want to impose the same view on all parts of the engine.
The scenegraph as it's traditionally viewed, a hierarchy of parent objects and child objects is nice for transforms, but might be totally inappropriate for rendering, where you are more interested in what materials are used (well okay, location counts too, but there are different ways to deal with that and parent-child doesn't guarantee they're close together, we just tend to see it that way).
In many games you'll find that you have a scene-root with a lot of children, but those children rarely have children of their own. The few that have children you might as well update yourself and skip the scenegraph as it adds unnecessary complexity and performance loss (every transform checking if it's parent is dirty whereas only a few actually have a parent that will get dirty ever (the world root rarely moves).

# Answer
> 2 votes
Why not use a game engine like Unity3d? It is very well known for being easy to use and with great documentation. I tried it out briefly myself and was impressed by how well documented everything was the API and a number of good tutorials. I had problems with my arm and some stage and had to get help from my wife. She has no clue about programming but thought Unity3D was really cool. You can accomplish a lot from just drag and drop. You can use several script languages with the engine. It support JavaScript among other things, which I guess given you background should be attractive. You can get a free version with all the features a beginning game developer would need.

If you **don't need 3D,** then GameMaker is a great alternative. It is really easy to get into and make games. I used it at University and made a couple of games with it. Great fun. It lets you really concentrate on making the game and you don't have to think so much about technology. You can put together a game entirely with just point and click. But as you progress and understand how it all works you start writing your own scripts.

In my opinion it works a lot better than say GameSalad which has no script language. As soon as you start doing more complicated stuff, it gets really annoying with only point and click I think.

# Answer
> 0 votes
I completely agree with Kaj. For more insights on this subject, see gamearchitect (by the way, if you're interested in game developpement, just read the whole site, especially the old one)

---
Tags: scene-graph
---


# Question
Title: Who has ownership of publicly developed projects?
After seeing the comments on selling an idea to developer for a game, the general concencus is that without a game, or atleast a demo, it’s not going to happen. So…someone (yes, Noctrine, I am looking at you) suggested that it might me an interesting idea to turn it into a “public” project.

A few people have asked if I minded if they turned some of my concepts into models, something I always have agreed on. They tell me that it would be to use as work for their portfolio or for practice. Still waiting on those, but that is another story.

If I do this, set up a group to help starting modelers and programmers practice or get stuff for their portfolio, after everything is said and done, who has ownership of the project. I ask in case we end up with an actual demo and a studio get’s interested. Who do they buy it from?

I have no issue with paying accordingly to all participants, but in the legal aspect, who owns it before a publisher buys it?

# Answer
> 7 votes
**I-am-not-a-lawyer** but, my two-cents.

Atleast in the United States, without a formal transfer of copyright each developer would own the work that they do. This is usually accomplished in the Employment Contract when you are hired by a company:

See Works made for hire

# Answer
> 3 votes
Generally, if a work features contributions from more than one person and is a generally indivisible whole, joint copyright exists. This means any one of those people can veto copying of the work, which is often not what you want.

For this reason, it's best to explicitly state that this will not be the case, via some sort of agreement. eg. Along the lines of, "I grant the project and future users of the project a perpetual and non-exclusive right to use my contributions as part of this work." But that makes no provision for payment either. If you want people to contribute work in exchange for actual or potential payment then you'll need to write that in as well.

# Answer
> 2 votes
What noctrine said. But if you aren't an employee, anything you write is covered by copyright. Software is transfered when you grant a license to the users.

When there isn't a license, it's like having a verbal contract-- sometimes possible to enforce, sometimes not, and who know what the terms are or how the court might treat it.

So you will want to read your contracts and licenses, and if they don't exist, get your collaborators to set them up.

# Answer
> 1 votes
I can't remember the project, but I know one open source project managed to give all ownership of code over to the original devs by having certain terms and conditions that took effect whenever someone committed code to the source control repository. In that case, there was a big uproar when those devs ended up selling said source to a commercial company, and all the tens of contributing devs got nothing. I'm pretty sure this is a viable strategy as well, but I would make any contributing member aware of whatever terms you are putting forth, to avoid bad blood getting developed...

(also IANAL)

---
Tags: game-design, open-source, legal
---


# Question
Title: Is there a common invitees/players ratio during closed beta?
The question itself is fairly straight forward, but the answer takes a lot of industry insight.

To give an example scenario, I am playing a game that's in closed beta right now. They have about 5000 people invited and the game is only open from Fridays to Mondays. On average there are only about 200-400 players online at any given time, across EU and US. For a closed beta, this looks like a bit of a low turn-over if you ask me.

# Answer
It varies based on time of day. For example, you'd expect to see more people in the US online at 7pm than 3am. I've seen activity measured at 15-minute intervals throughout the day and then averaged throughout the week.

If you've got 5k invites and each person is online for 1 hour per day, randomly distributed, then you'd expect to see in the 200-300 player range at any given time of day. So really if you want to analyze the invite-to-active-player ratio you'd need more information:

* Total number of beta keys used (that is, invitees who logged in at least once)?
* Average amount of time spent per play session?
* Average number of logins per day (or week) per account?

If you're just trying to ask instead, how many players to invite for beta... depends on whether your beta is more for bug-hunting purposes (keep it small and among trusted friends so you get good reports but you're not flooded with them), playtesting/balance purposes (mid-sized, large enough to get good playtest data but small enough that you don't generate too much bad press for your game if the players initially decide it sucks), or marketing purposes (bigger is better).
> 5 votes

# Answer
When you're setting up any invite beta, you have to remember about geographic distribution. Even on a commerically launched online game like an MMO, the peak concurrency differs VERY heavily from average concurrency. If you want to get to a higher level of concurrency you may consider specifying specific "testing periods" during the day when things are open. You can do it with soft restrictions by just reminding people to play during certain time periods, or you can actually disable the servers during off times. This can help raise your max concurrency.

As for the ratio, I would say getting 5% of invitees to play at a time is a reasonably decent total. Many, many people will sign up for betas, play 5 minutes, and never play again. I would actually pick right around 5% as a ballpark for expected concurrency for a closed beta.
> 3 votes

---
Tags: beta
---


# Question
Title: What all should be happening during the "Loading" screen?
Do I just need to be creating instances of all of my graphics into memory that are loaded from file? What is the best way to handle this? Do I just need some sort of assets manager that creates these graphic instances during the loading screen and is then referred to later?

What are common things that need to be pre-loaded in games? How much should I pre-load?

Is it worth showing some sort of progress bar? How can I keep load times short? What should the loading screen look like?

What are some good examples of loading screens? Any code examples?

Specifically, my game is for Andriod (Java/mobile), but feel free to make your answers generic.

# Answer
The typical things to pre-load is anything that you're going to need in realtime. Save for concepts like clipmaps and megatextures (where the idea is to load the parts you need, and iteratively update it as you move around in the world), you're going to want to keep everything you need for your level/area/whatever in memory rather than on disk. IO is sloooow, and you don't want to load your textures when you turn the corner and it is about to be displayed. And by everything, I mean textures, sounds, meshes, meta data... everything.

If you can show a progress bar (i.e. you have an accurate mapping of loading steps to percentage), then by all means show it. If not, at least show something, like a short text message or a loading indicator, which is updated after each step so you can at least tell *something* is happening.

If there's something which you know will be needed, but not right away, you can load it in the background, and stall the game (not great, but make sure it rarely happens) if it's needed too early. This will help you keep the load time down. I don't know much about android development, or if it'll be to much for the device to handle alongside the game, but it's usually rather light on the CPU so there shouldn't be a big problem there.
> 13 votes

# Answer
You need to be "Reticulating Splines"
> 20 votes

# Answer
Depends if you're going for one loading screen and instant level transitions or multiple loads.
I would say that the latter would be better on memory.
Something like:
`//First loading screen
Load menu layouts or whatever
Load GUI assets
Show something to pass the time
Switch to menu
`//In between levels
Remove any graphics specific to the last level - get rid of something that isn't going to reappear like a boss.
Load level graphics that haven't already been loaded
Again, show progress or something to pass the time``

And when you're loading, make sure not to have a black screen. Or for that matter, a static screen. Many a time have I seen a static image for a while at the start of an app, and immediately thought it had crashed.
A good way to get the player involved simply would be a nicely drawn background of a scene in the game, or some storyline reference; a loading bar with/without percentage, as long as it isn't a static 'Loading'; and then maybe some information.
> 3 votes

# Answer
On iphone and Android platforms, you must load all textures and sounds. Loading textures and sounds is really slow on old phones as iphone 2G, 3G or G1. You can't do it in the game.
> 2 votes

# Answer
As others have said, if you can load all of a level's data before you start playing it, then you'll have much better performance. It's a common source of hitches in frame time to load assets during gameplay.

Common things to do during a loading screen is a static background image, a very simple level, some tips and tricks on how to play, quick animations, etc.

Here's the loading screen for APB. Pretty freaking cool. :) http://www.youtube.com/watch?v=p5STix1t\_1E&feature=related

Here's some pseudo code for showing a progress bar in a loading screen:

```

LoadScreen::Init()
{
  mAssetsToLoad.add("Background.png");
  mAssetsToLoad.add("Player.png");
}

LoadScreen::Update()
{
  mProgress += 1;
  mAssetManager.load(mAssetsToLoad.top());
  mAssetsToLoad.pop();

  if mAssetsToLoad.empty()
    mDone = true;
}

LoadScreen::Draw()
{
  for( int i = 0; i != mProgress; ++i)
  {
     Vector2 pos(i*mProgressPartTexture.Width, 100);
     DrawProgressBarPart(pos, mProgressPartTexture);
  }
}

```

Ugh, forced to use != because it broke off the code rendering when I used \<
> 2 votes

# Answer
Loading screens can be used to hide pretty much anything; loading of assets, any connections it needs to make (tcp, etc), populating maps with game objects, and initialization.

The way I tend to go about things is to have some sort of asset manager (or maybe a manager for each asset types - sounds, graphics, etc.) and have them load what is going to be used into memory. Then just have your game pull references out of the managers.

Showing a progress bar, determining what to preload, etc. seem to be dependent on your project, it's loading times and your tastes. Progress bars are nice if they're accurate and it's a long load (it's nice to know how long you need to wait).

With that said, on my android phone I tend to favor apps that have their own custom, tastefully done loading screen. It doesn't need a bar, but animation tells the user the programs working. I believe android has a default bar you can use, which does the job fine.

Here's a SO question that might interest you.
> 1 votes

# Answer
It's worth noting that the platforms with quality control requirements (e.g. X360, PS3, DS, etc.) will all require you to have some form of animation in your loading screen (or in fact any screen which remains static for more than a few seconds).

This is because otherwise the user may think that your game has crashed, when in fact it is just taking a long time to load. Even where this is not a requirement, I'd certainly advise it.

Any form of animation is fine, but a simple progress bar may not be the best, as any large steps in the loading may result in the progress bar not moving at all for a while, meaning the screen is just as static as if there were no bar at all. Better to show some continually moving image, like a rotating icon, in addition to a progress indicator.
> 1 votes

# Answer
For the loading screens in Conquest, I went with a little bit of mission description (what game type it was, as well as a little bit of storyline for the mission), and some basic help on the commands.

In the background, I was loading sounds. The graphics were all loaded on demand, and that seemed to work pretty well for our game, but sounds were a bear, so I preloaded all of the sounds needed for the mission. The Loading/Start button is disabled until everything's loaded, but I don't have any type of animation (which would be a good thing to add).

This is our first game, so we're still learning a lot, but this has worked out OK for us so far.
> 1 votes

---
Tags: assets, graphics, android, loading, preload
---


title: Post processing texture sizes

text:
# Question
Title: Post processing texture sizes
I'm trying to write some code to do post processing in OpenGL ES2 on the iPhone. All is fine an dandy, except I am having trouble working out how to scale the texture rendered in the rendering step, such that it ends up pixel-aligned to the final image displayed on the screen.

I'm using a 512x512 texture, as provided by Apple's Texture2D class, to store my off screen rendering, and then mapping that onto a quad and rendering to cover the whole screen. The thing ends up taking up half of the screen vertically, more than the width of the screen, and is positioned about 2/3rds of the way down. Here's my setup:

```
        // Create render to texture targets
        for (int i = 0; i < 2; i++)
        {
            textures[i] = [[Texture2D alloc] initWithData:0
                                     pixelFormat:kTexture2DPixelFormat_RGBA8888
                                     pixelsWide:512
                                     pixelsHigh:512
                                     contentSize:CGSizeMake(512, 512)];

            // create framebuffer
            glGenFramebuffers(1, &textureFrameBuffers[i]);
            glBindFramebuffer(GL_FRAMEBUFFER, textureFrameBuffers[i]);

            // attach renderbuffer
            glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, textures[i].name, 0);

            // unbind frame buffer
            glBindFramebuffer(GL_FRAMEBUFFER, 0);
        }
        // Setup our render to texture quad
        // Screen bounds are usually -1 to 1 on both axis, but we
        // multiply 'y' coords by (2.0/3.0) in the vertex shader so that we
        // get to use a square coordinate system that matches the screen ratio.
        float xSize = 1.0f;
        float ySize = 1.5f;
        quadPoints[0] = -xSize;
        quadPoints[1] = -ySize;
        quadPoints[2] = -xSize;
        quadPoints[3] = ySize;
        quadPoints[4] = xSize;
        quadPoints[5] = -ySize;
        quadPoints[6] = xSize;
        quadPoints[7] = ySize;

```

I'm doing ping pong rendering, hence the 2 offscreen targets. I've tried fiddling with xSize and ySize to make the thing stretch out beyond the bounds of the screen, such that the texture aligns properly, but can't seem to get it right.

To render with a single post processing step, I do

```
// Bind to first offscreen framebuffer
glBindFramebuffer(GL_FRAMEBUFFER, textureFrameBuffers[0]);
glViewport(0, 0, backingWidth, backingHeight);

// Render scene

// Bind to the screen framebuffer, and render the previously generated texture through our
// post processing shaders.
GLuint currentProgram = [[postProcessPrograms objectAtIndex:i] intValue];
glUseProgram(currentProgram);
GLuint sourceTexture = (i % 2 == 0)? textures[0].name : textures[1].name;
// Render the texture
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glEnableVertexAttribArray(ATTRIB_VERTEX);
glVertexAttribPointer(ATTRIB_VERTEX, 2, GL_FLOAT, 0, 0, quadPoints);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

// Show our buffer
glBindRenderbuffer(GL_RENDERBUFFER, colorRenderbuffer);
[context presentRenderbuffer:GL_RENDERBUFFER];

```

Any help would be great - I feel like i'm missing something obvious!

# Answer
> 1 votes
It's a bit tricky to tell exactly without seeing your shader, but there are a couple of things you may be able to do differently:

* Use scale AND bias to control the rendering In effect, this becomes:

```
float xSize = 1.0f;
float ySize = 1.5f;
float xBias = 0.0f;
float yBias = 0.5f; // use whatever works, or figure it out analytically.
quadPoints[0] = -xSize + xBias;
quadPoints[1] = -ySize + yBias;
quadPoints[2] = -xSize + xBias;
quadPoints[3] = ySize + yBias;
quadPoints[4] = xSize + xBias;
quadPoints[5] = -ySize + yBias;
quadPoints[6] = xSize + xBias;
quadPoints[7] = ySize + yBias;

```

(play with bias to see how it affects your image)
* Use texture coordinates to control where on the texture each point in your quad is anchored to. You can specify them in a separate array called texCoords like this:

```
  texCoords[0] = 0.0f;  // (0,0)
  texCoords[1] = 0.0f;
  texCoords[2] = 0.0f;  // (0,1)
  texCoords[3] = 1.0f;
  texCoords[4] = 1.0f;  // (1,0)
  texCoords[5] = 0.0f;
  texCoords[6] = 1.0f;  // (1,1)
  texCoords[7] = 1.0f;
  glEnableVertexAttribArray(ATTRIB_TEXCOORD)
  glVertexAttribPointer(ATTRIB_TEXCOORD, 2, GL_FLOAT, 0, sizeof(float)*2, texCoords);

```
.. or you can interleave them in your quadPoints array.

---
Tags: opengl, iphone, rendering, opengl-es
---


# Question
Title: Programmers/Designers: working with artists
Expanding on this question, what information do I need to communicate my artistic goals for a game to a professional artist?

Assuming I'm an indie programmer. and I've found or hired an artist to for my game, how to I go about setting a template or a brief for the look and feel of my game?

# Answer
> 11 votes
Communicating your artistic goals is often not the problem. If you show him or her several examples of the sort of style you mean, along with some commentary on what you like (or don't like) about them, a good artist will usually be able to get the rough idea of what you want, and talk through the details with you.

Usually the problem is communicating the technical goals. These include polygon or vertex limits, texture sizes, the use of texture maps for specular/diffuse/bump/normal/etc (ie. which of these you support), different types of asset budget (eg. for the whole download, for a given level, for any one visible scene, for one model), the way your GUI is skinned, how 2D animations should be packaged (sheets or files), cursor/HUD/sprite sizes, the scale of the models (often 1 unit = 1 metre, but not always), the rotation of the models (which axis is 'forward'?), what the typical lighting will be like, etc.

The more of these you can fix or automate with tooling, the better. But as an indie programmer, your resources will be limited, so instead you will most likely have to resort to clear and unambiguous communication.

# Answer
> 12 votes
If you have an idea of what your game should look like, put together a style sheet which will show the artist where you're coming from. Take a look at the style sheet in this post about Velociraptor Safari and put something together that reflects the way you want your game designed.

The artist should then get a good feel for what you want and will combine elements that work together or tell you what they don't like.

Stock photography sites and Google image search can provide a lot of material to add to your sheet.

# Answer
> 2 votes
Seeing as you've found your artist, hopefully it's because they gave you a sample of their work which you wanted to see in your game. Take this sample and tell them what types of work you liked, why and how you want them to develop their artwork around this.

Even stick figures in the "right" positions will work wonders, especially if you work with humanoid models you want him/her to draw. Don't be afraid to reject artwork, but don't be too picky, remember they might have a better eye than you toward art. However, if you find yourself rejecting them often (like every submission) and it's not simply minor changes, you may not have chosen the right artist or art style you like.

Be prepared to pay out the wazoo, unless your artist graciously accepted a percentage of profits deal.

# Answer
> 1 votes
I was witness to one situation where 2 entrepreneurs with a load of cash and 0 game design skills wanted to clone a popular game on the NDS and make it for the iPhone. Unfortunately for my friends that got involved as the programmers/artists the two guys kept only one thing consistent, and that was changing up the gameplay style/art look every other week.

It seemed like they went out and bought every iPhone game they could, sat around playing it while my friends did programming then phoned in just to tell them that they want a game like this - and the look like this. It took ages for the art to get done because there were so many changes.

I feel sorry for my friends - but I don't think they will get into a crazy scheme like that again.

---
Tags: game-design, art
---


# Question
Title: Defining GUI control event responses using Lua in C++
I'm using Irrlicht(C++) for a 3D engine, and it has a built in GUI system. The GUI events are something like this:

switch(eventtype)
case button\_pressed:
stuff
case editbox\_edited:
stuff

So far I have begun writing a system that allows me to create the GUIs with Lua scripts. It was very easy to make it so it creates the GUI controls from Lua, but I can not think of a good way to define what should happen when control events occur from Lua too. Here's an example of what I have so far:

Lua:

```
local button = create_button("button label",10,10,100,50)
toggle_control(button,false)

```

C++:

```
static int CreateButton(lua_State* L)
{
 int n = lua_gettop(L);
 core::stringw label = lua_tostring(L,1);
 core::stringw tt((n>=5?lua_tostring(L,6):""));
 int x = lua_tonumber(L,2);
 int y = lua_tonumber(L,3);
 int w = lua_tonumber(L,4);
 int h = lua_tonumber(L,5);
 core::rect r(x,y,x+w,y+h);
 unsigned int id = NextID();
 if(r.isValid())
 {
  gui::IGUIButton* b = device->getGUIEnvironment()->addButton(r,0,0,label.c_str(),tt.c_str());
  cl.insert(ControlPair(id,b));
  lua_pushnumber(L,id);
 }
 else
  lua_pushnumber(L,-1);
 return 1;
}
```

Please ignore the security issues with the code (it is a very early version). So my question is this: What are some good ways of defining the control events from a script interpreter in C++?

# Answer
> 3 votes
I'm not familiar with Irrlicht, but you could pass a function to the CreateButton that should get called on an event that deals with that button. You could either pass a string, and do a lookup in the global table for a function with that name at run time, or store a pointer to the lua function itself (which should allow you to do lambdas).

In the past I've done a convention-over-configuation thing, where the game automatically picks up lua functions that fit a callback style. Eg:

```
createButton("myButton", "label text", 10, 10, 100, 50)

...

function onEvent_myButton(eventParams)
    -- process event
end

```

The game parses the global table, looking for onEvent functions and parsing the function name to see if it matches your new button name. It hooks that up as a callback.

For some reason our designers found this a more friendly approach.

---
Tags: c++, gui, lua
---


title: Flash Origin Problem with Movie Clips

text:
# Question
Title: Flash Origin Problem with Movie Clips
I'm working on a game that uses Flash for the user interface. I'm running into an odd issue with the origin of a library movie clip. Here are the steps to reproduce:

1. Create a new MovieClip and construct a single rectangle with both a fill and a stroke.
2. Set position of rectangle to (0,0) and notice that the origin is at the center of the border stroke surrounding the rectangle.
3. Change position of rectangle accordingly so that the origin is truly the top left (so if the stroke surrounding the rectangle was set to 10, adjust the position of the rectangle to 5,5.
4. Enable 9 slice for movie clip so that when you scale the rectangle it doesn't scale or distort the stroke surrounding the rectangle.
5. Drag an instance of the movie clip to the stage and use the free transform tool to scale it to the width of the stage. It should visibly be as wide as the stage.
6. Run the flash file and verify that the width during execution is not as wide as it was in design view.

So in a nutshell it seems that when you use the free transform tool, it distorts the origin even though 9 slice is enabled and it shouldn't (I would think). I understand that Flash denotes the center of a stroke to be the starting point and not the edge, which is why I adjusted the origin accordingly while editing the movie clip.

What I really need here is pixel perfect positioning for vector based components. I should be able to drag and drop a library movieclip that provides a window with a fancy border around it and scale it to whatever size I need, and place it where I need it to be without any odd positioning problems.

Here are some screenshots of the problem:

( i.imgur.com/8WU2F.png ) is a shot of my window with 9 slice enabled. You can see that the origin is correct being the top left of the window graphic.

( i.imgur.com/ciK8l.png ) is a shot of my window after using free transform to scale it to the width of the stage. It's pretty much perfect in design view

( i.imgur.com/QFUiJ.png ) is a shot of the flash application running. Notice that the window is no longer the width of the stage? I don't get it. It makes it very difficult to position because in order to get this to look right while executing, I have to make the window wider than the stage in design mode.

Any help is greatly appreciated. I'm sure it's something silly. This is pretty much bread and butter stuff that's been around since the early days of flash.

# Answer
> 2 votes
From the top menu in Flash go:

Modify \> Shape \> Convert Lines to Fills

# Answer
> 0 votes
Copy the movieclip to a new .fla and upload it somewhere and I will take a look at it.

**I figured out your problem. Using lines in 9 slice editor will always give strange results. Remake it from shapes that are made from fills only and have no lines.**

---
Tags: flash
---


# Question
Title: What is the name for the little numbers that appear over characters' heads when they lose health?
...you know the ones. Something like "value overlays" or "value pop-ups" describes them quite well, but I was thinking they might have a real name?

# Answer
> 7 votes
"Floating text" does it for me. That's what I've always called it, although I've never used it specifically for indicating damage done. My usage was usually to indicate where something important in the scene was (e.g. "retrieve this data disk").

# Answer
> 7 votes
In WoW terms the most popular addon is called Scrolling Combat Text, which I think describes it pretty well.

When I've written my own implementations I use the more general "Floating Game Text".

# Answer
> 7 votes
I think our term was "Damage floaters".

---
Tags: gui, interface, glossary, terminology
---


title: cocos2d Merging box2d bodies

text:
# Question
Title: cocos2d Merging box2d bodies
i'm using cocos2d to build an iphone game.

my game currently has two sprites: one for the main character and another for an item i should carry once he gets on him.

the main character and the item are both box2d bodies. i can detect the collision between the two. what is want is to make the item body stick to the main character body when they meet, that way any movement of the main character would also affect the item.

any suggestions on how to implement this?

thanks!

# Answer
There has been **a lot** of discussion on this very topic on the Box2D forums. You'll find most of the info under the guise of breakable bodies, which is your problem in reverse. Here are my suggestions in order of easiness:

1. Depending on the situation you could just change the animation of the main character to show that he is now carrying the item without needing the item to still be physically simulated.
2. If that isn't enough, add a new `b2Shape` to the main characters `b2Body`. The new shape will look exactly like the shape used in the item and be attached right where you need it.
3. Lastly, you can use the new weld joint to attach the item to the main character. Note, a weld joint is more like a rubber cement joint. If you want the item to fixed securely in place, use option 2.
> 5 votes

# Answer
I'm not familiar with Box2d in particular, but most physics engines implement the concept of a joint. You create a joint of the appropriate type, attach it to the bodies and presto! they move only in ways allowed by the joint.
> 2 votes

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


# Question
Title: How would I make behavioral AI, from a game engine, for character conversation modelling?
I want to use the behavioral AI from a game engine, for character conversation modelling. Most game engines provide very good graphics pipelines, like Unity, but I want to use the AI part, like in *"Assassins Creed 2"*.

It looks like the character is always in a state machine during gameplay, especially when he talks to the other characters and the NPCs. The other characters, like Lucy, do not say the same thing. Instead, they say something which is related to the local goal of the state. Is it all scripted, or is there any AI?

# Answer
In my experience, conversations with NPCs in games are always scripted. Natural-language parsing and sentence formation are difficult and mostly unsolved problems at this point, so we fake it.

To the extent that there's anything that could be called "AI" you can do one of two things, both of which still count as scripting in my book:

1) Flags. If the player has taken a certain action in the game, or earlier in the conversation, or whatever, then set a flag on the NPC that makes them treat the player differently. Think of every RPG you've ever seen where the palace guard tells you the princess has been kidnapped, until you bring her back, at which point he says something else.

2) Numeric ranges. The player has one or more numeric attributes. These might be global attributes (Karma in Fallout 3, Light/Dark side points in Knights of the Old Republic, etc.), or specific to that NPC or that NPC's faction (like your friendship/romance levels with other characters in The Sims). If your value is higher or lower than a certain threshold, the NPC treats you differently.
> 5 votes

# Answer
To my experience some games like RE Outbreak and L4D used a script + variables. Where variables are generated along with the map generator. This usually not part of a game engine, as game differ on the RND generating rules most of the time.
> 1 votes

# Answer
The Inform community, which probably writes more realistic game conversations than anyone else, has several different tricks and extensions for scripting character conversations. The *content* of these conversations is generally scripted, but the *form* is more dynamic, or at least more variable. This is not a traditional area of AI research, although some people like Nick Montfort are breaking new ground in this area.
> 1 votes

# Answer
To date, the only game I'm aware of that is not scripted (in the way you probably mean it) is Facade (Try it, it's worth the time spent)

But even there, it's scripted to some extend : every time you play, there will be 3 "special points" in the drama, and characters still obey to some "scripted" high-level rules.
> 0 votes

# Answer
One thing you can do to make conversation more "AI-Like" is to combine your scripts into a greater system. For an individual interaction between characters a script with variables, as described by Ian, is as good a solution as anything involving "real" AI.

But, the way you kick off and transition between these conversations can definitely use "real" AI. For instance, you can model a character's schedule so they go about their lives according to a set of priorities. Then, if an individual character comes into contact with another character, you have a system that evaluates rather they would talk, based on shared history or other factors. This can be as complicated as you would like and there's no need to pre-script the meta-conversations. But, as soon as you drop into an actual conversation you're better off going with something prescripted.
> 0 votes

---
Tags: ai
---


# Question
Title: Varying the strength of attacks by holding down the button
I am preparing a conference session about game design, and a question occurred to me that I haven't been able to answer with Google:

In Mario the player varies the height of Mario's jump by holding down the button while Mario is in the air. Has this approach ever been used to vary the power or attacks, i.e. hold down for a hard attack, tap for a fast attack. I feel like this must have been done many times but I can't think of a concrete example.

UPDATE 1: I'm specifically thinking about systems where the attack is launched as soon as you press the button, but gains power as you hold it down (like Mario's jump), rather than systems where you hold down to charge-up and release to attack.

# Answer
A few fightings games do this. Normally it's a hold to charge and then release to attack, but in a few cases holding changes which later attacks you can combo off the initial attack. In those cases holding is just keeping the combo going until the next branch point in the animation.

Hold as an analog continuation is less common in attacks because of the nature of animation. With a jump you can just loop a "launched" position as the player continues to rise, so the effect is easy to pull off. However for an attack, strong attacks tend to look different before contact is even made so it's difficult to transition them post starting an animation.
> 3 votes

# Answer
* On the Wii, in Super Smash Bros. Brawl you can 'charge' up smash attacks (powerful attacks) by holding the button down for longer.
* In fact, a significant amount of items on that game use that principle (i.e. one of the guns switches between rapid fire and a large energy ball depending on hold length)
* Not sure if it counts, but golf simulations tend to rely on it; the longer the button is held, the harder you hit the ball.
> 2 votes

# Answer
Most of them are used in fast paced or brutal games.

**EDIT**: After your update only one game comes to my mind right now: Fable 2, for magic you had to press down and hold one of the controllers trigger to build up bigger more powerful levels of the respective spell.
> 1 votes

# Answer
I think the games Tobal, The Bouncer, and Crimson Tears fit your description the most. In these games the pressure exerted on the Analog PS1/2 controller gives different results.

I.e. Tapping square gives you a jab, pushing it gives you an uppercut.

I should also add Tekken's Steve Fox has this tap, semi hold system where his attack change properties.

KoF's Shen Woo had the qcf+P where holding slightly makes it into a launcher rather than a flinch.
> 1 votes

# Answer
My contribution: **Tekken**. Different moves can be done by holding the button down or just tapping it.
> 1 votes

# Answer
Soccer games often have something like this: click once for a basic or short pass or shot, and hold down the button to ramp up the power and kick it harder and further. While not exactly an 'attack' this has the same time/potency tradeoff that you're presumably thinking about.
> 1 votes

# Answer
Yes, this mechanic is common enough that there's a name for them: "charge attacks".

I've seen them mostly with side-scrolling shooters; it was popularized by R-Type (which is the earliest game I know of that had this mechanic) but some of the Gradius and Raiden games featured this as well.
> 1 votes

# Answer
Isn't this true for any game where you are shooting a stream of bullets and don't have to release the button/key? If the enemy can be struck by three shots instead of one, is there any difference between that and making the attack stronger? (Sure, it also widens the area of attack over space or time, but it's still kinda the same.)
> 0 votes

# Answer
A thing to note also is the running within GTA. Holding A does a fast run but you get tired fairly quickly whereas tapping A makes you do a fast jog that you can keep up for a prolonged pierd of time. (I may have the presses the wrong way round)

Regards Mark
> 0 votes

# Answer
In most Arcade style SHMUPS, if you tap the shot button it fires regular shot, but when you hold it down, it turns into a laser that is more powerful.
> 0 votes

# Answer
I don't think you could do *exactly* what you're talking about. You would need at least a short delay to tell if the player is just tapping or holding the button. Unless the animations for a powerful and weak attack start the same. Alternatively you could just have your weak attack followed by a stronger one if the button is held down.
> 0 votes

---
Tags: input
---


# Question
Title: How do I prevent getting an access denied loading a file in XNA, when I have the application running in the program files directory (in Windows 7)?
I'm creating an app in XNA.

I'm trying to load a custom save file. I named the file with my own custom extension. It's an XML file serialized with the DataContractSerializer.

I've tried several things to load the file. And they all work when I'm running in my development environment, or when the game is running from most folders, but if the game has been placed in the program files folder (or any other protected by Windows 7), the game won't load my custom files, but it will load images and other items that the content importer handles naturally.

Things I have tried:

* Directly loading the file using the DirectoryInfo.CurrentDirectory() then scanning for files, and loading them.
* Using the StorageContainer.TitleLocation
* Creating a custom importer, and loading them into the content pipeline

In all cases, it works fine running in my IDE (C# Express 2008), but when the app is running from Program Files, I get the following error:

Access to the path 'C:\Program Files\MyFolder\MyAppName\Content\CustomFolder\Blah.CustomExtension' is denied.

I am running as administrator (though obviously, I eventually don't want the end user to need this right).

Any suggestions?

# Answer
> 5 votes
As the commenter said: check to see if your app runs fine when running as administrator, because if it does, that suggests something different.

Otherwise, I think you're running into a straightforward access rights issue. You don't, as a rule, have the right to open any files under "C:\Program Files" with write access. So you don't get to save any files there at all. Your question suggests though that it's not the saving that is causing you problems, but the loading. Still, you need to make absolutely sure that you're not trying to open the files with the wrong access permissions.

You don't say what functions you're actually using to do the loading, we'd need to see that code to confirm. But as an acid test, you should be able to call:

```
File file = File.Open(path, FileMode.Open, FileAccess.Read);

```

Which should work, even for files under Program Files.

NB: If you're just using the 'plain' versions of the functions, i.e. omitting the FileAccess.Read parameter, then **the system will default to FileAccess.ReadWrite**. You will not be allowed to open files using FileAccess.ReadWrite, if they live in the Program Files hierarchy. Even if you never write anything to those files, the open call will fail unless you ask for the right sort of access.

# Answer
> 1 votes
Unless you run the game as Administrator (which you don't want, if only because some players simply won't be able to) you don't permission to write in the Program Files directory.

You should write save games, downloaded maps and other such files somewhere in the directories belonging to the user (Documents, Application Data or something like that).

---
Tags: xna, windows, loading, file
---


# Question
Title: Anyone have a source for pictures/screenshots/demos of Mud OLC systems?
I really want to get access to some images of MUD (multi user domain/multi user dungeon) OLC (mud OnLine Creation), to use the structure of npcs/mobs/characters/areas/rooms that muds use on my own webgame project (http://www.ninjawars.net), which features a near predominant use of text itself.

I've played a mud for years, and experienced the OLC system of that mud first hand, but the mud went under, so I'm looking for

I tried compiling the type of Mud it was from source (ROM 2.4) but haven't been able to accomplish that.

I'm expecting that there are some images of the OLC of items/mobs/etc out there already, but I haven't been able to find any to base my implementation of the same concepts in my game off of. If there's some live way to get access to a demo of OLC, that would be even better.

# Answer
> 1 votes
I'm not sure what use you'd find with screenshots! Ultimately it's just plain text, and you are going to be given a menu which is a list of whatever is changeable for that entity. You pick your option, enter a new value, repeat. There are 3 or 4 different brands of OLC for MUDs and although the presentation is slightly different for each, they're all pretty much the same really. (Here's a screenshot, though I don't think it'll do you much good: http://mud.wikia.com/wiki/NiMUD)

Are you actually interested in the OLC, or are you more interested in just learning what attributes exist on mobs, objects, rooms, etc? The latter can be more easily found by scanning the source code. (eg. Go through Merc.h in a ROM 2.4, for example.)

---
Tags: design-patterns, mud
---


title: Where to look for team mates?

text:
# Question
Title: Where to look for team mates?
Where is a good place to look for people interested in creating games online? I'll be using XNA.

I'm going to start the project later this week, but I'm definitely commited to it. I'd like to find people who won't hit it and quit it after a month.

# Answer
A much better question to ask is "**How do I pick the right teammates/project?**"

This is an excellent article on the subject

**How to Pick Indie Game Collaborators: 11 Things to Watch Out For**

> ... The first groups I joined taught me most of the items I hope to pass on to you in this article. They all had heart, and lots of dreams, but very rarely did they have sufficient talent, dedication and management. I spent easily a year and a half spinning my wheels, going from group to group, before I found a really good one...
> 2 votes

---
Tags: project-management
---


# Question
Title: Autodesk Kynapse and Havok AI comparison
**Kynapse**

> Autodesk® Kynapse® game middleware is a leading artificial intelligence (AI) solution for game development and the creation of real-time simulations for nonplayer characters (NPCs).

**Havok AI**

> Havok AI is a new platform-optimized SDK focused on efficient pathfinding and path following. Havok AI is built from the ground up to consider dynamically changing environments.

Information about both of these middleware solutions is limited. I was looking for pros and cons of using either. As well as any type of comparison between both middleware packages.

**In particular:**

* Pros
* Cons
* Features
* Experience with using
* Difficulty
* Latency of response
* Clock cycle utilization
* API/tutorial documentation
* Source code included? or binary
* Supported platforms
* Supported languages
* etc

*A good response should be fact based, and any subjective subjects like difficulty should be based on an explained experiences with the product.*

# Answer
I'm the AI team lead at Havok, so my opinion may be obviously biased :)

Havok AI is relatively new (announced at GDC 2009), so you probably won't find many users responding on here. But as a company, Havok has been around for over 10 years and our Physics product is one of the best known pieces of game middleware.

The key features of Havok AI are:

1. Fast nav mesh generation
2. Cross-platform, optimized runtime. All major queries run on multiple threads (including SPU on PS3).
3. Dynamic pathfinding that integrates with (but doesn't depend on) Havok Physics.
4. Robust character steering system

The API is well-documented, and there are numerous demos to show different features of the system. Additionally, you'll have access to our support team, who are constantly cited as one of our strengths (i.e. check out the quote from Volition in the 2009 Frontline Awards).

Licensees get access to most (but not all) of the source code.

Supported platforms are: Win32/64 (Visual Studio 2005/2008), Xbox360, PS3, Wii, Mac, and Linux. If you have more exotic hardware needs, we can also do custom builds, although those can take time.

Language: C++

For serious commercial inquiries, you can fill out the form here and one of our sales engineers will contact you.

That's probably all that I can say without an NDA, but if you have any other questions, it can't hurt to ask...

-Chris
> 6 votes

---
Tags: ai, havok
---


# Question
Title: Help making a visual transition with pygame and NumPy
Perhaps this could be better answered on Stack Overflow, but I thought it would be worth posting here. Right now I'm trying to make visual transitions with pygame's `surfarray` module which uses NumPy. I'm using Cave Story's diamond-checkerboard transitions as a model right now (you can see them in this video http://www.youtube.com/watch?v=mJbAs-sSX4A).

I'm new to NumPy and I'm a little bit over my head. Is there an easy way to accomplish this, or are there any tutorials I should be following? Google brought up a bunch of general NumPy tutorials which I didn't find very helpful for my specific needs.

# Answer
You can easily do regular checkerboards by using numpy to copy parts of an image (array) onto another array, like this:

```
# Let's define two arrays to work on. They should be replaced with your surfaces
a = numpy.ones((640,480))
b = numpy.zeros((640,480))

a[100:110,200:210] = b[100:110, 200:210]

```

Obviously you can mix it up, copy from multiple sources and different locations if you need it for your effects. Since everything is handled by numpy (without coming back to python after every pixel) it is quite fast.

The only limitation is that the source and destination must be the same size (or obey the broadcasting rules, but that's not what you want here).

**Update**

I had completely forgotten about `choose()`. It is the missing piece you need to do the transitions "properly". What you need is something like this:

```
diamonds = [ ... ] # List of arrays containing 1 and 2 arranged in enlarging diamond patterns, say 100x100
for diamond in diamonds: # you probably want timers and events rather than a tight loop
    for x in [0,100,200, ...]:
        for y in [0,100,200 ....]:
            screen[x:x+100, y:y+100] = diamond.choose(screen1[x:x+100,y:y+100], screen2[x:x+100,y:y+100])
    # Pause for transition effect
    time.sleep(0.01)

```

This should get you the required effect. Post if you get into trouble.
> 1 votes

# Answer
The basic way to do this is with choose. You need surfarrays of both sides of the transition, and then make a set of arrays for each step of the animation.
> 1 votes

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


# Question
Title: How do I import real world models into a game engine?
What are the hardware and software tools required to import physical worlds into a game engine? Can I use a HD camera to do that? What do the popular game engines support?

# Answer
> 6 votes
Well, it's certainly nothing game-related, but it technically *is* possible to take multiple (2D) photographs of an object and use Photosynth to approximately recreate the object's 3D space. It's pretty neat, you should check it out.

Otherwise, there are **3D scanners** but they are typically pretty small-scale. You certainly can't scan a large area with one of those.

There is also such thing as a **stereo camera**, or a camera with 2 (or more) lenses, which can therefore capture "3D" data. But I don't think these have progressed as far as being able to create 3D models out of the dual images they create, and even if they did, the models would only be from one viewpoint so they'd be incomplete just as Photosynth's are. I would think the latest 3D movies use stereo cameras when recording in order to capture this effect, but they could be using something else (a camera with a sonar attached or something, maybe).

**The best thing to do is to create it from scratch.** Take pictures of textures and unique objects (signs, etc.), take note of dimensions, and take whole-scene pictures for reference. Then have a 3D artist sit down and recreate it in 3D. Any automated large-scale 3D model creator, if one exists, would be wildly expensive.

> Can I use a HD camera to do that?

To take the texture pictures, sure! I recommend a camera which is good at up-close shots.

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


title: Problem with box2d at beggining

text:
# Question
Title: Problem with box2d at beggining
I have problem with simple box2d physics: I have two bodies : 1 - static box , 2 - dynamic box. I only want to this dynamic box fall on this static, and lay. But now it looks like that at end , starting from . This is code, which bases on box2d HelloWorld:

```
#include <SFML/Graphics.hpp>
#include <Box2D/Box2D.h>
#include <cstdio>

int main(int argc, char* argv[])
{
    B2_NOT_USED(argc);
 B2_NOT_USED(argv);

 b2Vec2 gravity(0.0f, -10.0f);
 bool doSleep = true;
 b2World world(gravity, doSleep);

 b2BodyDef groundBodyDef;
 groundBodyDef.position.Set(0.0f, -10.0f);
 b2Body* groundBody = world.CreateBody(&groundBodyDef);
 b2PolygonShape groundBox;
 groundBox.SetAsBox(50.0f, 10.0f);
 groundBody->CreateFixture(&groundBox, 0.0f);

 b2BodyDef bodyDef;
 bodyDef.type = b2_dynamicBody;
 bodyDef.position.Set(0.0f, 300.0f);
 bodyDef.active = true;
 b2Body* body = world.CreateBody(&bodyDef);
 b2PolygonShape dynamicBox;
 dynamicBox.SetAsBox(3.5f, 3.5f);

 body->SetTransform(b2Vec2(0,100),30);

 b2FixtureDef fixtureDef;
 fixtureDef.shape = &dynamicBox;
 fixtureDef.density = 1.0f;
 fixtureDef.friction = 0.3;

 body->CreateFixture(&fixtureDef);

 float32 timeStep = 1.0f / 60.0f;
 int32 velocityIterations = 6;
 int32 positionIterations = 2;

    sf::RenderWindow app(sf::VideoMode(800, 600), "BOX/SFML");
 app.UseVerticalSync(true);
 sf::Shape shape = sf::Shape::Rectangle(-3.5f,-3.5f,3.5f,3.5f,sf::Color::Green);
 sf::Shape groundShape = sf::Shape::Rectangle(-50,-10,50,10,sf::Color(100,40,120));

    while (app.IsOpened())
    {

        sf::Event event_;
        while (app.GetEvent(event_))
        {

            if (event_.Type == sf::Event::Closed)
                app.Close();
        }

  world.Step(timeStep, velocityIterations, positionIterations);
        world.ClearForces();

  b2Vec2 position = body->GetPosition();
  float32 angle = body->GetAngle();
  b2MassData m;

  body->GetMassData(&m);
  printf("m %f\n",m);
  printf("%4.2f %4.2f %4.2f\n", position.x, position.y, angle);

  app.Clear();
  shape.SetPosition(position.x+400,-position.y+300);
  shape.SetRotation(angle);
  app.Draw(shape);
  groundShape.SetPosition(0+400,10+300);
  app.Draw(groundShape);

        app.Display();
    }
 world.DestroyBody(groundBody);
 world.DestroyBody(body);
    return EXIT_SUCCESS;
}

```

I looking for any advice for solve this problem. And another problem, why mass of dynamic shape is 0 ?

# Answer
I've found I hate SFML when dealing with Box2D. It's concept of inverted-y and pixel based coordinates is great if you want to draw a quick box. It's horrible if you need to tie its coordinate system into another library (which you will need to do in any game that's not an SFML demo).

My recommendation: use Box2D's debug rendering. That way when you see an object in the middle of the screen you know it's actually there. The `sf::Shape`s could be way off of the underlying `b2Body`.
> 1 votes

---
Tags: physics, box2d
---


# Question
Title: 2D Level design/editing/saving questions
I thought about making a simple 2D Sidescroller game like SuperMario. Then i wondered about how to save, load or create the levels for the game. The first thing i thought of was drawing a simple blocky png which represents the level, an making all the parts where the player can walk a special color (maybe lilac). I would import the level in blocks or tiles so i could check for collision.

so my questions are:
are there better methods for this?
what are the professional methods for this?
should i do this with Tiles and a Map editor based on tiles? (for some reason i dont like this, but i guess if its the best method i would use it)
with a tile based level, how would you realize slopes, and how would you check them for collisions?

# Answer
For an 2D MMO we use http://www.mapeditor.org/. We use several layers for background, background decoration, objects on the same level as the players and objects in front of the player. And an additional layer with just one red square to mark collisions.

I am not sure if this appoach or the software works out for an 2D side scroller but it may be worth to have a look at it.
> 10 votes

# Answer
A common way could be to just a string for example

0,0,0,0,0,0,1,1,1,0,0,0,2

where 0 would be a block you can walk on 1 could be spikes and 2 could be the finish line

you would simply read this in through a text file (or have it hardcoded into the game) and draw the relative block that is associated to the number and have your colision logic to handle however it is setup.

Obviously you can choose whatever format you want and perhaps 0 means draw 5 walkable blocks.

This is just one way it could be achieved.

http://www.smudgedcat.com/tut\_tiledlevel.html this link is of an example within c# using the XNA framework. it will give you a rough idea (it does NOT contain slopes, but a similar thing could be used to define this type of case)

Regards Mark
> 6 votes

# Answer
**A lot of games use an open source application called Mappy.** It has its own format that supports multiple layers and other features. You probably want to associate several types of data with a given tile.

---

**I think the in-game level editor approach is very common.** Developer Mode is an inside account of how the levels for a very popular game, Braid, were designed. The game has a development mode where levels can be constructed/modified. The levels themselves have a collision layer covered up with graphical tiles:

---

And I personally don't recommend it, but **a 2D demo program for Allegro used some type of 3D modeling format and converted it to a custom in-game format.** The advantage was it could model very smooth, continuous surfaces. (It was a 2D physics-based skate boarding game.)

> To edit the level data of the Allegro demo game, we use the free and open source tool Blender. You can obtain it here:
>
> http://blender.org
>
> Here are step by step instructions how it works:
>
> 1) Place the file ademo\_export.py into your Blender scripts folder. It is the export script which will convert from .blend format to the .txt format used by the demo game. Under unix, the path will be:
>
> ~/.blender/scripts/ademo\_export.py
>
> 2) Load the .blend file blender. Under unix, type this from the directory with the level.blend file:
>
> blender -w level.blend
>
> (The -w is to use windowed modes, which I prefer.)
>
> 3) Edit the level. In the menu, under
>
> Help -\> Scripts Help Browser -\> Export -\> Allegro Demo Game Level
>
> you will find some useful tips.
>
> 4) Save the file (use compression before committing). Export it as .txt from the export menu, choosing Allegro Demo Game Level.
>
> 5) Update level.dat using level.txt, the new level should appear in the game.
> 5 votes

# Answer
The 'professional' methods would probably involve a very detailed map editor, probably in C#, which would give them full control over everything.

There are two main approaches; one is easier to do, but not as effective.

* You could use a map editor; either writing your own or finding a pre-existing one such as mapeditor which nhnb mentioned. Writing your own would be good for a learning experience, but not so much for a finished product.
* You could just type data into a text file. This is simpler, but it's not easy to read again. You could probably get the same from the map editor, but that would be automated. The downside again of this is that you can't add any special effects such as certain tiles (not tile **types**, but tile (13,45) for example) to do special things.
> 2 votes

# Answer
I've had similar thoughts( ie get back into writing games a hobby - job and other commitments...)

I'd seriously consider the route of developing the 'Map Editor' as part of the game/application.

If your game ever gets beyond your own PC then Community Content would be great boon.
> 2 votes

---
Tags: 2d, collision-detection, level-design, tiles, maps
---


# Question
Title: What is some good examples about creating 2D fluids?
Anyone have any good examples, tutorials, or snippets to share that preferably in C# or C/C++?

# Answer
PixelJunk shooter from Q-Games has nice set of fluids. There is a GDC paper they have published here: http://fumufumu.q-games.com/gdc2010/shooterGDC.pdf (PDF!)

Jos Stam from Alias Maya fame (now Autodesk) wrote paper on real time fluids in games here: http://www.dgp.toronto.edu/people/stam/reality/Research/pdf/GDC03.pdf (PDF!)

And he wrote a simple FFT fluid solver here: http://www.dgp.toronto.edu/people/stam/reality/Research/pdf/jgt01.pdf (PDF!) where he included source in that PDF at the end.
> 9 votes

# Answer
http://cowboyprogramming.com/2008/04/01/practical-fluid-mechanics/
> 5 votes

# Answer
* Practical Fluid Mechanics
    + Very detailed explanation with C++ code and pre-compiled binary. You can interact with the demo, like creating new smoke and stirring the smoke with your mouse. The image is a capture of the demo. Lists several on-line references at the end, as well.
* Stable Fluids \[PDF\]
    + I think the author, Jos Stam, is the expert when it comes to fluid dynamics. 75 page summary of his research.
* Chapter 38. Fast Fluid Dynamics Simulation on the GPU
    + More technical and math-heavy then the Cowboy Programming Practical Fluid Mechanics. Also lists several off-line resources at the end.
* A Fire and Smoke Simulation for Mobile Game \[PDF\]
    + The weakest resource of the bunch, but I still found it worth bookmarking...
> 5 votes

# Answer
Here's a fairly primitive write up about using cellular automata for simulating fluids: http://w-shadow.com/blog/2009/09/01/simple-fluid-simulation/

In certain situations such a simple approach can be appropriate (Dwarf Fortress uses a similar approach to simulate liquid flow; also - the powder game). Also, this approach is pretty easy to grasp/get up and running fast.
> 4 votes

---
Tags: 2d, simulations
---


# Question
Title: How can I write a trigger to detect when a terran building burns to its death? (Starcraft 2)
I'm working with Starcraft 2 Map Editor, and am having a little bit of a trigger problem.

It's quite easy to detect when a specific unit kills a structure (simply check if triggering unit == whatever) but I'm not quite sure how to tell when a building dies to to either fire (terran buildings) or bleeding out (zerg buildings when off creep).

What condition should I be looking for in my "a unit dies" trigger to see if one of those two situations occured?

PS: Sorry for lack of available tags!

# Answer
There is a behavior for Terran buildings that applies the burning effect periodically if the building's health is below 1/3. To see if a building is killed by this effect, you could do this:

```
Events
    Unit - Any Unit takes Fatal Any damage (from Any effects)
Local Variables
Conditions
    (Damaging effect) == BurndownDamage (Unnamed)
    (Unit type of (Triggering unit)) == <building>

```

Edit: I forgot the zerg building part, but it's exactly the same but with a different effect:

```
    (Damaging effect) == ZergBuildingNotOnCreepDamage (Unnamed)

```
> 4 votes

# Answer
I've been poking around. I've determined that every terran building has an effect "Terran Burn Down" or some such, that I assume is what is actually causing the damage.

I'm not sure of the specifics, exactly, but I imagine one of two things should be possible:

* The building counts as its own killer (because its death is related to an effect it 'owns')
* The death can be tracked by attributing it to the effect, something along the lines of "Unit dies" Condition: Killing Effect == Terran Burn Down.

I imagine the zerg buildings have a similar 'requires creep' ability.

I'll keep investigating and keep this open in case someone can provide a fuller answer.
> 1 votes

---
Tags: scripting, modding, starcraft-2
---


# Question
Title: What is the right process to get compatibility or at least a workaround for the ‘Threaded optimization’ feature of NVIDIA?
It's peculiar this issue is not well understood on NVIDIA forums and project forums.

For example, the well known ioquake3 project based on id tech 3 requires to force 'Threaded optimization' off on the NVIDIA settings or there are severe FPS drops.

Do you know what a programmer has to do to acquire compatibility with the feature or at least a workaround to not get issues with it (e.g. turning it off explicitly via the application or other means)?

--

The main importance is that such projects get issues with it by default since not all users know they have to explicitly turn off the feature.

# Answer
> 3 votes
My understanding is that most programs won't have a problem with the feature, which essentially just allows the graphics driver to use an additional thread on multi-cpu systems. It doesn't do anything particularly special, it's just a normal windows thread. This will generally bring a flat increase in FPS.

It can be a problem if something gets in the way of the driver thread by disrupting the windows task scheduler. From looking around it seems like two cases are the primary cause of problems with threaded optimization:

1. Dealing with the windows message system on multiple threads at once or in a particularly weird way. This can disrupt windows's thread scheduling.
2. Manually adjusting thread priorities. If you're trying to micromanage thread priorities this can cause a higher priority thread to pop up at a bad time for the driver thread, causing some expensive context switching.

---
Tags: opengl, 3d, optimization, multithreading
---


# Question
Title: How can I make a good-looking explosion particle effect?
I'm not much of an artist, but I'm trying to make decent particle effects in a 2.5D game. I'm making a replica of Wii Play's "Tanks" and I can't quite get the explosions to look good. I'm not going for the exact style as they had, probably something more realistic, less childish.

My particle engine just draws a 2d texture on the screen, and supports, per particle: starting position, velocity, gravity (or any acceleration), air resistance (drag), color including alpha, starting size, size expansion rate, lifetime, and fade out rate.

In my tank explosions, I'm drawing around 100 particles, and I've been tweaking parameters for days trying to get things looking good. So I'm wondering, what are some tips for getting good results? What's most important, specifically for explosions?

* Having good quality textures?
* Having a variety of textures?
* The right colors?
* Realistic movement of the particles?
* Having lots and lots of particles, many more than 100?

Check out this image. I tried to replicate it by making particles that shoot out and create more particles in their wake. But mine still isn't anything like that.

# Answer
> 6 votes
For explosions in particular it's very important to get the blending right. One very important element is the use of pre-multiplied alpha. Quoted from the link:

> What if you want a single particle system that has additive flame particles turning into sooty lerping particles as they age? You can't change renderstate in the middle of a particle system, that's silly. Who can help us now? Why - it's Premultiplied Alpha Man - thank god you're here!
>
> So you can have particles change from additive to lerp as they get older - all you do is change the alpha value from 0 and the texture colour from a firey red/yellow colour towards an alpha of 1 and a dark sooty colour.

# Answer
> 3 votes
A huge volume of particles isn't necessary. What will help you the most is having each particle blend between a series of textures over time. So, have it start as a small bright ball, expand to a bigger orange flare, then to a light gray smoky patch, which then transitions to a smaller darker fading spot of smoke.

Even blending between a couple of textures will make a *huge* difference in how your particles look.

# Answer
> 3 votes
If you have a good looking particle system then you can consider to use some kind of spherical billboard implementation to remove the annoying cutting and popping artifacts.

You can found an example at http://www.iit.bme.hu/~szirmay/firesmoke.pdf.

---
Tags: graphics, textures, particles
---


title: Solids as high viscocity Liquids

text:
# Question
Title: Solids as high viscocity Liquids
A friend of mine and I were discussing different idea for allow materials in a world to be destroyed in a very piecemeal fashion and he proposed the idea of representing solids as very viscious fluids. My intuition is that this would be either: A) very difficult, or B) very resource intensive, but I am unsure.

Is such a model feasible for an RPG/adventure rpg/fps?

edit:clarification: The idea is for collisions and objects breaking to be handled by this system. To basically allow any object handled this way to be destructable instead of having scripted destroyable objects.

# Answer
FastLSM is sorta like what you're after.

Alec has also made 2D game engine based on deforming lattice (instead of voxels as in FastLSM). It's called Physical. Look at the demo asteroids style game to see what can be done and the performance.

Alec also built a full game using physical called Sopwith IV.

I never played Sopwith IV, but I spent plenty of time playing with the asteroids demo.

One of the key features that make it fun is, everything is destructible. Including you own ship. It's hilarious when you snap off on one rocket, but can still control it.
> 9 votes

# Answer
Glasses are basically that: matter arranged amorphously, that is without an order (a hallmark of a liquid) but with the molecules unable to move very far from their initial positions (very very high viscosity). If it works in real life, there's no reason it can't work in a simulation.

However you have to understand that when I say very very high viscosity, I mean very very very high viscosity. To contrast, water has a viscosity of 0.01 poise. The glass transition occurs (by definition) at 10^13 poise. That is a viscosity that is 15 orders of magnitude (a quadrillion times) higher than what we expect for a regular liquid. The expected motion of said liquid during the duration of the game will be pretty much exactly zero.

Well, that's just perfect! If the liquid does not move, we do not have to simulate it! We can just fill our liquid grid volumes and be done with it. Congratulations, you have just re-invented voxel rendering!

It's an excellent choice for destructible geometry if you can spare the horsepower.
> 4 votes

# Answer
This sort of makes me think about Soft Body Dynamics, but they would never return to their original form?
> 1 votes

---
Tags: physics, algorithm, graphics-programming
---


# Question
Title: In Box2dFlash my b2body gets detached from my Sprite after I use setXForm()
I have a scenario where I have red coin in a Carrom board game which should be moved outside of the visible window when it is pocketed, also if any coin either white or black is not pocketed in the next shot, the red coin should be replaced in the center of the board.

Now my problem is WHEN I apply the setXForm() method to move the b2body of the red coin outside of the visible area of my flash window.It moves,there is no problem in moving the body,but WHEN i replace the b2body and sprite after the event of no coin falling , the b2body is detached and works as a separate entity having no connection with the sprite of the red coin.

I'm not getting a clue as to what is happening, that is why I thought I'd try posting this here.

# Answer
Do you destroy the unused body? They are not automatically destroyed if the sprite that "owns" it is removed (precisely because it doesn't own it at all, the Box2D world does).
> 0 votes

# Answer
I don't know anything about the flash port, but is it possible that you are using an older version of box2d (or the port is from an older version) and you moving the b2body outside of the range of the b2World?

If I remember correctly, you had to specify min/max coordinates for the world, and if anything went outside this range it was no longer simulated. I'm not sure what happened at this point if you changed their position back into the world.
> 0 votes

---
Tags: flash, box2d, flash-develop
---


# Question
Title: Tips / pitfalls in selecting and working with publishers?
I am thinking about working with a publisher for an iPhone game that I have developed. I have been independent until now, but want to look into the publishing route because I just don't have the resources to market the game myself, and I would rather not take outside investment.

So, those of you who have gone this route, what should I be looking for in a publisher? What should I avoid?

# Answer
You mention that you're looking for a publisher primarily for marketing (rather than funding) your iPhone game, so if I understand correctly, you're looking at companies such as Chillingo (if I recall correctly, they'll take finished titles and expose them to hungry gamers).

We've worked with publishers such as Steam, D2D, and OnLive, all of which have been really great for us as indies. Here are some rules-of-thumb that have helped us navigate that:

* **Contracts:** We always, always, always, get a lawyer to review the publishing contract. Sometimes, this is a formal, lengthy back-and-forth process, but in the past, we've even relied on family friends (who were lawyers) for a simple review that turned up things we'd missed. And if a publisher refuses to sign a contract to which we've made reasonable changes, we run away.
* **Audience:** We do better if our publisher's audience is aligned with our own. This seems a no-brainer, but we didn't realize how pronounced the effect would be. We thought we'd sell (perhaps) twice as many units on one platform as on another. That discrepancy turned out to be two or three orders of magnitude.
* **PR:** A good publisher will get your game in front of as many (receptive) eyes as possible. Still, we get good results by doing some of the PR push, ourselves. No other company loves our games as much as ours does; and no other company is as invested in seeing them do well! To wit, we'll go above and beyond what publishers do. For example, if they're pushing our game primarily to their existing customers, we'll hit the press with a humble press release ourselves.
* **Making Friends:** Small game development studios tend to help each other out, so if we have questions about a publisher, we'll talk to other groups they've worked with. Cold calls work here! These studios can't say everything, as they'll be bound by a nondisclosure agreement, but "We love this publisher!" or "Beware!" goes a long way.

Good luck!
> 12 votes

---
Tags: publishing
---


title: A list of game mechanics

text:
# Question
Title: A list of game mechanics
I'm trying to compile a list of **game mechanics**, by which I mean high-level/meta game mechanics like Cooperation, Resource Management, Chance and Time Manipulation rather than low level mechanics like running, jumping climbing ladders, etc

Does any one have any suggestions or can point me to good existing lists? My WIP list is already proving to be quite useful to me in the way I think about games.

# Answer
> 13 votes
Something like the Three Hundred Mechanics page at squidi.net?

# Answer
> 8 votes
There's a book called Patterns in Game Design that is more or less exactly what you're looking for: http://www.amazon.com/Patterns-Game-Design-Development/dp/1584503548

I'll warn you of a few things. First, a lot of the mechanics in that book didn't have names, so the authors invented them, so sometimes the terminology can get confusing. Second, the list is large, and while there are links between related concepts, it's still a lot to take in. Third, about half of the mechanics are on an included CD-ROM rather than in the book itself, with lots of cross-referencing between the two, so looking up a chain of terms can sometimes take you back and forth from one to the other.

Admittedly, these are all issues you'd probably run into on your own once your list got to be a certain size, anyway.

# Answer
> 2 votes
I can't for the life of me find it at this moment (don't help that my computer fails to open pdf's at the moment), but I know there's a wiki out there what has a significant list of them. The keyword you're looking for is "Taxonomy".
Googling +taxonomy +videogames should definitely give you some leads.
Sorry for not being of more help, lost all my bookmarks.

---
Tags: game-mechanics
---


# Question
Title: Sending a struct containing a string over network
I'm trying to send structs as neatly sorted packets using iPhone Game Kit..

I have a struct which looks like:

```
typedef struct {
   int coolStuff;
   char playerID[100];
} MyStruct;

```

Then I'm using strncpy() to copy the NSString I want into MyStruct.playerID. However, I would like to be able to send a playerID (string) of any size and possibly multiple strings per struct. Any suggestions?

There is a chance I'm making this more difficult than it actually is..

# Answer
> 8 votes
Google's Protocol Buffers is a project designed to help with this kind of thing. Makes it somewhat easy to move structs around between memory, network, disk, et al.

# Answer
> 4 votes
The fundamental thing you need to do is just have code on one side that knows how to serialize data, and code on the other that knows how to deserialize.

So, for variable length strings, just send the length first:

```
   n = strlen(playerid) + 1; // for NULL terminator
   sendto(server_sock,&n,sizeof(n),0,0,0);
   sendto(server_sock,playerid,n,0,0,0);

```

and then on the receiving side get the length, and read that many bytes.:

```
   int n;
   char *s;
   recvfrom(client_sock,&n,sizeof(n),0,0,0);
   s = malloc(n)
   recvfrom(client_sock,s,n,0,0,0)

```

Of course, what you should really do is gather up your communication into packets, and then send blocks of data at once with headers, have type info in a debug mode for safety, etc. but that's the gist of it.

Google protocol buffers look like they are a way of turning data into something serializable, so in that version of this example send and recv would be an XML string, which is great for general servers, but you may want more explicit control.

---
Tags: c++, networking, objective-c, c
---


title: Game clock Synchronization in python

text:
# Question
Title: Game clock Synchronization in python
I am working on a network game project in python which we want to keep synchronized. I would assume we should use Network Time Protocol to cater for different levels of lag.

That being the case, is there an implementation for Network Time Protocol in python?

# Answer
You probably won't be able to use NTP directly -- for one, you need to have a server that is guaranteed to be available to all of your clients. Second, it's really overkill for what you need. What you want to really do is come up with some sort of common time stamp that all of the clients can agree on.

Based on the method from http://www.mine-control.com/zack/timesync/timesync.html, here is what I would do (modified slightly):

> 1. Client stamps current local time on a "time request" packet and sends to server
> 2. Upon receipt by server, server stamps server-time and returns
> 3. Upon receipt by client, client subtracts current time from sent time and divides by two to compute latency. It subtracts current time from server time to determine client-server time delta and adds in the half-latency to get the correct clock delta. (So far this algothim is very similar to SNTP)
> 4. The client repeats steps 1 through 3 five or more times, pausing a few seconds each time. Other traffic may be allowed in the interim, but should be minimized for best results The results of the packet receipts are accumulated and sorted in lowest-latency to highest-latency order. The median latency is determined by picking the mid-point sample from this ordered list.
> 5. All samples above approximately 1 standard-deviation from the median are discarded and the remaining samples are averaged using an arithmetic mean.

The only difference is that you shouldn't try to set the system time -- most users would consider this to be bad behavior and besides, it's most likely something that would require admin privileges and your game shouldn't need to do anything that requires admin privileges.

I would probably add that you should do some time synchronization periodically within the game as well, especially if it's been going on for a while. You should be able to find a point in the game where the action isn't as heavy and it's a good time to sync.

Alternatively, you could time stamp all packets from the client and the server and build your time synchronization code so that any packet can be used to determine the current latency and what the common game clock should be.
> 7 votes

# Answer
You didn't mention if a single server was an authority or not, but have a single time that every client syncs off of.

In my experience with City of Heroes, latency can be streaky, so a running average (root mean square is easy) is a good way to approximate. We also timestamp all roundtrips as part of the packet header.

Truth be told, since the cases that throw things off aren't predictable, there isn't much you can do when the hiccups come your way, and otherwise things are pretty smooth, so I wouldn't put too much effort into it.
> 4 votes

---
Tags: networking, synchronization, python
---


title: User definable keys for a flash game

text:
# Question
Title: User definable keys for a flash game
What is the best method for creating user definable or user changeable keys in a flash game?

Edit: I meant, user changeable keys. Not user changeable flash buttons. Why would a user need to change the graphic of a button in a game?

# Answer
> 3 votes
I'll answer the second question, "Why would a user need to change the graphic of a button in a game?" I think it would be an awesome idea to have a game like Upgrade Complete that is focused around the user customizing and upgrading the UI. Maybe the game has a set of undifferentiated buttons, and the player has to label and customize them so that she can figure out and remember what they do?

As for custom keys? Capture their keycodes and store them, then test against those keycodes in the input logic. You'll have some sort of options screen where you can set the custom keycodes, then use the settings in the game proper instead of using constants or magic numbers for your action buttons.

The trickiest part, oddly, is displaying the custom keys' names to the user. As far as I can recall, Flash doesn't have a lookup table matching keycodes with key labels. I'm guessing you'd need to create a dictionary yourself with the most important keys, and then just refer to any special cases as something like KEY\_1876.

# Answer
> 1 votes
Use the library I created, Gamepad.

# Answer
> 0 votes
You could create a class that extends Sprite or MovieClip that it's inputs are the height, width, x, y and action (function), and create a new instance of that class each time a user wants to create a new button.

---
Tags: flash, actionscript-3
---


title: Methods to 'cull check' polys in OpenGL

text:
# Question
Title: Methods to 'cull check' polys in OpenGL
A quick search through the web suggests there's quite a few methods of potentially detecting back-culled faces on the CPU.

The purpose of the check is to evaluate whether to performing other operations such as tessellations is reasonable by dynamically altering the LOD of visible polys based on the number of polys on the screen.

What would your suggestions be for implementing this? Speed isn't necessarily the greatest concern - for this prototype mathematical simplicity is more important. Code snippets welcome :-)

Edit: It seems obvious to me to calculate the dot product based on the camera's viewing vector in world-space against the surface normal vector - but I'm asking this question because I'm intrigued as to why everyone and their (programming genius) dog seems to have an alternative method of handling this.

# Answer
> 6 votes
dot(CameraViewInv.at, SurfaceNormal) can return \> 0.0 even if the the surface is visible. Think of a box whose right side normal is slightly away from the camera - as it's moved to the left of the frustum, it can become visible.

What avoids this phenomenon is dot(VecFromCameraToSurface, SurfaceNormal).

Another way is to check the winding of your screen-space vertices (ie. vertices after model, view and projection transform). This is done by checking the sign of the z component of the cross product of two edges on the screen space triangle (or quad). Code is here (not OpenGL specific):

```
// culls CW verts, passes CCW verts. Invert the condition for opposite behavior.
bool shouldCullTriangleScreenSpace(vec2 points[3])
{
  edgeA = points[1] - points[0];
  edgeB = points[2] - points[0];
  return (edgeA.x * edgeB.y - edgeA.y * edgeB.x) < 0.0;
}

```

EDIT: I just wanted to mention an extension to the dot(VecFromCameraToSurface, SurfaceNormal) technique that takes into account post-tessellation extrusion.

The idea is to precompute some metadata for the patch from the range of post-tessellation normals. First generate an average normal for the patch, and figure out the maximum angle of deviation for all normals on the patch from that normal.

This can be done like this at precalculation time:

```
  void getConeAngleForPatch(Patch p, vec3& coneDir, float& cosConeAngle)
  {
    // compute cone direction (average of all normals in the post-tessellation patch)
    vec3 coneDir = 0;
    foreach normal N generated by p
      coneDir += N
    normalize(coneDir);
    // calculate the cos of the maximum angle between normals N and coneDir
    cosConeAngle = 1.0;
    foreach normal N generated by p
      cosConeAngle = min(cosConeAngle, dot(N, coneDir));
  }

```

Then your patch backface culling trick in the shader becomes:

```
  dot(UnitVecFromCameraToSurface, coneDir) < -cosConeAngle

```

...instead of:

```
  dot(UnitVecFromCameraToSurface, SurfaceNormal) < 0

```

# Answer
> 1 votes
You can just check to see if your worldspace camera position is on the negative half-space of the the plane of the triangle you are considering (dot product of Normal and camera position and then a comparison to the plane constant).

This can be done hierarchically to be efficient i.e., you group triangle with similar normals together - effectively the normals all fall within some reasonably small cone. Then a test against this cone (effectively a dot product with a more conservative constant), can reject or accept many triangles at once.

In general, it is best to let the hardware do it - the overhead of dynamically altering your index or vertex buffers (when non-indexed) and the coding effort required likely isn't worth it.

Note that in your tessellation example, even if the pre-tessellated triangle or quad is invisible a tessellated AND displaced mesh may still have front facing triangles, so be careful. :-)

---
Tags: opengl, mathematics, culling
---


# Question
Title: What's the preferred way to put music in a java applet?
Is there an easy way to put music in a java applet? Preferably streaming so that it doesn't need to be preloaded.

# Answer
> 1 votes
You might try something like this, though as the author said he didn't stream so it stuttered. You'd want to preload a certain amount of the sound before feeding it to the Line.

# Answer
> 1 votes
This site may help you, it contains a lot of examples of how to use the Java sound API (loading, playing, streaming, recording...).

---
Tags: java, music
---


# Question
Title: How can I tell how much video card memory I'm using?
I want to programmatically determine at runtime how much video card memory is being used by my program. Specifically I'm wondering about how to do it on a Windows machine using OpenGL, but am interested of ways to do it on other platforms as well.

I know there are utilities out there that will show me the memory usage as my program is running, but I want to be able to query that information from my code.

# Answer
> 14 votes
You can find the video memory of an Nvidia card using the NVX\_gpu\_memory\_info extension, or an ATI card using ATI\_meminfo. Here is a snippet of code I found which might get you started.

---

However, Paul Nettle at flipcode wonders why one would want to find the available video memory, saying:

> The reason it's difficult (and sometimes impossible) to determine the amount of video memory is very similar to the reasons why OpenGL won't let you lock the frame buffer and access it directly.

And goes on to explain, in essence, that **an "amount of video memory" might not actually mean anything**. I concur with him on the reasoning that, for example, the amount of "free" memory in a Windows Vista/7 machine is irrelevant; hopefully there is no free memory, because free memory is wasted memory. But there is always some areas of memory dedicated to caches which are cleared by Windows, should an application need them.

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