title: Where is XNA headed?

text:
# Question
Title: Where is XNA headed?
I love XNA. I really do. As president of the Game Development Club at my school, we use it and I teach it. But I'm worried about it.

I've always wondered, are there any signs that XNA will ever become more than just a prototyping/arcade game language? I've always gotten the feeling that Microsoft is on the cusp of abandoning it, like they did Managed DirectX. The Xbox Live Arcade is an amazing idea but it's shoved off to the side, well overshadowed by the "real" Xbox games when I feel like it would've had so much more potential, had Microsoft given it more emphasis.

Now with XNA 4.0 CTP for Windows Phone 7 only, it seems to be morphing into some sort of phone-only thing. I'm really unsure about exactly why they are doing that.

What's the current state of XNA, and where is it headed? Is it going into mobile-only, or will 4.0 eventually be released for Xbox and desktop usage?

In other words, **is it a language to invest time and money into, or should it be only tentatively developed on, with the constant fear of abandonment?** *And when I ask this, I'm talking about desktop and Xbox games, as I can pretty clearly see that it is the game framework of choice for the Windows Phone 7 platform.*

Since this question is somewhat subjective (but I'm really looking for facts alongside your opinions!) I am making this a CW.

# Answer
> 2 votes
The feel i get from development of XNA is that they're eventually maneuvering it to be the replacement to Managed DirectX. As far as the phone features, that's simply because they're rigging XNA to support Windows Phone 7 (or whatever it's called). They did a similar thing with 3.0 (or was it 3.1?) and the Zune/Zune HD. **Overall, i think these mobile devices are just temporary features of the platform and will fade away at some point, while they continue to improve the core of XNA.**

Additional evidence is that XNA is being used more to develop high quality works (such as Sol Survivor).

# Answer
> 7 votes
The XNA 4.0 Beta allows you to target both Windows and the 360 under the Hidef profile. Given that the tools are still in beta, though, deployments to the Xbox 360 are not yet enabled.

I think the investment and promotion of XNA on the Windows Phone platform shows a firm level of commitment. At the very least, WP7 will have a slew of XNA-based applications, which will require supporting XNA for a long time.

As earok mentioned, a lot of the breaking changes involved in the 4.0 release are done in the interest of preparing XNA for the future.

# Answer
> 3 votes
For XBOX 360 is your only choice.

For windows I always recommended people to use something else... There are much better options, specially those that work on other platforms than windows (like, work in most of important PC OSes...)

Also Microsoft still act in any way that they think will give them some more money, even if it is bad in the long run or "looks bad", like their behavior with Direct Input (they made the XBOX 360 controller work like crap on Direct Input, declared DI deprecated, and invented XInput, that supports ONLY the 360 controller, and in general has WAAAY less features than DI, it is sorta obvious that MS did that only to sell more 360 controllers on Windows, specially because they are insanely expensive)

# Answer
> 2 votes
The XNA 4.0 CTP (now superseded by the Beta) is available for Windows development, I have been using it to work on a Windows game project. I think it's just that it isn't "Officially supported" for anything other than Windows 7 Phone development.

I don't see any reason why Microsoft would even consider abandoning it in the short term, Shawn Hargraves mentions on his blog that they're doing a lot of work on this version to future proof it for DirectX 10 and 11.

---
Tags: xna
---


title: Do we need tutorials?

text:
# Question
Title: Do we need tutorials?
Children learn through play, which by it's core nature is subversive. In digital games we can enforce and feedback any arbitrary rules and do not require "conceptual rules" like don't step outside the white lines.

Have we started using tutorials as a crutch rather than keeping our mechanics consistent and self-explanatory?

> So I was listening to Another Castle interview the extremly interesting Eric Zimmerman. They were talking about the subverssive nature of play when my brain started drifting to tutorials, thinking about Limbo. Then I realised that not once on Glo did we ask, do we need tutorials?
>
> Now I know the indie and art games scene has been promoting this concept of subversive play for a long time but I ask you how many developers question the need for a tutorial?
>
> \- Blog Post

# Answer
> 8 votes
The unmentioned assertion here is that tutorials are bad and not fun. Can we explain our game concepts to the player in a fun way?

To give two competing examples, the Halo tutorial was excellent, and famously selected your axis inversion for you by just watching what you did when asked to "look up." Conversely, I've recently played a cricket game whose tutorial was a sequence of text screens and actions to parrot, with little or no context.

Any tutorial should pass two requirements: the player shouldn't have to pick up the manual at any point in the game, and the player should have their immersion compromised as little as possible. If you can do these, I see no reason why you shouldn't have a tutorial.

# Answer
> 6 votes
By contrast, the game "Portal" is essentially a giant tutorial that teaches you how to beat it as you go. There is no "tutorial level"... rather, every level is at least part tutorial. Great game, very popular. So, to say "we need fewer tutorials" I think is an overgeneralization; there are many paths to making a good game here.

If the question amounts to "should I make a tutorial in my game" the answer is: it depends on the game!

# Answer
> 4 votes
> Children learn through play, which by it's core nature is subversive.

Both assertions there seem questionable to me. Play is one way we learn but the only way? And why is it subversive?

> I explore the question in depth here on my blog

Not sure if this is just an attempt to drive traffic to your site, but I will give my two cents. Whenever I have made a game (casual Flash game) and start to get feedback from the larger public the first thing I hear is "We want instructions".

I find not having instructions will probably take 1-2 points off my game's rating (out of 10). Even for something like a minigolf game where the user only ever has a single operation he can perform and has the same goal across each level.

> Have we started using tutorials as a crutch rather than keeping our mechanics consistent and self-explanatory?

Is it really reasonable to strive for "self explanatory" game mechanics? Should Modern Warfare 2 be self explanatory? It seems to me that it would take someone new to games an incredibly long time to learn the ins and outs for a complex FPS.

For a complex game, instead of striving for simplicity or obviousness I would instead focus on employing progressive disclosure so that users gradually are introduced to more complexity. This is a tried and true method and lets you stagger instructions across the entire game.

# Answer
> 2 votes
This is a good question. I would say that it really depends on the game; some games are complex by nature and thus need tutorials for people to effectively learn (see Dwarf Fortress, AI War, some RTS games), while others contain no tutorials and would be spoiled by them (see most adventure games, arcade games, some RPGs).

---
Tags: game-design
---


# Question
Title: I love game development books but they're so expensive!
What means do you use to get your game dev book fix? Do you pony up the big bucks for the thick books, or do you budget yourself and buy one at a time, or do you rent or limit yourself only to your library? Do you prefer to read them on your eBook reader?

**How do you obtain your game development books?**

# Answer
> 9 votes
**Inter-Library Loan** \- you're not just limited to your local library system, but they can get almost any book from any other library (in the US anyway). It's not as good as owning a given book, granted, but at least you can read it, get the information (maybe decide if it's *worth* buying).

# Answer
> 4 votes
Safari Books Online has a pretty good selection. Only 22.99/month gives you access to read 10 books and preview every book they have.

http://my.safaribooksonline.com/

# Answer
> 2 votes
For *development* books it has been pretty rare that I've found the dead tree form more useful than other internet resources. Design books are trickier, but those are usually less of a reference and more of a read-front-to-back kind of book (which are easier to resist since my book queue is far too big already).

Then again, now that this Stack Exchange is up, you can always just ask those kinds of questions here, right? ;-)

# Answer
> 2 votes
I work as a professional game developer which finally earns me enough money to buy the books.

I also recommend working as a surgeon in order to be able to afford books on anatomy. ;)

# Answer
> 2 votes
I usually buy from Amazon or one of their used book associates. For some reason, I have a hard time reading a PDF versus a real book when it comes to learning new material.

A lot of the books on amazon have used options at significant discount. Unfortunately, many of the new or hot books won't be much cheaper (e.g. Game Programming Gems). Most of the books I buy aren't game-specific, though, and some are old. The Fowler/Beck Refactoring book, for example, is $53 new and $25 used. Smalltalk 80: The Language is $36 new and .. $5 used (haha).

But you never know what you might find. Real Time Rendering 2nd edition hardcover is $55 new and $12 used. Good book, nice price.

# Answer
> 2 votes
I buy all of them.

I don't find most of them expensive, but that's subjective. Also, cheaper doesn't mean less valuable and I'm not a fan of the Programming Wisdom books, since they are expensive even to my mind because only little of each book is of any use to me.

Before purchase, I check if the information is readily available on the Internet and try to figure out what the book might be revealing which isn't readily available. If I buy a book I'm always thinking that, compared to alternative learning solutions like University or Seminars, books are comparably cheap. And the value it adds to my knowledge base over time can't even be expressed in money.

In over 15 years I've spent about $5,000 on educational and programming books. If I hadn't done so, I might not be here, I might not have had the great jobs I had. That's how I look at it. Money is a short term thing you best invest into yourself. Books are a very cheap way to learn from experts in their fields.

---
Tags: books
---


# Question
Title: Why do most games require you to patch them after downloading, instead of rolling the patches into the installer?
When I download a video game from the publisher's website, it typically needs to update itself several times before I can play it. Why can't the developer simply put the patched version of the game up for download? I assume there must be technical problems with this, but what are they?

# Answer
> 4 votes
A few reasons that I can think of off the top of my head -- I'm sure others will have reasons as well.

1. They have to distribute patches for the existing users no matter what. By doing it this way, they minimize the amount of work they have to do on their end.
2. Building new complete distributions takes a lot of time -- especially QA time. They would have to make sure the new build didn't have any bugs in it, essentially repeating what testing they are doing with the patch build.
3. If they did a complete version, they would have to deal with people downloading the complete game again instead of the patch, which would mean more bandwidth usage. Perhaps they have mirror sites -- if the game is large, they would potentially have a bunch of mirrors downloading the new content just because it's new. Patch files are typically smaller, so the burden of having a bunch of mirrors download them is smaller.

