title: Texture packing algorithm

text:
# Question
Title: Texture packing algorithm
What is a good texture packing algorithm? Technically, bin packing is NP-hard, so a heuristic is what I'm really after.

# Answer
> 71 votes
I spent a few months at one job coming up with a better texture packing algorithm.

The algorithm we started with was simple. Collect all the input items. Sort them by total pixels consumed, large-to-small. Lay them out in your texture in scanline order, just testing stuff from the topleft pixel to the topright pixel, moving down a line, and repeating, resetting to the topleft pixel after every successful placement.

You either need to hardcode a width or come up with another heuristic for this. In an attempt to preserve squareness, our algorithm would start at 128, then increase by 128s until it came up with a result that wasn't any deeper than it was wide.

So, we had that algorithm, and I decided to improve it. I tried a bunch of wacky heuristics - trying to find objects that fit together, doing some weighting over a bunch of desired space packing properties, rotating and flipping. After all my work, quite literally three months of work, I ended up saving 3% space.

Yeah. 3%.

And after we ran our compression routine over it, it actually ended up *larger* (which I still can't explain) so we threw the entire thing out and went back to the old algorithm.

Sort items, jam into texture in scanline order. There's your algorithm. It's easy to code, fast to run, and you won't get much better without an amazing amount of work. That work just isn't worthwhile unless your company is at *least* 50 people large, and probably more.

And as a side note, I just implemented this algorithm (fixed width 512 pixels) for quite literally the exact same application that you're doing (no ftgles, but opengl-rendered freetype glyphs.) Here's the result. It looks blurry because mine is using Valve's distance-field based text rendering algorithm, which also accounts for the extra space between glyphs. Obviously, there's not a lot of empty space left over, and it does a good job of cramming things into open spots.

All the code for this is BSD-licensed and available at github.

# Answer
> 27 votes
The PhD Thesis of Andrea Lodi is entitled *Algorithms for Two Dimensional Bin Packing and Assignment Problems*.
The thesis goes over some of the harder forms of this problems. Luckily, texture packing is the easiest version. The best algorithm he found was called *Touching Perimeter*.

To quote from page 52:

> The algorithm, called Touching Perimeter (TPRF ), starts by sorting the items according to nonincreasing area (breaking ties by nonincreasing min{wj , hj } values), and by horizontally orienting them. A lower bound L on the optimal solution value is then computed, and L empty bins are initialized. (The continuous lower bound L0 deﬁned in the previous section is obviously valid for 2BP|R|F as well; better bounds are proposed by Dell’Amico, Martello and Vigo \[56\].) The algorithm packs one item at a time, either in an existing bin, or by initializing a new one. The ﬁrst item packed in a bin is always placed in the bottom-left corner. Each subsequent item is packed in a so-called normal position (see Christoﬁdes and Whitlock \[41\]), i.e., with its bottom edge touching either the bottom of the bin or the top edge of another item, and with its left edge touching either the left edge of the bin or the right edge of another item.
> The choice of the bin and of the packing position is done by evaluating a score, deﬁned as the percentage of the item perimeter which touches the bin and other items already packed. This strategy favours patterns where the packed items do not “trap” small areas, which may be hard to use for further placements. For each candidate packing position, the score is evaluated twice, for the two item orientations (if both are feasible), and the highest value is selected. Score ties are broken by choosing the bin having the maximum packed area. The overall algorithm is as follows.
>
> ```
> touching_perimeter:
>   sort the items by nonincreaseing w,h values, and horizontally orient them;
>   comment: Phase 1;
>   compute a lower bound L on the optimal solution value, and open L empty bins;
>   comment: Phase 2;
>   for j := 1 to n do
>      score := 0;
>      for each normal packing position in an open bin do
>         let score1 and score2 be scores with tow orientations;
>         score := max{score,score1,score2};
>      end for;
>      if score > 0 then
>         pack item j in the bin, position and orientation corresponding to score;
>      else
>         open a new bin and horizontally pack item j into i;
>      end if;
>   end for;
> end;
>
> ```

Also of interest, the paper describes an algorithm to determine the size of an optimally packed texture map. That would be useful to determine if it's even possible to fit all the textures in one 1024x1024 atlas.

# Answer
> 22 votes
If anyone is still interested, I have completely rewritten the rectpack2D library so that it is way more efficient.

It works by keeping a `std::vector` of empty spaces in the atlas, beginning with some initial maximum size (typically, the maximum allowed texture size on a particular GPU), splitting the first viable empty space and saving the splits back to the vector.

The performance breakthrough came with just using a vector, instead of keeping an entire tree, like it was previously done.

The procedure is described in detail in the README.

The library is under MIT, so I'm happy for you if you find it useful!

## Example results:

Tests were conducted on a Intel(R) Core(TM) i7-4770K CPU @ 3.50GHz. The binary was built with clang 6.0.0, using an -03 switch.

### Arbitrary game sprites + Japanese glyphs: 3264 subjects in total.

**Runtime: 4 milliseconds**
**Wasted pixels: 15538 (0.31% - equivalent of a 125 x 125 square)**

Output (2116 x 2382):

In color:
(black is wasted space)

### Japanese glyphs + some GUI sprites: 3122 subjects.

**Runtime: 3.5 - 7 ms**
**Wasted pixels: 9288 (1.23% - equivalent of a 96 x 96 square)**

Output (866 x 871):

In color:
(black is wasted space)

# Answer
> 6 votes
A good heuristic algorithm can be found here. When I was trying something similar recently, I found this referenced as the basic starting point for most implementations I saw.

Works particularly well with either lots of regular shaped, similar sized items, or with a good mix of small and fewer larger images. The best advice to achieve good results is to remember to sort your input in terms of image size, then pack from largest to smallest as the smaller images will pack into the space around the larger images. How you do this sorting up to you and may depend on your goals. I used perimeter rather than area as a 1st order approximation since I took the view that tall+thin / short+wide images (which would have lowish area) are actually very hard to place later on in a pack, so by using perimeter you push these odd shapes towards the front of the order.

Here's a sample visulization of the output for my packer on a random set of images from my website image dump directory :).

The numbers in the squares are the id's of the containing blocks in the tree so give you an idea of the order of the insertions. The first is ID "3" because it is the first *leaf* node (only leaves contain images) and consequently has 2 parents).

```
        Root[0]
       /      \
   Child[1]  Child[2]
      |
    Leaf[3]

```

# Answer
> 4 votes
Personally, I just use a greedy largest-block-that-fits first system. It's not optimal, but it does the trick OK.

Note that, if you have a reasonable amount of texture blocks, you can exhaustively search the best ordering even if the problem itself is NP.

# Answer
> 3 votes
Something I've used, which works well even for irregular UV maps, is to turn the UV patch into a bitmap mask, and maintain a mask for the texture itself, searching for the first position the UV patch will fit into. I order the blocks according to some simple heuristic (height, width, size, whatever), and I allow rotations of the blocks to minimise or maximise the chosen heuristic. That gives a manageable search-space for brute force.

If you can then iterate that trying several heuristics, and/or apply a random factor in choosing the ordering and iterate until some time limit runs out.

With this scheme you'll get small UV islands packed into the gaps made by large ones, and even in holes left within single UV patches themselves.

# Answer
> 2 votes
It's pretty easy to pack fonts because all (or the great majority) of the glyph textures are nearly the same size. Do the simplest thing that occurs to you and it will be very close to optimal.

Cleverness becomes more important when you're packing images of very different sizes. Then you want to be able to pack into gaps, etc. Even then, though, a simple algorithm like the scanline order search discussed earlier will produce very reasonable results.

None of the advanced algos are magic. They won't be 50% more effecient than a simpel algo, and you won't get consistent benefits from them unless you have a staggering number of texture sheets. that's because the small improvements that better algorithms make will only be seen in aggregate.

Go simple, and move on to something where your efforts will be better rewarded

# Answer
> 1 votes
We recently released a python script which will pack textures into multiple image files of a given size.

Quoted from our blog:

"While there are numerous packers that can be found online, our difficulty was in finding any that could handle large numbers of images in multiple directories. Thus, our own atlas packer was born!

As is, our little script will start in the base directory and load all the .PNGs into an atlas. If that atlas is filled, it creates a new one. Then, it will try fitting the rest of the images in all previous atlases before finding a spot in the new one. That way, each atlas is packed as tight as possible. Atlases are named based on the folder that their images are from.

You can change the size of the atlas (line 65), format of the images you want to pack (line 67), the load directory (line 10) and the save directory (line 13) fairly easily with no experience in Python. As a small disclaimer, this was whipped together in a few days to work specifically with our engine. I encourage you to request features, comment with your own variations, and report any errors, but any changes to the script will happen in my free time."

Feel free to check out the full source code here: http://www.retroaffect.com/blog/159/Image\_Atlas\_Packer/#b

# Answer
> 0 votes
If it's specifically for font textures, then you probably do something non-optimal but nice and simple:

Sort characters by height, tallest first

Start at 0,0 Place first character at current coords, advance X, place next one, repeat until we can't fit another

Reset X to 0, advance Y downwards by the height of the tallest character in the row, and fill another row

Repeat until we're out of characters, or can't fit another row.

---
Tags: algorithm, textures
---


# Question
Title: Recreating Doodle Jump in Canvas - Platforms spawning out of reach
I have started to recreate Doodle Jump in HTML using Canvas. Here's my current progress. As you can see, if you play it for a few seconds, some platforms will be out of the player's reach. I don't know why is this happening. Here's the code which is responsible for the re-spawning of platforms.

```
//Movement of player affected by gravity
if(player.y > (height / 2) - (player.height / 2)) {
    player.y += player.vy;
    player.vy += gravity;
}
else {
    for(var i = 0; i < platforms.length; i++) {
        var p = platforms[i];

        if(player.vy < 0) {
            p.y -= player.vy;
            player.vy += 0.08;
        }

        if(p.y > height) {
            position = 0;
            var h = p.y;
            platforms[i] = new Platform();
        }

        if(player.vy >= 0) {
            player.y += player.vy;
            player.vy += gravity;
        }
    }
}

```

Also, here's the platform class.

```
//Platform class
function Platform(y) {
    this.image = new Image();
    this.image.src = platformImg;

    this.width = 105;
    this.height = 25;

    this.x = Math.random() * (width - this.width);
    this.y = y || position;

    position += height / platformCount;

    //Function to draw it
    this.draw = function() {
        try {
            ctx.drawImage(this.image, this.x, this.y, this.width, this.height);
        } catch(e) {}
    };
}

```

You can also see the whole code on the link I provided. Also, when a platform goes out of the view port, the jump animation becomes quirky. I am still trying to find out what's causing this but can't find any solution.

# Answer
Do not allow platforms to spawn higher than a players max height from the previous platform.
> 1 votes

---
Tags: mathematics, software-engineering, javascript, animation, html-canvas
---


title: Dealing with new animations in html5

text:
# Question
Title: Dealing with new animations in html5
Wish I knew of a better title, but the issue is rather specific.

So the producer of the game I'm working on has given me new animations to put in the game. I knew there might be issues right off when the new animations are 45mb when the originals were 1.7mb. This is a html5 browser game by the way.

Now a bit of history. What I have the engine do is cut up the spritesheets at load time into frames of canvas. Basically caching the animations beforehand so there's not need for computation while the game is running. Then I release the references to the spritesheet to be cleared by using ref = undefined; so the memory holding the big unused spritesheet images can be reclaimed.

And back on the story. The new animations crash the web browser at resource loading time. I assume it's taking up too much memory, and too fast for the garbage collector to catch up. As the only change made to the game between it working and not working were the new larger animations, I take that to mean the new animations are the problem. You can't push a web browser too hard as it is and the game is approaching 180mb with these new animations.

I then proceed to tell the producer that these animations are too big and to either slim them down or go back to the old animations(which looked fine enough to me). He claims that he got them down to 2mb and that it was still crashing for him. That doesn't sit well to me since he won't give it to me to test. Anyways, his prediction is it's just the pixel count that's causing the problem not the size of the images, and the size of the images doesn't matter. This doesn't sit well with me either. I'm not an expert on images but I have an idea on how they work and I'm pretty sure that's not it.

His solution is to join them all together into one giant massive image and have an xml file explain where the animations start and end. I've seen this before, so that's not a problem. It's that the resource manager doesn't do this, and I'd have to spend days on making this feature when I'm pretty sure it's not going to make a difference. Because if it's just a pixel count problem(like he says it is) then having one massive image won't fix that. It's the same surface area for the animations, just all together.

If there's someone out there with more knowledge on how images work and has stuck it out through the my long story, here's where I get to my question. **Am I right in this issue that the problem is the size in mb of the images? Or, is the producer right that it's the amount of pixels and one giant spritesheet with all animations will fix our problem?** By the way, this isn't a full game. It's a tech demo, that's past its set release date already by a week. The full game we'll work on later. Now I don't really care who's right in the end, as long as I know what I have to do to fix this.

Thank you

# Answer
> 0 votes
Your info is a bit sketchy, I would like to know what resolution is that spritesheet? How many sprites does it contain? How is it compressed? How is the 2 MB version different?

Browsers tend to work in different ways internally, so I can't tell exactly what will happen, but I would assume that as you load an image into into a canvas it is going to be uncompressed, meaning that whatever compression was applied won't matter, it's the raw pixel count that is important. If all else fails you have to get the pixel count down.

During the process of cutting up the image you will hold two full copies of the data, thus doubling the problem.

As for not cutting up the sprite sheet, I'm worried what performance effect that will have.

If I were you I'd split the sprites into multiple smaller spritesheets and keep only two of them in memory at once (one downloading, one being cut). That should keep the overhead reasonable.

And 180 MB, that is a heavy hitter for a browser game, I assume that it is mostly images? Are you trying to keep it all in memory at once or do you have some loading/unloading strategy? You might want to experiment with some tiered caching strategy, I guess you can avoid the unpacked version of an image but still assure that it sits in browser cache by keeping it in a dummy \<img\> object that is not attached to the DOM.

# Answer
> 0 votes
What about some asynchronous loading of that animations or lower quality of pictures? I don't think, that the giant massive image can resolve your problem.

---
Tags: javascript, html5, image, memory-efficiency
---


# Question
Title: Does Macbook Air 2012 (Intel HD4000) support GLSL 1.3+?
I'm using SDL2 and GLEW on OSX Mountain Lion (2012 Macbook Air) to create an OpenGL context. Querying for the GLSL version, it reports GLSL version 1.2. I'm curious if this is a limitation of the HD4000 driver, the Macbook Air/OSX, or perhaps a limitation of SDL/GLEW?

# Answer
> 3 votes
According to this, the hardware supports OpenGL 4.0, but the Mac drivers/OSX only support 3.2. That should still get you GLSL 1.50 (you might not be able to get 1.30 or 1.40), but you need to use the core profile, as OSX doesn't support the compatibility profile. I think SDL defaults to the compatibility mode, so you probably need to explicitly request core profile context.

---
Tags: opengl, glsl, sdl, macos
---


# Question
Title: What was the typical toolchain for DOS game development?
I'm wondering how people used to write DOS games (like Doom), I can't find much on this, but would love to learn more about the earlier days of game development.

**What language was used predominantly?**

I presume it was C. Or C++ already?

**What IDEs (or editors/compilers) were popular?**

Microsoft Visual C/C++ (or Microsoft C/C++ as I believe it used to be called) didn't exist back then AFAIK. So what did people use? *edit* and a command-line compiler from Intel or something?

**What APIs where used?**

What was common for 2D games? What about 3D games like Doom and Tomb Raider?

**Anything else that's different from today?**

I'd be happy to hear any other differences, like what image/audio formats were used.

# Answer
> 20 votes
Language: C was predominant, but C++ was around and used.

Dev tools: Development environments included those from Borland and Watcom (almost unheard of today) among others. Both Borland and Watcom had their own compilers and their own IDEs. Borland was by far the most popular in general, though Watcom had a reputation for producing faster compiled programs, iirc.

APIs: Few APIs existed or were used. Video programming often consisted of directly writing pixels to the VGA framebuffer. Even 3D game were software rasterized. The Miles sound API was used for audio, which included drivers internally as the OS didn't have it's own audio framework or drivers. Keyboard and mouse input were generally read straight from the system. There were a couple popular memory extenders for 32-bit mode which were very popular and necessary towards the end of DOS's reign. The hardware was simple, thankfully, but it was definitely a pain in the butt writing games that worked on a variety of hardware. Libraries to deal with all the simple low-level stuff (like SDL, SFML, GLFW, etc.) did not exist, and porting was a huge amount of the work in releasing a game due to all the different platforms and hardware popular at the time (though its getting equally bad these days, what with all the consoles, handhelds, and mobile devices, plus Windows and the fringe desktop OSes like OSX and Linux).

On a side note to the previous point, Doom was not 3D the way we know it today. That is, it imposed huge limitations on 3D environments due to its highly specialized software rasterization algorithm, and characters and items were all jut sprites.

File Formats: Asset formats were just as proprietary to the engine then as they are now. I vaguely recall Bink being around back then for video (which was very rare, generally only in opening and closing sequences), and I think Creative had some specialized sound formats. I'm unsure what source or intermediary formats were popular for sound or video back then, but TGA was pretty popular for images.

# Answer
> 4 votes
As a completion to Sean's post, since you mentioned Doom: there is a nice blog by Fabien Sanglard, who made a review on the part of code used for making Doom (the one from 1993). The review is here: http://fabiensanglard.net/doomIphone/doomClassicRenderer.php

PS: The blog has a lot of Doom/Quake-related code reviews, and it's a nice read for a game developer to see how others designed a game from ground up

---
Tags: software-engineering, editors, ide
---


# Question
Title: How to randomly create stars in the background?
My player flies around the screen in any direction he wants, and the camera follows him. There are stars in the background. I can't figure out how to randomly generate the stars. I made a star class. There are a few different types of stars, and some have different depths than others, hence they move slower as the player moves around. I can create a stars around the player when the game starts, and when they get 100 pixels off the screen they are destroyed, but I can't figure out a good way to create new stars.

Here is my code: Star Class:

```
#pragma once

struct Star
{
int xposition, yposition;
int type;
int velocity;

bool alive;

Star()
{
    xposition = yposition = 0;
    type = 0;
    velocity = 0;
    alive = false;
}

void create( int p_xposition, int p_yposition, int p_velocity, int p_type )
{
    xposition = p_xposition;
    yposition = p_yposition;
    velocity = p_velocity;
    type = p_type;

    alive = true;
}

void destroy()
{
    alive = false;
}
};

```

Background Class:

```
#include "background.h"

void Background::init( Engine* p_engine, SDL_Rect* p_camera )
{
engine = p_engine;
camera = p_camera;

delta_time = SDL_GetTicks();

for ( int s = 0;  s < 100;  s++ )
{
    stars[s] = new Star;
}

image[0] = engine->load_image( "star 1.png" );
image[1] = engine->load_image( "star 2.png" );
image[2] = engine->load_image( "star 3.png" );
image[3] = engine->load_image( "star 4.png" );

for ( int s = 0;  s < 30;  s++ )
{
    for ( int s2 = 0;  s2 < 100;  s2++ )
    {
        if ( stars[s2]->alive == false )
        {
            stars[s2]->create( rand() % engine->screen_width, rand() % engine->screen_height, rand() % 30, rand() % 4 );
            break;
        }
    }
}
}

void Background::cleanup()
{
for ( int s = 0;  s < 100;  s++ )
{
    delete stars[s];
}

for ( int i = 0;  i < 4;  i++ )
{
    SDL_FreeSurface( image[i] );
}
}

void Background::logic()
{
delta_time = SDL_GetTicks() - delta_time;

  //destroy stars
for ( int s = 0;  s < 100;  s++ )
{
    if ( stars[s]->alive == true )
    {
        if ( stars[s]->xposition < camera->x - 100 || stars[s]->xposition > camera->x + camera->w + 100 )
        {
            stars[s]->destroy();
        }
    }

    if ( stars[s]->alive == true )
    {
        if ( stars[s]->yposition < camera->y - 100 || stars[s]->yposition > camera->y + camera->h + 100 )
        {
            stars[s]->destroy();
        }
    }
}

  //create stars
if ()
{

}

delta_time = SDL_GetTicks();
}

void Background::render()
{
for ( int s = 0;  s < 100;  s++ )
{
    if ( stars[s]->alive == true )
    {
        engine->apply_surface( image[stars[s]->type], engine->buffer, stars[s]->xposition - camera->x, stars[s]->yposition - camera->y );
    }
}
}

```

# Answer
> 5 votes
I've made a star field, much like the one you describe. I would recommend wrapping the stars. If a star goes off the screen on one side, have it reappear on the other. This worked for me, but I also had a bajillion stars, so nobody could notice. As a side-effect, the stars always look the same at any given view point.

Before I was wrapping stars, I used to recycle the star object and provide it with some new random properties on the other side of the screen; random properties included: position (only 1 axis, based on which edge it fell off), size, brightness, and speed. This worked well, but I came across problems when my screen was moved very quickly, causing stars to bunch up along the edges of the screen. The reason for the bunching up was twofold. First, I was doing a direct assignment of the star's new position on the other side of the screen instead of taking into account how far the star was off screen, and secondly: what if you move the screen multiple screen-sizes away and you randomly generate the stars' speed. Just some stuff to think about if you end up taking this route, and why I switched to basic wrapping.

But I would recommend not deleting your star objects because allocating and releasing memory is a relatively expensive task, especially when you can just recycle your stars.

# Answer
> 2 votes
I suggest another solution to this, instead of keeping a lot of star objects, draw them to a large framebuffer once, and draw this framebuffer looped on the screen. If you want stars to have different speeds, create a few framebuffers, draw them all at the same time, but scroll at different speeds. This has a few advantages:

1) Simple - you only have to generate starfield once and you don't have to worry about memory-managing your star objects

