# Question
Title: Tiled perlin/value noise texture with (2^n)+1 size
Actually what I have in mind is value noise I think, but what I am going to ask applies to both of them.

It is known that if you want to produce tiled texture by using the perlin/value noise, the size of the texture should be specified as the power of 2 (2^n). Without any modifications to the algorithm when you use the size of (2^n)+1 the texture cannot be tiled anymore, so I am wondering whether it is possible (by modifying the algorithm somehow) to generate such tiling texture with the size of (2^n)+1. The article (from which I have my implementation) is here: http://devmag.org.za/2009/04/25/perlin-noise/

I am aware that I can produce texture with 2^n size and just copy twice the last column/row from the ends to make it (2^n)+1, but I don't want to, because such repetitions are visible too much.

# Answer
The paper Procedural Textures Using Tilings With Perlin Noise describes how to solve this.

**Perlin noise overview**

Perlin noise made by taking a regular square (or cube / hypercube) grid and selecting pseudorandom gradient vectors in the corners of this grid. Output of the noise is then based on the gradient vectors of the four nearest grid corners. (A little detail that was confusing me for a long time -- In all implementations I've seen you never calculate the gradient vectors directly, instead dot product of the gradient vector and a vector from the examined point is calculated directly).

Large part of Perlin noise implementation consists of hashing the point positions to obtain the gradient vectors. Because this operation starts by anding coordinates with 0xFF, the common implementation of the noise is periodic every 256 units.

**Periodic Perlin**

In the article they make the noise tileable by making sure that the first column of gradient vectors is the same as the last one, and that the top and bottom row are the same.

I must admit that I didn't read the article too carefully, but I think they are explicitly building a grid with gradient vector indexes, and copying the rows and columns where necessary. Also they use colored edges for Wang tiles. In my implementation I used a simple modulo operator calculated on the fly + some additional magic (I needed to make multiple sizes of noise (32x32px, 64x64px and 128x128px), each tileable with all sizes).

This is how the relevant part of my implementation looks like:

```
float grad(int X, int Y,
           int width, int height,
           int tilingWidth, int tilingHeight,
           int seed, int edgeSeed,
           float x, float y)
{
  int hash;
  if (X % width == 0 || Y % height == 0)
    hash = p[p[p[X % tilingWidth] + Y % tilingHeight] + edgeSeed];
  else
    hash = p[p[p[X] + Y] + seed];

  return ((hash & 1) ? x : -x) + ((hash & 2) ? y : -y);
}

```

Here `X` and `Y` are coordinates of the grid point, `width` and `height` are the size of the grid and `tilingWidth` and `tilingHeight` are size of the smallest tileable unit (my 32x32px tiles have `width` and `height` 1, `tilingWidth` and `tilingHeight` 1, 64x64 tiles have `width` and `height` 2, `tilingWidth` and `tilingHeight` 1). `seed` changes interior of the noise, `edgeSeed` changes the edges. `x` and `y` are the input vector that is getting dot-producted with the gradient vector.

The hashing trick (array of twice repeated permutation of 256 values in `p`, `hash = p[hash + nextByte]`) was copied from the regular Perlin noise as well as the final line that outputs the dot product.

**Multioctave**

Once this single octave noise is done, it is easy to add multiple octaves. Only thing that must be taken care of is to increase the period as the noise is scaled to higher frequency.

```
// ...
value += singleOctave(x * frequency, y * frequency,
                      width * frequency, height * frequency /* THIS!! */
                      tilingWidth * frequency, tilingHeight * frequency /* and THIS!! */
                      /* ... */) * amplitude;
// ...

```

**Limitations**

The seed does not has as much influence on the noise as it would have for a regular noise. This is because the large low frequency waves are almost completely determined by the edges.

Width and height must be integers. This is mostly a problem only for non-square tiles. with aspect ratios different than 1/2, 1/3, 2/3, ...
> 2 votes

---
Tags: perlin-noise
---


title: Optimization with VBOs

text:
# Question
Title: Optimization with VBOs
I am currently working on a cube engine and am experiencing some issues with CPU optimization.

I store all my quad VBO data inside a Block (at x,y,z of a chunk) class, which is stored inside an array with a length of 6 (the maximum number of cube faces). I would prefer to merge it all inside one VBO. The only issue I am having with this is that I cannot find a way to render 6 different textures on each face.

```
    GL11.glPushMatrix();
    GL11.glTranslatef(LENGTH.x * origin.x, LENGTH.y * origin.y, LENGTH.z * origin.z);
    for (int z = 0; z < LENGTH.z; z++) {
        for (int y = 0; y < LENGTH.y; y++) {
            for (int x = 0; x < LENGTH.x; x++) {
                Block b = get(x, y, z);
                if (b.getBlockType().isTransparent() || b.getVisibleFaces() == 0)
                    continue;
                GL11.glEnableClientState(GL11.GL_VERTEX_ARRAY);
                GL11.glEnableClientState(GL11.GL_TEXTURE_COORD_ARRAY);
                for (int i=0; i < b.getVertexBuffers().length; i++) {
                    QuadVBO q = b.getVertexBuffers()[i];
                    if (q == null || !q.isValid())
                        continue;
                    Game.GRASS.bind(i);
                    GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, QuadVBO.faceHandles[i].get(0));
                    GL11.glTexCoordPointer(2, GL11.GL_FLOAT, 0, 0);
                    GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, q.getVertexHandle());
                    GL11.glVertexPointer(3, GL11.GL_FLOAT, 0, 0);
                    GL11.glNormalPointer(GL11.GL_FLOAT, 0, q.getPointerVerticesBytes());
                    GL11.glDrawArrays(GL11.GL_QUADS, 0, q.getVerticesCount());
                    GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
                }
                GL11.glDisableClientState(GL11.GL_VERTEX_ARRAY);
                GL11.glDisableClientState(GL11.GL_TEXTURE_COORD_ARRAY);
            }
        }
    }
    GL11.glPopMatrix();

```

I am aware that this is a horrible way to do it but I cannot seem to find a better way to render these cubes on a screen, any help would be extremely appreciated!

# Answer
Pack the textures together into one big texture, use this for the entire VBO.

In your vertices, scale and offset the texture coordinates to "select" which texture to render with, (you'll have to keep track of what texture landed where in the big texture when you make your texture atlas)
> 1 votes

---
Tags: lwjgl, vbo, vertex-buffer
---


# Question
Title: Am I doing this node.js game loop wrong?
I have 2 arrays of JSON objects, actions and game objects.

At any time a user can make a request from the client which can add an action to the actions array.

I have a `setInterval(function(){ }, 1000);` that runs every second and first loops through all of the actions, doing them in order then dumping emptying the array. Then it for loops (on the length of the array) through all the objects and does change processing such as healing, repairing, consuming resources, updating location of travelling objects, etc.

Each game object is tied to a user and when it is done being modified it will push out to them using socket.io all the data they need for their current view (assuming they are in an active session still).

Is this right? Am I not taking advantage of the node.js event loop as well as I could for this?

# Answer
> 2 votes
It's better to use setImmediate() or process.nextTick() for game loop. setImmediate vs. nextTick

---
Tags: javascript, game-loop, events, node.js
---


title: LibGDX stretching 2d graphics

text:
# Question
Title: LibGDX stretching 2d graphics
I have a problem with stretching sprites in LibGDX.

I have one png file for the sky in the game (1 x 1000px) and I want to render it 1000 x 1000px

```
sprite.setSize(pixelWidth,pixelHeight);

```

I want to stretch this 1px-wide sky image. It has little gradient from the top to the bottom, as you can see. I want to make it 1000px in width. But I get this strange result:

You can see that there is something like a horizontal gradient, even with lines, but there's no apparent reason why that's happening, since I'm scaling a 1px wide image!

The strange thing is that everything looks fine on other PCs and mobile phones - but I don't think that the problem is with my PC!?

I don't know what to try. Any ideas?

# Answer
Without seeing your code, my ability to help you is limited. However, these are some ideas I can think of:

* There's another semitransparent texture on top of it, that is causing this problem. Try removing all other sprites, and if the problem is solved, then start adding sprites one by one to see which one is causing this problem.
* The texture coordinates are set to the corners, you're using bilinear filtering, and for some reason, the sampler is getting black pixels for out of range texture coordinates. To see if this is the problem, make the texture 2 pixels wide or more. If the correct color covers a wider area, this is probably your problem.

To fix this problem, you can do one or more of of:

+ Changing the texture U coordinates to 0.5 instead of 0 and 1
    + Explicity set the wrapping mode to clamp
    + Use nearest neighbor filtering
* The fragment shader is adding extraneous colors, probably due to an uninitialized uniform. Make sure you set values to all of your uniforms before you start drawing. In fact, this could actually explain why this only happens on your computer, which probably has shader debugging activated, and may set uninitialized uniforms to 0 (black).

The banding itself may be caused by the format of your framebuffer. When you created it, what pixel format did you set for it? RGBA4441 or similar could lead to banding like this.
> 1 votes

# Answer
If you want to make a gradient covering a rectangular area in libgdx, you can just use a `ShapeRenderer` and the method

```
shapeRenderer.fillRectangle(0,0,screenWidth, screenHeight, topColor, topColor, bottomColor,bottomColor);

```

for this.

It's a better solution as it's more portable and allows you to change the colors without making new art.
> 0 votes

---
Tags: textures, sprites, libgdx, scale
---


# Question
Title: XNA: Auto-populate content within the content project based on current folder/file structure and content management for large games
**1)** Is it possible to implement a system where I can simply drop a new image into my content project's folder and VS will automatically see that and bring it into the project for compiling?

**2)** Similarly, if I wanted a specific texture I could state something like `var texture = Game.Assets.Image["backgrounds/sky_02"];` (where `Game` is the standard XNA Game class and `Assets` is some kind of content manager statically defined within `Game`). I know this is fairly simple to implement manually and have done such things in the past (static `Dictionary` defined within `Game`) except this only works for relatively small games where you can have all assets loaded at the start without much issue. How would you go about making this work for games where content is loaded and unloaded based on level / area?

I'm not asking for the solution, just how you would go about this and what things you would have to be aware of. Thanks.

# Answer
I had the same problem, I constantly have to add/remove items from the Content Project and it's a pain to keep it updated. It becomes especially difficult if you create the folder structure outside of Visual Studio.

The solution I went for was to create a tool that generates the Content project file for me upon request/build. This means that I can create assets in an application and place them in the Content folder hierarchy without having to manually add them to the Content Project.

What this tool does (heavily simplified):

1. Loads existing Content Project file as a XML document. Removes all nodes that reference files.
2. Scans Content directory for files and stores their paths in a collection.
3. ...
4. Adds all the files in the collection back into the XML document.
5. Saves the XML document back to disk and overwrites the old Content Project file.

Now, you could simply build and run the tool whenever you need it or you could add it as a pre-build event on your game project so that whenever you build your game, it will update the content project.

The advantage with this type of tool is that you no longer have to touch the Content Project anymore. Simply add/remove files/folders to/from the Content folder hierarchy directly.

