# Question
Title: Is it possible to create an "impossible" rooms in games?
Forgive me my lack of knowlegde, but for quite a long time I asked myself whether it was possible to create a continous game space that some player could walk inside and so on, that would be absolutely impossible in reality, e.g. you have a very small house that allows you to go around it to see all sides and the full dimensions, and then, when you enter, it is like a giant hall, without any loading screen or (internal) "model change" and so on.

I'm no game designer and I never needed to learn 3D-modelling, so I don't know what is possible and what isn't. And is this the same as Is the "impossible object" possible in computer graphics? this? Or is it just the same category, but not exactly the same question?

Thanks.

# Answer
You can play a lot of tricks with space using portals (the rendering kind) - see Prey, Portal, or Antichamber, for examples. In case you're not familiar with this concept, it's much more than simply teleporting the player around - the renderer actually lets you see through the portal, so it can be completely invisible if that's what you want. Antichamber in particular uses invisible portals extensively to create the illusion of "continuous" impossible spaces. Also see this Youtube tutorial for an example of the sort of thing that can be done.

In an engine with good portal support (such as UDK), a house that's bigger inside than outside is easily done by modeling the inside and outside in separate locations, and placing portals at each door and window to connect them.
> 9 votes

# Answer
> Is it possible to create a continuous game space?

Well, it is possible to make the player feel that he/she is walking in continuous space, by procedurally generating the world, but I don't think that "true" continuous is possible, since the memory/processing usage will not be possible at some point even if you are going to use memory and hard disk if you want to save your already generated world.

> You have a very small house that allows you to go around it to see all sides and the full dimensions, and then, when you enter, it is like a giant hall.

This is not possible in 3D space math which is used in computer graphics. But I would say (only speculations) you might make the player "feel" something like this using Projective Geometry and by trying to draw (which will still happen in 3D ) something like Hyper Cubes.
> 1 votes

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


# Question
Title: Setting up cube map texture parameters in OpenGL
I see alot of tutorials and sources use the following code snippet when defining each face of a cube map:

```
for (i = 0; i < 6; i++)
    glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, InternalFormat, size, size, 0, Format, Type, NULL);

```

Is it safe to assume `GL_TEXTURE_CUBE_MAP_POSITIVE_X + i` will properly iterate the following cube map targets, `GL_TEXTURE_CUBE_MAP_NEGATIVE_X, GL_TEXTURE_CUBE_MAP_POSITIVE_Y, GL_TEXTURE_CUBE_MAP_NEGATIVE_Y` etc?

# Answer
> 2 votes
Yes, it is safe because if you look at the original extension spec for cubemaps, you can see that those enums are all defined as consecutive numbers.

> ```
> Accepted by the <target> parameter of GetTexImage,
> GetTexLevelParameteriv, GetTexLevelParameterfv, TexImage2D,
> CopyTexImage2D, TexSubImage2D, and CopySubTexImage2D:
>
>     TEXTURE_CUBE_MAP_POSITIVE_X_ARB     0x8515
>     TEXTURE_CUBE_MAP_NEGATIVE_X_ARB     0x8516
>     TEXTURE_CUBE_MAP_POSITIVE_Y_ARB     0x8517
>     TEXTURE_CUBE_MAP_NEGATIVE_Y_ARB     0x8518
>     TEXTURE_CUBE_MAP_POSITIVE_Z_ARB     0x8519
>     TEXTURE_CUBE_MAP_NEGATIVE_Z_ARB     0x851A
>
> ```

---
Tags: opengl, c++, windows
---


# Question
Title: How to make something happen every N seconds in game?
I want to have something happen every N seconds, how would I do that? Maybe use a timer but how?

# Answer
> 14 votes
A common approach for this is to use the update loop and delta time.

```
float timerCurrent = 0f;
float timerTotal = 5f;

Update() {
    timerCurrent += deltaTime;
    if(timerCurrent >= timerTotal) {
        //do timer action
        timerCurrent -= timerTotal;
    }
}

```

This supposes that you have access to a `deltaTime` variable. Delta time is simply the time that's elapsed since the last frame. Many engines will have this available to you, or you can learn more about setting up your own here.

# Answer
> 3 votes
In most languages, you need to start the clock with some kind of function call along the lines of `clock.startTimer()` before you enter the main loop. Then, you have to store the clock time value before you enter the main loop into a variable with a function like `time = clock.getTime()`. Store your step time into variable `n`.

In your main loop, the check you want to make is something along the lines of

```
if(time + n <= clock.getTime())
     //do stuff
     time = clock.getTime() //important to assign new time value here

```

Note: I'm not sure what language/library you are looking at so this is just a generic algorithm I thought of off the top of my head. It may not suit your needs exactly. Some languages/libraries require you to create a clock object while others you can simply make a function call directly.

As per the comments below, you must be careful with threading issues depending on which language you are using. You also should use a double float to store `time`.

# Answer
> 2 votes
As other answers already pointed out, implementing a timer can be done by incrementing a stored value by each frame's `deltaTime`, and comparing it to the expected duration. For completeness, I'll include code which is very similar to the other answers:

```
float elapsed = 0.0f;
float duration = 4.0f;

void update(float deltaTime) {
    elapsed += deltaTime;
    if (elapsed <= duration) {
        // Run code.
        elapsed = 0.0f;
        // Maybe remove from update loop?
    }
}

```

