title: Android: Angry Birds Scaling

text:
# Question
Title: Android: Angry Birds Scaling
Anyone have any idea how the scaling is accomplished in angry birds? I want to make sure my images/background always scale to match the screensize and this game seems to have a similar effect. I have been playing with the manifest settings lot on setting preferred screen sizes but I have yet to duplicate exactly what I want.

Are there any effective ways to make sure your game will always display X Y space, scaling down as needed depending on the pixel size?

I want to make sure everything is always displayed on the screen for all devices and not cut things off on small devices or add black space on large devices.

I am calculating my drawing space by getting the size of the view and using this as bounds for my sprites but it doesn't seem to be working too well.

# Answer
> 6 votes
To answer the original question, Angry birds uses regular raster graphics (not vectors). Just unpack the .apk (it's a zip file) and have a look at the textures yourself.

Angry Birds only happens to prevent you from setting a zoom factor over 1.x, thus avoiding upscaling(magnification) of the textures. It probably also uses OpenGL mip-mapping to avoid downscaling(minification) artifacts.

# Answer
> 4 votes
1. Use vector graphics. Vectors are not defined by points in space (i.e. individual pixels), they are defined by mathematical relationships, and easily adapt to smaller or larger views.
2. It's impossible to display the exact same image on a 4:3 ratio screen and a 16:9 ratio screen, for example, without compressing or stretching the image. Thus you will have to cut off things on 4:3 devices that would be displayed on widescreen 16:9 devices. This is not a bad thing in a game like Angry Birds where the user can pan to see what's missing.

# Answer
> 1 votes
On Android platform, there are:

* 320 * 240 (1.33)
* 400 * 240 (1.66)
* 480 * 320 (1.5)
* 800 * 480 (1.66)
* 854 * 480 (1.77)
* 1024 * 600 (1.71)

So, when you design your game in 2D, you must think about it. You have two technical solutions:

* choice a ratio (1.66 is the most widespread) and use black bands (like movies)
* Select a bounding box in which you cannot zoom out and another one for the zoom-in.

I use this method for Moblox and paint levels with these boxes. For best rendering on most phones, my bounding boxes have 1.66 ratio. With ratio 1.33 or 1.77 phones, there are background elements not visible but i have designed my Level with centered actions. So players don't care.

---
Tags: android, resolution
---


title: HTML Canvas drawing - Firefox error

text:
# Question
Title: HTML Canvas drawing - Firefox error
I am getting the following error ONLY when running my game in Firefox (3.6)

> Component returned failure code: 0x80040111 (NS\_ERROR\_NOT\_AVAILABLE) \[nsIDOMCanvasRenderingContext2D.drawImage\]

The issue does not occur in the other major browsers, and my game runs completely fine after I click 'OK.'

Here are a few snippets of code where I have localized the issue to. Has anybody seen this issue before? According to Google it has something to do with drawing the image before it is loaded, but from my understanding I am loading it properly before using it!.

**player class**

```
var player = new (function(){
  var that = this;
  that.image = new Image();
  that.image.src = "res/enemy1_sprites.png";
  that.width = 16;
  that.height = 16;
  that.frames = 2;
  that.actualFrame = 0;
  that.spriteXoffset = 0;
  that.spriteYoffset = 0;
  that.moved = false;
  that.boundary = false;
  that.num_balls = 5;
  that.rootX = 350;
  that.rootY = 250;
  that.ballX = [that.rootX,0,0,0,0];
  that.ballY = [that.rootY,that.rootY,that.rootY,that.rootY,that.rootY];

  that.directions = {"up":0, "right":1, "down":2, "left":3};
  that.dirs  = [that.directions.right,that.directions.right,that.directions.right,that.directions.right,that.directions.right];

  for (i = 1; i < that.num_balls; i++)
    that.ballX[i] = that.rootX - (i * that.width);

...
...

that.draw = function(){
    try {
      for (var i = that.num_balls-1; i >= 0; i--)
      {
        // update animation
        switch (that.dirs[i])
        {
          case that.directions.left:
            that.moveLeft();
          break;
          case that.directions.right:
            that.moveRight();
          break;
          case that.directions.up:
            that.moveUp();
          break;
          case that.directions.down:
            that.moveDown();
          break;
        }
        ctx.drawImage(that.image, that.spriteXoffset, that.spriteYoffset, that.width, that.height, that.ballX[i], that.ballY[i], that.width, that.height);
      }
    }
    catch (e) {
      alert(e.message);
    };

    if (that.moved)
    {
      if (that.spriteYoffset > 0)
        that.spriteYoffset = 0;
      else
        that.spriteYoffset += 16;
      that.moved = false;
    }
  }
})();

```

**game loop**

```
 var GameLoop = function(){
    ..
    ..
     player.move();
     player.draw();
    ..
    ..
      if (state)
        gLoop = setTimeout(GameLoop, GAME_SPEED);
    }

```

# Answer
The javascript is loaded and starts executing before you load the image, as you pointed out. When you do:

```
that.image = new Image();
that.image.src = "res/enemy1_sprites.png";

```

You are starting to load it, but then the javascript continues executing and reaches your line

```
ctx.drawImage(that.image, that.spriteXoffset, that.spriteYoffset, that.width, that.height, that.ballX[i], that.ballY[i], that.width, that.height);

```

... without knowing if the image is loaded or not. You need to check for that. The question is where to wait for the image to be loaded. An easy option is to modify your draw() function, so that the line I just quoted above this paragraph becomes:

```
if (that.image.complete)
    ctx.drawImage(that.image, ...)

```

But in this case you will be updating the whole game before being able to show it. It would be better to make the game wait for the image to be loaded. Then the game loop becomes something like:

```
..
if (player.image.complete) {
    player.move();
    player.draw();
}
..

```

If you have more than one image in your game (and not just the player one), you should wait for all of them to be loaded before launching the GameLoop function. This way you don't have to introduce extra checks within your game code. You can do that by launching a function with a timeout that periodically checks if all of them are loaded. When the condition is met, then you can launch GameLoop. But that is just an idea, there might be better ways.
> 4 votes

---
Tags: javascript, html5, html-canvas, browser-based-games
---


title: Why do we use scripts in development?

text:
# Question
Title: Why do we use scripts in development?
In my current project, Lua scripts are called by the C++ functions on the server side. After that, the scripts again call the C++ functions still in that solution. Why should we do such things and not call the C++ function directly? What are the situations in which scripts are needed?

# Answer
Scripts are usually **compiled at run time**, while the host language will be compiled at compile time. This means that we don't need to recompile if the script changes. Recompiling a full game can take minutes to hours, which implies a big productivity hit.

Usually, the critical code or backend code will not be scripted. This code should run fast and often memory management is crucial.
In games, game logic and configuration are typically contained in script files. These **scripts can easily be updated by non-programmers** (like the designer) to tweak the gameplay. Script languages are easy and act in a forgiving manner for that purpose.

Often, a script language is also used to do **scripting at real time**. This comes in handy for tweaking some gameplay elements or even for debugging. Many games provide a console for this (mostly in-house) purpose.

It is very well possible that you create a game using an existing game engine, just by scripting. The **game engine layer is thus fully decouple from the game logic layer**. Modern engines can usually be used to create FPS or RTS games easily like this, but it is not possible for any genre. An MMO would probably require another type of engine.

So the bottom line is decoupling. The benefits listed above often outweight the extra work to create or integrate a scripting language.
> 76 votes

# Answer
You asked the wrong question. The real question, I think, is why do we put up with "non-scripting" languages like C, C++, Java, and so on? And the answer is one reason: performance. (And maybe inertia, but that inertia is there because of performance, and anyone who can write good C/C++/Java can write at least passable Ruby/Python/Lua/JavaScript.)

We use "scripting" languages (which really means, very high-level, garbage collected, and usually some form of looser typing and dynamic compilation) because they're generally easier languages for anyone - programmers included - to write code in. There's less *stupid stuff* like remembering to free after you malloc or make sure your code is exception-safe, or remembering to make all your destructors virtual. If our computers were infinitely fast, we would be using "scripting" languages for everything.
> 41 votes

# Answer
Scripting languages for game logic is a very good example of the software architecture pattern Alternate Hard and Soft Layers. There's a good discussion on that site (and others I'm sure) on the benefits of doing so.
> 10 votes

# Answer
1. Each new lua class is two lines. Each new C++ class is pain.
2. No whining about types when all you want is shuffle values around.
3. Garbage collection.
4. Script code is nicely isolated in virtual machines, away from all those nasty wandering segfaults and array overflows.
> 8 votes

# Answer
Script changes are easy to deploy. For example, you can keep scripts in a database which means that instead of a full binary redeploy and possible service restart, you just issue a single SQL UPDATE statement, possibly followed by a signal to your running service to reload the script.

Also script languages are often simple to understand and easy to program in so you don't need the 'hardcore' devs (the ones dealing with Memory Management/Pointers and cpu-level optimizations) for the majority of code (if a large RPG, the scripts for AI, Spells, Item Effects and the world itself are often bigger than the engine code). Script languages allow a lot more focusing on the 'what' rather than the 'how' due to Garbage Collection (in case of Lua) and a higher level of abstraction.
> 6 votes

# Answer
One scenario where the scrips are useful is when we want our engine to be extensible by plugins/addons. These extensions are created in many cases by non-professional people (like advanced gamers and enthusiasts). Scripts are safer and easier for this purpose. By using scripts, they don't need to use compilers, and don't need to be aware of pointers...

A great example of this is the game World of Warcraft. It has thousands of addons created by the community. These addons are written using LUA + XML.
> 4 votes

---
Tags: scripting
---


title: UDK, can you add your own effects?

text:
# Question
Title: UDK, can you add your own effects?
I'm new to game development and am curious to know if you can add your own cg effects? Like if I wanted to add fog to my game and UDK didn't support that, is that possible?

What kind of coding does one do, in a engine like UDK?

# Answer
> 2 votes
What you ask is possible. There are a variety of nice tutorials on the UDN and on the UDK forum that shows you how to do exactly what you ask.

UDK, Like Unreal Engine uses the UnrealScript scripting language. Inspired by C++ and Java it's fairly easy to come to grips with. You don't have access to source code using the UDK.

