# Question
Title: Use client as server in client/server architecture
Let me clarify what i mean by that.

Let's say i want to create a multiplayer game which uses physics (box2d). If I would let the server handle all the physics I would end up with a very overwhelmed server with clients that only control one entity on the server.

**Question:**

What if i only use the server as a 'router' to control the traffic between clients and use one of the clients to handle the physics and do some checking to stop cheating? Is this a bad idea? ( But this may increase latency, since clients can't send data directly to each other.)

**Keep in mind that a game is between 2 players, that means the client which would handle the physics wouldn't have all clients body handled by it's pc.**

# Answer
As far as I'm aware, this is essentially what many console games do. This was even brought across to some PC games, like Call of Duty: Modern Warfare 2.

There are, of course, some drawbacks:

* Any coding effort to "do some checking to stop cheating" would almost have to be more complex than the physics code itself. You *can't* trust the client, pure and simple. They could be sending across barrels of dynamite and spyware for all you know (humorous exaggeration).
* Even if your unknowing "server" has the purest intents, they're likely to get a much smoother, more consistent experience than the other clients, more or less ensuring their headshots are computed first, and what's on their screen is most representative of the game.
* If players become aware of their server status, all they have to do is turn on something to throttle their bandwidth, ensuring all other players get a horrible experience. You can't even call this cheating, because players connecting from Chile aren't likely to have a consistent connection.

All you really should know is this: Yes, it is possible. But when Call of Duty: Black Ops (the next game in the series) came out, they gained a lot of players by announcing they would use dedicated, rather than player-hosted, servers.
> 6 votes

# Answer
It is not a 'bad idea' to do this over other methods of networking.

What developers typically have to discuss is how much power to give to a Client, and how much authority to give to the Server.

I would say that the more you allow a Client to do, the smoother things will be for the player. However, the more you allow a Client to do, the less authority the Server has to prevent cheating.

I will use different examples to explain my answer.

## Example1

Online multiplayer FPS games with client-side hit detection benefit all players by giving a more fair experience despite latency. No longer do players feel the results of lag preventing them from scoring a kill when they shot first. A common joke among FPS developers in the earlier days of FPS gaming was the banter between players: "I shot you first! NO I shot YOU first!" The downside is that cheating becomes extremely easy for players. It is not a coincidence that games with Client-Side hit detection have an enormous amount of cheaters compared to other games. While cheaters are in every FPS game, I personally experience a far greater number in Client-Side hit detection games. This makes sense given how much power the client has to send the server what seems like logical, rational headshots. IMO this has a major downfall but a major benefit, especially to high latency shooters like Planetside2. However, like with Planetside2, combining this with client-side movement detection makes for an absolutely idiotic nightmare for players who do not cheat. Yes, Planetside2 doesn't just allow players to decide who and where they shot their bullets, but allows players to teleport, warp around, or even fly simply by telling the server they are here instead of there, despite it not being rational. The benefit of the former is almost worth the negatives, but I see next to no benefit for the latter, compared to the overwhelming negatives that comes with pairing the two.

In a game where the client is the server, I do not see this to be as big of a problem, but the problems of cheating still remain. However there is a great resolution BECAUSE of the client being the server. The client (server) would have the authority to kick cheaters or players who ruin the game experience, or close down by simply leaving the cheaters behind, disconnecting them from everyone and sending them elsewhere to ruin someone else's game.

The negative side of Example1 with a client-as-server design is that the client (server) has an enormous amount of power to cheat. Not only do they hold all authority over all players, to the point of closing the entire game down if they so desire (although you may want this as a feature to handle trolls) but the client (server) can do even the simpest of things to cheat. Messing with one's modem, lagging one's connection, or manipulating flaws in the design can be achieved by even the most amateur of children who find out a simple trick (cheat). Not all cheating is as difficult as requiring a complex program such as an Aimbot.

## Example2

Physics for clients, but not on servers. The server's load is obviously very light with this example. However, a single misstep in physics calculation on any one client and everything could change dramatically. What most rational developers do is have the calculations on BOTH the client AND the server, and then check for consistency. This isn't just for Physics, but for many other calculations as well. It is amazing how a tiny insignificant difference in Clients can produce an enormous amount of differentiation between player's game worlds. Especially when the server does not catch and correct these errors.

My question would be, "Why does only 1 client (as server) do the physics calculations? If one client is capable of acting as client, server, AND performing the calculations, then why can't all clients perform the calculations? Unless the client (server) had to be a desktop which can connect to low hardware, low connection clients (mobile clients?) I have a hard time understanding why one would have physics calculations on only one client.

## Example3

A single client is the server, where other players connect to said client. This is very common for console games. While a good idea in theory, as a PC gamer and developer I find this to be so laughable that it verges on idiotic. At least for FPS games anyway. For other genre's I may view it entirely different. A turn based game for example would be genius to have this type of setup. Despite the horrendous flaws, there is a benefit in the design. It is easy for players to casually connect, they don't have to ever rely on a server which may go offline, and matchmaking can guarantee similar ping locations. The downfall is the obvious: The client that is the server has a ping of 0. They will have not a small advantage, but an enormous one. Nearly every game I viewed, the host would have one of the highest if not highest scores among all players due to this advantage. When I played games where I had 0 ping, my scores would double and I would be unstoppable almost like I was cheating. More negatives include how if the host leaves the game, all players on the 'server' will suddenly drop, almost as if a crash. Even more of a flaw is the fact that the majority of users do not have the most NAT friendly setup. It is very common for players of even console games to not be able to connect to their friends due to the fact there is no a healthy server to connect with.

While Ex.2 and Ex.3 do not give as specific as an example as Ex.1, I did not want to be repetitive. Example 1 can apply to more than just the feature of client-side hit detection. It is very common for games that allow clients to have power, to have a lot more cheating; undetectable cheating especially. When all the server receives is player input, it is next to impossible to detect whether or not they are cheating or are simply expert gamers. Especially if the cheating is sophisticated enough to know how to fool the server's consistency checks. A common piece of advice among developers which I have read online is to "Give the player as little power as possible for security reasons." and in MMO specifics, "Try to make the client nothing more than a keyboard, mouse, and display."

After all, if you CAN avoid using lag-prediction techniques, then you'd want to do so. These techniques are used as a resolution to a problem. Games that do not have the problem do not need them. So it entirely depends upon the design, but I would never consider your idea a "bad idea" compared to other methods. They are just different, with problems and solutions. Although I would definitely argue that restricting control for the Client to avoid cheating should be used whenever possible. If the Server can handle the load, then it is worth it.
> 1 votes

---
Tags: java, server, client-server, client
---


# Question
Title: How do you rotate a material 90 degrees in UDK?
So, I have started checking out UDK since yesterday, and most of it is clear and understandable.

I'm trying to create a curved road. The idea was to use a brush (Curved Staircase) and set the steps to 0 so it would be flat. This all worked well and I made a static mesh of it. Now, the problem arrives when I add a material. It doesn't rotate the material the way I want it.

Here's the way I do the example above:

* Create a brush:
* Convert to Static Mesh
* Add Static Mesh into the game:
* Change material to "Asphalt"
* Scale it a bit so you can notice the problem:

As you can see, the stripes aren't following 'the mesh' correctly. They have to rotate 90 degrees for them to appear correctly.

How can you do this?

# Answer
To **rotate** the look of a material (this will apply to all instances of that material):

1. Open the material in the Material Editor.
2. Find the Texture Sample node you want to rotate.
3. Create a Rotator node and leave the default values in.
4. Connect the Rotator to the UVs of the Texture Sample.
5. Create a Constant node.
6. Connect the output of the Constant to the Time input of the Rotator.
7. Play with the value of the Constant until you get the rotation you want.

To **scale** the above rotated material (again, for all instances):

1. Insert a Texture Coordinates node.
2. Connect its output to the Coordinate input of the Rotator you created above. If you don't have a rotator (perhaps you want to apply this to another, non-rotated material, later on), connect it directly to the UVs input of the Texture Sample.
3. Adjust the parameters of the Texture Coordinates node. As a rule of thumb, values higher than 1 mean that the texture will repeat itself, while values lower than 1 mean the texture will appear partially.
> 1 votes

---
Tags: rotation, udk, materials
---


title: Does Blender have a main menu?

text:
# Question
Title: Does Blender have a main menu?
1 - Does Blender have a main menu, and if so, how do I make it appear? This is what I'm looking at currently:

https://i.stack.imgur.com/xd0Zf.jpg

2 - Also, that text panel at the top, that is as large as I can make it. Is there any way to make it taller? Or change the panel layout...?

# Answer
> 2 votes
Yes, It does have a main menu and you must have hidden it.

There is a small plus sign in the upper right corner of the 3D view. Click on it and it should do the trick.

# Answer
> 1 votes
If by main menu, you mean the toolbar, you can access that by pressing `T`. The properties panel can be accessed by pressing `N`. And the majority of settings are changed in the properties *editor*(the default panel in the lower right hand corner. If there's ever a tool that you want to access, but cant remember it's location, use the search bar(`SPACE`).

---
Tags: blender, blender-game-engine
---


# Question
Title: A* search in hexagonal grid with minimum turn radius
I need to run an A\* search through a hexagonal grid. However, I have one nasty constraint: my vehicle can only turn so sharp. It has a specified minimum turn radius. I can't quite see how to translate this constraint into something I can use with each cell expansion to determine if a neighbor is viable or not. My grid cells are significantly smaller than the minimum turn radius.

I have an initial angle and location of the vehicle; it seems I need to keep a current angle with each cell. With that in mind, I'm not quite sure when I need to reset reference point. It seems that I cannot do that every cell or I will only go in a straight line.

I can translate that turn radius into a polygon (with several hundred sides) where each side length is the distance between my grid cells. I'm not sure how to use this, though.

# Answer
> 3 votes
Let's consider a generic turn-radius constraint.
It must consist of moving 'N' hexes in a straight line before a turn of 60 degrees is allowed.

This can be incorporated by:

* Extending the definition of a path-node with a counter: **StraightLineHexesRequired**
* Decrementing **StraightLineHexesRequired** on each node expansion if EntryDirection == ExitDirection and **StraightLineHexesRequired** \> 0
* If **StraightLineHexesRequired** != 0 then only expanding the hex dead-ahead
* If **StraightLineHexesRequired** == 0 then expanding only the nodes dead-ahead, and the two hexes 60 degrees off of dead-ahead.
* Setting **StraightLineHexesRequired** to N on every turn of 60 degrees.

This nicely generalizes to the case where N might be 0.

**Update:**
In the case where one is optimizing for time, and speed is a mutable parameter, and N depends on speed, one would add nodes to the open set with current speed as well as plus-one and minus-one on the speed scale, with appropriate new values of **StraightLineHexesRequired**

---
Tags: path-finding, geometry, hexagonal-grid
---


# Question
Title: How to make sure a game can be completed
I'm not sure what the correct term for what I'm looking for is described, so apologies if this is a duplicate question. But is there a term/algorithm for making sure a game is "completable" with relation to an infinite scroller. What I mean by completable is that, if I had a game, where a user has to keep jumping up blocks as the screen tries to catch up with them, how would I ensure that there is always a reachable new block that the user could in theory jump to?

I know in theory I would check how high the user can jump and ensure there is a block within that reach, but is there anything else to it? i.e avoiding expensive checks when placing new blocks to make sure they're not overlapping etc?

I'm specifically looking at html5/js but I wondered if there was a term for this or a specific type of algo that I could investigate?

Thanks

# Answer
> 6 votes
One interesting approach I've seen is to make a bot/AI that understands how to play the game. It doesn't even have to be good at it. Just make sure that for any particular point a jump appears necessary/possible that the AI speculatively tries out a good number of them (by simulating the jump) until it finds one it can do. Run the AI on the level some number of times and see if any of those result in completion.

See the Inifinite Mario AI video and supporting articles about this one possible technique. You might notice in the video that the AI is significantly better than a human should be expected to be. You might want to artificially dumb down any such AI to ensure that it represents a reasonable player skill level.

---
Tags: javascript, procedural-generation
---


title: 3D Reflection - Drawing Upside Down

text:
# Question
Title: 3D Reflection - Drawing Upside Down
After reading up on rendering reflections, it seems that the way to do it is the render the scene from underneath the plane of reflection, and then use projective texturing to map the reflected texture to the reflective surface. However, why can't you just use the image from rendering the scene underneath the water, and draw it upside down behind the terrain?

Here's what I mean: https://i.stack.imgur.com/g6VbX.png

The lines at the end of the views represent the drawn image, the colored dots are supposed to represent the corresponding points on the textures, and the brown is supposed to represent the terrain.

From the diagram, it would appear that you can just take the image rendered from the camera below the reflective surface, flip it upside down, and then draw it behind the terrain on the actual rendered image.

Is this another way to do it, or am I completely missing something here?

Thanks!

# Answer
When rendering planar reflections, you don't need to render the reflection to a texture at all. To render a reflective surface, you can use the following steps:

# Basic reflection

1. Render the surface (e.g. a table or pond) to a stencil buffer
2. Setup a custom clipping plane that clips objects behind the surface
3. Multiply the current camera matrix with a mirror matrix that reflects from the surface plane
4. Invert polygon winding rule
5. Enable stencil test to pass only pixels that were written in step 1.
6. Render the scene
7. Restore normal rendering settings
    * Original camera matrix
    * Polygon winding rule
    * Remove the custom clipping plane
    * Disable stencil test
8. Render the surface again with alpha blending

This algorithm can be used at any time during the rendering of the scene. Few notes:

* Step 1. and 5. are not needed if your reflective surface covers the whole area, i.e. the sea level
* Step 2 is only needed if you can have polygons behind the surface (often true)
* Step 8 is not needed if the surface if fully reflective

# Post processing

If you need to post-process the reflection (e.g. blur it), then you need to render the reflection to a texture. After post-processing the reflection texture, you need to render it to the screen. Here you have two options. One is the projective texturing, where you render the surface with texture mapping. Alternatively you can just blit the texture to the screen behind other geometry. However if the surface is not infinite, you have to restrict the reflection to be visible only on the surface. This can be achieved with the same stencil buffer approach as described above in the normal reflection. Alternatively the projective texturing solves this. With a shader the projective texturing can be implemented easily by using screen coordinates directly as the texture coordinates.

# Summary

To answer your actual question. Yes you can just draw the reflection behind your terrain, but if the reflection should appear only on specific polygon(s), you need either projective texturing or stencil buffer.
> 2 votes

---
Tags: shaders, graphics-programming, reflection-rendering
---


# Question
Title: Game Engine Design – Ubershader - Shader management design
I want to implement a flexible Ubershader system, with deferred shading. My current idea is to create shaders out of modules, which deal with certain features, such as FlatTexture, BumpTexture, Displacement Mapping, etc. There are also little modules which decode color, do tone mapping, etc. This has the advantage that I can replace certain types of modules if the GPU doesn't support them, so I can adapt to the current GPU capabilities. I am not sure if this design is good. I fear I could make a bad design choice, now, and later pay for it.

My question is where do I find resources, examples, articles about how to implement a shader management system effectively? Does anyone know how the big game engines do this?

# Answer
> 24 votes
A semi-common approach is to make what I call *shader components*, similar to what I think you're calling modules.

The idea is similar to a post-processing graph. You write chunks of shader code that includes both the necessary inputs, the generated outputs, and then the code to actually work on them. You have a list which denotes which shaders to apply in any situation (whether this material needs a bump mapping component, whether the deferred or forward component is enabled, etc.).

You can now take this graph and generate shader code from it. This mostly means "pasting" the chunks' code into place, with the graph having ensured they're in the necessary order already, and then pasting in the shader inputs/outputs as appropriate (in GLSL, this means defining your "global" in, out, and uniform variables).

This is not the same as an ubershader approach. Ubershaders are where you put all the code needed for everything into a single set of shader, maybe using #ifdefs and uniforms and the like to turn features on and off when compiling or running them. I personally despise the ubershader approach, but some rather impressive AAA engines use them (Crytek in particular comes to mind).

You can handle the shader chunks in several ways. The most advanced way - and useful if you plan to support GLSL, HLSL, and the consoles - is to write a parser for a shader language (probably as close to HLSL/Cg or GLSL as you can for maximum "understandability" by your devs) that can then be used for source-to-source translations. Another approach is to just wrap up shader chunks in XML files or the like, e.g.

```
<shader name="example" type="pixel">
  <input name="color" type="float4" source="vertex" />
  <output name="color" type="float4" target="output" index="0" />
  <glsl><![CDATA[
     output.color = vec4(input.color.r, 0, 0, 1);
  ]]></glsl>
</shader>

```

Note with that approach you could make multiple code sections for different APIs or even version the code section (so you can have a GLSL 1.20 version and a GLSL 3.20 version). Your graph can even automatically exclude shader chunks which have no compatible code section so you can get semi-graceful degradation on older hardware (so something like normal mapping or whatever is just excluded on older hardware that can't support it without the programmer needing to do a bunch of explicit checks).

The XMl sample can then generate something similar to (apologies if this is invalid GLSL, it's been a while since I've subjected myself to that API):

```
layout (location=0) in vec4 input_color;
layout (location=0) out vec4 output_color;

struct Input {
  vec4 color;
};
struct Output {
  vec4 color;
}

void main() {
  Input input;
  input.color = input_color;
  Output output;

  // Source: example.shader
#line 5
  output.color = vec4(input.color.r, 0, 0, 1);

  output_color = output.color;
}

```

You could be a little smarter and generate more "efficient" code, but honestly any shader compiler that isn't total crap is going to remove the redundancies from that generated code for you. Maybe newer GLSL lets you put the file name in `#line` commands now, too, but I know older versions are very deficient and don't support that.

If you have multiple chunks, their inputs (which aren't supplied as an output by an ancestor chunk in the tree) are concatenated into the input block, as are outputs, and the code is just concatenated. A little extra work is done to ensure stages match up (vertex vs fragment) and that vertex attribute input layouts "just work". Another nice benefit with this approach is that you can write explicit uniform and input attribute binding indices which are unsupported in older versions of GLSL and handle these in your shader generation/binding library. Likewise you can use the metadata in setting up your VBOs and `glVertexAttribPointer` calls to ensure compatibility and that everything "just works."

Unfortunately there is no good cross-API library like this already. Cg comes kinda close, but it has crap support for OpenGL on AMD cards and can be exceedingly slow if you use any but the most basic code generation features. The DirectX effects framework work too but of course has zero support for any language besides HLSL. There are some incomplete/buggy libraries for GLSL that mimic the DirectX libraries but given their state the last time I checked I'd just write my own.

The ubershader approach just means defining "well-known" preprocessor directives for certain features and then recompiling for different materials with different configuration. e.g., for any material with a normal map you can define `USE_NORMAL_MAPPING=1` and then in your pixel-stage ubershader just have:

```
#if USE_NORMAL_MAPPING
  vec4 normal;
  // all your normal mapping code
#else
  vec4 normal = normalize(in_normal);
#endif

```

A big problem here is handling this for precompiled HLSL, where you need to precompile all combinations in use. Even with GLSL you need to be able to properly generate a key of all the preprocessor directives in use to avoid recompiling/caching identical shaders. Using uniforms can reduce the complexity but unlike the preprocessor uniforms don't reduce instruction count and can still have some minor impact on performance.

Just to be clear, both approaches (as well as just manually writing a ton of variations of shaders) are all used in the AAA space. Use whichever works best for you.

---
Tags: opengl, shaders, deferred-rendering, resource-management
---


# Question
Title: How to move a sprite automatically using a physicsHandler in Andengine?
I use a `DigitalOnScreenControl` (knob with a four-directional arrow control) to move the entity and the entity which is bound to a `physicsHandler`.

```
physicsHandler.setEntity(sprite);
sprite.registerUpdateHandler(physicsHandler);

```

From the `DigitalOnScreenControl`, I know which direction I want my sprite to move. Inside its overridden `onControlChange` function, I call a function `animateSprite` that checks which direction I chose. Based on the direction, I animate my sprite differently.

**Problem:** I want to automatically move the sprite to a specific location on the scene, say at coordinates (207, 305). My sprite is at (100, 305, which means it has to move down by 107 pixels.

How do I tell the `physicsHandler` to move the sprite down by 107 pixels? My `animateSprite` method will take care of animating the sprite's downward motion.

# Answer
> 1 votes
why dont you extend the PhysicsHandler class yourself and add automatic movement to the sprite then call the onUpdate(). For example :

```
public class Handler extends PhysicsHandler {

public Handler(IEntity pEntity) {
    super(pEntity);

}

@Override
protected void onUpdate(float pSecondsElapsed, IEntity pEntity) {
    // TODO move the pEntity down. eg: pEntity.sety(300)
    super.onUpdate(pSecondsElapsed, pEntity);
}
}

```

# Answer
> 1 votes
I assume you are using Box2D extension from AndEngine. What you are looking for is `MouseJoint`. There is a working example of MouseJoint in the AndEngineExamples projects that you probably already have. The class you are looking for is `PhysicsMouseJointExample`.

MouseJoint is used to send the body in continuous movement to a target location. Basically you create MouseJoint as any other joint and then use its method `setTarget()`.

# Answer
> 0 votes
I'm not familiar with andengine, but it uses box2d so there should be some method similar to:

```
PhysicsBody.setTransform(float x, float y, float angle)

```

Which sets the body's position to x, y and rotation to angle.

# Answer
> 0 votes
Im using this listener to move my sprite around the screen. The "\*10" it's like the "velocity".

```
            @Override
        public void onControlChange(final BaseOnScreenControl pBaseOnScreenControl, final float pValueX, final float pValueY) {
            playerBody.setLinearVelocity(new Vector2(pValueX*10  , pValueY*10));
        }

```

Edit: The listener is inside the ScreenControl instance.

---
Tags: android, physics, sprites, movement, andengine
---


# Question
Title: Why is it when I render a basic cube, my editor's grid changes too?
I have one HLSL file for DirectX11 that only has input layout for color and position. Then another HLSL file for the simple cube that has position, normal and textures. What I noticed is when I render the simple cube; the grid also changes and doesn't remain pure white color. They have different pixelshaders, vertexshaders, constant buffers and different inputlayout descriptions.

Would anyone like to chip in and help get this resolved? This has been puzzling for a day!

# Answer
> 3 votes
I highly recommend grabbing a graphics debugger. Aside from the free GPU vendor ones (such as AMD's PerfStudio, and Nvidia's Nsight) there's also one built into VS2012 Professional. This will let you look at the current state of the ID3D11GraphicsContext and confirm you've set everything correctly when you draw the grid.

If you want to take the brute force approach, you could compare and contrast the state when you go to render said grid in two different scenarios: where you don't render the cube, and the grid looks correct, vs where you do render the cube, and the grid looks incorrect. If you understand the device context state, just looking at the wrong result is likely to let you figure things out faster.

Wildly guessing, I'm guessing the fundamental problem is that you set something on the graphics context once on the creation/initialization of something, when it really needs to be set each time before you render the grid that uses it. Direct3D and OpenGL are both very much driven by "what is the current state of the graphics context" rather than how things were originally created.

---
Tags: textures, shaders, hlsl, directx11, color
---


title: OpenGL + SDL Linking Problem

text:
# Question
Title: OpenGL + SDL Linking Problem
So I'm trying to write a simple application with SDL 1.2 and OpenGL. This a stripped down version of the code containing the one problem I'm having.

```
//The headers
#include "SDL.h"
#include "SDL_opengl.h"

//Screen attributes
const int SCREEN_WIDTH = 640;
const int SCREEN_HEIGHT = 480;
const int SCREEN_BPP = 32;

//Event handler
SDL_Event event;

bool initGL()
{
    //Initialize Projection Matrix
    glMatrixMode( GL_PROJECTION );
    glLoadIdentity();

    //Initialize Modelview Matrix
    glMatrixMode( GL_MODELVIEW );
    glLoadIdentity();

    //Initialize clear color
    glClearColor( 0.f, 0.f, 0.f, 1.f );

    //Check for error
    GLenum error = glGetError();
    if( error != GL_NO_ERROR )
    {
        printf( "Error initializing OpenGL! %s\n", gluErrorString( error ) );
        return false;
    }

    return true;
}

bool init()
{
    //Initialize SDL
    if( SDL_Init( SDL_INIT_EVERYTHING ) < 0 )
    {
        return false;
    }

    //Create Window
    if( SDL_SetVideoMode( SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, SDL_OPENGL ) == NULL )
    {
        return false;
    }

    //Enable unicode
    SDL_EnableUNICODE( SDL_TRUE );

    //Initialize OpenGL
    if( initGL() == false )
    {
        return false;
    }

    //Set caption
    SDL_WM_SetCaption( "OpenGL Test", NULL );

    return true;
}

void render()
{
    //Clear color buffer
    glClear( GL_COLOR_BUFFER_BIT );

    glBegin( GL_QUADS );
        glVertex2f( -0.5f, -0.5f );
        glVertex2f(  0.5f, -0.5f );
        glVertex2f(  0.5f,  0.5f );
        glVertex2f( -0.5f,  0.5f );
    glEnd();

    //Update screen
    SDL_GL_SwapBuffers();
}

void clean_up()
{
    //Quit SDL
    SDL_Quit();
}

int main( int argc, char *argv[] )
{
    //Quit flag
    bool quit = false;

    //Initialize
    if( init() == false )
    {
        return 1;
    }

    //Wait for user exit
    while( quit == false )
    {
        //While there are events to handle
        while( SDL_PollEvent( &event ) )
        {
            if( event.type == SDL_QUIT )
            {
                quit = true;
            }
            else if( event.type == SDL_KEYDOWN )
            {
                //Handle keypress with current mouse position
                int x = 0, y = 0;
                SDL_GetMouseState( &x, &y );
            }
        }

        //Render frame
        render();
    }

    //Clean up
    clean_up();

    return 0;
}

```

Anyway the code has a problem with `gluErrorString()` and reports:

```
1>main.obj : error LNK2019: unresolved external symbol _gluErrorString@4 referenced in function "bool __cdecl initGL(void)" (?initGL@@YA_NXZ)

1>C:\...\Debug\sdl1.exe : fatal error LNK1120: 1 unresolved externals

```

I'm using Visual Studio C++ 2010 Express. I'm using SDL 1.2.15 and freeglut. I've added to the VC++ Directories both the SDL and freeglut library and include directories respectively and in the Linker general dependencies have added SDL.lib, SDLmain.lib, OpenGL32.lib, and freeglut.lib. And SDL.dll and freeglut.dll are included with the executable.

What's really baffling me is I can run SDL code with this same set up as well as OpenGL (if I include gl/glu.h and gl/gl.h manually), but trying to run them together has brought me to a screeching halt. If I comment out the line `printf( "Error initializing OpenGL! %s\n", gluErrorString( error ) );` it works fine, but I have no idea why it can't seem to work with a simple thing like `gluErrorString()`, especially because `gluErrorString()` works fine in my OpenGL only code.

From what I understand `#include "SDL_opengl.h"` is supposed to include the opengl headers for me, and it seems to work for all but this one line, which I don't understand. If there's any further pertinent information needed I will provide it. Any help is greatly appreciated.

# Answer
> 3 votes
Headers provide (among other things) function declarations and type definitions into the source files which you include them. Libraries you link provide the symbols representing the definitions for those function declarations.

If you're missing an include, you're going to get a *compiler* error about an unknown identifier, type or function.

If you're missing a library or forgot to define a function you declared yourself, you're going to get a *linker* error about a missing symbol.

As your error is about a missing symbol for `gluErrorString`, you need to link `glu32.lib`, which is the OpenGL utility library.

For almost anything provided by a Microsoft-supplied library, you can find out which header to include and what library to link by reading the MSDN page for the function.

---
Tags: c++, opengl, sdl
---


# Question
Title: Ground for 2D AndEngine game with physics
I am using AndEngine to create a 2D Game for Android platform using Java and AndEngine.

I have learned how to use Tiled editor to create tiled maps. The only problem I am having is that I don't know how to place an object such as a character on the ground, and have it count as the ground.

How do I go about doing this or what is the best way to do this?

# Answer
AndEngine examples have a TMX Map Example which, among other things, demonstrates how to place a character on the map and how to determine in which map cell the character is currently in.

From there it should be simple(-ish) - you need to designate some map tiles as "empty" and some as "solid" - TMX format allows you to specify properties of tiles so I guess that's what I would use. Then you write a function which checks if your character is in "mid-air", an if so, the character should begin falling. In pseudocode:

```
if (map.isEmptySpace(character.getX(), character.getY()) {
   character.setVSpeed(character.getVSpeed() + GRAVITY);
}

```
> 2 votes

# Answer
I assume you are using Box2D Physics extension in AndEngine.

1. Design your level as you wish, paint tiles in the Map layer.
2. Create an object layer and set a "wall" or "ground" property to it. Use rectangles to draw ground.
3. In your code, iterate through the these rectangles and create physics invisible objects that will serve as ground. Something like this:

```
for (TMXObjectGroup tog : tmxMap.getTMXObjectGroups()) {
    if (tog.getTMXObjectGroupProperties().containsTMXProperty(
            "type", "wall")) {
        for (TMXObject to : tog.getTMXObjects()) {
            final Rectangle wall = createWall(to);
            scene.attachChild(wall);
        }
    }
}

```

I use exactly this and the following method to create the walls (not just ground).

```
private Rectangle createWall(TMXObject to) {
    final Rectangle wall = createPhysicsRectangle(to);
    wall.setVisible(false);
    PhysicsFactory.createBoxBody(physics, wall, BodyType.StaticBody, Constants.WALL_FIXTURE);
    return wall;
}

```

In my case `Constants.WALL_FIXTURE` is a non-elastic, high-friction, no mass fixture.
> 0 votes

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


# Question
Title: How to skip the sky in lighting shaders?
I recently implemented a sky in my deferred rendered game. It is a procedurally calculated sphere with a texture applied to it. Unfortunately all lighting shaders (light sources, ambient occlusion) are applied to that sky dome geometry as well.

Therefore the sky is completely dark without a huge light source in the level. And if there is one, the edges between triangles of that sphere are darkened by the ambient occlusion shader.

My quick and dirty fix was to read the depth texture to determine whether the lighting effect should be applied or not. For example, the view distance is `1000.0f` and every pixel with a depth higher than `900.0f` isn't shaded anymore. That works partly since every pixel of the sky is between `900.0f` and `1000.0f`.

But there are some issues with this approach. For example level geometry further away than `900.0f` isn't shaded, too. Moreover the depth values come from projecting the scene on a plane, the screen. That means that the distance to the sky, which is equally in all directions from the players world position, differs over the image. Sky seen on the sides of the screen is nearer than sky pixels seen in the center of the screen. That effect varies with the field of view setting. The issue with that is that for every field of view setting I would need different depth thresholds for shading.

Is there a common way to not, or differently, shade some pixels of the image? In my case, I would need to not shader sky pixels. If I could determine which pixel is from the sky, I could store that in a buffer and read from that in lighting shaders to skip those pixels. But I have no idea how to approach this.

# Answer
> 3 votes
I ended up using the stencil buffers. Basically, this are the steps my application goes through every frame.

* Draw geometry except skydome and set stencil buffer to `1`.
* Disable depth mask to not distort depth buffer.
* Draw skydome where stencil is still `0`.
* Use stencil test to only compute lighting and other shader computations where stencil is `1` and therefore where geometry is.
* Disable stencil test for computations which include the sky, like antialiasing and user interface.

# Answer
> 7 votes
You can easily use the Z-Buffer to render only the pixels that matter during skybox/light passes.

I render the skybox last (after all lights). When rendering the skybox, make sure your depth buffer is still intact and use GL\_GEQUAL for the depth function. Then in the vertext shader of the skybox, set the z value of gl\_Position to its w value. This makes sure the skybox is rendered onto the far plane.

If you want to skip the rendering of skybox pixels during the rendering of ligths, you can set the z-clear value to 1 and use GL\_LEQUAL for depth comparison during the light pass.

# Answer
> 1 votes
I'd suggest using the alpha channel of your color buffer to store a "lighting factor", which you can then use to linearly interpolate between a lit and unlit version of your geometry. Alternatively, using max seems attractive too - the calculation might be something like:

```
max (litColor * unlitColor.a, unlitColor)

```

The reason why that would appeal is that you could use it for other effects too, such as glowing regions on textures, or lightning flashes lighting up clouds in your sky. It also means that your stencil buffer remains unused, and therefore available should you also wish to use it for something else.

---
Tags: c++, opengl, deferred-rendering, sky, shading
---


# Question
Title: How can I load 24-bit audio as SoundEffect?
When I try to load .wav file I get an error:

> Audio file \*.wav contains 24-bit audio. Only 8-bit and 16-bit audio data is supported.

Here is my code:

```
SoundEffect menuSelectionChange = content.Load<SoundEffect>("Sound/Menu Selection Click");
SoundEffectInstance menuSelectionChangeInstance = menuSelectionChange.CreateInstance();

```

Even if I delete this code I'm still getting this error.

# Answer
You need to downsample your source audio file.

Digital audio is stored as a series of "samples" ("samples" of what a microphone "hears"). There are 2 aspects to sampling: sample *rate*, and \_bits used *per* sample\_. High quality audio is captured at something like 44100 samples *per second*.

Each sample is just a number though, so that's where "bits per sample" comes in. You can use 8 bits, (usually as type `unsigned char`), 16 bits (shorts) or even 24 bits per sample to store the audio data.

XNA doesn't seem to like 24 bits per sample. So you need to open the file and re-save it as 16 bits per sample.

Goldwave does this nicely
> 3 votes

---
Tags: xna, c#, audio, sound-effects
---


# Question
Title: Why was the DirectX mesh interface removed?
I'm currently working with D3D 11 and if I understood it correctly, D3D 10 had a mesh interface built in to it which was removed in 11.

If this is correct, why was the mesh interface removed? It seems like a useful interface to have.

# Answer
> 6 votes
D3D10 core didn't have a mesh class; you're probably thinking of ID3DX10Mesh, which is actually part of the D3DX API. D3DX itself was wholly deprecated with Windows 8. The relevant math bits were moved into another library. The higher-level utility interfaces, like mesh, were not ported.

The API was removed because it was a continuation of the evolving focus of D3D and its related APIs: to become narrower in scope, more representative of only the underlying graphics hardware. APIs like the mesh interface were an attempt both to provide something much higher level than the GPU actually does, and to be a one-size-fits-all solution (which is often a lowest-common-denominator solution).

Furthermore, by divorcing the graphics library from the utility library, it's easier for Microsoft to utilize separate (and more appropriate) release vehicles for both, and easier for the components to be updated and versioned independently.

All of the above factors contributed significantly to the decision to deprecate the functionality (which had been underway since the 9-to-10 transition, when the built-in functionality to load meshes from `.x` files vanished).

You should look at the DirectXTK or DirectXTK12 for potential replacements to interfaces you miss from D3DX.

---
Tags: directx11, directx10
---


title: Application of Game trees in AI

text:
# Question
Title: Application of Game trees in AI
My specific area of interest is designing the AI of real-time multiplayer games, for example, RTS games. Moves by players happen simultaneously, so I was wondering whether or not it would be modeled with a sequential (extensive form) game tree or something else. I don't know if this is even the correct approach at all, and if some other algorithms are more applicable.

How much of Artificial Intelligence design is based off of game trees or extensive-form games, and are there any suggested textbooks which thoroughly cover the subject game tree application to AI or AI of RTS games?

# Answer
> 2 votes
I will give this Question a partial try.

I guess that Game Trees are the same as decision trees and the answer to the question is, sure, why not.

But this alone will not solve the riddle for a RTS AI, you will need a combination of ai techniques to get the task done.

Some techniques you may want to use/combine:

(warning, the most of this is pure clasical ai stuff)

**Control**

* decision trees
* behaviour trees
* statemachines
* fuzzy logic
* recursive depth or Breadth-first search for planing tasks
* neural networks for more fuzzy stuff
* maybe even genetic algorithms/genetic programming for more fancy ai / emergent behaviour
* maybe even this Designing Emergent AI

to name only a few.

**Navigation**

* Dijkstra
* A-star

**Planing**

I have absolutly no idea about this field because i never programmed a rts ai, but take a look in the book i linked below.

---

**Books**

A very good book for Game AI Programming is Artificial Intelligence for Games.

---
Tags: game-design, ai
---


# Question
Title: How to obtain touch events from a GL Viewport, not the whole screen?
**Background**

I'm implementing viewport resizing in order for my game to maintain the same display ratio on all devices.

However, I've found an issue with getting touch events.

Basically, if my viewport, for example, uses the whole of the physical screen's width and height then there is no issue. However, if it is resized say in the vertical, then my touch events are thrown off, because touch events are registered from the top of the physical screen. Hence if I put a sprite at say position 50 in the Y direction then it put's the sprite 50 pixels down from the top of the *viewport*, **not** the top of the actual screen.

Do I have to manage this myself by adding my viewport's offset to my touch events or is there a way to tell Android to register 0, as the top of the viewport as opposed to the actual screen.

Here is a graphic to illistrate what I mean, any help would be appreciated

# Answer
You can see from the documentation related to touch events that touch events are related to the hardware screen, for example related to the x-axis:

> For a touch screen, reports the absolute X screen position of the center of the touch contact area. The units are display pixels.

The events are not affected by the viewport.

You can, however, easily get the viewport relative positions by subtracting the offset from the y value returned by the touch event.
> 2 votes

---
Tags: opengl, android, touch, viewport
---


title: XNA Level Select Menu

text:
# Question
Title: XNA Level Select Menu
I'll try to explain this the best I can. I'm trying to create a level select menu for a game I'm making. The menu is basically a group of blocks numbered 1-16, similar to something like the Angry Birds menu. What I've done is created a cursor, basically just an outline to surround a block, that the user can move to select what level they want to play. What I want it do is move from block to block instead of simply moving around on the X and Y axes as it does now.

So my question is, how can I get the cursor (highLight in the below code) to move from block to block(destinationRectangle1 etc. in the code)?

```
        /// Field for the "cursor"

        Vector2 highLightPos = new Vector2(400, 200);

        ///This is the Update code

        KeyboardState keyBoardState = Keyboard.GetState();
            if (keyBoardState.IsKeyDown(Keys.Up))
                highLightPos.Y--;
            if (keyBoardState.IsKeyDown(Keys.Down))
                highLightPos.Y++;
            if (keyBoardState.IsKeyDown(Keys.Right))
                highLightPos.X++;
            if (keyBoardState.IsKeyDown(Keys.Left))
                highLightPos.X--;

        /// This is the draw code

        SpriteBatch spriteBatch = ScreenManager.SpriteBatch;

        Rectangle screenRectangle = new Rectangle(0, 0, 1280, 720);

        Rectangle destinationRectangle1 = new Rectangle(400, 200, 64, 64);
        Rectangle frameRectangle1 = new Rectangle(0, 0, 64, 64);

        Rectangle destinationRectangle2 = new Rectangle(500, 200, 64, 64);
        Rectangle frameRectangle2 = new Rectangle(64, 0, 64, 64);

        Rectangle destinationRectangle3 = new Rectangle(600, 200, 64, 64);
        Rectangle frameRectangle3 = new Rectangle(128, 0, 64, 64);

        Rectangle destinationRectangle4 = new Rectangle(700, 200, 64, 64);
        Rectangle frameRectangle4 = new Rectangle(192, 0, 64, 64);

        Rectangle destinationRectangle5 = new Rectangle(800, 200, 64, 64);
        Rectangle frameRectangle5 = new Rectangle(256, 0, 64, 64);

        Rectangle destinationRectangle6 = new Rectangle(400, 300, 64, 64);
        Rectangle frameRectangle6 = new Rectangle(320, 0, 64, 64);

        Rectangle destinationRectangle7 = new Rectangle(500, 300, 64, 64);
        Rectangle frameRectangle7 = new Rectangle(384, 0, 64, 64);

        Rectangle destinationRectangle8 = new Rectangle(600, 300, 64, 64);
        Rectangle frameRectangle8 = new Rectangle(448, 0, 64, 64);

        Rectangle destinationRectangle9 = new Rectangle(700, 300, 64, 64);
        Rectangle frameRectangle9 = new Rectangle(0, 64, 64, 64);

        Rectangle destinationRectangle10 = new Rectangle(800, 300, 64, 64);
        Rectangle frameRectangle10 = new Rectangle(64, 64, 64, 64);

        Rectangle destinationRectangle11 = new Rectangle(400, 400, 64, 64);
        Rectangle frameRectangle11 = new Rectangle(128, 64, 64, 64);

        Rectangle destinationRectangle12 = new Rectangle(500, 400, 64, 64);
        Rectangle frameRectangle12 = new Rectangle(192, 64, 64, 64);

        Rectangle destinationRectangle13 = new Rectangle(600, 400, 64, 64);
        Rectangle frameRectangle13 = new Rectangle(256, 64, 64, 64);

        Rectangle destinationRectangle14 = new Rectangle(700, 400, 64, 64);
        Rectangle frameRectangle14 = new Rectangle(320, 64, 64, 64);

        Rectangle destinationRectangle15 = new Rectangle(800, 400, 64, 64);
        Rectangle frameRectangle15 = new Rectangle(384, 64, 64, 64);

        Rectangle destinationRectangle16 = new Rectangle(600, 500, 64, 64);
        Rectangle frameRectangle16 = new Rectangle(448, 64, 64, 64);

        spriteBatch.Begin();
        spriteBatch.Draw(forestBG, screenRectangle, Color.White);
        spriteBatch.Draw(highLight, highLightPos, Color.White);
        spriteBatch.Draw(levelSelectTiles, destinationRectangle1, frameRectangle1, Color.White);
        spriteBatch.Draw(levelSelectTiles, destinationRectangle2, frameRectangle2, Color.White);
        spriteBatch.Draw(levelSelectTiles, destinationRectangle3, frameRectangle3, Color.White);
        spriteBatch.Draw(levelSelectTiles, destinationRectangle4, frameRectangle4, Color.White);
        spriteBatch.Draw(levelSelectTiles, destinationRectangle5, frameRectangle5, Color.White);
        spriteBatch.Draw(levelSelectTiles, destinationRectangle6, frameRectangle6, Color.White);
        spriteBatch.Draw(levelSelectTiles, destinationRectangle7, frameRectangle7, Color.White);
        spriteBatch.Draw(levelSelectTiles, destinationRectangle8, frameRectangle8, Color.White);
        spriteBatch.Draw(levelSelectTiles, destinationRectangle9, frameRectangle9, Color.White);
        spriteBatch.Draw(levelSelectTiles, destinationRectangle10, frameRectangle10, Color.White);
        spriteBatch.Draw(levelSelectTiles, destinationRectangle11, frameRectangle11, Color.White);
        spriteBatch.Draw(levelSelectTiles, destinationRectangle12, frameRectangle12, Color.White);
        spriteBatch.Draw(levelSelectTiles, destinationRectangle13, frameRectangle13, Color.White);
        spriteBatch.Draw(levelSelectTiles, destinationRectangle14, frameRectangle14, Color.White);
        spriteBatch.Draw(levelSelectTiles, destinationRectangle15, frameRectangle15, Color.White);
        spriteBatch.Draw(levelSelectTiles, destinationRectangle16, frameRectangle16, Color.White);
        spriteBatch.End();

```

PS, I'm aware that this code is probably inefficient, cumbersome or that there's a better way to draw parts of a tile sheet. Any suggestions would be appreciated.

# Answer
> 1 votes
There are many solutions to this, but my favorite is to make an array of positions for these rectangles. For 16 levels, it would be a 4x4 array. Then have a variable representing which element of the array is "selected", and a variable representing the current position of the highlighter.

Now in your update function, always move the highlighter x% of the way toward the selected rectangle. Say, 5% to start, then adjust to get the desired speed.

This creates a smooth movement, which is always a nice effect, and it prevents glitches if the user moves the selection a second time before the highlighter reaches the first destination.

This also makes the controls easy, as when the player hits an arrow key you can just add or subtract one to the "selected" variable's x or y component.

This is just a theoretical explanation, but I hope it helps.

# Answer
> 1 votes
I would put both Rectangles into a List(s):

These are class level! Do not make inside your Draw method... scary...

```
private List<Rectangle> destinationRect = new List<Rectangle>();
private List<Rectangle> frameRect = new List<Rectangle>();

destinationRect.add(new Rectangle(400,200,64,64)); // 1
frameRect.add(new Rectangle(0,0,64,64)); // 1

// do for rest //

```

Now \[class level again\] add these Color fields:

```
Color RegularColor = Color.White;
Color HighlightedColor = Color.Tomatoe;

```

A 'pointer' field:

```
private Vector2 _elementPointer = Vector2.Zero;
private int _pointerAsIndex = 0;

```

Now in your update method:

```
KeyboardState keyBoardState = Keyboard.GetState();

var moveAmount = Vector2.Zero;

if (keyBoardState.IsKeyDown(Keys.Up))
    moveAmount.Y = -1;
if (keyBoardState.IsKeyDown(Keys.Down))
    moveAmount.Y = 1;
if (keyBoardState.IsKeyDown(Keys.Right))
    moveAmount.X = 1;
if (keyBoardState.IsKeyDown(Keys.Left))
    moveAmount.X = -1;

var futureLevelSelectPos = _elementPointer + moveAmount;

if (InBounds((int)futureLevelSelectPos.X, (int)futureLevelSelectPos.Y))
{
   _elementPointer = futureLevelSelectPos;
   _pointerAsIndex = (int)(_elementPointer.Y * 4 + _elementPointer.X);
}

```

A helper method:

```
private static bool InBounds(int x, int y)
{
    return x >= 0 && x < 4 &&
           y >= 0 && y < 4;
}

```

Back to Drawing:

spriteBatch.Begin();

```
for (var i = 0; i < destinationRect.Count; i++)
{
    if (i != _pointerAsIndex)
        spriteBatch.Draw(levelSelectTiles, destinationRect[i], frameRect[i], RegularColor);
   else
        spriteBatch.Draw(levelSelectTiles, destinationRect[i], frameRect[i], HighlightedColor);
}

```

This will work best visually with a 4 x 4 grid so play around with the numbers and bounds checking to get the effect you want.

---
Tags: xna, menu
---


title: creating bounding box list

text:
# Question
Title: creating bounding box list
I'm trying to create a list of bounding boxes for each cube drawn, so I can use the boxes to intersect with a ray that my mouse position is casting, but I have no idea how. I've created a list that stores the boxes, but how am I getting the values from each box?

```
    for (int x = 0; x < mapHeight; x++)
        {
            for (int z = 0; z < mapWidth; z++)
            {
                cubes.Add(new Vector3(x, map[x, z], z), Matrix.Identity, grass);
                boxList.Add(something here);
            }
        }

    public Cube(GraphicsDevice graphicsDevice)
  {
    device = graphicsDevice;

    var vertices = new List<VertexPositionTexture>();

    BuildFace(vertices, new Vector3(0, 0, 0), new Vector3(0, 1, 1));
    BuildFace(vertices, new Vector3(0, 0, 1), new Vector3(1, 1, 1));
    BuildFace(vertices, new Vector3(1, 0, 1), new Vector3(1, 1, 0));
    BuildFace(vertices, new Vector3(1, 0, 0), new Vector3(0, 1, 0));

    BuildFaceHorizontal(vertices, new Vector3(0, 1, 0), new Vector3(1, 1, 1));
    BuildFaceHorizontal(vertices, new Vector3(0, 0, 1), new Vector3(1, 0, 0));

    cubeVertexBuffer = new VertexBuffer(device, VertexPositionTexture.VertexDeclaration, vertices.Count, BufferUsage.WriteOnly);

    cubeVertexBuffer.SetData<VertexPositionTexture>(vertices.ToArray());

}

```

There aren't any clearly defined variables for the bounds of each cube created, so where do I create the bounding box from?

# Answer
> 0 votes
Generate the corner vertices of your cube. Apply the cube's rotation matrix. Find the min/max of the transformed vertices. Construct an AABB from those. Apply the cube's translation. Done.

```
min_vertex = (+float_max, +float_max, +float_max)
max_vertex = (-float_max, -float_max, -float_max)

foreach vertex in vertices:
  vertex = apply(rotation, vertex)

  min_vertex = (min(min_vertex.x, x), min(min_vertex.y, y), min(min_vertex.z, z))
  max_vertex = (max(max_vertex.x, x), max(max_vertex.y, y), max(max_vertex.z, z))

return aabb(min_vertex, max_vertex) + translation

```

If all you have is a transformation matrix, this is even easier. Just multiple that matrix by each vertex and forget about separately handling rotation and translation. You can even handle scaling transforms that way.

# Answer
> 0 votes
If by bounding box you meant AABB, then you can write a general AABB computer by finding the min and max coordinate on each axis by looping over the world space points of your object. Usually each object will generate its AABB every frame, unless that object hasn't moved at all.

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


# Question
Title: How do you find games with a similar idea?
I'm thinking about making an indie game and want to know if there's maybe one with similar idea.

I'm not asking about my idea specifically, I just want to know how to find out if a game has the same idea as the one I want to implement.

# Answer
I would like to add my own answer, which had elements already propositioned by the other two users here. However, their suggestion isn't the same as mine.

As Patrick said, "There is no shortcut to experience" and Byte56 said, "It's a research task." Both are great answers, and both define quite well what I was going to say before reading them.

Find someone (or multiple someones) who have experience. A lot of experience. A priority would be experience in the genre and platform, but a secondary priority is always beneficial when it comes to experience in gaming period.

For example, I have been playing PC games for over 15 years, and for many years I would play 18 hours a day some days. Not only this, but I am a renaissance gamer who has played nearly all genres, excel at all of them and typically come out on top in competitive play no matter the game, have read books and endless numbers of articles on game design, and I'm a game developer. There are thousands of people like me on the internet, and they are often very easy to find because they don't just love to play games, they love to talk about them, love to boast of their experience, love to be vocal on forums. (Ex. you could find a multitude of people with MMO experience, dedicated, decades of experience across endless numbers of titles, on popular MMO forums. They would be easy to find when browsing these forums, and would be VERY likely to respond when polling them about their favorite genre.)

The reason I suggest asking someone with a ridiculous amount of experience is that people like me have lived and breathed gaming quite hardcore, often for their entire conscious existence. As anyone who is devoted or in love with a specific hobby, they will be exuberantly available to answer all sorts of questions. Example, if you are making a MOBA game, then ask gamers who are passionate about the MOBA genre. They will be very willing to share, and to share in detail. They will have the experience to know not only one game, but most likely every single MOBA game. Even the ones no one has ever heard of!

The first priority takes precedence of course, as for example someone like me, would be ignorant and incompetent if asked about Console gaming. You'd probably get an incredibly biased, erroneous opinion along with a rant about how their genre (ex. PC gaming) is better than the other platform (ex. console gaming) in every way. This would be useless and a waste of time. Someone devoted to one platform who despises the other would be blind to the benefits of experience of other platform games similar to yours.

If you cannot find multiple people who are both hardcore devoted gamers and developers, then you should find some of both. Not game developers, but people invested in game design theory. There are plenty of gamers who don't know why the like one game but not another similar title. There are plenty of game developers who don't even think their ideas through before implementing them. However, the more experience one has, the most likely they've thought in depth about their hobby or theories before.

As Patrick suggests, nothing beats experience. Those who have significant experience about professional opinions, books, articles, or blogs, will not have their own thoughts, but will have a collection of understanding of game design theory from everything they've ever read. This can include thoughts from extremely experienced "master" game developers such as those who are part of "the greats".

When you lack the experience, get the thoughts and opinions from those WITH experience. I myself love to read what players think when they have been gaming for as long as me. However, it is difficult to take people seriously when they talk about how they have only played a very specific genre, only a handful of games, for a meager amount of time, but think they will revolutionize the genre with their game idea.

Part of what I find to be true in ANY field is this: Those who make quality products are those who know about the product firsthand, OR those who hire or outsource knowledge about the product firsthand. Most people who try to make a product (ex1. a business man who tries to make a AAA next-gen video game but doesn't know how to turn on their console without tech support) produce a horrid product and then are confused as to why their project failed. Another example are game design theorists or newbie game developer wanna-be's who post on forums "I have a really good idea..." and the contents within have horrendous flaws that anyone who plays the type of game could see immediately. It is not the scope of their project that results in facepalms, but their lack of experience in game design or the experience in design theory.

With all that said- finding experienced gamers, and you will immediately get a long list of similar games. A list that would include games that no one would think are similar, but due to a specific feature are in fact similar. Not only this, but in-depth details as to what similarities the games have to yours, how the features played out in the other games, and good/bad reviews of the features within each game on the list.

Why go out and do research on your own using something as vague and crap-friendly as google, when you have a massive network of human beings with decades of experience and tens of thousands of hours devoted to playing games? It's not a hard task for them, because they have ALREADY finished the research, and you can find enough of them to get a basic understanding as to what is a common complaint or praise to your game's features, based on their collective experiences.
> 6 votes

# Answer
It's a research task. You need to define your game well enough to assign a genre to it. Then find games in the same genre. Watch play videos, read descriptions, buy and play the games, etc.

(Further, you can post about your game online somewhere, and you can be sure that someone will question why you're making a clone of game X.)

However, as Code Assassin said, you should just try to make the game you want to make. It doesn't matter what someone else has made. Playtesting your own game should give you ideas on how to improve the features you've implemented.
> 3 votes

# Answer
**There is no shortcut to experience.**

For one directed avenue to achieve this experience check out David Perry's Game Challenge

You may also start working on your google skills to track down genre reviews and then read more deeply into titles that sound interesting. There is a drawback to this in that by only searching for genre titles you'll miss out on good ideas from outside, I think that cross-pollination is important to keep things fresh.

And don't forget about non-computer games, board games and dice have been around since before the ancient Egyptians.

It all comes down to playing a lot of games, reading a lot of reviews, following game forums, and it's a lot of time and work.

In your case, so this doesn't take a lifetime, I'd start with just one day of google and try many different searches (for example: "2d platformer with jumping") to get a broad overview. Then on day two only read the small number that you found interesting.

Then, like the other answers will most likely tell you, **go do what you want =)** and let testing help you decide what's a fun combination of features for your vision.
> 3 votes

---
Tags: 2d, platformer
---


# Question
Title: My game seems to be incompatible with recording software. What could be causing this?
I've just finished a little Game-Dev project for university and I need to record a video to accompany my submission (just in case they can't get my source to work). Basically my game doesn't work at all when FRAPS or Bandicam attempts to attach to it, I get a black screen and a stream of GL INVALID OPERATION messages from my error reporting code. Dxtory can't seem to hook into it correctly at all, it doesn't display it's FPS counter or anything. My game logic appears to be running correctly from the debug traces, it just seems like all the gl library calls break.

I don't know a huge amount about how these programs operate so I don't really know what I could be doing to cause this. I've heard they read from the OpenGL frame buffers so maybe I'm doing something wrong there? I'm letting GLFW and GLEW do all the low level initialization, but I have successfully recorded projects with the same setup and recording software.

Essentially, has anyone ever run into something like this before or do you know anything about how these programs work that could give a clue as to the cause of the issue?

# Answer
This question was answered and resolved by Vangel.

Would like to add this answer because no one else will, nor has for 2 months, but this is appearing at the top as "Unanswered" and in need of help.

Would vote to close if I could.

> Please can you try with OBS/Open Broadcaster software? It requires a bit of learning but it can usually tell you which version (32/64bit) to use and what applications/games it can detect. There is a good how to somewhere online on using OBS as well. It can do both Desktop and Game mode.
>
> – Vangel Apr 30 at 16:29

Replied by Asker,

> Cheers Vangel. OBS seems to work perfectly. I had to recompile my game as a non-console application but afterwards it worked fine. I also got a very low ammount of frame drop compared to what I'd expect from recorders. If you want to officially answer I'll accept it as correct.
>
> – Lewis Wakeford Apr 30 at 18:23
> 3 votes

---
Tags: c++, opengl, glfw, screen-recording
---


# Question
Title: The right way to add images to Monogame/Windows
I'm starting out with MonoGame. For now, I'm only targeting Windows (desktop -- not Windows 8 specifically).

I've used a couple of XNA products in the past (raw XNA, FlatRedBall, SilverSprite), so I may have a misunderstanding about how I should add images to my content.

**How do I add images to my project?**

Currently, I created a new Monogame project, added a folder called "Content," and added images under there; the only caveat is that I need to set the `Copy to Output Directory` action to one of the `Copy` ones.

It seems strange, because my "raw" XNA project just last week had a `Content` project in it (`XNA Framework Content Pipeline`, according to VS2010), which compiled my images to XNB (I think). It seems like Monogame doesn't use the same content pipeline, but I'm not sure.

**Edit:** My question is not about "how do I get the XNA content pipeline to work with Monogame." My question is "why would I want to use the XNA content pipeline in Monogame?"

Because there are (at least) two solutions (that I see today):

* Add the images to the Monogame project and set the `Copy to Output Directory` options to copy.
* Add a XNA content pipeline project and add my images to *that* instead; reference it from my MOnogame project.

Which solution should I use, and why? I currently have a working version with the first option.

# Answer
There is, in fact, a way around the Content Pipeline if you can't use it, at least for image dependencies: Use the TitleContainer class to load your dependencies in their raw forms:

```
// Load a Texture2D from a file
System.IO.Stream stream = TitleContainer.OpenStream("Content/My Sprite.png");
mySpriteTexture = Texture2D.FromFile(GraphicsDevice, stream);

// Load a SoundEffect from a file
// (NOTE: This is NOT in the current version of MonoGame)
stream = TitleContainer.OpenStream("Content/My Sound.wav");
mySound = SoundEffect.FromStream(stream);

```

These work wherever the Xna Framework can be used, but where the Xna Content Pipeline is not available or is too inconvenient.
> 3 votes

# Answer
What I do, is create an XNA project inside of my MonoGame solution. I set the compile location of this "Dummy" project to point to the same location that MonoGame compiles to.

When you build your project, the XNA Content project will convert your images to XNB files in the same location as your MonoGame binaries.

You need to use the XNA content pipeline in order to get your XNB files, there is currently no way around this if you are writing a MonoGame project.

I then delete the dummy.exe file if I am submitting a release.
> 2 votes

# Answer
I have got it to work by having an open XNA solution which i add the jpg's or png's to then rebuild.

I then copy this over to the content folder in the MonoGame solution and set it to a Content type in the properties.

I understand the monogame team are attempting to build a content pipeline but i'm not sure where they are up to it
> 1 votes

# Answer
The reason to use the content pipeline can be found in the Microsoft XNA documentation.

> The chief reason XNA Game Studio uses a Content Pipeline is to help your game run fast. Without the content pipeline, your game would have to be built with its art assets in their original file format. When the game needs to load its art to draw it on the screen, it would have to determine its format and convert the data into a form it can use more directly. This would have to be performed at run time, for each asset, making the player wait to have fun.

The downside is the extra effort required to setup a content project and manage the process of building your optimized XNB files. Here's a quote taken from the link in your question for clarity.

> The trouble using XNA content builder outputs on other platforms is that the XNB files it outputs are platform specific, MonoGame has gotten around this with its own multi-platform builder project allowing the creation of compiled assets for all its target platforms. It’s one deficiency is that it depends on the original XNA content project template which is still only available in VS2010 (express will do). Fear not however there are plans for a more open source version.

As you have already discovered, with MonoGame it's not necessary to use XNB files because you can add the raw content directly to the project. For a smallish project I think that's fine. It's what I've been doing with all of my projects thus far and I haven't had any issues (yet).

A word of caution though, things *may* change a little once the MonoGame team have finished implementing their own content pipeline. Here's a quote from a forum post I posted a while back.

> It's not necessary to use XNB files. They are simply the format that the ContentManager reads (MonoGame's ContentManager currently reads other formats such as JPG, PNG, etc, but that will be removed when we get a Content Build Pipeline going).
>
> The benefit to using XNB is that it is pre-processed into a format that is ready to be used directly by the GPU (in the case of GPU assets). Loading a PNG requires decompression of the PNG, perhaps some channel swapping (red and blue particularly) and then copy that uncompressed data into a Texture2D. If the texture has alpha, you would most likely need to pre-multiply the alpha for every pixel yourself. This is all done at load time. For XNB, the decompression, channel swapping and most importantly, pre-multiplication of alpha is done at build time. You can also optimize further as I have done in some of my games in that I output a dithered 16-bit texture to the XNB to save on memory use and bandwidth rather than the 32-bit default format.
>
> Loading from PNG is fine if it works for you. There are some trade-offs for the convenience, but they won't matter to most developers.

Lastly, if you do decide to go down the Content Pipeline path, this documentation might be helpful.
> 1 votes

---
Tags: sprites, monogame
---


# Question
Title: Playing part of a sfx audio file in HTML5 using WebAudio
I have compiled all of my sound effects into one sequenced .ogg file. I have the start and stop times for each sound effect. How do I play the individual effects? That is, how do I play part of an audio file.

More specificially, I've created a dictionary

```
{
    'sword_hit':
    {
        src: 'sfx.ogg',
        start: 265, // ms
        length: 212 // ms
    }
}

```

that my play\_sound() function can use to look up 'sword\_hit' and play the correct audio file at the correct start time for the correct duration. I simply need to know how to tell the WebAudio API to start playing at start ms and only play for length ms.

# Answer
> 3 votes
Read official docs on AudioBufferSourceNode. You can use `start` method's `offset` and `duration` parameters to play a sound in your sequenced file by setting `offset` where a particular sound effect starts in the file and `duration` to how long the effect is.

Example:

```
var context = new AudioContext();

function playSoundEffect(start, length) { //Ex. start=265, length = 212
    var source = context.createBufferSource();
    source.buffer = sequencedSoundBuffer; //loaded from your sequenced.ogg file
    source.connect(context.destination);
    source.start(0, start/1000, length/1000); //Convert from ms to seconds
}

```

---
Tags: html5, audio, chrome
---


title: Grid Based Lighting in XNA/Monogame

text:
# Question
Title: Grid Based Lighting in XNA/Monogame
I know that questions like this have been asked many times, but I have not found one exactly like this yes. I have implemented a top-down grid based world in Monogame, and am starting on the lighting system soon. How I want to do lighting is to have a grid that is 4 times wider and higher, basically splitting each world tile into a 4x4 system of "subtiles". I would like to use a flow like system to spread light across the tiles by reducing the light by a small amount each time. This is kind of the effect I was going for:

https://i.stack.imgur.com/ToHPi.png

The black grid lines are the light grid, and the red lines are the actual tile grid, and the light drop-off is very exaggerated. I plan to render the world by drawing the unlit grid to a separate RenderTarget2D, then rendering the lighting grid to a separate target and overlaying the two.

Basically, my questions are:

1. What would be the algorithm for a flow style lighting system like this?
2. Would there be a more efficient way of rendering this?
3. How would I handle the darkening of the light with colors, reducing the RGB values in each grid, or reducing the alpha in each grid, assuming that I render the light map over the grid using blending?
4. Even assuming the former are possible, what BlendState would I use for that?

# Answer
> 1 votes
A floodfill lighting system should do what you want.

First, set the light value of source tiles to 1, and all other tiles to 0. Next, to propogate the light, use a recursive DFS function to set light values of neighboring tiles to some attenuation of the source light.

So essentially, you would have something like:

```
void PropogateLight(float sourceLight, int toX, int toY)
{
     if(tiles[toX][toY].Light >= sourceLight) return;

     float newLight = attenuate(sourceLight);

     if(newLight < 0)
     { tiles[toX][toY].Light = 0; return; }

     tiles[toX][toY].Light = newLight;

     PropogateLight(newLight, toX + 1, toY);
     PropogateLight(newLight, toX - 1, toY);
     PropogateLight(newLight, toX, toY + 1);
     PropogateLight(newLight, toX, toY - 1);
}

```

Once you have the light values set, just do:

```
spriteBatch.Draw(texture, position, new Color(light, light, light));

```

---
Tags: xna, c#, algorithm, lighting, grid
---


# Question
Title: What is the purpose of bitdepth for the several components of the framebuffer in glfwWindowHint function of GLFW3?
I would like to know what are the following "framebuffer related hints" of GLFW3 function glfwWindowHint :

GLFW\_RED\_BITS GLFW\_GREEN\_BITS GLFW\_BLUE\_BITS GLFW\_ALPHA\_BITS GLFW\_DEPTH\_BITS GLFW\_STENCIL\_BITS

* What is the purpose of this?
* Usually their default values are enough?
* Where are those bits stored? In a buffer in the GPU?
* What do they affect? And by that I mean in what way

Thank you in advance!

# Answer
These flags allow you to specify the formatting of your color target, and depth stencil buffers that are a part of the final frame buffer.

The color target is typically formatted in a R8G8B8A8 format, providing 8 bits of precision for each color, and the alpha channel. This gives a total of 32 bits.

The final two flags specify formatting for the depth stencil, this is typically formatted as D24S8, and this indicates 24 bits of precision for the depth buffer, and 8 bits for the stencil. Higher precision on the depth buffer allows for more accurate depth testing when checking for overdraw.

When the frame buffer targets are created, it will use these formatting specifiers to indicate to the rendering pipeline how to interpret the data when reading from and writing to it. These buffers are allocated in VRAM to provide faster access to the GPU.
> 3 votes

---
Tags: c++, opengl, frame-buffer, glfw
---


# Question
Title: Show path of a body of where it should go after linear impulse is applied
I am making a game with Andengine and Box2D. I have a dynamic body and I apply linear impulse on the body to move it around when the user have touched the screen.

Now I want to show the path where the body will go when the user have touched. If you have played Angry Birds or Basket Ball Shoot or any other which have projectile motion with a path shown you will get my point. I want to show the white dots which are shown in those games.

# Answer
> 5 votes
To get the best result, you need to run the simulation like if you actually threw the projectile - just fast forward! And that is quite easy in any Box2D port. In AndEngine call method `step(float timeStep, int velocityIterations, int positionIterations)` from class `com.badlogic.gdx.physics.box2d.World` in a loop to run it as fast as you want. You can apply arbitrary forces at the beginning or between each two steps.

Note that in AndEngine the `World` class is wrapped in class `PhysicsWorld` that doesn't give you direct access to the instance of `World`. However you can extend `PhysicsWorld` to get access to `protected` fields, or you can simply call `onUpdate` method. This one updates all AndEngine physics connectors as well.

Just be careful with the performance, play with the parameters. Maybe create a clone of your physics world that will be simplified, containing just the objects directly needed for the simulation.

# Answer
> 2 votes
Two options come to mind, although I don't know if either is the most efficient route. (I also have no idea if your libraries already have functionality for this).

Option 1 is to simulate the path of the body each time the touch location changes, and draw a line or dots across the path. The advantage is that this will definitely give you an accurate path at the expense of unnecessary computation.

Option 2 is to derive an algorithm using quadratic equations etc to draw the dots based on a simple parabola. This would require knowing how the engine simulates the movement of the dynamic body. Advantage is that this is far more simple and scalable from the perspective of computation, but it won't lend itself well to changing the physics of the system, not to mention difficult physics math.

---
Tags: physics, box2d, andengine
---


# Question
Title: C# and Unity - Learning to Develop a game by developing the game I want to develop
So I am pretty new to C#, I have some python and javascript experience, but nothing substantial.

I have read a lot about C# and Unity and I know they are the tools I want to use.

**My question is: Should I be reading books about C# or should I just start hacking in unity and piecing the game together part by part?**

Right now I am going through the book, HeadFirst C#, and it is very good, but I taught myself web design and javascript by just creating and hacking until I got the results I wanted then looked at other code to see ways they did it and improved my code.

The issue is that with the browser I got immediate results and it was all under one roof, where developing games is a completely different monster. I am just wondering if my time would be better spent buying a book that uses C# to teach you unity, and doing that instead, or if the time spent in HeadFirst book is going to be valuable.

Thanks a ton, I am having difficulties using my time, and I just want to maximize it as I don't have a lot of free time.

Edit: Hopefully this isn't to broad? If it is, I will delete and go elsewhere just let me know. Thanks.

# Answer
> 5 votes
Your question is incredibly broad but still very answerable.

This answer completely depends on your personal preference with the way you work and more importantly on what will make **you** as a developer finish a working game.

Will hacking together bits and pieces and *then* adding the polish later be easier for you to finish a working version of your game or would you prefer to structure it properly with a knowledge of C# first and then direct your project workflow with a plan, going in the correct direction from step 1 to final product?

This can be difficult to know and so my advice is to simply:

# Try.

There is nothing better than to try even if you initially fail. I myself learnt how to do the unity engine work by copying Half Life 2 puzzles (mainly the physics based ones) into separate test levels in Unity3D. I did this to figure out how components and colliders worked together and how to write this in C# rather than JavaScript (which seems to dominate a lot of Unity scripting.) This then helped me work on my turret defense game by applying the same physics and collision detection to my mortar shells.

I could have read my way to the answer I needed easily and planned the components in C#. However, in actually doing a prototype and trying it myself from scratch without any set guidance I learnt not only what I needed to know for that problem at hand, but a lot more as well. The prototype level actually became used in the final project (showing that you can start with something rough and improve it after, just like you mentioned.) Also, who knows when this unnecessary extra knowledge won't become necessary in another section of the project?

Try it yourself and see what works for you. If you are going to learn C# and use Unity3D I would highly recommend the Unity tutorials online to understand the engine *separately* to the C# language. Once you have that under your belt - experiment. I look forward to seeing the results!

# Answer
> 1 votes
I am not familiar with the book *Head First C#* (or any programming book really, which should communicate to you how I feel about the necessity of reading programming books) but I'm pretty certain it's a bad choice for learning how to develop in Unity. That said, it may be a great resource for learning C# generally, so perhaps it would be worthwhile for you to learn C# outside of Unity for a bit before diving into Unity. I mean, I wouldn't recommend that approach, but perhaps *Head First C#* could be useful in that way.

I never read any books to get up to speed with Unity, and I'm the main client side developer on a Unity game (I was already extremely proficient at ActionScript 3 however, a language very similar to C# in the sense that both mostly copy their language design from Java). Personally I would recommend diving into projects and learning by doing, with the one caveat that as your learning projects get more complex you should really concentrate on object oriented development.

My path to getting proficient at game programming involved a year and a half at a job where I started with little experience in game programming. Because of that I wasn't being paid a ton, but the amount I learned made it one of the most worthwhile jobs I've had. While the whole approach of "get an entry level job in order to learn the process" may not be feasible if you have literally no previous experience at all (I was hired to develop web games, and I had already used Flash for a bunch of personal projects at that point), you could certainly replicate the aspects of that job which were so useful for learning. Specifically, that job pretty much amounted to a string of small two-week projects, and that is precisely how you should approach learning Unity, with a string of small learning projects (as opposed to trying to tackle something large right out of the gate).

---
Tags: c#, unity
---


# Question
Title: How to draw tile edges when you don't know where they're going.
This is more of an art question than a programing one but still game development.

I have a tile engine that makes a map randomly from tiles, each tile is a square 3x3 grid. The problem is that while the elements on each tile work well together such as having forests along the top three squares and grass on the other 6, the engine could put the forrests against anything such as rivers, grass, mountains or more forest.

how can i draw the edges of the tiles so the look good no matter what they are places against ?

# Answer
You are should look into auto tiling. There are two prevailing methods as to how to implement this.

The first assigns a bit value to each tile type, `tile_bit`, and a bit value to each tile surrounding the location, `loc_bit`. Multiplying `tile_bit` by `loc_bit` will give a unique value for every combination of surrounding locations. This very simple to do with only two or three types of tiles. More details here : http://www.saltgames.com/2010/a-bitwise-method-for-applying-tilemaps/

The second method instead divides each tile up into for sections. These four sections each get a bit value based on their neighbor tile's value. Then you can draw the appropriate tile that matches up with the four bit values. More details here : http://www.codeproject.com/Articles/106884/Implementing-Auto-tiling-Functionality-in-a-Tile-M

Both of these articles assume that you have every combination of transition drawn. This gives you greater control over the look of your map. However, this can get extremely tedious if you have a many tile types. Instead you can dynamics generate edges.

These articles talk about just having generic predrawn edge tiles and assembling them based on your map: http://www.xnaresources.com/default.asp?page=Tutorial:TileEngineSeries:6

http://www.gamedev.net/page/resources/\_/technical/game-programming/tilemap-based-game-techniques-handling-terrai-r934

This other topic also talks about even generating edges instead of drawing them. However I think this will just lead to a very crude edge most of the time: Map tile terrain transitions with 3-4 different types
> 6 votes

# Answer
It depends I suppose on how the different regions are rendered? (I.e, Do you generate a forest, then a river, then grass and glue them together? If that is the case you could manually provide the tiles that should go in between? A nice tile that indicates a tree next to a river and so on?

You could even provide a small region in between that interpolates between region A & B and makes the transition smooth. Let the forest end and provide some grass until the river region starts.
> 0 votes

---
Tags: tiles, tilemap
---


# Question
Title: Tutorial to port XNA game to MonoGame on iOS?
Are there any good tutorials to convert a current XNA game to work iOS using MonoGame?

# Answer
> 0 votes
I'm not sure if there are any specifically about porting to iOS yet but there are a few good tutorials around that might help. Check out this discussion on the forums lists current tutorials. https://monogame.codeplex.com/discussions/439595

There's also another related thread about ideas for new tutorials. https://monogame.codeplex.com/discussions/439728

I'm currently only using MonoGame to make games for Windows and port them to Android. I suspect the process is fairly similar though, and it's not too difficult. Give it a go and see if you run into any problems.

# Answer
> 0 votes
All you need to do is this:

Download Monogame And Mono, Along With Xamarin Studio.

Now Create A New Monogame iOS project. (You may get an error because i believe you can only make iOS projects on a Mac machine)

Now Copy All Of Your Code Files In.

Now For The Final Part, Put All Of The Built .XNB files from your projects Content Folder into your iOS's Content Folder As A Link To The Original XNB. (these should be located at ProjectName\ProjectName\ProjectName\bin\x86\Debug\Content)

From here, foreach of your .XNB files set there build action to 'Content' And Copy to 'Copy If Newer'. Now Test It And It Should Work. (this should work, for i have only tested this on android and not on iOS, but it should be the same process).

---
Tags: xna, ios, iphone, monogame
---


title: LWJGL Text Rendering

text:
# Question
Title: LWJGL Text Rendering
Currently in my project I am using LWJGL and the Slick2D library to render text onto the screen. Here is a more specific example:

```
    Font f = new Font("Times New Roman",Font.BOLD,18);
    font = new UnicodeFont(f);
    font.getEffects().add(new ColorEffect(Color.white));
    font.addAsciiGlyphs();
    try {
        font.loadGlyphs();
    } catch (SlickException e) {
        e.printStackTrace();
    }

```

then i use font.drawString to write onto the screen. This is a quick easy way but it has a lot of disadvantages. for example font.loadGlyphs take a very long time 1-3 seconds. so when i want to change a color or font type then i have to wait 1-3 seconds which means I cannot do it while rendering (ie. cant have different color text on the same screen).

My question is what is a better way of drawing multicolored text onto the screen? I use slick2d only for the text rendering so maybe i can fully get rid of the library and draw text some other way...

If you have an answer please leave a quick short example.

Thanks!

# Answer
I can't give you a short example using LWJGL alone, but what I can do is give you an way to solve your problem.

As I understand, you want to load one font at rendering time, and display it right away with multiple colours. My suggestion is to use Bitmap Fonts for this. Just use a tool (Example) to generate the bitmap font texture file and the textual file with the glyphs information, and load it to your engine.

The change of colours than becomes very easy, because all you have to do is generate white bitmap fonts (with transparent background), and draw the font texture using OpenGL to change its colours (like `glColor3f`) :)

\*Edit: No need for OpenGL shaders for this. Also, transparent background for the font is needed.
> 1 votes

# Answer
Remember to switch depth buffer off when drawing your font. Had same problem and this helped.

```
GL11.glDisable(GL11.GL_DEPTH_TEST);
// font drawing code here
GL11.glEnable(GL11.GL_DEPTH_TEST);

```
> 0 votes

---
Tags: rendering, lwjgl, fonts, text
---