# Question
Title: All of my matrix functions not working? OpenGL ES 2.0
I am trying to make a projection matrix scaling the screen and making a coordination system. For some reason I don't think any of my matrix calling is working... the 3 function I am using are

```
Matrix.orthoM(mProjMatrix, 0, 0, 1520, 0,  1000, -1, 10);
Matrix.setLookAtM(mVMatrix, 0, 0, 0, 1.0f, 0.0f, 0f, 0f, 0f, 1.0f, 0.0f);
Matrix.multiplyMM(mMVPMatrix, 0, mProjMatrix, 0, mVMatrix, 0);

```

Are they canceling each other out? anything wrong with it? (the full rendering class code is at the end)

My main goal in doing this is eventually getting to a situation where when I make a square, I could provide coordinates such as `(200, 100,0) //x, y, z` which are not only between -1 and 1.

Here is my full rendering class:

```
public class MyRenderer implements Renderer {

private static final String TAG = "MyRenderer";

Square square;

private final float[] mMVPMatrix = new float[16];
private final float[] mProjMatrix = new float[16];
private final float[] mVMatrix = new float[16];
private final float[] mRotationMatrix = new float[16];

private int camWidth,camHeight;

@Override
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
    GLES20.glClearColor(0.0f, 0.0f, 1.0f, 0.5f);
    camWidth=480;camHeight=320;
    // initialize a square
    square = new Square();
}

@Override
public void onDrawFrame(GL10 nope) {
    GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_DEPTH_BUFFER_BIT);

    //set camera position

    GLES20.glViewport(0, 0, camWidth, camHeight);

    Matrix.orthoM(mProjMatrix, 0, 0, 1520, 0,  1000, -10, 999999);
    Matrix.setLookAtM(mVMatrix, 0, 0, 0, 1.0f, 0.0f, 0f, 0f, 0f, 1.0f, 0.0f);
    Matrix.multiplyMM(mMVPMatrix, 0, mProjMatrix, 0, mVMatrix, 0);

    square.draw(mMVPMatrix);
}

@Override
public void onSurfaceChanged(GL10 nope, int width, int height) {

    GLES20.glViewport(0, 0, camWidth, camHeight);

    Matrix.orthoM(mProjMatrix, 0, 0, 1520, 0,  1000, -10, 999999);
    Matrix.setLookAtM(mVMatrix, 0, 0, 0, 1.0f, 0.0f, 0f, 0f, 0f, 1.0f, 0.0f);
}

public static int loadShader(int type, String shaderCode) {

    // create a vertex shader type (GLES20.GL_VERTEX_SHADER)
    // or a fragment shader type (GLES20.GL_FRAGMENT_SHADER)
    int shader = GLES20.glCreateShader(type);

    // add the source code to the shader and compile it
    GLES20.glShaderSource(shader, shaderCode);
    GLES20.glCompileShader(shader);

    return shader;
}

 }

```

My Square class (wasn't sure if needed or not, but just to be safe :) ) -

```
public class Square {
private final String vertexShaderCode =
    "attribute vec4 vPosition;" +
    "void main() {" +
    "  gl_Position = vPosition;" +
    "}";

private final String fragmentShaderCode = "precision mediump float;"
        + "uniform vec4 vColor;" + "void main() {"
        + "  gl_FragColor = vColor;" + "}";

static final int COORDS_PER_VERTEX = 3;

static float triangleCoords[] = { // in counterclockwise order:
-0.5f, 0.5f, 0.0f, // top left
        -0.5f, -0.5f, 0.0f, // bottom left
        0.5f, -0.5f, 0.0f, // bottom right
        0.5f, 0.5f, 0.0f

};
private short drawOrder[] = { 0, 1, 2, 0, 2, 3 };
private final int vertexCount = triangleCoords.length / COORDS_PER_VERTEX;

private final int vertexStride = COORDS_PER_VERTEX * 4; // bytes per vertex

// red-green-blue-alpha
float color[] = { 0.63f, 0.76f, 0.22f, 1.0f };

private final int mProgram;
private int mPositionHandle;
private int mColorHandle;
private int mMVPMatrixHandle;
private FloatBuffer vertexBuffer;
private ShortBuffer drawListBuffer;

public Square() {
    ByteBuffer bb = ByteBuffer.allocateDirect(
    // # of coords values * 4 bytes per float
            triangleCoords.length * 4);

    // use native byte order
    bb.order(ByteOrder.nativeOrder());

    // create a floating point buffer from the ByteBuffer
    vertexBuffer = bb.asFloatBuffer();
    // add coordination to FloatBuffer
    vertexBuffer.put(triangleCoords);
    // set the buffer to read first coordinate
    vertexBuffer.position(0);

    ByteBuffer dlb = ByteBuffer.allocateDirect(drawOrder.length * 2);

    dlb.order(ByteOrder.nativeOrder());

    drawListBuffer = dlb.asShortBuffer();
    drawListBuffer.put(drawOrder);
    drawListBuffer.position(0);

    int vertexShader = ChizRenderer.loadShader(GLES20.GL_VERTEX_SHADER,
            vertexShaderCode);
    int fragmentShader = ChizRenderer.loadShader(GLES20.GL_FRAGMENT_SHADER,
            fragmentShaderCode);

    mProgram = GLES20.glCreateProgram();
    GLES20.glAttachShader(mProgram, vertexShader);
    GLES20.glAttachShader(mProgram, fragmentShader);
    GLES20.glLinkProgram(mProgram);

}

public void draw(float[] mvpMatrix) {
    // Add program to OpenGL ES environment
    GLES20.glUseProgram(mProgram);

    // get handle to vertex shader's vPosition member
    mPositionHandle = GLES20.glGetAttribLocation(mProgram, "vPosition");

    // Enable a handle to the triangle vertices
    GLES20.glEnableVertexAttribArray(mPositionHandle);

    // Prepare the triangle coordinate data
    GLES20.glVertexAttribPointer(mPositionHandle, COORDS_PER_VERTEX,
            GLES20.GL_FLOAT, false, vertexStride, vertexBuffer);

    // get handle to fragment shader's vColor member
    mColorHandle = GLES20.glGetUniformLocation(mProgram, "vColor");

    // set color for drawing the triangle
    GLES20.glUniform4fv(mColorHandle, 1, color, 0);

    // get handle to shape's transformation matrix
    mMVPMatrixHandle = GLES20.glGetUniformLocation(mProgram, "uMVPMatrix");

    // apply the projection and view transformation
    GLES20.glUniformMatrix4fv(mMVPMatrixHandle, 1, false, mvpMatrix, 0);

    // Draw the triangle
    GLES20.glDrawElements(GLES20.GL_TRIANGLES, drawOrder.length,
            GLES20.GL_UNSIGNED_SHORT, drawListBuffer);

    // dispable vertex array
    GLES20.glDisableVertexAttribArray(mPositionHandle);

}
}

```

And lastly, just so you could have some visuals:

This is how it looks on my phone with and without the three metrix functions mentioned before, it also seems that the only thing that did make any change with the width and height was `GLES20.glViewport(0, 0, camWidth, camHeight);`

It seems as if the metrix is doing nothing.

# Answer
> 3 votes
In OpenGLES 2, your matrices are not multiplied for you by the fixed pipeline as in OpenGLES 1.1. You have to do that by yourself, and the best place to do that is in the vertex shader.

It seems like you're already passing the matrix to the vertex shader as a uniform called `uMVPMatrix`, so all you have to do is use it.

To do this, change your vertex shader code to look like this:

```
attribute vec4 vPosition;
uniform mat4 uMVPMatrix;

void main()
{
    gl_Position = uMVPMatrix * vPosition;
}

```

---
Tags: android, opengl-es, matrix, opengl-es2
---


title: Can I develop libgdx game with C#?

text:
# Question
Title: Can I develop libgdx game with C#?
I see some articles through Google that I can use `libgdx` in C#. Is it true? I found no official and unonfficial about this. If there is a way, please tell me how. Thank you

# Answer
A quick googling seems to suggest they are using IKVM, which is a JVM that runs on top of .NET. It is not official, and "you can use libgdx with C#" is about as true as "you can use any Java library with C#." In fact, it looks like the ios backend is build on top of MonoTouch, so the compatibility should be reasonably well-tested, although I still can't find .NET binaries in the official release. However, I imagine C#+libgdx would not be compatibile with the HTML5 or Android backends.
> 2 votes

---
Tags: c#, libgdx
---


title: 2D field of view detection inverted

text:
# Question
Title: 2D field of view detection inverted
**I'm not sure if the title matches what I'm actually facing**

I'm trying to test if I can see a point is in my field of view (in the context of an NPC seeing in it's direction.)

I know that:

```
cos0 = (A.B)/||A||||B||

```

We have our point x. We have our heading h. We have our position p.

```
cos0 = (h.(p-x))/||h||||x-p||

```

So to test whether a point is in it's view we simply check if

```
cos0 >= view/2;

```

But for some reason the bigger the angle, the closer you have to be to the center in order for it to detect you. For smaller angles it's the opposite:

Here is what I have now. (click the " Play flash full screen " , for some reason the hosting settings won't show it in it's original size)

You can see that the bigger views actually respond only when you are near the center. While the smaller views start rotating even though you're not even in their view.

for now I'm using the mouse coordinates. I'm pretty sure all vectors operate in the same space coordinates.

Properties and constructor:

```
private var heading:Vec2 = new Vec2(); // Always a unit vector
private var position:Vec2 = new Vec2();
private var fovDeg:Number = 30.0;
private var fovRad:Number = 0.0;
private var distance:Number = 300;
private static const toRad:Number = (Math.PI / 180);

public function Fieldofview(degree:Number = 45.0 )
{
   fovDeg = degree;
   fovRad = fovDeg * toRad;
   fovRad /= 2;
   heading._x = 1.0;
   heading._y = 0.0;
   drawField();
}

```

The function to test wether it's within the view

---

```
public function pointIsInView(p:Vec2) : Boolean
{
    //vector from our position to point to test
    var diffVec:Vec2 = p.sub(position);
    var diffNorm:Vec2 = diffVec.normalize();
            //both are unit vectors so the dot should be enough
    var dot:Number = diffNorm.dot(heading);

    if (diffVec.length() > distance ) {
        return false;
    }

    //Check if we are in bound
    if ( dot >= fovRad) {
        return true;
    }

    return false;

}

```

