# Question
Title: Huge procedurally generated 'wilderness' worlds
I'm sure you all know of games like Dwarf Fortress - massive, procedural generated wilderness and land. Something like this, taken from this very useful article.

However, I was wondering how I could apply this to a much larger scale; the scale of Minecraft comes to mind (isn't that something like 8x the size of the Earth's surface?). Pseudo-infinite, I think the best term would be.

The article talks about fractal perlin noise. I am no way an expert on it, but I get the general idea (it's some kind of randomly generated noise which is semi-coherent, so not just random pixel values).

I could just define regions X by X in size, add some region loading type stuff, and have one bit of noise generating a region. But this would result in just huge amounts of islands.

On the other extreme, I don't think I can really generate a supermassive sheet of perlin noise. And it would just be one big island, I think.

I am pretty sure Perlin noise, or some noise, would be the answer in some way. I mean, the map is really nice looking. And you could replace the ascii with tiles, and get something very nice looking.

# Answer
I think I better understand what you are asking now.

Noise is not random - it's random-looking but is completely based on a mathematical formula and is repeatable. All the information is encoded in the formula. This means that you can have a formula that potentially covers an infinite area, and just use the formula on the coordinates of the area you need. When you need an adjacent area, you just re-use the formula on the new coordinates, and since the formula yields continuous values, the areas will join seamlessly.

Here's a simplified example, using sine instead of perlin noise for the height generation, and imagining the world is infinite in the X axis but only 1 unit high in the Y and Z axes.

Formula is: `height(x,y) = sin(x/20)`

The game starts, and we generate heights for the nearby area, ie. (0,0) to (9,0):

`[0.0, 0.05, 0.10, 0.15, 0.20, 0.25, 0.30, 0.34, 0.39, 0.43]`

We have a hill, rising up towards the right. Let's say we walk to the end of it and need to generate the values from (10,0 to 19,0) now:

`[0.48, 0.52, 0.56, 0.61, 0.64, 0.68, 0.72, 0.75, 0.78, 0.81]`

Notice how the hill keeps rising steadily, and that the value at (10,0) follows on nicely from the one at (9,0). This is because the sine function is continuous, which basically means that if you feed it 2 adjacent numbers in, you'll get 2 adjacent results out - for a certain definition of adjacent. So if you use your world coordinates as the parameters to the function that defines your world, you will get a continuous landscape that fits together no matter how much or little of it you generate at once. When you generate new parts, they will flow on from the existing parts automatically, because the heights are already pre-determined.

If the world isn't going to change, you don't even need to store anything, since you can calculate exactly what the height is at any given point from the formula. Obviously with something like Minecraft the world is totally deformable so you just save each chunk as you create it. Given that there is a high degree of coherence between adjacent chunks (ie. if 1 block is grass, it's more likely than not that the block next to it will be grass too) you can compress the data very efficiently - run length encoding would work well, but then so would almost any standard compression algorithm.

Whereas I have talked about height as the most obvious value, you can use the same system to generate any characteristic you want. Use a mathematical function with continuous properties and where the inputs are your world coordinates and that can decide the presence of landmarks, mineral deposits, spawn points, whatever you like. (Obviously the values in one formula may affect another - no point placing a coal deposit in mid-air, so you generate the world height map and then only calculate coal possibilities for the blocks that are far enough below ground.)
> 39 votes

# Answer
This tutorial I wrote years ago might give you something like what you want:

If you do the island modification in the last step, it tends towards a single landmass that doesn't reach the edge of the map.
> 32 votes

# Answer
To create a large island you do not need to generate it all at once. I would build regions asynchronously as you visit them.

Instead of using a mask to create the island as the article describes, one thing you can do is play with the perlin noise octave wavelengths to achieve the look you are going for. Usually, the first octave describes the general shape of the terrain. All octaves after it simply add more fine grain detail. Therefore, play with the wavelength of the first octave to control how large your landmasses will be. If you want the landmass to be in the center you can simply reduce the height map by an increasing amount as you move away from the center and then normalize the noise. For instance imagine combining these two to create your island:

This article should help: Perlin Noise.

If you want to learn about infinite 3D worlds and about various tricks you can use to change the appearance of the terrain through playing with the noise input and output, have a look at this article: Generating Complex Procedural Terrains Using the GPU.

It may be a little bit of a difficult read if you are not familiar with the graphics pipeline and shader programming.
> 15 votes

# Answer
Some useful links for you about auto world generation:

http://pcg.wikidot.com/ \- Procedural Content Generation

http://www-cs-students.stanford.edu/~amitp/gameprog.html#tiles \- Amit's Building Worlds set of algorithms
> 12 votes

# Answer
Perlin noise and friends are a good starting point but you probably want to take it a step further. Most of the popular noise-based generators will give you a fairly uninteresting results. In order to make terrain realistic, you want to take a look at the algorithms emulating erosion effects. One of the most advanced game-ish world simulators out there - Dwarf Fortress - does erosion simulation as one of the world-building steps.

One of the pretty cool solutions I've seen was described in the "Advanced Particle Deposition" article in the Game Programming Gems 7. There are many others available on the Internet so there's a lot of resources to draw from (e.g.  or ).
> 7 votes

---
Tags: procedural-generation, terrain, rpg, roguelikes
---


title: Shifting from XNA/C# to C++?

text:
# Question
Title: Shifting from XNA/C# to C++?
For a while now, I've been working with XNA for game design and development (although only for personal use ATM.) Overall, I'm a major fan of XNA itself, and it's overall "feel." However, due to the fact that:

1. XNA seems to have a lack of support (no Metro support, no updates since 2010, etc.)
2. I plan to try and get a job in the game development industry, and due to C++'s dominance, being more familiar with it would be very useful
3. XNA only supports Windows (non-Metro) and Xbox 360, while I am interested in Mac and (to a lesser extent) Linux support.

I've been trying to shift over to C++ as my main language. However, I do not want to focus on learning raw DirectX/C++ at this time, so I've been looking for a higher level C++ API (something about the same level as XNA, although something a bit more low-level would be fine) with a feel similar to XNA. So, for someone switching from C#/XNA to C++, what would my best choice(s) be for API's similar to XNA, although unmanaged and running on C++?

# Answer
First of all, if you want to stick with C#/XNA, and still support Mac/Linux, you could consider FNA or MonoGame.

If you want to enjoy some of XNA's nice helper classes (eg: `SpriteBatch`, `SpriteFont`), while moving over to DirectX/C++, you could try the DirectX Tool Kit or DirectX12 Tool Kit. And don't forget that much of the niceness of XNA is in its content pipeline - so DirectXTex might help. It's made by some of the same folks who made XNA, so you know it's good (blog post).

You could consider trying Unity \- which uses C#, supports Mac and Linux and a bunch of other platforms, and is used in "The Industry".

If you'd like Metro support, want to learn DirectX, but don't want to leave the comfort of C#, you could check out SharpDX.

Finally, you could look at Cocos2d-X, which seems to be quite popular and is probably the closest cross-platform C++ library to XNA that I can think of.
> 13 votes

# Answer
For the sake of completeness I want to mention SFML. Everybody using C++ should at least take a look at it as SFML is completely object oriented whereas SDL basically is C.
> 1 votes

# Answer
IMHO, these libraries are interesting for solving your migration especially if you want to program in C++:
> 0 votes

---
Tags: xna, c++
---


# Question
Title: Adjusting the rate of movement of different objects on the same timer
I have a series of objects moving along the straight lines. I want to implement slight changes of velocity of each of the object. Constraint is existing model of animation. I am new to this, and not sure if it is the best way to accommodate varying speeds, but what do I know?

It is a Java application that repaints the panel every time the timer expires. Timer is set via swing.Timer object that is set by timer delay constant. Every time the game is stepped objects’ coordinates advanced by an increment constant. Most of the objects are of the same class.

Is there fairly easy way to refactor existing system to allow changing velocity for an individual object? Is there some obvious common solution I am not aware about?

Idea I am having right now is to set timer delay fairly small, and only move objects every so many cycles of animation so that the apparent speed can be adjusted by varying how often they get moved. But that seems fairly involved, and I do not think it is the most elegant solution in terms of performance what with repainting the whole frame every 3-5 milliseconds.

Can it be done by advancing the objects so many (varying) times during the certain interval (let’s say 35ms for something like 28fps), and use repaint() method to redraw just individual object? Do I need to mess with pausing animation for smoothness at higher redraw rates? Is it common practise to check for collision at larger step interval, but draw animation a lot more frequently?

# Answer
This is fairly simple. Don't change how frequently you move the different objects to alter their apparent speed, change *how far* you move them on each update. All the objects should be moved/updated at the same time. The faster objects should be moved farther per update than their slower counterparts. You say changes in velocity, I assume you know what you're saying and you mean acceleration. (not the same as different velocities). That means that not only will these objects be moving different amounts per update, the amounts they move will also be changing. This is basic equations of motion stuff (or more geared towards game developers).

Now, if you want to also change the animation speed to match, this is also fairly simple. Take for example, walking animations. At their default speed, they will animate the character moving at a certain speed. This animation could be applied to the model by tracking the time spent on each frame and incrementing the frame count when the current frame is done. So it's easy to change the speed of the animation, by changing the amount of time to stay on each frame. So for example, an animation might be tracked very simply like so:

```
if(currentFrameTime > timePerFrame) {
    currentFrame++;
    currentFrameTime = 0;
}

```

We can add an animation speed into this equation simply by adding a division:

```
if(currentFrameTime > timePerFrame / animationSpeed) {
    currentFrame++;
    currentFrameTime = 0;
}

```

This makes it so an animation speed of `1` makes the animation behave just as before, where an animation speed of `2` will cut the time per frame in half, therefore doubling the speed of the animation.
> 1 votes

---
Tags: java, animation
---


# Question
Title: Artificial intelligence for targeting 3D flying objects
I'm working on a 3D game in Xna in which there is my jet which I am controlling. I want to add other jets as enemies. For that I need their AI so that I could have them able to target my jet. I've searched Google but couldn't find good resources. I hope professionals here can help me with my project.

# Answer
Likely the simplest way to achieve this is to give your enemy jets some steering behavior. Particularly the a pursuit steering algorithm, with some avoidance Autonomous and follow behaviors tied in. There's an excellent paper on Steering Behaviors For Autonomous Characters. With it you'll be able to glean the information needed to implement steering in your own game. I recommend starting with basic pursuit steering and evolving it from there. Using an offset pursuit algorithm will ensure you don't have enemy airplanes kamikaze-ing into you. Something like this:

Where your plane is the center of the white circle.

You can see a live example of a similar behavior here. Also giving a enemy jet the flee behavior when they're targeted will make it a little more challenging to hit. (Have them flee from the firing cylinder that represents the kill zone in front of your plane)
> 1 votes

---
Tags: xna-4.0, ai
---


# Question
Title: OpenGL : sluggish performance in extracting texture from GPU
I'm currently working on an algorithm which creates a texture within a render buffer. The operations are pretty complex, but for the GPU this is a simple task, done very quickly.

The problem is that, after creating the texture, i would like to save it. This requires to extract it from GPU memory.

For this operation, i'm using glGetTexImage(). It works, but the performance is sluggish. No, i mean even slower than that. For example, an 8MB texture (uncompressed) requires 3 seconds (yes, seconds) to be extracted. That's mind puzzling. I'm almost wondering if my graphic card is connected by a serial link...

Anyway, i've looked around, and found some people complaining about the same, but no working solution so far. The most promising advise was to "extract data in the native format of the GPU". Which i've tried and tried, but failed so far.

***Edit*** : by moving the call to glGetTexImage() in a different place, the speed has been a bit improved for the most dramatic samples : looking again at the 8MB texture, it knows requires 500ms, instead of 3sec. It's better, but still much too slow. Smaller texture sizes were not affected by the change (typical timing remained into the 60-80ms range).

Using glFinish() didn't help either. Note that, if i call glFinish() (without glGetTexImage), i'm getting a fixed 16ms result, whatever the texture size or complexity. It really looks like the timing for a frame at 60fps.

The timing is measured for the full rendering + saving sequence. The call to glGetTexImage() alone does not really matter. That being said, it is this call which changes the performance.

And yes, of course, as stated at the beginning, the texture is "created into the GPU", hence the need to save it.

***Edit 2*** : I've also tried to use glReadPixels(), instead of glGetTexImage(). But it's worse unfortunately. Approximately twice slower.

***Edit 3*** : Here is the code. Note that it uses a "framework" that i've not developed. So some of the function calls here are not OpenGL standard. But they are nonetheless quite self-expressive.

```
glDisable(GL_BLEND);

// Simple construction, for test : the resulting texture is output into render buffer
renderbufx1.bind();
    clear(0,0,0,0);
    simpleDiffShader.bind();
    simpleDiffShader.setTexture("TextureRef",img.tex,0);
    simpleDiffShader.setTexture("TextureDown",renderbufx2.getTexture(),1);
    img.tex->drawPart(-1,-1,2,2,0,0,1,1);
    simpleDiffShader.unbind();
renderbufx1.unbind();

// Not really useful, but just in case, the result is copied into another render buffer.
// renderbufx1 is going to be displayed, and i want to avoid any access conflict
savebufx1.bind();
    clear(0,0,0,0);
    renderbufx1.getTexture()->bind();
    renderbufx1.getTexture()->drawPart(-1,-1,2,2,0,0,1,1);
    renderbufx1.getTexture()->unbind();
savebufx1.unbind();

savebufx1.getTexture()->bind();
glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_BYTE, t.data);  // <-- This is the line
savebufx1.getTexture()->unbind();

glEnable (GL_BLEND);

renderbufx1.getTexture()->bind();
renderbufx1.getTexture()->drawPart(tex2x,-1,w,h,texSpan,texSpan,fact,fact);
renderbufx1.getTexture()->unbind();

```

Timing measured encompasses all this (and a few other things, which do not really contribute to the total).

***Edit 4*** : (on course for the most edited question of the week)

The native texture format of the GPU is supposed to be retrieved through the function glGetTexLevelParameter. More precisely, i've used this line of code :

```
glGetTexLevelParameteriv ( GL_TEXTURE_2D, 0, GL_TEXTURE_INTERNAL_FORMAT, &iTexFormat);

```

The result of the function (within iTexFormat) is **32856**. 32856, decimal, is 0x8058, and within gl.h there is :

```
#define GL_RGBA8 0x8058

```

# Answer
First of all, it's worth mentioning that you should ensure you have the most up-to-date video drivers for your GPU installed.

You *might* be able to get better performance by using a Pixel Buffer Object (PBO) to read back your render target. A PBO can be created with a hint to the driver to locate the buffer in main memory; the GPU then transfers the render target contents to the PBO. Strangely enough, on some (many?) systems it's faster for the GPU to write to main memory than for the CPU to read video memory.

Details can be found in the article linked above, as well as the ARB\_pixel\_buffer\_object extension spec, but in general, you'd do the following:

1. Create a PBO (as shown in the article) using the hint `GL_STREAM_READ`, which tells OpenGL you intend to use this PBO for reading back a render target to the CPU.
2. Bind it for "pack" and then do your `glGetTexImage()` call, which will copy the contents of the render target into the PBO.
3. Call `glMapBuffer()` to get access to the PBO memory.

Note also that with PBOs the `glGetTexImage()` call is asynchronous. That is, you can do additional work on the CPU or GPU between steps 2 and 3, while the memory transfer runs in the background. When you call `glMapBuffer()` it will wait for the transfer to finish, if it's not already done.

However, all this being done, you may or may not see a performance improvement. This is all down to the driver and how it decides to allocate memory, schedule work, etc. Unfortunately, working on a PC you don't have much control over this stuff.
> 7 votes

# Answer
```
glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_BYTE, t.data);

```

This reads the image data back as a series of *signed bytes*. So unless your image is using the `GL_RGBA8_SNORM` internal format, this is going to require CPU conversion. And you don't want that.

You should be reading it back as `GL_UNSIGNED_BYTE` if your image format is `GL_RGBA8`. Also, try changing the pixel transfer format to `GL_BGRA` to see if that helps.
> 3 votes

---
Tags: opengl, textures, frame-buffer
---


# Question
Title: Is it only possible to display 64k vertices on the monitor with 16bit?
I did the first 3D tutorial over at riemers.net and stumbled upon that my graphic card only supports Shader 2.0 (Reach profile in XNA) which means I can only use `Int16` to store the **indices** (triangle to vertex).

This means that I can only store 2^16 = 65536 vertices. Also I read on the internet that you should prefer 16-bit over 32-bit because not all hardware (like mine) does support 32-bit.

Yet, I am wondering: Do really all game scenes get along with only so little vertices? I though already faces of people used a lot of polygons (which are made up of vertices?).

It’s not relevant for me yet, but I am interested:

* Do game scenes use only 65536 vertices?
* Do you use some trade-off to display more (e.g. 64k in GPU buffer rest on RAM)
* Is there some method to get more into the GPU buffer? I already read on some other posts that there seems to be a limit of 64k per mesh too, so maybe you can compact stuff to meshes?

# Answer
> This means that I can only store 2^16 = 65536 vertices.

No it doesn't. It means that you can only use 16-bit indices (assuming it even means that, as I'm fairly sure D3D9 allows 32-bit indices. That's what the INDEX32 index buffer format means, right?). Which means that a *single draw call* can only access a 16-bit range of indices. But you are not limited to a *single* draw call for the entire scene. That's one reason why `DrawIndexedPrimitive` has the BaseVertexIndex parameter, which allows you to bias the index for a rendering command by a fixed offset.

You don't have to draw everything in one draw call. So even if you were limited to 16-bit indicies (which again, you are not), you could still make several draw calls to render what you needed.
> 4 votes

# Answer
First of all, 32-bit index support is ubiquitous on modern hardware, and has been for quite some time. If you only support 16-bit then you're long overdue an upgrade.

OK, so once upon a time there was a class of hardware that only supported 16-bit. This wasn't a problem back then because there are other options available. One of them would have involved splitting a mesh into multiple vertex/index buffers. So, if the mesh has more than 64k you can't pack it all into a single set of buffers - easy solution - just use two. Draw half the mesh from one set of buffers, the other half from the other set.

Going further back in time we arrive at software T&L (where hardware restrictions in the per-vertex pipeline were irrelevant), not using index buffers at all (a mesh would just be in a vertex buffer and be composed of multiple long triangle strips each of which gets it's own draw call), not even using vertex buffers (vertices come from system memory instead) or (getting really ancient now) the likes of OpenGL's old immediate mode.

Should 16-bit be preferred even in cases where 32-bit are available? Maybe, maybe not. This is a tradeoff, and the work involved in splitting a mesh may cancel out the gains obtained in using a smaller index type.
> 1 votes

---
Tags: xna, vertex, index-buffer
---


title: backface culling error (in world space)

text:
# Question
Title: backface culling error (in world space)
I write simple software renderer. In my pipeline I have stage of backface culling.

But looks like it has some error.

I perform culling **right after world transformation** (is it correct?).

```
Vector3F view_dir(0.0f, 0.0f, 1.0f);

std::vector<Triangle> to_remove;

for (Triangle &t : m_triangles)
{
    Vector4F e1 = t.v2 - t.v1;
    Vector4F e2 = t.v3 - t.v1;
    Vector3F normal(
        e1.y * e2.z - e1.z * e2.y,
        e1.z * e2.x - e1.x * e2.z,
        e1.x * e2.y - e1.y * e2.x
        );
    normal.Normalize();

    float dot = Dot(view_dir, normal);
    if (dot <= 0)
        to_remove.push_back(t);
}

for (Triangle& t : to_remove)
    m_triangles.erase(std::remove(m_triangles.begin(), m_triangles.end(), t), m_triangles.end());

```

Camera sits in origin and points in screen (RH).

What is the reason?

**UPDATED:** The error occurs only when triangle has non-zero offset from origin

**UPDATED 2:** If i process backface culling in clip space (after transforming all vertices with view and projection matrix), and just check z coordinate of triangle normal - it works perfect... Can i perform culing RIGHT BEFORE view/proj transforms? In this case looks like culling will not depends of projection and it's not right?

# Answer
I had the following error: The direction of the view was always taken constant, whereas it should be taken as the difference between the position of the camera and one of the points of the polygon (or its center). Otherwise it will not be perspective-correct. I don't get this error with zero offset from origin because in this case view direction correctly was (0, 0, 1).

So working code looks like this:

```
// Calculate view position from view matrix
Vector4F view_pos = m_view_transform * Vector4F(0.0f, 0.0f, 0.0f, 1.0f);
std::vector<Triangle> to_remove;

for (Triangle &t : m_triangles)
{
    Vector4F e1 = t.v2 - t.v1;
    Vector4F e2 = t.v3 - t.v1;
    Vector4F normal(
        e1.y * e2.z - e1.z * e2.y,
        e1.z * e2.x - e1.x * e2.z,
        e1.x * e2.y - e1.y * e2.x,
        0.0f);

    // Calculate actual direction
    Vector4F view_dir = t.v1 - view_pos;
    view_dir.Normalize();

    float dot = Dot(view_dir, normal);
    if (dot <= 0)
        to_remove.push_back(t);
}

for (Triangle& t : to_remove)
    m_triangles.erase(std::remove(m_triangles.begin(), m_triangles.end(), t), m_triangles.end());

```

Also, looks like there's no reason to do backface culling in world space - it can be done in object space and it can help to increase perfomance. More about front-end backface culling can be read at this page: http://www.gamasutra.com/view/feature/131773/a\_compact\_method\_for\_backface\_.php?print=1

Hope this will help someone in future :)
> 0 votes

---
Tags: culling, software-rendering
---


title: Batching dynamic sprites in OpenGL

text:
# Question
Title: Batching dynamic sprites in OpenGL
I'm trying to wrap my head around how batching is done in a 2D sprite-based game. My understanding is I'd get the vertices that represent each sprite I want to draw and stuff them all into a single mesh. That way I'd only need a single draw call to render everything.

Does this apply when the sprites I render are different between frames, or when some sprites are moving? Because it sounds like I'd then have to recreate my batch mesh each frame, using either `glDrawArrays`/`glDrawElements` or a streaming VBO I assume. Does this sound correct?

# Answer
> 8 votes
Yes, that's correct. Take all sprites that use the same material (share the same atlas) and draw them using a single dynamic:/steaming VBO.

If you have static sprites, it may be more efficient to put all those in one VBO, and the dynamic ones in another. If you have a large number of sprites, it may also be advantageous to use more than one VBO and split your batches up to reduce the size and amount of geometry you send in each draw call.

As with *all* optimizations, profile and check what is faster rather than assuming or taking advice off the Internet at face value.

---
Tags: opengl, 2d, sprites
---


title: 3D Camera manager tool – is there any?

text:
# Question
Title: 3D Camera manager tool – is there any?
Are there some libraries or example codes, of a camera manager – a tool, that would move camera using some smooth lines (bsplines or similar)? So basically I request an animation to move to a new eye/center possition, and the tool takes care of the rest?

# Answer
I don't know of a tool specifically for cameras, but that's a pretty narrow requirement that is usually going to be part of a larger graphics/animation package rather than an independent camera-oriented library.

If you're stuck implementing your own, it's not too hard. There are a few libraries that might help implementing it.

The basic gist of what you're going to do is to tween between two positions/rotations, or tween an interpolant along a spline.

http://libclaw.sourceforge.net/tweeners.html or http://code.google.com/p/cpptweener/ provide basic tweening; unsure if they'll meet your needs. Catmull-rom and b-spline interpolation is pretty easy to cook up on your own (I'd recommend catmull-rom over a b-spline for this use case), and I'm sure there's a decent library out there.

You would combine that with the usual linear interpolation function for vectors (for camera position) and spherical interpolation function for quaternions (for camera angles). For the spline, you can define two splines to differentiate camera position and angle (e.g., the spline the camera moves along and a spline that defines the point the camera looks at).
> 4 votes

# Answer
http://www.dhpoware.com/demos/glCamera3.html

This is an easy to use OpenGL camera class. The code is very clean and easy to get into for understanding how it works. As far as animation, you'll still have to create your own.

Be sure to check out their other demos, they have shared quite a bit of useful code.
> 1 votes

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


title: Map format for 3d open world

text:
# Question
Title: Map format for 3d open world
I am making an open world 3d platformer in Ogre3D, and I have no idea on what kind of 3d map file format I should use for it.

I want to make low-polygon blocky-style objects. Probably rectangles and other geometrical figures that don't have circular edges. Some of those blocks will have properties, like climbable or they might move.

I was wondering what would be the best thing to do to make the map (just one level, as it is open).

# Answer
If you are using Ogre3D, a logical choice would be to use Blender for creating the map, and Blender2Ogre to export the map into a .scene file.

Then, in the code, you can use the DotSceneLoader class to import the .scene file into the game world. This will automatically attach each object to a scene node and you can access them as needed.
> 2 votes

---
Tags: maps, ogre, file-format
---


# Question
Title: How do I render terrain in a 2.5D perspective, like in the game Don't Starve?
I have experience in making 2D side scroller games such as Terraria, but now I want to challenge myself and make a game that has a 2.5D perspective. The game I am trying to mimic is Don't Starve. Right now my focus is on figuring out how to render the ground. I am having a hard time figuring out how they generated the ground, and then rendered it. The way I think they rendered the ground is by first painting the ground in some paint program, and then somehow manipulating that flat image so that it appears to have depth.

I am completely confused by how you would actually render that type of terrain. I want the terrain to have the following features:

Any tips and hints will be appreciated, Thank you in advance.

(I am working in Java, using the Light Weight Java Game Library (LWJGL).)

# Answer
I'm actually one of the Don't Starve devs (Kevin on our forums). I don't usually handle the rendering stuff, but I can tell you that the game is in 3D. The ground is just a regular 2D tile map with special transition pieces to make corners look better. There's no special Deathspank-style rounding going on, although we have talked about doing that in the past.

There are two types of game entities - upright and ground. The upright entities are kindof halfways billboarded to the camera, although not fully because with the camera angle this made them look like they were laying down. The ground stuff is just plain drawn on the ground.

The look that this gives works for a somewhat small range of camera angles. If you go too high, the upright stuff gets all weirdly foreshortened. Going really low works a bit better, but it's too hard to play the game because you can't see behind things or anything 'south' of your character. Finding the right trade-off between these two extremes took a bunch of experimentation.

Anyway, if you have any other questions about the tech behind the game, we're pretty friendly and forthcoming about such things over at the klei forums :)
> 37 votes

# Answer
I can't say for sure how that one game did it, but from the video it looks like it's just a regular 3D game world that uses billboarded sprites for game objects. Similar games include some of the Paper Mario games and the Death Spank series.

Render your terrain as 3D with a perspective camera. Maybe apply some simple vertex shader to get a little extra "roundness" (Death Spank did this to great effect, and it looks like Don't Starve might have a very subdued version of the same effect; hard to tell).

For your game objects, create sprites, and render them to always be camera-facing (called "billboarding"). There are many tutorials on how to achieve billboarding online, e.g. http://www.lighthouse3d.com/opengl/billboarding/
> 3 votes

---
Tags: java, rendering, game-mechanics, terrain, 2.5d
---


# Question
Title: Alternatives to NSMutableArray for storing 2D grid - iOS Cocos2d
I'm creating a grid-based iOS game using Cocos2d. Currently the grid is stored in an NSMutableArray that contains other NSMutableArrays (the latter are rows in the grid). This works ok and performance so far is pretty good. However the syntax feels bulky and the indexing isn't very elegant (using CGPoints, would prefer integer indices). I'm looking for an alternative.

**What are some alternatives data structures for 2D arrays in this situation?**

In my game it's very common to add and remove rows from the bottom of the grid. So the grid might start off 10x10, grow to 17x10, shrink to 8x10 and then finally end with 2x10. Note the column count is constant.

I've consider using a `vector<vector<Object*>>`. Also I'm vaguely aware of some type of "fast array" or similar offered by Cocos2d. I'd just like to learn about best practices from other developers!

# Answer
First of all, given the grid sizes you've talked about you're not likely to run into performance issues with your current implementation, so if you're asking this because you have a performance problem this may not be it (and you should profile). That said:

The "array of arrays" approach might seem like a reasonable representation of a grid (and to some extent, it is), but it has some drawbacks. As you've discovered, using the interface can be awkward (especially if you're using something the like Cocoa array classes, since their indexing APIs are cumbersome already).

They're also not very cache-coherent, since the entire grid is not guaranteed to be contiguous in memory, and they allow the grid to be "jagged" (i.e., not really a grid) since you *could* adjust the size of an individual row only, should you so choose (of course in some cases this is a benefit, but not in this one).

So, **why not just use a single array**? A one-dimensional array (`vector`, `NSMutableArray`, bare memory, whatever) can represent a *n*-dimensional grid easily and requires only a little bit of indexing math, and it provides you the significant benefit of improved locality-of-reference for the entire grid's elements.

An example using `vector` (although the principle applies to any other array interface):

```
unsigned width = /* ... */
unsigned height = /* ... */
std::vector<Object*> grid(width * height);

// Compute the linear index of the item at (row, column) in the grid:
unsigned row = /* ... */
unsigned column = /* ... */
unsigned index = column + (row * width);

// Access the grid:
grid[index] = /* assign some object */

```

The principle here is to treat each contiguous set of `width` elements in the array as a single row. That's how you arrive at the indexing math used to compute `index`.

Another issue you touched on is how your grid resizes. This is an issue regardless of the grid implementation you use. You might try handling it by only increasing the actual storage for the grid; never decrease it. Almost any implementation of a grid is going to involve a copy of the existing grid elements when the grid resizes. Implementations utilizing linked-lists won't (or will minimize them), but then you're back to having cache-coherency issues.

You want to minimize that copying, and at a minimum you only need to resize to *increase* storage. You can keep, independently, a variable indicating the grid's logical size and only process that many rows, ignoring any extra "deactivated" rows that might exist beyond that when your grid resizes down. This means the resize-downward operation only involves setting a variable to the new, lower number.

This can be extended to apply to cases where the grid resizes in both directions, even though your specific case does not currently seem to require that.

I mentioned cache coherency/locality of reference a few times, and that's because I'm assuming since your game is "grid based" your doing a lot of iteration over all (active) cells in the grid. It's that kind of use-case where coherency of your data can have a surprising impact on performance, although it's still true that at the specific numbers you mentioned it's unlikely to be that big of a deal.
> 3 votes

---
Tags: cocos2d-iphone, ios, grid
---


title: blurry image rendered

text:
# Question
Title: blurry image rendered
I'm using Direct2D to render a PNG image using a ID2D1BitmapRenderTarget and then caling it's GetBitmap() function and rendering the image using ID2D1HwndRenderTarget::DrawBitmap().

Some of the images rendered this way are clear but others appear blurry. I did some research and followed a tutorial to make my application "DPI Aware" but it didn't help.

(sample with a blurry image on the left)

What could cause the rendered image to appear blurry? Has anyone experienced this issue before? What can I do about this?

# Answer
> 3 votes
I’m not exactly knowledgeable in Direct2D, but you're probably drawing your image on a half-pixel boundary, and you're getting pwned by antialiasing.

Try drawing the first image half a pixel to the bottom right, so instead of doing

```
Draw(something, x, y);

```

do something like

```
Draw(something, x + 0.5, y + 0.5);

```

Google "Direct2D half pixel" for information on how to do this.

---
Tags: directx, rendering
---


title: Animating sprites in HTML5 canvas

text:
# Question
Title: Animating sprites in HTML5 canvas
I'm creating a 2D platformer game with HTML5 canvas and javascript. I'm having a bit of a struggle with animations. Currently I animate by getting preloaded images from an array, and the code is really simple, in `player.update()` I call a function that does this:

```
var animLength = this.animations[id].length;
this.counter++;
this.counter %= 3;
if (this.counter == 2) this.spriteCounter++;
this.spriteCounter %= animLength;
return this.animations[id][this.spriteCounter];

```

There are a couple of problems with this one: When the player does 2 actions that require animating at the same time, animation speed doubles. Apparently `this.counter++` is working twice at the same time. I imagine that if I start animating multiple sprites with this, the animation speed will multiply by the amount of sprites. Other issue is that I couldn't make the animation run only once instead of looping while key is held down.

Someone told me that I should create a `function Animation(animation id, isLooped boolean)` and the use something like `player.sprite = new Animation("explode", false)` but I don't know how to make it work.

# Answer
> 1 votes
You may benefit from looking at my answer to another question on this site: Sprite Animation Best Practices. In that answer I link to a working animation system written in JavaScript.

In short, there is probably an easy way to solve this. Create an object that represents an `Animation`. This is usually just an ordered list of frames and durations.

Create a separate object to store the playback information, in other words, how "far" into an animation you have played. I recommend using a time-based animation scheme. This way, you can play an animation by advancing time and you should not run into problems with double speed.

# Answer
> 2 votes
The update of the anim should take as argument the current time or *actual* frame duration (timers are not so acurate, and requestAnimationFrame can trigger any time). You can compute the time with Date.now() or even better window.performance.now().
(For reasons too long to explain here, the really best solution is to have your own game time.)
Each frame should also be assigned a given time. Most simple way is to have the same duration for each frame, and have an array that allows you to repeat some frame to shape your animation as you want :

```
frameDuration = 10 ;  // in ms
frameArray   = [ 0,0,1,2,3,3,2,3]; // array of index

```

obviously the best way is to have both a frameArray and a frameDurationArray :

```
frameArray   =         [ 0,1,2,3,2,3]   ; // array of index
frameDurationArray   = [ 20,10,20,10,10]; // array of durations

```

... but it requires a little more computation.

if you go for the first solution (same frame duration), the updateAnim should look like :

```
updateAnim = function ( time ) {
   var timeElapsed = Date.now()-this.startTime;
   var imgIndex = Math.floor(this.frameArray.length * timeElapsed / this.frameDuration );
   //... do some  %  if needed
   ...
}

```

---
Tags: javascript, html5, html-canvas
---


# Question
Title: Applying prerecorded animations to models with the same skeleton
well my question sounds a bit like, how do I apply mo-cap animations to my model, but thats not really it I guess. Animations and model share the same skeleton, but the models vary in size and proportion, but I still want to be able to apply any animation to any model. I think this should be possible since the models got the same skeleton bone structure and the bones are always in the same area only their position varies from model to model.

In particular Im trying to apply this to 2D characters that got 2arm, 2legs, a head and a body, but if you got anything related to that topic even if its 3D related or keywords, articles, books whatever Im gratefull for everything cause Im a bit stuck at the moment.

cheers

Jery

# Answer
> 1 votes
In the compsci literature, this problem is known as "motion retargeting", and in general it is quite difficult. If I recall, the most basic thing you can do is to naively transfer the joint parameters to the new skeleton, and then use IK to enforce whatever constraints you care about in your specific situation. So, if your character is supposed to be touching something, or stepping on a certain point on the ground, you can post-process this in. Of course, this doesn't always work, but for smaller skeletal deformations you can get away with a lot.

Anyway, here's a link to a Siggraph paper on the subject from 1998: http://www.cse.ohio-state.edu/~parent/classes/788/Sp06/OldStuff/Lectures/MotionCapture/Retarget/retarget-preprint.pdf

---
Tags: 2d, animation, models, procedural, skeletal-animation
---


# Question
Title: What animation technique is used in 'Dont Starve'?
While playing a few games in my personal time off development I've stumbled across a survival 2D/3D survival game. The game was apparently made in SDL and GLUT (Dont starve) but what really amazed me was the animations in the game.

The animations are extremely smooth and fluent. There is no distortion while animating, what usually happens in hand-made animations is that pixels get removed, animations are jaggy and they simply aren't as smooth. That got me thinking on how they managed to accomplish such a quality of animations. Were they really handmade (If they were, then it must've taken a very talented artist), is it bone animation or are they using another technique?

# Answer
My name is Kevin, and I'm a programmer/designer at Klei. I wrote a bunch of the animation stuff that we used in the Shank series, Mark of the Ninja, and Don't Starve.

Our animators work in Flash. We have a concept of a character 'build' which is a set of body-part symbols with multiple views. Depending upon the fidelity of the given game, there are more or less body parts with more or less 'view'. I think that Shank had about 30 body parts with 1-2 dozen views each, while Wilson from Don't Starve has about a dozen body parts with only about the same number of views. Custom JSFL scripts are used to analyze the flash symbol timelines, and then bake out the relevant images as a series of high-res PNG files, along with a bunch of metadata that we stick in an XML.

Given a character build, our animators create a new root symbol in another file to contain a chunk of animation for that character. In that timeline, they create the character out of build symbols and move it around, tween it, etc. to create individual animations (which are demarcated using frame labels). The exporter script exports these timelines into XML, taking note of the 2d transform of every build piece, and which view it is showing.

With all of this information exported to XML and PNG, we run a series of Python scripts to convert them into run-time data. One script downsizes, atlases, and mips all of the textures and convert them to (one or more) compressed, platform-specific formats. Another script processes the XML animation data into a more efficient to load binary format.

At run time, It's really just a matter of showing the right build symbols with the right transforms and view.

This system took a long time to build, and has been refined as we've moved it from game to game. There are a lot of details that I'm glossing over (like how we handle layering and run-time costume swapping), but that's the general outline.

Of course, the technology that we use is probably the least important aspect of the 'Klei Look'. The most important part is that we have a bunch of really, really good animators. :)

