title: Trying to generate some unique numbers

text:
# Question
Title: Trying to generate some unique numbers
I find impossible to get this code to work! I want to generate 10 numbers that are unique, but despite all I change, I get duplictates of numbers in the array! Would really preciate some help to solve this or improve the code, but I want it simple and easy to understand! Thanks!

```
int[] randomNumbers = new int[10];

        Random random = new Random();

        int index = 0;

        do
        {
            int randomNum = random.Next(0, 10);
            if (index == 0)
            {
                randomNumbers[0] = randomNum;
                index++;
            }

            else
            {
                for (int i = 0; i < randomNumbers.Length; i++)
                {
                    if (randomNumbers[i] == randomNum)
                        break;
                    else
                    {
                        randomNumbers[index] = randomNum;
                        index++;
                        break;
                    }
                }
            }
        }
        while (index <= 9);

        System.Console.WriteLine("Array ");
        foreach (int num in randomNumbers)
            System.Console.Write(num + " ");

```

# Answer
> 2 votes
random.next(0, 10) returns a random number between 0 and 10. It can happen, that it returns the same number multiple times in a row and it is not guaranteed, that you get every number between 0 and 10 exactly one time, when you call it 10 times.

What you want is a list of numbers, every number is unique, between 0 and 9 (or 1 and 10). A possible solution to this would be something like this:

```
//Create the list of numbers you want
var list = new List<int>();
for(var x = 0; x < 10; x++)
{
    list.Add(x);
}

var random = new Random();
//Prepare randomized list
var randomizedList = new List<int>();
while(list.Length > 0)
{
    //Pick random index in the range of the ordered list
    var index = random.Next(0, list.Length);

    //Put the number from the random index in the randomized list
    randomizedList.Add(list[index]);

    //Remove the number from the original list
    list.RemoveAt(index);
}

```

Explained in words, this is what you do:

1. Create the list with all the numbers, that your final list should contain
2. Create a second empty list.
3. Enter a loop. The loop continues, as long as the ordered list still has numbers in it.

1. Pick a random index between 0 and list.Length
    2. Put this random number in the randomized list
    3. Remove the item at the index position from the ordered list.

Like this you create the set of numbers you want to have in your randomized list and then always pick a random entry from the ordered list. With this technique, you can also achieve, that certain values occur multiple time in the list.

I'm not sure if my code compiles against c#, as I currently do not have visual studio running here, but I think the code should be mostly correct.

# Answer
> 7 votes
The simplest way to have this is to have an array of the numbers you want (i.e. 1-10) and use a random shuffling algorithm.

The Fisher-Yates shuffle is the easiest way to do this.

EDIT:

Here's a link to a C# implementation: http://www.dotnetperls.com/fisher-yates-shuffle

# Answer
> 1 votes
Something like this?

```
const int maxNumbers = 10;
List<int> numbers = new List<int>(maxNumbers);
for (int i = 0; i < maxNumbers; i++)
{
    numbers.Add(i);
}
Random r = new Random();
while (numbers.Count > 0)
{
    int index = r.Next(numbers.Count);
    Console.Write("{0} ", numbers[index]);
    numbers.RemoveAt(index);
}
Console.WriteLine();

```

**Edit:** For any random numbers:

```
const int maxNumbers = 10;
const int biggestNumbers = 10000;
List<int> numbers = new List<int>(maxNumbers);
Random r = new Random();
while (numbers.Count < maxNumbers)
{
    int index = r.Next(biggestNumbers);
    if (numbers.IndexOf(index) < 0)
    {
        numbers.Add(index);
        Console.Write("{0} ", index);
    }
}
Console.WriteLine();

```

---
Tags: c#, random
---


# Question
Title: How can I randomly generate arbitrary "rules" for a creative card game
My friends and I in school play this interesting card game, which we call 'the game without rules' (ironically, of course). The game is like this: in the beginning of a school year, we start with one rule: you have to lay a card that is higher. Everything else is not allowed and the one who is the first to have no more cards, wins.

When only one person remains with cards, the game ends. At that point, the winner can define a new rule, such as "on a seven, you have to play a lower card instead of a higher card". This makes the game harder and harder as we play on. Every time a person breaks a rule, he/she is given an extra card.

Now my idea was to make a computer program out of this and let them create new rules, so that would be pretty funny to see what combinations they come up with. Every time a 'computer' defines a new rule, they don't tell the others, so they have to figure out by trial and error.

Well at this point I am stuck. How can I let the computer define new rules and can someone write an example for me? And in what language should I do it?

# Answer
You're probably going to have to break down what kind of rules you guys have created in the past and just let the computer pick one at random and fill in the specific details. As far as your high level goals this isn't going to make it really "funny" since you'll know all the possible outcomes, but it will make the game possible.

So for example, the "lay a card that is higher" (aside: what happens if somebody puts down a king/ace and everybody has cards left?), you could generalize that to be a rule about ordering and the program could pick between higher cards only or lower cards only. Or you could make a rule about alternating colors, or whatever.

The real interesting part is going to be the conditionals that change the rules. Again, you figure out the base parts and then go from there. Like "on card X (defined by suit/number/color) change the existing rule". Or "after X subsequent cards (same color/suit/number, ascending/descending numbers, etc) change the rule".

I doubt you'll be able to come up with something truly random since how you're going to have to define how you interact with the cards and how to express that to the player in a way that makes sense.
> 4 votes

# Answer
Similar to what Tetrad has said, the rules will likely have to be pre-defined. However, you can go a step further and break the rules into parts which can be combined to form new rules.

For example, you can have a rule grid like the following, where you **select one item from each column to form a rule**:

Of course you can adapt this to whatever rules you've made up in the past. Keep in mind that this is just one type of "rule sentence" table. You can have multiple tables to choose from when creating a new rule, all with a different sentence format.

*Note: For the above table, you can have a rule that says that columns 3 and 5 must be different entities.*
> 3 votes

# Answer
I agree with Byte56 and Tetrad that you should think about elements of rules that can then be combined to form a variety of complex rules.

In terms of implementation, you could give this design a try:

* GameState holds a game state as specified by a stack of cards that were already played (especially the card that lies on top), the cards that each player holds, the remaining cards in the deck, the active player, and the order of players.
* Condition (abstract) represents conditions that the game accounts for. Use polymorphism to define CardCondition (like "heart", "jack", "red", "higher than 9"), DeckCondition ("less than 10 remaining cards in the deck"), and PlayerCondition ("at least one player with only one card left"). Each type of Condition is to be applied to a different part of GameState. Also, choose a data structure similar to data structures that can represent logical or algebraic expressions, so that you can combine atomic conditions to more complex conditions by joining them together with AND, OR, etc.
* Rule represents a game rule by holding a Condition and a Filter. Condition can be checked against a given GameState, indicating whether or not the GameState satisfies the Condition. Filter is a CardCondition that can be applied to a given set of cards, filtering the set so that only cards remain which satisfy the CardCondition. If the Condition for applying the Rule is met by the current GameState, then apply the Filter to the cards of the player to see which ones can be played.
* RuleStack holds all the Rules of the game. It also provides a method that returns the Rule that is relevant for a given GameState. In order to determine which Rule is relevant, RuleStack passes the GameState to each Rule in turn, beginning with the Rule that was created first. If GameState satisfies the Condition of that Rule, that Rule becomes the relevant one to be returned (or to be replaced by the next and younger Rule that also applies to GameState). (Based on your examples, I assume that only one rule is to be applied in any given situation. Return several Rules \[with a slightly different algorithm\] if several Rules can apply to a given GameState.\]

This allows you to

* check if a player did a legitimate move by asking RuleStack for the relevant Rule given GameState and apply the Filter Condition of that Rule to the card that the player wants to play.
* find out a computer player's next move by filtering its available cards through the Filter of the relevant Rule (given GameState) and choosing one of the remaining cards.
* create new Rules by defining a RuleFactory with different sets of Conditions (as in Byte56's answer), which can be combined recursively to create new complex rules.

Regarding your question as to how you can represent cards: Watch the first couple of lectures of this free udacity programming course: http://www.udacity.com/view#Course/cs212/CourseRev/apr2012
> 0 votes

---
Tags: c++, java, php
---


# Question
Title: Why don't developers these days make the classic 2D games?
I just finished playing Commandos 1 and Desperados: DOA. As you know these two games are entirely 2D with beautiful maps. This genre **Stealth strategy games** is somewhere lost in the market and people usually don't see many games like these two.

Now, I tried further parts of Commandos and Desperados but they have shifted to 3D maps unlike the original, classical one? This **new** design hasn't been much popular in the market. This is not my personal opinion but many people on sites like IGN, youtube say the same thing.

Why don't the developers stick to the original 2D maps and scenes which created ripples in the market, which was loved by all. Why do they shift to 3D always because I've seen this happening in almost all strategy games like AOE etc

# Answer
Main stream developers go where the market takes them. 3D was (or thought to be) desired for games, so they made their games 3D. It has to do with market analysis for what's wanted along with what's cheaper.

Hindsight is 20/20. I imagine if you were a gamer back when these games first came out and someone asked, "What about this 2D game you love, **in 3D?!**" you may have been really excited. You didn't know of any downsides, you had no idea the 3D would take away from the art.

Just see how it's happening with 3D movies today. I expect 10 years from now people will wonder why they even bothered making movies in 3D when 2D was much better. (Though I'm bias because I think that now). Further, I imagine some people today wonder why they ever switched from 2D art to 3D art in cartoons. And why did they ever switch from real life special effects to CG effects? Money and market analysis.
> 1 votes

---
Tags: rpg, strategy
---


# Question
Title: Calculation of a fight with many entities
User A can have many entities

A Entity is a object that has properties such as health, attack, defence, agility, stamina, etcetera.

When User A want to attack User B with x entities I am looking for the algorithm/equation to calculate the fight. I have brought some couple of ideas but they all have some pros and cons and I am not sure which one I would use or If I should use one of them at all?