Anyone have an idea what is causing this?

# Answer
"dot" is a cosin not an angle, can not be compared to "fovRad" that is an angle

You can get angle of "dot" with an arccosine function, or get the cosine of "fovRad" to compare them.
> 3 votes

# Answer
```
//Check if we are in bound
if ( dot >= fovRad) {
    return true;
}

```

You are comparing `cos(0)` to `fovRad`.
> 1 votes

---
Tags: mathematics, angles, linear-algebra
---


# Question
Title: Developing an interactive book for Windows-Runtime
My three year old loves playing with the interactive books on our iPad, and I love playing with code and I love my Surface RT...

So I thought I'd try and make a basic animated book using WinRT, I've spent some time reading about animations (granted the book isn't WinRT based), and thought I'd try and use the Storyboard approach rather than rolling any kind of bespoke animation framework.

That was until I saw the Faresee Physics Engine, and the Physics XAML Helper.

I've played around with some of the more basic examples, and it seems pretty good - very easy in-fact.

My issue is when I start thinking about stringing together animations that can react to input, the Farsee and Physics XAML Helper blows my mind a little.

As a proof of concept I was thinking about getting a character to walk from a path (in the top right), and while moving closer (getting larger) walk to the front at the center.

Then, based on some kind of decision, via an input, walk either back to the right, or up to the left. Both are back into the distance (getting smaller) as if walking away.

The character should have basic humoid movement, athough slightly cartoon-like - swinging arms, moving head and legs. Also, it would be nice to have the ability for the character model to swap images when it walks back up the path.

My question (finally!), is do you think that it's better to use the built in Storyboarding features of WinRT, with it's animations - primarily using easing and descrete key frames to create each animation 'scene'. Or, use something like Farsee and the Physics XAML Helper to create the scene using real word objects and physics?

Are there any examples, samples, tutorials etc of creating anything similar?

Thanks,
Kieron

# Answer
The real physics don't get good animations like the ones needed for a interactive book for children. My advice, use a tool like Flash or similar to create the animations and then load the files from your Book program.

A must see in animations is the 12 principles of animation
> 1 votes

---
Tags: c#, animation, farseer-physics-engine, storyboard
---


# Question
Title: How does a point squared equal the radius squared?
I am working on a simple ray tracer but I don't understand some of the formulas.

One that is bugging me at the moment is this:

> If a sphere is centred at origin, a point **p** lies on a sphere of radius ***r*2** if
> **p\*p = *r*2**

Now, as I understand it, 'p' is a point in 3D space, (x,y,z), so how is it possible to square the point and have it equal the radius squared?

For what it's worth, I'm reading this article on calculating the intersection of a ray and a sphere.

# Answer
There are two ways to "multiply" vectors: the dot product and the cross product.

In this case, they're using the dot product, and it is very easy to see that, if *p* is centered at the origin, then:

```
  dot(p, p)
= (p.x * p.x) + (p.y * p.y) + (p.z * p.z)
= mag(p) ^ 2 // per the pythagorean theorem

```

Now, if the magnitude of your vector happens to be the radius of the sphere, then your point will lie exactly in the sphere.
> 9 votes

# Answer
You seem to have paraphrased the formula incorrectly. In vector algebra, there are several types of multiplication and they use different symbols. The original article uses the dot product (·) which is not equivalent to the generic multiplication symbol \*. It also uses bold face to signify vectors as opposed to scalar quantities, i.e.  is not the same as . In fact, as you rightfully noted, you cannot really 'square' a vector.

The formula as it was originally written is:

***p** · **p** = r²*

If two vectors point in the same direction, as ***p*** and ***p*** obviously do, their dot product equals the square of their absolute values or 'lengths'. By definition, any point at a distance *r* from the origin lies on the sphere with radius *r* centered at the origin. Ergo, if the square of a vector's length equals the square of this sphere's radius (***p*** *· **p** = r²*), then the point lies on a sphere with radius *r*. The article mentions the sphere's radius is ; this is incorrect.
> 1 votes

---
Tags: 3d, mathematics, raytracing
---


# Question
Title: How to approach skinning a snake made of cubes and is it right method for snake 3d game
I'm making a 3d snake game clone for studies and prettly much got everything to work, I have a 3d ground object surrounded by walls, and a snake head piece (cube). when you start the game 2 additional snake body (cube) are being added and follow the head in a snake like movement, every time you eat an apple additional snake piece is added.

I want instead of cubes to have a snake object (which I got already) my question is what is the approach to make the cubes act like the bones of the snake object and make the snake object get it's shape from it's "bones".

also maybe there's a way to add bones to the snake object I got in a program like 3dsMax ? and then make the bones act like the cube pieces I got in the game and it will work?

I also tried cutting the body of the snake object I got and adding each snake body cube the cutted snake body object but then it doesn't get the look I want (smooth snake that can turn in 3d) so I think the right idea is to have one big object that get it's positon and rotation based on smaller bone objects.

# Answer
> 2 votes
Well, here's my 2c.

1. Having a single snake mesh in this context will be a lot harder to implement/maintain than having the modular cubes system. Think about it: initially your snake mesh has no joints (1 bone). When it eats an apple the mesh scales (on it's length axis) and needs to have 1 joint (2 bones - vertices on the mesh need to be re-assigned from 1 to 2 bones) etc.
2. One way to do this is to have multiple meshes for each of the possible number of bones (like 1 mesh with 1 bone, one with 2 bones, one with 3, etc). Then you still keep your cube system only now the cubes are not rendered, and then each time an apple is eaten, you remove the current mesh and add the one corresponding to the new length of the snake. At the same time your cube snake evolves as well, and each time you do this you link each of the new snake-mesh's bone to each corresponding cube and voalah, the mesh's bones are guided by the cubes.
3. Honestly what I'd do is:

-keep separate-cubes body style

-have 3 types of cubes: head, middle-body, tail

-size them so that they overlap and use some clever transparency on the textures to give a as-good-as-possible illusion of continuity.

---
Tags: 3d, game-design, unity, 3d-meshes
---


# Question
Title: Game state and input handling in component-based entity systems
My question is:

**How can I handle game states in my entity system, without resorting to keeping a stack of game state objects around?**

So the design of my entity system means that when an entity needs to register for input events for instance, the input component calls the input system and says "register this entity for this input". This is all fine and well, however if you add into this the concept of game states (say a pause screen), it becomes a problem to work out if an entity is in the current state and should receive the input.

I could augment the input component/system so that it says, "register this entity for this input while in these game states", but this requires that every entity know which states it's going to be used in, and that may not be obvious. Also, keeping a list of game states around per registered input (and other systems that use callbacks) doesn't sound too efficient.

Another idea I had is since there will be an entity that represents the game state, mark that as being disabled, then when generating the input event check that the entity is not a descendant of a disabled game state entity. Seems expensive to work out the parent for every callback.

Another idea is to have all the systems store their data keyed against the current state, that way when generating the input, the target entity won't even be a candidate. However this really hurts the ability to allow communication between entities in different states (not so much a problem for pause screens, but think lock picking in Oblivion/Skyrim).

The only other idea I've had is to have all components handle a state change events and communicate with their relevant system to disable anything they have registered, and re-enable it when switching back to this state.

The second (mark an object as disabled) and forth (have each component deal with state changes) seem like the best of my ideas, but none of them jump out at me as being particularly great.

Does anyone else have any other ideas on how to do this?

*edit* While I talk about input specifically in this question, it can mean any system capable of sending messages/events to entities, such as collisions, timer events, etc...

# Answer
> 15 votes
What is often used is an intermediate `Intent System` which abstracts the input and keeps track of the context and relevant gamestates.

The Intent system will stop transmitting inputs when the simulation is paused for example. It also handles the mapping between controller events and intents (move in direction, run, shoot, reload...).

This way your other conponents are not dependent on specific gamepads/inputs (BUTTON\_A, BUTTON\_B vs BUTTON\_X, BUTTON\_O...) but they all react to the same intents (IntentRun, IntentReload...).

Another advantage is that the intent system can be aware of available controllers being added/removed, as it can send intents to any subscriber even outside the simulation you can handle intents like `AddPlayer(controllerID)`.

How much information about the game state you provide to the system either through events/message or directly is up to you. But the time invested in the Intent system is usually worth it.

You can manage Intent Contexts which will generate intents when they are attached to the system.

The context can be prioritized, i.e.:

* SimulationAvailableContext sends intents to the simulation while it is available (but not running) for example move the camera, zoom in zoom out, add/remove player...
* SimulationRunningContext sends intents to the simulation while it is not paused move player, send unit to position, shoot...

This way you can add and remove the contexts which are currently relevant.

And one thing about the whole intent systems is that it should run while the simulation is paused.

One way which is often used to play/pause the game simulation without breaking non simulation related updates is to use a different sets of times. i.e. `GenericSystem::onTime(Long time, Long deltaTime, Long simTime, Long simDeltaTime)`.

With this approach your engine can simply block the increments on the games's simTime which in turn will block updates on the relevant animation & physics engines which use `simTime and simDeltaTime` while allowing continuous updates of your camera spring effect if it has to move even during pause, the animation of the loading effect on a virtual in-game billboard while data is being downloaded...

# Answer
> 2 votes
How about creating a global event system and then have an event listener component for your each entity? After an event "Game State Change" you could fiddle with components individually for each particular entity.

Let's say you have an input component. After the event listener component receives the game state change event, it changes very specific values for that particular input component, so it wouldn't receive any input calls or wouldn't make any movement or response calls to the system or it's owner.

This works for me as most of my components are scripted (via Lua). I.e. I have an input component, which is triggered once when a key is pressed and it fires of a movement + direction and then it is triggered when the key is released and it fires of a stop + direction. There is also an event listener component which contacts the input component (if the game is paused) to stop doing any function firing and halt if necessary. I could easily then add another entity with a different reaction to the same events and keypresses using another script. This way you would save the interaction between different entities in different states and even make it much more customizable. What is more, some entities might not even have the event listener component in them. There is one drawback though - since it requires the engine core to call in scripts every time something happens, it might affect performance, but I personally haven't got any problems with this particular solution.

What I just explained is basically a practical example of your fourth solution.

---
Tags: component-based, entity-system, input, state
---


# Question
Title: Game state management: the buck doesn't stop "here" soon enough
I realize there are already many Q&As on this site about GameState/GameScreen management, state machines, state stacks, etc. This question is meant as a follow-up:

Suppose hypothetically I decide to go with a simple state machine for the fundamental transitions in the program:

```
[intro loop] <---> [main menu] <---> [gameplay] <---> [pause menu]
                       \               /     \
                        `-<---[game-over]      `---> [ending]

```

of course that is not meant to be a comprehensive diagram by any means. (And I'm aware of the suggestion to not use a game state machine at all, but let's say I would like to go ahead and make one).

I happen to be using the SFML framework in C++, so in my code my main loop happens to look like this:

### MainLoop.cpp:

```
while(app->isRunning())
{
    while(app->win->pollEvent(event))
    {
        switch(event.type)
        {
        case sf::Event::Closed:
            app->exit();
            break;

        case sf::Event::Resized:
            app->resize(event.w, event.h);
            break;

        case sf::Event::KeyPressed:
            app->handleKeyPress(event.key));
            break;

        case sf::Event::KeyReleased:
            app->handleKeyRelease(event.key));
            break;

        // ... etc.

```

This means I have an 'app' object implementing a certain interface:

### Application.h

```
public:
    virtual bool isRunning() const = 0;
    virtual bool isPaused() const = 0;
    virtual void pause() = 0;
    virtual void resume() = 0;
    virtual void exit() = 0;
    virtual void resize(int w, int h) = 0;
    virtual void render() = 0;
    virtual void handleKeyPress(int key) = 0;
    virtual void handleKeyRelease(int key) = 0;
    virtual void handleMouseClick(int btn) = 0;
    // ... etc.

```

but following the principle of favouring composition over inheritance, my 'app' object (say `MyGame`) which implements this interface *is not* a state machine, but *contains* a StateMachine as a member, like so:

### MyGame.h

```
class MyGame : public Application
{
private:
    StateMachine * myStateMachine;
    // ... etc.

```

So for things like `handleKeyPress()` and `handleMouseButton()` it simply delegates these calls to its member state machine like so:

### MyGame.h

```
public:
    void handleKeyPress(int k) { myStateMachine->handleKeyPress(k); }
    void handleMouseClick(int b) { myStateMachine->handleMouseClick(b); }

```

Meanwhile, the `StateMachine` object DOES THE SAME EXACT THING, i.e. it forwards these same calls to the "current" `State`:

### StateMachine.h

```
class StateMachine : public Application
{
private:
    State * currentState;

public:
    void handleKeyPress(int k) { currentState->handleKeyPress(k); }
    void handleMouseClick(int b) { currentState->handleMouseClick(b); }

```

which -- to me, looking at the big picture now -- seems a bit crazy because now each time the user moves the mouse, presses a key, or breathes the wrong way I'm going through a chain of THREE virtual method calls?

Every class in the chain seems to implement this same `Application` interface of `handleThis()` and `handleThat()` and `enter()` and `exit()` and so forth. `StateMachine` might as well inherit from `Application`, and while we're at it, each `State` could also! But each of them ends up passing the buck down to the next lower layer:

```
[MainLoop] keyPressed:
  `-> [MyGame] handleKeyPress()
        `-> [StateMachine] handleKeyPress()
                   `-> [State] handleKeyPress()
                          `-> actual code that handles keyboard input

```

Should I be trying to "flatten" this architecture, so to speak, to avoid all this virtual method chaining & delegation? If so, how do I do that while still maintaining a reasonable separation of concerns, where `Application`, `MyGame`, `StateMachine`, and each individual `State` are not all stuffed into the same class? (Or maybe they should be.)

I may be worrying about optimization prematurely, since some of these virtual method calls (esp. from `StateMachine` --\> `State`) can be inlined. So who knows, maybe this design is not all that unreasonable.

*Obviously: first-time game architecture ever, guys... this exercise has been quite humbling.*

# Answer
Your class tree in general confuses me, namely the fact that you have multiple "Application" derived classes that presumably get implemented all in the same application. It further seems to be a grab bag of all sorts of unrelated functionality... simulation state management, layout, rendering, input... which seems to be why you have so much forwarding: These classes don't really have any reason to be dealing with these events. This is most evident by the fact that they *don't* deal with these events: they just forward them on for other classes to deal with.

Sometimes forwarding is appropriate... most components in a UI render their children, for example. Sometimes this is best handled with a single base class that forwards everything, leaving the classes deriving from that to override the methods they don't want forwarded. But here I'd rather break the classes up, and bring the state machine closer to the surface.

Say instead we had these classes. They're effectively the base state classes, each corresponding to one concern only, not meant to be used with multiple inheritance:

## BaseStates.hpp

```
class GameSimulationState
{
    virtual bool isPaused() const = 0;
    virtual void pause() = 0;
    virtual void resume() = 0;
};

class RenderState
{
    virtual void resize(int w, int h) = 0;
    virtual void render() = 0;
};

class LocalPlayerInputState
{
    virtual void handleKeyPress(int key) = 0;
    virtual void handleKeyRelease(int key) = 0;
    virtual void handleMouseClick(int btn) = 0;
};

```

This could perhaps be all tied together by a final "ApplicationState" containing these states, although they don't need to be. Imagine we want to implement the escape menu of an RTS. By splitting things up like this, we gain more flexibility.

Consider multiplayer: Perhaps the user can't pause? Or can only pause so many times? We're free to substitute a different SimulationState for multiplayer vs single player without having to reimplement rendering and input, right at this level. We couldn't really do that with a single monolithic "Application" without breaking it down at some later date in some subclass.

Maybe we want to implement a fancy effect where we swish between two screens when bringing up the pause menu: We can do this with a new render state that references the render state we were switching out of and the render state we were switching to. We can reuse this for other screens, even though we might not even *have* a simulation state (maybe we're doing the intro movies and ESRB ratings etc.)

And if you're doing local coop where everyone has their own gamepad with built in keyboard, you can have multiple LocalPlayerInputStates without having multiple SimulationStates. Maybe player one is looking at their inventory like a noob while player two does all the killing ;)

isRunning()/exit() can be simplified into not even being part of the state, or ever specialized or forwarded: If an application doesn't want to be running anymore, it can simply call exit().

This isn't the best or only way to break things up, but it hopefully is at least a decent example of how it can be done. We could keep just the StateMachine class, and have it expose what the current states are (reasonable: we're focusing on letting it manage states, selecting what new states to use, things of that nature) rather than a bunch of rendering and input specific stuff that only serve to forward things to the true workhorse: the states.

## MainLoop2.cpp

```
while(isRunning())
{
    while(win->pollEvent(event))
    {
        switch(event.type)
        {
        case sf::Event::Closed:
            exitMainLoop();
            break;

        case sf::Event::Resized:
            // Assuming everything is initalized to states, even if they do nothing,
            // instead of doing a bunch of if() checks
            stateMachine->currentRenderState()->resize(event.w, event.h);
            break;

        case sf::Event::KeyPressed:
            stateMachine->currentInputState()->handleKeyPress(event.key));
            break;

        case sf::Event::KeyReleased:
            stateMachine->currentInputState()->handleKeyRelease(event.key));
            break;

    // ... etc.

```
> 7 votes

# Answer
Why are you worrying about 3 virtual function calls per key-press? Modern computers can execute roughly 100,000,000,000 instructions per second and you're worried about a handful of function calls for events that happen once or twice per second?

Your structure is fine. Factor out the `Application` interface to one called `EventHandler` or similar, have the Game/Statemachine/States implement that instead, and you're done.
> 3 votes

---
Tags: architecture, component-based, state, sfml, inheritance
---


# Question
Title: How would the entity system handle dependent components?
Currently, I am learning about entity-component-systems, and I have a question concerning the components. How would the systems handle dependent components?

---

For example, In a 2D game, I have a game object entity that has the following components:

* `RenderComponent` \- contains current character sprite
* `AnimationComponent` \- contains set of sprites and frame index
* `CharacterStateComponent` \- tells what the character is actually doing

Given player input, such as *"move\_forward"*, I am not sure which of the following procedures should happen:

1. **System Polling:**

1. `Input` notifies `StateSystem`.
    2. `StateSystem` updates `CharacterStateComponent`.
    3. `AnimationSystem` reads `CharacterStateComponent` changes.
    4. `AnimationSystem` updates `AnimationComponent`.
    5. `RenderSystem` reads `AnimationComponent` changes.
    6. `RenderSystem` updates `RenderComponent`.
    7. `RenderSystem` draws `RenderComponent` normally.
2. **All-in-one Updates:**

1. `Input` notifies `CharacterSystem`.
    2. `CharacterSystem` updates `CharacterStateComponent`, `AnimationComponent` and `RenderComponent`.
    3. `AnimationSystem`iterates `AnimationSystem` normally.
    4. `RenderSystem`draws `RenderComponent` normally.

---

I am not quite sure how the engine would respond to a change in one component that is suppose to update other components, as well. I believe there will be performance issue, when it comes to each system having to poll its prerequisite component changes (as shown in *System Polling*).

How would the entity system handle dependent components?

# Answer
I wouldn't suggest having your systems be triggered by input. The systems should run in your update loop and should poll input when they start. You can solve that by having an input component and system. That also means that only entities controlled by the keyboard have an `inputComponent`, so they're the only ones that get updated on keyboard input. Pressed keys should be queued in the `inputSystem` when they happens. Then the `inputSystem` will process the input when it's time to run. Similar to your first scenario, they would run in order:

```
inputSystem.process()
stateSystem.process()
animationSystem.process()
renderSystem.process()

```

Just make sure to order your systems so that you're not a frame behind. At the moment there's no cyclic dependencies in your systems, so you have no problems.
> 5 votes

# Answer
Components should be independent, and Systems should communicate via some indirection such as a message bus/event aggregator. Your input system can publish an event to the message bus, and any other interested systems can opt to subscribe to the event, thus decoupling the two systems in this way:

`InputSystem --> MessageBus.Publish(MoveForwardEvent)`

`MovementSystem --> MessageBus.Subscribe(MoveForwardEvent, MovementSystem.MovePlayerForward)`
> 2 votes

---
Tags: component-based
---


title: Making a point light follow the camera

text:
# Question
Title: Making a point light follow the camera
I'm applying phong shading onto a single giant triangle, and I'd like the light's coordinates to coincide with the camera's coordinates in 3D space. In order to do this, whenever I update the camera's coordinates, I also update the light's coordinates. However, diffuse and specular lighting don't "focus" exactly at the camera position when I bring the camera close to the triangle, instead they do it a few units too far. The triangle is .5 units below the XZ plane and parallel to it. Here is a picture demonstrating this effect.

Also, here are my HLSL shaders; this is where all the transformations happen.

```
// Vertex Shader ////////////////////////////////////////

 float4x4    Matrix; // ViewProjection Matrix
 float4x4    Matrix2; // View matrix
 float4x4    Matrix3; // View matrix with translation zeroed out

 float4    lightPos;

struct VS_INPUT
{
    float4  Pos     : POSITION;
    float4  Normal  : NORMAL;
    float2  Tex0    : TEXCOORD0;
};

struct VS_OUTPUT
{
    float4  Pos     : POSITION;
    float4  Normal  : TEXCOORD1;
    float4  LightDir     : TEXCOORD2;
    float2  Tex0    : TEXCOORD0;
};

////////////////////////////////////////

VS_OUTPUT VShade(VS_INPUT In)
{
    VS_OUTPUT Out = (VS_OUTPUT) 0;

    Out.Tex0      = In.Tex0;

    //world space -> clip space transformation
    Out.Pos       = mul(In.Pos, Matrix);

    // world space -> camera space transformations
    Out.Normal    = normalize(mul(In.Normal, Matrix3));
    Out.LightDir  = normalize(mul(lightPos - In.Pos, Matrix3));

    return Out;
}

// Pixel Shader ////////////////////////////////////////

sampler   baseTex;

struct PS_INPUT
{
    float4  LightDir     : TEXCOORD2;
    float4  Normal  : TEXCOORD1;
    float2  Tex0    : TEXCOORD0;
};

struct PS_OUTPUT
{
    float4  Color   : COLOR;
};

////////////////////////////////////////

PS_OUTPUT PShade(PS_INPUT In)
{
    PS_OUTPUT Out = (PS_OUTPUT) 0;

    float4 Normal = normalize(In.Normal);
    float4 LightDir = normalize(In.LightDir);

    float di = saturate(dot(Normal, LightDir));

    float4 ambient = {0.1, 0.1, 0.1, 1};

    float4 Reflect = normalize(2 * di * Normal - LightDir);
    float specular = pow(saturate(dot(Reflect, LightDir)), 2);

    Out.Color = ambient + tex2D(baseTex,In.Tex0) * di + specular;
    return Out;
}

```

**EDIT**

In.LightDir *is* computed for each pixel. It is first computed for each vertex in the vertex shader *Out.LightDir = normalize(mul(lightPos - In.Pos, Matrix3));*, then it is interpolated across the whole triangle. lightPos is just the camera's position (which coincides with the light):

```
if(handle = m_pVertexConstants->GetConstantByName(NULL,"lightPos"))
        m_pVertexConstants->SetVector(pDevice,handle,(D3DXVECTOR4*)m_camera.GetPosition());

```

Also, the world transformation matrix is just the identity, so I have not included it anywhere.

# Answer
> 1 votes
Thanks to everyone for their responses, I have finally figured out the problem. Turns out I had to interpolate the positions, as they are transformed in view space, instead of the light direction. Apparently light direction does not linearly interpolate properly. Here are my modified shaders:

```
// Vertex Shader ////////////////////////////////////////

float4x4    Matrix; // ViewProjection Matrix
float4x4    Matrix2; // View matrix
float4x4    Matrix3; // View matrix with translation zeroed out
float4x4    Matrix4; // World matrix

//float4    lightPos;

struct VS_INPUT
{
    float4  Pos     : POSITION;
    float4  Normal  : NORMAL;
    float2  Tex0    : TEXCOORD0;
};

struct VS_OUTPUT
{
    float4  Pos         : POSITION;

    float2  Tex0        : TEXCOORD0;
    float4  Normal      : TEXCOORD1;
    float4  Pos2        : TEXCOORD2;
};

////////////////////////////////////////

VS_OUTPUT VShade(VS_INPUT In)
{
    VS_OUTPUT Out = (VS_OUTPUT) 0;

    Out.Tex0      = In.Tex0;

    //world space -> clip space transformation
    Out.Pos       = mul( In.Pos, mul( Matrix4, Matrix ) );

    // world space -> camera space transformations
    Out.Normal    = normalize(mul(In.Normal, Matrix3));
    Out.Pos2      = mul( In.Pos, mul( Matrix4, Matrix3 ) );

    return Out;
}

// Pixel Shader ////////////////////////////////////////

sampler   baseTex;

float4x4    Matrix; // ViewProjection Matrix
float4x4    Matrix2; // View matrix
float4x4    Matrix3; // View matrix with translation zeroed out
float4x4    Matrix4; // World matrix

float4    lightPos;

struct PS_INPUT
{
    float2  Tex0        : TEXCOORD0;
    float4  Normal      : TEXCOORD1;
    float4  Pos2        : TEXCOORD2;
};

struct PS_OUTPUT
{
    float4  Color       : COLOR;
};

////////////////////////////////////////

PS_OUTPUT PShade(PS_INPUT In)
{
    PS_OUTPUT Out = (PS_OUTPUT) 0;

    float4 Normal = normalize(In.Normal);
    float4 LightDir = normalize(mul(lightPos, Matrix3) - In.Pos2);

    float di = saturate(dot(Normal, LightDir));

    float4 ambient = {0.1, 0.1, 0.1, 1};

    float4 Reflect = normalize(2 * di * Normal - LightDir);
    float specular = pow(saturate(dot(Reflect, LightDir)), 2);

    Out.Color = ambient + tex2D(baseTex,In.Tex0) * di + specular;
    return Out;
}

```

---
Tags: 3d, directx
---


# Question
Title: Distributed C++ game server which use database
My C++ turn-based game server (which uses database) does not stand against current average amount of clients (players), so I want to expand it to multiple (more then one) amount of computers and databases where all clients still will remain within single game world (servers will must communicate with each other and use multiple databases).

Is there some tutorials/books/common standards which explain how to do it in a best way?

# Answer
> 8 votes
The MMO terminology for "remain within a single game world" is *single shard*. EVE online is the only major MMO to attempt stuffing every player into a single shard.

Lucky for you they published a very informative article on how they do it.

<sub>(source: gamasutra.com)</sub>

The bad news. You cannot apply EVE online's techniques generally. Their solutions are absolutely tailored to their particular genre and implementation.
*NOTE*: For all of EVE online's super fancy single shard network they use ***one*** database. They were unable to design a scalable, consistent, moderately real-time solution for distributed databases.

Either way reading how they did it ought to help you design you ownr solution. Beware however, you are attempting to solve a ***very*** difficult problem.

Instead of distributing your game server I would suggest explore your other avenues first.

* Profile your game server.
    + Optimize your server code to keep CPU burden down if that is a problem.
    + Optimize the communication protocol between the clients and the server to cut down on network chatter.
* Optimize the gamer server to database communications.
    + run a query optimizer then make changes as appropriate.
    + cut down DB interaction to a bare minimum
* Move the DB to a separate machine.
This often helps a ton. Keep the DB on the same local network if possible but that ought to help your game server be a lot more peppy when it's the only thing running on the server hardware.

# Answer
> 4 votes
Your first move should be decoupling direct database access from the game server and using a usage specific middleware to prepare data for your server (ie. XML, JSON). These would be able to handle any number of databases and more importantly be able to provide you with application specific caching options. Cache whatever you can and nag the db only when you must. Make big fetches and rarely instead of many small queries to achieve the best possible performance in your scenario.

The database of your choice might also allow you to operate clusters which make it easy to expand on the available database resources and provide your results faster, but this is a subject that needs much experience and a dedicated database administrator to set up and maintain - and not quite for the indie budget either.

# Answer
> 4 votes
**Regarding the game server:** A common strategy is to use multiple servers where each server manages a part of the game world. Each user usually only needs to know about what's happening around it, so it makes sense to divide the world by locality. This unfortunately gets a lot more complicated when you have an open world without any borders instead of a world which consists of closed zones and players teleport between them. When you have an open world, you need a way to transfer players between zones in a seamless way and a way to synchronize the areas near the borders between the servers. That's a tricky problem.

**Regarding the database:** SQL databases usually scale badly. They are not designed for being distributed. But there is currently a rather new trend of NoSQL databases like MongoDB or Cassandra which were designed to be distributed over multiple servers. They make it much easier to add capacity by just adding more servers. So why don't all the large games switch to them? Because:

1. SQL databases exist for over 40 years, those NoSQL databases only for a few years. There isn't much know-how yet how to use them most efficiently and their development is advancing rapidly. There are a lot of competing and completely incompatible products on the market, and there is no sign which of them will survive and which will be obsolete and discontinued in a few years. Most of the big players prefer the known shortcomings of SQL over the unknown risks of NoSQL databases.
2. They work very differently from SQL databases and require to rethink your whole persistence strategy. This might result in drastic changes throughout your whole software architecture.

So when your project is already very advances, switching to another database solution might be a large risk and a very big investment of time and energy.

# Answer
> 0 votes
No. This is an incredibly difficult area that has not been solved yet.

# Answer
> 0 votes
I know this is old but ....

There are actually two areas to focus on with this.

You need to distribute your application across several servers. You need to distribute your database across several servers.

And you need to have redundancy for both.

There are some open source solutions for this. Farmville is a good example using MemSQL / Couchbase.

---
Tags: server, databases
---


# Question
Title: How do I generate a 2d grid-based map without screwing it up?
I'm relatively new to the mechanics of game development - catching up fast, but there are still some things that escape me. For example: generating a fully-accessible map on a 2d grid.

See the example at http://crawl.s-z.org. Each floor map starts with dozens of winding labyrinthine passages and randomly drops in points of interest - temples, boss lairs, bazaars, etc. I know there's a lot of factors that go into this: generating passages that always have at least one exit (no isolated tunnels in the walls), making sure passages have at least a one-cell-width wall between them and adjacent parallel passages, and dropping points of interest in such a way that they connect to the dungeon.

I've taken a shot at it, and it's very easy to ranomly place lines in a 2d matrix that represent passages - but they're never guaranteed to connect, and it's not nearly as elegant as the maps at the above example.

I suppose my question is, what do I need to know to reproduce the example at crawl.s-z.org? I know this is a large question - I'd be fine with someone handing me a link to a reference site and telling me to learn it there. I'm just new enough at this that I don't even know what terms to google - maybe there are names for different generation processes? Available techologies are JS (jQuery) and PHP, so a solution tailored to one of those would be ideal. Thanks!

# Answer
I recently created a test program for an algorithm I found.

It works on the premise of:

> I'm an evil overlord and I want more space.

Basically the room is seems to be built out of necessity rather than uniformly with corridors.

The stages are as follows.

1. Fill the whole map with solid earth
2. Dig out a single room in the centre of the map
3. Pick a wall of any room
4. Decide upon a new feature to build
5. See if there is room to add the new feature through the chosen wall
6. If yes, continue. If no, go back to step 3
7. Add the feature through the chosen wall
8. Go back to step 3, until the dungeon is complete
9. Add the up and down staircases at random points in map
10. Finally, sprinkle some monsters and items liberally over dungeon

now at 4 the new feature in the Java example provided on that page, only builds a rectangle room or a corridor this could be expanded to have different kinds of rooms and at 5 implement a method to check your room will fit.

This ensures you can always reach the rooms/corridors as they have to be built off each other.
> 4 votes

# Answer
I didn't make random generating maps yet. But I'm sure I would use some path finding algoritms which aren't difficult to write.

For example path finding using queues. You add starting field to queue, then your function recursively takes first element from queue and adds every adjacent field of this taken field to queue. Then again you take first field from queue and so on.

Let's say you have two types of field (solid, nonsolid). When you get field from queue you can set it a type if it pass given conditions.

In example if adjacent field has already set type (nonsolid) that means you are going to make link between two routes or not going this way (setting it as solid) or if adjacent field is already in queue then dont add it to queue again so you wont go same route twice (unless you want to).

You have plenty of options and there is much more of explaining which I dont have time for. But queues is a way to go imo.
> 0 votes

---
Tags: javascript, maps, php, procedural-generation
---


# Question
Title: In modern AAA games with open environment and lot of static content (eg : crysis), how is occlusion culling performed?
Two ideas i have in mind :

1) Scene is rendered to a invisible buffer, using low resolution and low polygon count models (or even using only bounding volumes like cubes or spheres). The buffer is then checked to know what is visible or not. Before rendering the low resolution scene, some frustum culling could be applied, to already remove as much objects as possible.

2) A tool is run on the static map and will perform complex (and thus slow) ray tracing to know for some 3d positions on the map what is visible and what is not. All that information is then stored in a efficient way that can be user later at runtime (eg: an octree) This solution would only work for static meshes (eg : building) not moving objects.