# Answer
> 3 votes
As Dennis said, it's mostly reason #2. It takes a lot of time and effort to create a new distribution version, and this is a seperate process from creating the patch version. Creating patches is simply faster and needs to be done anyway.

But even more so, once you have had several complete versions of the product available for download, each new patch must be tested against each full download version in some cases. For a developer/publisher it is much better from a support point of view to have everyone download v1.0 full, then apply each individual patch successively. Because that's the process that must work for everyone.

# Answer
> 0 votes
There's also the issue of people having to change settings to get a game to work (on PC) and the installwr might obliterate though. To make the installer fully 're-entrant' where it leaves the right stuff intact yet cleans up the traces it should clean up imposes even more QA and user support risk. Plus indeed, bandwidth and user annoyance.

---
Tags: distribution
---


# Question
Title: Multi-disciplined: Strength or Weakness?
My last two credited titles I was Lead Programmer then moved to Lead Design role. At my current company I kinda switch between design and programming hats quite often.

The bulk of my education is in programming and my experience is pretty broad. I honestly can't pick which I prefer, and if I focused then I think I would do the other in my spare time. My colleagues consider me capable in both roles.

I'm currently looking for opportunities, some at larger companies, and often people seem to be thrown by my dual role. I feel like it may be damaging my chances in some cases, because they can't easily fit me into the company.

Should I just pick one and focus or is it viable to continue wearing my two hats?

# Answer
> 8 votes
You may want to set up two resumes, with slightly different focuses. Hiring managers, specifically, will HAVE to know what you are and will get very confused if you say you can do both. They will assume you know neither and fail to call you back. But, you can set up a programming resume and a design resume, mentioning the other discipline but customizing the skills list and focus for one discipline. You can say something like "I'm applying for the gameplay programmer position but am available for other opportunities as well" or even apply twice.

In reality the difference between a "gameplay programmer" and a "technical designer" is essentially 0 once you're working, but they probably go through slightly different hiring processes. Both sound like they would work for you, and both actual jobs would end up using both halves of your background.

I can tell you from personal experience that if you claim to like doing two things equally well, the person interviewing you will just get confused. Confused interviews do not equal successful interviews.

# Answer
> 10 votes
Smaller companies will generally want you to try and wear as many hats as you can. However usually larger companies will just want you to stick to what you do best. It's your call really but you should take into account where you want to head.

# Answer
> 4 votes
Tailor your resume towards the job you're applying to. (This goes even for those of us who are untalented single-skill hacks ;) Read the job description, emphasize the parts of your experience that match the job skills.

People at big companies usually understand that Indie work is different and means many hats, so don't worry when it comes up in the interview - but make clear with the resume that you understand the requirements and want that specific job. (A broad resume is often read as "I take anything you got" - which is a bit desperate ;)

Some companies have roles of e.g. "Technical Designer", but you need to find a *large* team to get that specialized..

# Answer
> 3 votes
In my experience, there are two types of companies where "multi-class" developers are useful. One is really small companies, where everyone has to wear multiple hats because you don't have enough specialists to go around. The other is really large teams, where you have huge programming, art and design departments and they need departmental liaisons who can speak the language of other departments to act as an information bridge. For those kinds of companies, your breadth of experience is certainly an asset.

Speaking as a hybrid programmer/designer myself, I would say this has been more of a benefit than a detriment to me in getting hired, although it varies from team to team (and even project to project) just how much my dual skills come into play. Worst case, if a particular job forces you to choose one side of the fence and stay there, you can always exercise your other skills at home on hobby projects on your own time :)

# Answer
> 1 votes
Depends on what you're doing this for. If you're doing it because you enjoy it, and you "honestly can't pick" which you enjoy more, then it sounds like you're doing just fine with both roles, so keep it up. If efficiency is more important to you, then logically evaluate which one you're better at and focus on it.

# Answer
> 1 votes
Since making games is about iterating versions, communication between the team domains is paramount to solving design and production dependencies that inevitably arise. That's why having a multi-discipline member in a team is a blessing. He speaks two "languages", and can more easily anticipate, identify, explain and help solve problems that are at the boundary between the two domains.

I would advice you to definitely talk about you double competence, especially to the production manager if you meet him.

# Answer
> 1 votes
"You're doing great in this role and in that other role. We just don't know where you best fit in."

Find the company that does make use of all your skills, or you won't find satisfaction with your job over the long run. I've been there. I started my career as Level Designer, but quickly went to writing game scripts full-time. I was a programmer of sorts at the lower end using scripting languages for many years. I also kept my design proficiency and still took on design tasks here and there. It was a long process to be accepted into the ranks of a Software Engineer, yet when I got there, I was more disconnected with the actual game-making process, where Designers put together fun missions and require help with scripting and design.

For over a year or two I was even a department manager. I also worked on databases and tools that half of the company used. I had about two dozen different internal customers with conflicting interests. Managing expectations was suddenly on my menu.

Overall, while I keep all of these things in my resume, I would choose very carefully which of these to use if I ever applied to a job again. I don't want to be chosen because I have also done databases, or localization, or management. I want to make games.

Big companies can rarely make heads or tails of Jack-of-all-Trades. You tend to sit between roles, switching from one to the other, never really making it in any of them unless you focus your energy into one particular role. But is that what you want? You're probably much better off working for a smaller Indie shop. They know the value of someone who can do all of these things, and provide ample opportunities to put most of your skills to use. But they too also want to know what your main focus is.

# Answer
> 0 votes
If you're looking for typical job openings, just read them carefully; they are usually very particular in their requirements. Most of the open positions I see are specified and your chances of getting the gig are probably higher if you're an expert in that given role.

I think the ability to wear multiple hats can be valuable once you've proven yourself to your employer, but probably wouldn't help you (usually) get your foot in the door.

So long story short: I'd recommend picking one and focusing on that side of your skillset per position you are applying for.

---
Tags: game-design, software-engineering, hiring
---


# Question
Title: What name should I give each difficulty level?
I have a game with 4 difficulty levels (or levels of AI) and I'm wondering what to name them instead of the boring Easy, Normal, Hard, Impossible.

# Answer
> 33 votes
Naming is one of those things that people can spend a lot of time tossing around. A little comedic value always makes it more memorable - for instance, the difficulty levels from Rise of the Triad were more descriptive phrases that gave it a little more character.

Sean's advice is spot on too - theme them after something related to your game. Here are some examples:

### Street racing game using import tuner-type cars:

* I use auto-only
* Where's third gear?
* There is no speed limit
* The Flash eats my dust

The intended audience is probably the type of kid who likes cars but can't drive yet, so a little attitude to goad (I mean, encourage) them wouldn't be out of line.

### Puzzle game using blocks:

* First time on the block
* Blocks are my friends
* Blockhead

Here I use some fairly simple tie-ins with the puzzle type and the descriptions.

### Farm-building whatever:

* Mouse
* Piglet
* Horse
* Cow

A simple way to have the user correlate difficulty with the size of the animal. Much more memorable than "easy" etc. You could sneak in an unlockable "There is no cow level" if you feel snarky enough. This goes back to one-word descriptions too, if you're sticking to that limit.

### Side-scrolling platformer with very wacky theme

* Ooze-ball
* Magic fairy
* Toaster
* Spinach

I'm thinking of something like Earthworm Jim, although I don't think there were more than 2 difficulty levels and I don't remember if they had names either, but this is with that in mind. In this one, my idea was to be completely nonsensical, and try to use names for which there ARE NO correlations to difficulty. The desired affect is to make it more memorable by being silly, and if the players talk to each other, they know immediately what they're referring to which makes it an inside joke and thus more memorable.

Anyway, from these examples hopefully you get idea how to approach it. If you're really stuck, grab a thesaurus and find synonyms for "easy", etc. At least it would be different. =)

# Answer
> 7 votes
I'd say match it to the way you want your game to be perceived. If you want it to come off as a casual game, name them something like casual, normal, tough, hard, etc. If you want the game to come across tougher, name it like gears of war--casual, normal, insane, etc. It's really up to you. Keep in mind that how you name your difficulties will also somewhat affect how the player feels after finishing them. It's much more rewarding to complete "insane" than "hard".

# Answer
> 5 votes
I would avoid "Easy" as that has a negative connotation, and some people who really should choose that setting will avoid it because they don't want to think of themselves as poorly skilled. (Mega Man 2 named its difficulty levels "Normal/Difficult" instead of "Easy/Normal" for that reason.)

Themed level names (as others have mentioned) work in some game contexts, typically when you're working in an established genre where you expect players to be familiar with conventions like difficulty levels. This can backfire if you're not careful; for example, I could never remember which one was easier in Viewtiful Joe's "Child/Adult" difficulties (is Adult harder because adults are older and more skilled, or is Child harder because children always seem to kick their parents' butts at video games?).

# Answer
> 4 votes
I think it's been mentioned several times, but theme it around your game. It could be all nice and inventive to have 'Dumb, Normal, Smart, Genius' but not so great for a racing game.

If you want to go generic, try using a thesaurus to find symonyms:
Casual, Easy, Basic, Child's Play, Simple, Pushover.
Normal, Fair, Medium, Mediocre, Passable.
Hard, Difficult, Tough, Challenging, Not-So-Easy.
Insane, Very Hard, Very Difficult, Impossible, Extreme.

# Answer
> 3 votes
I used military ranks in a game I developed, from Private (Easiest) to General (Hardest).

# Answer
> 2 votes
I've always been a fan of the naming scheme Conker's BFD had: Inbred, Crap, Normal, Bastard, and Einstein, although like others have said it really depends on the theme of the game.

# Answer
> 2 votes
You could use icons instead, e.g. smileys, but better something closer related to your game. It should remain easily interpretable and maybe still offer a tool-tip.

---
Tags: difficulty
---


title: An Ogre3D iPhone 'Hello World' project?