**Model A** \- The while loop Basically I would get all the entities that is suppose to fight in this battle, I would assign each of them (objects) in to an array (the User A array and the User B array). Now I would simply loop through until one of the array is empty. Inside the loop I would let one of the User attack first, calculate the result (If the Entity has 0 health, remove it) and then let the next User attack back, calculate the result (If the Entity has 0 health, remove it) And then continue.

The Pros with Model A would be that every entity would be battling and instead of just do a calculation on all around there would be a justice fight.

The Cons To loop through like 10 entities would be fine but what about 1000-2000 entities? And how about the different strength of each entity I mean how could I decide which entity should battle against what entity? This could be just an sorted array (weakest \> to strongest) But then I couldn't have like different types of entities is better against a different type of entity, meaning like a Gunner wouldn't mean anything If it met a Swordsman even though a Gunner would most likely win such in a real fight.

**Model B** The idea of Model B is quite simple basically calculate all the attributes (properties) together and then If User A army has greater stats than User B army, User A army would win the fight. The Pros with this is it easy on the performance. The Cons are "Which entities would survive?" And it would basically be, the one with greatest army would win. You wouldn't even have a "chance" to win.

**Model B B** Then I started to think what If I take the concept of Model B calculate the stat and then I have a battle between just those two single entities. This way User B actually would have a chance ( a small one but the possibility to win) even though the User A has greater army (better stats). The Cons are yet again, How would I know which entities that would survive on the winning team?

The answer I am looking for to this question is what Model should I use? And how would I solve the cons in that particular Model. Or should I use some completely different model (idea) ? *(If possible please provide some php pseudo code)*

# Answer
> 5 votes
I've recently used both models A and B in two different games. Neptune's Pride and Jupiter Folly.

In both games, when two armies meet, they fight until one army remains.

In Neptune's Pride, players take turns inflicting damage on one another until one of the armies is dead. In Jupiter's Folly, the strength of the armies is simply compared and some die rolls are added to the result, the stronger army wins. The winner suffers damage equal to the loser strength.

For your games you must ask yourself, how well the player will be able to guess the outcome of the battle. Will they be able to calculate their odds in their head before the battle? Will they be able to understand the math that is going on under the hood.

Instead of thinking about the problem in terms of how you code it, you should think about what the player will see and think.

**Model B will be much easier for the player to understand.**

# Answer
> 2 votes
Here is a basic version of a battle model that combines some features of A and B with WWII troop organization, while at the same time avoiding a problem you mentioned, namely that "a Gunner wouldn't mean anything if it met a Swordsman even though a Gunner would most likely win in a real fight."

Define the interface of battle entities in ITroop. Implement ITroop with GunnerTroop, SwordmenTroop, etc., with different behaviors for finding targets, applying damage, reacting to battle events, etc.

Now implement the Composite design pattern in order to branch together several leaf like entities to form Troops of different sizes. Define Group (up to 10 single entities), Platoon (up to 4 Groups), Company (up to four Platoons), Battalion (up to 5 Companies), and Regiment (up to 8 Battalions). In each of these classes, define a couple of additional constants and methods:

```
const damageMultiplier
const damageFullRanks
isFull()

```

as well as any new behavior that troops of that type and troop size have:

```
reactToOnBeingTargeted()
reactToBeginSecondBattleRound()

```

The battle then follows these steps:

* Before the fight starts, the entities of both armies are grouped by entity types. 10 entities of the same type and army are put into Groups (of the given entity type), until no more Groups can be filled that way. Groups of the same type are grouped together to form Companies, Companies of the same type to form Battalions, etc. For example, if you have 180 gunners, this process would result in one Company with 1 full Platoon and another half-full Platoon. Register the Company in the player's Army data structure as the biggest Troop of gunners available to that player. Also register any event handlers that Groups, Platoons, and Companies of gunners might have.
* Cycle through the combat rounds and tell different entity types to act.
* When it's player A's gunner's turn to shoot, look for the biggest Troop of gunners available to player A. Let's say that it is the Company described above. The Company now looks for a target in the other player's army; let's say that it looks for cavalry troops. Again, the biggest troop of that type is returned as the target.
* Having found a suitable target, the Company determines how much damage it does. This is a two-step process:
    + Company calls its own isFull() method to see if the ranks of the Company are fully filled. If this is the case, return the constant damageFullRanks. This is a precalculated number that prevents large troops from causing a myriad of requests down the composite tree.
    + If Company is not fully filled, cycle through its members and ask for their damage. In this case, the first request goes to the full Platoon of gunners, which returns its damageFullRanks constant. The second request goes to the half-full Platoon, which in turns asks its members for their damage values. When all damage values are collected, Company applies the constant damageMultiplier to the sum of the damage of all its members.
* Apply the damage at the target. If the troop size of the target drops because of the attack, register the new and smaller sized Troop object as the new biggest troop of that kind for that player.

This model has a couple of advantages:

* Each unit fights. If there are other units of this type, it types within a Troop, but if not, it fights alone.
* You don't need to handle the battle behavior of 2,000 individual objects. You might HAVE that many objects, but the number of attacks to be calculated is much lower, because the composite pattern groups many entities into bigger units.
* damageMultipliers should be \> 1, thus providing an incentive to build bigger armies. This represents the advantage that bigger armies have over smaller ones without aggregating all the units into a single number which is then compared to a single number of the opponent. The damageMultipliers \> 1 should, of course, be thematically motivated somehow, for example by saying that a Company of Swordmen carries a banner that boosts morale, and that a Battalion has a commander who makes them more efficient.
* Having different ITroop implementations for different unit types allows for game mechanics that require careful army composition (instead of just adding more junk to the pile in order to make the numbers bigger). For example, information about an enemy's army composition could be exploited by 'countering' his composition.
* Another way to add a size bonus AND strategic depth to army composition is to define custom event listeners for different troop types and sizes. For example, each Company of gunners might have a canon that can do something fancy against another entity type once per battle to counter that entity type, or Groups of fairies might fight alongside Groups of Paladines, proving some kind of protection in case of certain onBeingAttacked events.
* Having an OO design approach generally adds flexibility for whatever you might want to add to your game later on.

# Answer
> 1 votes
If a user is sending just 5 soldiers than of course there's no point in dividing in even smaller groups, let alone using different simulation models. But you also considered a case where there are 2000 entities in play.

If you want something even barely realistic, 2000 soldiers won't be attacking as a single mass of people (or stats). They would be divided in groups, possibly with different game stats.

Instead of just doing 500 VS 200 (where the 500 would win) or 500+rnd VS 200+rnd (where the 200 could have a slight probability of winning, depending on the rnd factor) you could define groups of (pick a number) 25 units and compare groupA1 VS groupB1 etc. And, to improve the randomness, making it groupA1+rnd VS groupB1+rnd.

Defining a formula to find out if a soldier is taken out of combat shouldn't be that hard at that point.

I.E: Let's say there's a 25 vs 20 situation. The 25 should have better probability of winning (and surviving). Random1 = random\[0,5\] and Random2 = \[0,5\]

So if it's Value1+Random1 VS Value2+Random2, the result could be 25 VS 25. Then you could say that taken\_out1 = (group2/group1)+X taken\_out2 = (group1/group2)+X

Where X is another random value (probably related to the other variables)

Of course all the numbers are just made up in a couple of minutes, but they should provide a decent enough example.

That way each group has a probability of winning, and a 2000 soldiers army would have 80 groups (that is, a maximum of 80 check to do).

That would make the battle both less predictable and less heavy to simulate, and also give you a way to modify your simulation later (adding specific unit types, or terrain variables, etc).

---
Tags: game-design, php
---


# Question
Title: Finding line of best fit demarcating national borders
Per title, what algorithms are available for defining borders for states (or other entities) based on certain nodes in the world (eg. cities or armies) with varying weights?

For example, there are three non-equidistant city-states and a bunch of military vehicles of varying strength nearby representing each city-states' military power. I would like to be able to draw a border that accounts for the fact city-state A has a huge great army on their outskirts, projecting their power outward.

Ideally the optimal algorithm would be able to calculate a series of connected lines with a high level of precision for multiple states and a large number of nodes (let's say three dozen, for the sake of argument). Speed isn't too much of a factor, since the results would be cached and I'd need to apply a function to 'curve' it anyway.

# Answer
One solution that springs to mind is creating a Voronoi diagram. This will, in the original form, only take into account distance (although you can use different norms like manhattan or euclidean) which is not exactly what you want. I think though that you could tweak the algorithm to use some other heuristic like the one you mention, taking into account armies, economics or other factors.
> 4 votes

---
Tags: algorithm
---


# Question
Title: Shape Centers as Vectors: Local space or World space?
Given a shape (any shape) in a 2D world where all positions, locations, and centers are two dimensional vectors, should the shape's center be described in local space or world space?

EXAMPLE:

World Space center of a Rectangle: Position: (100, 100); Dimensions: (200, 200); Center: (200, 200);

Local Space center of a Rectangle: Position: (200, 200); Dimensions: (100, 200); Center: (50, 100);

World Space center of a Circle: Position: (100, 100); Dimensions: (50, 50) (diameter); Center: (100, 100);

Local Space center of a Circle: Position: (50, 50); Dimensions: (200, 200); Center: (0, 0);

# Answer
If at all possible, make a shape's center and its origin in local space be the same point. That is, describe the center in local space, but don't bother storing it—make it always (0, 0).

This is simply an attempt to reduce the number of unique spaces you have to think about. If your shape's center differs from its origin, you will probably at some point have to think about all of these:

1. world space vector from world origin to object origin;
2. world space vector from world origin to object center;
3. local space vector from object origin to object center;
4. local space vector from object origin to some other point on the object; and
5. local space vector from object center to some other point on the object.

If you make "object origin" and "object center" be the same thing, you can hopefully reduce that to 2 unique kinds of vectors (vector from world origin to object origin and vector from object origin to some other point on the object).
> 1 votes

# Answer
I assume your object's position in the world is not the same as its "center" (otherwise, if you specified the center in local coordinates it would always be the zero vector).

It all depends on your requirements, but I would imagine that specifying the "center" (whatever you define the center to be) in local coordinates would be easier since whenever your object moves you would not need to update its center vector as well.
> 0 votes

---
Tags: c++, 2d
---


# Question
Title: Good resources for learning about game architecture?
Are there any good resources for learning about game architectures? I am looking for high level overviews of different architectures. I tend to find information about the various pieces of a game such as entities, physics engines, scripting, etc but not about how to bring all of the pieces together.

As a bonus, how does the type of game influence this? For example, a platformer and an MMO would have differences.

# Answer
Game Engine Architecture by Jason Gregory is a good book in this topic. You can read it in Google Books before buying it.
> 64 votes

# Answer
My book, Game Programming Patterns, is incomplete and on hiatus, but what I have is freely available online. You may get some use out of it.
> 41 votes

# Answer
Enginuity is one of the best free tutorials on game engine design. Behold, this is not exactly what You asked for. It's a tutorial on writing a game engine down to the low level aspects - however - it's a **general purpose** engine and You might be able to derive a greatest common divisor for every game.

Just read through the introduction and stop when it becomes too detailed for Your taste ;)
> 15 votes

