title: XNA Inheritence via Texture2D

text:
# Question
Title: XNA Inheritence via Texture2D
As you know to draw a Texture2D mostly an Origin, scale-factor, rotation-value and color is necessary.

To inherite a new class ATexture2D from Texture2D with adding this parameters, can cause performance problems if many of them are called ?

Or what is prefered to do it in this case.

I ask this question for 2D games, where many texture2D objects are used, updated and drawn.

# Answer
> 2 votes
There's pretty much only one reason you *can't* reasonably do this, and that is that you generally get your textures from either `Content.Load<Texture2D>` or `Texture2D.FromStream`.

Both of these methods return `Texture2D`. To get a child class involves either an expensive copy operation, or overcomplicated changes to the content pipeline to get it to return your child class instead.

If this were not the case, then a child class wouldn't be unreasonable. Object composition (as suggested in both Roy T and Blau's answers) is a good alternative.

In fact, object composition can be better. It allows you to share a single texture between many sprite objects (something you can't do easily with inheritance). This is useful for, for example, having different sprite objects refer to individual sprites that are on a single texture atlas.

---

Although, in the majority of cases you will find that you have either:

* Standard defaults: scale of 1, a rotation of 0, a colour of White, and an origin at some fixed point, like the top left (`Vector2.Zero`) or centre (`new Vector2(tex.Width/2, tex.Height/2)`)
* Code-derived values. For example: you might animate the rotation of your player sprite, or the scale and opacity of an explosion sprite. (Or have a fixed colour per-team, for example.)

Or some combination of the above two. And in these cases you should pass either the constant or the result of your animation calculation directly to `SpriteBatch.Draw`.

It's quite unusual to have many different, fixed-per-sprite values for rotation, scale and colour. A better argument could be made for storing per-sprite source-rectangle and origin, though (useful for a texture atlas).

# Answer
> 1 votes
You will need to store scale, translation and rotation somewhere so memory wise there isn't really a penalty by inheriting from Texture2D and adding this data. I think performance wise the same applies although you do add some extra look ups for methods.

However I would suggest using composition in this case because that makes more sense.

```
class Sprite
{
    Texture2D myTexture;
    Vector2 myPosition;
    float myScale;
    float myTranslation;

    void Draw(); { ... }
}

```

The benefit of this is that you keep your type hyarchy shallower, and conceptualy it makes more sense because adding information on how to draw a texture does not make something a specialization of a texture for which (conceptually) inheritance is intended.

# Answer
> 0 votes
You dont need to inherite from texture2D... I think you are describing a sprite class...

```
 class Sprite
 {
      Texture2D Texture;
      Vector2 Position;
      float Scale;
      float Rotation;
      ....
 }

```

Later you can use this class as base for other components like AnimatedSprite, Enemy, Player, Background, ...

Usually there is no problem with having many sprite objects... but is known that changing too many times the drawed texture can cause a penalty... but is easily solved ordering by texture with SpriteSortMode.Texture in your spritebatch.Begin() method or using testures atlas to avoid using too many textures.

http://msdn.microsoft.com/es-ES/library/microsoft.xna.framework.graphics.spritesortmode(v=xnagamestudio.40).aspx

---
Tags: xna, textures
---


title: Consistency of DirectX models

text:
# Question
Title: Consistency of DirectX models
Is there a way to check the consistency of a DirectX model (.x) ?

Whilst compiling .x files with XNA GameStudio 3.1 compilation is aborted with the following error message:

`Error 2 Could not read the X file. The file is corrupt or invalid. Error code: D3DXFERR_PARSEERROR. C:\WFP\Browser\Content\m.x KiviBrowser`

Some models compile correctly without any error/warning and some abort as described. The files of each model have several thousand lines.

I am creating the files in Googles SketchUp 8 where they all look fine and don't show any sign of corruption.

Suppose I have such a model my XNA compiler won't compile because their is an inconsistency somewhere in the file - how could I identify this in order to correct it ?

# Answer
It's possible the exporter you're using to write the `.X` files out of SketchUp has a bug. There are a few things you can try:

* You could try a different exporter. It looks like there are a few.
* You can try to export the model and then load it up in another modeling tool via some other importer and see if that importer presents any errors (hopefully with a better diagnostic message). Blender may be an option here.
* If you're exporting to the text-based format, you can compare the output file against the specification by hand, especially if your model is small and simple.
* Using the specification, you could in fact write your own validator and try to diagnose the problem yourself that. This would likely be more work, but more useful if your models are complex.
> 2 votes

---
Tags: xna, directx, models
---


# Question
Title: How to create a curve from a set of points that passes through said points?
What is the best way to create a smooth curve path from a set of points? For example:

I've seen Bezier curves before, but those try to smooth out the path from the set of points, like this:

# Answer
> 7 votes
There are multiple types of Splines, Bezier curves are one of them. Beziers aren't required to pass through the points that define them. From the looks of it, you want a regular cubic spline. It will ensure that the line crosses through the points specified. You can find some interactive examples of different types here.

Also, I know you're busy being an 80's guy, but get that boneitis checkout ASAP.

# Answer
> 2 votes
You may want Catmull-Rom splines. They go through every point (unlike Bezier curves, which don't go through the control points).

---
Tags: path-finding, curves
---


# Question
Title: What's wrong with this turn to face algorithm?
I implement a torpedo object that chases a rotating planet. Specifically, it will turn toward the planet each update. Initially my implement was:

```
void move() {
        vector3<float> to_target = target - get_position();
        to_target.normalize();
        position += (to_target * speed);
}

```

which works perfectly for torpedo that is a solid sphere. Now my torpedo is actually a model, which has a forward vector, so using this method looks odd because it doesn't actually turn toward but jump toward. So I revised it a bit to get,

```
double get_rotation_angle(vector3<float> u, vector3<float> v) const {
    u.normalize();
    v.normalize();
    double cosine_theta = u.dot(v);
    // domain of arccosine is [-1, 1]
    if (cosine_theta > 1) {
        cosine_theta = 1;
    }
    if (cosine_theta < -1) {
        cosine_theta = -1;
    }
    return math3d::to_degree(acos(cosine_theta));
}

vector3<float> get_rotation_axis(vector3<float> u, vector3<float> v) const {
    u.normalize();
    v.normalize();
    // fix linear case
    if (u == v || u == -v) {
        v[0] += 0.05;
        v[1] += 0.0;
        v[2] += 0.05;
        v.normalize();
    }
    vector3<float> axis = u.cross(v);
    return axis.normal();
}

void turn_to_face() {
    vector3<float> to_target = (target - position);
    vector3<float> axis = get_rotation_axis(get_forward(), to_target);
    double angle = get_rotation_angle(get_forward(), to_target);
    double distance = math3d::distance(position, target);
    gl_matrix_mode(GL_MODELVIEW);
        gl_push_matrix(); {
        gl_load_identity();
        gl_translate_f(position.get_x(), position.get_y(), position.get_z());
        gl_rotate_f(angle, axis.get_x(), axis.get_y(), axis.get_z());
        gl_get_float_v(GL_MODELVIEW_MATRIX, OM);
    } gl_pop_matrix();
    move();
}

void move() {
    vector3<float> to_target = target - get_position();
    to_target.normalize();
    position += (get_forward() * speed);
}

```

The logic is simple, I find the rotation axis by cross product, the angle to rotate by dot product, then turn toward the target position each update. Unfortunately, it looks extremely odds since the rotation happens too fast that it always turns back and forth. The forward vector for torpedo is from the `ModelView` matrix, the third column `A`:

```
        MODELVIEW MATRIX
--------------------------------------------------
R           U           A           T
--------------------------------------------------
1           0           0           0
0           1           0           0
0           0           1           0
0           0           0           1
--------------------------------------------------

```

Any suggestion or idea would be greatly appreciated.

**EDIT**
In my current implementation, I don't have `forward` vector, the only vector I have is `position`. `OM` is my orientation matrix. In addition, I have my camera call to `glu_look_at` before any object update, that's the reason why I have to store all the transformation of object in `OM` and doing this allow me to check for collision easier. In short,
`vector3<float> get_forward()` : return the third column.
`vector3<float> get_position()` : return the forth column.
`vector3<float> get_up_vector()` : return the 2nd column.

And in my drawing routine,

```
void draw() {
    gl_push_matrix(); {
        // camera is set here ...
        // ...
        gl_mult_matrix_f(OM);
        // draw
    } gl_pop_matrix();
}

```

# Answer
> 2 votes
At the moment it looks like you are setting the rotation of your torpedo (in the modelview matrix) to the wrong angle. The angle you calculated is between the torpedo's facing vector (`forward`) and `to_target`. This is useful in determining how far to turn but for displaying the torpedo with the correct orientation you want the rotation from the identity matrix to `forward`.

## Maintain a Matrix

Instead of re-creating a matrix every time you call `turn_to_face` it might be easier to maintain a matrix which you just translate and rotate each time.

```
matrix44<float> position_and_rotation; // Or whatever class you have.

...

void turn_to_face()
{
    ...

    position_and_rotation.rotate(axis, angle);
    glMultMatrixf(position_and_rotation.data()); // Where data() returns a raw
                                                 // pointer to the underlying
                                                 // data of the matrix.

    ...
}

void move()
{
    position_and_rotation.translate(get_forward() * speed);
}

```

## Rotate Over Time

What I've written above is closer to correct but it's still wrong. It won't turn your torpedo *toward* the planet, it will turn it *directly* to the planet in a single call to `turn_to_face`. To turn it gradually you'll need to define a `rotational_speed`.

```
position_and_rotation.rotate(axis, min(rotational_speed, angle));

```

That'll mean you never turn more than `rotational_speed` during a call to `turn_to_face` and it also stops you from continually over-shooting the correct orientation.

## Minor Stuff

You'll need to make sure you are always actually moving in the direction you are facing. At the moment I can't see anywhere that `forward` is updated.

In `get_rotation_angle` you are normalizing both of the vectors which means that the range of the dot product is already \[-1,1\] (you don't need to manually clamp to that range).

`to_target` in the `move` function and `distance` in the `turn_to_face` function are both unused so get rid of 'em :)

# Answer
> 2 votes
As Gary already mentioned, you need to take the local forward vector of your torpedo into the calculation (not necessarily the 3rd row of the identity matrix, depends on how your model was created). If the local forward vector of the torpedo is different, change it there.

4 things changed in your code:

1. renamed `to_target` to `forward` and introduced `forward_torpedo_local`
2. dont use `gl_load_identity()` here, it messes up your camera settings
3. moved code from `move()` into `turn_to_face()`, since it is just 1 line of code anyway
4. actually move the torpedo before rendering, otherwise rot and pos are out of sync

Here is the code:

```
void turn_to_face() {
    vector3<float> forward_torpedo_local(0.0, 0.0, 1.0);
    vector3<float> forward = (target - position);
    forward.normalize();
    position += (forward * speed);
    vector3<float> axis = get_rotation_axis(forward_torpedo_local, forward);
    double angle = get_rotation_angle(forward_torpedo_local, forward);
    gl_matrix_mode(GL_MODELVIEW);
        gl_push_matrix(); {
        gl_translate_f(position.get_x(), position.get_y(), position.get_z());
        gl_rotate_f(angle, axis.get_x(), axis.get_y(), axis.get_z());
    } gl_pop_matrix();
}

```

You should normalize the vectors before calling get\_rotation\_axis and get\_rotation\_angle, instead of inside those functions, it's less normalizing, but that's just a minor optimization, once it is working.

---
Tags: c++, opengl, algorithm
---


title: Good 2D Platformer Physics

text:
# Question
Title: Good 2D Platformer Physics
I have a basic character controller set up for a 2D platformer with Box2D, and I'm starting to tweak it to try to make it feel good. Physics engines have a lot of knobs to tweak, and it's not clear to me, writing with a physics engine for the first time, which ones I should use. Should jumping apply a force for several ticks? An impulse? Directly set velocity? How do I stop the avatar from sticking to walls without taking away all its friction (or do I take away all the friction, but only in the air)? Should I model the character as a capsule? A box with rounded corners? A box with two wheels? Just one big wheel? I feel like someone must have done this before!

There seem to be very few resources available on the web that are not "baby's first physics", which all cut off where I'm hoping someone has already solved the issues. Most examples of physics engines for platformers have floaty-feeling controls, or in-air jumps, or easily exploitable behavior when temporary penetration is too high, etc.

Some examples of what I mean:

* A short tap of jump jumps a short distance; a long tap jumps higher.
* Short skidding when stopping or reversing directions at high velocity.
* Standing stably on inclines (but maybe sliding down them when ducking).
* Analog speed when using an analog controller.
* All the other things that separate good platformers from bad platformers.
* Dare I suggest, stable moving platforms?

I'm not really looking for "hey, do this." Obviously, the right thing to do is dependent on what I want in the game. But I'm hoping someone somewhere has gone through the possibilities and said "well technique A does feature X well, technique B does Y well, but that doesn't work with C", or has some worked examples beyond "if (key == space) character.impulse(0, 1)"

# Answer
Here is an extremely detailed Sonic The Hedgehog physics guide. I would recommend reading it over, if not actually copying parts of it mostly-verbatim.
> 59 votes

# Answer
It's quite tricky to implement, say, 'Mario-like' physics using a real physics engine.

Last time I tried this, using Chipmunk, I modelled the player as 2 circles - a 'body circle' on top of a 'feet circle'

The 'feet circle' had some friction, was non-bouncy, and fairly small. The 'body circle' was larger and frictionless, to avoid sticking to walls/steep slopes

The object was constrained to not allow rotation - it would just slide around

If the 'feet' are touching something, or were within the last few frames (to allow falling down slopes), the player was considered as on the ground (may have had a surface normal check, too)

It's a while since I looked at the code, but the behaviour was along the lines of:

When on the ground:

* Apply 'additional gravity' (downward force to help with running down slopes)
* Apply ground friction (larger amount of horizontal damping)
* Apply left/right movement force, based on the controls.
* (Scale down the left/right movement force as approaching a maximum run speed)
* If jump is pressed, apply upwards impulse

When in the air:

* Apply air resistance (small amount of horizontal damping)
* Apply regular (or reduced) gravity
* Apply left/right movement force, if you're allowing in-the-air control

You've got to be a bit careful with switching between the two states - remember that when running down a slope, you may leave the ground for a couple of frames - you probably don't want to switch states/disallow jumping at that point

A few other things to watch out for, though... 'jump-up-through' platforms can be hard to implement, and when you start doing fun stuff (moving platforms, rotating worlds, etc), you have to be careful to make sure the player can't get trapped/crushed by any 'animation driven' moving object.
> 25 votes

# Answer
Honestly I don't think using a physics engine is the right approach for something of that size domain with super strict requirements.

Just write it all yourself. You'll get much better results by saying "move character up by x units in this parabola shape when holding down jump button for length y" than by having a bunch of knobs to tweak.
> 18 votes

# Answer
I wrote a series of articles about building a platform game from the ground up using modern technologies and it includes how I handled the simple physics:

http://www.wildbunny.co.uk/blog/2011/12/14/how-to-make-a-2d-platform-game-part-2-collision-detection/

However if you want something more high-tech it's entirely possible to approach this using full a physics engine. Here's a technique you can use (from Little Big Planet) which makes the player character a fully integrated part of the physics engine:

Instead of applying impulses or setting velocities to move the player around as 'external inputs' to the physics engine, you can develop a constraint which controls the character.

So this constraint will have the player's desired speed and direction as an input (from the game) and will model things like the player's maximum strength and speed. The constraint will try to move the player according to its inputs (and obeying the maximums), and because its a constraint it will apply a equal and opposite force on the object the player is standing on, thereby allowing the player to stand on moving platforms and to affect the things he moves over.

Doing things like this means can you have the player totally naturally be able to deal with situations like being under a huge pile of boxes, or jumping across several moving platforms because he is now a core part of the physics engine.

Hope that helps!

Cheers, Paul.
> 10 votes

# Answer
This question has seen significant discussion on the Box2D forums. Reading though the discussions about character movement, jumping, or platformer and you'll come across every possible issue. However, the issue got complicated enough that the collision filtering system was updated and a Test Bed example created solely to show how it should be done.
> 7 votes

---
Tags: box2d, physics, input
---


# Question
Title: DirectX 11 Constant Buffers vs Effect Framework
I'm having some trouble understanding the differences between using constant buffers or using the effect framework of DirectX11 for updating shader constants.

From what I understand they both do exactly the same thing, although from reading the documentation it appears as if using effects is meant to be 'easier'. However they seem the same to me, one uses `VSSetConstantBuffers` and the other `GetConstantBufferByName`.

Is there something I'm missing here?

# Answer
> 5 votes
Effect interface has always been the highest level shader-related interface. Most probably the Effect interface simply abstracts away some of the problems in dealing with constant buffers but it also uses them under the hood.

Whether the API is actually easier could probably be a question of requirements. If you want to build a very simple application, the effect interface might prove itself useful. However, if a more sophisticated engine is what you actually need then the Effect interface could probably even slow down the development and impose restrictions on some of the required optimizations.

# Answer
> 6 votes
The Effects framework is nothing more than a wrapper around the main API, so yes, under the hood it ends up calling VSSetConstantBuffers/etc.

While it's true to say that using Effects can take away some of the hassle of having to get down and dirty with actual cbuffers, for any non-trivial case it's actually an incredibly leaky abstraction in that the reality of cbuffers tends to rear it's ugly head more often than you might like; you have to be conscious and aware that yes, there are actual real-life cbuffers behind the scenes, and you have to be conscious and aware of what the good and bad usage and update patterns are, even despite the abstraction.

While Effects tries to make some best guesses, it's not a mind reader - you know your program better and you know what you intend by your code better, so you're in a better position to organize things properly.

None of this was a big problem in D3D9 where you had standalone constants (although it was also the case even back then that batching constant updates would lead to higher performance); in D3D10 and 11 it's a huge problem, and in many cases it's actually easier to bypass Effects and just use the raw API.

This perhaps is one reason why the use of Effects is heading to deprecation land.

# Answer
> 5 votes
The Effects API gives you an interface where you don't need to worry about constant buffers yourself. (At least, that's the intention.) You can instead work in terms of individual parameters and set their values one at a time. Internally, it's keeping track of the constant buffers and updating them as needed. The shaders still do have constant buffers, but the CPU side of your application doesn't need to know about them. Although you can get access to the constant buffers yourself with `GetConstantBufferByName` etc., you wouldn't normally do so.

However, that does mean that you're incurring a function call and other overhead every single time you set a parameter. Depending on the internals, there might be additional overhead in memory use, extra bus traffic, and so on. As the other answers mentioned, for a high-performance engine it might be preferable to just deal with constant buffers yourself. If you know the layout, you can create a struct in C++ that matches, so setting the parameters is just setting the members of a struct and doing a couple of API calls for the whole thing.

# Answer
> 4 votes
As said above the Effects framework is an additional layer on top which gives you some higher level of abstraction.

It's not deprecated in any way, it's only provided outside the DirectX core, and also in source code form (which means you can see what it does under the hood and tune it to fit your needs).

The biggest disadvantage of it, as mentioned above, is that it's really easy not to use declarative buffers at all and create unoptimized code if you're not careful (you can use separate buffers using effects framework and it's pretty recommended to do so).

This is perfectly valid using effects framework:

```
cbuffer cbPerScene : register( b1 )
{
float4x4 tViewProjection;
};

cbuffer cbPerObject : register( b0 )
{
float4 ambientcolor;
float4 diffusecolor;
float4x4 tWorld;
};

```

When you modify a variable it will mark it's parent buffer as "dirty" , and update accordingly (please note it only updates resource when you Apply Pass, not when you set a variable).

Now some advantages of it.

* Layout validation : It will verify that data you pass between shader stages are compatible (data passed from vertex shader to pixel shader for example). In a production environment it's not too useful, but a design stage it's quite handy.
* Reflection/Semantics : Having the ability to enumerate individual variables and attach semantics to them allows to have some dynamic pipeline, which can be really useful for prototyping (as soon as you recompile your shader you can automatically create gui elements for variables to test it, semantics are commonly used for global settings, for example:

float4x4 tViewProjection : VIEWPROJECTION;

you can detect the semantic and automatically send your camera transform.

So now when you do a lot of draw calls with plenty of different material shaders, it's true that it can introduce some performance hit (even tho in modern dx11 programming Instancing and using Buffers/StructuredBuffers is pretty much the way to go), for other parts like post processing the hit is generally very minimal.

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


# Question
Title: How can I refactor my code to use fewer singletons?
I started a component based, networked game (so far only working on the server). I know why singletons can be bad, but I can't think of another way to implement the same thing. So far I have:

* A GameState singleton (for managing the global state of the game, i.e. pre-game, running, exiting).
* A World singleton, which is the root entity for my entity graph
* An EntityFactory
* A ComponentFactory
* I'm thinking about adding a "MessageDispatcher" so individual components can subscribe to network messages.

The factories do not have state, so I suppose they aren't so bad. However, the others do have global state, which is asking for trouble. How can I refactor my code so it uses fewer singletons?

# Answer
You could turn the EntityFactory and ComponentFactory modules into namespaces, since they don't have state. This will effectively cut the number of singletons in your code by 50% ;). Also, you don't have to make the world entity a singleton. You could make it an entity created from the factory just like all the other entities. Then you could have a game with multiple worlds! But that really depends in what your goal is. If you do manage to go that route though, you'll have been able to reduce your singleton usage by 75%!
> 2 votes

---
Tags: c++, architecture, networking, design-patterns
---


# Question
Title: How to make this game loop deterministic
I am using the following game loop for my pacman clone:

```
long prevTime = System.currentTimeMillis();
        while (running) {
            long curTime = System.currentTimeMillis();
            float frameTime = (curTime - prevTime) / 1000f;
            prevTime = curTime;

            while (frameTime > 0.0f) {
                final float deltaTime = Math.min(frameTime, TIME_STEP);
                update(deltaTime);
                frameTime -= deltaTime;
            }

            repaint();
        }

```

The thing is, I don't always get the same ghost movement every time I run the game (their logic is deterministic), so it must be the game loop. I imagine it's due to the `final float deltaTime = Math.min(frameTime, TIME_STEP);` line. What's the best way of modifying this to perform the exact same way every time I run it? Also, any further improvements I can make?

# Answer
What you need to do is use a fixed time step. http://gafferongames.com/game-physics/fix-your-timestep/ has some more details - it looks like you used the loop from before the 'free the physics' section. What you want is one that only updates with a fixed time step. Here's roughly what you should end up with (without spiral of death handling or interpolation):

```
    while (running) {
        long curTime = System.currentTimeMillis();
        float frameTime = (curTime - prevTime) / 1000f;

        while (frameTime > TIME_STEP) {
            update(TIME_STEP);
            frameTime -= TIME_STEP;
            prevTime = curTime;
        }

        repaint();
    }

```
> 3 votes

---
Tags: java, game-loop, optimization
---


# Question
Title: Passing multiple Vertex Attributes in GLSL 130
(note this question is closely related to this one however I didn't fully understand the accepted answer)

To support videocards in laptops I have to rewrite my GLSL 330 shaders to GLSL 130. I'm trying to do this but somehow I don't get vertex attributes to work properly.

My 330 shaders look like this:

```
#version 330
layout(location = 0) in vec4 position;
layout(location = 3) in vec4 color;

smooth out vec4 theColor;
void main()
{
    gl_Position = position;
    theColor = color;
}

```

Now this explicit layout is not allowed in GLSL 130 so I referenced this page to see what the default layouts for some values would be. As you can see position should be the 0th vertex attribute and color should be the 3rd vertex attribute. Because this is a test case I had already configured my explicit layouts in the same way, which worked, so I now simply rewrote my shader to this and expected it to work:

```
#version 130
smooth out vec4 theColor;
void main()
{
    gl_Position = gl_Vertex;
    theColor = gl_Color;
}

```

However this doesn't work, the value of gl\_Color is always `(1,1,1,1)`. So how should I pass multiple vertex attributes to my GLSL 130 shaders?

For reference, this is how I set my vertex buffer object and attributes (I've just adapted this tutorial to JAVA+JOGL)

```
gl.glBindBuffer(GL3.GL_ARRAY_BUFFER, vertex_buffer_id);
gl.glEnableVertexAttribArray(0);
gl.glEnableVertexAttribArray(3);
gl.glVertexAttribPointer(0, 4 , GL3.GL_FLOAT, false, 0, 0);
gl.glVertexAttribPointer(3, 4, GL3.GL_FLOAT, false, 0, 4*4*4);

gl.glDrawArrays(GL3.GL_TRIANGLE_STRIP, 0, 4);

gl.glDisableVertexAttribArray(0);
gl.glDisableVertexAttribArray(3);

```

**EDIT** I solved the problem by querying for the layout locations of position an color using glGetAttribLocation however I still don't understand why the 'hardcoded' values like gl\_Color didn't work, can't I upload data in there as normal? Shouldn't they be used?

# Answer
gl\_Color is for the deprecated fixed function context. It's set up when you call the glColor\* functions. If you want to set it, you have to use the fixed function pipeline, otherwise gl\_Color will have the default value, which is white opaque.

You used GLSL version 330 which means you should've been using OpenGL version 3.3 which uses the core specification (glColor\* functions are deprecated; GLSL version 330 doesn't have gl\_Color). Your code should be set up for the programmable pipeline with pure shaders (the code you posted is that exactly), which means you can't call glColor\* thus can't set gl\_Color in the shader. **If you want to use the programmable pipeline then you shouldn't be using gl\_Color.**

Post which version of OpenGL you're using for the GLSL 130 version and some code if what i said didn't satisfy the answer.
> 2 votes

# Answer
This:

```
layout(location = 0) in vec4 position;
layout(location = 3) in vec4 color;

```

is simply the nice form of this:

```
//GLSL
in vec4 position;
in vec4 color;

//Program linker
GLuint prog = glCreateProgram();
glBindAttribLocation(prog, 0, "position");
glBindAttribLocation(prog, 3, "color");
...
glLinkProgram(prog);

```

So rather than mucking about with built-in vertex attributes like `gl_Position` and such, just do that. Indeed, you can build up an entire naming convention scheme using `glBindAttribLocation`. The best part is that you can bind *any* name to any location, even if that name *never appears* in your shader. It will simply be ignored by OpenGL.

So you can have a standard set of naming-to-attribute location mappings somewhere that you use for every program. Just apply this mapping as part of your program setup before linking, and you get the behavior you want.

And even better, you can keep doing this even when you work in GLSL 3.30 and `layout(location)` syntax. See, `layout(location)` has precedence, so it overrides any `glBindAttribLocation` calls. So they'll just be ignored.

Most importantly, ***DO NOT USE*** `glGetAttribLocation`. *Always* directly specify your attribute indices, either with `layout(location)` or with `glBindAttribLocation`.

I would have thought the reason for this was obvious (since it's the same reason to use `layout(location)` to begin with). But since some asked...

By specifying attribute locations, you create a convention for your attributes. Positions are always attribute 0. Colors are always attribute 1. Or whatever. You establish a convention and you maintain it.

This now means that when it comes time to load, setup, and render your models, your `glVertexAttribPointer` calls can use the convention ***without*** having to know which program they use. `glVertexAttribPointer` is known for many things; *speed* is not one of them. So you want to make as few calls to it as possible.

This means packing multiple objects in the same buffer(s) and using `glDrawArrays` and/or `glDrawElements[BaseVertex]` to draw different segments of the buffer(s). Each draw call represents an object. But they don't have to use the same program.

If you switch programs without an established attribute convention, now you need to use `glGetAttribLocation` (a function who's performance is unknown) and `glVertexAttribPointer` for each attribute for each object in the buffer. Rather than just doing it once for all of the objects and rendering each one in turn.

Plus, it makes everything cleaner. Your mesh objects can make the necessary `glVertexAttribPointer` calls they need without having to know what program they use. There's no reason why a mesh should need to know what program it will be rendered with.

## The NVIDIA Problem

This somewhat overblown. Indeed, I advise you to ignore pretty much all of the documentation on the "OpenGL SDK" page on OpenGL.org, except for the actual man pages (and even some of those are wrong).

You *cannot* rely on `gl_Position` to have a particular attribute index. Indeed, the OpenGL specification is quite clear that `gl_Position` does not *have* an attribute index. NVIDIA's implementation is in violation of the specification by *giving* it an attribute index that can conflict with user-defined indices. Non-NVIDIA implementations (aka: those that actually follow the specification) don't do this.

But this is an easily avoidable problem. Never use any of the built-in attributes. Then you won't have a problem.
> 7 votes

---
Tags: glsl
---


title: How to Draw texture between 2 Vector3

text:
# Question
Title: How to Draw texture between 2 Vector3
My scenario: RTS combat style, 1 unit fires beam on another unit

My problem is i want to draw a flat texture between 2 Vector3 points. I have looked at various Billboarding styles but that doesn't give me a proper solution.

I looked at this: http://msdn.microsoft.com/en-us/library/bb464051.aspx

is BasicEffect and DrawPrimitives the correct solution just stretch the texture to the distance between point of origin to target? I used the quad class they used but i found this it seemed to inflexible

So my question to you is how would i go about this sort of problem?

Regards

# Answer
> 2 votes
There are some aspects of billboarding you can use, but not all of it. The beam can either be a model or you can set up a series of 4 vertices and update it each frame and use `DrawPrimitives` if you want.

I've done it by using a model of a Plane (4 vertices) and stretching and orienting(partial billboarding) its matrix to cause the beam to display properly.

Mostly it's about building an orthogonal matrix to transform the beam vertices properly.

Here's a video of the way I did a similar thing for someone who asked a similar question. If you want the source code, email me. http://www.screencast.com/t/LDzD2NXOZ

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


# Question
Title: How to implement the light trails for a tron game?
Well I was creating a TRON style game, but had an issue with creating the actual light trails for the game. What I'm doing currently is I have an array the same size as my window in pixel size, implemented like this:

```
int* collision[800][600];

```

Then when the bike goes on a certain pixel, it is marked with a `1` for traveled on. However what is the most efficient way to create a working light trail display?

I tried to do something like this:

```
int i, j;
for(i=0; i<800; i++)
    for(j=0; j<600; j++)
        if(*collision[i][j] == 1)
            Image::applySurface(i, j, trailSurface, gameScreen);

```

But it isn't working properly? It just fills the whole screen with a sprite instead. Whats a better/faster/working way to do this?

# Answer
> 1 votes
You don't need to keep track of each and every pixel.

Just create a class like this

```
class MyTrail
{
    int x;
    int y;
    public MyTrail(int x, int y)
    {
        this.x = x;
        this.y = y;
    }
    public void Draw()
    {
        //code to draw a pixel at (x, y)
    }
}

```

Then create its instance at each and every pixel your bike passes. Through this, you will have a OO way of doing this. This benefits in a way that you will also have control over the trail. Suppose you may want to have timer after which the trail should disappear; Or you may want its color to fade with time. You can include additional members like this

```
class MyTrail
{
    int x;
    int y;
    int life;
    Color color;
    public MyTrail(int x, int y)
    {
        this.x = x;
        this.y = y;
        this.life = 3000;   //3000ms = 3seconds
        this.color = Color.Blue;  //(R, G, B) = (0, 0, 255)
    }
    public void Draw()
    {
        if(life > 0)
        {
            //code to draw a pixel at (x, y)
        }
    }
    public void Update()
    {
        //Lets say Update is called after 16ms
        //decrement the time
        life -= 16;   //depends upon frequency of method call
        //update the color with respect to time
        color.B -= 16;    //depends on your implementation
    }
}

```

# Answer
> 2 votes
The first thing that comes to my mind is to create a list of points. Add a point to the list at the start, then each time the bike makes a turn. Then simply draw a line between those points plus the bike position at the end. This way you'll have easy time doing collision aswell. Trying to do this pixel by pixel seems like just a massive waste of resources.

# Answer
> 2 votes
For trails, my objects usually have an X/Y structure (such as a Vector2 in XNA) stored in an array of 100 members or so. Element 0 is the current position, with each subsequent value being the previous step. This is a quick and dirty method, and isn't very efficient however, especially if you start to move the elements around.

You might be able to use a queue to easily push data, and pop it when the position structure expires. The answer by Shashwat seems the most robust, as it you can extend it in many ways, including giving them timers.

# Answer
> 1 votes
If I read this correctly, you're drawing a sprite at every pixel that is marked as collided with. However, you might not even need to keep record of which pixels or blocks have been collided with. Can you use offscreen render targets? Because if so, you could just draw the sprite at the position of the object making the light trail and not clear the surface. That would produce a smearing effect which is, in this case, what you want.

Pseudocode:

```
render to canvas()
  draw sprite(vehicle.x, vehicle.y)
end()

draw canvas(0, 0)

```

Update: collision detection! (in Lua, untested)

```
 --collision on right side of box
for i = box1.y, box1.y + box1.height do
    if box1.x + box1.width > box2.x and box1.x + box1.width < box2.x + box2.width and i > box2.y and i < box2.y + box2.height then
        --there is a collision!
    end
end

```

And then you just do a similar block of code for each side of the block.

# Answer
> 1 votes
I'm not sure if it's applicable in your case, but back in the old days people used a very simple method. they just didn't clear the screen for each frame draw. or in the case they want to distinguish body and head, they used to draw head and only the first body part after head. again not clearing render surface at when render function begins.

---
Tags: game-mechanics, sdl
---


title: Migration from XNA to SharpDX

text:
# Question
Title: Migration from XNA to SharpDX
My fear is that XNA has reached the end of the road. To keep up with the latest technology a shift to another game framework might be needed. We have many games in a large codebase, all based on XNA. My question is, how much work would it be to migrate to SharpDX and are there other possibilities?

Our code base mainly uses basic 3D rendering and the SpriteBatch, no fancy shader stuff.

Update:

I should have mentioned we only use 2.5D, we have a simple engine that builds textured quads to render text and animated sprites. Also for sound we use XACT (what else..) with some effects.

# Answer
> 6 votes
As catflier mentionned, moving from a "high level" framework like XNA to a low level Direct3D11 API would require quite some work in order to achieve the same results. But there are now some options that you could also consider:

* Use new SharpDX.Toolkit, which is basically a XNA like API on top of Direct3D11 API, running on Windows Desktop, WinRT and WP8. The goal of this toolkit is to provide a high level API for DirectX and Windows only platforms (not strictly compatible with XNA, as we want also to have access to latest Direct3D11 features). It has the famous BasicEffect, SpriteBatch, SpriteFont, an effect framework, a content manager, a game class infrastructure (almost identical to XNA Game class). But there is still no Model/Mesh rendering and no input/audio API. Concerning XACT support you could probably use SharpDX.XACT, though I would try to not leverage any more on this library, as It is completely deprecated. Because SharpDX is AnyCpu, It can run on any Windows x86/x64 easily , and using the toolkit, you don't need to install anything (no DirectX runtime, no C++ runtime).
* Use MonoGame, which is using SharpDX under the hood on Windows and more targeted to be fully compatible with XNA, cross-platform, and allows you to reuse your existing content pipeline, assets, and port easily existing XNA game. I don't remember if they have a pure Windows version (they have a WinRT), but if not, they should be able to provide one soon.

# Answer
> 3 votes
There's a few options, since you mention SharpDX i guess you want to stay in c#.

If you move to SlimDX/SharpDX, there's few things to take into consideration (which are also DirectX related)

From DirectX10+, you have no more fixed function, so you will need to create shaders for your rendering.

Also there's not really any proper built in model loader, so you will need to create your own importer (or use another one, in my case I wrapped Assimp into a managed assembly).

Resources use the concept of views (you you never bind a resource directly to the pipeline, you need to create the appropriate view for it and bind that view).

There's no more SpriteBatch either, but it should be trivial to reimplement it in a way that suit your needs.

Text support can be a bit of a pain (if using dx11, in case of dx10/dx10.1 it's ok)

So that's some of the changes you'll need to make, but on the good side, you'll have access to later hardware API, with all the goodies that goes with it (StructuredBuffers are awesome, instancing is much nicer than in xna, you can use compute shaders...).

Hope that helps

---
Tags: xna-4.0, sharpdx
---


# Question
Title: Unable to Call Instantiate in Class Member Function
The following javascript is attached to a gameObject.

```
var instance : GameObject;

class eg_class   {
    function eg_func(){
       var thePrefab : GameObject;
        instance = Instantiate(thePrefab);
    }
}

```

Error,

> Unknown identifier: 'instance'.
> Unknown identifier: 'Instantiate'.

Questions,

1) Why is it that "instance" cannot be accessed within a class? Isn't it supposed to be a public variable?
2) "Instantiate" function works in Start()/Update() root functions. Is there a way to make it work from within member functions?

Thanks in advance!

# Answer
> 1 votes
You have a couple of things in your code backward. This is how it should be:

```
var thePrefab : GameObject;

class eg_class   {
    function eg_func(){
        var instance : GameObject;
        instance = Instantiate(thePrefab,transform.position,transform.rotation);
    }
}

```

---
Tags: unity
---


title: Pygame Import Error, Python 3.2

text:
# Question
Title: Pygame Import Error, Python 3.2
I'm having an issue with the Pygame module. I run Python 3.2 and installed the respective Pygame file, but now when I try to import it in the IDLE, it gives me this error:

```
>>> import pygame
Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    import pygame
  File "C:\Python32\lib\site-packages\pygame\__init__.py", line 95, in <module>
    from pygame.base import *
ImportError: DLL load failed: %1 is not a valid Win32 application.

```

Any help will be appreciated.

# Answer
> 1 votes
According to this question about the same error, the issue is likely that you have a 64-bit version of Python installed, and a 32-bit version of Pygame. I don't think Pygame has any 64-bit versions available, so to fix your problem you will have to download a 32-bit version of Python.

---
Tags: python, pygame
---


# Question
Title: Game has noticeable frame drops but when through a profiler it always runs smooth
I'm trying to optimize my PC game but I can find the bottleneck since every time I run it through a profiler (gDEBugger) it runs smooths. When running outside gDEBugger I get these annoying hiccups. It's not just the graphics, the sound also gets choppy. The drops are inconsistent across runs, i.e, sometimes I run the same scenario and get no drops at all, sometimes I get a few drops, and others the game is consistently slow. The only constant is: when running through gDEBugger I ALWAYS get a smooth run.

I'm suspecting something outside my game is interfering and causing these drops, but what in the hell does gDEBugger do that nullifies these drops? A higher process priority? Any ideas?

Thanks in advance.

# Answer
This question might be too general to give an answer that fixes your problem.

Before using profilers I would recommend adding 1) Lots of tracing statements to your program and 2) ability to turn on/off features at runtime (including tracing but also things such as textures, culling, using very simple meshes, etc). I've found doing these 2 makes it much easier to pinpoint performance problems in my games.

That being said, you do have other options depending on your target platform. Since the problem might be environmental and assuming you are targeting Windows (big assumption I know) you might find using xperf valuable.

xperf is a system level profiler that will tell you everything that is happening in your computer and has a low impact on the programs that are running. Bruce Dawson's blog has a lot of very good tutorials and examples (such as finding performance problems in random programs such as Powerpoint or backup drive ). One trick he mentions is having xperf running all the time in a circular buffer so that as soon as you are able to repro the problem you will have a snapshot of everything that was happening in the machine.
> 6 votes

# Answer
Does the same thing happen on other machines or just your dev box? Once I took a break from developing a game and when I came back to it I noticed it was strangely slow, I just updated my graphics driver and it magically sped up, why it was slow in the first place I have no idea.
> 1 votes

---
Tags: c++, opengl, optimization, profiling
---


title: Inter Quake Model IQM render Directx9

text:
# Question
Title: Inter Quake Model IQM render Directx9
I'm trying to render an Inter Quake Model(http://lee.fov120.com/iqm/) in DirectX9 that I exported from blender.

I want to display animations which IQM supports and my model format does not.

The model is a cylinder.

It loads fine in the iqm sdk opengl viewer but when i try to render it in directx9 using for example(this is just to render the vertices):

```
IDirect3DDevice9 * device;
HRESULT hr = S_OK;

for(int i = 0; i < nummeshes; i++)
{
    iqmmesh &m = meshes[0];

    hr = device->DrawIndexedPrimitiveUP(D3DPT_TRIANGLELIST, 0,
    3*m.num_triangles, m.num_triangles ,&tris[m.first_triangle] ,D3DFMT_INDEX32
    ,inposition ,sizeof(unsigned int));
}

```

It renders like this:

Incorrect

The light grey bit that looks like two triangles in the middle is what is rendered(ignore the other stuff).

Whereas it is meant to look like this(using a custom importer which I designed which matches what is displayed in blender):

Correct

Anyone have any suggestions on what might be going wrong?

# Answer
> 1 votes
The last parameter of your DIP call is wrong - it should be the size of your vertex struct, which - for position only - is going to be 3 floats.

---
Tags: opengl, rendering, blender, directx9
---


title: How to add a ramp in a flash game?

text:
# Question
Title: How to add a ramp in a flash game?
I am a huge novice and this isn't really a programming question, but here I go, say I want to make a game that involves rolling up a ramp like this one:

to move upwards, similar to how it would work in an old Sonic the Hedgehog game or something, how would I go about doing that, where could I find a good recourse to learn this?

# Answer
> 3 votes
first off not to descurage you or anything, but collison detection and response is quite math intensive, but luckily there are some good resourses and frameworks that can help out with this. if you are just looking for a quick fix a toolkit or library is your best bet, otherwise if you want to write it from scratch it is quite complex, but there are some good resources out there.

the Colision detection toolkit is a good one: http://code.google.com/p/collisiondetectionkit/

anther good framework is box2D, but it is a bit more involved, because it requires everything to be set up in a very specific way, but the advantage is, there is a lot of good documentation and less math involved. : "http://box2dflash.sourceforge.net/" (I can only post two links because I'm somewhat new to the site, so I had to quote the URL... sorry)

if you would like to learn about the way collision detection works here is a pretty good tutorial on the subject: http://www.metanetsoftware.com/technique/tutorialA.html

the basic idea in making a ramp like this work in a game, is you need to figure out if your two objects are intersecting... if so you need to determine the amount they are intersecting and find a the vector orthogonal(aka perpendicular) to the surface of the ramp, to push your player or object out of, so it does not intersect... this process is checked every frame or so to make sure the object does not go inside the other object.

# Answer
> 1 votes
Here is a good resource for sonic-like tile collisions/interactions http://info.sonicretro.org/SPG:Solid\_Tiles

---
Tags: flash, actionscript-3
---


# Question
Title: 2D OBB collision detection, resolving collisions?
I currently use OBBs and I have a vehicle that is a rigid body and some buildings.

Here is my update()

```
private void update()
{

    camera.setPosition((vehicle.getPosition().x * camera.getScale()) - ((getWidth() ) / 2.0f),
            (vehicle.getPosition().y * camera.getScale()) - ((getHeight() ) / 2.0f));

    //camera.move(input.getAnalogStick().getStickValueX() * 15.0f, input.getAnalogStick().getStickValueY() * 15.0f);
    if(input.isPressed(ControlButton.BUTTON_GAS))
    {
        vehicle.setThrottle(1.0f, false);
    }

    if(input.isPressed(ControlButton.BUTTON_BRAKE))
    {
        vehicle.setBrakes(1.0f);
    }

    vehicle.setSteering(input.getAnalogStick().getStickValueX());

    vehicle.update(16.6666f / 1000.0f);

    ArrayList<Building> buildings = city.getBuildings();
    for(Building b : buildings)
    {
        if(vehicle.getRect().overlaps(b.getRect()))
        {
            vehicle.update(-17.0f / 1000.0f);
            break;
        }
    }
}

```

The collision detection works well. What doesn't is how they are dealt with.

My goal is simple. If the vehicle hits a building, it should stop, and never go into the building. When I apply negative torque to reverse the car should not feel buggy and move away from the building. I don't want this to look buggy.

This is my rigid body class:

```
class RigidBody extends Entity
{
  //linear
  private Vector2D velocity = new Vector2D();
  private Vector2D forces = new Vector2D();
  private float mass;

  //angular
  private float angularVelocity;
  private float torque;
  private float inertia;

  //graphical
  private Vector2D halfSize = new Vector2D();
  private Bitmap image;

  public RigidBody()
  {
      //set these defaults so we don't get divide by zeros
      mass = 1.0f;
      inertia = 1.0f;
  }

  //intialize out parameters
  public void initialize(Vector2D halfSize, float mass, Bitmap bitmap)
  {
      //store physical parameters
      this.halfSize = halfSize;
      this.mass = mass;
      image = bitmap;
      inertia = (1.0f / 20.0f) * (halfSize.x * halfSize.x) * (halfSize.y * halfSize.y) * mass;

      RectF rect = new RectF();
      float scalar = 10.0f;
      rect.left = (int)-halfSize.x * scalar;
      rect.top = (int)-halfSize.y * scalar;

      rect.right = rect.left + (int)(halfSize.x * 2.0f * scalar);
      rect.bottom = rect.top + (int)(halfSize.y * 2.0f * scalar);
      setRect(rect);
  }

  public void setLocation(Vector2D position, float angle)
  {
      getRect().set(position, getWidth(), getHeight(), angle);
  }

  public Vector2D getPosition()
  {
      return getRect().getCenter();
  }

  @Override
  public void update(float timeStep)
  {
      //integrate physics
      //linear
      Vector2D acceleration = Vector2D.scalarDivide(forces, mass);
      velocity = Vector2D.add(velocity, Vector2D.scalarMultiply(acceleration, timeStep));
      Vector2D c = getRect().getCenter();
      c = Vector2D.add(getRect().getCenter(), Vector2D.scalarMultiply(velocity , timeStep));
      setCenter(c.x, c.y);
      forces = new Vector2D(0,0); //clear forces

      //angular
      float angAcc = torque / inertia;
      angularVelocity += angAcc * timeStep;
      setAngle(getAngle() +  angularVelocity * timeStep);
      torque = 0; //clear torque
  }

  //take a relative Vector2D and make it a world Vector2D
  public Vector2D relativeToWorld(Vector2D relative)
  {
      Matrix mat = new Matrix();
      float[] Vector2Ds = new float[2];

      Vector2Ds[0] = relative.x;
      Vector2Ds[1] = relative.y;

      mat.postRotate(JMath.radToDeg(getAngle()));
      mat.mapVectors(Vector2Ds);

      return new Vector2D(Vector2Ds[0], Vector2Ds[1]);
  }

  //take a world Vector2D and make it a relative Vector2D
  public Vector2D worldToRelative(Vector2D world)
  {
      Matrix mat = new Matrix();
      float[] Vectors = new float[2];

      Vectors[0] = world.x;
      Vectors[1] = world.y;

      mat.postRotate(JMath.radToDeg(-getAngle()));
      mat.mapVectors(Vectors);

      return new Vector2D(Vectors[0], Vectors[1]);
  }

  //velocity of a point on body
  public Vector2D pointVelocity(Vector2D worldOffset)
  {
      Vector2D tangent = new Vector2D(-worldOffset.y, worldOffset.x);
      return Vector2D.add( Vector2D.scalarMultiply(tangent, angularVelocity) , velocity);
  }

  public void applyForce(Vector2D worldForce, Vector2D worldOffset)
  {
      //add linear force
      forces = Vector2D.add(forces ,worldForce);
      //add associated torque
      torque += Vector2D.cross(worldOffset, worldForce);
  }

  @Override
  public void draw( GraphicsContext c)
  {
      c.drawRotatedScaledBitmap(image, getPosition().x, getPosition().y,
              getWidth(), getHeight(), getAngle());
  }

}

```

Essentially, when any rigid body hits a building it should exhibit the same behavior.

How is collision solving usually done?

Thanks

# Answer
> 3 votes
I wrote an article a while back about the basics of 2D collision detection, which covers circles, AABBs, OBBs and polygons moving linearly and rotating.

Collision detection for dummies.

It should give you some pointers :)

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


# Question
Title: Where to start learning OpenGL with C++?
> **Possible Duplicate:**
> What are some good learning resources for OpenGL?

I have learnt C++ and made some cool text based games and such but I would love to start graphical programming. I'm a decent artist (I will have some of my work below) I know the basics of C++ but I really would like to get into OpenGL.

I need someone to show me some good tutorials for OpenGL with C++ so I can really get into game development. My goal is to be able to program a simple 2D game by the end of the year and I have lots of time to do so. I'm en-rolled in a game development course next year and really need some help with starting off.

# Answer
**Pure Basics (for Latest/Modern OpenGL/OpenGL 3D Graphics Programming)**

**Online Resources (for Latest/Modern OpenGL/OpenGL 3D Graphics Programming)**

**Basics Examples (from http://en.wikibooks.org/wiki/OpenGL\_Programming)**

**Intermediate Examples (from http://en.wikibooks.org/wiki/OpenGL\_Programming)**

**Other samples**

**Community Resources**
> 21 votes

# Answer
There is a free book, released this year, called "Learning Modern 3D Graphics Programming" which I saw John Carmack (from ID/DOOM fame) recommend. You can browse it here https://learnopengl.com/arcsynthesis.pdf I've been going through it myself to learn more about the 'proper' way to do things in OpenGL. Now I realize this is in C, not C++. But since OpenGL is mostly a C API its best to learn it this way and then later encapsulate it in objects later if you want to and of course all the C code works perfectly fine in C++.

As for other tutorials and books. There are a lot of old ones out there which learn you a lot of bad practices (that used to be good practices). Shun away from anything that is using the fixed pipeline functions like `glVertex`, `glColor`, the matrix stack, the gluPerspective and gluLookAT functions. These are all depricated and outdated. Try to write as clean as possible OpenGL 3.
> 4 votes

---
Tags: opengl, c++, game-design
---


# Question
Title: How can I make an infinite cave using stage3d?
I want to make an infinite cave in my 3d game using flash stage3d. But I got no idea about how to build that cave. Can anyone can give me some solution or hint?
update: I've tried agal fragment shader like squeae tunnel in shadertoy

code:

```
var fragmentProgramCode:String =
                AGALUtils.build()
                .mov("ft0","v0")
                .div("ft1","ft0.xy","fc3.xy")
                .mul("ft2","fc6.x","ft1")
                .sub("ft3","ft2","fc5.x")//vec2 p = -1.0 + 2.0 * gl_FragCoord.xy / resolution.xy;
                .mul("ft1","ft3.x","ft3.x")
                .mul("ft2","ft3.y","ft3.y")
                .pow("ft4","ft1","fc6.z")//float r = pow( pow(p.x*p.x,16.0) + pow(p.y*p.y,16.0), 1.0/32.0 );
                .pow("ft5","ft2","fc6.z")
                .add("ft1","ft4","ft5")
                .pow("ft4","ft1","fc6.w")
                .mov("ft5","fc5")//uv
                .sub("ft1","fc7.x","ft4")
                .add("ft5.x","fc7.x","ft1")//uv.x = .5*time + 0.5/r;
                .mov("ft6","fc0")//for atan
                .atan2("ft5.y","ft3.y","ft3.x",new <String>["fc7.y","fc5.x","fc7.z","fc7.w","fc8.x","fc8.y","fc8.z","fc8.w","fc9.x","fc9.y"],"ft6")
                .tex("ft0","ft5","fs0","repeat","linear","nomip")//tex
                .mul("ft1","ft4","ft4")
                .mul("ft2","ft1","ft4")//r*r*r
                .mul("ft1","ft0.xyz","ft2")
                .mov("ft0.w","fc5.x")
                .mov("oc","ft1").toString()

```

it can only apply one material,but my project requires different types of material (like floor,ceilling). so ,I create a 3d model Is there anyway to make that 3d model render like "infinity cave"? use agal to make each side of cave's texture move? thanks for your help

update again:

```
I tried glsl to make a cube,when using color It looks good,but when I don't know how to apply texture's transform. It's really hard for me to accomplish this,haven't 3d experience before,thanks for your time !

#ifdef GL_ES
precision highp float;
#endif

uniform vec2 resolution;
uniform float time;
uniform sampler2D tex0;
uniform sampler2D tex1;
uniform sampler2D tex2;
uniform sampler2D tex3;

vec4 p1 = vec4(0.0, 1.0, 0.0, 1.3);//down
vec4 p2 = vec4(0.0, - 1.0, 0.0, 1.3);//up
vec4 p3 = vec4(1.0, 0.0, 0.0, 1.3);//left
vec4 p4 = vec4(-1.0, 0.0, 0.0, 1.3);//right
vec4 p5 = vec4(0.0, 0.0, 1.0, 1.3);//center

void main(){
 vec2 uv = -1.0 + 2.0*gl_FragCoord.xy/resolution.xy;
 uv.x *= resolution.x/resolution.y;
 vec3 o = vec3(0.0, 0.0, 2.3);
 vec3 rd = normalize(vec3(uv, -1.0));
 vec3 lp = vec3(sin(time), sin(time), cos(time));
 float li = 2.0;
 vec3 co;

 float tm = 10000.0;
 float t=- (dot(p1.xyz, o)+p1.w)/dot(p1.xyz,rd);
 if(t>0.0&&t<tm){
   co =vec3(.2);//down
   tm=t;
 }
 t=- (dot(p2.xyz, o)+p2.w)/dot(p2.xyz,rd);
 if (t>0.0&&t<tm){
   co =vec3(.3);//top
   tm = t;
 }
 t=- (dot(p3.xyz, o)+p3.w)/dot(p3.xyz,rd);
 if (t>0.0&&t<tm){
    co =vec3(.4);//left
    tm = t;
 }
 t=- (dot(p4.xyz, o)+p4.w)/dot(p4.xyz,rd);
 if (t>0.0&&t<tm){
    co =vec3(.5);//right

    tm = t;
 }
 t=- (dot(p5.xyz, o)+p5.w)/dot(p5.xyz,rd);
 if (t>0.0&&t<tm){
     co =vec3(.6); //center
     tm=t;
 }
 gl_FragColor = vec4(co, 1.0);
}

```

# Answer
altering the code you've pasted in Shader Toy I've reached something acceptable:

```
#ifdef GL_ES
precision highp float;
#endif

uniform vec2 resolution;
uniform float time;
uniform sampler2D tex0;
uniform sampler2D tex1;
uniform sampler2D tex2;
uniform sampler2D tex3;

void main(void)
{
    vec2 p = -1.0 + 2.0 * gl_FragCoord.xy / resolution.xy;
    vec2 uv;

    float r = pow( pow(p.x*p.x,32.0) + pow(p.y*p.y,32.0), 1.0/.0 );
    uv.x = .5*time + 0.5/r;
    uv.y = 2.0*atan(p.y,p.x)/3.1416+2.5;
    vec3 col0 = texture2D(tex0,uv).xyz;
    vec3 col1 = texture2D(tex1,uv).xyz;
    vec3 col2 = texture2D(tex2,uv).xyz;
    vec3 col3 = texture2D(tex3,uv).xyz;
    vec3 col  = vec3(0);
    col += (step (4.0,uv.y) + step(uv.y,1.0)) * col0;
    col += step (1.0,uv.y) * step(uv.y,2.0) * col1;
    col += step (2.0,uv.y) * step(uv.y,3.0) * col2;
    col += step (3.0,uv.y) * step(uv.y,4.0) * col3;
    gl_FragColor = vec4(col*r*r*r,1.0);
}

```

this code uses all 4 texture slots so if you want to see the results in shader toy you need to fill all 4 texture units there, here are the textures I used:

```
unit 0 : http://www.iquilezles.org/apps/shadertoy/presets/tex0.jpg
unit 1 : http://www.iquilezles.org/apps/shadertoy/presets/tex1.jpg
unit 2 : http://www.iquilezles.org/apps/shadertoy/presets/tex2.jpg
unit 3 : http://www.iquilezles.org/apps/shadertoy/presets/tex3.jpg

```
> 1 votes

---
Tags: actionscript, stage3d
---


# Question
Title: how to make a continuous machine gun sound-effect
I am trying to make an entity fire one or more machine-guns.

For each gun I store the time between shots (1.0 / firing rate) and the time since the last shot.

Also I've loaded ~10 different gun-shot sound-effects.

Now, for each gun I do the following:

```
function update(deltatime):
    timeSinceLastShot += deltatime

    if timeSinceLastShot >= timeBetweenShots + verySmallRandomValue():
        timeSinceLastShot -= timeBetweenShots

        if gunIsFiring:
            displayMuzzleFlash()
            spawnBullet()
            selectRandomSound().play()

```

But now I often get a crackling noise (which I assume is when two or more guns are firing at the same time and confuse the sound-device).

My question is whether

A) This a common problem and there is a well-known solution, maybe to do with the channels or something, or

B) I am using a completely wrong approach to the task. I had a look at some sound-assets for other games and they used complete burst with multiple shots. I suppose I could try that, but I would like to have organic little hickups in the gun-fire (that's what the random value is for) to make the game more gritty and dirty.

I am using Panda3D, but I had the exact same problem in PyGame and SDL.

\[edit\]

Thanks a lot for the answers so far! One more problem with faking it though: Now how do I stop the sound? Let's say I have an effect with 5 bangs...

```
*bang* *bang* *bang* *bang* *bang*

```

And I magically manage to loop it so that there's no gap or overlap if the player fires more than 5 shots. Now, what do I do if the player stops firing halfway through the third *bang*? How do I know how long to keep playing the sample so that the third *bang* is completed and I can start playing the rumbling echo of the last shot?

Of course I can look up the shot/pause timing of that sound-sample and code accordingly, but it feels extremely hacky.

# Answer
A) Yes, fake it

Don't synchronize each bullet with a single shot sound. Rather play one sound having multiple shots in it as long as you are shooting. As long as your damage and impact effects code is setup properly nobody is gonna see any difference.
> 3 votes

---
Tags: sound-effects, panda3d
---


# Question
Title: How can I store spell & items using a std::vector implementation?
I'm following along with a book from GameInstitute right now, and it's asking me to:

> Allow the player to buy and carry healing potions and potions of fireball. You can add an Item array (after you define the item class) to the Player class for storing them, or use a std::vector to store them.

I think I would like to use the `std::vector` implementation, because that seems to confuse me less than making an item class, but I am unsure how to do so. I've heard from many people that vectors are great ways to store dynamic values (such as items, weapons, etc), but I've not seen it used.

# Answer
`std::vector` is a fine way to store "dynamic" (as you call them) things like items, but the real benefit of the vector is not that the thing you are storing can change, but that the *number of items in the vector* can change without minimal effort on your part. To illustrate, were you to have store your `Item` objects as an array, you'd have to fix the size of the array at compile-time (`Item items[SIZE];`), which means you have a fixed upper limit on items (among other issues, which aren't as relevant to this specific subject and so I will skip over them).

You could also dynamically-allocate the array at runtime (`Item * items = new Item[SIZE];`) which would let you resize the array later by allocating new storage, copying the items over, and deleting the old storage. This, however, is a lot more work for you to do.

Fortunately, that's what `std::vector` does for you -- it is a dynamically-sized array implementation, essentially, and handles the memory management for growing the array beyond its current capacity for you. It's definitely the option I'd suggest you pursue for now -- but note that you'll still want to create an `Item` class.

It's very easy to use:

```
// Create an item list and two item objects to add to it.
std::vector<Item> items;
Item fireballPotion("Potion of Fireball");
Item healingPotion("Potion of Healing");

// Add the items:
items.push_back(fireballPotion);
items.push_back(healingPotion);

// operator[] is supported for accessing items.
// This will print "Potion of Fireball" for example:
std::cout << items[0].GetName();

```

The MSDN documentation for the `vector` class is probably worth a read, and if you aren't familiar with templates -- which is what `vector` uses to allow it to store "anything" -- you should brush up on the basics there as well. Which also leads me to a final point: while it looks like a vector can store anything, it does have constraints for what is allowed in it and these sometimes throw beginners. In particular, the type you store in a vector must be copyable, because the vector will need to make a copy of the objects when resizing its internal storage, for example. C++'s rule of three is something to keep in mind here.
> 13 votes

---
Tags: c++, text-based
---


# Question
Title: XNA + Windows Forms: How make them work together without making the trick of the custom GraphicsDeviceControl?
What I've found is a solution where you have to code a custom GraphicsDeviceControl to put inside the form (the well known tutorial from the APPHub), but that's **not** what I'm searching for.

I would like to say that before start to write my question here, I "googled" a lot and I saw some questions here, but I couldn't find what I'm looking for.

I would like to have the Draw/Update loops completly managed by XNAFrameWork (with XNA project and so), and not by a custom component.

I hope you understand what I asked.

Thanks in advance.

**Edit**

What's the most important thing for me and wasn't shown in the tutorial of APPHub is: where I have to put the input handling? That's one the problems that wasn't covered by the tutorial.

# Answer
> 4 votes
What I learned to do was to start your main project as usual with a Windows Game (4.0) then add your winform.

Create a field to hold a reference to the Game1 class inside the form1 class

`Game1 gameEntry`;

Set the modifier on your pictureBox to public.

In Program.cs : replace everything in static void Main()

```
Form1 form = new Form1();
form.show();
// This line creates a Game1 object in the gameEntry field created earlier.
form.gameEntry = new Game1(form.pictureBox1.Handle, form, form.pictureBox1);
form.gameEntry.Run();

```

**OR:**

```
using (Form1 editorForm = new Form1())
{
    editorForm.Show();
    editorForm.gameEntry = new Game1(editorForm);
    editorForm.gameEntry.Run();
}

```

This means we need to modify the constructor that comes with Game1.

```
System.Windows.Forms.Control gameForm;

public Game1(IntPtr drawingSurface, System.Windows.Forms parentForm, System.Windows.Forms.PictureBox pictureBox)
{
    this.drawingSurface = drawingSurface;
    this.parentForm = parentForm;
    this.pictureBox = pictureBox;

    // prepare graphics event
    graphics.PreparingDeviceSettings +=
new EventHandler<PreparingDeviceSettingsEventArgs>(graphics_PreparingDeviceSettings);

    gameForms = System.Windows.Forms.Control.FromHandle(this.Window.Handle);

    //Tell the mouse it will be getting it's input through the pictureBox
    Mouse.WindowHandle = drawSurface;

}

private void graphics_PreparingDeviceSettings(object sender, PreparingDeviceSettingsEventArgs e)
{
    // Finally attach game1's draw ability to the picture box in winforms.
    e.GraphicsDeviceInformation.PresentationParameters.DeviceWindowHandle = drawSurface;
}

```

At this point you should be able to run the program and will have two windows. You probably don't want the game1 window showing so create an event to hide it.

```
private void gameForm_VisiblilityChanged(object sender, EventArgs e)
{
    if (gameForm.Visible = true)
    gameForm.Visible = false;
}

```

---
Tags: xna, xna-4.0, windows-forms
---


title: How to manage my model

text:
# Question
Title: How to manage my model
I have in my model, a list of Classes : Player, NonPlayerCharacter, Monster, Item, NonMovableItem etc

With AndEngine I've a list of sprite for each piece of my model,

How can I manage the relashionship between my model's classes and the graphical elements, what is the degree of abstaction recommended for my problem?

One sprite for one Model or one Model for one Sprite or n for n

for exemple If I do drag&drop have I to make abstraction of the Sprite Class, another exemple a map is a List of sprite or a list of element of my model?

# Answer
> 1 votes
The Model (collectively) is the actual state of the world. There is one true world state; there can never really be more than one. So yes, use one model which consists of one sub-model for each unique element in the world.

In the real world, the "model" or state for your backyard might state that there are 7 puppies there; no more, and no less -- there is no ambiguity, because there is only one true "state" of your backyard (ignoring quantum mechanics :)

Views are *representations* of the world. A thing can be represented in an infinity of different ways. For instance, your puppies might be represented by nametags which give them each a unique name; they can be represented by photographs of each individual puppy; they could be represented each by their own unique DNA (as an alphanumeric string); or each puppy could even have a unique theme tune associated with it. So you see there are countless means of representation; as many, in fact, as you care to dream up.

A good example of using multiple views for the same part of a model, in a game, is the main world viewport vs. the minimap which many games have. In a minimap, each entity is represented as a small icon (Elder Scrolls) or even a pixel of a particular colour (StarCraft), whereas in the world view they might be 3D models or full sized, animated 2D sprites.

So the number of "views" is determined by looking at how many ways a particular thing needs to be represented, within the bounds of your design. But the relationship between model and view is always 1:n, where n can theoretically be anything from 0 to infinity.

**Feedback from sprite to associated model**

This is usually done through a publish/subscribe model, commonly found as event dispatcher / listener pairs. So when the sprite view object is moused over, clicked or whatever the case may be, it will dispatch an event which will trigger some update in the game logic -- which thus affects the model.

But if you wish to keep things simple, and bend the rules of MVC a bit, you can just give the view a direct reference back to the model. That's not good encapsulation, but it is much simpler / more direct to set up.

---
Tags: java, android, architecture, andengine
---


title: UI mockups to the code

text:
# Question
Title: UI mockups to the code
My UI designer has made a lovely photoshop PSD of the UI and everything pretty. The biggest problem I'm having is converting some of the more elegant fonts used into something renderable in-game. Is there a way to convert these font styles in Photoshop to a bitmap font of some sort?

I need to be able to render text like this inside my code:

# Answer
Okay, you're going to have to forgive me for not giving you specific XNA code, because I'm not knowledgeable in that platform, but what I'm going to tell you should work on any game engine that lets you draw sprites.

Fonts is not your only problem, so I'm going to give you a piece of advice, and then I'm going to answer your question. With these two things, you should be able to make a lovey-dovey relationship with your GUI designer, and you both will be able to very happily make games.

The first thing is that you're going to sit down with your designer, and you're going to ask her to give you two sets of files. The first is a set of transparent files that make up your GUI (optimally in PSD or DXT format). For every button, fixed label, background, border and textbox, you will get one file (you can also do texture atlasing, but I'd recommend you do that after you assemble your GUI, and then adjust your source coordinates when blitting). Non-static text should be left out at this point (I'll revisit this later).

The second thing you will get is the actual GUI design, this time in Photoshop format. For this file, you're going to ask your designer to make the entire GUI design, using *only* the files she previously gave you.

She's then going to put each GUI element into a separate layer, using no effects whatsoever. You're going to tell her to do this pixel perfect, because the locations where she's going to put everything, is where everything will actually be in the finalized game.

Once you get that, for each layer, you're going to press Ctrl-T, and on the Info pane (F8), you will take note of the X and Y coordinates for each element. Make sure your units are set to pixels (Preferences-\>Units & Rulers-\>Units). These are the positions you're going to use when drawing your sprites.

Now, for fonts, as you may clearly know now, you won't be able to get your fonts to look exactly the same way as you see them in Photoshop using text rendering APIs. You're going to have to pre-render your glyphs, and then programatically assemble your texts. There are many ways to do this, and I will mention the one I use.

First thing is to render all your glyphs into one or more files. If you only care about English, one texture for all the glyphs will suffice, but if you want to have a more extended character set, you can use several files. Just make sure all the glyphs you want are available on the font your designer chose.

So, to render the glyphs, you can use the facilities of `System.Drawing` to get the font metrics and draw your glyphs:

```
Color clearColor = Color.Transparent;
Color drawColor = Color.White;
Brush brush = new SolidBrush(drawColor);
TextRenderingHint renderingType = TextRenderingHint.AntiAliasGridFit; // Antialias is fine, but be careful with ClearType, which can blergh your renders when you apply effects
StringFormat stringFormat = StringFormat.GenericTypographic;
string fileNameFormat = "helvetica14_{0}.png";
string mapFileFormat = "helvetica14.txt";
string fontName = "Helvetica";
string fontPath = @"c:\windows\fonts\helvetica.ttf";
float fontSize = 14.3f;
int spacing = 2;

Font font = new Font(fontName, fontSize);
int x = 0;
int y = 0;
int width = 1024; // Force a maximum texture size
int height = 1024;
StringBuilder data = new StringBuilder();
int lineHeight = 0;
int currentPage = 1;
var families = Fonts.GetFontFamilies(fontPath);
List<char> codepoints = new List<char>();
HashSet<char> usedCodepoints = new HashSet<char>();
foreach (FontFamily family in families)
{
    var typefaces = family.GetTypefaces();
    foreach (Typeface typeface in typefaces)
    {
        GlyphTypeface glyph;
        typeface.TryGetGlyphTypeface(out glyph);
        foreach (KeyValuePair<int, ushort> kvp in glyph.CharacterToGlyphMap) // Render all available glyps
        {
            char c = (char)kvp.Key;
            if (!usedCodepoints.Contains(c))
            {
                codepoints.Add(c);
                usedCodepoints.Add(c);
            }
        }
    }
}
Bitmap bitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb);
Graphics g = Graphics.FromImage(bitmap);
g.Clear(clearColor);
g.TextRenderingHint = renderingType;

foreach (char c in codepoints)
{
    string thisChar = c.ToString();
    Size s = g.MeasureString(thisChar, font); // Use this instead of MeasureText()
    if (s.Width > 0)
    {
        s.Width += (spacing * 2);
        s.Height += (spacing * 2);
        if (s.Height > lineHeight)
            lineHeight = s.Height;
        if (x + s.Width >= width)
        {
            x = 0;
            y += lineHeight;
            lineHeight = 0;
            if (y + s.Height >= height)
            {
                y = 0;
                g.Dispose();
                bitmap.Save(string.Format(fileNameFormat, currentPage));
                bitmap.Dispose();
                bitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb);
                g = Graphics.FromImage(bitmap);
                g.Clear(clearColor);
                g.TextRenderingHint = renderingType;
                currentPage++;
            }
        }
        g.DrawString(thisChar, font, brush, new PointF((float)x + spacing, (float)y + spacing), stringFormat);
        data.AppendFormat("{0} {1} {2} {3} {4} {5}\n", (int)c, currentPage, x, y, s.Width, s.Height);
        x += s.Width;
    }
}
g.Dispose();
bitmap.Save(string.Format(fileNameFormat, currentPage));
bitmap.Dispose();
File.WriteAllText(mapFileFormat, data.ToString());

```

With this, you've drawn white glyphs over a transparent background on a bunch of PNG files, and made an index file which tells you for each codepoint, in which file the glyph is located, its location and dimensions. Notice that I also put two additional pixels to separate each glyph (to accomodate for further effects)

Now, for each of those files, you put it in photoshop, and do all the filters you want. You can set colors, borders, shadows, outlines, and anything else you want. Just make sure that the effects don't make the glyphs overlap. If so, adjust the spacing, re-render, rinse and repeat. Save as PNG or DXT, and along with the index file, put everything in your project.

Drawing text should be very simple. For each char you want to print, find its location using the index, draw it, advance the position and repeat. You can also adjust for spacing, kerning (tricky), vertical spacing, and even coloring. In lua:

```
function load_font(name)
    local font = {}
    font.name = name
    font.height = 0
    font.max_page = 0
    font.glyphs = {}
    font.pages = {}
    font_definition = read_all_text("font/" .. name .. ".txt")

    for codepoint, page, x, y, width, height in string.gmatch(font_definition, "(%d+) (%d+) (%d+) (%d+) (%d+) (%d+)") do
        local page = tonumber(page)
        local height_num = tonumber(height)
        if height_num > font.height then
            font.height = height_num
        end
        font.glyphs[tonumber(codepoint)] = { page=tonumber(page), x=tonumber(x), y=tonumber(y), width=tonumber(width), height=height_num }
        if font.max_page < page then
            font.max_page = page
        end
    end

    for page = 1, font.max_page do
        font.pages[page] = load_image("font/" .. name .. "_" .. page .. ".png")
    end

    return font
end

function draw_text(font, chars, range, initial_x, initial_y, width, color, spacing)
    local x = initial_x - spacing
    local y = initial_y - spacing
    if range == nil then
        range = { from=1, to=#chars }
    end
    for i = 1, range.to do
        local char = chars[i]
        local glyph = font.glyphs[char]
        if char == 10 then -- line break
            x = initial_x - spacing
            y = y + ((font.height - (spacing * 2)) * 1.4)
        elseif glyph == nil then
            if unavailable_glyphs[char] == nil then
                unavailable_glyphs[char] = true
            end
        else
            if x + glyph.width - spacing > initial_x + width then
                x = initial_x - spacing
                y = y + ((font.height - (spacing * 2)) * 1.4)
            end
            if i >= range.from then
                draw_sprite(font.pages[glyph.page], x, y, glyph.x, glyph.y, glyph.width, glyph.height, color)
            end
            x = x + glyph.width - (spacing * 2)
        end
    end
end

```

And there you go. Repeat for every other font (and optimally size as well)

**Edit**: I changed the code to use `Graphics.MeasureString` instead of `TextRenderer.MeasureText()` because they both use different measurement systems, and may lead to inconsistencies between the measured glyph and the drawn one, especially with overhanging glyphs found in some fonts. More information here.
> 18 votes

# Answer
Well, like someone else said, in XNA, spritefont does the heavy lifting for you. on the creators club website there is a bitmap font exporter that exports in XNA style font images. (http://xbox.create.msdn.com/en-US/education/catalog/utility/bitmap\_font\_maker) Then, you can open it in photoshop or whatever and make it look pretty. From there, you add the texture to your content project, and in the content type, select sprite font texture. In your code, you load it like a normal sprite font

(Example: http://www.youtube.com/watch?v=SynGWrWYUQI)
> 6 votes

# Answer
The solution is quite simple and is used by a great number of games. All you have to do is treat your fonts as if they were sprites.

Have your designer draw out the entire range of numbers and letters that you want to use in your game. Then render them to varying sized static images (.png, .bmp, whatever format you use). You'll have something like this:

Now all you have to do is render each letter from your "font sheet" as if it were a sprite to the screen. It certainly helps to build a helper class to translate between strings and sprites.

My implementation is more complex, but handy. The font sheet is built like the above image with multiple fonts all in one .png file. I have a `.ini` file that maps each fonts' letter to a position on the sheet, along with its width and height. This lets my designer (and myself) go nuts making cool fonts without having to touch any code. When drawing a string to the screen, I have a method that looks up the font and the `char` from the .ini file to get the position and boundaries of the letter from the font sheet, then I just draw the `Texture2D` with `SpriteBatch.Draw()` using the source `Rectangle` of the letter in question.
> 4 votes

# Answer
UI is a vast and complex subject. Font rendering is a tough part. I advise you to use an already-existing library that allows you to display Flash or HTML content in-game, instead of redoing everything yourself.

Awesomium looks promising and should work with XNA, so you could give it a try. It's free for use for non-commercial games, or if you're not making tons of money:

> Free for Indie Companies
> <sup>If your company made less than $100K last year, you qualify! </sup>
> Free for Non-Commercial Use
> Free for Evaluation & Development
> 2 votes

# Answer
If you are looking for fancier effects than the plain .spritefont importer, you can try searching for a "bitmap font generator".

Personally I prefer this one: http://www.ironstarmedia.co.uk/2010/01/free-game-dev-utility-fancy-bitmap-font-generator/

Some other ideas:

* Use a bitmap font generator and then edit the bitmap it produces further in photoshop, etc.
* Put as much static text as possible into pre-drawn sprites. Then fill in just things like gamertags and score totals using .spritefonts or fonts generated from a bitmap font generator.
> 1 votes

# Answer
`XNA` does all of the hard work for you. With `Spritefont` you can easily convert a font file on your machine into the kind of sprite sheet you are asking about by defining an XML file.

Once you add the XML file to your Content project load it with the `ContentManager`:

```
ContentManager.Load<SpriteFont>(@"MyFont");

```

Here is an example of a .spritefont file from my content project:

```
<?xml version="1.0" encoding="utf-8"?>
<!--
This file contains an xml description of a font, and will be read by the XNA
Framework Content Pipeline. Follow the comments to customize the appearance
of the font in your game, and to change the characters which are available to draw
with.
-->
<XnaContent xmlns:Graphics="Microsoft.Xna.Framework.Content.Pipeline.Graphics">
<Asset Type="Graphics:FontDescription">

    <!--
Modify this string to change the font that will be imported.
//TODO: A different font should be chosen before shipping for licensing reasons
-->
    <FontName>Pericles</FontName>

    <!--
Size is a float value, measured in points. Modify this value to change
the size of the font.
-->
    <Size>8.5</Size>

    <!--
Spacing is a float value, measured in pixels. Modify this value to change
the amount of spacing in between characters.
-->
    <Spacing>0</Spacing>

    <!--
UseKerning controls the layout of the font. If this value is true, kerning information
will be used when placing characters.
-->
    <UseKerning>true</UseKerning>

    <!--
Style controls the style of the font. Valid entries are "Regular", "Bold", "Italic",
and "Bold, Italic", and are case sensitive.
-->
    <Style>Bold</Style>

    <!--
If you uncomment this line, the default character will be substituted if you draw
or measure text that contains characters which were not included in the font.
-->
    <DefaultCharacter>@</DefaultCharacter>

    <!--
CharacterRegions control what letters are available in the font. Every
character from Start to End will be built and made available for drawing. The
default range is from 32, (ASCII space), to 126, ('~'), covering the basic Latin
character set. The characters are ordered according to the Unicode standard.
See the documentation for more information.
-->
    <CharacterRegions>
        <CharacterRegion>
            <Start> </Start>
            <End>~</End>
        </CharacterRegion>
        <CharacterRegion>
            <Start>	</Start>
            <End>	</End>
        </CharacterRegion>
    </CharacterRegions>
</Asset>
</XnaContent>

```
> 0 votes

# Answer
I am not sure as I never used it but people suggested me to use Glyph Designer. Here is a video tutorial:

http://vimeo.com/32777161

Here there is a discussion on it mentioning photoshop.

There are people using also Hiero font editor.

In this website there is a list of other font editor you might want to have a look at.

Let me know which one works best for you :)
> 0 votes

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


# Question
Title: Developing an ELO like point system for a multiplayer gaming site
I'm currently working on a gaming site where users will submit virtual players for different games, like Chess, Nash, Backgammon, Go, etc. The idea is that users don't compete themselves, but through their virtual players. There will be leagues, tournaments, and other competition formats.

The question is which would be a good rating system for users in this environment. Take into account that every user may have many different virtual players playing in many different games. As a general guideline I would like to guarantee the following properties:

* Users who have a lot of mediocre players should not score higher than users with a few very good players.
* A user with a high rating should not be penalized if he adds a new bad player, until he has had enough time to improve his player.
* Users who don't play often should not score higher than users who play every day.

Thanks in advance.

# Answer
> 1 votes
I would divide the ranking into 3 levels:

1. Bottom level is where **players** are rated. Use ELO or a similar system, where a strong player is penalized much more for loosing with a weak opponent, than he could be awarded. Also secure game system for users using many accounts, e.g. by random matchmaking. This will solve your 3rd point:

> * Users who don't play often should not score higher than users who play every day.
2. Middle level is rating for every **group of players owned by one user and playing one game**, e.g. Alejandro's Chess players. You most probably don't want a chess player to play with a Go player, as they use different algorithms, and even the best player of one game will probably lose with one of the worst players in another. To calculate the rating of a group, take an average of ELO of the players in the group, not considering 20% of the worst players in this group. This will ensure the extraordinarily terrible players won't affect average rating. Keep in mind this is yet another reason to make matchmaking random. So this covers two remaining points of your requirements

> * Users who have a lot of mediocre players should not score higher than users with a few very good players.
>     * A user with a high rating should not be penalized if he adds a new bad player, until he has had enough time to improve his player.
3. Top level is rating for a **user**. This is a very subjective part; you could for example:

* show best achievement of the user (#23 place in silver league)
    * show average of scores of all game-groups
    * show average of scores of all game-groups the user is active in
    * show the highest of scores of game-groups
    * calculate the main score in a complex way, e.g. find the highest possible score of a user, being an average of chosen groups plus 100 bonus points for every group taken into an average.

# Answer
> 2 votes
ELO works by matching you with an opponent based on your rating, and then transferring some rating from one player to the other based on the result and the rating difference between the players (i.e. a high rated player beating a low rated player gains very little, but if he lost the game he would lose a lot).

I think that is not going to work well without a separate rating per game for each player. For example if a really good backgammon player decided to learn chess, it would seem strange for their rating to decrease while they are just learning how to play. You'd also need to be able to match them with a chess opponent of the appropriate skill, which a single overall rating can't do effectively.

You could still have an overall rating which is calculated as say the maximum of all other ratings, or maybe the sum of all other ratings if you want to encourage people to play all the games.

I would also strongly consider only allowing one player per user, or alternatively one player per game type. This is because new players need to be awarded an initial ELO rating. If they lose their first game then that rating will drop, and creating a new user and getting a fresh rating would be an easy way to exploit the system.

# Answer
> 2 votes
It looks like you have three free variables to play with. The first one is the number of 'mediocre playes versus better players', the second one is 'user rating agains new player success rate' and the third one is 'frequent players versus infrequent players'.

My suggestion: Divide and conquer. Find an elo-inspred rating for each of the three variables and take a (weighted) average of it. Now you have three problems, but the sum of problems with the three might be smaller than the problems of the whole.

# Answer
> 2 votes
I've thought about ranking systems quite a bit and I think it's best to create a new ranking system whenever you have a new project since every time you'll have different parameters and requirements. You could adjust for example parameters of the elo ranking etc. but this will always result in a half-hearted solution. Most game companies create their own rankings & matchmakings for every game.

Of course the already existing rankings are not bad by any means but usually they try to generalize a given scenario which only gives a rough trend. Looking at how other ranking systems work is a good basis for your own ranking but usually creating a ranking system is a complex process which even after implementation requires a lot of tweaking. Thousands or millions of dummy scenarios are required in order to evaluate the quality of a ranking system and often the math behind it is not that simple.

Writing down how the ranking is supposed to work is one of the first steps at creating one, although this might sound simple it is a lot more complex than you might think.

**Example:**

Users who don't play often should not score higher than users who play every day.

This sounds obvious but on the other hand, how do you quantify often? Is someone who only played one time (scored high points) supposed to have a higher ranking who has mid scores but plays every day? You would have to define a mathematical relation between amount of games/days played with the amount of points. How does this relation look like? Is it supposed to be linear, logarithmic, exponential etc. How will this effect the strategy of the players (will they play less put try to play well in order to get higher points)? Will this behavior have an impact on other aspects of the game (less trained players per user?)?

Every requirement will affect the ranking and thus you have to analyse how they will effect each other (maybe give some higher priorities than others or even ignore certain requirements in some cases). Every ranking system is comparable to a dissertation (depending on how detailed you want to make it)

**Ranking**

I'm not sure whether I understood your request correctly but to me it sounds like you want to create a ranking for every user based on the success of every player a user has.

My first idea would be to create a ranking for every game (chess, go etc.). Rank every player who plays this game in it and then calculate the overall ranking based on these rankings for every user. Of course this would be very complex since you would have to create a ranking for every game BUT there are lot's of decent rankings for every game. This way the only thing you would have to think about (given you found a ranking for every game) is in which way you want to calculate the overall ranking based on the rankings of every game (still not easy but way easier than creating only one ranking containing all information of every game).

This is what I would recommend to someone who doesn't want to spend too much time with the math behind it, which is still a lot.

Edit:

The advantage of a ranking for every game would be that you could use this ranking for your matchmaking process, but this is another topic.

# Answer
> 1 votes
Before diving into formulae, if you want to create a ranking system, you'll have to come up with a list of specifications and requirements. Decide what the ranking system should accomplish and work from there. Be specific. Requirements that are rock solid can be a great guide, where general guidelines, such as the ones you drew up, may lead to confusion instead.

An example. Alice and Bob both have a few good virtual players, but Alice's are slightly better. Alice then continues to add mediocre players to her set. Eventually, she'll have quite a lot of them. According to rule #1, Alice's score may no longer be higher than Bob's and therefore must go down. Rule #2 forbids this.

Carol joins the party. She has one virtual player and it's terrible, no match for anyone of Bob's players. However, on account of her enthousiastic daily participation and rule #3, she still scores higher than Bob, who only plays once a week.

If you stick to basic limitations instead, even seemingly trivial ones like 'winning increases your score', 'playing often adds to your score'... as long as the set is consistent, it will make the mathematics a lot easier.

# Answer
> 1 votes
Some function to test and to fool around with for gaining/loosing rating points.

Say player A has rating `A` and player B has rating `B`.

The difference in rating is: `D = |A - B|`

Put a cap on the difference: `if (D > Dmax) D = Dmax`

You need some function to calculate the gain/loss for a match.

```
AdjustRatings(Player Winner, Player Looser)
{
    const int Dmax    = 100;
    const int MaxGain =  50;

    int Difference = Looser.elo - Winner.elo;
    if ((Difference) < -Dmax) Difference = -Dmax;
    else if (Difference > Dmax) Difference = Dmax;

    // the gain is a ratio from the differecene in rating.
    int Gain = (Dmax + Difference) * MaxGain/DMax;

    Winner.elo += Gain * Winner.FrequencyFactor;
    Looser.elo -= Gain * Looser.FrequencyFactor;
}

```

---
Tags: game-design, multiplayer
---