Also, there is a visual scripting language called Kismet And it is usually how people accomplish what you may be looking to do from your question.

I also recommend Raven67854's Tutorial Series on Youtube. It's an excellent primer for getting started.

# Answer
> 0 votes
I'd advise that you start out making some small 2D games, it takes a lot of time and skill to get 3D stuff looking good, and as a beginner you are better off waiting with those worries.

To answer your question, yes you can add your own effects in UDK, primarily using shaders. But I'd guess it ships with a bunch of effects, a fog effect would probably be very easy to include in a game, whereas some other shader effects would require some specific instructions in order to only apply where they should.

UDK has some C branch language included, I guess it's not very different from common programming languages, there is also some visual code editor, but I guess the former is preferable.

# Answer
> 0 votes
If I understand correctly, and you're asking specifically about adding your own Cg/HLSL, the short answer is, no, you cannot write your own shader code. I've been down that path, and eventually had an Epic employee tell me that everything I wanted to do is impossible in UDK.

Question here: Questions about rendering access in UDK

Epic forum thread: http://forums.epicgames.com/showthread.php?t=741801

---
Tags: udk
---


# Question
Title: Chess engine on which to apply a custom-made OpenGL skin
Is there any open source chess engine that I can use to practice my OpenGL skill-set? I think it would be a neat exercise.

# Answer
You could take a look at GNU Chess . I'm not 100% sure, but I think there was a Python project that used GNU Chess as the AI "engine", so you can probably extend it to and make a 3D frontend.
> 4 votes

---
Tags: opengl, chess
---


# Question
Title: What does it mean to "strafe" the camera?
I'm looking at a tutorial in which both the terms camera moving and "strafing" are used. I looked onto dictionary.com and found:

> **strafe** verb (used with object) 1. to attack (ground troops or installations) by airplanes with machine-gun fire. 2. Slang . to reprimand viciously. –noun 3. a strafing attack.

WTF???

I'm not a native english speaker.

# Answer
Strafing is generally moving directly left or right, instead of rotating the camera.
> 11 votes

# Answer
Strafe is more of a character term than a camera term, although in games I've seen people use it for cameras since they are often directly linked to character movement.

Typically when talking about a camera the movements are.

* Tilt (rotation on fixed position camera to look up/down)
* Pan (rotation on fixed position camera to look left/right)
* Dolly In/Out (physically moving the camera towards or away from the subject)
* Zoom In/Out (changing the focal length of a fixed position camera to make the subject appear larger)
* Truck Left/Right\* (physically moving the camera left/right as defined by current orientation, this is what is matched to "Strafe" for characters)
* Pedestal Up/Down (physically move the camera up/down)
* Arc Left/Right (physically orbit the camera around some central object involving a combination of Panning and Trucking)

\*Truck is regularly used in TV, but sometimes Dolly is used for both forward/back and left/right movements.
> 9 votes

# Answer
It's a gaming term, so here are the relevant definitions: Wikipedia, Urban Dictionary

Basically it means translating/moving the camera (or player) left and right, where left and right are defined by the camera's current orientation.
> 3 votes

---
Tags: camera
---


# Question
Title: Is there any opengl cel shading tutorial out there (without GLAUX)?
I want to implement cel shading into my opengl game. I have only found a nehe tutorial that uses glaux (old as hell). I'm looking into it, but I wanna avoid the pain of learning how to translate those old glaux functions/variables. Is there any cel shading tutorial out there that uses glut/sdl?

http://nehe.gamedev.net/data/lessons/lesson.asp?lesson=37

# Answer
You should search Toon Shading too.

For english readers, a short tutorial.

For french readers, there is a great tutorial.
> 0 votes

# Answer
Here's an article explaining all the processes behind it, but not actually giving code.

Or there's the fact you also asked this on SO too, which is wasting everybody's time.

> Try the Linux/GLUT or Linux/SDL versions. No glaux.h needed.
>
> The Visual C++ version doesn't seem to actually use anything from glaux.h, it just #incudes it.

Above quote from genpfault.
> 2 votes

---
Tags: opengl
---


title: Why are my polygons not opaque?

text:
# Question
Title: Why are my polygons not opaque?
A newbie to XNA here. This is a followup to my previous question that showed me part of what I was doing wrong but I'm still not getting what I want. I'm setting up a BasicEffect thus:

```
Effect = new BasicEffect(GraphicsDevice);
Effect.VertexColorEnabled = true;
Effect.Alpha = 1.0f;
Effect.GraphicsDevice.DepthStencilState = DepthStencilState.Default;
Effect.GraphicsDevice.BlendState = BlendState.Opaque;

```

and the draw loop:

```
GraphicsDevice.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.Black, MaxDepth, 0);

```

All polygons are being rendered where and how I wish except they should be fully opaque and they aren't. The actual image looks more like the various colors are being combined in a fashion I'm not sure about:

# Answer
> 3 votes
You must set the DepthStencilState and BlendState before drawing the object, and not when creating your Effect, just like this:

```
GraphicsDevice.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.Black, MaxDepth, 0);
GraphicsDevice.DepthStencilState = DepthStencilState.Default;
GraphicsDevice.BlendState = BlendState.Opaque;

DrawYourThings();

```

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


# Question
Title: Lag compensation with networked 2D games
I want to make a 2D game that is basically a physics driven sandbox / activity game. There is something I really do not understand though. From research, it seems like updates from the server should only be about every 100ms. I can see how this works for a player since they can just concurrently simulate physics and do lag compensation through interpolation.

What I do not understand is how this works for updates from other players. If clients only get notified of player positions every 100ms, I do not see how that works because a lot can happen in 100ms. The player could have changed direction twice or so in that time. I was wondering if anyone would have some insight on this issue.

Basically how does this work for shooting and stuff like that?

Thanks

# Answer
Summary for those that don't like long answers...

It can be done but it's impossible to do *perfect* multiplayer physics if there is any latency. Why latency impacts physics is explained, and then tips for reducing the impact of latency on your physics simulation are offered.

---

Creating a multiplayer physics game can be fraught with peril. It is impossible to create a "perfect" online multiplayer physics experience. There are things you can do to make it better, but there is no way to make perfect physics assuming any latency.

The problem is, physics has to be fast and responsive to be realistic, but at the same time has to be calculated based on the combined actions of ALL factors -- meaning the combined actions of all players. And if there is latency, this can't be done in real time.

It is up to you as a developer to decide if you can keep the different factors under control, and to understand that the player's experience will degrade if the latency becomes too high. If you can live with that (and your players can), then go for it. See towards the end of this post for some notes about how you can keep things running smoother.

**An example to show how things can get messed up**

Imagine a game where two players (clients) are connected to a server. It takes 100 milliseconds (1/10th second) for a message to go across the internet from client to server. When a player does something, a message is sent to the server saying what they did. The server then broadcasts the message out to the other players so they all know what the acting player did.

Now create a scenario where two players have a crate on the ground which is a physics object. Player A hits it on one side, sending it moving in some direction. However at the same time, player B hits it on another side, sending it another direction.

Let's look at different ways to handle this and what the results would be...

**What if physics is calculated just on the server?**

Suppose we have the physics calculated only on the server. Player A sends "I hit crate this way" message to server, 1/10th second later server gets message. Player B sends their "I hit crate this other way" message. The server calculates physics change from the combination of the two actions, and sends message back to both players saying, "OK it moves like this." Perfect physics is performed, based on the actions of both players combined.

But the problem is, it will be 2/10th of a second before either player sees the crate react. The messages from both players take 1/10th of a second to reach the server, then another 1/10th of a second for the servers calculation results to be sent for both players.

Bottom line, laggy gameplay.

**What if physics is just calculated on the client?**

Suppose we have physics calculated on just the client. Let's look at it from Player A's point of view. Player A hits crate and it immediately starts going their direction. A message is also sent to the server saying what Player A did.

At the same time though, B has done their hit and seen the crate going in *their* direction and sent a message to the server about what they did.

2/10th of a second later, a message arrives from the server to the clients. A is told what B did, and B is told what A did. The problem is, both clients say, "Well player X may have done that hit at this spot, but there is no longer a crate at that location, so their hit did nothing."

Bottom line is, two games out of sync and players not having a shared experience. What's the point of multiplayer if they both see different things?

**What if physics is calculated on both client and server?**

In this case, physics is calculated on the client so players see an immediate no-lag reaction, but it's also calculated on the server so it is "correct" for all players.

Both players hit the crate their respective directions and each sees the crate move based on their hit only. But then 2/10th of a second later, the server comes back and says, "Well actually, you are both wrong. The crate went this way." Suddenly both players see the crate drastically change directions and glitch to a new location.

Bottom line is, a glitchy game.

**Conclusion**

Basically there is no way to make a *perfect* physics game with multiple players when any kind of latency exists. You can make a pretty good game, but you always will have the risk of excessive latency creating a bad experience for some players. However there are things you can do to keep your game experience a good one.

**Things you can do to make a multiplayer game run well**

Use simple collision volumes. Don't bother modeling every detail of a shape with physics when a simple cube shape will do. A spikey ball doesn't have to be modeled as a spikey ball for physics. Instead just model it as a sphere.

Make small inconsequential objects client-only items. An example might be bits of broken glass from a broken window. You can let each client simulate it on their own, and it won't really matter if they are different.

Only make objects physics objects if they need to be physics objects to keep the number of active physics objects low.

Run your game in slow motion when doing multiplayer physics. Think "bullet time" maybe. Slow motion games compensate for latency and allow multiple players to interact with physics together.

Allow players to setup a situation of some kind together, and then on some cue, the physics is simulated for both players and both watch the result of their combined actions. Players may not interfere with the sequence until it is completed.

Separate players phsyics so they can't interfere with each other. This would be great for a game like bowling or pool, where only one player at a time has control, or each player has their own "sandbox" (like a bowling lane).

If you can't beat 'em, join 'em and make physics lag be part of your game. Imagine a story about being in a glitchy universe with broken physics laws or something :)

**Appendix: How shooting games deal with it**

Shooting games deal with it by not doing overly complex physics. They do use client side effects so players see things quickly, but then the server makes the final call on what has happened.

Imagine a scenario where player A shoots player B. Your typical shooter game will do something like this...