# Answer
Game Programming: The Express Line to Learning provides a nice, beginner-level introduction to a basic game engine structure the author calls "IDEA/ALTER":

* I – Import and initialize
* D – Display configuration
* E – Entities
* A – Action (broken into ALTER steps)
    + A – Assign values to key variables
    + L – Loop (setup main Loop)
    + T – Timer to set frame rate
    + E – Event handling
    + R - Refresh the display

The book walks through a complete example game implemented in Python/Pygame.
> 14 votes

# Answer
I can recommend the book Game Coding Complete, Mr. Mike knows a lot about Game Architecture and does a good job explaining it to the reader. I don't know about the third edition, I only have the second edition, but it was worth a read. He explains everything from Scripting to Sound, even a bit of 3D math. Not in the deepest possible detail, but good enough to dig deeper using other materials. At the end of the book he constructs a complete game utilizing everything you learned with this book.
> 7 votes

# Answer
My good friend Joel posted a talk he gave at a conference concerning the architecture he ended up using on some PS1 games. Though the talk is specific, he ends up bringing it all back to general advice about what to look for in a good architecture.

Talk is here: http://jdinolt.tumblr.com/post/756062883/hrraaah-ego-trippin-my-first-talk-at-the-igad
> 4 votes

# Answer
Not game-related, actually, but an invaluable resource for any programmer: The Pragmatic Programmer: From Journeyman to Master. It won't tell you how to write a 3D pipeline--rather, it will take you on a tour of the principles that underly good software architecture.
> 4 votes

# Answer
Jeff Plummer "A Flexible and Expandable Architecture for Electronic Games":

http://members.cox.net/jplummer/Writings/Writings.htm

Nice overview and comparisson of different Game architectures.
> 2 votes

# Answer
Scene graphs ftw. These can be used for game logic as well as rendering, and they let you really optimise your pipeline. If you're going to use them, you want to do it from the start.
> 1 votes

# Answer
I think for *overall* architectural knowledge, experience/trial/error are the main resources.

Because the overall architecture WILL change so much based on the kind of game you're writing, looking at resources/papers on entity systems/engines/scripting/etc and putting it together into something that has meaning in your own application is the best way to learn.

That said, I really like the Game Programming Gems books for going into depth on the individual components that you can use in your games, I still commonly use a lot of the ideas published in them across my professional activities, as well as in my hobby-code.
> 0 votes

# Answer
An interesting source of game-building knowledge that I recently became aware of is Penny Arcade - Extra Credits. They are in the form of short (~5 minute) weekly videos. They have covered a variety of topics, all of which are available for viewing at the above link.
> 0 votes

---
Tags: architecture
---


# Question
Title: Real-time multiplayer game server development
I'm an Android developer, and I want to start developing a real-time multiplayer game, like Pocket Legends.

Would this type of server be good for a real-time multiplayer action game - http://systembash.com/content/a-simple-java-udp-server-and-udp-client/?

I'm absolutly new to server development, so it would be great if you explaind even more about this stuff ...

# Answer
> 11 votes
I'm working on my first multiplayer game as well. It can be daunting just learning the problems specific to multiplayer, so I highly recommend that you get good at making single player ones first.

First, see if any of the game/networking engines fit your needs. For an Android game especially, starting with a well-developed toolset is almost always a good idea. Here are some of the popular ones that I know of:

If you decide to implement the networking code yourself, or if you're curious, you'll need to start learning about the best techniques. After lots of reading myself, I've found these guides to be a cut above the rest:

There are many resources available for almost anything you need to learn if you search for them.

# Answer
> -1 votes
ElectroServer is another solution you can use for Flash, Unity, native iOS and Android games. ElectroServer is Java on the server with APIs for AS3, C#, C++, Objective-C, Java, and Javascript. It's used by major companies and indies alike, and supports millions of players every month.

You can find dev resources here: http://www.electrotank.com/resources.html The resources include 50 tutorials and examples (text and video), a free 100 CCU trial version, a free forum managed by dedicated senior engineers, and several free game examples.

---
Tags: android, java, multiplayer, server
---


# Question
Title: Java collections and managing simultaneous operations / concurrency (java.util.ConcurrentModificationException)
Ok, so i have created my first "game" and it uses a lot of java's collections. for example, i have a bunch of monsters in a HashSet which sometimes gives me the fabled java.util.ConcurrentModificationException when i try to modify the HashSet.

Basically im getting these exceptions when im within a for loop and then some other part of the system find it suitable to add or remove an element to/from the collection.

My options as far as i know is:

> 1) Use a Thread Safe collection or use Collections.asSynchronizedCollection().
>
> 2) Only work on copies of the collection when looping through it.

My question thus becomes. Is there any other methods more widely deployed solutions in the gamedevelopment world that handle's these issues?

As an example, i thought ive read somewhere that queues are more heavily used instead of collections and that work is done on input and output queues. \<-- any elaboration on this would also be appreciated!

Thanks for your time!

# Answer
> 6 votes
The root of your trouble lies in the necessity to add or remove elements while iterating over collection. You should keep these things to a minimum, but sometimes it just can't be avoided.

Making copies every time you want to iterate a collection is often not an option due to performance reasons.

Now there are two possibilities: your loop and your adds|removals are either on the different threads or on the same thread.

**If it's the multithreaded case**, Tyn gave you pointers on what to do. One simple solution would be to synchronize all access to the collection, using some object as the monitor. It may be slow if your collection is large, because threads wanting to add or remove something will be blocked while waiting for iteration to complete:

```
// For loop
synchronized (lockObject)
{
    for (...) // Iterations here
}

//Now when other thread wants to add or remove something,
// it needs to synchronize too:

// Somewhere on the other thread
synchronized (lockObject)
{
    gameObjects.add(...);
}

```

You can use ConcurrentHashMap, but be prepared to face the consequences. I can remember only that its iterators sometimes reflect adds or removals occured since the iterator construction and sometimes they don't, but there should be plenty of other subtle things, maybe like "get" operation placing a memory barrier. So if you add and remove things very rarely, it may be better to use a "copy on write" approach.

Funny thing is, unless your threaded operations with objects on the loop are slow as hell (and usually they shouldn't be), it may actually be faster to keep them single-threaded. I deduced that if there is a bunch of monsters with some petty Update() functions, and you want to process their little functions on different threads, you're in for a trouble :) So keep in mind that multithreading just for the sake of it eats up your CPU with context swaps and supply you with livelocks and starvation issues here and there.

**If it's the single thread case**, then removal of the elements in the collection being iterated won't work, so there are two another options:

1. The most usable option: add a queue of objects to add|remove, and process them out of your loop.
2. If you only need to remove a current object of an iteration phase, it is possible to use an indexed collection with a for loop, and then remove current element while adjusting loop counter. Or just loop backwards.

Just for clarity, example for the first approach:

```
while ((objectToRemove = objectsToRemove.Pop()) != null)
{
    allGameObjects.Remove(objectToRemove);
}

foreach(var gameObject in allGameObjects)
{
   // process your objects here as always, but if you need to
   // add or remove an object, push it to the appropriate queue.
}

```

And example for the second approach:

```
for (int i = 0; i < allGameObjects.Count; i++)
{
   // to remove an object, do something like
   allGameObjects.RemoveAt(i--);
}

```

# Answer
> 5 votes
There is a few concepts that might help you in Java:

1. **Synchronized methods.** A method can be made synchronous by adding the `synchronized` statement to its definition. This has two effects: it is not possible that two calls on the same method of the same object instance to interleave anymore, and it guarantees that any further call will benefit of the changes made during the previous call.
More on that here: Synchronized Methods
2. **Synchronized statements.** A statement block that makes a particular object synchronous. Could be useful in your case, by synchronizing your `HashMap`.
More on that here: Intrinsic Locks and Synchronization
3. **Concurrent collections.** The `java.util.concurrent` package defines collections with atomic operations (i.e. operations that are guaranteed to be executed fully before giving time to another thread). That might help you avoiding the need of synchronization.
More on that here: Concurrent Collections
4. **There's more.** There is a lot of tools to help you dealing with concurrency issues in Java. Specialized thread wrappers like Executors, Lock objects, Atomic variables, a thread-safe PRNG, and more. All of those are described in the Java lesson on Concurrency.

In general, the Java lesson on concurrency cover all you need to know about threading and synchronization. It can be found here. It is a must-read to start dealing efficiently with this difficult problem. You'll also understand more deeply what are the issues that can come with synchronization, like deadlocks and starvation, as well as to avoid it.

I hope this helped!

# Answer
> 4 votes
Option 1 is only relevant if the problem relates to threading, and the majority of ConcurrentModificationExceptions don't. Vigil gives some useful options; there's one which he hasn't mentioned, and that's to mark objects as deleted.

In other words, you give the object a field isDeleted; you ignore deleted objects in calculations; and on one of your loops you use the `remove()` method of the `Iterator` when it returns a deleted object.

# Answer
> 1 votes
If you find yourself iterating over the set a lot more than you mutate it, there's a cool class called CopyOnWriteArraySet or CopyOnWriteArrayList that will make your life easier. It basically basically captures a 'snapshot' of the set when you start iterating, and performs any mutations (adds/removes) after iterating is complete.

