title: How to write a network game?

text:
# Question
Title: How to write a network game?
Based on Why is it so hard to develop a MMO?:

> Networked game development is not trivial; there are large obstacles to overcome in not only latency, but cheat prevention, state management and load balancing. If you're not experienced with writing a networked game, this is going to be a difficult learning exercise.

I know the theory about sockets, servers, clients, protocols, connections and such things.

Now I wonder how one can learn to write a network game:

* How to balance load problems?
* How to manage the game state?
* How to keep things synchronized?
* How to protect the communication and client from reverse engineering?
* How to work around latency problems?
* Which things should be computed local and which things on the server?
* ...

Are there any good books, tutorials, sites, interesting articles or other questions regarding this?

I'm looking for broad answers, but specific ones are fine too to learn the difference.

# Answer
> 61 votes
In addition to the article linked in other answers, I can tell a bit about the experience of the Arianne Project.

**How to keep things synchronized?**

We have build framework „Marauroa“ around the concept of actions and perceptions: Actions are sent from the client to the server carrying user input like (walk left, attack monsters #47, say 'hello'). And perceptions are sent from the server to the clients telling them about the state of the world closely around them. Those perceptions are sent every turn. Depending on the game we use turn times of 30ms to 300ms.

We have two types of perceptions: A full perception is sent on login and when the player enters a new area (zone). After that differential perceptions are sent including only the modified attributes (e. g. position) of the modified objects, and of course new and removed objects.

**How to work around latency problems?**

We strongly belief in “the server is always right”. The client does some predictions like smooth walking, collisions checks and so on. But if a client and the server disagree about something, the server wins. The subproject Stendhal (a 2D RPG) uses a turn time of 300ms by default (with a lot of smoothing done client side). This makes Stendhal very resistant against lag.

Note: Some other games trust the client to some extend to minimize the impact of network lag. In WoW it was often exploited in one of the battle field called “Warsong Gulch”. There are two ways which a player with the flag can choose: On in the middle through a tunnel and one on the right sight going up the hill. So a cheating player runs towards the tunnel, and then causes lag for himself. The server and the other clients will continue to see him running towards it. But after a little time this client can tell the server that it went towards the hill. WoW will check that the distance between the last transmitted coordinates and the current ones fits within the time segment and accept that.

**Use of UDP vs. TCP**

In early versions we used UDP to reduce the overhead of TCP. We handled lost packets on our own. This worked perfectly at the early days of the project. But when the server was moved from some home DSL connection to a real data center several years ago, we got huge issues. UDP is (or at least was 5 years ago) extremely demanding on CPU power of firewall hardware: The ruleset has to be applied to every single UDP packet. For TCP, however, the ruleset is only applied for the first 3 packets. After that the connection is established. All following packets will bypass the normal ruleset because they are in the connecting tracking table or because they don't have a SYN flag.

**How to protect the communication and client from reverse engineering?**

Arianne is completely open source, this include the client, server, graphics, music. And of course that includes our protocol documentation and even an analyzer used for debugging.

It is easy to protect the communication against unauthorized sniffing by third parties using SSL.

It is, however, impossible to protect it against reverse engineering. Sure you can obfuscate it and use anti debugging techniques. But in the end you cannot prevent reverse engineering of software you give away to users. There is a very interesting presentation on how Skype was reversed engineered despite the developers putting a lot of effort into anti debugging techniques: http://recon.cx/en/f/vskype-part1.pdf

Note: There are some countries in which reverse engineering is illegal or which allow to put a paragraph into the license or ToS disallowing reverse engineering. But there are other countries (like the one I am living in) which explicitly allow reverse engineering in the context of developing compatible data storage formats or transmissions protocols, paragraphs in the license or ToS trying to disallow that are void. (Everything in this section is as far as I know, I am not a lawyer)

**Which things should be computed local and which things on the server?**

We compute everything related to the game logic on the server. The client will predict certain events in order to make the game play smoothly. But in the end the server is always right.

Predicted events are for example stopping of movement when a collision is hit. Stendhal uses a grid to position elements. And from the server point of view, the top left corner of every entity is on exactly one square. But the client will move them around smoothly between tiles. It will draw the pseudo 3d effect, too. So an entity that has a base of 1x1 may be higher in the client.

**How to balance load problems?**

Try to keep this as simple as possible, to ease maintenance.

Load balancing of static content is well known in the area of http server clusters and content distribution networks.

An rather simple concept for load balancing of game services is to split servers across regions/zones. So zone A-C are on one server and zones D-F are on another. This is especially easy if you cannot look from zones in one set to zones in another set. You need to put some checks in there so that a client can only connect to a zone server responsible for the zone the player is in.

The easiest way to transfer players from one server to the other is to write them to the database, tell the client to connect to the other zone server, and disconnect them from the current one. The client will then connect to the new zone server which will load it from the database. (Since you need the load from / store to database code anyway, direct communication between the servers for handover can be implemented later).

Some additional global services are needed through: On login the clients have to be told to connect to the correct zone server. And you might want a world wide chat system.

I went into detail on this topic at How is load balancing achieved in MMOs?

# Answer
> 27 votes
http://gafferongames.com/networking-for-game-programmers/

Is a great set of articles on various problems and solutions dealing with game networking.

# Answer
> 9 votes
Depending on the type of game you're writing, you may be able to avoid some of the low-level network programming. Some types of games do not require a lot of back-and-forth communication between the clients and the server. In such cases, one could opt to use a higher level framework. For example, I am developing a turn-based strategy game in C#/.NET. Turn-based strategy games are somewhat unique in that the vast majority of client/server communication occurs at the beginning and end of a turn, with relatively little in between. Thus, I opted to use the Windows Communication Foundation (WCF), a high-level communications framework designed primarily for web services. Instead of working directly with sockets and all of that low-level networking gunk, I can make what appear to be standard method calls, and let WCF deal with the protocol and transport layers for me. The only time I've had to deal with the low-level network stuff was when I configured my endpoints, which is pretty much a one-time deal in a config file. It may still be necessary to implement some custom serialization logic, but you'd need to do that sort of thing regardless.

# Answer
> 8 votes
The question is far too broad. The answers could fill a website all on their own. But, there are books that touch on this, primarily these two:

Note that even these books are not a complete guide, but are instead a collection of ideas and approaches you can use, some of which won't work together, or are even contradictory. Typically it assumes some experience developing games, network applications, or ideally both.

(Note that I'm talking more about the MMOs in the original question - a 'network game' could mean all sorts of things from a PHP-based text game right through to an MMO, and the sub-questions above don't all apply to each type.)

# Answer
> 7 votes
> How to balance load problems?

fixed geographical size + multiple instances is the easiest solution. The guys working on SWG tried dynamic size and regretted it.

> How to manage the game state?

Server is authoritative.

> How to keep things synchronized?

Periodic sync updates from server. (not quite sure what the concern is here)

> How to protect the communication and client from reverse engineering?

Impossible. just make sure you don't trust anything you receive from the client, and that the server is authoritative.

> How to work around latency problems?

This goes miles deep, but superficially you run the same simulation on the client as the server and when the sync happens, fix things. All decisions made on the client are simulated on the server as well, so there may be bad decisions, but things generally work out.

> Which things should be computed local and which things on the server?

Think of the client as running a non-authoritative sim of what is going on on the server. Responsiveness is key for the player experience, so you have to do *something* every time a player makes a decision, even if it is just starting a bar.

Truth be told, a lot of these problems are orthogonal, and can have solutions applied later. Just start doing the game and don't worry too much about these things.

# Answer
> 4 votes
This question is *very* broad. It's also a very tricky area to master, network programmers are pretty sought after in the industry with a matching pay, which kinda indicates it's a 'non-solved' area. Are there books out there, yes, plenty. Are there good books out there, no doubt. Are there books out there that will answer your questions?...I don't think so. They might have solutions that work in some situations or pointers on what to look for, but almost all your questions are game dependent....this is an area where you'll really have to work a lot on your own, it's so seemingly trivial and it can go wrong in so many (uncontrolled) ways.

---
Tags: networking, multiplayer, books, scalability
---


title: How public should you make your betas?

text:
# Question
Title: How public should you make your betas?
I am approaching the point where I can release a playable beta of a very complex game I am making in Flash/AS3. It is fairly involved and the deepest game Ive made so far. I plan on hosting it on my personal site but I want to try and get good feedback on the game elements so far.

Is it worth it to expose this beta to as many places as possible before the release? What are good communities to do this?

Please note this will be freeware in its final release

# Answer
It's probably good to stage your beta into at least 2 sections. The key issue is that having a "public" beta too early is a bad idea, as it can server as bad word of mouth. The people who are in your public beta test are the same people you want to use to spread some publicity (even for a free game).

If you need to get some early testing in, I would recommending doing a "friends and family" beta where you hand it out to people you have a relationship with, such as friends in real life or just users on a forum you frequent. Mention that it shouldn't be distributed and you'd really like some feedback. This way you'll get less of a dispersal effect, as being in public beta can make the testers think that they don't have to give feedback (because everyone else is).

Once your game is fully functional and you want to open it up for either balance or scalability testing, a more public beta is the way to go. Frankly for a freeware game there's not much benefit to actually "releasing" a game, and things like Dwarf Fortress are still technically in Beta despite having thousands of active users. At this point I'd open it up to everyone, and the "beta" label is really just there to let people know that it's not a commercially polished experience. Heck, gmail was in beta for like 5 years.
> 8 votes

# Answer
Dwarf Fortress is a good example of a freeware game that started releasing to the public early and then kept being expanded as people tried it. I think you have little to lose if you make it available as soon as it's playable to get early feedback.
> 3 votes

# Answer
Follow Stackoverflow's example: **release your beta in multiple groups**. Why?

Because most likely the user will check your beta out once, poke around, and then is highly likely to not return or keep testing as much as they did when they first began. Also, new users at different stages of beta development can spot things that, well, only a new user would spot. Older users will also have learned or become accustomed to the game so they might not spot some issues.

If you keep getting users in stages during development, you'll always get new fresh eyes and ideas/thoughts/etc. throughout your development.
> 2 votes

# Answer
For City of Heroes, we were lucky enough to have a community of fans who were very excited to give us feedback on the game, but having a pool of people you trust to give feedback is very important.

I'd usually roll things out to as few people as possible because getting a few hundred people reporting the same bug is a waste of time. Once you started to get around a thousand people betaing, the noise outweighed the value so it was almost a promo at that point (we never had the heart to boot people from the beta and forums).

Analyze feedback. This is important and time consuming. Make sure you have feedback gathering mechanisms in place. Forums work well, but instrumenting your code is important too. This can take a lot of time, and you usually think of the most important questions to ask after you wish you'd instrumented.

Another easy mistake to make is rolling buggy stuff out. It is a complete waste to show anything to people if you know it is broken. Even when you think it is solid, hallway playtest with a single person (or small group) and just watch them play. Right now that's all I need for Neverwinter, when I start to get lots of conflicting advice and I'm unsure of what to do next I'll start rolling it out to more people.

Finally, (and a little off-topic, sorry!) trust your gut and your vision. People are great at telling you *something* is wrong, but you almost never want to listen to their suggestions. You understand the big picture better than they do.

good luck!
> 2 votes

# Answer
As long as you aren't representing it as a "final" product, there really isn't any reason to go public with a beta on your own site as soon as it's playable.

I wouldn't put it on portals or anything like that, as the primary reason for releasing games early is to try to get a tightly knit community around it. You want people to be getting the game from your site so that when they have issues they know where to turn to for support and feedback.

Wolfire Games and TaleWorld both release their work-in-progress games to their preorder customers, and it works out really well for them.
> 1 votes

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


# Question
Title: Which 2D rendering algorithm is the most suited for mobile devices?
Which 2d rendering algorithms are popular for mobile game engines (specifically Android) and why? Are the same ones for the desktop and/or console world as effective here?

# Answer
At first glance many consoles support the same OpenGL-like interface where you throw triangles at the hardware and it figures out how to do it best. In real life each hardware has been optimized for certain uses and modifying *how* you throw your triangles at it can make a difference.

For instance, the iPhone uses a deferred tile renderer, where the driver collects triangles until a certain limit, then renders them in small tiles (see http://developer.apple.com/iphone/library/documentation/3DDrawing/Conceptual/OpenGLES\_ProgrammingGuide/OpenGLESPlatforms/OpenGLESPlatforms.html). For the iPhone you should research building texture atlases, since texture unit switches are not free. You can also disable the depth buffer and also lower the graphic resolution from 32bit to 16bit to reduce memory consumption.

I've heard that Gameboy-like hardware uses a more explicit tile renderer which you have to get at it at the low level to get good performance and is hard to do properly. PS3 consoles are multi-core, so there your algorithms work best if you are able to parallelize your load, I wonder how the PSP does in comparison, apparently it's between PS1 and PS2 tech level.

Then there are OpenGL characteristics which may be used, abused or underutilized. In the case of the iPhone one would be Vertex Buffer Objects, advertised as the best thing since sliced bread, but in practice worthless (http://www.idealbinary.com/ib/blog/kevin/2010/1/12/iphone-opengl-es-performance). Again, from personal experience I found that the iPhone hardware is very much bandwidth limited. If you want to darken the screen, you could create a sprite the whole size of the screen with translucency and blit it on the screen. Don't do it! It's better to create a smallish 4x4 sprite and let the hardware stretch it to the full size. The hardware has less pixels to read from the source, and that is faster than the stretching operation itself, which would be slow to do in software.

Long ago I played with GPX2 hardware but not at the lower level, so I don't know about more mobile consoles. But most definitely, each mobile platform can use fine tuning, so unless you specify more your question it is going to be tough to answer it.
> 5 votes

# Answer
I'm not sure what you mean by "rendering algorithm". The modern 2D rendering algorithm is "you feed some quads into OpenGL, and if the rendering is kind of slow, you sort them by texture first, and if they're transparent, you sort them by order before any of that". I don't know of any platform with a different process - at least, without getting into game-specific techniques.
> 2 votes

---
Tags: 2d, opengl, iphone, android
---


title: Start work Unity 3d

text:
# Question
Title: Start work Unity 3d
> **Possible Duplicate:**
> Best place for learning how to write games in Unity3d

Hi all,

I am just a new candidate who is going to work upon the `Unity 3D` game engine so guys I need some help to get some good tutorials where I can learn the moving characters, effects, and creating the surroundings.

Is there a place where I can get some links or pdf with which I can learn `Unity` in little time?

Thanks!

# Answer
> 6 votes
If you already know basic programming, go there: http://unity3dstudent.com/

---
Tags: unity
---


title: Linux Game Engines

text:
# Question
Title: Linux Game Engines
What Linux Game Engines are out there? Name, link, and intended use.

# Answer
> 4 votes

---
Tags: linux
---


title: Lightweight lua objects vs. inheritance

text:
# Question
Title: Lightweight lua objects vs. inheritance
Although I did this a couple of times from scratch, still no solution really fits.

I'm using lua for scripting in my games. Lua holds the "prototypes" of the game elements, that are copied to each entity on it's creation. A prototype represents a class of objects ("Soldier with shotgun"). Also, each prototype may hold event hooks (OnDie, OnSpotEnemy, etc). Clearly it's a prototype, not the object that will be handled.

So, each time a hook is executed, I need to create an object to represent the calling entity (and any entities it interacts with) *only for the lifetime of a single script execution*. What it means is that a instance of the object lives in lua only for the time needed to run this script.

Simple execution of this idea wasn't much work -- I used `lightuserdata` to hold the C++ pointer to the entity encapsuled in a `being` class. To access the fields of the C++ object, I overloaded the metatable of `being`. However, the fact that the fields of the object are handled by a metatable practically breaks any reasonable implementation of inheritance.

I pondered with the usage of normal userdata, but I'm afraid that the dynamic allocation needed to run each script (some of them being ran each tick in the game loop) are going to ruin performance.

Any suggestions? Or maybe a better solution altogether?

# Answer
> 5 votes
Use composition to model properties of complex entities rather than inheritance. More specifically, use a component-based design rather than an inheritance-based design for your entities. Each component has a known metadata table and your entity's metadata table just exposes a list of components.

# Answer
> 2 votes
If your normal userdata solution produces better code, I'd go with that. Lua is so allocation-heavy anyway that you're probably not going to make a significant performance problem for yourself. How many entities and events are you going to have anyway? 10s? 100s? You'll probably still be render-bound\*.

And if you do encounter issues, there's ways to mitigate it through the use of different allocators, such as object pools, tiny allocators, and slot allocators.

Without firm profiler evidence either way, I'd always err on the side of cleaner code.

`*` warning vast over-generalisation based on knowing nothing about your game

---
Tags: lua
---


# Question
Title: What pitfalls should one look out for when starting a studio
What are the common mistakes or oversights made when starting a new game studio?

Please only one mistake or oversight per answer and if you can explain why it is an issue and what one should do to avoid falling into the mistake or recover if they've already made it.

# Answer
> 13 votes
*Success* is defined as your equity in your studio is greater than the amount which you could have earned working for someone else's studio.

By and large, it is the same as any industry. An individual that has much technical knowledge in a field is able to make very smart technical decisions because they have much experience doing it. At the same time, they lack experience making smart business decisions because they generally lack experience in business management.

Making smart business decisions affects *success* way **way** more than making smart technical decisions.

The oversight or common mistake is to not employ an experienced business manager early on in the enterprise or somehow mitigate this shortcoming within the enterprise.

The moral: Find a good business manager and pay them more than anybody else in the enterprise. Sounds counter intuitive but the better manager you have, the sooner your enterprise hits critical mass where your studio achieves *success*.

# Answer
> 13 votes
My #1 mistake- going into business not only with a friend, but also with the spouse of said friend. Thought it would be a good idea; the spouse had "business" experience, friend and I had complementary skills.

This friend admitted to me one day that in any disagreement that I would always lose because the friend would always side with the spouse.

I didn't last much longer in that business arrangement. That business didn't last much longer than me, and the marriage wasn't to last much longer yet.

Fun times in the world of "business".

Our #2 mistake: expecting to get anything useful without paying for it. Nobody wants promises of profits or shares of company or any of that. People want cash.

# Answer
> 3 votes
I started a game studio a few years back. We were all engineers and artists. We didn't have a "business guy" - someone that was more interested in making a business that writing code or drawing pictures. If you want to make an awesome game, I'd suggest getting a job at an existing game company if that's possible. If your cup of tea is making a business please email me I'd love to start a company!

# Answer
> 2 votes
Experience!

If you don't have it consult people who do. Most mistakes can be avoided by a little bit of experience.

The various business, technical, design and management aspects are too numerous to explain.

There are many good books on business consult those and don't be tied to game specific resources.

Also check in your area, consult local council or businesses as there may be support programs in the area for SME (Small Medium Enterprise). They often provide funding, services or advice.

# Answer
> 2 votes
Money. Someone has to be paying attention to this at all times or you're screwed. This is a full time job, it takes a lot of time and energy to drum up.

A second thing is someone to handle the books, hr, etc. This can be outsourced, but it takes time and it is just a little silly when your server architect is firing up Quickbooks to make sure you don't get audited.

# Answer
> 1 votes
Always, always spend that little bit extra on consulting a lawyer. Build up a good relationship with your lawyer if you can. I've never taken anyone to court but it's amazing how often running a tiny studio throws minor legal issues your way. How to handle trademark infringements, publishing contracts, hiring contractors... people will screw you if you give them the chance when there's money involved.

# Answer
> 0 votes
To nuance what Steve H said, you need a tech savvy manager.

In this industry, you need someone who is able to quickly grasp what can be achieved and when, what are the limits of you tech/skill pool, etc. Someone with a production experience is invaluable.

# Answer
> 0 votes
I have never started my own studio or business so take this with a grain of salt. That said I do a great deal of reading and research on the subject so I thought I'd share something. My advice would be to:

> Identify your core assumptions, create tests to test the most risky ones first, repeat

In practice this may mean validating your

* Who the players are
* Who the customers are (i.e. advertisers for a Flash game, the players for a traditional game)
* That the customers are interested in buying what you're selling
* The cost to acquire a customer

An example experiment might be:

1. Create an advertisement
2. Create a landing page with additional copy and a prototype screenshot
3. Show your ad to the target audience on Facebook
4. Measure click through on ad, click through on "Download Trial" or "Buy Now" button

All of this can be done for a couple hundred dollars and can help answer some of the above questions. (Method is known as dry testing.)

If you want more information or to read a more formal framework for thinking about experiment driven processes take a look at:

1. Steve Blank author of Customer Development
2. Eric Ries leading figure for Lean Development
3. The Entrepreneur's Guide to Customer Development a "cheatsheet" to some of the ideas from the two guys above

---
Tags: business
---


title: Premultiplied alpha, yea or nay?

text:
# Question
Title: Premultiplied alpha, yea or nay?
Should I be using premultiplied alpha? Reading Tom Forsyth's article it seems a nobrainer. Premultiplied alpha (AKA additive blending) is superior in every sense.
However, premultiplied alpha seems to have one major drawback, it's not well supported with tools.

Do you/have you used premultiplied alpha?

How is the tool support?

In particular, I don't think gimp will edit premultiplied alpha images well. Are there any gimp plugins to export premultiplied alpha? How about an external tool?

# Answer
I use XNA 3.1 at the moment with premultiplied alpha (native Premultiplied Alpha support was added in 4.0).

Mostly it saves me time going through and making sure the transparent areas of my images have the correct colours. I also port to Silverlight, which does premultiplication by default.

XNA has a content pipeline which makes adding premultplied alpha preprocessing super-easy.

That link contains the code for doing the conversion. For every pixel:

```
c.R = (byte)(c.R * c.A / 255);
c.G = (byte)(c.G * c.A / 255);
c.B = (byte)(c.B * c.A / 255);

```

There is a lot to be said for having a content pipeline. If you're not using XNA, but are using Visual Studio, then you could throw together one yourself. Any other IDEs/build processes should also be capable.

And finally, if you don't have a content processing step in your build (and so odds are you don't have a lot of content anyway), you could just as easily perform the premultiplication at runtime when you load your textures. It will add some constant factor to your texture load time.

(If the implication wasn't clear: you probably *shouldn't* be editing premultiplied alpha images. Export them premultiplied if you can, or better yet preprocess them.)
> 4 votes

# Answer
If you happen to be using XNA, there's quite a bit of support for pre-multiplied alpha. Usually the conversion is done in the content pipeline, but there's nothing stopping you from doing it yourself.
> 3 votes

# Answer
I use premultiplied alpha by default in my engine (the artist can force non-premultiplied in the material definition file, if it's needed for a special effect of some sort)

Tools, as you've noticed, do not deal well with premultiplied alpha - the artist can set the color and alpha channels totally independently. I've set things up so my artist can create the texture images with non-premul alpha (which seems to be easier on artist brains), and the tool that converts to the engine's texture format multiplies the alpha by default. There's a switch so non-premultiplied can be generated if it's absolutely needed.
> 1 votes

---
Tags: textures
---


title: Help with legalese for an HTML5 contest

text:
# Question
Title: Help with legalese for an HTML5 contest
This contest looks pretty interesting but I'm having some concerns about the wording in the rules:

`Once submitted, a prize winning Submission becomes the exclusive property of Sponsor and will not be acknowledged or returned.
You expressly agree that by entering into the Contest any rights you may own in respect to a prize winning Submission shall be transferred to Sponsor by means of this Agreement. You shall be obliged to perform any measures necessary in order to vest any intellectual property rights in the name of Sponsor in case required by any law or regulation. In such case, Entrant shall – at Sponsor’s first request – execute any deed or transfer or such other document as required in that effect. For the avoidance of doubt, Sponsor shall have the exclusive right to make any kind of sequels, spinoffs, changes and translating the prize winning Submission in any language , all in relation to the exploitation of the prize winning Submission on any kind of media now known or hereinafter developed, without territorial or time limitations. The responsibility to implement localizations made by Sponsor in up to 19 languages will be that of the developer.`

So it sounds like they get full IP rights, but I can't read this law stuff. Anybody have any insight? Much appreciated!

# Answer
> Once submitted, a prize winning Submission becomes the exclusive property of Sponsor and will not be acknowledged or returned.

If you win, your submission is now theirs, and theirs only.

> You expressly agree that by entering into the Contest any rights you may own in respect to a prize winning Submission shall be transferred to Sponsor by means of this Agreement.

They also want all the exclusive rights for everything in the game that you own the rights to.

> You shall be obliged to perform any measures necessary in order to vest any intellectual property rights in the name of Sponsor in case required by any law or regulation. In such case, Entrant shall – at Sponsor’s first request – execute any deed or transfer or such other document as required in that effect.

They want you to sign over on paper that they own the property.

> For the avoidance of doubt, Sponsor shall have the exclusive right to make any kind of sequels, spinoffs, changes and translating the prize winning Submission in any language , all in relation to the exploitation of the prize winning Submission on any kind of media now known or hereinafter developed, without territorial or time limitations.

For clarification, they really want to completely own your IP, and want exclusive rights to any sequels or anything, and they can basically do what they want with it.

> The responsibility to implement localizations made by Sponsor in up to 19 languages will be that of the developer.

If you win you have to translate your game into 19 different human languages.

In my opinion, stay away from this unless you are willing to completely loose all rights to what you make.

*Edit: I meant languages. :/*
> 10 votes

---
Tags: legal
---


title: 2D collision-detection middleware

text:
# Question
Title: 2D collision-detection middleware
(This question was split off from 3D collision-detection middleware)

Are there any recommendable middleware available for 2D collision detection?

I believe I've heard that Box2D could be used for collision detection without the physics part. I'd like to hear if people have any experiences on Box2D or others libraries for 2D collision detection specifically.

# Answer
I had SEVERE issues with Box2D collision detection...

Mostly, because Box2D collision detect broadphase is a binary tree, everything that use collision (even if they don't use physics) need to update that tree, and then the tree need to be searched back.

For few objects with bizarre size differences (like a golf ball and a bus), Box2D is acceptable, or even fast, but for various objects of roughly the same size (like you would have in a clone of asteroids, or in a tile-based game, or anything like that) then it behaves extremely slow, even unstable sometimes as it need to write and read massive amounts of data on the tree.

Chipmunk Physics fix this, they use a spatial hashing thing, that I really don't understand how it work, but it work!
> 3 votes

---
Tags: 2d, collision-detection
---


# Question
Title: New Vector Calculation for Elastic Collision of Circle and Fixed Rectangle
I am writing a fairly simple breakout-style game for Android phones. I have successfully detected the collisions between the ball(s) and bricks. The problem that I am having is in calculating the new vector for the ball. Even though the bricks are rectangular, I want to treat them as circles for the purpose of introducing more uniqueness to the ball directions.

I have the center point and vector of the ball and the center point of the brick which it has collided with and need to determine the new vector. The speed of the ball is always constant so the vector will be adjusted to that length but the direction is where I am having issues calculating. I've given it a few shots but they always end up being wildly incorrect.

---

The following is the code which I wrote but it has unpredictable results. All of the calculations must be done directly or using any of the methods in the Android SDK without a physics library of any sort.

```
float collisionUnitVectorX = ball.getLocation().x - blockCenterX;
float collisionUnitVectorY = ball.getLocation().y - blockCenterY;
final double collisionVectorLength = Math.sqrt(Math.pow(collisionUnitVectorX, 2) + Math.pow(collisionUnitVectorY, 2));
collisionUnitVectorX /= collisionVectorLength;
collisionUnitVectorY /= collisionVectorLength;

final double ballVectorLength = Math.sqrt(Math.pow(ball.getVectorX(), 2) + Math.pow(ball.getVectorY(), 2));
final float ballUnitVectorX = (float)(ball.getVectorX() / ballVectorLength);
final float ballUnitVectorY = (float)(ball.getVectorY() / ballVectorLength);

ball.setVectorX((float)(collisionUnitVectorX + ballUnitVectorX));
ball.setVectorY((float)(collisionUnitVectorY + ballUnitVectorY));

```

Here is a list of the information that I have for calculation:

* ball center (x,y)
* ball radius
* ball vector (x,y)
* block center (x,y)

The calculation should result in a new vector x and y values which has a length equal to the constant `BALL_SPEED`.

Remember, collision has already been determined, I am only looking for the new vector calculation. Thank you in advance.

*(accepted answer author will be attributed in game credits)*

# Answer
> 5 votes
Here is some pseudo code that will accomplish this. I'm assuming ball vector represents the position change (velocity) of the ball.

```
Vector collisionUnitVector = blockCtr - ball.GetLoc();
float cuvLength = collisionUnitVector.Length();
collisionUnitVector /= cuvLength;

Vector Velocity = ball.GetVector();
float speed = velocity.Length();
Vector velocityNormal = velocity / speed;

float dotProduct = Dot(collisionUnitVector, velocityNormal);

Vector vFactor = 2 * (-collisionUnitVector * dotProduct * speed);

Vector newVelocity = velocity + vFactor;

```

---
Tags: physics, collision-detection, java
---


title: 3D collision-detection middleware

text:
# Question
Title: 3D collision-detection middleware
(I've split this question into two. For 2D, see: 2D collision-detection middleware)

Are there any recommendable middleware available for 3D collision detection?

I believe I've heard Bullet has a pretty good 3D collision detection that can be used without the physics engine. I'd like to hear if people have any experiences on Bullet or other libraries for 3D collision detection specifically.

# Answer
If you just want collision detection, and not a full physics engine, it might be worth taking a look at OPCODE - http://www.codercorner.com/Opcode.htm (although it is a bit old now, there may be newer/better things out there?)
> 2 votes

# Answer
Bullet has a very well-working collision pipeline. They support various broadphases (sweep n prune, hashed broadphase, 3-axis sweep, etc) and have narrowphase with optimized bv-tree's. I've worked professionally with bullet for over a year and although their performance is not as good as havok(which I've worked with for over two years), it's free and the source code is maintained and enhanced often.

It should be fairly easy to look into their source-code to figure out how to only use their collision detection.

PhysX also has a collision-detection network but I haven't relly looked into it. Havok is a solution that costs a lot of money and I don't think anyone can afford retrieving their source-code unless you're a professional developer. They do have free-to-use libraries but then you can't modify it.
> 6 votes

# Answer
**Open Dynamics Engine** is another semi-popular open source middleware solution for physics and collision.

http://www.ode.org/

**PhysX** is another popular collision/physics middleware from NVIDIA. Binary available.

http://developer.nvidia.com/object/physx.html

Last but not least is **Havok** which is the gold standard of collision/physics. Binary available.

http://www.havok.com/
> 1 votes

---
Tags: collision-detection, 3d
---


# Question
Title: Would using Lua scripts to define game logic for an MMO server be a lot slower than compiled in C++?
I am using an entity system for my MMO server and I was thinking about defining the behavior of "actions" using Lua scripts. The server is written in C++. I am not very familiar with the speed/memory usage of Lua in C++ but I have used it for scripting the GUI of the client. Would using Lua to define the game logic on the server side cut the performance by a lot?

# Answer
**TL;DR: Lua does have overhead, but if used properly it is negligible and easily mitigated. Don't use it for heavy math operations or transforming geometry. You will probably not see any performance problems at all using it to script a GUI.**

I've done some basic benchmarks regarding Lua's performance as a game scripting language, and it's pretty damn fast. Using tolua++ to bind LuaJIT to my game engine, I spawned 2,000 actors, each actor controlled by a Lua script called every game loop (with a time-delta argument). Half of the actors had a flocking script and the other half were doing a sort of random walk (and were avoided by the flock).

Turning off the rendering component gave me a bit over 400 ticks per second on my Opteron 170 (2x2.0GHz, though my engine was single threaded at the time). I imagine I could have squeezed out quite a bit more than that if I dug in and optimized, perhaps moving some of the heavy work back into C++. Updating 2000 actors 400 times per second was still pretty impressive, and far exceeded my expectations at the time.

I now use Lua in all of my projects, and it actually constitues quite a large portion of the actual game code (AI, GUI layout/logic, Events/Messages). Making games is MUCH more fun when you can quickly change something and test it without having to exit, recompile, and reinitialize. I've run into some performance issues from time to time, but those are easily solved by reimplementing the offending code in C++ (and then calling it from Lua).

While slightly off-topic, EVE Online's servers are written almost completely in Stackless Python (I believe they defer most of their math operations to a C++ lib), which is considerably heavier than Lua, and, based on my own personal research and several available benchmarks, far less performant than LuaJIT. They manage to handle 30k+ concurrent players without too many issues. Granted, they do have a ton of expensive hardware running all of that, but I believe the majority of the cost is in their database cluster...

Apologies for the wall of text.
> 20 votes

# Answer
Short answer: Yes, yes it would.

Long answer: It depends how much game logic, how much it is run, and how complex it is, and if you need to run it for every player. If it is very simple and is not repeated a lot, you might be fine with it. **But for most cases using LUA instead of C++ will give you much lower performance and will scale badly, assuming of course that the code is well designed and optimized.**
> 2 votes

---
Tags: mmo, lua, server
---


# Question
Title: What is the best approach to resource management in game design?
I studied computer engineering before but have been lagging in the technical aspects as of late.

Seeing as I think it would be to my advantage as a designer to understand how resources are used and calculated. I would like to ask if people here know of methods to compute to a certain degree how much power/resource a design would entail? (i.e. how many polygons per scene, how many AI running, how many physics components, particles etc.)?

# Answer
This is a pretty wide open question. Can you be more specific?

In my experience, and I'm probably doing it wrong, there is a lot of dead reckoning and adjustment with performance. AI too expensive? run it less often. UI? optimize and hack. etc. So the things that are hard to do this with you have to get right early.

Graphics budgets tend to be the most important things to get right because they're the most expensive to revisit. Environments are harder than characters.

If you want to see what other games are doing, I believe PIX will tell you what is going on (there's a windows version). Your have different limitations across different generations of cards as well.

If you're PC, just make sure you get a min-spec machine, and keep it working on that.

Also, and maybe in line with what you're asking, I know the God of War guys give each designer a flexible budget for things like RAM, processing, etc. so they can choose what to emphasize for their levels. These are techniques and not solid numbers, but may be useful to you.
> 4 votes

# Answer
In my experience, there's two major ways of doing it.

1) Dead reckoning. Got someone on-staff who's written that kind of game before? Got someone who has really good instincts? Maybe they can tell you. If you're real lucky, their response will bear at least vague similarity to reality.

2) Prototype it and find out. The only reliable way.

There's a third, if you're using a well-established engine in a way that many other people have used that same engine, and not planning on doing anything fancy or out-of-the-ordinary:

3) See what they did, then do the same thing.

but that only really works if you're, say, making a first-person shooter with Unreal Engine 3.
> 2 votes

# Answer
As this question seems to be coming from a designer, my response would be: design isn't about numbers, it's about ideas.

Don't concentrate on the nitty gritty reality of how many polys you can render per frame. Once you have a design that must be made into a game, you will be able to work with a programmer to write up what gets resources and what gets stripped.

Real games have limited budgets, and programmers work with designers to provide information about what each feature costs. Poly counts and AI time are features that can be optimized so you can stretch a little, and normally, a programmer can provide an alternative solution that provides the effect the design requires without actually implementing the specified feature that a designer may have assumed was necessary.

As a designer, your role is to make the best usability model of the game problem. You must iterate through different control layouts or strategies, and try to mentally play through the game numerous times, trying out different progressions. Some designers I've worked with even wrote out paper versions of games they were developing just to see the flow better.

In Conclusion, don't sweat what isn't your domain, but be prepared to prioritize your features.
> 2 votes

# Answer
As a designer what you need to focus on is the priority of your features, and the minimum bar needed to pull each of them off. As you start prototyping and learning the various costs of certain mechanics, you'll use those priorities to figure out what gets cut back and what is axed completely.

You aren't expected to know exactly how many resources will be allocated to each aspect of the game before you get started, although you should have a rough idea. But a team does expect you to be able to react intelligently to learning that some feature costs twice what was expected and that means it either needs to go away, be redesigned in a simpler fashion, or something else gets cut to make room.

In time with experience you can better anticipate where stumbling blocks will occur. The more you work with an engine or hardware you get a feel for it's limitations and the relative cost of different features.
> 2 votes

# Answer
Rather than guessing blind, one thing you can do is implement budgeting tools early in development. Get a test machine, get out your budgeting tool, and start seeing where performance falls over. Make the budgeting tool yell at programmers/artists/designers if they go over the limits.
> 1 votes

---
Tags: architecture, resource-management
---


title: Silverlight 3d api

text:
# Question
Title: Silverlight 3d api
Is there an Silverlight 3d API ? or Isometric API ?

# Answer
> 3 votes
This thread:

> Currently there is no support for true hardware accelerated 3D in Silverlight. It is not possible to write 3D games that run in browser nor is the development model similar to Managed Direct3D. Any kind of 3D game will be very hard to port to Silverlight. Silverlight is more suitable for development of games, that are currently built using Adobe Flash.

I guess that's a no at the moment. EDIT: It appears the thread I mentioned is slightly dated. So to some extent, there is hardware accelerated 3D.

# Answer
> 2 votes
Silverlight 3 introduced `Projection` which allows for 3D transformations of elements. And in Silverlight 4 it became hardware accelerated.

(There are a very limited number of things that Silverlight 3 and 4 will hardware accelerate - and lots of ways to accidentally turn it off or make it perform poorly.)

There are two projection elements: `PlaneProjection` and `Matrix3DProjection`. The former is useful for making 3D interfaces. The latter will give you sufficient control to actually place elements in full 3D (providing you're pretty handy with your matrices).

This is a **far cry** from a 3D engine that renders triangles. You will be basically placing textured quads in 3D space.

Using this, a game that uses "2.5D" like Doom or Diablo 2 should be possible with *a lot* of work. It's worth pointing out that Silverlight as a whole is woefully inadequate for making games that require "fancy" graphics.

For a more generic 3D engine, you could take a look at the Silverlight version of Balder. Last time I looked, it was slow and buggy - although it seems to have improved since then. It does software rendering on Silverlight, so performance is going to limit you to the simplest of 3D environments.

---

**UPDATE**: Silverlight 5 now supports real 3D with an API that is very close to the one used by XNA.

# Answer
> 1 votes
You might want to check this book out at amazon: 3D Game Development with Microsoft Silverlight 3: Beginner's Guide

---
Tags: 3d
---


title: How to show iPad keyboard?

text:
# Question
Title: How to show iPad keyboard?
I am developing a game, a word game. I have UIView, in this I have to show the keyboard, without using UITextField. Could you please suggest me something on how to do this?

# Answer
There is no API for the keyboard. You have to go through a text input UI element. You could write your own on-screen keyboard but don't forget about Bluetooth keyboard users.

Also this isn't game dev specific. See here https://stackoverflow.com/questions/1472258/iphone-keyboard-without-textview
> 3 votes

---
Tags: ipad
---


# Question
Title: What are some good MMO middleware server packages?
If you have any experience with any MMO middleware packages and have any positive or negative experiences with them, your feedback will be appreciated.

Specifically I'm looking for server packages. Price, functionality, speed, and ease of use would all be useful metrics to know about.

For example, doing some preliminary research has led me to some packages like Exit Game's Photon, RedDwarf Server, and SmartFoxServer.

# Answer
This is from my experience as a server programmer for a commercial MMO:

MMO middleware is not a well established commercial field, and there have been very few successful attempts to use mmo-specific middleware, at least within the realm of large scale MMOs such as your World of Warcraft.

Multiverse has been used in a few smaller MMOs and I believe is free for noncommercial MMOs. However, the graphics are somewhat dated and it is not designed for large scale deployment.

Hero Engine has been around for several years, and has some very good content creation tools. I have no direct knowledge but have heard disappointing information about the usefulness of the back end server package, and I am yet to see a shipped game using this middleware. The upcoming The Old Republic MMO is using this engine, although I do not know to what extent.

BigWorld has been integrated into several actually shipped medium-scale MMOs so has a bit of a leg up. I again have no personal knowledge other than being impressed by their content creation tool at GDC. I suspect they are not particularly cheap.

In general, I would be extremely skeptical of using any Middleware solution that has not been used in actual shipping product. There is a huge gap between making content creation tools and making a scalable, working server architecture. Until an MMO has gone public and been hit with real users there's no way of knowing if the tech is good.
> 14 votes

# Answer
A fair number still use Speedtree, and Bink and Scaleform are as common in MMOs as they are everywhere else.
> -3 votes

---
Tags: mmo
---


# Question
Title: Efficient structure for representing a transform hierarchy
Can anyone suggest a memory efficient way to represent a tree of matrices, for example in a hierarchy model?

I'm particularly keen to preserve data locality, and I suspect a structure-of-arrays (matrices & indices to matrices) type approach might be suitable.

As well as many chained matrix computations, this structure will probably be copied around in memory a fair bit, so having contiguous storage would be a big bonus.

# Answer
The tree-as-array sounds like a win to me. Just do a depth-first traversal of your hierarchy and fill out an array; when rewinding through the recursion you can either update the parent with the absolute index to the child or just the delta-from-me, and the children can store the parent indices either way as well. Indeed, if you use relative offsets then you don't need to carry the root address around. I suppose that the structure would probably look something like

```
struct Transform
{
   Matrix m; // whatever you like
   int parent;   // index or offset, you choose!
   int sibling;
   int firstchild;
};

```

...so you'd need nodes to know how to get to siblings too since you can't (easily) have a variable size structure. Although I guess if you used byte offsets instead of Transform offsets, you could have a variable number of children per transform:

```
struct Transform
{
   Matrix m; // whatever you like
   int parent;  // negative byte offest
   int numchildren;
   int child[0]; // can't remember if you put a 0 there or leave it empty;
                 // but it's an array of positive byte offsets
};

```

...then you just need to make sure that you put successive Transforms in the right place.

Here's how you build a totally self-contained tree with embedded child "pointers".

```
int BuildTransforms(Entity* e, OutputStream& os, int parentLocation)
{
    int currentLocation = os.Tell();

    os.Write(e->localMatrix);
    os.Write(parentLocation);
    int numChildren = e->GetNumChildren();
    os.Write(numChildren);

    int childArray = os.Tell();
    os.Skip(numChildren * sizeof(int));
    os.AlignAsNecessary();  // if you need to align transforms

    childLocation = os.Tell();
    for (int i = 0; i < numChildren; ++i) {
        os.Seek(childArray + (i * sizeof(int)));
        os.Write(childLocation);
        os.Seek(childLocation);
        childLocation = BuildTransforms(e->GetChild(i), os, currentLocation);
    }

    return os.Tell();
}

void BuildTransforms(Entity* root)
{
    OutputStream os;
    BuildTransforms(root, os, -1, 0);
}

```

(If you want to store relative locations, just add `- currentLocation` to the two "location" writes.)
> 7 votes

# Answer
Indexing into array of matrices would probably be the most straight forward, memory efficient approach.

A chain of transforms could be held in a LIFO as series of pointers or integers or other small struct that index into the matrix array. This would help prevent storing redundant matrices and would separate the data storage code from the data accessor code.

Ultimately you would just push and pop index values from the LIFO to store or play back your transform chain.

You might also be able to save a little memory if your matrix structure could also contain the transform type...rotation, translation, etc. Otherwise the type would need to be stored with the index resulting in more possible duplication.
> 1 votes

---
Tags: memory-efficiency, tree
---


# Question
Title: Social Network Gaming on Windows, Linux and OS X
I'm working on mobile platforms as Android, IOS... Many users of Moblox ask us a windows and an OS X version. There is no difficulties to provide these versions, because we are developing on OS X C++ code but we miss global scores and social network part (facebook, twitter). Is there any library to implement these functions on Desktops plaforms ?

On mobile platforms, we have many SDK to provide theses functions as OpenFeint, ScoreLoop, Plus+. We have used cocoslive and uploaded scores with libcurl but it's very limited.

# Answer
> 2 votes
Facebook and Twitter provide cross-system APIs accessible in a variety of ways, typically a simple HTTP request (or a few).

---
Tags: c++, social, facebook, twitter
---


title: Revisitability of Game Elements

text:
# Question
Title: Revisitability of Game Elements
In some games, when you miss a pickup, you can never get it again unless you restart the game, and those pickups count in your collection. (therefore, you must restart the game to finish the collection, if you made any mistakes).

In *Pokémon*, you have only one Master Ball, limited supply of Ethers and legendary Pokémon appear once per game. Trading fixes all of those problems.

For a more radical perfectionist, they demanded all dialogs, background music, and even items to be revisitable. Some games, like *Naruto Ninja Council*, satisfied all of those needs.

Is it always a good practice to make things revisitable? Even cutscenes and music? When is it not a good practice to do so?

# Answer
It definitely depends on what your intentions are for the game!

For example: If the game is some sprawling RPG with 60h of gameplay and 1000 secrets, then yes, as a player I would expect to be able to slowly chart out the world and collect things. Or, they should be able to miss things (make them non-revisitable) by choice, but not by ignorance (i.e. get the Super Sword, or the Super Shield, but not both).

Alternatively, if the game is short and/or linear, missing content on the first playthrough can provide motivation for second/third/... playthroughs. In this case it may be interesting to make it impossible to see everything in a single playthrough. Or it may not!

It depends on how you want people to approach the game, what kind of value (both gameplay and real-world) these things hold, and why you want people to be gaining these things in the first place. Remember: You can't please everyone, all of the time. Figure out who your game is for and make a game for them!
> 8 votes

# Answer
I would say it depends on the kind of game. Something like an RPG, it wouldn't fit the game that Mr. Look At Me With My Amazing Armour Which You Didn't Pick Up Earlier suddenly reappeared, with the set of unique armour just because you didn't pick it up and instead a band of rogues did. However, it would fit that, for example, you find those rogues with the armour later. Then again, the other issue would be that the player could not physically pick up said items. An idea would be that they are kept, somehow. **You do not want to punish players for something they cannot control or predict, such as inventory space.**

On the other hand, an arcade game or something with less of a storyline would probably benefit from being able to replay. There's no reason for the player not to be able to re-defeat Master Foo, when the game is split up.

Cinematics and the like, I would say, are a different ball-game. I know on Red Faction: Guerilla, I am a fan of the cutscenes and am glad that I can rewatch.

It really depends on the game length, the type of market, and the game genre.
> 2 votes

# Answer
I would say a lot depends on your intention.

With the original Pokemon Red/Blue, I think it was flatly impossible to complete your collection without trading. But since trading and battling other players was a large part of the intended core gameplay, forcing the issue made sense.

I think Chrono Trigger was the first game to offer the popular "New Game+" option that lets you restart after beating the game, preserving your inventory and levels and giving you immediate access to all game locations, specifically to aid completionist players. You might find that to be a good compromise, if the player might miss out on some things early on but be able to go back after the game is done.

I'm sure at least some games had obscure secrets in them with no clues and no way to go back and get them again after passing a certain point, specifically as a ploy to sell more strategy guides. If that's your reason, I'd say that is borderline unethical design, at least.
> 1 votes

# Answer
It's a question of how complex you want your game to be. Everything that isn't revisitable implies there's state stored with the player's game to note which things have been visited and which things haven't. That state makes the game more complex to play (players must correctly do things in the right order), but more importantly, makes the game more complex to *design*.

Every time you store an additional piece of state, the game designers have to carefully track how the game works when that data is in either state. For example, consider a key that is spawned somewhere and can unlock a door. If the game forgets that the player has gotten the key before and allows it to respawn, it's pretty simple. Any time the player needs that key, they can go there to get it.

If the game doesn't let you revisit it, now designers have to make sure they handle situations like:

1. The player dropped the key somewhere inaccessible. Are they stuck?
2. What if they use the key on the wrong door. Can they still get a second key to use on the expected door?

The more game state that gets tracked, the more complex the player's flow through the game world, and that complexity increases combinatorially. You can consider game state to be a state machine. Every bit of state you store ("has X been visited before?") *doubles* the number of states in that state machine.
> 1 votes

---
Tags: game-design
---


title: vertex/pixel shaders and "materials"

text:
# Question
Title: vertex/pixel shaders and "materials"
What relationship is there, if any, of "materials" and vertex/pixel shaders (or the "effects" that combine the latter two)?

I have the impression that before the advent of HLSL, materials were explicitly handled by Direct3D or OpenGL. I also have the impression that with HLSL, many prior effects are now handled directly (and generically) via the rendering pipeline in vertex/pixel shaders. In other words, I hae the impression that materials are often little more than what DirectX would call an "Effect." If so, this means that many models that specify materials would be transformed by a content pipeline into an "Effect".

Is this correct? Where can I get a little more history/info that either corroborates or corrects the impression I have?

# Answer
Materials in the Direct3D 9 sense were simply parameters for the fixed function pipeline, which implements a Gouraud shading model (IIRC). The values of a D3DMATERIAL9 struct can be thought of as nothing more than shader constants. The definition of a "material" is entirely dependent upon context.

It's the distinction between fixed function and programmable that is most important here. When you're using shaders, you define the shading model yourself. Therefore, even though many of the surface properties that are described by a D3DMATERIAL9 (e.g. diffuse color) would likely apply to your shading model of choice, it's up to you to do something with those values.

The fixed function pipeline was essentially one monolithic "effect" (or pair of vertex/pixel shaders) that you couldn't change. You could only pass it different parameters to control the behavior, whether these parameters were render states or D3DMATERIAL9 structs.

You might find this instructive: FixedFuncShader

It's a partial reimplementation of the fixed function pipeline using D3DX effects. It'll help you understand the parallels between the two concepts.
> 2 votes

# Answer
The meaning of this words are not set in stone. I use the following distinction :

* a shader is the low level code that implements a material
* a material is an instance of a material type with all slots set. it uses a shader.
* a material type is a kind of material. it defines a format (like 3 textures, the first being used for diffuse, the second for normal and the third for specular.) but not the value of the slots (at this level we know the format but not what are the DNS textures). not the slots can be of any type (int, float, mat4, symbol).

YMMV
> 2 votes

---
Tags: shaders
---


# Question
Title: Why are MVC & TDD not employed more in game architecture?
I will preface this by saying I haven't looked a huge amount of game source, nor built much in the way of games.

But coming from trying to employ 'enterprise' coding practices in web apps, looking at game source code seriously hurts my head: "What is this view logic doing in with business logic? this needs refactoring... so does this, refactor, refactorrr"

This worries me as I'm about to start a game project, and I'm not sure whether trying to mvc/tdd the dev process is going to hinder us or help us, as I don't see many game examples that use this or much push for better architectural practices it in the community.

The following is an extract from a great article on prototyping games, though to me it seemed exactly the attitude many game devs seem to use when writing production game code:

> Mistake #4: Building a system, not a game
>
> ...if you ever find yourself working on something that isn’t directly moving your forward, stop right there. As programmers, we have a tendency to try to generalize our code, and make it elegant and be able to handle every situation. We find that an itch terribly hard not scratch, but we need to learn how. It took me many years to realize that it’s not about the code, it’s about the game you ship in the end.
>
> Don’t write an elegant game component system, skip the editor completely and hardwire the state in code, avoid the data-driven, self-parsing, XML craziness, and just code the damned thing.
>
> ... Just get stuff on the screen as quickly as you can.
>
> And don’t ever, ever, use the argument “if we take some extra time and do this the right way, we can reuse it in the game”. EVER.

is it because games are (mostly) visually oriented so it makes sense that the code will be weighted heavily in the view, thus any benefits from moving stuff out to models/controllers, is fairly minimal, so why bother?

I've heard the argument that MVC introduces a performance overhead, but this seems to me to be a premature optimisation, and that there'd more important performance issues to tackle before you worry about MVC overheads (eg render pipeline, AI algorithms, datastructure traversal, etc).

Same thing regarding TDD. It's not often I see games employing test cases, but perhaps this is due to the design issues above (mixed view/business) and the fact that it's difficult to test visual components, or components that rely on probablistic results (eg operate within physics simulations).

Perhaps I'm just looking at the wrong source code, but why do we not see more of these 'enterprise' practices employed in game design? Are games really so different in their requirements, or is a people/culture issue (ie game devs come from a different background and thus have different coding habits)?

# Answer
> 143 votes
As the quote says, many programmers make the mistake of (trying to) build a system, not a game. Typically that system keeps ballooning out of control until it's so complex that *theoretically* it can handle anything, but in practicality all you have is a big bundle of code. Or more often, before you even get to a working stage, you are so tangled up in code that doesn't run that you lose focus (if you had any to begin with) and motivation (since nothing is truly working).

Prototypes and iteration tend to work much better. In the end, a great design might come out of it, but more often something more simple and refined comes out of it. KISS and YAGNI come to mind.

I personally believe there needs to be a balance. If there's a core mechanic of your game, work on it. You still need to iterate, but you do need to refine it. Hint: organization of your code is not a core mechanic of your game.

Case in point: Peggle, by PopCap Games. A core mechanic of the game is the ball physics. They perfected it! I'm sure they spent quite a lot of time making sure it was absolutely perfect, because it is what makes the game. But at the same time, I can totally picture an early prototype of their game that maybe just draws sprites to the screen and does some type of more primitive collision detection and bouncing, just to see if the game idea is fun. Then once they found out that shooting a ball and watching it bounce can actually be fun, they refined the bouncing of the ball. (this is all just speculation, of course)

It also depends on your technical requirements, which you should nail down early on (not your game design, just the technical requirements). The platform that your game runs on should not change, or if it should be allowed to change, you need to know exactly the extent that you plan to allow it to change, no more and no less. Design on that. If you're developing a game for OpenGL, and you don't care about DirectX, then really, don't care about it. That means that if it's more convenient for you to have each entity draw itself and not worry about Factories and other design patterns like that, then do that. It's okay, because it meets the requirements. You should not have to change it later, despite what you tell yourself. And really, worst case scenario? Refactor later. It takes time later but it lets you focus on the **now**, getting a working game on one platform even if it means it can't simultaneously and automatically run on your toaster.

Test driven design, however, is a more opinionated topic. I am of the belief that game developers should do more of it. I also think game developers have some of the most rigorous, tight schedules, and they think they can't afford to spend time on TDD when they just want to get a game going. Also, again with the motivation, TDD is a lot slower and you get to see a lot less of a functioning game (in the beginning at least). This can have serious negative effects on programmer motivation.

I think it's also just a general lack of knowledge and practice. I don't think TDD is prevalent in other areas either, but like agile development, I think it's spreading. You might say it's ahead of its time (or maybe not, as the case may be years from now). More important than TDD is "RDD" - Requirements Driven Development. I just made that up. What is your goal? To make a game. Everything else comes second. If you can prove that TDD increases productivity and helps teams reach deadlines, then don't you think everyone would be using it? And maybe that's the case. But right now, our industry is more competitive than ever, there are harder and sooner deadlines, and stuff just needs to work. Construction workers don't build scaffolding first; they lay a foundation, then they raise some walls and floors, and only then do they build selective bits of scaffolding to do specific tasks which scaffolding makes more convenient. I think the same applies to software development.

Sorry for such a long post. I hope you've gained some bits of wisdom from it. I am just a student, talking about my observations, with very limited industry experience but a lot of reading from industry experts. So take my words with a grain of salt.

And hey, do what you think will work. You can always change it or scrap it and start over. That's the cool thing about any form of engineering; if at first you don't succeed, try something different. (or something like that :-P ) You're not pouring concrete; software is malleable.

---

By the way, I've been asking this same type of question and researching these types of design principles for some time. Here are some questions, both here and in Stack Overflow, that you might find relevant:

# Answer
> 36 votes
*Here's my original answer to a similar question on SO from a while back, at least concerning the MVC part of your question:*

It's rarely used in games. It took me a while to figure out why, but here's my thoughts:

MVC exists to make a distinction between two representations. The Model is the abstract representation of your data. It's how the machine views the state of your application. The View (and Controllers) represent a more concrete visible instantiation of that system in a way that's meaningful to humans.

In most business apps, these two worlds are pretty different. For example, a spreadsheet's model is simply a 2D grid of values. It doesn't have to think about how wide the cells are in pixels, where the scrollbars are, etc. At the same time, the spreadsheet view doesn't know how cell values are calculated or stored.

In a game, those two worlds are much closer to each other. The game world (model) is typically a set of entities positioned in some virtual space. The game view is also a set of entities positioned in some virtual space. Bounding volumes, animation, position, etc., all things you would consider part of the "view" are also directly used by the "model": animation can affect physics and AI, etc.

The end result is that the line between model and view in a game would be arbitrary and not helpful: you'd end up duplicating a lot of state between them.

Instead, games tend to decouple things along domain boundaries: AI, physics, audio, rendering, etc. will be kept as separate as possible.

# Answer
> 22 votes
Because MVC doesn't fit in the architecture of a game. The dataflow for a game is entirely different than that of a enterprice application, because it's not as event driven and there is often a (very) tight millisecond budget in which to perform these operations. There are a lot of things that need to happen in 16.6 milliseconds so it's more beneficial to have a 'fixed' and rigid data pipeline that processes the data you need on screen in exactly that time.

Also, the separation is there; most of the time it's just not wired the same way as the MVC pattern. There is a rendering engine (View), user input handling (Controller) and the rest such as gameplay logic, ai, and physics (Model). Think about it; if you're fetching user input, running the ai and rendering the image 60 times per second, then why would you need an Observer between the model and the view to tell you what has changed? Don't interpret this as me saying that you don't need the Observer pattern in games, you do, but in this case you really don't. You're doing all that work, every frame, anyway.

Although TDD is hardly ever used in development studios, we do use Agile practices towards software development and SCRUM seems to be the popular choice at least here in Europe. The reason is simple, the changes come from everywhere. The artists might want more texture budget, larger worlds, more trees while the designers want a richer story (more content on disk), a streaming world and the publishers want you to finish on time, and on budget and so does the marketing department. And apart from that, the "state of the art" keeps changing rapidly.

That doesn't mean that we don't do testing either, most studios have large Q&A departments, run loads of regression tests and do unit tests on a regular basis. However, there's hardly any point doing unit tests upfront because a large part of the bugs are art/graphics related (holes in collision meshes, wrong textures whatever, glitch in the depth of field shader) that unit tests can't cover. And besides working code, the most important factor of **any** game is that it's fun, and there's no unit testing that.

Also remember that in the console world this is even different still, because you're programming more for the hardware then for anything else. This generally (PS2/PS3) means that the flow of the data is way more important then the flow of the code in nearly every case; due to performance considerations. Which nullifies the use of TDD as an architectural tool in most cases. Good OOP code generally has bad dataflow, making it hard to vectorize and parallelize.

# Answer
> 14 votes
> Why are MVC & TDD not employed more in game architecture?

Warning: opinion ahead.

MVC isn't used (much) because:

1. MVC is a relatively new approach and games are typically built on old code. Most people making MVC apps are building them from nothing each time. (I know MVC itself is actually decades-old; what is new is the widespread interest in it, which essentially came from web apps like RoR). In the business software I worked on that was based on legacy code, there was no use for MVC there either. It is a culture thing, but it's not game-specific.
2. MVC is essentially a GUI pattern for event-driven programs. Games are neither GUI-dominated nor event-driven, hence the applicability is not as great as it is for web apps or other form-based applications. MVC is typically the Observer pattern with some well-known roles, and games often don't have the luxury of waiting to observe something interesting - they have to update everything every frame (or some variation on that) whether or not anybody has clicked anything.

That's not to say games can't learn a lot from MVC. I always try and separate the model from the view in games I make. The traditional idea of the view and controller being 2 parts of the same (widget) object doesn't really work though, so you have to be a bit more abstract about it. I agree with you that performance is unlikely to be a real problem here. If anything performance can benefit from keeping visual stuff and logic stuff separate as that is more amenable to cache coherency, parallelism, etc.

TDD isn't used (much) because:

1. It's really awkward to use in games. Again, it's fine for event-driven software where inputs come in and outputs come out and you can compare what you saw against what you expected and tick it off as correct. For simulations with large amounts of shared state it's significantly more awkward.
2. There's no indisputable evidence that it helps anything at all. Just a lot of claims, and some figures often based on self-reporting and appeals to authority. Perhaps it helps poor programmers become mediocre but holds back good programmers. Perhaps the time spent writing tests could be better spent learning SOLID principles, or designing the correct interface in the first place. Perhaps it gives a false sense of security to have tests that pass without any real proof that you have enough tests to ensure your object does the right thing.

Again, as a caveat, I think unit tests are great, but I don't think "test first" is either beneficial or sensible. I also don't think it's practical to test the main simulation when there is so much shared state changing many times per second. I limit my tests to my low level and library code, generally.

However, as you can probably guess, I am largely biased against "'enterprise' coding practices" as enterprises are well-known for overrunning timescales and budgets. *"So do games developers!"* I hear you say - well, yes. I don't think anybody really knows the best way to develop software right now and I'm not convinced that adopting regimented practices in mainstream software is at all a step up from the freer practices in entertainment software. In fact I suspect it's primarily of benefit to those who rely on commodity Java programmers where these approaches are not a ladder to climb to greater heights but a safety net to stop them falling too low.

# Answer
> 9 votes
As Kylotan notes, "In games you can't treat the presentation aspect as a detachable and replaceable concept like HTML and CSS is for web apps". Having built a couple of games using a simple MVC pattern (not a huge framework) I've found the major problem is that your model needs to know about your view. It is very likely that you will need to use either sprite bitmap data, hitbox data or 3D geometry data from your art assets to help work out collision detection (or another similar task). This means each model needs a reference to its view, which breaks the classic MVC pattern - for example you can no longer create a new view to an existing model etc.

The component model you see in e.g. Unity3D is the best way to organise game code.

# Answer
> 4 votes
MVC, at some levels, is already used in game development. It's forced on it by the OS, which has different interfaces for input and graphics. Most games also have a few more instances of MVC in them, e.g. separating the physics and rendering and input threads. This works fine. The modern idea of MVC appears to be that it should be repeated, fractally, until no one can understand the code anymore. Games don't do that, thankfully.

TDD is not used because it's rarely known a game is "supposed to do" before you iterate on a prototype many times. Practices from TDD, like continuous testing or integration testing, are often used in game development.

# Answer
> 3 votes
Game systems are slowly moving over to better practices. Frameworks like XNA provide an insight into making code more generalized/clean without adding too much overhead in design or execution time. But in general I would say that game systems are all about optimizing complexity vs execution speed, all while staying on a tight development schedule and staying motivated. Applying software engineering concepts and system design is just not priority #1 in such an environment.

In my personal game projects, I try to comment code or at least make it readable, and I throw together systems that will allow a bit more flex later on (ie generality) as much as possible, but at the end of the day, if you haven't moved your game forward it just doesn't feel very good.

Also typically by the time you've finished your game, you've got at least 1000 ideas on how to improve the underlying mechanics, the core systems, etc, in such a way that very little of that "re-usable" code will really be usable. By day I work a regular SE job, and while the systems we work on may be massive, in all honestly I think they pale in comparison to the complexity in games.

# Answer
> 2 votes
I have no particular opinion of MVC outside of the fact that the view is often separated from the logic by the simple fact that the render loop is packaging a bunch of stuff up for some hardware to process and that's not the place where you want "game logic" happening concurrently. The "controller" is also separated by hardware, but unfortunately many if not most game developers do "interesting" work in the controller handler. (IMO the controller handler should be reading the buttons and sticks and building a "presentation" for the game to view, but my soapbox isn't that strong.)

TDD on the other hand is something that I have very strong opinions about. It just changes development in a way to yield software that is easier to build upon. It is harder to do, no doubt about it. Of course, since it's harder to do, it's not done. Some folks whine about TDD (or more generally unit testing) having no value because "the game is the test," but the fact is that in TDD, the testing is almost irrelevant. The point of TDD is the software design and architecture that comes out of the process.

Embracing TDD really changes one's approach to programming. I had some feelings about what was right and what was wrong before I started down the TDD path, but once I jumped in with both feet I really came to understand a lot more about how the things I was doing was either helping or hindering future development. Indeed, this is sort of the point behind the coderoom post, TDD without the t.

Back to why it's not used more in games, beyond being hard, it makes people realize that the way they've always done it in the past needlessly made their own jobs harder, and for programmers especially that's a bitter pill to even look at, much less swallow.

I am convinced that people who refuse to accept TDD simply don't want to be better programmers. They already think that they're "excellent" at programming or design or architecture, when in fact their code says something completely different.

---
Tags: architecture, design-patterns, project-management
---


title: Blitting in AS3 with anti-aliasing?

text:
# Question
Title: Blitting in AS3 with anti-aliasing?
What would be the fastest method for doing anti-aliasing for a flash game that is drawn via blitting to a BitmapObject?

A method I thought of would be to make games stage smaller than the BitmapObject that the game is drawn to, and then somehow shrink it to the size of the stage.

Would that method work? If so what would be the fastest and highest quality to shrink the bitmap? Or would there be a completely different way to do it?

# Answer
The simple way is to let Flash do the bitmap resampling for you. Rather than composing the scene with blitting, make a movable object an individual Bitmap added to a parent DisplayObject, give the Bitmap fractional x,y coordinates, and set its pixelSnapping to NEVER. (The default for pixelSnapping is AUTO, which means Flash will round to int coordinates when the Bitmap's scale is close enough to 1.0, which I think is for aesthetic reasons as well as performance.)

I don't know how fast this dynamic resampling will be in arbitrary conditions. You should try it for your case and see if it's fast enough. One complication: I think Flash will use the GPU for this when it can, so simple tests may be misleading.

The much-more-work-but-maybe-faster way is to precompute resampled Bitmaps, like for one Bitmap, generate 16 Bitmaps, one for every .25 pixel offset in the x/y directions, and then blit whichever one is closest to the subpixel position.
> 3 votes

# Answer
I think that would work, and that you'd need to make your bitmap twice the screen size (or a higher integer multiplier) for the best quality.

However, that means you have to either draw everything scaled (so no copyPixels) or just work with larger source bitmaps (larger file, more memory usage), and you might be losing more performance than blitting is giving you.
> 1 votes

# Answer
I believe that you could add a Bitmap to the stage that is twice the size of the stage, set its scalex and scaley to 0.5, and then blit to its BitmapObject. I'm not sure how the performance would work out on it.

I'm a bit confused as to why you need antialiasing at runtime, though. Can't you antialias your bitmap resources beforehand, and just blit them directly, with alpha merge if necessary?
> 1 votes

---
Tags: actionscript-3
---


# Question
Title: Scripting and Cinematics without Threading
I've been struggling with how to implement scripting in my game engine. I only have a few requirements: It should be intuitive, I don't want to write a custom language, parser and interpreter, and I don't want to use threading. (I'm certain there's a simpler solution; I don't need the hassle of multiple game logic threads.) Here's an example script, in Python (aka pseudocode):

```
def dramatic_scene(actors):
    alice = actors["alice"]
    bob = actors["bob"]

    alice.walk_to(bob)
    if bob.can_see(alice):
        bob.say("Hello again!")
    else:
        alice.say("Excuse me, Bob?")

```

That epic piece of storytelling poses implementation problems. I can't just evaluate the whole method at once, because `walk_to` takes game time. If it returns right away, Alice would start walking up to Bob, and (in the same frame) say hello (or be greeted). But if `walk_to` is a blocking call that returns when she reaches Bob, then my game gets stuck, because it's blocking the same thread of execution that would make Alice walk.

I considered making each function enqueue an action -- `alice.walk_to(bob)` would push an object onto a queue, which would get popped off after Alice reached Bob, wherever he was. That's more subtly broken: the `if` branch is evaluated immediately, so Bob might greet Alice even if his back is turned to her.

How do other engines/people handle scripting without making threads? I'm starting to look in non-game-dev areas, like jQuery animation chains, for ideas. It seems like there should be some good patterns for this sort of problem.

# Answer
The way something like Panda does this is with callbacks. Instead of blocking it would be something like

```
def dramatic_scene(actors):
    alice = actors["alice"]
    bob = actors["bob"]

    def cb():
        if bob.can_see(alice):
            bob.say("Hello again!")
        else:
            alice.say("Excuse me, Bob?")
    alice.walk_to(bob, cb)

```

Having an on-complete callback allows you to chain these kinds of events as deeply as you want.

EDIT: JavaScript example since that has better syntax for this style:

```
function dramatic_scene(actors) {
    var alice = actors.alice;
    var bob = actors.bob;
    alice.walk_to(bob, function() {
        if(bob.can_see(alice)) {
            bob.say('Hello again!');
        } else {
            alice.say('Excuse me, Bob?');
        }
     });
}

```
> 3 votes

# Answer
The term you want to search for here is "coroutines" (and usually the language keyword or function name is `yield`).

> Coroutines are program components that generalize subroutines to allow multiple entry points for suspending and resuming execution at certain locations.

The implementation will depend first of all on your language. For a game you want the implementation to be as light weight as possible (lighter than threads or even fibres). The Wikipedia page (linked) has some links to various language-specific implementations.

I hear Lua has built-in support for coroutines. So does GameMonkey.

UnrealScript implements this with what it calls "states" and "latent functions".

If you use C# you could look at this blog post by Nick Gravelyn.

Additionally the "animation chains" idea, while not the same thing, is a workable solution to the same problem. Nick Gravelyn also has a C# implementation of this.
> 13 votes

# Answer
not going threaded is smart.

Most game engines work as a series of modular stages with stuff in memory driving each stage. For your 'walk to example', you usually have an AI stage where your walked characters are in a state where they shouldn't be looking for enemies to kill, an animation stage where they should be running animation X, a physics stage (or simulation stage) where their actual position is updated, etc.

in your example above, 'alice' is an actor composed of pieces that live in many of these stages, so a blocking actor.walk\_to call (or a coroutine you call next() on once per frame) would probably not have the proper context to make lots of decisions.

Instead, a 'start\_walk\_to' function would probably do something like:

```
def start_cutscene_walk_to(actor,target):
    actor.ai.setbrain(cutscene_brain)
    actor.physics.nocoll = 1
    actor.anims.force_anim('walk')
    # etc.

```

Then, your main loop runs its ai tick, its physics tick, its animation tick, and its cutscene tick, and the cutscene updates the state for each of the subsystems in your engine. The cutscene system should definitely track what each of its cutscenes is doing, and a coroutine driven system for something linear and deterministic like a custscene might make sense.

The reason for this modularity is that it just keeps things nice and simple, and for some systems (like physics and AI), you need to know the state of everything at the same time to resolve things properly and keep the game in a consistent state.

hope this helps!
> 3 votes

---
Tags: scripting
---


title: Vertex Shader Fundamental Workings

text:
# Question
Title: Vertex Shader Fundamental Workings
I understand that water ripples (e.g. stone thrown into a pond) are often handled with vertex shaders. My first question is: are the ripples nothing more than an algorithm that is the function of time?

If yes, it means that the size and diameter of ripples is not "additive." It means water vertices do not statefully "remember" their previous "disturbance" positions and accumulate more translation info. Rather it means that, as a function of time, the position of "disturbed" water vertices are freshly computed each frame *per unit time*.

If no, it means that indeed the vertices accumulate disturbance / translation information - the vertices are stateful.

I hope the answer is "yes," because that actually makes sense to me. If the answer is no, the I feel it creates tremendous burden on the CPU/GPU to keep track of all the state-per-vertice. If the answer is "neither," do tell. :)

My second question is, assuming a "yes" above, how does such a "water disturbance shader algorithm" account for continuous interaction with irregular shapes? For example, please look at the video 40 second mark showing a car crashing through water. It is not so clear how the vertex shader knows how to make a rectangular disturbance shape (the shape of the car). Perhaps, over-simplifying, the vertex shader takes both time and a vector to generate the ripples, where the vector is the speed/direction of a car (and the shader code always makes a car-shaped rectangle no matter what).

Is this the right high-level understanding of how this water trick works?

# Answer
To answer your base question - a vertex shader does **not** modify the vertices of the mesh that it is acting on. A vertex shader is basically a transformation function that the vertices pass through when they are drawn. So vertices of the original model cannot accumulate movement.

So how is Dirt 2 doing its water effect? A bit of googling revealed this page that explains it:

> An example of hardware tessellated dynamic water surfaces using DirectX 11 in DiRT 2. Many areas of the track are covered in water. The CPU generates the height field texture when cars drive through it. The tessellator using ATI Radeon hardware generates hundreds of triangles based on the camera position. The result: A beautiful, physically accurate, dynamic water surface. In the DirectX 9 version of the game, the surface is an illusion represented by just two triangles.

So to take a stab at decoding this to explain how it works on a technical level:

You have a texture (probably quite low resolution) that is generated each frame (or couple of frames) on the CPU that describes the waves that are moving through the water (probably height and velocity). Because it's on the CPU it can easily be accumulative.

On DirectX 9 you have the vertex shader reading that texture and displacing the vertices of the water mesh based on the values in that texture.

On DirectX 11, where, as well as vertex shaders, you have geometry shaders that can create vertices, it is also subdividing the water mesh to add additional detail. And it's probably generating that detail based off information originally coming from the texture describing the wave (adding small ripples and turbulence and so on).

(It wouldn't surprise me if the pixel shader is also using the same texture, generated by the CPU, to figure out where to draw foam on the water's surface.)
> 4 votes

# Answer
yes to your first point. and yes to your "if yes".

Mystagogue: *how does such a "water disturbance shader algorithm" account for continuous interaction with irregular shapes?*

It is probably less irregular than you think. Wave propagation simply has a direction, time, a magnitude (amplitude), frequency, & some sort of dampening variable. In this case the direction is simply 90 degrees to the car's velocity.

Knowing the point of entry into the pond and the car's speed & direction (velocity), the propagation is simply calculated.
> 2 votes

# Answer
I am not entirely sure, but in the video you linked of Dirt 2, I believe the water is handled by a 2d height-map height map simulation of the water, and then that data is used by tessellation shaders to make a high resolution 3d displacement of the water without using too much GPU or CPU time.

Other games do something similar but use vertex shaders. I have seen some games that use pre-baked animations for the ripples and stuff so they are not additive, and some games use the 2d height map fluid simulation.
> 1 votes

---
Tags: shaders
---