# Question
Title: Rotating and Translating a Node in Horde3D with Matrices and Quaternions
I have been trying to learn how to use the `Horde3D` rendering engine for the past couple of days, and so far I have managed to learn a decent amount and integrate `Bullet Physics` with it as well.

My problem is in my maths for rotating and translating a node in `Horde3D` to keep it in sync with `Bullet Physics`.

I have a terrain and a sphere, both of which are in the `Bullet Physics` dynamics world. The sphere drops from the sky and hits the terrain and everything works fine and collides/moves around as it is supposed to.

The problem is that I can successfully translate the 3D model in `Horde3D` to stay in sync with the position of the sphere shape in `Bullet Physics`, but as soon as I try to introduce rotation things start to go wrong.

It's a bit difficult to describe so I have uploaded a video of the problem to YouTube (below). Basically, the green wireframe is the `Bullet Physics` sphere shape, and the brown sphere is the sphere at the `Horde3D` node.

Everything is fine while the sphere is falling, because there is no rotation, but as soon as it hits the terrain and rotation is supposed to take place the `Horde3D` node moves in a completely different direction to the `Bullet Physics` wireframe.

You can see what I mean by watching the video here: http://www.youtube.com/watch?v=Yi\_DJIWpxOo&feature=youtu.be

I assume this is probably a quaternion/multiplication/matrix/order of multiplication error of some kind, but I can't figure it out myself.

`Horde3D` provides two ways that I know of to set a node's position.

They are:

```
h3dSetNodeTransform (http://www.horde3d.org/docs/html/_api.html#h3dSetNodeTransform)
h3dSetNodeTransMat (http://www.horde3d.org/docs/html/_api.html#h3dSetNodeTransMat)

```

I could use `h3dSetNodeTransform` and set all of the Euler angles, but `Bullet Physics` provides a quaternion, so I would rather try and use translation and rotation matrices instead of converting the quaternion to Euler angles etc.

For calculations I am using `GLM`, if that makes any difference, although I don't think it should do.

The code that handles the updating of the Horde3D node is as follows:

```
btTransform trans;

sphere_body->getMotionState()->getWorldTransform(trans);

// getOrigin() returns the absolute coordinates, so I am keeping
// track of them to make sure I translate the correct amount
glm::vec3 sphere_cur_pos = glm::vec3(
    trans.getOrigin().getX(),
    trans.getOrigin().getY(),
    trans.getOrigin().getZ()
);

glm::mat4 sphere_node_matrix, matrix_t, matrix_r;

const float *matrix_floats;
h3dGetNodeTransMats(sphere_node, 0, &matrix_floats);

sphere_node_matrix = glm::make_mat4(matrix_floats);

matrix_t = glm::translate(
    sphere_node_matrix,
    sphere_cur_pos - sphere_last_pos
);

// sphere_last_pos is declared earlier in the code
sphere_last_pos = sphere_cur_pos;

btQuaternion quat = trans.getRotation();

matrix_r = glm::rotate(
    matrix_t,
    quat.getAngle(),
    glm::vec3(quat.getAxis().getX(), quat.getAxis().getY(), quat.getAxis().getZ())
);

h3dSetNodeTransMat(sphere_node, glm::value_ptr(matrix_r));

```

The above code produces the behaviour you can see in the YouTube video.

If I remove the rotation matrix and just use:

```
h3dSetNodeTransMat(sphere_node, glm::value_ptr(matrix_t));

```

then everything works fine and the sphere node stays in sync with the `Bullet Physics` wireframe, but there is of course then, there is no rotation.

Can somebody point out what I am doing wrong?

If any more information is needed just let me know and I will update the question.

# Answer
I managed to fix everything through a lot of experimenting.

It seems my problem came from my own misunderstanding of quaternions.

I was under the impression that they represented a change in angle, when actually they represent an orientation.

So my rotation matrix was always a bit strange because I was just pushing seemingly random values into it, directly from the quaternion provided by `Bullet Physics`.

I now understand that I should properly convert the quaternion to a matrix, and that would be my final rotation matrix with no further changes.

In GLM it seems that if you include:

```
#include <glm/gtx/quaternion.hpp>

```

you get given functions like `glm::angleAxis` which can create a quaternion in GLM from an angle and a vector. And `glm::toMat4` which can do things like converting quaternions to matrices for you.

By default `glm::angleAxis` takes an angle in degrees not radians, so you have to do the conversion, so that's the only thing you really have to remember to do.

Anyway, here is the working code:

```
dynamics_world->stepSimulation(delta_time, 10);

btTransform sphere_transform;
sphere_body->getMotionState()->getWorldTransform(sphere_transform);

// Create a copy of the Bullet Physics world position in GLM
glm::vec3 sphere_world_position = glm::vec3(
    sphere_transform.getOrigin().getX(),
    sphere_transform.getOrigin().getY(),
    sphere_transform.getOrigin().getZ()
);

// Create a copy of the Bullet Physics quaternion in GLM
btQuaternion sphere_bullet_orientation = sphere_transform.getRotation();

glm::quat sphere_horde3d_orientation = glm::angleAxis(
    sphere_bullet_orientation.getAngle() * 180 / PI,
    glm::vec3(
        sphere_bullet_orientation.getAxis().getX(),
        sphere_bullet_orientation.getAxis().getY(),
        sphere_bullet_orientation.getAxis().getZ()
));

// Create a new identity translation matrix and
// use the quaternion copy to get a rotation matrix
glm::mat4 translation_matrix = glm::mat4(1.f);
glm::mat4 rotation_matrix = glm::toMat4(sphere_horde3d_orientation);

// Translate using the world position vector
translation_matrix = glm::translate(translation_matrix, sphere_world_position);

// Create the final matrix
glm::mat4 transform_matrix = translation_matrix * rotation_matrix;

h3dSetNodeTransMat(sphere_node, glm::value_ptr(transform_matrix));

```
> 1 votes

---
Tags: c++, 3d, matrix, quaternion, glm
---


# Question
Title: OpenGL noob: Using VBO to draw a colored triangle
I tried using straight vertex arrays to draw a triangle with different colors for each vertex and it works fine, but when I use VBO it won't work, so I'm doing something wrong.

```
// point 1
side_1.push_back(-2.0f); //x1
side_1.push_back(-2.0f); //y1
side_1.push_back(0.0f); //z1

// side color
side_color_1.push_back(0.8f); //r1
side_color_1.push_back(0.0f); //g1
side_color_1.push_back(1.0f); //b1

// point 2
side_1.push_back(2.0f); //x2
side_1.push_back(-2.0f); //y2
side_1.push_back(0.0f); //z2

...etc

// init code
////////////
glGenBuffers(2, &m_vertexBuffer[0]); //Generate a buffer for the vertices

glBindBuffer(GL_ARRAY_BUFFER, m_vertexBuffer[0]); //Bind the vertex buffer
glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * side_1.size(),
                 &side_1[0], GL_STATIC_DRAW); //Send the data to OpenGL

glBindBuffer(GL_ARRAY_BUFFER, m_vertexBuffer[1]); //Bind the vertex buffer
glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * side_color_1.size(),
                 &side_color_1[0], GL_STATIC_DRAW); //Send the data to OpenGL

// render code
////////////
glEnableClientState(GL_VERTEX_ARRAY);   // enable vertex array
glEnableClientState(GL_COLOR_ARRAY);    // enable color array

// bind the buffer to the VBO
glBindBuffer(GL_ARRAY_BUFFER, m_vertexBuffer[0]);
glBindBuffer(GL_ARRAY_BUFFER, m_vertexBuffer[1]);

glVertexPointer(3, GL_FLOAT, 0, 0);
glColorPointer(3, GL_FLOAT, 0, BUFFER_OFFSET(sizeof(GLfloat) * side_1.size()));

glDrawArrays(GL_TRIANGLES, 0, 3);

glDisableClientState(GL_COLOR_ARRAY);
glDisableClientState(GL_VERTEX_ARRAY);

```

# Answer
> 4 votes
You are currently putting the position data into one VBO (`vertexBuffer[0]`) and the color data into another one (`vertexBuffer[1]`). But when drawing you bind both buffers one after the other, so the second binding will just override the previous one. Then you set the pointers as if both attributes were in the same buffer. This is slightly messed up. The `gl...Pointer` calls always use the VBO that is currently bound (the one last called with `glBindBuffer(GL_ARRAY_BUFFER, ...)`).

If you want to draw from your two buffers, you have to first bind the first buffer and tell OpenGL to find the position data at offset `0` of the currently bound buffer:

```
glBindBuffer(GL_ARRAY_BUFFER, m_vertexBuffer[0]);
glVertexPointer(3, GL_FLOAT, 0, 0);

```

*Then* you bind the second buffer and again tell the GL to take the color data from offset `0` of this buffer.

```
glBindBuffer(GL_ARRAY_BUFFER, m_vertexBuffer[1]);
glColorPointer(3, GL_FLOAT, 0, 0);

```

---

If you on the other hand really want to source both attributes from the same buffer, using the offset to reference sub-regions of it, then you would have to create a single buffer only, filling it's sub-regions with the corrsesponding data:

```
// init code
////////////
glGenBuffers(1, &m_vertexBuffer); //Generate a buffer for the vertices

glBindBuffer(GL_ARRAY_BUFFER, m_vertexBuffer); //Bind the vertex buffer
glBufferData(GL_ARRAY_BUFFER,
             sizeof(GLfloat) * (side_1.size()+side_color_1.size(), //large enough for both
             nullptr, GL_STATIC_DRAW);         //No data yet, just allocate

//fill sub-regions with corresponding data
glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(GLfloat)*side_1.size(), side_1.data());
glBufferSubData(GL_ARRAY_BUFFER, sizeof(GLfloat)*side_1.size(),
                sizeof(GLfloat)*side_color_1.size(), side_color_1.data());

// render code
////////////
// bind the buffer to the VBO
glBindBuffer(GL_ARRAY_BUFFER, m_vertexBuffer);

glVertexPointer(3, GL_FLOAT, 0, 0);
glColorPointer(3, GL_FLOAT, 0, BUFFER_OFFSET(sizeof(GLfloat) * side_1.size()));

```

---
Tags: opengl, vbo
---


title: How to disable mipmapping?

