# Question
Title: Why is my collision resolution failing on the corners?
I'm tearing my hair out trying to work out how to handle my collision resolution at the corners of the rectangles that I'm colliding with.

The code that I'm working with is:

```
class Player(object):
    def move(self):
        # Calculate velocity based on gravity, etc
        # ...

        # Check collisions
        for obj in self.controller.collidable():
            sides = self.get_intersect(obj)

            if sides & TOP:
                self.mover.vy = 0
                self.mover.y = obj.coord.y + obj.size.y
            elif sides & BOTTOM:
                self.mover.vy = 0
                self.mover.y = obj.coord.y - self.size.y
            elif sides & LEFT:
                self.mover.vx = 0
                self.mover.x = obj.coord.x - self.size.x
            elif sides & RIGHT:
                self.mover.vx = 0
                self.mover.x = obj.coord.x + obj.size.x

        self.coord.x = self.mover.x
        self.coord.y = self.mover.y
        self.velocity.x = self.mover.vx
        self.velocity.y = self.mover.vy

    def is_intersecting(self, other):
        return (
            (
                self.coord.x + self.size.x > other.coord.x
                and
                self.coord.x < other.coord.x + other.size.x
            )
            and
            (
                self.coord.y + self.size.y > other.coord.y
                and
                self.coord.y < other.coord.y + other.size.y
            )
        )

    def get_intersect(self, other):
        if not self.is_intersecting(other):
            return 0

        pos = 0

        # Are we overlapping the bottom edge?
        if self.coord.y < other.coord.y < (self.coord.y + self.size.y) > other.coord.y:
            pos |= BOTTOM
        # Are we overlapping the top edge?
        if self.coord.y < (other.coord.y + other.size.y) < (self.coord.y + self.size.y):
            pos |= TOP

        # Are we overlapping the left edge?
        if self.coord.x < other.coord.x < (self.coord.x + self.size.x):
            pos |= LEFT
        # Are we overlapping the right edge?
        if self.coord.x < (other.coord.x + other.size.x) < (self.coord.x + self.size.x):
            pos |= RIGHT

        if pos == 0:
            pos = INSIDE

        return pos

```

The problem I'm experiencing is during vertical movement. If you push into a wall and jump, as you reach the top corner, it will push you vertically. This is due to the `sides & TOP` being the first check. Moving the horizontal checks first fixes this when jumping up, but then falling onto a corner moves the player horizontally.

I've tried doing checking based on what the horizontal/vertical velocities are, but this falls apart, since the vertical velocity is always non-zero due to gravity (and is corrected by this check if standing on a platform). Any other answers I've found fail to take this into account.

# Answer
> 2 votes
Maybe this:

```
       elif sides & LEFT:

```

Should actually be this:

```
       if sides & LEFT:

```

Otherwise the left/right branches are never visited when there is a top/bottom collision.

The first part of the `get_intersect` tests also seem incorrect. This is what would make sense to me:

```
    # Are we overlapping the bottom edge?
    if self.coord.y < (other.coord.y + other.size.y) < (self.coord.y + self.size.y):
        pos |= BOTTOM
    # Are we overlapping the top edge?
    if self.coord.y < other.coord.y < (self.coord.y + self.size.y):
        pos |= TOP

```

# Answer
> 2 votes
I managed to fix this by using the qualifying the top and bottom checks with statements checking for vertical movement:

```
if self.mover.vy <= 0 and sides & primatives.TOP:
    self.mover.vy = 0
    self.mover.y = obj.coord.y + obj.size.y
elif self.mover.vy >= 0 and sides & primatives.BOTTOM:
    self.mover.vy = 0
    self.mover.y = obj.coord.y - self.size.y

```

---
Tags: 2d, platformer, collision-resolution
---


title: How to get a game done?

text:
# Question
Title: How to get a game done?
My problem is, whenever I start programming a clone of a game (for practice) or my own game or some other problem I stop somewhere in the middle of the development, because I lost interest in it.

How do you keep up the interest in developing a game, or developing in general?

# Answer
> 29 votes
As a designer, I tend to think of people as collections of stats and variables. When you pose your question, I can easily picture \[Pong\_Dev\_Interest\] decreasing and \[Spa\_Inv\_Dev\_Interest\] increasing. When the difference between the two is greater than \[Dev\_Project\_Inertia\] (somewhat related to \[Dev\_Completion\_Desire\]), activity on \[Pong\_Dev\] halts and \[Spa\_Inv\_Dev\] starts.

In English: You fail to complete the project because your raw desire to see a finished product is overridden by your lack of interest in the current project. If you *really* want to finish one, the only solution is to pick one (I'd go with your pong clone) and *finish it*. Say to yourself "Self, I know that maybe I could have refined that clone some more but gosh darn it sure feels good to kick a project out the door". Then keep working.

When you are bored, keep working. When it's going great, keep working. When it's falling to crap, keep working! Persevere! Be the Little Dev That Could! I believe in you!

Ahem. Got a bit overexuberant there. But you get the drift.

I am following my own advice daily. I got my environment and actors working, built in my win and loss conditions and created the objects the Player will use. I'm basically ready to start doing some level design and my interest tanked. But I do some every day. *Every* day. One day I will be done.

And it will feel so goooooood.

# Answer
> 12 votes
I always ask myself the same question and there are a couple of things you can do to motivate yourself (a lot of them already posted here). What works well for me is something I heard at one of the Indie Talks at this year's GDC, I think it was the guy making the Monaco game :-)

First, find a project that's well in your line of experience. I.e. don't start out to make a FPS if you don't even know the basics of OpenGL/DirectX. (unless you're using a game engine but that's not the point here ;-))

Then, make yourself a list of things to do and milestones you like to achieve, so you always know where to go. The TODOs is the important part. **Define your tasks such that each task can easily be done on a day or in a couple of hours**. So when you start out coding, designing, modeling etc. you already see the light at the end of the tunnel. Nothing is more depressing than designing and coding your big Game Engine for a month without getting nearer to the finishing line. Break down big tasks into smaller ones. Finishing a task quickly is really rewarding and keeps you going. For example, this was my task list for a small space shooter game at one time :

* Sound Effects
* Music
* Remodel Ship
* Remodel Rockets
* Colission Detection between shots and player/enemy
* Make enemies shoot
* Title Screen
* Score/Lives/Energy Whatever Overlay

All these tasks were easy to do and once they work in the game, you can iterate on those areas and polish them.

And hey, I finished a small game. It's not pretty but it's basically done which was really rewarding in the end :-)

# Answer
> 3 votes
You have to identify the problem before you can solve it. Why do you lose interest?

For me, it usually happens because I am spending so much time on the framework, and after weeks, I couldn't even get a single gameplay element up.

One way I find to improve my motivation is to do iterative prototyping, or some form of Test Driven Development. Usually that involves automating test cases, but as games are graphics intensive, you can't automate screens and animations as tests, but your game logic could be automated.

For the parts which can't be automated, basically I'll plan a couple of milestones for the game. Milestone 1 probably would be render a sprite on the screen and get WASD to work, for example. Gradually, I will add more features, and refactor.

It's a form of divide and conquer. Break into small chuncks, work on the one you are comfortable with, then integrate. Rinse and repeat. Eventually you may see a better way of re-arranging stuff, and you can refactor your code. It's messy not to have an architecture up front, but usually when getting started in programming it's hard to visualize the architecture till you have some years of experience.

# Answer
> 2 votes
I try to find some easier part to make. Like if I can't figure out how to make something or don't wan't to, I shift gears and model or write a shader, etc.

See this and this other post.

# Answer
> 2 votes
If you don't know how to correctly structure a game, you should start learning how to abstract their elements into game-independant blocks. This may help you in many ways (besides being interesting), such as: experience dividing abstractions from implementations, a better exploiting of inheritance and interface design, or just how to put the game into multiple files for it to look pro (or to provide a fexibility of implementations by the use of dynamic link libraries or other interface uses). Sooner or later you'll realize that everything can be done and then you will find yourself without that motivation problem anymore (you just do it).

I had the same problem when I got stuck at first, but the best solution is to keep moving, or you can stall forever until something resets you somehow (and it may take too long). It doesn't matter if you just code 2 lines some days, but every day you have at least to open the project and try to improve something (it's a neverending task but that's not the problem).

If at some point the program doesn't work, you should undo what you did last (keep a backup use an svn or at least a .rar with the name of the date) to a point it did work, and try to do it again, or work on other changes you need to do until you want to try again.

At first you should try to fix the error with the help of the debugger, but I don't know if your language even supports a debugger... but if you by chance use C++ or something like that (which I would recommend if you want to make games), you should make better use of your debugger as it will help you a lot for finding the error fast in a single run.

Reading about game programming is also a good thing to keep on the topic if you don't want to work on anything in particular. There are some good books and articles about game engines and design you can find online.

You won't be able to do anything if you don't practice. Trying to find a bug can be very frustrating at first but then you learn that it's actually easy if you know how to do it. This is something you learn how to avoid with the time, by coding in a way your changes don't impact in the whole program, decreasing the amount of places on where to look for the error. If every time it gets difficult you give up, then every next time you think on making a game you will give up before starting. Just learn how to overcome the bad moment by overcoming it :P If you don't pass through that moment in which you lose motivation, your laziness will win, and you will lose, that's how it works, until you learn how to regain motivation without much effort.

PS I was wondering... what are you using to make the game?

