title: Converting 2D Physics to 3D

text:
# Question
Title: Converting 2D Physics to 3D
I'm new to game physics and I am trying to adapt a simple 2D ball simulation for a 3D simulation with the Java3D library. I have this problem:

Two things:

1) I noted down the values generated by the engine: ***X/Y*** are too high and ***minX/minY/maxY/maxX*** values are causing trouble.

*Sometimes the balls are drawing but not moving*

*Sometimes they are going out of the panel*

*Sometimes they're moving on little area*

*Sometimes they just stick at one place...*

2) I'm unable to select/define/set the default correct/suitable values considering the 3D graphics scaling/resolution while they are set with respect to 2D screen coordinates, that is my only problem.

Please help.

This is the code:

```
public class Ball extends GameObject {
    private float x, y; // Ball's center (x, y)
    private float speedX, speedY; // Ball's speed per step in x and y
    private float radius; // Ball's radius
    // Collision detected by collision detection and response algorithm?
    boolean collisionDetected = false;

    // If collision detected, the next state of the ball.
    // Otherwise, meaningless.
    private float nextX, nextY;
    private float nextSpeedX, nextSpeedY;

    private static final float BOX_WIDTH = 640;
    private static final float BOX_HEIGHT = 480;

    /**
     * Constructor The velocity is specified in polar coordinates of speed and
     * moveAngle (for user friendliness), in Graphics coordinates with an
     * inverted y-axis.
     */
    public Ball(String name1,float x, float y, float radius, float speed,
            float angleInDegree, Color color) {
        this.x = x;
        this.y = y;
        // Convert velocity from polar to rectangular x and y.
        this.speedX = speed * (float) Math.cos(Math.toRadians(angleInDegree));
        this.speedY = speed * (float) Math.sin(Math.toRadians(angleInDegree));
        this.radius = radius;
    }

    public void move()  {
        if (collisionDetected) {
            // Collision detected, use the values computed.
            x = nextX;
            y = nextY;
            speedX = nextSpeedX;
            speedY = nextSpeedY;
        } else {
            // No collision, move one step and no change in speed.
            x += speedX;
            y += speedY;
        }
        collisionDetected = false; // Clear the flag for the next step
    }

    public void collideWith()  {
        // Get the ball's bounds, offset by the radius of the ball
        float minX = 0.0f + radius;
        float minY = 0.0f + radius;
        float maxX = 0.0f + BOX_WIDTH - 1.0f - radius;
        float maxY = 0.0f + BOX_HEIGHT - 1.0f - radius;

        double gravAmount = 0.9811111f;
        double gravDir = (90 / 57.2960285258);

        // Try moving one full step
        nextX = x + speedX;
        nextY = y + speedY;
        System.out.println("In serializedBall in collision.");

        // If collision detected. Reflect on the x or/and y axis
        // and place the ball at the point of impact.
        if (speedX != 0) {
            if (nextX > maxX) { // Check maximum-X bound
                collisionDetected = true;
                nextSpeedX = -speedX; // Reflect
                nextSpeedY = speedY; // Same
                nextX = maxX;
                nextY = (maxX - x) * speedY / speedX + y; // speedX non-zero
            } else if (nextX < minX) { // Check minimum-X bound
                collisionDetected = true;
                nextSpeedX = -speedX; // Reflect
                nextSpeedY = speedY; // Same
                nextX = minX;
                nextY = (minX - x) * speedY / speedX + y; // speedX non-zero
            }
        }
        // In case the ball runs over both the borders.
        if (speedY != 0) {
            if (nextY > maxY) { // Check maximum-Y bound
                collisionDetected = true;
                nextSpeedX = speedX; // Same
                nextSpeedY = -speedY; // Reflect
                nextY = maxY;
                nextX = (maxY - y) * speedX / speedY + x; // speedY non-zero
            } else if (nextY < minY) { // Check minimum-Y bound
                collisionDetected = true;
                nextSpeedX = speedX; // Same
                nextSpeedY = -speedY; // Reflect
                nextY = minY;
                nextX = (minY - y) * speedX / speedY + x; // speedY non-zero
            }
        }

        speedX += Math.cos(gravDir) * gravAmount;
        speedY += Math.sin(gravDir) * gravAmount;
    }

        public float getSpeed()  {
        return (float) Math.sqrt(speedX * speedX + speedY * speedY);
    }

    public float getMoveAngle()  {
        return (float) Math.toDegrees(Math.atan2(speedY, speedX));
    }

    public float getRadius()  {
        return radius;
    }

    public float getX() {
        return x;
    }

    public float getY() {
        return y;
    }

    public void setX(float f) {
        x =  f;
    }

    public void setY(float f) {
        y =  f;
    }
}

```

Here's how I'm drawing the balls:

```
public class 3DMovingBodies extends Applet implements Runnable {

    private static final int BOX_WIDTH = 800;
    private static final int BOX_HEIGHT = 600;
    private int currentNumBalls = 1; // number currently active

    private volatile boolean playing;
    private long mFrameDelay;
    private JFrame frame;

    private int currentFrameRate;
    private Ball[] ball = new Ball[currentNumBalls];

    private Random rand;
    private Sphere[] sphere = new Sphere[currentNumBalls];
    private Transform3D[] trans = new Transform3D[currentNumBalls];
    private TransformGroup[] objTrans = new TransformGroup[currentNumBalls];

    public 3DMovingBodies() {

        rand = new Random();
        float angleInDegree = rand.nextInt(360);

        setLayout(new BorderLayout());
        GraphicsConfiguration config = SimpleUniverse
                .getPreferredConfiguration();
        Canvas3D c = new Canvas3D(config);
        add("Center", c);

        ball[0] = new Ball(0.5f, 0.0f, 0.5f, 0.4f, angleInDegree, Color.yellow);
        // ball[1] = new Ball(1.0f, 0.0f, 0.25f, 0.8f, angleInDegree,
        // Color.yellow);
        // ball[2] = new Ball(0.0f, 1.0f, 0.15f, 0.11f, angleInDegree,
        // Color.yellow);

        trans[0] = new Transform3D();
        // trans[1] = new Transform3D();
        // trans[2] = new Transform3D();

        sphere[0] = new Sphere(0.5f);
        // sphere[1] = new Sphere(0.25f);
        // sphere[2] = new Sphere(0.15f);
        // Create a simple scene and attach it to the virtual universe
        BranchGroup scene = createSceneGraph();

        SimpleUniverse u = new SimpleUniverse(c);
        u.getViewingPlatform().setNominalViewingTransform();

        u.addBranchGraph(scene);

        startSimulation();
    }

    public BranchGroup createSceneGraph() {
        // Create the root of the branch graph
        BranchGroup objRoot = new BranchGroup();

        for (int i = 0; i < currentNumBalls; i++) {

            // Create a simple shape leaf node, add it to the scene graph.

            objTrans[i] = new TransformGroup();
            objTrans[i].setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE);
            Transform3D pos1 = new Transform3D();
            pos1.setTranslation(randomPos());
            objTrans[i].setTransform(pos1);
            objTrans[i].addChild(sphere[i]);

            objRoot.addChild(objTrans[i]);
        }

        BoundingSphere bounds = new BoundingSphere(new Point3d(0.0, 0.0, 0.0),
                100.0);

        Color3f light1Color = new Color3f(1.0f, 0.0f, 0.2f);
        Vector3f light1Direction = new Vector3f(4.0f, -7.0f, -12.0f);
        DirectionalLight light1 = new DirectionalLight(light1Color,
                light1Direction);
        light1.setInfluencingBounds(bounds);
        objRoot.addChild(light1);

        // Set up the ambient light
        Color3f ambientColor = new Color3f(1.0f, 1.0f, 1.0f);
        AmbientLight ambientLightNode = new AmbientLight(ambientColor);
        ambientLightNode.setInfluencingBounds(bounds);
        objRoot.addChild(ambientLightNode);

        return objRoot;
    }

    public void startSimulation() {
        playing = true;
        Thread t = new Thread(this);
        t.start();
    }

    public void stop() {
        playing = false;
    }

    public void run() {

        long previousTime = System.currentTimeMillis();
        long currentTime = previousTime;
        long elapsedTime;
        long totalElapsedTime = 0;
        int frameCount = 0;

        while (true) {
            currentTime = System.currentTimeMillis();
            elapsedTime = (currentTime - previousTime); // elapsed time in
            // seconds
            totalElapsedTime += elapsedTime;
            if (totalElapsedTime > 1000) {
                currentFrameRate = frameCount;
                frameCount = 0;
                totalElapsedTime = 0;
            }
            for (int i = 0; i < currentNumBalls; i++) {
                ball[i].move();
                ball[i].collideWith();
                drawworld();
            }

            try {
                Thread.sleep(88);
            } catch (Exception e) {
                e.printStackTrace();
            }
            previousTime = currentTime;
            frameCount++;
        }
    }

    public void drawworld() {

        for (int i = 0; i < currentNumBalls; i++) {
            printTG(objTrans[i], "SteerTG");
            trans[i].setTranslation(new Vector3f(ball[i].getX(),
                    ball[i].getY(), 0.0f));
            objTrans[i].setTransform(trans[i]);
        }
    }

    private Vector3f randomPos()
    /*
     * Return a random position vector. The numbers are hardwired to be within
     * the confines of the box.
     */
    {
        Vector3f pos = new Vector3f();
        pos.x = rand.nextFloat() * 5.0f - 2.5f; // -2.5 to 2.5
        pos.y = rand.nextFloat() * 2.0f + 0.5f; // 0.5 to 2.5
        pos.z = rand.nextFloat() * 5.0f - 2.5f; // -2.5 to 2.5
        return pos;
    } // end of randomPos()

    public static void main(String[] args) {
        System.out.println("Program Started");
        3DMovingBodiesbb = new 3DMovingBodies();
        bb.addKeyListener(bb);
        MainFrame mf = new MainFrame(bb, 600, 400);
    }
}

```

# Answer
i think the easiest way to solve your problem is to change your camera type from prespective to isometric, that will solve the problem you are facing, but if you want to realy render tour scene with perspective features you have to change your set position function, the whole idea is to find a position where a ray hits a plane right in front of the camera, you have to compute what ray is using x/y your physics engine (ray's starting point is your camera and it's direction is based on the x/y of your object) and the plane it hits is perpendicular to camera direction right in from of it.
> 1 votes