text:
# Question
Title: How to disable mipmapping?
I'm making a 2D game in which I create some textures dynamically for displaying as simple 2D quads. To achieve this, I call `ID3D11Device::CreateTexture2D` that requires a `D3D11_TEXTURE2D_DESC`.

```
typedef struct D3D11_TEXTURE2D_DESC {
  UINT             Width;
  UINT             Height;
  UINT             MipLevels;
  UINT             ArraySize;
  DXGI_FORMAT      Format;
  DXGI_SAMPLE_DESC SampleDesc;
  D3D11_USAGE      Usage;
  UINT             BindFlags;
  UINT             CPUAccessFlags;
  UINT             MiscFlags;
} D3D11_TEXTURE2D_DESC;

```

One of the fields is MipLevels. What I understand about this is that mipmaps consist of a collection of the same texture downscaled for better representation and performance of them when they are far away from the view camera.

Since what I'm making is a 2D game, I don't need this feature and I want to disable it. Is there any way to do so? At first, I thought I could just set miplevels parameter to 0, but then I read this:

> MipLevels Type: UINT The maximum number of mipmap levels in the texture. See the remarks in D3D11\_TEX1D\_SRV. Use 1 for a multisampled texture; or 0 to generate a full set of subtextures.

and:

> pInitialData \[in\] Type: const D3D11\_SUBRESOURCE\_DATA\* A pointer to an array of D3D11\_SUBRESOURCE\_DATA structures that describe subresources for the 2D texture resource. Applications cannot specify NULL for pInitialData when creating IMMUTABLE resources (see D3D11\_USAGE). If the resource is multisampled, pInitialData must be NULL because multisampled resources cannot be initialized with data when they are created.

This is what confuses me. I want to create an IMMUTABLE 2D texture (once it's dynamically generated at runtime it's not going to change anymore) plus I don't want any mipmap levels. How am I supposed to do this?

# Answer
> 1 votes
If you set your MiPLevels to 1, and ArraySize to 1, it will just have one miplevel. thats all you do to it. beacuse you cannot simply "disable" mipmaping, since it´s a part of the GPU pipeline.

---
Tags: directx11, mipmaps
---


title: Game mechanics based on similar game

text:
# Question
Title: Game mechanics based on similar game
I want to make an iOs game that is based on an online flash game. There will be quite some differences, but the game mechanics will be extremely similar. Do I have to worry about getting sued by the company that made the flash game??? I think not , after all DOOM is similar to Quake but they didn't get sued as far as I know. Has anybody had any similar problems? (getting sued for making a game with very similar game mechanics)

# Answer
Not at all. Just don't use the names that are a TM and you are good.
> 1 votes

---
Tags: game-mechanics, copyright
---


# Question
Title: Separation algorithm in flock simulation?
I'm using box2d (the c++ one).