2) Nice from the memory point of view - you make less dynamic allocations, the only memory you allocate is likely to be video memory

3) I think it will be faster to draw the contents of a framebuffer once than constantly asking the video device to draw one star here, one star there.

---
Tags: 2d, random, procedural-generation
---


title: Advice on a PHP RPG System

text:
# Question
Title: Advice on a PHP RPG System
I am looking to make a php/mysql/javascript based rpg on a site. I am trying to figure out the best method when it comes to items, quests, etc. For instance should I make classes for each item type and then store just the item level etc in the database, thus making a object of the item when the player starts playing. Or to store the full item data in the database and update that as the player plays.

I figured the object one would cause less calls to the database but I then wonder how would I go about this method. That is I know how to make the classes etc, but what would the method be when the player logged in and you needed to get their inventory etc.

Any advice on how to go about this would be nice, any tutorials you know of etc too. Thanks.

# Answer
As to

> but what would the method be when the player logged in and you needed to get their inventory etc

You need to look at Managing Sessions and State with PHP or PHP Session Management With Cookies.

In general when the player logs in you'll query the database for all the information needed to *hydrate* the objects associated with the player, such as their inventory and the properties of the objects contained within. After you've got all of that loaded you can store it in the session and updated it as needed, such as removing a used item from inventory. When the session ends you update the database with the final state.