Anyway, I hope this helps. If you have any more questions about Don't Starve, you can stop by our forums, where I'm usually quite happy to talk shop.
> 40 votes

# Answer
Klei typically uses a really nice combination of Skeletal animations and sprite-changes.
They rig a skeleton, apply sprites to the bones and then they'll swap sprites as an animation frame calls for it.

The exact "how" (workflow/tools/etc) can really only come from them, however, they said so themselves when advertising "Shank", pre-release.

And if you look at Shank/ShankII, Mark of the Ninja and Don't Starve, you'll notice that the animation looks a lot like the stuff that might come out of Nickelodeon.

I would imagine that they're working with scene graphs to keep everything sane, as well, but again, that's more an assumption based on complexity and what works for animation (2d/3d) than a guarantee.
> 7 votes

# Answer
I think they definitely use bone animation. They also either use high-res sprites(to prevent jagginess) or they use some form of vector graphics. It is entirely possible, they pre-rendered vector graphics into high res sprites. They definitely did not use pixel art for this one. :)
> 2 votes

---
Tags: animation, sdl, glut
---


# Question
Title: I'm looking to learn how to apply traditional animation techniques to my graphics engine - are there any tutorials or online-resources that can help?
There are many traditional animation techniques - such as blurring of motion, motion along an elliptical curve rather than a straight line, counter-motion before beginning of movement - which help with creating the appearance of a realistic 3D animated character.

