title: 3D models in 2D world

text:
# Question
Title: 3D models in 2D world
I want to create a simple Flash game. Let's say, it's about soccer hooligans. I would need the characters to walk around the isometric landscape, drink, fight or whatever it is they do.

Now, how do I create those characters? I imagine it could be possible just to draw a separate movie clip for every action for 8 different directions (will 8 be enough?). But this seems like a little bit of work, to say the least.

Some people recommend creating and animating the models in some 3D editor (3DS Max, for instance). This looks better. But, how do I use them? There's no 'native' 3D in Flash (yet). And I don't really feel like being involved with one of the flash 3D engines (some have overly sophisticated APIs, others have bugs, the rest are not maintained anymore).

I could pre-render the animations to frame sequences and then just download them, right? But that makes a HUGE chunk of data.

Any thoughts or advices?

# Answer
I would definitely go for the 3D modeling and pre-rendering. Even drawing your Sprites from 4 sides is going to be a lot of work and if you have several similar looking characters, you'll probably do that work multiple times.

When using a 3D modeling tool, it's going to take some time to get that base-model done, but after that you can easily create multiple characters from the same base-model by changing textures or add an item like a "hat" or other accessories.

I don't know if your sprites are animated, but if yes, that will also be easier when using 3D.

As for the workflow, I suggest you animate your character in a 3D tool and place (orthographic) cameras for all directions. Then you render the animation with every camera.

Once you got the rendered frames, you can combine them to a sprite-sheet using this technique: What is a good tool for producing animated sprites?

I don't know about your file-size constraints, but these sprite-sheets shouldn't get very large in terms of file-size. If they do, you could still render the animations with less frames (chunky movement) or change them to a indexed-palette (works best if your background tiles all have roughly the same color).
> 2 votes

# Answer
Is this a true isometric game? If so I question the value of using real 3D models since the idea of isometric engines is to create the illusion of 3D without it being proper 3D. Or by 3D models did you mean just the appearance of 3D? In that case 4 different directions should be enough (up, down, left, right) which is not too much work. You could maybe look at reusing some of the animations by scaling them with the Flash IDE transformation tools (so scale the down animation into the left animation, but they will look like flat pieces of paper which you may not want). I would avoid pre-rendering the animations as frame sequences unless you could really keep the size down to something reasonable.

However, maybe you meant a 3D game with the camera aligned in the sky facing down towards the ground (like with SC2). In that case you will need to use one of the 3D engines out there. Papervision has a nice API and plenty of documentation. Some footage of the next gen 3D apis for Flash have been released recently and look promising http://www.youtube.com/watch?v=tgwi0lWgX8w
> 0 votes

---
Tags: 3d, flash, models
---


title: How to use Irrlicht with Objective-C?

text:
# Question
Title: How to use Irrlicht with Objective-C?
Irrlicht uses namespaces, a C++ feature not available in Objective-C:

```
/*
In the Irrlicht Engine, everything can be found in the namespace 'irr'. So if
you want to use a class of the engine, you have to write irr:: before the name
of the class. For example to use the IrrlichtDevice write: irr::IrrlichtDevice.
To get rid of the irr:: in front of the name of every class, we tell the
compiler that we use that namespace from now on, and we will not have to write
irr:: anymore.
*/
using namespace irr;

```

How can I still use Objecive-C with Irrlicht? Thanks.

# Answer
There is a forum thread in which some people are trying to get the OpenGL ES branch to compile for iPhone; there are some instructions there, so you might have success with it in Objective-C.

Here is another thread which covers some Objective-C Irrlicht problems.

At this point it's probably blatantly obvious I'm just searching around to try and help you. If these didn't help I'll just delete my answer, since I am obviously not (yet) a Mac guy. :(
> 0 votes

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


# Question
Title: What are the common character animation techniques used in tile based hack&slash games?
I wonder what kind of animation techniques are used for creature and character animation in modern **hack&slash type tile based** games? Keyframing for different actions may be one option. Skeletal framing may be another. But how about the physics? Or do they use a totally hybrid system of inverse kinematics supported with a skeleton,physics and mixed with interpolated keyframing for more realistic animations? If so, how and for what reasons? I can think of many different solutions for the issues below but I wonder what's used and best suited for issues like:

1. Walking or moving on an uneven terrain
2. Combat interaction, combat physics and collisions
3. Attaching rigid items to character and their iteractions ih physics world
4. Soft body dynamics like hair, vegetation, clothes and fabric in line with animations and iteractions.

# Answer
> 6 votes
Although it may appear to be 3D, 'hack and slash' games (like Diablo) are really 2D games. Often the components (the sprites) are created in a 3D modeling tool, but only the 2D renders of the sprites are used in the actual game. This type of game tends to be much more about the data interactions (the map, the player, the treasures, and the monsters) than about the visual representation.

2D games tend to not use dynamic animation (skeletons and deformations.) Instead, the animations are often created in a 3D package and saved as a library of images. The sprite then has a lookup table of images (either stored as a single massive sprite sheet or as a series of individual images.) During the game animation phase, the sprite determines what image to display based on the sprite's current state. For example, I have an animation of a cow (http://www.aharrisbooks.net/pythonGame/ch08/cow.py) that walks in eight direction. Each direction is an animation of ten frames.

(more examples in Python at http://wwww.aharrisbooks.net/pythonGame)

The sample program checks the direction and frame, then displays the appropriate image. My example is written in Python, but the language is not important; the idea remains the same.

The visual aspects of being in different states (combat, wounded, etc) would be handled by simply adding more animations to the stack.

However, the more difficult aspects of these things are the data aspects. For example, how is terrain managed. I'd likely use a variation of the A\* algorithm to pick a path between where the sprite is and where it wants to go, and I'd add some sort of weight to each node to depict the difficulty of that terrain. (roads would have a very light weight, mountains and oceans would be very 'heavy')

I probably wouldn't worry about soft-body dynamics in a 2D engine. That can be added later, but it's not key to the functioning of the game.

You could certainly build a 'hack and slash' in 3D. However, the added challenges of 3D modeling make it harder to concentrate on the gameplay mechanics which often attract players to this kind of game.

Best of luck to you....

---
Tags: game-design, 3d, physics, animation, tiles
---


# Question
Title: In XNA, should I use the built-in game component classes?
I'm just getting started on an XNA game for Window Phone 7. For my Flash games I have my own framework that I was just going to port from AS3, but I have just found the built-in game component stuff in XNA. So should I use this stuff? Should my Entity class extend game component/drawable game component? I'm sure it will be quicker just to port my AS3 code, but I thought this built-in stuff may have some advantages?

UPDATE: I decided not to use them. It doesn't seem that they are meant to be used in the way I described.

# Answer
I suppose it depends entirely on how you want to do things. I can say that most of the XNA tutorials and examples I've seen use them sparingly. Typically I see the built in GameComponent/DrawableComponent types being used as the base class for services, and then those services call customized draw/update methods on the child-objects they manage.

The main advantage you get from them is that if you add them to the Game.Components collection, the game will call their update, draw, and initialize methods during that phase of the game's cycle. You can get the same effect by just putting your own code into the Game's overrides for those methods and managing object collections yourself.
> 4 votes

---
Tags: xna, architecture, game-component
---


# Question
Title: For a 2D XNA game, should I use the built in Vector2 or Vector3 or port my own class from ActionScript?
I use a lot of 2D vectors in my Flash games - basically all velocities, positions etc I store in this way. My Vector2D class has lots of built in functions for rotation, dotproduct, projectOnto etc. The native Vector2 class doesn't seem to have half of this stuff, but it is used in a lot of places. The Vector3 has all this stuff, but has an extra dimension I don't need. So should I use either of the built in ones or port my AS3 class? Or should I try to extend Vector2 and add the extra functionality I need. Could that cause any problems?

# Answer
> 9 votes
> The native Vector2 class doesn't seem to have half of this stuff, but it is used in a lot of places. The Vector3 has all this stuff, but has an extra dimension I don't need.

I believe you're mistaken; Vector2 and Vector3 both have extensive functionality. Note that **this functionality is exposed as static methods to the Vector2/Vector3 class**, rather than of the form `someVector.operationOn(otherVector)`. So for example, for the dot product of two `Vector2`s, you simply write `Vector2.Dot(firstVector, secondVector)`. In addition, the same set of methods has existed since XNA 2.0, so I'm certain we are not talking about different versions.

Here is the list of Vector2 Members and Vector3 Members from Microsoft. The pages default to the latest XNA version, but you can view prior versions by clicking on the "Other Versions" dropdown at the top of the page, right under the title.

You will see, though, that the class does not implement rotation and projection. Of course, the projection operation is simply `Vector2.Multiply(vecB, Vector2.Dot(vecA, vecB))` so you can write a small function for that if you use it often. For rotation, you should make use of Vector2.Transform and feed it a rotation matrix; I definitely recommend writing a function for that.

Overall, I recommend using the built-in Vector2 class, and I think you'll find it suits most of your needs. The rest, like I said, are very short functions which you can port. But no need to duplicate the entire class, right? But if you feel the need to rewrite it, I don't see a strong reason why you shouldn't, as I can't see how XNA may somehow implement it better than you can.

# Answer
> 2 votes
The XNA Vector classes also have a hell of a lot of functionality, and the Matrix functions take in Vector classes specific to XNA, so personally, I'd probably use the XNA ones. Why reinvent the wheel?

---
Tags: xna, vector
---


# Question
Title: How do I make an extensible engine in XNA?
I making a new engine for my game, based on the component system. Every game object is a set of some components, like render, physics, AI, etc. I want to make my game extensible; I now how to make a plugin system with .NET, but how do I make my game able to add new resources from plugins, at runtime? How should such the plugin that stores content look? I want to make simple system, like *"Total Annihilation"* has, to be able to add new units.

# Answer
> 4 votes
You can create as many instances of `ContentManager` as you like. Just create a new instance for each plugin and set its root directory to something specific to that plugin.

For example, you could organise your plugin directory like this:

```
Plugins
|
+- TotallyCoolPlugin
   |
   +- TotallyCoolPlugin.dll
   |
   +- Content
      |
      +- TotallyCoolImage.xnb

```

Presumably your plugin will have some kind of plugin object that you can use reflection to find and instance. Tell it its base path, so then you can have it create a content manager (or something like this - it depends on your implementation). For example:

```
[PluginMainClass]
public class MyTotallyCoolPlugin : Plugin
{
    public override void LoadPlugin(string basePath)
    {
        ContentManager content = new ContentManager();
        content.RootDirectory = Path.Combine(basePath, @"Content");
    }
}

```

Once you have something like this working, you could expand it with other clever things. One possible example is to use `ResourceContentManager` to embed your content in the DLL itself. Read this and this.

---
Tags: xna
---


title: Flash <=> server, protocol protection

text:
# Question
Title: Flash <=> server, protocol protection
I am making a flash game that will interact heavily with the server. For quite some time already I am using 'request hashing' technique to make sure that request data hasn't been tampered with. This works pretty well. However, in this game I'd like to go a little bit further and completely hide the protocol from the observer (right now it's plain JSON).

I imagine that I could zip and encrypt data (using one of symmetric algorithms). That would make it pretty unreadable by human, right (also smaller)? And SWF encryption/obfuscation should protect the encryption key (it is being done anyway).

As a side benefit that will also protect dynamically loaded resources from directly saving them to disk (or copying from the cache).

**Questions**:
* are there tools that allow you to simply dump the SWF with all its content, received and decrypted? If yes, this will render 'the side benefit' invalid.
* do you think it's worth it to burn all that CPU power?

To support my point, I will say that I like to inspect data being exchanged between client and server. And occasionally I find a bug or two which I can use to my benefit. But then there was a game that was sending and receiving some binary data. Being a lazy attacker, I decided not to analyze further. Otherwise, who knows what I could find :-)

Comments, ideas, criticism, suggestions? :-)

# Answer
> 5 votes
**Yes there are many tools that allow dumping of the full swf, and/or all of the actionscript.** http://www.buraks.com/asv/index.html being one of the many out there.

**No, its not worth the CPU power as it will be easy to crack and design a fake program using your "hidden" key.** If someone is going through the trouble of hacking your game, a "hidden" key and data transfer protocol are going to be easy to find.

Treat the client as hostile, always, and assume any protection that is in the client program will be hacked.

**Design your server software to detect cheating instead of the client.**

# Answer
> 1 votes
The golden rule of security is "always assume that your client is compromised". You're giving the client away, and no matter what you do, someone, somewhere WILL hack it. Unless no-one play your game, of course.

So, encrypting protocol with a key "hidden" in the client is about the same as not encrypting at all. If you're worried about cheating, the best way to cope with it is check everything server-side. If you're worried about players' privacy, use safe protocol like SSL for communications. AND check everything server-side.

---
Tags: flash, client-server, encryption
---


# Question
Title: Objective-C to plain c iPhone game performance improvements
I'm testing a 2D OpenGL ES based iPhone game on both the iPhone 3G and the iPhone 4. It runs great on the iPhone 4... and pretty well on the 3G. The game state is updated at 60 Hz... and the rendering is done at 60 fps. Would the following conversion from Objective-C to c improve the performance at all?

```
// current Objective-C function
- (void) updateSomething {
    // simple update like x_position += 2.0;
}

// plain c function
void updateSomething(){
    // simple update like x_position += 2.0;
}

```

Assume these functions are called at a rate of 60 Hz. **The reason I'm curious is this blog post**. The author mentions substantial performance improvements when making a similar conversion.

Cheers!

Edit: after running w/ the CPU Sampler instrument in XCode it looks like about 65% of the function calls are to **mach\_msg\_trap**. **objc\_msgSend** apparently takes up a trivial amount of resources.

# Answer
> 3 votes
For a function that is called at 60hz you're not gonna notice a difference, a profiler pretty much can't pick up on that. Rule #1, identity bottlenecks - and don't mention fight club of course.
Now if those functions call other functions that call other functions in a loop and call other functions, then it starts adding up.
How much? That you can only find out by trying. But at least try it with the function that are called hundreds of times per frame to get any significant difference.
If you don't use ObjC functionality to begin with (might be smart to at least isolate it for porting purposes might the opportunity arise, and it's good practise to keep platform dependencies wrapped away anyhow) the conversion should be fairly trivial.