**Note:** the above could easily run into scaling issues, as keeping large objects and collections of objects in memory becomes expensive, however, it is straightforward to implement, and by the time you become the next WOW you'll either have the experience or enough clout to hire those who do.
> 6 votes

# Answer
Contrary to Jonathan Hobbs' comment, if you know PHP and want to build (the backend of) a web-based game with it, that's totally fine. PHP is powerful enough to run Facebook, and your game is unlikely to be more complex, resource hungry, or demanding in terms of responsiveness than that.

Having that said, you might want to use one of the many PHP frameworks available to make your life easier.

For example, with regard to items, you can use a framework's system for handling data objects to define the classes Character, Equipment, Item, and Skill (and child classes for specific Items, Skills, etc.). Character, Equipment, Item, and Skill would correspond to tables in your database, so in the table 'item' there would be a row for each item. Then, when a user makes a request, you load these entries from the database and construct the objects accordingly. (This is similar to your first approach for storing item data.)

In a framework called Yii, you could then do something like this:

```
/**
 * Load a character and all related items and skills.
 * Do this when the user logs in. You can save the data in a session or
 * reload it every time the user makes a new request
 */
$Character = Character::model()->with('items, skills')->find(
    'username:=username',
    array('username' => 'demo')
);

// Find a skill with id 5 and attach it to the character
$Fireball = Skill::model()->findByPk(5);
$Character->addSkill($Fireball);

// Manipulate attributes of the character table
$Character->money -= 500;

// Update the new state of the character in the database
$Character->update();

```

Don't worry about the specifics of this code; I just want to demonstrate how much easier it is to retrieve, manipulate, and save game related data in PHP frameworks as opposed to native PHP.

When it comes to tutorials, just read about software engineering in general (OOP, design patterns, web technologies), and the PHP framework of your choice in particular. Games don't add any magic to software engineering.
> 3 votes

---
Tags: rpg, browser-based-games, php, objects
---


# Question
Title: Implementing Online Leaderboards for indie windows PC Game
I've just finished my game and I'd like to add some ranking functionality to it. I have a mySQL database running on my website and want to be able to insert and retrieve data from it. My knowledge in server side programming is basic to none and I'm wondering if you could provide me some tips on how to approach this. My game was developed in C++.

1) Should I look for I library written in C/C++ that handles this client/server communication directly?

OR

2) Should I implement it through a script (say python) and somehow interface it through my C++ code. By interfacing I imagine I'd call .py passing in a string as argument, and somehow receiving a string as return. (table entries, error messages, etc). Also I don't want anyone messing up with the database. I don't know, the source code would be there with connection authentication and I assume anyone knowing python could adjust it to inject any value in the database. Well, If that is a good approach what libraries could I use to interface C and Python (or any other say Java).

# Answer
> 1 votes
Write a script in perl, python, or some other convenient scripting language that processes a form which specifies the game, who won etc. You can develop and test this script using any web browser. Use a network package such as libcurl to submit these forms from within the c++ application.

You will need to take some steps from the beginning to prevent fraud and accidents from trashing your rankings. For example, make your request include a md5 checksum to authenticate it and prevent altering the request, and keep track at the server to prevent the same request from being used twice.

---
Tags: c++, python, client-server, leaderboards, ranking
---


# Question
Title: How to tune the collision handling to respond differently depending on the collided objects?
I'm making a collision handler for a Java game engine. I made an interface called Collidable. I have a method called onCollision which takes the parameter of my Engine Game Object.

```
public void onCollision(engine.objects.Object obj) {

}

```

I want to know how I can redo this so that I can give individual instructions for each Collidable object's onCollision method for how to collide with a Wall object or an Enemy object without having to write another method that has the parameters Wall and Enemy so that my engine is flexible.

How can I do this?

# Answer
> 2 votes
You are about to begin your journey into Overloading, it's an essential part of the Polymorphism.

The first result from Google is just enough to give you an idea.

This topics are the basic topics for every Java programmer and in general for every programmer who wants to code in an OO way, i suggest to pick a good book that can teach you the basic stuff or a good online resource.

---
Tags: java, collision-detection, architecture
---


# Question
Title: If I were to start an Android or iPhone app or game, what program should I use?
I don't really know a lot about programming and the only things I do is using codes with Gamemaker, but I have read that it is too basic and it can't be used with iPhone or Android.

Is there anything free that I can use to make games for those platforms? Or if not, any suggestions for engines or anything else? I was wondering about Unity, for example, is that a good investment to use for making games?

# Answer
As for the iPhone:

xCode is free for the mac, as are frameworks for making 2D games like cocos2D.

For 3D you could use a free version of unity (mac and pc) or UDK (pc), but I believe if you wanted to publish the game you'd have to pay. In fact if you want to publish anything anywhere you pretty much have to pay a little bit for a licence, but the making and learning part can be free.

If you're not really a programmer I would recommend either UDK or unity (unity is a bit more simple and iPhone friendly at this point). You don't need to code with them, but are things you can script if you want to get into that side of things.

Unity (Recommended for beginners)

UDK
> 3 votes

# Answer
If you know Python, you can use kivy to develop apps for both iOS and Andriod. Kivy is free, can be used on Windows, Linux, and OS X. The Kivy site has got tons of documentation and resources. The only problem with it is that there aren't many examples of source code out there (though they provide a few starter tutorials).

As for learning Python, it's a pretty language easy to learn. May I suggest this site to get started with game programming in Python.
> 1 votes

# Answer
I'm a hudge fan of libgdx, it's not an engine, but I think that is for the better. A summary can be found on there Wiki.
> 0 votes

---
Tags: android, iphone
---


title: Managing the user input

text:
# Question
Title: Managing the user input
I'm studying a good number of articles about this topic and seems to me that there is just one way to do this: a signal/slot design.

I was also looking at some more complex async examples but I don't think I will adopt this, the tradeoff is not convenient in my opinion.

The classic C++ code that I have read until now is done with a template design and adopt a signal/slot logic, now my question: there is a better way to handle the input from the user? Is there a good pre-packed library for this?

I'd like to handle a broad range of different inputs: mouse, keyboard, gamepad, maybe also touch screen gestures, on several different platforms. My system should also be user-configurable.

# Answer
You don't *need* any kind of complexity for this. You don't *need* signals/slots for input.

For most games, simply **polling the input state** works. How to do that exactly is up to you, but this usually means you'll fill one table of inputs per-player each time your game updates:

* An option is to define you inputs for one platform & input device only. For instance let's say the Xbox 360 is your development platform: you'll have a map of the Xbox 360 buttons. Then whatever code makes your character jump just polls for the "A" button state. This makes input handling quick and easy on the programming side, but starts to get messy as soon as you want some configurablity (either for designers or for users).
* A more advanced option is to have a map of "actions" that are defined per-platform as combinations of button presses, or some other kind of input (gestures, voice...). Then whatever code makes your character jump just polls for the "jump" action's state. Actions state should probably be a float or any kind of range, but not a boolean, so it can handle analog inputs (stick, gesture "match factor"...). The upside of this is that it's easy for you (and your user) to redefine which action is associated with which input. The downside is that this kind of actions map tend to grow very quickly to a point they start to be unmanageable.
* Compatible with both option: instead of redefining your inputs for each controller type, it's a good idea to pick a default one, and then just define a correspondence.

You *can* also use a very simple messaging system. Maybe combine it with a publisher/subscriber model, but that's not necessary.

That said, if you're set on signals and slots, Boost has an implementation, which is itself based on libsigc++.
> 5 votes

---
Tags: c++, architecture, input
---


title: When to Use Collision Detection Methods

text:
# Question
Title: When to Use Collision Detection Methods
I've done some research into different collision detection methods but I don't know when I should be using one over the others. Some I've seen are:

* Continuous Collision Detection (CCD) or Raycasting
* Quadtrees
* Discrete stepping

So for example if I want to shoot a bullet which method would I use? Well I've herd CCD is the way to go for that. But what if I have an unrealistic machine gun that has a huge rate of fire making 100 bullets shot at any given time. I don't know if I should be using a quadtree or be consistent and use CCD or even use something else.

Could I get some clarification on what each method is best suited for? That way I'm confident I'm using the right method for the situation. Also if you know of any other good collision detection methods let me know. Oh and if the dimensions matter I'm talking 2D here.

Thanks.

# Answer
Quad trees are a totally different thing than the collision method. Quad trees are a form of spatial partitioning. Spatial partitioning helps weed out distant objects when trying to find pairs of colliding objects or testing ray collisions. Spatial partitioning is technically entirely optional, but in practice is required for performance.

Continuous vs discrete determines how often collisions are checked for. Continuous collision detection works without stepping time, instead checking to see when the next collision would occur and telling you what time that collision will be. Some folks also call swept volumes a form of continuous collision detection.

The primary advantage of continuous collision testing is to avoid tunneling. Tunneling occurs in discrete systems because objects are only checked for collision at specific intervals. If an object is small and fast enough, it may be completely on one side of a wall at one time and the next increment it will be completely on the other side. Continuous collision detection also provides more accurate results, as it can tell you the precise moment two objects will collide, while discrete systems only find out about collisions after the objects have penetrated each other.

The primary advantage of discrete detection is that it tends to be much faster and simpler for objects with complex shape or large size. Continuous collision detection requires mathematical descriptions of all objects and their motions and the solving systems of equations, which can be difficult, slow, or outright impossible in many circumstances.

Swept volumes are a way of using discrete detection while solving tunneling. You can take an objects current position and old position and enclose a shape around both of them ( this would be a line if your objects are points, a capsule if your objects are spheres, etc ). It is not as accurate as continuous collision, but simpler.

In general for simpler physics engines, use discrete methods for most objects and use a ray cast (continuous) for bullets. Specific games might need to use continuous or swept volumes more often, depends entirely on the specific game.

For things like your machine gun, consider simply reducing the number of bullets. Players really aren't going to notice 100 individual bullets when you can "cheat" and simply draw a bullet spray wffect and use a much smaller number of rays for actual hit tests.
> 5 votes

# Answer
A lot of shooters tend to use limited range on their bullets making line collision detections instead of using rays. This is quite a bit faster than raycasting because it has an extent. You could also do updated line collision, making smaller lines that move over a few frames to do accurate collisions so you don't get shot and killed as soon as someone pulls the trigger, this being most noticeable on long range weapons such as a sniper.

You can also use a combination of both line collisions and a tree, allowing you to only grab the areas that you know the bullet will be within and check with in those.
> 1 votes

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


title: iPhone game - saving player state data

text:
# Question
Title: iPhone game - saving player state data
I am developing my first app for iPhone, using C++ and some Objective C code to interface with ios sdk api. My app is obviously a game. I was wondering where to save the state of the player (in my case, i want to save something like the number and identification label of every level finished, the score made at a level, how many stars taken, how many hidden item discovered and so on). My idea is to create (if it does not exist yet) a temp directory somewhere (is there a c: drive?). The temp directory will be there till the disinstallation of the game. In the temp directory, i will save all the relevant info. Is this the right way to handle this situation?

Ps. I see the reason for the downvote. I forget to specify that my app needs to run on different systems (iphone, android and so on...). I would like to employ a more portable technique...

# Answer
> 0 votes
there is no C: Drive in this Case, but in Objective-c you could use the DocumentDirectory of your application.

```
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];

```

So you get the path to the Document directory of your app. In this directory you can save your files.

Edit: if someone downvote, please submit the reason in a comment.

---
Tags: iphone, savegame
---


# Question
Title: Programming  languages reccomended for a career in game design
I'm currently in year 11 and about to complete the highest level IT subject that my school offers leaving me no advanced programming courses to do next year. My question is: are there any quality online courses worth doing and which languages should i focus on learning. So far I've learnt java applet writing semi-self taught myself Android activity writing in Eclipse and tiny bits of c\* and I pretty much know Gamemaker back to front.

So if i wanted to move into a career in programming for games, and such, which courses would you recommend, and which languages would you study?

# Answer
> 2 votes
Rather than taking endless courses, you should be programming actual games - you will learn more and even half-complete prototypes will get you further in a job interview than some course credits, let alone online courses. So pick a genre you like and start developing a simple game and use Google every time you encounter a problem.

As to what language to choose, it depends wildly on several factors. Are you looking to get hired by a big game company? Are looking to go indie, developing smaller games yourself? Is the mobile market something you are interested in? AAA titles are usually C++, indies make games with just about any languages and tools, iPhone uses Objective-C and Android requires at least some Java.

You should also take a look at the Related-column on the right. Lot's of info there.

---
Tags: software-engineering, career
---


# Question
Title: Disadvantages of using multiple versions of OpenGL in LWJGL?
So, I'm trying to figure out LWJGL, and my goal is to use OpenGL 3.2 (because pretty shaders are pretty). But in every tutorial I can find for LWJGL, they import a bunch of different OpenGL versions and use them at the same time. For example, this one imports GL11, GL15, GL20, and GL30 and uses functions from all of them. This seems intuitively like it would be messy and generally a bad idea. Besides the normal disadvantages of using deprecated functions, is there any particular reason not to do this? Could it affect performance in any way? Is there a potential for errors and odd behavior to occur?

Also, if possible, does anyone have an example of LWJGL written only using GL32? I've found C++ code samples that do this, but I'm not too familiar with C++, so it's difficult for me to translate.

# Answer
> 5 votes
LWJGL prefaces all core functions and enumerators with the OpenGL version that those functions were introduced in. So `glBindBuffer`, a function introduced in OpenGL version 1.5, is called `GL15.glBindBuffer`.

That's just how it works. It's not really importing "a bunch of different OpenGL versions"; it's just using the version those functions/enumerators was introduced in as a "namespace" scope.

That way, if you're writing to a specific OpenGL version, it's easier to prevent yourself from using functions that aren't available in that version. Of course, OpenGL core extensions kinda confound this notion.

# Answer
> 4 votes
As Nicol Bolas said, the version number corresponds directly to the version number were a symbol, function or constant was introduced.

It's probably impossible to write a working application using only the GL32, or any one namespace for that matter (maybe apart from GL11). For instance look at this snippet from my game:

```
    this.fbo = GL30.glGenFramebuffers();
    GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, fbo);

    GL30.glFramebufferTexture2D(GL30.GL_FRAMEBUFFER, GL30.GL_COLOR_ATTACHMENT0, GL11.GL_TEXTURE_2D, this.fboImg, 0);
    GL30.glFramebufferTexture2D(GL30.GL_FRAMEBUFFER, GL30.GL_COLOR_ATTACHMENT1, GL11.GL_TEXTURE_2D, this.fboTileCoordsImg, 0);
    GL30.glFramebufferTexture2D(GL30.GL_FRAMEBUFFER, GL30.GL_DEPTH_ATTACHMENT, GL11.GL_TEXTURE_2D, this.depthImg, 0);

    int status = GL30.glCheckFramebufferStatus(GL30.GL_FRAMEBUFFER);
    if (status != GL30.GL_FRAMEBUFFER_COMPLETE)
    {
        throw new RuntimeException("Framebuffer creation failed with code: " + status);
    }

    IntBuffer scratchBuffer = BufferUtils.createIntBuffer(2);
    scratchBuffer.put(0, GL30.GL_COLOR_ATTACHMENT0);
    scratchBuffer.put(1, GL30.GL_COLOR_ATTACHMENT1);
    GL20.glDrawBuffers(scratchBuffer);

```

I'm using glFramebufferTexture2D which came with OpenGL30, but I need the constant GL11.GL\_TEXTURE\_2D. Later on I need to call glDrawBuffers which comes from GL20. Nothing fishy here; I just an older function to do a newer thing, like the OpenGL docs tell me to. Besides, I don't really have a choice :)

What you should worry about are deprecated functions, like these: glBegin, glEnd, glVertex\*, glNormal\*, glTextCoord\*, glTranslate\*, glRotate\*, glScale\*, glLoadIdenity, glModelViewMatrix... etc. Generally everything that uses fixed pipeline or the matrix stack.

If you are worried if you are using deprecated functionality, you can force LWJGL to create a strictly core profile rendering context with an appropriate openGL version by passing an appropriate ContextAttribs to Display.create.

---
Tags: opengl, java, lwjgl
---


# Question
Title: Jitter during wall collisions with Bullet Physics: contact/penetration tolerance?
I use the bullet physics engine through Panda3d.

