# Question
Title: Camera field of view: 3D projections & trigonometry
Okay, here goes.

I have a camera at (Xc, Yc, Zc.) The Xc and Yc coordinates are latitude/longitude, and the Zc coordinate is an altitude in metres. I have a point at (Xp, Yp, Zp) and a field of view on the camera (Th1, Th2) - where Th1 is horizontal FOV and Th2 is vertical FOV.

Given this information, I'd like to:

* test if the point is visible (i.e. in the camera's FOV)
* project the point as the camera would see it

I've figured out already that the camera's horizontal view at any given distance is tan(Th1) * distance, but I don't know how to test if the point is visible.

Accuracy is not critical. I would prefer a simple solution over a complicated solution, if it works well enough. The computations will be performed by a small microcontroller, which isn't very fast at things like trig functions.

P.S. this is not homework, I'm doing this for some game development. It will be integrated with the real world, hence the latitude/longitude/altitude. It involves flying real RC planes through virtual hoops (or chasing virtual targets), so I have to project the positions of these hoops on a display.

# Answer
You're missing some information - you've haven't got the direction that the camera is facing. I normally represent this by a matrix, but you could use axis/angle or quaternion representations too. So, assuming you already have a matrix M\_view that takes a world-space point and converts it into a view space point, you can easily do it without any trig or floating point divides. My thoughts are this:

* project point into view space. Ie. P\_view = M\_view * P\_world.
* calculate the horizontal view span size given the depth of P\_view (ie. P\_View.z * absTanTH1)
* calculate the vertical view span size given the depth of P\_view (ie. P\_view.Z * absTanTH2)
* check whether P\_view.xy are within both horizontal and vertical spans.

In the end you should have a function that looks like this:

```
bool isPointInFrustum(vec3& P_view, float absTanTH1, float absTanTH2)
{
  if (P_view.z < 0.0 ||                          // point is behind camera
      abs(P_view.x) < (absTanTH1 * P_view.z)) || // point is outside horizontal planes of frustum
      abs(P_view.y) < (absTanTH2 * P_view.z))    // point is outside vertical planes of frustum
    return false;
  return true;
}

```

absTanTH1/TH2 are pre-calculated constants, computed like this:

```
  absTanTH1 = abs(tan(TH1));
  absTanTH2 = abs(tan(TH2));

```
> 3 votes

# Answer
I am facing the exact same kind of problematic, so I was happy to find that post, but things remain a little confusing to me.

I do not understand how the conversion from M\_View to P\_View works.

Here what I have \- the absolute 6d position of the camera (x,y,z,wx,wy,wz) and its fields of view \- the absolute 3d position of a point

I would like : to know of the point is in the field of vision of the camera

I understood how to answer this question once I have P\_View, but I do not get how the conversion takes place ...

Thanks a lot
> 0 votes

---
Tags: 3d, camera
---


title: why specular light is not running?

text:
# Question
Title: why specular light is not running?
this is my method for lighting:

```
private void lights(GL gl) {
    float[] LightPos = {0.0f, 0.0f, -1.0f, 1.0f};
    float[] LightAmb = {0.2f, 0.2f, 0.2f, 1.0f};
    float[] LightDif = {0.6f, 0.6f, 0.6f, 1.0f};
    float[] LightSpc = {0.9f, 0.9f, 0.9f, 1.0f};

    gl.glLightfv(GL.GL_LIGHT1, GL.GL_POSITION, LightPos, 0);
    gl.glLightfv(GL.GL_LIGHT1, GL.GL_AMBIENT, LightAmb, 0);
    gl.glLightfv(GL.GL_LIGHT1, GL.GL_DIFFUSE, LightDif, 0);
    gl.glLightfv(GL.GL_LIGHT1, GL.GL_SPECULAR, LightSpc, 0);

    gl.glLightfv(GL.GL_LIGHT0, GL.GL_SPECULAR, LightSpc, 0);

    gl.glEnable(GL.GL_LIGHT0);
    gl.glEnable(GL.GL_LIGHT1);
    gl.glShadeModel(GL.GL_SMOOTH);
    gl.glEnable(GL.GL_LIGHTING);
}

```

and i see my objects flat, no specular light.. any ideas?

ps. to render my objects:

```
gl.glColor3f(1f,0f,0f);
gl.glBegin(GL.GL_TRIANGLES);
for(Triangle t : tubeModel.getTriangles()) {
    gl.glVertex3f(t.v1.x, t.v1.y, t.v1.z);
    gl.glVertex3f(t.v2.x, t.v2.y, t.v2.z);
    gl.glVertex3f(t.v3.x, t.v3.y, t.v3.z);
}
gl.glEnd();

```

this is what i'm looking for:

this is what i get:

well it's not all black but if i rotate it becomes grey-white

# Answer
You have to set up material.
Enable material:

```
glEnable(GL_COLOR_MATERIAL);

```

Set ambient and diffuse to read from what you set in glColor:

```
glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE);

```

Setup specular. For complete specular you have to have defined specular reflective color and shinines.

```
float specReflection[] = { 0.8f, 0.8f, 0.8f, 1.0f };
glMaterialfv(GL_FRONT, GL_SPECULAR, specReflection)
glMateriali(GL_FRONT, GL_SHININESS, 56);

```

Shinines is between 1 - 128. Bigger value = more bright.

You can find more help on these links:
http://www.falloutsoftware.com/tutorials/gl/gl8.htm
http://www.ozone3d.net/tutorials/glsl\_lighting\_phong.php
> 1 votes

# Answer
Agree with notabene's answer, material needs to be specified.

But for correct lighting (diffuse and specular) you will also need to specify a normals for each vertex. Although the default normal may create (incorrect) specular reflections.

```
glNormal3f(x,y,z);

```
> 2 votes

---
Tags: opengl, lighting
---


# Question
Title: What's wrong with this OpenGL model picking code?
I am making simple model viewer using OpenGL. When I want to pick an object OpenGL returns nothing or an object that is in another place.

This is my code:

```
GLuint buff[1024] = {0};
GLint hits,view[4];

glSelectBuffer(1024,buff);
glGetIntegerv(GL_VIEWPORT, view);

glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
gluPickMatrix(x,y,1.0,1.0,view);
gluPerspective(45,(float)view[2]/(float)view[4],1.0,1500.0);

glMatrixMode(GL_MODELVIEW);
glRenderMode(GL_SELECT);

glLoadIdentity();
//I make the same transformations for normal render
glTranslatef(0, 0, -zoom);
glMultMatrixf(transform.M);
glInitNames();
glPushName(-1);
for(int j=0;j<allNodes.size();j++)
{
    glLoadName(allNodes.at(j)->id);
    allNodes.at(j)->Draw(textures);
}
glPopName();
glMatrixMode(GL_PROJECTION);
glPopMatrix();
hits = glRenderMode(GL_RENDER);

```

# Answer
> 3 votes
Do you have an ATI card? I think they deprecated some portions of OpenGL (picking included) a long time ago.

# Answer
> 3 votes
OpenGL picking using the selection buffer is deprecated. If your scene is small enough, you should use colour-based picking; otherwise, you can use gluUnProject to obtain a world coordinate from a mouse coordinate and a depth read from the depth buffer using `glReadPixels()`.

# Answer
> 0 votes
No one use OpenGL picking this days, you have to implement it yourself. Transforming from camera to worlds space is a bit tricky, here is a good article http://trac.bookofhook.com/bookofhook/trac.cgi/wiki/MousePicking

# Answer
> 0 votes
Ok, but for 3d viewer application opengl isn't better ? My doesn't work, beacouse I have two mistakes: **1.**

```
gluPerspective(45,(float)view[2]/(float)view[3],1.0,1500.0);

```

**2.**

```
gluPickMatrix(x,view[3]-y,1.0,1.0,view);

```

So it is looking that picking still works on ati, my friend said my that picking can be making by software implementation of opengl.

---
Tags: c++, opengl, graphics-programming
---


# Question
Title: Beginner question about vertex arrays in OpenGL
**Is there a special order in which vertices are entered into a vertex array?** Currently I'm drawing single textures like this:

```
glBindTexture(GL_TEXTURE_2D, texName);
glVertexPointer(2, GL_FLOAT, 0, vertices);
glTexCoordPointer(2, GL_FLOAT, 0, coordinates);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

```

where vertices has four "xy pairs". This is working fine.

As a test I doubled the sizes of the vertices and coordinates arrays and changed the last line above to:

```
glDrawArrays(GL_TRIANGLE_STRIP, 0, 8);

```

since vertices now contains eight "xy pairs". I do see two textures (the second is intentionally offset from the first). **However the textures are now distorted**. I've tried passing GL\_TRIANGLES to glDrawArrays instead of GL\_TRIANGLE\_STRIP but this doesn't work either. I'm so new to OpenGL that I thought it's best to just ask here :-)

Cheers!

# Answer
You've got the two quads joined by the tri-strip. You could either do two separate glDrawArrays with the first being (0,4) and the 2nd being (4,4) to split the two quads up, or as you say, do triangles instead.

If you switch to triangles then you'll need to either duplicate up vertices, or if you use indices to index, you'll need to specify the 3 corners of each triangle.

Tri-strips work by taking the first 2 vertices specified then draw a triangle to the 3rd. Subsequently every extra vertex results in another triangle where it makes a triangle using the last 2 vertices and the new vertex. Some platforms support providing an index value allowing you to "reset" the tri-strip and effectively allowing you to split a sequence into multiple tri-strips with a single call.
> 3 votes

---
Tags: opengl, iphone, vertex-arrays
---


# Question
Title: Ray-plane intersection to find the Z of the intersecting point
I have a rectangle in 3d space `(p1, p2, p3, p4)` and when the mouse rolls over it I need to calculate the exact Z of the point on the rect, given the mouse coordinates `(x, y)`.

Would a Ray-plane intersection find the Z of the intersecting point?

---

**Edit:** Would this one-liner work? .. it returns the `t` value for the intersection, apparently the Z value.

```
 float rayPlane(vector3D planepoint, vector3D normal, vector3D origin, vector3D direction){

     return -((origin-planepoint).dot(normal))/(direction.dot(normal));
 }

```