I found a method for an arriving behavior (on http://www.red3d.com/cwr/steer/gdc99/ ), which works well, problem is, the bodies are bumping into each other and it results in an ugly shaking effect.

How do you make sure bodies keep away from each other after I applied the arriving behavior ? Or the other way around ?

I'm wondering if it might be a better idea to completely remove the arriving behavior to implement the separate algorithm.

edit: even setting a low restitution results in shaking

# Answer
> 3 votes
Each body finds the bodies closest to it. It then attempts to steer away from the sum of the neighbors. The closer a neighbor is, the more it adds to the repel force.

If each body does this, they will spread out away from each other. This combined with a cohesion algorithm keeps the bodies grouped, but not on top of each other.

Both of these are covered in the link you shared.

---
Tags: c++, physics, box2d
---


# Question
Title: How can I update Display settings from an Options screen without restarting?
I'm currently creating a 2D RPG in C++11 with Allegro 5 and boost.

My goal is to somehow update my game settings when an option is changed in the Options Menu. I don't want to force the user to restart my game. Other games don't require a restart when changing resolution or going from fullscreen to windowed, so my game shouldn't either. Please see a simplified view of the system below.

Please note that I am not necessarily wanting to directly call my Game object from the OptionsScreen. The dashed line is merely to illustrate the effect I am trying to achieve; to somehow cause an update of the game when an option is changed in a different part of the system.

**Detailed explanation**

The ScreenManager contains a list of all `GameScreen` objects currently in existence. These will be various screens in the game including popups. This design adheres more or less to the Game State Management sample in C#/XNA.

The `ScreenManager` contains a reference to my `Game` object. The `Game` object initializes and modifies the game's settings. If I want to change the resolution, go fullscreen, or mute the volume I would do so in the `Game` class.

However, the OptionsScreen currently cannot access the Game class. See below diagram:

A GameScreen can signal three events, `onFinished`, `onTransitionStart` and `onTransitionEnd`. There is no `onOptionsChanged` because only one screen does that. The ScreenManager cannot set-up the event handling for that because it handles all screens as `GameScreen`s.

My question is, how can I change my design so that a change in the OptionsMenu doesn't require a restart, but is changed immediately? I would preferably request my `Game` object to update once the apply button is clicked.

# Answer
> 1 votes
From what I've seen, the easiest approach is read an options file on startup to determine current display settings; then, when your options screen is displayed, load all current options from a file.

When changes are finalized via an `apply` or `ok` button, they are saved back to a file. If any changes effect the display, notify the user that the game must be restarted for them to take effect.

When the game is restarted, the (now new) display settings are again read from the file.

**--EDIT--**

Annd...it would have helped if I noticed that last sentence. You don't want to have to restart. Makes things a little more difficult depending on your implementation and your back-end Graphics Library.

IIRC, Allegro has a function call that allows you to change the display settings on the fly. I'm not up-and-up on Allegro 5 just yet, but I know you could in 4.

# Answer
> 1 votes
This is what I do for my game. I have 2 separate functions for initialising stuff, 'init' and 'reset'. Init is only called once at startup and does things that do not rely on any settings, such as loading main assets. Reset does things like laying out the UI based on screen resolution, so is called every time the settings change.

```
init();
bool quit = false;
while( !quit )
{
    createWindow();
    reset();

    bool settings_changed = false;
    while( !quit && !settings_changed )
    {
        ... main loop
        // set quit=true if user clicks 'quit' in main menu
        // set settings_changed=true if user clicks 'apply' in options
    }

    destroyCurrentWindow();
}

```

I am not familiar with Allegro, but my answer is quite general, so I hope it helps you or anyone else with a similar problem.

# Answer
> 1 votes
Without messing your current architecture, I see two ways. First, you could store a pointer to the `Game` instance in the `OptionsScreen` class. Second, you could the `Game` class fetch current settings in a given interval, say every second.

To actually adapt to the new settings, the `Game` class has to implement some sort of reset functions which fetches the current settings and reinitializes based on those.

For a clean solution you need a global manager of some kind, thus it is more effort to implement. For example a event system or messaging system. It is very useful to let classes communicate without such strong bindings like aggregation or composition, and so on.

With a global event manager, the `OptionsScreen` could simply globally fire a redraw event which `Game` has registered to listen to before.

Generally you can implement a manager class storing events and callbacks listening to them in a hash map. Then you can create a single instance of that manager and pass pointers to it to your components. Using newer C++ it's quite easy since you can use `std::unordered_map` as hash map and `std::function` to store callbacks. There are different approaches what you can use as key. For example, you could make the event manager string based which makes components even more independent. In that case you would use `std::string` as key in the hash map. I personally like this and it is definitely no performance issue, but most traditional event systems work with events as classes.

# Answer
> 1 votes
Well, this is some specific case of the Observer pattern.

There is a solution that involves callbacks. This is the best way of doing this if you want loose coupling, and I think it's also the cleanest one. This won't involve any global managers or singletons.

Basically, you'll need to have some sort of `SettingsStore`. There you store the settings. When you create a new screen they'll need a pointer to the store. In the case of the `OptionsScreen` it will modify some of the settings value itself. In the case of the `GameScreen` it will just read them. So, in your game you would create just one instance, which will be passed along all screens that require one.

Now, that `SettingsStore` class will have a list of `notifiables`. They are classes that implement a certain `ISettingChanged` interface. The interface would be a simple one that contains the following method:

```
void settingChanged(std::string setting);

```

Then in your screen you will implement the logic for each setting you care about. Then, add yourself to the store to be notified: `store->notifyOnChange(this);`. When a setting is changed, the callback is called with the setting name. The new setting value can then be retrieved from the `SettingsStore`.

Now, this can be further augmented with the following ideas:

* Use a class that stores the settings strings - may be even the `SettingsStore` (const strings) in order to prevent copy-pasting strings around.
* Even better, instead of a string, use an enum to specify at what settings you have
* You could even specify the old and new values as arguments in the callback, but that would be more convoluted, since you can have string or int values, or whatnot. It's up to you.

# Answer
> 0 votes
Read your settings from a file into into variables. Have your Screen Manager track if the screen it just came from was the Options screen, and if it was, reload your settings from the variables. When the user is exiting your game, write the settings in the variables back to the file.

---
Tags: c++, architecture, software-engineering, menu, game-state
---


# Question
Title: What problems could occur if you make use of both the MonoGame API and the underlying graphics API?
What kinds of problems could one run into if they were making a game with MonoGame and started making calls to the underlying graphics API as well?

For example, if I wanted to do something in a MonoGame project that MonoGame didn't necessarily support, or I just couldn't find the proper documentation / example for but I could find an example of how to do it in OpenTK, am I setting myself up for trouble if I implement it using OpenTK directly while using the MonoGame API everywhere else? Specifically I'm looking to find out if there are any big issues that are known that might result of this and not something obscure that will happen in very rare cases.

I tried doing a little research via Google and the GD.SE site itself and I couldn't find much. Maybe MonoGame has really covered most of its bases, but what if I manually wanted to work around one of it's outstanding issues or a feature that is not yet implemented?

If so what sort of problems might arise and are there any ways to help mitigate these issues?

# Answer
In most cases these problems would fall into the category of "undefined behavior" (not in the C++ sense, but in a more broad understanding).

What you'd be doing is essentially circumventing the abstraction provided by MonoGame (as an example, this of course applies to basically any such higher-level API). In doing so, you can cause class invariant guarantees to be violated, which in turn means the assumptions the MonoGame authors were able to write their code under may no longer be true and the code may behave unexpectedly. Your own code can really no longer rely on the abstraction's invariant guarantees, either, since you've broken them.

This unexpected behavior will include, potentially, the entire gamut of such behavior from simple rendering artifacts to crashes or memory corruption.

* For example, if you fiddle with some rendering API state by end-running around MonoGame itself, it may not be able to detect that state change (because it probably won't poll the underlying API for changes, it's more efficient for it to simply assume it's the one controlling the API and track those changes itself). Consequently it may decide, on the next render pass, that it doesn't need to update something that should in fact be updated and your scene may not correctly render.
* Or you could mess with the underlying API and alter the reference count of some device object (assuming D3D), which means that it may get prematurely released from under MonoGame or accidentally *not* released, resulting in a probable crash or resource leak.
* Or you could do something that works, but because you are mucking about in an unsupported manner and with undocumented features or unexpected access patterns, you could find your code horribly broken on the next release.
* Or you could do something, it works fine for a few versions, but later you run into some other bug and have difficulty tracking it down, so you ask the MonoGame folks for help, perhaps sending in a bug report because you're sure its a problem in their code. They can't reproduce the bug, of course, and it finally comes out that you're doing this weird direct-access hackery and at that point -- regardless of whether or not your hackery is the root cause of the bug -- they'll probably stop spending resources on your fix simply because you are doing an unsupported thing (or at least, they'll likely de-prioritize you).

Of course, in some cases you might absolutely *have* to circumvent the API, perhaps to work around a bug in shipping software for which the official patch will not be released in time. If you absolutely *have* to do this, you should take the soft approach: try to scope your direct access as narrowly as possible, and make sure you try to leave the state of the underlying API as unchanged as possible when you are finished with your meddling. It's not a guarantee of success, but it can help.

Ideally you'll avoid this kind of thing entirely, though.
> 12 votes

# Answer
I agree with Josh's answer fully but I'd like to add some thoughts.

The purpose of MonoGame is to bring the XNA API to many platforms. If you are using OpenTK directly you are restricting yourself to only those platforms that support it. Therefore, you could loose one of the main benefits of using the abstraction.

If you find yourself wanting to do something that MonoGame doesn't support or are having trouble finding the documentation, first ask the more specific question of what you're trying to do. You might find that there's a way to do it already or perhaps it's a planned feature that hasn't been implemented yet.

After discussing it, it may be that you, or someone else, could implement the missing features in MonoGame for everyone's benefit.
> 3 votes

# Answer
With regards on how to mitigate the problems arising on combining those two ideas:

**MonoGame is open source, modify it directly and you don't need to worry about problems from using both.**

If you think you need additional stuff in it, then by all means: create a fork. Use that base code and add yours on top of it. Recompile MonoGame and there you go. This would also let you update the MonoGame fork when it's updated (of course you'll have to fix any conflicts that may arise in the process).
> 3 votes

---
Tags: monogame
---


# Question
Title: Unity + Kinect - Current, and active wrapper options?
What are some current wrapper solutions for using the Kinect with Unity? The initial primesense one seems not to be in active development.

I'm aware of the Zigfu one, however are there any open-source alternatives?

# Answer
Why not use the oficial Microsoft Kinect SDK? It's a .NET assembly that can be added as reference to a normal C# project.

You can download the SDK from here: http://www.microsoft.com/en-us/kinectforwindows/develop/developer-downloads.aspx
> 1 votes

---
Tags: unity, kinect
---


# Question
Title: Implement 2x speed in tower of defense type game
I was currently developing tower of defense game and I want to implement 2x feature for my game. Game usually run with 1x speed that was normal speed of the game.

Here what 1x and 2x mean : 1x - mention normal speed of the game, 2x - mention the game object moves with double speed means user experience the fast game play.

I want to implement such functionality for my game. The functionality that I want contains in the game Medieval Castle game that was available in the market.

https://play.google.com/store/apps/details?id=com.nova.root&feature=search\_result#?t=W251bGwsMSwxLDEsImNvbS5ub3ZhLnJvb3QiXQ..

The screen shot also shows the 1x and 2x button in that game. I think for 2x speed of the game I have to increase the speed of each object that were in the game.

So any member please help what to do for that implementation. Only idea become enough for me.

# Answer
> 2 votes
I know the thing that I am answering my own question but I found suitable answer so I think I have to post it for other user and save their time.

```
  public class BaseScene extends Scene {

    private float speed_factor = 1f;

        public float getSpeedFactor() {
            return speed_factor;
        }

        public void setSpeedFactor(float new_factor) {
            this.speed_factor = new_factor;
        }

        @Override
        protected void onManagedUpdate(float pSecondsElapsed) {
            super.onManagedUpdate(pSecondsElapsed * speed_factor);
        }
    }

```

Develop this type of subclass and use this one for you game then on click of 1x and 2x button apply the value that you want suitable for your game.

There is no need to handle each character manually only handle scene and all the thing done for you.

# Answer
> 5 votes
In most update methods there is a delta, which provides the number of milliseconds (or some other measurement of time) since the last update was called. By calculating all of your movement calculations using both a delta and a movement speed, you get movement that is unaffected by a fluctuating frame rate.

The following is code pulled from the movement system of an Asteroids clone I'm working on (but modified to make my point more clear):

```
    public void process(Entity e, int delta) {
       // Imagine that velocity is a vector
       x += e.velocity.getX() * (world.delta / (float) 1000);
       y += e.velocity.getY() * (world.delta / (float) 1000);
    }

```

Notice that the actual change of coordinates happens based on the amount of time passed. By modifying the delta passed into your system with some multiplier, you can make things in your game move more quickly or slowly:

```
    public void process(Entity e, int delta, float timeScale) {
       // if timeScale were .5, the game would slow. If it were 2, the game would speed up.
       x += e.velocity.getX() * (world.delta / (float) 1000) * timeScale;
       y += e.velocity.getY() * (world.delta / (float) 1000) * timeScale;
    }

```

# Answer
> 3 votes
I'd just like to add another answer here.

When performing speedup by changing the timestep, it might mean the behaviour is different. For example, if you have some physics in there with euler integration, the behaviour at double speed will diverge over time.

This is not a problem in 99% of cases, but it is something you should be aware of.

If you are multiplying speed by an integer as you are in your example, I would suggest doing multiple updates per frame with fixed timestep. This will ensure your simulation always behaves exactly the same way but at double, triple or quadruple speed.

This is of course more cpu intensive because you are doing double the simulation processing.

One very important thing to note: your update and drawing functionality should be completely separate, but this should ALWAYS be the case anyway, in any project. What I mean is, your display function should not change ANY state, it should ONLY draw the scene at the current time.

I'm not saying this is how you should do it, but it is very simple to implement and is another method to think about.

```
void mainLoop()
{
    for(int i=0; i<NUMBER_OF_UPDATE_STEPS; ++i) update(FIXED_TIME_STEP);
    draw();
}

```

---
Tags: andengine
---


# Question
Title: Moving sprites based on Delta time - consistent movement across all devices with different resolutions
This is the formula I am currently using to move my sprites across the screen:

Examples below only deal with X coordinates to keeps things as short as possible.

**Initial variable declarations:**

```
float frames_per_second = 30;         //Set this to target frames per second, 30 for this example.
float dt = 1/frames_per_second;       //Delta
float spriteXGrid;                    //Sprite's position on a grid (grid can be any explicit value, I use something simple like 800 x 600)
float spriteXScreen;                  //Sprite's actual final position in screen coordinates
float spriteXTime=5;                  //Time variable.  This is in seconds and is the amount of time the sprite should take to traverse the screen
float spriteXVel=1/spriteXTime;       //Velocity value used in conjunction with time value to calculate new position

```

**To set my sprite's initial position I simply do this:**

```
spriteXGrid = (pos/800);           //Where pos is the position on the grid (0-800) and 800 is the grid size that I chose to work with.
spriteXScreen=spriteXGrid*width;  //To convert to actual screen coordinates - where width is the actual width of the device currently running on.

```

**Then to move my sprite, I do this:**

```
spriteXGrid = spriteXGrid + (spriteXVel * dt);  //Update sprite's position on the grid
spriteXScreen=spriteXGrid*width;                //And convert to screen coordinates (again, width is the screen width of the current device)

```

Then I just use the spriteXScreen variable to plot the sprite, something like:

```
sprite.drawSprite(spriteXScreen,0);            //this is from a custom class I wrote that takes in sprite's x and y coordinate and draws it there.

```

My question is, is there an easier way I can do this?! It's a nightmare to manage when it comes to collision detection etc.... because, you have 2 different coordinates, the 'screen' one (which I would describe as 'superficial'), and the 'grid' one which is needed for all the good stuff, and is a nightmare to actually work out and work *with*.

is there anyway I can just do something like:

```
spriteXScreen+='some value'

```

Which would allow my sprite to move across the screen **in the same amount of time** on all devices?

(I mean I can't just say move it by 1 pixel, because if I move 400 pixels in say 5 seconds on a 400 pixel wide screen, the sprite will have passed the whole screen in those 5 seconds, but on an 800 pixel wide screen it would have only passed halfway in the same amount of time).

The whole business of have a 'grid' coordinate and having to convert it to a 'screen' coordinate is extremely irritating and I'm wondering if I'm doing this all wrong....?

Suggestions and solutions would be *very* welcome

# Answer
You are essentially creating 3 coordinate systems when you only need 2. The coordinate system for your grid is 0 to 800. Your "real" space is a normalized position from 0 to 1.0. And your "screen" space is measured from 0 to whatever your pixel width is.

You will always need to convert between some kind of world coordinate system and screen space in order to properly position your sprites.

The units for the math you are doing are basically:

```
grid     real     screen      screen
----  *  ----  *  ----     =  ----
 1       grid     real         1

or  ( objectX / 1 ) * ( 1 / 800 ) * ( width / 1 )

```

If you calculate the ratio between your screen resolution and your grid space, then you can multiply by that ratio to know where to render your sprite, without involving your "real" coordinates.

```
grid    screen     screen
---- *  ----    =  ----
 1      grid        1

or ( objectX / 1 ) * ( width / 800 )  == spriteXScreen (in pixels)
or objectX * ( width / 800 )

```

You can write all your game logic to only deal with grid space coordinates, and then when you're ready to draw everything, loop through all your objects, multiply x and y by the ratios you've computed, and draw at those pixels.

You will need to specify your velocity in terms of "grid" units instead of "real" units, in this case. But it should simplify things somewhat for you.
> 6 votes

---
Tags: android, animation, sprites, logic
---


# Question
Title: What is billboarding, and can/should it be used in 3D games to create special effects for weapon blasting effects?
What is billboarding, and can or should it be used to create special effects for 3D games on weapon blasting effects?

# Answer
> 24 votes
> What is billboarding ?

Billboard is a textured flat object, usually a polygon, which faces the camera. Its direction usually changes constantly as the object and camera move, so it always faces the camera direction, this operation is called Billboarding. Billboards usually use texturing + alpha to represent many phenomena that do not have smooth solid surfaces (e.g. Clouds, Grass, Smoke, Fire).

> Can or should it be used to create special effects for weapon blasting effects?

You need to **make a distinction between billboards and particle systems**. A particle system is a set of small objects that are animated and controlled using an algorithm. Particles can be represented by Billboards, but other forms are also common such as points and lines. You can make gun blasting effects using billboards, but in the end, you will need a way to control those billboards which will end you up making a particle system (though might be a very simple one)

# Answer
> 3 votes
> BillBoard

A billboard within your game is always orientated to face the camera. As the camera moves the object is orientated to face the camera. The same theory can also be applied to cause an object to always face another object within your game.

based on orientation its divided into 2 types Points, Axial

---
Tags: special-effects, billboarding
---


# Question
Title: Libgdx import bin/xml/json from physics editor
I'm using Libgdx. I did a simple json file in Physics Body Editor and I don't have any idea how could I import it into my physic world in libgdx.

Any idea will be appreciated.

P.S: Sorry if there are question with the same subject, I didn't find any of them.

# Answer
use this code. Though you must have got a file named app.java when you downloaded .zip of physics body editor. This code is from that file only which uses .json file from the editor.

// 0. Create a loader for the file saved from the editor. BodyEditorLoader loader = new BodyEditorLoader(Gdx.files.internal("data/test.json"));

```
    // 1. Create a BodyDef, as usual.
    BodyDef bd = new BodyDef();
    bd.type = BodyType.DynamicBody;

    // 2. Create a FixtureDef, as usual.
    FixtureDef fd = new FixtureDef();
    fd.density = 1;
    fd.friction = 0.5f;
    fd.restitution = 0.3f;

    // 3. Create a Body, as usual.
    bottleModel = world.createBody(bd);

    // 4. Create the body fixture automatically by using the loader.
    loader.attachFixture(bottleModel, "test01", fd, BOTTLE_WIDTH);
    bottleModelOrigin = loader.getOrigin("test01", BOTTLE_WIDTH).cpy();

```
> 1 votes

---
Tags: box2d, libgdx
---


# Question
Title: How to map absolute Joystick position to object rotation?
In my (Ogre) 3d scene I have an object that should be rotated locally based on Joystick input. I have a Joystick with min/max values of \[-32767, 32767\] on both X and Y axes. When the Joystick is in its origin position, the object should not be rotated. When the user moves the Joystick, the object in the 3d scene should follow this movement (or better: orientation) up to a max. of +/- 45 degrees on both axes.

Or in other words: when the user moves the Joystick e.g. fully to the left, the object's orientation in the 3d scene should be set to 45 degrees on the according axis.

Being new to 3d programming I searched on the Internet on how to achieve this. I think to understand that I want to use Quaternions for this task. I found some examples and tutorials on how to use Quaternions for rotating objects. What I don't understand though is how I can map from the Joystick's current absolute axes positions to the absolute, local rotation of an object.

I see that I could use the `rotate()` method of the object's node to set its rotation, but I understand that this rotates the object relatively to it's current position. But instead I want to map from the Joystick's absolute position to the absolute orientation/rotation of the object in the scene.

Any advice how I should approach this?

# Answer
> 1 votes
I don't know about the rotation part but for the mapping input to rotation you can do the following:

(this doesn't go in code)

add 32768 to your input getting a value 0-65535

from here you can get your multiplier which is 90/65535 = 0.00137

then to get your rotation distance you can simply multiply your input by your multiplier

(this goes in code)

32767 * 0.00137 = ~45 (may want to do some rounding)

---
Tags: rotation, ogre, quaternion, orientation
---


# Question
Title: Is Jump Point Search (A* with JPS) appliable to non-diagonal grids?
I'm trying to speed up my pathfinding and discovered A\* with JPS. It basically prunes tiles before adding them to the OPEN set.

Can I use that technique with my grid that only allows straight directions?

# Answer
If you read the article, you'll see that they list this as an open problem in the "Conclusions" section:

> "One interesting direction for further work is to extend jump points to other types of grids, such as hexagons or texes (Yap 2002). We propose to achieve this by developing a series of pruning rules analogous to those given for square grids."

So, to apply Jump Point Search to your orthogonal grid, you'd need to decide which points should count as jump points on that grid. After thinking about this for a moment, I think — but have *not* proven! — that the following rules (based on Definitions 1 and 2 in the paper, somewhat rephrased for readability) may work:

*A node y is the jump point from node x, heading in direction d, if y is reachable from x by moving straight in direction d, and is the closest such node to x to satisfy at least one of the following conditions:*

1. *node y is the goal node,*
2. *d is a horizontal move, and either of the cells vertically adjacent to the cell y − d (that is, the cell one step before y when moving in the direction d) is blocked, or*
3. *d is a vertical move, and there exists a node z which is a jump point from y (by condition 1 or 2) in some horizontal direction d'.*

Of course, the words "vertical" and "horizontal" can be exchanged in the definition above. The point is that we need to pick *some* way of breaking the symmetry so that only one of the possible paths for traversing an open rectangular region is considered. Harabor and Grastien do that by preferring "diagonal-first" paths, but since we can't do that, we have to make do by preferring vertical-first (or horizontal-first) paths instead.

It *might* also be possible to develop alternative pruning rules that produce more "natural-looking" paths, such as preferring the current heading over turning, or perhaps even preferring constantly turning staircase paths. The rule I gave above is simply the most straightforward translation of the Harabor & Grastien rule to an orthogonal grid I could think of.
> 10 votes

# Answer
Actually, if you look at the definition of 45-degree route, it is always possible to transform a path with 45-degree route into a path without 45-degree turn. And it's also optimal (you can easily prove it by contradiction).

So, the simplest way is to run the jump point search and then transform it into orthogonal route.
> 2 votes

---
Tags: path-finding
---


title: What is "game state?"

text:
# Question
Title: What is "game state?"
The terminology "game state" is a bit vague to me. Could anybody clarify what is included in the game state, please?

Is it a state of all the variables and objects within the game at particular moment?

# Answer
> 21 votes
> An Introduction: Just what in the world is state?
>
> Game state can be used to mean a variety of things and you'll find it used in many different ways in the game industry. In this case I'm using "game state" to provide a description of an object at a given point in time in a game. Clear as mud to you now? Don't worry, I'll try to describe it in a different way, one as a geek like me you might identify with a little better.
>
> Comic books. When buying used comic books, they often say what "state" or condition the comic book is in. The current state of the comic book gives you some indication of how the comic book is going to look when you purchase it. Mint, Fine and Poor all give an image in your mind of just how battered or worn the comic book is.
>
> The same is true for objects in your game. By defining the various valid states for your objects, your game will know just what to do when it is in that state. And just like the comic book industry has defined the various valid states for comic books, you as the governing board for your game must define valid states for your objects and just exactly how the game should respond when those objects are in any given state.

Since this Game State introduction has a very nice way to explain it, i quoted it and you can find the complete article at http://www.xnadevelopment.com/tutorials/thestateofthings/thestateofthings.shtml

# Answer
> 1 votes
I was recently looking this subject up myself. This link gives great advice to implement a simple game stack/ state. http://gamedev.tutsplus.com/articles/game-design-articles/how-to-build-a-jrpg-a-primer-for-game-developers/#state

---
Tags: game-design, terminology
---


# Question
Title: Tilemap collision in component based entity system
I am trying to set up a collision system for a tilemap in my component based entity system, but having trouble with figuring out how to do so.

Currently I have the following approach: My tilemap consists of a Tilemap\_Component, which just holds the array, a Tilemap\_Render\_Component, which holds the Tileset image, and a Tilemap\_Collision\_Component, which holds the information which tile value is handled as a wall.

To make an entity collideable with the tilemap it needs currently the following components: Movement\_Component, which holds the X/Y Velocity, Position\_Component, which holds X/Y Position and Tilemap\_Collider\_Component, which holds the information if the object only collides with walls or as well with some other objects in the tilemap.

Now my problem is the following: It is very hard to determine what to do with an object which collides with the tilemap. If I set velocity to zero, it is possible to glitch through walls because Movement and Input are handled in other systems than the collisions. If I just change the Position of the object, there occur two problems: One is, that the object starts to flicker because it has moved a bit. The other is, that I would have to know how big the object is which is colliding with the wall. Now I could just say that a Render\_Component is required for objects which can collide with the tilemap and then use the image information in the Render\_Component of the object and the Tilemap\_Render\_Component of the tilemap to calculate collision, but I think this is a bit against the intention of component based system.

What would be your suggestions? How could I handle this problem? Or, as well: Was anyone of you faced to such a problem? How did you solve it?

# Answer
> 1 votes
I do tiles collision in a dedicated TilesCollisionSystem where relevant objects register their TilesCollisionComponent.

The component contains a pointer to the geometry used for collisions. Some objects only register to the TilesCollisionSystem (some particles for example).

This way there is a dedicated system for tiles collision and it goes only through the list of objects registered with the system and for each object only the nearby squares are manually tested in the system. This is not the most flexible way but it works really fast in my case.

You could make it more flexible by adding geometries for the different tiles types as well.

I test the position of each object and if the movement since the previous tic goes into the tile I check the nearby tiles that have collided ad well and move the object out of the tiles using a vector which allows the most movement to the object without entering the tiles. Once the object is moved I go to the next object.

Of course the collision is applied after all movements have been applied (including other more complex collisions). And after input and AI scripts which could change the position have run. The movement vector (current speed) is set to the resulting movement (calculated from the tiles collision) adjusted by the delta time, this way gravity is applied on the next tick and cancelled in the same tick by the TilesSystem if the object is still touching a tile.

The display is synced with the simulation only at the end.

If your sprites define the size of your objects then, i guess, they can serve as "geometry" in your component.

---
Tags: architecture, component-based, entity-system, tilemap
---


# Question
Title: Determine corners of a specific plane in the frustum
I'm working on a game with a 2D view in a 3D world. It's a kind of shoot'em up. I've a spaceship at the center of the screen and i want that ennemies appear at the borders of my window. Now i don't know how to determine positions of the borders of the window.

For example, my camera is at (0,0,0) and looking forward (0,0,1). I set my spaceship at (0,0,50). I also know the near plane (1) and the far plane(1000). I think i'd have to find the 4 corners of the plane in the frustum whose z position is 50, and with these corner i can determine borders. But i don't know how to determine x and y.

# Answer
> 6 votes
*Disclaimer:* This solution really is simplified for your particular problem, because your camera is looking straight down the Z axis of the world's coordinate system. Also, the center point at 50 units away is already given as (0, 0, 50). If your camera's viewing direction was an arbitrary vector, there would be more multiplications involving the distance with a cross product of the viewing vector and the camera's Up vector.

Determining the borders of a plane at a given distance is dependent on the FOV angle in which the view is projected. Usually, the FOV angle is measured in the Y axis for rectangular viewports.

For any given distance Z from the camera, the shortest distance D from the center point of a plane perpendicular to the viewing vector at Z to one of its borders above or below the center (really, the intersection of the plane and frustum) is `D = tan(FOV / 2) * Z` . Add and subtract D from the center point's Y component to get the maximum and minimum Y extents.

To get the minimum and maximum X extents, add and subtract `D * aspect_ratio`.

Now getting the location of the plane's corners is simply plugging in the mix/max X and Y in its four possible combinations along with the Z distance.

# Answer
> 15 votes
## This is a more general solution

To start you will need some data.

The Camera's position represented by **P** (this is a point)

The normalized viewing vector represented by **v**

The Camera's up vector represented by **up**

The Camera's right vector represented by **w** (this is the cross product of v X up)

The near distance represented by **nDis**

The far distance represented by **fDis**

The field of view represented by **fov** (this usually in radians)

The aspect ratio represented by **ar** (this is the width of the screen divided by the height)

---

First we will get the width and height of the near plane

**Hnear = 2 * tan(fov / 2) * nDis**

**Wnear = Hnear * ar**

---

Then we do the same for the far plane

**Hfar = 2 * tan(fov / 2) * fDis**

**Wfar = Hfar * ar**

---

Now we get the center of the planes

**Cnear = P + v * nDis**

**Cfar = P + v * fDis**

---

And now we get our points

Near Top Left = **Cnear + (up * (Hnear / 2)) - (w * (Wnear / 2))**

Near Top Right = **Cnear + (up * (Hnear / 2)) + (w * (Wnear / 2))**

Near Bottom Left = **Cnear - (up * (Hnear / 2)) - (w * (Wnear /2))**

Near Bottom Right = **Cnear + (up * (Hnear / 2)) + (w * (Wnear / 2))**

Far Top Left = **Cfar + (up * (Hfar / 2)) - (w * Wfar / 2))**

Far Top Right = **Cfar + (up * (Hfar / 2)) + (w * Wfar / 2))**

Far Bottom Left = **Cfar - (up * (Hfar / 2)) - (w * Wfar / 2))**

Far Bottom Right = **Cfar - (up * (Hfar / 2)) + (w * Wfar / 2))**