---
Tags: java, design-patterns
---


# Question
Title: How can I accomplish Pokemon-style movement over tiles in java?
I'm talking about where if you press a directional key once you walk over to the adjacent tile and can't do any other actions during the walk. I can get my character to move one tile width, but my trouble is animating the walk and having the character actually walk to the next tile, rather than teleport. The research I've done has pointed me in the direction of interpolation, but I don't really understand how to get it working.

# Answer
The easiest way is to use linear interpolation (AKA lerp) over time.

Let's say you want you character to move from `posA` to `posB`. You calculate it's current position every frame from those two positions, the current time (incremented by a delta time every frame), and the wanted movement duration, as follows:

```
float t = currentTime / moveDuration
vector currentPos = posA  + (posB - posA) * t

```

This movement might feel a bit mechanical but that's a good first step, if you want to go further, look into easing functions:
> 2 votes

---
Tags: 2d, java, movement, slick
---


# Question
Title: Are there any good books for GameMaker:Studio?
I'm just wondering if there are any good books for the GameMaker:Studio software?

I want to using it to prototype my projects and will be travelling for the next few days so I thought it might be a good time to familiarize myself with it. I see that there are a ton of tutorials online, but I won't have internet for most of my travels so I'm really looking for an offline resource, thanks.

# Answer
> 1 votes
I have really enjoyed "The GameMakers Apprentice." When you finish that one, "The GameMakers Companion" goes deeper into GML.

Neither book is GameMaker studio specific, but the core functionality hasn't really changed.

# Answer
> 1 votes
A quick search on Amazon would help you out, but if you're looking for first hand opinions, the only one I've read, but do recommend is The Game Maker's Apprentice: Game Development for Beginners.

---
Tags: game-maker
---


# Question
Title: How can I set up a loading screen in Panda3D?
How would I go about using Double Buffering (to create a loading screen) in Panda3D using C++? I've searched Google and found some forums that talk about the concept of swapping buffers, but I haven't seen any that show any type of source code (specifically Panda3D/C++). I'd like to try and stay away from using pure OpenGL code and work it through Panda3D, but if I have no other choice, then I'll have to go with OpenGL coding.

# Answer
Usually 3D engines like Panda3D handle trivial details like double buffering for you automatically. You only have to start tweaking the back-buffer settings if you want things like triple-buffering.
> 2 votes

# Answer
You just need to have an image on top of everything, so you won't see new things popping up one after another.

The default Panda3d nodes for GUI/HUD are render2d, aspect2d and pixel2d. Attach an image NodePath to one of them.

Manual explains each in detail.
> 0 votes

---
Tags: c++, panda3d
---


# Question
Title: What are the properties of "position, velocity, acceleration, rotation" collectively named?
They say naming things is one of the hardest problems in computer programming. They were right.

Given the pseudocode below, what is a more appropriate name for this collection of properties? "Course", "Route", "Heading", "Orientation" all don't capture it.

```
class NewtonianStuff { // <-- Needs a better name
  vec3 position, velocity, acceleration; // <-- What is this group called
  quat rotation;
};

class SpaceShip {
    NewtonianStuff xxxxxx; // <-- What do you call that
};

```

Perhaps that collection is too abstract. What is the formal name for this collection of properties?

```
vec3 position, velocity, acceleration;

```

The best I can come up with is "PositionAndDerivatives", which doesn't really flow.

# Answer
The position and rotation (and scale) are generally referred to as the transform.

Velocity, acceleration, force, impulse, etc are usually just lumped together as "physics state" or "body" (which might also have handles to the shape of the physical object or any bounding shapes, or those might be part of a separate "collider"). I don't believe there is a formal name used in games for this collection of properties, especially as the properties used varies for each game / physics engines.
> 10 votes

# Answer
Like Sean said, position and rotation are usually referred to as the object's **transform**.

Velocity and angular velocity can be called the "**kinematic state**" or "kinematic properties" of your object.

Force, torque, and impulse can be called the "**dynamic state**" or "dynamic properties" of your object.

("Dynamics" and "kinematics" come from two sub-fields of classical mechanics that deal with motion with respect to forces and without respect to forces, respectively.)
> 10 votes

---
Tags: physics, movement, vector, terminology
---


# Question
Title: How can my "world" provide the information required to render itself?
I am writing a JavaScript game that provides a top down view of the player, to eventually create a ray caster that can render the view in faux 3D (the top down view will end up as the *mini-map*).

A while ago, I asked the question *Should actors in a game be responsible for drawing themselves?*, to which I received the suggestion of having my game objects have a draw descriptor which provides the renderer with the information required to draw it.

I have a `world` object and a `renderer` object. I am trying to do this the right way, so I gave my `world` object a `getDrawDescription()` method which returns information required to render itself.

However, it's not quite as simple as a game actor, which may return an `x` and `y` offset and an image resource. My world's data is a matrix of information about cells, each with a number that relates to a different cell/texture. It may be best to show the implementation of my two objects (and some code to work with them)...

```
var world = {
    cells: [
        [/* ... */]
    ],

    getDimensions: function() {
        return { width: this.cells[0].length, height: this.cells.length };
    },

    getDrawDescription: function() {
        return {
            type: 'cells',
            cellSize: 16,
            data: this.cells
        };
    }
};

var renderer = {
    objects: [],
    width: 0,
    height: 0,
    ctx: null,
    canvas: null,
    addObj: function(obj) {
       this.objects.push(obj);
    },
    setDimensions: function(width, height) {
        this.width = width;
        this.height = height;
    },
    setCanvas: function(canvas) {
        this.canvas = canvas;
        canvas.width = this.width;
        canvas.height = this.height;
        this.ctx = canvas.getContext("2d");
    },
    draw: function() {
        var ctx = this.ctx;
        this.objects.forEach(function(obj) {

            var drawingDescription = obj.getDrawDescription();

            switch(drawingDescription.type) {
                case 'cells':
                    var cellSize = drawingDescription.cellSize;

                    drawingDescription.data.forEach(function(row, y) {

                        row.forEach(function(cell, x) {

                            // Obviously, this is a major violation of having
                            // the object provide all the drawing info.
                            var fillStyles = {
                                0: "#ccc",
                                1: "#000",
                                2: "#776",
                                3: "#fr2",
                                4: "#f0f"
                            };

                            ctx.fillStyle = fillStyles[cell];

                            ctx.fillRect(x * cellSize, y * cellSize, cellSize, cellSize);

                        });

                    });

                    break;
            }
        });
    }
};

var game = {
    loop: function() {

        renderer.draw();

        setTimeout(this.loop.bind(this), 500);
    },

    init: function() {

        renderer.addObj(world);
        this.loop();

    }
};

document.addEventListener("DOMContentLoaded", function() {
    var dimensions = world.getDimensions();
    var description = world.getDrawDescription();

    renderer.setDimensions(dimensions.width * description.cellSize, dimensions.height * description.cellSize);
    renderer.setCanvas(document.getElementsByTagName("canvas")[0]);

    game.init();
});

```

As you can see, I wasn't sure how to provide the render with the information required to render the world. I could have a function such as `getColorById()`, but it would require the renderer to know about the world's implementation (possibly OK?) and would require a lot of function calls (maybe a function with returns an object which provides the mappings would be OK).

So, how is this typically achieved in game development? It may be a case of YAGNI, but I figure if it provides a good separation of concerns, it's a win (I'm unlikely to switch the renderer from `canvas`, though I could prove its usefulness by having it write elements with a `background-color`, for example).

I'm still fairly new to game development, so help me out if I'm doing anything wrong on a more fundamental level.

# Answer
It just so happens that I'm working on something roguelike-esque in JavaScript, and it looks like we're approaching the problem in similar ways. Here's what I'm doing:

* **GameMap**. This object knows what the entire map looks like. It's basically an array of arrays of tiles. Each cell in the array is a number, with -1 being a sentinel for "no room here". Those numbers *might* graduate to objects, but I think I won't need too many of them -- there are only so many possible types of tiles, never more than about 50 in a map.
* **TileMap**. This object knows about the viewport (which tiles are visible in the canvas at this moment based on the player's position in the world) and is responsible for making the actual draw calls. It knows how to draw a tile based on the index in the GameMap (it's the View to the GameMap's Model). It is also responsible for transforming click coordinates on the canvas into worldspace coordinates (canvas position \[250, 300\] might actually be world position \[11, 8\] depending on where the viewport is as the player walks around).
* **Canvas**. A wrapper around canvas code that knows a little bit about my drawing optimizations. Don't know that you'll need it, but it's involved in this little dance so I thought I'd include it in my explanation.

Here's how they're connected: the GameMap is synced from the server. The TileMap has an instance of GameMap and knows when the tiles are update (thanks, KnockoutJS!). It knows that it has to draw itself. The TileMap uses its instance of the Canvas object to draw the map. And voila: a drawn world.

I think you're basically on the right track, but I might make some suggestions:

* See that switch statement in your renderer? That's a sign that you might be missing some objects. Right now you might have "sprites" and "cells", but what about random particle effects, or GUI elements? Do each of those get a case statement? That'll make the switch statement kind of big. What if you separated out "the thing that knows how to draw my world" from the renderer? Then the renderer could call that thing. Even better, the draw descriptor could return the object that knows how to render it to the renderer. Make sense?
* Don't use setTimeout for your render loop, use requestAnimationFrame. That way, the player can navigate away from the window of your game and the browser will know to slow the animations down.
> 2 votes

# Answer
Normally the world renderer will get the list of tiles from the world. Then, for each tile, you can get the method or details for rendering that tile. That looks pretty close to what you have.

Renderers are expected to know about the implementation of what they're rendering. It's the other way around, where the logic of the game knows about the renderer, that is usually a bad idea.

(As for "how is this typically achieved in game development", there is no typical method.)
> 1 votes

---
Tags: javascript, rendering
---


title: Platformer movement and collisions

text:
# Question
Title: Platformer movement and collisions
I'm working on a platformer but I'm stuck at the player movement and collisions.

Right now I'm not including the grid at all in the movement, but it's time I do it. I've read this article on how to do it. But there's no real code examples just theory.

I like the second example and that's the one I'm going for. I want the movement to be smooth, and the player should be able to run in between squares from my map array. This means I have to get tile information from the array, and according to that allow/forbid my player to move in that direction. And that's where I'm stuck.

My array is a bunch of 1's and 0's right now. I know how to calculate a hitbox around the player, but how do I compare that to the array in an efficiant way?

**UPDATE:** I've been playing around with this for a while now, and the only thing I came up with is using player X and Y which is in pixels, dividing by tile size, and getting a rough estimate on the map. Then I make it an AABB by adding its width and height to get the corners.

This showed to be very unreliable though, and I would really need some help on how to structure this.

# Answer
> 1 votes
Well you have to obviously loop through tiles to see what ones are interesting the player and deal with it accordingly.

If your map is not very large it's trivial to loop through all tiles to find the collision. something like \`tiles.forEach(function(tile){})\`. Once your game and maps start to get larger this of course can be very intensive.

One solution I can think of is to only check the tiles that in the view port. Then all it becomes is a matter of finding what section your character is in and looping though only the tiles in view.

Another way would be to split your tile map into sections, so section 1 might be (0,0) to (20,20). You then determine what section the charter is and loop through only those tiles. That way you can loop through an even smaller number of tiles

# Answer
> 0 votes
I think you are on the right track. It sounds like you have two subquestions:

* How do I track the position of the player in tilespace and in viewspace?
* How do I efficiently track collisions in tilespace?

In a platformer that I wrote, my position objects had tileX and tileY fields and fineX and fineY fields to help with this exact problem. fineX and fineY were bounded from \[0, TILE\_SIZE). My physics code took these positions into account when determining what happened to objects as they moved around: first use tileX and tileY to get info from the game map, then use that in combination with fineX and fineY for drawing. I'd love to find out a better way to do this, though.

You're almost there with the collisions, too. The only optimization I might add is to "chunk up" your collision grid a bit. Your "normal" tile is TILE\_SIZE x TILE\_SIZE, right? So, your collision grid can track (TILE\_SIZE\*2) x (TILE\_SIZE\*2) chunks at a time since moust objects, even when crossing tile boundaries, will fit into that space? Maybe even TILE\_SIZE\*4 to allow for growth or quick moving objects. That way, you decrease the number of lookups to only when your object is crossing chunk boundaries.

Then again, there's a big YAGNI here. When you talk about efficiency, are you actually seeing slowdowns in your game? Modern browsers are pretty good about optimizing for you, especially around array accesses and nested function calls. Don't write too much code around this stuff, complexifying (complecting? anyway...) your object model, until you've profiled a bit or actually seen some slowdowns.

You might want to see this article about colliding AABBs as well: http://www.metanetsoftware.com/technique/tutorialA.html

---
Tags: collision-detection, javascript, html5, html-canvas
---


# Question
Title: How should I handle tiny objects in a physics engine?
I am making a 3D physics engine for throwing dice. Up until now a dice has been 1x1x1m and gravity has been 9.82 m/s^2. This of course does not look realistic as the dice will respond to everything in a way that looks a little bit slow.

To fix this I tried to just change all sizes to make a dice be about 0.02m along a side. This in turn made my inverse masses and inverse inertia matrices get very large values which lead to numerical instability.

What is the best route to handle this? Can I keep the scale up so that a dice is 1x1x1 and just change mass or size of acting forces? Or should I tweak something else?

I guess the same problem could turn up if you made a game with very large physical bodies like spaceships or something so I hope that someone has run into something similar before.

# Answer
> 1 votes
You could

* increase the gravity constant? Games often use 2 * 9.81 m/s^2. Can't remember where I read this, but games usally use none-sensical units. Whatever constants feel right (make the game fun). Using a realistic constant makes the physics seem slow and floaty.
* run the simulation at a faster rate. If you're using a fixed timestep, this will increase the rate of animation.
* use higher precision floats?

# Answer
> 4 votes
In case you are having troubles with small numerical values, I suggest that you simply scale everything down. You might even not use "real" measurment units, but just some "generic" units that only make sense inside the engine.

The first option, scaling down, would require that you use millimeters or centimeters as a base measurement unit. Your cube's dimensions wouldn't suffer from loss of precision, then.

The second solution is basically the same thing, but then you wouldn't need to think about the actual units.

Also, why don't you just change the cube's mass?

# Answer
> 2 votes
Bullet Physics library has a wiki page about scaling the physics world. This information is probably useful with other physics engines as well.

# Answer
> 0 votes
I thought I should share my final solution to the problem. Increasing the gravity constant as suggested did indeed make the dice move faster thus giving the impression of correct scale. This, however, increased issues of microbouncing. I added microcollisions which mitigated the problem although did not solve it perfectly. Note that this becomes a problem only for "small" objects, if you are having the reverse issue and want to simulate very large objects (spaceships or something like that) then you won't be getting any microbouncing problems at all and can contend with that solution.

So I found the highest level of gravity I could have without getting way too much "microbouncing". Then I used a simple shake-detection on the phone which responded to large changes from the accelerometer readings and applied impulses to all the objects when such shakes are detected. It isn't perfect but as it will set the dice moving fast when phone is shaken it will give an impression of "tiny" dice. It's a bit of a hack but it will have to do :) Here's a clip of the engine in action.

---
Tags: physics-engine
---


# Question
Title: How to efficiently manage animations and/or textures (resources) in a game?
I am using Java, particularly the Slick2D library. Seeing as this is my first game, I have no idea how I should manage the Animations and the textures in the game in a way to be both memory efficient and processing efficient.

I was wondering if I should give each and every entity I have its own animations and its own textures. Currently, the way I'm doing this is by making a limited set of images, which are then shared by the animations. These images are only created once in memory.

The animations, however, are done by creating a separate and new animation for every new entity I have.

I have also created a class specifically to handle the resources.

I was wondering if this is the correct way of doing things, or is it not memory and/or performance efficient, or should the entities with similar animations share the same single animation in memory? I find this a bit inconvenient since if I want to add a frame to a particular entity's animation, then all the entities with those animations will be affected.

Or is it perhaps the other way around, and I should even make new textures for every single entity, from which I create new animations. The main reason I can think of for doing this is the effects I might want to do later on on a frame in an animation without affecting the other animations that might use this texture.

My second question is, I'm letting the resource class decide which animation it should send to an entity, depending on the state it's in. For example, it will see if the player is walking left, and give it the according animations, if he's walking right, then the right animation.

I wonder if it's more correct to let the Player class decide which animation it will request from the resource class.

This is my resource class:

```
    package blackhorn;
    import org.newdawn.slick.Animation;
    import org.newdawn.slick.Image;
    import org.newdawn.slick.SlickException;

    public final class CAnimations {
    // Player walking left
    Image playerWL1;
    Image playerWL2;
    Image playerWL3;
    Image[] playerWL;
    // Player walking right
    Image playerWR1;
    Image playerWR2;
    Image playerWR3;
    Image[] playerWR;
    // Player standing
    Image[] playerS;
    // Enemy standing
    Image[] enemyS;

    //Ground
    Image[] groundS;

    //Bullet
    Image[] bulletS;

    public void init() throws SlickException {
          playerWL1 = new Image("data/playerWL1.png");
          playerWL2 = new Image("data/playerWL2.png");
          playerWL3 = new Image("data/playerWL3.png");
          playerWR1 = new Image("data/playerWR1.png");
          playerWR2 = new Image("data/playerWR2.png");
          playerWR3 = new Image("data/playerWR3.png");
          playerS = new Image[] {new Image("data/playerS1.png")};
          enemyS = new Image[] {new Image("data/enemyS1.png")};
          groundS = new Image[] {new Image("data/groundS.png")};
          bulletS = new Image[] {new Image("data/bulletS.png")};
          playerWL = new Image[] { playerWL2, playerWL1, playerWL3, playerWL1 };
          playerWR = new Image[] { playerWR2, playerWR1, playerWR3, playerWR1 };
    }

    public void getCurrentAnimation(Player player) {
        if(player.getSideSpeed()<0)
                    player.setCurrentAnimation(new Animation(playerWL, 500));
              else if(player.getSideSpeed()>0)
                        player.setCurrentAnimation(new Animation(playerWR, 500));
                    else if(player.getSideSpeed()==0)
                            player.setCurrentAnimation(new Animation(playerS, 500));
    }

    public void getCurrentAnimation(Enemy enemy) {
            enemy.setCurrentAnimation(new Animation(enemyS, 500));
    }

    public void getCurrentAnimation(Ground ground) {
            ground.setCurrentAnimation(new Animation(groundS, 500));
    }

    public void getCurrentAnimation(Bullet bullet) {
            bullet.setCurrentAnimation(new Animation(bulletS, 500));
    }

    }

```

And this is my player class.

```
    public class Player extends Character {
    private boolean hasFired = false;

    public Player(float x, float y) {
            super(x, y, 1, 1, 1, 1, 0, CConstants.ROTATION_RIGHT, CConstants.PLAYER_JUMP_SPEED, CConstants.PLAYER_WEIGHT);
    }

    public void init(GameContainer container) throws SlickException {
            MainGameState.animationList.getCurrentAnimation(this);
            super.init(container);
    }

    public void update(GameContainer container, int delta) throws SlickException {
            super.update(container, delta);
    }

    public void render(GameContainer gc, Graphics g) throws SlickException {
            MainGameState.animationList.getCurrentAnimation(this);  //animationList is the CAnimation class instance
            super.render(gc, g);
    }

```

The full code is on Github for those who are interested.

# Answer
First of all, don't listen to people who say that Java is a bad language for making games in. Everybody should start their game development career by using the tools you're already familiar with.

It seems your animations are entangled with your images, which makes it difficult to share animations between objects.

I propose that your animations should not *own* the images it is made out of, but only hold references to their images.

You should let the `Animation` class hold references to frames in the form of indices. For example, "playerWL1.png", "playerWL2.png" and "playerWL3.png" becomes 0, 1 and 2.