# Answer
> 4 votes
If you dont mind using your rect as two triangles, here is the code from my (working) raytracer:

```
//RAY-TRAINGLE test
Vec3f e1 = p2 - p1;
Vec3f e2 = p3 - p1;
Vec3f s1 = cross(aRay.dir, e2);

float divisor = dot(s1, e1);
if (divisor == 0.)
 return false; //not hit

float invDivisor = 1.f / divisor;

// Compute first barycentric coordinate
Vec3f d = aRay.org - p1;

float b1 = dot(d, s1) * invDivisor;
if (b1 < 0. || b1 > 1.)
 return false; // not hit

// Compute second barycentric coordinate
Vec3f s2 = cross(d, e1);
float b2 = dot(aRay.dir, s2) * invDivisor;
if (b2 < 0. || b1 + b2 > 1.)
 return false;

// Compute _t_ to intersection distance
float t = dot(e2, s2) * invDivisor; /// << HERE you go.
Vec3f intersection = aRay.org + t*aRay.dir;

```

---
Tags: 3d, raycasting, coordinates
---


title: Tips for creating great game trailers

text:
# Question
Title: Tips for creating great game trailers
Impressive trailers for your game can really help show players how awesome your game is, but I'm having trouble finding tips that describe how to create a great trailer. I would like to learn about the best way to decide trailer length, structure, music/sound, and content. Basically, what parts of my game do I show in a trailer, how should the scenes be organized, and how would you do the sound?

Any advice on things to avoid would be great as well; for example, I read that splicing some video, switching to a screen with text, switching back to video, etc., probably isn't the best way to do it. Thanks!

# Answer
> 13 votes
Obviously there's no one answer to a question like this, because it depends on your audience. And that's part of the answer - you need to tailor your trailer to your audience or they won't see why they should like the game.

You also need to tailor the trailer to the type of game. If you are showing a real-time strategy game, no one is going to want to see more than a couple seconds of building your initial base.

Here are some things I think you should keep in mind:

* Length - I wouldn't have a trailer any longer than 2.5 minutes, because if it takes longer than that it becomes a gameplay video and you've failed at accomplishing what a trailer is supposed to do in the time it's supposed to do it in.
* Audio - Use music that represents the aesthetic of your game. If your audience likes that music, they're closer to giving your game a try. Try to stick with one song or have very smooth transitions between sounds, unless you are trying to jar your audience on purpose (which might be something you want to do, although you've got to be careful)
* Video - Capture scenes (images/video) of varying length that represent the core gameplay. Quick, few-second bursts of many of these types of scenes tell the viewer both that the gameplay is stimulating, as well as make it seem as though there is a vast amount of content to explore the gameplay in. Don't misrepresent your content, or you'll create disappointment. I think it's essential to have the majority of your content be video or it will be boring and more importantly, not represent your content well.
* Text - If you have to use text, I'd put it next to gameplay/screenshots or directly over it - a title card at the beginning and some lone text at the end is acceptable. I don't know how others feel about this one. Don't have 30 seconds of different text cards before you show gameplay. Everyone knows how to create text videos in Windows Movie Maker, and no one wants to read it when they're trying to understand what your game plays, looks, and sounds like.
* Pacing - I think the most important thing you need to worry about with pacing is accurately representing the pace of your game. Don't have a light-speed trailer for a slow, methodical puzzle game. Try to keep your cuts and such in sync with music as much as possible - even if it's not an obvious synchronization viewer subconscious will fare better if the audio and video components are even mildly concerned with each other.
* Random thought - If you can illustrate the entire game with one scene of varying action or complex puzzle solution, if it isn't more than a minute or two it could be a fantastic teaser. Think advertising Portal with one puzzle - the viewer is almost overwhelmed with how interesting the concept is on initial viewing.

Hope that helps at least a bit.

# Answer
> 3 votes
I'm not a film guy, so I'm afraid I can't give many specific tips about that, but if you're trying to generate buzz, make three or so and roll them out over time. Make sure you have a coherent theme, (presumably you've got one or two gameplay elements to show off that show well visually, I'd emphasize those), and maybe even make a single longer trailer and chop that up.

The unsung note is the sweetest, so don't show stuff that looks bad and hide your week spots. Crank the resolution up all the way if you're doing screen grabs. Audio can help a ton for giving things feeling (not just music, but good hit sounds etc.).

Good luck!

# Answer
> 3 votes
I just noticed this article today on creating good game trailers, and thought it would be useful to link it as an answer to this question.

---
Tags: marketing, trailer
---


# Question
Title: What happens to allocated video memory when the program terminates?
Using OpenGL it is possible to load textures, buffer arrays, compiled shaders and more to the video memory. When a C++ program exits, heap memory that was allocated by it is cleaned. What happens to the stuff allocated on the video memory? Will memory leak beyond program's scope?

# Answer
> 2 votes
Your question was answered on SO:

https://stackoverflow.com/questions/2215088/opengl-gpu-memory-cleanup-required

Basically the answer is when your program exits, the memory should be cleared, so you will not have leaks.

You can test this by opening/closing multiple instances of your program without freeing the resources and verifying that your video memory usage stays the same.

However, as also mentioned in the link, you should of course get into the habit of freeing resources when they are no longer needed.

# Answer
> 0 votes
No. If the driver is written correctly, everything should be cleaned up just fine.

At least that's the theory. Drivers are rarely written 100% correctly; you may find on particular models of video cards, on particular OSs, you need to do some manual cleanup.

---
Tags: 3d, c++, opengl, software-engineering
---


# Question
Title: Ogre3D how to use many images in a particle system
In the example I found, it usually uses one images for a particle system. Is it possible to use multiple images in a system?

# Answer
> 5 votes
Particle system can only use one material type. The particle system can, however, alter the tint and transparency (obviously) of specific particles as well as have an arbitrary number of emitters. To get more complex effects, however, you will need to combine different systems.

# Answer
> 2 votes
I do not have experience with Ogre3D specifically but maybe you can make a texture with multiple images inside and replace the UV's matching the image you want?

# Answer
> 1 votes
You can write wrapper around your Ogre particle system which represents internally two particles systems with the same parameters but with different images, and call it instead direct call of Ogre3d Api.

---
Tags: ogre, particles
---


# Question
Title: Changing Palette for Day/Light Mode using GIMP
Suppose I've a picture, which want to achieve day/light mode by changing 8bpp color palette.

If I want the pixel index of my picture is always fixed for both day mode and night mode. For example, the 1st pixel index is 100. Which I can look up index 100 in day mode palette and night mode palette. How can I use GIMP to do so? My goal is to not update my pixel index of my picture.

Also, as you see in two palette, they are not one one mapping. That is index 1 of the day mode palette and index 1 of the night mode palette may not used in the same pixel of the picture, how can I tackle this problem?

Actually, my use case is as follow I want to use one 8bpp picture to achieve day/night mode by update only the color palette (without updating the pixel index). The advantage is I only have to prepare 2 256 byte palette rather than saving 2 big pictures in my limited data ram.

Thanks a lot

# Answer
> 0 votes
When I want to change the color balance on an entire image like is being done in the example, I tend to use the Color Balance tool, which is one of the simplest ways the shift colors throughout a selected area.

There are also a few other tools that you can use to fine tune the color in your images.

---
Tags: gimp
---


title: Collision filtering by object, team

text:
# Question
Title: Collision filtering by object, team
I am looking for a good method to determine which objects will be considered for collision with other objects.

My current idea is that each object has the following properties:

alwaysCollidesWith = \[list of objects that will always trigger a collision check\] neverCollidesWith = \[lost of objects that will never be considered\] teamCollidesWith = \[list of objects that will be checked, provided they belong to a different team\]

For example: -projectiles never have to be checked for collisions with other projectiles -players are always checked for collisions with players, regardless of team -projectiles are only considered for collisions if they collide with another teams players

Does anyone see any weaknesses with this approach? Can anyone recommend a better approach?

# Answer
> 7 votes
The problem I see with your approach is that it doesn't scale very well. For every object, you are storing relations with all the objects that collide with it. If you only have 2 players and a 10 proyectiles, it will work ok. But when that number increases to, say, 20 players and 100 proyectiles, then the number of relations increases exponentially. It'll gradually run more slowly and consume more memory when the number of players increases.

You would be better off by organizing your objects into "groups". And then adding collision/non-collision relationships between each object and those groups. The memory consumption will be slower, and the checks will be faster.

Box2D has a fairly flexible system set up for that.

First, there's categories and masks:

1. Shapes can have up to 16 "categories" (it's really a 16-bit mask). By default, they are on category "1"
2. Shapes can also have a "mask" that defines with what categories they can collide. By default, they collide with category "1" only.

Then, there's also groups. A group is an integer.

1. Two shapes with the same group will always collide, if the group is positive.
2. Two shapes with the same group will never collide, if the group is negative.
3. Group rules override mask and category rules.

With these two things, the question "do these two objects collide?", filtering is very fast (a bitmask operation and an integer comparison) and has a very small memory footprint (4 bytes per object).

In your example:

* Players would have category 1, and mask {1,2} (so they collide with all projectiles by default)
* Projectiles would have category 2, and mask {1} (they only collide with players)
* Players and projectile of team 1 would all be in group -1, and team 2 would have the group -2. This way, friendly fire would not happen.

The most recent tutorial that I could find is from 2009 - here it is:

http://www.emanueleferonato.com/2009/10/01/introducing-box2d-filtering/

You can also browse the box2d manual \- scroll down until it says "Filtering"

---
Tags: collision-detection, optimization
---


# Question
Title: How are potentially visible sets (PVS) determined in state of the art games?
As I understand it, potentially visible sets (PVS) are used to determine 2 things; 1. which objects are inside the camera's view volume 2. which objects are not occluded (hidden) from the camera's point of view.

I understand that things like octtrees & BSP trees have been used for PVS calculation in the past, but how are PVSs calculated in today's AAA titles?

# Answer
> 9 votes
If you ask 5 game developers you may well get 5 different solutions or overlapping answers. The system to go for depends a lot on the type of game and the environment you exist in. There's also the divide between offline and real-time solutions. There's also no reason why octree and BSP tree solutions aren't also still used in certain scenarios.

Personally, for what I've worked on (racing games) we've used a pre-calculated static visibility system where offline we divide the world up into a grid, then we move the camera around inside the grid cell checking to see what it can see at a fairly coarse level. What we end up with is for every cell we have a bit list which says which models definately are not visible to the camera from that location. Once in game, we can very quickly get a subset of the world from which we can frustum cull to work out what we actually need to render in front of the camera.

Another title here uses a combination of that and portals, where you effectively have a door through which you can determine if you can see whats on the other side. If you can't see the door, you don't need to worry what's on the other side.

A real-time system that I've seen used (but have no personal experience of) is dPVS, which performs occlusion testing in real-time (they've got a paper linked from their website on how it works).