My scene is still very simple, think 'Wolfenstein3d': tile-based, walls are solid cubes.

I expect walls to block the player, and I expect the player to slide along the walls in case of non-normal incidence.

What I get is what I expect, with one difference: there is some jitter. If I try to force myself into the wall, then I see the frames blinking quickly between two positions. These differ by about 0.04 units of distance, which corresponds to 4 cm in my game.

I noticed a 4 cm elsewhere: the bottom of my player capsule is 4 cm below ground, when at rest.

Does that mean that there is somewhere in the Bullet engine a default 0.04-units-long tolerance to differentiate contact from collision? If so, what should I do ? Should I change the scale of my game so that these 0.04 units correspond to 0.4 cm, making the jitter ten times smaller? Or can I ask bullet to change its tolerance to a smaller value?

**Edit**

This is the jitter I get: 6.155 - 6.118 = 0.036

```
LPoint3f(0, 6.11694, 0.835)
LPoint3f(0, 6.15499, 0.835)
LPoint3f(0, 6.11802, 0.835)
LPoint3f(0, 6.15545, 0.835)
LPoint3f(0, 6.11817, 0.835)
LPoint3f(0, 6.15726, 0.835)
LPoint3f(0, 6.11876, 0.835)
LPoint3f(0, 6.15911, 0.835)
LPoint3f(0, 6.11937, 0.835)

```

I found a setMargin method. I set it to 5 mm both on the BoxShape for the walls and on the Capsule shape for the player. It still jitters by about 35 mm as illustrated by this log (11.117 - 11.082 = 0.035):

```
LPoint3f(0, 11.0821, 0.905)
LPoint3f(0, 11.1169, 0.905)
LPoint3f(0, 11.082, 0.905)
LPoint3f(0, 11.117, 0.905)
LPoint3f(0, 11.082, 0.905)
LPoint3f(0, 11.117, 0.905)
LPoint3f(0, 11.0821, 0.905)
LPoint3f(0, 11.1175, 0.905)
LPoint3f(0, 11.0822, 0.905)
LPoint3f(0, 11.1178, 0.905)
LPoint3f(0, 11.0823, 0.905)
LPoint3f(0, 11.1183, 0.905)

```

The margin on the capsule did change my penetration with the floor though, I'm a bit higher (0.905 instead of 0.835). However, it did not change anything when colliding with the walls.

**How can I make the collisions against the walls less jittery?**

**Edit, the day after:**

After more investigation, it appears that dynamic objects behave well. My problem comes from the btKinematicCharacterController that I use for moving my character; that stuff is totally bugged, according to the whole Internet :/.

# Answer
> 4 votes
This sounds like numerical instability due to floating point inaccuracy. Are you using the scale factors for your scene/objects as per the vendor's recommendation?

**Edit:**

General checklist for physics engine jitter

* Make sure you are using the correct scale factors
* Make sure that the *quantities* are reasonable (e.g. 10m, 80kg, ...)
* Enable sleeping if this is an object without any internal forces (i.e. it has no controller/force generator)
* Explore all settings related to ray casting. *Plausible cause to your problem*
* Relax the penetration depth tolerance to allow for some penetration. *Likely cause to your problem*

† This can potentially allow cameras to "see through" walls, and can be solved by putting a thin, invisible object in front of the wall or expanding the AABB to act as a buffer.

# Answer
> 1 votes
Sounds like your engine constantly tries to update the parameters of that object. The object should freeze in position once it reaches a state that Bullet has decided upon to be "stable". Otherwise, numerical errors won't ever result in accurate collision handling, therefore that jittery motion (forces build up eventually, objects are penetrating again, oscillations result). Some ideas are mentioned here. I would start investigating the "sleep issue". Perhaps someone who has hands on experience with this engine could provide a way to set the sleeping threshold efficiently in your case.

# Answer
> 0 votes
One thing you might want to look into is a CCD option. In some physics engines you can an option to enable "Continuous Collision Detection."

Its much more resource intensive, but rather than solve the collision as a Yes/No at each time step it works to find the actual point of collision and stop you there.

I'm not familiar with the bullet engine, but that might give you something to look for. Interestingly enough its most often used for things like bullets to prevent wall penetration.

---
Tags: bullet-physics
---


# Question
Title: Must I worry about quad-based rendering in real world scenarios?
Most of the time in the first chapters of a random book about rasterization and rendering techniques, I find some phrases about a triangle-based rendering system and a quad-based one.

I have never encountered a quad-based GPU or pipeline. Do I have to worry about that when dealing with OpenGL 3.0+, or is it just legacy stuff?