**UPDATE**

As requested, the project can be downloaded from here: ContentProjectUpdater

Steps to use:

1. Place it where ever you like. You can include it in your project or use it as a standalone application.
2. Update the App.config file so it points to your content project file.
3. Run the project by either executing the executable or right-click on the project-\>Debug-\>Start new instance.

It is mandatory that the Content Project already exists, it will not create it for you.
> 1 votes

# Answer
1. Should be possible, you need to compile your content to .xnb. You could etiher try to add a content pipeline extension which handles this for ou or take a look at the 'offline' content compiler project, which sure could be used to do this from code.
2. I have constructed a similar system some time ago, where I had content packages, which define the content needed at a certain point (level, game state, whatever you see fit). I would use an assertion like system to make sure the content is present when needed and at the same time backload the next packages. so while the player is playing level 1 the system will load level 2 as much as it could and when level 2 starts the game will show a loading screen until the package was fully loaded.
> 0 votes

# Answer
1) You can build assets at runtime if you have VS2010 installed.

There was a ContentManager project that scan a folder to find new files and builds them automatically at runtime, but I can't remember the blog where was the code.

But seems easy to code a standalone application to manage it, you need to use a FileSystemWatcher, built it again with a tool like the Xna 4.0 content compiler, or made by yourself (see Winform series )

And then if you have a Game running, you would comunicate both, the compiling tool and the game with an UDP socket to alert that assets have benn changed.

2) You can instance several content managers, so you can create a content manager per level, although it implies tht some assetes can be duplicated.

But there is a project named Content Tracker at codeplex that lets you know the references count of an asset and unload it when there is no references to it, so it's easy to implement a solution for what you want.

This is the link to the Xna 4.0 to the Content Tracker project
> 0 votes

---
Tags: xna, xna-content-pipeline
---


# Question
Title: Best way to implement achievement system?
I'm currently trying to implement achievement system for my game. However, I can't find a better way to realize some complex ones like: The player has collected x coins, complete level with time least than x seconds, Kill over x enemies etc. Can you share your experiences please?

Secondly, Why don't we just implement achievement system as local only instead of using server like Scoreloop or OpenFeint? Or put it in another way, What are the advantages of using server for managing player's achievement?

# Answer
> 9 votes
An achievement system can be pretty complex. Many of the achievements are special cases that need to be watched for. That means special code, just for that achievement. Some will be easy to code for, like finishing a level under a certain amount of time or total number of coins collected. As simple as having a timer or a global counter. The more complex achievements, obviously, require more complex code. Killing x type of enemies over x number of seconds would could require a rolling counter or detailed logging with regular analysis.

Basically, if you want achievements, you need to code them in. Just like any other feature. As the developer you have access to all the information about the game, you just need to log what happens and see if it matches your achievement requirements.

I plan on implementing my achievement system into the event system. Since I'm already sending significant events to be logged, I might as well let the achievement system listen in. This is nice because then all the code for achievements is in one place. So for example, you could fire an event each time a level ends. The event would include all the information about the performance of the player on that level including their score, time to complete, number of coins collected and so on. Those events are read by the event system and logged. You can then keep running totals of coins collected and compare finish times to previous bests.

As for the server for managing achievements. I believe one of the big draws with achievements is sharing them with others, or comparing your achievements to your friends. Having the achievements hosted publicly implements the social features that are appealing to many types of gamers.

**EDIT**

Absolutely you can avoid hard-coded rules! The system I describe is mostly for collecting information and getting it all into one place. That would be best hard-coded and you will have to hard-code collection code for any additional rules. You try to collect as much significant data as you can, so you'll have more to work with later.

How you analyze the data is up to you. Incoming events can be filtered by rules defined in JSON or Lua. As for implementing Lua, I've not done that, so I don't know if it's easy to do. I imagine it is. Lua is a very powerful scripting language with plenty of resources to help if you get stuck. Seems like a good choice to me.

# Answer
> 0 votes
Usually achievement systems boil down to a simple pattern of:

values -\> conditions -\> achievements

1. Define a list of values that might influence achievements (e.g. Highscore, Highest-Completed-Level, Number-Of-Hours-Player, Cash-Earned)
2. Every time one of these values changes have the "owner" of the value (e.g. the "Player-Class" for "Cash-Earned") send a valueChanged( value\_id, new\_value ) event which is routed to the AchievementManager.
3. The AchievementManager checks his list of conditions (for incomplete achievements depending on that value) and updates the achievements (sending an event if needed).

Don't forget the load/save/reset edge-cases, but that's it.

My current implementation has around 70 lines of code, not including the "Achievement.config to achievement.cfg" converter.

The configuration currently looks like this:

```
ACHIEVEMENT_PLAYED_VERY_LONG_AND_EARNED_LOTS_OF_CASH: [
  VALUE_PLAY_TIME_IN_MINUTES > 3600,
  VALUE_CASH > 10k
]

```

The created .cfg, which is loaded by the game, then looks something like this

```
[Number of Achievements]
for each achievement
[CRC32 of the achievement string, e.g. ACHIEVEMENT_PLAYED_VERY_LONG_AND_EARNED_LOTS_OF_CASH]
[Number of Conditions]
for each condition
[CRC32 of the value name string, e.g. VALUE_CASH]
[condition type, e.g. 0 => less than, 1 => greater than]
[value, e.g. 10000]

```

The converter is actually a little smarter, extending "10K" to "10000", warning about duplicates, detecting of conditions are conflicting, etc.

Sidenotes: You could use an enum for the achievement and value id, but I prefer CRC32s, since you don't have to update a list for new values and still get the benefit of numeric keys and even can map them back to the original name in debug builds. (But ids are a completely different topic ;) )

The system once had a quite complexe boolean logic for conditions, but in the end all we ever used was "and", so we removed it.

---
Tags: android, game-design, achievements
---


# Question
Title: Calculate when round object is inside an ellipse
I want to calculate in java when a circle is inside an ellipse. I drew an example below:

For this particular problem, the top left corner of the field has the position `0.0f, 0.0f`. The bottom right corner has the position `1.0f, 1.0f`. The position of the bat is: `0.48f, 0.94f`. The goal is located at: `0.5f, 1.0f`, height is `0.1f` and the radius `0.4f`.

How can I calculate if the bat is inside the ellipse? What is the general algorithm?

# Answer
Ellipse math is not significantly more difficult than circle math (for detecting distance from the center).

To detect if a point is inside an ellipse, you check a `(a/b)` ratio of each component of the coordinate against a known constant. So really, it's the same as any 2-Vector distance check, except you manipulate the coordinates slightly before squaring them.

For example, if you scale the y-coordinate to the same range as the x-coordinate, you can treat it identically to circle. Like so:

```
Vector2 puckPos = {puck_x, puck_y};
Vector2 goalCenter = {screen_height, screen_width / 2};

float a = 0.4f * screen_width;
float b = 0.1f * screen_height;

if ((
       (puckPos.y * (a / b) - goalCenter.y) ^ 2 +
       (puckPos.x - goalCenter.x) ^ 2
    ) < a ^ 2) {

       // inside ellipse
}

```
> 2 votes

---
Tags: java, mathematics
---


# Question
Title: Proportional speed movement between mouse and cube
Hi i´m trying to move a cube with the freeglut mouse "glutMotionFunc(processMouseActiveMotion)" callback, my problem is that the movement is not proportional between the mouse speed movement and the cube movement.

MouseButton function:

```
#define MOVE_STEP 0.04
float g_x=0.0f;

glutMouseFunc(MouseButton);
glutMotionFunc(processMouseActiveMotion);

void MouseButton(int button, int state, int x, int y){
if(button == GLUT_LEFT_BUTTON && state== GLUT_DOWN){
    initial_x=x;
    }
}

```

When the left button gets clicked the x cordinate is stored in initial\_x variable.

```
void processMouseActiveMotion(int x,int y){
if(x>initial_x){
    g_x-= MOVE_STEP;
}else{
    g_x+= MOVE_STEP;
}
initial_x=x;
}

```

When I move the mouse I look in which way it moves comparing the mouse new x coordinate with the initial\_x variable, if x\>initial\_x the cube moves to the right, if not it moves to the left.
Any idea how can i move the cube according to the mouse movement speed? Thanks

EDIT 1 cube http://oct.imghost.us/S1lC.png

The idea is that when you click on any point of the screen and you drag to the left/right the cube moves proportionally of the mouse mouvement speed.

# Answer
> 1 votes
The easiest "sure fire" method of doing this that I know of is to project rays from the screen into the world, just like the various picking articles on this site talk about.

You can project a ray onto a surface upon which the cube is meant to move. In the simplest case this may just be the XY plane at Z=0. It could be a plane at a non-screen-aligned angle, like the "ground" XZ plane. Or it could be any arbitrary surface, like a heightmap or curved surface or polygonal surface.

I found it best when dragging and moving the mouse to shoot two rays. Take the original mouse position before the move and then the mouse position after the move. Project both rays into the scene. Form a vector from the pre-move projected point to the post-move projected point. Move the dragged object by that vector. This allows you to grab any part of the object - not just the center - and have the drag movement "feel right." If your surface is not a flat plane you'll need to snap the object to the surface (or project many points along its surface between the mouse move vector) in order to have the dragged object follow the surface visually and look nice.

Alternatively, if you're not dragging, but just want a fixed point on an object to follow the mouse, you need only project the single new mouse position and move the object there.

You could also use either interpolation or some super basic physics if you want the box to "chase" the mouse rather than instantly move along with it. If you go this route and want the movement to accelerate/decelerate, I highly recommend the physics approach rather than interpolation as interpolation doesn't work too well if the interpolated path might change in mid-interpolation, but the physics will just work as expected usually.

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


# Question
Title: OpenGL: Filtering/antialising textures in a 2D game
I'm working on a 2D game using OpenGL 1.5 that uses rather large textures. I'm seeing aliasing effects and am wondering how to tackle those.

I'm finding lots of material about antialiasing in 3D games, but I don't see how most of that applies to 2D games - e.g. antisoptric filtering seems to make no sense, FSAA doesn't sound like the best bet either.

I suppose this means texture filtering is my best option?

Right now I'm using bilinear filtering, I think:

```
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

```

From what I've read, I'd have to use mipmaps to use trilinear filtering, which would drive memory usage up, so I'd rather not.

I know the final sizes of all the textures when they are loaded, so can't I somehow size them correctly at that point? (Using some form of texture filtering).

# Answer
Techniques like filtering and mipmaps will be useful when you have projections different from Orthogonal (specially anisotropic filters), or you don't previously know the resulting size of your textures on screen. And this, as you mention it, is not your case.

I think the best answer for your problem is first to ensure the 1:1 aspect ratio between your source art and the presentation of it, and exploring the use of Multisampling, where it will sample a pixel multiple times with slightly variations and then combine them.
> 1 votes

# Answer
Resample the image as soon as you know the target size.

You can use the GPU to resample with hardware acceleration:

1. Load your big texture and enable/create mipmaps.
2. Create your real texture at the perfect size.
3. Use an FBO to draw the big texture as a quad into the small texture.
4. Delete the big texture from memory.

---

Or you can use the CPU if you aren't satisfied with how mipmaps look, but going further than that in image quality would be a much longer answer, and probably more suited to another stack network site as it's more of general programming algorithm question. With that said, SDL\_rotozoom can give you the basic idea of how it can work at the lowest level.
> 1 votes

---
Tags: opengl, 2d, textures, antialiasing, filtering
---


title: Orthographic (0,0) center

text:
# Question
Title: Orthographic (0,0) center
I want to display coordinates from 0 to n, where n is `int > 0`.
The map is displayed correctly heaving it's center in the middle of the screen pointing top right. I would like to have it pointing bottom right.

My implementation is:

```
effect.Parameters["wvp"].SetValue(Matrix.Translation(0, 0, 0) *
    Matrix.LookAtLH(Vector3.Zero, Vector3.UnitZ, Vector3.Up) *
    Matrix.OrthoLH(GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height, 0, 1));
effect.Techniques[0].Passes[0].Apply();

GraphicsDevice.SetDepthStencilState(GraphicsDevice.DepthStencilStates.None);
GraphicsDevice.SetRasterizerState(GraphicsDevice.RasterizerStates.CullNone);
GraphicsDevice.Clear(Color4.Black);
GraphicsDevice.SetVertexBuffer(layer.Buffer);
GraphicsDevice.SetVertexInputLayout(layer.InputLayout);

GraphicsDevice.Draw(PrimitiveType.TriangleList, layer.Buffer.ElementCount);

```

And a screenshot of the situation now. The white area is around coordinate (0, 0). The line is just at X = Y for orientation. The black line should be pointing bottom right as mentioned above. Any Idea how this can be done?

# Answer
To do this the right way, you'll need to do two things. First, adjust your Translation matrix to offset by -1 in the Y direction (0, -1, 0). Second, you should adjust the texture coordinates in your layer.Buffer data so that it matches what you want. Alternatively, if you are reusing the layer.Buffer for multiple positions, you can programmatically adjust the coordinates by modifying effect parameters other than wvp, assuming the effect supports it.
> 2 votes

# Answer
Negate the height in your `OrthoLH` call and that should do the trick.

Note that if you're using backface culling, you'll have to reverse the culling orientation after making this change, as it switches the handedness of the coordinate system.
> 1 votes

---
Tags: sharpdx
---


# Question
Title: A-Star Pathfinding Not Giving Shortest Path
I'm attempting to implement the A\* pathfinding algorithm in Java. I thought it was working well, but then I found instances where it doesn't follow the shortest path

Green = start, red = target, black = walls (unwalkable), blue = path

Red # in top left is G value, green # in top right is H value, black # in middle is F value. Black lines show parents.

I have a Node class which has the following properties: Integers x, y == 0 Integers f, g== -1 Node parent

H is calculated using the diagonal shortcut method described here

```
int xDist = Math.abs(end.x - x);
int yDist = Math.abs(end.y - y);
//end == target node
if (xDist > yDist) {
    h = 14 * yDist + 10 * (xDist - yDist);
} else {
    h = 14 * xDist + 10 * (yDist - xDist);
}

```

G is calculated as follows:

```
public int getG(boolean force) { //force == true will recalculate G
    if (g == -1 || force) {
        if (equals(start) || parent == null) {
            g = 0; //If its the start, g = 0
        } else {
            g = parent.getG(force) + (parent.x != x && parent.y != y ? 14 : 10);
            //10 for orthogonal moves, 14 for diagonal
        }
    }
    return g;
}

```

The path is calculated using this findPath method:

```
public static boolean findPath(Node start, Node end) {
    if (start.block || end.block) {
        //start or target has a wall on it
        return false;
    }
    Node.start = start;
    Node.end = end;
    LinkedHashSet<Node> open = new LinkedHashSet<Node>();
    LinkedHashSet<Node> closed = new LinkedHashSet<Node>();
    //open and closed lists, respectively
    boolean found = false;
    open.add(start);
    //add the starting node to open list
    while (open.size() > 0) {
        //while there is something in open list
        int lowF = Integer.MAX_VALUE;
        int curF = 0;
        Node curN = null;
        for (Node node : open) {
            curF = node.getF();
            if (curF < lowF) {
                lowF = curF;
                curN = node;
            }
        }
        //curN == lowest F value in open list
        if (curN == end) {
            //target has been found
            found = true;
            break;
        }
        open.remove(curN);
        closed.add(curN);
        //switch the lowest F value Node to the closed list
        for (Node node : curN.getAdjacent()) {
            //iterate over non-wall adjacent nodes
            if (closed.contains(node)) {
                //already on closed list
                continue;
            }
            if (!open.contains(node) || node.getG() < curN.getG()) {
                //not on open list OR it has a lower G cost
                node.parent = curN;
                //set node's parent to the lowest F cost Node from before
                node.getF(true);
                //recalculates the F (and G) values
                open.add(node);
                //add to the open list.
                //will NOT be readded if already present
            }
        }
    }
    return found;
    //loop is over, return true
}

```

I lead myself to believe that the issue was in my heuristic, however I'm not sure that's the case anymore: shouldn't the shortest path still be found eventually?

The path begins by approaching the target the fastest way because of the heuristic, but then seems to "change it's mind." I've been baffled for days.

When I remove the H value (i.e. set it to 0) I get the expected result. When I remove diagonal movement I also get the expected result.

# Answer
Here is the pseudo-code from wikipedia for A\* with a consistent-heuristic:

```
1. while openset is not empty
2.     current := the node in openset having the lowest f_score[] value
3.     if current = goal
4.        return reconstruct_path(came_from, goal)
5.
6.     remove current from openset
7.     add current to closedset
8.     for each neighbor in neighbor_nodes(current)
9.        tentative_g_score := g_score[current] + dist_between(current,neighbor)
10.       if neighbor in closedset and tentative_g_score >= g_score[neighbor]
11.          continue
12.
13.       if neighbor not in openset or tentative_g_score < g_score[neighbor]
14.          came_from[neighbor] := current
15.          g_score[neighbor] := tentative_g_score
16.          f_score[neighbor] := g_score[neighbor] + heuristic_cost_estimate(neighbor, goal)
17.          if neighbor not in openset
18.             add neighbor to openset
19.
20. return failure

```

The important lines are these:

```
9.        tentative_g_score := g_score[current] + dist_between(current,neighbor)
...
13.       if neighbor not in openset or tentative_g_score < g_score[neighbor]

```

The purpose of `tentative_g_score` is that you may need to update the g-score of a node in the open-list if you find a closer neighbor to it. You are not doing that; you are instead comparing the g-score of the node to the g-score of its neighbor.
> 7 votes

# Answer
I agree about the G values. Note that all paths chosen are diagonal unless there is no other choice.

I suspect that the error may be in this line: if (!open.contains(node) || node.getG() \< curN.getG())

The G comparison doesn't seem to compare apples with apples, you're comparing the G cost of the current node with the G cost of it's neighbour. Perhaps you should be comparing the G cost of the current node *plus the distance to the neighbour* with the G cost of the neighbour, or possibly comparing the F costs.
> 4 votes

# Answer
There is another bug beyond the neighbor-g confusion (described in BlueRaja's answer) and the incorrect computation of G (hinted at by poster's response).

Unlike optimal search algorithms like Dijkstra's algorithm, A\* requires re-opening closed nodes, so this code is incorrect:

```
        if (closed.contains(node)) {
            //already on closed list
            continue;
        }

```

Conceptually, you can only avoid re-opening closed nodes if you're guaranteed to only close them when you've found the optimal path to them. Dijkstra's algorithm finds the optimal path to all nodes on the grid, and so has this optimal subsequence property that avoids the need to reopen. But A\* uses H to bias the search and therefore does not guarantee that the first time a node is visited (closed) the optimal path to that interim node was actually found.

The internet appears to be full of incorrect descriptions and pseudocode for A\* that avoid reopening closed nodes. The wikipedia page is correct, as its pseudocode includes:

```
        if neighbor in closedset and tentative_g_score >= g_score[neighbor]
           continue

```

Another link which shows this correctly (but is easy to misinterpret the g values): http://en.wikibooks.org/wiki/Artificial\_Intelligence/Search/Heuristic\_search/Astar\_Search

On many A\* searches, failing to do this will have no effect (the bug is invisible). But with some searches it can have significant effects.
> 1 votes

---
Tags: java, algorithm, path-finding
---


title: Geometry shaders on Surface RT

text:
# Question
Title: Geometry shaders on Surface RT
Can anyone tell me if geometry shaders are supported on the Microsoft Surface RT? On one hand, MSDN makes it sound like the Surface RT supports only feature level 9\_1, and geometry shaders are only available in feature levels \>= 10\_0. On the other hand, there's this guy saying:

> Jesse Barker @incendy
> @dotMorten I am confused haha.. so my geometry shaders work on Surface rt?
>
> Morten Nielsen @dotMorten
> @incendy Yes ! They might run software emulation, but yes. That's why DX is so awesome. Don't worry about hardware. It'll work

Does anybody have actual experience with this? I don't have a Surface RT here to test with, so any guidance on this would be much appreciated.

# Answer
Surface RT is indeed FEATURE\_LEVEL\_9\_1, so hardware geometry shaders are unsupported. The Windows software rasterizer, WARP, does support it though. This could be what Morten is referring to. To create a WARP device, use D3D\_DRIVER\_TYPE\_WARP in your call to D3D11CreateDevice. Note that on Surface RT, the performance of geometry shaders on WARP will not likely be adequate for real-time scenarios.
> 3 votes

---
Tags: directx, windows-8, geometry-shader
---


title: Use light cone/range as a Trigger

text:
# Question
Title: Use light cone/range as a Trigger
I was wondering, in Unity 3D, how I could do something with the Spot Light (Range/cone) as a trigger? Since it would be very interesting to be able to manipulate whats actually in sight of Light range/cone, and then trigger an event / method.

Example of the Spot Light (Range/cone)

Since i'm at a Game Jam right now, I don't have infinite time, so some help or atlest thoughts on this, would be very much appreciated.

# Answer
> 3 votes
I'm not sure, but in Unity the surefire approach to anything tends to follow this pattern:

1. Create an empty GameObject.
2. Create a cone shaped collider and set as a trigger, e.g. using something like this: http://wiki.unity3d.com/index.php?title=CreateCone
3. Move the spotlight and collider under the GameObject.
4. Put a script on the GameObject which allows changing the range etc, possibly by scaling the collider or possibly by re-generating the mesh.
5. Moving/rotating should work fine because you always move/rotate the parent GameObject.

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


# Question
Title: Shadow mapping with deffered shading for directional lights - shadow map projection problem
I'm trying to implement shadow mapping to my engine. I started with directional lights because they seemed to be the easiest one, but I was wrong :) I have implemented deferred shading and I retrieve position from depth. I think that there is the biggest problem but code looks ok for me.