It all depends on what you need, different systems also allow you trade a bit of extra memory for speed.

---
Tags: graphics, graphics-programming, binary-space-partitioning
---


title: xna download website source code

text:
# Question
Title: xna download website source code
I have to download the html code of a web site during the game. I am taking the poster url of a movie from the imdb web site by scrapping the html ( also other informations ). I have to do the download process many times during the game for different movies. I can download and scrap the html but downloading the html takes too much time and it causes the game to slow down(freeze while downloading). How can I solve this problem? My one approach is to download and scrap all the information and store them in a database before the game and during the game access this information from the database. I think this will work properly but that is not what I exactly want. It would be better if it is dynamic. I also thought of using multi-threading but I am a bit confused about how to implement threading in xna. I read some articles about it but it is not so clear. I mean when should I start the thread and what about the update function etc. I need your help guys

# Answer
> 4 votes
Creating a thread for your downloading operation will solve the problem. It means your game will create thread every time that you need download, than thread runs in parallel independently with download and after downloading is done, thread ends. Make thread for every download you need (so they can run in parallel too).

---
Tags: xna, multithreading
---


title: Rendering with Direct3D

text:
# Question
Title: Rendering with Direct3D
I'm slightly confused about how Direct3D rendering works. Basically, as long as I render to one surface, everything is fine. But when I try rendering to multiple surfaces, it seems like everything is still rendered to one surface. I think there's something wrong with my calls.

For each update cycle this is what I do 1. device-\>BeginScene() 2. sprite-\>Begin(...)

... A bunch of GetRenderTarget to store the old render target, then SetRenderTarget to set a new surface, and then things like CreateVertexBuffer, SetTexture, etc to draw on the new render target. Then resetting to the old render target.

1. sprite-\>Draw(\[the back buffer\]) (the back buffer is actually another surface, not the actual back buffer. But here it is being drawn onto the actual back buffer, I think)
2. sprite-\>End()
3. device-\>EndScene()
4. device-\>Present(...)

Also, it seems like if I mix sprite drawing and non-sprite drawing onto a surface, that first one set of render commands is executed and then the other set, rather than in order by when each command was called.

If anyone could shed light on any of this, it would be much appreciated.

EDIT: To clarify, my render targets are mainly surface 0 of the texture created by D3DXCreateTexture or D3DXCreateTextureFromFileEx.

# Answer
> 5 votes
It sounds like the bulk of what you're doing when you say "... A bunch of GetRenderTarget to store the old render target, then SetRenderTarget to set a new surface, and then things like CreateVertexBuffer, SetTexture, etc to draw on the new render target. Then resetting to the old render target." is actually stuff that needs to be done outside of a BeginScene()/EndScene() block. Certainly you shouldn't be creating vertex buffers in there, in the general case (just for performance concerns).

Depending on what the render targets are, and how you're creating and setting them, you may need to doing one BeginScene/EndScene per target, and not shoving them all into a single scene.

I assume you're clearing the render targets before you start drawing, too.