# Answer
> 2 votes
\[meant to be left as a comment to anon's answer, which was deleted as I posted it. He mentioned that he had all this functionality working, then split the single file code into multiple files, only for everything to fall apart\]

Re: refactoring, stuff can happen, even to pros. Sometimes even with good tools like Git, a merge can fail so instead of feature A and feature B both working, neither work! The only choice is to go back to A and try again. Luckily version control will save this code for you; if you don't use real version control, at least do it manually by zipping your dev folder regularly -- HD space is cheap! In conclusion, go back to what works and refactor in smaller steps, making sure the game still works at each step. It is really depressing to clean up code only to see everything fall apart. Just revert to old code.

# Answer
> 1 votes
To stay motivated, keep telling yourself that you are making a game, not a game engine -- well, unless that's your thing. And that's cool, game engines are great, but they too often get in the way of making games.

To illustrate my point, I can tell you how things often go: at first you create a few sprites, move them on the screen with your proto-framework and you are thrilled! You can see your progress and it is going well; you can show your friends.

Then, once you have played with your concept a bit you realize that you need to make your framework (or game engine) more flexible. Or that you should re-factor some class that are not following the latest patterns. And from there, you embark on a spiral of death: you stop working on a game and you start working on a game engine. And game engines are not nearly as fun to make. You can spend hours refactoring and have nothing to show for it - in the game. And then, you lose interest.

So, remember: make games, not game engines. Only refactor when you need to. Don't be too flexible - just the bare minimum.\*

\*: of course refactoring and flexibility are important. But not as important as actually having a finished game.

# Answer
> 1 votes
Try to make a playable version in a day, no matter how simple. Then iterate.

# Answer
> 1 votes
1. Don't try to make your game too complicated!
2. Split your task into small, specific, measurable subtasks. If any subtask seems too big, then subdivide it further.
3. Ensure that you write "DONE" in big letters on your task list (I use a .txt file) when your task is done. Don't remove the task, because then it won't look like you're making progress.

This is what I do. It's worked in the past.

---
Tags: software-engineering, motivation
---


# Question
Title: Ideas for attack damage algorithm (language irrelevant)
I am working on a game and I need ideas for the damage that will be done to the enemy when your player attacks. The total amount of health that the enemy has is called `enemyHealth`, and has a value of 1000. You start off with a weapon that does 40 points of damage (may be changed.) The player has an attack stat that you can increase, called `playerAttack`. This value starts off at 1, and has a possible max value of 100 after you level it up many times and make it farther into the game. The amount of damage that the weapon does is cut and dry, and subtracts 40 points from the total 1000 points of health every time the enemy is hit. But what the `playerAttack` does is add to that value with a percentage. Here is the algorithm I have now. (I've taken out all of the gui, classes, etc. and given the variables very forward names)

```
double totalDamage = weaponDamage + (weaponDamage*(playerAttack*.05))
enemyHealth -= (int)totalDamage;

```

This seemed to work great for the most part. So I statrted testing some values...

```
//enemyHealth ALWAYS starts at 1000
weaponDamage = 50;
playerAttack = 30;

```

If I set these values, the amount of damage done on the enemy is 125. Seemed like a good number, so I wanted to see what would happen if the players attack was maxed out, but with the weakest starting weapon.

```
weaponDamage = 50;
playerAttack = 100;

```

the totalDamage ends up being 300, which would kill an enemy in just a few hits. Even with your attack that high, I wouldn't want the weakest weapon to be able to kill the enemy that fast. I thought about adding defense, but I feel the game will lose consistency and become unbalanced in the long run. Possibly a well designed algorithm for a weapon decrease modifier would work for lower level weapons or something like that. Just need a break from trying to figure out the best way to go about this, and maybe someone that has experience with games and keeping the leveling consistent could give me some ideas/pointers.

# Answer
The answer provided by Grzegorz Sławecki is already a good one, but I wanted to explain the rationale behind his method and give you the tools to adapt the solutions to your gameplay needs.

The parameters of the present problem are the player's attack level *a*, weapon damage *w*, the total inflicted damage in one attack *d*, the enemy's health *H* and the minimum number of hits necessary to kill the enemy, let's call it *n*.

If you want the player to kill in *n* hits, then his total damage *d* must be such that

*(n-1).d \< H ≤ n.d* or in other words, *n = ceil(H/d)*.

*d* depends on weapon damage *w* and on the player's attack level *a* and we can expect weapons to get better as the level increases, so let's write *d(a)* and *w(a)* instead of simply *d* and *w*. The enemies the player faces are also expected to get tougher so, again, *H(a)*. These are all increasing functions of *a*, and you want them to satisfy the above inequations. **The unknowns of the problem are functions. You set one as a constraint, and you find the others.** You do have degrees of freedom though, which is a good thing.

If I understand your question well, you have a precise gameplay in mind, and this gameplay is mainly represented here by the number of hits required to kill the enemy, *n(a)*. Therefore, **set *n(a)* depending on the gameplay you envision for the game and then find the rest of the variables of the problem**. This is what you should always do because, as your question shows, your first attempt was to try an algorithm you thought may do and then realized it resulted in undesired gameplay.

Let's suppose, for instance, that you want the player to have to hit more and more times as he progresses in the game. You also want that, as the required number of hits increases, it increases less and less often, so that the player spends a longer part of the game hitting 5 times than 2 times. Here's what *n(a)* looks like:

The function used is *n(a) = ceil( 2/3.sqrt(a) )*.

We want *H(a)/d(a)* to stay within the ranges of values that make *n(a)* have the desired value and since *n(a) = ceil(H(a)/d(a))*, these ranges are the following rectangles:

and *H(a)/d(a)* can naturally be set to *2/3.sqrt(a)* so that we get the following graph, with the red curve being *H(a)/d(a)*:

*Remark:* we can easily find *H(a)/d(a)* here because we know the function of which *n(a)* is the ceil, but if our specification for *n* was less nice, we'd have to make our own fitting function using various tricks. Not all problems are this nice!

So we want *H(a)/d(a)* to resemble a customized square root function and we know that *H* and *d* must be increasing functions. Solutions are aplenty. For example,

*H(a) = a . 2/3.sqrt(a)* and *d(a) = a*

But we'd like the damage and the enemy's HP to increase an awful lot so that there are big, impressive numbers at the end of the game, just for style, so we instead set

*H(a) = a² . 20/3.sqrt(a)* and *d(a) = 10.a²*

**The whole point, and the best part, is this: you know that your solutions to the problem (*H(a)* and *d(a)*) obey the specifications (*n(a)*), so you get the same *n(a)*, but you have freedom.** You know exactly the freedom you have, and you can use it to customize the experience. You should always try to give yourself such freedom while satisfying your most important needs, whenever possible.

Now that we've chosen the one-hit damage *d(a)*, and since *d(a)* depends on the weapon damage *w(a)*, we can use *d(a)* as our specification and try to find a *w(a)* that gives us this *d(a)*. The principles are the same, the problem is different: we want the player to cause more damage as his level increases, even with the weapon remaining the same, and we also want the damage to increase when the weapon alone gets better and the level stays the same.

But what importance should each factor have? Suppose we want level to be more important than weapons: a bigger part of the variations of *d(a) = a²* should be independent from *w(a)*, for example with

*w(a) = 22.sqrt(a)* and, therefore, *d(a) = ( 22.sqrt(a) ) . ( 10/22.a.sqrt(a) ) = w(a).( 10/22.a.sqrt(a) )*

We get the following graph for *w(a)*...

...and **still the same *d(a)*, because we again found a solution that obeyed the specification**, here *d(a)*, and we do have the properties mentioned above with *w* and *a* contributing to the damage (suppose we look at *d* as a function of *a* and *w*: then if *a* were fixed and we had *w* vary in the equation *d(a,w) = a/30.w*, *d* would still be an increasing function of *w*, and the same is true if you fix *w* and make *a* vary).

This *w(a)* could give you the value to be displayed in the weapon's ingame description: we would get "Weapon Damage : 220" with the best weapon in the game for instance.

We could have used a completely different specification for our gameplay and therefore for *n(a)*, for example one that makes the number of required hits increase quickly as the game progresses and then plateau, and the resulting solutions would have been different.
> 14 votes

# Answer
I would recommend you to design your game from the other direction: First think about how you want your game to play (in terms of game experience, not in terms of numbers), and then design both the formulas and the number-ranges to get that result.

Your gameplay goal is that it takes a certain number of hits to kill an enemy. How many hits depends on three variables:

* power level of the enemy
* power level of the character
* power level of the weapon

You should first create a table of all possible combinations of these three variables being low-, mid- or high-tier (no concrete numbers yet, just "low", "mid" or "high") and how many hits you wish to be required for these combinations.

Then you should try to find a formula and value ranges which approximates your wish-values the best.
> 9 votes

# Answer
The easiest way, is to increase weapon damage between the levels of weapon exponentially.

However, what matters is that You should also define how is HP of enemies growing when they're getting stronger. So, when Your very strong You should kill easy enemies with just a few hits, but those at Your level should be relatively harder to kill than the enemies that were at Your level at the beginning. So I would design it to look somewhat like below:

```
level   weapon  enemy   attack  total   hits needed
        dmg     hp      factor  dmg     to kill
======================================================
1       1       2       5       1.25    1.6
2       4       16      10      6       2.666666667
3       9       54      15      15.75   3.428571429
4       16      128     20      32      4
5       25      250     25      56.25   4.444444444
6       36      432     30      90      4.8
7       49      686     35      134.75  5.090909091
8       64      1024    40      192     5.333333333
9       81      1458    45      263.25  5.538461538
10      100     2000    50      350     5.714285714
11      121     2662    55      453.75  5.866666667
12      144     3456    60      576     6
13      169     4394    65      718.25  6.117647059
14      196     5488    70      882     6.222222222
15      225     6750    75      1068.75 6.315789474
16      256     8192    80      128     6.4
17      289     9826    85      1517.25 6.476190476
18      324     11664   90      1782    6.545454545
19      361     13718   95      2075.75 6.608695652
20      400     16000   100     2400    6.666666667

```

```
Where:
1. total dmg is calculated using Your formula
2. weapon dmg = level*level (exponential growth)
3. enemy hp = 2*level*level*level (exponential growth)
4. attack factor = 5*level
5. hits needed describes how many hits are needed being on level x and using weapon on level x, to kill an enemy on level x

```

I tweaked those constant factors in formulas just to achieve results i think are acceptable, bo what is important is where You want linear growth and where You want exponential.

You should also notice that to e.g. kill enemy lvl 20 having 100 attack and having lvl1 weapon which takes total 6 dmg will take lots of time. If it takes too much in Your opinion, play with constants.
> 7 votes

# Answer
I think the world of war craft method is one of the best. The players base stats have a low impact on the total damage, with most of the damage modifier coming from bonus stats on gear. That makes it much easier to expand the game and balance it as time goes on
> 0 votes

---
Tags: game-design, algorithm
---


title: Physics/Logic behind self-bounce

text:
# Question
Title: Physics/Logic behind self-bounce
What would a ball look like when it makes itself bounce. Say, for example that the ball had its own "inner power", was made out of (mostly) rubber, and pulled the top of itself inward and then released, causing itself to 'bounce' up. Is that logic correct? And is this what it would look like?

If this logic is correct, what other materials can have this effect given the scenario described above?

# Answer
> 6 votes
If I was the ball, I think I would try to 1. maximise the surface of contact with the ground and 2. maximise the vertical compression so that the release will generate forces that are normal to the ground:

In your example, a lot of the energy stored by the compression is lost: if the released surface does not touch or hit the ground, it'll just move air around.

However, I am also a great fan of Richard Williams's The Animator's Survival Kit, where one of the most valuable lessons is probably to focus more on the viewer's perception than on physical accuracy. Actually your animation may look a lot better if it's *not* physically accurate.

Here's an example from Williams; see how the 5th frame stretches the ball *before* touching the ground, for no physical reason:

So, my idea would be to go for the very simple vertical stretch (such as in this video), and add dramatic effects instead, such as causing the ball to shake and vibrate more and more as it squeezes itself. I suggest watching various animation examples frame to frame. There may also be good stuff in One Piece!

---
Tags: 2d, physics
---


title: Apply portion of texture atlas

text:
# Question
Title: Apply portion of texture atlas
I'm trying to write a shader that only maps a portion of a large texture to my sprite and I'm getting a strange behaviour with my current code.
This is what I have right now:

Texture atlas example (256x256px):

**EDIT**
I've changed both shaders and I get the following output right now (first image), but I need to zoom the texture so I only render the highlighted portion of the second image, how should I modify the shaders to achieve that?
-\>

These are my current shaders:
Vertex:

```
uniform mat4 uMVPMatrix;
attribute vec4 aPosition;
attribute vec2 aTextureCoord;
varying vec2 vTextureCoord;
varying vec2 vTextureCoordOffset;
void main() {
    // offset and texSize will be defined as attributes later.
    // They're defined here for test purposes only
    vec2 offset = vec2(128.0, 64.0);
    vec2 texSize = vec2(256.0, 256.0);

    float u = offset.x / texSize.x;
    float v = offset.y / texSize.y;
    vTextureCoordOffset = vec2(u, v);
    vTextureCoord = aTextureCoord;
    gl_Position = uMVPMatrix * aPosition;
}

```

Fragment:

```
precision mediump float;
uniform sampler2D sTexture;
varying vec2 vTextureCoord;
varying vec2 vTextureCoordOffset;
void main() {
    gl_FragColor = texture2D(sTexture, fract(vTextureCoord) + vTextureCoordOffset);
}

```

**SOLVED**
I solved it changing the fragment shader to:

```
gl_FragColor = texture2D(sTexture, fract(vTextureCoord) * vZoom + vTextureCoordOffset);

```

vZoom is calculated in the vertex shader:

```
vZoom = subTextureSize / texSize;

```

# Answer
> 1 votes
You're not interpolating the texture coordinates at all. You're sampling a single point at all times.

```
f(N) = (N + 0.5) / 256

N = 0 -> 0.001953125
N = 64 -> 0.251953125
N = 128 -> 0.501953125

```

So in case of (0,0) you're always sampling a point near top corner, and with (128,128) you're sampling a single point near the center, but somewhat on the magenta (although bilinear interpolation may cause other colors to appear).

You should be using varyings to interpolate the texture.. and while at it, you might want to do all of these calculations on the vertex shader, so they're done per polygon instead of per pixel.

---
Tags: opengl, shaders, opengl-es, fragment-shader
---


# Question
Title: What compilers are used in game development?
I was kinda wondering *what **compilers** are used in game development*, since the **game development industry** always tries to squeeze every inch of performance out their software, using, among other, (*sometimes very aggresive*) compiler optimizations and the big boys in compiler technology (**llvm, gcc**), that excel in such kind optimizations are out of the game in the `*Windows operating System*`.

# Answer
> 10 votes
**Update for November 2018**

LLVM/Clang is the primary (or only) compiler for many gaming platforms these days. iOS, Android, PlayStation 4, MacOS/OSX, and Nintendo Switch all use Clang as their default native compiler.

XBox One is only supported by Microsoft's compiler, and their compiler is also still the most commonly used for Windows.

A handful of legacy or less mainstream platforms use other compilers, like 3DS' use of Green Hills' compiler.

GCC may sometimes see use on Linux (server) builds due to it being the default C++ compiler on most major Linux distributions.

Some studios may use specialized optimizing compilers like ICC for supported platforms, but most do not. This is partly because no mainstream client gaming platform besides PC uses Intel processors

**Original circa 2012**

There's a few misconceptions in your question. First, games don't really new any kind of special super-optimizing compiler. We've long since hit the point where the hardware is beefy enough, common compilers optimize well enough, and games are complex enough that micro-optimizing instructions has little value outside of a few specialized loops. Also, while I love LLVM, it is hardly a "big boy" in the compiler space, and it generally has the worst optimizations of all the major compilers (for now), and hence it is not really used outside of Apple's newer dev environments.

Microsoft Visual C++ is the primary compiler for Windows and XBox. A few places use Intel's ICC for Windows, but that's rare.

Modified ancient crusty versions of GCC provided by the hardware vendor are used for all the non-Microsoft consoles.

Apple's ancient modified GCC is used for iOS, and OSX. It is being phased for the LLVM-based Clang. A more modern version of GCC is used for Android.

Linux isn't much of a gaming platform, but the few commercial games out there for it are compiled with a fairly recent GCC usually.

# Answer
> 5 votes
On windows, most people use visual studio and its build tools. Xbox 360 uses it as well. On just about everything else, some version of GCC is typically used. (PS3 & Nintendo consoles use a customized version of GCC)

# Answer
> 1 votes
The compiler that comes with Visual Studio / C++.

I don't program for a game development company, just a boring business software developer. Our target platform is Microsoft, and we use Visual Studio 2010 for C++ and C# .Net.

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


# Question
Title: Hobby project : learning game design or game development?
I plan to start with a hobby game project. So while doing the research about the same, I learnt about two activities mainly of game design & game development. Now this being my first game I am not sure which of these activities will take more time.

Just a little background about myself : I have been programming for nearly 10 years now and am quite adept in C++ and can code decently in Java as well.

I am currently collecting reading material for both game design and development. So my question is, which should I study first : game design or game development? Which of these if learnt first will help in the other activity?

# Answer
> 0 votes
I'd say game design might cause You more trouble as You're an experienced programmer. I suppose, in the field of development You might just need some time to learn frameworks/libraries and get some experience with those elements of programming specific to games.

If You intend to write some very simple games just for fun, You might not notice that You need to design something heavily. E.g. if You'll write pong or snake or something similar, that shouldn't be hard to design. Probably You already know how would the gameplay look like.

However when You get deeper into this and start making some even slightly more sophisticated games, then You'll notice, game design will start to be more and more demanding.

So, in my opinion start with some easy games, try to use some simple libraries frameworks but focus on design even if it's trivial. Try changing some game rules for well known simple games and see how they change the gameplay.

# Answer
> 1 votes
It's really a matter of whether you want to learn high-level, abstract concepts to games or whether you'd rather get down and dirty with a lot of the code basics that make up games.

I usually consider game development to be focused on the design and implementation of tools and platform solutions that aid designers in creating games. Game development isn't as much about creating the game as it is to creating the foundation that games can be built and managed. This is essentially your programmers.

Game design is on the receiving end of this foundation & tools. This group is often what drives requirements to the programmers and this is the group that takes those tools and creates an virtual world filled with interaction and fun packed adventure. These are often the creative types, ones who may have some minimal technical skills to write simple scripts in UnrealScript, Lua, Mono, etc. But these guys aren't the ones programming in C++ and concerned with engine code, network code, and how all the nodes of an MMO process hierarchy communicate in a distributed fashion.

Both have advantages & disadvantages to going into one or the other first, as with any choice in life. What drove me to development was the fact I enjoy programming, and so the choice was clear. If you're on the fense, then consider which avenue appeals to you more and start there.

---
Tags: game-design
---


# Question
Title: Determining whether two fast moving objects should be submitted for a collision check
I have a basic 2D physics engine running. It's pretty much a particle engine, just uses basic shapes like AABBs and circles, so no rotation is possible. I have CCD implemented that can give accurate TOI for two fast moving objects and everything is working smoothly.

My issue now is that i can't figure out how to determine whether two fast moving objects should even be checked against each other in the first place. I'm using a quad tree for spacial partitioning and for each fast moving object, i check it against objects in each cell that it passes. This works fine for determining collision with static geometry, but it means that any other fast moving object that could collide with it, but isn't in any of the cells that are checked, is never considered.

The only solution to this i can think of is to either have the cells large enough and cross fingers that this is enough, or to implement some sort of a brute force algorithm. Is there a proper way of dealing with this, maybe somebody solved this issue in an efficient manner. Or maybe there's a better way of partitioning space that accounts for this?

Here's a diagram:

Object A and B's "areas of effect" cross, they should be checked against each other. But with the way i'm currently checking for collisions does not account for this. Again, i can think of a few solutions to this like actually checking if objects' paths cross once their velocity is higher than x, or something, but that feels like a hack and it's a mess to try and implement.

# Answer
The problem you are talking about is often called 'broadphase collision detection' and your solution is a 'swept volume', not really a hack, just how it's done (simply take tha AABB of the object including both start and end of the motion and use that for collision - though things get a little tricky with rotations).

Then the go to broadphase collision detection algorithm that makes this fast is called 'Sweep and Prune.'
> 5 votes

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


title: How do you rotate a cube map?

text:
# Question
Title: How do you rotate a cube map?
I'm looking for suggestions on this

Say you have a cube map. You want to rotate it as efficiently as possible.

You *can* render the cube map, rotate the camera, and render the scene to another cube map.

But it would be faster to rotate the cubemap by operating on the texels.

I'm using D3D11, and I need to read the texels in the code (so I can't use the OpenGL "Texture Matrix"!)

# Answer
> 0 votes
I did it by the following. Create a new cubemap called *rotated*. To get the color at each texel in *rotated*, just get the color from the original cubemap that *will land there* after rotation.

So, for each texel in the *rotated* cube map, find the vector *u* from the center of the cubemap towards that texel.

"Unrotate" *u* by multiplying by the inverse (which is just the transpose) of the rotation matrix to get *v*. Find the texel that *v* corresponds to, and grab the color from the original cubemap, and write that value into *rotated*.

You will get better results by interpolating between the few pixels that *v* kinda points to (it will almost never point to the dead center of a pixel).

# Answer
> 2 votes
You can use "texture matrix" also in shaders (D3D or OpenGL - doesn't matter).

Pass float4x4 as uniform to your shader, and multiply it with texture coordinate before fetching texel.

# Answer
> 0 votes
If I understand correctly, you have a cubemap and want to generate another cubemap that is a rotated version of the first one, and you have the capability of capturing a cubemap from an in-game scene (by rendering six times with cameras set to match the cube faces, or whatever).

It seems this should be easy to do by setting up a temporary scene that consists of a cube around the camera, with the original cubemap applied onto it; then rotate the cube and use the camera to capture the new cubemap.

---
Tags: directx11, cubemap
---


# Question
Title: Syncing game states in a multiplayer RTS game
I'm working in a group with 2 friends on our Gr. 12 final project for programming. We're making a multiplayer RTS game. I've been assigned to the networking section of the game, and none of us have any experience doing network programming.

We've established that we'll have the server process everything such as path finding, build queues etc. The client will receive packets from the server, which will contain information such as HP, x, y, etc of each unit/building (Well, the server will send a packet whenever a unit/building's state such as losing HP, movements etc is changed).

The problem is identifying which unit the packet contains information for. I've thought of generating a number as an ID for each unit/building, and storing the units in a map data structure, where the key is the ID. **Is there a better way to do this? How do most RTS games do it?**

# Answer
Your technique will be sufficient. Since you seem to understand how to do it and what needs to be done, for this situation, it's the best way to go.

As it is with many decisions like this in programming, you'll have to consider your requirements and see what your budget allows. Your budget is the time you have to complete the project. You know your requirements better than anyone here would.

So if storing an integer for each unit and building meets your requirements, and you think you can do it in the time allowed, go for it. It's not a bad way of doing things, and I don't foresee any major problems with doing it that way.
> 1 votes

# Answer
Your approach isn't a bad one and there's a lot you can do with it. However, since you're a novice at network programming as you have stated I'm sure there's a lot of things you might not be aware of. The Age of Empires team was already down this road once and you could probably learn a lot from them. Check out this article. You'll be glad you did!
> 0 votes

---
Tags: java, algorithm, networking, server, synchronization
---


# Question
Title: Blend multiple regions from same texture atlas
I'm representing terrain in my game as a grid with at each node a composition, for example 100% rock, or 50% grass, 50% soil. I'd like to use this composition vector to blend textures together. I'm using a single texture atlas which contains all my terrain textures.

I've tried various ideas but I always seem to stumble on the rasterization part of the pipeline, because the interpolation does not work correctly between coordinates across the texture atlas.

What is the recommended way to accomplish this?

# Answer
You don't want to interpolate between coordinates in the texture atlas.

Instead, you want to sample from each of your textures within the texture atlas, and interpolate between the colors that are returned from the sampler.

Typically, you'll do this by specifying a texture coordinate as a vertex attribute (along with 'position', 'normal', and whatever other attributes you need), and treat that texture coordinate as being the coordinate within one of the textures in the atlas, as if that texture wasn't in an atlas at all. Then you put code in your GLSL shader to convert from the "generic" texture coordinate you specified before into atlas coordinates for each of the textures you want to blend together, samples from the atlas at those atlas coordinates, and blends the resulting colors together using the ratios expressed in the composition vector.
> 2 votes

---
Tags: opengl, textures, glsl
---


# Question
Title: OutOfBounds Exception when creating a PolygonShape using jbox2d
So here's the deal, i'm parsing a file that contains the vertices for a polygon, that i want to create in box2d. I create a `new PolygonShape()` and then call `.set()` giving it a defined array of `Vec`, and that defined array's .length property. I expected this to work, since the documentation for jbox2d says this method takes a Vec array, and the count of Vec objects in that array. However, it errors out, and it seems to be unrelated to my code. The error i get is

```
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 8
    at org.jbox2d.collision.shapes.PolygonShape.set(PolygonShape.java:174)
```
and, upon looking at that line in the jbox2d svn repository, i still cannot figure out the issue.

Any help is appreciated!

# Answer
Your problem is that you are trying to create a `PolygonShape` with more than 8 vertices. Box2D, and thus JBox2D, default to a maximum of 8 vertices per polygon. This is why you don't get an `ArrayIndexOutOfBoundsException` until index 8 (0 based indexing means it's vertex #9).

You can change the maximum number of vertices by simply modifying `org.jbox2d.common.Settings.maxPolygonVertices`.

However, if you take a look how PolyShape utilizes this setting you'll see why changes can have a global performance impact.

In this conversation *iforce2d* suggests you can increase the limit a little, if you need, but should consider alternatives before making big changes.
> 1 votes

---
Tags: java, jbox2d
---


# Question
Title: What do you think about Ogre3d as first time engine for first time 3d Game?
This is a question for the experienced 3d game developers.

I'm a long time programmer (c++/java), and after 15 years, I'd like to get into 3d gaming.

After some internet research, I saw that the trend is mostly with Ogre as a 3d engine.

What do you think? I'll be targeting OSX, Linux and Windows.

# Answer
It depends on whether you are interested in programming lower level game system frameworks or higher level game design and behavior.

If you start with Ogre you will initially be programming the framework and working your way up to the higher level stuff. If you start with say Unity, the framework will all be setup for you.

For example if what you really want to program is an idea for an AI or NPC behavior, you're better off with Unity as you can get right to what you are interested in.
> 4 votes

# Answer
Keep in mind that Ogre3d is a Graphical engine and it will not allow you to build a game only using it, you will need to implement all the other subsystems or integrate with other engines, like physics, audio, etc.

If you have no experience with game programming, I suggest as a first project that you use Unity3d or UDK. If you really want to use C++ instead of a scripting language, you can try to create a mod for a game, one good option is any game from Valve (like half life).
> 6 votes

# Answer
You do not need a full-blown graphics engine at this point. I suggest starting with OpenGL and writing a little renderer yourself. It's actually pretty easy to get simple scenes on screen, it's rewarding and you will learn far more about graphics programming than from using Ogre or any other 3D engine. You can also refer to one of the thousand books on the subject during the process. With any engine you are mostly at the mercy of documentation writers.

Start simple though, graphics programming can be a really challenging task, but IMO is one of the most rewarding types of programming.
> 1 votes

# Answer
It depends on how much you want to customize the final product.

Using Unity, or some other pre-packaged solution, will let you get there more quickly. The drawback is that there are a lot of design decisions already made for you and they cannot be easily changed.

If you're willing to work hard and spend a lot of time to get it exactly how you want it then rolling your own is the way to go.

Good luck!
> 0 votes

# Answer
I think you should try developing something small in Unity and then in Ogre and see which works better for you. Set yourself a small, specific project to do (since you're totally new to game programming, just make a cube on a plane ground that moves around) and do it in both development tools. Those are two of the better indie game development tools available and they take very different approaches to how development is done, so this'll tell you pretty quickly what you will be most successful learning game dev using and thus where you should focus your energy.

Ultimately I think it's pretty misguided to ask others to decide this for you, so here's how to evaluate engines and decide for yourself.
> 0 votes

---
Tags: ogre
---


title: Vehicle physics with skid

text:
# Question
Title: Vehicle physics with skid
How would I go about creating vehicle physics for a car that can loose traction? I want it to seem like the driver has a flat foot, so when you press the gas, they cars driving (rear) wheels loose traction, and makes it somewhat hard to control. I would also like to be able to do doughnuts and "drift" around corners.

I would also need to know how much "skid" is happening, so I can add a proportional amount of smoke and tire marks.

Assume a 2d, top-down style car game.

Thanks

# Answer
This is a very simplified version but would be fine for most arcade type games. You need the following properties:

```
positionX, positionY - where the car is
velocityX, velocityY - speed on each axis
drag - how fast the car slows down
angle - the rotation of the car, in radians
angularVelocity - speed the car is spinning, in radians
angularDrag - how fast the car stops spinning
power - how fast car can accelerate
turnSpeed - how fast to turn

```

every frame:

```
positionX += velocityX
positionY += velocityY
velocityX *= drag
velocityY *= drag
angle += angularVelocity
angularVelocity *= angularDrag

```

to accelerate

```
velocityX += sin(angle) * power;
velocityY += cos(angle) * power;

```

to steer left

```
angularVelocity -= turnSpeed;

```

to steer right

```
angularVelocity += turnSpeed;

```

To get good drift, set drag and angularDrag to very close to 1, e.g. 0.9
> 11 votes

# Answer
I was reading a paper today which simulates some vehicle dynamics during a collision and spin-out:

Jing Zhou; Jianbo Lu; Huei Peng, "Vehicle Dynamics in Response to the Maneuver of Precision Immobilization Technique", Proceedings of 2008 ASME Dynamic Systems and Control Conference

This contains a physics model which represents roll-over moment and loss of rear-tire traction during yaw caused by a deliberate collision force. It seems interesting to game programmers interested in vehicle dynamics during collisions.
> 2 votes

# Answer
I don't generally recommend Bourg's *Physics for Game Programmers*, but he talks about this a bit in Chapter 10 (around page 171), and might give you a starting point.

Unfortunately, the vehicle code in PhysX is still 'sample' and not well documented, so you can't easily figure out how that works. I believe I've seen code derived from their sample display the kind of behavior you're looking for in 3D, but it's a lower-level simulation than I think you want.
> 1 votes

# Answer
First things you need to understand are "slip ratio" and the "traction circle". Slip ratio is a good approximation for tire behavior, with a non-linear relationship between angle difference and lateral tire force. It also provides you with driver torque feedback information (for force feedback steering wheel).

The super simple version of both concepts are as follows: the more angle difference between rolling direction and movement direction, the more force there is perpendicular to the rolling direction (lateral force). It reaches peak at (typically) maybe 5° to 8° and falls off from there if tire angle is increased.

The traction circle is basically a limiter that clips off any force vector that goes outside it. It models the way that heavy acceleration/braking reduces steering ability, and vice versa. The size of the traction circle (max traction force vector) scales with the force pressing the tire onto the ground.

You'd need to model the lateral (steering) force separately from the driving/braking (rotational) torque and the opposing traction force from the ground.
> 1 votes

---
Tags: 2d, physics
---


# Question
Title: getting direction of x and y... north,south,east,west
I have a player in the center of the screen, where I also have my mouse position origin. (0,0) I would like to know the direction of the mouse, imagine splitting the screen with a X, so the top quadrant would be north, the bottom would be south... and so on. So if my mouse was at 5,-100 it should log ("North") as that is just a bit to the left and up 100 pixels.

# Answer
```
if (Abs(Y) > Abs(x)) {
  if (Y < 0) {
    return "North";
  } else {
    return "South";
  }
} else {
  if (X < 0) {
    return "West";
  } else {
    return "East";
  }
}

```
> 10 votes

---
Tags: mathematics, trigonometry
---


# Question
Title: Where to generate data in an Entity-Component System?
So I'm making a small game where I generate 2D landscape using perlin noise when the game first loads.

I've got it working in a OO way, but want to move over to an ES architecure, and I'm just struggling to work out the right place for the code that does the generation to go?

In OO world, I have a `World` object which gets passes a `coordinate` value that is used as the seed for the perlin noise, and generates all the points for the land mass when the world is created.

I'm thinking I need a `World` component with a `coordinate` field on it - that's an easy part.

From there - is it right for a component to generate data when it's first initialised (or is that too OO?)? Or should a System be doing that instead, when the game first starts?

Or... some other solution I'm not aware of?

Thanks in advance for any guidance.

# Answer
> 5 votes
I come from the mindset that components contain nothing more than data. Depending on your game, that data is derived from static files that ship with the game to sometimes being combined with the information sent from the game world server to your client if we're talking about networked games.

That implies that rather than components generating anything, I prefer to offload that to systems. I prefer this route because it sometimes makes sense for a component to be shared across a few systems and rather than trying to muck with managing all that logic in one class with an Update() method, I can separate it out into multiple systems and allow each system to work with that same component.

As an example, when your game loads, you have some level data file that desribes what you want this level to look like, what entities exist within it, where, what their attributes consist of, etc. So this LevelLoader reads this level file and determines it needs to place an Orc in the scene at 1, 10, 5.

```
// Allocate an Entity Id (in our case its just an unsigned int)
TEntityId id = mEntitySystem.CreateEntity("Orc123");

// Create position
PositionComponent& position = mEntitySystem.AddComponent(id, "Position");
position.SetPosition(1, 10, 5);

// Create renderable
RenderableComponent& renderable = mEntitySystem.AddComponent(id, "Renderable");
renderable.SetMesh("UglyOrc.mesh");

// Allows components to wire up references, etc for given id before it
// gets added to the world.
mEntitySystem.Finalize(id);

// Add entity to the world, will start to receive world messages
mWorld.AddEntity(id);

```

To relate the above to your example, I'd probably abstract the creation of the terrain to some type of terrain generation system. Once the landmass has been created by the terrain system, you could easily adjust the above code as follows:

```
// Create position
PositionComponent& position = mEntitySystem.AddComponent(id, "Position");
position.SetPosition(mTerrainSystem.GetGroundPointAt(1, 10, 5));

```

The Terrain System would look at the generated heightmap, determine what the right height should be at that point to place the Orc on the ground, return the proper adjusted position and that would cause the entity to appear above ground but relative to the same two directions in 3D space.

HTH.

# Answer
> 4 votes
Just because you want to use an entity-component architecture doesn't mean you need to use it for *every* game object. Forget about trying to implement edge cases like terrain as a collection of generic components, because all you'll end up with is components specific to terrain.

Entities are really only good for game objects that exist in many different forms with differing behaviours depending on the values of certain properties, like mobs. Instead of making terrain an entity, make it an intrinsic part of the physics/collision systems. That way, your entities can raycast and pathfind and bounce around and interact with the terrain without needing to handle the terrain differently than the other static objects in the scene. Hell, the entities don't even need to know that the terrain exists, just that they can interact with it if it does.

---
Tags: architecture, entity-system
---


title: Changing water color based on depth

text:
# Question
Title: Changing water color based on depth
I'm looking to make a water shader that colors the water based on its depth. Up until now my water shader that I've used has basically been extremely reflective and only looked somewhat blue because it was reflecting a blue sky. The effect I'm shooting for looks something like the one from the first page in this article.

I don't necessarily need exact shader code, just the gist of how I calculate the color of the pixel based on the depth, while still getting a proper reflection and refraction. I should mention that I already have the water's depth calculated, per-pixel, and I also have working reflection and refraction. All I'm lacking is a color based on depth.

I've tried a bunch of stuff, the next thing I'm considering is actually coloring the terrain that is underwater, and coloring it based on depth.

# Answer
> 11 votes
My impression is that this color is essentially a fog color, thinking of the water as being a fog volume with a shiny surface. The simplest thing to do is probably to just let your artists pick a shallow color and a deep color, and lerp between them based on the depth. Something like:

```
lerp(shallowColor, deepColor, saturate(depth * depthColorScale));

```

Here `depthColorScale` is 1.0 / the depth at which the water should reach `deepColor` (probably a couple meters, I'd guess). Then treat the result as a fog color applied to the terrain under the water in the usual way: namely, lerp from the terrain color to the fog color based on the length of the refracted underwater eye ray.

You could also use a smoothstep instead of a lerp, or some other interpolation function, if you find it looks better.

---
Tags: xna, graphics, shaders, hlsl
---


title: My VBO is always empty

text:
# Question
Title: My VBO is always empty
I'm trying to render an obj file with a VBO but I have some problems. I have a Renderer object that has a method "setPositions()" that simply stores some data from a QVector to a VBO. The render part is in another method. I couldn't render anything, so I wanted to check if the array was really copied in the VBO. Instead of working on the Qvector, I wrote this simple code to make some test to render a simple square. As you guessed, the bufferSize variable is still at 0, and I have no render.

```
     /* setPositions() */
     float vertices[] ={
          0, 0, 0,
          100, 0, 0,
          100, 100, 0,
          0, 100, 0
     };
     glGenBuffers(1, &pos); // Gluint pos : class attribute

     glBindBuffer(GL_ARRAY_BUFFER, pos);

     glBufferData(GL_ARRAY_BUFFER,
                   12 * sizeof (float),
                   NULL,
                   GL_STATIC_DRAW);
     glBufferSubData(GL_ARRAY_BUFFER,
                      0,
                      12 * sizeof (float),
                      &vertices[0]);

     int bufferSize = 0;
     glGetBufferParameteriv (GL_ARRAY_BUFFER, GL_BUFFER_SIZE, &bufferSize);

     if (bufferSize != (12*sizeof(float)))
     {
          glDeleteBuffers (1, &pos);
          std::cout << "sizes mismatch. Buffer: " << bufferSize << " Array : " << 12*sizeof(float) << std::endl;
     }

     glBindBuffer (GL_ARRAY_BUFFER, 0);

     /* render() */
     glBindBuffer (GL_ARRAY_BUFFER, pos);

     glEnableClientState (GL_VERTEX_ARRAY);

     glVertexPointer (3, GL_FLOAT, 0, BUFFER_OFFSET (0));

     glDrawArrays (GL_QUADS, 0, 4);

     glDisableClientState (GL_VERTEX_ARRAY);

     glBindBuffer (GL_ARRAY_BUFFER, 0);

```

Does somebody have an idea ?

# Answer
the problem didn't come from the part of code I showed you. I just read some doc and found the problem. To have Qt and OpenGL working together properly, you have to set an OpenGL context. But you have to make sure that you set it before any call to an OpenGL function (or at least a drawing function i guess). So, to have it working, I just added a line in the constructor of my OpenGL window (wich inherits from QGLWidget) :

```
this->makeCurrent ();

```

Magic. Also, I found that Qt had a simple way to handle buffers with QGLBuffer.

```
 buf = new QGLBuffer (QGLBuffer::VertexBuffer); // I just declared a QGLBuffer *buf in my class attributes
 buf->create (); // equivalent to glGenBuffers()

 buf->bind (); // equivalent to glBindBuffer()

 /* The two next functions are the equivalent of glBufferData() (you have to call setUsagePattern before allocation) */
 buf->setUsagePattern (QGLBuffer::DynamicDraw);
 buf->allocate (data, 18 * sizeof (float));

 buf->release (); // equivalent to glBindBuffer(target, 0)

```

For the render, you just have to bind the buffer as described above and use the regular OpenGL functions. I hope it'll help somebody.
> 2 votes

---
Tags: c++, opengl, vbo
---


title: is ECS a kind of (or vs) OOP?

text:
# Question
Title: is ECS a kind of (or vs) OOP?
Is Entity Component System (ECS) considered a part of OOP or is it a completely different concept?

# Answer
Short answer: Entity Component System (ECS) is not a part of OOP.

The discussion that most influenced my understanding of Entity Component Systems is on T-Machine and an example framework inspired by this discussion useful for reference is Artemis.

One of the fundamental concepts of OOP is encapsulation - application design breaks the domain into objects that have private state that can only be mutated via methods exposed by said object. Extending the functionality of an object can be done via inheritance or through composing existing objects into new objects that expose new accessor/mutator methods. In all cases the driving force is to create a system that is loosely coupled and thus easy to maintain and extend. A trivial game related example might be creating the notion of a GameEntity with the ability to draw itself via a public render method. This object can be extended by subclassing and the logic for rendering and all of its state is always encapsulated within.

In ECS, on the other hand, application design is based on the idea that applications are fundamentally transforming/processing structured data. In such a system a GameEntity is a bundle of data against which transformations are performed - there is no encapsulation. In the Artemis framework you will notice that Entity is finalized specifically so it *cannot* be subclassed. Of course, not all GameEntities will have the same data - the player GameEntity may have inventory data while MOB game entities do not. If this were an RDBMS we'd have one massive sparse table that would quickly get unwieldy as the game grew. Enter components. A component is a piece of structured data that can be linked to an Entity just as one row in an RDBMS table can link to one or more rows in another table. This provides a way of structuring the methods used for transforming the data. The RenderSystem (or RenderMethod), for instance, would want to process any entity with a SpriteComponent and the InputSystem (or InputMethod) would want to process any entity with a KeyboardInputComponent.

While there is a hardline position that *true* ECS means eschewing OOP entirely I think it is possible to incorporate OOP into ECS and still remain to true to ECS design goals. For instance, you'll notice in the Artemis framework that the systems responsible for processing entity data are objects themselves using encapsulation and inheritance. Similar functionality can be obtained without relying on inheritance or classes (I used function pointers and structs in my C version) but I don't think Artemis is any less an ECS framework, it may simply be more ripe for OO abuse.

Since an ECS is based on the idea that data should drive domain design as opposed to object hierarchies it is data oriented and best understood as a concept separate from, if not mutually exclusive with, OOP.
> 10 votes

# Answer
Component systems are an architecutre. Object-oriented programming is the combination of object-oriented features in a programming language and the design principles behind the inclusion of these features as well as how to effectively use them.

### Some of the key aspects of object oriented programming are:

* Language-level mechanism for tightly packaging data with the procedures that manipulate it. Methods/member functions are bound to an instance of an object
* Additionally, the raw data is often hidden (encapsulated) in order to protect the integrity of the data and ensure the consistent state of an object. Bound methods have access to the encapsulated data, as the general idea is that the author of the class knows what the internal state should be at any given moment and can be reasonably trusted to maintain that state when writing methods that manipulate hidden data (keep in mind that the "hidden" part of that means different things in different languages).
* Inheritance: A derived class can inherit behavior and data from a base class
* Polymorphism: An instance of a derived class can be used as though it were an instance of its base class.
* Implementation contracts: Polymorphism, but via the mechanism of interfaces or protocols

### Some of the key aspects of component systems are:

* The "primary objects" are lightweight containers for logic and data
* Logic and data are often encouraged to be separated. At the very least, a behavior component will track its own data required to execute said behavior. Other systems treat components as pure data and behaviors as systems (not bound to a primary object) that operate on that data.
* Behavior is added to a primary object at runtime, often in such a way that the construction of objects can be described by data/configuration rather than code
* Because component systems can be data-driven, it's easier to build tools for non-programmers to create behavior and content

Look at these bullet points and think about them long enough and you'll realize they can't really be classified in the same way. Object-oriented programming can be helpful in implementing a component system, but is not strictly required. And except for prototype-based languages like Lua and Javascript (where it's rarely useful to think on this kind of scale, and are often thinking of code as data), component systems are generally not baked into a language and are more of a architecture pattern.

You could just as well implement a component system in idiomatic C and have it serve you as well as something similar in C++ or C# (Type-safety problems and less syntax sugar not withstanding). People interfacing with your C component system wouldn't care that it's C because they're typically just manipulating data to produce complex behavior.

As for object oriented design and where it fits into this spectrum, I think that it doesn't. *In my arrogant, young opinion*, SOLID is essentially a list of platitudes that, while useful in a broad, rule-of-thumb kind of way, ultimately don't provide us with that much useful information beyond achieving a good sense of general organization and structure. And that's certainly not OOP-specific. Much more useful are design patterns and principles in specific languages. I just find it weird that OOP gets its own qualifier to stick in front of the word "design." When's the last time you saw a *Teach Yourself Imperative Design in 24 Hours* or *Functional Programming Architecture for Dummies* book?

Having been raised on OOP, many of us generally find it easier to implement component systems in an object-oriented language because we're familiar with the design patterns and best practices of this paradigm. Haskell nerds, Lisp hackers and C gurus will have a completely different opinion on how one would approach to implementing (or possibly refusing to implement, because their languages offer superior idioms that accomplish similar goals in ways more appealing to their programming palette) this pattern.

To understand the benefit and principles of component systems in game programming, try this: Imagine constantly for every second that you're building out your game's systems, that as soon as it's built you won't ever be able to actually build content for it. Another person who has no coding skill must work with it and you can only affect the outcome of their work orthogonally by updating the tools. Components are a pattern for maximimizing flexibility of creating a variety of different behaviors at runtime and enabling this behavior to be determined by non-code data. OOP can help, or it can not.
> 4 votes

# Answer
A component system is just a way to organize the data belonging to your objects, and how to create processes that act on this data. It can be done with and without object oriented programming (which, really, is just a very broad term for a set of loosely related programming techniques, with a lot of dogma attached).
> 3 votes

# Answer
Component based systems are not part of OOP.

Originally, they don't rely on OOP functions. Component based architectures exist since long. They have been used in financial and banking apps for decades. They enable strong modularity, parallelization (even across servers) thanks to the segmented data, very simple storage mapping (database \<-\> component) and composition without the overhead of inheritance (and OOP).

Since video games grew in complexity it became obvious that inheritance is not an efficient option when it comes to the structure of game entities. Segmenting games into systems which handle the specifics of each function simplifies the reuse and maintenance of code (across entities and across games). It also simplifies the execution of parallel tasks (i.e. run multiple systems or segments of a system in parallel).

But all of this can be achieved without OOP. Here is a very primitive example of of how a component based system would look like in C:

```
#include <stdio.h>
#include <unistd.h>

struct TransformComponent {
    int x;
    int y;
};

struct ScriptComponent {
    void (*scriptPtr)(int,int);
    void (*handleMessagePtr)(int,int,void*);
};

struct RenderComponent {
    char* model;
};

#define MAX_ENTITIES            4
#define GRID_X                  16
#define GRID_Y                  10

#define noStatus                0x00
#define goStatus                0x01

int componentsStatus[MAX_ENTITIES];
struct TransformComponent positionComponents[MAX_ENTITIES];
struct TransformComponent movementComponents[MAX_ENTITIES];
struct ScriptComponent scriptComponents[MAX_ENTITIES];
struct RenderComponent renderComponents[MAX_ENTITIES];

void RunScriptSystem(int time)
{
    for (int i=0; i<MAX_ENTITIES; ++i) {
        if (goStatus == componentsStatus[i] && 0 != scriptComponents[i].scriptPtr) {
            (*scriptComponents[i].scriptPtr)(i, time);
        }
    }
}

void RunTransformSystem(int time)
{
    for (int i=0; i<MAX_ENTITIES; ++i) {
        switch (componentsStatus[i]) {
            case goStatus:
                positionComponents[i].x += movementComponents[i].x;
                positionComponents[i].y += movementComponents[i].y;
                while (GRID_X < positionComponents[i].x) {positionComponents[i].x %= GRID_X; }
                while (GRID_Y < positionComponents[i].y) {positionComponents[i].y %= GRID_Y; }
                while (positionComponents[i].x<0) {positionComponents[i].x += GRID_X; }
                while (positionComponents[i].y<0) {positionComponents[i].y += GRID_Y; }

                movementComponents[i].x = movementComponents[i].y= 0;

                break;

            default:
                break;
        }
    }
}

void RunRenderSystem(int time)
{
    printf("\n=======================================\n");
    for (int i=0; i<MAX_ENTITIES; ++i) {
        switch (componentsStatus[i]) {
            case goStatus:
                printf("%s: (%i,%i)\n"
                       ,renderComponents[i].model
                       , positionComponents[i].x
                       , positionComponents[i].y);
                break;

            default:
                break;
        }
    }
    printf("=======================================\n");
}

void initCmps(int time);
void RunSystems(int time) {
    printf("Run simulation %i.\n", time);
    initCmps(time);
    RunScriptSystem(time);
    RunTransformSystem(time);
    RunRenderSystem(time);
}

int main(int argc, const char * argv[])
{
    int time = 0;
    for (int i=0; i<MAX_ENTITIES; ++i) {
        componentsStatus[i] = noStatus;
    }
    printf("Starting simulation!\n");
    while (1) {
        RunSystems(time++);
        sleep(1);
    }
    return 0;
}

//Game stuff:

char chickenModel[] = "kooot";
char coyoteModel1[] = "yip";
char coyoteModel2[] = "howwwwwwwwl";

void moveScript(int id, int time)
{
    movementComponents[id].x += rand() % 3 - 1;
    movementComponents [id].y += rand() % 3 - 1;
}

void coyoteScript(int id, int time)
{
    if(rand()%5 < 3)
    {
        renderComponents[id].model = coyoteModel1;
        moveScript(id, time);
    }
    else{
        renderComponents[id].model = coyoteModel2;
    }
}

void initCmps(int time) {

    for (int i=0; i<MAX_ENTITIES; ++i) {
        if (componentsStatus[i] == noStatus) {
            if (i==0) {
                scriptComponents[i].scriptPtr = &coyoteScript;
                renderComponents[i].model = coyoteModel1;
            }
            else {
                scriptComponents[i].scriptPtr = &moveScript;
                renderComponents[i].model = chickenModel;
            }
            positionComponents[i].x = rand() % GRID_X;
            positionComponents[i].y = rand() % GRID_Y;
            componentsStatus[i] = goStatus;
        }
    }
}

```

*A real implementation would allocate IDs to each component and would not rely on the array index as the entity ID.*

OOP languages simplify the implementation of features in entity systems, most notably the management of the components themselves, the handling of messages and other tasks shared by components... But ECS and OOP are not directly related.
> 3 votes

# Answer
If you are referring to a Components-Based Entity System (CBES), then the answer is "it is reliant on OOP" rather than "it is a kind of OOP", since components refer to an OOP class that holds both state and functionality for that entity aspect represented by the component (whether it be physics, or AI, or a weapon slot, or a view representation).

In contrast, I couldn't quite see a CBES existing in something like functional programming, where there cannot be a single "object" representing both state and functionality, since these are not bundled together in FP as they are in OOP.
> 1 votes

# Answer
I think that Entity-Component Systems lend themselves much better to data-oriented design rather than object-oriented design, as long as you're willing to use components only for storing data, in which case I would choose the term "properties" over "components". You can think of all the data that the entities hold as being in a big table. Each row of the table stores all the data for a single property for every entity. Each column of the table represents an entity as a whole.

```
// Property table
Vector position     [MAX_ENTITIES];
Vector velocity     [MAX_ENTITIES];
Vector acceleration [MAX_ENTITIES];
Sprite sprite       [MAX_ENTITIES];
Vector spriteOffset [MAX_ENTITIES];

// The entity with ID 2 is the aggregation of position[2], velocity[2], etc.

```

Systems are responsible for doing operations on that data, where the same operation is performed on every entity. For example, one operation the movement system might perform would be calculating the effects of an object's acceleration and velocity.

```
// Accelerates and moves entities
void UpdateEntityMovement(float deltaTime)
{
    for(int i = 0; i < MAX_ENTITIES; i++)
    {
        acceleration[i].y -= 9.8 * deltaTime; // Gravity
        velocity[i] += acceleration[i] * deltaTime; // v = at
        position[i] += velocity[i] * deltaTime; // d = vt
    }
}

// Draws all sprite-based entities
void DrawEntities()
{
    for(int i = 0; i < MAX_ENTITIES; i++)
    {
        DrawSprite(sprite[i], position[i] - spriteOffset[i]);
    }
}

```

The advantages of this design are not limited to the flexibility you get. Data-oriented programming is much friendlier in terms of cache performance, and it's easy to multithread any independent operation like in *UpdateEntityMovement()*, so DOD is very scalable in terms of current-gen hardware developments.

---

**More information on DOD:**

http://gamesfromwithin.com/data-oriented-design

http://knight666.com/blog/tutorial-a-practical-example-of-data-oriented-design/
> 1 votes

# Answer
It's definitely OOP - just advanced OOP. The classic (Gamma) Design Pattern book even documents this kind of solution, though not as an explicit pattern but under others. The section 'inheritance versus composition' explains the concept well. Somewhere the disadvantage of the 'component systems' is mentioned: **systems relying heavily on object composition are difficult to learn and harder to debug**.

Each component encapsulates a different aspect about your game entities. The data and logic pertaining to this aspect is moved out from the entity. This is normal, not a violence of the encapsulation. The Visitor pattern also does something similar - you move out operations/methods of a class into different classes, in order to have a maintenable system.
> 0 votes

---
Tags: component-based, entity-system, oop
---


# Question
Title: Matrix interpolation for animation blending
I use the XNA Animation Component library to perform blending between animations. It uses spherical linear interpolation between matrices.

In most cases this works without problems. However, I have one model where all of the animations are blended wrong. Weird rotation and warping of the model occurs.

I was told by a math expert that the problem may lie in the method that does the matrix interpolation. He said: "The right way to do it would be to decompose A=UP (polar decomposition), obtain quaternion from U and lerp/slerp it, while interpolating P component-wise. I'm not sure why the original author refrained from implementing the polar decomposition as its implementation is straightforward and easy."

I have included the code below.

I need some help in making the recommended changes. I am an expert in C# but know almost nothing about matrix interpolation.

```
private static Quaternion qStart, qEnd, qResult;
private static Vector3 curTrans, nextTrans, lerpedTrans;
private static Vector3 curScale, nextScale, lerpedScale;
private static Matrix startRotation, endRotation;
private static Matrix returnMatrix;

public static void SlerpMatrix(
        ref Matrix start,
        ref Matrix end,
        float slerpAmount,
        out Matrix result)
    {
        if (start == end)
        {
            result = start;
            return;
        }
        // Get rotation components and interpolate (not completely accurate but I don't want
        // to get into polar decomposition and this seems smooth enough)
        Quaternion.CreateFromRotationMatrix(ref start, out qStart);
        Quaternion.CreateFromRotationMatrix(ref end, out qEnd);
        Quaternion.Lerp(ref qStart, ref qEnd, slerpAmount, out qResult);

        // Get final translation components
        curTrans.X = start.M41;
        curTrans.Y = start.M42;
        curTrans.Z = start.M43;
        nextTrans.X = end.M41;
        nextTrans.Y = end.M42;
        nextTrans.Z = end.M43;
        Vector3.Lerp(ref curTrans, ref nextTrans, slerpAmount, out lerpedTrans);

        // Get final scale component
        Matrix.CreateFromQuaternion(ref qStart, out startRotation);
        Matrix.CreateFromQuaternion(ref qEnd, out endRotation);
        curScale.X = start.M11 - startRotation.M11;
        curScale.Y = start.M22 - startRotation.M22;
        curScale.Z = start.M33 - startRotation.M33;
        nextScale.X = end.M11 - endRotation.M11;
        nextScale.Y = end.M22 - endRotation.M22;
        nextScale.Z = end.M33 - endRotation.M33;
        Vector3.Lerp(ref curScale, ref nextScale, slerpAmount, out lerpedScale);

        // Create the rotation matrix from the slerped quaternions
        Matrix.CreateFromQuaternion(ref qResult, out result);

        // Set the translation
        result.M41 = lerpedTrans.X;
        result.M42 = lerpedTrans.Y;
        result.M43 = lerpedTrans.Z;

        // Add the lerped scale component
        result.M11 += lerpedScale.X;
        result.M22 += lerpedScale.Y;
        result.M33 += lerpedScale.Z;
    }

```

# Answer
The scale computation looks wrong to me. It should be obtained by dividing, not subtracting (with additional checks for divisions by zero), then it should be applied by multiplying (not adding) each column or each row of the final rotation matrix (not just the diagonal term).

If you're fluent in C# you probably have realised that the code is very poor quality. Reading and writing to static member variables from a static method instead of local variables is a good indication of code smell.

Anyway, here is a much simpler version which makes use of the decomposition methods available in XNA:

```
public static void SlerpMatrix(
        ref Matrix start,
        ref Matrix end,
        float slerpAmount,
        out Matrix result)
    {
        Quaternion qStart, qEnd, qResult;
        Vector3 curTrans, nextTrans, lerpedTrans, curScale, nextScale, lerpedScale;

        start.Decompose(out curScale, out qStart, out curTrans);
        end.Decompose(out nextScale, out qEnd, out nextTrans);

        Quaternion.Lerp(ref qStart, ref qEnd, slerpAmount, out qResult);
        Vector3.Lerp(ref curTrans, ref nextTrans, slerpAmount, out lerpedTrans);
        Vector3.Lerp(ref curScale, ref nextScale, slerpAmount, out lerpedScale);

        result = Matrix.CreateScale(lerpedScale)
               * Matrix.CreateFromQuaternion(qResult)
               * Matrix.CreateTranslation(lerpedTrans);
    }

```
> 3 votes

# Answer
Hard to tell from just the code, but a common issue with quaternion interpolation is that 2 (antipodal) quaternions represent the same rotation. If matrix -\> quaternion ever returns the 'wrong' one in one of the two cases, your lerp is going to put you at 0 which will lead to all sorts of nonsense. Also your scale calc looks bogus as Sam mentioned ;)
> 0 votes

---
Tags: xna, quaternion, skeletal-animation
---


title: Libgdx optimization of big arrays

text:
# Question
Title: Libgdx optimization of big arrays
I am working on a game using libgdx and I have the following code that I want to optimize.

```
    Array<Bullet> enemyBullets = Enemy2.getEnemyBullets();
    for (Bullet bullet : enemyBullets) {
        c = bullet.getHitBox();
        debugRenderer.circle(c.x, c.y, c.radius, 5);
    }

```

Basically I just have a big array of objects that I want to preform some action on and I am not sure if this is the best way to do it. I'm not sure if it would be better to use a pool or try to use an iterator instead. I am just not really familiar with these things and I need some help.

# Answer
> 4 votes
If you follow this guide: http://developer.android.com/training/articles/perf-tips.html

Your method is the best approach, just remember to call the array from a reference that is in the same scope as your loop. Also, if possible, remove the "getHitBox" method, and get the object through public variables. Yes, this is ugly, but can be used in performance critical region for a small boost...

# Answer
> 1 votes
Reverse your loop:

> for (int i = enemyBullets.size - 1; i \>= 0; i--) {
> c = enemyBullets\[i\].getHitBox();
> debugRenderer.circle(c.x, c.y, c.radius, 5);
> }

The check 'i \>= 0' is faster because it doesn't need to load the variable that holds the size, for each iteration.

# Answer
> 0 votes
I think a general rule of most languages is that something like this is faster (not necessarily safer):

```
int count = enemyBullets.size;
for(int i=0;i<count;i++) {
    c = enemyBullets[i].getHitBox();
    debugRenderer.circle(c.x, c.y, c.radius, 5);
}

```

But it doesn't account for the fact that your collection could change inside the block.

For doing something like debugging, is this a considerable issue? Obviously, you wont run the debug renderer in your final game but for what you are debugging, is the for loop you're using causing issues?

---
Tags: android, performance, libgdx
---


# Question
Title: How fast do games in Flash C++ Compiler execute compared to C++?
Flash Player can now run C++ code, that is cross complied with the Adobe Flash C++ Compiler. How fast does such code run in comparison to a C++ application running as an EXE, in the context of gaming?

And does GPU rendering performance compare with C++ applications? Or is Flash far behind?

# Answer
**GPU rendering speed** for 3D FlasCC games/apps is likely to be similar to C++ apps for obvious reasons - the actual rendering takes place on the GPU. Flash includes a cross-platfrom shader language (AGAL) to describe GPU kernels (programs run per pixel on the GPU).

**CPU/computing speeds** however at best reaches 15% the speed of MS VC++ on Windows (tested with a simple encryption function operating on an array of bytes). Some benchmarks for the latest FlasCC are available here, that compare a set of C++ programs running as an EXE and in Flash Player.

This essentially comes down to:

* Anything you can move to the GPU can possibly be done close to native speeds. This includes rendering, lighting, mip-mapping, and to some extent physics operations (depends on the library)
* Anything still done on the CPU will be a few *times* slower than C++, so don't expect to have a million moving objects on screen with full physics even if you can do that with the native (C++) library.
* Flash vector graphics does not use the GPU and is rendered fully on the CPU. So if you need HUDs (heads up displays) with high-performance 3D vector rendering like what Scaleform provides for C++ apps, don't expect that to be easily possible in Flash Player, unless you're willing to roll your own 3D vector renderer that takes advantage of the GPU to composite vector shapes.
> 2 votes

---
Tags: c++, flash, performance
---


title: Generated 3d tree meshes

text:
# Question
Title: Generated 3d tree meshes
I did not find a question on these lines yet, correct me if I'm wrong.

Trees (and fauna in general) are common in games. Due to their nature, they are a good candidate for procedural generation.

There's SpeedTree, of course, if you can afford it; as far as I can tell, it doesn't provide the possibility of generating your tree meshes at runtime. Then there's SnappyTree, an online webgl based tree generator based on the proctree.js which is some ~500 lines of javascript.

One could use either of above (or some other tree generator I haven't stumbled upon) to create a few dozen tree meshes beforehand - or model them from scratch in a 3d modeller - and then randomly mirror/scale them for a few more variants..

But I'd rather have a free, linkable tree mesh generator.

Possible solutions:

* Port proctree.js to c++ and deal with the open source license (doesn't seem to be gpl, so could be doable; the author may also be willing to co-operate to make the license even more free).
* Roll my own based on L-systems.
* Don't bother, just use offline generated trees.
* Use some other method I haven't found yet.

**Update 2015**: ended up porting proctree.js to c++ https://github.com/jarikomppa/proctree

# Answer
I've done a fair bit of work in this area, although most of my demos are older:

(flash 2010)
http://genesisbbs.com/appstem.html (click and drag mouse)
http://genesisbbs.com/appstem2.html
(directX 2006)
http://vimeo.com/5206795

I highly encourage you to roll your own, if you are doing this for fun. You will almost certainly need to work with Quaternions. Understanding them is very hard, but you don't need to go too deep to use them. Think of a quaternion as a vector with an extra component: rotation. If you want your plants to twist and turn as they grow, they will need quaternions.

Other things to learn:
Lichtenberg Figures
Laplacian Growth
Voronoi Diagrams
Nearest Neighbor algorithms (google them)

I (personally) would discourage the use of L-Systems, other than to perhaps dictate a grammar for what grows where, i.e. \[seed -\> \[root\] / \[trunk-\>branch-\>\[flower/leaf\]\]. L systems are not good for responding to environmental stimuli like sunlight direction, gravity, obstacles, etc.

As for speed concerns, a single tree can be generated in realtime. For memory purposes and performance though, you will likely only want to generate a small set of trees and instance them a bit if you are dealing with forests.

Most existing tree generators are not that great (IMHO), besides the high-end ones used for Maya and such.

I also highly, highly recommend using voxels to generate the tree (then skin with a mesh if needed). The advantage of voxels is that you can easily simulate growth algorithms using things like Laplacian growth and various automata (not Conway's game of life, but other rules produce interesting results).
> 12 votes

# Answer
Personally I would probably start with pre-generated trees and only once I'd have a kick-ass forest rendering engine - complete with bushes, grass, mushrooms and stuff - would I start looking if I need more variable tree meshes.

That being said, you could take a look at ngPlant. It includes a GPL procedural tree modeler app, but the libraries that do all the heavy lifting are BSD licensed. It's written in C++.

For the forest rendering, there is (MIT licensed) Paged Geometry for Ogre rendering engine.
> 3 votes

# Answer
The main problem with procedural trees is not generating them, but rendering them all every frame at runtime. This is the reason you will see many identical trees in AAA games, it's not that they couldn't implement or write tech that created unique trees, it's that it would mean you'd have to cut out a load of other features for the game to run.

If you have many identical trees, you can rotate them and possibly scale them uniformly to make them look different from every angle, and since they are identical you can instance them in order to save precious milliseconds each frame.

Just thinking about this problem for a second, there might be a happy medium - how about you generate a few different tree parts, trunks, branches, leaves etc.. but ones that all fit together in modular ways, like tree lego. Then you could have many combinations and so some quite unique trees, but you could also instance all of the many parts for a faster running game.
> 3 votes

# Answer
This is a neat little solution, and I have used it in a project and can tell you it is fast enough to gen trees on the fly why the game is running. It's certainly not detailed, but if you got rid of the billboards it could be pretty neat.

http://ltrees.codeplex.com/
> 1 votes

# Answer
I stumbled across tree\[d\] some time ago... I used it for only a small amount of time to test a project but that was only because I stopped development - the tool gives you a wide range of generator options to play with and, from what I remember, is quite fast. A link is below.

The downside is that it isn't a tree generator that you can incorporate. You'd have to pre-generate a few trees and then modify the data when placing them at run-time to tweak their uniqueness.

> Best of all TreeD is free to use, and you can include the trees you make in your own projects, commercial or free, as long as they are not model packs, texture packs, 3D model generators, or texture generators.
> 1 votes

---
Tags: 3d, procedural-generation, tree, mesh
---


title: Particle systems on multiplayer games

text:
# Question
Title: Particle systems on multiplayer games
I'm working on a 2D javascript/Three.js multiplayer game, using web sockets and an authoritative server currently written in Python.

The combat mechanic will be similar to Geometry Wars however i'm struggling to get my head around how to implement this in an efficient way.

There are several drawbacks/concerns I need to take into account:

* Efficiency is key
* Three.js particle systems aren't mutable, you cannot add or remove particles once the system has been created, only move them off screen
* All calculations with respect to collision and damage must be done server side
* My game currently implements entity interpolation with fixed time step updates from the server
* Potentially several different weapons/projectile types

I can see several solutions:

**Handle each 'bullet' particle individually**

Pros

* Most accurate way of doing thigs

Cons

* Slow on server
* Lots of bandwidth
* Hard to batch draw objects, will have to draw each individually

**Use ray casting on server and have some form of network synced particle emitter**

Pros

* Much easier on the server and network

Cons

* Network synching issues
* What happens when a bullet hits an object? Bullet will pass right through

**Use ray casting on server for collision/damage and use raycasting on client for more accurate particles**

Pros

* Much easier on the server and network
* Will look more accurate

Cons

* May still have some synching issues
* More work for the client

Obviously the amount of players currently connected will have an impact on the implementation, I would ideally like to allow hundreds of players to share a game world but there may only ever by 20 or so on screen at once.

The mutable particle system is an issue for all of these but I would still like to use it as it is more efficient that drawing each particle individually. In a test I could have over 10000 particles all moving and still get 60fps.

Any help or comments on my though process would be greatly appreciated. Is there another approach that would be better?

# Answer
> 2 votes
Your players may hack your game. Verifying things on the server is good to combat that but potentially bad for performance.

Collision detection can fail if not done carefully. Say the particle is moving quickly and you're only testing for intersection with an object. If the particle moves from one side of the object, through the object, and on to the far side within one simulation time step then you don't detect a valid hit.

You might look at how ogre3d does particles. It sounds very similar to what you're looking at.

---
Tags: game-design, networking, particles, websocket, three.js
---


title: Server side game loop

text:
# Question
Title: Server side game loop
Many java games use thread.sleep() to controll fps. Since the server does not display graphics, should the server game loop keep running just calculating delta time? Like this example:

```
long lastLoopTime = System.nanoTime();
final int TARGET_FPS = 60;
final long OPTIMAL_TIME = 1000000000 / TARGET_FPS;

while (gameRunning)
{
   long now = System.nanoTime();
   long updateLength = now - lastLoopTime;
   lastLoopTime = now;
   double delta = updateLength / ((double)OPTIMAL_TIME);

   doGameUpdates(delta);
}

```

# Answer
> 6 votes
There are many reasons I wouldn't suggest that:

1. Computer resources are valuable. even if they are free, you shouldn't waste them. consider the case where two or more server are running simultaneously on one computer. If a single instance of server consumes all CPU cycles, other instances will simply fail. Surly OS will try to handle this kinda greedy behavior but it'll come with a cost. You won't know where will OS pause your process and give CPU cycles to the other one. Also you might want to release your server along side the actual game, so that players could initiate their own LAN games. It's kinda annoying if I have dedicate one of my CPU cores just to run a game server!
2. Most games, Specially networked synchronized games, use fixed time-step. simply because they want to be able to predict what is going to happen client side. Dynamic time step is great for so many reasons as long as you are running a single instance of your game and it's not going to be synchronized with anywhere else. It'll grant you the power of the system running the game to it's fullest extent. But again there is a price for it. You won't be able to predict what is going to happen if you run the game again. consider simple physics collision, where a box is hitting another box. Even slightest change in time step will result in big differences in the resulting collision resolution.
3. There is a simple reason why people use Thread.Sleep as you suggested, because adding more precision will not result in a better game. When you are playing a game, you usually won't notice if an object is one or two pixels off. So you won't gain anything by increasing accuracy. Also there is a network band width limit, both server side and client side. Meaning you usually won't be able to send more than 30-60 updates per second. So I can ask why should you compute states you are simply going to throw away?
4. There are many cases where increasing precision might cause trouble. For example people tend to use "Vertical synchronization" so that graphics buffer is not updated while it's sending data to the monitor (which might result in shattering). Also most games use floats as their primary number container but they are not precise. You might not notice when numbers are between 2^-20 and 2^20 but outside that range you'll see inaccurate behaviors. For example if you try adding 10^-5 to 10^5 it simply ignores your addition. These kinda errors are not usually visible, but when you don't have a full control over your time step, things might get ugly. In your case, since there is no rendering involved I'll assume your update time should be something around 10^-4 at most, meaning all changes for numbers above 100 will be messed up! using doubles will fix this problem but as I said before it won't necessarily result in a better gaming experience.
5. In some games, it's only player commands that will make an unpredictable differences. so you might want to only use your server to broadcast each player's commands to the other players. In these cases you could simply wait for until any of the clients send the server an update. There is nothing to calculate between those updates, meaning clients can do everything (beside broad casting) so let the server only do it's job and leave anything else to the clients.

# Answer
> 4 votes
You should read this (Semi-fixed or Fully-fixed timestep?) and this (Gaffer on Games - Fix your Timestep).

I'm not sure why you're including a target FPS in your server logic. Find a fixed time step that works for you and update according to that.

Basically you'll have another while loop inside your `while (gameRunning)` loop that will accumulate time until it's ready to do an update. Then you're doing updates at fixed intervals.

---
Tags: java, server, game-loop
---