Now more about problem:

Shadow map projected onto meshes looks bad scaled and translated and also some information from shadow map texture aren't visible.

Yellow frustum is light frustum and I have mixed shadow map preview and actual scene. As you can see shadows are in wrong place and shadow of cone and sphere aren't visible.

Could you look at my codes and tell me where I have a mistake?

```
// create shadow map
if(!_shd)glGenTextures(1, &_shd);
glBindTexture(GL_TEXTURE_2D, _shd);
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, 1024, 1024, 0, GL_DEPTH_COMPONENT, GL_FLOAT,NULL); // shadow map size
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, _shd, 0);

glDrawBuffer(GL_NONE);

// setting camera
Vector dire=Vector(0,0,1);
ACamera.setLookAt(dire,Vector(0));
ACamera.setPerspectiveView(60.0f,1,0.1f,10.0f); // currently needed for proper frustum corners calculation

Vector min(ACamera._point[0]),max(ACamera._point[0]);
for(int i=0;i<8;i++){
    max=Max(max,ACamera._point[i]);
    min=Min(min,ACamera._point[i]);
}

ACamera.setOrthogonalView(min.x,max.x,min.y,max.y,-max.z,-min.z);

glBindFramebuffer(GL_DRAW_FRAMEBUFFER, _s_buffer); // framebuffer for shadow map

// rendering to depth buffer

glBindFramebuffer(GL_DRAW_FRAMEBUFFER, _g_buffer);

Shaders["DirLight"].set(true);

Matrix4 bias;
bias.x.set(0.5,0.0,0.0,0.0);
bias.y.set(0.0,0.5,0.0,0.0);
bias.z.set(0.0,0.0,0.5,0.0);
bias.w.set(0.5,0.5,0.5,1.0);

Shaders["DirLight"].set("textureMatrix",ACamera.matrix*Projection3D*bias); // order of multiplications are 100% correct, everything gives mi the same result as using glm

glActiveTexture(GL_TEXTURE5);
glBindTexture(GL_TEXTURE_2D,_shd);

lightDir(dir); // light calculations

```

Vertex Shader makes nothing related to shadow calculatons

Pixel shader function which calculates if pixel is in shadow or not:

```
float readShadowMap(vec3 eyeDir)
{
// retrieve depth of pixel
float z = texture2D(depth, gl_FragCoord.xy/screen).z;

vec3 pos = vec3(gl_FragCoord.xy/screen, z);

// transform by the projection and view inverse
vec4 worldSpace = inverse(View)*inverse(ProjectionMatrix)*vec4(pos*2-1,1);

worldSpace /= worldSpace.w;

vec4 coord=textureMatrix*worldSpace;

float vis=1.0f;
if(texture2D(shadow, coord.xy).z < coord.z-0.001)vis=0.2f;

return vis;
}

```

I also have question about shadows specifically for directional light. Currently I always look at 0,0,0 position and in further implementation I have to move light frustum along to camera frustum. I've found how to do this here: http://www.gamedev.net/topic/505893-orthographic-projection-for-shadow-mapping/ but it doesn't give me what I want. Maybe because of problems mentioned above, but I want know your opinion.

EDIT:

vec4 worldSpace is position read from depht of the scene (not shadow map). Maybe I wasn't precise so I'll try quick explain what is what: View is camera view matrix, ProjectionMatrix is camera projection,. First I try to get world space position from depth map and then multiply it by textureMatrix which is light view *light projection*bias. Rest of code is the same as in many tutorials. I can't use vertex shader to make something like gl\_Position=textureMatrix\*gl\_Vertex and get it interpolated in fragment shader because of deffered rendering use so I want get it from depht buffer.

EDIT2:

I also tried make it as in Coding Labs tutorial about Shadow Mapping with Deferred Rendering but unfortunately this either works wrong.

# Answer
I've already found some time and solution to my problems and I want share it with you. Maybe it will help someone:

```
float distFromCentroid=ACamera.far();
camera.setLookAt(frustum_centroid+dir->direction*distFromCentroid,frustum_centroid);

for(int i=0;i<8;i++){
    point[i]=ACamera._point[i]*camera.matrix;
}

min=point[0]; max=point[0];
for(int i=0;i<8;i++){
    max=Max(max,point[i]);
    min=Min(min,point[i]);
}

camera.setOrthogonalView(min.x,max.x,min.y,max.y,-max.z-distFromCentroid,-min.z);
camera.set();

glBindFramebuffer(GL_DRAW_FRAMEBUFFER, _s_buffer);

Shaders["Null"].set(true);

glViewport(0, 0, D.shadowMapSize(), D.shadowMapSize()); // this helps me to solve first problem
// rendering to depth buffer, I used here glPolygonOffset to solve problems with bias
glViewport(0, 0, D.x(), D.y()); // reset viewport

glBindFramebuffer(GL_DRAW_FRAMEBUFFER, _g_buffer);

// rest of code is almost the same as in first post

```

Shadow shader method:

```
float readShadowMap()
{
vec4 worldSpace=inverse(View)*vec4(posFromDepth(gl_FragCoord.xy/screen),1); // posFromDepth get position in view space from depth texture

vec4 coord=textureMatrix*worldSpace;

float visible=1.0f;

if(texture2D(shadow, coord.xy).z < coord.z)
    visible=0.2f;

return visible;
}

```

Hope it will be useful :)
> 3 votes

---
Tags: deferred-rendering, shadow-mapping, lighting, direction
---


# Question
Title: What is faster - loop in shader vs draw-call
I am doing some program, that can be written in two ways.

* render full screen quad and send some additional info to fragment shader. But in fragment shader I need to perform for-loop
* Move the loop to the CPU side of program and call draw-call on fullscreen quad repeatedly. Output will be rendered to texture. I will have two of them and swap active (write) and inactive (last output, read-only).

What can be faster ? I think, that number 1, but on the other side, loops are not very efficient in GLES shaders. And I need to calculate texture coordinates on the fly, which according to Apple doc is slower than if they goes directly from vertex shader and are not changed.

**Edit:**

Point two can be improved by this:

* I can put all quads to single buffer and draw them with one draw call (each quad will have different depth, but will be still fulscreen), where depth will be "loop" variable. In shader I take this "depth" and use blending (which can be used on iOS 6 via gl\_LastFragData\[0\])

# Answer
> 3 votes
There's only one way to be sure. Implement both and benchmark them on the hardware you care about. I'd be surprised if multiple passes was quicker though, because of the extra reading and writing of render targets required.

Multiple identical passes are generally only useful to work round the limitations of what a single pass can do (e.g. shader instruction count limits).

The cases when multiple passes are quicker tend to be one of:

* The shader can be much simpler with more passes (e.g. a separable blur).
* The extra pass does something quick and simple which makes the rest of the work much cheaper. For example downsizing the source render target, or filling in the stencil buffer.

---
Tags: opengl-es2
---


# Question
Title: cocos2dx - Custom Fragment Shader and CCRenderTexture
I have a `CCRenderTexture` that is filled with a sprite when the scene is loaded, as follows,

```
canvas = CCRenderTexture::create(this->getContentSize().width, this->getContentSize().height);
canvas->setPosition(data->position);
canvas->beginWithClear(0.0, 0.0, 0.0, 0);
this->visit();
canvas->end();

```

The above code is written within a class, which derives from CCSprite (Hence `this`).

Then, in another function `applyShader()`, I create a sprite named `splat`, from the texture of `CCRenderTexture *canvas`. Thus `splat` will contain the whole texture of `canvas`.

Now I apply a custom fragment shader to the `splat` by calling the function `splat->renderShader()`, which will modify some small portion of the whole texture.

Then I draw the modified texture back to the `CCRenderTexture *canvas`.

Hence, `applyShader()` will * take a texture from CCRenderTexture, * create a sprite based on it, * apply a fragment shader to it * and draw the modified texture back to CCRenderTexture.

This `applyShader()` will be called repetitively and its code is as follows:

```
splat = Splat::createWithTexture(art->canvas->getSprite()->getTexture());
splat->renderShader();
art->canvas->begin();
splat->visit();
art->canvas->end();

```

My shader code is (nothing fancy)

```
precision mediump float;

varying vec2 v_texCoord;
uniform sampler2D u_texture;
uniform sampler2D u_colorRampTexture;
uniform float params[5];

void main() {
    gl_FragColor = texture2D(u_texture, v_texCoord);
    return;
}

```

So, with the above code I expect the original sprite `this` to get rendered over and over again without any visual changes. But on each call to `applyShader()`, the texture is getting stretched a little and the stretched image is getting rendered. After some 10 calls, the image gets so distorted.

Can someone please tell me where I am going wrong?

Thanks :-)

PS: All code shown here is partial, not complete code.

Edit: Adding Screens

Update: **The problem has nothing to do with shaders it seems. It happens even when I dont call `renderShader()`.** The actual lines of code is:

```
splat = Splat::createWithTexture(art->canvas->getSprite()->getTexture());
splat->setPosition( ccp( art->getContentSize().width * 0.5, art->getContentSize().height * 0.5 ) );
splat->setFlipY(true);
art->canvas->begin();
splat->visit();
art->canvas->end();

```

# Answer
> 1 votes
Not a solution, but something that improves the situation

```
splat->setScale(0.995f);

```

Since the problem appears to be the `Splat` which gets scaled up a bit for some reason, I am trying to scale (down) it back. But 0.995f doesnt give exact results, I am in search for a `magic` number between 0.994 and 0.995 !!!

# Answer
> 0 votes
I don't know if you already solved this or not, but try this:

```
art->canvas->beginWithClear();
splat->visit();
art->canvas->end();

```

---
Tags: cocos2d-x, fragment-shader
---


# Question
Title: Database vs classes in a rpg character sheet app for android
i'm trying to develop an android app to handle character sheets in roleplay games like D&D and Pathfinder.

My target is to avoid calculations of bonuses by the player who only cares to set which talent is he using or by which magic he is afflicted.

The easiest way (imho) is to handle all talents and magic with classes, with methods that modify the attributes of the character class.

Another way is to store all talents and spells in a db and read from it when the user choose or use a talent or a spell.