Have you enabled the D3D debug runtimes (via the D3D "Control Panel" in the DX SDK's start menu folder, under the utilities or tools subfolder)? They will cause useful diagnostics to be printed to the output window in VS while you debug.

There are a few multiple-render-target samples in the SDK, too, and probably a few online (although they may deal with multiple swap chains, which isn't what you're done I don't think?)

# Answer
> 4 votes
The name "Draw" is somewhat misleading. It should better be called "AddToBatch". What it actually does is batch your Draw calls. Only when you call ID3DXSprite::Flush or Id3DXSprite::End it fills the sprites into one big vertex buffer and renders that onto the current render target.

So if you want to switch render targets in between, you will have to do something along these lines (pseudo-code):

```
Scene->Begin()

Device->SetRenderTarget( FirstTarget )
  Sprite->Begin()
  for each sprite to draw onto first target
    Sprite->Draw()
  Sprite->End()

Device->SetRenderTarget( SecondTarget )
  Sprite->Begin()
  for each sprite to draw onto second target
    Sprite->Draw()
  Sprite->End()

Scene->End()

```

---
Tags: directx, directx9
---


# Question
Title: What is the contents of the buffer *after* a call to glSwapBuffers()?
(`SDL_GL_SwapBuffers()` in particular)

When you have drawn a scene, and you call swap-buffers, it is routine to then `glClear()` the scene before drawing anything; if you ***don't*** clear, what is the contents of the buffer? Is this defined by any specification, or does it vary by driver?

# Answer
> 13 votes
The details of how to swap the front and back buffer vary from platform to platform, and so the answer is platform-dependent.

According to the GLX glXSwapBuffers reference documentation:

> The contents of the back buffer become undefined after a swap. Note that this applies to pixel buffers as well as windows.

However, there exists the GLX\_EXT\_buffer\_age extension:

> The aim of this extension is to expose enough information to applications about how the driver manages the set of front and back buffers associated with a given surface to allow applications to re-use the contents of old frames and minimize how much must be redrawn for the next frame.

But Win32 SwapBuffers only says:

> If the current pixel format for the window referenced by this device context includes a back buffer, the function exchanges the front and back buffers... If the current pixel format for the window referenced by the device context does not include a back buffer, this call has no effect and the content of the back buffer is undefined when the function returns.

And CGLFlushDrawable, for OS X Core Graphics says:

> If the backing store attribute is set to false, the buffers can be exchanged rather than copied. This is often the case in full-screen mode. If the receiver is not a double-buffered context, this call does nothing.

Finally, in OpenGL ES standard buffer-swapping function eglSwapBuffers:

> The color buffer of surface is left undefined after calling eglSwapBuffers.

So what does all this mean?

* To be truly cross-platform, you can't assume anything about the back buffer after a swap. Its content is undefined, and you should probably glClear or otherwise fix it up before using it.
* If you are using Linux, you can check for the buffer age extension. Because a system might be triple buffered you may have to keep track of multiple frames worth of damage and deal with that.
* If you are using OS X, you might get copied, and you might get an exchange. So you can assume that the contents of the backbuffer is not garbage, but you don't control whether it's the frame you just sent or the one before that.
* If you are only targeting Win32 and are *sure* you have a back buffer, you can presumably assume its contents are now what was in the front buffer. (Although this is an assumption from omission rather than explicitly stated; I would not be surprised if it doesn't work on many/any configurations.)

Given the constraints of GLX and CGL, and a desire to minimize changes between OpenGL and OpenGL ES, you might as well just assume the contents are garbage.

# Answer
> 1 votes
From what i have read the only behaviour is UNDEFINED. So i would assume there is no guarantee to what will be the contents of the buffer. Not to mention that some libs actually wrap a clear call into the swap buffers call.

# Answer
> 0 votes
The behavior is UNDEFINED, so if you're going to fill the whole screen anyway, you may consider dropping the clear.. except, on some environments (certain tiling architectures at least), that will actually degrade performance. The full screen clear at the start of rendering is so common operation that I'd be surprised if it wasn't optimized well on all target platforms.

Reason why it's UNDEFINED is that for many architectures, making the content state defined would be an extra overhead, regardless of how you'd define the standard.

As to what you'll find there, I can take a guess based on experience;

On double (or multi-) buffered architectures, like most desktop PC video hardware, you'll likely find the "other" buffer data. This is not guaranteed though, as it's not in the spec, if some weird optimization benefits from it, they will garble the data.

On tiled architectures, you might find the same data as the last frame, some oddly garbled data based on the tile size, or just about anything else.

Then you have some oddball architectures (like the NDS) which might give you just about anything, as their definition of the buffer isn't exactly what you'd expect.

---
Tags: opengl, sdl, double-buffering
---


title: how to do partial updates in OpenGL?

text:
# Question
Title: how to do partial updates in OpenGL?
It is general wisdom that you redraw the entire viewport on each frame.

I would like to use partial updates; what are the various ways can do that, and what are their pros, cons and relative performance?

(Using textures, FBOs, the accumulator buffer, any kind of scissors that can affect swapbuffers etc?)

A scenario: a scene with a fair few thousand visible trees; although the textures are mipmapped and they are drawn via VBOs roughly front-to-back with so on, its still a lot of polys. Would streaming a single screen-sized texture be better than throwing them at the screen every frame? You'd have to redraw and recapture them only on camera movement or as often as your wind model updates or whatever, which need not be every frame.

# Answer
Do not try to keep anything persistent in the window's framebuffer. For example, graphics cards usually maintain a hierarchical z-buffer that only works if you call glClear regularly. If you have a rarely redrawn background, I suggest you render that into an FBO (or PBUFFER, if you lack proper FBO support with MSAA) when it changes. If the background drawing takes very long, you can even spread it out over multiple frames and smoothly blend over. That's a technique that's often used for very expensive skyboxes with lots of atmospherical effects.
> 4 votes

# Answer
There is a MESA extension to do this, glXCopySubBufferMESA. As buffer swaps are platform-dependent, any partial buffer copy is also going to be.

Although, the obvious question is, what are you tackling where you think such a thing may help?
> 3 votes

# Answer
I'd have to agree with JoeW further up, the question seems to be too specific, in that you state you want to solve the performance problem of lots of trees, but the question states only by partial updates and that leaves only to solutions based around that.

What you don't seem to mention above is any form of LOD on the mesh, just mip-maps for the textures. When I've needed to make sure lots of tree's have to be drawn on screen I'd have at least two polygon mesh LOD's for them and in the distance have that go down to a simple forward facing sprite (we've used a bit of a hybrid solution where we also use SpeedTree which does pretty much the same thing). I guess it comes down again to where the bottleneck is and until you understand exactly what it is that's slowing it down the most you can't really optimize that area.

Just in case by FBO you didn't mean 2D Imposters I've also thrown a link in for that. I've not shipped anything using them dynamically myself but I know titles have with success, it all depends how much video memory you have free on your target platform to implement.
> 2 votes

# Answer
I think you should always compose the final image completely, but you may keep parts of it in auxiliary buffers.

In other words, let's say you have some very complex HUD. Render that to a separate texture with everything see-through masked with alpha. You don't need to update the HUD texture every frame, only whenever it actually needs to be updated.

When rendering a frame, you just re-use the HUD texture each frame.

This was just an example, the same principle could be applied to other things that do not require update each frame.

The only place where I think updating only parts of the screen would help are extremely platform-specific to some obscure low-end hardware, and OpenGL doesn't really apply there. Everything else more or less requires the full screen update (either due to double buffering, tiling, or whatever weird NDS did again).
> 0 votes

---
Tags: opengl, performance, double-buffering
---


title: Any interesting thesis topic?

text:
# Question
Title: Any interesting thesis topic?
I study Computer Science at Technical University of Lodz (in Poland) with Computer Game and Simulation Technology specialization. I'm going to defend BSc thesis next year and I was wondering what topic I could choose but nothing **really interesting** is coming to my mind.

Maybe You could help me and suggest some subjects related to programming graphics, games or simulations? (or maybe something else that is interesting enough :) ). I would be very grateful for any suggestion!

# Answer
> 7 votes
Few topics come to my mind

* Fluids simulation: Navier-strokes equations. And gpgpu acceleration (video)
* Fluids rendering - volumetric raycasting (video)
* Volumetric rendering - marching cubes (video)
* Realtime bokeh rendering (paper)
* Point based rendering (video)
* Realtime rain rendering (paper)
* Simple raytracer with global ilumination - propably without accelaration structs.

And the best is contact some computer games/graphics/movie company and offer them to create something they need for free. That have only pluses. You will have hard and interesting thesis ( and prototype ) and some experienced advisor from company who will help you. Don't be afraid to do it. Enthusiasm helps very much in this case. (I know it)

# Answer
> 1 votes
I did pathfinding on arbitrary 3D environments. Admittedly not totally interesting nor innovative, but it was the closest thing to a game-related thesis I managed to negotiate :S

It was a few years ago, though. Now they're talking about having game development as an elective. How times change :(

# Answer
> 0 votes
Inverse kinematics and behaviors ala NaturalMotion.

---
Tags: graphics, education
---


title: How to create games with scrolling?

text:
# Question
Title: How to create games with scrolling?
In games like city story or we farm how do they implement scrolling?

1. To do scrolling using UIScrollView the EAGLView size has to be bigger. In those games EAGLView size look like more than 1024\*1024. But there is limitation in viewport size in iphone devices(in 3G iphone max is 1024).
2. I played those games in 3G iphone they are working fine.
3. Any idea how they implemented their scrolling mechanism?

# Answer
Well they don't use something like a UIScrollView, that's for sure. You would just move the camera over a stationary world or move the world under a stationary camera. I'm a little rusty on my GL, but I would guess you just push a new translation matrix before all your drawing.

For the actual dragging part, you would also implement that yourself. It would probably be something where you check to see if there was a certain amount of cursor/finger movement delta in a given amount of time to see if it's a "drag" or a "click". Or maybe you always drag unless the user clicks on a UI element or something like that. It really depends on the design of how you want that system to work.
> 4 votes

# Answer
A scroller is quite simple a "virtual viewport" that pushes new tiles/objects in from direction you are scrolling.

Simple example to see this, is to build a simple 1 line marquee(textscroller).

Lets for example purpose say we have a line with 20 characters/letters/chars.

We place them in an string/array like:

```
String viewport = "....................";
String text = "Hello World (how original!)";

```

now if we print this, we will only see the "dots".

```
Console.WriteLine(viewport);

```

Now to scroll it, we need to make the dots go to the left. So we can read the text comming in.

For this to happend, we remove the first letter from left and adds the next to be shown from the right.

so we say:

```
viewport = viewport.Substring(2);

```

to take the 2nd letter and forward which equals rest of viewports current content.

Now the viewport is 1 char/letter to narrow, so we need to add the next char from the scroller. Therefore we need a variable for controlling where we are in the scrolltext.

```
// place this outside your scroll loop
int scrollPos =0;

```

Now with this index, we can find the next character.

```
char next = text.substring(scrollPos,1);

```

Then add this to the viewport.

```
viewport += next;

```

And increment your position in the scrolltext.

```
scrollPos++;

```

Now we have scrolled the contents 1 char left.

Keep doing this over and over, and it will look like the "Hello World" is scrolling across your viewport.

Now imagine this trick in all directions. Instead of characters, you use your own "Tiles". Secondly, to make it go smooth, you also add a "pixel scroll" within your scroller or you just multiple your scrollpos for simplicity. Then when you need to figure out which tile to add next, then just divide your current scrollpos with tile-width, then you know if you need to move the viewport scroll contents in any direction.

if you need to scroll arrays (with tile/block data) you can do it with simple for-loops.

**left scroll**

```
for (int pos=0;pos<viewwidth;pos++)
{
    tilemap[pos] = tilemap[pos+1];
}

tilemap[width] = newTile; // from maparray.

```

**Phew**

That was a long explanation. Do you understand my point here, or do you need further explanation?
> 4 votes

# Answer
Scrolling doesn't necessarily mean loading everything into memory. The usual way to deal with this is to separate your content into *tiles* which are loaded into memory as needed. Apple has an example at http://developer.apple.com/library/ios/#samplecode/ScrollViewSuite/Introduction/Intro.html for showing big images.

Games, however, tend to do something else. Even if it is possible to use the previous technique, loading data from disk is slow and may disrupt the game experience for the user. For this reason the area to scroll is usually cut into pieces you can later reuse, giving the feeling that the whole world is bigger than it could really fit into memory.

You can learn more about tiles with a map editor like Tiled Map Editor and searching the net for tutorials on how to use it/integrate into your game. Games like Diablo are known to use tiled maps which are logically split into bigger tiles that glued together create inmense pseudo-random maps on each different game.
> 2 votes

# Answer
Another way to implement scrolling for a 2d game is to manipulate your projection matrix to reflect where the screen/camera is located in the game world.

What I did was implement a 2d camera class that had its position and the width/height of the viewable area.. Then before you draw the game world you set up the ortho projection matrix.

e.g.

```
float left = camera->X - (camera->Width / 2.0f);
float bottom = camera->Y - (camera->Height / 2.0f);
float right = left + camera->Width;
float top = bottom + camera->Height;

glMatrixMode(GL_PROJECTION);
glLoadIdentity();

glOrthof(left, right, bottom, top, -50.0f, 1.0f);

```

I hope this helps. Oh, and you would reset the projection matrix to something else if you wanted to draw UI elements afterwards etc.

Of course, all of this applies only if your writing your game in openGL.
> 0 votes

# Answer
refer this tutorial:- http://www.raywenderlich.com/2343/how-to-drag-and-drop-sprites-with-cocos2d

this tutorial contains how to scroll the view and with uipanrecogniser.

this will helps .
> 0 votes

---
Tags: iphone
---


# Question
Title: OpenGL's matrix stack vs Hand multiplying
Which is more efficient using OpenGL's transformation stack or applying the transformations by hand.

I've often heard that you should minimize the number of state transitions in your graphics pipeline. Pushing and popping translation matrices seem like a big change. However, I wonder if the graphics card might be able to more than make up for pipeline hiccup by using its parallel execution hardware to bulk multiply the vertices.

My specific case. I have font rendered to a sprite sheet. The coordinates of each character or a string are calculated and added to a vertex buffer. Now I need to move that string. Would it be better to iterate through the vertex buffer and adjust each of the vertices by hand or temporarily push a new translation matrix?

# Answer
> 7 votes
It's my understanding that in the most recent versions of the spec (3.3 and 4.x) the matrix stacks are gone and you need to keep track of your transformation matrices by hand. I believe this might be true for the mobile (ES) spec as well.

If you're looking for a consistent way to handle your matrices by hand, you might be interested in GLM. It's a pretty neat math library (which includes matrix transformations) modeled after the GLSL spec so you only need to keep one set of math routines in your head when dealing with OpenGL code.

# Answer
> 3 votes
The stack is the less-optimal option here -- not because pushing and popping it was expensive, as it should not ever induce a complex driver-level state change (the matrix shouldn't be sent to the card until a render command is issued, so it's all CPU-side manipulation in the API, usually).

The problem with the stack is that it has a limit to how far you can push it -- it's one of the parameters you could get at via glGet\* I think. There's no big advantage to using the stack unless you don't have or are incapable/do not desire to write matrix math. I would recommend doing it yourself.

I don't know what the state of the stack functions are in modern GL. I believe they've been deprecated/removed as well, but I haven't had the need to actually use GL in a while so I have not kept as up to date.

# Answer
> 3 votes
As others have noted, the matrix stack is on its way out, which is a good reason to investigate alternatives.

On one of my projects, I used the OpenGL's matrix ops to calculate my matrices, but ended up having to use glGet functions to fetch the matrix back so I could do some operations on the matrix that OpenGL's own functions didn't support. The performance was abysmal, and I traced the loss to the single glGet function. It's possible that the matrix ops are actually performed on the GPU somehow, and using glGet caused pipeline flush, or something.

Whatever the reason, I replaced the matrix operations with CML, the configurable math library, and the performance improved dramatically. Not only was I no longer bound to the performance metrics of the OpenGL matrix operations, CML also included tons of operations OpenGL doesn't support.

And implementing a stack of matrices is pretty easy using STL vector or some such.

# Answer
> 2 votes
I'm not sure of your level of experience, but I would recommend doing it by hand. It may take more effort to learn how to do this, but it is immensely beneficial to know what your matrices are doing and to be able to manipulate them yourself. It will also make you more aware of issues that may crop up when applying matrices in different orders (eg. scaling then rotating). I know I spent many hours trying to figure out weird render "bugs" before deciding my time would be better spent thoroughly studying what each operation was doing. It's worth the investment.

Addressing your specific issue, applying a transform to the vertices seems like the easiest way, just be aware of the order of operations of matrices.

# Answer
> 1 votes
The main problem that I see is that you need to access the results for other game tasks and acessing those results can be complicated and slow.

Thats why I prefer to do those matrix operations myself.

---
Tags: opengl, optimization, opengl-es, fonts
---


# Question
Title: How to implement "computer player" for a card game based on a few rules?
I'm developing a gameboard for a 4 players cardgame well know in my region (like a Bridge with 8 cards).

I create a cardcontrol class, all the deck methods and all the logics for value card and score count.

But I need some link or suggestion for the implementation of "computer player" based on a few rules to follow.

# Answer
Try building a class which handles game turns, who knows all the players and their order, in a array for example.

Each time a player (human or CPU) finish playing, check if the condition to end the game (win or lose) are met.

If not, find who will be the next player. In case the next player is CPU, make it choosing the correct card combination according to its level (easy-medium-hard), and then finish the game loop again by triggering the same method I've just discussed.
> 1 votes

# Answer
Here's something that I try to follow when programming AIs.

Create a set of "personalities", that is, ways in which you might expect the computer player to act. Have their actions conform to these. For instance, in a card game, you might have 3 personalities: aggressive, defensive and moderate.

Next, when it gets to the computer player's turn, randomly choose an action that conforms to the player's personality, and make sure the action is also in a list of sensible things to do.

So the logic comes down to this:

1- Based on the situation, what is a list of sensible actions to take?

2- Based on my personality, what actions from the above list would I choose?

3- Randomly choose one of these, then do it!
> 0 votes

---
Tags: ai, card-game
---


# Question
Title: Can I Base My Game on Another Game and Earn Money?
> **Possible Duplicate:**
> How closely can a game resemble another game without legal problems

I want make a game similar to Pocket Tanks but for Android and then sell it. Since I am not directly copying anything from Pocket Tanks, but simply using it to give me ideas, I should be allowed to make it. I don't want to finish making my game and then get into some legal trouble, so I wanted to ask here if its allowed. If this is the wrong place to ask, can you tell me where I could ask this question?

# Answer
> 2 votes
If you search around a bit, you can find a bunch of games that are also much like Pocket Tanks. For instance, just Google "Scorched Earth game".

Find these other games, then determine how they differ from Pocket Tanks. Then, make sure that your game is at least that different.

There's no way to know what kind of legal issues may arise. The best you can do is as much as possible to make your software different.

---
Tags: legal
---


title: Custom mesh format - yea or nay?

text:
# Question
Title: Custom mesh format - yea or nay?
In the process of writing my game prototype, I have found the OBJ format to be insufficient for my needs - it does not support any sort of animation, it doesn't support triangle strips (I'm targeting my ancient hardware). MD2 wouldn't fit the bill because it doesn't have support for named model pieces. MD3 would probably work, but like OBJ, it doesn't have support for triangle strips. Considering the limitations of the formats above, I've come to the conclusion that it may be necessary to write my own format to accommodate my requirements, but that feels like reinventing the wheel.