---
Tags: 3d, java, physics, physics-engine
---


title: moving 2D camera

text:
# Question
Title: moving 2D camera
I've got a camera that places the character about a 1/4 way into the screen. The problem I'm having is that when the character moves left the character stays in place now placing the character 3/4 the way into the screen. I tried rectifying the issue with the following code.

```
public Vector2 Position = Vector2.Zero;
        public Matrix TransformMatrix
        {
            get
            {
                return Matrix.CreateTranslation(new Vector3(-Position, 0f));
            }
        }

        public void LockToTarget(Vector2 charPosition,Rectangle bounds, int screenWidth, int screenHeight, bool direction)
        {
            float multiplyBy = 0;

             if(direction)
                 multiplyBy = 0.25f;
             else if(!direction)
                 multiplyBy = 0.75f;

             Position.X = charPosition.X + (bounds.Width * multiplyBy) - (screenWidth * multiplyBy);
             Position.Y = charPosition.Y + (bounds.Height / 2) - (screenHeight / 2);
        }

```

it pretty much gets a boolean value telling it if the character is moving towards the left or right (true = right, false = left), the problem is that the when the character starts moving from on direction to another he simply jumps to the other side of the screen and I'm not sure how to get the camera to move position instead.

any help with this would be really great.

# Answer
> 2 votes
This is because you're setting the position of the camera right away. This will make the camera jump from one position to another when you change direction, therefore giving the illusion that your player is jumping.

Since you're using XNA, you could use the magic of MathHelper.Lerp to progressively change from one position to another:

```
const float CAM_LERP_FACTOR = 0.2f; // change this to what you prefer
float newX = charPosition.X + (bounds.Width * multiplyBy) - (screenWidth * multiplyBy);
Position.X = MathHelper.Lerp(Position.X, newX, CAM_LERP_FACTOR);

```

By playing with the values of the lerp factor (I usually choose a value between 0.1f and 0.2f) you should get an interesting effect.

---
Tags: xna, 2d, c#, camera
---


title: Draw and update order in 3d graphics

text:
# Question
Title: Draw and update order in 3d graphics
In all of the code samples that I have looked at, the game loop looks something like this:

```
while(true)
{
   InputAndUpdate();
   Draw();

   SwapBuffers();
}

```

However doesn't this destroy parallelism between the CPU and the GPU? After the swap buffers call, the GPU will be sitting there idly while the CPU is handling input and updating. Then when the CPU has finished issuing draw commands, it waits until the GPU is finished rendering. Why isn't it done like this? :

```
while(true)
{
   Draw(); //First issue the draw commands
   InputAndUpdate(); //Update while the GPU is busy rendering

   SwapBuffers(); //Now block and wait for the GPU to finish
}

```

# Answer
> 5 votes
This would be true unless you have an extra back buffer to render into (double-buffering). That allows the CPU to carry on and do stuff without having to wait for the actual buffer swap to occur (which would normally be the case as you couldn't start modifying the back buffer until it had been copied to the front buffer without risk of corrupting what you just rendered). When a draw call or swap is made, the request goes into a buffer of commands that the GPU can process, allowing the CPU to get on with doing other things while the GPU runs behind. This is how modern hardware gets parallelism. I believe D3D has a limit on just how many frames you can render ahead before a "Swap" will block (you'd need multiple back buffers to achieve this - also the more you buffer up the more latency you can potentially introduce between the input method and what is appearing on screen).

The concept of a game loop like either example above is quite dated. With the introduction of multiple processing units on the CPU you could potentially be doing rendering on one thread while doing some "update" work on one or more others. You might want to look into the concept of job queues to help maximise all the CPU processing power available.

# Answer
> -1 votes
the solution you sied doesn't accualy make CPU and GPU to work parrarel, it just changes the order they are waiting for each other, since as the other answer implys draw always put it's results into a backbuffer and using swapbuffers you only change what is monitor shoing with the latest thing drawn, to take full potential of both CPU and GPU you have to call draw and update in two diffrent threads and use another second buffer for what CPU is doing (so that when CPu is generating update results in buffer 2 GPU read from Buffer 1 and when CPU is working with Buffer 1 GPu use Buffer 2 just like swap buffers GPU uses to prevent changes in frame already drawn)

---
Tags: architecture, rendering, game-loop
---


# Question
Title: Which is better, one big level model or multiple smaller level models?
I am writing a game in XNA 4 and I want to have something like a corridor. Do you think that is better to use one big and solid model, or to use multiple small parts (window, stairs, door...)?

# Answer
In terms of graphics rendering, one large mesh is faster to draw than several smaller meshes.

If you're talking about something like a corridor, it's probably not going to be that intensive for the GPU if you send it in as a door and a floor and some walls. The smaller meshes also allow you to fiddle with positioning more easily.

If your drawing becomes a bottleneck, then consider it.
> 8 votes

# Answer
I'd suggest keeping the door as a separate model, unless you're certain you never want to be able to open it.

Windows if they are transparent also want to be separate models so they can be depth sorted appropriately for rendering.

Everything else should probably be a single model and texture for best performance, and to eliminate any cracks where they join together.
> 5 votes

# Answer
If your level has too much detail you should split it in parts and apply some frustum culling to draw only currently visible meshes.
> 3 votes

# Answer
in most cases using small parts are worth it because it gives your code reusability and flexibility; and in case of a corridor or something similar that does not include MANY (many would mean a number like at least 40) smaller parts, the performance gain of using a big and solid models is negligible(except if you are drawing the object many times per frame).

if you care about the performance i recommend precomputing the lighting or using some kind of vertex arrays(vertex buffers?) which would actually make a difference. ( if those things are possible in XNA - i dont know a lot about XNA )

p.s. : the first paragraph of this post is correct only about drawing ( not about for example using separate physics models for parts of the corridor )
> 1 votes

---
Tags: xna-4.0, models, assets, level-design
---


title: Should I be subclassing CCSprites?

text:
# Question
Title: Should I be subclassing CCSprites?
When I am working with cocos2d I can add CCSprites to the layer or 'stage' and manipulate them.

Now, to do my ongoing calculations for movement AI and such, things that will always run, should I:

subclass CCSprites and add methods to manipulate themselves and run schedules?

-OR-

create a controller class that 'owns' all of the CCSprites and manipulate them from the 'outside'? I am not really sure what would be accessible from the outside though.

My guess is that I should probably subclass the CCSprite object, I could have a different object that inherits from CCSprite for each type of sprite needed.

Player, Enemy, PowerUp, Bullet, etc...

Or what do you think?

# Answer
> 3 votes
It's often better to prefer composition to inheritance.

In this specific case, I would strongly advise against using inheritance to arrive at a solution. What you are trying to do is take a sprite, which is naturally a rendering entity, and inject into it some methods and data for handling responsibilities outside its domain -- namely what sounds like AI and pathfinding. This is violating the single responsibility principle.

A far superior solution would be to have some kind of object (for things dealing with AI and scheduling, such objects are often called "actors") that *contains* a pointer or reference to a sprite and manipulates that sprite as-needed based on its own logic. This sounds more similar to your second, "controller" type approach.

However I would also advise, along the same lines, against creating a subclass of this controller type for each classification of actor (player, enemy, bullet). The behavior of those different types of controllers tend to differ in data, not in code, so there's little reason to create a complex inheritance hierarchy where no hierarchy is required at all. The differences between a player and a bullet are probably all things that can be altered by altering properties of the controller or sprite -- the image used, its bounded, and perhaps the name of the script that controls motion behavior.

---
Tags: sprites, cocos2d, ccsprite
---


# Question
Title: Getting started at 3D modelling and animation
I'm looking for book or a guide that will direct me to 3D modelling/animation for gaming. Most tutorials will go for lengths about things I don't really need for games and I want to get to the chops of making assets for my games -- like many developers have said: the best way to get experience is finish a game!

So what good books/tutorials are there on modelling for games?

# Answer
Blender's site has a lot of decent documentation and tutorials.
> 5 votes

# Answer
I totally agree with the *Josh Petrie's* recommendation of using Blender tutorials. Blender is a great free tool and those tutorials can't be useless even if they do not focus on modeling and animation for games.

---

But as you asked for 3D modeling/animation for *games*, I recommend you to search for **low polygon** 3D or modeling informations, which is the type of 3D modeling often used in video games.

Here is an interesting website, where you can see a professional at work in videos (with explanations) and read some interesting text tutorials about 3D modeling for video games (partially):
http://poopinmymouth.com/tutorial/tutorial.htm

And, If you are really a beginner, I recommend its very old but still interesting tutorial *Character Modeling for Game Design*:
http://poopinmymouth.com/process/character\_tutorial/character\_process.htm
> 1 votes

# Answer
Here's one I have personally read and recommend: http://www.amazon.com/Game-Artists-Guide-Maya/dp/0782143768/ref=sr\_1\_6?ie=UTF8&qid=1306115253&sr=8-6

Note however that this book is about Maya and is specific to character art. If you want to learn on a different 3D tool and are more interested in environment art, well then you need to specify that.