Am i right saying that with 1st way i use more memory than the 2nd? (if not i'm choosing it)

If is better using db, I don't know how to save the data because is poorly structured:

Talent Improved Bluff: +2 to Bluff checks

Talent Speed: if the character wears no armor or light armor he moves 5 feet fast than his base speed

I can save the talent description as a meta-code string and parse it whithin the program but it seems too complicated. Do you have any better ideas for this db?

# Answer
It kind of sounds like you are confusing your concepts here. Classes and databases aren't mutually exclusive things, and most likely you would have your classes populated by a database on game/event/other load.

So the question should be more "What would an appropriate data structure for an RPG be? And what would be the most appropriate data store be?"

A data store may be a database, a xml file, a json file, a flat file, etc. The data structure could be anything from using classes/objects, right through to nothing and accessing the data store directly.

Knowing only that you want a small footprint I would use a combination for classes for the structure and json for the data store.

A class may be "Skill" with methods such as "name", "mp", and "magic attack". Your JSON might be something like:

```
{skills:[
  {"name":"Fire", "mp":20, "magic attack": 200},
  {"name":"Ice", "mp":30, "magic attack":250}
]};

```

And then when your game is loaded, or when the menu is accessed, etc, you would create a "new Skill(json.fire)" or similar. So there would be an instance per skill.
> 0 votes

# Answer
I am not exactly sure what you are asking, but I would not use a database.

If anything use XML. You can store the XML in a database if you want, or you could access the file directly via:

```
InputStream is = res.openRawResource(R.raw.fileName);

```

Really, I would use basic object orientation and just set up character class to contain or handle properties that represent the objects of the spells or the attributes, etc, and have the players input build the character class properties at run time.

If you are executing in a game loop I would recommend trying everything else before parsing xml or calling a database, especially a remote database.
> -1 votes

---
Tags: java, android, rpg, databases
---


title: Implementing Vehicles in your game

text:
# Question
Title: Implementing Vehicles in your game
In the game i am creating as an hobby (learning is the primal goal of it all) i plan to implement a space ship that the player can enter and use to explore it. I tried to search the internet for the concept of vehicle implementation but i couldnt find anything worth mentioning, and before I start writing the code I really want a clear idea of what I strive for. So id like to ask the pro game developers how should I look at a vehicle, should I think of it as a player's body extention with different mechanics? or should I just think of it as a usable exterior object? What kind of link should be between the player and the drivable vehicle? How do games usually do it, like GTA 2 and that kind of games?

Main Question: What is the basis of vehicle implementation?

P.S. I dont think its important to mention but the game is 2D and top-down perspective, so i guess GTA 2 can be a close reference to what i wanna do, although the gameplay is very different, but ye, the vehicle implementation i want is similar to GTA 2 although i only plan to do a space ship for now.

# Answer
> 4 votes
Most likely you will have a variable stored somewhere that is the current object (depending on how everything is set up).

This variable will be a pointer for a bunch of things such as the camera's anchor but also control.

For example (not java, just pseudo):

```
// Start up
var main_dude:Entity = new Dude();
var controlled_character:Entity = main_dude;

// Listen to events
this.addEventListener(ENTER_VEHICLE, onEnterVehicle);

// Later, as part of your main update cycle
function update() {
    controls.update(controlled_character); // listen for input, and update the controlled entity, what ever that is, if anything
    camera.update(controlled_character); // make sure camera is still over the main character
}

// Later later, depending on how your events are set up
function onEnterVehicle(enteredVehicle:Entity) {
   controlled_character = enteredVehicle; // now during the above update loop, the controls are being applied to the car, not the person
   main_dude.visible = false;
}

```

---
Tags: java, architecture, lwjgl, vehicle
---


title: Create fog (smoke) on Unity3D?

text:
# Question
Title: Create fog (smoke) on Unity3D?
I'm creating a game where you are inside a boiler room, the problem is I want to create the fog (smoke) to make this more realistic.

# Answer
There's particle effects, global fog and custom shader effects such as volumetric fog. A few helpful links are below:

Check the Unity Asset Store for alternate fog solutions.
> 4 votes

---
Tags: unity, graphic-effects
---


title: GetData() error creating framebuffer

text:
# Question
Title: GetData() error creating framebuffer
I'm currently porting a game written in C# with XNA library to Android with Monogame. I have a `Texture2D` and i'm trying to get an array of `uint` in this way:

```
Texture2d textureDeform = game.Content.Load<Texture2D>("Texture/terrain");
uint[] pixelDeformData = new uint[textureDeform.Width * textureDeform.Height];
textureDeform.GetData(pixelDeformData, 0, textureDeform.Width * textureDeform.Height);

```

I get the following exception:

> System.Exception: Error creating framebuffer: Zero at Microsoft.Xna.Framework.Graphics.Texture2D.GetTextureData (Int32 ThreadPriorityLevel) \[0x00000\] in :0

I found that the problem is in `private byte[] GetTextureData(int ThreadPriorityLevel)` creating the `framebuffer`:

```
private byte[] GetTextureData(int ThreadPriorityLevel)
{
            int framebufferId = -1;
            int renderBufferID = -1;

            GL.GenFramebuffers(1, ref framebufferId);  // framebufferId is still -1 , why can't be created?
            GraphicsExtensions.CheckGLError();
            GL.BindFramebuffer(All.Framebuffer, framebufferId);
            GraphicsExtensions.CheckGLError();
            //renderBufferIDs = new int[currentRenderTargets];
            GL.GenRenderbuffers(1, ref renderBufferID);
            GraphicsExtensions.CheckGLError();

            // attach the texture to FBO color attachment point
            GL.FramebufferTexture2D(All.Framebuffer, All.ColorAttachment0,
                                    All.Texture2D, this.glTexture, 0);
            GraphicsExtensions.CheckGLError();

            // create a renderbuffer object to store depth info
            GL.BindRenderbuffer(All.Renderbuffer, renderBufferID);
            GraphicsExtensions.CheckGLError();
            GL.RenderbufferStorage(All.Renderbuffer, All.DepthComponent24Oes,
                                   Width, Height);
            GraphicsExtensions.CheckGLError();

            // attach the renderbuffer to depth attachment point
            GL.FramebufferRenderbuffer(All.Framebuffer, All.DepthAttachment,
                                       All.Renderbuffer, renderBufferID);
            GraphicsExtensions.CheckGLError();

            All status = GL.CheckFramebufferStatus(All.Framebuffer);

            if (status != All.FramebufferComplete)
                throw new Exception("Error creating framebuffer: " + status);

...
}

```

The `frameBufferId` is still -1, seems that `framebuffer` could not be generated and I don't know why. Any help would be appreciated, thank you in advance.

# Answer
> 1 votes
I would look at the "ref" parameter. Your frame ID might be zero and when you use the "ref" it will add 0 + -1 = -1.. Microsoft example...

```
class RefExample
{
    static void Method(ref int i)
    {
        // Rest the mouse pointer over i to verify that it is an int.
        // The following statement would cause a compiler error if i
        // were boxed as an object.
        i = i + 44;
    }

    static void Main()
    {
        int val = 1;
        Method(ref val);
        Console.WriteLine(val);

        // Output: 45
    }
}

```

---
Tags: xna, android, opengl-es, opengl-es2, monogame
---


# Question
Title: Should the networking of my game be a component or a service?
I am working on a windows game and I am trying to understand the XNA GameComponents and GameServices classes and use. From what I understand about a component is that it has an Update method that gets call in every frame, and a service can be referenced from other components if needed.

So the way I think a network component would work is that in its Update method it would receive and send data. It probably makes sense to receive the network data once per frame, but it doesn't for sending it. Shouldn't the game send its own updates to others the moment it has it to cut down on lag?

# Answer
I would suggest looking at threading to communicate so you know when you lose connections and when to drop that client from your list. There is a good example of this here. A server that uses a COM object will run as a service automatically and may still run even if you close your APP...

I would run the clients and severs as a class and create them on the heap rather than the stack.
> 0 votes

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


# Question
Title: Bullet Physics implementing custom MotionState class
I'm trying to make my engine's camera a kinematic rigid body that can collide into other rigid bodies. I've overridden the btMotionState class and implemented setKinematicPos which updates the motion state's tranform. I use the overridden class when creating my kinematic body, but the collision detection fails. I'm doing this for fun trying to add collision detection and physics to Sean O' Neil's Procedural Universe

I referred to the bullet wiki on MotionStates for my CPhysicsMotionState class.

If it helps I can add the code for the Planetary rigid bodies, but I didn't want to clutter the post.

Here is my motion state class:

```
class CPhysicsMotionState: public btMotionState {
protected:
    // This is the transform with position and rotation of the camera
    CSRTTransform* m_srtTransform;
    btTransform m_btPos1;
public:
    CPhysicsMotionState(const btTransform &initialpos, CSRTTransform* srtTransform) {
        m_srtTransform = srtTransform;
        m_btPos1 = initialpos;
    }

    virtual ~CPhysicsMotionState() {
        // TODO Auto-generated destructor stub
    }

    virtual void getWorldTransform(btTransform &worldTrans) const {
        worldTrans = m_btPos1;
    }

    void setKinematicPos(btQuaternion &rot, btVector3 &pos)
    {
        m_btPos1.setRotation(rot);
        m_btPos1.setOrigin(pos);
    }

    virtual void setWorldTransform(const btTransform &worldTrans) {
        btQuaternion rot = worldTrans.getRotation();
        btVector3 pos = worldTrans.getOrigin();

        m_srtTransform->m_qRotate = CQuaternion(rot.x(), rot.y(), rot.z(), rot.w());
        m_srtTransform->SetPosition(CVector(pos.x(), pos.y(), pos.z()));
        m_btPos1 = worldTrans;
    }
};

```

I add a rigid body for the camera:

```
// Create rigid body for camera
btCollisionShape* cameraShape = new btSphereShape(btScalar(5.0f));
btTransform startTransform;
startTransform.setIdentity(); // forgot to add this line
CVector vCamera = m_srtCamera.GetPosition();
startTransform.setOrigin(btVector3(vCamera.x, vCamera.y, vCamera.z));
m_msCamera = new CPhysicsMotionState(startTransform, &m_srtCamera);
btScalar tMass(80.7f);
bool isDynamic = (tMass != 0.f);
btVector3 localInertia(0,0,0);
if (isDynamic)
    cameraShape->calculateLocalInertia(tMass,localInertia);
btRigidBody::btRigidBodyConstructionInfo rbInfo(tMass, m_msCamera, cameraShape, localInertia);
m_rigidBody = new btRigidBody(rbInfo);
m_rigidBody->setCollisionFlags(m_rigidBody->getCollisionFlags() |
    btCollisionObject::CF_KINEMATIC_OBJECT);
m_rigidBody->setActivationState(DISABLE_DEACTIVATION);

```

This is the code in Update() that runs each frame:

```
CSRTTransform srtCamera = CCameraTask::GetPtr()->GetCamera();
Quaternion qRotate = srtCamera.m_qRotate;
btQuaternion rot = btQuaternion(qRotate.x, qRotate.y, qRotate.z, qRotate.w);
CVector vCamera = CCameraTask::GetPtr()->GetPosition();
btVector3 pos = btVector3(vCamera.x, vCamera.y, vCamera.z);
CPhysicsMotionState* cameraMotionState = CCameraTask::GetPtr()->GetMotionState();
cameraMotionState->setKinematicPos(rot, pos);

```

# Answer
> 1 votes
I would try this first.. You might be having trouble getting your projection and view into your class...

1. Try running your code in the same program where your camera World, View, and Projection settings are located.
2. Set your matrices to Matrix.Identity before you use them.

---
Tags: opengl, bullet-physics
---


# Question
Title: What is the difference between DXGI_SWAP_EFFECT_DISCARD and DXGI_SWAP_EFFECT_SEQUENTIAL?
I have difficulty understanding the difference between those two values of the DXGI\_SWAP\_EFFECT enumeration. MSDN documentation states:

> **DXGI\_SWAP\_EFFECT\_DISCARD**
>
> Use this flag to specify the bit-block transfer (bitblt) model and to specify that DXGI discard the contents of the back buffer after you call `IDXGISwapChain1::Present1`. This flag is valid for a swap chain with more than one back buffer, although, applications only have read and write access to buffer 0. Use this flag to enable the display driver to select the most efficient presentation technique for the swap chain.
>
> **DXGI\_SWAP\_EFFECT\_SEQUENTIAL**
>
> Use this flag to specify the bitblt model and to specify that DXGI persist the contents of the back buffer after you call `IDXGISwapChain1::Present1`. Use this option to present the contents of the swap chain in order, from the first buffer (buffer 0) to the last buffer. This flag cannot be used with multisampling.

So, `Sequential` is for displaying the contents of the chain "in order", in other words, in the same order as you called `Present()`. If so, is `Discard` not in order? Obviously an older picture should never be shown before a newer one. What kind of "most efficient presentation technique" would this flag enable then?

What if your monitor's refresh rate is 60fps and your code is able to render at 90fps. In this case, every one out of two `Present`s, the queue will be full. What happens then? Does `Present` block until the next vsync, capping your rendering rate to 60fps and introducing input lag, or does it discard the oldest buffer in the queue with the new one and allows you to go on with your rendering code as fast as you can? Do these `DXGI_SWAP_EFFECT` flags have any bearing on the issue?

Thanks.

# Answer
> 4 votes
Both techniques will always render frames in the correct order. The key difference is that once you have Present()ed enough frames to get back to a buffer you've already rendered, \_SEQUENTIAL will guarantee that the contents are the same as what you presented. With \_DISCARD, however, it could be garbage.

This relates to the larger "discard" semantics of modifiable surfaces in D3D. As an example, on some hardware architectures, rendering is done in "tile" chunks, with a lot of the intermediate color data stored in a cache. When a new frame is rendered, if the hardware needs to guarantee correctness for incremental rendering (i.e. \_SEQUENTIAL), it has to flush this cache to main memory after the Present() call. If \_DISCARD is used, however, this flush can be omitted, but main memory will not be updated with the cached values (they are discarded). If you are always re-rendering the entire scene every frame, this won't be a problem.

---
Tags: directx
---


# Question
Title: Size of an image imported with FreeImage
I'm having abit of a brainfart and I can't quite grasp what I'm doing wrong. It's quite simple, I am importing an image with FreeImage (http://freeimage.sourceforge.net/) which has a method `FreeImage_GetBits` that returns a pointer to the first byte of the image data. I then try to load all the data into memory using (bitsperpixel / 8) * pixelsWidth ' pixelHeight, like this:

```
uint32_t bitsPerPixel           = FreeImage_GetBPP(bitmap);   // resolves to 24
uint32_t widthInPixels          = FreeImage_GetWidth(bitmap);  // resolves to 1024
uint32_t heightInPixels         = FreeImage_GetHeight(bitmap);  // resolves to 1024

// container is a std::vector<uint8_t>
pkgMaterial.mTextureData.insert(pkgMaterial.mTextureData.begin(), FreeImage_GetBits(bitmap), FreeImage_GetBits(bitmap) + ((bitsPerPixel/8) * widthInPixels * heightInPixels));

```

I have a jpg which is 31 kilobytes in size on disc. Yet when I load it using the above formula, I see the vector is then filled with 3145728 bytes, which is approx 3145 kilobytes. What am I doing wrong?

# Answer
You are doing nothing wrong.
FreeImage simply decompresses the image, so you can easily read from it and/or modify it.
You cannot render an image or read any pixel values from it without decompressing it first.
And obviously the memory consumption increases if you decompress the image.

You can try to compare the file size of a BMP image before and after loading it. It should roughly be the same, because BMP images are not compressed.
> 1 votes

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


title: Modify game using external file

text:
# Question
Title: Modify game using external file
In Flash, for example, I can place an **xml** file along with the **binary**, then if I modify some variable the game will change for everyone.

How to achieve something like that in **Android**? I know that for every change I make to the game, the player would need to download a new update.

But the main goal I'm looking for, is modifying a game stats **without** the need for recompile the **entire** APK.

I'm working with **Haxe+OpenFL**.

# Answer
> 1 votes
You can either store the settings in a database connected to your application or save them on the SD card.

The integrated databases are assigned to a certain application and only this application cann access them. So you can save them there even though only the application can change them.

The other way would be to use the SD card (or other external memory) and save them there. Access to the SD card is possible for each application so anyone could change the settings then.

To create or change the settings create a service in your application that queries this settings from an external server.

# Answer
> 0 votes
You can use a SQLite database, but it has to be on your SD card or on your device. Here is the reference for SQLite on Android: http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#openDatabase

However you may be able to download the file to your SD card, check out this URL where someone downloaded an image to their SD card: https://stackoverflow.com/questions/3296850/how-do-i-transfer-an-image-from-its-url-to-the-sd-card

# Answer
> 0 votes
I'm loading a local file from SD card (Android 4.3) like that:

```
// loading local file
#if android
loadTextFromURL( "/sdcard/PROjekty/testHaxe.txt" );
#end
#if flash
loadTextFromURL( "file:///C:/O/PROjekty/testHaxe.txt" );
#end
#if windows
loadTextFromURL( "C:/O/PROjekty/testHaxe.txt" );
#end
...

// loading file over http
loadTextFromURL( "http://oskarswierad.com/temp/testHaxe.txt" );
...

public function loadTextFromURL( address:String ):Void {
    var newLoader:URLLoader = new URLLoader();
    newLoader.dataFormat = URLLoaderDataFormat.TEXT;
    newLoader.addEventListener( Event.COMPLETE , textLoaded );

    newLoader.load( new URLRequest( address ) );
}
...

public function textLoaded( evt:Event ):Void {
    var text:String = cast(evt.target, URLLoader).data;

    trace( text );

    evt.target.removeEventListener( Event.COMPLETE , textLoaded );
}

```

You'll need to find out how to get path to SD card dynamically. I mean on every device model or system version the path can be different.

---
Tags: android, mobile, configuration, flash-develop, haxe
---


# Question
Title: What's the simplest way to determine the size of an empty space between rectangles?
I'm working on a dungeon generator and I'd like to be able to connect rooms through other rooms. What I currently have set up is two dictionaries and a map (an int array.) The first dictionary holds room templates separated by height, width and type (so: `Dictionary<string, Dictionary<int, Dictionary<int, List<Room>>>`.) The other dictionary holds rooms that have already been added to the map and uses rectangles as keys. I'd like to be able to find the maximum rectangular area that could fit into an empty space, then select a template room accordingly.

So what would be the simplest way for me to do that?

**Edit:**

Admittedly, I was a little vague before so here's a little more information.

My current method for creating the map follows certain steps:

1. Load in room templates from an xml file.
2. Create the start room in the middle of the map using a start room template with a random size.

```
Point mid = new Point(MapWidth / 2, MapHeight / 2);

int height = roomTemplates["Start"].ElementAt(random.Next(roomTemplates["Start"].Count)).Key;

int width = roomTemplates["Start"][height].ElementAt(random.Next(roomTemplates["Start"][height].Count)).Key;

int index = random.Next(roomTemplates["Start"][height][width].Count);

Room r = roomTemplates["Start"][height][width][index];

    for (int x = r.RoomSize.X; x <= r.RoomSize.Width; x++)
        for (int y = r.RoomSize.Y; y <= r.RoomSize.Height; y++)
        {
            Global.map.Map[x + (mid.X - r.Center.X), y + (mid.Y - r.Center.Y)] = r.Grid[x, y];
        }
    roomList.Add(new Rectangle(mid.X - r.Center.X, mid.Y - r.Center.Y, r.RoomSize.Width, r.RoomSize.Height), r);
    foreach(Door door in r.Doors)
    {
        doorTemporary.Add(new Point((mid.X - r.Center.X) + door.Location.X, (mid.Y - r.Center.Y) + door.Location.Y), new Door(doorMap, new Point((mid.X - r.Center.X) + door.Location.X, (mid.Y - r.Center.Y) + door.Location.Y), door.Facing));
    }

    List<Point> points = new List<Point>();
    points.Add(start);

```
3. Using a similar method as before, create rooms necessary to the game (shrines, barracks, treasure rooms, etc.) and place them randomly throughout the map, checking if they collide and moving them accordingly.

```
    Point u = new Point(-1, -1);
    Restart:
    while (points.Contains(u) || u.X == -1 || Global.map.Map[u.X, u.Y] != 0)
        u = new Point(random.Next(1 + r.Center.X, (Width - r.RoomSize.Width) - 1), random.Next(1 + r.Center.Y, (Height - r.RoomSize.Height) - 1));

    var eo = roomList.Where(n => n.Key.Intersects(new Rectangle(u.X - r.Center.X, u.Y - r.Center.Y, r.RoomSize.Width, r.RoomSize.Height))).Select(n => n.Key);

    if (eo.Count() > 1)
        goto Restart;
    if (eo.Count() == 1)
    {
        foreach (var ei in eo)
        {
            Rectangle ri = new Rectangle(u.X - r.Center.X, u.Y - r.Center.Y, r.RoomSize.Width, r.RoomSize.Height);
            Rectangle intersection = Rectangle.Intersect(ri, ei);

            if (intersection.X < intersection.Y)
                if (ri.X == intersection.X)
                    u.X += intersection.Width;
                else
                    u.X -= intersection.Width;
            else
                if (ri.Y == intersection.Y)
                    u.Y += intersection.Height;
                else
                    u.Y -= intersection.Height;
        }
    }

    Rectangle ro = new Rectangle(u.X - r.Center.X, u.Y - r.Center.Y, r.RoomSize.Width, r.RoomSize.Height);
    if (ro.X < 1 || ro.X + ro.Width > MapWidth - 1 || ro.Y < 1 || ro.Y + ro.Height > MapHeight - 1)
        goto Restart;

```
4. Create paths to the rooms using triangulation, a minimal spanning tree algorithm and A\* pathfinding.
5. (And this is where my question comes into play) use the paths generated before as guides and connect the already existing rooms together using rooms from roomTemplates. In order to do that, I need to know how much space I have available before selecting a room template.

What I've generated already looks like this:

Blue is walls, white is floors, orange is doors and green is the designated "center" of that room (usually used only for A\* pathfinding.)

I kind of already had an idea of how I could find the available space, but decided to ask because I wanted to know if there was an simpler way of doing it.

# Answer
I would go with a simple iterative approach. Assuming coordinate (0,0) is top left corner.

* Check if (x,y) is 'in' existing rectangle Google
* Increment 'x' until (x,y) is not in an existing rect **or** out of bounds(oob)
* Record the position(we'll call it *Point1*) of the first 'miss' (point not in rect) as the **top left** of the new rect
* Continue incrementing 'x' until you 'hit' another rect **or** oob
* Record that point as the **top right** of the new rect (*Point2*)
* Now increment 'y' and repeat the process (You can start from x = *Point1*.x)

Now depending on how your map is 'allowed' to be laid out, there are ways to optimize, and also pitfalls to watch out for. But for the most part, once you have the top left and right corners, its just a matter of checking that 'misses' are greater than *Point1*.x and less than *Point2*.x and incrementing y until it hits the bottom left corner of empty space.
> 2 votes

---
Tags: c#, maps, procedural-generation
---


# Question
Title: What's the most memory efficient way to load a tiled map?
Currently I am working on a simple 2D platformer and I want to load a tiled map.

What I've started working on is loading the tiles using a text file. My first question is simple: is a text file the best way to load a map, and in what cases would different types of files be preferred?

I'm reading the file using a buffered reader. First of all I'm getting it to check the size of the map, then I'm using a second loop to create a byte array of that size. This is my code:

```
    try {
        BufferedReader findSize = new BufferedReader(new FileReader(filePath));
        String line;
        while ((line = findSize.readLine()) != null) {
            if(!line.startsWith("#")) {
                String[] values = line.split("\\s");
                if(values.length > rowSize)
                    rowSize = values.length;
                columnSize++;
            }
        }
        grid = new short[rowSize][columnSize];
        findSize.close();
    } catch(Exception e) {
        e.getMessage();
    }

    BufferedReader readTiles;
    try {
        readTiles = new BufferedReader(new FileReader(filePath));
        String line;
        short rowNum = -1;
        while ((line = readTiles.readLine()) != null) {
            if(!line.startsWith("#")) {
                rowNum++;
                String[] values = line.split("\\s");
                short y = 0;
                for(String v : values) {
                    grid[y][rowNum] = Byte.parseByte(v);
                    y++;
                }
            }
        }
        readTiles.close();
        initializeMap();
    } catch (Exception e) {
        e.getMessage();
    }

```

My second question is to ask whether this is the best way to do it. I've done some research and found that BufferedReader is faster than using the scanner, but I'm not exactly sure how I could shorten my code, and if it would be possible to create the array while checking its size. One way I've thought about doing it is through a list, but I'm not sure if this would be more efficient or even possible.

My third question concerns displaying the map. What would be the best way to do this? Should I create an array of BufferedImages and then assign each number in the current array to an index in that array?

# Answer
The "best" (for certain definitions of "best") way is to store it on disk in a binary format that *exactly* matches the in-memory format you're going to use; all that you need to do is open the file and read it directly in. Optionally, a file header can be used for storing information about sizes/etc that can allow you to set up memory buffers in advance. If using e.g VBOs in OpenGL you can memory-map the file and send your current pointer straight into a glBufferData call without even needing to read it into intermediate storage.

There are a number of things *severely* wrong with your current approach. The first big one is that you need to do two passes over the file; the first to determine sizes and set up storage, the second to actually read things in. You're also doing a lot of string parsing and splitting, which are slow operations (and in the case of splitting involve a lot of temporary short-lived allocations).

"Memory-efficiency" doesn't have much to do with any of this; you're doing slow and error-prone loading to begin with, particularly with those two passes where you've got to ensure that you read consistently in both; the potential for introducing bugs is just enormous here. Just think of what would happen if you needed to change the file format to introduce a new feature - you're giving yourself *two* parsers that you have to modify to support the new format.

If you need to (or prefer to) use a human-readable format, then convert it to binary as a pre-processing step, and actually load the binary version in your game. That way at least you're moving the slow and potentially buggy work out of the game itself.
> 2 votes

---
Tags: java, 2d, tilemap, platformer, loading
---


title: Memory Leak in SharpDX

text:
# Question
Title: Memory Leak in SharpDX
one Thing I found out: Windows 7 produces a memory leak while using certain methods to access rendertargets. Why doesn't Windows 8 leak at this method?

```
public class Game : SharpDX.Toolkit.Game {
    GraphicsDeviceManager gdm;
    RenderTarget2D target;
    public Game() {
        gdm = new GraphicsDeviceManager(this);
    }
    protected override void LoadContent() {
        target = RenderTarget2D.New(GraphicsDevice, 1000, 1000, PixelFormat.R8G8B8A8.UNorm);
        base.LoadContent();
    }
    private Color GetColor(int x, int y) {
        using (Image image = target.GetDataAsImage()) {
            PixelBuffer buffer = image.PixelBuffer[0];
            Color color = buffer.GetPixel<Color>(x, y);
            buffer = null;
            return color;
        }
    }
    protected override void Update(GameTime gameTime) {
        GetColor(5, 5);
        base.Update(gameTime);
    }
}

```

The memory consumption with this on Windows 8 is around 25 MB, Windows 7 uses up full memory. Any idea why Windows 8 handles memory/graphics in another way than Windows 7 (and how to fix it)?
For clarification if it was a memory leak:
The drop is caused by closing the application.

# Answer
> 7 votes
There are 2 issues in your synthetic sample:

* The first issue is that you are calling `target.GetDataAsImage` which is unoptimized in scenarios where you need to do it each frame. Internally the GetDataAsImage is creating a CPU/GPU staging resource (same size as the render target) and allocating an Image on the CPU (again same size on the render target). A correct way to do it (see samples below) is to pre-allocate yourself the staging resource and the image just once, and then get the data from the render target to the image through this allocated staging resource.
* The second issue is that you don't make any draw calls. The flush of the graphics device is usually automatically done if you are making many consecutive draw calls (to split the GPU command buffer) or at least one draw call in a frame before a swap chain present (then the flush will be done at present time). Usually, during a flush, Direct3D takes the time to cleanup things that it can cleanup (like allocated staging resources). That's why by adding an explicit flush (and because of no draw calls), you are able to let D3D freeing some resources. I don't have Windows 7, but I would believe that It would fix your issue.

Minor issue: don't perform any GPU interaction in the update method but only in Draw (in fixed time step, this method can be called several times per frame).

The correct way to implement the micro-synthetic test is to do it like this:

```
// TestLeak.cs
using System.Diagnostics;
using SharpDX;
using SharpDX.Toolkit;
using SharpDX.Toolkit.Graphics;

public class TestLeak : Game
{
    private GraphicsDeviceManager graphicsDeviceManager;
    RenderTarget2D target;
    private Texture targetStaging;
    private Image image;

    public TestLeak()
    {
        graphicsDeviceManager = new GraphicsDeviceManager(this);
    }

    protected override void LoadContent()
    {
        target = RenderTarget2D.New(GraphicsDevice, 1000, 1000, PixelFormat.R8G8B8A8.UNorm);

        // Pre-Allocate an image same size as the render target
        image = Image.New(target.Description);

        // Pre-Allocate a staging resource for the render target
        targetStaging = target.ToStaging();

        base.LoadContent();
    }

    private Color GetColor(int x, int y)
    {
        // Get the data from the RenderTarget using the allocated staging resource and the
        // allocated image
        target.GetData(targetStaging, new DataPointer(image.DataPointer, image.TotalSizeInBytes));

        var buffer = image.PixelBuffer[0];
        var color = buffer.GetPixel<Color>(x, y);
        return color;
    }

    protected override void Draw(GameTime gameTime)
    {
        // Just clear the target with red
        GraphicsDevice.Clear(target, Color.Red);

        // Check the color
        var color = GetColor(5, 5);
        Debug.Assert(color == Color.Red);

        base.Draw(gameTime);
    }
}

```

# Answer
> 1 votes
Oh wow -.-
Someone on private IRC reminded me to use `GraphicsDevice.Flush()`.
Who knows the answer? Correct, it's "working". Well .. at least there is no memory leak. Although memory consumption is twice of Windows 8. (Windows 8 ~20 MB, Windows 7 starting at 80 MB falling to 45 MB)

For everyone who has this problem with `SharpDX.Toolkit` I suggest overriding `Game.EndDraw`.

```
protected override void EndDraw() {
    base.EndDraw();
    GraphicsDevice.Flush();
}

```

That will sort of fix the issue of memory leaks.

---
Tags: sharpdx, memory
---


# Question
Title: Splitting a large number of FLAs into multiple gifs
I currently have a large number (300 or so) FLAs that I wish to convert to GIFs for a HTML5 game I'm creating.

Each one of these FLAs contains multiple animations in the timeline, and they all have the same basic structure (Animation one in frames 1-25, animation 2 in frames 26-34, etc.)

Is there a way I could automate splitting them up and converting them into the GIFs?

I am on a Mac, but do have access to a Windows machine, so any solution will work, basically. I don't have the Windows version of Flash though, so that is annoying.

Thanks in advance, and if this the wrong StackExchange to ask in, then I apologise in advance.

# Answer
There are a number of swf-to-png-sequence tools out there you might want to try. For example, Zoe from CreateJS is used for this purpose and may give good results for the specific way you've organized your animations.

(incidentally, you don't have to use CreateJS in order to use Zoe, although if you're making an HTML5 game you might consider it)
> 1 votes

# Answer
You should look into JSFL. It's a scripting language that you can use to interact with flas.

JSFL Reference

There's a lot you can do with it, and your problem sounds exactly like something it could solve.

```
var timeline = doc.getTimeline(); // Timeline

for (var i=0; i < timeline.layerCount; i++)
{
    timeline.layers[i].locked = true;
}

```

This example locks all layers in your FLA. But there's much more you can do.

Pro Tip: In Flash (I'm using CS5), open the History window. (Window -\> Other Panels -\> History). All of your actions using the Flash editor, will be reported back to you in usable JSFL. You can use this to do one test case of your FLA, and then extend the script to do multiple FLAs.

Hope this helps.
> 0 votes

# Answer
IIRC Creative Suite has an "export to QuickTime" button.

Once you have a .mov file, you can use ffmpeg (available with brew or ports) to convert it to png frames or jpg frames. (ffmpeg can convert straight to gif, but is not a very good quality gif encoder).

Once you have a series of png or jpg images, you can use imagemagick to create optimised gifs from them.
> 0 votes

---
Tags: flash, macos
---


# Question
Title: A* algorithm: is the heuristic h an input?
We have a formula of `f=g+h` wherein `g` is the *path cost* and `h` is *the distance* left to the goal.

Given that I only want to move my unit in 4 direction (N,S,E,W), my question is:

Can we consider `h` as an input? Because we will choose what heuristic to use? Or not because its value is given automatically?

# Answer
Firstly I would suggest looking at some general A\* information and A\* tutorials, e.g.:
http://en.wikipedia.org/wiki/A\*\_search\_algorithm
https://web.archive.org/web/20171022224528/http://www.policyalmanac.org:80/games/aStarTutorial.htm

Secondly, the h function needs to be some sort of heuristic guess on the remaining distance, for example the Euclidean distance or Manhattan distance. The more accurate the heuristic is, the faster A\* will find the optimal solution. However take care not to choose a heuristic that overestimates the remaining distance. This is called an inadmissable heuristic, and is not guaranteed to find the optimal solution. More advanced A\* users may intentionally choose an inadmissable heuristic for speed purposes or because the resulting path looks nicer, but leave that until you have a basic implementation working. If you're only moving in 4 directions, the Manhattan distance is a good heuristic.
> 6 votes

---
Tags: algorithm, path-finding
---


title: Correct rotation with Quaternion

text:
# Question
Title: Correct rotation with Quaternion
I have some problems with a rotating marble.
I've tried it with `Matrix.CreateFromYawPitchRoll` and `Matrix.CreateRotation` but there were some problems, I think it's due to the *Gimbal lock* effect.

So, I've tried using **quaternions** instead, but nothing changed.
When moving on only an axis it works fine, but when the rotation occurs on two different axes the marble still rotates on wrong axes.

Here's my code:

```
// declarations
Vector3 Position = Vector3.Zero;
Vector3 Rotation = Vector3.Zero;
Quaternion qRotation = Quaternion.Identity;

AbsoluteBoneTransforms = new Matrix[Model.Bones.Count];
            Model.CopyAbsoluteBoneTransformsTo(AbsoluteBoneTransforms);

```

In the `Update` method:

```
Position += speed;
Rotation = speed * MathHelper.ToRadians(-1.5f);

Quaternion rot = Quaternion.CreateFromAxisAngle(Vector3.Right, Rotation.Z) *
                Quaternion.CreateFromAxisAngle(Vector3.Backward, Rotation.X);

qRotation *= rot;

```

And in the `Draw` method:

```
effect.World = AbsoluteBoneTransforms[mesh.ParentBone.Index] *
  Matrix.CreateFromQuaternion(qRotation) * Matrix.CreateTranslation(Position);

```

What's wrong?

**EDIT**

I've tried calculating directly the axis of rotation of my marble, instead of using combination of multiple axes:

```
angle += speed.Length() * angularVelocity;
qRotation = Quaternion.CreateFromAxisAngle(Vector3.Cross(speed, Vector3.Up), angle);
qRotation.Normalize();

```

`angle` is a float that keeps track of the current movement. This solution doesn't seem to create *Gimbal lock*, but marble rotations aren't correct, it seems that the rotating speed is not constant, but became faster and slower over time, I can't understand why.

# Answer
> 1 votes
Although I don't know any XNA, this might help you "cheat" your way into achieving that rolling effect of the marble:

```
Position += speed;

angle = Magnitude(speed) * MathHelper.ToRadians(-1.5f);

Quaternion rot = Quaternion.CreateFromAxisAngle(Vector3.Cross(speed, Vector3.UP), angle);

qRotation *= rot;

```

So, instead of multiplying quaternions and achieving a chaotic wobbly effect, you should only update the angular position and use that to achieve the rolling effect.

**Later edit**:

What happens when your sphere moves from position *A* to position *B*:

* the speed is used to translate it (you should consider adding a *deltaTime* to make it more FPS independent)
* you know how much the ball moves: |AB| = |speed| (for your particular case) so you can determine how much it has rolled/rotated around the `cross(speed, up)` vector/axis. This amount is the angle `|AB|/(2*pi*radius)` \- you should incorporate the marble radius to achieve believable roll with no sliding/slippage
* lastly, `qRotation` is updated to reflect the sphere's current rotation w.r.t. to its starting pose

Of course, the correct way to achieve rolling behaviour from a physically accurate POV is to use the inertia tensor.

I implemented a short OpenGL demo using the following snippet to update the rolling sphere (and it worked):

```
  double radius = 0.1;
  static Quaternion qRot = identityq<double>();
  static double dTime = 0.002;

  Position += Velocity * dTime;
  double angle = length(Velocity) / radius * dTime;
  Vector3 axis = cross(Vector3(0,0,1), Velocity);
  normalize(axis);

  qRot = quat_from_axis_angle<double>(axis, angle) * qRot;

```

---
Tags: xna, c#, 3d, rotation, quaternion
---


title: Which .jar has JBox2d's p5 package?

text:
# Question
Title: Which .jar has JBox2d's p5 package?
Using Eclipse, I'm trying to write a simple hello world program in processing that simply draws a rectangle on the screen then has gravity drop it as seen in this tutorial.

The problem is that when I try to import the p5 package, it's not resolving so I can't declare my physics object. I tried two things.

1. Download the zip, unzip it, then import the 3 jars (library, serialization, & testbed)

a. import org.jbox2d.p5.\*; doesn't resolve but the others do

b. Physics physics; doesn't resolve
2. Download the older standalone testbed jar then import it

a. Physics physics; doesn't resolve;

Here is basically where I'm starting

```
import org.jbox2d.util.nonconvex.*;
import org.jbox2d.dynamics.contacts.*;
import org.jbox2d.testbed.*;
import org.jbox2d.collision.*;
import org.jbox2d.common.*;
import org.jbox2d.dynamics.joints.*;
import org.jbox2d.p5.*;
import org.jbox2d.dynamics.*;

import processing.core.PApplet;

public class MyFirstJBox2d extends PApplet  {

    Physics physics;

    public void setup() {
      size(640,480);
      frameRate(60);
      initScene();
    }

    public void draw() {
      background(0);

      if (keyPressed) {
        //Reset everything
        physics.destroy();
        initScene();
      }

    }

    public void initScene() {
      physics = new Physics(this, width, height);
      physics.setDensity(1.0f);
      physics.createRect(300,200,340,300);
    }
}

```

# Answer
> 1 votes
The "Physics" and p5 package/class was an extension to the jbox2d framework the guy wrote. It seemed pretty nice but not ideal for what I'm doing. I ended up doing this:

```
import org.jbox2d.common.*;
import org.jbox2d.dynamics.*;
import org.jbox2d.collision.shapes.PolygonShape;
import processing.core.PApplet;

public class MyJBoxTest extends PApplet {

    private Vec2 gravity = new Vec2(0, -10f);;
    private World world;
    private Body floor;
    private Body player;
    private float fieldBottom = 300;
    private float timeStep = 1.0f / 60.f;
    private int velocityIterations = 6;
    private int positionIterations = 2;

    public void setup() {
        size(300, (int)fieldBottom);
        frameRate(60);
        background (0);
        world = new World(gravity);
        gameInit();
        //simulateWorld();
    }

    public void gameInit() {
        //Create Floor
        BodyDef aboutFloor = new BodyDef();
        aboutFloor.position.set(0.0f, -8.0f); //-8 instead of -10 so I can see it
        PolygonShape groundBox = new PolygonShape();
        groundBox.setAsBox(50.0f, 10.0f); // top lands at 0 aka floor

        floor = world.createBody(aboutFloor);
        floor.createFixture(groundBox, 0.0f);

        //Create Player
        BodyDef aboutPlayer = new BodyDef();
        aboutPlayer.type = BodyType.DYNAMIC; //movable
        aboutPlayer.position.set(0.0f, 200.0f);
        PolygonShape playerBox = new PolygonShape();
        playerBox.setAsBox(10.0f, 10.0f);
        FixtureDef fixtureDef = new FixtureDef();
        fixtureDef.shape = playerBox;
        fixtureDef.density = 1.0f;
        fixtureDef.friction = 0.3f;

        player = world.createBody(aboutPlayer);
        player.createFixture(fixtureDef);
    }

    public void draw() {
        Vec2 floorLoc = floor.getPosition();
        Vec2 playerLoc = player.getPosition();

        background(0);

        rectMode(RADIUS);
        fill(255,0,0);
        rect(floorLoc.x, fieldBottom - floorLoc.y, 50, 10);

        rectMode(RADIUS);
        fill(255,100);
        rect (playerLoc.x, fieldBottom - playerLoc.y, 10, 10);

        world.step(timeStep, velocityIterations, positionIterations);
    }

}

```

---
Tags: java, jbox2d
---


# Question
Title: Multiple render targets: Output target format performance questions
This is probably API independent (more dependent on hardware implementation), but just in case, I'm using OpenGL.

The question is restricted to PC hardware.

I have a couple of questions concerning the output textures that are being rendered to (e.g. in gbuffer geometry pass)

* Is there a (noticeable, measurable) performance penalty of using different formats for the different output textures? e.g. RGB8 (unsigned byte) (8 bits for each component) for diffuse color, RGBA8 (unsigned byte) for specular color + roughness, RGB16F for normals?
* Is it worth it to pack smaller component data into larger types just so I can have equal render targets (and fewer of them in number)? E.g. just having two RGBA16F render targets, packing diffuse + specular + roughness into the first, and normals and other stuff into the second render target using bitmasking?
* Are there output texture data types/formats that I should avoid entirely?

# Answer
It's going to depend on the hardware and app, of course, but on current generation GPUs (NVIDIA Kepler, AMD GCN), I believe there is no penalty for using different render target formats at once. On older GPUs you simply couldn't do it; all render targets had to be the same format.

Writing out to multiple render targets is usually memory-bound, so you can expect performance to scale based on the total number of bytes per pixel. In other words, thinner formats are better. This also applies to reading the data back in for subsequent passes: thinner formats take less memory bandwidth to read, and bilinear filtering might also be faster for thin formats.

However, the number of render targets also has an effect; 4xRGBA8 will likely be slower than 2xRGBA16F, even though they have the same memory size. This is due to cache effects as well as the shader needing a separate write instruction for each render target.
> 3 votes

---
Tags: performance, optimization, deferred-rendering
---


title: Where to save enemy positions in C++?

text:
# Question
Title: Where to save enemy positions in C++?
I'm wondering how and where to save the positions my enemies should spawn.

My idea was to use a struct such as:

```
struct enemy{
    int x,y,type;
}

```

And save an array of it in a .dat with `fwrite()` but I'm not sure if it's a good idea.

I want to know how it's commonly done. Also I recently asked a question about events and was answered something about scripting languages like Lua, is this related to the enemy positions too? Could I create a file in a scripting language with them?

# Answer
> 3 votes
> I'm not sure if it's a good idea.

This sounds like a perfectly good idea for a start. Apparently you plan on dumping directly your struct in binary data files: as Evan said, this is a commonly used approach. It's compact and efficient, but it has quite a few pitfalls:

* It's hard for a human being to read them.
* It's hard to find differences between versions of the same data file.
* It works for POD-types but will get you into trouble for anything more object-oriented.
* For multi-platform games, due to the variety of computer architectures out there (e.g. endianness), C++ offers you no warranty that data files will be compatible between platforms.
* And probably more.

Advanced game engines usually use binary data files only for the final game for performance reason, but use a more "human-friendly" text format for development. It's perfectly feasible to support both at the same time and switch between the two when required (do some research about *serialization* if you want to know more, e.g. see this question on GDSE).

> Also I recently made a question about events and was answered something about scripting languages like LUA, is this related to the enemy positions too? Could I create a file in a scripting language with them?

Yes. You can use a scripting language to define this type of data. I've seen a few engines doing that and it works quite well. Another approach is to use a static, data-only text format (.ini, XML, JSON, something custom...) and write or reuse a parser for it.

---
Tags: c++, architecture, serialization
---