# Answer
> 2 votes
I asked pretty much this question on Stackoverflow a while back. The conclusion was that it is quite a bit slower than a C++ virtual function call (which is what I'd compare it to rather than a C function call which is much faster still) and the compiler cannot inline them, but you shouldn't worry about it unless you have a perf problem.

Remember that Cocoa Touch is using Obj-C message dispatch to do all the communication of events within the user interface of the whole iPhone as well as for setting properties when it repositions a UIView during a scroll. So clearly it's not a holdup for realtime animation, but I'm not as sanguine about it as some Cocoa fans. I wouldn't, for example, have a particle system with each particle implemented as an Obj-C object, whereas I'd be happy to implement each as a C++ object (although without virtual functions because they wouldn't be needed).

# Answer
> 2 votes
I think you might have been a bit inaccurate in your description of the problem. It sounds like you are calling this function 60Hz. That is 60 times per second. But given that it updates a position, I assume what you mean is it gets called 60 x number\_of\_game\_objects times per second at least. So it depends on number of objects which you update position of.

Also remember that most of the performance hit is likely due to lack of inlining and cache misses. That will not show up in your profiler as **objc\_msgSend** taking up a lot of time, because the other instructions will be slowed down due to cache misses. A more Data Oriented Design could reduce these problems. E.g. if your Objective-C methods handle collections of objects rather than single objects. E.g. your update method could update several positions instead of just one.

To be fair I don't think your particular example would be a problem performance wise, but in my case I have to simulate that objects move down multiple paths each frame to find an optimal tactical path. Then these kind of update methods gets called a lot of times per frame, and need to be as fast as possible.

# Answer
> 1 votes
I have a couple of games up on the App Store right now that were written in 100% Obj-C. There are definitely some areas where a naive approach would suck in Obj-C (particles, for example), but overall it's not as bad as some people make it out to be.

By using Obj-C, I was able to make heavy use of the foundation collection classes, like NSMutableArray, NSMutableSet, etc, etc. I can't stress how nice it was to be able to just use Obj-C's fast enumeration to quickly apply a change to set of game objects. I use them everywhere.

My suggestion would be to make sure your low level code is written well and not to worry about the higher level code unless you see something that needs to be addressed performance wise. There are plenty of games that you can write without having to worry about dropping down to C++ or C -- even on the original iPhone.

---
Tags: performance, objective-c, c
---


# Question
Title: What external 2d animation formats can I use in android?
For an artist who won't be dealing directly with the code, what formats for 2d animation could they use that would be portable into an android game?

In my particular case there are no collision requirements or anything, just need to be able to place the animation on screen at a specific point.

# Answer
You could use the page flipping technique. You generate the animation as a sequence of images, where each image is a frame of animation. Then if you display each image (or frame) in succession, you get your animation.

You could/should also add all the images to the sprite sheet, so that you only need to load one image, and then just display each portion of the sprite sheet that contains the current frame.

So if your animation images are all 64\*64 pixels, and let's say you have 4 frames in the animation, you would end up with 4 images that each represent a frame of the animation. Those 4 images would be added to a bigger image or 256 * 64 pixels, and when you render each image to display the animation, you would first render only the 64 * 64 first pixels. Then you move over by 64 pixels and render the next 64 * 64 rectangle of pixels.
> 2 votes

---
Tags: android, animation, pipeline, file-format, importing
---


# Question
Title: Why do games dynamically link to the CRT?
Almost all big titles that I have played require you to install the MSVC runtime. There have been numerous questions about "statically vs. dynamically linked CRT" on StackOverflow, the reasons for dynamic CRT generally boil down to:

1. Reduced memory usage if other programs are using the same libs
2. Can update the libraries independently.

But I wonder, how often are these reasons related to game development?

* Most games spend at least a hundred MB of RAM and it's not like saving some KBs really matter. Besides, games are supposed to capture the user's sole attention so he'll probably not be running other programs to share the CRT.
* I don't think I have seen a game needing to upgrade its CRT in its life-cycle.

So, why don't games statically link their CRT so they can reduce the extra step of installing MSVC runtime?

# Answer
> 4 votes
The argument for dynamic linking the CRT is that you get bug fixes for free. If a bug is fixed in the CRT and the user updates his machine and gets the fix then your program is fixed where it wouldn't be if you were static linked.

The argument against is that you get bug fixes for free. You might be relying on the potentially undocumented and incorrect behaviour and the 'fix' breaks your code. Suddenly your game stops working for 'no reason'.

Personally I tend to avoid dynamic linking wherever possible.

# Answer
> 3 votes
If the CRT contains a critical bug, it means they don't need to recompile their huge code base as they would have to do with static linking. it also adds ease to certain debugging tools that replace crt calls(IAT hooks are easier than finding every call instance and rerouting it).

Imo, static linking of the CRT should be avoided, as lot of older games had this, but some of them now suffer due to changes in the CRT of the host not matching what the internal CRT is doing.

# Answer
> 0 votes
Doesn't it come preinstalled with windows? I am not a full-time gamer, but I don't remember a single time when I had to install/update MSVC runtime.

---
Tags: c++
---


title: Runtime Storage vs Static Storage

text:
# Question
Title: Runtime Storage vs Static Storage
**Runtime Storage (hardcoded) vs Static Storage (file storage)**

> *(original question)*
>
> I extended my engines GUI from procedural style to object orientated style, but I still have to create menues, buttons etc. So I got the choice to create each menue via a class or have a static main class which loads menues from a XML file. My problem is that I actually like to have static and external storage in XML because it keeps the code and the project clean. But if a GUI Object is created e.g. a button I want to have delegates/callbacks/events on it, but I think that isn't possible with loading and creating GUI Objects by XML files that only contain ints and strings.

The question is when do you hardcode parts of your game and when do you store them locally.

**Runtime Storage**

\+ You safe time while you do not have to write a parser or something similar.

\- You lose a lot of flexibility in late development

**Static Storage**

\+ You gain a lot of flexibility in the late development

\- You spent a lot of time into a system to read and write, and also handle the storage

# Answer
Well, the rule of thumb is: "If something is going to change a lot, use config files or dynamic scripting. Otherwise, hardcode".

The idea is, hardcoding saves you time now, and soft-coding saves you time later.. provided your config files can be edited more easily than code. So, if your GUI is relatively simple, and you're not going to change it a lot, you're better off hardcoding it. If you want to change GUI rapidly, use XML or some kind of dynamic scripting, but be careful. These systems quite often turn out to be actually harder to read and write than code. Xml is especially prone to that.
> 3 votes

# Answer
My rule of thumb is that if it has double quotes around it, it should probably be in an XML configuration file, unless the double quotes are being used to index into a configuration file.
> 3 votes

# Answer
You need a higher level of abstraction there. You can create a fixed set of functions that can be executed from your GUI elements (OpenMenu, ShowWindow, AddControl...) and then tag each one with a constant string. Then, when adding that property to the XML of the control, you will know what in-game code to execute.

Or, you can extend it with a script/plug-in system that allows bidirectional communication between your game code and your XML files.
> 2 votes

---
Tags: gui, file, xml
---


# Question
Title: Who kept a blog for a year with a new game idea every day, and where is it?
There's this indie game developer who tried to come up with a new original idea for a game every day for a year - and he put all his thoughts on his website. **+200 ideas** so far, if I remember correctly.

I don't remember the URL to his site, or the name of the author. Anyone know what I'm talking about?

\[Delete this post if it doesn't belong here! Just wanted to add it to the blog thread if I managed to find it\]

# Answer
> 27 votes
I think you mean Squidi's 300 Game Mechanics..

I wonder how many of those have gotten actual use. I know the light/dark idea (his first 3 posts) got implemented as fairly popular flash games, but I don't know if he did that or someone else did.

# Answer
> 11 votes
Patrick Curry did "A new game idea every week" a few years ago:

http://www.patrickcurry.com/thoughts/

---
Tags: game-design, assets, blog
---


# Question
Title: What scripting language would you recommend for a C++ game project?
By scripting here I mean not just putting config data in a script, but scripting parts of the project like some class methods, test specific game loop, etc. This would be not just to accelerate development, but also allow players to see some of these scripts to tweak some aspects of the game.

Some language like Lua have some wrappers like luabind, but when I've used it in the past it had problems because it didn't support method redefinition in a context of inheritance.

What are your suggestions of language / wrappers to use or not to use?

# Answer
Lua-scripted video games
Lua-scriptable game engines

I think Lua is the best shot.

This article is about integrating Lua and C++. It says:

> LuaBind is great product but for me it looked too complicated. For one the code is not easy to follow where the classes and objects are. Also seeing that I wanted to integrate Lua into a wxWidgets application, using templates was a bit of a no no (you can read cross-platform issues on the wxWidgets site).

There are many other binding libraries:

http://luabridge.sourceforge.net/
http://www.stackedboxes.org/~lmb/diluculum/
http://cpplua.sourceforge.net/
http://www.tecgraf.puc-rio.br/~celes/tolua/

What is the best C++/Lua wrapper?

Just select and enjoy.
> 10 votes

# Answer
I would recommend Lua.
Python is very popular, too. Many featured game engines (Blender, for example) use it.
C++::Boost has a library to work with Python.
I've read about Squirrel, but didn't use it.

You can read this Game Engine overview. There is a `Scripting` column. You can see that Lua and Python are most popular scripting languages.
> 6 votes

# Answer
I've been liking Chaiscript; I haven't been using it for very long, but it seems pretty solid so far.

Unlike Python or lua, it's built from the ground up to be used with C++. The binding process seems a lot cleaner than with luabind/etc.

Here's the website's summary:

> ChaiScript is the first and only scripting language designed from the ground up with C++ \>compatibility in mind. It is an ECMAScript-inspired, embedded functional-like language.
>
> ChaiScript is licensed under the BSD license.
> 5 votes

# Answer
**Why not build your own?**

If you've got time, patience and the willingness to learn - you could always try developing your own scripting engine with all the features and syntax that you need.

**Advantages**

1. You'll learn about an interesting part of Computer Science.
2. By developing an 'in-house' scripting engine, it gives you complete control from start to finish by allowing you to tailor the engine to exactly what you need.
3. If you need to make any changes later down the road, they can made somewhat easier knowing the in's and out's of your own codebase, rather than learning the in's and out's of someone elses.
4. You won't have to worry about keeping your engine up to date with someone else's patches.

**Disadvantages**

1. Time. Not many people have it. If you need something NOW, try an already existing engine (like one of those already suggested).
2. Speed. A lot of existing scripting engines are very fast - a custom solution may not be as fast.
3. Team Size. A lot of existing scripting engines have larger teams of people working on the codebase, whether that be private teams or global volunteers, there is something to be said for code that is checked and re-checked by many other people.
4. A scripting engine requires a certain amount of initial planning to pull of effectively. There is a lot of groundwork that would need to be implemented as well that may not have to do with the actual scripting engine at all.
5. Your playerbase/developers would have to come accustomed to your scripting engine. This may not be a problem if the syntax and functionality is nearly the same as most modern scripting engines, but just be aware of that.

This is by no means an exhaustive list. If you find yourself having to make an large amount of changes to the back-end of an existing scripting language to get the functionality you want, IMO you should probably look for another engine that fits your requirements more closely or just build your own.

I realize people enjoy throwing around "laziness" and "don't re-invent the wheel" but I think there is something to be said about learning how this stuff is done. And a specific implementation is probably going to be better for your project than a generic implementation.

"Creating Scripting Systems in C++" seems to be the favored article(s) that people share when discussing the topic: http://www.gamedev.net/reference/list.asp?categoryid=76
> 4 votes

# Answer
I've tried Lua, Python, Scheme, and Squirrel. Lua worked out the best; it has a larger community and better support than Squirrel, and much better memory and performance characteristics than Python. Scheme worked really well too, and has a really tiny interpreter, but it was hard for designers to wrap their heads around a functional language.
> 2 votes

# Answer
Here are links to luabind and tolua, wrappers for lua / c++

http://luabind.sourceforge.net/

http://www.tecgraf.puc-rio.br/~celes/tolua/
> 1 votes

---
Tags: c++, software-engineering, scripting
---


title: Skybox Development Help

text:
# Question
Title: Skybox Development Help
I'm a freelance game designer, and I can't afford to hire someone to do skyboxes for me.

However, I am unable to do them my self.

Let's say I have a texture that can be tiled on four sides...

If I put that very texture on each side of the skybox.. It just comes out looking like a cube.

I'd like to know how exactly I need to "warp" a texture, so that when applied to a cube on all four sides, it looks spherical.

Thanks! -- G

# Answer
> 1 votes
You might want to take a look at Sky Domes. Due to their shape it's a lot easier to get a decent result.

Here you can find a tutorial on how to implement it:

http://www.riemers.net/eng/Tutorials/XNA/Csharp/Series4/Skydome.php

And here's a very nice example of how it can look like if you put some work into it:

.http://sites.google.com/site/wlifeengine/home/screenshots

# Answer
> 1 votes
Why don't you try Terragen? It's a terrain generator that allows you to render to the six faces of a cube and save the images to use them as a skybox.

http://www.planetside.co.uk/

# Answer
> 0 votes
If you are a programmer talking about skyboxes, I assume you have some knowledge of the 3D engine / librairy / tool you are using. If not, you should ask questions about this engine / librairy / tool to get help on how to create such a skybox (I mean, the programmer job of creating the entity correctly).

Otherwise, all you need is a nice texture to apply to your skybox and there is plenty of websites that will offer you free textures for you to use in your project.

Here are some that I've found :

http://forums.epicgames.com/showthread.php?t=555904

http://www.tutorialsforblender3d.com/Textures/Skys/Sky\_Box\_2.html

Here is a tread on BlenderArtist and another from GameDev about it :

http://blenderartists.org/forum/showthread.php?t=64228

http://www.gamedev.net/community/forums/topic.asp?topic\_id=201602

---
Tags: textures, sky
---


# Question
Title: Converting a Google Sketchup file to 3DS?
I have a couple models that I've made or found in Google Sketchup, and I want to be able to use them in some programs I have that only support 3DS. What is the best way to convert, without paying for Sketchup Pro?

Right now sketchup can export to .dae, so a .dae to 3ds would be just as helpful :)

# Answer
> 2 votes
Download Autodesk's free FBX Converter. Convert your COLLADA file to FBX, and then select the newly exported file. You will see that the program now gives you more export formats, including 3DS.

http://usa.autodesk.com/adsk/servlet/pc/item?siteID=123112&id=10775855

---
Tags: 3d, models, file-format
---


# Question
Title: Can you develop a game in XNA only on Windows for the Xbox 360?
I'm going to start developing a game for the Xbox 360, its a small homebrew development and I don't have an Xbox 360 yet. Is it possible for me to develop the entire game targeting the XNA framework on Windows, and lastly "Create Copy of Project for Xbox 360" and have it work flawlessly?

What are the issues I would run into? Why do you recommend targeting and deploying to the Xbox 360 during development? and do I really need an Xbox 360 during development?

I'm also planning on using the superbly built Torque X game engine. Would this work well on my PC alone as well? And then transition over to the Xbox 360 without changing much code?

# Answer
First of all - let me say - I have done exactly this (developing on PC and then porting to Xbox 360 late in development) and had only minimal trouble.

With XNA 4.0 and the introduction of the profiles (HiDef is what you want to target for the 360) it has become significantly easier to keep within the specifications of the Xbox.

You basically need to remember that the Xbox 360 has different performance characteristics to a PC. So while your game may port fine, you may have to spend some time doing performance tuning, especially if you are doing anything "fancy".

By far the biggest performance gotcha is the garbage collector on the Xbox 360. It is *slow* \- certainly a lot slower than the one on the PC. So when you are developing on the PC you will want to use the Microsoft CLR Profiler to profile your memory: Once your game has loaded and is running you want to see close to zero allocations (XNA on Windows will still allocate a few things, usually to do with input, that are not a problem on the 360). Here is a blog post about avoiding garbage collector issues.

I recommend buying some Xbox 360 controllers early on, and using those during PC development.

The other thing to be aware of when developing for the 360 is the The Evil Checklist that your game is checked against during peer-review.

You will notice that there's a lot of stuff in there to do with profiles, the guide, the marketplace and particularly storage devices. These cause issues that just don't come up on PC. If your game stores data, does networking, needs to interact with profiles, etc, I would recommend getting an Xbox 360 *early* in your development cycle. Also - remember to build in support for a demo, as it is required for XBLIG.

I also can't speak much about Torque-X, but I assume that it's just a bunch of libraries that use XNA - so it should not cause any issues.
> 8 votes

# Answer
Yes you can build your entire game with XNA targeting Windows, and then with a few minor adjustements, you can also deploy the same code to Xbox360. I think there are a few places where you might have to add some #if #endif conditions, the code for controls and keyboard for instance. That code would be a little different.

All in all XNA is designed to be deployed on Windows and XBox, so it should not be a problem, I have done this before, and after 5 months of programming, our game was "ported" to Xbox too with just a little bit more work.

As for Torque X, I don't know about that, but if it is an engine for XNA, it shouldn't be a problem.
> 2 votes

---
Tags: xna, windows, xbox360, torque-x
---


# Question
Title: How to create endless scrolling landscape using coco2d's CCParallaxNode
I created a horizontally scrolling landscape using CCParallaxNode. However it does not seem to support endless scrolling in one direction. As soon as the first image "ends" the background shines through. Adding an unlimited number of images is of course not an option. I thought about the usual way, namely adding two sprites for each parallax layer next to each other, and simply moving one at the end of the other at the appropriate time.

However, I have two issues:

* parallax child nodes can't seem to be re-positioned
* the position of the child nodes vs how far they have moved seem to be in no relation to the parallax factor

This is how I set up the parallax node using 4 sprites with identical horizontal width:

```
CGPoint topOffset = CGPointMake(0, screenSize.height);
CGPoint midOffset = CGPointMake(0, screenSize.height / 2);
CGPoint downOffset = CGPointZero;

// Create a parallax node and add the sprites to it.
CCParallaxNode* paraNode = [CCParallaxNode node];
[paraNode addChild:para1 z:1 parallaxRatio:CGPointMake(0.5f, 0)
positionOffset:topOffset];
[paraNode addChild:para2 z:2 parallaxRatio:CGPointMake(1, 0) positionOffset:topOffset];
[paraNode addChild:para3 z:4 parallaxRatio:CGPointMake(2, 0) positionOffset:midOffset];
[paraNode addChild:para4 z:3 parallaxRatio:CGPointMake(3, 0) positionOffset:downOffset];
[self addChild:paraNode z:0 tag:ParallaxSceneTagParallaxNode];

```

Did anyone succeed in using CCParallaxNode for seamlessly endless scrolling?

# Answer
> 2 votes
First you will need to have as many sections as are needed so that you can fill the size of the screen plus one. So if you have a screen width 480 and a section width of 480 you need two sections to repeat. If your section width is only 240 then you would need 3 sections.

I would step back from using this CCParallaxNode for now and just get a single layer to endlessly scroll. You can do it by subclassing Layer to make EndlessLayer and then when it pans you will move the sections accordingly and move the floating extra section from the left to right if you are scrolling right (or left if you are moving left). Once you have this it is a piece of cake to just layer as many of these new layer types over each other and just move each one a fraction of what the nearest layer moves. You could even group this behavior into a new class like EndlessParallaxNode.

---
Tags: parallax-scrolling, cocos2d, cocos2d-iphone
---


# Question
Title: Does the older Xbox 360 Elite support XNA 4?
Can I develop an XNA 4.0 game for the older Xbox 360 Elite? Or would I need a newer Slim model?

# Answer
> 8 votes
The development platform for all Xbox 360 models is identical - that's the nice aspect of developing on consoles. The models differ in mostly incidental things like disc drive speed, number of cooling fans, and hard drive size.

The speed of the hard drive and disc drive are the only things that even remotely affect game quality / technical requirement compliance, and unless you're streaming lots of data, they're unlikely to matter for you.

# Answer
> 6 votes
Any Xbox 360 will do, regardless if old or new since they are essentially all the same in terms of CPU/RAM/GPU.

---
Tags: xna, xbox360
---


# Question
Title: How should I structure my menu / game loop?
I'm trying to decide on how to structure my main game loop - every example I've seen of the game loop looks a bit like this:

```
while (true) {
    UpdateGame();
    DrawGame();
}

```

i.e. it ignores the menu. Should my game loop look like this:

```
if (ShowMenu() == Play) {
    PlayGame();
}

PlayGame() {
    while (true) {
        UpdateGame();
        DrawGame();
    }
}

ShowMenu() {
    while (true) {
        HandleUserInput();
        DrawMenu();
    }
}

```

(I.e. the menu and game have separate loops), or should I structure my loop as such:

```
while (true) {
    switch (state) {
    case Menu:
        MenuLoop();
        break;
    case Game:
        GameLoop();
        break;
    }
}

GameLoop() {
    HandleUserInput();
    DrawMenu();
}

MenuLoop() {
    HandleUserInput();
    DrawMenu();
}

```

I.e. one big outermost loop. (or does it not really matter?)

For what its worth I'm using SDL / C (although I'd like to think that the question is language agnostic)

# Answer
> 5 votes
From having read a couple of the related questions posted by Joe I've identified that menu state and game state is often maintained through a stack of states. For example if the user is playing the game and brings up the menu, then after navigating around a bit the game state stack might look a little like this:

* Graphics menu
* Options menu
* Main menu
* Playing game

The game loop is then structured as single outer loop that updates the current state stack (rather than a loop for each state) - This has the added advantage of being able to cope with a far more complex menu system, for example one where multiple states are layered on top of each other, however the previous state is still visible.

```
while (true) {
    // This example only updates the topmost state,
    // however it might be necessary to perform processing on
    // the other states if (for example) the menu doesn't obscure
    // the entire screen and the game itself still needs drawing
    Tick(GetTopmostState());
}

```

The following questions are related to this and cover it in more detail:

# Answer
> 1 votes
That depends a little bit on how the menu is related to your game.

If you are using the standard GUI stack for menus (say you have a traditional GUI form with a drop-down menu but your game in a specialized canvas context) then the event loops are already separated, and you would use the primary event system for your GUI to handle menu events. This won't go into the main loop, because your GUI system presumably already has one.

If instead your menus are part of the context of the game, there are still two options - The menu pops up as part of the game, or the menu state is a completely separate state. In either case, I would probably make the menu elements based on the same kinds of content as the rest of your game, SDL sprites for example. That way, if the menu is integrated into the game, you can just have a sprite group containing the menu elements, and break your event-handling code into code to read traditional elements and menu elements (maybe as separate functions.)

If the menu is in an entirely different state, the easiest thing is to have your entire game switch states and have a new event-handling trigger inside the menu state.

Hope this helps...

---
Tags: game-loop
---


# Question
Title: When to return a reference and when to return a copy?
I was looking at the d3dx math .h and noticed that a difference between the "+" and "+=" operators:

```
D3DXVECTOR3& operator += ( CONST D3DXVECTOR3& );
D3DXVECTOR3 operator + ( CONST D3DXVECTOR3& ) const;

```

Why is it returning a reference in the case of a += operation and a copy in the case of + operation ?

I'm guessing in the first case it's modifying the vector on which you call the += operation, something like this:

```
this->_x += x;
...
return *this;

```

and in the case of a + operation it would be doing something like this:

```
return D3DXVECTOR3(this->_x + x, this->_y + y, this->_z + z);

```

That being said, if that's what happens in the D3DXVECTOR3 implementation, why not return a reference in the case of + operation ?

# Answer
You return a reference to the original vector in a += because you are modifying the actual vector itself and the vector will not fall out of scope.

While in a + you do not want any modification of the original vector. Instead a + operator computes a new value and uses copy constructors to return the value.

If you would try something like

```
D3DXVECTOR3 newVal = D3DXVECTOR3(this->_x + x, this->_y + y, this->_z + z);
return &newVal;

```

You would return a reference to a vector which fell out of scope and therefore will be cleaned up very soon.
> 3 votes

# Answer
**Why is a reference returned for += ?**

A reference is returned because the object is (likely) being modified directly, and as such it wouldn't make sense to create a copy for the sole purpose of returning one.

Note that the reference can still be converted to a copy by other operations (such as =):

```
D3DXVECTOR3 a (1,2,3);
D3DXVECTOR3 b (1,2,3);
a+=b;                 //no copy made
D3DXVECTOR3 c = a+=b; //one copy made

```

So this approach (returning by reference) allows for the least amount of work to be done in each situation.

**Why is a reference NOT returned for + ?**

A reference is not returned for + because a copy is made as part of the operation, so it's returned. Consider what would happen if you added two D3DXVECTOR3's together, like this: (a + b). Which of the two objects should the result be referencing? Well obviously the answer is neither - the result should be a copy. Hence a copy is returned.
> 3 votes

# Answer
In the `operator +=` case, the method is probably modifying the calling object in place. On the other hand, `operator +` is creating a new `D3DXVECTOR3` that is the sum of the calling object and the argument.
> 0 votes

---
Tags: c++, directx, vector
---


# Question
Title: Recommend a game engine with 2D GUI for a UI-intensive strategy game
Yes, this is another recommend game engine request; the 'twist' is I am doing a strategy game and on top of sprites, animation and abstraction of input controls, it has to have GUI support for rather complex controls, such as scroll-bars, select boxes, buttons and such.

I have tried XNA with various GUI libraries, but the problem is that those libraries was not 'completed'. I am just wondering if there are other engines which I can look at?

# Answer
libRocket recently went open source.

It's not a game engine. They describe themselves as middleware. But the library is pretty well done, with focus on removing boilerplate code from you GUI design. It's based on XHTML and CSS, so if you're already familiar with Web developoment it might be a great fit.

But it is not a game engine you'll still need to solve those issues separately. You might find some guidance with this question.
Recommended 2D Game Engine for prototyping
> 5 votes

# Answer
I don't know any free game engines that come with a Windows-level UI library, but CEGUI is a mature solution for those using OGRE.

Another option would be to use GTK+ or your platform's native widget set on Win32 / OS X, and embed an OpenGL context inside one of those widgets. Those are generally the "best" UIs if you're looking for a long feature list.

If your target platform is XNA you won't find much useful. The key selling point of XNA is cross-platform compatibility, which means heavy mouse control is not a priority for people using it.
> 2 votes

# Answer
XPF is still early in development, but it's progressing pretty quickly. It's based loosely on WPF and Silverlight, but it's developed for XNA.
> 2 votes

# Answer
Well, if you don't mind moving away from C# to C++ you could check out HGE. It's a little on the old side but is very easy to use and extend. If you're willing to search the forums a bit you will find ports of it to DirectX 9 and maybe OpenGL (it has been a while). By default it doesn't support things like shaders. It does include sound and input, but no physics or collision detection. For that there is always Bullet or Box2D. For a turn based game or simple real time game that may not even be necessary.

As far as GUI goes its built in GUI is garbage, but you can integrate CEGUI into it. CEGUI is actually pretty easy to extend to different rendering systems, even if skinning it can be cumbersome. The implementation for HGE is two files and they are pretty short.

Clanlib may also be something you want to look into. I haven't used it personally but it appears to be quite powerful and includes a pretty straightforward GUI component. It is also actively developed while HGE hasn't been updated for a couple of years.
> 2 votes

# Answer
As for XNA, have you tried FlatRedBall combined with Neoforce?
> 2 votes

# Answer
You could give Squid a try. It's an engine independent gui sdk for .net (written by me :P). Over here: http://www.ionstar.org/?page\_id=4
> 2 votes

# Answer
If you don't mind making some controls yourself and whish to have many custom controls and looks check out **Scaleform**. It's one of the leading in games menus UI.

You may think of it like a in-game Flash player.
> 0 votes

# Answer
You may consider immediate mode GUI method which is available in **Unity 3D**. Unity 3D is an awsome game engine which does very well 3-D, 2-D and GUI among other things.
> -1 votes

---
Tags: strategy
---


# Question
Title: What other components would one have to combine with Ogre 3D render engine to make a full fledged custom game engine?
I have heard that Ogre 3D is not actually a game engine, rather it is a 3D render engine. I have also heard people claim that one can piece it together with other components (engines?) to create a full featured game engine. So my question is:

* What are the other **types** of components/engines one would have to add to Ogre 3D to create a game engine?
* Also, what are the most popular and powerful examples of these other components/engines?

# Answer
> 7 votes
This question is pretty much 'what is a game engine'. Game engines are whatever software is needed to make a game, and there is no accepted checklist of what needs to be in such an engine for it to qualify.

That said, any simulation-style game will essentially do three things: acquire input, perform simulation, and present output.

For input you need to consider spatial peripherals such as mice, keyboards, joysticks, joypads, tablets, touch-screens, computer vision systems like Kinect, Wiimotes, etc. You might also consider audio peripherals such as microphones and indeed speech-to-text one layer up from that. The network is also another potential form of input.

For simulation, a lot of this is game-specific so it's hard to provide generic functionality that suits all games. But systems that may exist for this purpose could include physics simulation, pathfinding and planning algorithms, hooks for script-based decision-making, different types of time-based animation, and so on.

For output, the classic one is graphics - typically divided into the presentation of 3D models (which in turn tends to divide into environments and vehicles/characters) and 2D sprites and particles, but often with some overlap between the two and additional functionality for post-processing. There may also be support for video streaming support, multi-monitor displays, a GUI/HUD system, etc. Beyond graphics you have sound, usually including positional and non-positional sound effects, streamed music, and maybe filters to apply to the sound. Other forms of output include networking (again), force-feedback devices, log files (often more complex than you think), on-screen debugging aids and overlays.

There will also be some systems that exist outside of or parallel to the simulation which are useful for development - eg. tools for creating and manipulating game assets, persistence of game state (for save/load), script editors, internationalisation and localisation tools, test suites, etc.

How many game engines contain all of the above? Probably none of them. I expect some of the commercial offerings come pretty close however.

What would you have to add to Ogre to get a full game engine? Well, you find out what you need for the kind of game you want, see what Ogre provides for you, and add the rest.

# Answer
> 1 votes
I'd say the most important are:

Sound Physics Networking

Of course, depending of the kind of game you want to do, you have to choose how to implement the game architecture and the AI. I don't really know if there is a common way to program AIs of such or such kind. And you may also strike out networking if you want to make a solo game.

Of course there are dozens and dozens of other feature you might want to implement in a game engine, but those are subject to how you plan to design your game engine. Things like game file loading, GUI...

Sound: Fmod, IrrKlang Physics: Havok, Bullet, PhysX Networking: I don't really know if there exists a popular networking engine... networking in a game has already several architectures to choose from and even then, it depends a lot on the architecture of the game (I think).

---
Tags: ogre, physics-engine
---


# Question
Title: Can I develop XNA games without an XNACC subscription?
I'm looking forward to buying an Xbox 360 Slim 4GB to get started with XNA development. Can I develop games/apps on my Windows PC and deploy them to the Xbox without a Creators Club subscription? I'm not looking at publishing my work or putting it up on a marketplace.

And does this model of Xbox 360 support game deployment and storage? I heard that it doesn't. Can anyone confirm which model of Xbox I should purchase to begin XNA development? If I buy the 4GB Slim what development features would not be supported?

One MSDN deployment article says:

> At the very least, you will need a Silver Xbox LIVE membership, an XNA Creators Club premium membership, and a hard drive for your Xbox 360 console to be able to develop games for Xbox 360 using XNA Game Studio.

Another deployment technique article is a little ambiguous.

# Answer
> 5 votes
If you're a student, head over to www.dreamspark.com and you can get a free one year Creators Club subscription. It doesn't include access to the premium materials on the website, but it is enough to deploy to your 360.

---
Tags: xna, xbox360
---


# Question
Title: Using "friend" classes in game development
Typically in C++ game development speed is valued over encapsulation, you therefore see a ton of publicly accessible class members which really shouldn't be public.

I seem to find in most cases that only a very select few clases really need to known the inner workings of another classes to the point of modifying or reading their private data.

Creating public getters/setters for this private data exposes things which really shouldn't be modified willy-nilly.

Would a compromise here be to use friend classes? or is there some drawback to friend classes I'm not seeing.

# Answer
There are two major drawbacks to friending classes.

1. You can't pick and choose what you want to expose to your friends. It's all or nothing. This can prove problematic if you're trying to enforce mandatory use of some kind of non-inconsequential setter.
2. Your two classes are now somewhat coupled in the sense that the friend-er knows about the friend.

That being said, using friend classes can definitely improve encapsulation, especially if the alternative is public getters/setters.

Also, related question on SO: https://stackoverflow.com/questions/521754/when-to-use-friend-class-in-c
> 8 votes

# Answer
Encapsulation is nice, but separation of concerns is nicer.

A class accessing "some private part" of other class could indicate that the code isn't well designed in the first place.

Every time you find yourself in the "gosh, I need to make a friend class here" spot, the question you should ask yourself is "am I doing this correctly, or is there a cleaner way?" (a.k.a. "Is this going to bite me in the ass later on?").

If you are sure about the "friendliness", put it there without hesitation.
> 5 votes

# Answer
Another option is to use the PIMPL idiom, where part of the structure's implementation is a pointer to another type. Most users of the class will just include the normal header file, where the implementation is an opaque pointer. Classes that need access to the private data can include the header defining the other type, and use the interface it provides.

This a common pattern for C programmers wanting friend-like functionality. In my opinion it also hews more closely to thinking about separation of concerns (a generally good design principle that leads to reusable, orthogonal code) rather than encapsulation (an OO-specific technique that is useful for implementing separation of concerns, but also often misused to overcomplicate things).

It has an advantage over friend that it doesn't couple the friend-er to the friend-ee at all. Some people might claim that's a disadvantage, since now anyone can "friend" your class. I think that's an unwarranted fear, since you're still making the relationship explicit (by including the header). If you're afraid of that, you're afraid of your (or your coworker's) ability to make smart architectural decisions. But if you can't make those decisions properly later, why are you trusting yourself with `friend` now?

It has a disadvantage of runtime cost. By storing the data in a pointer you have worse cache coherency and more allocation counts, and you also need a destructor to clean it up.
> 2 votes

---
Tags: c++, architecture, design-patterns
---


title: how to breakdown my game project?

text:
# Question
Title: how to breakdown my game project?
I am a newbie so when ever i start over i get stuck how to organize things (code) or what should be the order of my work. Can you share your experience of project granularity so i can make my mind what should be done first and so on.

# Answer
Here are the general steps I would go through:

1. **Understand what your goal is** \- Without a clear understanding of what you're trying to achieve, you'll have a hard time completing a project of any scale.
2. **Write the rules down on paper** \- Every system has rules. Take the time to write them down in bullet format. This will get your brain thinking about the logic, and will provide you with a handy reference to use later on.
3. **Rewrite the rules to follow the programmatic flow** \- Keep the rules in bullet format, but reorder and indent them, so they form an outline of the programmatic flow.
4. **Write the pseudo-code** \- Using your outline as reference, write out the pseudo code.
5. **Create the classes** \- Make a list of classes you'll need, based on your pseudo code, and implement them.
6. **Replace your pseudo-code with code**

The process is a little slow, but it has a number of benefits to someone in your situation:

* Each step creates documentation that can be referenced in future steps
* You have multiple opportunities to catch mistakes in your logic before you ever touch code
* It's very easy to see how logic should breakdown into code
> 4 votes

# Answer
Mostly it sounds like what you need to do is read up on software engineering. The approach I use is called the spiral development model. In this model you repeatedly do the software development cycle(design, code, test, release) on an ever slightly expanding project.

Lets say we were going to apply this to a 2d shooter.

first spiral open a window.

second spiral get player on screen and moving to user input.

third spiral get enemies on screen.

fourth spiral be able to shoot stuff.

5th spiral ad AI to enemy units.

6th spiral polish.
> 3 votes

# Answer
I recall this tutorial being quite helpful in learning to refactor and (re)structure code - while doing something fun (physics engine with opengl visualisation). I especially enjoy the way test-driven development is introduced in a fairly practically way..
> 1 votes

# Answer
Make sure to know what you're doing. Have a definite plan, design document, whatever - you don't want the problem of 'done that, ooh this sounds good-I'll add this. Oh and this and maybe I'll try adding this thing I just though of'.

I cannot remember if this is top down or bottom up. It's one of them. But if you're newbie, a very important point is to get stuff done. I mean:

* Don't spend weeks on a highly generic system.
* Make sure you make your game, not an engine.
* Get stuff on the screen. This is the best way to make sure you stick with it; you'll feel better about having a square moving around shooting red balls than having a 2d sprite animation and component system and not even a window open.
> 0 votes

---
Tags: software-engineering, project-management, motivation
---


# Question
Title: How to develop a concept to receive funding?
I have a game concept which I wish to develop but don't have the funding to begin it.

What should I do?

# Answer
> 11 votes
I recommend that first, you really evaluate your concept. What are the issues in funding it? Why do you need someone to fund it, are you capable of building it yourself (or with some friends) sans-funding?

To put it the best, and nicest way, I can. No one, will fund a AAA quality game (if this is what your concept is in your head) if you don't have a track record of quality selling games.

So what do you do if you are in that boat? The only way to get funding is to make, well... pretty much all of the game without funding. Then you could get people to possibly reimburse you and handle marketing (but you'd be giving away most of your IP in the process more than likely) but if funding is what you need that's where you are.

In the event that you need funding to pay people to develop your idea because you are just an idea guy, you are going to need to learn some if not all of the skills (to some capacity) necessary so that you can make the demos that attract people to work on your titles.

But yes, this question has been asked time and time again. I recommend you read.. well everything here:

Sloperama Game Development Advice FAQ

# Answer
> 5 votes
Without specific details about your game development background, your game, etc, it is difficult to answer your question. Could you please edit your question with details about the following:

* What is your game development background?
* Have you ever made a game before?
* Is your current game idea similar (or smaller) in scope to previous games you've developed?
* How large is the game idea scope?
* What **specifically** are you trying to raise funds for?

Understand that although these questions are fairly personal, they just scratch the surface of what any potential investor might ask. I'm not asking that you disclose your complete game idea, just the information necessary for people here to give you answers that are accurate for your situation.

Below are some resources I think you may find useful:

---
Tags: business, fund-raising
---


title: Rendering a 3D scene without a window

text:
# Question
Title: Rendering a 3D scene without a window
This is kind of an odd question, but what would be the best solution for rendering a 3D scene without a render window active? The end goal would be to simply render a 3D scene to an image file.

I have done similar things in the past with DirectX and XNA but both required me to have a render window running in-order for the API to initialize. Is there a way to render directly to a texture so that you could perform the rendering with a DLL file in other desktop applications?

The way I envision it working is you create a self contained DLL which has all the rendering logic, a user is using a standard windows application to customize his parameters, once he has them locked he sends a render request to the DLL and it responds with a PNG file of the rendered scene. Ideally this would be a CPU based render since performance is not a huge issue.

Are there APIs out there which one could use to accomplish this?

# Answer
> 1 votes
It sounds to me like you are looking for a ray tracer. It has many benefits over rasterization but if you need something fast then it might not be for you.

> **Ray Tracing** is a technique for generating an image by tracing the path of light through pixels in an image plane and simulating the effects of its encounters with virtual objects. The technique is capable of producing a very high degree of visual realism, usually higher than that of typical scanline rendering methods, but at a greater computational cost. This makes ray tracing best suited for applications where the image can be rendered slowly ahead of time, such as in still images and film and television special effects, and more poorly suited for real-time applications like computer games where speed is critical. Ray tracing is capable of simulating a wide variety of optical effects, such as reflection and refraction, scattering, and chromatic aberration.

I am not aware of any major ray tracing specifications or platforms other then openrt. However, it appears to be an outdated project now.

I would recommend visiting the "ray tracing" forums (http://ompf.org/forum/) if you have more specific questions. Also, they have a tools section where you may find something that suits your needs. For example TinyRT is a good place to start.

Also, here are some articles to get you started:

**C#:**

**C++:**

# Answer
> 1 votes
That's pretty easy to do with both DirectX and OpenGL: You initialize with an hidden window (for OpenGL and DX9) or no window at all (DX10+). Then you create FBO or RenderTargets of arbitrary size and do all your rendering into those. This also allows you to render images with higher than screen resolution without problems. In all that cases, no window will be visible to the user and no rendering is ever blitted on the screen. You can read back those buffers by simply mapping the underlying surface.

You might consider to write a renderer in CUDA/OpenCL, in that case, you can just create a buffer on the GPU to write to. The reason for using DX/GL/etc. is that you usually can get results on screen faster than writing your own ray-tracer :)

Of course, if you just want to render an image, a CPU only implementation is probably the easiest thing to do. As mentioned, look at Aqsis for a complete renderer which can be linked into your app. It basically boils down to providing some API to pass data from the app to the renderer and retrieve the image. Usually you don't want to send PNGs back though, but rather provide a callback so the calling application can provide progress output as well as store it in any format it wants.

# Answer
> 0 votes
There are lots of software rendering programs out there. The most common model is just to execute the renderer as another process, rather than call into a DLL. (Though, that exists as well.) Depending on your needs you may find that Aqsis or LuxRender suits your needs. Another renderer to check out is PovRay.

Many such applications exist. Hopefully, those couple of examples will give you enough information to get you started.

Another way to go would be an OpenGL FBO. That's basically rendering to a texture in memory on the GPU. You can then use it for whatever you want, such as reading back to host memory, and writing it out as a PNG.

---
Tags: 3d, rendering, image
---


# Question
Title: How to orient a surface normal to a cubic surface
**The immediate question is: in HLSL, how can I orient a surface normal generated in UV space so that I can apply it to a cube face?**

The overall project is that I'm trying to build a procedural planet generator. I'm using a cube projected to a sphere where each face is a quad-tree. The intermediate project is that I want to generate a normal map for the terrain. I think the best way for me to do this (and understand what I'm doing) is to generate the normals for the cube version first, then work out the transformations to warp those normals to the sphere.

Ideally the method would not involve branching code based on which face I'm working on (i.e., if we're on the top side of the cube, then U = X and V = Y). In other words, what I'm hoping for is some math-magic like "Oh, just cross multiply the terrain normal by the dot product of the cube face normal and blah blah blah".

**9/20/10 ETA:**

I know how to calculate normals for a flat surface. My subsequent problem is two-fold:

1. How do I rotate the normal map so it is oriented correctly on each of the cube faces?
2. how do I warp the flat normal map so that it wraps the sphere?

I've found one solution that uses a Jacobian matrix, but I can't get it to work. Even when all of the normals are pointing straight up (i.e. a flat surface), the HLSL code involving the Jacobian totally messes up the lighting--so it makes me not trust my implementation of the solution.

# Answer
Your normals should be in tangent space, that way you can apply them onto any surface for which you can create a tangent space (trivial for spheres.) Basically the normal map describes how the normal differs from the actual normal on a small patch on the surface. The tangent space is what you probably try to get with your Jacobian matrix -- for a sphere, you can create a tangent space coordinate system at any given point by using the normal at the point and two perpendicular vectors -- just orient them consistently (for instance, along u and v) and you're done. You can then translate your incoming light vector into tangent space (or the other way round) and light with the new normal. The advantage is that your normal map will work on any object with a defined tangent space and UV mapping.

On the cube, your tangent space for each face is simply that face itself (i.e. if you have a face which has a normal -Z for instance, and your tangent space up is +Y, you just rotate that normal using a matrix which maps -Z to +Y.)
> 3 votes

# Answer
"I know how to calculate normals for a flat surface." Exactly how are you doing this? As far as I know, you shouldn't have to do anything to map it to a sphere other than map your UV's to the sphere surface correctly. Normal maps are always in a "flat" plane because the texture itself is "flat". The shape of the object that you apply the normal map to shouldn't matter.
> 0 votes

---
Tags: procedural-generation, terrain-rendering
---


title: Coordinates from 3DS Max to XNA 3.5

text:
# Question
Title: Coordinates from 3DS Max to XNA 3.5
My problem is this. I have a simple box made in 3DS Max 2009, the Box is 10x10x10. I've tried to load it on XNA and traslate the camera for 15 units, but I can seem to find the values needed to see the box properly. Can anyone point me to a good resource where I can find some good introduction to XNA coordinate system and how is a simple box made in 3DS Max imported properly

Best regards, David

# Answer
> 4 votes
According to the MSDN:

> The XNA Framework uses a right-handed coordinate system, with the positive z-axis pointing toward the observer when the positive x-axis is pointing to the right, and the positive y-axis is pointing up.

Here is a video on how to export animated 3d meshes from 3DS Max to XNA, using kW X-port, which is a quick and easy way of exporting 3d meshes as DirectX .x model files and loading them into XNA using the SkinnedModelProcessor.

# Answer
> 2 votes
You need to apply the bone transforms to the model before drawing it. Check the "Draw the model" section in the following page for a example of what you need to do:

http://www.toymaker.info/Games/XNA/html/xna\_models.html

---
Tags: xna, c#, coordinates, 3dsmax
---


# Question
Title: Multiplayer Implementation, Can I implement it later if I chose to?
I plan to use XNA to build a game project. I'm not entirely sure at the moment if I want to add multiplayer functionality or not, bearing I have a lot of other problems to solve that I'm still new at. I don't want the project to necessarily get out of hand.

My question is, If I head into my project with no plan to add multiplayer support, is it easy to go backwards (It's usually not) and add the necessary code to capture a multiplayer game?

# Answer
Here is sound advice taken from the Zoidcom networking library manual:

> If your project is in the planning stage, it is advised to design the project for networking right from the start. Bolting on network code in a late state of the project will most likely either lead to massive refactoring or a large amount of hacking, resulting in hardly maintanable and bug ridden code.
>
> The cleanest way is to implement the whole game as if it were a pure network game. That is, implement code for a dedicated server, and implement this code for being server code only. Implement the game client code in a similar manner. Server and client can run in the same process and don't even need to use a real network socket, but they should be seperate entities and all code should be designed to work that way. When the player jumps, don't alter the player's jump vector directly, but send a 'jump-key-pressed' packet to the server and let the server handle that.
>
> This means that even in a singleplayer game, there is an invisible server running in the background. A multiplayer version of the same game just needs to connect to a remote server instead of the local one et voila, multiplayer done. The advantages of this are:
>
> no seperate code for single and multiplayer the network code is tested and developed during the whole project clean code
>
> Projects using this scheme are almost all games using any of the Quake engines, Civilization 4, Neverwinter Nights and many many more.
>
> For connecting client and server in the same process with zero latency, local sockets can be used. These are provided by Zoidcom and pass packets directly from one ZCom\_Control to another, without going through an OS level socket.
> 23 votes

# Answer
I agree with the advice quoted in Leftium's answer; **design it for networking from the start, because you won't be able to add it later**.

The first time I tried to make a multiplayer game (I wasn't even trying to make a single player game!), I figured I would first get the game working and then add networking. Bad idea. I was left with a prototype of a really boring single player game and no clue how to transform that into a multiplayer game. I scrapped it entirely and started over, this time writing multiplayer networking code right from the start. Everything clicked.

I'm sure it's not *impossible* to start with a one-player game and add multiplayer functionality. If you think it through, plan it correctly and make sure you know your strategy then sure, give it a try. I think it would be an interesting puzzle to work through at the very least. But really make sure you know your plan as to how you're going to add networking.

I think there is a middle ground (though I've never tried it). You could write some dummy classes for networking/multiplayer features, and be diligent in using them as you're writing the single player game. Then later, if you decide to implement multiplayer, just fill in the dummy classes and you'd be most of the way done. This very much approaches the server/client method, but you might be able to get away with less work; after all, a single player game is easier to make than a multiplayer game, so if you're going to write your single player game like a multiplayer game then why not just make it multiplayer?
> 2 votes

---
Tags: game-design, xna, multiplayer
---


# Question
Title: Can I develop XNA using an Xbox 360 in India?
I'm sending an Xbox 360 to a guy in India. Will he be able to play the games I'm sending along in India? Will Xbox Live work in India with my US-bought Xbox? Can he do XNA development on it?

# Answer
> 2 votes
According to the Create MSDN forum, your friend will be able to develop XNA games, and deploy them locally to the Xbox, but cannot upload them to the XBLIG store nor download other people's games, as there is no XBLIG store in India.

It is possible to set up a US XBL account from elsewhere in the world. I suspect there are many legal issues involved if you try to do that and then accept payments. The XNA XBLIG FAQ contains several questions related to this \- I'd suggest consulting a lawyer or reading it and your tax codes very carefully.

---
Tags: xna, xbox360
---


# Question
Title: Offline XNA Deployment to XBOX. Can it be done?
Well,

The question is pretty explicit on its own. I want to know if I can deploy a game from my PC directly to a XBox. I'm not a professional developer of games, I do it on my free time because it amuses me, but nothing else. Im planning on buying an XBox but only if I can connect directly to my Visual Studio and test the games. I don't want to connect to XNA creators club or anything like it, is this possible?

I have XNA 4.0 with VS Ultimate 2k10

Best regards and many thanks in advance, David

# Answer
> 5 votes
No, you need to be connected to Xbox Live at all times. If the connection drops for any reason you will be kicked out of your game. Therefore, if you are offline, you cannot run any XNA games.

You also need an XNA Creators Club membership to deploy onto the Xbox 360. This plus Xbox Live Gold will set you back about $150. If you are a student you can get a free version of the XNA Creators Club membership over to www.dreamspark.com. However, it is not the same as the full version and does have limitations.

# Answer
> 3 votes
Well, you do need the XNA Creators Club membership activated on your Xbox, in order to get their app running (which connects to your computer and to the Visual Studio add-in). But once you have that app in your Xbox, the act of running (or debugging) your game is as simple as hitting the "Start Debugging" button in VS. The game is automatically transferred to your Xbox and starts. You can even pause it and debug it via Visual Studio. It's really neat!

---
Tags: xna, xbox360, xna-4.0
---


title: Questions about rendering access in UDK

text:
# Question
Title: Questions about rendering access in UDK
I also asked about this over on the UDK forums, but haven't had much luck getting any responses. Basically, I have some experience with UT3 modding, but I'm just getting started with the UDK, and I have a few questions about the degree of control over the rendering you have.

1. I gather that, despite the presence of several HLSL shader files in the UDK distribution (with the extension .usf), there is no means of implementing your own shaders outside of the material editor; is this correct? (I know about the Custom node in the material editor, but it's very limited, and unwieldy for all but the simplest logic.)

3. I understand that UE3 employs deferred rendering. I know you can access the color and depth at the *current pixel* in a post process. However, is there any way to access these or other G-buffer attributes in a more general way? (Normals, position, values at neighboring pixels...)

5. Are render targets supported in a general way? For the sake of argument, would it be possible to set up a camera to render depth from an alternate POV, then do shadow map-style depth comparisons while rendering the main view?

7. Is it possible to override all the materials on the client (en masse), such as those being used for the terrain or BSP geometry in the current level? (For implementing alternate vision modes and things of that nature.)

The tools that come with the UDK are of course very polished, and it's hard to beat free Scaleform and SpeedTree, but I'm starting to think the platform is a terrible fit for anyone who wants to go above and beyond drag-and-drop material editing in terms of graphics. I feel like I have much more control over the rendering in a Source engine mod, for example.

# Answer
I realized I should probably update this, in case anyone reading this neglected to click through to the thread on the UDK forums. I was told by a moderator that everything I want to do is impossible without engine modifications.

> 1) Unfortunately the custom node is the only way to get HLSL into UDK materials.
> 2) UE3 doesn't do full deferred, so only color and depth are available in postprocess effects. There's currently no node that lets you access position at the current pixel, but it would be very useful (and this calculation is done in lots of shaders like shadow filtering).
> 3) Rendering from alternate POV's is supported through scene captures, but the only attribute that can be captured is color.
> 4) This is only possible with changes to engine code.
> Basically all the things you are asking about require full access to UE3 source.

Citation: http://forums.epicgames.com/showthread.php?p=27609556#post27609556
> 1 votes

# Answer
1. I seriously don't see a lot which couldn't be done with MaterialEditor. You can do almost everything that you need. One could argue that the material-editor isn't generating optimal shader-code, but the shader-compiler does a great job in optimizing the autogenerated code here. So, just try it. A lot of AAA games were developed with this toolchain and a lot of these just worked completely with materials built whith this editor. But to answer your question: No, this is not possible with the plain UDK.
2. UE3 does not use deferred rendering. The shadowing system uses a kind of deferred technique on top of the forward renderer. But the renderpipeline is not deferred at all, so no G-Buffer or anything like that are available. More info about this: http://www.unrealtechnology.com/Downloads/Slides/xfest-gfx.ppt Unfortunately I was not able to find other publicly available documentation of the internals of UE3 with a quick search, so I hope this presentation gives you a good overview. The access of neighboring pixels is possible out of the box. Take a look at the DOF or Bloom posteffect. I am not sure if this is implemnted in code or via the Material-Editor, but if it is in the MaterialEditor, than you should be able to find an working example for this.
3. You should take a look at the SceneCaptureActors. These can be used for render-to-texture stuff, but I'm not sure how much tuning possibilites you have for the out-of-the box UDK actors. You than can use this rendered texture in a material. Unfortunately your specific case ( rendering the depth ) is not supported in the UDK out of the box.
4. No, this is not possible, but you could do a workaround by using Material-Parameters which are handled in the Material ( so one material would contain the shader for both modes ). You than can change the Material parameters via Kismet, which would allow you to do exactly what you need.

In my opinion there isn't a lot that you can't do with the UE3 rendering-wise. The drag-and-drop material editing and the level-editor centric design might be not what a programmer expects, but it is exactly what content-guys are needing. This has proven itself as a really good solution at the end of the day. This of course requires that the content creators know the system and it's limitations.

You should just give it a shot and try to build what you need using the tools the UDK provides. I am very positive that you will be able to get what you want.
> 4 votes

# Answer
For what you're asking, I would **not** suggest the UDK. You do not have native access.

Even if UDK did provide you script access to what you're asking for, it would be insanely sluggish, as UnrealScript is not the fastest of languages.

Unreal does not use deferred rendering. Where did you hear this? Some licensees have implemented deferred rendering; but, natively, it does not ship with it.

Other than that, I'm not a graphics guy :)
> 0 votes

---
Tags: graphics, rendering, udk, unreal
---


# Question
Title: How to implement a starwar energy shield in game
I am using Ogre3D.

How can I implement an energy shield like this image?

In the picture, the shield is a semi-sphere, where I want to make it a sphere surround my object. The shield should be transparent (this should be adjustable). Can the community advise how to do this? Thanks.

# Answer
I would use:

* a semi-transparent sphere with a nice texture on it,
* a collision detection system to understand where the sphere has been hit,
* vertex and pixel shaders to implement ripples leaving from the contact point (maybe even with bump mapping, without actually displacing vertices).
> 6 votes

# Answer
The magic in that screenshot is the Fresnel effect at the border. A plain transparent sphere with a texture is not sufficient. There is a demo in the Ogre programming book, but I don't know if sources are available.
> 3 votes

# Answer
For the "border" effect on the shield, you could try some Fresnel/Rim lighting shader.
> 2 votes

# Answer
Wouldn't that just be a sphere with a partially transparent texture on it? You would need to break it into discrete polygons, but any 3D modeling package will have a drawing tool for this. The shimmer effect might be a little trickier, not sure how complex you are looking for though. Are you trying to do that kind of rippling impact animation too? The "right way" would probably be to implement it as a geometry shader, but that might be a lot harder than you need.
> 1 votes

---
Tags: ogre
---


title: Correct Blitting 2 surface problem

text:
# Question
Title: Correct Blitting 2 surface problem
this is a graphics/math problem. Consider this 2 sprite / surface

As you can see they are a tank and his gun turret. Now, i manage the turret rotation, and it works, and, also, the rotation of the tank on the screen.

What it'snt work is the correct "blitting" of the turret on my tank.

The problem is that the turret is never blitted correctly on the tank. This is a math problem, and i'm not so good in math ! How can i correct blit the turret centered on the "right" hole of my tank sprite ?

I'm using c# and sdl.net and actually i blit the turret with this code ( 13,13 are the X and Y position of the 'black' hole of the tank, but, i know, this is not the right method to blit it!):

```
            Surface tmpsurf = new Surface("graphics/tank_turret_long.png");

            Surface turretSurf = tmpsurf.CreateRotatedSurface(cannonangle);

            turretSurf.Transparent = true;

            turretSurf.TransparentColor = Color.Black;

            Point posTurret = new Point(13+this.X,13+this.Y);
            Video.Screen.Blit(torrettaSurf,posTorretta);

```

Thank in advance

# Answer
Your problem seems to be that you're blitting the turret with respect to its top left corner, when you actually want to blit it with respect to the center of the actual turret. Now, assuming your turret has its center at `x_1`, `y_1`, rotating it clockwise by `theta` degrees should give you a "new" center at `x_2=x_1*cos(theta)`, `y_2=y_1*sin(theta)`. You then have to line this up with the center of the turret hole, located at `13,13`. This shouldn't be a problem (keep in mind I'm not very versed in C#, so this is probably syntactically incorrect):

```
Point posTurret = new Point(13 + this.X - x1*Math.cos(cannonangle),
                            13 + this.Y - y1*Math.sin(cannonangle));

```

Where `x1` and `y1` are the coordinates of the center of the turret in "`tank_turret_long.png`".
> 1 votes

---
Tags: c#, algorithm, mathematics
---


title: Importing a .x file to 3D Studio Max?

text:
# Question
Title: Importing a .x file to 3D Studio Max?
I've been googling this for a while and haven't been able to find anything (blenders importer does not work). How can I import a .x file to 3D Studio Max? There are heaps of resources in converting formats readable by Max to .x but not the other way around.

# Answer
If you download Milkshape, you can import the DirectX file and export it as a Collada, Fbx, or Obj, which can be imported into 3DS Max.
> 2 votes

---
Tags: 3d, directx, models
---


title: 2d map: how to manage it?

text:
# Question
Title: 2d map: how to manage it?
i'm developing a 2d game (top down), and i'm a beginner. Now, i've to create a map, with object (to interact with) ... I don't know how to .. manage the problem ! Does anyone can help me ? What are the methodology used ? Thanks

# Answer
> 5 votes
I answered with the following for this question. If you look for tutorials for using these technologies, you should be able to get started or at least have other more detailed questions.

Two programs you should at least take a look at are **Mappy** and **Tiled**. A library for XNA integration with Tiled called **TiledLib** was been developed and could have bene of some use, if only to take a look at for ideas, but no longer appears to be available.

---
Tags: design-patterns, tiles, maps, level-design
---


title: FPS Camera Look Direction

text:
# Question
Title: FPS Camera Look Direction
I'm using XNA to create an FPS camera that uses a Direction vector instead of a Target vector control the camera's orientation.

I'm having trouble with the math for looking up and down when the camera is rotated about the Y axis. No problems looking left and right.

Here's my code:

```
Vector3 LookDirection {get;set;}

public void LookLeft(float scale)
{
    LookDirection = Vector3.Transform(LookDirection, Matrix.CreateRotationY(MathHelper.ToRadians(scale)));
}

public void LookRight(float scale)
{
    LookDirection = Vector3.Transform(LookDirection, Matrix.CreateRotationY(MathHelper.ToRadians(-scale)));
}

public void LookUp(float scale)
{
    //doesn't work when camera is rotated into the X axis
    LookDirection = Vector3.Transform(LookDirection, Matrix.CreateRotationZ(MathHelper.ToRadians(scale)));
}

public void LookDown(float scale)
{
    //doesn't work when camera is rotated into the X axis
    LookDirection = Vector3.Transform(LookDirection, Matrix.CreateRotationZ(MathHelper.ToRadians(-scale)));
}

```

I know I need to manipulate both the X and Z components when looking up and down, I just can't figure out exactly what to do. Thanks

# Answer
> 3 votes
I think you would be better off having separate variables to store the amount of up/down and left/right rotation. These variables should be adjusted by your functions. Then you can calculate your rotation matrix in one place on each frame as in the code below and use that matrix to rotate your LookDirection.

```
Matrix rotation = Matrix.CreateRotationX(upDownRotation) * Matrix.CreateRotationY(leftRightRotation);

```

---
Tags: xna, camera
---


# Question
Title: Best methodology to prepare 3d models for avatar customization?
I know preparing mount points and the like. But what's the best way to prevent Z fighting with customizations close to moving parts like elbows and knees?

# Answer
> 3 votes
Here are some ways to prevent z fighting.

* Make the near and far planes close together and the space between clothing parts as far as possible.
* Depending on the types of animations and the situation it might be possible to disable z testing/writing and rely on painters algorithm.
* Write a screen capture app. Go through your characters and animations and have your artist adjust the animations if there are problems.

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


# Question
Title: Geometric Transformations on the CPU vs GPU
I've noticed that many 3d programs normally do vector/matrix calculations as well as geometric transformations on the CPU. Has anyone found an advantage in moving these calculations into vertex shaders on the GPU?

# Answer
Generally speaking: Mesh transformations are done on the GPU. You send in the transformation matrix to the GPU and the shader applies it to all verticies of the mesh.

Using the GPU to calculate the Matrix itself is a different matter & is actually slower on the GPU because there are so many stored values that change from frame to frame that are necessary to help determine the final transformation matrix. Sending this data to & from CPU - GPU is slow. Also, on the CPU, the calculations are done once, whereas on the GPU, they would be done for each vertex.
> 4 votes

# Answer
Many geometric transformations can be done on non-GPU processors, however one must consider the target platform. Your mileage will vary based on what platform you're targeting, and the bottlenecks of that platform.

One consideration is bus bandwidth between the device that is generating the geometry, and the device that is rendering the geometry.

In a typical modern PC system, the CPU is on one side of the PCIe bus (http://en.wikipedia.org/wiki/PCI\_Express), and the GPU is on the other. The only way you can transfer per-frame generated data from CPU to GPU (and vice-versa) is via this bus. This means, you can be limited by the transfer speed of this bus. If your target platform has PCIe 2.x with 16 lanes, you have 8GB/s bandwidth. In practice, transfers across the PCIe are not 100% efficient, as some of the bandwidth is consumed for the protocol during your transfers. Depending on the size of your transfers, you could lose 5-10% of your bandwidth just on the per-packet overhead.

eg. Given a PC platform that is running PCIe 2.x with 16 lanes, how much data can you generate per frame for feeding to the GPU? Assuming you want the run at 60fps, this translates to 8GB/60 = 136MB per frame for PCIe 2.x. Multiplying by some (guestimated) 90% factor to account for driver communication overhead and PCIe transfer protocol overhead, you can generate around 120Mb data per frame without being limited by PCIe 2.x bandwidth.

Another question you have to answer: will the generation of this 120Mb of data be easily achievable in 1/60th of a second on your target CPU? Remembering that you have to perform a number of other game tasks on your CPU, you can run into a lack of time to generate the transformed data. In terms of just pure ALU throughput, this can limit you on CPU. In terms of CPU to sysmem buses, you can also be limited by the bandwidth (which varies, but is around ~8.5GB/s on recent CPUs).

Alright, so what factors makes it more viable to do on a GPU then? One factor is GPU memory bandwidth, which is the bandwidth between the GPU and it's local video memory. On contemporary mid-range GPUs this video memory bandwidth can be as high as 200GB/s (yes, that's 25x the PCIe 2.x bandwidth). Another factor is that the GPU is massively parallel, has hundreds of ALUs and is able to hide memory access latency by running thousands of threads at a time.

All of these factors can contribute to the obvious win of pushing more work onto the GPU, but again YMMV depending on your target platform.
> 3 votes

# Answer
What do you mean by "mesh transformations"? Transforming geometry by some set of matrices? Most games these days will let the GPU handle simple transformations, skinning, etc. And most of them will be using vertex shaders to do it. On some platforms you either don't have shaders, or there are other advantages to doing these things on the CPU. For example, on the PS3 you can take some load off the RSX by letting the SPUs handle skinning and transformation. If you're doing multi-pass lighting then skinning on the CPU can be advantageous, since you only have to do it once and submit the results to be drawn for each rendering pass. So there are exceptions, but in general most games are doing these things on the GPU and in shaders.

Or did you mean something fancier, like using the GPU for general vector math? These days we have general purpose GPUs that can run fairly generic C code via systems such as CUDA. It is possible to take advantage of this for heavy vector math, and I know there are programs out there that do this. I don't have any experience with it personally though.
> 1 votes

# Answer
There are situations where having everything on rendered on the GPU might make sense, but you can't set constants inside a shader and there is really no where else to set them up except on the CPU side before a draw call.

Even if you could compute your constants, like the bone transformation matrices, on the GPU with a custom initialization program, you probably wouldn't want to. the GPU is really good at parallel execution, but has a much slower clock speed.

Transforming a hierarchy is not trivially parallelizable, because the child nodes depend on the parents, but transforming all the vertices in a mesh is, because the vertices are computational independent from each other.

The general rule is:

* Serial processing : CPU
* Parallel processing : GPU
> 0 votes

---
Tags: opengl, 3d, performance, transformation, gpu
---