# Answer
Jovan's answer is great, but just wanted to add that there is sometimes hardware support for asking the question "Did this geometry actually render any pixels?" (your idea #1) These are called occlusion queries - these is a good GPU Gems article about them here

This is pretty similar to your idea #1, except you don't need an invisible buffer, and can be more efficient or simpler than checking the buffer. The linked article does a great job going in-depth with how hardware occlusion queries work.

The Unreal Engine leverages hardware occlusion queries on platforms that support it, in addition to other techniques like view frustum culling and pre-calculating what static geometry is occluded.
> 13 votes

# Answer
> 1) Scene is rendered to a invisible buffer, using low resolution and low polygon count models (or even using only bounding volumes like cubes or spheres). The buffer is then checked to know what is visible or not. Before rendering the low resolution scene, some frustum culling could be applied, to already remove as much objects as possible.

This technique is used by Killzone, and is detailed in their presentation Practical Occlusion Culling on PS3. They also use *portals* for indoor areas.

One thing to keep in mind about large outdoor maps is that mesh simplification is as important as occlusion culling, so some variation of height-fields with geometry clipmapping is often used. Here is a good paper that covers culling as well. GPU Gems 2 has an implementation of it.
> 12 votes

# Answer
At least the first two Quake games used strategy 2; I don't know if idTech engines still use it. The reachable world is divided into convex spaces organized in a tree data structure ("binary space partition"), and for each node in the tree there's a bit vector representing which other nodes are visible from that node ("potentially visible set").
> 5 votes