When rendering the animation, it looks up the images in some kind of `ResourceManager` using the indices. This allows you to share frames between animations and gives you a way to make animations unique for each object, depending on which frames are used.

This also makes it easier to customize the rendering per animation. For example, you could have a standard animation colored in white for an enemy and use color replacement to color the enemies red or blue.
> 5 votes

# Answer
Generally, I think you are optimizing in the wrong place. Animations are cheap, it's just one reference to an image + the time needed to run one frame. I think keeping them separate for each entity would be a great help in fine-tuning game content later. It's not even about adding or removing frames, actually tuning the time for each frame is more important.

As a side note, I'd recommend using sprite sheets for animations - keep the whole animation (or several animations) in a single image file, like this. It'll make editing whole spritesets easier (depends on your image editing software, though, some make it easy to export each frame as a separate file).

Regarding your second question, like all 'pretty code' it kinda depends on the size of the project. It makes more senses that the entity chooses the animation and that the `ResourceManager` is only a 'lower layer' (especially since more complex entities, notably the player entity, can have complex animation systems), but don't waste time fixing it until it becomes a problem :)
> 1 votes

---
Tags: 2d, java, animation, slick, resource-management
---


title: Do SDL surfaces get reused?

text:
# Question
Title: Do SDL surfaces get reused?
In SDL, lets say I'm rendering text to a surface. Then I blit it with the scene's main surface to form a composite image to flip.

I get the text surface into a class-level member called 'messageSurface':

```
messageSurface = TTF_RenderText_Solid( ..... );

```

So, do I have to call

```
SDL_FreeSurface(messageSurface);

```

on every loop to prevent memory leaks? Or will SDL "reuse" the old surface the next time around?

# Answer
According to documentation here:

http://www.libsdl.org/projects/SDL\_ttf/docs/SDL\_ttf\_43.html

the pointer returned is to a new surface. So yes, you need to free the surface to avoid memory leaks.

Offhand, that seems a rather odd API design. Instead, I would have expected you to pass an allocated surface to the function.
> 1 votes

---
Tags: sdl
---


# Question
Title: Stopping an object after applying an impulse or force?
I'm having a small issue where after applying an impulse or force it is impossible to actually get an object to stop, i.e. a velocity of zero.

This code is run every `1 / 60` of a second:

```
void RigidBody::Update(double deltaTime) {

    double mass = GetMass();
    //If static body, do nothing.
    if(Math::IsEqual(mass, 0.0)) return;

    Vector2D F;
    Vector2D total_forces = std::accumulate(_curState._forces.begin(), _curState._forces.end(), Vector2D());
    Vector2D total_impulses = std::accumulate(_curState._impulses.begin(), _curState._impulses.end(), Vector2D());
    F = _curState._gravity + total_forces + total_impulses;
    _curState.ClearImpulses();
    SetAcceleration(F / mass);
    SetVelocity(GetVelocity() + GetAcceleration() * deltaTime);
    SetPosition(GetPosition() + GetVelocity() * deltaTime);

}

RigidBody::SetAcceleration(const Vector2D& acceleration) {
    _prevState.SetAcceleration(_curState._acceleration);
    _curState.SetAcceleration(acceleration);
}
//Similar for RigidBody::SetVelocity and RigidBody::SetPosition...

```

If I apply an impulse, say (-1.0, 0.0), the object's acceleration changes by -0.012 or -0.011 instantaneously and only once then reverts to (0.0, 0.0), which then changes the velocity to (-0.012/-0.011, 0.0). Equal and opposite changes in acceleration causes rounding errors to accumulate to the point where the velocity will never be zero and the object will never stop.

Similarly, if I apply a force, (-1.0, 0.0), the object's acceleration changes to (-1.0, 0.0), equal and opposite forces applied so the acceleration changes to (0.0, 0.0) works but the velocity changes so minutely that again, the object will never stop. (The closest I've ever gotten it was (0.009, 0.0) )

# Answer
When you add the impulse to the force, perhaps it might be better to use the `force = impulse / dTime` formula (There was a question on these topics). Apart from that, when running a simulation, the null vector is almost never numerically encountered. That's quite bad because, in reality, the objects stop at a macro level, whereas they never (or never should) on the quantum level.

Game Physics engines cheat their way around this numerical issue and make up for two major issues: update almost stable objects like crazy even they are not changing their states that much and have the objects vibrate like electrons in a dielectric structure. They do this with a technique that's quite obvious to a programmer: when the dynamic states of the objects allow it and the kinematics are also almost stable (a threshold for velocities and forces that is), the objects are put in a "sleep"mode. Only when they're perturbed beyond this threshold the engine starts managing their updates again and actually moves them. That's why a box thrown against a wall will eventually stop on the ground and not continue to bounce indefinitely near the surface of contact.

Here's a post on the Bullet Forums that explains the concept nicely.
> 3 votes

---
Tags: c++, physics, physics-engine
---


title: Making online battles take time

text:
# Question
Title: Making online battles take time
Let's say I have an account on an MMORTS and I send my 10,000 strong army to a location on the map. I then shut off my computer.

Another player gives orders to his 10,000 strong army to walk to the same location and attack anyone located there. He then turn off his computer.

After 30 minutes when his 10,000 guys arrive at the scene the battle begins. Now killing 10,000 guys where both armies are using the same skill and weapon might take several hours.

Let's say I turn my computer on again and find the raging battle and that I only have 4500 soldiers left, so I decide to pull my army back.

This type of ongoing battle happens on the server. How could this be accomplished? I'm thinking JavaScript / PHP technologies. I'm thinking that there should be some sort of dice system to each attack so it could end with one side winning with 1500 men left even if they started with equal amount. Is there some sort of clever logic that would not require 20,000 calculations per frame to calculate each hit and and parry for every unit?

# Answer
> 1 votes
It looks like you might be asking two different questions, so I'll answer them each separately (though one may influence the other).

Taking Time: What you want is that the battle actually executes over a longer period of time, rather than just as quickly as can be calculated. This gives the user the impression that something is actually hapenning and allows them to change their orders during the battle. Here a timeslicing approach makes sense. Presumable you will be hosting several battles on the same server, so you'd probably need to do this anyway.

In this approach each of your active games represents an object on the server. Now your server will poll each active game at a fixed interval. Say every 30s: you can adjust upward to lower total load and downward to improve user real-time feedback. Each interval you will simply step each active game by 30s (scaled to the world time).

Calculations: Trying to represent 10000 units as 10000 objects is simply not going to be possible. Perhaps if you write in C++ and have a very optmized algorithm you could do it, but you still wouldn't be able to support many active games on one server. Instead what strategy games tend to do is lump together units into groups. So you have 500 rifleman, 2500 infinitry, 20 artillery, etc. That is, reduce your battle to a small number of actual objectds. These cumulative objects can then fight each other in turn.

In the simplest model, say for infinitry, you could simply multiple per unit HP times the number of units to get one virtual infinity unit with a really high HP, and also a really high firing power. This is perhaps not ideal, but it is a decent logical starting point. Here you don't really do pure die roling anymore, you'll be using statistical projections (easier than it sounds). So if each unit has only a 10% chance to hit, the logical group will simply do 10% of its total damage each round. Again, simplified, but gives you the basic idea.

# Answer
> 0 votes
I see two problems here - optimizing the battle on the server and allowing the player to view and change the battle before it is finished.

First things first - optimizing the battles. You need to design combat in rounds, and roll dices for each unit separately within each round, giving you 20000 computations per round - each unit attacks one other unit and defends from one attack. You can design the combat system so that it will last a small amount of rounds, for instance a 100 for 10000-unit armies. If you find your battles take longer, you could make them more 'bloody' using various techniques - make combat between opponents more random (higher standard deviation), penalize fighting between the same 2 units for more than 2 rounds etc. This should give you a required total number of 'computations' in the millions per one battle of 10000 units, which seems sensible. Moreover, it is easily breakable down into smaller chunks or parallelizable from the other server work.

A different approach you could try is using Lancherster's laws for mathematically modelling battles.

Once you have that, you can look at your second problem differently. You can precompute battles and store them as a series of states, each state corresponding to a combat round. Displaying battles is, like many things in games, interpolation - you know in what timeframe each round should occur, so when displaying the battle at any given time you can choose the two nearest precalculated rounds and show to the player a dynamically-changing state that is somewhere in-between. You don't have to be precise; nobody is interested in exact numbers. If the player decides to retreat, you can confirm the action instantly and send it to the server, which will recalculate part of the battle - from the current (or next) frame onwards. If you give the player instant feedback, he will accept that the action is non-instantious and that there might be more casualties that the last displayed number (it's believable that receiving an order and retreating take time). Other events - reinforcements, change of tactics, spells/abilities etc - can all be handled in the same way, by recalculating the battle from the given moment onwards.

In essence, what I'm saying is discretize the battle, store it, interpolate for the purposes of showing it to the player and recalculate when a player decision is made.

---
Tags: architecture, algorithm, multiplayer, mmo, mmorts
---


# Question
Title: I'm looking for a C++/OpenGL/SDL game engine tutorial
I have a decent knowledge of SDL, OpenGL and FMOD. I am looking for a recent tutorial or book on the basics of making a game engine. Most of the book and tutorial I found are using old dead library like glut and glaux or simply outdated like NeHe tutorial.

The one thing I would really like to understand is the structure and how everything is linked together.

I do not want to use a tutorial to copy it or anything else like that but simply to understand the structure behind it. No server stuff.

I would really appreciate if the tutorial/book use OpenGL and SDL because I really love to use them.

# Answer
> 0 votes
I honestly think that a book on a game engine can be only worst for a beginner, i also read some some of this books and most of them are wroted with just 1 platform in mind, without focusing on the language, and in the end if you learn how to initialize 1 context for your rendering you are blessed.

I think that you have to focus on your language, simply because the fact that you can master or not your library of choice only depends on how good you are with that language, if you can't say what a library does, it's probably your fault about some missing concepts about the language.

The architecture and the design of your application also heavily relies on your know-how about the choosen language.