1. A will locally calculate if they hit B, and if it looks like there is a hit, it plays a "hit" effect like a blood puff. This is done client side so that the player immediately sees a reaction to their action. If you don't do this, the game feels laggy.
2. A also sends a message to the server saying, "I shot along this vector"
3. When the server gets the message, it looks at where IT thinks the players are, and decides if A's shot vector hits B.
4. If the server decides A hit B, it decides B is hit, and sends a message to BOTH clients saying what happened.
5. If the server decides A did NOT hit B, B is fine, and A "misses". It may look to A like they hit ("I saw the blood puff!") but it's the servers call that they missed.

So how could A miss B when it looked like they hit them? Because B may have moved, but A hasn't seen it yet because the server hasn't sent a, "B moved to here" message yet to the client.

Valve has a good writeup on their site about this. See http://developer.valvesoftware.com/wiki/Source\_Multiplayer\_Networking
> 60 votes

# Answer
I've written a series of articles about the topic here: http://www.gabrielgambetta.com/fpm1.html

The first three articles deal with an introduction to the topic, client side prediction, server reconciliation, and entity interpolation (this is the part that answers your specific question). The 4th article (coming soon) will deal with "shooting stuff" :)

Tim Holt's answer is pretty much it. My articles have a couple of diagrams that may help you understand what's going on, but Tim and I are basically saying the same thing.
> 13 votes

# Answer
It's not unreasonable to do full prediction on your own character for responsiveness and to have other characters lag behind by 100ms for consistency. If this looks bad then consider having your own character lag slightly to keep them in sync. Either way you're still going to need correction mechanisms to smooth out incorrect predictions in the event of lag spikes, and that system will deal with situations like the one you describe. It doesn't matter whether the latency is 100ms or 1ms - your client is always 'late' in some sense and therefore always has to act like it is dealing with old data and apply cosmetic effects such as interpolation to make it look reasonable.
> 2 votes

# Answer
In the end its all about making do with the available network resources. Ideally we would live in a world with zero latency and everything can be perfectly synchronized. Realistically, you update the clients every 100, 200, 300 ms and in the client there needs to be logic in place to make what has happened look smooth. The "smoothness" is very important, in the end the game just needs to feel smooth even if at the back end there is some chaotic synchronization happening between client and server.

A good post and better answer can be found:

How to write a network game?
> 0 votes

# Answer
The problem isn't really the latency. It can be compensated and predicted quite well to hide any problems caused it. Packet loss isn't a problem either - the networking system should be written to be robust and tolerable for packet loss. However, the problem is the lag spikes and unpredictable latency. Packets arriving out of sync, some of them being dropped only because of latency swings, inability to predict and interpolate because of latency swings etc.
> 0 votes

---
Tags: game-design, physics, networking
---