---
Tags: game-mechanics, optimization, culling, occlusion
---


# Question
Title: AndEngine - Dragging a sprite that has a path modifier registered to it
I'm looking to be able to drag a sprite that is currently on a path from a path modifier. Currently, I have sprites on a path, and I have stationary sprites that are draggable. However, simply overriding the sprite's `onAreaTouched` doesn't work until the sprite completes its path. How would I do this?

# Answer
> 2 votes
I see those possibilities:

* you could call `clearEntityModifiers();` in the `onAreaTouched` of your sprite. This will kill **all** modifiers you registered to the sprite (so your pathmodifier but also any `AlphaModifier` or else).
* or you can call `unregisterEntityModifier( yourPathModifier );`

hope this helps. regards

Christoph

---
Tags: andengine
---


# Question
Title: How to generate houses procedurally in a voxel world?
I am developing a mod for the game Minecraft, a block-based voxel game. As part of the mod, I want to create a procedural house generator that will be generated based on specific needs/desires, such as a desire for a bed, a desire to have certain blocks as part of the 'furniture'/walling. It also needs to be able to be extended over time.

What kind of algorithms would be suitable to generate unique-ish houses of this sort? I was thinking some kind of genetic algorithm perhaps, or a collection of built in house modules. I would like to avoid manual user input / manual input of a large collection of widgets as much as possible, or at least allow the layout of a room to be dynamically generated or themed.