So, I need a format which can specify indexed tri-strips, supports textures, UV-mapping, collision data, can have multiple named segments and supports animations (have I forgotten anything?). Is there any format like that which already exists, or do I have to write my own?

# Answer
> 5 votes
I won't refer to any specific formats, but here's points for your "yea or nay" question:

**Reasons to use custom formats:**

* Speed up loading of your game
    + Can do all preprocessing your heart desires and store the results
* Support for features not in generic formats
* Doesn't include anything you don't want to
    + .3ds, for instance, has tons of stuff you'll never need, but will add to your binary size
* Slow down or stop content alteration / stealing
    + Some consider this a plus, ymmv.

**Reasons to use generic formats:**

* Support built-in in modelling packages
    + Be careful to test the actual support though. The actual quality of COLLADA support varies from one package to the next, for instance. Most formats supported by Blender don't include bones, even if the format would support them, etc.
* Can (possibly) use existing loading code made by other people
* No need for additional build step (conversion from generic format, preprocessing) or custom exporters
    + Supporting custom exporters can be a huge pain

# Answer
> 2 votes
There are data structures in meshes that work best for development and others that are more optimal for loading. In the development phase generic formats can speed up production and creation of assets.

In the final stages of development closer to completion, start optimizing for load times. When all your assets are final use a custom-made mesh exporter to convert your meshes off-line, and use those converted meshes for the final game.

A mesh file that is most optimized for fast loads would have its data aligned exactly as it is in whatever kind of vertex buffer you use in your API. It would be a simple copy operation and it's done.

# Answer
> 0 votes
Never used it myself, but there was some interest a while back (or maybe still is) in Collada. Projects I've worked on have always rolled our own export formats, you'll always have exactly what you want that way, just depends how much work you want to do.

# Answer
> 0 votes
I'd look through the standards first, just to make sure; but if your needs aren't being met that may be a decent solution.

Check out FBX, I've been working in XNA and so have been kind of bound into them (or .x but we had difficulties with that due to Maya). They are a bit of a headache at times, but I've been told they support animations well, and I have seen evidence of the ability for named bones n' the like.

---
Tags: 3d-meshes, file-format
---


title: How Can I Improve This Card-Game AI?

text:
# Question
Title: How Can I Improve This Card-Game AI?
Let me get this out there before anything else: this is a learning exercise for me. I am not a game developer by trade or hobby (at least, not seriously) and am purely delving into some AI- and 3D-related topics to broaden my horizons a bit.

As part of the learning experience, I thought I'd have a go at developing a basic card game AI. I selected Pit as the card game I was going to attempt to emulate (specifically, the 'bull and bear' variation of the game as mentioned in the link above). Unfortunately, the rule-set that I'm used to playing with (an older version of the game) isn't described. The basics of it are:

* The number of commodities played with is equal to the number of players.
* The bull and bear cards are included.
* All but two players receive 8 cards, two receive 9 cards.
* A player can win the round with 7 + bull, 8, or 8 + bull (receiving double points).
* The bear is a penalty card.
* You can trade up to a maximum of 4 cards at a time. They must all be of the same type, but can optionally include the bull or bear (so, you could trade A, A, A, Bull - but not A, B, A, Bull).

For those who have played the card game, it will probably have been as obvious to you as it was to me that given the nature of the game, gameplay would seem to resemble a greedy algorithm. With this in mind, I thought it might simplify my AI experience somewhat.

So, here's what I've come up with for a basic AI player to play Pit... and I'd really just like any form of suggestion (from improvements to reading materials) relating to it.

Here it is in something vaguely pseudo-code-ish ;)

```
While AI does not hold 7 similar + bull, 8 similar, or 8 similar + bull, do:
    1. Establish 'target' hand, by seeing which card AI holds the most of.
    2. Prepare to trade next-most-numerous card type in a trade (max. held, or 4, whichever is fewer)
    3. If holding the bear, add to (if trading <=3 cards) or replace in (if trading 4 cards) hand.
    4. Offer cards for trade.
    5. If cards are accepted for trade within X turns, continue (clearing 'failed card types').
        Otherwise:
            a. If only one card remains in the trade, go to #6.
                Otherwise:
                    i. Remove one non-penalty card from the trade.
                    ii. Return to #5.
    6. Add card type to temporary list of failed card types.
    7. Repeat from #2 (excluding 'failed card types').

```

I'm aware this is likely to be a sub-optimal way of solving the problem, but that's why I'm posting this question. Are there any AI- or algorithm-related concepts that I've missed and should be incorporating to make a better AI? Additionally, what are the flaws with my AI at present (I'm well aware it's probably far from complete)?

Thanks in advance!

# Answer
> 7 votes
What you've got there is a basic rules-based system. It's fine, but it will play the same way every time and possibly have exploitable patterns of play. The domain's simple enough that there might not be an easy pattern to exploit, but it's not a very interesting approach. :)

You may want to look into planning AIs. Instead of defining an algorithm for play, you can code the AI with the steps it can take: how to trade and what the consequences are for it. These are sometimes called "inference rules." Then you use forward or backward chaining to figure out a sequence of actions from the current state to the goal state.

Alternately, if you think you can define a good heuristic for how close you are to winning, you can use an adversarial approach like alpha-beta pruning search that allows the AI to take the state of the opponents into account. I'd guess that a good heuristic would include what the AI can know about its opponents' hands based on their previous trades.

I'm sure there are approaches that an AI expert would think of that I've missed.

---
Tags: algorithm, ai, card-game
---


# Question
Title: Why does OpenGL seem to ignore my glBindTexture call?
I'm having problems making a simple sprite rendering. I load 2 different textures. Then, I bind these textures and draw 2 squares, one with each texture. But only the texture of the first rendered object is drawn in both squares. Its like if I'd only use a texture or as if glBindTexture don't work properly. I know that GL is a state machine, but I think that you only need to change active texture with glBindTexture.

I load texture with this method:

```
 bool CTexture::generate( utils::CImageBuff* img )
 {
  assert(img);
  m_image = img;
  CHECKGL(glGenTextures(1,&m_textureID));

  CHECKGL(glBindTexture(GL_TEXTURE_2D,m_textureID));
  CHECKGL(glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR));
  CHECKGL(glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR));
  //CHECKGL(glTexImage2D(GL_TEXTURE_2D,0,img->getBpp(),img->getWitdh(),img->getHeight(),0,img->getFormat(),GL_UNSIGNED_BYTE,img->getImgData()));
  CHECKGL(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, img->getWitdh(), img->getHeight(),
   0, GL_RGBA, GL_UNSIGNED_BYTE, img->getImgData()));

  return true;
 }

```

And I bind textures with this function:

```
void CTexture::bind()
 {
  CHECKGL(glBindTexture(GL_TEXTURE_2D,m_textureID));
 }

```

Also, I draw sprites with this method