I'm looking to incorporate tools and short cuts for some of these into my graphics engine, to make it easier for my end users to use these techniques in their animations. Is there a good resource listing the techniques and the principles behind them, especially how they might apply to a graphics engine or 3D animation?

# Answer
> 4 votes
You can simulate a lot of different movement types using easing-equations. Your engine would definitely benefit from having them built in.

See this question and it's answers for more resources: Easing Functions

The "Interpolation Tricks Tutorial" by Jari Komppa is a good starting point IMHO

# Answer
> 2 votes
This classic Siggraph paper by John Lasseter is required reading for any programmer working with animation:

http://www.siggraph.org/education/materials/HyperGraph/animation/character\_animation/principles/prin\_trad\_anim.htm

It's pretty high-level, but it introduces you to the language that animators use to describe their craft.

---
Tags: animation
---


title: Data-driven animation states

text:
# Question
Title: Data-driven animation states
EDIT: To clarify what exactly my question is: is this a good way to handle animations / animation state in a game engine with the eye on content creation / management? What are the flaws in doing it this way and what would be an alternative way to do it? -- Though my answer got partially answered in the comments, as it seems to be the way to go.

I'm trying to handle **animations in a 2D game engine** hobby project, without hard-coding them. Hard coding animation states seems like a common but very strange phenomenon, to me.