(There are also a few other books about game art by that same author listed on that page. I haven't personally read any of the others, but having the same author is a good sign.)
> 0 votes

---
Tags: 3d, animation, models
---


# Question
Title: Creating an electricity/lighting/tesla coil effect in a 2D XNA game?
I'd like to create beams of electricity between two points very similar to this video: http://www.youtube.com/watch?v=eMJ8-56L3Lc. The effect is so dynamic, with varying lengths and pseudo-random movement in-between the points, that I'm having trouble imagining how I'd accomplish such a thing. Is there any helpful information that might point me in the right direction?

I should note that I'm using the XNA 4.0 Reach profile, but custom shaders are okay because I'm not targeting the Windows Phone.

# Answer
> 3 votes
http://www.catalinzima.com/samples/12-months-12-samples-2008/lightning-sample/

and for XNA 4.0: http://www.hatchingdisaster.com/LightningSampleXNA4.zip

# Answer
> 16 votes
My friend is working on a side-scrolling shooter in XNA that uses similar effects (here's a video of an early test). He wrote a blog post about the technique that you might find helpful.

He's also usually hanging out in the #graphicschat IRC channel on irc.afternet.org (name's Drilian) and could probably help you out.

---
Tags: 2d, graphics-programming, xna-4.0, graphic-effects
---


title: Testing for 2D collision outcome

text:
# Question
Title: Testing for 2D collision outcome
I'm currently building a small 2D game in Processing (and it has to be Processing) for a school project. The basic makeup of the game is 4 different cells (objects, all are circles): An avatar, controlled by the player, a number of cowardly cells fleeing from all other cells, huntercells hunting and attempting to eat everything, and passive disruptorcells which will burst apart other cells in differnt ways depending on what they hit. Also, whether one cell is bigger than another affects the outcome of collisions. All these different cells are child classes of the cell superclass, all stored in a cells ArrayList, which is handled inside a World class, which is updated/displayed in the main Draw loop.

My main problem right now is how I should handle the outcome of all these different collisions, without too much code-duplication: My idea is to do it through a double for-loop, which would then again need 16 different if-like methods to figure out who's colliding with who, and what to do about it.

E.g. if a predator cell collides with prey cell, the latter will be eaten and the predator will grow a certain amount in size and speed. The outcome should be the same (predator grows, prey dies) if the tested subjects are found in reverse order through the for-loops. Cells also need to know where they are in relation to eachother all the time, so they know when/what to flee from/chase.

Any thoughts/suggestions on best practices and how to do this most efficiently are much appreciated.

# Answer
> 1 votes
Checking collision on circles should be easy and has been described very well by Valkea. If your entity amount doesn't go into the thousands, checking *all* collisions shouldn't be a performance problem, since circle vs. circle tests are very fast.

As for the resolving of the collisions: *Don't* write if-statements for all possible collision types. Consider something like this instead: Each of your *Cell-classes* has a method `handleCollision` which takes a cell-class as parameter. Your collision check could look like this:

```
// perform a circle vs. circle test
if(checkCollision(cellA, cellB)){
    cellA.handleCollision(cellB);
    cellB.handleCollision(cellA);
}

```

So it's in the responsibility of the cell class to react to a collision. The `handleCollision` method of the `Predator` cell could look like this:

```
public void handleCollision(Cell otherCell){
    switch(otherCell.type){
        case PREY:
            speed += SOME_SPEED_INCREASE;
            size += SOME_SIZE_INCREASE;
            break;
        case DISRUPTOR:
            // other stuff...
            break;
        default:
            // handle anything else
            break;
    }
}

```

If your cells are dependent on the current state of the other cell during collision (eg. if the predator gains more speed if he "eats" bigger prey), then you can't apply effects of the collision directly. Here's why:

```
// prey cell will be eaten, size = 0
prey.handleCollision(predator);

// predator won't have anything to eat.. prey is already marked as eaten
predator.handleCollision(prey);

```

So instead of directly applying state-changes in the `handleCollision` method, you should store the result and apply it after all collisions have been resolved.

# Answer
> 2 votes
To test for the collision in 2D, I would recommend something like this :

```
struct AABB { int x, y, width, height; }

bool isColliding( AABB box1, AABB box2 )
{
    if( box1.x + box1.width < box2.x || box1.x > box2.x + box2.width ) return false;
    if( box1.y + box1.height < box2.y || box1.y > box2.y + box2.eight ) return false;

    return true;
}

```

Thus you can test the collision with small or big entities, and they can evolve in size and position.

---

You can also use a circle test collision using a circle center and a radius if circles are most adapted to the context of your game.

```
struct Circle { int x, y, radius; }

bool isColliding( Circle cir1, Circle cir2 )
{
    // Calculate the vector from cir1 center to cir2 center
    // then calculate the (non root-squared) distance using cross product to compare with radius
    int distX = cir2.x - cir1.x;
    int distY = cir2.y - cir1.y;
    int distanceCenters = distX * distX  + distY * distY;

    int radiusSum = cir1.radius + cir2.radius;
    return (distanceCenters < radiusSum*radiusSum );
}

```

The distance is not square-rooted as it should, because square-root operations are often expensive compared to products. Thus we don't use square-root on distanceCenters, but we use product with itself for radiusSum.

---

**To avoid testing all entities over all others entities**, I would split the "game area" in some smaller areas. Thus when you move the entities, you record in which "small" area of your game area they currently are (by adding a zone ID to the entity), and next you can test only the entities which are registered to be in the same "small" area (you need to test multiple area when an entity is at the edge of 2+ small areas).

Finally, as you need to know "where they are in relation to eachother all the time, so they know when/what to flee from/chase", I would recommend to test for the nearest cells of each types using small areas once again (and greater area if not found) and distance from center to center (as in the circle collision test).

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


# Question
Title: Component based entity system API naming problems
My engine uses a component-based entity system internally, and I want to bind it to Lua for scripting.

Now, I want to save people who write scripts for it typing work. In C++, to set the position of an entity, you'd do the following:

```
pEntity->GetComponent< CPoint >()->SetPos( Vector( X, Y ) );

```

That means, if I'd bind it to Lua 1:1 you'd also have to:

```
ent:GetComponent( CP_POINT ):SetPos( 123, 456 )

```

**But let's be honest, would you want to type so much just to set an entities' position?**

I don't think so, that's why I "hid" the component system from Lua:

Right now, what you do is

```
ent:SetPos( 123, 456 )

```

The component stuff is handled internally. You can still manually add and remove components from Lua with ent:AddComponent and ent:RemoveComponent, etc.

Now, this doesn't seem perfect either:

* The Entity metatable gets cluttered because it has to take all functions of all components
* Naming problems: `ent:SetJointMotorEnabled()` again seems kind of bad

**Do you have any ideas how I could find a better naming scheme for component functions, without risking the scripting comfortability?**

# Answer
We have a similar situtation in our project, and we solved the problem by saving components (not functions) to LUA metatables. Basically, when we are creating an entity (or game object as we call them) on LUA side, code looks something like:

```
function createShip()
    ...

    self.transform = registerToComponent("transform")
    self.sprite = registerToComponent("sprite")

    ...
end

```

Now, we can use simply

```
entity.transform:setPosition(5.2, 4.8)
entity.sprite:setTexture("ship.png")

```

to set position (and texture). And we are totally happy with this!

(And actually I think this is better than having just entity:setPosition and entity:setTexture since when you have lots of components, resulting entity API would be just a big mess.)
> 11 votes

# Answer
The fundamental problem here is that you've exposed the component system to the API. You need to encapsulate that stuff behind your interface.
> 4 votes

# Answer
I haven't worked with Lua in a while, but couldn't you let your components themselves change the entity interface through the Lua wrapper (last time I used Lua in a game was in 2005, the wrappers must have evolved since then)?

By having it at the components level, you could have your position component register a "SetPos" function on the entity that calls the component directly and have a JointMotor component register an object in entity with a function "SetEnabled", this way it's "data driven" and support both ent:SetPos(123, 456) and ent:JointMotor:SetEnabled()?

As long as the registering of subobjects and functions validates that there is no name clash, you should be alright.
> 0 votes

---
Tags: c++, entity-system, component-based, lua
---


# Question
Title: Most useful free third party Android Game libraries?
Since I have started finding a good third party libraries for game development on android platform, Im getting confused. So want to know from the people who are already using some of the game libraries themselves (no googled resources please).

So my question is : What are some of best Android Game libraries(2D/3D)?

Note: to keep this poll as useful as possible, please remember:

When adding a new library, provide a short summary of what it does / why you think it's useful. Please make sure the answers are not repeated.

One link/source per answer is preferable.

# Answer
LibGDX - http://libgdx.badlogicgames.com/features.php

LibGDX is a game engine with a more low-level approach. It is very fast and flexible, has a really good Box2d-JNI wrapper, and lots of extensions and tools built around it.

It is free open source software with very active developers and a helpful community, a lot of games in the market use it already.

You can run the same code on Android and on Desktop, which helps in development, as you don't have to use the emulator or adb too often, which helps with turn-around times.

There is even a tool to fetch input events on your phone while using the desktop-version of your game, so you can develop and test control schemes fast too. ( https://market.android.com/details?id=com.badlogic.gdx.remote )
> 4 votes

# Answer
http://www.anscamobile.com/corona/

Extremely easy to use. Has BOX2d implemented in an easy to use way. Can build native IOS and Android applications.
> 2 votes

---
Tags: android
---


# Question
Title: Should I use animated objects or use the physics engine on iOS scenes with lots of rigidbodies?
I have a scene with lots of houses and other objects. These objects will be bombarded from the sky. How to handle these kind of settings having in mind that you want the physics to be as realistic as possible.

In Unity3D, if I set all the objects with isKinematic=true and on collision I set it to false, then the physics isn't as realistic as I want it to be... Can you have these kind of scenes on iPhone? Should I have animated objects? I really don't know what is the best practice in this kind of scenes....

# Answer
> 1 votes
the problem with the kinematic object is that physics engine doesn't check if 2 kinematic object have collision and even if it collide with a dynamic object there won't be any change in kinematic object's speed, so basically you have to set all your game objects as dynamic, on the other hand you have to define all your objects as simple as possible for performance issue, you have to use only rects and ellipses, and at most triangles, and there are too many games with your base concept available in iphone now (remember `angry birds`?)

---
Tags: physics, unity, animation, ios
---


# Question
Title: Abstracting multiple math libraries with C++
I would like to create some level of abstraction above math in my code. I mean I don't want to be dependant on the implementation of math operations or even on class names, which are provided by some math library. I will show you a simple example.

Let's assume that we have 2 math libraries. Let's consider 3D-vector classes:

Library A has 3D-vector class as "Vector3D" and its method "Subtract".

Library B has 3D-vector class as "vector3" and its method "subtr".

Now I want to be able to swtich between these 2 different implementations, but without changing any line of code. For, instance I would like to have it like this:

My 3D-vector class name will be "vec3" and its method "sub". But behind "vec3" and "sub" it can be implementation from library A or library B, depending on what I choose with 1 line of code in the beginning of program or even on compilation stage.

In other words it should look like a plugable system for math libraries.

I think it's about programming patterns here right? It look like delegation or factory. Could make clear for me how to implement this approach and is it worth it?

# Answer
> 9 votes
The design pattern you are looking for is the adapter pattern (wikipedia).

> The adapter pattern (often referred to as the wrapper pattern or simply a wrapper) is a design pattern that translates one interface for a class into a compatible interface...

One way to implement the adapter pattern is to create a generic interface (abstract) for the vector class, and then you could derive classes from it that call the correct functions.

To switch between the concrete derived classes you could use a typedef. e.g. you would define

```
typedef VectorDirectX Vector

```

or

```
typedef VectorOpenGL Vector

```

and then you would only use Vector in your code. This would only work if you weren't planning on switching Vector classes at runtime.

If you did need to switch between them at runtime you could use a factory, which would create the required class and return a pointer/reference to the base abstract class.

**In practice** for performance reasons I'd rather rely on refactoring tools (e.g. Visual Assist) to rename functions and classes unless I'm working on a massive project or there's a legitimate reason why the classes would need to frequently change.

# Answer
> 6 votes
I strongly recommend not to put a layer of abstraction between your application and the math-lib, neither high level factories nor inheritance for different platforms, nor delegation nor similar patterns.

You want your vector math code as **optimized** as possible.

Unfortunetely layers of abstraction that make your design more user-friendly, have massive performance impacts, especially in low level code such as math libraries.

**So what can you do?**

Either use those libraries that do all the dirty work for you like: multi platform implementation, passing vectors via registers rather than the stack if possible, etc:

1. Sony's vectormath SSE2 and Altivec
2. Bullet's Linearmath SSE2

Or use them as the inspiration for your own. Forget about fancy design patterns in this case, here performance is priority No. 1

# Answer
> -1 votes
since you are coding with c++ you can use some advance template features like this :

```
struct vector3
{
    void subtr(vector3 p){};
};

struct vector3D
{
    void Subtract(vector3D p){};
};

template <bool t> class Vector3DWrapper{
    vector3D v3d;
public:
    void subtract(Vector3DWrapper pv) {v3d.Subtract(pv.v3d);};
};

template <> class Vector3DWrapper<true> {
    vector3 v3;
public:
    void subtract(Vector3DWrapper pv) {v3.subtr(pv.v3);};
};

```

now if you declare some vector from `Vector3DWrapper<true>` type it'll use all vector3d features and other wise it'll all be Vector3D features, the only thing is that this code will generate errors if want to set some `Vector3DWrapper<false>` variable to `Vector3DWrapper<true>` value, but this can also be solved by just implementing cast operators for these classes.

---
Tags: c++, mathematics, architecture
---


# Question
Title: What are useful server metrics to gather for a table card game?
When building a game server intended to accomodate large numbers of simultanous games (e.g. table card games), where the server manages lots of tables and each table has up to a small handful of users, what metrics are most useful to collect and why?

# Answer
For metrics regarding the gameplay I'd suggest simply recording a full history of each game, with each action timestamped.

As card games tend to be fairly slow paced that shouldn't generate too much data and it lets you do any other analysis of the games you want to at a later date by just using that history data.
> 1 votes

# Answer
Since you're already tracking the state change of the game for each move, I don't see what else you might monitor in relation to the "game" itself; however, many commonly tracked server metrics include:

* CPU Load
* Physical Memory Use
* DISK IOPS
    + Read Queue Length
    + Write Queue Length
    + Average Service Time
* Network IO Use

Depending on your server platform there are different tools to monitor this data. The reason to monitor these, is because they directly impact performance and they are all finite resources on any given server. If you start maxing one of these out, you need do either, add more of that resource, re-write some of your application to work within the limits on your server.
> 1 votes

---
Tags: server
---


title: Slow Tower for a Tower Defense Game

text:
# Question
Title: Slow Tower for a Tower Defense Game
I am making a tower defense game in Flash and I have a slow tower that is built directly on the path. I have it setup to use a hitTestObject function.

The tower is in its own class and the enemies are in their own class.

In the update function for the tower, it has

```
if (this.hitTestObject(enemy))
{
    enemy.slow = true;
}

```

In the enemy class update function, I have:

```
if (slow == true)
{
    finalSpeed = speed/2;
}
else
{
    finalSpeed = speed;
}

```

This seems to work fine until I build a second slow tower. Whenever I build the second one, it works, but the first one stops working (it no longer slows enemies). However, it is still detecting the collisions with the enemies. I don't understand why it doesn't slow them down though.

# Answer
> 4 votes
I can't tell for sure without seeing more of the code, but what it *sounds* like is that something involving the later tower is setting the .slow of enemies it's not hitting back to false.

I haven't really worked with actionscript, but I'd look into watching when that variable changes to false. If it's getting set to true but when the enemies movement comes around it is back to false, something between the two has to be resetting it.

# Answer
> 0 votes
i guess for some reason the first `if` statement which should be working for every tower is only working for the latest tower build, (maybe it's just an instancing problem, eg. you just create an instance for tower shape but not from the whole tower class)

some new ideas : what if you just unmark slow flag whenever enemy is not near a tower (you know some if/else statement) and that is cuasing tower 2 overwrite what tower 1 flaged?

---
Tags: flash, actionscript-3, tower-defense
---


title: Job prospects for game QA/testers

text:
# Question
Title: Job prospects for game QA/testers
I'm currently a (happily employed) automated software tester that's curious about game testing/QA. Do game companies hire dedicated testers for pay? If yes, then what are the job prospects like? If no, then how does becoming a game tester work (volunteers? mixed roles? crowdsourcing?). Obviously game companies have full-time devs, artists, designers, managers, etc. but what does QA look like?

NOTE: I'm curious about how QA works in a game dev setting, but I'm not really looking for job tips or "Do this if you want to get into game QA".

# Answer
> 6 votes
Testing/QA in the games industry is basically just like anywhere else, albeit with a tendency towards less process and formal methodology than in non-game work. Companies will hire for full-time QA as well as contract staff; the ratio of each will vary based on the culture of the studio and the needs of their current project or projects (typically contract QA positions are staffed up in the lead out to a release, for example).

Some studios will interact with QA contracting services like Volt, some will hire directly, some will do both. Volunteers are typically only used for one-off usability tests.

As of the Game Developer 2010 salary survey, QA remains a relatively low-compensated domain relative to other areas in the industry (which is, admittedly, low-compensated on average). Average salaries reported for the 2010 survey period were around 50k.

# Answer
> 4 votes
There's two major "types" of game testing/QA. Publisher and developer.

Publisher QA is like AttackingHobo's comment, where you're mostly sitting in front of a game in a cubicle with tons of other people around you, and you're turning the game on and off to make sure it doesn't crash. Or you're running into every single wall to make sure there's no seams in the geometry. And you're doing this for 12 hours straight, and getting paid $8/hour, and you better show up early tomorrow if you want to keep the job. This is the game industry equivalent of a retail position. Low pay, long hours, not much chance for advancement unless you're promoted to manager of the team. It's often a temp job where you might not work for 3 months because there's no games to test.

Developer QA is more in line with the automated software tester position you have now. You work with the team who is developing the game, pointing out major bugs, being able to provide useful feedback that could impact the game, and possibly deal with build issues, or other things. Developer QA is generally full time, salaried, and will be hired by studios like all the other jobs. You're probably not going to find too many QA positions at small indie studios, but a "larger" studio might have openings.

This is just a broad overview, and as always, there's going to be differences depending on your location and other things. Josh's answer covers salary and job prospects fairly well. Realise that the game industry is competitive, and less stable than a typical software job.

# Answer
> 2 votes
There is some professional companies dedicated to game testing.

The biggest one I know of, is Enzyme, a Canadian company:
http://www.enzyme.org

Lutin Userlab in France is another one:
http://www.lutin-userlab.fr/\_pages/english

But there is probably a lot of other companies doing the same king of work all over the world and particularly in USA.

The "Game testing" wikipedia page could provide you some useful informations too:
http://en.wikipedia.org/wiki/Game\_testing#Employment

As far as I know, Game testers used to be paid hourly, they don't earn a huge amount of money, but hey they have fun at work ;)

---
Tags: testing, jobs, job-hierarchy
---


title: Enabling virtualization on a PC

text:
# Question
Title: Enabling virtualization on a PC
I was designing games in unity with some friends but none of us have a mac so none of us can download the apple sdk. To use the sdk, we will have to run a virtual machine with osx on it. Virtualization is disabled on most PCs by default and I was wondering if there was any way to change that without rebooting into the bios. If not, how would I change it in the bios? Thanks for your help.

# Answer
You can't run "legally" OSX on a virtual machine. In fact, Apple grant licenses for their stuff only, so you can't run OSX on a non Apple computer, even if it is virtually.

But there is some way to do it using **Virtual Box** or **VMWare** and a slightly modified version of osx...

For more informations, see this StackOverflow link, "**Is it possible to run OSX in a virtual machine?**": https://stackoverflow.com/questions/39159/is-it-possible-to-run-osx-in-a-virtual-machine
> 2 votes

---
Tags: ios, virtual-machines
---


title: Flash AS3 Tower Defense MouseEvents

text:
# Question
Title: Flash AS3 Tower Defense MouseEvents
In my tower defense game and every tile has its own mouse event listener. I am wondering, would it be better to use one event listener (MouseEvent.CLICK) and then when it runs the function, should I just use evt.target to determine what was clicked, and then run an appropriate function?

I am programming the game for web and phone and I started to notice some lag on my phone so I am trying to optimize my code. Any other tips to speed up code would help too.

# Answer
> 3 votes
I doubt that the event listeners are the main bottleneck of your applications. However as you are trying to optimize your code, here are some useful informations to know about Events alternatives and performances.

The main alternatives to the Events are the Signals & Slots, Observers and indeed the direct Callbacks.

*Performance tests and articles:*

*AS3 Signal libraries:*

---

Finally, you can check this video tutorial about how to use as3signal

---
Tags: flash, actionscript-3, optimization, events, tower-defense
---


# Question
Title: How do I display same “proportional” text size on different resolutions?
I draw some text on screen using ID3DXFont::DrawText. This text should be displayed the same regardless of screen resolution.

For example, if screen resolution is low, text wrapped and when it is higher text is not wrapped. How can I avoid such situation? I want text size to be connected to screen resolution so if resolution is lower I want the text to be relatively smaller so that no wrapping happens. Is there any way?

Thanks in advance

# Answer
You will have to manually get the size of the screen and scale down the requested text size.
> 3 votes

---
Tags: directx, rendering, text
---


# Question
Title: Converting 3D coordinates to 2D and back?
I'm wondering if there is a simple way to convert 3D coordinates to 2D coordinates. Also, if it's possible, to convert in the reverse direction.

I'm using OpenGL(GLUT) in my C++ project.

I am also using SFML for the 2D information (sprites text etc.)

I found out that I can use gluProject(), but I have no idea how to use this.

I'm asking for a simple example of using gluProject() or another example to convert 3D coordinates (such as from the player) to 2D coordinates.

If I can't get the simple process I'm confident that I can figure out the rest.

# Answer
You can convert between 3D and 2D coordinates in a variety of ways, some of which have more meaning than others. For example you could just drop the Z coordinate, yielding an (x,y) pair, but that probably doesn't do what you want semantically.

But you're specifically asking how to convert between model, world or view space 3D and screen space 2D as used by your graphics API, it sounds like. This primarily involves application of the appropriate transformation matrix, as well as performing the perspective division by W and any viewport transformations that may be warranted. gluProject does exactly this operation, all you have to do is provide it with input coordinates and matrices.

gluProject assumes the input coordinates `objX`, `objY`, and `objZ` to be in model space, but they can be anywhere as long as the matrices you provide it via the `model` and `proj` parameters have associated meaningful values. The format of the `model` and `proj` matrices is an array of 16 floating point values, the same kind of data you'd get from `glGetFloatv` and such. The `view` parameter is an array of 4 integers representing the position and size of your viewport (from `glGetIntegerv` for example).

To perform the operation in reverse, you can use gluUnproject. Note that since you'll have a 2D coordinate you'll have manually specify an arbitrary depth value. The 3D → 2D conversion perforce loses data, so you must invent new data when going in the other direction.
> 4 votes

---
Tags: opengl, c++, coordinates, sfml, glut
---


title: Java 2D Game looks like 3D

text:
# Question
Title: Java 2D Game looks like 3D
i have fair experience with java game programming,
i already made a simple mario game (side-Scrolling)
i'm wondering how can i make a "Java" Game like that
http://www.youtube.com/watch?v=utwtXEYW1L0
or that
http://www.youtube.com/watch?v=uqz4dunlhX4
the main problem is that i don't know how to make a 2D game looks like 3D
i just need a tutorial or the idea behind such things. Thanks in Advance :)

# Answer
To elaborate on Valkea's comment, the trick is to use 2D sprites just as you would in a "true" 2D game, but shade and style them to give a sense of depth. The game feels 2D because your character has realistic shading that appears 3D, and because the map is constructed so that your character can go behind objects. This is achieved by making your character walk on a 2D space, but partially obscuring your view of him when he goes behind a wall (such as the wall transparency shown from your first link).

Dynamic shadows like those shown in your second link are trickier and uncommon. I would look into the "Sunburn Engine" mentioned in the description of that second video for more details.
> 7 votes

# Answer
If your serious about making proper games with java then you need to stop using stuff like Swing, AWT and Java2D and pick up a proper OpenGL binding, e.g. LWJGL or use a games library built on top of an OpenGL binding, like Slick2D, Ardor3D, jMonkeyEngine, jPCT, Xith3D or LibGDX.
> -3 votes

---
Tags: 2d, 3d, java
---


# Question
Title: A good beginners' game engine to run on linux
I am involved with a research that deals with 3D graphics. I am very new to 3D graphics. In my research I have to move a 3D object based on some information queried by processing a video. Viewer's only interaction with the 3D environment is, changing the camera viewpoint.

I am not that worried about the speed or efficiency at this level. What I need is easy to learn and easy to program 3D game engine, I suppose.

I'd like to know about any open 3D model file format supported by the game engine, as I will have to use custom made 3D models using 3D modelling techniques of computer vision.

I tried Panda3D, but the most significant drawback was it's inability to use .max files directly (most of the 3D models available were of this format). Panda3D was quite simple when it came to scripting.

Thank you in advance.

# Answer
Have you looked into Ogre3D? Ogre is a fairly intuitive hardware-accelerated graphics rendering engine. Not a full game engine, but it doesn't sound like you really need much beyond graphics drawing and basic manipulation, which it can handle. There's an incredibly informative wiki with plenty of tutorials here; the beginner's project is preconfigured with basic camera movement controls.

It uses a mesh format for it's model data, but there are plugins for most (if not all) of the major 3D modeling software for converting their formats to Ogre's.

There are bindings for Ogre in quite a few different languages, including Python and C++, as well as an experimental port for .NET called Axiom3D.
> 3 votes

# Answer
Blender (the 3D editor) may be useful, it has an interactive game feature and python scripting. http://blender.org/features-gallery/features/
> 1 votes

---
Tags: linux
---


title: C++ GameState management

text:
# Question
Title: C++ GameState management
I have been attempting to make a game engine in C++ and have come across the dilemma of game state management. I have done a lot of research and found numerous ways of accomplishing from game engine with derived classes to using enums and I would like to know the most effective/efficient way of managing game states.

EDIT
I would like to know how other people implement their game state management, i.e. what you like the most and why you like it. Also, any tutorials/code examples that are generally about game state would also be much appreciated.

# Answer
In most of my games (that are all small in scope) I have used an `enum` and a `switch` (in some cases an `if..else if...`) and it has always been sufficiently fast. I've never had more than a few states, which helps.

```
enum GameStates
{
    Running = 1,
    Menu = 2,
    Credits = 3
}

// update loop

switch(this.CurrentState)
{
    case GameStates.Running:
        UpdateRunning(gameTime);
        break;
    case GameStates.Menu:
        UpdateMenu(gameTime);
        break;
    case GameStates.Credits:
        UpdateCredits(gameTime);
        break;
    // add more states here
}

void UpdateRunning(GameTime gameTime)
{
    if(running == null) LoadRunning(); //
    // perform the rest of your game logic
}

```

This gives you a few things worth mentioning:

1. You can change state anywhere, as long as you have a pointer to your main class.
2. You can load/unload as necessary to save memory (if your game is big it might be nice)
3. ***You've kept your very simple and easy to follow. This is the single most important thing a programmer can do IMO.***

(Please excuse my C#/XNA style this was copy/pasted and tweaked, shouldn't be to hard to adapt to C++)
> 1 votes

# Answer
The most common approch to GameState algorithm is to have some game states and program can freely choose to run any one of them, this means there is a GameDirector which has a pointer to current running state, and in each update cycle it'll call 'currentState-\>run()\`. in this approch GameDirector is a singleton and every one can access it, and also every one can change game state. also gameDirector is responsible for game's main loop.

```
class Director
{
private :
    RendererEngine* rEngine;
    SoundEngine* sEngine;
    PhysicsEngine* pEngine;
    GameState* gState;
    static Director* instance;
    Director()
    {
        rEngine = sEngine = pEngine = gState = NULL;
    }
public :
    static Director* GetDirector()
    {
        if (instance == NULL)
            instance = new Director;
        return instance;
    }

    RenderEngine* getRenderEngine() {return rEngine;};
    SoundEngine* getSoundEngine() {return sEngine;};
    PhysicsEngine* getPhysicsEngine() {return pEngine;};

    void runGame(GameState* pState)
    {
        return instace;
        rEngine = new RenderEngine;
        sEngine = new SoundEngine;
        pEngine = new PhysicsEngine;
        gState = pState;
        gState->onEnter();
        while (gState)
        {
            gState->onUpdate();
            gState->onDraw();
            rEngine->swapBuffers();
        }
    }

    void changeState(GameState* pState)
    {
        gState -> onEnd();
        gState = pState;
        if (gState)
            gState -> onEnter();
    }
}

```
> 0 votes

# Answer
Something I found interesting when looking around was the Advanced Ogre Framework which has a state management implementation. It is designed for the Ogre3D rendering engine but that part can be replaced pretty easily.

http://www.ogre3d.org/tikiwiki/Advanced%20Ogre%20Framework
> 0 votes

---
Tags: c++, architecture, game-loop, state
---


# Question
Title: Android: Layouts and views or a single full screen custom view?
I'm developing an Android game, and I'm making it so that it can run on low end devices without GPU, so I'm using the 2D API. I have so far tried to use Android's mechanisms such as layouts and activities where possible, but I'm beginning to wonder if it's not easier to just create a single custom view (or one per activity) and do all the work there.

Here's an example of how I currently do things: I'm using a layout to display the game's background as an image view and the square game area, which is a custom view, centered in the middle.

What would you say? Should I continue to use layouts where possible or is it more common/reasonable to just use a large custom view? I'm thinking that this would probably also make it easier to port my code to other platforms.

# Answer
It depends on your game. It's probably okay to use several views for more passive games like minesweeper or sudoku, but not for a shoot 'em up or a platformer. If your current setup is working fine and you find it easier to code using views then you might as well continue doing things that way. It doesn't really matters as long as you're satisfied with the result.

If porting is an issue then you want to use abstractions for the platform-specific stuff regardless of your implementation. But I think that you're right about it being easier with using a custom view, mainly because you wouldn't worry about parsing the layout XML files on the new platform (unless you define the layout in code).
> 1 votes

# Answer
I have also developed a casual game for Android version 1.6. As you have done, i have also used a imageview as the background, added custom views to accomodate my gameplay area.

This is working very fine for my game. Because, first thing, the views are not complex, second thing, the responsiveness is good, and third, the game flow is also maintained efficiently.

But this is okay for a casual games like board games, games where only 2/3 activities are used (my game uses only 2 activities, with complete game life cycle) or simple puzzle games.

So depending on the complexity of the project the views must be defined. It is better to keep the flow simple and responsive.
> 0 votes

---
Tags: android
---


# Question
Title: Engine with Terrain and Indoor Areas (BSP-like)
I'm not really a graphics programmer, but I used to toy around with Truevision3D 6.5 a few years ago. It wasn't too bad, but TV3D was just going nowhere so my foray into 3d game dev ended there.

I know nothing of XNA. I think it's time to get up to date.

My goal is to be able to render chunks of terrain from heightmaps (big huge terrain a la Morrowind) and BSP-like indoor areas (think Quake, so moveable objects like doors included).

I googled for "xna engine", "best xna engine" but the quantity of results is a bit scary for a xna-impaired like me.

Can anyone recommend a *xna* engine (or a combination of libraries) to achieve the desired result? If you targeted similar features, can you share your experience?

(and for a laugh, has anyone tried TV3D 6.5 here?)

Edit: I'm looking for something xna-related.

# Answer
> 1 votes
One I have heard good things about is the Sunburn engine. (Site seems down currently)

Chances are you're not going to get all you want out the box. However, Riemer has a great tutorial about heightmaps here \- in XNA!

EDIT: This is probably a little off what you want, but Sean James has a great (well, I'm not a fan of the architecture of gamescreen/component but other than that I love it) tutorial on writing a simple 3D engine in XNA \- it's pretty concise. The advantage is it's free to do by yourself, and if your goal is learning it would be good.

# Answer
> 2 votes
Look into Unity3D. It's a nice engine that uses C#, and it has nice terrain engine and can work with "indoor" maps (no BSP though, as far as I know). Although you'd have to jump through a *lot* of hoops if you want to use them both simultaneously in the same scene.

---
Tags: xna, c#, terrain, levels, binary-space-partitioning
---


# Question
Title: Make player to always move along the terrain
I'm working on a 2D platformer side scroller game. I am giving high impulse to player, the player starts moving and if it hits a slope on terrain, it gets a vertical movement and starts to fly over (Box2D physics).

What I need is that the player should always be on the terrain and move along the ground.

I would like to know if it's possible using Box2D engine.

# Answer
> 2 votes
If you want perfect terrain contact at all times then you need to stop applying Box2D collision response to the player, and apply your own physics rules, because what you describe is not compatible with newtonian physics rules, which are the rules that Box2D follows.

However, you can get pretty close, while still using newtonian physics.

Increase the mass of the player to something large, and apply some downward force to the player.

Do not make the player's mass too large relative to other objects though, as large mass differences can result in large floating point errors and poor collision response.

Start with a small amount of mass, and gradually increase it until you find something that works while the simulation remains stable.

As you increase the mass of the player, increase the amount of downward force applied to the player at each frame. I'm not very familiar with Box2D, but this can probably be done with an impulse that is applied to the player every physics update.

Keep in mind that this means that all objects interacting with the player are not going to move the player very much unless they are also heavy, like your player is.

Note that you're going to have to increase the size of the impulse you apply to the player to make him move, as you increase the mass of the player, if you want him to continue at the same speed.

Keep in mind that the hero will have higher inertia with higher mass, so you have to decide if you want the hero to keep moving after the player moves him to the right a little. If not, try increasing friction forces on the player.

# Answer
> 1 votes
Two possible solutions I can think of:

1. Don't apply physics to the player character. Unless they jump or fall, I guess - not sure if this is possible in your game.
2. Add a lot of "fake gravity" (a force pointing down) to the player character only. It won't make him move along the terrain *perfectly*, but it might be close enough. Again, this force shouldn't be applied when the character is *supposed* to be jumping or falling.

# Answer
> 0 votes
I'm not sure if i perfectly get the problem here, nor have i used Box2d. Actually... if its for flash i might have...

But anyway, try calculating the direction the player is to the terrain (if the terrain is within 10 pixels say), and move it closer to the terrain if possible.

Of course this isn't a full proof method, and you might want to only do this if you have first checked that the player was actually running in a recent step.

Sorry if i didn't answer the question 100%. More detail could be good.

# Answer
> 0 votes
I'd add an invisible object just after the slope that uses gravity to pull down your character to avoid the character flying off like you said.

Yes this is possible in box2d but I am unable to tell you how without more information on your project.

(You'll need to learn box2d engine and look at what you can change to the players characters physics when they come off the slope or what you can do to prevent the actions occuring).

---
Tags: box2d, movement, terrain, platformer
---


# Question
Title: Collision Detection/Response in Vector-based levels
I have a 2D side scroller whose levels are stored as vectors (that is, a bunch of lines) which looks like this:

How would I detect that I'm colliding with one of these lines, and react accordingly (say, slide down the slope, or stand still on a flat platform)? We can assume the player uses an AABB.

# Answer
You might want to use a physics engine that does the work for you. Even if you get the collision detection right, there is still the problem of the collision response that let's the character slide down a slope, which can be even harder than the actual collision detection.

Box2D can do it for you.
> 4 votes

# Answer
for each line (represented by ax+by+c = 0) and each object(which moved from x0,y0 to x1 y1) you have to check if the result of this product is negetive `(a*x0+b*y0+c)*(a*x1+b*y1+c)`. negetive value means there is a collision somewhere(it may be after the both end of line) and the possitive value means there are no collisions. if there realy was a collision then you have to calculate collision point using these formulas and check if that's somewhere between two ends of your line.

we want to calculate the collision point of these 2 lines :

```
ax+bx+c = 0
(x1-x0)x+(y1-y0)y - (x1-x0)x0+(y1-y0)y0 = 0

```

so we set these 3 parameters for comuting ease:

```
a' = x1 - x0
b' = y1 - y0
c' = -(a' * x0 + b' * y0)

```

and now our problem is :

```
ax +by +c  = 0;
a'x+b'y+c' = 0;

```

and then you can have x',y'(collision coordinates)

```
x' = -(c/b + c') /(a' + b'/b*a)
y' = -(c/a + c') /(b' + a'/a*b)

```

after that to check if it's inside the line fragment you have to check if `(x0-x')*(x1-x')+(y0-y')*(y1-y')` is a negetive value, if yes you have a real collision if not the object is past from sides of your line.
> 1 votes

---
Tags: collision-detection, physics, vector, side-scroller
---


# Question
Title: OpenGL web game: C++ with Java vs pure Java?
I'm going to write **browser online game**, **not MMO**, but something like a lot of Flash game. But with OpenGL rendering, because Flash is using CPU for rendering.

What are advantages of pure Java or c++ with Java that only create window.

My requirements are:

* **good performance** \- low overhead when calling OpenGL functions
* short code( if possible ) - so, Java is fully object oriented language, which can require usage of object for each called OpenGL function
* basic **portability - Linux, Mac, Windows** \- multiple builds for each platform aren't problem
* little communication with server for saves, top score,... not multiplayer - may be slow
* game should be downloadable

# Answer
> 4 votes
Just use Java, don't bother with anything else. If it becomes necessary to start augmenting the program with C++ bolt-ons, you can do so later once you've proven it to be to true.

Until then, you'll be able to build a perfectly excellent game in Java that meets all your requirements and has the advantage of being significantly easier to build and deploy since you won't have to deal with the hassle that is C++'s lack of *binary* portability.

If you're into it, it looks like it's also possible to use a developer preview version of Flash to get the hardware accelerated features bummzack mentions.

# Answer
> 0 votes
If you're writing it for the browser, C++ is not an option; you would have to use Java. Alternately, look at Unity.

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


# Question
Title: Are there any resources about performance tweaks?
There are many optimization tricks that you can apply to your C++ code that can help speed up your program, and there are more game-related tweaks poping out every day. For example, I've just heard where you are trying to draw some meshes with same texture it's faster to draw them all in one call (or something like that which mean to pass texture once and for all of them).

Are there any books or weblogs or something which demonstrate these things? I'm working with C++ if there are any general advises about optimization, I'll be glad to hear about them.

# Answer
> 2 votes
For general C++ optimization considerations I can not recommend the Effective C++ and More Effective C++ books enough.

I will also add in that I have contacted this author a few times and he has not only been very forth coming with additional clarifications if need be, but genuine interest in the information.

# Answer
> 4 votes
> general advises about optimization

1. The most important thing when optimizing is: **Profiling**. Learn your code from the hard profiling-facts. Don't make any assumptions about your code, profile it!
2. Make automated profiling runs and compare the results in a machine readable format, make them easy accessable in graphical performance charts, so you will more likely know which checkin caused new hitches, or whether optimizations were good or not.

# Answer
> 2 votes
Situational awareness.

Measure your product, both by manual on-demand profiling with external profiling tools when you see something that acts more slowly than you'd like, any by instrumenting your code with automatic metrics gathering so that you can have some kind of measurements even when your code is running unattended by a developer -- these latter metrics can also be used to create a history of the execution profile of your application and thus provide hints into what changed to make things drop in performance.

There are very few "general solutions" to performance problems other than this (situational awareness). Things that are oft hailed as such can just as often have exactly no effect, or worse, harm either the performance of the application or the quality of the code. Especially in languages like C++, it's really not possible to reason *in general* about how the shape of a bit of C++ code will translate to the machine instructions actually executed. Too much of the language is undefined and too much is up to the compilers which are usually much better than humans at balancing and pipelining a lot of subtle, multi-factored variables.

Situational awareness is just as important when applying the handful of general advice that is out there -- consider, for example, your note about swapping array indexing order that you mention in a comment to Maik's answer. Do you know why this is (sometimes) true? Do you know what will make it not true, or have no impact? If you can't explain it it can be a dangerous thing to go and try to do. Don't trust, know.

Furthermore, many of these so-called general performance techniques apply in very small and localized contexts and can usually be used for little more than providing performance band-aids rather than full-fledged solutions to performance problems (which may be algorithmic in nature). The way to write high-performance code is to understand the scope and shape of the problem your code must solve and the context-specific tweaks and enhancements you can make. Looking for band-aids won't really help you in the long run, it will just give you a false sense of accomplishment.

# Answer
> 1 votes
Gajet, you are asking us to tell you about all of the millions of possible cases where modifying your C++ code can yield a performance improvement.

A performance improvement at the low level you're describing on one type of hardware is not necessarily a performance improvement on another type of hardware.

For example, your C++ code running on a processor with a 12MB L1 cache might benefit from using a method that consumes a great deal of memory, where that same method yields slower code on a processor with a 512kb cache.

Judging by your question, low level optimizations like this should be the least of your priorities.

If you want to write fast code, first consider learning about different **algorithms**.

Here's a book on the subject: http://mitpress.mit.edu/algorithms/

The algorithm you choose will often affect your runtime speed much more than any low level optimizations of particular operations in your C++ code.

My program written in Python might run 100x slower than your program written in C++ for small amounts of input data. However, if I choose a better algorithm than you (e.g. heap sort), then my Python code will always run much faster than your C++ code (e.g. insertion sort), no matter how well you optimize it, when the input data size is large.

If you are just getting started with programming (i.e. you have less than 1000 hours of experience) then by far your priority right now should just be building things that actually work, efficiently or not. Otherwise, either start reading about alrgorithms, or profile your code and come here with a specific question about how to make a particular solution go faster on some particular hardware. We can't address all of the millions of possible cases for you here in advance.

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


title: C++ low-level optimization tips

text:
# Question
Title: C++ low-level optimization tips
Assuming you already have the best-choice algorithm, what low-level solutions can you offer for squeezing the last few drops of sweet sweet frame rate out of C++ code?

It goes without saying that these tips only apply to that critical code section that you've already highlighted in your profiler, but they should be low-level non-structural improvements. I've seeded an example.

# Answer
**Optimise your data layout!** (This applies to more languages than just C++)

You can go pretty deep making this specifically tuned for your data, your processor, handling multi-core nicely, etc. But the basic concept is this:

When you are processing things in a tight loop, you want to make the data for each iteration as small as possible, and as close together as possible in memory. That means the ideal is an array or vector of objects (not pointers) that contain only the data necessary for the calculation.

This way, when the CPU fetches the data for the first iteration of your loop, the next several iterations worth of data will get loaded into the cache with it.

Really the CPU is fast and the compiler is good. There's not really much you can do with using fewer and faster instructions. Cache coherence is where it's at (that's a random article I Googled - it contains a good example of getting cache coherency for an algorithm that doesn't simply run through data linearly).
> 78 votes

# Answer
A very, very low-level tip, but one that can come in handy:

Most compilers support some form of explicit conditional hinting. GCC has a function called \__builtin\_expect which lets you inform the compiler what the value of a result probably is. GCC can use that data to optimize conditionals to perform as quickly as possible in the expected case, with slightly slower execution in the unexpected case.

```
if(__builtin_expect(entity->extremely_unlikely_flag, 0)) {
  // code that is rarely run
}

```

I've seen a 10-20% speedup with proper use of this.
> 86 votes

# Answer
The first thing you need to understand is the hardware you're running on. How does it handle branching? What about caching? Does it have a SIMD instruction set? How many processors can it use? Does it have to share processor time with anything else?

You may solve the same problem in very different ways - even your choice of algorithm should be dependent on the hardware. In some cases O(N) can run slower than O(NlogN) (depending on implementation).

As a crude overview of optimisation, the first thing I would do is look at exactly what problems and what data you are trying to solve for. Then optimise for that. If you want extreme performance then forget about generic solutions - you can special case everything that doesn't match your most used case.

Then profile. Profile, profile, profile. Look at memory usage, look at branching penalties, Look at function call overhead, look at pipeline utilisation. Work out what is slowing down your code. It's probably data access (I wrote an article called "The Latency Elephant" about the overhead of data access - google it. I can't post 2 links here as I don't have enough "reputation"), so closely examine that and then optimise your data layout (nice big flat homogeneous arrays are awesome) and data access (prefetch where possible).

Once you've minimised the overhead of the memory subsystem, try and determine if instructions are now the bottleneck (hopefully they are), then look at SIMD implementations of your algorithm - Structure-of-Arrays (SoA) implementations can be very data and instruction cache efficient. If SIMD isn't a good match for your problem then intrinsics and assembler level coding may be needed.

If you still need more speed then go parallel. If you have the benefit of running on a PS3 then the SPUs are your friends. Use them, love them. If you've already written a SIMD solution then you'll get a massive benefit moving to SPU.

And then, profile some more. Test in game scenarios - is this code still the bottleneck? Can you change the way this code is used at a higher level to minimise its usage (actually, this should be your first step)? Can you defer calculations over multiple frames?

Whatever platform you're on, learn as much as you can about the hardware and the profilers available. Don't assume that you know what the bottleneck is - find it with your profiler. And make sure you have a heuristic to determine if you have actually made your game go faster.

And then profile it again.
> 36 votes

# Answer
First step: Think carefully about your data in relation to your algorithms. O(log n) is not always faster than O(n). Simple example: A hash table with only a few keys is often better replaced with a linear search.

Second step: Look at the assembly generated. C++ brings a lot of implicit code generation to the table. Sometimes, it sneaks up on you without you knowing.

But assuming it's really pedal-to-the-metal time: Profile. Seriously. Randomly applying "performance tricks" is about as likely to hurt as it is to help.

Then, everything depends on what your bottlenecks are.

data cache misses =\> optimize your data layout. Here's a good starting point: http://gamesfromwithin.com/data-oriented-design

code cache misses =\> Look at virtual function calls, excessive callstack depth, etc. A common cause for bad performance is the erroneous belief that base classes *must* be virtual.

Other common C++ performance sinks:

* Excessive allocation/deallocation. If it's performance critical, don't call into the runtime. Ever.
* Copy construction. Avoid wherever you can. If it can be a const reference, make it one.

All of the above are immediately obvious when you look at the assembly, so see above ;)
> 31 votes

# Answer
**Remove unnecessary branches**

On some platforms and with some compilers, branches can throw away your whole pipeline, so even insignificant if() blocks can be expensive.

The PowerPC architecture (PS3/x360) offers the floating-point select instruction, `fsel`. This can be used in the place of a branch if the blocks are simple assignments:

```
float result = 0;
if (foo > bar) { result = 2.0f; }
else { result = 1.0f; }

```

Becomes:

```
float result = fsel(foo-bar, 2.0f, 1.0f);

```

When the first parameter is greater than or equal to 0, the second paramter is returned, else the third.

The price of losing the branch is that both the if{} and the else{} block will be executed, so if one is an expensive operation or dereferences a NULL pointer this optimisation is not suitable.

Sometimes your compiler has already done this work, so check your assembly first.

Here's more information on branching and fsel:

http://assemblyrequired.crashworks.org/tag/intrinsics/
> 19 votes

# Answer
Avoid memory accesses and especially random ones at all costs.

That's the single most important thing to optimize for on modern CPUs. You can do a shitload of arithmetic and even a lot of wrong predicted branches in the time you wait for data from RAM.

You can also read this rule the other way around: Do as much calculations as possible between memory accesses.
> 16 votes

# Answer
**Use Compiler Intrinsics.**

Ensure that the compiler is generating the most efficient assembly for certain operations by using intrinsics - constructs that look like function calls that the compiler turns into optimized assembly:

Here's a reference for Visual Studio, and here's one for GCC
> 13 votes

# Answer
**Remove unnecessary virtual function calls**

The dispatch of a virtual function can be very slow. This article gives a good explaination of why. If possible, for functions that are called many many many times per frame, avoid them.

You can do this in a couple of ways. Sometimes you can just rewrite the classes to not need inheritence - maybe it turns out that MachineGun is the only subclass of Weapon, and you can amalgamate them.

You can use templates to replace run-time polymorphism with compile-time polymorphism. This only works if you know the subtype of your objects at runtime, and can be a major rewrite.
> 11 votes

# Answer
Use SIMD (by SSE), if you don't do already. Gamasutra has a nice article on this. You can download the source code from the presented library at the end of the article.
> 9 votes

# Answer
My basic principle is: *don't do anything that's not necessary*.

If you've found that a particular function is a bottleneck, you could optimize the function -- or you could try to keep it from being called in the first place.

This does not necessarily mean you're using a bad algorithm. It might mean that you are running calculations every frame that could be cached for a short while (or entirely precalculated), for example.

I always try this approach before any attempts at really low-level optimization.
> 9 votes

# Answer
Minimize dependency chains to make better use of the CPU pipleline.

In simple cases the compiler may do this for you if you enable loop unrolling. However it often won't do it, especially when there's floats involved as reordering the expressions changes the result.

Example:

```
float *data = ...;
int length = ...;

// Slow version
float total = 0.0f;
int i;
for (i=0; i < length; i++)
{
  total += data[i]
}

// Fast version
float total1, total2, total3, total4;
for (i=0; i < length-3; i += 4)
{
  total1 += data[i];
  total2 += data[i+1];
  total3 += data[i+2];
  total4 += data[i+3];
}
for (; i < length; i++)
{
  total += data[i]
}
total += (total1 + total2) + (total3 + total4);

```
> 6 votes

# Answer
Don't overlook your compiler -- if you are using gcc on Intel, you could easily get a performance gain by switching to the Intel C/C++ Compiler, for example. If you are targeting an ARM platform, check out ARM's commercial compiler. If you are on the iPhone, Apple just allowed Clang to be used starting with the iOS 4.0 SDK.

One issue that you will probably come into with optimization, especially on the x86, is that a lot of intuitive things end up working against you on modern CPU implementations. Unfortunately for most of us, the ability to out optimize the compiler is long gone. The compiler can schedule instructions in the stream based on it's own internal knowledge of the CPU. In addition, the CPU can also re-schedule instructions based on it's own needs. Even if you think of an optimal way to arrange a method, chances are the compiler or CPU has already come up with that on it's own and has already performed that optimization.

My best advice would be to ignore the low-level optimizations and focus on the higher level ones. The compiler and CPU can't change your algorithm from an O(n^2) to an O(1) algorithm, no matter how good they get. That's going to require you to look at exactly what you are trying to do and find a better way to do it. Let the compiler and CPU worry about the low level and you focus on the mid to high levels.
> 5 votes

# Answer
The **restrict** keyword is potentially handy, especially in cases where you need to manipulate objects with pointers. It allows the compiler to assume the pointed-to object is not going to get modified in any other way which in turn allows it to perform more aggressive optimisation such as keeping parts of the object in registers or reordering reads and writes more effectively.

One good thing about the keyword is that it's a hint which you can apply once and see benefits from without rearranging your algorithm. The bad side is that if you use it in the wrong place, you might see data corruption. But usually it's quite easy to spot where it's legitimate to use it - it's one of the few examples where the programmer can reasonably be expected to know more than the compiler can safely assume, which is why the keyword has been introduced.

Technically 'restrict' doesn't exist in standard C++, but platform-specific equivalents are available for most C++ compilers, so it's worth considering.

See also: http://cellperformance.beyond3d.com/articles/2006/05/demystifying-the-restrict-keyword.html
> 4 votes

# Answer
**Const everything!**

The more information you give the compiler about the data the better the optimizations are (at least in my experience).

```
void foo(Bar * x) {...;}

```

becomes;

```
void foo(const Bar * const x) {...;}

```

The compiler now knows that the pointer x is not going to change and that the data it is pointing to will not change either.

The other added benefit is that you can reduce the number of accidental bugs, stopping yourself (or others) modifying things that they shouldn't.
> 2 votes

# Answer
Most often, the best way to gain performance is to change your algorithm. The less general the implementation the closer you can get to the metal.

Assuming that has been done....

If it's really critical code indeed, try to avoid memory reads, try to avoid calculating stuff that can be precalculated (though no lookup tables as they violate rule number 1). Know what your algorithm does and write it in a way that the compiler knows it too. Check the assembly to be sure it does.

Avoid cache misses. Batch process as much as you can. Avoid virtual functions and other indirections.

Ultimately, measure everything. The rules change all the time. What used to speed up code 3 years ago now slows it down. A nice example is 'use double math functions instead of float versions'. I wouldn't have realized that one if I hadn't read it.

I forgot - don't have default constructors intialize your variables, or if you insist, at least also create constructors that don't. Be aware of the things that don't show up in the profiles. When you lose one unnecessary cycle per line of code nothing will show up in your profiler, but you'll lose a whole lot of cycles overall. Again, know what your code is doing. Make your core function lean instead of foolproof. Foolproof versions can be called if needed, but are not always needed. Versatility comes at a price - performance being one.

Edited to explain why no default initialization: A lot of code says: Vector3 bla; bla = DoSomething();

The intialization in the constructor is wasted time. Also, in this case the wasted time is small (probably clearing the vector), however if your programmers do this habitually it adds up. Also, a lot of function create a temporary (think overloaded operators), that gets initialized to zero and assigned after straight away. Hidden lost cycles that are too small to see a spike in your profiler, but bleed cycles all over your code base. Also, some people do a lot more in constructors (which is obviously a no-no). I've seen multi-millisecond gains from an unused variable where the constructor happened to be a bit on the heavy side. As soon as the constructor causes side effects the compiler won't be able to optmize it out, so unless you never use above code, I prefer either a non-initializing constructor, or, as I said, a version of the constructor that doesn't initialize.

Vector3 bla(noInit); bla = doSomething();
> 2 votes

# Answer
**Reduce boolean expression evaluation**

This one is really desperate, as it's a very subtle but dangerous change to your code. However if you have a conditional that is evaluated an inordinate number of times, you can reduce the overhead of boolean evaluation by using bitwise operators instead. So:

```
if ((foo && bar) || blah) { ... }

```

Becomes:

```
if ((foo & bar) | blah) { ... }

```

Using integer arithmetic instead. If your foos and bars are constants or evaluated before the if(), this could be faster than the normal boolean version.

As a bonus the arithmetic version has less branches than the regular boolean version. Which is another way to optimize.

The big downside is that you lose lazy evaluation - the whole block is evaluated, so you can't do `foo != NULL & foo->dereference()`. Because of this, it's arguable that this is hard to maintain, and so the trade-off may be too great.
> 1 votes

# Answer
**Keep an eye on your stack usage**

Everything you add to the stack is an extra push and construction when a function is called. When a large amount of stack space is required, it can sometimes be beneficial to allocate working memory ahead of time, and if the platform you're working on has fast RAM available for use - all the better!
> 1 votes

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


title: Multiplayer FPS server side performance

text:
# Question
Title: Multiplayer FPS server side performance
This is related to MMO Performance except that question is about bandwidth. This is about cpu load.

I put together a simple FPS using node.js and webGL. It's extremely simple, a lot like the BuddyMaze clone of MIDI Maze. There's very little going on, everyone moves in two dimensions (no height), shoots simple projectiles, and runs into walls.

Right now, if I make multiple connections to the server where every player shoots rapidly while spinning in circles, I can get about 15 - 20 players in the game before the server maxes out a core and slows way down. And this is when running at 30 fps on the server. At 10 fps, I get about 25 - 30 connections. This is pretty bad, since the game is going to have a lot more to do soon and I'll need to fit more players for this to be a feasible endeavor.

My brother just pointed out some stats about his coworker's TF2 server. His server is lower specs than ours, yet it runs TF2, obviously a much more complex game, at a whopping 500 ticks per second, with 36 users per core. Also, we currently consume much more bandwidth than they do, but we haven't been trying to lower that much yet.

How is this possible? What sort of tricks are there to increase server performance to this magnitude? Some things that I know of include:

* Lowering framerate on the server, and interpolate positions on the client. I got some benefit, but clearly the TF2 server doesn't even bother with this.
* Doing expensive things like collision detection on the client, and verify it infrequently on the server. I haven't moved this over just yet, I will tonight. Even so I don't expect such an enormous gain.
* Break the playing field into regions (quad trees) to minimize calculations. Haven't had an opportunity for this yet.
* I've considered the unfortunate possibility that node.js is just way slower than whatever TF2 is using, and may not be suited for this kind of high intensity task.
* Is it all in the server configuration magic?

So what are the other tricks of the industry to do only the minimum required on the server but still have a flawless game experience? There's a big conflict between "defer to client to save cpu time" and "don't trust the client", so maybe it helps to know where the line is drawn in various situations?

## Update

Profiling really is the only mantra I've ever found that's absolutely infallible. I quickly wrapped some timing functions around my code (thanks, FP!) and discovered what I never expected: the act of broadcasting the data to clients accounts for nearly all of the execution time. Specifically, around 90% of it. Further testing showed that this time is dependent on both the number of clients and the size of the data, but more so the latter. On a 20 user load, I cut my broadcast time 90%, from 24ms down to just over 2ms by sending only "{}" instead of the full data. But with only 5 users, broadcasting takes around 0.5 ms. So I clearly need to do some optimization here.

The first most obvious improvement is line of sight checking. This would decrease both the number of people who care about data, and also the amount of data sent to interested parties. Are there other tricks in this realm I can try, which focus on minimizing the cost of my broadcast operation?

# Answer
Your server should not send the state of all players to all players at every tick. Instead it should send a specially crafted message to each client say every 500 ms saying "these x players in your view port should be at these coordinates in 500 ms." Most of the time this will work fine, but if the server realizes it has given wrong information it just sends an extra message.

This will decrease network traffic dramatically.

Another thing to consider is to not have game ticks on the server, but instead have the client send messages only when an action occurs (changed direction, shot fired) and then calculate ahead on the server when an action is received.
> 5 votes

# Answer
> I've considered the unfortunate possibility that node.js is just way slower than whatever TF2 is using, and may not be suited for this kind of high intensity task.

It's probably this. TF2's server is written using C/C++, and thus, is going to be faster than node.js (which if I remember correctly, uses Javascript interpreted in Java)

Google's WebGL based Quake uses java for the server, and the source code is found here: http://code.google.com/p/quake2-gwt-port/. It might be worth looking through that to see how it's done. I also wonder what you mean when you talk about having a framerate on the server. There's no reason to render anything on the server, it should just be there for processing commands sent by the client.

Finally, the rule "do not trust the client" is more important than offloading expensive calculations onto the client in hopes of improving performance. Especially something as important as collision detection. Doubly so when your game is Javascript based, and thus fairly easy to hack (compared to something like TF2 which is compiled).

I know this isn't much of an answer, but hopefully it'll point you in a few directions that might help improve performance.
> 1 votes

---
Tags: performance, client-server, first-person-shooter
---


title: Online multiplayer game basics

text:
# Question
Title: Online multiplayer game basics
I'm currently working on a c# online multiplayer game in real-time. The aim is to have client/server based connection using the UDP protocol. So far I've used UDP for players' movements and TCP for events (a player shooting, a player losing life) because I need to be sure such data will arrive to all players connected to the server. I know that UDP is said 'unreliable' and some packets may be lost. But I've read everywhere to never mix TCP and UDP because it can affect the connection.

The main question is how should I organize my network?

UDP is connectionless, how should I save who's is who? Should I save ip adresses of the clients in a list?

Should I use TCP for important events or use UDP? If I need to use UDP, how can I make sure that data will not be lost?

By using both TCP and UDP, I need to save for each player their IP in a list (for UDP) and the TcpClient which is connected in another list (for the UDP). How could I change that to be more effective?

# Answer
UDP has less overhead, but at the cost of losing packets without knowing about it (part of the overhead with TCP ensures that lost packets get re-sent).

However, the big problem with using UDP is that there are many sites that block all UDP traffic (except for DNS) because many administrators believe it's a good security practice.

Also, don't assume that every one of your players will have a different IP address -- there are many situations where multiple users share the same internet connection, and if school kids get hooked on your game you can bet that they're probably going to figure out how to install and run it during class instead of doing their work (and wouldn't you rather that they be spending this precious time on your game instead of someone else's?).

Once your TCP stream is open, it's still pretty efficient. The next step is to minimize the amount of data you're sending/receiving, and this is where protocol design comes into play. If you just send a few bytes for each command (e.g., "move forward") instead of, for example, wrapping the same command in hundreds of bytes of XML code, then your overall network bandwidth consumption will be lower AND fewer CPU cycles will be required to process the information (a few bytes are easily compared versus dismantling and interpreting and syntax-checking a big chunk of XML).

You certainly can open multiple TCP streams and use them for different purposes, such as one for commands, another for graphics transfers, another for audio-based chat, etc. That way, if you're transferring a large graphic that takes 5-10 seconds to download, at least player command movements won't lag because they'll be on a different stream (and you can display a default sprite until the new sprite is finished downloading, which is always more fun than waiting).
> 6 votes

# Answer
This is not a direct answer to your question, but gafferongames has some really nice articles on network games: http://gafferongames.com/networking-for-game-programmers/what-every-programmer-needs-to-know-about-game-networking/
> 3 votes

---
Tags: c#, networking, multiplayer, websocket
---