```
void CSprite2D::render()
 {
  CHECKGL(glLoadIdentity());
  CHECKGL(glEnable(GL_TEXTURE_2D));
  CHECKGL(glEnable(GL_BLEND));

  CHECKGL(glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA));
  m_texture->bind();

  CHECKGL(glPushMatrix());

  CHECKGL(glBegin(GL_QUADS));
  CHECKGL(glTexCoord2f(m_textureAreaStart.s,m_textureAreaStart.t)); // 0,0 by default
  CHECKGL(glVertex3i(m_position.x,m_position.y,0));

  CHECKGL(glTexCoord2f(m_textureAreaEnd.s,m_textureAreaStart.t)); // 1,0 by default
  CHECKGL(glVertex3i( m_position.x + m_dimensions.x, m_position.y, 0));

  CHECKGL(glTexCoord2f(m_textureAreaEnd.s, m_textureAreaEnd.t)); // 1,1 by default
  CHECKGL(glVertex3i( m_position.x + m_dimensions.x, m_position.y + m_dimensions.y, 0));

  CHECKGL(glTexCoord2f(m_textureAreaStart.s, m_textureAreaEnd.t));  // 0,1 by default
  CHECKGL(glVertex3i( m_position.x, m_position.y + m_dimensions.y,0));

  CHECKGL(glPopMatrix());

  CHECKGL(glDisable(GL_BLEND));
 }

```

Edit: I bring also the check error code:

```
int CheckGLError(const char *GLcall, const char *file, int line)
{
    GLenum errCode;

    //avoids infinite loop
    int errorCount = 0;
    while ( (errCode=glGetError()) != GL_NO_ERROR && ++errorCount < 3000)
    {
        utils::globalLogPtr log = utils::CGLogFactory::getLogInstance();
        const GLubyte *errString;
        errString = gluErrorString(errCode);
        std::stringstream ss;
        ss << "In "<< __FILE__<<"("<< __LINE__<<") "<<"GL error with code: " << errCode<<" at file " << file << ", line " << line << " with message: " << errString << "\n";
        log->addMessage(ss.str(),ZEL_APPENDER_GL,utils::LOGLEVEL_ERROR);
    }
    return 0;
}

```

# Answer
> 6 votes
Once you are done sending vertex data to OpenGL, you need to call glEnd, which I don't see called anywhere in your code. It should probably be before your PopMatrix call.

For example, glBindTexture's documentation says:

> GL\_INVALID\_OPERATION is generated if glBindTexture is executed between the execution of glBegin and the corresponding execution of glEnd.

I assume your CHECKGL macro is supposed to catch reports via glGetError, in which case you might want to go back and make sure it works.

---
Tags: opengl, textures
---


# Question
Title: What is the Xbox360's D3DRS_VIEWPORTENABLE equivalent on WinXP D3D9?
I posted this on StackOverlow, but of course it should be posted here.

I am maintaining a multiplatform codebase for Xbox360 and WinXP. I am seeing an issue on the XP side that appears to be related to D3DRS\_VIEWPORTENABLE on the Xbox360 version not having an equivalent on WinXP D3D9. This article had an interesting idea, but the only way to construct an identity matrix is to supply negative numbers to D3DVIEWPORT9::X and D3DVIEWPORT9::Height, but they are unsigned numbers. (I tried to put in negative numbers anyway, but nothing interesting happened.)

So, how does one emulate the behavior of D3DRS\_VIEWPORTENABLE under WinXP/D3D9?

(For clarity, the result I'm seeing is that a 2d screen-aligned quad works fine on Xbox360 but is offset/stretched on WinXP. In fact, the (0, 0) starts in the center of the screen on WinXP instead of in the lower-left corner like on the Xbox360 as a result of applying the viewport transform.)

Update: I didn't have an Xbox360 devkit at the time I wrote up this question, but I've since gotten one. I commented out the disabling of the D3DRS\_VIEWPORTENABLE state, and the exact same behavior resulted on the Xbox360 as on the WinXP build. So, there must be some DirectX magic to bridge the gap here for emulating D3DRS\_VIEWPORTENABLE being turned off on WinXP.

# Answer
Just set up your projection matrix to reverse any offset+scale done by the viewport?
> 3 votes

# Answer
The viewport transform transforms co-ordinates into normalized device co-ordinates. They're kind of similar to texels, with 0,0 in the center and the corners being various permutations of 1 and -1.

However, you can observe that in ID3DXSprite, there is an option to render in screen-space co-ordinates. You could render to a texture, and then present it to the screen in a custom way by rendering it with ID3DXSprite.

D3D9 generates the Viewport transform with the following formula:

If you know that you want an identity transform, you could solve to find it using this, or alter the projection matrix to counteract it's effects. I wish I could be of more use but I couldn't find any documentation on D3DRS\_VIEWPORTENABLE for the 360- I only code for D3D9 on Windows.
> 1 votes

---
Tags: graphics, xbox360, windows, directx9
---


title: GL_INVALID_OPERATION in glEnd

text:
# Question
Title: GL_INVALID_OPERATION in glEnd
I'm having problems drawing a simple sprite. When I draw:

```
void CSprite2D::render()
    {
        CHECKGL(glLoadIdentity());
        CHECKGL(glEnable(GL_TEXTURE_2D));
        CHECKGL(glEnable(GL_BLEND));

        CHECKGL(glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA));

        m_texture->bind();

        //CHECKGL(glPushMatrix());

        CHECKGL(glBegin(GL_TRIANGLE_STRIP));
            CHECKGL(glNormal3i(0,0,1));
            CHECKGL(glTexCoord2f(m_textureAreaStart.s,m_textureAreaStart.t)); // 0,0 by default
            CHECKGL(glVertex3i(m_position.x,m_position.y,0));

            CHECKGL(glNormal3i(0,0,1));
            CHECKGL(glTexCoord2f(m_textureAreaEnd.s,m_textureAreaStart.t)); // 1,0 by default
            CHECKGL(glVertex3i( m_position.x + m_dimensions.x, m_position.y, 0));

            CHECKGL(glNormal3i(0,0,1));
            CHECKGL(glTexCoord2f(m_textureAreaEnd.s, m_textureAreaEnd.t)); // 1,1 by default
            CHECKGL(glVertex3i( m_position.x + m_dimensions.x, m_position.y + m_dimensions.y, 0));

            CHECKGL(glNormal3i(0,0,1));
            CHECKGL(glTexCoord2f(m_textureAreaStart.s, m_textureAreaEnd.t));  // 0,1 by default
            CHECKGL(glVertex3i( m_position.x, m_position.y + m_dimensions.y,0));
        CHECKGL(glEnd());

        //CHECKGL(glPopMatrix());

        CHECKGL(glDisable(GL_BLEND));
    }

```

I'm always get an GL\_INVALID\_OPERATION in glEnd(). I suspect that error is not here, but I can't detect where may be. Actually, the output render seems ok. But I want to solve this situation before to catch a subtle bug tomorrow.

Any idea of what could be

# Answer
> 9 votes
My guess is your CHECKGL macro is calling glGetError between a glBegin/glEnd, which is not one of the defined functions that can be called.

http://www.talisman.org/opengl-1.1/Reference/glEnd.html

http://www.opengl.org/sdk/docs/man/xhtml/glGetError.xml

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


# Question
Title: How much to pay for artwork in an indie game?
I am an indie developer and I need some detailed artwork. How much is reasonable to pay an artist for say 20 character designs? I know it depends on the artist's skills, etc, but I am wondering what to expect so that I can budget it.

Edit:

Let's say cartoon-ish art (Example \- not necessarily in that level of detail but that kind of cartoony-art style). No 3-d modelling - The art will be used as still images in game and for promotional reasons. I'd provide a base sprite design for them to expand on and detail.

Also, some numbers would be nice - I like numbers. Even a range is helpful.

Like: expect to spend $x2 ~ $x1 for top-notch and $y2 ~ $y1 for decent quality.

I understand I can ask at some indie-help site but, if an artist says something like $1000 for 20 designs, I wouldn't have any idea if it's reasonable / good deal / bad idea etc.

# Answer
The DeviantArt Job Offers Forum is a place where people often request such projects from designers. You can probably find proposals with prices, but from what I can tell, they're very disparate.
> 10 votes

# Answer
Random art costs random money.

You can find any kind of quality and any kind of cost.

Set a budget, search for people who will do that for that budget, and among them chose the one you like most.
> 3 votes

# Answer
Before you run out to pay for any art, see what you can find online for free that comes with a license that works for you, if nothing satisfies you I would use temporary art that is on the net until you able to come up with something.

Also, try poking around an art department at a local university or an art guild. I'm sure there might be a student dieing to get there work exposed or create something that can get them more exposure.

Ultimately, you may not have to pay much if at all if you can find the right people and prove that you wont be wasting anyones time! =)
> 2 votes

# Answer
I wanted an answer to this very question. But as the others state, Random art, Random price.

Also think about it logically, a drawing that is going to become a 3D model, a drawing that is going to be created in to a realistic person once in the game and then a Sprite (eg SNES style) are both going to cost different amounts.

If you want a ball park figure then you'll probably looking at again a different amount for the detail inside. For example if this is going to be a cartoon style character, or in the style of perfect people, or in the style of a realism. Additionally it is a different story to draw an animal, a person, an imaginary creature or combination.

Without spices you'll never get a figure. I'd suggest posting (not necessarily on here...) a more in depth request with the intention of people coming back with amounts they feel it is worth or they would draw them for you.
> 2 votes

---
Tags: art, costs
---


# Question
Title: Retrieve the coordinates of the *occluding* (closest/drawn) pixels during 3D overlap, using OpenGL?
Sorry if the question is not worded well, I'm a new to both 3D and OpenGL.

How could I go about obtaining the 3D coordinates of the ***occluding*** object, **at the point where occlusion is happening** (i.e. the 'intersection' of the object in front/closest to the screen)?

Just to offer a \[very\] rudimentary, visual, example, if you were to form an index-finger cross, with your right hand closest to your face, I'd like to know the coordinates of the part of your ***right*** finger which obscures the other finger (obviously back within the OpenGL context - no jokers ;-) ).