# Answer
First you need a very general function for creating rooms. So it takes a lot of parameters, say length, width, height, main material, detail material, floor material, number and style of windows, and so on.

Then you can create rooms considering the user requirements and the dimensions which you calculate out of the number of furniture the user selected. (For example assuming that every piece of furniture needs two blocks space at the edge of the room. So pass dimensions to the functions resulting in a big enough perimeter.)

After that you have to place the actual pieces like doors, windows, beds, workbenches, chests, and so on. I am not entirely sure how to that this but maybe you could just walk along the edges of the room and place things consecutively.

For now that algorithm would create determined results which is a bit boring. On the other hand it is hard to extend a random house because you would either store the edges or find them out later again. Nevertheless you could vary the dimensions by a random offset.

To create non-rectangular rooms take a closer look on noise algorithms or space division algorithms.
> 2 votes

# Answer
One Idea would be to provide so called modular sections of a house so.

For example you have modules for each section eg.

* Intersection
* Single room with NORTH,EAST,SOUTH,WEST entrance
* T junctions.
* Corridors

You would design these parts of the model with say 3 distinct block types base wall,detail, floor and store these sections with knowledge of their design and which block type they set at.

Your user can now select what to use for base wall, detail and floor and a design you came up with and also where to add an intersection or t-juction etc, at which the section would change accordingly.

This way is a fair bit of work to set up the logic but you can speed up the process if you take rotation into consideration.

Hope this helps
> 0 votes

---
Tags: algorithm, ai, procedural-generation, minecraft-modding
---


# Question
Title: Why does this geometry shader slow down my program so much?
I have an OpenGL program, and I'm rendering a terrain mesh. I displace the vertices in the vertex buffer and don't really color them in the fragment shader yet. I'm adding a geometry shader one part at a time.

Before I added the geometry shader, when I was just programming the fragment and vertex shading steps of the pipeline, I was getting framerates of about 30+. Enough that I couldn't notice any choppiness. After adding the geometry shader, I get around 5 frames per second. Why? This is the entirety of the geometry shader:

```
#version 420

layout (triangles) in;
layout (triangle_strip, max_vertices = 3) out;

void main()
{
    for (int i = 0; i < gl_in.length(); i++)
    {
        gl_Position = gl_in[i].gl_Position;
        EmitVertex();
    }
    EndPrimitive();
}

```

Isn't this exactly what OpenGL was doing without the geometry shader?

# Answer
> Isn't this exactly what OpenGL was doing without the geometry shader?

No, it isn't. The GS is an *optional* step, not a step that has a default.

In order for OpenGL to execute a geometry shader, it must perform what is known as "primitive assembly". When you render a series of triangles via `GL_TRIANGLE_STRIP`, OpenGL will do internal stuff to convert every 3 adjacent vertices into an individual triangle, modifying the winding order appropriately.

Normally, when not using a GS, this process is performed once. When you use a GS however, it must be performed before the GS executes. But it must also be performed *after* the GS, because a GS can output a totally different primitive type (e.g. quads).