---

Common assumptions that might be useful:

* Most games have their field of view set at 110 degrees as this is close to the human field of view
* The camera is most often set at the origin (0,0,0)
* The view vector is usually along the negative Z axis (0,0,-1)
* The up vector is usually along the Y axis (0,1,0)
* The right vector is usually along the X axis (1,0,0)

# Answer
> 0 votes
Conisdering you translate your "camera" by writing something like: gltranslatef(1, 3, 0). Make values such as posX and posY, and whenever you translate your camera, add to those values. Then when you add your enemy set it's X value to posX and it's Y value to posY for the enemy to appear where it would if the camera was at the origin.

---
Tags: camera, frustum
---


title: One job per method

text:
# Question
Title: One job per method
I always hear things about that each method should only do one job. But lets say I got Update() method in my game that updates entities state, path finding, player position, etc. Should I refactor that method into separate methods like UpdateAI(); UpdatePlayer(); UpdateWorld(), etc.? I know that mostly it depends on me, but I want to know the best practice.

# Answer
> 7 votes
No. Regardless of whether or not that rule is sound you have to remember that "one job" can have different scopes. "Update" is one job - updating the (whole) logic of your application each frame. But this task consists of several smaller tasks, like the ones you mentioned - "updating AI", "updating player" and so on. They can, of course, consist of further subtasks. That's why you usually call some functions that do smaller tasks in another function that is responsible for a bigger task. (Of course, you can also have some additional code (**not** function calls) in that function, too.)