If there is a way to find out both about the occluder (hider) and the occluded (hidden) objects in OpenGL, then that would be of great use, also.

Cheers

Rich

# Answer
Finding the foremost object can be thought of as 'picking'. There are basically three obvious ways to do it - using GL's selection mode, using unique colours for objects when rendering them and finally doing it via geometry on the CPU rather than using OpenGL.

If using OpenGL, you could draw the scene back to front, doing a test after each draw, to determine the next-most-top object at that location.

Ultimately, using ray intersections with octrees is going to be a far more professional solution.
> 1 votes

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


title: XNA 4.0 Post-Processing Libraries?

text:
# Question
Title: XNA 4.0 Post-Processing Libraries?
Are there any free XNA 4.0 post-processing libraries that are easy to hook into projects? I am looking specifically for a glow effect (although anything is great), and I should also mention that I'm using the Reach profile.

EDIT: I should add that I'm not concerned about the Windows phone, because it can't support custom shaders.

# Answer
> 3 votes
Here is a lot of tutorials on Post Processing.

---
Tags: xna-4.0, post-processing
---


# Question
Title: How do I get Apple to pull an App that violates a copyright?
A friend of mine has had his Flash game stolen and published on the iPhone app store without his consent. What is the best way to get Apple's attention about this?

# Answer
At the bottom of every app's page in the app store on the phone is a "Report a problem" button you could try, but I suspect the best way is to have your friend's lawyer handle it (and if your friend does not have a lawyer, he or she may want to consider finding and talking with one).
> 12 votes

# Answer
IANAL but unless they directly copied art resources you are likely out of luck. Game mechanics are incredibly hard to defend and frankly it's in the industries interest that they remain that way.

You can attack someone for directly coping the wording of your games rules, and art coping is an obvious point of contention. However if their game just plays like your game then you are pretty much out of luck.
> 6 votes

# Answer
Here is a interesting thread regarding copyright and games.

How closely can a game legally resemble another?
> 0 votes

---
Tags: copyright
---


# Question
Title: Can LittleBigPlanet2's engine be used for other?
LittleBigPlanet2 just came out. I've worked with the original LBP level editor a bit and really enjoyed it. I've read that LBP2's featureset in the game is much richer; is it possible to use these advanced features to create different sorts of game other than just a regular platformer? I imagine that something along the lines of a Breakout clone would definitely be manageable, but I'm interested in hearing more about the capabilities of the platform.

# Answer
> 3 votes
Seems like it can: http://www.youtube.com/watch?v=afjZUFRNLqc If you google for various game "genres" along with "LittleBigPlanet 2," there are plenty of other examples.

---
Tags: console
---


# Question
Title: How can I separate entities from their actions or behaviours?
I'm having a go at creating a very simple text based game and I'm wondering how I can design the entities (characters, sentient scenery) with regards to the actions those entities can perform.

As an example, I have an entity that is a 'person' with various properties such as age, gender, height, etc. This 'person' can also perform some actions such as speaking, walking, jumping, flying, etc etc.

How would you separate out the entity from the actions it can perform?

# Answer
> 4 votes
The common answer you'll get is "with components". There are lots of questions with that phrase in them that you can search through.

In particular, here's a good article that has been linked to several times that's worth a read: http://cowboyprogramming.com/2007/01/05/evolve-your-heirachy/

# Answer
> 1 votes
There's plenty of prior art in the whole MUD and MUSH culture, with many open source platforms. Many MU\*'S include support for adding behaviors/actions on the fly--i.e. admin users can create new commands via scripting. Then there's Inform7, which is arguably the state of the art for IF or and single-player, text-based games today.

---
Tags: architecture, behavior
---


# Question
Title: Is there a global "low resolution" filter for OpenGL?
I'm trying to learn a little about OpenGL, so I'm making a simple 2D game (with OpenTK), and so far it's coming along well. I thought it would be fun to give it that, for lack of a better word, retropixelated look of games from the early nineties. I figured it would be an easy thing to do -- simply draw everything at half its normal size and scale up with no anti-aliasing.

But I can't find any resources on how to do this. I can set the min/mag filters of my textures to nearest and that works fine for my sprites, but I'm using lots of primitives and I'd like the effect to apply to them as well.

The one idea I had was to draw everything at half size, then somehow copy the render buffer to a texture, then render that texture full-size, but I don't know how to do that, and it seems like there must be a better way. Can anyone help me out?

# Answer
> 8 votes
Basic idea is to render to a framebuffer object, bind that as a texture and render the texture on screen on a full-screen quad.

If you want to support lower-end hardware, you may want to render to the top-left corner of the screen instead, copy the bits to a texture and then render the full-screen quad; this is, however, much slower than the FBO technique, if FBO is available.

---
Tags: opengl
---


# Question
Title: Can I publish games with adult content to Android Market?
I have a very old adult (e.g. boobs and stuff) arcade game (think Delphi 7/DirectX 8 age), that currently is backported to Droid. Can the game be published to Android Market? Are there any age restrictions?

# Answer
> 5 votes
Android Market has a very restrictive adult category. So you probably can't. But, you can publish your application on alternative markets that allow adult content.

# Answer
> 4 votes
Obviously you can't. You'll have to host it on your own.

See developer content-policy.

---
Tags: android, content-rating
---


# Question
Title: Are there any command line swf packing tools?
I want to packing image files(png, jpg) into swf, then game can load files easily. But I want to do this by a Makefile, not FLASH CS.
Do you know any command line swf tool set can do that? And can I packing XML files into it as well?

# Answer
> 1 votes
Besides SWFMill, there's also Sam HaXe. Haven't used it (yet), but I ran into some obscure problems with SWFMill at some point so I'll be trying SamHaXe in the near future instead. According to the documentation, you can embed arbitrary (binary) files with optional zlib compression, so embedding xml files shouldn't be a problem.

# Answer
> 5 votes
Flex SDK has support for command-line compilations because it is a compiler. And then you could be interested also in Mike Chambers Flash Command

# Answer
> 3 votes
SWFMill is the tool to use.

And you might also be interested in developing with Haxe.

# Answer
> 1 votes
I've done this quite a lot using the standard Flex SDK. With a bit of python or something else you can even generate some nice class stubs to improve your work flow with the end product.

---
Tags: flash, swf
---


title: How does 2D Game Physics work?

text:
# Question
Title: How does 2D Game Physics work?
> **Possible Duplicate:**
> How do I build a 2D physics engine?

If we take the game Angry Birds that had big success lately I were thinking how do they implement the physics in a game like that?

Your are shooting of your birds and they hit something that will fall off and in turn creating a chain reaction of things either falling or exploding.. Are all this happening with calculations with rules considering all collisions together with gravity etc.?

# Answer
Erin Catto, the guy who wrote the Box2D physics engine has made a lot of good presentations on how to make 2D physics engines.

The general idea is to move your objects in small time steps, calculate intersections and then resolve them iteratively. Check out the GDC talks at http://code.google.com/p/box2d/downloads/list
> 7 votes

---
Tags: game-design, physics
---


# Question
Title: Implementing my Entity System. Questions about some problems I have found
Well during this week I have deciding about implementation of my entity system. It is a big topic so it has been difficult to take one option from the whole. This has been my decision:

1) I don't have an entity class it is just an id.

2) I have systems that contain a list of components (the list is homegenous, I mean, RenderSystem will just have RenderComponents).

3) Compones will be just data.

4) There would be some kind of "entity prototypes" in a manager or something from we will create entity instances.Ideally they will define the type of components it has and initialization data.

5) Prototype code to create an entity (this is from the top of my head):

```
int id=World::getInstance()->createEntity("entity template");

```

6) This will notify all systems that a new entity has been created, and if the entity needs a component that the system handles it will add it to the entity.

Ok, this are the ideas. Let's see if some can help with the problems:

1) The main problem is this templates that are sent to the systems in creation process to populate the entity with needed components. What would you use, an OR(ed) int?, a list of strings?.

2) How to do initialization for components when the entity has been created? How to store this in the template? I have thought about having a function in the template that is virtual and after entity is created an populated, gets the components and sets initialization values.

3) Don't you think this is a lot of work for just an entity creation?.

Sorry for the long post, I have tried to expose my ideas and finding in order other could have a start beside exposing my problems.

Thanks in advance, Notbad.

# Answer
> 5 votes
Hey again NotBad, lets see if I can give you a hand again :)

1) EDITED. If you have alot of common components then pre-making a set of them could be very helpful in increasing the speed of creation and deletion. In previous component systems I have used all of the components were tied together with a single ID for example. So to 'allocate' a component to a specific object you would just give it the id of the object it belonged to. To 'deallocate' the object you would remove the id or set it to -1 or some other value to mark it as Unused. This way you only ever allocate memory on startup or when you run out and need to make another handful of a specific type. Deallocating would basically only be done at the end of the game's runtime.. You would eventually want to put in some sort of balancing routine that if you have say 15 unused components in a pool of 30 of that type that it dumps a certain number of them down or the like.. What you DO have to be careful of with this setup though is memory fragmentation.. If you are working within a managed system this should not be a concern, but just in case you are not be aware of that. Hope this helps answer the question a little better :)

2) As eluded to in the first one, you may want to include default values in the templates, this would set up their initial values when they are created (Read in a component, add it to the object in whatever tethering method you are using for your component system and then give it the values supplied by the teamplate). If I recall you are using Lua in here. If the object is represented in Lua after you call the sample CreateEntity() method you may want to return a Lua object that represents the object (even if in C/C++ it is just unified by Id). You could then just set the values directly via the object reference. This may be a bit more work in translation and such between the two systems but I can almost guarantee the payoff will be there in the long run.

3) EDITED. All in all some of the slowest execution speed in what you are doing here is going to be memory allocation. Having a good method as touched upon in the first answer can be key to this. Using a pooling system as described above can be very nice especially in a component system.. if you have a component that moves entities then you can use the same one for a positional sound effect, a particle effect, a player character, etc.. All it does is hold a position and functions for movements. Reuse-ability of component based systems along with their wide instead of tall structure a just a few of the benifits you can get :) For example, the engine I was working in professionally a few years ago was capped to say 100 objects for an entire level, I made a pooling/spawning system to make it 100 objects at a time.. now a PSP can not render that many objects at once, but it freed up the designers to really go wild and make the levels more interactable :) Back on topic, if you can allocate and deallocate all your memory on 'loading' screens (Yes, giving away knowledge that generally the first thing done on Loading screens in games is Unloading data) you will have much smoother game play sessions.