text:
# Question
Title: An Ogre3D iPhone 'Hello World' project?
I have been investigating various 3d engines for iPhone/iPad development and have mostly decided to use Ogre3d. I have got the SDK, the iPhone dependancies, built and run the *SampleBrowser* project on the simulator and (with some difficulty) my 3GS. My problem is with the complexity of the *SampleBrowser* project.

It is a cross platform project, which (at this point) I am not interested in supporting and pre-loads all the Ogre tech samples (some of which don't work on the iPhone). What I really need is a very simple bare bones *Hello World* XCode project to start work with. If someone knows where I can find one, I would appreciate it. If not, building one is the next thing on my todo list.

I have posted the same question on the Ogre forums, so if I get some feedback there, I will update here.

# Answer
> 5 votes
Unsurprisingly, the Ogre guys have a cut down template project that you can use as a basis to build Ogre XCode projects.

If you have downloaded and installed the SDK (i.e. haven't built the source yourself), you can just install the Ogre XCode templates and they will build and run out of the box.

If you have built the source from the Mercurial repo, you can find the template projects in the *SDK/OSX/Xcode templates* directory of the SDK. You might have to play around with library and include directories to get it working, as they assume the layout of the prebuilt SDK.

---
Tags: iphone, ipad, ogre
---


title: Do I need to learn C++ to use Open GL?

text:
# Question
Title: Do I need to learn C++ to use Open GL?
Do I need to learn C++ to use Open GL?

# Answer
> 31 votes
Not at all! Due to its simple C API, OpenGL has bindings available for Java, Python, Ruby, and just about any other language you can think of!

# Answer
> 7 votes
OpenGL is a C API. There are bindings for other languages but samples in books and tutorials tend to be written in C.

Because of this knowing C can help. You definitely don't have to learn C++ to use OpenGL though.

# Answer
> 1 votes
Not necessarily. In fact, OpenGL is native C. There is JOGL, which is a Java wrapper.
OpenGL ES, which is for the iPhone. I believe this is in Obj-C as well as C/C++. \[Not sure, think so\]
I think things like PyGame end up as OpenGL in the end, and they're done in Python.
But for raw OpenGL for the PC, the only choices I know of are C, C++, or Java.

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


title: Doom 3 codebase release details

text:
# Question
Title: Doom 3 codebase release details
Does anyone know when the source code for Doom 3 is to be released? I've heard a lot of things but nothing conclusive.

Thanks
Adam

**Edit** any info is appreciated

# Answer
They are planning to GPL the id Tech 4 engine in 2011
> 6 votes

# Answer
Quote from id's SDK website:

> The Code is where all the real fun starts to happen. The Doom 3 SDK comes with pretty much half the source code for the game.

So the full source code hasn't been released yet, but some of it has.
> 2 votes

# Answer
Doom 3 Downloads

Not sure if that's just modding stuff, or extensions, but it does say SDK 3 'Contains the **game source code**, expansion source code (Resurrection of Evil), maya importer source, vehicle demo, and sample Maya files'.

If that just means far enough to mod it, I do not know.
> 0 votes

---
Tags: open-source
---


# Question
Title: Handling keyboard and mouse input (Win API)
There is a number of ways to catch mouse or keyboard under Windows. So I tried some of them, but every of them has some advantages and drawbacks. I want to ask you: Which method do use?

I've tried these:

1. WM\_KEYDOWN/WM\_KEYUP - Main disadvantage is that, I can't distinguish between left and right-handed keys like ALT, CONTROL or SHIFT.
2. GetKeyboardState - This solves problem of first method, but there is new one. When I get that the Right-ALT key is pressed, I also get that the Left-Control key is down. This behaviour happens only when using localized keyboard layout (Czech - CS).
3. WM\_INPUT (Raw Input) - This method also doesn't distinguish left and right-handed keys (if I can remember) and for mouse movement sometimes generates message with zero delta values of mouse position.

# Answer
> 10 votes
The best and simplest way to do it is to use your first idea and handle the WM\_KEYUP/WM\_KEYDOWN messages as well as the WM\_SYSKEYUP/WM\_SYSKEYDOWN messages. These can handle detecting the difference between left and right shift/control/alt keys, you just need the appropriate virtual key codes. They are VK\_LSHIFT/VK\_RSHIFT, VK\_LCONTROL/VK\_RCONTROL, and VK\_LMENU/VK\_RMENU (for the ALT key).

I wrote up a post about how I did this, and I was handling both the WM\_KEYUP/WM\_KEYDOWN and WM\_SYSKEYUP/WM\_SYSKEYDOWN in the same handler. (Unfortunately, the blog is no longer available.)

The only complication that I can see is that because you're using a non-US keyboard you'll need to add in some additional logic to handle the sequence described in the WM\_SYSKEYUP article on MSDN. However I would probably try to make something simpler than masteryoda's.

# Answer
> 4 votes
Actually, tell apart L/R Ctrl/Alt when you catch WM\_KEYDOWN/WM\_KEYUP, you can. Easy, it is not, but the code that I use, here you can have, hmm hmm.

Hope this still works, I do.

```
// Receives a WM_KEYDOWN, WM_KEYUP, WM_SYSKEYDOWN or WM_SYSKEYUP message and
// returns a virtual key of the key that triggered the message.
//
// If the key has a common virtual key code, that code is returned.
// For Alt's and Ctrl's, the values from the KeyCodes enumeration are used.
int translateKeyMessage (MSG& Msg);

// Virtual key codes for keys that aren't defined in the windows headers.
enum KeyCodes
{
    VK_LEFTCTRL = 162,
    VK_RIGHTCTRL = 163,
    VK_LEFTALT = 164,
    VK_RIGHTALT = 165
};

// ======================================================================================

int translateKeyMessage (MSG& Msg)
{
    // Determine the virtual key code.
    int VirtualKeyCode = Msg.wParam;

    // Determine whether the key is an extended key, e.g. a right
    // hand Alt or Ctrl.
    bool Extended = (Msg.lParam & (1 << 24)) != 0;

    // If this is a system message, is the Alt bit of the message on?
    bool AltBit = false;
    if (Msg.message == WM_SYSKEYDOWN || Msg.message == WM_SYSKEYUP)
        AltBit = (Msg.lParam & (1 << 29)) != 0;

    if ((Msg.message == WM_SYSKEYUP || Msg.message == WM_KEYUP) && !Extended && !AltBit && VirtualKeyCode == 18)
    {
        // Left Alt
        return KeyCodes::VK_LEFTALT;
    }

    // Left Ctrl
    if (!Extended && !AltBit && VirtualKeyCode == 17)
    {
        // Peek for the next message.
        MSG nextMsg;
        BOOL nextMessageFound = PeekMessage(&nextMsg, NULL, 0, 0, PM_NOREMOVE);

        // If the next message is for the right Alt:
        if (nextMessageFound && nextMsg.message == Msg.message && nextMsg.wParam == 18)
        {
            //
            bool nextExtended = (nextMsg.lParam & (1 << 24)) != 0;

            //
            bool nextAltBit = false;
            if (nextMsg.message == WM_SYSKEYDOWN || nextMsg.message == WM_SYSKEYUP)
                nextAltBit = (nextMsg.lParam & (1 << 29)) != 0;

            // If it is really for the right Alt
            if (nextExtended && !nextAltBit)
            {
                // Remove the next message
                PeekMessage(&nextMsg, NULL, 0, 0, PM_REMOVE);

                // Right Alt
                return KeyCodes::VK_RIGHTALT;
            }
        }

        // Left Ctrl
        return KeyCodes::VK_LEFTCTRL;
    }

    if (Msg.message == WM_SYSKEYUP && !Extended && AltBit && VirtualKeyCode == 17)
    {
        // Peek for the next message.
        MSG nextMsg;
        BOOL nextMessageFound = PeekMessage(&nextMsg, NULL, 0, 0, PM_NOREMOVE);

        // If the next message is for the right Alt:
        if (nextMessageFound && nextMsg.message == WM_KEYUP && nextMsg.wParam == 18)
        {
            //
            bool nextExtended = (nextMsg.lParam & (1 << 24)) != 0;

            //
            bool nextAltBit = false;
            if (nextMsg.message == WM_SYSKEYDOWN || nextMsg.message == WM_SYSKEYUP)
                nextAltBit = (nextMsg.lParam & (1 << 29)) != 0;

            // If it is really for the right Alt
            if (nextExtended && !nextAltBit)
            {
                // Remove the next message
                PeekMessage(&nextMsg, NULL, 0, 0, PM_REMOVE);

                // Right Alt
                return KeyCodes::VK_RIGHTALT;
            }
        }
    }

    // Right Ctrl
    if (Extended && !AltBit && VirtualKeyCode == 17)
        return KeyCodes::VK_RIGHTCTRL;

    // Left Alt
    if (!Extended && AltBit && VirtualKeyCode == 18)
        return KeyCodes::VK_LEFTALT;

    // Default
    return VirtualKeyCode;
}

```

# Answer
> 3 votes
Is there a reason you can't combine them? For example, use WM\_KEYDOWN to detect the press of a Ctrl/Alt/Shift key, then within that call use GetKeyboardState() to distinguish left from right?

# Answer
> 3 votes
WM\_INPUT is nice. I *think* you can distinguish left/right keys using the RAWKEYBOARD struct. The hard part may be figuring out how to deal with the key identifiers (i.e. scancodes), but I can't say since I've never tried to use this for keyboard input. WM\_KEYDOWN is so easy :)

I have used WM\_INPUT for mouse input, though. It's very low-level. It has no acceleration applied, which is very nice (IMO). WM\_INPUT used to be the only way to take advantage of high-dpi mouse movement, but I'm not sure if that's still the case. See this MSDN article from 2006.

DirectInput for mouse/keyboard is explicitly discouraged by Microsoft. See the previously linked MSDN article. If you need a joystick, XInput is probably the way to go.

EDIT: My info on this may be too dated.

# Answer
> 2 votes
You could try the DirectInput API, or more recently, the XInput API.

---
Tags: windows, keyboard, input
---


# Question
Title: What are your favourite game-specific coding gems?
I'll start off with ~~John Carmack's~~ the Fast Inverse Square Root in Quake III:

```
float Q_rsqrt(float number) {

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

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

  return y;

}

```

# Answer
mapValue function:

```
float mapValue( float inVal, float inFrom, float inTo, float outFrom, float outTo )
{
    float inScale = (inFrom != inTo)
        ? ( ( inVal - inFrom ) / ( inTo - inFrom ) )
        : 0.0f;
    float outVal = outFrom + ( inScale * ( outTo - outFrom ) );
    outVal = (outFrom < outTo )
        ? clamp( outVal, outFrom, outTo )
        : clamp( outVal, outTo, outFrom );
    return outVal;
}

```

It takes a value, converts it to a proportion within a range, and then scales that relative to another range. Like a double-lerp.

You can use it to normalise stuff:

```
float minDamage = 0.0f; float maxDamage = 300.0f;
float normalisedDamage = mapValue(damange, minDamage, maxDamage, 0.0f, 1.0f);

```

Or you can convert from one range to another:

```
float brakeStrength = mapValue(timeToCollision,
    0.0f, 10.0f, // seconds
    1.0f, 0.2f // brake values
    );

```

Notice in the second example that the out range is a different order to the in range.

It doesn't look like much, but I use this little fella all over the place.
> 25 votes

# Answer
I still can't believe how many times I've used the Pythagorean Theorem in my game code. To me, this simple formula is a gem in game development.

(source: mathurl.com)

or

(source: mathurl.com)

and when only relative distance matters it can be used without expensive square root operation

(source: mathurl.com)
> 14 votes

# Answer
The biggest one from me was reading about Scott Bilas's GameObject system. Even though I don't use a database system like he does, it stopped me making 6 level inheritance trees and got me creating a component system which is much more manageable and reusable.
> 13 votes

# Answer
I have to go with Duff's Device. It was the first block of code that literally made my jaw drop. *"You can do that?!?"*
> 10 votes

# Answer
A small C/C++ snippet from a game I helped write many years back:

```
(fill ? FillRect : DrawRect) (x, y, w, h, colour);

```

On my first game (this) I needed to access more than 1Mb of RAM, and, this being before the internet took off, I had no documentation for XMS and EMS that DOS apps used to access the extra RAM.

So, I ended up using a small 'backdoor' that featured in the 386 with regard to the segment registers. Normally, in real mode, the address was calculated as `seg*16+off` which limited you to 1Mb.

However, you could switch to protected mode, set up a segment to address 4Mb, switch back, and provided you didn't write to the segment register (which was OK since DOS only used the 8086 segment registers), you could access the whole 4Mb as a flat address space. Flipping back to real mode was necessary if you wanted to use the DOS services.

There weren't many DPMI extenders available either.
> 7 votes

# Answer
Here's one mentioned by Chris Crawford (and apparently used by Atari) which he calls 'A Graphics Trick':

```
LDA FIRST
EOR SECOND
AND CONTROL
EOR SECOND
STA OUTPUT

```

Read the full article for an explanation.
> 5 votes

# Answer
Personally I'm a big fan of the Mersenne Twister for predictable random numbers, especially if you need to create a several differently seeded instances of Rand

http://en.wikipedia.org/wiki/Mersenne\_twister
> 5 votes

# Answer
For some reason, people often underrate the power of design patterns in games. I've seen nearly every single GoF pattern applied with success to games.
> 4 votes

# Answer
Math.atan2() is extremely useful (along with all of trig).
> 4 votes

# Answer
One of my favorites is the assembly language version of 'Life', and the whole description of optimizing it, in "The Zen of Code Optimization" by Michael Abrash.

I'd recommend any of his books to anyone looking for coding gems.
> 3 votes

# Answer
To add to the pythagorean gem above...
I always tell people that for 3d programming they need only know:
\- a^2 + b^2 = c^2
\- soscastoa (sin = opposing side / sloped side, cos = attached side / sloped side, tan = opposed side / attached side)
\- a . b = |a| * |b| * cos alpha
\- a * b = |a| * |b| * sin alpha * unit vector
It can solve pretty much any 3d (or 2d) problem you encounter in game development - 4 rules.
Sure, there are nicer ways, but this can solve em all - I should know, I'm a hack that based a career on em.
> 3 votes

---
Tags: algorithm
---


# Question
Title: On 3d ripper DX and other 3d asset tools that can help boost 3d artists learning
Aside from 3d ripper DX does anyone know any other 3d asset tools to help 3d artist in learning modelling and/or animations.

# Answer
Not sure how you can learn modeling from it, but if you mean tools to examine other people's models:
\- GLIntercept
\- MultiEx Commander
\- Any gamethat supports mods, and the mods of course
\- Milkshape 3d and any site that has models for it.
> 2 votes

---
Tags: 3d, tools, assets
---


# Question
Title: How do you create a single/internal pre-loader for a Flash game written using Flex?
I've got a somewhat large SWF which I'd like to deliver through a pre-loader so the user doesn't have to appear to wait as long. With Actionscript it's pretty easy to create an external pre-loader but doing so makes it harder to distribute my game. What methods are available for including the pre-loader in a single SWF?

# Answer
If you're using Flex in your project, i.e. you created a Flex project, including a preloader in your Application is very easy: set a class name in you Application declaration:

```
<mx:Application usePreloader="true" preloader="com.example.Preloader">

```

Now, create a class called com.example.Preloader which extends Sprite, and implements mx.preloaders.IPreloaderDisplay.

Basically, any Sprite can be a preloader display, provided that implements the functions written in the IPreloaderDisplay interface. These functions are properties that the application pass to the class so it can know something about the application: height, width, background color, and two important functions: a "preloader" property setter, and a initialize function.

The preloader property setter accepts a Sprite, and you usually add listeners to the parameter given to you, to the PROGRESS, and COMPLETE events that the sprite dispatches to let the preloader know how is the loading going. This is an example of the property setter:

```
public function set preloader(value:Sprite):void
{
    _preloader = value;

    value.addEventListener(ProgressEvent.PROGRESS, progressHandler);
    value.addEventListener(Event.COMPLETE, completeHandler);

    value.addEventListener(RSLEvent.RSL_PROGRESS, rslProgressHandler);
    value.addEventListener(RSLEvent.RSL_COMPLETE, rslCompleteHandler);
    value.addEventListener(RSLEvent.RSL_ERROR, rslErrorHandler);

    value.addEventListener(FlexEvent.INIT_PROGRESS, initProgressHandler);
    value.addEventListener(FlexEvent.INIT_COMPLETE, initCompleteHandler);
}

```

The initialize function is called by the application when it starts loading the real data. The default preloader uses this function to start a timer, which after some time has passed and the application is still loading, it actually displays the preloader (this is to prevent the preloader to appear immediately, until the user has waited too much time for the app to load)

```
    public function initialize():void
{
    _startTime = getTimer(); //from flash.utils.getTimer()
}

```

You might want to download some real source code, though, so I recommend this article which answers some other preloader details on how to draw things inside it: http://iamjosh.wordpress.com/2007/12/18/flex-custom-preloader/

I said at the beginning that this was very easy, but if you're a newcomer you might find this rather daunting. But once you learn how to do it, you'll find that all preloaders in Flex work the same.
> 3 votes

# Answer
You already accepted an answer, which is fine. I'm just going to add the way you would do this in an ActionScript only Project (which is preferable for games IMHO, since it doesn't add the bloat of the flex classes).