A little background: I'm working with an entity system where components are bags of data and subsystems act upon them. I chose to use a polling system to update animation states.

With **animation states** I mean: "walking\_left", "running\_left", "walking\_right", "shooting", ...

My idea to handle animations was to design it as a **data driven model**. Data could be stored in an xml file, a rdbms, ... And could be loaded at the start of a game / level/ ... This way you can easily edit animations and transitions without having to go change the code everywhere in your game.

As an example I made an xml draft of the **data definitions** I had in mind.

One very important piece of data would simply be the **description of an animation**. An animation would have a unique id (a descriptive name). It would hold a reference id to an image (the sprite sheet it uses, because different animations may use different sprite sheets). The frames per second to run the animation on. The "replay" here defines if an animation should be run once or infinitely. Then I defined a list of rectangles as frames.

```
<animation id='WIZARD_WALK_LEFT'>
    <image id='WIZARD_WALKING' />
    <fps>50</fps>
    <replay>true</replay>
    <frames>
        <rectangle>
            <x>0</x>
            <y>0</y>
            <width>45</width>
            <height>45</height>
        </rectangle>
        <rectangle>
            <x>45</x>
            <y>0</y>
            <width>45</width>
            <height>45</height>
        </rectangle>
    </frames>
</animation>

```

Animation data would be loaded and held in an **animation resource pool** and referenced by game entities that are using it. It would be treated as a resource like an image, a sound, a texture, ...