So now you're making the system basically do a bunch of extra work for nothing. After all, OpenGL can't *assume* that your GS is doing nothing (that's a undecidable problem).

Furthermore, a number of optimizations no longer function in the presence of a GS. Consider indexed rendering.

Each index from an element array buffer will produce the same outputs from a vertex shader. So the GPU will often cache these outputs in a post-T&L cache. If it sees an index that is already in the cache, the VS is not run again; it just fetches data from the cache.

What is "it"? "It" is... the *primitive assembly unit*. Yeah, that thing that gets run twice when you use a GS. The index caching stuff? It only works for the *inputs* of the GS.

So what happens to the outputs of the GS? Well, that's hardware dependent. But it has to go into some kind of memory buffer. And therein lies the problem: that buffer isn't indexed at all. It's like a glDrawArrays situation.

So if you send an index buffer of `0, 1, 2, 0, 2, 3`, this would translate into 4 vertices in the post-T&L cache. But the post-GS buffer of vertices now has 6 vertices in it. The post-GS buffer uses more space. So if you go through the trouble of making properly post-T&L optimized triangle lists or strips, and you flip on a pass-through GS like yours, you basically killed about half of your performance gains from that optimization.

It wasn't useless, but it does hurt.

Adding to this is the fact that many GL 3.x-class GPUs (aka: DX10) had rather small post-GS buffers. The smaller the buffer, the fewer GS invocations you can have active simultaneously. So your hardware effectively bottlenecks on the GS. Because tessellation is a big feature of 4.x class hardware, most such hardware has buffers sufficient to make heavier GS use viable.

So using a GS is more likely to make your code vertex processing bottlenecked. Of course, you can always use that to your advantage by making your vertex and fragment shaders more complex, since it's just free performance at that point.

For more information about GS-induced slowdowns, read this article.

Here is a basic rule of thumb about GS's: never use a GS because you think it will make rendering *faster*. You should use it when it makes what you're trying to do *possible.* If what you're trying to do is an optimization, use something else.

The general exceptions to this are:
> 41 votes

---
Tags: opengl, glsl
---


# Question
Title: Level creation of Rayman Origins type game?
Does anyone know the technique they used to create their levels (using rayman origin as an example)? I'm strictly speaking of the floors and walls. Doesn't look like tiled based. What is the workflow that would be needed for a non-tiled based game? I am trying to implement something like this (below) but I am stuck between two ways of doing it

First: Just have art assets and get/set positions of them, similar to tiled based but the objects would be more detailed (with different positions for the x and y)-seems slightly tedious, I could save the locations to a text file and load it from there.

Second: I have seen an article which I can't find, but the game dev pretty much drew the base level (the walls, floors) and then added a bit of imagery on top of it. So in the picture below, they would've just drew green ledges and walls, then cover them up with leaf-like assets. - I would really like to implement this option, as I could for example, draw a straight line for a hill, then cover it up with some assets, but the collision would still be the straight line

# Answer
> 9 votes
Check out the article linked to below, it might be what you're looking for...

http://javilop.com/gamedev/c-game-programming-tutorial-non-tile-based-arbitrary-positioned-entity-engine-editor-like-in-braid-or-aquaria-games/

Not only does this approach allow arbitrary x, y locations for objects, it also lets you have depth. Depth lets you do parallax effects, plus focal depth (farther items out of focus).

This is the style used in Braid and Aquaria, both of which have an "almost" 3D look. The game you mention may be done the same way. Even scenes where objects are animated in a 3D way may just be animated sprites.

**edit** Looking further I'm pretty sure Rayman Origin is just a set of 2D sprites, some animated.

# Answer
> 9 votes
I can give more insights on this since I worked on it. We were indeed using a level editor similar to what's described in Tim Holt's answers: levels are built in 3D but all objects are flat, and the projection is orthographic.

But there is more than "a set of 2D sprites". The way UBIart worked at that time (I'm sure it evolved quite a lot today with the upcoming release of *Rayman Legends*) is that we had roughly two different sets of entities:

* The *friezes* were the blockout geometry, so the static collisions on the gameplay side. Level designers could edit them with a simple polygon editor to create a level's layout. Level artists could create and assign different sets of border and filling textures to give the levels their base look.
* The *actors* were either decoration or gameplay elements, using a component-based system. Most of them were either static images, or animated using a custom 2D skeletal animation tool. Level designers could place gameplay actors them anywhere in a level and play right away. Level artists could also drop images straight into the editor which would create actors for them.

The key point was that level editing was done straight in the game engine: any change in layout or look could be tested in-game straight away.

---

If you're interested, you'll find some pretty interesting articles on Gamasutra:

---
Tags: level-design, levels
---


title: PNG image as a level map for 2d game

text:
# Question
Title: PNG image as a level map for 2d game
I've been using a tilemap editor for making levels, but I was wondering if there was a way to use PNG images as the level map, as maps created in tiled editor are graphically uninteresting.

*Background*: I've recently started 2d game development and have learned basics i.e collision, game loop etc. I am developing game in JavaScript for Windows 8, but c#/c++ would work for me also.

# Answer
Sure it's possible and it has been done in the past, but there are several advantages and disadvantages associated with using a texture as the map:

* You'll need some way to determine specific attributes of parts of the map, e.g. whether some position is actually solid, or for other things, such as destructible terrain, ice, etc.
* Making parts of the map dynamic is rather tricky. So you can't do things such as moving platforms or doors as easy (they'll have to be in a different layer).
* Doing bigger maps can get rather memory consuming. Also consider limited hardware capabilities (maximum width/height for textures and such).

The only games I can think of right now using images as maps are several artillery clones, such as Worms, Gunbound, Warmux and others.

If you don't want to use repetitive tiles in a tile map, I'd suggest you use polygons to describe your map and separated tiles/textures to decorate your map. E.g. your map file defines the solid outlines of your map and where to place art assets for the solid areas to be visible in some way (e.g. as a rock).
> 3 votes

---
Tags: c++, 2d, javascript, level-design, map-editor
---


title: A starter need some tips and tricks

text:
# Question
Title: A starter need some tips and tricks
This might be a very stupid question as it's frequently asked on the internet. But i'm new to the game development and i would like to learn C++ in creating 3D games. what software is good for such things? :) also a little tip and tricks would be nice if some of you experienced guys could lend out.

# Answer
> 4 votes
This is the best link i can give you. It´s the best explenation i ever read.

http://www.gamefromscratch.com/post/2011/08/04/I-want-to-be-a-game-developer.aspx

# Answer
> 0 votes
as a quick response to a very open question you need to decide why you want to learn these things

if it is to purely make games in your spare time why not have a look at unity3d

if it is to become a programmer / gamedeveloper you should first learn the very basics of c++ http://thenewboston.org/tutorials.php or any other language you may choose.

after that you need to start thinking about which platforms you want to target and types of games you would like to make.

then i would start to consider your options in line with DirectX or openGL but always keep the options open to things like XNA, monogame or other libraries

there are thousands of tutorials out there microsoft has plenty of DirectX tutorials, and reimers.net has some also

---
Tags: c++
---


# Question
Title: Looking for an elegant way to represent fixed parts of a randomly generated level map
I'm coding from scratch a small experimental game on a medium-sized random rectangular square tile map. (Say, a map of a dungeon.)

There are several types of tiles (for example: floor, wall, monster, boss, treasure, player etc.). There are no extra information stored in the map tiles, just tile type.

Most parts of map are randomly generated. However there are several features that are to appear on every generated map in pre-set places. Say, walls around the dungeon, boss locations, player spawn point and the treasure.

*Note: Since the game is small, coded for fun, and the only game designer is a programmer (that is, me myself), I do not plan to spend resources on coding a level editor or supporting an existing one. Also, I do not plan to support existing tile map libraries as I want to dig into some of the related coding problems myself (see above about fun), but I be happy happily to look at relevant existing code as a reference.*

When I look at my map generation code, I find it rather ugly.

Is there an elegant way to deal with the problem? If that matters, I'm writing this game in JavaScript, but I will be happy to see a relevant reference in any programming language.

Here is a partial pseudocode to illustrate how my current tile generator solution looks like:

```
this.init = function(w, h) {
  this.w = w;
  this.h = h;
  this.tile_presets_ = { };

  var mid_h = Math.floor(h / 2);
  var quarter_w = Math.floor(w / 4);

  /* Here is the part I don't like -- a set of generator rules: */

  this.preset_col_(0, Tile.GRASS);
  this.preset_tile_(0, mid_h, Tile.FLOOR);

  this.preset_col_(1, Tile.GRASS);
  this.preset_tile_(1, mid_h, Tile.FLOOR);

  this.preset_col_(2, Tile.WALL);
  this.preset_tile_(2, mid_h, Tile.FLOOR);

  this.preset_tile_(2, mid_h, Tile.PLAYER);

  this.preset_tile_(1 * quarter_w, mid_h, Tile.BOSS);

  this.preset_tile_(2 * quarter_w, mid_h, Tile.BOSS);

  this.preset_tile_(3 * quarter_w, mid_h_, Tile.TREASURE);

  this.preset_col_(w - 1, Tile.WALL);
};

```

Implementation details that may help to understand the code above:

```
this.tile = function(x, y) {
  var preset = this.tile_presets_[x + y * this.w];
  if (preset !== undefined) {
    return preset;
  }

  return this.random_tile_();
};

this.preset_tile_ = function(x, y, tile) {
  this.tile_presets_[x + y * this.w] = tile;
};

this.preset_col_ = function(x, tile) {
  for (var y = 0; y < this.h; ++y) {
    this.preset_tile_(x, y, tile);
  }
};

```

Note that I shown a rather simple set of generator rules above. Actual thing is several times longer.

I hate that the code looks imperative — and it is hard to figure out what is going on from the first glance. I think that declarative approach could help. But so far I can't figure out a good solution.

Any clues?

# Answer
I've created several similar dungeon-based games and I've always used a string-based representation for the map, where a different character represents each tile, e.g:

```
var map = [
    "##########",
    "#........#",
    "#..>.....#",
    "#........+",
    "#........#",
    "##########"
];

```

In my opinion, this gives a great visual representation and allows you to use a regular text editor as "tile editor". This character representation is used for generating the actual level data, if you e.g. need coloring, graphical tiles or as I've done, a 3D dungeon mesh.

As for the handling of preset sections, just create similar character representations for each of them and in your generator, loop through them and put them into correct locations in the big dungeon map. Here's some pseudo JavaScript for one possible approach:

```
var map = /* stuff */ // Here's the dungeon map without preset stuff
var presets = [
    { x: 2, y: 5, map: [ "()]" ] },
    /* More map fragments with positions */
];
for (var i = 0; i < presets.length; ++i) {
    for (var j = 0; j < presets[i].map.length; ++j) {
        /* Figure out coordinates based on presets[i].x/y and j */
        var x = , y = ;
        map[y][x] = presets[i].map[j];
    }
}
/* Now the presets are part of the main map
   and you can process the map into final representation if needed */

```

EDIT:

I seem to have thought this a bit too high level (as in preset rooms instead of preset walls as you mentioned). However, you could change the preset x and y to be relative to the map size, e.g. x=0.333 would be 1/3 of map width (the loop would multiply x by the width). Null could mean "repeat the pattern through the dimension". Thus the preset for your lava-column example in the comment would be `{ x:0.333, y:null, map:"L" }`.

However, this is rather limited and getting a little complex. For such components as straight, varying size wall sections you are eventually going to have a loop that creates it. The easiest way is to call a function as you did, but if that looks ugly, you can use data-oriented approach as I outlined.