---
Tags: software-engineering
---


title: Separate classes communication

text:
# Question
Title: Separate classes communication
Lets say I have a key and door. My third class (player) needs to pick up a key and open the doors. How should those objects communicate without making too much dependencies between them?

# Answer
Precise answer usually (or always?) depends on the specific situation and circumstances but I think it's a good idea to try to model the real-world relations between objects.

Like in your example - the human is the only entity that actually does something (takes action). So probably this class should call key and door's methods. Key doesn't have to know or do anything. It only has to have some kind of ID (to check if that's the right one). The door has to know what key fits into its lock (have the key's ID). Nothing else. Well, it can also have some kind of Open() method (to allow player to pass through it, but that's a different thing, actually). The human takes the actions (take/produce a key, put it in the door's lock and try to open the door).

Modeling the real-world relations between objects is good... because it's proven to work! It works in real-life so it should work in your application, too (provided it's not too complex/impossible to implement).

Also, as always, try to keep things as simple as possible and use common sense - if your app or the situation your trying to implement is small/simple - it's sometimes just better to do it the easiest way you can think of without overthinking and overdesigning objects' relationships - because there's no point in it.
> 6 votes

# Answer
The simplest way to enforce a relationship without strong coupling is to use a Mediator. There could be an `Unlocker` system that keeps track of the player's keys and listens to collision messages between the player and doors. By moving this dependent logic upwards, you keep the player, the key, and the door decoupled.

Here's some C# code to illustrate. If you need clarification just leave a comment.

```
class Unlocker
{
    public OnCollision(Entity a, Entity b)
    {
        TestCollision(a, b);
        TestCollision(b, a);
    }

    private void TestCollision(Entity a, Entity b)
    {
        if(a is Player)
        {
            if(b is Key)
            {
                b.Destroy();
                _keys++;
            }

            if(b is Door && _keys > 0)
            {
                b.Destroy();
                _keys--;
            }
        }
    }

    private int _keys;
}

```

In this example, OnCollision is registered to the collision system, which activates it (and the other collision handlers) when two entities collide.

As you can see, this simple Unlocker class added a new set of behaviors dependent on the player, keys, and doors without creating any coupling between the entities themselves. This is especially important for object models like composition where entities are not able to implement their own behaviors.
> 3 votes

---
Tags: architecture
---


# Question
Title: How to determine the best approximate direction
I want to determine which sprite to use when one agent is "facing" another agent.

My game is 2d, and uses 8-directional movement. Deciding which sprite to use for movement is easy enough since there are only 8 options when moving form one square to another.

```
def direction(self, start, end):
    # method for determining facing direction
    s_width = int(start[0])
    s_height = int(start[1])
    e_width = int(end[0])
    e_height = int(end[1])
    # check directions
    if s_height < e_height and s_width == e_width:
        return 'down'
    elif s_height < e_height and s_width > e_width:
        return 'downright'
    elif s_height == e_height and s_width > e_width:
        return 'left'
    elif s_height > e_height and s_width > e_width:
        return 'upleft'
    elif s_height > e_height and s_width == e_width:
        return 'up'
    elif s_height > e_height and s_width < e_width:
        return 'upright'
    elif s_height == e_height and s_width < e_width:
        return 'right'
    elif s_height < e_height and s_width < e_width:
        return 'downleft'

```

It's verbose, but gets the job done. `start` is the agents current coordinate position, and as you might guess `end` is the next step in the list of waypoints which makes up an agents path. The problem is that using the same function for determining which sprite should be used when attacking another agent does not look very good at all.

For example, if the target is down, but only one pixel to the right, we would want to show the 'down' sprite, but this function returns 'downright' instead. How can we change it to appropriately return the fitting sprite?

# Answer
> 0 votes
You can test the distance between self and target to determine what sprite to use. If the distance is greater than a set MAX, then it looking to left/right otherwise it is just looking down. For example,

```
let self = (sx, sy) target = (tx, ty)

if (sy < ty)
    distx = abs(sx - tx);
    if (distx <= MAX_X OR sx == tx)
        return  "down"
    else
        if (sx < tx) then return "downright" else "downleft"
    endif
else // handle up

```

Notes:

1. I am using pseudocode not any specific language
2. I used x/y pair instead of width/height since the former refers to coordinates not dimension like the latter.

---
Tags: sprites, python, direction
---


title: Story line implementation in a game

text:
# Question
Title: Story line implementation in a game
Say I have the general engine working and the only thing missing is a story line.

Let's take the Pokemon games as an example: How would I implement surfing if I don't want to check wether the next tile is a water tile on every step I take? (I assume this would be horrible performance wise) The guards will let me pass once I have delivered some juice to them. How would this be done?

The second one should I should be able to implement with a state machine. Am I correct in understanding that a state machine is an enum(java) with my different states?

The other thing I am a little bit confused about is Events. For example how would I implement that if I step on a certain tile my character dies - again without checking this for EVERY tile I step on. I believe the tile would need to call some sort of Event that then kills my character. How should I write my "EventHandler"?

# Answer
1. Checking for next tile being water is not going to hurt your performance in any way. It takes very little computing power. Modern games operate with thousandfold amounts of data at 60 times per second, and your occasional checking of next tile is nothing.
2. You can implement state machine in different ways. For example having a variable "isFirstPlayerTurn = 1" or having it at 0 is a state machine. You can use few or dozens of variables to describe certain state.
3. You can use player (sprite, object, whatever you have) to handle this logic, just check on what tile you are standing once in a while (once a frame?) and if it is lava for example, perform function that kills player and resets game.
> 1 votes

---
Tags: game-mechanics
---


title: Does XNA have a built-in GUI library?

text:
# Question
Title: Does XNA have a built-in GUI library?
Does such a thing exist or do I have to code one?