The second piece of data to define would be a **state machine to handle animation states** and transitions. This defines each state a game entity can be in, which states it can transition to and what triggers that state change.

This state machine would differ from entity to entity. Because a bird might have states "walking" and "flying" while a human would only have the state "walking". However it could be shared by different entities because multiple humans will probably have the same states (especially when you define some common NPCs like monsters, etc). Additionally an orc might have the same states as a human. Just to demonstrate that this **state definition might be shared but only by a select group of game entities**.

```
<state id='IDLE'>
  <event trigger='LEFT_DOWN' goto='MOVING_LEFT' />
  <event trigger='RIGHT_DOWN' goto='MOVING_RIGHT' />
</state>
<state id='MOVING_LEFT'>
  <event trigger='LEFT_UP' goto='IDLE' />
  <event trigger='RIGHT_DOWN' goto='MOVING_RIGHT' />
</state>
<state id='MOVING_RIGHT'>
  <event trigger='RIGHT_UP' goto='IDLE' />
  <event trigger='LEFT_DOWN' goto='MOVING_LEFT' />
</state>

```

These states can be handled by a **polling system**. Each game tick it grabs the current state of a game entity and checks all triggers. If a condition is met it changes the entity's state to the "goto" state.

The last part I was struggling with was how to **bind animation data and animation states to an entity**. The most logical approach seemed to me to add a pointer to the state machine data an entity uses and to define for each state in that machine what animation it uses.

Here is an xml example how I would define the animation behavior and graphical representation of some common entities in a game, by addressing animation state and animation data id. Note that both "wizard" and "orc" have the same animation states but a different animation. Also, a different animation could mean a different sprite sheet, or even a different sequence of animations (an animation could be longer or shorter).

```
<entity name="wizard">
    <state id="IDLE" animation="WIZARD_IDLE" />
    <state id="MOVING_LEFT" animation="WIZARD_WALK_LEFT" />
</entity>

<entity name="orc">
    <state id="IDLE" animation="ORC_IDLE" />
    <state id="MOVING_LEFT" animation="ORC_WALK_LEFT" />
</entity>

```

When the entity is being created it would add a list of states with state machine data and an animation data reference.

In the future I would use the entity system to build whole entities by defining components in a similar xml format.

--

*This is what I have come up with after some research. However I had some trouble getting my head around it, so I was hoping for some feedback. Is there something here what doesn't make sense, or is there a better way to handle these things? I grasped the idea of iterating through frames but I'm having trouble to take it a step further and this is my attempt to do that.*

# Answer
> 4 votes
Animation clips are best described in plain-old-data, as you've done in your first XML snippet. You can make this by hand, or export to it from an art package. Either way, you're probably going to want to create a pipeline that takes it from a human-readable intermediate format like XML and puts it into something that's nice and quick to load.

The next step is being able to render the thing. If you're using some sort of scene graph, that'll probably mean making an Anim Node for it. You should be able to tell the anim node which animation it is currently playing, and where in the timeline it currently is. Make sure that you keep bounding box information accessible at this level so that you can easily feed it into your culling system.

Now, you're going to want to associate an animation with a game entity. I tend to use a component-based model, so for me this means and AnimState component. This is your intermediate layer between gameplay and rendering. It keeps track of which animation an entity is playing, playmodes (looping, once, ping-pong, etc), timing, etc. It can send events like "animover" back to the entity, and updates the state of the animnode when appropriate. AnimStates for active entities will get updated once per sim tick if they are playing an animation.

An animstate component is probably enough for simple game items (basic background props and the like), but for more complicated entities you are going to want to use a state machine t o mange it. This is best expressed in a scripting language like Lua or Python. A state can have several functional blocks (onEnter, onExit, onUpdate, onEvent), as well as a timeline that specifies certain actions and triggers that should happen at certain times. You will probably have some kind of manager class that is responsible for updating these state machines as appropriate, as well as triggering the timeline callbacks when they occur. You should try to keep these things as event-based as possible, since every OnUpdate you write will be a linear cost with entity count. You're also going to want to be able specify tags ('attacking', 'idle', 'ignoreinput', etc) that are associated with both whole states and certain time regions of states. You'll probably also want some high-level event handlers that apply to the entire state-graph, and not just a particular state.

'Sentient' characters will probably have some kind of an AI as well. I tend to make a specific 'locomotor' component that handles walking around. It interfaces with the stategraph using a system of signals and events and querying for state-tags, and can be told to "walk to point", or "run in a certain direction at a certain speed". Higher-level AI components (like a behaviour tree or whatever) can then use this interface without worrying about the details.

# Answer
> 1 votes
The best data-driven animation system I've seen so far is the *Blend Tree*. Really, it's damn good and it can do all you're asking for here. According to AIGameDev.com it's now the de-facto standard in the industry, and I believe they're right.

Unfortunately I found no good resource with a quick googling, but you can try this or that to get an overview. There's also a paying article on AIGameDev.com, don't know if it's worth getting a premium account.

---
Tags: animation, state, fsm
---


# Question
Title: Given an angle for an arrow, how do I find its X and Y velocities?
I want to fire an arrow toward the mouse location.

```
X0 = the players X location
X1 = the mouse X location
Y0 = the players Y location
Y1 = the mouse Y location

```

I want to make a method which *takes degrees as a parameter*, and sets the `Yspeed` and `Xspeed` accordingly, so the arrow can reach the mouse position, starting at the player position.

I am using float coordinates (i.e. `float x, y, z`).

How can I do this?

# Answer
> 7 votes
This " answer " is to add some visual information to the answers already given.

2: We first create a vector ( 2D in this case with component x and y ) by taking the difference from both positions ( mouse - player ).

3: We then Normalize it to create a so called " unit vector ". Which means to bring the length of our vector to 1. This is done by dividing both x and y component of the vector by the length/magnitude. We need this because this is our direction vector. It simply tells in which direction we are heading for the x and y axis.

4: Now we have the direction we just need to multiply it by a scalar ( or simply put by your speed). Since the length is 1. Any number we multiply with will result in a new vector with the length equal to your given speed. Just remember that a unit vector represents the direction of your vector. Basically the red dotted lines is how much it moves in the x direction and how much it moves in the y direction per frame.