Most of the books about rendering techniques are good for teaching you what *to expect* from a certain context or a certain use of the hardware, what your application really *will do* only depends on what your write in the code and a book about a game engine can only be a bad refactoring of some design patterns oriented to rendering and you end up using only this patterns with a closed mind.

Do yourself a favor and buy a book about advanced techniques with the C++ rather than one about a pseudo game engine design, or buy a book that can give you a broad view about the rendering world without focusing on the programming libraries at all like this one.

# Answer
> 0 votes
Given that you have already made a working game and are comfortable with sdl and opengl I'd rank you as more than just a beginner, although I'm sure compared to all the things that you want to know it certainly feels that way!

The book I'm recommending is not language specific (though the code examples are in c++ they are easy to follow), not Graphics API specific (though it does mention opengl and directx in areas where there are implementation differences) and is NOT a programming guide (in that it does not show how to program the things it explains).

What is does, and does *brilliantly*, is to explain techniques people have used in game engine development for real games of different styles. It provides tonnes of links to websites and discussions to help you further your knowledge in specific areas and it (and for me is the important part) fires the imagination.

What I mean by that last one is that as you read how other people have done things and the kind of techniques they used, you *will* automatically start thinking about what you could do with these ideas and how they fit into the projects you are excited about.

Here's the link for the book: http://www.amazon.co.uk/Game-Engine-Architecture-Jason-Gregory/dp/1568814135/

I hope it helps you, I find myself picking it up often just to flick through and grab ideas for what I want to play around with next!

---
Tags: opengl, c++, architecture, sdl, education
---


# Question
Title: There is something like the BigO notation for the GPU world and the programmable pipeline?
I find difficult to study the performance of a shader or a series of statement probably because the OpenGL is a state machine and also the execution is in parallel and not serialized like a standard X86 CPU I/O.

There is something that i can use for this? The BigO notation is based on the concept of growth, but with a state machine there is nothing growing, how i can approach the study of this kind of code/algorithm?

# Answer
I think there's a bit of confusion going on here. Let me just quote the Wikipedia article:

> In computer science, big O notation is used to classify algorithms by how they respond (e.g., in their processing time or working space requirements) to changes in input size.

In other words, it just measures how "good" an **algorithm** is, independently from the platform, library, API, or weather forecast.

I'll give you an example: let's say you want to use an algorithm to do some motion blur: it could be O(n), n being the number of pixels to process. If you write a **program** for the CPU, or a parallelized version running on the GPU thanks to OpenGL (whatever you think OpenGL is), it doesn't change the fact that your **algorithm** is still O(n).

Now some algorithms are parallel by nature, and and a parallel program will of course run faster than the sequential equivqlent, but this has **nothing to do** with the Big O notation. So to summarize, the lowest order (Big O) your algorithm is the better, and if it's a parallel algorithm, then it's even better.

Check this question on Stack Overflow if my prose isn't convincing enough: Are algorithms rated on the big-o notation affected by parallelism?. Or this blog post, for more details.
> 4 votes

# Answer
Usually you just look at differentials. Yes, OpenGL has a lot of state, but that doesn't matter here.

Usually you are doing something per pixel or per vertex. Usually that operation can happen in parallel among the available GPU cores.

So if you are doing Phong shading, it will get slower as the window resolution increases, or faster as the core count increases.

Usually only things O(N^2) benefit from GPGPU computing as it brings N cores. Thus on a GPU you aim for `N^2 / N = N` and the like.

I am not articulating things clearly, but GPGPU computing tries to bring N cores. Where as in classical Big O notation you had a single core. Let the number of cores be `K`

`N^2 / K` so with CPU thinking that would still be `N^2`. The aim of GPGPUs is to treat that like `N` things to do per core.

So then you have to consider what `N` is. Is it pixels? Vertexes? Faces? Tip: What shader is it in? is usually the answer.

Then for each Pixel you have too look at what is happening. Say you have `L` lights for each `N` Pixels. Then you have `L`*`N` complexity

Given all that, not everything can be done in parallel, in which case you can't use all `N` cores.
> 2 votes

# Answer
The BigO notation is just a way to display **results** \- what you are really looking for is a different **machine-model**. Every processor is slightly different. For example, some have different L1/L2 caches, some can't do branching well, while others blaze through small branches with conditional instructions. This is why you do your performance analysis on a simplified model, which is oblivious to the details and makes your results applicable to a wider rage of machines.

Usually, for single threaded CPU algorithms, the RAM model, or some variation of it, is used. Most theoretical proofs (e.g. those about NP-completeness) are usually using a turing machine.

For massively-parallel architectures, such as GPUs, a PRAM can be used reasonably well. But there are also more specialized models such as this model.
> 1 votes

---
Tags: opengl, algorithm, pipeline
---


title: Debugging Shader Code?

text:
# Question
Title: Debugging Shader Code?
I'm writing a game engine, and when I use a perspective camera I get a black screen. I am not going to ask exactly why this is because there would be a lot of code to share and, frankly, I think that's a bit petty a question even to bother you all with.

The trouble is that I don't know how to debug it. All that changes is my projection matrix, and if my projection matrix looks fine, I don't know why it doesn't work. Ideally I'd print out the values of various things as the shader did its calculations, but GLSL inconveniently doesn't have a printf() function.

So my question is: how do I debug my problem? The only thing I can think of is checking as many values as I can client-side and then programming by permutation, but I've done that and gotten nowhere. Is there a way I can see what's happening in the video card? Is there a completely different technique I could be using?

I'm using GLSL version 420 (and features specific to that version), so I don't think that glslDevil is an option, considering that it was last updated in 2010.

**EDIT**

I managed to solve my problem through some completely unrelated debugging.

# Answer
You can also use a program like glIntercept, which is like PIX but then for OpenGL. Next to intercepting and logging all calls it also let's you display shader usage and edit the shaders at run time. This last option (editing the shaders at runtime) could be extremely helpful when debugging because you can keep editing in parts until something goes wrong and you can quickly debug a value by outputting a color.

http://code.google.com/p/glintercept/
> 2 votes

# Answer
Although I am not sure, NVIDIA Nsight should be able to debug Shaders, at least I think it supported GLSL in some previous version (that you should be able to find). It integrates quite OK with Visual Studio, is not easy but has loads of useful things, but in the older versions you needed 2 machines with a GPU each to debug shaders through a network (while the latest version says it allows "local" debugging). Also, check Shader Designer \[2\] which seems to be an useful IDE (but lacking GLSL debugging).

\[1\] http://developer.nvidia.com/content/nvidia-nsight-visual-studio-edition

\[2\] http://www.opengl.org/sdk/tools/ShaderDesigner/
> 4 votes

# Answer
Unfortunately debugging opengl is not easy. Here are things that I found useful:

* use glGetError after every call
* try to use the new debug extension (ARB\_debug\_???)
* use gDebugger to see what's drawn on the screen after each call
* use apitrace to see what happens after each opengl command
* modify your shader to output different colors based on the current input and try to understand why it shows a certain color
* disable every opengl functionality that limits drawing capabilities: scissor test, depth test, backface culling, etc.
> 1 votes

# Answer
Personally I still use RenderMonkey. However it's not entirely suitable for this exact question because it's only a facade of a real app and therefore has some odd limitations. It's well out of support but I've just not found anything better for debugging GLSL.
> 1 votes

---
Tags: shaders, glsl, graphics-programming, debugging
---


# Question
Title: Calculate the angle between two 3d vectors: Function always returns 89.1-89.9
I have my own 2d game and I am attempting to calculate the angle between 2 GameObjects.

**My Problem:** My function that is meant to calculate the angle(direction) between 2 Vector3's doesn't appear to be correctly calculating the angle. It always returns a value thats between 89.1 and 89.9, its never any other value.

What am I doing wrong? Can you help me to get my function to correctly calculate the angle between 2 Vector3's?

```
float getAngle(Vector3 p1, Vector3 p2) {

    // If p1 or p2 == Vector3.zero then this funciton wont work. What shd I do in this case?

    float coefI  = p1.x * p2.x;
    float coefJ  = p1.y * p2.y;
    float coefK  = p1.z * p2.z;
    float scalar = coefI + coefJ + coefK;
    float magnitude1 = p1.sqrMagnitude;
    float magnitude2 = p2.sqrMagnitude;

    Debug.Log (System.String.Format ("{0}, {1}, {2}, {3}, {4}, {5}", coefI, coefJ, coefK, scalar, magnitude1, magnitude2));
    return (Mathf.Acos ( scalar / (magnitude1 * magnitude2) ) * Mathf.Rad2Deg); // Always returns between 89.1 and 89.9 for some reason
}

void Update() {
    Debug.Log( getAngle (Input.mousePosition, transform.position) );
}

```

# Answer
`sqrMagnitude` is the vector length squared, but you need the vector lengths. Simple fix:

```
return (Mathf.Acos ( scalar / Mathf.Sqrt (magnitude1 * magnitude2) ) * Mathf.Rad2Deg);

```

Of course you could just use Unity's angle calculation function: http://docs.unity3d.com/Documentation/ScriptReference/Vector3.Angle.html
> 3 votes

---
Tags: 2d, 3d, unity, trigonometry
---


title: 3D Modeling Software for Programmer

text:
# Question
Title: 3D Modeling Software for Programmer
I've recently learned how to make games for Unity3d, and now I want to start making games! I can't wait to start!

However, before I can make 3D games, I need to learn 3D modeling for character design, level design, and some animation.

What is the easiest 3D modeling software, compatible with Unity3d? I do not want to spend too much time learning the software. From what I've heard, Blender is a bit complicated to use. Maya and 3dsMax seem very powerful.

Could someone point me in the right direction? I don't want to spend a lot of time learning. I know its not that easy, but you guys have experience, you guys probably know out of all which one is easier and powerful. Could you recommend a software?

Many Thanks!

# Answer
> 5 votes
There is no single "best" 3D Modelling software. But being a hobbyist, and a complete newbie: I'd go with **Blender**

You have tons of resources, and it's completely **free**, in both senses. It's also multiplatform, so you can easily use it if you use GNU/Linux or Mac OS X.

It has it's own 3D game engine, and you can script it with Python, it's probably the best option for a programmer.