My project needs textboxes, buttons, input capture, timings for "press and hold keys" and so on. These are quite standard for a GUI library but hard to code from scratch.

What options do I have?

# Answer
> 4 votes
There is no form controls available for XNA. There are 3rd party source code you can get however:

NeoforceControls

http://xnainterfaceelements.codeplex.com/

XNAUI

\** I do not endorse any of these products, nor have I looked at these since I posted this answer back in 2013.\*

---
Tags: xna, c#, gui
---


# Question
Title: Different kinds of movement in component based entity system
I am writing a pong clone with a component based entity system. But I am having trouble with the different kinds of movement in the game.

The problem is the following: My paddles will just move up and down, so I only need a Y-velocity for these. But the ball can move in each direction. So the ball will need an angle and a velocity. Now my question is: Is it usual to put the data for moving a ball in another component than the data for moving a paddle? Because if I would do so, I would need two systems just for movement. Is that a good approach?

A little bit information about my system: My entites are only IDs. I have an entity manager which holds all the entities and the linked components. Components only hold certain data on which systems operate. Basically I am using this approach: Tutorial

# Answer
They should use the same movement component for both, if the movement component is velocity. However, the systems that modify the velocity will be different. The ball will use the physics component to bounce off the paddles and walls, where the paddles will use the mouse/keyboard input component to move. So the physics system will be modifying the movement component of the ball, and the input system will be modifying the movement component of the paddles. The paddles won't use the x-axis for movement, but that's OK.

The will both use the movement system. The movement system will take their movement components and update their position components.
> 4 votes

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


# Question
Title: Looking for pre-broken models/meshes for use in a unity project
Hi guys for my final year project I'm working on comparing the difference between a few destruction techniques for a game environment, based on looks and computational efficiency. I intend on comparing a model with pre-broken parts (which falls appart on collision), to the same model that uses my shattering algorithm in real time. I will be trying to implement my algorithm using the mesh classes in unity to access c vertex data and I should have everything I need except for a model which has a pre-broken, and nonbroken form. I was wondering if you guys could point me in the direction of any free to use resources which have a solid form and a form in pieces. (A standard wall for example would be ideal). Thanks for reading, Andrew.

# Answer
In practice modular meshes are achieved using a combination of techniques like mesh deformation, noise generation, and subdivision.

Meshes are actually recalculated (or split) at runtime to create several separate meshes. Noise generation is sometimes used to create particle effects and subdivision to create better levels of detail when a split mesh has too few faces.

That being said, it is going to be difficult to find the resources you are requesting. You'll be better off modeling a few cubes yourself to achieve your goal.

Another option is to render a group of cubes that will listen to the collision event, and another group that will not. This way one will fall apart on collision and the other won't.

You could write a small method that will actually combine the meshes of the later group of cubes. Unity3D has a built in method for doing this: CombineMeshes
> 0 votes

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


title: 3D Camera raytracing (PSM SDK)

text:
# Question
Title: 3D Camera raytracing (PSM SDK)
I am currently creating a 3D Camera on the Playstation Mobile SDK (which is basically openGL with just a little bit of abstraction).

The game I am trying to make is a 3D Tactical. That means my world is composed of 3D cubes, all of the same size (unit size) and placed at integer position.

I'd like to be able to detect on which block the player clicks. That means, some sort of raytracing from the camera to detect the nearest block. My problem is that I am new to all this maths/physics/3d stuff. How could I implement this easily (and in a efficient enough way) ?

My camera currently have a position, and two modes : Target mode (it uses a LookAt on a point) and direction mode (it uses a lookAt on its position + the direction). That means I have access to the direction of the camera.

# Answer
> 1 votes
What you need to do is unproject a 2D screen coordinate to a ray within the world. Perform intersection tests of some sort with the ray, and then perform whatever handling logic you want. The first link explains the process of creating a ray from a screen coordinate, it uses DirectX, but the principle is the same. How you choose to identify the object you are clicking on is up to you. Chances are you will want some sort of acceleration structure to minimize the number of intersection tests, which can be done using some form of space partitioning, such as BSP/KD-Tree/Quad/Oct/whatever.

The second link provides a method for performing AABB intersection tests with a ray, and is one method you could use for identifying which cube you intersect.

http://www.mvps.org/directx/articles/rayproj.htm -Unproject http://www.siggraph.org/education/materials/HyperGraph/raytrace/rtinter3.htm -Slab test

*EDIT* Another note, you don't have to actually calculate a ray from a 2D coordinate, but instead could simply use the unprojected 3D coordinate to perform containment tests rather than intersection tests. You would still need to perform some sort of hierarchical bounding box tests to eventually identify what object you are clicking on is.

---
Tags: 3d, camera, psm
---


title: Drawing in 3D with LibGDX

text:
# Question
Title: Drawing in 3D with LibGDX
Is there any way to simply draw in 3D, just like you would draw with ShapeRenderer or SpriteBatch? All I want is to draw circles that are in x.y.z coordinates, so some circles are far away from view and some are closer. Also I would like to be able to rotate these circles.

# Answer
The simple way to draw in 3D is to wait until LibGDX has implemented their 3D functionality.

Otherwise, you can simulate the effect in 2D. Basically, you change the scale of the object to represent its movement along the Z-axis. Rotating would only be with respect to the current 2D perspective.
> 0 votes

---
Tags: 3d, libgdx, lwjgl
---


title: Matchmaking by user-supplied parameters

text:
# Question
Title: Matchmaking by user-supplied parameters
I'm looking for matchmaking algorithm for a 1 vs 1 online game. Players must not be matched by their skill level, but instead by some specific filters set by the players.

Each player sends a request that specifies some set of parameters (generally, 2-4 parameters). If some parameter is specified, the player can be matched only with those who had sent this parameter with exactly the same value or those who haven't specified the parameter at all.