So recap:
Unit vector = direction
Magnitude/Length/*speed* = steps to move per frame on x and y axis.

(The lengths in the drawing are just for visual aid, they are not meant to be accurate )

Hope this helps.

# Answer
> 3 votes
You are trying to fire an arrow from point a(player) to b(mouse position) in 2d space?

you can simply do the following formula to get the direction. (rather than degree)

```
v1 = ( Player.x, Player.y );
v2 = ( Mouse.x, Mouse.y );
dir = v2 - v1;
dir.normalize();
arrow.xy += dir * speed;

```

hope this helps you achive what you want.

# Answer
> 3 votes
The ratio of the horizontal to the vertical component of the vector is proportional to the ratio of the horizontal and vertical difference in position. The proportion factor is the speed divide by the direct distance (calculated by the pythagorean theorem).

```
distance.x = target.x - start.x;
distance.y = target.y - start.y;
distance_direct = square_root((distance.x * distance.x) + (distance.y * distance.y)); // pythagoras

vector.x = distance.x * (speed / distance_direct);
vector.y = distance.y * (speed / distance_direct);

```

Note that this will result in a division by zero when the distance is zero (start and target position are identical). That makes sense, because in that case the vector is undefined (in what direction do you not-go when you want to stay where you are?). This case needs to be handled separately.

Note that there is no reason to use degree here. When you have an angle in degree and a speed, you can convert it to x and y direction using sine and cosine:

```
vector.x = sin(angle) * speed
vector.y = cos(angle) * speed

```

In most programming languages, the sine and cosine functions use radiants, not degrees. That means a full 360° circle is 2\*PI (approximately 6.283185) you can convert degree to radiants by multiplying them with `PI / 180` or approximately 0.01745329.

---
Tags: vector, angles, aiming
---


# Question
Title: How can I create a flexible system for tiling a 2D RPG map?
Using libgdx here. I've just finished learning some of the basics of creating a 2D environment and using an OrthographicCamera to view it. The tutorials I went through, however, hardcoded their tiled map in, and none made mention of how to do it any other way. By tiled map, I mean like Final Fantasy 1, where the world map is a grid of squares, each with a different texture.

So for example, I've got a 6 tile x 6 tile map, using the following code:

```
Array<Tile> tiles = new Array<Tile>();

tiles.add(new Tile(new Vector2(0,5), TileType.FOREST));
tiles.add(new Tile(new Vector2(1,5), TileType.FOREST));
tiles.add(new Tile(new Vector2(2,5), TileType.FOREST));
tiles.add(new Tile(new Vector2(3,5), TileType.GRASS));
tiles.add(new Tile(new Vector2(4,5), TileType.STONE));
tiles.add(new Tile(new Vector2(5,5), TileType.STONE));

//... x5 more times.

```

Given the random nature of the environment, for loops don't really help as I have to start and finish a loop before I was able to do enough to make it worth setting up the loop. I can see how a loop might be helpful for like tiling an ocean or something, but not in the above case.

The above code DOES get me my final desired output, however, if I were to decide I wanted to move a piece or swap two pieces out, oh boy, what a nightmare, even with just a 6x6 test piece, much less a 1000x1000 world map. There must be a better way of doing this.

Someone on some post somewhere (can't find it now, of course) said to check out MapEditor. Looks legit. The question is, if that is the answer, how can I make something in MapEditor and have the output map plug in to a variable in my code? I need the tiles as objects in my code, because for example, I determine whether or not a tile is can be passed through or collided with based on my TileTyle enum variable. Are there alternative/language "native" (i.e. not using an outside tool) methods to doing this?

# Answer
I believe that Tiled Map Editor (TME) can create files of different types, however the main feature that caught my eye was it's ability to export to JSON files.

JSON is somewhat similar to XML and you will find good supporting APIs for parsing JSON files in Java. See here.

Once you have created a map in TME you will be able to export it as one of these JSON files. Then you will be able to load and parse that file to create java objects. You might find it convenient to parse to some intermediate set of java objects, then extract from them only the information you want and use it to make YOUR tile objects.

See this question for some more information. One answer mentions this tool which might help you out. This tool will allow you to generate the Java Object equivalent to the JSON objects created by TME.
> 3 votes

# Answer
A map editor of some sort is what you are going to need (and want!) when your game moves more to the level design phase from the initial engine/coding phase.

If you are using any kind of map/level editor, you will need to code a class (or set of classes) that can:

1. Read/Input the Data
2. Translate the data into actual objects (and sets of objects). Your tiles look simple now, so the map file would just be X, Y pairs with a tiletype name you can translate into a `Tile` enum.

You have to understand the editor output and figure out how it relates to your game objects. Creating an editor on your own helps with that, but you may get stuck implementing "basic" quality-of-life features like undo/redo and forget about the actual game! Those kinds of things are already implemented in a 3rd part editor.

If you do create your own, just get it to the point where you can place tiles on any size map you want, get some output, and then import that into your game. Implement additional features as you develop them in your game. Get something simple working first!

One important take-away is whatever solution you use, keep a layer between your actual level/tile objects and whatever map format you are using. That way, if you decide to change the map format, it won't impact your game code as much.
> 7 votes

# Answer
LibGDX has now added support for loading and rendering Tiled Map Editor's own `.tmx` file format. This should most certainly be your preferred method of loading and rendering TME created tile maps in LibGDX now, rather than having to manually parse through the JSON/XML data yourself.

Link to LibGDX tutorial on using `.tmx` tile maps.
> 5 votes

---
Tags: tiles, maps, libgdx, tilemap
---


title: Object oriented approach to debug mode

text:
# Question
Title: Object oriented approach to debug mode
I'd like to introduce a way to turn off/on debug messages and in-game tooling (tweak menus, for example) without non-game related branches, e.g:

```
if(DEBUG_MODE) {
    // show tweak menu

    // some message
    console.log("In this function");
}

```

Is there a more reusable approach to this problem?

# Answer
The best bet, taking into account performance considerations, is to simply have a means of wrapping up debug code in a way that can be "compiled out" as best as possible, and then left in as run-time selectable if not compiled out.

In C/C++ this generally means a macro (or a set of macros for different specific needs) that wraps calls to debug functions that internally check debug flags. In a language like C#, you can use the \[Conditional()\] attribute and the run-time debug flags internally.

In languages like JavaScript, which it appears you might be using, you can fall back on good ol' functional composition for the run-time behavior, and simply including different .js files for the "release mode" vs "debug mode" implementation.

Note that this is *not* object-oriented. I don't think you're actually looking for an object-oriented approach at all, though.

Consider a debug script like so:

```
// debugtools-release.js
function debug(expr) {}

// debugtools-debug.js
function debug(expr) {
  if (window.debug_on && expr instanceof Function)
    expr.call(this);
};

```

You can now wrap up any debug logic you want like so:

```
do_something();

debug(function(){
  console.log("Did something");
  graphics.drawDebugLine(foo.x, foo.y, bar.x, bar.y, Color.Yellow);
  ++some_debug_counter;
});

do_something_else();

```

All of that debug code will be skipped if debugging is turned off. Better, modern JS compilers might completely remove any overhead involved, giving you similar performance to using macros in C++. (I'm not sure if they do or not, you'd have to test to be sure.)

For simpler cases, like just printing out a console log message, you can of course create helpers for those cases. Something like:

```
// debugtools-release.jse
function debug_msg(msg) {}

// debugtools-debug.js
function debug_msg(msg) {
  if (window.debug_on)
    console.log.apply(this, arguments);
};

```

If you're of the mind, you could combine both the debug and debug\_msg functions by checking argument types and the like (though I prefer having clearly differentiated functions for differing behavior myself):

```
function debug(expr) {
  if (window.debug_on) {
    if (expr instanceof Function)
      expr.call(this);
    else
      console.log.apply(this, arguments);
  }
}

```

The general functional composition technique works equally well for other languages that lack explicit compiler support for optionally disabling code and which have lambda/anonymous functions of some form. I've even used it in C++11 code, though I'm still unsure whether I prefer that or the macro approach (and for games, since we generally have to support older compilers, the C++11 approach is just not yet feasible).
> 2 votes

# Answer
Well, as a first attempt you can move branching to debug objects:

```
Log: function (msg) {
    if (DEBUG_MODE) {
        console.log(msg);
    }
}

// and then use:
Log("In this function");

```

Not sure how well this approach can integrate with your "tweak menu" however.
> 2 votes

# Answer
If you use a **ServiceLocator** you could use a preprocessor flag to return either the debugging service or the production service.

See: http://gameprogrammingpatterns.com/service-locator.html#design-decisions (*Bind to it at compile time*).

The other method I know from non-games is Petr Abdulins way of having a **Logging class** where you can bind output devices (File, Console, Monitor, Nowhere) or logging filters (levels) to, so they can ignore messages if desired.

They would be used something like this, but probably my syntax is not totally correct.

```
Logger logger = new Logger();
logger->addOutput(new ScreenDevice());
logger->addOutput(new FileDevice(new LevelFilter(Level::WARNING)));

```

You would then either pack them into a Registry (globally available) or they come with Singleton or an own static function to retrieve multiple loggers like this:

```
Logging::getLogger('myfirstlogger');  // these could be used instead of new Logger()
Logging::getLogger('mysecondlogger'); // and when a Logger is already available
                                      // return that one

```

The problem I see with this is, that you always ship it with your compiled program, so you always have this call to a function that does nothing. Yet, it’s possible that compilers might optimize this so that the unneeded call would be deleted.
> 2 votes

# Answer
Why so object-oriented? What's wrong with a flag?

You can define flags simply by creating a new variable: `DebugFlags = DEBUG_GAME | DEBUG_TOOLS;` where `DEBUG_GAME = 1<<0` and `DEBUG_TOOLS = 1<<1` etc.

This would require adding a parameter to the Log function like this: `function Log( message, flags )` and having all irrelevant messages disabled at startup, this way: `if( flags & DebugFlags == 0 ) return;`.

Assuming that you do all your logging from a single thread (each thread should have its own logging state anyway), you can at some point just store the old flags, assign new flags and execute some code, after which you set the flags back to the old ones.

P.S. Object-oriented = less reusable on the scale of all reusable things. Functions/data are above OO and algorithms are above both.
> 1 votes

# Answer
Using the Component Based approach (c#) i have created a debug object that gets added as component to the Overall solution it is able to handle all debug requests that i'm interested in and draw them to screen by passing an object to the handler

i have then wrapped anything that it does within the compiler if statements

```
#IF DEBUG
#ENDIF

```

therefore if i add a peice of text to the Debug handler

i.e

```
public void AddTouchLocation(vector2 location , string text)
{
    #IF DEBUG
    Dosomething(location,text);
    #ENDIF
}

```

the code doesn't do anything with it

i can also wrap the draw method like this also

whilst it maynot be the cleanest solution (it leaves a empty component in release mode) it does allow me to ignore any if debug anywhere else in the project.

```
public override void Draw()
{
    #IF DEBUG
     //Perform draw of touchlocations
    #ENDIF
}

```
> 1 votes

# Answer
When you would like to solve it in the most unnecessary, gratuitous, by-the-book OOP way possible, you would do it like that:

Define an interface (or abstract base class, when your programming language doesn't support interfaces) for everything you would usually have a class for. Have two implementing classes for each: one debug class and one release class. The debug class either extends the corresponding release class or works as a proxy for an instance of it. The methods of the debug class would output the debugging information and then call the corresponding method of the release class instance.

No debug and release objects are created directly. Instead of that, you have factory classes (or at least factory methods) which create release objects in release mode and debug objects in debug mode.

But seriously. There is nothing wrong with having some `if (DEBUG)`'s in your code or with a logging function which only outputs messages in debug mode. In one game project we had a logger function which also required a severity level for each logging call (DEBUG, INFO, WARNING, ERROR). A compilation switch determined the minimum log level which would be outputted in the log and the minimum which would be outputted on-screen.
> 0 votes

---
Tags: software-engineering, debugging
---


# Question
Title: Estimating players' odds of winning in a fighting game
I'm creating a fighting game where two opponents face off against each other in the ring. While I've been able to figure out the odds of a player winning based on previous wins/losses, I have yet to find a formula which modifies those odds based on opponent. For example:

* Player 1: W:5 L:5 - 1/1 odds
* Player 2: W:5 L:0 - 1/5 odds

I want to calculate the odds that Player 1 will wins against player 2. Compounding this, the players could be of different levels: if the players are within a few levels of each other, the odds should map closely to wins/losses. However, as the levels diverge, the odds of the lower level player winning reduce. As a swag:

Player 1 - W:5 L:5 - 1:1 odds

* Against a level 8 - 1:2
* Against a level 9 - 2:3
* Against a level 10 - 1:1
* Against a level 11 - 3:2
* Against a level 12 - 2:1

These are just estimates, my sense is that there is a math formula out there which will calculate that - can anyone out there point me to what this could be?

# Answer
Sounds like http://en.wikipedia.org/wiki/Elo\_rating\_system might be a good starting point: it's a system which ranks players based on their win/loss record, weighted by their rank. The gap between players' Elo rankings can then be used to calculate the relative odds of each winning.
> 5 votes

---
Tags: scoring, ranking, probability, fighting-game
---


# Question
Title: Using Ogre particle point billboards with shaders
I'm learning about using Ogre particles and had some questions about how the point type particles work.

Q. I believe point type particles are implemented as a single position. Is one single vertex is passed to the vertex shader?

Q. If one vertex is passed to the vertex shader then what gets sent to the fragment shader?

Q. Can I pass the particle size to the shader? Perhaps with a custom parameter?

# Answer
> 1 votes
Ogre can do 'point sprites' but it has some important caveats.

* if the center of the sprite hits a screen edge it will be culled. Half the visible sprite will vanish when it's culled.
* some video cards don't allow large sprites.

If you do choose to use point sprites under opengl you must set the pixel attenuation values or pixel sprite mode will not be enabled. The PSIZE parameter in the shaders will just not work. It's not obvious what it's doing under the covers. Generating vertices for the billboard for you or just generating a point sprite.

---
Tags: shaders, ogre
---


# Question
Title: shader coding: calculate screen coordinates of fragment
Good morning, I'm new to shader coding and trying to implement some visual effects code in shaders using billboards. (Yes, I couldn't have picked anything harder to start with, but I'm lucky that way)

**Setup:** I have rendered the full screen z depth to an array of floats in a previous pass. In the fragment shader I need the scene depth where the rendered fragment is displayed (to see if it's occluded). I can use tex2d() to get the depth value if I have the screen coordinates of the point being rendered in the fragment shader.

**Question:** In the fragment shader how do you calculate the screen coordinates of the pixel (in the range 0-1.0)?

Is the position passed to the fragment shader a pixel offset? If so, I guess it would be: float2( position.x / screen-width, position.y / screen-height )

Thanks for any help/

# Answer
CG (as your tags indicate) supports the `WPOS` semantic in some profiles, for example this one. An input parameter bound to the `WPOS` semantic will get the window position (with the origin in the lower-left) of the fragment.

Other languages, like GLSL, have similar predefined uniforms or inputs (`gl_FragCoord` for example), although the specifics of their value ranges may vary.
> 4 votes

---
Tags: shaders, cg, fragment-shader
---


# Question
Title: How to rotate to a target position over time
I know how to do rotations to vectors, but how do I rotate over time?

For instance say I made a function

```
RotateTo(vec2 iPosition, float iTime);

```

so it rotates to `iPosition` over `iTime` \- how would this look? Does anyone know simple algorithm?

# Answer
> 4 votes
If you’re in 3D space it really depends on the axis on which you want to rotate. There are indefinite numbers of possibilities when you do not tell your function where it should rotate. With the current function signature there seem to be two possibilities:

* you rotate in 2D space
* you always want to rotate over the smallest distance

I can only give you a theoretical overview of how rotation can be done. As it seems real game programming uses other methods (see other answers and the comment below my text). However, I guess it still good to know as it is a first principle of rotating.

## Rotation over time

Rotation over time is simply a partial rotation each time step. You have to find out about which timespan you want to rotate and which time has elapsed since the last rotation performed. This will require at least 3 variables:

* rotation timespan
* elapsed time since last partial rotation
* angle to rotate

Of course we also need the position the vector is currently in:

* vector position

There are now two possibilities I currently see (when using rotation matrices). As I learned, quaternions would be better, because they do not suffer from that much error when doing many small rotations. Yet I think, there also is a method to minimize that with matrices.

There are different ways to go now. The ones I see:

* really use the time since last rotation and rotate n times by angle/n degree
* remember the time elapsed **since you started** and the **starting position** and do the rotation from there. This will eradicate error, as the final position will be like one rotation from the original position.

Let’s describe the second method.

You need to have a method that takes:

* original vector position
* target angle
* timespan to rotate
* elapsed time since rotation start

Then you can simply rotate by the following formula:

```
function rotateOverTime(vector, angle, timespan, elapsedTimeSinceStart):
    partialAngle = elapsedTimeSinceStart / timespan * angle;
    rotateZ(vector, partialAngle);

```

Note that with this method `vector` will always be the **original vector** (not taking into consideration the partial rotations) and `elapsedTimeSinceStart` is the since **since the beginning of all your rotations**.

The other method is to use the new vector position and onl the time since last rotation, but then you would accumulate error from small rotations and the rotation would not be a nice circle anymore.

## Rotation in 2D space

If you want a rotation in 2D space, you actually rotate around the z-axis (because you draw on x- and y-axis). In case your library has a RotateZ function implemented, you can use this. Otherwise, you can use **sin** and **cos**.

I do not know it in detail, but it should work something similar to this. Possible that it’s not the fastest and most elegant solution:

* Calculate the current angle of the vector. This can be done with `atan2()`
* The point around which you want to rotate is usually not (0,0), so you have to move your stuff so that it **seems** like that was the case (if the rotation center is e.g. (10,10) you have to subtract 10,10 from the point which shall be rotated)
* Multiply the new point (=vector; I will use both later, because in algebra you always talk about vectors) with a rotation matrix. I will show in more detail later what this is.
* Remove your point to the old location by adding the amount you have subtracted before (here 10).

I hope these images make my math talk a bit clearer ;)

We want to rotate the point (5,5) around (1,2) like the green circle indicates. But with matrices we would rotate around (0,0) as the purple circle shows.

To solve it, we move our point a bit left-down, then we can rotate it around (0,0) and then we move it back again. This moving-around is called **translation**. Actually my image sucks a bit here, the purple arrow which is going upwards should be the same diagonal as the first purple arrow. Remember, we move our point (-1,-2) down at first and then (1,2) up again. So my arrows are not that well.

I talked about **rotation matrix**. A rotation matrix is a matrix which you can multiply with your vector to achieve a rotation around the origin (0,0).

```
cos a     -sin a
sin a      cos a

```

Where *a* is the desired angle you want to rotate. This angle is determined by the number of frames you have like Philip has already shown. E.g. if you want it to be rotated in **2 seconds by 90°** and 1 second has passed since then, you would rotate it by 1/2 of the total rotation (=45°).

In this case your rotation matrix would look like this:

```
cos 45°     -sin 45°
sin 45°      cos 45°

```

Given this matrix, you can multiply it with your current vector to rotate it.

Let’s imagine your vector is (5, 7). This would give you (-1.414, 8.485) which is a rotation by 45° counterclockwise.

In case you need a rotation clockwise, you can just adjust the rotation matrix. Either by subtracting your rotation from 360 (e.g. 15° clockwise is 365° counter clockwise) or by using trgonometrical rules.

Let me mention that this always rotates around the **origin**. Usually you do not want to rotate around the origin in games, because the origin is some random point. In 2D programming it’s often the top-left point of either the whole world or the current viewport (camera). Higher level abstractions within your library usually use the **image’s origin** (top-left position), but that’s also not what’s often desired.

What can we do against this? The magic keyword here is **translation** and it means moving an object around. When rotating you have to make sure to move your object to a desired place for rotation, later you can move it back.

Imagine you have a point in 2D at (200, 300) world coordinates. Now you want to rotate it around (250, 250) by 50°. If you would just multiply (200, 300) with the rotation matrix (where you would set a = 50°), the point would be totally of the screen. Instead, move your point so that (250,250) equals (0,0). We would get our current point (200-250, 300-250) = (-50, 50). Now you can rotate this one! After the rotation you move your new point back again (+250).

## Rotation in 3D space

In 3D space you can rotate around an indefinite number of axises to reach one point from a given other point. However, the rotation will not always be the shortest. It can require some time to understand this, but just use your left and your right index finger as points in space. Now you can either make a turn upwards, a turn downwards, a turn frontwards, …

Thus we always need to know around which axis to turn when we are in 3D. Generally, you have the base rotations around X, Y and Z axis. Remember we used Z axis for 2D.

Maybe you remember I mentioned something about the shortest distance from the top. Actually, I am not totally sure if this is right, but I think I remember something from my linear algebra classes. According to what I think now, there should always be a shortest distance when rotating in 3D. Only when both vectors are not independant there is again an indefinite number of shortest distances, but let’s forget about this for now.

So if you do not have an axis to circle around, but want to determine one, you could go like this:

* Calculate the cross product of both vectors (points) =\> the result is a vector which is independant from both other vectors.
* Rotate around the newly vector as axis. This will give you the shortest rotation distance.
* Measure the angle between the two vectors (around the calculated axis). Can’t tell you at the moment how this could be done, but it’s not a hard compuation, you just have to know how ^\_^
* Normalize this vector (length = 1)
* Move your whole scene so that the point around which you want to rotate is the origin (0,0,0)
* Use a formula for rotation around axis and angle in 3D
* Remove your (rotated) scene back to the former position

Hope I could somehow help you, because it seems pretty difficult to me, but I wanted to explain in detail how rotating works.

# Answer
> 3 votes
Let's say you wanted it to spin 360 degrees in one second.

Let's also say that iTime determines how many seconds since the function was called. So if iTime was .01 then 1/100 of a second had passed since the last time the function was called.

Then you would use iTime / 360 to figure out how much rotation you'd need to apply.

# Answer
> 0 votes
As noted by others, you really don't have enough information there to do what you want. You need an axis to rotate around, a starting angle, and an ending angle.

However, given all of that, what you want to look up is slerp. Most APIs and engines will provide the calls you need to implement and construct what you're trying to achieve, but you haven't given enough information in your question to point you at any specific resources.

---
Tags: c++, rotation, timer
---


title: Set vertex position

text:
# Question
Title: Set vertex position
Can anyone tell me how to set the positions of model vertices? I want to be able to change the position of some of the vertices of a Model. Is there any way to make that happen? And make the changed visible at that moment.

---

**EDIT:** Well, the thing is,I have a model, a cube, that is made up of four "thin" cubes(top,bottom,left side, right side), so I get this cube with "hole" in the middle. And I want to scale it on **Y** axis. If I do `Scale(0,2,0)` it will scale the whole object meaning, it will double the **Y** size of left and right side, but also double the size of the top and bottom cube, which I do not want. Same for **X** axis I want to double the size of top and bottom cubes but not the left and right one.

Hope you can help

# Answer
You generally don't want to manipulate the vertices of the model objects to move them around in your world.

Instead, you set the world transformation matrix (that you pass to Draw) accordingly, for example setting it to a translation matrix that moves the model by the desired amount.

That said, if you really want to manipulate the vertices directly -- perhaps because you only need a subset to change, or infrequently, you can iterate the Parts collection of the Meshes collection of the model. Each mesh part has a vertex (and index) buffer object you can use to update the model.
> 4 votes

# Answer
Since you say you want to move *some* vertices...

Assuming you do simply want to move the vertices in object space, you would need to reupload them to the graphics card (however XNA handles this).

Or else apply a transformation to a particular *set* of vertices (eg. if you are moving an arm or a leg). That would require some method of identifying only those vertices which are intended to move, in your shader code... this can be done using vertex IDs, possibly.
> 2 votes

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


title: How to do geometric projection shadows?

text:
# Question
Title: How to do geometric projection shadows?
I have decided that since my game world is mostly flat I don't need better shadows than geometric projections - at least for now.

The only problem is I don't even know how to do those properly - that is to produce a 4x4 matrix which would render shadows for my objects (that is, I guess, project them on a horizontal XZ plane).

I would like a light source at infinity (e.g., the sun at some point in the sky) and thus parallel projection.

My current code does something that looks almost right for small flying objects, but actually is a very rude approximation, as it doesn't project the objects onto the ground, but simply moves them there (I think). Also it always wrongly assumes the sun is always on the zenith (projecting straight down).

```
    Gdx.gl20.glEnable(GL10.GL_BLEND);
    Gdx.gl20.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);

//shells

    shellTexture.bind();
    shader.begin();
    for (ShellState state : shellStates.values()) {
        transform.set(camera.combined);
        transform.mul(state.transform);

        shader.setUniformMatrix("u_worldView", transform);
        shader.setUniformi("u_texture", 0);

        shellMesh.render(shader, GL10.GL_TRIANGLES);
    }
    shader.end();

// shadows
    shader.begin();
    for (ShellState state : shellStates.values()) {
        transform.set(camera.combined);
        m4.set(state.transform);

        state.transform.getTranslation(v3);
        m4.translate(0, -v3.y + 0.5f, 0); // TODO HACK: + 0.5f is a hack to ensure the shadow appears above the ground; this is overall a hack as we are just moving the shell to the surface instead of projecting it on the surface!
        transform.mul(m4);

        shader.setUniformMatrix("u_worldView", transform);
        shader.setUniformi("u_texture", 0); // TODO: make shadow black somehow

        shellMesh.render(shader, GL10.GL_TRIANGLES);
    }
    shader.end();

    Gdx.gl.glDisable(GL10.GL_BLEND);

```

So my questions are:

a) What is the proper way to produce a Matrix4 to pass to openGL which would render the shadows for my objects?

b) I am supposed to use another fragment shader for the shadows which would paint them in semi-transparent grey, correct?

c) The limitation of this simplistic approach is that whenever there is some object on the ground (it is not flat) the shadows will not be drawn, correct?

d) Do I need to add something very small to the y (up) coordinate to avoid z-fighting with ground textures? Or is the fact they will be semi-transparent enough to resolve that problem?

# Answer
> 4 votes
(a) To produce a "squash" matrix that smashes things to the ground plane parallel to a given sun vector, I would build it by composing two matrices:

1. A shear matrix that maps the sun vector to +Y (straight up) while leaving the X and Z axes unchanged.
2. A scaling matrix that scales Y by zero while leaving X and Z unchanged.

Specifically, assuming you're using column vectors (since that's the usual OpenGL convention), after multiplying, this comes out to be:

```
[ 1 (-sun.x / sun.y) 0 0 ]
[ 0         0        0 0 ]
[ 0 (-sun.z / sun.y) 1 0 ]
[ 0         0        0 1 ]

```

where `sun` is the vector pointing toward the sun. I assume it is always in the upper half of the sky, i.e. sun.y \> 0.

(b) There are various things you could do here. Drawing the squashed shadow geometry in semi-transparent black or gray is one possibility. If you do this, you should also use the stencil buffer to ensure that each pixel is darkened only once. (For instance, configure the stencil test to pass if stencil == 0, and write 1 to the stencil buffer when a shadow pixel is drawn.) Otherwise you'll get multiple darkening where there are multiple "layers" of the squashed object.

Another possibility is to do additive ambient and directional light passes, and use the stencil buffer to mask out the directional light whereever there are shadows.

(c) Correct.

(d) Yes, z-fighting is likely to be an issue here. You could add a small y-offset, or perhaps better, use hardware polygon offset.

---
Tags: matrix, libgdx, projection, shadows, transformation
---


# Question
Title: Is 1 pixel of a height map representative of 1 vertex on the mesh?
I'm trying to get my head around heightmap terrain generation. If I have a plane say 64 x 64 verts will I need to create a 64px by 64px greyscale heightmap in order to displace the geometry of the plane correctly?

# Answer
> 13 votes
You may be confusing some details. A height map is simply a 2D array of data. Each point represents 3 pieces of information: an `x` and `y` location and a number to represent the height at that point. For a simpler example, lets look at a 1D array of data that creates some 2D terrain. Each data point here will contain an `x` location and a number to represent the height at that point:

Pretty simple right? It's just a regular old graph. As you can see, the numbers on the x axis go up by tens. We could easily change that to go up by 100's or by .01's. Same goes for the data displayed on the y axis. We can scale those values however we like.

Basically, it's just numbers until you decide how you're going to visually represent it. So, saying a height map of 64px by 64px is already one step beyond where we need to go. Since a grayscale image is just another way to display the same data as a 3D height map. The data to represent each is coming from the same place.

Further, you don't even need a 1 to 1 relationship between data and display. You could have far more vertices than you have data points, or far fewer. They don't even need to be equally spaced.

**For the most basic example:** Yes, generate an array of `[64][64]` data points to make a grayscale image or a 3D heightmap. Each `[x][y]` of your array will correspond to the `x`, `y` of your vertices and the value stored in each `[x][y]` will represent the `z` value of your vertex.

---
Tags: terrain, heightmap
---


title: Texturing a Sphere in libGDX

text:
# Question
Title: Texturing a Sphere in libGDX
I created a sphere (planet) with a texture (earth texture) in Blender, and exported it using the G3DT exporter. Then when I go to use it in my application I convert to the G3D binary format, and load my texture. When I render my sphere each face contains the texture. It is not wrapping around my whole sphere like it was in Blender. Any ideas what I'm doing wrong?

# Answer
My problem ended up being the way that Blender exported my model. I changed the export to just a .obj and re-created my model following this guide and everything is mapping correctly now.
> 1 votes

---
Tags: opengl, android, libgdx
---


# Question
Title: How can I get the palette of an 8-bit surface in SDL.NET/Tao.SDL?
I'm looking to get the palette of an 8-bit surface in SDL.NET if possible, or (more than likely) using Tao.SDL. This is because I want to do palette swapping with the palette directly, instead of blitting surfaces together to replace colours like how you would do it with a 32-bit surface.

I've gotten the SDL\_Surface and the SDL\_PixelFormat, however when I go to get the palette in the same way, I get a System.ExecutionEngineException:

```
private Tao.Sdl.Sdl.SDL_Palette GetPalette(Surface surf)
{

// Get surface.
Tao.Sdl.Sdl.SDL_Surface sdlSurface = (Tao.Sdl.Sdl.SDL_Surface)System.Runtime.InteropServices.Marshal.PtrToStructure(surf.Handle,
    typeof(Tao.Sdl.Sdl.SDL_Surface));

// Get pixel format.
Tao.Sdl.Sdl.SDL_PixelFormat pixelFormat = (Tao.Sdl.Sdl.SDL_PixelFormat)System.Runtime.InteropServices.Marshal.PtrToStructure(sdlSurface.format,
    typeof(Tao.Sdl.Sdl.SDL_PixelFormat));

// Execution exception here.
Tao.Sdl.Sdl.SDL_Palette palette = (Tao.Sdl.Sdl.SDL_Palette)System.Runtime.InteropServices.Marshal.PtrToStructure(pixelFormat.palette,
    typeof(Tao.Sdl.Sdl.SDL_Palette));

return palette;
}

```

When I used unsafe code to get the palette, I got a compile time error: "Cannot take the address of, get the size of, or declare a pointer to a managed type ('Tao.Sdl.Sdl.SDL\_Palette')".

My unsafe code to get the palette was this:

```
unsafe
{
    Tao.Sdl.Sdl.SDL_Palette* pal = (Tao.Sdl.Sdl.SDL_Palette*)pixelFormat.palette;
}

```

From what I've read, a managed type in this case is when a structure has some sort of reference inside it as a field. The SDL\_Palette structure happens to have an array of SDL\_Color's, so I'm assuming that's the reference type that is causing issues. However I'm still not sure how to work around that to get the underlying palette.

So if anyone knows how to get the palette from an 8-bit surface, whether it's through safe or unsafe code, the help would be greatly appreciated.

# Answer
Maybe this can help you:

http://www.libsdl.org/docs/html/sdlsurface.html

On the documentation, the struct SDL\_Surface have an attribute SDL\_PixelFormat \*format. And the struct SDL\_PixelFormat have an attribute SDL\_Palette \*palette. I think you just need to do this:

```
SDL_Surface* targetSurface;
SDL_Palette* myPalette = targetSurface->format->palette;

```
> 1 votes

---
Tags: c#, image, palette
---