# Question
Title: Creating non-rectangular hotspots and detecting clicks
Say for a game with irregular hotspots (say Risk, or a strategy game like Paradox's Hearts of Iron or Crusader Kings), how do you

1. Define a non-rectangular hotspot of irregular shape (much like a territory on a map?), in code?
2. What tool can you use to trace out the hotspot and import into your game?
3. What is the algorithm for detecting if someone has clicked within such a hotspot?

# Answer
> 9 votes
Besides the vector/polygon approach, another way to do this is to use a bitmap.

If each "color" in the bitmap represents a territory (France, Belgium etc.), then it's simply a matter of figuring out which pixel in the bitmap was clicked, looking up the color and determining if that color represents the territory of interest. You can even represent overlapping territories with specific colors, or treat your colors as a bitmask of territories.

In terms of tools, have your artists/content producer author the bitmap in any pixel editing tool. For example if you use Photoshop or the Gimp, you could represent different territories (France, Belgium etc.) as either named layers or as 1 layer but distinguishing the territories based on colors. You would then write a tool to convert the image/layers into a format that is suitable for game-internal purposes.

The game internal format would very likely be per-row run-length compressed (see: http://en.wikipedia.org/wiki/Run-length\_encoding). You should be able to achieve very good compression ratios this way, as adjacent pixels on rows will very often belong to the same territory. The algorithm then becomes, for the current y coordinate of the mouse, traverse that row and figure out which run it belongs to, and therefore which corresponding territory.

# Answer
> 7 votes
You'll need to define the hotspots as a series of polygons that overlay your image. Then, when a user clicks on the map, go through the list of polygons (clickable hotspots) and see which (if any) the click point is inside of.

Also, you might look into how imagemaps in HTML are done. Not that you will be working with HTML, but basically they are essentially what you want to implement. They allow for defining hotspots as rectangles, circles, and polygons (which is what you want).

Here's a webpage describing HTML image maps that might give you some ideas: http://www.javascriptkit.com/howto/imagemap.shtml

Here's a Wikipedia article on algorithms to tell if a point is in a polygon: http://en.wikipedia.org/wiki/Point\_in\_polygon

# Answer
> 2 votes
You can define an arbitrary shape as just a series of points that are turned into line segments.

The collision test for "am I inside this arbitrary shape" is given by my answer here: In Cocos2D, how do I check for collisions against an arbitrary user-drawn shape?

# Answer
> 1 votes
For this kind of thing we use an image used as a mask, with transparent/opaque or black/white pixels. The masks aren't drawn, but are conceptually "placed" over the map region they cover.

When you get a click, first check the bounding box of the image. If it's outside, the player didn't click the region. If it's inside, check the pixel. If it's transparent/black, the player didn't click the region. Otherwise, he did.

If memory usage is a serious concern, you can use half-sized images and apply the appropriate screen to image coordinate conversion. You won't get pixel-perfect detection but you probably don't need it in this case.

Also, if you go transparent/opaque, either save the masks as PNG (or any other lossless compression scheme) or use a high threshold (alpha \> 128 instead of alpha \> 0). Otherwise, JPEG artifacts may cause some of the transparent pixels to appear not so transparent (say alpha = 1 or 2 instead of alpha = 0)

---
Tags: algorithm, gui
---


title: Die Roll Mechanics

text:
# Question
Title: Die Roll Mechanics
I'm developing an RPG (goodness, I'm doing a lot actually.) and I'm trying to come up with a decent die roll mechanic for skills.

In d20 systems, it's usually

```
Die Roll + Skill + Bonuses - Penalties >= Some Target Number

```

For Many Warhammer (old) systems, you:

```
compare skill vs. skill on chart, Die Roll >= # given on chart.

```

For the HERO system, it's generally:

```
Roll 3D6 <= Skill + Bonuses - Penalties

```

etc.

But for each of these systems, they use a different die mechanic to determine the outcome of the action. D20 is notorious for using D8s, D10s, D12s, etc. Which you total up, and deal to someone else. That other person is then *fine* until they drop to 0hp. (other games are similarly designed, HERO for example using Body, STUN, and END).

Are there games that discard a second mechanic for action resolution as well as success?

For example, I'm thinking of using a black-jack mechanic.

```
Die Roll <= Skill + Attributes + Bonuses - Penalties

```

to determine if an attacker hits an opponent, and then that opponent must "resist" the damage caused by the attack, using a very similar roll. This is used on the table-top Warhammer games (Roll to-hit, Break Toughness, Armor Saves).

Damage is measured in penalties instead of in numbers. (ex. if a combatant failed 2 resists in combat, he'd suffer a -2 penalty for all other skill rolls). The penalties being easy to see/keep track of using counters etc.

* What pitfalls am I missing?
* What games use a mechanic similar to this?
* What other mechanics should I be concerned about?

Thanks,

---

\[EDIT\] Thanks for all the answers. These are really great.

**Damage and Death**

So the game has two types of damage, Injury and Wounds.

Each Injury (IJY) over the Injury Threshold (IJT) gives the player a -1 penalty. If the number of IJY exceed the Injury Limit (IJL), they are converted wounds instead.

Each Wound (WND) over the Wound Threshold (WDT) gives the player a -4 penalty. If the number of wounds exceed the Wound Limit (WDL), they go into a coma and begin to die.

So for the complete n00b, the numbers would look something like this:

* Injury Threshold 3
* Injury Limit 6
* Wound Threshold 0
* Wound Limit 3

A mid-level cyborg might look something like this:

* Injury Threshold 6
* Injury Limit 12
* Wound threshold 2
* Wound Limit 6

Able to take far more damage, and shrug off the first few strikes in combat.

Healing will also be non-random, and if a character uses a healing item - there's no roll or chance involved. They gain the benefit, and can go on with their life.

**Enemies**

I like very much the mechanics in Feng Shui and in DnD 4E in regards to Minions, Monsters, and Villains. I intend for Minions to have Wound Limits of 0. (one-hit kills) while Villains would be large, hard-to-take-down mosters where tactics and cover will be your best friends.

**Role-Playing Mechanics**

Similar to HEX, players can spend "points" the earn during roleplaying to negate bad rolls, or improve good successes. Players are not just at the whim of their dice, but can use other resources like points tactically.

And yes, this is intended as a table-top turn-based game.

Thanks!

# Answer
> 7 votes
Potential issues that come to mind:

**Negative Feedback Loop**

The biggest issue with degradation of skills/abilities when damaged is that you have potential for a feedback loop. The first entity to land a hit not only pushes their opponent towards death, but limits the opponents ability to respond. This makes it almost impossible for the loser at the beginning of an encounter to rally.

**Asymptopic Damage Reduction**

If both sides of a battle reduce their ability to hit/damage as they injure one another you may get to a point where both of them are constantly missing each other or doing such little damage that they fight to the equivalent of a standstill.

**Tactical Consideration Time Available to the Player**

If characters change in ability during the course of a fight the player needs the time to adjust to their changing status and react accordingly. Table top games are inherently turn based giving players plenty of time to make such considerations. If your combat resolves in real-time the effects of a degradation system can be lost of players adding confusion instead of a layer of strategic thinking.

# Answer
> 2 votes
One oversight with your system; unless I'm just missing it (possible), you don't actually detail how someone is defeated. Presumably at some level of penalties, they would be considered dead/incapacitated, but you don't actually spell that out. And for that matter, such a system isn't very different from hit points. It's still a resource which combatants, which is reduced by combat, and when it hits the magic number you fall over.

Your idea reminds me a bit of Mutants & Masterminds, a d20-based (albeit heavily modified) superheroes game.

Characters and enemies don't have hit points, they have toughness. The damage dealt to them is inflicted as a DC which they must beat on a toughness save. If they make the DC, they're fine. If they fail the DC by less than 5 (I think? been a while), they take a -1 penalty to further toughness save. If they fail the DC by more than 5, they're KOd.

So there's an idea to differentiate it from HP. Instead of dying when you reach a certain threshold, if you ever fail a check by a certain amount then you drop.

# Answer
> 1 votes
The New World of Darkness Storytelling System combines to-hit and damage in the same roll. Rolls use a pool of d10s of a size appropriate to the difficulty of the roll, and each d10 which rolls 8 or above is considered a "success" on the test. Attack rolls work like:

```
Attribute + Skill + Weapon Damage - target's Defense and Armor

```

The "successes" on that roll are equal to the number of points of damage taken by the target. There are three types of damage (bashing, lethal, and aggravated), but regardless of the type of damage, the character starts getting penalties when she has 3 or fewer "hit points" left.

This takes some feeling of agency away from the target, as she doesn't get to roll to resist getting damaged, but it makes combat a bit faster in tabletop: a single roll (single handful of dice) determines damage, and if you're repeating the attack the modifiers remain the same.

One pitfall to look out for is whether the penalties from damage will affect the target's defense. I recommend against this; it can suck when getting hurt makes it easier for you to get hurt.

# Answer
> 1 votes
It's pretty simplistic and designed for beginner gameplay, but you might check out the combat system used by the old D&D era pencil & paper game Tunnels and Trolls.

Basically, you and your opponent get a certain number of 6 sided dice. For you how many dice you get is based on your weapon. Bigger weapons get more dice, so a great sword user rolls 6 dice and adds them up, but a quarterstaff user gets just 2. Monsters also get dice based on their level.

In addition to your weapon dice, you get modifiers (additions to the dice roll) based on your attributes. Monsters also get modifiers based on their level.

To quote from the rules...

> After you get your hit point total, and your foe's hit point total, compare the two numbers. The side that had the higher number hurt the side that had the lower number. The difference between the two numbers indicates how badly the loser was hurt.

If you have armor, it just automatically blocks damage below a certain amount. Leather armor takes 6 hits for example, so if you get hit for 7 points of damage, the result is 7 - 6 or 1 point of actual damage.

Overall it is meant to be a very simple game that can be picked up very quickly and played by your average group that can scrounge up a bunch of 6 sided dice.

---
Tags: game-design
---


title: Lighting in a Minecraftian World

text:
# Question
Title: Lighting in a Minecraftian World
Minecraft is a game that is largely based on a heightmap and uses that heigtmap information to flood the world with light. From my understanding the highest point in the heightmap is the end of the sunlight influenced area. Everything above that is lit by sunlight, everything below that just is influenced by light nearby in a radius of 8 blocks.

Thus if you have a floating island on the top of your world everything below that will be seen essentially as a cave. When two lights influence the same point the brighter light wins (unsure about that).

Either way there are a couple of problems with minecrafts lighting model: first of all, if your world does not have a heightmap it becomes trickier to figure out what exactly is supposed to emit sunlight and what not. A simple way would be to assume that the world is (in my case) a floating rock and then traverse each axis from both directions and figure out where the rock starts and ends. But this does not fully eliminate the problem as dents in the rock are not supposed to be in darkness.

Minecraft itself will cache the light information in its chunks together with the information about the material of a block. Thus only if the world is modified the lighting has to update. Unfortunately that process is still pretty slow on updates and on quick light changes one can see the lighting lag behind. That's especially true if a lot of blocks change (TNT, sunset etc.) and you're not running the fastest computer (Or Java on Mac).

From my still limited understanding of 3D graphics lighting a world like minecraft shouldn't be the biggest issue. How would you tackle the problem?

I think the basic requirements for lighting in a voxel world would be

1. update fast enough that it could happen in a single frame. One might be able to do the lighting in the graphics device and download the changed light information to the main RAM.
2. light information must be quickly available for the main game logic so not entirely based on the graphics device: reasoning: light affects the growth of grass, spawning of monsters etc.
3. light updates would have to be local to a chunk or have some other limit so that one does not have to relight the whole world which might be very large in size.

The main idea would be to make the light updates fast, not necessarily more beautiful. For general light rendering performance improvements one could easily add SSAO on top of that which should result in much nicer worlds.

# Answer
Lighting in Minecraft is calculated asynchronously and is baked into the geometry. It is not done in realtime.

Each voxel stores the lighting for that voxel, probably as a single byte (or 2, notch uses a layered approach to make day and night cycles possible). There are only 16 levels of light. To light the world, Minecraft does 2 passes. One for the sunlight, and another to propagate or flood the light into caves and such. The lighting is localized because any light source can only propagate its light at most 16 blocks away. Water and lava works in almost the same way.

More info is available on his blog: http://notch.tumblr.com/post/434902871/per-request-this-is-how-the-new-lighting-will-work
> 7 votes

# Answer
Can you not use GPU Render to Texture & double-buffer your results so you always have computed lighting information available to read-back each frame?

How you'd organise this data for lighting is entirely up to you but I don't see why this shouldn't be the first option for investigation if all you're looking to do is improve the speed of your lighting algorithm..?
> 1 votes

# Answer
Real-time Rendering folks seem to have a bit of a love affair with Minecraft. There was a comment something about how they've not figured out the lighting yet.. but you might want to stay tuned for further developments / links.

http://www.realtimerendering.com/blog/?s=minecraft
> 1 votes

---
Tags: opengl, maps, lighting
---


# Question
Title: Are there existing software frameworks for traditional "Roll dice and move pawn" boardgames?
I am looking for a library or framework for creating software versions Roll and Move board games -- games where the basic play centers around players rolling a dice and advancing a pawn along a path.

I'm not interested as much in graphics, rendering methods, and so forth. I'm more interested in a system for defining these kinds of games, their rules, and managing game states. Ideally I'd like to see something like an XML file I could create that defines the game, and an interpreter that could load it up and run the given game.

# Answer
> 4 votes
The closest thing I can find is something called VASSAL. It doesn't seem to be as easy as setting up XML files for the game to work properly, but if you want a board game framework that supports multi-player, there you go.

Now your question is pretty interesting. Although to meet your specifications exactly, you might have to **Roll** your own. And I don't know if XML will be the correct tool for the job. For defining complex rules, either the interpreter will have to be overly complex and specific to work with all the variations of rules you could do in a board game, or you would have to define the rules in some kind of scripting language.

# Answer
> 2 votes
For something like this I'd just Excel. The problem with a general solution is that rules are one of the most unique elements in a game so creating a framework that let you plug in rules is kind of hard.

Most of them break down to basic math and boolean state changes which Excel handles well.

So do what you can with standard cell math, and then when needed throw in a little VBasic to make buttons for rolling dice and so on.

---
Tags: architecture
---


# Question
Title: Net code: What are your expected and max latency and packet loss targets?
When doing the net code for a video game what sort of latency targets and packet loss rates do you design around?

To be more specific I have my net code working local network only at the moment. I plan on using WANEM to simulate packet loss and latency but I am not sure what I should use for max and average values.

# Answer
Packet loss is hard to guess, but internet latency you should probably plan for up to ~750ms, though the vast majority will be under 500ms. The biggest outliers are Australia\<-\>US pings and satellite internet. Depending on your target market maybe you can ignore those. If you are doing stuff for mobile devices it can be even more unpredictable. As a random guess for packet less I would say to plan for somewhere around 1-5% at the most, generally we see much less than that (~0.1% at the worst of times) and usually that is only on UK\<-\>US links at peak hours (UK peak that is). The packet loss itself isn't a problem, but throw the transatlantic latency into the mix with TCP retransmission and you get a very jittery connection and can have trouble managing network buffers (this was for file transfers, for lower data rates I doubt this would be a problem).
> 5 votes

---
Tags: architecture, networking
---


title: Best API coverage for 2D game?

text:
# Question
Title: Best API coverage for 2D game?
If one were to code a game for most versions of Windows, which API should be used?

I know DirectDraw works from NT4 and up (although DirectDraw is emulated on NT4 with GDI). However, I am told DirectDraw is deprecated in newer versions of Windows?

I could revert to just GDI, but then it is hard to completely eliminate flicker, since there is no double buffering with flipping between buffers.

Should I go for Direct3D or DirectDraw? Or is there some way of completely eliminating flicker in GDI or some other Windows API I am not aware of?

If Direct3D is the answer, which version of it is supported on most platforms?

# Answer
I personally would not bother targeting anything below Windows XP. Writing something that works on XP/Vista/7 will get 99% of people on Windows and allow you to use modern technologies.

Direct3D is definitely an option, and so is DirectX. Another option is OpenGL.

I would personally recommend DirectX 9. There are a lot of great resources and tools that will allow you to pick it up quickly and build a good game with it. As I understand it, D3D and OpenGL are pretty ugly.
> 7 votes

---
Tags: directx, windows
---


# Question
Title: What tools are available for creating 3D collision and pathfinding data?
What is the process of creating geometry data to assist on NPCs movements and such on a 3D world to avoiding having them from going through the ground, etc? Are there specific modelling programs that can create the world and the collision geometry to be used?

The map I made has caves, lakes with deep water, varying terrains heights, mountains, etc.

# Answer
Check out recast: http://code.google.com/p/recastnavigation/

It has a lot of good starting points. You'd have to extend it for how you want things like water to be treated, but it's probably the closest thing to a free out of the box solution out there that I know of.
> 5 votes

---
Tags: tools, ai, path-finding, level-design
---


# Question
Title: How can I distribute a native executable for a Python program?
Lately all of my work has been in Python (and Ruby), and I'm in love with those two languages. There are many libraries for game development on Python but the problem I see is that many of those frameworks don't cover the "distribution" aspect of game creation. I'd like to code my game on Python (and any other pure Python extra libraries I need) and be able to distribute an executable for the main PC platforms (Windows, Mac and Linux).

Any options out there or what are the best combinations for this? (maybe pyglet + cx\_freeze)

# Answer
Some Options for Python:

* Multiplatform (Win/Linux/Mac): PyInstaller
* Multiplatform (Win/Linux/Max): cx-freeze
* Windows: py2exe
* Mac: py2app

The bad news is that, as far as I can tell, you can't create binaries for a platform from another platform. The reason seems to be dependencies on platform-specific libraries.

**Edit**: By the way, you might be interested in looking at this comparison table. The guy was using pyglet too.
> 12 votes

# Answer
py2exe + NSIS works well enough, though it can take some voodoo to figure out the right py2exe config usually (but you only have to do that once). You can also look at setuptools' entry-point-based script generation and the pkg\_resources API for working with data files.
> 4 votes

---
Tags: python, pyglet
---


title: Tile sizes in 2D games

text:
# Question
Title: Tile sizes in 2D games
While developing a small game using tile-mapping method a question came to my mind:

I would develop the game on Windows but wouldn't exclude adapting it to another platform.

What size(in pixels) would you recommend using for creating the tiles of a tile-mapped game(ie: RPG) with the following requirements?

* Have an acceptable level of detail without having too many tiles.
* Having a decent map size.
* Allow adaptation of the game on a handheld(ie: PSP), smartphone or a computer without too much loss of detail or slowdowns.
* Allow more or less important zoom-in / zoom-out.
* Have a resolution of tile that permits either pixel-perfect collision or block-collision.

Anything from a good explanation to a game example is useful as long as it can fit the requirements.

This question may seem a bit simplistic, but I noticed that many Indies game developer were using inappropriate scales scenery.

*Also sorry for the poor syntax and the lack of vocabulary of my question, being a non-native English speaker doesn't help when talking about computers programming.*

# Answer
> 25 votes
You can calculate the tile size based on the screen resolution and the number of tiles that need to be visible. If you were putting up a chess board (8x8 tiles) on a 768 pixel tall screen, your tiles can't be more than 768/8 or 96 pixels, otherwise they won't all fit on the screen. How many tiles need to be visible is of course dependent on your game design.

So decide how many tiles a player should see at once, decide on the screen resolution, and calculate from there.

That said, I like 64x64 ;^)

---

I wanted to go back and edit this old answer to add a link to a nice post with tile making guidelines. It could be of use to anyone looking at tile size and tile design in general:

Liberated Pixel Cup styleguide

---
Tags: 2d, tiles
---


# Question
Title: Can you recommend a 2D game engine compatible with Windows Phone?
I'm curious what people are using to develop games for the Windows Phone (or XNA in general). I have come across a few engines but for the most part they don't seem to be actively maintained. If you are using an engine which you think does the job well please recommend it below.

# Answer
> 3 votes
FlatRedBall is an actively maintained XNA-based (MDX version still exists but isn't maintained I think) 2.5D engine that supports Windows Phone 7 as well as XNA PC and XNA Xbox 360 (and it's also simple to integrate with Farseer).

# Answer
> 3 votes
I kind of agree with coderanger. For all those specific examples you gave him, microsoft provides samples on their site. Full working state management, collision detection, animation. I know you want something put together but since you haven't received an answer you like, you could always take the game state project http://create.msdn.com/en-US/education/catalog/sample/game\_state\_management and pull some of the other samples together. All the code works fine. Again if someone provides you with an answer you like then ignore but it really won't take long to do what I am suggesting.

# Answer
> 1 votes
I've asked similar question on App Hub.

The answer was that there is only limited number of possible solutions, like Helium (helium.codeplex.com/) or Farseer Physics Engine ( farseerphysics.codeplex.com/) But, yes, they are not advanced enough yet.

Torque engine (torquepowered.com/) is coming somewhere in the future.

# Answer
> 0 votes
You might try Jemgine, it doesn't technically run on WP7 but only because of a few simple shaders that could be replaced with BasicEffect.

---
Tags: xna, windows-phone-7
---


title: Algo for narrowing cavern

text:
# Question
Title: Algo for narrowing cavern
I'm in a bit of crunch time and I find myself spending way too much time tinkering with an algo, so I would like some help.

In the game I am working on, there are some old-style, pixelated minigames. One of the minigame is a spaceship in a cavern. The caverns curves and narrows down over time until the ship crashes in a wall. I want them to be generated at random during runtime.

I'm having a problem creating the walls of the cavern and narrowing them while keeping a smooth curve on them.

For the narrowing, I keep track of it with a variable that decreases over time, but how about the curving and how to keep it natural? I've though of a keeping a target point that goes up and down randomly and have the wall try to reach for it, therefore smoothing the randomized number but it is not working great.

Any ideas/algo?

# Answer
> 8 votes
You're on the right track, add noise (perlin or otherwise..) to the floor and ceiling to make it look 'natural' and jagged. Then you could use 1D Brownian motion, as you suggested actually, as a target point, and draw the opening around that point.

Generate the level one slice at a time, and simply move that slice toward the player. If it goes up and down too fast (the target value, that is), you can try and smooth it using a sliding window, the simplest being simply averaging with the previous target value like so

```
window = 0.8;
targetY = next_brownian_value() * (1-window) + targetY * window;

```

Which will create an exponential sliding window (in this case, the targetY will be one fifth the new random value, 4/25ths of the previous random value, 16/125ths of the one before that, etc). Try playing with the window size and see what happens, higher value gives more smoothing (higher influence of previous values).

Note that the `next_brownian_value` should not be influenced by the targetY, it should go on its usual drunken walk.

**EDIT**
Naming the weighting factor 'window' was a slight misnomer, as a larger window should have a more smoothing effect. I've reversed the meaning above to make it more intuitive. It's still not really a window 'size' in a theoretical sense (which is usually defined to where the contribution is 1/e for exponential stuff..), but it least it's the right way around now..

# Answer
> 3 votes
You could use one-dimensional Perlin noise to generate the floor and ceiling, and weight the values so they get closer together towards the right side of the level.

---
Tags: algorithm, procedural-generation
---


# Question
Title: Getting a black scene with XNA, what am I doing wrong?
I'm new to XNA (ver 4) and I'm obviously doing something wrong but I don't know what.

So far I have managed to model my scene (quite simple, just a bunch of squares which are calculated--there are no models involved) correctly except for a big problem with the light. I'm using a BasicEffect to render things, as I lower the transparency level the scene also gets darker until it goes totally black when the transparency is zero. There's nothing black in the scene other than the background fill color (which doesn't show anywhere, anyway.)

Setting various depths of the zbuffer when clearing the screen has no effect on the result.

Each vertex has a color value that is being calculated and appears to be being displayed properly, I haven't tried to do anything with textures yet. All the polygons should be completely opaque.

Edit again: Fusspawn solved half my problem--my understanding of alpha was backwards. That still doesn't explain why I can see through things even when alpha is at 1.0, though.

Edit: I didn't add the code before because I think this is some misunderstanding of how things work rather than a simple bug. This code generates all the triangles where they are supposed to be, the only problem is lighting.

(Note: I've replaced the recursive hunt with a breadth-first one to get the cutoff distance right. No change to the vision problem.)

```
        private void PushBox(int x, int y, int z, int Distance)
    {
        if (World.MapData[x, y, z].Contents.Impassible()) return;
        if (World.MapData[x, y, z].Scanned) return;
        if (Distance >= MaxDistance) return;
        World.MapData[x, y, z].Scanned = true;
        // Left
        if (World.MapData[x + 1, y, z].Contents.Impassible())
            Walls.Square(Vertex(x + 1, y, z, WallColor), Vertex(x + 1, y + 1, z, WallColor), Vertex(x + 1, y + 1, z + 1, WallColor), Vertex(x + 1, y, z + 1, WallColor));
        else
            PushBox(x + 1, y, z, Distance + 1);
        // Right
        if (World.MapData[x - 1, y, z].Contents.Impassible())
            Walls.Square(Vertex(x, y, z, WallColor), Vertex(x, y, z + 1, WallColor), Vertex(x, y + 1, z + 1, WallColor), Vertex(x, y + 1, z, WallColor));
        else
            PushBox(x - 1, y, z, Distance + 1);
        // Behind
        if (World.MapData[x, y - 1, z].Contents.Impassible())
            //Distance = Distance;
This square is generated wrong (no such square was visible so I didn't catch it), it's now fixed.  It isn't the problem.
            Walls.Square(Vertex(x, y, z, WallColor), Vertex(x, y, z + 1, WallColor), Vertex(x + 1, y, z + 1, WallColor), Vertex(x + 1, y, z, WallColor));
        else
            PushBox(x, y - 1, z, Distance + 1);
        // Front
        if (World.MapData[x, y + 1, z].Contents.Impassible())
            Walls.Square(Vertex(x, y + 1, z, WallColor), Vertex(x, y + 1, z + 1, WallColor), Vertex(x + 1, y + 1, z + 1, WallColor), Vertex(x + 1, y + 1, z, WallColor));
        else
            PushBox(x, y + 1, z, Distance + 1);
        if (World.MapData[x, y, z - 1].Contents.Impassible())
            Ceiling.Square(Vertex(x, y, z, CeilingColor), Vertex(x, y + 1, z, CeilingColor), Vertex(x + 1, y + 1, z, CeilingColor), Vertex(x + 1, y, z, CeilingColor));
        else
            PushBox(x, y, z - 1, Distance + 1);
        if (World.MapData[x, y, z + 1].Contents.Impassible())
            Floor.Square(Vertex(x, y, z + 1, FloorColor), Vertex(x + 1, y, z + 1, FloorColor), Vertex(x + 1, y + 1, z + 1, FloorColor), Vertex(x, y + 1, z + 1, FloorColor));
        else
            PushBox(x, y, z + 1, Distance + 1);
    }

    private VertexPositionColor Vertex(int x, int y, int z, Color Base)
    {
        float Distance = Math.Abs(State.xLocation - x) + Math.Abs(State.yLocation - y) + Math.Abs(State.zLocation - z);
        float Scale = Math.Max((MaxDistance - Distance) / MaxDistance, 0);
        Color ThisColor = Color.Multiply(Base, Scale);
        //ThisColor = Color.White;
        return new VertexPositionColor(new Vector3(x, y, z), ThisColor);
    }

```

and the main draw routine:

```
        protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.Black, MaxDepth, 0);

        // TODO: Add your drawing code here

        spriteBatch.Begin();
        DrawStatusMessages();
        DrawDungeon();
        spriteBatch.End();
        base.Draw(gameTime);
    }

```

# Answer
I might be missing something simple here. But shouldn't this be exactly what should happen?

For instance.

if i have a black piece of paper, and apply a completely transparent piece of paper on top of it. All I'm going to do is see through the transparency to the black?

Have you tried just rendering any old texture in the background first, and seeing if the screen turns to whatever colour the background texture is when turned transparent?
> 4 votes

# Answer
Sounds like it could be depth testing. Try this:

```
DepthStencilState depthStencilState = new DepthStencilState();
depthStencilState.DepthBufferEnable = true;

device.DepthStencilState = depthStencilState;

```

I'm no expert but when the depth buffer isn't enabled then faces at the back can show through to the front. Try this code out and see if it works, if it does then just google 'xna 4 depth testing' or similar and read up on it.
> 0 votes

---
Tags: xna, xna-4.0, lighting
---


# Question
Title: How to decide the budget as independent game developer?
I'm currently try to make a business plan and was just wondering, how you guys decide the budget for outsourcing tasks. Is there a kind of a reference point? Or does the client decide this mostly by himself, what he want for his work? I speaking specially about tasks like:

* translation (en-\>xxx)
* character artwork
* tiles/background artwork
* sprites
* music (BGM/SE)
* voice synchronization

Naturally it depends **really** a lot about content size and requirements - but have any here a generally idea about the neccessary budget for tasks like this? Any link or ressource to this topic would be highly appreciated. Thank you guys,

Edit: Already thank you, for the great answers! Specially I mean also things like: How do you compromise with graphics artists and what kind of "contract" do you use. In which frame I can imagine the payment for i.e. a drawn character artwork or a standard sprite sheet with a few animations? Any experiences? I haven't really an idea, what to offer an artist for such tasks...

# Answer
I think it depends on how much money you have available. A simple 'indie' scenario:

Let's say you have a 10k budget for your game, and you plan to work on it for two months. Take out 4k to live on (you'll need to eat, really). That leaves your 6k.

You'll want some 'slack' in your budget for unforseen stuff, reserve 1k: 5k remaining.

What other things do you need to pay out of your budget?

Hosting? 0.5K Ads/PR? 1k, etc.

That leaves you with 3.5k to distribute around the items you named. Distribute them according to 'workload'. E.g. making one animated model takes approx. 15 times more work/time/money than creating a 2d tiles/sprite.

Edit: setting your budget is setting a limitation. This will force you to find creative solutions to stay within your budget. (I mean, you're not Blizzard, are you?)
> 8 votes

# Answer
Or you could always make a small team (if you find some new grads, or people just wanting to use their skills) you can divide the profits up in a fair way. 50% for programmer, 30% for artist, 20% for audio. But this depends on the content of the game.
Then your budget would mainly be for tools, hosting/blogging, advertising, snacks (the better the snack, the better the game)
> 5 votes

---
Tags: outsourcing
---


# Question
Title: Can you sync screen update on vertical retrace with OpenGL?
In OpenGL, is there a way to ensure I get exactly, *no more nor less*, **60** (or whatever rate my monitor is set for) frames per second?

Of course given that the new frame can be calculated in less than 1/60 second. I was thinking Windows more than Linux or Mac OSX, even though it is interesting to keep an eye on portability.

# Answer
I think you need to go platform specific for this, SDL's SDL\_GL\_SwapBuffers (i think it's called) will wait for retrace before swapping. If you specify your platform, there might be more we can help you with.

HTH.

A quick google turned up this: http://osdl.sourceforge.net/main/documentation/rendering/SDL-openGL.html, search the page for 'retrace' and you'll see it.
> 2 votes

# Answer
Synchronizing with the vertical retrace is not only platform dependent, but vendor-dependent and therfore not covered by the OpenGL-Specification.

Additional information can be found here: https://stackoverflow.com/questions/589064/how-to-enable-vertical-sync-in-opengl
> 2 votes

# Answer
What you want is called VSYNC. And for your question:

> no more nor less, 60

This is imposible, if you are talking about no less. It is depended on how much your app cuts gpu's performance.

No more is not that easy in OpenGL (compared to directx). Opengl doesnt support vsync in its basics, but the extension for VSYNC exists. Problem is that works only on windows.

Best resource for start studying is stack overflow and this QA: https://stackoverflow.com/questions/589064/how-to-enable-vertical-sync-in-opengl
> 1 votes

---
Tags: opengl, graphics-programming
---


title: interpolating frames in a vertex shader

text:
# Question
Title: interpolating frames in a vertex shader
My models are stored as a set of meshes, each with a vertex list and normal list per key-frame, and indices for GL\_TRIANGLES which is shared for all frames. Each frame I `lerp` between two adjacent key-frames to generate the vertices for that frame on the CPU and then draw it.

How can I move this into a GLSL vertex shader? Can a shader interpolate between two sets of vertices, and how can I store those vertices on the GPU?

# Answer
> 5 votes
This could be easy. You can send another informations then X,Y,Z position with your vertex. If you are not using one of color, normal or texture coord, you can use them for adding there your second vertex list XYZ. It is very common to use texture coords etc. to something different than what its name says. (dont forget to comment it to dont get confused another programmers...)

On vertex shader you can use mix function. It does linear interpolation between two values (or vectors) based on third value between 0-1. `mix(vec1,vec2,mixValue)`.

If you dont have any free space in your vertex desc, use mutlitexturing coords. And if you dont have this either - or you dont want to use this. Make your second vertex list array of floats, send it to the gpu and use `gl_InstanceID` for addresing in this array. It is vertex id... or index if you want.

# Answer
> 0 votes
In the vertex shader, you can use Texture too. This is the "VTF" tricks. This is used in GPU Particle engine.

Look this document: Nvidia VTF Introduction

---
Tags: opengl, glsl
---


title: Mega Man-style screen scrolling design

text:
# Question
Title: Mega Man-style screen scrolling design
The NES classic Mega Man series uses a very specific scrolling technique that I'm having a hard time wrapping my head around implementing. Essentially, the level is divided into "screens" which are all the same size. Some of the screens *smoothly scroll* in to one another, creating the illusion of a wider fields of play. Some of the screens *stop the camera from scrolling* until the player has reached the edge of the screen, at which time a transition occurs and the next screen is shown. It is also possible for a single screen to have more than one transition, for example it has a ladder that goes up to one screen, but you could also walk forward to another screen.

How can these screen transitions be modeled?

* Screen 0 is the starting screen, where the player starts.
* Screen 0-3 is horizontally smooth-scrolling and appears to the player as one continuous field of play.
* Since there is a transition between Screen 3 and it's neighboring screens 4 and 5, the camera will not advance past the right or top edges of Screen 3 unless the player moves to that respective edge and "pushes" through to the next screen.
* Once the player moves to either of the transition edges, user input is momentarily disabled and the camera transitions into the new area, after which user input is restored.
* The blue screen (Screen 5) has disabled horizontal scrolling so that only vertical transitions are possible.
* The green screen (Screen 6) has a vertical transition back to Screen 5 but also allows horizontal smooth-scrolling into Screen 7.

**Edit**: Implementing the transitions in terms of rooms lead me to this:

The small notches with an arrow are the regions in which a transition can occur. Each region has a "direction" and lies *just* outside of the room's visible area. As soon as the player hits a region, a transition will be started.

# Answer
It sounds like what you need is the concept of *rooms* as opposed to *screens*. Screens 1-3 would be one room, e.g. Your rooms could then be of any size and shape, or even restricted to the size of multiples of a *screen*.

Your camera would follow the player through a given room, up until the player gets too close to the border (half a screen width). When the player moves across the border, and into another room, you perform the transition visualization.

Each room would have a set of access points, which are mapped to access points of another room--creating the transition points.
> 21 votes

# Answer
The concept of larger smooth scrolling areas being made up of screen-sized chunks is an artifact of severe resource limitations on classic consoles, where performance gains could be had by keeping data in chunks of specific sizes (such as one memory page). There is very little reason to use such a system in a modern game.
> -8 votes

---
Tags: 2d, camera, platformer
---


title: Architecture for Versioned Save Data

text:
# Question
Title: Architecture for Versioned Save Data
We're working on an iOS game that we plan on having several content updates for.

It's a story type game with lots of little flags when things have been accomplished and such. There is also an inventory system.

I'm looking for ideas on how to best design a game state save data system that will be resilient to a lot of updates and changes to the game.

# Answer
> 0 votes
Having never written something similar, grain of salt etc. However, writing for changing systems is what all agile programming should be about - so hopefully I'm not totally useless ;)

I think you'll want to take a full-team meeting and discuss what is known/likely to change over time? Where are your points of variation? This will give you focus on the right bits. E.g. if backgrounds will never change, don't worry about having a smart solution for that. Then adjust the solutions after *how* you see variation occuring.

Other than that, probably saving only as small and relevant a portion of information as possible will be the most resilient. If you save the state of every flag, you might shoot yourself in the foot when the number changes, where saving only set flags would allow new flags and removing obscure flags more easily. Either way I think just putting in safe-guards and checks early and *methodically* is a must (and possibly enough of a solution, depending on what you're doing).

# Answer
> 1 votes
I haven't personally used it. but I've heard good things about Google Protocol Buffers. And it looks like there is an Obj-C port.

---
Tags: architecture, data
---


# Question
Title: Can a user / a game developer get their credit back in dollars? If yes, at what cost?
You can find every information about how to give money to facebook, but when it comes to take it back…

If I give credits to a user, can he get it back in dollars?

If a user gives me credits, can I turn it into dollars?

If so, how much does it cost?

# Answer
> When you redeem Credits with us we will redeem them at the rate of $0.10 per Credit, less a service fee of $0.03 per credit redeemed. If we change the service fee or redemption rate, the redemption rate and service fee in effect at the time you accepted a Credit as consideration will apply to that Credit. We will give you 30 days notice on the Facebook Developer Wiki of changes to the redemption rate or service fee.

I do not believe that an end-user is able to redeem credits. If they were, then Facebook Games might constitute gambling and that would cause problems.

You can find the entire Facebook Credits Policy here. If you are interested in applying for the credits beta program, click here. http://developers.facebook.com/credits
> 4 votes

---
Tags: facebook
---


# Question
Title: Why do consoles have so little memory compared to classic computers?
I remember the Playstation having 2MB ram and 1MB graphic memory.

The Playstation 3 now has only 256MB ram and 256MB graphic memory, and I'm sure that the day the console was released, even laptop's "standard" capacity was at least 1GB.

So why do they put so little memory in their machines, while developers would benefit a lot by having more ? Or is the memory that much faster than desktops and thus more expensive ? Or is it not that much worth it for developers ? What are the Sony/XBox/Nintendo engineers thinking that seems to be the same reason ?

# Answer
> 9 votes
As @AttackingHobo said, the memory is very fast and expensive. Also, you must take into account that these consoles launched years ago, when memory and hardware prices were higher.

Another factor that goes into making consoles very performant on what appears to be very limited resources, is that since every console is identical, we as developers can take advantage of platform specific optimizations. On a PC you can't do that as much, and thus you are required to have a beefer PC so it can brute-force its way through a similar unoptimized task.

That isn't to say there is no optimization in PC games, but it is in different areas than consoles, and in general due to the wide range of supported hardware, it is less effective.

# Answer
> 5 votes
Obviously they want them to be cheap to make. As for the PS3 specifically, memory prices were very high at it's release, but they dropped soon after.

There ain't a big clunky operating system running alongside games, so unlike Windows developers can actually utilize all the memory, you easily have more "room" on a PS3 than on an XP machine with 512 MB of system memory. Knowing the exact hardware specifications means that it is easier to go to the limit.

Most memory eating PC games can to some extend be attributed to lazy programmers, there really ain't a lot one can do with more memory, except not care as much about filling it up.

While the console memory is generally fast I doubt that it is a lot more expensive, it is to a great extent the development of the technology that cost, the production itself is probably not a lot more expensive. So when Sony and Microsoft make or purchase a big pile of fast memory it doesn't get a lot more expensive than slower memory would have been.

It all comes down to the added consumer value being deemed too small to justify the extra price.

# Answer
> 3 votes
The memory in the 360 and the ps3 is very fast, and expensive.

**If the amount of memory was higher on console launch, they either would have to raise the price or take an even larger loss per console sold.**

# Answer
> 3 votes
In addition to what others have pointed out here, I'd like to say that the consoles have very little overhead when it comes to memory (XBox 360 only reserves ~32 MB of RAM for system use, the rest of the 512 MB is for the game). Once you figure out what is already used by the OS and background apps on the majority of consumer PCs, you will realize there isn't too much spare RAM available.

Luckily modern OS's have paging systems for their RAM so we generally don't need to worry about memory usage, but even on a PC game it would be a good idea to stick to a limit of 256 to 512 MB of memory so you don't start thrashing the paged memory and ruin game performance.

# Answer
> 2 votes
Size isnt everything ;)

No seriously it isnt, memory speed is a key performance realted stat that alot of people overlook. 256meg of Fast memory is preferable over larger space slower spead memory.

Cost is also an issue, I believe both XBox 360 and Playstation 3 were/are sold at a loss

---
Tags: console
---


title: Game engine for turn based wargame

text:
# Question
Title: Game engine for turn based wargame
I would like to ask for game engine recommendations for turn based wargame development. I would like my engine to support;

* hex maps
* agents on hex
* rule based ai for the agents
* terrain on hex
* cultural features on hex
* los analysis
* abstract agent templetes

# Answer
Check out Vassal \- it may do the trick for you. @AttackingHobo pointed it out to me a while back in a previous question.
> 2 votes

---
Tags: turn-based
---


title: game models that stand in grass

text:
# Question
Title: game models that stand in grass
The open source game Glest has models that feel detached from the ground that they sit on because of the hard edges. In real life, grass is not flat!

What are the options and recommendations for breaking up the hard edges where the meshes of the models meet the terrain? How do other games do it? What are the options on a sliding scale of rendering performance and widespread GPU support?

# Answer
> 5 votes
I downloaded and ran the game from http://www.glest.org, and the "feet not on the ground" issue comes from lack of shadows and other visual cues that help you get the perspective right.

In the screenshot you posted, shadows seem to be turned off. Turn them on to get a better effect. Even when using the shadows Glest provides, the shadows are pretty weak. But turning them on does help reduce the floating characters effect.

Take a look at the screenshot below I took from Glest. The models fail to visually blend into their terrain because the textures don't visually blend between object and ground, nor are there any shadows.

Now take a look at this picture. This is the same scene, but I did a quick photoshop job to add shadows and a few other changes by hand. The characters and some objects (I didn't do everything) have a dark shadow blob under them. The shadows aren't even real shadows (shaped like the object), but simply darker "blobs" at the object's base. They are also overly dark, but on purpose.

In addition to the shadow blobs, I darkened the bases of the objects (base of rocks, base of buildings, character feet) so that they better blend into the shadow "blob" under their feet.

So my advice is to add stronger shadows under objects, even if with blobs to fake a shadow. And also darken the textures of objects where they contact the ground. These are things a nice high end engine could take care of for you with the lighting model, but there are ways to still get the effect.

# Answer
> 9 votes
I think that the problem of objects which look like flying is realy not about hard edges but it is problem of **"absence of shadows"**.

For shadows google for "shadow mapping" or "shadow volumes".

If you really dont want hard edges. Use alpha transparency for vertices near ground (it could be easy). But then you have to sort objects which you are rendering in distance from camera. But it will not produce anything nice i think. In fact i'm pretty sure that there is no way how to get rid of hard edges in computer grapgics.

# Answer
> 3 votes
You can render grass. There are a couple of widespread techniques for this that I've seen; one uses lots of little billboards, placed in a clever fashion. The other works more like a static particle system, where each blade or bunch of grass is a particle. They end up generating much the same geometry, if I recall correctly.

---
Tags: opengl
---


# Question
Title: Is it easy to use Sun Burn engine for WP7 game development?
I was wondering if anyone has tried to develop a game using the SunBurn game engine for the **Windows Phone 7** platform.

How good is documentation, examples, etc? Is it easy in use and implementation?

Any feedback would be greatly welcome.

# Answer
> 2 votes
The SunBurn Game Engine has a free version called the SunBurn Framework:

http://www.synapsegaming.com/products/sunburn/framework/

It doesn't include the editor or deferred rendering, but it uses the same api and design as the game engine.

Also SunBurn uses the exact same code and assets for Windows, Xbox, and Windows Phone 7, so it's just as easy to develop on all three platforms.

-JohnK (SunBurn team member)

---
Tags: windows-phone-7, sunburn
---


title: Successful Elements to a 4X Game

text:
# Question
Title: Successful Elements to a 4X Game
4X games (That is, Xpand, Xplore, Xploit and Xterminate) like Civilization, Sins of a Solar Empire, and other top Strategy games, all seem to have the same addictive hook. I'd like to know what elements these developers incorporate into their games to make them:

* Well paced (You can't beat the game in 5 minutes, but it wont take a week)
* Replayable (The first game isn't your last)
* Competetive (The AI doesn't play like a 3 year old)
* Not repetetive (Such as using the same strategy over and over, or spamming units)
* Economical (Not having 7 trillion metal and coins after 10 minutes of play)
* Not to much micro-managing
* Exciting (Necessary?) combat
* You stil need to use *strategy*
* Intuitive interfaces (Civilization 5 is a good example)
* And any other important parts to the Strategy/4X genre

Some of these seem pretty simple, but others look like balancing acts, and I'd like to have some opinions on how to make a game that is **fun to play**. I'd be grateful if anyone could answer tell me how you or another game\developer has managed to successfully balance them together.

# Answer
> 7 votes
> Well paced (You can't beat the game in 5 minutes, but it wont take a week)

Not driven by a single game element, so much as the overall scope of the game. Arrived at mainly through playtesting, I think.

> Replayable (The first game isn't your last)

Mostly done through randomized starting positions and a variety of opponents that each have their own strategies / special abilities.

> Competetive (The AI doesn't play like a 3 year old)

Most 4X games I've seen do not actually achieve this. AI in a 4X game is a really hard problem; the solution for many games is to keep it as a "dumb" AI but give it numerical boosts (faster production/growth curve). My understanding is that AI is usually developed through trial-and-error and playtesting; start with a fairly simple AI, play until you see it do something really stupid, then figure out how to make it so it doesn't do that stupid thing anymore... and repeat. Not particularly interesting or glorious but it works.

> Not repetetive (Such as using the same strategy over and over, or spamming units)

Same as "replayable".

> Economical (Not having 7 trillion metal and coins after 10 minutes of play)

Same as "well paced".

> Not to much micro-managing

Also arrived at through playtesting. Earlier 4X games actually did have quite a bit of micro-managing, and in fact it could be argued that for SOME players who enjoy that level of control, this is desirable. To cut down on this, it's generally a matter of simplifying the mechanics and automating certain processes. (Note that simply giving the player an option of full hands-on or automating is not optimal; if the automation is just as good as micro-managing then there's no point to letting the player take control, but if it's significantly worse then you punish players for NOT micro-managing.)

> Exciting (Necessary?) combat

Unsure what this means. Most 4X games that I've seen (such as the Civilization series) automate combat almost entirely; you choose one unit or stack to move onto an opposing stack, a winner is determined behind the scenes, results are displayed. Entering a tactical or real-time combat map isn't something I've seen before in 4X, as it would likely ruin the pacing by making the overall game take too long.

> You stil need to use strategy

As opposed to what, following a single easy-to-find overly-powerful algorithm? Playtesting for game balance to prevent a single unit or tech or strategy or whatever from being overwhelmingly better than the others. Also, some "broken" strategies are really just exploiting weak AI, so the solution to that is to iterate on the AI a bit.

> Intuitive interfaces (Civilization 5 is a good example)

UI is a huge topic in general, but core principles of the field apply to 4X games just as they apply to anything else. Since you're talking about a niche genre to begin with, expect your players to be familiar with the major other games in the genre, and start with those games as the basis for your own UI. Obviously this depends on platform, too... 4X for PC is going to have a radically different interface than a similar game on console.

> And any other important parts to the Strategy/4X genre

IMHO, decent multiplayer is still an unsolved problem in the genre, due to the tendency for players to micromanage on their turn, thus making the game take forever. (An exception would be games such as the Advance Wars series, that are so insanely simplified and constrained that they can be played multiplayer in a reasonable period of time.)

---
Tags: game-design, game-mechanics, strategy, 4x
---


# Question
Title: Does anyone know where I can find wp7 indie game sales data?
I am curious about whether to develop an xna game for the windows phone 7. It would be nice to know how the games are doing on that platform sales wise.

Something like this would be very helpful: http://www.xboxist.com/xbox-360/games/xna-community-games-is-a-failed-experiment-010122.php

# Answer
> 3 votes
This shows some small and grim numbers: http://blogs.techrepublic.com.com/smartphones/?p=2005

> **Conclusion**
>
> My advice still stands for the time being: do not develop applications for Windows Phone 7 with the expectation that you will make big bucks.

# Answer
> 3 votes
There's a thread in the AppHub forums where people shares their trial/paid data: http://forums.create.msdn.com/forums/p/69061/421667.aspx

And yes, sales don't look very good for now... not even trials/free apps. It looks like as if not much people is paying attention to the existing apps in the market.

---
Tags: xna, windows-phone-7
---


# Question
Title: What are the usual tools for importing models and animations?
I'm a total noob with regard to game programming (though not a noob to programming) and I'm using pygame + opengl to do some experiments with a little game I've been thinking of.

I've been trying to import OBJ files into my pygame OpenGL "game", but there's apparently different formats of OBJ files, and writing a loader is a fairly nontrivial process. At least from my experience, which is not too large.

So I guess my question is: What do people generally use in the industry to read 3d model files? What about animation? Is there a place I can look into to understand?

Thanks, Marcelo.

# Answer
Reading your comment,Malvin, was better to post this as a new answer:

Malvin, OBJ is quite used for static models. But for character animations, you need to be able to transport bones information, and vertex weights (the value with which each vertex is influenced by several bones, or only one, or none). Also constraints info, in some cases. That all would be the "rigging" info, basically. Then there's animation info needed, like keyframes (frames where some change happens), interpolation type between them, etc, etc. All these is not supported by OBJ. A good, lightweight and practical format for this is \*.md5 , but is probably more recommended Collada, which is becoming a very adopted standard and that can port everything, from statics, scenery, to character animation. It is supported by the big ones: Maya, Max, XSI. Blender is supporting it but not yet fully. The collada issue is that is complex to make yourself a loader, as is a very complete format, and for this reason, several packages don't have a fully functional exporter for this. Still, might be the way to go.

You can of course dump OBJ frames from an animation package, and then interpolate in the engine, as exporting one obj per frame would be too much heavy and costs memory. Maybe one every 2 or 4 frames...

You can also use FBX for character animations, but my advice would be using collada instead of it.

First of all, check if your artists are going to be able to export in whatever the format, from their package. Otherwise is a hard to solve problem. Indeed, make complete tests of features ported and and confirm is working in your engine.

About what people is doing, in my experience, all of this... But in game companies, often just they do a converter from whatever format to a custom, native, binary format for their engine. Optimized and faster to load, etc.

I have done prototypes or even games just using OBJ or ASE and md5 for animations..Depends on artists workflows, toolset, etc.

Edit: Sorry, seems Fuzzy had already answered several matters. Agreeing there.
> 2 votes

# Answer
You should use existing options that someone else has already fought.

1) http://assimp.sourceforge.net/ Open Asset Import Library supports a huge amount of formats.

2) http://openctm.sourceforge.net/ A very nice LZMA based mesh compression system with SDK's.

Also, "industry" usually use what they have in their toolset. Collada is common, FBX is common, Proprietary formats even more so. Some studios use .MAX directly, maya scenes directly. Alot of studios also go for transport formats (see opaque data, and such) where the animation software is extended via tools and plugins to feature the game ready tools, instead of working backwards from a mesh format.

For example, Naughty Dog use Maya exclusively as their main 3d content tool See this link : http://usa.autodesk.com/adsk/servlet/item?linkID=10225710&id=7670571&siteID=123112
> 4 votes

# Answer
Writing a loader for OBJ models shouldn't be too hard. Its one of the simpler model formats out there. You only have to use what you need and if you are making your own models you can tailor what is exported to only what you need.

I believe there is only one OBJ format, but each file can have parts omitted depending on what the model requires. One model might not use texture coordinates, so they would be missing in the file for example.

Basically your loader would look something like this:

```
for all lines in file
 Read next non empty line
  Get first token
   if token is #, skip line
   else if token is v, make a vertex
   else if token is vn, make a normal
   else if token is vt, make a texture vertex
   else if token is f, make a face

```

You would store a list of vertices, normals, texture vertices, and faces. Each face would store indices into the other lists.

Most simple models would not have more than that, even though the OBJ format can handle curves and other non polygonal data. I would bet you don't want to handle any thing else either.

http://www.royriggs.com/obj.html is a good page to look at specifically for OBJ files.

What model format is used in a project depends on the engine used. For example, if you use Unreal, they have a model converter that converts model files from a 3d modeler into the unreal format. If you use a custom engine, you would probably have written your own model format, or at least your own model reader.
> 1 votes

---
Tags: 3d, models, pygame
---


# Question
Title: Is it possible to make calculations in a Quake 3/Live hud?
I would like to add a new field to a Quake 3/Quake Live HUD that shows the following number:

```
min(health + armour, health * 3) * (1.5 if guard_rune else 1)

```

This is the amount of damage you can take before getting killed, btw.

Is this even possible?

# Answer
No, as far as I know, it's not. People have tried this without success.
> 2 votes

---
Tags: 2d, gui
---


title: Match Making Groups of Players

text:
# Question
Title: Match Making Groups of Players
Given a situation where I have a pool of `X` people of different scores (ranks) `S` with game size `N`. How do I partition the pool into `N` sized games where the standard deviation of ranks for each games is minimized?

(quality of the game is inversely proportional to STD of ranks)

# Answer
If your values for X and N are very large, it would probably make the most sence to keep the player list sorted by `Rank` such that you could always take the bottom `N` elements to create a group. This will front-load your computation time (keeping the list sorted every time you add a new item), in contrast with the above algorithm which would require execution every time a new group is to be created.
> 1 votes

# Answer
This is probably not mathematically optimal (optimality in this case reeks of NP to me, but I'm not certain), but assuming N is fixed and a unimodal, approximately normal S distribution you should be able to get something close to optimal just sorting by rank and slicing a group off every N players.
> 1 votes

---
Tags: ranking, tournament, matchmaking
---


# Question
Title: SNES Bung Game Doctor, add RAM retention modification (battery backup)
Firstly I'd like to say that this doesn't seem like the right "forum" for this question as it actually doesn't relate directly to the development of games.

As this is my first post on 'game development', I cannot include more links - sorry.

**I recently obtained a Game Doctor SF7** ("Professor SF2" in the US I believe) backup unit for the Super Nintendo, **and I'd like to add battery backup** to it.

**Quick background**

This first model (SF1) unit was designed by Bung Enterprises starting in 1994. It was placed on top of the SNES (interfacing with it via the standard cartridge slot) and allowed backup of SNES cartridges to floppy disk and PC(via a straight-through DB-25 M/M cable).

The unit can store the cartridge ROM, SRAM ("Save" RAM - used by many cartridges to store save games) as well as complete SNES RAM onto its own (expandable) RAM so that one can later dump this to floppy/PC, or to simply keep the games retained in memory for quick recall during development/gaming.

More interestingly, it can *download* ROM and SRAM data from a PC on most *modern* platforms thanks to the ucon64 project; this is of course of great interest if you want to actually do some SNES development on real hardware (which I do)!

**Dilemma**

The main kink is that the unit does not have any battery backup - if you cut power to the unit, RAM is lost. This wouldn't have been much of a bother in '94 when floppy disks were the bees knees, but nowadays it's very frustrating!

**Idea**

The idea is to add battery backup functionality to the unit. I've tried to find people who have made similar (or *any!*) modifications to the unit, Unfortunately as the machine is very old (and has more modern, "non-programming" everyday alternatives) it's very hard to find any information at all - most of the websites I've found which *do* have some information have been on archive.org!

**Finding information**

There are a number of reasons for it being exceptionally frustrating to find information about the unit. Firstly, Nintendo(and others) basically forced Bung out of business about ten years ago, so none of the original sites exist. Secondly, the unit series has different names in the US as compared to Japan - it's called the **game doctor sf7** in Japan, and **professor SF2** in the US. Thirdly, the majority of the userbase used the unit for the sole purpose of "game backups" and not development/hardware mods.

**So,** Has anyone performed such a feat before, got information about it, or simply the hardware know-how to get me on the right track? Am I perhaps thinking this might be easy when it might actually be quite hard (difficulty in retaining power to the RAM versus the entire unit, unforeseen issues, etc)?

Thanks for taking the time!

# Answer
> 1 votes
Just because your question doesn't really belong here, doesn't mean I won't try to give you an answer! :)

If you are set on hacking this thing and adding a battery, that's fine. But might I suggest obtaining an alternative instead? The everything2 post on SNES Backup Units lists several others, some of which do retain their memory through a poweroff:

> Ahh yes. The Super Nintendo Backup Systems... Anybody remember the Pro Fighter? Multi Game Hunter? Game Doctor SF? Or the ever popular Super Wild Card DX?

Or you could always take a spare computer and run an emulator (ZSNES or Snes9x) on it, and then get a USB SNES controller or a USB SNES controller *adapter* (plugs into USB and has 2 plugs for any SNES controllers).

If you have a Game Boy or Nintendo DS, there are a number of homebrew cartridges that will play SNES games as well. I have been extremely pleased with my recent purchase of a DSTWO as recommended by Lifehacker, and the Nintendo DS gamepad layout is extremely similar to that of the SNES so it hardly takes away from the feel of playing the games.

Remember of course that it's only legal to play ROMs of games that you own.

---

**Edit:** Ah, my apologies, I missed one of the key parts of your question when I first read it:

> this is of course of great interest if you want to actually do some SNES development on real hardware (which I do)!

Hopefully, then, the first part of my answer might at least help lead you to better alternates to the Game Doctor.

# Answer
> 0 votes
From the HW point of view, you need to take lithium battery, and connect it to power in this module through a diode. This diode will protect the battery while AC power is on, and will provice power to retain state in standby. If you are lucky it would be that simple.

Be careful with - and + as wrong polarity might explode the battery.

---
Tags: hardware, modding, nintendo
---