How you want to handle the `// Run code.` portion is up to you. Maybe you have a `Timer` class, an instance of which takes a `delegate` (C#) or a `callback` (C++) and calls it when the timer expires. Also, pausing the timer is a matter of removing it from the update loop.

An alternative approach is to mark the starting time of the timer, and instead do an on-demand calculation of elapsed time:

```
double startTime = 0.0; // This is a double for a reason, I'll explain below.
bool running = false;

void start() {
    startTime = getTime(); // This is whatever system time call you want to use.
    running = true;
}

double getElapsed() {
    double elapsed = getTime() - startTime;
    return elapsed;
}

```

This style gives a little more control to the user of the timer. The structure itself isn't concerned with what to do when the elapsed time reaches a certain point; it isn't even updating. The user can simply query the elapsed time when it's needed. This pattern has the unfortunate side-effect of not being debugger-friendly. System time continues on as your program is halted on a debugger, so timers like this will behave differently when stepping through programs. A potential solution to *that* is to maintain a program-specific elapsed time value which is updated every frame using system time deltas.

I think most important though are two quirks of timing on a computer, especially when it comes to game development. The first is floating point precision and the second is native timer resolution.

You'll note that in the second example, I used a `double` type instead of a `float`, as in the first example (the typename of course depends on the language you are using). The reason for this is the second example is storing *total elapsed game time*. If the game is left running for a very long time, single-precision floating point format values will have insufficient precision to accurately measure elapsed time, leading to stability issues. The first example is fine using the `float` type so long as huge durations are not expected.

On the other end of the spectrum, if the update time you're expecting is small enough, you may not actually be able to initially achieve it, depending on how you get system time. Timers will often be dependent on the timer resolution of the OS you are running on. For example, the default timer resolution of Windows 7 and below is 15.6 ms. This means that the lowest timer precision you could achieve using functions such as `timeGetTime` or `GetTickCount`, is 15.6 ms, unless you change the timer resolution (there are dangers associated with that, too).

Well, that turned out a bit long, but these are important things to be aware of when implementing timers.

---
Tags: game-design, timer
---


title: c++ most used libraries

text:
# Question
Title: c++ most used libraries
I'm trying to find out whether or not I want to switch from Java to c++ for my OpenGL game programming. I now have setup a test project in VS 11 professional, with GLUT. I created my windows with GLUT, and I can render OpenGL primitives without any problems.

Now my question: *What library(s) is/are used **mostly in the indie/semi professional industry** for using OpenGL in c++*?

With 'using OpenGL' I mean:

* Creating and managing an OpenGL window
* Actually using the OpenGL API
* Handling user-input (keyboard/mouse)

# Answer
> 1 votes
Qt, SFML, GLFW, SDL, GLUT. All do Windowing and Input. I've got more in depth descriptions and links here.

Qt is the only one that handles some of the OpenGL API itself (as opposed to just making the OpenGL context), but I'm not sure I would want to use it over native OpenGL and afaik it's only some things like shaders (and maybe a simple scene graph). Qt is also fairly heavy if you just want a basic game as it's a whole Widget toolkit.

As for directly interacting with OpenGL API there's not too much.

You will probably want an extension loader like GLEW. Also some support libraries that don't directly interface with OpenGL like GLM for matrix functions, assimp for mesh loading, and stuff like texture loading.

Other than that there are some C++ bindings that wrap the older raw C OpenGL API. I know of 2.

OOGL gives full object orientated bindings. However there are problems with OOP and OpenGL. One example is you can often set things like buffer attributes for your entire scene then just draw all the meshes with the same settings. With OOP it's not possible to do that and so you take an efficacy hit. There are also problems with side effects, for example some commands require things to be binded so a seemly simple command to change a shader property could change your active shader, Direct State Access, glProgramUniform (as opposed to glUniform\*) and similar functions could help avoid that to some degree but in the real world you will likely need fallbacks for older systems and they are probably still less efficient than doing things in bulk. There's also issues surrounding multiple OpenGL contexts.

The other library doesn't bother with OOP but just takes the C api and adds things like proper C++ types for type safety. Not sure it's worth the dependency though. I think OGLplus works that way (but I'm not %100 sure).

Realistically you would be better off targeting higher functionality and just using raw OpenGL under the hood. Instead of dealing with raw shaders/programs, deal with materials. And instead of directly calling the OpenGL API in the objects its probably better to put things into some kind of a render pipe (like a command list, but you can do things like sort meshes by material and draw them in one go). I haven't seen any libraries that just do that.

Otherwise you can go the next level and start looking at an engine and avoid directly deraling with OpenGL at all. For example Gameplay 3D

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


title: Models not rendering when far away

text:
# Question
Title: Models not rendering when far away
I am making a game where objects are represented by colored cubes. I have files that mark the location and rotation of the cubes. I've been using Processing's 3D library and the cubes disappear within a certain distance, like this:

Why is this happening?

# Answer
Try using the perspective() command to set a greater far drawing distance.
> 3 votes

---
Tags: opengl, 3d, processing
---


title: Lwjgl or opengl double pixels

text:
# Question
Title: Lwjgl or opengl double pixels
I'm working in java with LWJGL and trying to double all my pixels. I'm trying to draw in an area of 800x450 and then stretch all the frame image to the complete 1600x900 pixels without them getting blured. I can't figure out how to do that in java, everything I find is in c++... A hint would be great!

Thanks a lot.

EDIT : I've tried drawing to a texture created in opengl by setting it to the framebuffer, but I can't find a way to use glGenTextures() in java... so this is not working... also I though about using a shader but I would not be able to draw only in the smaller region...

# Answer
Try setting the texture filtering (`GL_TEXTURE_MIN_FILTER` and `GL_TEXTURE_MAG_FILTER`) to `GL_NEAREST`

`GL_NEAREST_MIPMAP_LINEAR` is the default on most platforms, which would explain the blurring you are getting.

this can be done using:

`glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)`

or your platforms equivalent.
> 2 votes

---
Tags: opengl, java, lwjgl
---


# Question
Title: How many VBOs should I use and should I keep a copy of their data?
Firstofall, I am sorry if my question is to broad.

I am developing a tile based game and switched from those gl.Begin calls to using VBOs.

This is kind of working allready, I managed to render a hexagonal polygon with a simple shader applied.

What I am not sure is, how to implement the "whole" tile concept.

Concrete the questions are:

* Is it better to create 1 VBO for a single tile and render it n-Times in every different position, or render one huge VBO that represents the whole "world"
* Depending on the answer above, what is the best way to draw a "linegrid". Overlay with the same vbo using the respecting polygon.mode , or is there a way to let the shader to this?
* How would frustum-culling or mousepicking work then, do i need to keep the VBO-data in memory?

# Answer
> Is it better to create 1 VBO for a single tile and render it n-Times in every different position, or render one huge VBO that represents the whole "world"

Less VBOs are usually better for performance (less draw calls) but are also harder to manage.

1 VBO per tile seems an overkill to me especially if you have a lot of tiles. 1 VBO to represent the whole world might or might not be ideal (usually it's not). You may want to use multiple VBOs especially for tiles that do not share the same material and texture. So I would say render tiles in one VBO when they:

* Share the same material.
* Tiles with spatial coherency which makes other operations such as transformation and frustum culling tiles much more intuitive).

> Depending on the answer above, what is the best way to draw a "linegrid". Overlay with the same vbo using the respecting polygon.mode, or is there a way to let the shader to this?

If I understand your question correctly just use the same VBO in a different draw call with different polygon mode supposedly `glPolygonMode(GL_FRONT, GL_LINE)` and revert to the original Polygon mode after that. As a note you might need to use Polygon offset to avoid Z-Fighting problems.

> How would frustum-culling or mouse picking work then, do i need to keep the VBO-data in memory?

You usually test against a bounding volume before testing the actual mesh you can store the bounding volume in world space or local space and do your intersection test accordingly.

If you want to test the actual mesh you can map your buffer using `glmapBuffer` and `glUnmapBuffer` to get pointer to your actual mesh data once it's stored on the gpu memory, or you can keep a copy of your mesh data in your main memory.
> 1 votes

---
Tags: opengl, tiles, vbo
---


# Question
Title: What makes a game responsive to user input?
Many games, like *"Super Meat Boy"* and *"Shank"*, have been praised for their responsive game play, where each user action input corresponds to a quick and precise character movement.

What makes a game responsive, and what prevents other games from achieving the same? How much of it is due to the game framework used to queue input events, and update the game, and how much is attributed to better coding?

# Answer
This is a tough question to answer, cause it really depends on the actual game. Usually there are many tricks involved to make a game feel responsive. The classic Mario games on consoles are often considered still being some of the best platformers due to awesome controls and responsiveness. They've got their own issues, but there are many things you can learn just by looking at them for a bit.

Here are some things to notice:

* Players are able to control their character any time. They can quickly try to change direction no matter where they are (even mid-jump). There are other platformers that don't allow you to steer while in the air, which is usually considered very bad and unresponsive.
* When trying to jump, the game allows you to do so even if you just ran off a cliff (just for a few milliseconds). This makes last-minute-jumps a lot easier and also avoids the game feeling like it didn't respond to your button press.
* The jump button usually considers how long you hold down the button, so the player has more control over the character (i.e. it's not just binary jump yes/no). Tap the button and you make a small hop, hold it down and you jump far further.

However, with networked games appearing over the last 15-20 years another problem surfaced when talking about responsiveness: Network latency. In theory you can write a simple client/server game, where you're sending your inputs to the server and the server will tell the client what to display. This will work rather well in a LAN, but it will feel very sluggish when played over the Internet. Imagine pressing the jump key, it takes 200 ms for your command to reach the server and another 200 ms for the result to be visible on your PC. We're suddenly talking about almost half a second delay, which will be noticeable. Due to such issues game clients usually allow the local client to immediately apply movement or actions and then compare that to the results sent back by the server. If the results don't match and there are significant corrections to be made, you'll get the effect often called "rubberbanding", which usually is not desired and makes a game feel very unresponsive (i.e. you're never able to move how/where you want).

Another possible reason for unresponsive gameplay can be low framerates, i.e. the game isn't able to react in time, simply due to you not seeing everything happen in time. This can also be a Timing issue, e.g. when your game logic is tied to your framerate even small slowdowns (like from 60 fps to 40 fps) will be noticeable, cause the game will run much slower at once.

And one last source for unresponsive or sluggish gameplay I can think of: Delays caused by calculations. For example, in an RTS game, you'll want to see your units move immediately when you issue a command. Due to pathfinding this might be delayed a bit, even if it's just one or two seconds, this can cause a bad experience (e.g. seeing the units being destroyed just due to moving too slow). To counter something like this, you can make rough guesses, e.g. let the unit start moving in the direction of the last known path or the new target position.
> 7 votes

---
Tags: game-design, architecture
---


# Question
Title: Rotation and translation like in GTA 1 OpenGL
Okay, so I have a figure in XZ plain. I want to move it forward/backward and rotate at it's own Y axis, then move forward again in the rotation's direction, like the character in GTA 1.

Code so far:

```
Init:
  spaceship_position = glm::vec3(0,0,0);
  spaceship_rotation = glm::vec3(0,0,0);
  spaceship_scale = glm::vec3(1, 1, 1);

Draw:
  glm::mat4 transform = glm::scale<float>(spaceship_scale) *
                        glm::rotate<float>(spaceship_rotation.x, 1, 0, 0) *
                        glm::rotate<float>(spaceship_rotation.y, 0, 1, 0) *
                        glm::rotate<float>(spaceship_rotation.z, 0, 0, 1) *
                        glm::translate<float>(spaceship_position);
  drawMesh(spaceship, texture, transform);
Update:
   switch (key.keysym.sym) {
   case SDLK_UP:
       spaceship_position.z += 0.1;
       break;
   case SDLK_DOWN:
       spaceship_position.z -= 0.1;
       break;
   case SDLK_LEFT:
       spaceship_rotation.y += 1;
       break;
   case SDLK_RIGHT:
       spaceship_rotation.y -= 1;
       break;
    }

```

So this only moves on the Z axis, but how can I move the object on both Z and X axis where the object is facing?

# Answer
> 0 votes
IIUC, your order of matrix multiplication looks incorrect. Essentially, what you are doing is:

```
transform = rot * trans

```

Which means that the object will be translated first and then rotated. After translation, the object won't be at the origin, but your rotation matrices will rotate it around the world axis, which is not what you want. The effect that you want is to rotate the object around its local axis, for that, reverse the order, i.e., trans * rot.

---
Tags: opengl, rotation
---


# Question
Title: How do I render endless terrain using TerrainGrid?
I have started to learn game development, using the jMonkey engine. I am able to create single tile of terrain using `TerrainQuad`, but in the next step, I'm stuck at making it infinite. I have gone through the wiki and a tutorial, and want to use the `TerrainGrid` class, but my code does not seem to work. I have looked around on the web, and searched other forums, but cannot find any other code example to help.

I believe in the below code; `ImageTileLoader` returns an image, which is the height map for that tile. I have modified it to return the same image, every time, but all I see is a black window. The `Namer` method is not even called.

```
terrain = new TerrainGrid("terrain", patchSize, 513,
    new ImageTileLoader(assetManager, new Namer() {
        public String getName(int x, int y) {
            //return "Scenes/TerrainMountains/terrain_" + x + "_" + y + ".png";
            System.out.println("X = " + x + ", Y = " + y);
            return "Textures/heightmap.png";
        }
    }));

```

---

This is the result, when I use `TerrainQuad`:

---

This is my full code:

```
// Sample 10 - How to create fast-rendering terrains from heightmaps, and how to
// use texture splatting to make the terrain look good.
public class HelloTerrain extends SimpleApplication {
    private TerrainQuad terrain;
    Material mat_terrain;
    private float grassScale = 64;
    private float dirtScale = 32;
    private float rockScale = 64;

    public static void main(String[] args) {
        HelloTerrain app = new HelloTerrain();
        app.start();
    }

    private FractalSum base;
    private PerturbFilter perturb;
    private OptimizedErode therm;
    private SmoothFilter smooth;
    private IterativeFilter iterate;

    @Override
    public void simpleInitApp() {
        flyCam.setMoveSpeed(200);

        initMaterial();

        AbstractHeightMap heightmap = null;
        Texture heightMapImage = assetManager.loadTexture("Textures/heightmap.png");
        heightmap = new ImageBasedHeightMap(heightMapImage.getImage());
        heightmap.load();

        int patchSize = 65;

        terrain = new TerrainGrid("terrain", patchSize, 513,
            new ImageTileLoader(assetManager, new Namer() {
            public String getName(int x, int y) {
                System.out.println("X = " + x + ", Y = " + y);
                return "Textures/heightmap.png";
                // set to return the same height map image.
            }
        }));

        terrain.setMaterial(mat_terrain);
        terrain.setLocalTranslation(0,-100, 0);
        terrain.setLocalScale(2f, 1f, 2f);
        rootNode.attachChild(terrain);

        TerrainLodControl control = new TerrainLodControl(terrain, getCamera());
        terrain.addControl(control);
    }

    public void initMaterial() {
        // TERRAIN TEXTURE material
        this.mat_terrain = new Material(this.assetManager,
            "Common/MatDefs/Terrain/HeightBasedTerrain.j3md");

        // GRASS texture
        Texture grass = this.assetManager.loadTexture("Textures/white.png");
        grass.setWrap(WrapMode.Repeat);
        this.mat_terrain.setTexture("region1ColorMap", grass);
        this.mat_terrain.setVector3("region1", new Vector3f(-10, 0, this.grassScale));

        // DIRT texture
        Texture dirt = this.assetManager.loadTexture("Textures/white.png");
        dirt.setWrap(WrapMode.Repeat);
        this.mat_terrain.setTexture("region2ColorMap", dirt);
        this.mat_terrain.setVector3("region2", new Vector3f(0, 900, this.dirtScale));

        Texture building = this.assetManager.loadTexture("Textures/building.png");
        building.setWrap(WrapMode.Repeat);

        this.mat_terrain.setTexture("slopeColorMap", building);
        this.mat_terrain.setFloat("slopeTileFactor", 32);
        this.mat_terrain.setFloat("terrainSize", 513);
    }
}

```

# Answer
So, I worked further on my problem and was able to achieve what I wanted to. But I still cannot understand what was the error on my first code. Below is the final code that I got by modifying the `TerrainGrid` example from here. Below is the final code for anyone who falls into the same situation. It is not the final thing but does answer my question above.

```
public class TerrainGridTest extends SimpleApplication {

    private Material mat_terrain;
    private TerrainGrid terrain;
    private float grassScale = 64;
    private float dirtScale = 16;

    public static void main(final String[] args) {
        TerrainGridTest app = new TerrainGridTest();
        app.start();
    }

    @Override
    public void simpleInitApp() {
        this.flyCam.setMoveSpeed(100f);
        initMaterial();
        initTerrain();
        this.getCamera().setLocation(new Vector3f(0, 200, 0));
        this.getCamera().lookAt(new Vector3f(0,0,0), Vector3f.UNIT_Y);
        this.viewPort.setBackgroundColor(new ColorRGBA(0.7f, 0.8f, 1f, 1f));
        initLight();
    }

    @Override
    public void simpleUpdate(final float tpf) {

    }

    public void initMaterial() {
        // TERRAIN TEXTURE material
        this.mat_terrain = new Material(this.assetManager, "Common/MatDefs/Terrain/HeightBasedTerrain.j3md");

        // GRASS texture
        Texture grass = this.assetManager.loadTexture("Textures/white.png");
        grass.setWrap(WrapMode.Repeat);
        this.mat_terrain.setTexture("region1ColorMap", grass);
        this.mat_terrain.setVector3("region1", new Vector3f(-10, 0, this.grassScale));

        // DIRT texture
        Texture dirt = this.assetManager.loadTexture("Textures/white.png");
        dirt.setWrap(WrapMode.Repeat);
        this.mat_terrain.setTexture("region2ColorMap", dirt);
        this.mat_terrain.setVector3("region2", new Vector3f(0, 900, this.dirtScale));

        // ROCK texture
        //Texture rock = this.assetManager.loadTexture("Textures/Terrain/Rock2/rock.jpg");
        Texture building = this.assetManager.loadTexture("Textures/building.png");
        building.setWrap(WrapMode.Repeat);

        this.mat_terrain.setTexture("slopeColorMap", building);
        this.mat_terrain.setFloat("slopeTileFactor", 32);

        this.mat_terrain.setFloat("terrainSize", 513);
    }

    private void initLight() {
        DirectionalLight light = new DirectionalLight();
        light.setDirection((new Vector3f(-0.5f, -1f, -0.5f)).normalize());
        rootNode.addLight(light);
    }

    private void initTerrain() {
        this.terrain = new TerrainGrid("terrain", 65, 257, new ImageTileLoader(assetManager, new Namer() {

            public String getName(int x, int y) {
               //return "Interface/Scenes/TerrainMountains/terrain_" + x + "_" + y + ".png";
                return "Textures/heightmap.png";
            }
        }));

        this.terrain.setMaterial(mat_terrain);
        this.terrain.setLocalTranslation(0, 0, 0);
        this.terrain.setLocalScale(3f, 1.5f, 3f);
        this.rootNode.attachChild(this.terrain);

        TerrainLodControl control = new TerrainGridLodControl(this.terrain, getCamera());
        control.setLodCalculator( new DistanceLodCalculator(65, 2.7f) ); // patch size, and a multiplier
        this.terrain.addControl(control);
    }
}

```
> 1 votes

# Answer
I just had the same problem and i managed to solve it. You have to use TerrainGridLodControl to make it work, as TerrainLodControl doesn't work. Looks like we failed to notice that when changing from TerrainQuad to TerrainGrid.
> 3 votes

---
Tags: java, jmonkeyengine
---


# Question
Title: What algorithm to use to fill a KenKen square board with cages?
I am working on recreating KenKen, a popular math puzzle involving a blank grid that is divided into "cages". Each cage is just a collection of adjacent squares and has a clue which is generally a number and an operand, shown below:

**What type of algorithm would be best to fill the square with cages?** Assume the maximum number of cells per cage would be 3 and the board is 4x4 in size, like in the example above.

# Answer
> 3 votes
you can build those kind of puzzles in 4 phases:

1. create a Sudoku puzzle board
2. choose regions
3. put some random operations for those regions and their respective results
4. try solving that puzzle yourself and check if there is any other solution for that specific puzzle. (which is not really necessary)

if by any chance you've generated a puzzle with multiple results, you can keep changing some of those regions or operators until there is a unique answer!

**Edit**

Now to specify regions: Here is some basic idea, start from the top left square and move over all squares using DFS method, with a little adjustment. In each iteration choose the direction you are moving in a random order. Here is the potential path your DFS algorithm might follow:

And then when closing each node you group them with number of their parents as a block. which might result in boxing as follows:

to increase or decrease difficulty you can try gearing block sizes toward 3 or 1.

# Answer
> 1 votes
Another way would be to repeatedly merge adjacent blocks.

1. Start with a grid of singleton blocks
2. Pick two adjacent blocks, with a combined cell count less than *S*, at random.
3. Merge them.
4. Repeat *N* number of times, from step 2.

Adjust *S* and *N* for difficulty.

A good data-structure for this, is Disjoint-sets.

---

```
Board GenerateBoard(int width, int height, int maxSize, int numMerges)
{
    var rnd = new Random();
    var board = new Board(width, height);

    // TODO: Optimize
    var candidates =
        Enumerable.Range(0, width).SelectMany(x1 =>
             Enumerable.Range(0, height - 1).Select(y1 =>
                    new { x1, y1, x2 = x1, y2 = y1 + 1 }))
        .Concat(
            Enumerable.Range(0, width - 1).SelectMany(x1 =>
                   Enumerable.Range(0, height).Select(y1 =>
                        new { x1, y1, x2 = x1 + 1, y2 = y1 })))
        .OrderBy(o => rnd.Next());

    foreach (var o in candidates)
    {
        var cell1 = board.Grid[o.x1, o.y1].FindRoot();
        var cell2 = board.Grid[o.x2, o.y2].FindRoot();
        if (cell1.Size + cell2.Size <= maxSize)
        {
            cell1.Merge(cell2);
            if (--numMerges == 0) break;
        }
    }

    return board;
}

class Board
{
    public readonly int Width;
    public readonly int Height;

    public readonly Cell[,] Grid;

    public Board(int width, int height)
    {
        Width = width;
        Height = height;

        Grid = new Cell[width, height];
        for (int y = 0; y < height; y++)
            for (int x = 0; x < width; x++)
            {
                Grid[x, y] = new Cell(x, y);
            }
    }
}

class Cell
{
    public readonly int X;
    public readonly int Y;

    public Cell Parent;
    public int Size = 1;

    public Cell(int x, int y)
    {
        X = x;
        Y = y;
    }

    public void Merge(Cell other)
    {
        var root1 = FindRoot();
        var root2 = other.FindRoot();
        if (root1 == root2) return;

        if (root1.Size < root2.Size)
        {
            var tmp = root1;
            root1 = root2;
            root2 = tmp;
        }

        root2.Parent = root1;
        root1.Size += root2.Size;
    }

    public Cell FindRoot()
    {
        if (Parent == null) return this;
        var root = Parent.FindRoot();
        Parent = root;
        return root;
    }
}

```

Sample grid:

---
Tags: mathematics, algorithm, random, puzzle
---


# Question
Title: GLM Velocity Vectors - Basic Maths to Simulate Steering
**UPDATE** \- Code updated below but still need help adjusting my math.

I have a cube rendered on the screen which represents a car (or similar).

Using Projection/Model matrices and Glm I am able to move it back and fourth along the axes and rotate it left or right.

I'm having trouble with the vector mathematics to make the cube move forwards no matter which direction it's current orientation is. (ie. if I would like, if it's rotated right 30degrees, when it's move forwards, it travels along the 30degree angle on a new axes).

I hope I've explained that correctly.

This is what I've managed to do so far in terms of using glm to move the cube:

```
glm::vec3 vel; //velocity vector

void renderMovingCube(){

    glUseProgram(movingCubeShader.handle());
    GLuint matrixLoc4MovingCube = glGetUniformLocation(movingCubeShader.handle(), "ProjectionMatrix");
    glUniformMatrix4fv(matrixLoc4MovingCube, 1, GL_FALSE, &ProjectionMatrix[0][0]);

        glm::mat4 viewMatrixMovingCube;
        viewMatrixMovingCube = glm::lookAt(camOrigin, camLookingAt, camNormalXYZ);

        vel.x = cos(rotX); vel.y=sin(rotX);
        vel*=moveCube;

        //move cube
        ModelViewMatrix = glm::translate(viewMatrixMovingCube,globalPos*vel);

        //bring ground and cube to bottom of screen
        ModelViewMatrix = glm::translate(ModelViewMatrix,  glm::vec3(0,-48,0));
        ModelViewMatrix = glm::rotate(ModelViewMatrix, rotX, glm::vec3(0,1,0));     //manually turn

        glUniformMatrix4fv(glGetUniformLocation(movingCubeShader.handle(), "ModelViewMatrix"), 1, GL_FALSE, &ModelViewMatrix[0][0]); //pass matrix to shader
    movingCube.render();        //draw
    glUseProgram(0);
}

```

keyboard input:

```
void keyboard()
{
    char BACKWARD  = keys['S']; char FORWARD   = keys['W'];
    char ROT_LEFT  = keys['A']; char ROT_RIGHT = keys['D'];

    if (FORWARD) //W - move forwards
    {
        globalPos += vel;
        //globalPos.z -= moveCube;
        BACKWARD = false;
    }
    if (BACKWARD)//S - move backwards
    {
        globalPos.z += moveCube;
        FORWARD = false;
    }
    if (ROT_LEFT)//A - turn left
    {
        rotX +=0.01f;
        ROT_LEFT = false;
    }
    if (ROT_RIGHT)//D - turn right
    {
        rotX -=0.01f;
        ROT_RIGHT = false;
    }

```

Where am I going wrong with my vectors? I would like change the direction of the cube (which it does) but then move forwards in that direction.

# Answer
To make the cube move forward, you need to find the cubes's velocity vector. The direction of the velocity vector is simply the angle of rotation. Then simply add it to the position;

```
//pseudocode
vector velocity(cos(rotX),sin(rotX); //assume rotX converted to radians
velocity*=SPEED_PER_FRAME;//SPEED_PER_FRAME is a scalar (might be moveCube)

if (FORWARD)        //W - move cube along zAxis positive
{
    globalPos += velocity;
    BACKWARD = false;
}
if (BACKWARD)       //S- move cube along zAxis negative
{
    globalPos.z -= velocity;
    FORWARD = false;
}

```
> 3 votes

# Answer
You need to apply some level of physics. At the very least you need to be familiar with basic Newtonian motion and Euler integrations of the base 'p2=p1+v\*t' and 'v2=v1+a\*t' equations. You can then apply some approximations of forces using algorithms like those on red3d's site (which is not about vehicle steering but is applicable with some thought) . The goal is that you don't move the car left but instead you apply a force (or just change the acceleration if you don't care about mass or other forces like surface friction) that turns the car left over time resulting in a more natural curve to the motion.

Note that you'll end up having to tweak and experiment with values a lot to get something that feels good. Having the ability to edit parameters to the algorithms at runtime as you experiment like with AntTweakBar will be invaluable.

Actual car physics are incredibly complicated. Even with an expensive middleware like Havok you're going to need a lot of time and someone(s) with a very deep understanding of physics simulation to simulate wheels, suspension, engine-driven acceleration, breaking, friction, etc. to get a game with car physics like you see in AAA driving games (or most other games with vehicles like Battlefield or Halo or whatnot). The basics above are not even close to physically accurate and there simply isn't any "basic math" version that is, unfortunately.
> 1 votes

---
Tags: opengl, glsl
---


# Question
Title: Spherical harmonics lighting interpolation
I want to use hardware filtering to smooth out colors in texels of a texture when I'm accessing texels at coordinates that are not directly at the center of the texel, the catch being that the texels store 2 bands of spherical harmonics coefficients (=4 coefficients), not RGBA intensity values.

Can I just use hardware filtering like that (GL\_LINEAR with and without mip mapping) without any considerations?

In other terms: If I were to first convert the coefficients back to intensity representations, than manually interpolate between two intensities, would the resulting intensity be the same as if I interpolated between the coefficient vectors directly and then converted the interpolated result to intensities?

# Answer
Yeah, I think this is valid and one of the big nice properties of spherical harmonics. Bilinearly or trilinearly filtering the data doesn't have any cross-channel operations so it will preserve the 4 separate sets of coefficients fine.

Basically evaluating the SPH is like this right:

```
for(i=0..coefficients):
  result += coefficient[i] * basis[i]

```

So in the 1-D case if you have two results resultA and resultB them you linearly interplolte them like this:

```
result = lerp(resultB, resultA, t)
result = resultA * t + resultB * (1.0 - t)

```

If you sub this in you get:

```
for(i=0..coefficients):
  resultA = (coefficientA[i] * basis[i])
  resultB = (coefficientB[i] * basis[i])
  result +=  resultA * t +  resultB * (1.0 - t)

```

then

```
for(i=0..coefficients):
  result += (coefficientA[i] * basis[i]) * t + (coefficientB[i] * basis[i]) * (1.0 - t)

```

The the basis is constant w.r.t A vs B so you can factor it out

```
for(i=0..coefficients):
  result += ((coefficientA[i]) * t + (coefficientB[i]) * (1.0 - t))*basis[i]

```

So coefficients is really

```
for(i=0..coefficients):
  result += lerp(coefficientB[i], coefficientA[i], t)*basis[i]

```

Which means, yes, you can filter the coefficients texture and get the same result as filtering the result of the evaluation.

Also this implies that you can apply any constant scale or sum up sets of coefficients arbitrarily which is useful.
> 7 votes

---
Tags: opengl, spherical-harmonics
---


# Question
Title: Accessing 3D texture data without normalized coordinates directly, but with filtering
texelFetch() exists to access texture data with texture coordinates in "image dimensions", but texelFetch skips filtering.

In case of 2D textures, it's possible to use a rectangle texture sampler to access textures without normalized coordinates with filtering, but the same equivalent doesn't seem to exist for 3D textures.

Is this somehow possible with 3D textures?

# Answer
If your OpenGL version is new enough you can use the textureSize intrinsic to get the dimensions of the texture: http://www.opengl.org/sdk/docs/manglsl/xhtml/textureSize.xml Then you can divide your pixel coordinate by this to get the UV to sample at for that pixel.

If not you can just pass it as uniform but that may not be as clean depending on how your code is setup.
> 1 votes

---
Tags: opengl, glsl
---


# Question
Title: Using a permutation table for simplex noise without storing it
Generating Simplex noise requires a permutation table for randomisation (e.g. see this question or this example).

In some applications, we need to persist the state of the permutation table. This can be done by creating the table, e.g. using

```
def permutation_table(seed):
    table_size = 2**10  # arbitrary for this question
    l = range(1, table_size + 1)

    random.seed(seed) # ensures the same shuffle for a given seed
    random.shuffle(l)
    return l + l  # see shared link why l + l; is a detail

```

and storing it.

Can we avoid storing the full table by generating the required elements every time they are required?

Specifically, currently I store the table and call it using `table[i]` (table is a **list**). Can I avoid storing it by having a **function** that computes the element `i`, e.g. `get_table_element(seed, i)`.

I'm aware that cryptography already solved this problem using block cyphers, however, I found it too complex to go deep and implement a block cypher.

Does anyone knows a simple implementation of a block cypher to this problem?

# Answer
Rather than using very large table sizes, I would suggest just using a hash function. The permutation table is just a kind of pre-calculated hash function anyway. I don't believe the permutation property (i.e. that there are no collisions within the table size) is required for good simplex noise.

Some hash functions that could do the job are listed here. I've used the first one on that page, Thomas Wang's 32-bit integer hash, quite a bit. I copied its source code below:

```
uint32_t hash(uint32_t a)
{
    a = (a ^ 61) ^ (a >> 16);
    a = a + (a << 3);
    a = a ^ (a >> 4);
    a = a * 0x27d4eb2d;
    a = a ^ (a >> 15);
    return a;
}

```

This might even be faster than looking up a value from a large table, if the memory access takes longer than the 10 math operations in the above function. I haven't benchmarked this though. Probably the table stays in cache pretty well when you're generating many noise values.

Also, you can easily incorporate a per-map seed by changing the values passed to the hash function. For instance you can pass `(seed * mapHeight + y) * mapWidth + x` to generate a different value for each xy coordinate in each map.
> 2 votes

---
Tags: maps, procedural-generation, random
---


title: Quaternion LookAt for camera

text:
# Question
Title: Quaternion LookAt for camera
I am using the following code to rotate entities to look at points.

```
glm::vec3 forwardVector = glm::normalize(point - position);
float dot = glm::dot(glm::vec3(0.0f, 0.0f, 1.0f), forwardVector);

float rotationAngle = (float)acos(dot);
glm::vec3 rotationAxis = glm::normalize(glm::cross(glm::vec3(0.0f, 0.0f, 1.0f), forwardVector));
rotation = glm::normalize(glm::quat(rotationAxis * rotationAngle));

```

This works fine for my usual entities. However, when I use this on my Camera entity, I get a black screen. If I flip the subtraction in the first line, so that I take the forward vector to be the direction from the point to my camera's position, then my camera works but naturally my entities rotate to look in the opposite direction of the point.

I compute the transformation matrix for the camera and then take the inverse to be the View Matrix, which I pass to my OpenGL shaders:

```
glm::mat4 viewMatrix = glm::inverse(
    cameraTransform->GetTransformationMatrix()
);

```

The orthographic projection matrix is created using glm::ortho.

What's going wrong?

# Answer
> 2 votes
You are comparing the world-space forward vector to the target (view-space) forward vector to calculate the rotation necessary to transform the camera into view-space right ?
In that case, I think you should try to change the second line to

```
float dot = glm::dot(glm::vec3(0.0f, 0.0f, -1.0f), forwardVector);

```

since -if I'm not mistaken- in OpenGL, the camera is assumed to be looking down the negative z-axis in view-space. That might also explain why fliping the subtraction in the first line somewhat fixes your problem. The angle between the negative forward vector and the positive z-direction should be the same as between negative z-direction and positive forward vector. (You could confirm this by drawing a small sketch).
To fix the wrong rotation of the other entites, I believe you shouldn't take the inverse of the transformation matrix you computed. The orientation you obtained already transforms a given vector into view-space -this is the constraint, that you derived it from afterall- and not the other way around. The translation that maps the origin to the camera position would have to be inverted though, however if you use the transformation that maps the camera position to the origin, don't invert that either.

There also is the glm::lookAt() function for computing the view matrix, that would fit nicely with using glm::ortho() if you don't have any specific requirements that need you to do the calculations on your own.

---
Tags: opengl, camera, quaternion, mathematics
---


title: How to debug Android App Eclipse?

text:
# Question
Title: How to debug Android App Eclipse?
Ok. So while this isnt a programming question. I wanted to know how do people debug apps? How do you view log cat, and where these exceptions are thrown etc? And do I need to run the app on the emulator to see all the stuff, or is there a way to view this after running the app on my phone(while not being connected to the computer)

Links to plugins and tips would be really helpful, as im gonna start work on my next game, and while the first one works fine, had a lot of problems while debugging.

# Answer
Use a cord to connect what ever device you using to test your program with your computer.

You should see the log cat in place of the command prompt. All thrown exceptions and null pointers will show up there and will include line numbers which are very helpful for debugging.

Also It is important to note that System.out.print will not show up in log cat unless you specify that you want it to in preferences. Alternatively you can use System.err.print which will show up as orange text in your log cat.

Hope this helps.
> 1 votes

---
Tags: android, debugging, eclipse
---


# Question
Title: Bouncing off a circular Boundary with multiple balls?
I am making a game like this :

Yellow smiley has to escape from red smileys, when yellow smiley hits the boundary game is over, when red smileys hit the boundary they should bounce back with the same angle they came, like shown below:

Every 10 seconds a new red smiley comes in the big circle, when red smiley hits yellow, game is over, speed and starting angle of red smileys should be random. I control the yellow smiley with arrow keys. The biggest problem I have reflecting the red smileys from the boundary with the angle they came. I don't know how I can give a starting angle to a red smiley and bouncing it with the angle it came. After some tips I did the reflection, looks reasonable but I am not sure if it is working because sometimes it just bounces to the way they came from.

**Now the problem is after each bounce the speed of the red smiley increases and after 4-5 bounces they the speed goes to infinity and balls disappear.**

How can I overcome this?

My js source code :

```
//Smiley.js

var canvas = document.getElementById("mycanvas");

var ctx = canvas.getContext("2d");

    var vx;
    var vy;
    var twiceProjFactor;
// Object containing some global Smiley properties.
var SmileyApp = {
   radius: 15,
   xspeed: 0,
   yspeed: 0,
   xpos:200,  // x-position of smiley
   ypos: 200  // y-position of smiley
};

var SmileyRed = {
   radius: 15,
   xspeed: 0,
   yspeed: 0,
   xpos:350,  // x-position of smiley
   ypos: 67  // y-position of smiley
};

var SmileyReds = new Array();

 for (var i=0; i<5; i++){
 SmileyReds[i] =  {
   radius: 15,
   xspeed: 0,
   yspeed: 0,
   xpos:350,  // x-position of smiley
   ypos: 67  // y-position of smiley
};
 SmileyReds[i].xspeed = Math.floor((Math.random()*50)+1);
 SmileyReds[i].yspeed = Math.floor((Math.random()*50)+1);
 }

function drawBigCircle() {
 var centerX = canvas.width / 2;
      var centerY = canvas.height / 2;
      var radiusBig = 300;

      ctx.beginPath();
      ctx.arc(centerX, centerY, radiusBig, 0, 2 * Math.PI, false);
//      context.fillStyle = 'green';
//      context.fill();
      ctx.lineWidth = 5;
 //     context.strokeStyle = '#003300'; // green
      ctx.stroke();
}

function lineDistance( positionx, positiony )
{
  var xs = 0;
  var ys = 0;

  xs = positionx - 350;
  xs = xs * xs;

  ys = positiony - 350;
  ys = ys * ys;

  return Math.sqrt( xs + ys );
}
function drawSmiley(x,y,r) {
   // outer border
   ctx.lineWidth = 3;
   ctx.beginPath();
   ctx.arc(x,y,r, 0, 2*Math.PI);
  //red ctx.fillStyle="rgba(255,0,0, 0.5)";
   ctx.fillStyle="rgba(255,255,0, 0.5)";
   ctx.fill();
   ctx.stroke();

   // mouth
   ctx.beginPath();
   ctx.moveTo(x+0.7*r, y);
   ctx.arc(x,y,0.7*r, 0, Math.PI, false);

   // eyes
   var reye = r/10;
   var f = 0.4;
   ctx.moveTo(x+f*r, y-f*r);
   ctx.arc(x+f*r-reye, y-f*r, reye, 0, 2*Math.PI);
   ctx.moveTo(x-f*r, y-f*r);
   ctx.arc(x-f*r+reye, y-f*r, reye, -Math.PI, Math.PI);

   // nose
   ctx.moveTo(x,y);
   ctx.lineTo(x, y-r/2);
   ctx.lineWidth = 1;
   ctx.stroke();
}

function drawSmileyRed(x,y,r) {
   // outer border
   ctx.lineWidth = 3;
   ctx.beginPath();
   ctx.arc(x,y,r, 0, 2*Math.PI);
  //red
  ctx.fillStyle="rgba(255,0,0, 0.5)";
  //yellow ctx.fillStyle="rgba(255,255,0, 0.5)";
   ctx.fill();
   ctx.stroke();

   // mouth
   ctx.beginPath();
   ctx.moveTo(x+0.4*r, y+10);
   ctx.arc(x,y+10,0.4*r, 0, Math.PI, true);

   // eyes
   var reye = r/10;
   var f = 0.4;
   ctx.moveTo(x+f*r, y-f*r);
   ctx.arc(x+f*r-reye, y-f*r, reye, 0, 2*Math.PI);
   ctx.moveTo(x-f*r, y-f*r);
   ctx.arc(x-f*r+reye, y-f*r, reye, -Math.PI, Math.PI);

   // nose
   ctx.moveTo(x,y);
   ctx.lineTo(x, y-r/2);
   ctx.lineWidth = 1;
   ctx.stroke();
}

// --- Animation of smiley moving with constant speed and bounce back at edges of canvas ---
var tprev = 0;   // this is used to calculate the time step between two successive calls of run
function run(t) {
   requestAnimationFrame(run);
   if (t === undefined) {
      t=0;
   }
   var h = t - tprev;   // time step
   tprev = t;

   SmileyApp.xpos += SmileyApp.xspeed * h/1000;  // update position according to constant speed
   SmileyApp.ypos += SmileyApp.yspeed * h/1000;  // update position according to constant speed

    for (var i=0; i<SmileyReds.length; i++){
   SmileyReds[i].xpos += SmileyReds[i].xspeed * h/1000;  // update position according to constant speed
   SmileyReds[i].ypos += SmileyReds[i].yspeed * h/1000;  // update position according to constant speed
    }
   // change speed direction if smiley hits canvas edges
   if (lineDistance(SmileyApp.xpos, SmileyApp.ypos) + SmileyApp.radius > 300) {
     alert("Game Over");
   }

    for (var i=0; i<SmileyReds.length; i++){
  if (lineDistance(SmileyReds[i].xpos, SmileyReds[i].ypos) + SmileyReds[i].radius > 300) {
  // Red Smiley collusion
  //SmileyReds[i].xpos
  //SmileyReds[i].xspeed
  //SmileyReds[i].ypos
  //SmileyReds[i].yspeed
  // r = v − [2 (n · v) n] formula
  //n calculation

    nx = 350 -  SmileyReds[i].xpos ;
    ny = 350 -  SmileyReds[i].ypos ;

  nx = nx / (Math.sqrt(nx * nx + ny * ny));
  ny = ny / (Math.sqrt(nx * nx + ny * ny));
  //new calc
   v_newx = SmileyReds[i].xspeed - (2 *( nx * SmileyReds[i].xspeed + ny * SmileyReds[i].yspeed ) ) * nx;
   v_newy = SmileyReds[i].yspeed - (2 *( nx * SmileyReds[i].xspeed + ny * SmileyReds[i].yspeed ) ) * ny;

   SmileyReds[i].xspeed = v_newx;
   SmileyReds[i].yspeed = v_newy;

 //to calculate "n," you do (626/L, 282/L) where L=sqrt(xpos^2+ypos^2)
    }
    }
   /* Square canvas
   if ((SmileyApp.xpos + SmileyApp.radius > canvas.width) ||
       (SmileyApp.xpos - SmileyApp.radius) < 0) {
      SmileyApp.xspeed = -SmileyApp.xspeed;
   }
   if ((SmileyApp.ypos + SmileyApp.radius > canvas.height) ||
       (SmileyApp.ypos - SmileyApp.radius) < 0) {
      SmileyApp.yspeed = -SmileyApp.yspeed;
   }
   */
   // redraw smiley at new position
   ctx.clearRect(0,0,canvas.height, canvas.width);
   drawBigCircle();
   drawSmiley(SmileyApp.xpos, SmileyApp.ypos, SmileyApp.radius);

   for (var i=0; i<SmileyReds.length; i++){
   drawSmileyRed(SmileyReds[i].xpos, SmileyReds[i].ypos, SmileyReds[i].radius);
   }
}
// uncomment these two lines to get every going
// SmileyApp.speed = 100;
run();

// --- Mouse wheel event handler to grow and shrink smiley
function mousewheelCB(event){
   //    alert("Hallo");
   event.preventDefault();
   event.stopPropagation();

   SmileyApp.radius += event.wheelDelta/40;
}
canvas.addEventListener('mousewheel',
                        mousewheelCB,
                        false);

// --- Control smiley motion with left/right arrow keys
function arrowkeyCB(event) {
   event.preventDefault();

   if (event.keyCode === 37) { // left arrow
      SmileyApp.xspeed = -100;
      SmileyApp.yspeed = 0;
   } else if (event.keyCode === 39) { // right arrow
      SmileyApp.xspeed = 100;
      SmileyApp.yspeed = 0;
   } else if (event.keyCode === 38) { // up arrow
      SmileyApp.yspeed = -100;
      SmileyApp.xspeed = 0;
   } else if (event.keyCode === 40) { // right arrow
      SmileyApp.yspeed = 100;
      SmileyApp.xspeed = 0;
   }
}
document.addEventListener('keydown', arrowkeyCB, true);
/*
function run(){
console.log("Here is run");
console.log(Date.now());

ctx.clearRect(0,0,canvas.width, canvas.height);
xpos = 200;
drawSmiley2(100,100,20);
xpos = xpos-50;
// decent animation 30 pictures per second
}

setInterval(run, 50);

*/

```

JSFiddle : http://jsfiddle.net/gj4Q7/2/

# Answer
You can do this using vector math. There's a standard formula for reflecting an incoming vector (v₁) off a normal, which you can see derived on this page. The formula is

> v₂ = v₁ - 2 (v₁ · n) n

Since it's a circle, the normal is just the normalized vector from the collision point toward the center of the circle. This is a good formula to put in a utility function in your math library, since it will come in handy all over the place when programming games.
> 1 votes

# Answer
I wanted to comment on the answer given by @Nathan Reed (which is pretty good, btw - I do not wish to make his answer less relevant by answering again), but I do not have enough reputation yet. Anyway, I just wanted to point out that you can try to use this Vector2D class from Kevin Lindsey: http://www.kevlindev.com/gui/math/vector2d/index.htm Include that class in your project and then just do as Nathan suggested. You can find many other implementations of vector math, just google for "Vector2D Javascript".

Also, it might be useful for you to study a little about steering behaviours. These links have relevant information:

http://gamedev.tutsplus.com/tutorials/implementation/understanding-steering-behaviors-seek/ http://www.red3d.com/cwr/steer/
> 1 votes

---
Tags: mathematics, javascript, html
---


# Question
Title: Project collision shapes to plane for 2.5D collision detection
I am working on a top down 2.5D game. In the game anything that overlaps on the screen should be 'colliding' with each other regardless of whether they are on the same plane in the 3D world. This is illustrated below from a side-ways view:

The orange and green circles are spheres floating in the 3D world. They are projected onto a plane parallel to the viewport plane (y = 0 in the image) and if they overlap there is a collision event between them. These spheres are attached to other meshes to represent the sphere bounding boxes for collisions.

The way I plan to implement this at the moment is the following:

1. Get the 3D world position at the center of the sphere.
2. Use Camera.WorldToViewportPoint to project the point to the viewport plane.
3. Move a Sphere Collider with the radius of the sphere to that point.
4. Test for collisions using unity colliders.

My question is how to extend this to work for rotated cuboids. For instance if I have two rotated cuboids, if I follow the logic above it would not work as intended as the cuboids may not collide but they could still be intersected on the view plane. An example is below:

In the example above the cuboids are overlapping from the view of the player, but not colliding when they should be.

Is there a way to project a cuboid that would be aligned with the plane? Would it be a valid cuboid for all rotations if I did this?

EDIT: Corrected the images, before they were incorrectly projecting onto the y=0 plane at 0 rotation, not the plane parallel to the viewport plane.

# Answer
You might use Plane's Normal (in math), get your view's normal, get spheres or other objects position and every objects, plane's normal by their rotation, scale for size of collision tests, get distances and make a simple Ray collisions, so you can use that Boolean ray for your game, if your framework has Physic engine then certainly that engine has ray tests.

Edit:

**Idea 1 (Slow)**

This idea might works! every collision cube has 2 planes with distance of scale-Y of cube and length of scale-x for accurate collision.

if any CollisionCubes is in view-port (CPU usage)

```
if number of CollisionCubes > 2

    then every CollisionCubes plane send ray from 4 tips of your planes to down & test with other cubes

       if collision accured
          then you have collision

```

**Idea 2 (Better & Faster)**

This may be faster and much better, if you are using just in 2d like perspective,

every Collision-cube when rotate its length of collision to plane would change depends on, say you just Projected on cube without rotation and its Scale-X is your length of collision, if you rotate that Cube 90-degrees then you have Scale-Y as length of your collision, so, **think of this cube as a Sphere that changes its Scale**, that is simple you have Sphere collision that just changes its Scale when Rotate, this would be much easier to calculate just like first example you showed.
> 1 votes

---
Tags: collision-detection, unity, mathematics, camera
---


title: How should I handle missing resources?

text:
# Question
Title: How should I handle missing resources?
Your game expects a certain asset to be loaded, but it isn't found. How should the situation be handled? For example:

```
Texture* grassTexture = LoadTexture("Grass.png"); // returns NULL; texture not found
Mesh* car             = LoadMesh("Car.obj");      // returns NULL; 3D mesh not found

```

It might have been accidentally deleted by the user, corrupted or misspelled while in development.

Some potential responses:

* Assertions (ideally only during development)
* Exit the game gracefully
* Throw an exception and try to handle it.

Which way is best?

# Answer
> 19 votes
Lots of games have a generic "error material" and "error mesh" that is really obvious to see. Pair this with a warning in the logs, of course.

# Answer
> 6 votes
If you have *different resolution assets* of the *same texture*, you could try to salvage the situation by using a different resolution.

```
Texture* grassTexture;
try {
    grassTexture = LoadTexture("Grass.png");
} catch (WhateverExcaption e) {
    grassTexture = LoadTexture("Grass_512.png");
}

```

If even *that* fails, it might be time to bail.

---
Tags: assets, resource-management, exceptions
---


title: Shadowmap first phase and shaders

text:
# Question
Title: Shadowmap first phase and shaders
I am using OpenGL 3.3 and am tryin to implement shadow mapping using cube maps. I have a framebuffer with a depth attachment and a cube map texture.

My question is how to design the shaders for the first pass, when creating the shadowmap.

This is my vertex shader:

```
in vec3 position;

uniform mat4 lightWVP;

void main()
{
    gl_Position = lightWVP * vec4(position, 1.0);
}

```

Now, do I even *need* a fragment shader in this shader pass? from what I understand after reading http://www.opengl.org/wiki/Fragment\_Shader, by default `gl_FragCoord.z` is written to the currently attached depth component (to which my cubemap texture is bound to).

Thus I shouldnt even need a fragment shader for this pass and from what I understand, there is no other work to do in the fragment shader other than writing this value.

Is this correct?

# Answer
Your problem is that you need to render the scene twice. One from the view of the Light and then the normal rendering pass from the camera point of view.

> Now, do I even need a fragment shader in this shader pass?

Yes. According to your question you are using OpenGL 3.3 which makes it required to define a fragment shader to be able to render anything.

In your first pass (which will be rendered from the light point of view) the output need to be written to a RenderTarget whether it was the main frame buffer or your offscreen frame buffer.

What makes you write a fragment shader is not gl\_FragCoord being explicitly written or not, but actually rendering the scene from two different point of views, **your vertex shader where you transform the scene to the light view should be coupled with a fragment shader.**

```
void main(){
    // Not really needed, OpenGL does it anyway
    fragmentdepth = gl_FragCoord.z;
}

```

The above code resembles the fragment shader for the first pass. Notice that it's really faster than other shaders that need to do alot of work like light calculation which is not really needed in your shadow pass.
> 4 votes

# Answer
You do need a fragment shader (it's required by the standard), but you can just provide an empty fragment shader.

shadowmap.frag:

```
void main() {}

```
> 3 votes

---
Tags: opengl, c++, shaders, shadows, shadow-mapping
---


# Question
Title: What are some ways to texture map a terrain?
I'm working with XNA on a 3D Game, and I'm trying to have a proper and nice environnement. I actually followed a tutorial to create a terrain from a heightmap. To texture it, I just apply a grass texture on it and tile it a number of times.

But what I want to do is to have a really realistic texturing, but also generate it automatically (for example if I want to use Perlin noise to generate a terrain and then texture it).

I already learned about multi-texturing, loading a map file with different colors for different textures, but I don't think this is really efficient, for instance for cliffs or very steep areas it will tile a texture badly as it's a view from the top. (Also, I don't know how I'll draw roads or dirt paths with that.)

I'm looking for an efficient solution to realistically texture mapping procedurally-generated terrain.

# Answer
I guess you're not concerned with blend maps or texture splatting (as that's independent of your UV mapping). Since you specifically asked for minimizing distortion caused by the mapping, you could consult section 1.5 of this GPU Gems article:

https://developer.nvidia.com/gpugems/GPUGems3/gpugems3\_ch01.html

This could work even on procedurally generated terrain. The concept is also known as "triplanar texturing".

LATER EDIT: I've tested the technique in my own terrain renderer using no precomputed uvs for the mapping. All you have to do is compute 3 sets of UVs for the 3 different projection planes (XY, YZ and ZX). This can be achieved using simple vertex and fragment shader snippets:

VShader:

```
float tileSize = 2.0;
vec4 worldPos = ( gl_Vertex);//So we obtain the world position

TexCoordX = (worldPos.zy/tileSize);//here are our texture coordinates...
TexCoordY = (worldPos.xz/tileSize);
TexCoordZ = (worldPos.xy/tileSize);
normal =  gl_Normal;
wNormal = normal;

```

FShader:

```
vec3 n = wNormal;
n*=n;
vec2 tcX = fract(TexCoordX);
vec2 tcY = fract(TexCoordY);
vec2 tcZ = fract(TexCoordZ);

vec4 grassCol = texture2D(grassTexture,tcX)*n.x+
                texture2D(grassTexture,tcY)*n.y+
                texture2D(grassTexture,tcZ)*n.z;

```
> 2 votes

# Answer
You could define a set of textures (grass, dirt, rock) and use those. Let's say using these three layers (rock at the bottom, dirt on top and grass topmost), you can define three alpha channels to define how much of each texture is visible. Start with a simple noise map for your alpha channels and maybe take the slope of terrain into account. The more slope, the more rock will shine through. This is a technique called 'Texture Splatting' as far as I remember. Here are some links to get you started. Advanced Texture Splatting (gamasutra)

TextureSplatting (charlesbloom, the one I used to get started with this topic)

You should be able to get good looking results rather quick, very rewarding topic
> 3 votes

---
Tags: 3d, xna-4.0, textures, terrain, uv-mapping
---


# Question
Title: Precise exposition of an image for set number of frames (Vsync?)
I need to make a simple enough program in C#, but it seems to be impossible via usual WinForms means. I need to show something (a string of text, an image) on the screen for very small time interval. Since typical monitors are 60Hz, this interval would be 1 or 2 frames (16,6 or 33,3 ms). I tried doing this with usual WinForms, and it is not possible because, apparently, there is no way to know how many frames were output to the monitor since some point in time. I can only draw on the controls, and monitor output is totally independant.

So even if I run the timer, say, for 17 ms, between showing and hiding the image, it still sometimes manages not to draw a single frame of my image on the screen (even though theoretically it should, because 17ms \> 16,6ms). Moreover, even 20ms seems to slow (even though i should be more than enough).

I did some game development as a hobby in the past (Delphi X, XNA) and I know that you usually draw the whole screen by yourself, each frame. Also, I know that there is an option called Vsync in most modern games, that allows you to synchronize your framerate to your monitor's frame rate.

So, is it possible? I mean, to actually know how many frames were sent to the monitor with w/e I want to show?

**EDIT:**

After doing some study, I guess there really is no way to check when monitor is updated. All you can do is use vsync - and all that does it just pauses your double-buffer-flipping until right after monitor refresh. Which would achieve what I want... if only it would be possible to guarantee that it will actually work! Turns out, it works only if it was not disabled previously in one of the million ways to disable it (like, in the driver, in the driver-bundled software, and wherever else).

I guess there is no way from your software to check if vsync is disabled in the driver either... Or is there? I guess only outputting several frames and checking timestamps between them - like, does outputting a blank screen and swapping buffers takes 16,(6)ms or 0,1 ms.

Anyways, I think I'll be using C# SDL and try to somehow do it via setting double buffering and swap control... If someone has useful information to add though, please do!

# Answer
VSync is generally not possible to control precisely on a PC without writing driver level code. Most graphics drivers even have an option to disable it completely. However there is an OpenGL API for controlling it on Windows (which doesn't override driver settings).

Also note that not everybody's monitor is 60Hz. There's some 120Hz ones available for example so you'll need to do some high precision timing to get it right (on Windows that generally means using either timeBeginPeriod(1) or QueryPerformanceCounter()).
> 1 votes

---
Tags: frame-rate
---


# Question
Title: Isometric Movement in Javascript In the DOM
I am creating a game using Javascript. I am not using the HTML5 Canvas Element. The game requires both side view controlles, and Isometric controls, hence the `movementMode` variable.

I have got the specific angles, but I am stuck on an aspect of this.

https://chillibyte.makes.org/thimble/movement

```
function draw() {
            if (keyPressed) {
                if (whichKey == keys.left) {
                    move(-1,0)
                }
                if (whichKey == keys.right) {
                    move(1,0)
                }
                if (whichKey == keys.up) {

                    move(0,-1)
                }
                if (whichKey == keys.down) {

                    move(0,1)
                }
            }
        }

```

This gives normal up, down , left, and right. i want to refactor this so that i can plugin two variables into the move() function, which will give the movement wanted.

Now for the trig.

```
         /|
        / |
       /  | y
      /   |
     /a___|
        x

```

Take This Right angled Triangle.

given that x is 1, y must be equal to tan(a)

That Seems right. However, when I do Math.tan(45), i get a number similar to 1.601. Why?

To Sum up this question.

I have a function, and i need a function which will converts an angle to a value, which will tell me the number of pixels that i need to go up by, if i only go across 1. Is it Math.tan that i want? or is it something else?

# Answer
> 3 votes
If I'm not mistaken `Math.tan(x)` does not take angles as degrees, but rather radians. If you want to supply angles as degrees, try the following code sample:

```
function getTanDeg(deg) {
   var rad = deg * Math.PI/180;
   return Math.tan(rad);
}

```

Source - Mozilla Developer Network

---
Tags: mathematics, javascript, movement, isometric
---


# Question
Title: What is the minimum of shader I need to use to run basic calculation on GPU?
I read, that the Hull Shader, Domain Shader, Geometry Shader and Pixel Shader can be used optional. So, is the Vertex Shader optional too? If no: What does a basic Vertex Shader look like? Just like a simple pass through? Is the Vertex Shader necessary to tell what kind of datastructure (Van Stripes or Meshes) are used? What can I do, with just the vertex shader? Are the fixed functions working without any help of programming a programmable stage?

# Answer
> 2 votes
See Shader Stages on MSDN:

> The vertex shader stage must always be active for the pipeline to execute. If no vertex modification or transformation is required, a pass-through vertex shader must be created and set to the pipeline.

From this you can infer that a vertex shader is absolutely required to write SV\_Position but that's all, so the most basic possible vertex shader will just write an arbitrary value to SV\_Position; in the pass-through case this just means copying over the input position to output, but (since D3D10+ allows drawing without input buffers) you can set it to any value you like if you wish (this is commonly seen in code for drawing full-screen quads).

# Answer
> 5 votes
If you use compute shaders, or a GPU compute API like CUDA or OpenCL, then you don't need any of the graphics pipeline shaders. Depending on your application, GPU compute may be a better fit for you, e.g. if what you're doing has nothing to do with rasterizing triangles. Compute allows you to simply launch a large block of GPU "threads" running in parallel, and what they do is up to your program.

As for the graphics pipeline, you can't do much with just a vertex shader. You can rasterize triangles to the depth buffer, and that's about it. If you want to do some computation at each pixel of an image, a common approach is to put the computation in a pixel shader, and do a "full-screen pass" by drawing a single triangle that covers the entire image. This requires a very simple vertex shader, but the real work is done by the pixel shader.

# Answer
> 2 votes
Vertex shaders are iirc not optional.

They tend to be used to transform vertices from world to view space and then project them onto a 2d plane (screenspace).

Vertex shaders doesn't know what kind of data structure it is, merely that you're taking in a vertex with some input data.

The vertex shader outputs the projected position and any optional data you want to pass along.

---
Tags: shaders, directx11
---


# Question
Title: How to update off screen bitmap in a surfaceview thread
I have a Surfaceview thread and an off canvas texture bitmap that is being generated (changed), first row (line), every frame and then copied one position (line) down on regular surfaceview bitmap to make a scrolling effect, and I then continue to draw other things on top of that. Well that is what I really want, however I can't get it to work even though I am creating a separate canvas for off screen bitmap. It is just not scrolling at all.

I other words I have a memory bitmap, same size as Surfaceview canvas, which I need to scroll (shift) down one line every frame, and then replace top line with new random texture, and then draw that on regular Surfaceview canvas.

Here is what I thought would work;

My surfaceChanged where I specify bitmap and canvasses and start thread:

```
@Override
    public void surfaceCreated(SurfaceHolder holder) {
    intSurfaceWidth = mSurfaceView.getWidth();
    intSurfaceHeight = mSurfaceView.getHeight();

    memBitmap = Bitmap.createBitmap(intSurfaceWidth, intSurfaceHeight,
            Bitmap.Config.ARGB_8888);
    memCanvas = new Canvas(memCanvas);

    myThread = new MyThread(holder, this);
    myThread.setRunning(true);
    blnPause = false;
    myThread.start();
}

```

My thread, only showing essential middle running part:

```
@Override
public void run() {
  while (running) {
    c = null;
try {
    // Lock canvas for drawing
    c = myHolder.lockCanvas(null);

    synchronized (mSurfaceHolder) {
        // First draw off screen bitmap to off screen canvas one line down
        memCanvas.drawBitmap(memBitmap, 0, 1, null);

        // Create random one line(row) texture bitmap
        memTexture = Bitmap.createBitmap(imgTexture, 0, rnd.nextInt(intTextureImageHeight), intSurfaceWidth, 1);

        // Now add this texture bitmap to top of off screen canvas and hopefully bitmap
        memCanvas.drawBitmap(textureBitmap,
                    intSurfaceWidth, 0, null);

        // Draw above updated off screen bitmap to regular canvas, at least I thought it would update (save changes) shifting down and add the texture line to off screen bitmap the off screen canvas was pointing to.
        c.drawBitmap(memBitmap, 0, 0, null);

        // Other drawing to canvas comes here

    } finally {
        // do this in a finally so that if an exception is thrown
        // during the above, we don't leave the Surface in an
        // inconsistent state
        if (c != null) {
            myHolder.unlockCanvasAndPost(c);
        }
    }
}
}

```

For my game Tunnel Run.
Right now I have a working solution where I instead have an array of bitmaps, size of surface height, that I populate with my random texture and then shift down in a loop for each frame. I get 50 frames per second, but I think I can do better by instead scrolling bitmap.

# Answer
At the moment, you are taking the super-fast fps but incredibly memory inneficient approach. I'm not expert with surfaceview / canvas but I'd guess you should be using this: `public void drawBitmap (int[] colors, int offset, int stride, float x, float y, int width, int height, boolean hasAlpha, Paint paint)` (link)

and setting x to be 0 and y to be the number of lines from the top the bitmap should be. Or maybe try using `canvas.translate(0,number_of_lines);` before each call of `canvas.drawbitmap`

UPDATE:

Again, use with caution, but this code will scroll the icon down the screen:

```
package com.example.SurfaceViewTest;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.Paint.Style;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class SurfaceViewTest extends Activity implements SurfaceHolder.Callback {

SurfaceView mSurfaceView;
SurfaceHolder mSurfaceHolder;
int intSurfaceWidth, intSurfaceHeight;

static Paint paint = new Paint();

static final String TAG = null;

// bitmap to scroll
Bitmap myScrollingImg;

// y position of bitmap. 0 = top of screen
int y = 0;

// check that surface has not been destroyed
boolean surfaceExists = false;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);

    mSurfaceView = (SurfaceView) this.findViewById(R.id.Surface);
    mSurfaceHolder = mSurfaceView.getHolder();
    mSurfaceHolder.addCallback(this);

    paint.setColor(0xFFFFFFFF);
    paint.setStyle(Style.STROKE);

    // load the bitmap
    myScrollingImg = ((BitmapDrawable)getResources().getDrawable(R.drawable.icon)).getBitmap();

}

@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
        int height) {}

@Override
public void surfaceCreated(SurfaceHolder holder) {

    // start a new thread. According to android docs, canvas can only be
    // manipulated between surfaceCreated and surfaceDestroyed
    surfaceExists = true;
    MyThread thread = new MyThread();
    thread.execute(null);

}

@Override
public void surfaceDestroyed(SurfaceHolder holder) {
        surfaceExists = false;
}

class MyThread extends AsyncTask{

    @Override
    protected Object doInBackground(Object... params) {

        while(surfaceExists){
        Canvas rCanvas = mSurfaceHolder.lockCanvas();

        // reset the canvas to blank at the start
        rCanvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);

        // translate to the desired position
        rCanvas.translate(0,y);

        // draw the bitmap
        rCanvas.drawBitmap(myScrollingImg, 0, 0, paint);

        mSurfaceHolder.unlockCanvasAndPost(rCanvas);

        // increment y so that bitmap is 1 pixel further down next call
        y++;
        }
        return null;
    }

}

}

```
> 2 votes

# Answer
I had this problem and figured out why this happened. It's due to a bit of negligence in android's translate function. Basically it's because the function ONLY works by copying pixels left-to-right per row from top-to-bottom, without checking which direction you're translating to. So going left and down, it works because it is copying existing pixels to 'old' pixels, but the other way around, you're copying pixels to pixels you want to copy later on.

The trick to solving this is to use the faster translate function in the right/down translation, but use a slower, bitmap copying way for the other directions. Or maybe find some way to override the translate function with one which does it correctly, but I haven''t figured out how to do that yet.

I have a little writeup here: http://spiralcode.wordpress.com/2013/06/17/long-time-no-see-of-rivers-cartography-and-tiling/
> 1 votes

---
Tags: android, java, html-canvas, bit-blit
---


# Question
Title: SpriteFont Exception, no such character?
I have such spriteFont:

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

    <!--
    Modify this string to change the font that will be imported.
    -->
    <FontName>Segoe UI</FontName>

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

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

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

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

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

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

```

It has the character regions (32-1200)

And I get this exception:

`A first chance exception of type 'System.ArgumentException' occurred in Microsoft.Xna.Framework.Graphics.ni.dll`

`The character 'с' (0x0441) is not available in this SpriteFont. If applicable, adjust the font's start and end CharacterRegions to include this character.`

`Parameter name: character`

Why?

I'm drawing the string like this:

```
spriteBatch.DrawString(font24, zasadyText, zasadyTextPos, kolorCzcionki1, -0.05f, Vector2.Zero, 1.0f, SpriteEffects.None, 0.5f)

```

I even changed the spriteFont to cyrillic:

```
    <CharacterRegions>
      <CharacterRegion>
        <Start>	</Start>
        <End>	</End>
      </CharacterRegion>
      <CharacterRegion>
        <Start> </Start>
        <End>ſ</End>
      </CharacterRegion>
      <CharacterRegion>
        <Start>А</Start>
        <End>ї</End>
      </CharacterRegion>
    </CharacterRegions>
  </Asset>
</XnaContent>

```

and it still doesn't work. I got the (0x441 =\> char) exception

-- EDIT --

Ok, I got the solution. It was a letter mistake in language. I had this:

```
if (jezyk == "ru_RU")
{
    font14 = Content.Load<SpriteFont>("ru_font14");
    font24 = Content.Load<SpriteFont>("ru_font24");
    font12 = Content.Load<SpriteFont>("ru_czcionkaFloty");
    font10 = Content.Load<SpriteFont>("ru_font10");

    font28 = Content.Load<SpriteFont>("ru_font28");
    font20 = Content.Load<SpriteFont>("ru_font20");
}

else
{
    font14 = Content.Load<SpriteFont>("font14");
    font24 = Content.Load<SpriteFont>("font24");
    font12 = Content.Load<SpriteFont>("czcionkaFloty");
    font10 = Content.Load<SpriteFont>("font10");

    font28 = Content.Load<SpriteFont>("font28");
    font20 = Content.Load<SpriteFont>("font20");
}

```

and there should be not `"ru_RU"` but `"ru-RU"`

---

I have no idea. I changed the spriteFont to cyrillic:

```
    <CharacterRegions>
      <CharacterRegion>
        <Start>	</Start>
        <End>	</End>
      </CharacterRegion>
      <CharacterRegion>
        <Start> </Start>
        <End>ſ</End>
      </CharacterRegion>
      <CharacterRegion>
        <Start>А</Start>
        <End>ї</End>
      </CharacterRegion>
    </CharacterRegions>
  </Asset>
</XnaContent>

```

and it still doesn't work. I got the (0x441 =\> char) exception

# Answer
> 1 votes
Your code:

```
<CharacterRegion>
   <Start>	</Start>
   <End>	</End>
</CharacterRegion>

```

Is basically instructing your compiler that you only want to use 1 character (code 09). You should remove this section of the code and leave only:

```
<CharacterRegion>
    <Start> </Start>
    <End>Ұ</End>
</CharacterRegion>

```

# Answer
> -1 votes
You could also uncomment this:

```
<DefaultCharacter>*</DefaultCharacter>

```

---
Tags: xna-4.0
---


title: How to do a multishot in xna?

text:
# Question
Title: How to do a multishot in xna?
I am trying to simulate a gun in which shoots multiple bullets at the same time(similar to a spread out shot). I am thinking I have to create another bullet array then do the same as I have below but in a different direction.

Here is what I have so far:

```
foreach (GameObject bullet in bullets)
    {

            // Find a bullet that isn't alive
            if (!bullet.alive)
            {
                //And set it to alive
                bullet.alive = true;

                if (flip == SpriteEffects.FlipHorizontally) //Facing right
                {
                    float armCos = (float)Math.Cos(arm.rotation - MathHelper.PiOver2);
                    float armSin = (float)Math.Sin(arm.rotation - MathHelper.PiOver2);

                    // Set the initial position of our bullets at the end of our gun arm
                    // 42 is obtained by taking the width of the Arm_Gun texture / 2
                    // and subtracting the width of the Bullet texture / 2. ((96/2)=(12/2))
                    bullet.position = new Vector2(
                        arm.position.X + 42 * armCos,
                        arm.position.Y + 42 * armSin);

                    // And give it a velocity of the direction we're aiming.
                    // Increae/decrease speed by changeing 15.0f

                    bullet.Velocity = new Vector2(
                        (float)Math.Cos(arm.rotation - MathHelper.PiOver4 + MathHelper.Pi + MathHelper.PiOver2),
                        (float)Math.Sin(arm.rotation - MathHelper.PiOver4 + MathHelper.Pi + MathHelper.PiOver2)) * 15.0f;

                }

                else //Facing left
                {
                    float armCos = (float)Math.Cos(arm.rotation + MathHelper.PiOver2);
                    float armSin = (float)Math.Sin(arm.rotation + MathHelper.PiOver2);

                    //Set the initial position of our bullet at the end of our gun arm
                    //42 is obtained be taking the width of the Arm_Gun texture / 2
                    //and subtracting the width of the Bullet texture / 2. ((96/2)-(12/2))
                    bullet.position = new Vector2(
                        arm.position.X - 42 * armCos,
                        arm.position.Y - 42 * armSin);

                    //And give it a velocity of the direction we're aiming.
                    //Increase/decrease speed by changing 15.0f
                    bullet.Velocity = new Vector2(
                       -armCos,
                       -armSin) * 15.0f;
                }

                return;
            }// End if

    }// End foreach

```

# Answer
I am assuming you are using some sort of pre-created bullet pool and every time the player shoots you call the above method? I would do the following.

1. Create a bullet creation method - Instead of hard coding the logic of setting the velocity and position you can encapsulate this in a method:

```
public Bullet createBullet(Vector2 position, Vector2 velocity)
{
    Bullet b = getUnusedBullet();
    b.velocity = velocity;
    b.position = position;
    b.alive = true;
    return b;
}

```
2. Have this method in a singleton service that can be accessed by your gun object.

```
public class BulletService
{
    private static BulletService instance;

    private BulletService() { }

    public static BulletService getBulletService()
    {
        if(instance == null)
        {
            instance = new BulletService();
        }
        return instance;
    }

    // Implementation logic...
}

```
3. Have your bullet pool inside this singleton service, the service should also handle stuff like updating the bullets during the update loop, managing the bullet pool e.t.c.
4. Your gun object can then call call it as follows:

```
    private void shoot()
    {
        BulletService bulletService = BulletService.getBulletService();
        bulletService.shoot(position, angle);
        bulletService.shoot(position, angle);
        bulletService.shoot(position, angle);
        //e.t.c.
    }

```

The above is one way to solve the problem, there are many many other ways but in general you should break up the code and make things reusable if it makes sense.

Your bullet pool logic is horribly inefficient as well, you shouldn't loop through every bullet everytime you need to find a new one that you can use. There are ways to do pools with all operations being constant time. This is a very simple to understand implementation: http://www.blackwasp.co.uk/ObjectPool.aspx There are better ones that don't affect the GC at all but the above one should suffice.
> 1 votes

---
Tags: xna, c#, game-design
---


# Question
Title: How to stop camera from rotating in 2.5d platformer
I'm stuck with a problem: I can not make my camera stop rotating after character.

What I already have tried: using empty game object with rigid body and locked rotation and make it parent of camera, while player being the parent of object. Also, I've tried using few scripts from web, that did not help.

Right now I'm bad with using JS in Unity (can handle JS on website, but I dont know how to integrate it for now) and practicing the basics, making easy 2.5d platformer with basic features, so I can not write code for now.

# Answer
This is a pretty straightforward coding problem, so don't shy away from writing a custom script to handle this problem. You just need to:

* Create a new script
* Double click that script to edit it
* Add a public variable at the top to link the target (in C# you'd want to declare this variable as Transform, but I don't think you need to type variables in JS)
* In the Update() function that is created with the basic script template, make this.transform.position = Vector(target.position.x, target.position.y, camera offset)
* In the Unity Editor drag this script onto the camera to set it as a component of the camera
* Drag the target object into the target variable of the component

The Update() function runs over and over while the game is running, so what this script does is position the camera every frame to move with the target, but the script doesn't affect the camera's rotation.
> 2 votes

---
Tags: unity, camera, 2.5d
---


title: fast java2d translucency

text:
# Question
Title: fast java2d translucency
I'm trying to draw a bunch of translucent circles on a Swing JComponent. This isn't exactly fast, and I was wondering if there is a way to speed it up. My custom JComponent has the following paintComponent method:

```
public void paintComponent(Graphics g) {
    Rectangle view = g.getClipBounds();

    VolatileImage image = createVolatileImage(view.width, view.height);
    Graphics2D buffer = image.createGraphics();
    // translate to camera location
    buffer.translate(-cx, -cy);
    // renderables contains all currently visible objects
    for(Renderable r : renderables) {
        r.paint(buffer);
    }
    g.drawImage(image.getSnapshot(), view.x, view.y, this);
}

```

The paint method of my circles is as follows:

```
public void paint(Graphics2D graphics) {
    graphics.setPaint(paint);
    graphics.fillOval(x, y, radius, radius);
}

```

The paint is just an rgba color with a \< 255:

```
Color(int r, int g, int b, int a)

```

It works fast enough for opaque objects, but is there a simple way to speed this up for translucent ones?

# Answer
The immediate potential performance problems I see in your code are:

1. You are recreating the volatile image in every paintComponent
2. Calling image.getSnapshot() to convert the VolatileImage to BufferedImage.

There is a good example in the beginning of VolatileImage documentation on how to deal with both of the problems.

In the comments you say that 2. is required so that you can later use BufferedImageOp to filter the rendered image. I think this is a mistake, because as far as I know, BufferedImageOp processes each individual pixel of the image on CPU. This operation alone is likely much slower than any problems regarding image creation or conversion.

I recommend you to take a look at AlphaComposite and the related tutorial. Alternatively depending on what exactly you want to achieve, you could just fill another semi-transparent rectangle on top of everything. With a TexturePaint you can probably create the noise filter you are looking for.

In addition instead of using VolatileImages, you could try GraphicsConfiguration.createCompatibleImage to create accelerated BufferedImages. Benchmark if this has the same performance as VolatileImage. If it does, it will be easier to manage than VolatileImage.
> 1 votes

# Answer
Pixel-pushing speeds are a known limitation of Java's out-of-box software renderer. Even with GPU hardware rendering, built for pushing pixels, overdraw / pixel blending / fill rates are known to have profound impacts on performance. Nevertheless, this is one of the reasons we have GPUs. If it's mission critical, I suggest a low-level library that provides access to native GPU functions, like LWJGL or JOGL, or else google "fast 2D graphics libraries Java".

P.S. Under the hood, millions of division and conditional operations have to take place every tick, in software, in order to support what you're trying to do, and all on a single thread / core (the main thread). GPUs handle this load through being massively parallel -- several tens to several hundreds of cores will be operating on large blocks of pixels simultaneously, reducing blending costs by orders of magnitude.

Slick2D may be a good option for you, as it is a 2D library that utilises LWJGL / OpenGL / your GPU under the hood.
> 1 votes

---
Tags: java, transparency, swing
---


title: Large resolution differences

text:
# Question
Title: Large resolution differences
I want to develop a game on multiple devices such as PC, Android or IOS. Want it to be in 1080p, but that means a massive scale down for the smartphones.

I know how to do that, just render everything on a 1080p rendertarget and then render it on the screen smaller.

But what should I do so that the scalling down doesn't look bad and blury? I can't do it vector based or anything because the sprites simply need a specific size. Should I make the sprites power of two size to get some nice mipmapping? And which other settings can I do?

Or should I rather go with a lower resolution but then having a little bit worse look PC version? The performance seems not to be a problem for me, so would be sad not using 1080p because of other problems.

# Answer
Design the game for the lowest resolution, not the highest. The only benefit you get from designing for a high resolution in a game with 2D graphics is that you can display more at once while maintaining the same level of detail. There are plenty PC games that are designed for lower resolutions some games using Pixel art even go as low as 320x240 or even 160x120. They still look good on modern HD monitors.

Art wise, *unless you making pixel art*, make the assets in the highest resolution, and always render in the highest native resolution, but design the game/the UI in a low resolution.

**A game that works well with a low resolution will work well on a high resolution screen, the other way around that is not the case.**
> 2 votes

# Answer
If you are trying to create an ultra portable game for Windows, IOS, and Android from one code base, you are going to have a bad time.

In terms of Android see here.

In order to port your bitmaps to multiple devices on Android it is best practice to create each bitmap for each of the target densities. This translates into about 4 or 5 png files for each image.

When it comes to portability on Android mobile devices - different devices have different screen sizes. Some have more some have less, which means that you have to account for this extra and missing space.

It is not quite the same on iOS. iOS densities just scale by a factor of two (so I've been told) which makes it slightly easier to manage than Android.

I recommend picking a single target platform, or ideally use C++ and program your game. Worry about porting your game after you have it completed.

If portability is ultra important, make it a web based browser game, or try using an engine.
> 0 votes

---
Tags: c#, 2d, android, windows, monogame
---


# Question
Title: How does a segment-based rendering engine (as in Descent) work?
As far as I know Descent was one of the first games that featured a fully 3D environment, and it used a segment based rendering engine.

Its levels are built from cubic segments (these cubes may be deformed as long as it remains convex and sides remain roughly flat). These cubes are connected by their sides. The connected sides are traversable (maybe doors or grids can be placed on these sides), while the unconnected sides are not traversable walls. So the game is played inside of this complex.

Descent was software rendered and it had to be very fast, to be playable on those 10-100MHz processors of that age. Some latter levels of the game are huge and contain thousands of segments, but these levels are still rendered reasonably fast. So I think they tried to minimize the amount of cubes rendered somehow.

How to choose which cubes to render for a given location? As far as I know they used a kind of portal rendering, but I couldn't find what was the technique used in this particular kind of engine. I think the fact that the levels are built from convex quadrilateral hexahedrons can be exploited.

# Answer
descent uses a portal rendering engine this engine divides the world in convex rooms and the engine knows which room you are in

then to render you render the rooms faces and for each visible face that is a portal you adjust the frustum and render the room that the portal links to

in psuedo code:

```
renderRoom(room) {
    foreach face in room
    {
        if(!visible(face))continue;
        if(!isPortal(face))render(face);
        if(isPortal(face))
        {
            push frustum
            adjustFrustum(face)
            renderRoom(face.room)
            pop frustum
        }
    }
}

```

if a portal face is not visible then you don't need to render the room that connects through the portal

tutorial I found for creating a portal engine: http://www.flipcode.com/archives/Building\_a\_3D\_Portal\_Engine-Issue\_01\_Introduction.shtml
> 8 votes

---
Tags: software-rendering, portals
---