So again, hope I have helped as much as I thought I did on your first set of questions and good luck!

# Answer
> 1 votes
1) Your question sounds like "What type should the template identifier be", but seeing your comment on James' answer I think you're actually asking "How should templates be stored to make creating instances fast". It sounds like your entity template is basically a set of component templates, which themselves basically *are* instances of components. So, when you register these entity templates (either in code or by loading from a file), you'd just go through each component template in the entity template, look up the system by name (the components will need some kind of identifier, e.g. "Renderable"), and give that system the entity name ("Alien") and the block of data that makes up that component template.

If doing this at runtime, you can just construct a component and pass it along as that type (e.g. RenderSystem-\>register("Alien", AlienComponentData(1,2,3)); ), or if loading in from a file you can either pass in binary data for the system to just memcpy, or xml data for it to parse.

2) Carrying on from my answer to 1), just copy the template, which *is* an instance of a component (just not one that's active in the game). Then add that to your set of active components, with its entity id set. Nice and fast.

3) Not really, these things have to be done somewhere! In traditional inheritance-based entity structures it's just harder to see. Creating an entity by just copying some memory is going to be pretty slick, especially if you're copying it into already-allocated space inside a pool.

I hope I've understood, and I hope my answers are what you were expecting :)

---
Tags: architecture, entity-system
---


# Question
Title: Is there any difference between storing textures and baked lighting for environment meshes?
I assume that when texturing environments, one or several textures will be used, and the UVs of the environment geometry will likely overlap on these textures, so that e.g. a tiling brick texture can be used by many parts of the environment, rather than UV unwrapping the entire thing, and having several areas of the texture be identical. If my assumption is wrong, please let me know!

Now, when thinking about baking lighting, clearly this can't be done the same way - lighting in general will be unique to every face so the environment *must* be UV unwrapped without overlap, and lighting *must* be baked onto unique areas of one or several textures, to give each surface its own texture space to store its lighting.

My questions are:

1. Have I got this wrong? If so, how?
2. Isn't baking lighting going to use a *lot* of texture space?
3. Will the geometry need two UV sets, one used for the colour/normal texture and one for the lighting texture?
4. Anything else you'd like to add? :)

# Answer
> 8 votes
1. I think you are right. You would really like to tile your bricks, because it saves a lot of memory space and is also quick in your GPU. Baking the lighting does need a unique texturing, because no place is the same. You could tile some parts of your texture, for example, on really straight long places. (I'm no UV wrapper, but I do think that is possible to tile just parts, right?)
2. Yes, baking lighting uses texture space, but you could use different LOD's (level of detail's) to create your lighting. For instance, you could choose to just create a low-quality image as your baked lightmap.
3. Yes, you will need two UV sets, because this is way better than baking your tiled bricks into the lighting map as well. UV maps are just a matter of asking what the coordinates are (which is fast), so storing an extra UV maps isn't that much of a burden.
4. Shouldn't know what to add. It seems very clear. Just create 2 UV maps and create a lightmap if you want. It is always faster than casting realtime shadows.

---
Tags: textures, lighting, uv-mapping
---


title: 'Binary XML' for game data?

text:
# Question
Title: 'Binary XML' for game data?
I'm working on a level editing tool that saves its data as XML.

This is ideal during development, as it's painless to make small changes to the data format, and it works nicely with tree-like data.

The downside, though, is that the XML files are rather bloated, mostly due to duplication of tag and attribute names. Also due to numeric data taking significantly more space than using native datatypes. A small level could easily end up as 1Mb+. I want to get these sizes down significantly, especially if the system is to be used for a game on the iPhone or other devices with relatively limited memory.

The optimal solution, for memory and performance, would be to convert the XML to a binary level format. But I don't want to do this. I want to keep the format fairly flexible. XML makes it very easy to add new attributes to objects, and give them a default value if an old version of the data is loaded. So I want to keep with the hierarchy of nodes, with attributes as name-value pairs.

But I need to store this in a more compact format - to remove the massive duplication of tag/attribute names. Maybe also to give attributes native types, so, for example floating-point data is stored as 4 bytes per float, not as a text string.

Google/Wikipedia reveal that 'binary XML' is hardly a new problem - it's been solved a number of times already. Has anyone here got experience with any of the existing systems/standards? - are any ideal for games use - with a free, lightweight and cross-platform parser/loader library (C/C++) available?

Or should I reinvent this wheel myself?

Or am I better off forgetting the ideal, and just compressing my raw .xml data (it should pack well with zip-like compression), and just taking the memory/performance hit on-load?

# Answer
> 18 votes
We used binary XML heavily for *Superman Returns: The Videogame*. We're talking thousands and thousands of files. It worked OK, but honestly didn't seem worth the effort. It ate up a noticeable fraction of our loading time, and the "flexibility" of XML didn't scale up. After a while, our data files had too many weird identifiers, external references that needed to be kept in sync, and other strange requirements for them to really be feasibly human-edited any more.

Also, XML is really a markup format, and not a data format. It's optimized for a lot of text with occasional tags. It isn't great for fully structured data. It wasn't my call, but if it had been and I knew then what I know now, I probably would have done JSON or YAML. They're both terse enough to not require compaction, and are optimized for representing *data*, not *text*.

# Answer
> 12 votes
Store and edit your levels as normal XML, but have your game engine lazily bake it into binary XML during loading, and save the binary XML back to the disk so that it can load that next time (if the raw XML hasn't changed).

Something like this:

```
data loadXml(xmlFile)
{
    if (xmlFile has changed OR binFile doesn't exist)
    {
        binFile = convertToBinary(xmlFile)
        save(binFile)
    }
    return loadBinaryXml(binFile)
}

```

That way you get the best of both worlds. On release, you just need to make sure all the binary files are there.

# Answer
> 5 votes
Google Protocol Buffers seem like the way to go, but I haven't used them myself.
http://code.google.com/p/protobuf/

You define a .proto file which describes the file format:

```
message Person {
  required int32 id = 1;
  required string name = 2;
  optional string email = 3;
}

```

This is then compiled with a command line tool which generates C/C++ classes to write and parse binary data files in the previously defined data format. There are also a couple of extension for different programming languages.

The downside to ProtocolBuffer is that they aren't a plaintext format. You would need a tool to generate, read and edit them. But this shouldn't be a problem if you're using them only to exchange data between your game editor and your game. I wouldn't use it to define config files ;)

Compressing the raw xml files should also work. What type of game are you making? If it is level-based then you should load all necessary resources only once when the level is loaded.

**update:** There are several projects for other languages such as C# to work with ProtocolBuffers:
http://code.google.com/p/protobuf/wiki/ThirdPartyAddOns

# Answer
> 4 votes
What about the JSON-format?

http://www.json.org/xml.html

# Answer
> 4 votes
## Use JSON.

(Building on Munificent's response, and largely in response to your concerns expressed elsewhere)

You've mentioned concern that JSON has the issue of wasting space naming elements, like XML. It doesn't.

JSON is built on two structures: name/value pairs (**objects**) and ordered lists of values (**arrays**). XML is built *only* on name/value pairs.

If you think JSON relies on objects you've been reading JSON that's built to be self-descriptive and human-readable, like this (using octal digit pairs to represent single bytes):

```
{
    "some": ...,
    "data": ...,
    "fields": ...,
    "cars": [
        {"name":"greg","cost":8C,"speed":FA,"age":04,"driverID":384FFFFF},
        {"name":"ole rustbucket","cost":00,"speed":00,"age":2A,"driverID":04FF54A9}
    ]
}

```

However you also have the option of writing it like this, so long as you know where everything will be (and so can look for index 4, rather than object "cars", to get your list of cars):

```
{
    [
        ...,
        ...,
        ...,
        [["greg",8C,FA,04,384FFFFF],["ole rustbucket",00,00,2A,04FF54A9]],
        ...,
    ]
}

```

Does it get more concise than just having `[`, `]`, `,` and your values?

Well, it does if you're willing to just get closer and closer to a pure binary stream.

```
"cars":{"names":["greg","ole rustbucket"],"stream":8CFA04384FFFFF00002A04FF54A9}
or
[["greg","ole rustbucket"],8CFA04384FFFFF00002A04FF54A9]

```

Just don't shoot yourself in the leg by optimising too much.

# Answer
> 2 votes
I know you've accepted an answer, but Google both "Fast Infoset" (binary XML) and vtd-xml.

Although latter (VTD) might not resolve the compression aspect of you XML usage, it might speed up node access across large files, considerably (it uses a binary offsets 'dictionary' to jump to nodes, and *doesn't* create objects for each node, instead work on the original XML string). Therefore, it's XML lookup are \[said to be\] both faster and it doesn't require as much in-process memory to access/manipulate the XML doc.

Both of the above have bindings in the popular languages (which include C#).

Cheers

Rich

# Answer
> 1 votes
You could try Karvonite. It's supposed to be agile. It's a persistence framework that will adapt to the changes in your data fairly well (which is nice compared to handling binary your self). I'm not actually sure how the data is structured, but the files are a lot smaller than xml bloated files. (I'm assuming it saves the data in a binary format instead of text like xml)

The only con I can think of with this is that if your data gets corrupted or some how messed up in a way that Karvonite doesn't like it, your kind of at the mercy of it's creators unless you figure out how the structure of the data works.

The way you specify how to save/load your data is you just open up their persistence editor, import your assembly with all the data objects and check some check boxes to show what objects you want supported and what fields/properties to save.

It might be worth a try. Since your using C#, this fits right in with your language since it works with XNA (Windows, Xbox360, and Windows Phone 7 which I think your interested in since you mentioned the iPhone?).

Edit: Just noticed your only using C# for the tools. This probably wouldn't fit very well in your workflow. For some reason I had XNA in my head.

---
Tags: tools, xml, compression
---