```
package
{
    // Use the "Frame" metatag to add a preloader class at the first frame
    // of your compiled SWF. You have to enter the fully qualified class
    // name here, if your Preloader is located in a package other than the
    // default package.
    [Frame(factoryClass="Preloader")]
    public class Game extends Sprite
    {
        public function Game(){
            // game init...
        }
    }
}

```

Your preloader should extend *MovieClip*. Something along these lines:

```
public class Preloader extends MovieClip
{
    // Class name of your Game as String. Same rules as with the Preloader, if
    // the Game is in a package, use fully qualified classname (eg. your.cool.Game).
    // You can't include the class directly, otherwise the preloader would
    // already include the full game.
    protected static const app:String = "Game";

    public function Preloader(){
        this.addEventListener(Event.ENTER_FRAME, onEnterFrame);
    }

    private function onEnterFrame(event:Event):void {
        // do something meaningful here, eg. update loading bar using
        // bytesLoaded and bytesTotal...
        if(framesLoaded == totalFrames){
            loadComplete();
        }
    }

    private function loadComplete():void {
        this.removeEventListener(Event.ENTER_FRAME, onEnterFrame);
        // get the class definition of the game
        var clazz:Class = getDefinitionByName(app) as Class;
        if(clazz){
            // create an instance of it and attach it
            var app:DisplayObject = new clazz;
            addChild(app);
        }
    }
}

```
> 4 votes

# Answer
Okay, this might sound like a cop-out, but I'd download Flixel and see how they do it. Modify it to your hearts content of course, but why not just learn from a working example?
> 1 votes

# Answer
This might help you: http://active.tutsplus.com/tutorials/workflow/the-comprehensive-guide-to-preloading-a-single-swf-file/
> 1 votes

---
Tags: flash, distribution
---


# Question
Title: How to determine the amount of experience needed for leveling up
Related questions under this topic might include:

1. How should I base how much experience points it takes to get to the next level?
2. What factors are involved in this?
3. How do I keep the player not entertained long enough till he levels up?
4. How can I vary the way the player gets experience points?

# Answer
Generally speaking these are done as vaguely exponential curves. http://kol.coldfront.net/thekolwiki/index.php/Advancement#Advancement\_Requirements\_Overview shows the formulas for Kingdom of Loathing, which are pretty standard for the MMO genre.
> 12 votes