I need this algorithm to be thread-safe and preferably fast. It would be great if it worked with 3-4 or even more parameters, but even one is alright (in my case, it's a game bet). Also, I'd appreciate ideas on how to implement or improve this algorithm on my server platform - ASP.NET.

One more problem I'm facing is that match finding can't be executed right after the user sends request, because if another user sends a request before a previous matching is finished, they won't be matched even if they possibly could. So it seems that match finding should be started on schedule. I need help on how to optimize it and how to choose time interval for starting new match finding.

**P.S.** I've also posted this question on stackoverflow

# Answer
The easiest method that performs well and gives a lot of flexibility is to use a SQL database, e.g. an in-memory SQLite database.

Using such, you can trivially find all pending matches that meet some criteria, insert a pending match, and remove "stale" matches that are too old (indicating no match was found).

Define a table that has a column for your match criteria and metadata, like so:

```
| id | username | created  | gamemode | gamesize | gamelength |
| 77 |    bob52 | 08:17:23 |      ctf |       16 |         15 |
| 63 | johnny77 | 08:16:59 |       dm |       32 |         15 |
| 59 |  theboy1 | 08:16:49 |      ctf |       32 |         30 |

```

When you get a request for a new match, do a query for rows matching that pattern, limiting yourself to the oldest match (depending on the sophistication of your criteria and how you select "good" matches, you may end up with a queue building up, e.g. where two players A and B don't match each other but C matches both, and you want FIFO behavior in these cases). Form a match on that pair. If there are no matches, insert the request into the table to be paired with the next matching request.

You can periodically clean out old entries that might accumulate. In general you don't need a timeout, though you do need a way to cancel match-making (and remove any rows for that client). There's no reason to always time out at 30 seconds an dmake a player resubmit their request over and over, especially as it might just be that matches could be found by just waiting a bit. If you are having long match-making times, that means your algorithm is bad, or your game is unpopular. Or you have unpopular game modes; if very few people play 32-person ctf with a 30min timer, just remove that as a valid option. The more game modes you have the more your playerbase is spread apart and the harder it is to make a match.

One nice advantage of SQL is that you can easily make some criteria less explicit. If a player has no preference on match length, that column simply isn't queried when looking for matches, and a value of NULL can be created for that column if the request is queued. Matches can have a "gamelength IS NULL or gamelength=:length" to the query so folks who don't care about game length can be matched with those who have a preference, which is a fine match.

A query from a user looking for any ctf match thus might look like:

```
SELECT id FROM matches WHERE gamemode IS NULL or gamemode='ctf' ORDER BY created ASC LIMIT 1;

```

(note that LIMIT is a non-standard extension, but a lot of DBs support it.)

Replace the id as appropriate. This might be the IP of the host user, a unique id for a dedicated server instance, or a per-match id used to coordinate users while spinning up a dedicated server instance. Whatever.

You can also keep matches in the queue for running games and have columns to track how many players are in the match (on each team) already and how old the match is, making is easy to selectively place someone into an in-progress game if a desired team color/type/whatever is in need of more people.

Using a SQL database also makes it easy to just move from in-memory SQLite to a full RDBMS if ever your game needs such. While I recommend strongly to avoid using a single SQL database for an entire world-wide game, you could easily having a single DB environment for each region of a game. RDBMS are not the most efficient ways to implement queues but they work well enough for most games, especially if you have a lot of match criteria.

Another option that can work a bit better in some cases is to create a list of queues. Create one queue for each game configuration choice. Eg. a ctf 32-player queue, ctf 16-player queue, ctf don't-care-how-many-people queue, a dm 32-player queue, etc. When a request for a match comes in, try each appropriate queue. Take the oldest match found (again, maintain FIFO ordering).

This works well if there are a smaller finite number of game mode configurations, and it can be scaled in some interesting ways, but in general is more work to do (especially to do well) than just using a SQL database.
> 2 votes

# Answer
The simplest way to do this is with a dictionary. That provides fast access to specific keys.

So, from each player you'll generate a dictionary with the parameters he set and fill in the dictionary. When the matchmaking is required to be done, you just check if the keys from one dictionary match any existing ones in the other one. If there is no such key, you just continue searching for the remaining keys.

Since you mentioned ASP .NET, here is a quick code that could do the matchmaking (it uses LINQ). Basically, what it does is it counts the number of conflicts (both have set a specific parameter and it's different).

```
Dictionary<string, string> player1Settings, player2Settings;
int conflicts = player1Settings.Keys.Count(k => player1Settings.ContainsKey(k) && player2Settings[k] != player1Settings[k]);
if (conflicts != 0)
{
     // OK
}

```

Of course, you can use a simple for loop and optimize the process by using `TryGetValue` to prevent double look-ups, if you really want.

With regards to the matchmaking interval, what I suggest is to allow the process of matchmaking to be a continuous process. For example, if I start finding a match, I should be allocated a specific time (like 30 seconds), and at intervals of 2-3 seconds to check again if any matches could be found. If in that period of time no match was done, then you'll just let the user quit or retry a new matchmaking process. You can even let the user see a progress bar based on the time left to find a match.
> 1 votes

---
Tags: algorithm, matchmaking
---


title: Ogre: Light not reflecting correctly

text:
# Question
Title: Ogre: Light not reflecting correctly
In my Ogre 3d scene I have an empty box, and within that there are three small cubes. The camera is also within the box, facing the three small cubes. The user can move and rotate the camera with the mouse.

There is only one (spot) light source, attached to the same node and facing the same direction as the camera. The idea is that the light should always spot the same direction as the camera, like a flash light (with a narrow light cone).

The problem now is that the light emitted by the spot light used in this scene is not reflected by the sides of the empty box correctly. When I face the camera perpendicular to a side of the box, then no light is reflected at all. Only when I move/rotate the camera so that it spots the box "walls" from a specific angle some light is reflected. The problem only occurs with the box sides, the small cubes within the box are reflecting the light correctly.

In this first screenshot you can see what happens when I look to the edge/corner of the box. You can see a wooden texture on the box sides, and those three cubes in the box. The blue-ish box in the middle is exactly on the border of the light cone, so that only the left side is within the cone and reflecting the light.

That seems like the correct behaviour. Now when I move the camera so that I looks exactly top-down to the same cube within the box, then only that cube is reflecting the light, but not the side of the box. It then looks like as the empty box would not be there at all, as you can see on the second screenshot. (Note also a second small cube on the top of the screenshot, which is again exactly on the border of the light cone.)

I am pretty sure the texture/material is not the problem. Because when I use the same blue-ish material for the box sides as I use for the small cube, then the cube is still correctly reflecting the light, whereas the box side is again not reflecting the light at all.

Any ideas what I am doing wrong here?
I am completely out of ideas here :(

# Answer
From looking at your screenshot, I guess Ogre is using per-vertex lighting. This means it calculates the lighting only at the corners of your box, then it just blends (interpolates) across the box sides. When you look directly at a box side, all 4 corners are outside the narrow spotlight, so all 4 corners are black.

One solution is to tesselate your box sides. Instead of one big square (2 big triangles), replace each side with a bunch of tiny squares, like a checkerboard. By adding more vertices like this, the lighting will look somewhat better (although still not great).

The best option for visual quality would be to configure per-pixel lighting in Ogre for the box. I haven't done that myself, but here's a thread about it: http://ogre3d.org/forums/viewtopic.php?f=2&t=77052
> 1 votes

---
Tags: textures, lighting, ogre, materials
---


title: Client-side physics simulation

text:
# Question
Title: Client-side physics simulation
I am trying to create a very simple client-server based physics game, using box2d library. A simple football game.
Obviously, the server runs only the box2d world. My question is:
is it correct to state that the client should run not only the needed rendered simulation but another box2d world as well?

I ask this because I know that the client should receive state information of the elements that have a changing state. And this information is received in packets every few ticks. And between every packet received, there's a time gap where I need to run the world like "nobody did nothing", and then correct the world state if somebody did something after I received the next packet.
That is why I need to run the box2d world in the client as well, but I feel it's kinda awkward and assymetrical.

Is this right? Is box2d prepared for this?

# Answer
> 2 votes
> Is this right?

Sounds good to me.

> then correct the world state if somebody did something after I received the next packet.

The simple approach is to remove the "if" here--always update everything from the server. The important state is the transform and linear and angular velocities for each box2d dynamic rigid body. You would update all these bodies on every server update.

With this approach (updating everything on every server update), you don't rely on determinism between the server and clients, which is good, because it would be difficult to get box2d to run deterministically across the server and both clients.

To improve performance on the client, you could try disabling collision detection on the client. If server updates are coming often enough (at least several per second), nobody will notice bodies briefly interpenetrating. Details:

* Ideally, you would make your bodies shapeless, but I don't see a way to do this in box2d.
* You could disable all collisions using collision filtering.
* Or, you could make all your bodies kinematic. So, in between server updates, bodies will just move in straight lines (and also rotate). Their velocities won't be affected by gravity in between server updates.

# Answer
> 0 votes
From my experience it's never a good idea to wait on the server to send out the world update packets before the next world update. I'd day that it'd be best if you put a copy of the whole box2d world for each client and act as if each of the other clients have the same keys pressed down, but try and send the packets to the client to update the other client's keys whenever possible. And as well update the world with these conditions. This "guessing system" works decent and updates the world without the need of the server sending them the update.

---
Tags: box2d, client-server
---


# Question
Title: How do I export Daz3D characters into an XNA format?
How do I export 3D animated characters created in Daz3D studio to a format suitable for inclusion in XNA video games? I'm looking for instructions on how to make sure weight, bones, vertices and materials are properly translated over into an XNA useable format.

# Answer
> 1 votes
Use the FBX-Koverter. XNA can read fbx.

---
Tags: xna, 3d, character
---


title: OpenGL ES 2.0: Enabling hi-res on iOS

text:
# Question
Title: OpenGL ES 2.0: Enabling hi-res on iOS
I created an empty iOS project and then added a custom GLView class which is then added to AppDelegate. I have following questions:

1) How do I enable hi-res retina mode on iPhone 4? Currently I am using the following code to check for device. The following code is from the AppDelegate where it first allocates GLView and then sets contentScale.

```
CGRect screenBounds = [[UIScreen mainScreen] bounds];
self.window = [[[UIWindow alloc] initWithFrame:screenBounds] autorelease];
// Override point for customization after application launch.
_view = [[GLView alloc] initWithFrame:screenBounds];
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
    NSLog(@"iPad detected");
}
else {
    if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)] && [[UIScreen mainScreen] scale] == 2) {
        NSLog(@"iPhone4 detected");
        _view.contentScaleFactor = [[UIScreen mainScreen] scale];
    }
    else {
        NSLog(@"iPhone detected");
    }
}

self.window.backgroundColor = [UIColor whiteColor];
//self.window.rootViewController = [[[UIViewController alloc] initWithNibName:nil bundle:nil] autorelease];
[self.window addSubview:_view];

```

But even after setting content factor it is drawing pretty poor quality polygons with jagged edges as shown in the image below:

http://farm8.staticflickr.com/7358/8725549609\_e2ed1e0e2a\_b.jpg

Is there any way to set the resolution to 960x640 instead of the default 480x320 ?

Please note that I can not use "someImage@2x.png" because I am generating images at runtime in the render buffer.

2) Second problem I am having is this warning message:

```
"Application windows are expected to have a root view controller at the end of application launch"

```

Thank you for your time.

**Edit:** Problem solved. Set contentScale **before** allocating render buffer memory, i.e: inside GLView, not AppDelegate.

# Answer
The warning you see is because you didn't add a view controller to your window. If your AppDelegate does the work of loading up the view, a view controller isn't necessary, however Apple recommends using them. It's not a critical warning.

I believe you need to set the content scale on both the backing EAGL layer and the view itself. `UIView` has the `layer` property, which you can cast to CAEAGLLayer. So after you set the content scale of your view, do something like this:

```
CAEAGLLayer *eaglLayer = (CAEAGLLayer *)_view.layer;
eaglLayer.contentsScale = 2.0f;

```
> 1 votes

# Answer
Set contentScale **before** allocating render buffer memory, i.e: inside GLView, not AppDelegate. I deleted the following code from AppDelegate and placed it into GLView:

```
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
        NSLog(@"iPad detected");
    }
    else {
        if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)] && [[UIScreen mainScreen] scale] == 2) {
            NSLog(@"iPhone4 detected");
            eaglLayer.contentsScale = 2.0f;
        }
        else {
            NSLog(@"iPhone detected");
        }
    }

```

What happened before was that the GLView was being initialised just before setting new scale factor with AppDelegate.

If Apple is ok with the warning and will not reject the app due to this:

```
"Application windows are expected to have a root view controller at the end of application launch"

```

Then problem solved. Thanks a lot !
> 1 votes

---
Tags: ios, opengl-es, opengl-es2
---


title: MMOFPS Player Positions

text:
# Question
Title: MMOFPS Player Positions
I'm working on a MMO game project. I have a question about MMOFPS game architecture. (I have basic network knowladge)

* (MMOFPS) I want to send player position to other players(clients) and other players will render the player. Namely this is the base of the game world. I have read some article about positioning and somebody says "use inputs for movement update" and others says "use position posting". That's the first problem. What is better? input or position based movement posting? What is more suitable for a MMOFPS game? (And how to do it?)

**SUMMARY:** I need to learn "how real multiplayer games work?" (but basically). In my first project I have used TCP protocol for posting position (not inputs) and I have sent position data 4 times per second. Server delivered them to other clients and other clients handled this data and maked a smooth movement. This is a very basic method to do it but I know that isn't MMO! Can anybody help me about understanding MMO game architecture?

# Answer
> I have read some article about positioning and somebody says "use inputs for movement update" and others says "use position posting".

Did they also provide reasons?

Using "input posting" increases program complexity because now with every input you need to post position and also update position on the client whereas with "position posting" you only need to update position on the client. Adjusting post interval with position posting is reasonably simpler as well.

But the better choice also depends on your requirements. If you do a lot of validity/collision checking on client-side (on top of server-side which is a must), "input posting" will reach other players faster.
> -1 votes

# Answer
That isn't about position sending performance. That's about server-client style. If you use input based movement (network), that means server decide your new position (authoritative server) and server tells your new position to you and other clients. If you use like position based movement, that means client decide his new position and tells that to server and server tells the player's new position to others. The difference is platforms. I think if your MMOFPS like game have a anti-hack (or anti-injection), you should use position based network movement because position isn't very important and you can prevent speed hacks. But that isn't suitable method for big (high-level) MMO games because there are always hackers and server must decide client's events-operations-commands etc. (also position based movement is more easy -lightweight- and server not loaded very much with calculating world)

> If you want to detect speed-hacks you can create a position-time based check function in server. That function checks time-position and calculates the client's speed. You can decide is it cheating via movement speed. (this is a simple detection).
>
> **EDIT:** In big (high-quality) MMO's, never trust the client!
> -1 votes

---
Tags: c#, mmo, first-person-shooter, udp
---


title: Constant buffer content packing

text:
# Question
Title: Constant buffer content packing
I've read this: http://msdn.microsoft.com/en-us/library/windows/desktop/ff476898%28v=vs.85%29.aspx#Shader\_Constant\_Buffer but there's not much information in it. When creating a constant buffer do I have to worry about what I put in it and in what order? Do I have to stick to a multiplicity of some power of 2 in bytes or something?

# Answer
> 6 votes
You need to make sure that any variable you use within the constant buffer does not cross a 16 byte alignment boundary, or you won't be able to access it from the shader.

For example, you could have a constant buffer that looks like this:

```
struct constant_buffer
{
     XMFLOAT4X4 wvp; // 64 bytes -> 16 byte aligned = OK
     XMFLOAT3 position; // 12 bytes (4 bytes left to reach 16 byte boundary)
     XMFLOAT4 color; // 16 bytes -> error,  this isn't aligned
};

```

You won't be able to read the last component (color) from your shader, since it's split between two 16 byte boundaries.

This can be solved by rearranging the order of the buffer, like this:

```
struct constant_buffer
{
     XMFLOAT4X4 wvp; // 64 bytes -> 16 byte aligned = OK
     XMFLOAT4 color; // 16 bytes -> still 16 byte aligned
     XMFLOAT3 position; // 12 bytes -> OK, no 16 byte boundary has been crossed
};

```

Or you can add some padding, like this:

```
struct constant_buffer
{
     XMFLOAT4X4 wvp; // 64 bytes -> 16 byte aligned = OK
     XMFLOAT3 position; // 12 bytes (4 bytes left to reach 16 byte boundary)
     float padding; // 4 bytes for padding to reach next 16 byte boundary
     XMFLOAT4 color; // 12 bytes -> OK, no 16 byte boundary has been crossed
};

```

The first way is preferred since it has less data to send, but sometimes you have no other choice than padding.

There's more information at Windows Dev Center.

---
Tags: hlsl, directx11
---


# Question
Title: Direction from the camera to the light source
I'm currently writing a game using OpenGL and GLSL. For the shader I need the direction from the current camera to the light source. The lightsource is given by `lightSource.position` as a uniform as well as the ModelviewMatrix (mat4).

The task is

> TODO: compute the vectors from the current vertex towards the camera and towards the light source

I need to fill two varyings with those information, but I'm not sure how to compute them. In addition I've the following information:

```
#version 330
layout(location = 0) in vec3 vertex;
layout(location = 1) in vec3 vertex_normal;

```

# Answer
> 5 votes
You can't do it with *just* that information. You need more.

For example, I assume you also actually have a the world, view, and projection transformation matrices available to you. In that case, you can compute the vertex's position in view space by multiplying it by the world matrix and then by the view matrix.

Since you're in view space, the eye is at (0, 0, 0) you can easily know the vector between that and the transformed, light-space vertex.

You can do the same if you have the light position. Bring the light position in to view space, then you can easily determine the vector between that position and the eye (which is, again fixed at the origin).

---
Tags: opengl, glsl
---


title: Min. Distance for Spotlights in Ogre3d?

text:
# Question
Title: Min. Distance for Spotlights in Ogre3d?
I have a simple scene with only one empty box. Within that box I have the camera attached to a scene node, which the user can move (translate/rotate). Additionally a spotlight is attached to the camera's scene node, facing into the same direction as the camera. So when the camera is moved, then the light moves as well.

```
m_pCamera = m_pSceneMgr->createCamera("Camera");
m_pCamera->setNearClipDistance(0.01);
m_pCamNode->attachObject(m_pCamera);

Light* spotLight = m_pSceneMgr->createLight("spotLight");
spotLight->setType(Light::LT_SPOTLIGHT);
spotLight->setDiffuseColour(1, 1, 1);
spotLight->setSpecularColour(1, 1, 1);
spotLight->setSpotlightRange(Degree(50), Degree(100));
spotLight->setSpotlightNearClipDistance(0);
spotLight->setDirection(m_pCamera->getDirection());
m_pCamNode->attachObject(spotLight);

```

So, this basically works fine. There is one problem though: As soon as the user moves the camera very close to a side of the box, then suddenly all is black, I can't see anyting. I am sure the camera is NOT moving through the box's side, it is still within the box.

So the problem seems to be that the light does not "work" when it is too close to an object, as if the object (the box side in my case) is not reflecting the light any more.

Any ideas?

# Answer
> 0 votes
It seems the problem is with per-vertex lighting vs. per-pixel lighting.
More details in this thread: Ogre: Light not reflecting correctly

# Answer
> 1 votes
It's probably the near clip distance of the camera. So your camera is outside of the box but the near clipping plane sees through it.

Usually you fix this by making sure the collision on whatever is moving with the camera is larger than the near clipping plane so that you can't physically get close enough to the world to see through it.

---
Tags: camera, lighting, ogre
---


# Question
Title: Creating rectangles from the inner part of a texture2D
This may be hard to understand, but I'll do my best.

You will see that the first image is a normal Mario, and the other is the result I am looking for. I'm trying to find a way to extract rectangles (biggest possible to smallest) from a texture2D, without overlapping rectangles. If the pixel is completely transparent, leave it out of the loop. I know it would be really easy to implement a rectangle for every pixel, but millions of rectangles isn't going to help performance wise. The goal is to get rectangles somewhat like this, decreasing the total rectangles greatly.

Any ideas or links? Anything would be great.

# Answer
Honestly, this is a solution in search of a problem. I can't see any benefits towards doing such a thing, and it doesn't seem like you can think of any either. Best just to take existing solutions and run with those. (and chances are "a new way of doing collision detection" will suck, when pretty damn smart people like the chipmunk physics and box2d devs are regularly improving their algorithms).

You're creating more rectangles when that's the wrong way to go about it.

What you *should* be doing is creating one polygon from a trace/outline of the sprite. There are loads of algorithms out there which can do it, including marching squares/cubes. Chipmunk Physics (Pro) even has the ability to construct physics objects from traces, as do several other physicy things that I am aware of.
> 1 votes

---
Tags: c#, xna, textures, xna-4.0
---


title: OpenGL FBO to OpenCV image

text:
# Question
Title: OpenGL FBO to OpenCV image
I am trying to figure out the best way to share an image between OpenGL and OpenCV libraries. I perform a render to texture on OpenGL, so I have and FBO/texture that then I want to pass it OpenCV, where (ideally) I will be some GPU stuff with it.

I know a naive way would be using glReadPixels, but this is obviously way to slow. It requires to copy the data from GPU memory to memory and then load it through cvLoadImage or similar in OpenCV.

I am pretty sure there must be a way to bind or map the memory from OpenCV, so I can "load" an image by just accessing to its FBO pointer or something like that... but I cannot figure out how.

I have goggled a lot about it, and so far I could just find this answer that I don't quite understand. What do they mean by `glbuffer.bind();`?

Any guess? Thanks.

# Answer
The answer you are referring to seems to be this one:

```
glbuffer.bind();
unsigned char *dest = (unsigned char*)glbuffer.map(QGLBuffer::ReadWrite);
// creates an openCV image but the pixel data is stored in an opengl buffer
cv::Mat opencvImage(rows,cols,CV_TYPE,dest);
.... do stuff ....
glbuffer.unmap(); // pointer is no longer valid - so neither is openCV image

```

What is done here is a mapping of the GL buffer memory into the virtual memory of the application. Thus you can write to the buffer or read from it as if it were any other memory you have a pointer to. Note that the code above uses Qt, but you can do this without Qt also.

By creating the OpenCV matrix (not the header, only the internal image data) within the mapped region, you can effectively read/write the region via OpenCV. There may be problems with stride, so be careful.

In general if you would want to transfer the buffer to OpenCV, you would first map the region, then build a OpenCV Mat header around it (like in the example code above) and finally call Mat::copyTo() to another Mat object. After releasing the mapping, you would still have the data from the buffer in that other object. It might very well be that for this operation you would need to set the CV\_TYPE to sth. like 4-channel unsigned char (or whatever you have in your buffer) and then convert to BGR.
> 2 votes

---
Tags: opengl, gpu, memory-efficiency
---


# Question
Title: Framebuffer formats with enhanced Alpha precision
I render some lines with alpha values into an FBO. Because I play a lot with alpha, I need the alpha channel to have more detail than RGBA8. For example, RGBA32F works like a charm.

As I have only a Quadro GPU to test. Is there a general advice on which FBO format works best (in terms of speed) on most cards?

1. Would there be a benefit in using RGBA16F, RGBA16 etc.?
2. What formats can I expect a GPU to support?
3. Is RGBA32F a regular feature for a GPU not older than 5 years?

# Answer
> 2 votes
In general, yes, there will often be a performance benefit to using "thinner" (fewer bytes per pixel) FBO formats. It depends on the details of your hardware and how you're using the buffers, but it's quite common for performance to be memory-bandwidth-limited for at least part of the graphics frame (postprocessing, for instance). In that case, a thinner FBO format means a smaller amount of memory to access, which means it'll be faster.

Assuming you only need the extra precision for the alpha channel, but not the color channels, it's also possible on recent GPUs to use multiple render targets (MRT) with an 8-bit format for the RGB and a second, separate render target in single-channel R16F or R32F format for the alpha. (Your shaders would have to be altered to output the alpha to the second render target.) That might be a performance gain too, especially if you need to perform postprocessing operations on the alpha channel alone - it'll be faster to read and write if the alpha is in a buffer by itself.

As for which formats are supported, any GPU supporting Direct3D 10 or 11 (which is probably most of the discrete desktop GPUs sold in the last 5 years, but not integrated or mobile GPUs) should support RGBA16, RGBA16F, and RGBA32F. However, the oldest GPUs within that 5-year time frame might not support bilinear filtering or mipmaps for RGBA32F, although they should support it for RGBA16F.

All in all, RGBA8 is generally going to be the fastest format, but if RGBA8 isn't doing it for you due to precision or range problems then I'd recommend trying out RGBA16F. It has broader support than RGBA32F, is quite possibly faster as well, and probably gives plenty of precision for whatever you're doing.

---
Tags: opengl, frame-buffer, format
---