# Answer
No, you don't. All current-generation commodity GPUs use (and have used for some time) triangle-based rasterization methods exclusively. Even though older version of OpenGL support the `GL_QUADS` rendering mode, these were converted to triangles by commodity GPUs. It's likely that `GL_QUADS` only resulted in actual quadrilaterial-based rasterization on esoteric academic hardware or hardware used for high-end offline 3D rendering in the early 80s or 90s (I have no evidence to support this claim, I'm just postulating).

That said, looking at quadrilateral (and in general, polygon rasterization other than triangle rasterization) can still be educational, and thus useful, simply by providing a different perspective of things. The algorithms involved in doing so efficiently are interesting and sometimes still have applications beyond graphics programming. I once used a edge-walking polygon rasterization technique as a means of implementing a simplistic fake 2D water simulation, for example.

It also may help you understand why triangle rasterization is preferable, in part due to the potentially non-planar nature of polygons other than triangles and because of some of the resulting optimizations you can make with triangles.
> 9 votes

# Answer
If you're using a rendering API, then you only need to worry about what that API tells you to worry about. OpenGL doesn't say anything about quad-based or triangle-based rendering systems. So you don't need to concern yourself with it.

In any case, all consumer-grade GPUs use triangles, not quads.
> 7 votes

---
Tags: opengl, gpu
---


# Question
Title: HTML5 or Javascript game engine to develop a browser game
I would like to start developing a MMO browser game, like Travian or Ogame, probably involving also a bit of more sophisticated graphical features such as players interacting in real time with a 2d map or something like that.

My main doubt is what kind of development tools I should use: I've a good experience with PHP and MySQL for the server side and Javascript (and jQuery) regarding the client side. Coding everything from scratch would be of course really painful so I was wondering if I should use a javascript game engine or not. Are there (possibly free) game engine you would recommend? Are they good enough to develop a big game?

Also, I saw a lot of HTML5 games popping up lately but I'm now sure if using HTML5 is a good idea or not. Would you recommend it? What are the pro and cons about using HTML5? If you'd recommend it, do you have any good links regarding game development with HTML5?

(PS: I know that HTML5 and a Javascript engine are not mutually exclusive, I just didn't know how to formulate a proper title since English is not my main language. So, please, answer addressing HTML5 and a game engine pro and cons separately)

# Answer
> 5 votes
HTML5 game engines are really designed more for "single page" games, basically, re-creating Flash games (load the entire game once, and play it on a single page in the browser). Travian and Ogame consist of multiple pages, and existing HTML5 game engines really aren't designed to handle that sort of setup. If you're going to create a game like Travian or Ogame, then it's probably fine to simply use jQuery or whatever other Javascript DOM manipulation library you're familiar with.

That said, if you do want to make your game a "single page game" as it were, any of the options in this related question would be good choices.

# Answer
> 1 votes
LimeJS is an excellent HTML5 game dev framework.

Pros:

* can develop for multiple devices without having to worry about screen resolution, etc.
* easy to learn
* good community and tutorials. For example: Create a Mobile HTML5 RPG

Cons:

* runs a bit slow in mobile
* a bit hard to integrate with other canvas libraries

# Answer
> 0 votes
I have used Cocos2d-x which is the C++ port of Cocos2d. I am just starting to play with Cocos2d-x Html5 port which looks stable so far.

http://www.cocos2d-x.org/projects/cocos2d-x/wiki/Html5

When starting with 2d-x over a year ago the project was really solid and had some full time developers who were subsidized by some big Chinese phone company. Now, a year + later it is getting a lot of steam and I think the Html5 version will become a big deal?

https://github.com/cocos2d/cocos2d-html5/

You'll even see Ricardo Quesada (the orginal Cocso2d Obj-C guru) is a contributor to this (if not main contributor) to this project.

Of course it uses Html5 but you will really only need to program in javascript. Keep the PHP for your server side leaderboard and/or other centralized logic if you want that sort of thing.

# Answer
> -2 votes
This engine costs a little bit of money, but it looks decent: http://impactjs.com/

---
Tags: browser-based-games
---


title: android 2d bullet-spawn (shooting)

text:
# Question
Title: android 2d bullet-spawn (shooting)
This will be a quick question since Im pretty sure I'm overlooking something small that I for some reason cant see.

My sprite is moved using a joystick, and I want my sprite to be able to shoot. I've got the direction and speed of my bullet working, but I cannot get it to shoot from the right place (my sprites location).

Code for moving sprite:

```
    angle = Math.atan2(touchingPoint.y - inity,
                touchingPoint.x - initx) / (Math.PI / 180);

        pointerPosition.y += Math.sin(angle * (Math.PI / 180))
                * (touchingPoint.y / 90); //Sprites y-position
        pointerPosition.x += Math.cos(angle * (Math.PI / 180))
                * (touchingPoint.y / 90); //Sprites x-position

```

Current code for moving bullet:

```
    if(shooting){
        bulletPos.y += Math.sin(angle * (Math.PI / 180)) * 2;
        bulletPos.x += Math.cos(angle * (Math.PI / 180)) * 2;
    }

```

Since the angle is calculated using constants I get why my bullet only spawns at one place, even tho Im moving my sprite around. My question is, how do I fix this?

First time working with vectors like this and all I can find on stack is logic for tower-defence games, if there is a duplicate of this question I apologise but really cannot find it.

# Answer
> 2 votes
Set the `bulletPos.x` and `bulletPos.y` equal, or slightly offset, to your sprite's x and y position, `pointerPosition.x` and `pointerPosition.y`. This will make your bullet sprite "spawn" where your sprite is.

# Answer
> 2 votes
If I'm reading your code correctly you need to set the bullets position to the same position as your sprite as soon as you spawn the bullet and before start to move it.

Something like:

```
bulletPos.y = pointerPosition.y;
bulletPos.x = pointerPosition.x;

```

Once that's in place you can angle and move it however you want.

---
Tags: 2d, android, physics, vector, shoot-em-up
---


# Question
Title: Transformation matrix that maps a window
I'm currently learning OpenGL at uni, and they give us questions to help us learn (these are not worth anything), however I'm stuck on this one question and would have to travel over an hour and a half to uni for an answer.

How do I do this question? Please include as many steps as you can, I want to be able to follow exactly how to do this.

Find the transformation that maps a window whose lower left corner is at (1,1) and upper right corner is at (3,5) onto:

1. The entire device screen whose dimension is (600, 500)
2. A viewport that has lower left corner at (100,100) and upper right corner at (400,400)

Edit: Damn sorry I should have added I am meant to find the matrix, so no code.

# Answer
You need a combination of scale and translation matrices. You could first go to a "normalized" screen space (origin at 0,0 and scaling to 1,1) using, in pseudo-code:

```
MatToNormalized = Translation(-1, -1) x Scale(1/2, 1/4)

```

Then you can easily map to any kind of screen space. E.g. for question 1.:

```
MatToFullscreen = MatToNormalized x Scale(600, 500)

```

And for question 2.:

```
MatToViewport = MatToNormalized x Scale(300, 300) x Translation(100, 100)

```

**EDIT**

A Scilab dump with the actual matrices:

```
MatToNormalized = [1 0 0; 0 1 0; -1 -1 1] * [1/2 0 0; 0 1/4 0; 0 0 1]
    0.5    0.      0.
    0.     0.25    0.
  - 0.5  - 0.25    1.

MatToFullscreen = MatToNormalized * [600 0 0; 0 500 0; 0 0 1]
    300.    0.      0.
    0.      125.    0.
  - 300.  - 125.    1.

TestMinFullScreen = [1 1 1] * MatToFullscreen
    0.    0.    1.

TestMaxFullScreen = [3 5 1] * MatToFullscreen
    600.    500.    1.

MatToViewport = MatToNormalized * [300 0 0; 0 300 0; 0 0 1] * [1 0 0; 0 1 0; 100 100 1]
    150.    0.     0.
    0.      75.    0.
  - 50.     25.    1.

TestMinViewport = [1 1 1] * MatToViewport
    100.    100.    1.

TestMaxViewport = [3 5 1] * MatToViewport
    400.    400.    1.

```

Please note that Scilab uses a column-major notation, so if you want the row-major notation, just transpose the result (`'` is Scilab's transpose operator):

```
MatToFullscreen'
    300.    0.    - 300.
    0.      125.  - 125.
    0.      0.      1.

MatToNormalized'
    0.5    0.    - 0.5
    0.     0.25  - 0.25
    0.     0.      1.

```

If you don't get why the translation and scale matrices are formatted this way, try Wikipedia.
> 4 votes

---
Tags: matrix, transformation
---


# Question
Title: Converting many faces to single mesh and reduce poly-count in Blender
I'm not so familiar with 3D modelling, and I'm stuck on a simple task in Blender.

I have a fairly complex model that's been imported as a .DAE file from SketchUp. This model is composed of many polygons, not as one single mesh but in many components, in fact over many hundreds of surfaces.

As I said I'm new to Blender and want to learn. If I select one of the component surfaces, I can go into Edit mode and then use the Decimate modifier to reduce the poly-count.

But it doesn't want to let me do this if I select the whole object!

I think I need to combine all the surfaces into one mesh (?) and then apply the Decimate algorithm to gracefully reduce the poly-count.

I've managed to do this before but unfortunately I forgot how and I need to try again to get the balance right on the poly-count.

Appreciate the help.

Alex

# Answer
1. select 2 or more "components" (in Blender terms, these are separate objects) (\[B\] will box-select, may be easier than shift-clicking through all the objects)
2. \[Ctrl\] \[J\] "Join"

I haven't used Blender in a long time. What helped me learn some commands was remembering the name of the command. If you bring up the spacebar menu and type in "Join", it will bring back a list of all the commands containing that word, including their keyboard shortcuts.
> 1 votes

# Answer
I figured it out by just selecting the biggest objects and decimating them one at a time, rather than trying to do the whole object, although you'd think that would be possible.

I tried all the vertex/edge/face merging tools and none of them seemed to do anything, still need to figure that one.
> 0 votes

---
Tags: models, blender, 3d-meshes
---


# Question
Title: how to modify shadow mapping in "3D Graphics with XNA Game Studio 4.0"?
So I've been following the tutorials from the book Sean James's "3D Graphics with XNA Game Studio 4.0", and have been doing fine until i reached the shadow mapping part. in this book it creates point lights with a Sphere model. my first Q is how to draw a directional Light with this frame work? secondly it can do shadow mapping just for one light, how can i do shadow mapping for all or parts of the lights in the game? i just want to know how to modify this codes to do the above tasks. I've followed tutorials on MSDN and some other sites and didn't got the answer. please help me, its so urgent.

# Answer
> 0 votes
For a directional light that is global you don't really have to make the volumetric test, you can just assume that all pixels are eligible for lighting. If it is local somehow then you can just use a volume of your choice.

For a spotlight you can use a cone. To make it a bit softer in appearance you can have the light get a little weaker the further away from the center vector of the light they are. You can make it dissipate to zero before reaching the edge of the cone.

You can see an example of such spotlights in this clip.

It's been a while since I did this but IIRC you will need to create a shadow map for each of the lights. When you do your final pixel shader you will add the lights from all of these together for each pixel.

You ARE going to have a lot of bugs and trouble when working with shaders. A very good way to handle this is to have a possibility to draw all your different buffers separately. That Way you can draw your normal map and see if that is causing trouble, then check you shadow buffers etc. Just looking at a totally screwed up rendered frame will most often not help you much :)

---
Tags: xna, shaders, hlsl, lighting, shadow-mapping
---


title: OpenGL: VBO or glBegin() + glEnd()?

text:
# Question
Title: OpenGL: VBO or glBegin() + glEnd()?
I recently was given this link to a tutorial site from someone who I gave the original OGL Redbook to. The third header down says distinctly to forget glBegin() & glEnd() as the typical render method. I learned via the Redbook's method, but I see some benefit in VBOs. Is this really the way to go, and if so, is there a way to easily convert the render code, and subsequent shaders, into VBOs and subsequent datatypes?

# Answer
> 27 votes
With modern OpenGL's VBO's are the way to go, fixed function stuff (including glBegin/glEnd and the stuff in between) has been deprecated since 3.0 and removed since 3.1.

With the OpenGL Core Profile, OpenGL ES 2.0+ and WebGL you don't even have access to the old stuff.

Some people think learning the old stuff first is better because it's a bit easier, but that stuff you learn is mostly useless and then stuff you have to unlearn.

It's not just VBO's though, you need to use shaders for everything and do matrix transforms yourself (or use GLM).

The only reason to use the old stuff would be if you wanted to target OpenGL before 2.0. which was back released in 2003. There are a few really crappy embedded netbook chipsets that are 1.5 but even 1.5 should support VBOs just not shaders. Or OpenGL ES 1.x which is based on the fixed function pipeline (for example it's used on older iPhones). Or OpenGL SC (for safety critical systems).

The following commonly used functions are all deprecated:

* glBegin
* glEnd
* glVertex\*
* glNormal\*
* glTextCoord\*
* glTranslate\*
* glRotate\*
* glScale\*
* glLoadIdenity
* glModelViewMatrix

The opengl-tutorial.org tutorials have what I think is the best way to go about learning OpenGL. They rely on some of the legacy compatilibty stuff but they don't actually teach it to you. For example your not supposed to render anything without a shader but it does work. And you need to handle matrices operations (rotate, translate, etc.) yourself but by default you will get a basic flat 2D viewport.

In addition to avoiding the deprecated stuff there are a bunch of functions that make coding OpenGL much nicer but with many of them you have to decide if you are ok with requiring newer 3.x+ versions of OpenGL and compatible hardware.

There's more info in a post I made here.

If you do need to support older OpenGL for some reason, you can use VBOs when possible and when it's not, provide a fallback that uses glBegin/glEnd and loops across your vertex data.

On the other hand, there's no real 'easy' way to upconvert old render code. You could perhaps implement your own version of the functions that add the vertices to a array/vector that then dumps it into a VBO and draws it when you fake glEnd is called. but that would be very inefficient since it would be doing it every frame (unless you put in a check to only do it once but that doesn't work for animated objects) and would probably be more work that just switching to VBOs. I suppose if you had a lot of code that approach might work.

# Answer
> 7 votes
With VBOs you generally have two major advantages.

Advantage 1 relates to fully static data and comes from being able to keep your vertex data in memory that is more optimal for the GPU.

Advantage 2 relates to dynamic data and comes from being able to specify your vertex data at any point in time prior to using it for rendering, which can pipeline better.

A third advantage comes from draw call batching, but is also shared with old-school vertex arrays so I'm not calling it out specifically for VBOs. Sending data to a GPU (or using data already on the GPU) is similar in many ways to disk I/O and network traffic - if you have a few large batches it's more efficient than many small batches.

A good (not 100% accurate but enough to help you get the idea) analogy for this is if you're a bus driver who has to bring 50 people from one city to another. You can load them up one at a time and make 50 separate trips - that's glBegin/glEnd. Alternatively you can put all 50 of them on the bus and just make a single trip - that's batching with vertex arrays or VBOs (in the VBO case the 50 people would already be on the bus ;)).

This comes at a price though, and here the price is that you lose the ability to just specify vertex data as and when you require it. Well, OK, you can do that (with some additional work), but you won't be getting the full performance out of your code. Instead you need to think more about your vertex data, how it's used, how (and if) it needs to be updated, whether any animations can be done in a shader (thus enabling the data to remain static - VBOs really need shaders for a lot of animation cases to work well) or whether you need to respecify the vertex data each frame, efficient update strategies if the latter, etc. If you don't do this and just implement a naive conversion you have a very high risk of putting in a lot of work only for the end result to actually run slower! (I frequently get annoyed when I see recommendations to just "use a VBO" when it's obvious that the person making that recommendation hasn't put much, if any, thought into the actual problem.)

This can seem like an awful lot of work when you first encounter it, but it's not, really. Once you get into the mode of thinking like this, you'll actually find that it's incredibly easy and almost comes naturally. But you may screw up your first few attempts and you shouldn't be discouraged if so - screwing up is an opportunity to learn from what you did wrong.

A few final thoughts.

Having your model data in a format that can be easily loaded into a VBO can help make this whole process a lot easier for you. That means that you should avoid more complex or exotic formats, at least at first (and until you're more comfortable with the process); keep things as simple and basic as possible when learning and there will be less things to go wrong, and less places to have to look for error if (or when!) things do go wrong.

People are sometimes put off if they see a VBO implementation using more memory than an optimized/compressed glBegin/glEnd implementation (they may even refer to it as "waste"). Don't be like that. Except in extreme cases, memory usage is really not *that* important. It's a clear tradeoff here - you're accepting potentially higher memory usage in exchange for substantially higher performance. Also helps to develop the mindset that memory is a cheap and plentiful resource that is there to be used; performance is not.

And finally the old chestnut - if it's already fast enough then your job is done. If you're hitting your target framerate, if you have headroom for transient conditions, then it's good enough and you can move on to the next step. You can waste a *lot* of time and energy squeezing an extra 10% out of something that doesn't actually need it (been there, done that, still fall into the trap) so always consider what the most optimal use of your own time is - because programmer time is even less cheap and less plentiful than performance!

---
Tags: opengl, graphics, glsl, vbo
---


# Question
Title: Where can I find some good 3D character artists?
I am searching for 3D artists for a 3D iPad game. Is there a good place in the net, where I could find one? He or she should have created game models before.

# Answer
Depending on your budget, you could try contacting professional 3D artists at sites dedicated to 3D art. Two big ones are:

There's also a "Renderotica" for more *naughty* stuff, but I'm not going to link it here ...

A cheaper variant could be looking through modding sites for games for both art and artists. Two I can recommend are:

Finally, you can always look for nice objects at Google's 3D Warehouse and contacting the artists of the models you like.
> 5 votes

# Answer
You can also try GameDev.net. You can always find good freelance artists there looking for jobs.
> 2 votes

# Answer
I am working on an Android 2D game that uses 3D model animation frames for its animation (i.e. I'm not manipulating 3D models in real-time, just playing back previously captured frames).

I found a lot of my 3D models on TurboSquid.com, many of which were free and a handful I payed maybe $25 to $35 dollars for.

Depending on what kind of stuff you are looking for, there are a ton of free and low priced art already available.

Good Luck
> 1 votes

---
Tags: 3d, blender
---


# Question
Title: What tools are available for developing 2D games like Tetris or Angry Birds for Android?
I would like to ask the following regarding developing Tetris- and Angry Birds-like 2D games for Android:

1. Is Java the official development language for Android?
2. What free or commercial Android development environments (like Xcode is for iOS) are available?
3. What open source game development engines, like cocos2D, are available for Android?
4. Are there any great tutorials available for developing such games?

# Answer
> 10 votes
1. Java is the default language to develop on Android, although you can use NDK (native C) for performance issues on specific parts. But basically, Java + OpenGL is fast enough for most 2D games.
2. One of the best (in my opinion) development environments for Java/Android is Eclipse : you can download plugins for Android from the official website.
3. You have Andgine, a free 2D game engine : http://www.andengine.org/
4. You'll find many tutorials for Andgine on their website. If you're missing something, maybe ask for a specific topic here or on their forum.

# Answer
> 6 votes
1. The Android developer site doesn't make it clear anymore that the SDK uses the Java language, but that's the official language. Compiled languages can be used through the Native Development Kit, allowing for languages like C or C++ to be used; however, this is for augmenting Java code rather than replacing it.
2. The supported IDE is Eclipse, and Google provides a plugin to help automate the creation, testing, and deployment of Android apps.
3. There's a relatively new 2D game engine called andEngine which is LGPL licensed. There is also an Android port of the cocos2D engine you mentioned, which is New BSD licensed. Box2D is also available for Android, and is the physics engine used by Angry Birds and many physics-based 2D games.
4. There are examples and tutorials available for andEngine, and more are being created all the time. For cocos2D you could adapt any of the many tutorials for iOS development; or find some specific to cocos2D-android. There's an example Android Tetris game you can use for reference and a Java Tetris tutorial you could use for guidance.

# Answer
> 1 votes
As far as engines are concerned, check out the Corona SDK . It's really easy to use (Lua) and there are a lot of great resources and tutorials available. It isn't free, though; there is a yearly subscription, but it's well worth the price.

# Answer
> 0 votes
I am developing an OpenGL application on android, and found that LibGDX is the way to go.

It has very high performance and runs on multiple platforms very easily (Windows, OSX, Linux, Android...). It was a steep learning curve for me as this is my first game and my first open gl application combined, and I truly suck at math - but its working and it looks good!

I develop and debug using Eclipse on my windows box and occasionally test the game on my android phone (A Rezound) just to make sure I haven't broken anything on android.

Doing the development and debugging natively on windows via LibGDX is awesome as it is fast and hassle free.

Doing debugging on the phone was getting old really quick as it was slow to load and install.

Good Luck

---
Tags: 2d, android, ide
---


# Question
Title: Is there already an accepted way to measure the "enjoyment/entertainment value" of a certain game?
I don't know if the question is legit, but I've tried my best. I've found this post here about measuring the creative/entertainment value of video game requirement. I've done some reading but I can't see if there already exists a specific way to measure such.

This one is research study about a model for evaluating player enjoyment. I don't know but, is it outdated? The study was conducted way back 2005.

Is there any any studies or researches you know that is somewhat related to this or some other way?

# Answer
I think the latest researches to obtain such data, is to measure biometrics values on players during tests.

Using metrics such as

can capture some inconscious feelings of the player. Biometric can't completely substitute verbal reports of player after/during tests, but can integrate them and offer some new useful informations on game experience.

Here's some nice simple slides I read sometime ago:

You can search for academic articles using google scholar, you'll find several articles related to this subject.
> 1 votes

# Answer
I actually wrote a paper this spring for a Empirical Studies course that referenced the paper you listed above as it's main reference. The paper I wrote was based on evaluating human-computer interaction and user experience/enjoyment in games. My main conclusion was that models like the one in the paper above are most useful if geared toward a certain game and not any game in general. I added HCI to the evaluation because it can directly effect the user experience/enjoyment.

The developers need to figure out what they think is fun about their game, create questions with ratings centered around these fun parts, and get testers to test the game and fill out a questionnaire with these questions.

I personally think, you don't see more academic research in user experience/user enjoyment in games because the paper above goes about as deep I feel you can go without biometric data. I personally think biometric testing in academia won't add any value to actual industry because it WON'T be replicated. Developers, IMO, are not going to wire people up to see if their games are fun.
> 1 votes

# Answer
I don't believe this is a possible goal. The "entertainment value" of something is very subjective.

If you know exactly what reaction you want to invoke, sure you might use biometrics to measure this. If you want to excite the player, you might measure their pulse, adrenaline levels, etc, but measuring a physical reaction isn't the same as how enjoyable it is.

Besides, what makes one game enjoyable may be completely different than what makes another game enjoyable. Some games are meant to be contemplative and somewhat depressing, rather than pulse-pounding action.

One of the video series I watch, Errant Signal did an excellent video on this topic of what makes games enjoyable called An Aimless Diatribe On Fun. It does a great job answering this question and I believe addresses some of the academic research into the area.

A good quote from that video:

> "Think of what it does to a potentially vibrant and expressive artform when out of the gate the expectations for its emtional range is just this *one little thing*. It's tantamount to saying "Pictures need to be pretty" or that "Music needs to be catchy", but some of the most powerful pictures of all time are anything but pretty, and some of the most powerful music ever composed defies toe-tapping catchiness".
> 0 votes

---
Tags: game-design
---


# Question
Title: Updating code at runtime, without recompiling
Hey guys i was wondering if anyone has come across a c++ ide that you can actively play test the updates without having to recompile all the code.

# Answer
Strictly speaking, there's at least one IDE than allows changing code while debugging: it's Visual Studio (the Edit and Continue feature Tetrad mentions in comment). Looks like GDB (GCC's debugger) has a similar feature as well.

However I've never seen this feature used in a real game project. The reason for this is probably that the changes allowed by Edit and Continue are too limited to be practical. You might be able to change one or two variables, but there's no way you'll be able to add a complete function, for instance.

The usual way of having code that can be changed at runtime is to build a scripting engine on top of the C++ code (Lua, UnrealScript, Boo, etc.). It's typically used for gameplay code that is subject to frequent changes and isn't performance-critical .

A less frequent way is to compile this kind of code in separate DLLs. This allows to recompile and reload them when the code changes, see for instance this question on GDSE or this blog for more details. This is probably more experimental, but I personally like the idea of keeping the whole code base in one language.
> 6 votes

# Answer
Easiest solution without recompiling ALL of the code, aside from VS's awesome edit/continue, is to keep the part your working on in a separate library,(DLL, etc depending on your platform), and just rebuild that part. Include a command in your primary/host app to unload and reload the library in question. You'll still have to recompile the lib, but not the host app.

Of course, whether this will work depends on the OS and how you reference the library, but its another option beyond IDE-specific features.

Or: if what you're really looking for is runtime tweaking/debugging, I'd look at integrating IronPython, Lua, etc, and exposing the objects in question to the script engine. This is easier in .NET than C++, but I've seen it done both ways.

If you're using an Entity/Component architecture, there are precedents for providing an "Object Inspector" window/CLI to dump component field values (to a grid or stdout), and let you change those values on the fly via a simple REPL. ID's console is a good example of this. In an older project, I redirected stdin/stdout to a stream that was read per-frame and displayed on screen. It was kind of neat in that, anywhere in the code, I could write to stdout and the text would be executed as script.
> 3 votes

# Answer
Ch (formerly Cint) allows you to do this.

You could also probably hook something up with Clang and the LLVM JIT, which I believe is what Ch is doing.

Technically you must always recompile, but it's definitely possible for that compilation to be automatic and for the changes to be made to a running program in some limited circumstances.

It'll never be perfect or even close to how a dynamic language can do this, though. C++ assumes a lot about how things are laid out in memory. Changing the fields of a struct for instance would require not only updating the code, but also updating all the copies of that struct in memory. Since C/C++ supports unions and other means of "hiding" objects in memory (void pointers, buffers, etc.) it is impossible for the compiler to do this, and so runtime changes of code will generally require restarting any application.

It's worth pointing out you can do something similar yourself. Allow your game engine to serialize/deserialize its game state on demand. Move all the logic you're expecting to be changing frequently to a DLL, which you should load dynamically. You are then capable of saving your game state to a buffer or disk, unloading the current logic DLL, loading in a new one, and restoring your game state. You can then also hook up your own editor that allows you to seamlessly compile some C++ source and do the reload dance with the click of a single "Test Changes" button.

Engines like Unity do something similar for C#, and it appears that Unreal Engine 4 will do it for C++. I know a couple smaller game-specific engines that have done similar things. Takes some work to set up, but can be worth it if you're using C++ as your primary game logic language instead of a scripting language.
> 2 votes

# Answer
An alternative suggestion is to expose the necessary API's to a scripting language such as LUA (World of Warcraft) which allows you to update things on the fly without recompiling your core code as often.
> 1 votes

# Answer
I recall reading of a technique where the game engine tracked changes to a C source file and parsed the numeric values - that let the developers tweak the constants without recompile. I can't remember what they called this technique so I can't easily find the article.

However, this sounds to me like too much of a hassle when you could, for example, move the constants to a LUA file and use that instead.
> 0 votes

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


# Question
Title: What's the best way to keep battle log in a browser based game written in PHP?
I've searched for it, but I couldn't find any question about this.

I'm working on a game where PvP fights are possible. The game is written in PHP/MySQL.

What I want to implement is to save all the actions of users in the fight (hits, misses, critical hits etc.).

However, I couldn't decide **how** and **where** to keep them. As an array, xml file, in json format; in a log file, in the database or in a separate cookie? Which way is the best practice?

# Answer
If you're using MySQL as your persistence layer, I don't see any reason why you wouldn't keep your combat logs there.

The amount of sense that your listed options make goes about like this:

* Array: 0% (array in what? "array" is a data structure, not a persistence mechanism)
* XML file: 50%
* JSON file: 30%
* Log file: 20% (have fun finding the records you want again)
* Database: 100%
* Cookie: -1000% (!?!?)
> 3 votes

# Answer
**Where** to keep that kind of data is obvious: use a database. **How** to keep it depends on a number of factors. Here are some use cases that come to mind:

**Scenario 1**: You only have to be able to reprint rendered combat messages

In this case, you could actually save strings in your database:

```
table combatmessages
    id
    combat_id
    combatant_id
    message

```

You can think of message as a cached version of an already rendered combat message. If reprinting rendered combat messages is all you want, this allows you to skip the rendering process, which makes data retrieval and processing very fast. The downside is that reprinting combat messages is really ALL you can do. (Unless you want to process the message, which would be insane.) Also, you have to store each message twice, for it reads differently for the two players involved in a battle.

**Scenario 2**: You want to access battle actions to calculate things

In this case, the structure of your database will be more complicated, for it has to represent combat action data, not just some lousy string. On the plus side, you can actually do interesting stuff with it. The design of your database will depend on what kind of stuff you want to do, and on how complex your battles are. If you are only talking about 500 or so players playing at the same time, I'd suggest to err on the side of flexibility and just store every bit of information that you can.

In order to store battle actions and events like the ones you posted, a table structure like this might suffice:

```
table battle
    id
    combatant1_id
    combatant2_id
    winner_id
    combatant1_startHP (in order to be able to calculate remaining HPs in messages)
    combatant2_startHP

table battlelog
    id
    battle_id
    turn (if your combat system makes use of turns)
    subject_id (null if there is no actor or receiver of this battle message,
                e.g. if it's a global message to both combatants)
    action_id (or action enum ('attack','backstab','missile'), if there is only
               a limited, predefined set of possible actions.
               null if the record stores an event that is not the direct result of an action)
    target_id (null if there is no target)
    resultHit enum('miss', 'hit', 'critical hit', null)
    resultDamage int
    resultWound bool (or enum if there are several types of wounds)
    resultSkillImprovement_skill_id
    resultSkillImprovement_points int

```

Note that storing combat data instead of rendered battle messages is also necessary if you want to be able to render battle messages in different ways, for example by using different message templates in different contexts. Another advantage is that you don't have to save battle messages twice anymore; one battlelog record provides enough information to render battlelog messages for both players.

Note also that this design is a trade-off between a simple table structure and easy data storage/retrieval on the one hand and high data efficiency and level of normalization on the other. If your game knows 200 different results of battle events, then storing 199 null values in each battlelog record would no longer be the preferred route to take.
> 1 votes

---
Tags: rpg, php
---


title: Game resources storing

text:
# Question
Title: Game resources storing
I'm working on a browser-based RTS, and we are targeting 10k+ users with multiple towns per user.

I have the following table `townresources` in which I store every resource value for every town ID:

```
CREATE TABLE IF NOT EXISTS `townresources` (
  `townResourcesId` int(10) NOT NULL AUTO_INCREMENT,
  `userId` int(10) NOT NULL,
  `resourceId` int(10) NOT NULL,
  `townId` int(10) NOT NULL,
  `balance` decimal(8,2) NOT NULL,
  `resourceRate` decimal(6,2) NOT NULL,
  `lastUpdate` datetime NOT NULL,
  PRIMARY KEY (`resourceId`,`townId`,`townResourcesId`,`userId`),
  KEY `townResources_userId_users_userId` (`userId`),
  KEY `townResources_townId_towns_townId` (`townId`),
  KEY `townResourcesId` (`townResourcesId`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='Stores Town Resources' AUTO_INCREMENT=9;

```

I'm a bit reserved about performance impact for a large amount of users. I'm thinking about moving the balance for resources to the towns table, and the general value of a resource to a PHP file. Is this a better option?

# Answer
Performance wise: Yes. If you have a column for the various balances in one row, you will improve performance when looking up this information. Looking up and returning 1 row is faster than returning X rows and generating the totals from the compiled results.

Example:

```
CREATE TABLE town_totals (
   town_id  int(10),
   iron     decimal(8,2),
   gold     decimal(8,2),
   wood     decimal(8,2),
...etc
);

```

Design Wise: Academic DB design will say that this isn't a good thing to do. A design like this does become a problem if you are changing values or creating a large number of them. For resources, this likely isn't an issue... but take a look at say units instead. As you will likely be adding various units over the life of the game, having to change a similar table every time to create a new "totals" can be painful from a maintenance perspective, especially when the alternative allows you to create new options without touching your tables at all.
> 1 votes

# Answer
I would suggest to add balances and resource rates to the table for towns and make the general values of the resources part of your PHP code base. Resource balances for a given town seem to be the kind of information that you will have to retrieve regularly, so improving the performance of this data retrieval is desirable.

This suggestion is based on a number of assumptions, though:

* **The types of resources that a town can produce are very limited, an integral part of the game design, and thus unlikely to change.**

If you are building a trading empire style of game, with lots of different goods and resources, then normalization (as in Academic DB design) will make your software easier to maintain and extend. This is way more important than speed improvements for some queries.
* **Resources are not updated very often.**

Your current database design allows for very efficient resource update commands, so your decision is also a speed and memory trade-off. I suggest to conduct two comparative benchmarks: the first to find out how much faster data retrieval of resource information is with resource information being stored in the town table, the second to find out how much faster updating resource information is with your current design. Then multiply the speed difference in the resource information retrieval test with the number of players that are online at peak times, and again with the average number of such data retrievals per player per minute. Do the same for the differences in the updating resource test by multiplying the speed difference with the number of such update commands per minute at peak times. Comparing the two resulting numbers should give you some insight on which database design performs better overall. Do both benchmarks with mock data for 10,000 players and as many towns as you would expect from an active player base.
> 0 votes

---
Tags: php, sql
---


# Question
Title: How do I go about hiring Level Designers from the Modding community?
The company I'm working for is growing fast and there's been talk of trying to hire level designers from the modding community. My question is simply, where would be good places to look for this, and how would we go about vetting who to hire?

Does anyone have any experience of this?

# Answer
> 4 votes
Ultimately, I think a lot of people end up going to various game forums and posting requests for applicants. However I think that doing it this way leads to a lot of unqualified applicants and can waste a lot of your HR persons time sifting through them.

When my company started hiring game developers and modelers, they ended up going to several game conventions (GDC is the only one I can think of off hand) and setting up a booth. That way, you know the people there are more serious about wanting a job and not just replying on a forum. Also, the potential applicants know that your company is serious about hiring devs.

# Answer
> 2 votes
DesuraNet got a hiring/jobs section on their websites which is shared across ModDB & IndieDB. (Those are quite big developer/modding community's)

I saw Mojang there a while ago hiring some artists for Minecraft too.

# Answer
> 0 votes
My company has decided to run a level design competition with our lead designer offering insight at each stage as to why certain things were good, and what is done in the industry etc.. sort of like a mini-masterclass but driven by several little design challenges. The runners-up get a load of swag and the winners get interviewed - the best of which will start working for us.

---
Tags: game-industry, level-design, jobs, hiring
---