PS: And no, it's not that complicated ;)

# Answer
> 1 votes
I like 3DS Max, but when I have to choose $4k versus free, I will use Blender.

---
Tags: unity, models, blender
---


title: Deferred Rendering and Normal Mapping

text:
# Question
Title: Deferred Rendering and Normal Mapping
I'm working on a deferred renderer and need a bit of help getting normal maps working. What I've been doing with them so far is just multiplying the normal texture with the object normals (gl\_NormalMatrix * gl\_Normal). That appears to be wrong.

I just need someone to explain how I can add the normal map the the normal gbuffer.

The offending line:

```
    vec3 normal = Normal * texture2D(normalTexture, gl_TexCoord[0]).rgb;

```

Edit: I managed to get it working :)

**Solution:**

```
vec3 Normal = normalize(gl_NormalMatrix * gl_Normal);
vec3 Tangent = normalize(gl_NormalMatrix[0]);
vec3 Binormal = normalize(gl_NormalMatrix[1]);
mat3 tangentToWorld = mat3(Tangent.x, Binormal.x, Normal.x,
                           Tangent.y, Binormal.y, Normal.y,
                           Tangent.z, Binormal.z, Normal.z);

```

and

```
vec3 normal = (texture2D(normalTexture, gl_TexCoord[0]).rgb * 2.0 - 1.0) * tangentToWorld;

```

# Answer
> 5 votes
Right, normal mapping isn't done by componentwise multiplying the object normal and the texture normal. They're vectors, and that operation doesn't make geometric sense for vectors.

For the standard way of doing normal mapping - tangent-space normal maps - the idea is to construct a 3x3 tangent-to-world matrix at each fragment and transform the texture normal using this matrix. The matrix is constructed using the geometric vertex normal as well as per-vertex tangent and bitangent vectors constructed from the UV mapping.

There are plenty of articles about how to do this online, and it has nothing to do with deferred shading; normal mapping works the same way whether you're doing deferred or not.

---
Tags: opengl, glsl, deferred-rendering, normal-mapping
---


# Question
Title: Doesn't multiple inheritance solve all problems that entity systems do?
The question is pretty self explaining: doesn't multiple inheritance solve all the problems that entity systems also solve?

I just remembered a term called "multiple inheritance", and that seems to solve a lot of bloating problems that classical inheritance imposed.

# Answer
No, multiple inheritance does not solve all the same problems that entity systems do: entity systems and multiple inheritance are two very different things. You can build an entity system with or without multiple inheritance and similarly you can utilize multiple inheritance without building an entity system.

Traditionally, component-focused entity systems are developed because of a desire to move away from heavy inheritance in any form, aiming instead for composition. There is sufficient literature and discussion elsewhere on this adage, for example on programmers SE or SO itself, and it the larger question of *why* to prefer composition is sort of off-topic for game development. In short, however, it's an approach that tends to lend itself to improved mutability and maintainability.
> 10 votes

# Answer
Josh's answer is awesome, but I'd like to add:

One of the coolest features of Entity/Component is the data-driven way in which every "thing" in your game is created and managed. From what I've seen, once you have a nice library of component types and systems created, you can build just about anything with minimal code modifications. (Note: **minimal != 0**)

By defining your game in terms of behavior, and giving yourself the ability to modify those behaviors on the fly - at runtime, during initialization by loading them from a script or database, etc. - you open up an entire world of new possibilities. Want to see why your shadows don't land where you'd expect? Add a camera/POV component to your light.

Entity/component lets you build anything you want, as long as you've created the blocks.

Also, multiple inheritance causes the same problem as single inheritance. When you add an attribute or behavior in the hierarchy, it propagates. As long as you're making deep hierarchies, you'll run into situations where you're carrying unnecessary weight, duplicating code, or resolving conflicts. Most of that can be avoided when you imagine your game as data.

I've just started playing with this in the past few weeks, but I'm impressed at how simple things have become. It's not a silver bullet - I've run across a few cases where attaching a lambda to a component was the cleanest and most expedient way to solve a problem - but it's a pretty great pattern, if you can call it that.

On a slightly related note: one of the big, boring maintenance generators in data-centric applications (websites, etc.) is mapping hierarchical objects into relational databases. We've got lots of nifty solutions around, but they're ultimately all hacks designed to flatten hierarchies. Instead of building your model so that it serves the purpose of the application, you wind up compromising between an effective hierarchy and a logical relational representation. I've been toying with the idea of rebuilding a pretty large hierarchy in one of my apps as an entity/component system - ditch the hierarchy and make the database the Gold Standard for the rest of the implementation - and it's promising.

When you integrate capabilities like dynamic code generation/code caching that can address performance issues, you wind up with a fast, flexible, logical architecture that might just realize the reusable code goal of OOP in a much, much better way.
> 2 votes

---
Tags: software-engineering, entity-system, oop, inheritance
---


title: Transforming bounding spheres

text:
# Question
Title: Transforming bounding spheres
When testing bounding spheres as part of the collision detection process, I'm using this method:

```
    public static BoundingSphere TransformBoundingSphere(Matrix m, BoundingSphere b)
    {
        var center = b.Center;
        var edge = b.Center + Vector3.Right * b.Radius;

        var worldCenter = Vector3.Transform(center, m);
        var worldEdge = Vector3.Transform(edge, m);

        return new BoundingSphere(worldCenter, (worldEdge - worldCenter).Length());
    }

```

... to get a sphere in world coordinates (where `m` is a world matrix for the object encompassed by the original sphere).

(Yes, I'm aware that this relies on uniform scaling.)

This is obvious, reliable and easy, but is there a better way?

# Answer
If the scaling is uniform and it is a known quantity, why not simply multiply b.Radius by the known scale. This will save cpu cycles by not having to perform the 2nd Vector3.Transform and a square root in the .Length() call

```
public static BoundingSphere TransformBoundingSphere(Matrix m, BoundingSphere b)
{
    var worldCenter = Vector3.Transform(b.Center, m);

    return new BoundingSphere(worldCenter, b.Radius * myUniformScale);
}

```
> 2 votes

# Answer
If you are sure your has a uniform scale and no skew components, then the non-translation part of the matrix can be expressed as M\_33 = R * (s * I), where R is the an orthogonal rotation matrix, and s is the uniform scale. This is vaguely annoying so solve, but in 3d comes out to be:

```
scale_x = sqrt(m00^2 + m01^2 +m02^2);
// scale_y = sqrt(m10^2 + m11^2 +m12^2);
// scale_z = sqrt(m20^2 + m21^2 +m22^2);
// Assert(scale_x == scale_y == scale_z);
newRadius = b.radius * scale_x;

```

For transforms for game objects (that tend to have requirements like 'uniform scale'), it's often easier to store object transforms in their components, and compute the full matrix when necessary, as opposed to storing the full matrix and then having to extract the components.

```
struct Transform
{
   Vector3 translation;
   Quaternion rotation;
   float scale;

   Matrix44 ToMatrix44();
};

```

This form also assures the transform has the appropriate form and epsilon-ish errors don't sneak in, while maintaining composability.
> 6 votes

---
Tags: c#, transformation, bounding-spheres
---


# Question
Title: Access vertex data stored in VBO in the shader
If I wanted to store extra data in a VBO for skinning (indices for indexing into an array of matrices of bones and floats for applying weights to those bones) How would I go about accessing that data in GLSL? I already know how to put the data in the buffer, interleaved with the rest of the data.

For example I want each vertex for a model to contain:

```
Vec3 position;
Vec3 normal;
Vec4 color;
Vec2 texCoords;
int boneCount;
int[3] boneIndex;
float[3] boneWeight;

```

Then drawing like:

```
bind(vertexBufferID);
glVertexPointer(3, GL11.GL_FLOAT, stridePlus, 0 * 4);
glNormalPointer(GL11.GL_FLOAT, stridePlus, 3 * 4);
glColorPointer(4, GL11.GL_FLOAT, stridePlus, (3 + 3) * 4);
glTexCoordPointer(2, GL11.GL_FLOAT, stridePlus, (3 + 3 + 4) * 4);
glVertexPointer(7, GL11.GL_FLOAT, stridePlus, (3 + 3 + 4 + 2) * 4);
glDrawArrays(GL11.GL_TRIANGLES, 0, VPNCTEnd);

```

Then in my vertex shader I want:

```
 //Get indices of bones
 //Get weights of bones
 //Get bone transforms
 //for each bone transform, apply it to gl_Position at the specified weight

```

What is the GLSL required for the last part of the process? It seems like I need to set a attribute pointer to the data somehow, but I'm not sure where to do that when the data is stored in the VBO.

# Answer
First of all, you probably want to use `glVertexAttribPointer` on the application side to specify all the components, including the bone stuff, rather than the deprecated glVertexPointer and friends. Something like:

```
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, stride, 0 * 4);  // Position
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, stride, 3 * 4);  // Normals
// etc.
glVertexAttribPointer(4, 3, GL_INT, GL_FALSE, stride, (3 + 3 + 4 + 2) * 4);  // Bone indices
glVertexAttribPointer(5, 3, GL_FLOAT, GL_FALSE, stride, (3 + 3 + 4 + 2 + 3) * 4);  // Bone weights

```

You don't need a separate attribute for the bone count, since you can just zero the weights of unused slots (and set the index to 0 or something). The first argument to `glVertexAttribPointer` is the attribute index, and each attribute can store up to 4 values.

You'll also need to use `glEnableVertexAttribArray` to tell OpenGL which attributes you're using.

In the GLSL shader, you then access these by declaring them as `attribute` variables, like:

```
attribute vec3 Position;
attribute vec3 Normal;
// etc.
attribute vec3 BoneIndices;
attribute vec3 BoneWeights;

```

Finally, you can control which variables are mapped to which attribute by using `glBindAttribLocation`. You'd insert a bunch of these calls before linking the shader, which will tell OpenGL the desired correspondence between the variables and the attribute indices used in the `glVertexAttribPointer` calls. (There are also other ways to set up this mapping; a more in-depth discussion is at this StackOverflow question.)
> 7 votes

---
Tags: opengl, java, shaders, glsl
---