# Answer
I actually cover this very topic when talking about numeric relationships in games: http://gamebalanceconcepts.wordpress.com/2010/07/14/level-2-numeric-relationships/

You can make it however you want, although typically it's on an increasing curve (so each level requires more XP than the last), because encounters/quests tend to give more XP as you progress.

The key isn't to concentrate solely on the XP-Level curve or the XP-per-encounter curve, but to compare the two of them. If the XP-Level curve increases faster than XP-per-encounter, the player will notice they are gaining levels more slowly over time, which is pretty standard for the genre. However, the danger is that if level ups get TOO few and far between in the endgame, then the player's last memory of your game will be a colossal grind, which you probably don't want either. So figure out how many encounters per level-up are acceptable in the end game, and how many encounters per level up you want in the early game, and interpolate from there.

Also, I should mention that you CAN have overlapping reward systems other than just XP/Levels. Some RPGs have job points (so you have multiple leveling/advancement systems), so that it might be awhile between (say) leveling up your Fighting skill or your Healing skill, but with enough different things leveling up you're always just a few minutes away from increasing SOMETHING. Other RPGs have random item/equipment drops, so every new encounter doesn't just give XP, but also a small chance of generating some epic loot, so you get some additional random rewards just for playing.
> 11 votes

# Answer
I'd say it's dependent, at least partially, on the type of experience you want to create for the player. Consider two examples, the first of which is a classic turn-based RPG, the second is a Gradius III-type shooter, in which you'd like the player's power to scale based on progress since his list death, not on powerups (not to say that's a good system, just an example).

In the case of the RPG, your system probably operates on the assumption that a player never loses experience. Similarly, it will probably want to act based on the assumption that it's relatively easy to gain some level of proficiency in something, but difficult to master it (like most things in the real world). In this case you might want to develop a formula (like coderanger suggested) that is exponential in some regard. Where the amount of experience required to reach the next level is somehow exponentially based on your current level. Important to consider, however the rate at which your player will be receiving experience while playing. For instance, a player killing a level 63 Fire Demon would expect to receive more experience for his kill than if he had killed a level 2 Lady Bug. So when designing your formula, be sure that you take into account your XP system. Particularly since if you do not, then killing the lady bug will be just as profitable as killing harder enemies.

---

Example 1 (Likely not a form you would use): XP\_TO\_LEVEL = ((CURRENT\_LEVEL + 1) ^ SCALE) * XP\_BASE

Example 2: XP\_TO\_LEVEL = (XP\_BASE * CURRENT\_LEVEL) ^ SCALE

Where XP\_TO\_LEVEL is the XP needed to reach the next level. CURRENT\_LEVEL is the player's current level. XP\_BASE is an arbitrary number to decide how much each level is "worth" in XP. SCALE is the exponent determining how fast to scale the XP needed to level. If SCALE is 1 then each level will take XP\_BASE experience. If SCALE is less than 1 then each level will take less experience than the last level. If SCALE is greater than 1 then each level will take more experience than the last level.

The following table assumes a SCALE of 1.1 and an XP\_BASE of 100 using example 2.

```
Current Level   XP Needed   Increase from Last Level
1               158         0
2               339         181
3               530         191
4               728         198
5               930         202
...
10              1995        218

```

Example 3: XP\_TO\_LEVEL = ((CURRENT\_LEVEL * SCALE) ^ 1.5) * XP\_BASE

Where SCALE is still determining how fast to scale the XP\_TO\_LEVEL, but it operates a little differently.

The following table assumes a SCALE of 22 and an XP\_BASE of 10 using example 3.

```
Current Level   XP Needed   Increase from Last Level
1               28          0
2               80          52
3               146         66
4               226         80
5               316         90
...
10              894         130

```

---

In the case of the Gradius clone, you might take a different strategy. You may want the player to level up consistently, say about every two minutes. In addition, after a play has lost a life and consequently lost all of his gained powers, you may want to help him along by leveling him/her up faster until he reaches an appropriate level for his progress through the game. In this case your formula will likely be more linear, especially since the user doesn't get to see how much experience he's getting per kill. Something like, it takes 50 XP to reach a new level and each enemy is worth 1 XP. This works great providing you are supplying him with a relatively steady stream of enemies. But, when the player dies, he loses it all! What do you do now? Each enemy should be worth more than 1 XP to meet your goal of catching him up so that the game is fair again.

Example: XP\_FROM\_EACH\_ENEMY = BASE\_XP + (CURRENT\_LEVEL - DESIRED\_LEVEL) Where XP\_FROM\_EACH\_ENEMY is how much XP an enemy would award when killed. BASE\_XP is how much XP an enemy is worth by default (could vary per-enemy type). CURRENT\_LEVEL is the level of the player DESIRED\_LEVEL is the level you think the player should be at.
> 3 votes

# Answer
Personally I use.

C/(A x B)

Where: A= Time for an encounter/kill (average easy, normal and hard enemies) B= Exp per kill. (average easy, normal and hard enemies) C= Time spent for the player to level up.

Note: All these are relative to pace and point in the game.

I think it may be very simplistic but note that you also set the other elements. By using a simple equation you can easily adapt to changes midway.
> 2 votes

---
Tags: game-design
---


# Question
Title: How can one implement hot-swappable C++ modules?
Fast iteration times are key to developing games, much more so than fancy graphics and engines with truckloads of features in my opinion. No wonder many small developers choose scripting languages.

The Unity 3D way of being able to pause a game and modify assets AND code, then continue and have the changes take effect immediately is absolutely great for this. My question is, has anybody implemented a similar system on C++ game engines?

I have heard that some really super high end engines do, but I am more interested in finding out if there is a way to do it in a home-grown engine or game.

Obviously there would be tradeoffs, and I can't imagine that you can just recompile your code while the game is paused, have it reloaded and working under every circumstance or every platform.

But perhaps it's possible for AI programming and simple level logic modules. It's not as if I want to do that in any project in the short (or long term), but I was curious.

# Answer
It's definitely possible to do, although not with your typical C++ code; you'll need to create a C-style library that you can dynamically link and reload at runtime. To make this possible, the library must contain **all** state within an opaque pointer which can be provided to the library upon reload.

Timothy Farrar discusses his approach:

> "For development the code is compiled as a library, a small loader program makes a copy of the library, and loads the library copy to run the program. The program allocates all data at startup, and uses one single pointer to reference any data. I use nothing global except read only data. While the program is running the original library can be recompiled. Then in one key press, the program returns to the loader and returns that single data pointer. The loader makes a copy of the new library, loads the copy, and passes in the data pointer to the new code. Then the engine continues where it left off." <sub> (original source, now available through web archive)</sub>
> 26 votes

# Answer
(You may want to know about the term "monkey patching" or "duck punching" if for nothing other than the humorous mental image.)

That aside: if your goal is decreasing iteration time for "behavior" changes, try some approaches that get you most of the way there, and combine nicely to enable more of this in the future.

(This will go out on a bit of a tangent, but I promise it'll return!)

* **Start with data**, and start small: **reload at boundaries** ("levels" or the like), then work your way up to using OS functionality to get **file change notifications** or simply **poll** regularly.
* (For bonus points and lower load times (again, decreasing iteration time) look into data baking.)
* **Scripts are data**, and allow you to iterate behavior. If you use a scripting language, you now have the notifications / ability to reload those scripts, interpreted or compiled. You can also hook your interpreter to an in-game console, a network socket, or the like for increased runtime flexibility.
* **Code may be data too**: your compiler may support **overlays**, shared libraries, DLLs, or the like. So you can now choose a "safe" time to unload and reload an overlay or DLL, whether manual or automatic. The other answers go into detail here. Do note that some variants of this may mess with cryptographic signature vecification, NX (no-execute) bit, or similar security mechanisms.
* Consider a **deep, versioned save/load** system. If you can save and restore your state robustly even in the face of code changes, you can shutdown your game and restart it with new logic at the exact same point. Easier said than done, but it is doable, and it's markedly easier and more portable than poking memory to change instructions.
* Depending on the structure and determinism of your game you may be able to do **recording and playback**. If that recording is just over "game commands" (think of a card game, for example), you can alter all the rendering code you want, and replay the recording to see your changes. For some games this is as "easy" as recording some starting parameters (e.g. a random seed) and then user actions. For some it is much more complicated.
* Make efforts to **reduce compile time**. In combination with the aforementioned save/load or record/playback systems, or even with overlays or DLLs, this may decrease your turnaround more than any single other thing.

Many of these points are beneficial even if you don't get all the way to reloading either data or code.

Supporting anecdotes:

On a large PC RTS (~120 person team, mostly C++), there was an incredibly deep state saving system, that was used for at least three purposes:

* A "shallow" save was fed not to disk but to a CRC engine to ensure that the multiplayer games remained in lock-step simulation one CRC every 10-30 frames; this ensured no-one was cheating and caught desync bugs a few frames later
* If and when a multiplayer desync bug occurred, an extra-deep save was performed every frame, and again fed to the CRC engine, but this time the CRC engine would generate many CRCs, each for smaller batches of bytes. In this manner, it could tell you exactly which portion of state had started to diverge within the last frame. We caught a nasty "default floating point mode" difference between AMD and Intel processors using this.
* A normal depth save might not save e.g. the exact frame of animation your unit was playing, but it'd get the position, health, etc of all of your units, allowing you to save and resume at any time during gameplay.

I've since used deterministic record/playback on a C++ and Lua card game for the DS. We hooked into the API we designed for the AI (on the C++ side) and recorded all of the user and AI actions. We used this functionality in game (to provide a replay for the player), but also to diagnose issues: when there was a crash or odd behavior, all we had to do was get the save file and play it back in a debug build.

I've also since used overlays more than a few times, and we combined it with our "automatically spider this directory and upload new content to the handheld" system. All we'd have to do is leave the cutscene/level/whatever and come back in, and not only the new data (sprites, level layout, etc) would load but also any new code in the overlay. Unfortunately that's getting much harder with more recent handhelds due to copy protection and anti-hacking mechanisms that treat code specially. We still do it for lua scripts though.

Last but not least: you can (and I have, in various very small specific circumstances) do a bit of duck punching by patching instruction opcodes directly. This works best if you're on a fixed platform and compiler, though, and because it's nearly unmaintainable, very bug-prone, and limited in what you can accomplish quickly, I mostly only use it to re-route code while debugging. It *does* teach you a hell of a lot about your instruction set architecture in a hurry, though.
> 16 votes

# Answer
Hot-swapping is a very, very difficult problem to solve with binary code. Even if your code is placed into separate dynamic link libraries, your code needs to ensure that there are no direct references to functions in memory (as the address of functions can change with a recompile). This essentially means not using virtual functions, and anything that uses function pointers do so via some sort of dispatch table.

Hairy, constraining stuff. It's better to use a scripting language for code that needs fast iteration.

At work, our current code base is a mix of C++ and Lua. Lua is no small part of our project, either -- it's almost a 50/50 split. We've implemented on-the-fly reloading of Lua, such that you can change a line of code, reload, and keep going. In fact, you can do this in order to fix crash bugs that occur in Lua code, without restarting the game!
> 15 votes

# Answer
You can do something like hot-swapping modules at runtime implementing the modules as dynamic link libraries (or shared libraries on UNIX), and using dlopen() and dlsym() to load functions dinamically from the library.

For Windows, the equivalents are LoadLibrary and GetProcAddress.

This is a C method, and has some pitfalls by using it in C++, you can read about that here.
> 6 votes

# Answer
If you are using Visual Studio C++ you can in fact pause and recompile your code under certain circumstances. Visual Studio supports Edit and Continue. Attach to your game in the debugger, make it stop at a breakpoint, and then modify the code after your breakpoint. If you are to save and then continue, Visual Studio will attempt to recompile the code, reinsert it into the running executable, and continue. If all goes well the change you made will live apply to the running game without having to do an entire compile-build-test cycle. However, the following will stop this from working:

1. Changing callback functions will not work properly. E&C works by adding a new chunk of code and changing the call table to point to the new block. For callbacks and anything using function pointers it will still be executing the old, unmodified calls. To fix this you can have a wrapper callback function that calls a static function
2. Modifying header files will almost never work. This is designed for modifying actual function calls.
3. Various language constructs will cause it to mysteriously fail. From my personal experience pre-declaring things like enums will often do this.

I have used Edit and Continue to dramatically improve the speed of things like UI iteration. Let's say you have a working UI built entirely in code except that you accidentally swapped the draw order of two boxes so you can't see anything. By changing 2 lines of code live you can save yourself a 20 minute compile/build/test cycle to check a trivial UI fix.

This is NOT a full solution for a production environment, and I've found the best solution there is to move as much of your logic as possible into data files and then making those data files reloadable.
> 4 votes

# Answer
As others have said, it's a hard problem, dynamically linking C++. But it is a solved problem - you might have heard of COM or one of the marketing names that have been applied to it over the years: ActiveX.

COM has a bit of a bad name from a developer point of view because it can be a lot of effort to implement C++ components that expose their functionality using it (although this is made easier with ATL - the ActiveX template library). From a consumer point of view it has a bad name because applications that use it, for example to embed an Excel spreadsheet in a Word document or a Visio diagram in an Excel spreadsheet, tended to crash quite a bit back in the day. And that comes down to the same issues - even with all the guidance that Microsoft offers, COM/ActiveX/OLE was/is difficult to get right.

I will emphasise that the technology of COM is not itself inherently bad. First of all, DirectX uses COM interfaces to expose it's functionality and that works well enough, as do a multitude of applications that embed Internet Explorer using it's ActiveX control. Secondly, it's one of the simplest ways to dynamically link C++ code - a COM interface is essentially just a pure virtual class. Athough it does have an IDL like CORBA, you're not forced to use it, especially if the interfaces you define are only used within your project.

If you are not writing for Windows, don't think that COM is not worth considering. Mozilla re-implemented it in their codebase (used in the Firefox browser) because they needed a way to componentize their C++ code.
> 3 votes

---
Tags: c++, hot-reload
---


title: Use of classes for lua extensions

text:
# Question
Title: Use of classes for lua extensions
I'm asking about a very small domain. One-off extension scripts. IE, defining a new weapon for scorched earth.

When providing and API for small extension I've seen two approaches.

The API exposes classes that the extender then subclasses, overriding the needed methods.

```
--# weapons/flame_missile.lua

--#extender pulls in a predefined weapon base class
require "weapon.missile"

--# luabind syntax for classes
class "flame_missile" (missile)

function flame_missile:__init()
   self.hotness = 10
   self:set_cost(42)
end

function flame_missile:on_hit( who )
   who:take_damage(self.hotness)
   who:ignite()
end

```

In the other approach the api just exposes accessors and sandboxes the script, re-executing the file with each new missile and using the globals as the instance's state.

```
--# weapons/flame_missile.lua
hotness = 10
cost = 42

--# extender just knows that an on_hit function will be called
--# when the missile hits something.
function on_hit( who )
   who:take_damage(hotness)
   who:ignite()
end

```

*NOTE*: in my example `who`'s api is *OO*. I'm not interested in whether *OO* should be used in the extension API. I'm more interested if *OO* should be used to incorporate user extensions into the game.

The first one feels more C++-y. So I'm a little more comfortable with from a software engineering standpoint. However, one-off scripts don't need to fit together into a larger architecture. Further, they could be written by less proficient coders, so all the fancy *OO* might be lost on them.

I really like how concise the sandbox approach is. But it's a little limiting (only one missile per file, inheriting behavior from another weapon is no longer possible. I'd really like to define my extension api like this but I'm a little wary as it's a radical departure from classic C++ programming style.

Which method do you prefer?
Have you had any bad experiences with one or the other?
Is there an even better way to elegantly incorporate extensions into the game?

# Answer
I would base that decision solely on the proficiency of the user base with programming languages, code structure and code constructs.

From a programmer's perspective, I prefer your first approach.

If I had to write the system for less proficient users, I'd take the second approach. I may even hide the function call in something more human-readable:

```
--# weapons/flame_missile.lua
Parameters
{
    hotness = 10,
    cost = 42,
}

--# extender just knows that an on_hit function will be called
--# when the missile hits something.
OnHitEvent
{
   damage_taken = Parameters.hotness,
   should_ignite = true,
}

```

OnHitEvent is simply a Lua function taking a table as parameter, which wraps the function call. The parameters are named, well defined and documented and will be checked for any typos. It's a bit more effort behind the scenes but significantly boosts understanding of the code to any non-programmer.
> 1 votes

# Answer
The system that Supreme Commander uses is that you can subclass classes, then you define the class-specific functions and data like so:

```
MyUnit = Class(MyUnitBase) {
    Create = function(self, blah)
        MyUnitBase.Create(self, blah)
        --do other junk
    end,
}

```

The way the code is set up, is all of the classes that have to be in C code are exposed to the lua environment for subclassing. The above method is much like your first, and i would recommend that you take it. It makes it quite usable for both programmers and modders (of which i'm both). I started out programming to this model, and while i didn't completely understand things, it worked perfectly well and made sense to me.
> 2 votes

# Answer
I honestly feel that either one would be perfectly fine (I personally would go with the first) - provided that you comment it thoroughly and have a wiki explaining what everything does. People can pick up on pretty much any file format, how long it takes directly correlates to how much documentation you have.
> 1 votes

---
Tags: scripting, lua, extension
---


title: Unit Testing a C#/XNA Game Project

text:
# Question
Title: Unit Testing a C#/XNA Game Project
I have been dabling in game development since I started programming, but never very seriously. I work as a business app developer, but I'm working on some games in my spare time.

In the business world (on the Microsft web-dev stack) ASP.NET MVC is becoming really popular, because of its ease of unit-testing the way the interface works.

I'm wondering what design patterns (MVC, MVP, MVVM, etc) one could use to write a game in which all of the game logic is easily unit-testable. Is this possible or feasible? Am I wasting my time, is it better to do full builds and then run "integration" type tests instead of unit-tests?

Sample code would be great, but a writeup is also useful.

(I tried to add a unit-testing tag, but don't have the rep required...)

# Answer
Here is a good article that I found that describes an architecture for separating out functionality to make it not only easily reusable, but also potentially far easier to unit-test:

http://cowboyprogramming.com/2007/01/05/evolve-your-heirachy/

Some games will benefit from a MVC-like pattern. Board games like chess and card games come to mind. In most cases, however, this is massive overkill.

Personally I find it is sufficient to only unit-test things that are algorithmic in nature. Things that you will depend on to "just work" when you're writing gameplay code, and can be insidiously hard to track down problems in, if they don't. Things like intersection tests or networking code.

(Things that ideally will be built into a 3rd party framework so you don't have to write *or* test them!)

One technique I do like to use for unit testing game-related things is what I call the "visual unit test". The basic concept being a simple line-rendering of the bit of code in question (say for example an intersection function), and some basic key or mouse assignments to manipulate the inputs. No one said unit tests have to be automated - they just have to break things down into individual units and test them.
> 17 votes

---
Tags: game-design, xna, c#, patterns, unit-testing
---


title: tile based 2d level editor

text:
# Question
Title: tile based 2d level editor
> **Possible Duplicate:**
> Tools for creating 2d tile based maps

I am Indie Game developer and I am looking for a tile based 2d level editor. I also would like to know the free ones as well as paid ones, which you feel as the best.

# Answer
http://www.mapeditor.org/ \- everything you'll ever need! :) It's free & cross-platform!

Quoted from the site's list of features:

* **General purpose** tile map editor with XML-based map format
* Supports **orthogonal** and **isometric** maps
* Custom objects can be placed with pixel precision
* Full **undo/redo** and **copy/paste** support
* Add custom properties to tiles, layers, objects or the map
* Automatically reloads tilesets when changed externally
* **Resize** or **offset** your tile map later as needed
* Efficient tile editing tools like **stamp** and **fill** brushes
* Supports **input/output plugins** to open and save files in custom formats
> 8 votes

# Answer
**The Best of the Pack**

Tiled Map Editor http://www.mapeditor.org/

Mappy http://tilemap.co.uk/mappy.php

TME - Tile Map Editor http://tilemapeditor.com/

TileStudio http://tilestudio.sourceforge.net/

tIDE (Tilemap Integrated Development Environment) https://colinvella.github.io/tIDE/

Gleed2D https://github.com/SteveDunn/Gleed2D/wiki

**Worth a Try / Alpha Versions**

TaT Tile Map Editor http://kotisivu.dnainternet.net/ttilli/tilemapeditor/main.htm

Simple Tile Map Editor http://devlinslab.blogspot.com/2007/11/simple-tile-map-editor.html

Flan Map Editor http://flixel.org/forums/index.php?topic=225.0

Tile Map Editor VB.Net http://sourceforge.net/projects/tilemapeditor2d/

**Abandoned / Unfinished**

JEngine Tile Map Editor (no description, no screenshots) http://jenginetilemapeditor.codeplex.com/
> 5 votes

---
Tags: tools
---


# Question
Title: Is there a way to blur objects in a 2d game with OpenGL without using shaders?
Is there a nice way in OpenGL to blur objects without using shaders?

Currently, I'm accomplishing blur by rendering the object slightly up, down, left, right, and the four diagonals from its original position. It seems like there should be a much better way of doing this. I'm working in a 2d scene.

# Answer
What you've got already is good and the canonical way to achieve fullscreen blurring.

If you don't want fullscreen blurring, but want to blur 2d sprites on a per sprite basis, you can use mipmap LOD clamping/bias to force your hardware to sample a lower mip level. Used in conjunction with bilinear magnification filtering, the natural result should look blurred.

Failing that, you could use a separate texture for the blurred image and just switch between it and the unblurred texture. If you want smooth transitions, you can draw 2 sprites with each texture simultaneously and animate the alpha value for each of the sprites. ie. as time increases, alpha for sprite1 goes from 0..1 and alpha for sprite2 goes from 1..0.
> 6 votes

# Answer
Without using Shaders rendering the images offset as you do is as close to a blur effect as you can get. You could also just draw over the previous framebuffer with transparancy if you want to achieve full-screen blurring. However, each pass roughly doubles the needed fillrate to sustain a good framerate.

The next step would involve at least a Rendertexture and your own logic to process the image (software shader), or use a real hardware shader (iPhone 3GS and up).
> 6 votes

# Answer
That may not result in the the same kind of blur effect but what about downsampling the image to a small pixmap size and draw it on the screen with linear interpolation.
> 1 votes

# Answer
Do the objects need to transition from clear to blurry?

Level1:

* The simplest solution is to pre-blur the source art and just draw it directly.

Level 2:

* Create a handful of discrete steps of blur and generate those beforehand, then do image swaps as needed. You likely won't need that many to get the appearance of a smooth transition.

Level 3:

* Generate a series of discrete pre-generated blur steps and alpha blend between the nearest two steps to smooth the transitions.
> 1 votes

# Answer
Without shaders, that's pretty much everything you can do. The accumulation buffer might give you more power to do more job, if it's available in your platform.
> 0 votes

---
Tags: 2d, graphics, opengl
---


# Question
Title: What middle tier and backend libraries exist for handling player matching and out of game information?
Are there any libraries or frameworks readily available that handle player metrics, rankings, matching, tournaments, etc? Anything for managing the player community? (Please don't say DotNetNuke)

# Answer
> 2 votes
There are a number of frameworks depending on the target platform.

* On PC, you can use Steamworks
* Xbox 360 and PS3 both have matchmaking for full-on developers
* For independent games, XNA allows acess to a limited set of Xbox Live features

I can't think of any others, so beyond these you'd likely have to build your own.

# Answer
> 1 votes
I'm not aware of any, so I'm building something in this vein more or less from scratch. Currently just using libcurl on the client side and Django on the server side as bases.

# Answer
> 1 votes
ElectroServer4 was pointed out in another question as being an off the shelf middle tier.

---
Tags: ranking, tournament
---


# Question
Title: Target Tracking: When to accelerate and decelerate a rotating turret?
Say I have a moving circular `target` defined as:

```
Vector2 position;
Vector2 velocity;
float radius;

```

And a rotating `turret` (mounted on a moving vehicle of some kind) defined as:

```
Vector2 position;
Vector2 velocity;
float angle; // radians
float angularVelocity; // radians per second
const float maxAngularVelocity; // radians per second
const float maxAngularAcceleration; // radians per second per second

```

(Or something along those lines. Note that position and velocity of both are controlled elsewhere - assume velocity is constant and position changes based on velocity.)

I am trying to write two related AI functions to determine, on a given frame:

* What angular acceleration (and in which direction) to apply to the turret's angle to keep the turret pointing at the target?
* If the target is currently in sight, can it (any part within its radius) be kept in sight for `x` seconds, where `x` is a fraction of a second? (Alternatly: is there another strategy to ensure the target is actually "locked on" and not simply flying across the sights?)

And I could use some help...

# Answer
> 19 votes
First you need to determine the difference in angle between the turret facing direction and the direction to the target.

```
Vector2 turretToTarget = target.position - turret.position;
float desiredAngle = atan2(turretToTarget.y, turretToTarget.x);
float angleDiff = desiredAngle - turret.angle;

// Normalize angle to [-PI,PI] range. This ensures that the turret
// turns the shortest way.
while (angleDiff < -PI) angleDiff += 2*PI;
while (angleDiff >= PI) angleDiff -= 2*PI;

```

Once you have these quantities you can set up a second degree expression for the turret angle. You need to compute this on each update to make sure you always use the latest data of positions and velocities.

```
// Compute angular acceleration.
const float C0 = // Must be determined.
const float C1 = // Must be determined.
float angularAcc = C0 * angleDiff - C1 * turret.angularVelocity;

```

Here, the first term (zero degree) in the acceleration expression will cause the turret to begin turning towards the target. However it will not stop in time but rather oscillate back and forth over it. To make it stop we need the dampening second term (first degree) which causes a high turning velocity to be opposed by a high acceleration.

Now the positive constants (not necessarily program constants) need to be determined and balanced to make the system behave well. `C0` is the major control for the speed of the system. A high value for `C0` will give a fast turning speed and a low value will give a low turning speed. The actual value depends on many factors so you should use trial and error here. `C1` controls the damping magnitude. The *discriminant* of the quadratic equation tells us that if `C1*C1 - 4*C0 >= 0` we have a non-oscillating system.

```
// New definition.
const float C1 = 2*sqrt(C0); // Stabilizes the system.

```

You probably should choose `C1` a little bigger than this for numerical reasons, but not too big because it may get very over-damped and slow to respond instead. Again, you need to tweak.

Also it is important to note that this code only computes the angular acceleration. The angle and angular velocity needs to be updated from this somewhere else, using and integrator of some sort. From the question I assume that this has been covered.

Finally there is something to say about lagging, because the turret will probably always be behind when tracking a fast target. A simple way to tackle this is to add a linear prediction to the target's position, i.e. always aim slightly ahead in the target's forward direction.

```
// Improvement of the first lines above.
const float predictionTime = 1; // One second prediction, you need to experiment.
Vector2 turretToTarget = target.position + predictionTime * target.velocity - turret.position;
/// ...

```

As for keeping the turret aimed within the radius of the target for some time, this may be a tough requirement to impose directly on this sort of system. You can be certain that this controller will strive to keep the turret aimed at the target (or rather the predicted position) at all times. If the result turns out not to be satisfactory you have to modify the parameters `predictionTime`, `C0` and `C1` (within stable bounds).

# Answer
> 3 votes
What you have here is a basic control problem. The turret is the system, the acceleration is the control and the sensor measures position/velocity. There are many ways of tackling these problems, as it's a very well-studied problem in engineering.

Key is ending up with a stable system, i.e. a system that does not generate oscillations. This is usually done by adding damping. The wikipedia page should get you started.

# Answer
> 3 votes
What you're probably looking for here is a PID Controller, similar to the answer accepted on this SO question

I had initially answered that question by "rolling my own" but this answer is significantly more complete and elegant.

# Answer
> 2 votes
First off, calculate the vector from turret to target. Then compare this with the turret's current vector. Then use the difference between the two to work out the angular acceleration and angular velocity required to get the turret to turn to point in the right direction within a given time.

OK, that seemed simple. However, you should really try to anticipate the target's position since the target is going to move by the time you've turned the turret. To do this:-

```
Pd' = Pd + t.Vd
Ps' = Ps + t.Vs

```

where P is position and V is velocity and the subscript is d for destination (target) and s for source (turret), which gives a direction vector:-

```
Dsd' = Pd' - Ps' = Pd + t.Vd - (Ps + t.Vs) = Pd - Ps + (Vd - Vs).t

```

where D is a direction vector and Dsd' is the required direction at time t. Now, work out the direction of the turret based on current position and maximum velocity and acceleration for a given time t:-

```
Ds' = t.Ds.Rs -> this is a vector rotation

```

Ds and Ds' are the source directions and Rs is the rotational velocity. With all that, you want to find t for when Dsd' == Ds' and thus Rs, the required rotational velocity. Don't forget that all the P's, D's and V's have x and y components.

I haven't taken acceleration into account here - that adds a lot more to the complexity. Once you've got Rs and t you could probably approximate a parabolic Rs (i.e. accelerate and decelerate) to get the same result.

# Answer
> 0 votes
First thing to do is to calculate the angle between the turrent and the tracked object.
Next thing is to check if using the current torrent speed and applying the maximum acceleration backwards(stopping the torrent) will the torrent stop before or after the tracked object.
If the answer is that the torrent will stop before the tracked object, apply maximum acceleration forward(increasing speed).
If the answer is that the torrent will stop after the tracked object, apply maximum acceleration backward(stopping the torrent).
This way the torrent will alwais arrive the fastest and will stop at the right point(or a fraction after).

---
Tags: ai, aiming
---


title: Managing depth in actionscript3

text:
# Question
Title: Managing depth in actionscript3
I have a `3D` field with many `MovieClip`s in it, and seems like the one last added is the one that overlaps others and not the one with highest `z` value.
Is there any property/function that sets `z-index`? (sorting children by `z` value seems too much like a hack).
A `3D` engine that can place `MovieClip`s will be helpful(but not one that requires custom drawing).
I'm using `Flash CS5` with `ActionScript 3`

# Answer
You need this helper class:

http://blog.theflashblog.com/?p=470
> 2 votes

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


title: Profiling server side game loop in java

text:
# Question
Title: Profiling server side game loop in java
I am looking for tips to profile the server side game loop of a Java program for CPU usage. I tried to use the TPTP plugin for Eclipse so far.

The problem I am having is that it is really slow. For example the startup of the server is normally done in less than a minute. But with the profiler it takes about 30 minutes.

Okay, I can enable the profiler only after the server is started, but I am still facing the problem that it is way too slow and using much CPU. So I am unable to connect a number of clients in order to reproduce the problem (even with disabled timeouts).

I already did some optimization based on no client at all and some very short profiling sessions with one client. This is, however, not really helpful because the game server is doing most of its work only if a player is in reach.

I am thankful for any tips on profiling for CPU usage.

# Answer
> 2 votes
Netbeans has a pretty good profiler built in as well and its free! I struggled to get TPTP to work and YourKit always seemed slow. The Netbeans one seemed to be the best of the bunch.

Some profilers will allow you to mark points in your code where profiling should start and stop. This can definitely help when measuring performance.

However, a really good (but old school) means of debugging is print statements!

Try putting these in at various stages. You can then use a binary chop method to identify the slow bits. We do this all the time and its amazingly effective.

If you have good unit tests there are 3p libs that will allow you to put in timing restrictions i.e. fail the test if it takes more than nnn ms to complete.

# Answer
> 3 votes
Have you tried adding your own "profiling" classes - eg a Timing class that you can call before/after key methods, which will log/track start/end/elapsed times. This could expand into tracking down potential problem areas. This should add only a small overhead. You could also have 2 versions a PROD vs PROFILE version so that you can switch to the PROD one when needed and thus gain back any of the added overhead.

# Answer
> 1 votes
Yeah you have discovered the main problem with most profilers. They profile everything.

You can use options to reduce the profiling scope to some key classes or just time very small bits of your code.

You should already know what is probably slowing it down, so test that part. It will take some time to hunt down the slow bits, but I find it a lot more productive than using a uber slow profiler.

# Answer
> 1 votes
I've had much better success profiling using **YourKit for Java**. I tried TPTP but it is very painful to use.

YourKit also allows for remote connection.

If you want a more simplified monitoring solution you can give **JConsole** a try. This is the bundled monitor program that is distributed with Java.

---
Tags: java, server, profiling, scalability
---


# Question
Title: Experiences of test-driven devleopment in large projects
I've used TDD in personal projects, but I wondered if anyone had any experience of using this approach across a large team? Was there resistence to the test-first approach? Did you keep code coverage high for the whole project? How did coverage survive fixing those two-in-the-morning-and-you-ship-in-four-hours crash bugs? Did you run tests on all platforms, or just assume that passing on one meant passing the others?

I love the decoupled code that TDD produces, and the large suite of regression tests you get for free, but if you only have a few in the team who don't want to contribute tests, won't everyone suffer?

# Answer
Games are notoriously hard to unit test, so I really can't imagine this working out all that well. Also games are not spec-driven. Sure, maybe some low-level components are, but game logic itself is driven by the needs of the designers. The parts of your code that would code usefully do TDD with are also the parts you should probably use a library for (file formats, networking, etc).
> 3 votes

# Answer
The Arianne project had rather bad experience with people writing their tests first and concentrating on implementing something that fits their tests. This may lead to a lost focus on the bigger picture. And it gets a real issue if those people refuse to look at user visible bugs in their code because the tests are green.

From our experience it is way better to write the tests in parallel to writing the program. This way you concentrate on writing code that fits the general requirements and not just the return value of a method. But writing the tests in parallel to the code (instead of later) will result in code that is well structured for easy unit testing.

Automatic low level tests are very important for two reasons: They speed up development because small parts can be tested without starting up the complete application. And they can catch unintended changes done at a later time.

But they are no substitution for high level tests done by other people than the person who wrote the code. If the person who wrote the code made wrong assumptions it is likely that those wrong assumptions are in his own tests, too.

Keeping the team motivated works best when the member belief in automated testing and there is some progress visible: Public coverage and number of tests chart can be helpful. And of course it is a good idea to praise people for writing high quality tests (e. g. no bogus tests for the sake of stats).
> 2 votes

---
Tags: software-engineering, test-driven-development
---


title: Gesture Recognition Strategies

text:
# Question
Title: Gesture Recognition Strategies
Working with the Wii I often find it necessary to recognize simple gestures, so far I've been able to mainly look at magnitude of acceleration in order to recognize the gestures called out for in our game design documents, but I'd like to create a more robust system that allows "recording" of example gestures and recognition of complex gestures.

What strategies have you used in the past? Why did they work? Why didn't they work? What would you do differently?

# Answer
**Edit** Affine invariance requires this version of curvature apparently.
http://en.wikipedia.org/wiki/Affine\_curvature#Affine\_curvature
Assume that is what I am referring to. (Although normal curvature I think is invariant to rotations which could be good enough).
**Edit** for a scale invariant version of curvature look here
https://math.stackexchange.com/questions/1329/what-is-the-form-of-curvature-that-is-invariant-under-rotations-and-uniform-scali

Gesture recognition problems are a subclass of recognition problems, and recognition problems are basically model comparison problems.

Your trying to fit your gesture to some collection of gestures, the best gesture wins.

I would record your gesture several times, and try to fit your training data with something like a b-spline (a curve). You probably want your gestures to be invariant to affine transformations (rotations, scaling, translation), so store the curve as a table of curvature values (It is unlikely to have a nice closed form), as opposed to the Cartesian coordinates of the control points.

That's a model of a gesture. Let's say you have several.

To compare them start by fitting your input data and then evaluate the curvature x number of times, where x gives a good trade-off between accuracy and performance.

Now iterate through the models and subtract the curvature values (evaluated at the same point along the respective curves in terms of arc-length) and square the difference. The value that results is called a residual. Sum up all the residuals. The model with the smallest residuals is the best fit, and is your most likely gesture.

Compare my answer to @Olie's. They are basically the same, although we are choosing different models for the gesture, (building a table of the signed curvature and recording the change in the angle of the tangent are almost the same, I'm assuming the data is generated by a smooth curve with noise though), the main difference is @Olie is including speed.

Picking what parameters to include in your model depends on the situation and performance requirements. Bear in mind that the adding parameters to your model increases the dimension.
> 5 votes

# Answer
In very broad terms, you probably want to define a gesture as a direction, followed by a \[possibly very-short\] delay, followed by another direction (and the relative angles between the directions, etc., until the end.

For example, making a "t" with your wand (and don't forget that some people are lefties, so your definitions should not be hand-dependant!) is a vertical swoosh, short delay, reversal curving out, short delay, reversal headed horizontal, abrupt \[near\] stop.

As you read the gesture, you want to see how closely the pattern read matches the pattern description.

In general terms, you can first cull the definition dictionary by eliminating obvious mis-matches (ones that don't even begin correctly, or that are too long or too short by far), then "score" the gesture against the remaining definitions. Score the gesture by rating each portion as to how well it matched the definition (0-100%) and RMS-ing that (take the errors, squared, sum them, then take the square root of that sum.)

Using RMS accentuates large differences (resulting in a lower score), while tending to gloss over small differences (resulting in a better match.)

There's a ton of material on this stuff -- Google gesture recognition. Don't worry if it's for a stylus or other non-Wii thing, the principles adapt well.
> 4 votes

# Answer
I've only done this with the mouse, but my solution worked really well. I created a join the dots pattern of points to represent the gesture - this is the shape to draw. Then I stored the path of the cursor as it moved around. Next I scaled this mouse path so that it has the same width and height as the target pattern. Every update I looped through all the points of my cursor path making sure they were each within a certain distance of a gesture path node, looking at each gesture path point in order.
> 0 votes

# Answer
I was taught Game AI by one of the lead developers at AiLive (he's in some of the videos), and the short answer is that trying to do these gesture recognitions is just too painful to spend your life on. I'd suggest going the middleware route, and getting AiLive's LiveMove suite.
> 0 votes

---
Tags: algorithm, motion-control
---


title: How do I generate surface normals?

text:
# Question
Title: How do I generate surface normals?
I have quite a few debug drawing methods in my engine that can generate geometry useful for debugging, like spheres and cubes.

At the moment I do not generate any normals for these shapes. Is there a general purpose method of generating face normals and per vertex normals for an arbitrary mesh? (I'd imagine you would need face normals to generate per vertex normals?)

# Answer
> 12 votes
To generate face normals, use the vector cross product of two edges each triangle and then normalise the result. Make sure you get the directions right, otherwise some normals will point in and some out.

Vertex normals would then be an interpolation of all the face normals the vertex is attached to.

# Answer
> 2 votes
There are various ways of interpolating normals between faces. More details here: http://meshlabstuff.blogspot.com/2009/04/on-computation-of-vertex-normals.html

---
Tags: normal-generation
---