One wild idea I just came up would be to create a small hand-made prototype map which would have all the bosses and treasures in their relative positions, but during the map generation you would multiply all their positions with the actual map dimensions (i.e. you kind of magnify the map, but keep the preset features as one tile. With some constraints, this could be expanded to walls too (if the proto map has adjacent wall tiles, the gaps are filled during expansion in that dimension, but not in the dimension where there is no neighbouring wall). Below is an illustration with only horizontal expansion (S and E are just some preset tiles you want to place relatively but don't want to use explicit function calls).

```
#####         #############
#S# #         #  S  #     #
# # #   ==>   #     #     #
# #E#         #     #  E  #
#####         #############

```

In the end I think the best way to make the generator feel nice, is to structure it with high-level functions as ashes999 suggested.
> 4 votes

# Answer
If you're not going to invest in a level editor, the only thing left is to invest in the level generation algorithm. This is generally how any randomly-generated game (like a roguelike) will work out.

What you may want to do is extract things out into high-level functions so you can tweak the generation, eg.

```
function createaMap() {
  setDefaultFloorTo(grass);
  generateBorderWalls;
  placeBossInCenter();
  placeSpawnPoint();
  // ...
}

```

This will help you stay organized and tweak the order of generation if you need to (eg. spawn point first, then boss, or vice-versa).

With respect to fixed items, you should probably place those *first,* and then generate everything else around them.

Also, as mentioned in Tapio's answer, you may want to dump the final map out to a file in some format that you can easily review to see what the final dungeon looks like.
> 1 votes

---
Tags: software-engineering, tilemap, random
---


title: How do I prototype an online game?

text:
# Question
Title: How do I prototype an online game?
I would like to know if you guys know of any libraries, engines, or even simply design patterns that heavily simplify the task of sharing information and sending of messages between networked programs, so one can focus on tweaking gameplay instead of rewriting networking code, while prototyping networked games. Since this is meant for prototypes, ease of use and flexibility is much more important than speed and security.

# Answer
The easiest way to prototype an online game, which allows you to quickly change almost anything in the game (even factors such as real-time vs. turn-based), is to implement the prototype as a physical game. Get all the designers together in a room, get a bunch of cards, or dice, or board game components, or whatever is necessary to prototype the general game interactions. Then play the game.

You can do this without needing to pay programmers or artists. Trying different variations of game rules takes only a minute or two instead of requiring hours or days (or weeks!) of programming work, and you can know whether or not your game works by actually playing it, instead of having to design ahead of the implementation and make guesses about what will or won't work. Plus, your programmers will still like you at the end of the process. :)

* When doing this, I recommend having at least one person acting as an observer; not taking part in the game itself, and another person whose job is to keep notes about who did what and when. That data about what actually happened during each game can become tremendously useful while adjusting the rule set between games.

Pen, paper, dice, cards, boards, tokens. That's really all you need. And for prototyping a game design, it's better than anything else.
> 4 votes

# Answer
`relatively simple rule changes such as "let's try this in real time instead of turn-based"` That sounds like a pretty fundamental change to me, not a simple rule change. I think fundamental design choices like that should be made before you even get to writing any networking code, either with offline prototypes or even paper prototypes.

That is, prototype the gameplay without doing any networking. That would mean writing a game that is multiplayer locally (ie. both players are on the same computer) in order to test gameplay ideas.

I mean, at my job we once took a game that was already halfway developed turn-based and converted it to real-time, and yeah that involved a massive rewrite of the networking code. In retrospect, that was a really inefficient way to approach things, and we pretty much decided "never again."
> 2 votes

# Answer
I can't imagine a need for such a tool because I believe network logic is best done through a solid analysis of what information needs to go where.

But, if I were forced to create such a thing for someone who wanted one, I would use:

* the Python programming language
* 0MQ for messaging (via pyzmq)
* the pickle module to send arbitrary data (as given in an example here)

This covers all the problems of reliable transport, message delineation, and serialisation/deserialisation. (Pickle is not safe for anything other than intranet use however.)

You will still need to set up the logic to decide what to do with the data, make and implement the decision of which computers connect to which other computers, and so on. And it doesn't support unreliable messaging, or remote procedure calls, or automatic state replication, etc etc. That's why it's usually better just to plan out what you want and write it that way.
> 0 votes

---
Tags: networking, prototyping
---


title: Playing Video In MonoGame

text:
# Question
Title: Playing Video In MonoGame
I'm trying to play a video in a monogame project. I've done this in XNA in the past by including the Framework.Video directory and it's very simple. This cannot be done in monogame as Visual Studio 2012 wont accept the XNA directories.

I've not been able to find any other way explained anywhere if you can actually put video in monogame yer and if you can how it's done.

Any ideas?

# Answer
The Mono Framework seems to implement a media player via the windows media player. https://github.com/mono/MonoGame/blob/develop3d/MonoGame.Framework/Media/MediaPlayer.cs
> 3 votes

---
Tags: xna, monogame, video
---


title: Hide original video file in XNA game

text:
# Question
Title: Hide original video file in XNA game
I want to play some videos in my XNA game. I have looked at this tutorial. I have tried it. It creates XNB file but also copies original WMV file into output content directory.

Is there some simple solution, how can I pack/hide original WMV file? I don't want user get it.

Thanks for any help.

# Answer
The XNA video player component is very much an opaque box that only plays loose WMV files. You can't really pack the file.

All that the XNB file contains is a filename that points to that WMV file (plus some metadata for the `Video` object).

The content processor (`VideoProcessor`) is responsible for copying the WMV file along side the XNB file at build time.

You could perhaps just give it a sneaky extension (eg: "myVideo.dat") to hide it from end users. Unfortunately the provided content processor automatically renames file to give it a WMV extension - so you'd have to provide a replacement processor.

(Or just stick the video in a directory. Is it so bad if inquisitive users find it?)
> 6 votes

# Answer
I think when it comes down to it, short of writing your own codec or something, if a user wants to view the videos, they'll do it. For the most part though, I don't think "regular" players will be mucking about in the game's install directory.

If this is a single player game and they player chooses to ruin it for themselves by watching the video early, then so be it. It's their game, they paid for it.

If it's multiplayer, then maybe they'll be able to see something before they get there, but then, they could just ask a player who's already been there. This actually goes for single player too.

So, I'd say don't worry about it. Just make a great game that they'll want to keep playing to see the new videos.
> 2 votes

# Answer
Stream your video instead. This will then only require "hiding" the video URL, although it won't work if your players are offline.

I've seen this pulled off in Flash games. When you reach certain progress points, they pull a (YouTube) video off the web and stream it in-game, and life is good. Again, players were pretty much guaranteed to have internet connectivity at that time.

I'm not 100% sure if you can pull this off in XNA and MonoGame though. I'm pretty sure XNA supports streamed video.
> 0 votes

---
Tags: xna, video
---


title: How can I draw a texture line by line

text:
# Question
Title: How can I draw a texture line by line
I wish to draw a texture to the screen line by line (horizontal lines). Can I do this in xna?

At first I wish to just start at the top of the texture, draw one single horizontal line of pixels and x no of milliseconds later draw the next line and so on until the texture is fully drawn. In the future I may want to draw these horizontal lines in any order.

Any ideas how best to achieve this?

# Answer
You can just specify how much of the image you want to draw in the spriteBatch.Draw() method, like so: (Variable declaration is only for self-documentation)

```
height = Math.Max(height + 1, 500);
Rectangle destinationRect = new Rectangle(0, 0, 500, height);
Rectangle sourceRect = new Rectangle(0, 0, 500, height);
spriteBatch.Draw(my500x500Texture, destinationRect, sourceRect, Color.White);

```

All this does is draw one more pixel of the background texture every call until it reaches the full height of the image (500 in the example). Note that render speeds will be different on different machines, so you will likely want to base the draw height on the gametime to be more consistent.

To draw random one-line segments of the image, I would use one draw statement per line and draw each line like so:

```
lineY = 42;  // Figure this part out yourself, and loop this somehow
Rectangle destinationRect = new Rectangle(0, 0 + lineY, 500, 1);  // Drawing at (0,0)
Rectangle sourceRect = new Rectangle(0, lineY, 500, 1);
spriteBatch.Draw(my500x500Texture, destinationRect, sourceRect, Color.White);

```
> 4 votes

# Answer
use Texture2D.getData() to extract the colors array

then use this array to create a new Texture and add a pixel on each time increment

you should be able to modify the below to your need

```
var texture = new Content.Load<Texture2D>("file");
var colors = texture.GetData();

var colorsNew = new Color[texture.Width * texture.Height];

colorsNew[0] = colors[0]
texture.SetData(colorsNew);

//DRAW texture

//nextUpdate

colorsNew[1] = colors[1]
texture.SetData(colorsNew);

//DRAW texture

```

note this is untested and you may need to alter the order in which colorsNew is filled, but this should basically do what you require
> 0 votes

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


# Question
Title: How can I switch between DirectX and OpenGL renderer in my engine?
I am currently developing my engine with DirectX, but I want to make it cross-platform in the future, using OpenGL.

How can I check which platform my engine is running on? And can I use an if statement after I've checked the platform to say which renderer to use?

I currently have an abstract renderer and a DirectX9 renderer as it's child.

# Answer
> 7 votes
Advice: Don't do this. It is a complete waste of time. You will have to rewrite your engine after the 1st time doing this. If you're just starting out in graphics development, wasting time with low level API functionality equivalences is *not going to teach you much*, it's just going to be very tedious work.

That said, if you have to, then design a bunch of abstract interfaces to interact with a graphics API. THen write concrete classes underneath that, that actually interact with the specific API chosen.

Examples are: abstract classes for `GraphicsWindow`, `VertexBuffer`, `Surface` (frame buffer in OpenGL, surface in D3D). You then write concrete implementation classes `D3DWindow : public GraphicsWindow`, `OpenGLWindow : public GraphicsWindow`.

Example of a method: In `GraphicsWindow` you would provide a pure virtual method `void flipBuffer()=0`. Implementation would be different for OGL and D3D, and the implementation code would be in their respective classes.

---
Tags: opengl, directx
---


# Question
Title: deferred rendering and a few shading functions
How to use a few shading functions together with deferred rendering (for example some objects are shaded based on a lighting equation, other get a fixed color) ? I draw a full screen quad when shading (later I want to add optimizations for point lights). I have some idea how to solve that problem: during a gbuffer stage a shading function id should be saved in one of the render targets. Then we can do something like this:

```
if(id == 0)
{
    fragColor = shadingFun0(...);
}
else
{
    fragColor = shadingFun1(...);
}

```

What do you think about that ?

# Answer
> 3 votes
I believe having a lot of ifs in a fragment shader could have a serious performance impact. You could probably use the stencil buffer for this purpose.

Or save up to 4 light types in the color channels of a separate rendertarget and do this: fragColor = shadingFun0(...) * texColor.r + shadingFun1(...) * texColor.b and so on.

Or as a hack, you can manipulate the normals of some objects, so the light equation returns a different color.

Or just do multiple passes, one for each light type. So one deferred shading pass, and then you just draw the other objects on the resulting FBO (keeping the depth buffer, I guess).

Also I'm not sure about this, but isn't the whole point of using deferred shading that you can use the best lighting model for everything?

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


title: haxe level scrolling

text:
# Question
Title: haxe level scrolling
How would level scrolling be implemented with haxe and nme?

I started plying with haxe and currently the only way to display things on screen is by using `nme.display.Sprite`.

I don't think changing the position of all sprites to scroll the level is the most efficient way of doing things.

I can't find any comprehensive example of how this should be done with haxe.

Any pointers?

# Answer
> 3 votes
Basically you want to have a "camera" concept to show exactly what you want in your game. In this case the camera may follow your hero, so that it tries to keep the hero centered on the screen as much as possible (similar to how the original super mario bros. game worked).

In order to do so you would add all of your sprites to a parent sprite so your display hierarchy looks like this:

* Stage
    + Game Container
        - Game Sprites

So now your "camera" is in the Game Container layer and you simply use scrollRect() to show exactly what you want. The scrolling parts come into play by having your scrollRect() follow the hero. You could do this with a listener or just a function call, something like:

```
var oldHeroXPos = hero.x;
var oldHeroYPos = hero.y;

//move your hero in game
hero.moveTo(newHeroXPos,newHeroYPos);

//make the camera follow the hero..i.e. move same amount as the hero
camera.moveOffset(newHeroXPos-oldHeroXPos,newHeroYPos-oldHeroYPos);

```

The camera.moveOffset() function would look something like this:

```
public function moveOffset(inXDiff:Float,inYDiff:Float):Void
{
    gameContainer.scrollRect.x += inXDiff;
    gameContainer.scrollRect.y += inYDiff;
}

```

After you get this working you will have an issue where scrolling isn't smooth, so you will have to do additional work to change the camera position over time...maybe give it some elasticity to make it look nicer.

Note if you use a game engine such as flixel, or awe6 that this type of thing is already taken care of for you, and unless you are interested in learning exactly what it takes to implement a smooth camera I always suggest using a tried and true game library to help get your game out quicker, but the end goals are up to you.

Keep in mind that whatever game logic you use to move your enemies would apply regardless of the camera, and you would probably want a slightly larger box (bigger than the camera) that would be used to indicate if the game entity was "alive" i.e. needs its AI run. If you did something like this then you could have enemies walk into your screen even if the hero stands still (camera not moving).

# drawTiles

Instead of using the build in `nme.display.Sprite` class you can roll your own game entities and render with `drawTiles()`.

In `drawTiles()` you will optimally have only one layer for game content, so that you only need to call `drawTiles()` once per frame. In order to do this you need to build up a class that has everything you need in it (ex: `GameEntity`). `nme.display.Sprite` has x/y, width/height, rotation, scale, graphics, etc and you will need to replicate all of that in your `GameEntity` class. Handling the graphics yourself is the major hurdle since you will need to plan out how you layout your graphics before you load a level in your game (using a Tilesheet).

**Note:** The libraries Tilelayer or gm2d (look in the blit folder) handle the drawTiles() abstraction nicely. TileLayer uses `TileSprite` to replace `nme.display.Sprite`, while gm2d uses `Tile` for the `nme.display.Sprite` functionality

Your main game loop would something like this:

```
class GameMain
{
    public var renderArray:Array<Float>;
    public var gameEntities:Array<GameEntity>;

    public function new():Void
    {
         renderArray = new Array<Float>();
         gameEntities = new Array<GameEntity>();
         //Here we update all game entities and then render
         Lib.current.stage.addEventListener(Event.ENTER_FRAME,onUpdate);
    }

    private function onUpdate(inEvent:Event):Void
    {
        //Reset render array...see TileLayer for most efficient way to handle
        renderArray = [];

        for (entity in _gameEntities)
        {
            entity.update(); //update x,y position
        }

        //we now have all the graphics at the correct positions...one batch render!
        Lib.current.stage.graphics.drawTiles(renderArray);
    }
}

```

You game entity would look something like this (only x/y and graphics shown for simplicity):

```
class GameEntity
{
    //drawTiles tile ID
    private var _tileID:Int;
    private var _x:Float;
    private var _y:Float;
    private var _gameMain:GameMain;

    public function new (inTileId:Int,inGameMain:GameMain):Void
    {
        //get ref to main game so we can update render array
        _gameMain = inGameMain;

        //This is the graphic we show every frame
        _tileID = inTileId;

        _x = _y = 0.0;

    }

    //Call me on each ENTER_FRAME event!
    public function update():Void
    {
         //Assign arbitrary values to x and y
        _x = Std.random(100);
        _y = Std.random(100);

        //Update render array with this entities information
        //order for drawTiles() is id,x,y,...etc
        _gameMain.renderArray.push(_tileID);
        _gameMain.renderArray.push(_x);
        _gameMain.renderArray.push(_y);
    }
}

```

At this point the code still won't work, and that's because the tileID is meaningless at this point...i.e. what does the tileID refer to? It needs to represent something inside of a `nme.display.Tilesheet`. A tilesheet is just a large image made up of smaller images...that's it. Each small image occupies some space in the large image and that "occupied space" is what the tileID represents.

Example:

* tileID=0 represents the image at x=0,y=0,width=100,height=100
* tileID=1 represents the image at x=101,y=0,width=300,height=100

So now you need to setup your tilesheet...and with that you could use a tool like texturepacker that will generate a large image (from many small .pngs,.jpgs,etc) and will ALSO generate rectangle data...and that rectangle data correlates 1:1 with the tile IDs. The TileLayer library is already setup to read in texturepacker sparrow output so all you have to do is open the tool drop in some images and export the .png and .xml file and then TileLayer will autocreate your tilesheet data.

If you want to roll your own solution you can just create a blank bitmap (i.e. `new BitmapData(2048,2048)`) and then start adding smaller `BitmapData` to the larger image and track the rectangles yourself...but then you need an algorithim on how you are going to stack the rectangles..i.e. a binning or packing algorithim like repack or the algorithim I added for gm2d use here.

So as you can see your todo list grows very quickly...I highly recommend TileLayer and Texturepacker if you want to use drawTiles() Tilelayer is efficient, well written, well commented, and should have you up and running 100x quicker then rolling your own solution.

---
Tags: sprites, rendering, side-scroller, haxe
---


# Question
Title: Dealing with field of view when zooming into a terrain from a height
I'm creating a tech demo featuring a small planet. The problem I'm having is that the planet doesn't really feel like the right "scale" when the camera in down on the surface, I think it could be the curvature of the surface of the planet.

I was wondering if anyone had any suggestions for adjusting maybe the field of view, or any other camera tricks to give the impression that, once on the surface, the planet is larger than it appears at the moment.

# Answer
> 0 votes
> feel like the right "scale" when the camera in down on the surface,

The 2nd image makes it seem like the camera is positioned about 1/4 planet diameter (or so) above the surface, which affects how everything looks. Is the camera really "on the surface"? The closer the camera is to the surface of the planet, the bigger the planet will seem and the flatter the horizon will be.

---
Tags: camera, graphics-programming
---


title: Ball bouncing infinitely and constantly

text:
# Question
Title: Ball bouncing infinitely and constantly
Alright, so I've got hold of some simple physics mechanics, and am currently trying to implement bouncing. Based on the first answer of this question, I've developed the following algorithm:

```
    Vector2 velocity;

    float gravity;
    float elasticity;

    Hitbox dummy;

    // ---

    void bounce() {
        dummy.MoveY(velocity.Y);
        velocity.Y += gravity;

        if (dummy.ThereWasContact.South) velocity.Y *= -elasticity;
    }

```

Gravity can be any value, and Elasticity is always between `0.0f` and `1.0f`. Velocity.Y's initial value can also be anything.

Weight factors aside, which would determine a minimal rebound force for the object to be able to leave the ground again and (probably) aren't related to the problem, this is apparently fallacious.

What happens here is somewhat like this:

If I drop an object from a height of 128 units, for example, 0u marking ground height, with a gravity of 1u and elasticity of 0.9, the object would bounce once, reach a maximum height of ~126u from the rebound, and from then on keep alternating on maximum heights between this and ~122u.

This example is based on one of my own experiments, in which I drop an object from a height of 64 pixels and there is a floor at 192 pixels. The maximum height will keep going from ~66 pixels to ~70.

What am I missing? Does weight after all do more than I think? If I need to explain something better or details appear to be missing, let me know.

# Answer
> 3 votes
Whenever the ball hit the ground, first you add gravity, then you invert the direction, thus the ball is going to spring back with greater speed. Let's step through a case where elasticity is 1, gravity is 1 and the ball's initial speed is 10:

1. The ball moves 10 and hit the ground.
2. The speed is increased to 11.
3. The ball's speed is changed to -11.

Next update:

1. The ball moves -11.
2. The speed is decreased to -10.

So the ball impacted the ground with speed 10 and left with speed -11, next time it hit the ground it will be at speed 11, and it will leave at speed -12 etc.

A very simple fix is to split gravity application into two, half before collision detection and half after.

### The future

Your next error will be that the ball get stuck in the ground. This happens because you let the ball pass into the ground before registering a collision, and sometimes the ball will have lost so much speed that the following move doesn't take it out of the ground, so your collision detection invert its direction again. The easy fix is to check that the ball is actually moving towards the object that it is colliding with before inverting the direction.

# Answer
> 5 votes
Your 'elasticity' should be removing energy from the system so that it settles down. The first thing that comes to mind given that that isn't working, and that you mention measuring in pixels, is: make sure that your velocity is floating-point, not an integer.

If that isn't the problem, then the first thing I would do to debug is calculate the energy (ignoring mass) of the ball: `pow(velocity.Length(), 2) + position.Y * gravity`. If your units are right and your simulation is good, this should slowly decrease with each bounce. If it doesn't, then the bounce is a problem. If it increases continuously while not bouncing, then your basic simulation step is wrong.

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