title: Yet another frustum culling question

text:
# Question
Title: Yet another frustum culling question
This one is kinda specific. If I'm to implement frustum culling in my game, that means each one of my cubes would need a bounding sphere. My first question is can I make the sphere so close to the edge of the cube that its still easily clickable for destroying and building? Frustum culling is easily done in XNA as I've recently learned, I just need to figure out where to place the code for the culling. I'm guessing in my method that draws all my cubes but I could be wrong. My camera class currently implements a bounding frustum which is in the update method like so

```
   frustum.Matrix = (view * proj);

```

Simple enough, as I can call that when I have a camera object in my class. This works for now, as I only have a camera in my main game class. The problem comes when I decide to move my camera to my player class, but I can worry about that later.

```
    ContainmentType CurrentContainmentType = ContainmentType.Disjoint;
    CurrentContainmentType = CamerasFrustrum.Contains(cubes.CollisionSphere);

```

Can it really be as easy as adding those two lines to my foreach loop in my draw method? Or am I missing something bigger here?

UPDATE: I have added the lines to my draw methods and it works great!! So great infact that just moving a little bit removes the whole map. Many factors could of caused this, so I'll try to break it down.

```
    cubeBoundingSphere = new BoundingSphere(cubePosition, 0.5f);

```

This is in my cube constructor. cubePosition is stored in an array, The vertices that define my cube are factors of 1 ie: (1,0,1) so the radius should be .5. I least I think it should. The spheres are created every time a cube is created of course.

```
    ContainmentType CurrentContainmentType = ContainmentType.Disjoint;

        foreach (Cube block in cube.cubes)
        {
            CurrentContainmentType = cam.frustum.Contains(cube.cubeBoundingSphere);

    ///more code here

     if (CurrentContainmentType != ContainmentType.Disjoint)
            {
                cube.Draw(effect);
            }

```

Within my draw method. Now I know this works because the map disappears, its just working wrong. Any idea on what I'm doing wrong?

# Answer
> 1 votes
**answer:**

A bounding sphere for a cube will not have a radius of `0.5`. If the furthest point on a cube (a corner) has a model-local position of `+/-(0.5,0.5,0.5)` then the radius of the sphere must be equal to the length of that vector, or `sqrt(0.5*0.5 + 0.5*0.5 + 0.5*0.5)=0.86602540378`. A radius of `0.5` will make a sphere that touches the midpoints of the cube's faces but which does not include the corners (a midpoint along the X axis would be at `(+/-X,0,0)` for instance putting it at radius `sqrt(0.5*0.5 + 0*0 + 0*0)=0.5`, which is too small to contain the whole cube).

**unsolicited advice:**

Really, though, bounding spheres are not ideal here. You have cubes. Why not use an AABB? They will more tightly fit your objects (perfectly fit them, in fact) and you can easily enough do an AABB-Frustrum collision test.

Furthermore, if you're doing the Minecrafty type of rendering, don't render individual cubes. You'll spend more time culling little cubes than you will rendering the actually visible ones. Precompute a full mesh for each "chunk" of the world and simply recompute this mesh whenever you add or remove a block. Now you can cull whole chunks, which will be relatively efficient, and rendering a whole chunk in a single draw call will be cheap and the built-in triangle clipping will be more than sufficient when only a part of a chunk is visible (most likely much quicker than culling each block).

To generate the mesh, do something like:

```
modify(chunk):
  clear chunk.mesh
  for each block in chunk.blocks:
    for each face in block.faces:
      if face is not adjacent to another block:
        add face to mesh

```

All your blocks' textures will need to be in a single atlas, of course.

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


title: How should I invoke a physics engine?

text:
# Question
Title: How should I invoke a physics engine?
I'm new to writing games. I'm planning to write a 2D battle game which may require an physics engine. Suppose I've written one, but how can I combine it with the main routine of my game? Should I attach it directly to the graphics render routine or put it in an individual thread? I've spent much time looking for some common approach, but found nothing. So can you reveal some basics idea for me, a newbie? Thanks!

P.S. There're many other problems I have to deal with if I choose to start a separate thread for the physics engine, for example, the lock problem, while from my intuition, I guess I'd better separate the render and the physics engine.

# Answer
> 3 votes
Physics has nothing to do with graphics, so certainly don't put it there. Really, physics is its own subsystem. It takes inputs from game logic (forces to insert into the system) and generates an updated game state (and generates messages for collision updates).

For integration, it's common to have something like:

```
game loop:
  pump events
  update input
  update AI
  update physics
  render

```

The physics update can generate events during collisions so that AI and other game logic can respond to them if appropriate (either by dispatching them immediately or putting them in a buffer for next frame) like triggers or falling damage or whatnot.

It's a huge fallacy to think that each component of the game should get its own thread. A game engine is inherently a serialized beast. If you have 3 systems and put each on their own thread you'll still be massively under-utilizing a 6- or 8-core system, and not even making benefit of the more common 4-core systems. Use a job system instead. Run the system in serial but have each system spawn multiple jobs (handled by a thread pool) to complete its work. Done right, each system scales up to the number of cores in the computer. Some systems demand their own threads for latency reasons (audio processing, networking) but the meat of the simulation benefits more from having many-thread-scalable individual systems rather than a parallel engine design.

---
Tags: physics, game-loop, multithreading, physics-engine
---


# Question
Title: How do games like Halo 3 save in-game footage?
I was just wondering how games (such as Halo 3, like the title says) save in-game replay? Since it gives the ability to look around at almost every possible angle it can't be a simple recording. What is the logic behind this? Here is a good example of what Halo 3's footage looks like.

# Answer
> 2 votes
Pretty much exactly the same as networking works, except they store the gamestate in a buffer rather than send it to a remote client.

The *replay* is just the playback of that buffer.

The buffer, and your Networking, will track (*at least*) the location, orientation, and *some* sort of state information about every object which can effect the game state determinism at that point in time. Things which are purely visual and have no impact on the game itself are not typically stored. E.g: Barrels in racing games which bounce off the player car but do not change the physics of the car, or the objects in the world.

How much, and exactly what data you need to store will depend on how your engine works and how it deals with determinism. You can at worst store every single transform for every single animatable node in every single character if your engine sucks and doesn't handle determinism well. If you have a very solid engine, you can store much less data possibly even just controller input, which is how Starcraft replays work. The disadvantage is that you have to simulate the entire state from the beginning of the replay, and cannot quickly jump to different points in time.

So, the answer is "It Depends". It also depends on what your replay requirements are: Do you need to jump to certain points in the replay? Will you play them back linearly? Do you just want to capture the "fun" bits? (and that is an entire different question on its own).

---
Tags: game-recording, screen-recording
---


# Question
Title: Mixing Objective-C and C++: Game Loop Parts
I'm trying to write all of my game in C++ except for drawing and game loop timing. Those parts are going to be in Objective-C for iOS.

Right now, I have ViewController handling the update cycle, but I want to create a GameModel class that ViewController could update. I want GameModel to be in C++. I know how to integrate these two classes. My problem is how to have these two parts interact with the drawing and image loading.

GameModel will keep track of a list of children of type GameObject. These GameObjects update every frame, and then need to pass position and visibility data to whatever class or method will handle drawing.

I feel like I'm answering my own question now (talking it out helps) but would it be a good idea to put all of the visible game objects into an array at the end of the update method, return it, and use that to update graphics inside ViewController?

# Answer
You want to try and avoid inter-mingling objective-c and c++ as much as possible, it will create code that is very hard to debug and even harder to understand by others potentially joining your project.

It is essential that you ground a sense of framework and work in a modular fashion in respect to how the platform wants to you to interact with objective-c modules and how your c++ modules fit with these.

If you're using c++, that indicates to me that you want to abstract away from objective-c and use c++ as your main language, then do so. Objective-c will only handle the low-tier ios system-specific features.

What purpose do you have for crossing the two languages over in such a complicated way, this speaks to me of bad software design and poor consideration of design methodologies.

I can only advise to keep it straight forward:

//Init In your ViewController.mm just invoke a main engine class(c++) such as:

```
-(void)viewDidLoad
{
/*unrelated ios-specific init code*/
[super viewDidLoad];

self.context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2];

engine = new engine();//your engine class, that contains init, update and draw methods

if(!self.context ||  ![EAGLContext setCurrentContext:self.context])
{
    NSLog(@"Failed to create ES context");
}

GLKView * view = (GLKView *)self.view;
view.context = self.context;

GRect screenRect = [[UIScreen mainScreen] bounds];
CGFloat screenWidth = screenRect.size.width;
CGFloat screenHeight = screenRect.size.height;

view.drawableDepthFormat = GLKViewDrawableDepthFormat16;

if(engine != NULL)
    engine->init(screenWidth, screenHeight);
}

```

//Update

```
-(void)update {
engine->update();
}

```

//Draw

```
- (void)glkView:(GLKView *)view drawInRect:(CGRect)rect
 {
   engine->draw((GLfloat)view.drawableWidth,(GLfloat)view.drawableHeight);
   [self.context presentRenderbuffer:GL_RENDERBUFFER];
 }

```

You will need to assert a solid architecture for communicating between your lower-level objective-c and higher-level c++ classes if you wish to use all the features the platform has to offer.
> 2 votes

---
Tags: c++, game-loop, objective-c
---


# Question
Title: Could someone explain why my world reconstructed from depth position is incorrect?
I am attempting to reconstruct the world position in the fragment shader from a depth texture. I pass in the 8 frustum points in world space and interpolate them across fragments and then interpolate from near to far by the depth:

```
highp float depth = (2.0 * CameraPlanes.x) / (CameraPlanes.y + CameraPlanes.x - texture( depthTexture, textureCoord ).x * (CameraPlanes.y - CameraPlanes.x));

// Reconstruct the world position from the linear depth
highp vec3 world = mix( nearWorldPos, farWorldPos, depth );

```

CameraPlanes.x is the near plane CameraPlanes.y is the far.

Assuming that my frustum positions are correct, and my depth *looks* correct, why is my world position wrong?

(My depth texture is of format GL\_DEPTH\_COMPONENT32F if that matters)

Thanks! :D

Update:

Screenshot of world position https://i.stack.imgur.com/RW8XG.jpg

So you can see it looks nearly correct. However as the camera moves, the colours (positions) change, which they shouldnt.

I *can* get this to work, if I do the following:

Write this into the depth attachment in the previous pass:

```
gl_FragDepth = gl_FragCoord.z / gl_FragCoord.w / CameraPlanes.y;

```

and then read the depth texture like so:

```
depth = texture( depthTexture, textureCoord ).x

```

However this will kill the hardware z buffer optimizations.

# Answer
After a while I came back to this question. I was using the OES\_depth\_texture extension. I found that the answer was explained here very well: http://www.opengl.org/wiki/Compute\_eye\_space\_from\_window\_space#From\_XYZ\_of\_gl\_FragCoord

I have used this method with success. Unfortunately all other methods did not work. At the end you get a vec4 eyePos which you can multiply by the inverse view matrix to get to world space.
> 0 votes

# Answer
yuumei, I do not believe you are accounting for the perspective divide in your calculations. You are correctly determining the depth in the *picture plane* in your first equation, but then using a simple linear interpolation (mix()).

See entry 12.070 here:

> **12.070 Why is there more precision at the front of the depth buffer?**
>
> After the projection matrix transforms the clip coordinates, the XYZ-vertex values are divided by their clip coordinate W value, which results in normalized device coordinates. This step is known as the perspective divide. The clip coordinate W value represents the distance from the eye. As the distance from the eye increases, 1/W approaches 0. Therefore, X/W and Y/W also approach zero, causing the rendered primitives to occupy less screen space and appear smaller. This is how computers simulate a perspective view.

This is why when you divide by the fourth coordinate in your alternative implementation the results are correct.

Incidentally, whenever I calculated the world space position from the depth buffer the method I used was to retrieve the picture plane depth (as you do), then project a ray with the camera properties for each pixel like so:

```
//Get depth value to resolve
    depthValue d = depthValues[i];

    //Compute clip-space coordinate of pixel
    float2 screenspace = ( (d.screenposition) / ((float2)(width,height)) ) * 2.0f - 1.0f;

    //Get direction of ray from camera through pixel
    float3 ray_direction = normalize(camera_forward.xyz + (camera_right.xyz * screenspace.x) - (camera_up.xyz * screenspace.y));

    //Reconstruct world position from depth: depth in z buffer is distance to picture plane, not camera
    float distance_to_camera = d.depth / dot(ray_direction, camera_forward.xyz);
    float3 world_position = camera_position.xyz + (ray_direction * distance_to_camera);

    positions[i] = (float4)(world_position, 1);

```

This is not as 'short' as some other methods to be found on-line; but this always worked for me and I cannot necessarily say the same of them!

Good Luck!
> 2 votes

---
Tags: opengl-es2, deferred-rendering
---


# Question
Title: In XNA, how should I organize content shared between projects?
I have an XNA library using several custom effects. They need to be accessed by:

1. a content pipeline project (models are built with the effect), and
2. projects that use my game library (they should be able to load a standalone instance of the effect).

Where should I put the `.fx` files for the custom effects? How do I access them from separate projects?

# Answer
> 1 votes
You can add the effects to a content project referenced by the game library project. I've done this for my own engine for effects, lighting textures, etc., that need to be accessible by both the engine and projects using the engine.

Simply add a new content project and make a content reference to it from the game library project. The effects will be built and embedded in the game library build and can be made accessible from outside the game library.

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


title: Lightmapping & runtime combine children

text:
# Question
Title: Lightmapping & runtime combine children
Is it possible to have lightmapping on runtime generated combine children in Unity? It is possible to bake combined meshes when they are done in the editor, but the .apk/.ipa size increases too much.

# Answer
> 1 votes
You could use LightProbes.

Create a `Light Probes Group` from the editor. When you bake the lightmap it will be populated with info on the various light sources.

If your combined model `MeshRenderer` are receving probes (check `Use Light Probes` in the inspector), then the shader can calculate approximated lighting coefficients sampling them from the probes structure at run time.

---
Tags: unity, 3d-meshes, lightmap
---


# Question
Title: Is using multiple canvas objects a good practice?
We're developing a jump and run game with HTML5 and JavaScript and have to build an own game framework for this. Here we have some difficulties and would like to ask you for some advice:

We have a "Stage" object, which represents the root of our game and is a global div-wrapper. The stage can contain multiple "Scenes", which are also div-elements. We would implement a Scene for the playing task, for pause, etc. and switch between them. Each scene can therefore contain multiple "Layers", representing a canvas. These Layer contain "ObjectEntities", which represent images or other shapes like rectangles, etc. Each Objectentity has its own temporaryCanvas, to be able to draw images for one entity, whereas another contains a rectangle.

We set an activeScene in our Stage, so when the game is played, just the active scene is drawn. Calling `activeScene.draw()`, calls all sublayers to draw, which draw their entities (calling `drawImage(entity.canvas)`). But is this some kind of good practice? Having multiple canvas to draw? Each game loop every layer-context is cleared and drawn again. E.g. we just have a still Background-Layer, … wouldn't it be more useful to draw this once and not to clear it every time and redraw it? Or should we use a global canvas for example in the Stage and just use this canvas to draw? But we thought this would be to expensive...

# Answer
This page contains an excellent list of optimizations that can be made to canvas. In the section labeled "Use multiple layered canvases for complex scenes" it describes why having multiple canvas objects is actually better in many cases because you don't have to redraw large expensive objects (background images) as frequently as smaller, fast moving ones (projectiles). Here is a tutorial to get you started. In a nutshell, simply create a number of canvases for things that require drawing differently and line them up with absolute positioning:

```
position:absolute;
left:0px;
top:0px;

```

Each canvas object can be named and layered using z-index:

```
<canvas id="layer1" style="z-index: 1;" />
<canvas id="layer2" style="z-index: 2;" />

```

Finally, draw to the different contexts:

```
function draw1() {
    context1... // draw background
}

function draw2() {
    context2... // draw character
}

function draw3() {
    context3... // draw bullets
}

```
> 8 votes

# Answer
Contre Jour does this, in fact. I don't know many details, but you may be able to find more technical notes from them. If you play their game, I believe each of the landmasses your character interacts with are canvases.

It seems to be a good idea to seperate your active portions of the game into canvases. For instance, if you were making an RTS, the command bar might make sense to be a seperate canvas to only redraw once in a while.
> 2 votes

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


title: Constrained/penalized distance function

text:
# Question
Title: Constrained/penalized distance function
Assume a character is located on a n by n grid and has to reach a certain entry on that grid. Its current position is `(x1,y1)`. Also on the same grid is an enemy with coordinates `(x2,y2)`. Each step algorithm randomly generates new candidate locations for the hero (if there are k candidates then there is a kx2 matrix of new potential locations.

What I need is some distance objective function to compare the candidates. I'm currently using `d1 - c * d2`, where `d1` is distance to the objective (measure in terms of number of pixels for each axis), `d2` is distance to the enemy and `c` is some coefficient (this is very much like a set-up for Lagrangian). It's not working very well though. I'd be quite keen to learn how what constrained distance function are used for similar cases.

Any suggestions are very much appreciated.

# Answer
> 1 votes
Based off your comments on the original question, what you are describing are two basic steering behaviors:

1. Avoidance (or flee): the character has to maintain as much distance as possible from the enemy.
2. Seek: the character needs to get closer to the entry point on the grid.

For each, generate a separate movement vector for the character. With avoidance, find the vector to the enemy and negate it (flip it 180 degrees). For seek, simply find the vector to the entry point.

Now the trick is to blend the two vectors. If both behaviors are equal priority, then add the two vectors. If you are moving on a grid, then you'll need to find the grid square closest to where the vector points and set that as the destination. Obviously if constraining movement speed is required, normalize the final vector and multiply by the character speed before determining the destination.

---
Tags: 2d, mathematics, algorithm
---


title: Shader Variable Types

text:
# Question
Title: Shader Variable Types
I have a simple question. what are the meaning of :

```
half4 myHalf;
myHalf.yyyy;
myHalf.xxzz;
// or
myHalf.yw

```

Thanks a lot !

# Answer
It's a simple answer! `half4` is a four component vector, using half precision floating point coordinates. The extensions you've shown are quick ways to create new vectors using the values from `myHalf`.

`myHalf.yyyy` is a four component vector with the values: `(myhalf.y, myhalf.y, myhalf.y, myhalf.y)`

`myHalf.xxzz` is a four component vector with the values: `(myhalf.x, myhalf.x, myhalf.z, myhalf.z)`

`myHalf.yw` is a two component vector with the values: `(myhalf.y, myhalf.w)`.
> 4 votes

---
Tags: opengl, directx, shaders, glsl, hlsl
---


# Question
Title: Using real football (soccer) names from the past?
Is it legal to use really old names in a manager style game? It there an expiration on name license rights?

# Answer
License rights are not public rights. Licensing rights are contracts given to a single company or individual. The terms of which are decided upon a case by case basis. The license is for the use of various things, including Brands, Trademarks and Logos.

In the case of people's names, it's the trademark that's being licensed. Trademarks never expire as long as they're in use (along with some paperwork and fees).

You need to go on a name by name basis, and check if any trademarks exist for the name you want to use. You can do a trademark search here for the US. When you find a trademark, you'll need to contact the owner and create a license agreement. If you don't find a trademark, use at your own risk! There's always the possibility you're breaking some other use law.

If you plan on doing this, it's highly recommended you get a lawyer for advice. Basing large decisions such as "am I breaking the law or not" shouldn't be left up to the advice of some stranger on the internet.
> 3 votes

---
Tags: legal, licensing
---


title: Rendering artifacts at a large scale

text:
# Question
Title: Rendering artifacts at a large scale
I'm a new to OpenGL or graphics in general. Trying to write a game with realistic scale. I had a perfectly fine rendering of earth at a small scale, but when I try to scale it up to 1:1 I get this artifact. Any ideas what this could be? I suspect it's because I am using floats, but I would rather avoid using doubles in the shader for performance reasons.

# Answer
When rendering massive 3D bodies can occur 2 problems, both of them related to precision.

1) Jitter: Most of today’s GPUs support only 32-bit floating-point values, which does not provide enough precision for manipulating large positions in planetary scale terrains. Jitter occurs when the viewer zooms in and rotates or moves, then the polygons start to bounce back and forth.

The best solution for this is to use "Rendering Relative to Eye Using the GPU" method. This method is described in the book "3D Engine Design for Virtual Globes" (I'm sure you can find it on the internet aswell) in where basically you have to set all your positions with doubles on CPU (patches, clipmaps, objects, frustrum, camera, etc) and then MV is centered around the viewer by setting its translation to (0, 0, 0)T and the doubles are encoded in a fixed-point representation using the fraction (mantissa) bits of two floats, low and high by some method (read about Using Ohlarik’s implementation and The DSFUN90 Fortran library).

Although the vertex shader requires only an additional two subtractions and one addition, GPU RTE doubles the amount of vertex buffer memory required for positions. This doesn’t necessarily double the memory requirements unless only positions are stored.

2) Depth Buffer Precision: Z-fighting. As we are rendering very large terrains, in this case: planets, the Z-buffer has to be HUGE, but it doesn't matter wich values you set for znear and zfar, there will always be problems.

As the Z-buffer depends on a float point interval, and also it is linear (although perspective projection is non linear) values near the eye suffer from Z-fighting because the lack of precision 32-bit floats have.

The best way to solve this problem is to use a "Logarithmic Depth Buffer" http://outerra.blogspot.com/2012/11/maximizing-depth-buffer-range-and.html

A logarithmic depth buffer improves depth buffer precision for distant objects by using a logarithmic distribution for zscreen. It trades precision for close objects for precision for distant objects. Since we are rendering with a LOD method, far objects require less precision because they have less triangles.

The problem you have (as I can see from the image you posted) is z-fighting. Try to solve it first by moving the znear to a very far plane and the zfar a little more close to the camera, for example, put znear in some range between the orbit of the satellite and your camera, and switch to 1000, 100, 10, 1 meters as you are approaching the surface of the planet, the zfar value can alway be set to a little more distant to the center of the planet, because is a fact that you will never see the back part of the sphere, so you cull half of the globe. If this solution doesn't fit your needs, go for the logaritmkc depth buffer.
> 5 votes

# Answer
Do *not* use real-life scales. You absolutely, positively, for-sure do not need them at all in this use case.

You give the example of satellites. They are a few dozen meters across usually. The earth is 12,742,000 meters in diameter. A satellite that is three dozen (36) meters wide is still 1/76166th the size of earth. If you can see the whole earth as a globe then your monitor cannot possibly render the satellite; it'd be significantly significantly smaller than a single pixel on even the highest end \>$30k medical-oriented displays on the market.

The point being that using "real meters" doesn't help you. You're either rendering a satellite in a visible way with the earth being a distant object that has no significant detail (so it can be a "tiny" sphere with a low-quality texture) or you're zoomed in to the earth (and can still use a "tiny" sphere with more heightmap data and higher-quality textures). Using meters for the earth does absolutely nothing mathematically in terms of making the earth more "real" nor simplifying all the hard parts of graphically rendering it. Using a near plane of 10000.0f just means that you can't get close to satellites or the earth's surface without it being clipped.

Instead, deal the LOD (level of detail). When you are far enough away to see the earth as a globe, render it as a small sphere with a reasonable unit size in graphics, say 10 or 100. After you close in enough, switch to a higher detailed model or set of textures and "reset" the camera to an equivalent position. Remember that an object twice as far away is half as large visually will help you work out the right math to use here. Using LOD, you can zoom in and out of the earth, surrounding space, individual satellites, etc. all without incurring float-precision problems.

Assuming I did all this math right: say a 40m satellite is at maximal low-earth orbit, ~2,000,000 meters. The earth does not need to be its "real" diameter to keep 1:1 scaling visually intact. If you put the camera right up against the farthest point on the satellite, the earth will still be 1/50000th the size than "normal" when rendered (2 million meters is 50000x larger than 40 meters). Keeping consistent units of meters hence means it only needs to be ~255 units wide if rendered at the same z-depth from the camera as the satellite. You can render the earth at a consistent 100 or even 10 units and scale it "slightly" to appear visually correct based on a function of distance to get the exact same visual effect as if you rendered it at a 1:1 ratio and set the camera at a "real" distance (and all the floating point impression you'll get as a result of that).

Far more likely, if you're close enough to the earth to see a satellite, the earth is not just a sphere anymore. You'll be looking at at a patch of the earth something like:

You now have no need to even think of the earth as a complete sphere. You'll be rendering a portion of the earth and trying to find a scale that lets you apply a height/normal map plus "zoomed-in" textures, which again can be rendered with units where 1 unit \> 1 meter. If a whole mountain is only 3 pixels wide, do you really need to represent that mountain as 5000 units=meters in width? Of course not.

You do however still need to completely change how you're rendering the earth. Your work is not going to be simplified in any significant capacity by using astronomical (literally) measures to represent objects. Most of your work is going to come into scene management, LOD, and so on.
> 5 votes

---
Tags: opengl, planet, spaces
---


# Question
Title: Ambiguation between multitouch geistures tap and free drag in Windows Phone 8 Emulator (Monogame)
I am making a 2d tile based tactic game. I want the map to be slided around (because it's bigger than the screen) with FreeDrag (It's perfectly done, the map can moved around, that's not the problem).

And then, I want to display the character's actions, everytime it's tapped.

The problem then appeared. Everytime I want to FreeDrag the map, the Tap trigger always fired first before the FreeDrag one. Is there any way to differ the map sliding than the character tapping? Below is my code.

```
while (TouchPanel.IsGestureAvailable)
{
    GestureSample gesture = TouchPanel.ReadGesture();
    switch (gesture.GestureType)
    {
        case GestureType.FreeDrag:
            {
                //a
            } break;
        case GestureType.Tap:
            {
                //b
            } break;
    }
}

```

Every time I first want to free drag (at the first touch), it always goes to "b" first (see commented line above), and then to "a" rather than immediately goes to "a".

I've tried flick, but it seems the movement produced by flick is too fast, so freedrag fits the most.

Is there any way or workaround to perform FreeDrag (or similar) without firing the Tap trigger?

Thanks in advance.

# Answer
> 2 votes
To be honest I've never used the gesture API so my answer might be wrong. However, I think I know how to solve your problem.

The idea is to perform action B only if action A has not already occurred and the only way to know this is to somehow detect when the user has released their finger. Since their is no Release gesture type you might be able to craft your own like this:

```
bool isTapped = false;
bool isDragged = false;

while (TouchPanel.IsGestureAvailable)
{
    GestureSample gesture = TouchPanel.ReadGesture();
    switch (gesture.GestureType)
    {
    case GestureType.FreeDrag:
        {
           isDragged = true;
        } break;
    case GestureType.Tap:
        {
           isTapped = true;
        } break;
    }
}

if(isTapped && !isDragged)
{
    // b
}
else if(isDragged)
{
    // a
}

```

You might also need to use some tolerance checking on the Delta values to see if the user has actually dragged a significant distance. Not sure.

That said, it does seem odd that the API behaves this way, it could it be a bug in MonoGame. It might be worth bringing this up on their forums and/or checking it against the behavior of XNA.

# Answer
> 1 votes
Sorry, it seems that I pressed on a area not quick enough to freedrag. It's done well now if there is no delay between "tap" and drag to freedrag

---
Tags: monogame, windows-phone-8, multitouch, gestures
---


# Question
Title: How to tell what part of a 3D cube was touched
I am writing a rather simple android game and I am implementing Open GL to draw a 3D cube that spins upon the X, Y and Z axis and I need to know where the user has clicked on the texture of the cube.

The texture is a simple square bitmap (100x100) that has a smaller square in the center. I need to know if the user touches the inner square. As well was tell which face of the cube the user touches. Does anyone know how this can be accomplished if not can anyone give some pseudo code on how to tell where the ray correlates to the texture? Or at least point me in the right direction.

The textures of each face are like this:

The whole cube looks like this: https://docs.google.com/file/d/0BzmLnD4ub-ohaU9CM21WWC1GRW8/edit?usp=sharing

The code I am using is from: http://www3.ntu.edu.sg/home/ehchua/programming/android/Android\_3D.html2.9 It is a port to android from Lesson 6 NeHe. Example 6a: Photo-Cube

# Answer
If your hit test is really that simple, then instead of doing more complicated triangle intersection as Byte56 suggests you could do simple AABB-ray intersection test. The intersection test will tell you the point that was hit. This point in model space will lie on one of the faces (so one of X, Y, or Z will be `+/-h`, where `h` is the half-width of your cube). Assuming that the red square is one third the size of the cube itself, that means that the *other* two coordinates must both fall within `[-h/3,+h/3]` in order for the hit to have been the red area.

The triangle approach is also sensible, especially if you want to support more complicated shapes (you could represent any shape on a cube's face with a 2D function, but say you want to support tetrahedrons or something beside just cubes). Tessellate your shape's faces so that (for the cube example) a face is made up of more than a single quad. With one third being the desired hit area width of your cube you'd need 9 quads or 18 triangles for your face. You can then do a triangle-ray collision test. Check if the collided triangles are the ones making up the central quad of any particular face to register hits to the red area.
> 3 votes

---
Tags: opengl, android, textures, touch, picking
---


# Question
Title: Which Graphics/Geometry abstraction to choose?
I've been thinking about the design for a browser app on the HTML5 canvas that simulates a 2D robot zooming around, sensing the world around it. I decided to do this from scratch just for fun. I need shapes, like polygons, circles, and lines in order to model the robot and the world it lives in. These shapes need to be drawn with different appearance attributes, like border/fill style/width/color. I also need to have geometry functions to detect intersections and containment for the robot's sensors and so that the robot doesn't go inside stuff.

One idea for functions is to have two totally separate libraries, one to implement graphics (like `drawShape(context, shape)`) and one for geometry operations (like `shapeIntersectsShape(shape1, shape2)`). Or, in a more object-oriented approach, the shape objects themselves could implement methods to do their own graphics (`shape.draw(context)`) and geometry operations (`shape1.intersects(shape2)`).

Then there is the data itself: whether the data to draw a shape and the data to do geometric operations on that shape should be encapsulated within the same object, or be separate structures (where one would contain the other, or both be contained inside another structure).

How do existing applications that do graphics/geometry stuff deal with this? Is there one model that is best, or is each good for certain applications? Should the fact that I'm using Javascript instead of a more classical language change how I approach the design?

# Answer
Do *not* make shapes draw themselves. That is a huge problem with naive object-oriented design. Avoid coupling, even at the interface layer. The computer does not need a shape to be able to draw objects (it'll usually be working with more complex models only or sprites which are only loosely approximated by a shape for collision) nor does a shape need dependency on the graphics system in order to exist. The concept of a high-level shape and the concept of a low-level graphics API are entirely orthogonal.

You might have a helper library which can take a shape and the renderer and generate the right darawing commands for the shape. This way all the logic that needs this coupling between shapes and graphics is moved out to a separate place. Since you probably won't be drawing shapes for any reason besides debugging collisions, you might make this part of your `DebugDraw` system. (it's useful to have a module which can draw simple shapes and lines and overlay text to help debug physics, AI, and so on.)

Whether you use an OO approach is a matter of taste. I've been turned off to the OO approach for geometric shapes over the years, but that's me.
> 6 votes

---
Tags: graphics, geometry
---


# Question
Title: Shear transformation in the projection matrix?
I am trying to understand what the shear transformation (l+r/r-l & b+t/t-b) is actually doing in the projection matrix? The only thing I got till now is headache :) Can you please help?

# Answer
Those components come into play when making an "off-center" projection. They are normally zero, since people usually set the left and right edges to be equal and opposite - for instance, L = -1 and R = +1, which makes (L + R)/(R - L) = 0/2 = 0. Similarly for the top and bottom edges. This makes a projection whose center (the point where all the rays converge) is behind the center of the screen, which is normally what's desired.

However, by setting the left/right/top/bottom edges to values that aren't equal and opposite, you can put the center of projection anywhere on screen, or even off the screen entirely. One use case for this is in stereo 3D projection, where the two eyes look at the same screen, but each sees a different vanishing point. There's a paper about this here: Generalized Perspective Projection.
> 3 votes

---
Tags: matrix, projection, view, transformation
---


# Question
Title: Auto-organized / smart inventory system?
for the past week I've been working on an inventory system with Unity3D. At first I got help from the guys at Design3 but it wasn't too long till we split path, because I really didn't like the way they did their code, it didn't have any smell of OOP whatsoever.

I took it further steps ahead - items take more than one slot, advanced placement system (items tries their best to find the best close fit), local mouse system (mouse gets trapped in active bag area), etc.

Here's a demo of my work.

What we would like to have in our game, is an auto-organizing feature - not auto-sort. We want this feature because our inventory's going to be in 'real-time' - not like in Resident Evil 1,2,3 etc where you would pause the game and do things in your inventory. Now imagine your self in a sticky situation surrounded by zombies, and you don't have bullets, you look around, you see that there are bullets nearby on the ground, so you go for them and try to pick them up, but they don't fit! you look at your inventory and find out that if you reorganize some of the items, it will fit! - now the player - in that situation doesn't have time to reorganize because he's surrounded with zombies and will die if he stops and organizes the inventory to make space (remember inventory in real-time, no pausing) - wouldn't it be nice for that to happen automatically? - Yes!

(I believe this has been implemented in some games like Dungeon siege or something, so sure it's doable)

take a look at this picture for example:

Yes, so if you auto-sort the issue you will get your spaces but it's bad because: 1- Expensive: it doesn't need a whole sort operation to free those spaces, in the first picture, just slide the red item at the bottom to the very left, and you get the same spaces that you got from the auto-sort. 2- It's annoying to the player: "Who the F told you to re-order my stuff?"

I'm not asking for "How to write the code" for this, I'm just asking for some guidance, where to look, what algorithms are involved? Is this something related to graphs and shortest path stuff? I hope not cuz I didn't manage to continue my college studies :/ But even if it is, just tell me and I will learn the stuff related.

Notice there could be more than just one solution. So I guess the first thing I have to do is figure out if the situation is 'solvable' - if I know how to determine if a situation is solvable or not, then I can 'solve' it. I just need to know the conditions that makes it 'solvable'. And I believe there must be some algorithm/data structure for this.

Here's a pic for more than one solution of trying to fit a 1x3 item:

The arrows show just one of the solutions, but if you look you will find more than one. This is what I ultimately not auto-sorting but find a solution and applying it.

Note that if I spend time on it I will come up with a way to solve it, but it wouldn't be the best way, it's like, holding a car wheel with your feet instead of your hands! XD Or just like trying to solve an issue that requires arrays, but you're not yet aware of their existence! So what is the right approach to this?

**Updates from Commentary**

@Stephen I'm really no guru in Alogs, you mentioned 'knapsack' and @BlueRaja - Danny Pflughoeft mentioned a 2D bin packing algo. Are they somehow related/same? - I'm still confused as to how should I approach this.

And yes I'm already using a "heuristic" but I didn't really know that I was :D it finds the first available slot, and see if the item fits there.

I don't know if ordering items based on their "bulkiness" (which I call nSlotsRequired=nRowsReq\*nColsRec) would work, because you have a 2x2 and 1x4 items for example, they have the same bulkiness, but different shapes and will have a different effect on how the rest of the items next will go. SO... :/

I watched this video, I really liked the full packing idea, but I wonder how to go about it since the inventory is 2D. I'm not even sure that bin packing is the key here because, well it's true that I can have more than one bag, but in our game it's just gonna be one bag. So, it's a matter of fitting items in 'one' bag and not more than that. So the examples in that vid (the pipes and buses) don't really match with my problem. Also watched some stuff about this knapsack thing, I didn't see how the 'value' is related to my items/inventory, but I guess 'weight' is the same as bulkiness, not sure.

# Answer
This is a variation of the knapsack problem. As Danny Pflughoeft mentions it's NP-Complete. Meaning that it can't be solved in linear time, if I remember correctly.

But you can try to solve this in several steps. It's basically a sorting problem.

I would start by calculating the 'bulkiness' of each item: this could be calculated several ways:

* bulkiness = max(length, width);
* bulkiness = length\*width
* bulkiness = sqrt(length\*width)

Then start putting items with the highest score first into the inventory. Since they most likely won't fit into the remaining space later. Small items will fit always.

You need an heuristic (a fancy name for educated guessing ;-) ) for your placing strategy. Something like trying to fit items in the first free slot from top-left or something.

Diablo II inventory sorting strategy worked somewhat similar I think. Stuff like swords and spears would end up top left, then clothes and armor, then buckler and so on.

I think you really need to try this out and tweak the algorithm (different bulkiness calculation, different heuristic), until it works reasonable enough.
> 9 votes

# Answer
Haha, @Everybody who helped, thanks. I managed to finally solve it. Here's what I basically did:

```
IEnumerator AddItem_Sorted (Item item)

```
1. Trivial condition: check if we got the min nRequiredSlots for the item to fit in, if we do have it, proceed...
2. we'll empty out all the bag - putting the items in a placeholder (list or something)
3. add the wanted item to the VERY last slot/place it could fit in, making sure it's sure in its horizontal shape
4. using the first-fit decreasing algo we'll add the rest of our items
5. during the adding, we'll use dynamic programming (memoisation) to remember that index that we're adding at (index of next available slot)
6. if all adding is success, we have managed to fit our wanted item, and somehow sort the bag - from big to small items
7. if we couldn't add all the items, this means that, this wasn't a solvable situation, so we have to get the bag to its previous state
8. one way to do that, (came out of my mind's surface), is to copy the state of the bag before this whole opperation, and then if it fails we'll snap to that previous state, or even better, in during the 'emptying' of the bag, we memorize where each item was, so that if the op fails, we'll get them back - using AddItem(item, index) - at their previous indices :)
9. this whole process might take time, so we could divide the load on separate frames, using my lovely yield :)
10. DONE! \m/ (@~9:00)

UPDATE:

1. I made an array that stored the indices of all the added items, that way I don't have to go and look for the occupied slots for me to free - big boost.
2. no need to add at the last slot, in fact sometimes it might not work that way, I've added the wanted item to the rest of the other items and sorted it with them.

As you can see from the video, it needs a bit of optimizing, the sorting is not perfect, I would like to use full bin packing, but it's already performance-greedy. I'm open to any optimization suggestions, thanks again :)
> 3 votes

---
Tags: algorithm, unity, inventory
---


# Question
Title: Quaternions, Axis Angles and Rotation Matrices. Which of these should I use for FP Camera?
After 2 weeks of reading many math formulas and such I know what is a Quaternion, an Axis Angles and Matrices. I have made my own math libary (Java) to use on my game (LWJGL). But I'm really confused about all this.

I want to have a 3D first person camera. The move (translation) is working fine but the rotation isnt working like I need. I need a camera to rotate arround world Axis and not about its own axis. But even using Quaternions, this doesnt work and no matter how much I read about Euler Angles, everybody says to me dont touch on it!

This is a little piece of code that i'm using to make the rotation:

```
    Quaternion qPitch = Quaternion.createFromAxis(cameraRotate.x, 1.0f, 0.0f, 0.0f);
    Quaternion qYaw = Quaternion.createFromAxis(cameraRotate.y, 0.0f, 1.0f, 0.0f);

    this.multiplicate(qPitch.toMatrix4f().toArray());
    this.multiplicate(qYaw.toMatrix4f().toArray());

```

Where `this` is a Matrix4f view matrix and cameraRotate is a Vector3f that just handle the angles to rotate obtained from mouse move. So I think I'm doing everything right:

1. Translate the view Matrix
2. Rotate the Move Matrix

So, after reading all this, I just want to know: To obtain a correct first person camera rotate, I must need to use Quaternios to make the rotations, but how to rotate around world axis?

**EDIT:**

OK, i'm following **@Sean Middleditch** solution and this should be good, but I think i've missed something...here is the code:

```
public Matrix4f getView() {
    if (!viewChanged) return viewMatrix;
    if (position == null) position = Vector3f.createEmpty();
    if (rotation == null) rotation = Vector3f.createEmpty();

    viewMatrix = Matrix4f.createIdentity();
    viewMatrix.rotate(rotation);

    Vector4f forward = Vector4f.multiplicate(viewMatrix, new Vector4f(0, 0, -1, 0));
    Vector4f up = Vector4f.multiplicate(viewMatrix, new Vector4f(0, 1, 0, 0));
    Vector4f right = Vector3f.cross(forward.toVector3f(), up.toVector3f()).toVector4f();

    viewMatrix = new Matrix4f(new float[]{
            right.x,                                        up.x,                                       -forward.x,                                     0,
            right.y,                                        up.y,                                       -forward.y,                                     0,
            right.z,                                        up.z,                                       -forward.z,                                     0,
            -Vector4f.dot(right, position.toVector4f()),    -Vector4f.dot(up, position.toVector4f()),   -Vector4f.dot(forward, position.toVector4f()),  1
    });

    setViewChanged(false);
    return viewMatrix;
}

```

Everything seems to be right, but the "Camera" is rotating now over the origin axis...and I think the problem is because I didnt understand the following:

> construct a regular rotation matrix, and then multiply the standard camera vectors by that matrix

Thanks for reading it.

Best regards,

Afonso Lage

# Answer
Don't use quaternions here. Whoever told you to avoid Euler angles for first-person cameras was not speaking from experience.

A possible choice, if you really want to avoid Euler angles, is to store explicit `view` (`forward`) and `right` vectors. You can then modify your yaw by rotating both vectors around `(0,1,0)`. I assume you have an implicit "always up" vector like this; most FPS games do. You can modify pitch by rotating both vectors around the right vector, which is `cross(view,up)`.

It's easier still to just store the Euler angles, construct a regular rotation matrix, and then multiply the standard camera vectors by that matrix.

```
// if you don't store the vectors pre-calculated
rotation = rotate(yaw,pitch,row)
forward = rotation * vec4(0,0,-1,0)
up = rotation * vec4(0,1,0,0)
right = cross(forward, up)

// maybe the transpose for your matrix class, don't know
camera = mat44(
   right.x, right.y, right.z, -dot(right, pos),
   up.x, up.y, up.z, -dot(up, pos),
   -forward.x, -forward.y, -forward.z, -dot(forward, pos),
   0, 0, 0, 1)

```

Euler angles can cause some problems in some contexts, but not generally here. Unless you're making a free-form space shooter, odds are that you will have constraints on the pitch (something like `(-pi/2,+pi/2)`) and will not allow free control of roll. The problems with gimbal lock, which are made out to be a much larger problem than they really are, will not be an issue for you in this use case.

Take a look at gluLookTo for more information on constructing a camera matrix.
> 3 votes

---
Tags: java, camera, lwjgl, quaternion
---


# Question
Title: Is it important for reflection-based serialization maintain consistent field ordering?
I just finished writing a packet builder that dynamically loads data into a data stream for eventual network transmission. Each builder operates by finding fields in a given class (and its superclasses) that are marked with a `@data` annotation.

When I finishing my implementation, I remembered that `getFields()` does not return results in any specific order.

Should reflection-based methods for serializing arbitrary data (like my packets) attempt to preserve a specific field ordering (such as alphabetical), and if so, how?

# Answer
> 2 votes
If your system can *deserialize* the data on the other end regardless of the field order, you don't *need* to enforce that order. But you probably want to anyway, because it's better.

If you have any dependency on that ordering (as in, you enumerate the results of `getFields()` on the receiving end and deserialize each field in succession), you had best make sure you have control over it, or you will end up tracking down a very subtle-looking bug a long way in the future. Then you'll really kick yourself. This is the most important reason to order the fields, but it will also be useful for a programmer to know the expected ordering when he or she works on the system, or its data.

There are a few downsides to some ordering methods. They have the potential to introduce diffs within the middle of the serialized data, which can make versioning a chore (append-only versioning is much easier to deal with). If you can guarantee that you won't interoperate data between versions, this is less of a concern.

It's usually hard to get reflection APIs to return results in code-declaration order. So any ordering method (alphabetical, size, name hash, whatever) will have some disconnect with the layout of the structure as read by a programmer. At least with a defined, enforced ordering you know what that disconnect will be. The ordering of `getFields` shouldn't be relied on and could potentially change underneath you when you least expect it.

---
Tags: java, packet, code-reflection
---


# Question
Title: GL_GENERATE_MIPMAP vs. GL_MAX_TEXTURE_SIZE
If we generate mipmaps for a texture using `GL_GENERATE_MIPMAP` (or `glGenerateMipmap`), how big can the original texture be? Is it the size returned by `GL_MAX_TEXTURE_SIZE`, or half of it?

# Answer
> 2 votes
It might be neither. The value of `GL_MAX_TEXTURE_SIZE` is not to be trusted, as the specification calls it a "rough estimate of the largest texture that the GL can handle". It might be much smaller, it might even be larger, depending on the `format`, `internalformat` and `type` parameters of `glTexImage2D`.

The correct way to determine whether or not a texture is too large, is to use texture proxies. Then just trust `glGenerateMipmap()` will succeed. (The documented failure modes for `glGenerateMipmap()` don't say anything about a maximum size.)

If you want to be really sure, you could check the sizes of each mipmap level using `glGetTexLevelParameteriv()` to see if all went well.

---
Tags: opengl, mipmaps
---


# Question
Title: Improving performance of a particle system (OpenGL ES)
I'm in the process of implementing a simple particle system for a 2D mobile game (using OpenGL ES 2.0). It's working, but it's pretty slow. I start getting frame rate battering after about 400 particles, which I think is pretty low.

Here's a summary of my approach:

I start with point sprites (`GL_POINTS`) rendered in a batch just using a native float buffer (I'm in Java-land on Android, so that translates as a `java.nio.FloatBuffer`).

On GL context init, the following are set:

```
GLES20.glViewport(0, 0, width, height);
GLES20.glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
GLES20.glEnable(GLES20.GL_CULL_FACE);
GLES20.glDisable(GLES20.GL_DEPTH_TEST);

```

Each draw frame sets the following:

```
GLES20.glEnable(GLES20.GL_BLEND);
GLES20.glBlendFunc(GLES20.GL_ONE, GLES20.GL_ONE_MINUS_SRC_ALPHA);

```

And I bind a single texture:

```
GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textureHandle);
GLES20.glUniform1i(mUniformTextureHandle, 0);

```

Which is just a simple circle with some blur (and hence some transparency)

http://cl.ly/image/0K2V2p2L1H2x

Then there are a bunch of `glVertexAttribPointer` calls:

```
mBuffer.position(position);
mGlEs20.glVertexAttribPointer(mAttributeRGBHandle, valsPerRGB, GLES20.GL_FLOAT, false, stride, mBuffer);

...4 more of these

```

Then I'm drawing:

```
GLES20.glUniformMatrix4fv(mUniformProjectionMatrixHandle, 1, false, Camera.mProjectionMatrix, 0);
GLES20.glDrawArrays(GLES20.GL_POINTS, 0, drawCalls);
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, 0);

```

My vertex shader does have some computation in it, but given that they're point sprites (with only 2 coordinate values) I'm not sure this is the problem:

```
#ifdef GL_ES
// Set the default precision to low.
    precision lowp float;
#endif

uniform mat4 u_ProjectionMatrix;

attribute vec4 a_Position;
attribute float a_PointSize;
attribute vec3 a_RGB;
attribute float a_Alpha;
attribute float a_Burn;

varying vec4 v_Color;

void main()
{
vec3 v_FGC = a_RGB * a_Alpha;
v_Color = vec4(v_FGC.x, v_FGC.y, v_FGC.z, a_Alpha * (1.0 - a_Burn));
    gl_PointSize = a_PointSize;
    gl_Position = u_ProjectionMatrix * a_Position;
}

```

My fragment shader couldn't really be simpler:

```
#ifdef GL_ES
    // Set the default precision to low.
    precision lowp float;
#endif

uniform sampler2D u_Texture;
varying vec4 v_Color;

void main() {
    gl_FragColor = texture2D(u_Texture, gl_PointCoord) * v_Color;
}

```

That's about it. I had read that transparent pixels in point sprites can cause issues, but surely not at only 400 points?

I'm running on a fairly new device (12 month old Galaxy Nexus).

My question is less about my approach (although I'm open to suggestion) but more about whether there are any specific OpenGL "no no's" that have leaked into my code.

I'm sure there's GL master out there facepalming right now... I'd love to hear any critique.

# Answer
This may not be a general answer, but in my case the problem was state change in native buffers.

My particles are drawn in a batch using an approach similar to sprite batching but obviously with GL\_POINTS rather than quads (or GL\_TRIANGLES). Every time a particle is "drawn" an instruction is sent to the batch with the location/color/size information for the particle (point), then once all particles are "drawn" the batch executes a single glDrawArrays call.

This is (was) implemented by writing the location/color/size information to a native buffer for each "draw" call on a particle.

I didn't ever get gl profiling to work, but normal Java profiling revealed that writing to the native buffer (java.nio.FloatBuffer) is incredibly slow (not really surprising) so now rather than writing every particle's information to the native buffer I simply hold them in heap memory until the draw call is ready to execute then send them all down to the native buffer in one hit.

There may be an optimal middle ground here (i.e. a balance between writing large amounts of data to native buffers once vs frequent small writes) but for now doing one single large write seems to be ok.
> 2 votes

# Answer
An approach I use to avoid computing particle positions on the CPU and updating buffers on the GPU is to instead procedurally generate everything on the GPU's shaders.

If you create a buffer of random numbers, and another random number for the particular particle effect instance, you can use these numbers in your shader to to decide, for any given time point, where a particle would and the rest of its state.

And although you are re-using this exact same little VBO for each and every particle system, and many may be visible on-screen at the same time, no two particle systems look the same!

I've used it for 2D flame effects and even for particles that follow moving objects in 3D. There are obvious limitations - particles that react with other things in the scene e.g. bounce off walls - cannot be modelled easily this way.

Here's some example code for a flame-effect vertex shader from my barebones.js engine:

```
attribute float aLifetime;
attribute float aXPos;
attribute float aYSpeed;
attribute vec2 aColor;
uniform mat4 mvp;
uniform float uTime;
uniform float uPointSize;
varying float vLifetime;
varying vec2 color;
uniform float randseed;
float rand(float f) {
    return fract(456.789*sin(789.123*f*randseed)*(1.+f));
}
void main(void) {
    float lifetime = mix(0.0,2.0,rand(aLifetime))+1.0;
    vLifetime = mod(uTime,lifetime);
    float ti = 1. - vLifetime/lifetime;
    gl_Position = mvp * vec4(mix(-1.0,1.0,rand(aXPos))*ti,
        mix(0.0,0.7,rand(aYSpeed))*vLifetime - 1.,
        0., 1.);
    vLifetime = 4.*ti*(1. - ti);
    color = aColor;
    gl_PointSize = uPointSize;
}

```

My blog post about it.

For 3D effects, here's how to scale the point size with distance from camera.
> 0 votes

---
Tags: opengl-es, performance, particles
---


title: Edge Detection on Screen

text:
# Question
Title: Edge Detection on Screen
I have a edge collision problem with a simple game that i am developing. Its about throwing a coin across the screen. I am using the code below to detect edge collisions so i can make the coin bounce from the edges of the screen.

Everything works as i want except one case. When the coin hits left edge and goes to right edge the system doesnt detect the collision. The rest cases are working perfectly, like hitting the right edge first and then the left edge.

Can someone suggest a solution for it?

```
public void onMove(float dx, float dy) {
 coinX += dx;
 coinY += dy;

  if (coinX > rightBorder) {
    coinX = ((rightBorder - coinX) / 3) + rightBorder;
  }
  if (coinX < leftBorder) {
    coinX = -(coinX) / 3;
  }
  if (coinY > bottomBorder) {
    coinY = ((bottomBorder - coinY) / 3) + bottomBorder;
  }

  invalidate();
}

```

# Answer
Your code should look something like this assuming you are movin from the center of the object.

```
onMove(...)
{
//check collision against right wall. to get the center, take the position and add the half of width. if that is bigger than our rightscreen edge. lets assume it´s 800.

float rightScreenEdge = 800.0f;
if( coinX + ( Width / 2 ) > rightScreenEdge )
{
//lets take the velocity and negate it to make it move the otherway.
    velocity.x = -velocity.x;
}
//lets check against the left corner, which is actualy 0 in screenspace.
else if( coinX - ( Width / 2 ) < 0 )
{
    velocity.x = -velocity.x;
}

coinX += velocity.x;
}

```

i hope this gives you the idea how it works.
> 1 votes

---
Tags: android, game-design, animation, screen
---


title: Undefined fireball movement behavior

text:
# Question
Title: Undefined fireball movement behavior
Demonstration video

I try to do after the player shoot 10 times of fireball, then delete all the fireball objects and recreate a 10 new set of fireball objects. I did it but there is a weird bug happens that sometimes the fireball will come out from top and move to the right after shooting a few times. All the 10 fireballs should follow the player all the time and all the fireball should come out from player even after a new set of fireballs is recreated. Any ideas to fix it?

Variables

```
typedef struct gameObject{
float X;
float Y;
int length;
int height;
bool action;
};

// Fireball
#define FIREBALL_NUM 10
LPDIRECT3DTEXTURE9 fireball = NULL;
RECT fireballRect;
gameObject *fireballDest = new gameObject[FIREBALL_NUM];
int iFireBallAnimation;
int fireballCount = 0;

```

Set up Fireball

```
void setUpFireBall()
{
    // Initialize destination rectangle, rectangle height and length
    for (int i = 0; i < FIREBALL_NUM; i++)
    {
        fireballDest[i].X = 0;
        fireballDest[i].Y = 0;

        fireballDest[i].length = fireballRect.right - fireballRect.left;
        fireballDest[i].height = fireballRect.bottom - fireballRect.top;
    }

    iFireBallAnimation = fireballRect.right - fireballRect.left;

    // Initialize boolean
    for (int i = 0; i < FIREBALL_NUM; i++)
    {
        fireballDest[i].action = false;
    }
}

```

Initialize fireball

```
void initFireball()
{
    hr = D3DXCreateTextureFromFileEx(d3dDevice, "fireball.png", 512, 512,
    D3DX_DEFAULT, NULL, D3DFMT_A8R8G8B8, D3DPOOL_MANAGED,
    D3DX_DEFAULT, D3DX_DEFAULT, D3DCOLOR_XRGB(255, 255, 0),
    NULL, NULL, &fireball);

    // Initialize source rectangle
    fireballRect.left = 0;
    fireballRect.top = 256;
    fireballRect.right = 64;
    fireballRect.bottom = 320;

    setUpFireBall();
}

```

Update fireball

```
void update()
{
    updateAnimation();
    updateAI();
    updatePhysics();
    updateGameState();
}

void updatePhysics()
{
    motion();
    collison();
}

void motion()
{
    playerMove();
    playerJump();
    playerGravity();
    shootFireball();
    fireballFollowPlayer();
}

void shootFireball()
{
    if (keyArr['Z'])
        fireballDest[fireballCount].action = true;

    if (fireballDest[fireballCount].action)
    {
        fireballDest[fireballCount].X += 10;
        if (fireballDest[fireballCount].X > 800)
            fireballCount++;
    }
}

void fireballFollowPlayer()
{
    for (int i = 0; i < FIREBALL_NUM; i++)
    {
        if (fireballDest[i].action == false)
        {
            fireballDest[i].X = playerDest.X - 30;
            fireballDest[i].Y = playerDest.Y - 14;
        }
    }
}

void updateGameState()
{
    // When no more fireball left, rearm fireball
    if (fireballCount == FIREBALL_NUM)
    {
        delete[] fireballDest;
        fireballDest = new gameObject[10];
        fireballCount = 0;
        setUpFireBall();
    }
}

```

Render fireball

```
void renderFireball()
{
    for (int i = 0; i < FIREBALL_NUM; i++)
    {
        if (fireballDest[i].action)
            sprite->Draw(fireball, &fireballRect, NULL, &D3DXVECTOR3(fireballDest[i].X, fireballDest[i].Y, 0), D3DCOLOR_XRGB(255,255, 255));
    }
}

```

# Answer
You are setting fireballCount to 0 in updateGameState, so I think the problem is that what is being animated and drawn is fireballDest\[0\], which is the first of the new fireballs and was just initialised with a position of (0, 0), which, presumably, is the upper right corner.
> 2 votes

---
Tags: c++, 2d, game-mechanics, movement, directx9
---


# Question
Title: Advantages And Disadvantages Of Resource Serialization
A good example is let's say I'm making a pong game. I have a PNG image for the ball and another PNG image for the paddles. Now which would be better, loading the PNG images with a PNG loader, or loading them in a separate program, serializing it, and de-serializing it in the game itself for use?

The reason why this may be good to know is because it seems like game companies (or anyone in the long run) build all of their resources into some sort of file. For example, in the game *Fallout: New Vegas* the DLCs are loaded as a *.ESM* file, which includes everything it needs, all the game does is find it, serialize it, and it has the resources. Games like *Penumbra: Black Plague* take a different approch and add a folder which contains all the textures, sounds, scrips, ect that it needs, but not serialized (it does this with the game itself, and the DLC).

Which is the better approch and why?

# Answer
> 4 votes
As with so many things, the answer is "Depends"

Do you need to load a couple of hundred megs of data quickly? Are you streaming data in as the player traverses the level? Are you reading from optical media?

If the answer is "yes", then pre-packed resource streaming is for you.

If you're just making pong. It's not really a big issue, loading flat resources is more than likely OK. If you're making commercial games, then yes, you want to minimise your level loading times and use pre-packaged data.

It boils down to this:

* A lot of the time in file I/O is simply opening files. If you're opening a lot of small files, you're going to be spending more time opening files than you'll spend reading them.
* Loading game ready data is typically a linear disk read. This is optimal for the way that our physical storage media works (aside from SSD's). You'll get better read performance loading one big file than many small files.
* When you're streaming the level, you want predictable load times, having a single file gives you far better predictability with disk performance than many small files. Different level "segments" may have vastly different asset requirements, and vastly different "load" times.

TL:DR - For pong, no. For commercial, or semi-serious games, yes.

---
Tags: assets, file-format, resource-management, serialization
---


# Question
Title: Determining explosion radius damage - Circle to Rectangle 2D
One of the Cocos2D games I am working on has circular explosion effects. These explosion effects need to deal a percentage of their set maximum damage to all game characters (represented by rectangular bounding boxes as the objects in question are tanks) within the explosion radius. So this boils down to circle to rectangle collision and how far away the circle's radius is from the closest rectangle edge. I took a stab at figuring this out last night, but I believe there may be a better way. In particular, I don't know the best way to determine what percentage of damage to apply based on the distance calculated.

Note : All tank objects have an anchor point of (0,0) so position is according to bottom left corner of bounding box. Explosion point is the center point of the circular explosion.

```
        TankObject * tank = (TankObject*) gameSprite;

        float distanceFromExplosionCenter;
        // IMPORTANT :: All GameCharacter have an assumed (0,0) anchor
        if (explosionPoint.x < tank.position.x) {
            // Explosion to WEST of tank
            if (explosionPoint.y <= tank.position.y) {
                //Explosion SOUTHWEST
                distanceFromExplosionCenter = ccpDistance(explosionPoint, tank.position);

            } else if (explosionPoint.y >= (tank.position.y + tank.contentSize.height)) {
                // Explosion NORTHWEST
                distanceFromExplosionCenter = ccpDistance(explosionPoint,
                                                          ccp(tank.position.x, tank.position.y + tank.contentSize.height));

            } else {
                // Exp center's y is between bottom and top corner of rect
                distanceFromExplosionCenter = tank.position.x - explosionPoint.x;

            } // end if
        } else if (explosionPoint.x > (tank.position.x + tank.contentSize.width)) {
            // Explosion to EAST of tank
            if (explosionPoint.y <= tank.position.y) {
                //Explosion SOUTHEAST
                distanceFromExplosionCenter = ccpDistance(explosionPoint,
                                                          ccp(tank.position.x + tank.contentSize.width,
                                                                              tank.position.y));

            } else if (explosionPoint.y >= (tank.position.y + tank.contentSize.height)) {
                // Explosion NORTHEAST
                distanceFromExplosionCenter = ccpDistance(explosionPoint,
                                                          ccp(tank.position.x + tank.contentSize.width,
                                                              tank.position.y + tank.contentSize.height));

            } else {
                // Exp center's y is between bottom and top corner of rect
                distanceFromExplosionCenter = explosionPoint.x - (tank.position.x + tank.contentSize.width);

            } // end if
        } else  {
            // Tank is either north or south and is inbetween left and right corner of rect
            if (explosionPoint.y < tank.position.y) {
                // Explosion is South
                distanceFromExplosionCenter = tank.position.y - explosionPoint.y;

            } else {
                // Explosion is North
                distanceFromExplosionCenter = explosionPoint.y - (tank.position.y + tank.contentSize.height);

            } // end if
        } // end outer if
        if (distanceFromExplosionCenter < explosionRadius) {
            /*
             Collision :: Smaller distance larger the damage
             */
            int damageToApply;
            if (self.directHit) {
                damageToApply = self.explosionMaxDamage + self.directHitBonusDamage;
                [tank takeDamageAndAdjustHealthBar:damageToApply];
                CCLOG(@"Explsoion-> DIRECT HIT with total damage %d", damageToApply);
            } else {
                // TODO adjust this... turning out negative for some reason...
                damageToApply = (1 - (distanceFromExplosionCenter/explosionRadius) * explosionMaxDamage);
                [tank takeDamageAndAdjustHealthBar:damageToApply];
                CCLOG(@"Explosion-> Non direct hit collision with tank");
                CCLOG(@"Damage to apply is %d", damageToApply);
            } // end if

        } else {
            CCLOG(@"Explosion-> Explosion distance is larger than explosion radius");
        } // end if
    } // end if

```

Questions:

1) Can this circle to rect collision algorithm be done better? Do I have too many checks?

2) How to calculate the percentage based damage? My current method generates negative numbers occasionally and I don't understand why (Maybe I need more sleep!). But, in my if statement, I ask if distance \< explosion radius. When control goes through, distance/radius must be \< 1 right? So 1 - that intermediate calculation should not be negative.

Appreciate any help/advice!

# Answer
> 2 votes
You could simplify the checks by calculating the squared distance from the center of the explosion to each corner, then comparing the minimum squared value to the square of the radius to see if there is an overlap. If so, then calculate the square root of the minimum distance to calculate the percentage of damage. However, your code looks efficient enough, so I'd recommend profiling both options to see which is better. What you have is well documented and readable and I don't think the performance needs optimization.

The reason for the occasional negative values for damage is the order of operations. You are performing this calculation:

```
(distanceFromExplosionCenter/explosionRadius) * explosionMaxDamage

```

before subtracting the result from 1. If the result of that multiplication is greater than 1, you'll get a negative damage value.

Change your existing code to:

```
damageToApply = (1 - (distanceFromExplosionCenter/explosionRadius)) * explosionMaxDamage;

```

This will calculate the percentage first, then multiply by maximum damage so that you don't end up with negative values.

---
Tags: mathematics, performance, cocos2d, objective-c
---


# Question
Title: AI for a mixed Turn Based + Real Time battle system - Something "Gambit like" the right approach?
This is maybe a question that's been asked 100 times 1,000 different ways. I apologize for that :)

I'm in the process of building the AI for a game I'm working on. The game is a turn based one, in the vein of Final Fantasy but also has a set of things that happen in real time (reactions). I've experimented with FSM, HFSMs, and Behavior Trees. None of them felt "right" to me and all felt either too limiting or too generic / big.

The idea I'm toying with now is something like a "Rules engine" that could be likened to the Gambit system from Final Fantasy 12. I would have a set of predefined personalities. Each of these personalities would have a set of conditions it would check on each event (Turn start, time to react, etc). These conditions would be priority ordered, and the first one that returns true would be the action I take. These conditions can also point to a "choice" action, which is just an action that will make a choice based on some Utility function. Sort of a mix of FSM/HFSM and a Utility Function approach.

So, a "gambit" with the personality of "Healer" may look something like this:

> (ON) Ally HP = 0% -\> Choose "Relife" spell
>
> (ON) Ally HP \< 50% -\> Choose Heal spell
>
> (ON) Self HP \< 65% -\> Choose Heal spell
>
> (ON) Ally Debuff -\> Choose Debuff Removal spell
>
> (ON) Ally Lost Buff -\> Choose Buff spell

Likewise, a "gambit" with the personality of "Agressor" may look like this:

> (ON) Foe HP \< 10% -\> Choose Attack skill
>
> (ON) Foe any -\> Choose target -\> Choose Attack skill
>
> (ON) Self Lost Buff -\> Choose Buff spell
>
> (ON) Foe HP = 0% -\> Taunt the player

What I like about this approach is it makes sense in my head. It also would be extremely easy to build an "AI Editor" with an approach like this. What I'm worried about is.. would it be too limiting? Would it maybe get too complicated?

Does anyone have any experience with AIs in Turn Based games that could maybe provide me some insight into this approach.. or suggest a different approach?

Many thanks in advance!!!

# Answer
For a game like you described you might consider going for a full **Planner** based solution. This allows you to describe simple transformations of the world state the AI can perform. Essentially the AI plans a number of moves ahead of time to reach its desired goal. This approach is computationally expensive but for a turn based game it's a great fit over classical min/max and alpha/beta pruning techniques.

The issue you run into with the **Rule Based System** you described is having to constantly tweak conditionals and re-prioritize the list. When the list of rules grow larger they become nontrivial to fix small issues without affecting everything else. Utility systems have similar issues when a large number of utility functions constantly struggle between themselves.

**STRIPS** is a well known planner algorithm that was used very effectively in **F.E.A.R** http://en.wikipedia.org/wiki/STRIPS

**Jeff Orkin's** paper on his **STRIPS** implementation for **F.E.A.R** is a great starting place. A **SDK** to **F.E.A.R** is also available to take a look at some of the AI implementation details. http://web.media.mit.edu/~jorkin/gdc2006\_orkin\_jeff\_fear.pdf
> 4 votes

# Answer
I decided that I would build a system that is a mix of the various different AI systems out there. I just felt that was the best approach for my game. It is heavily influenced by Rule Based systems, but also has some features from STRIPs, Behavior Trees, and Finite State Machines.

Each "node" in my AI has a method I call depending on the type (Decision, Condition, or Action). They all also have a Precondition and Postcondition step, which let me evaluate if I should even run that action or if that action was successful. If all 3 methods return true, I can continue onto the next node (or, if the last node, I'm done).

Each method also takes in the current BattleState and the current AIState. The AIState is modified by each behavior, as needed. The BattleState is NOT changed by the AI, but instead by the battle system as a result of the AI.

I really hope that makes sense. If not, here's a screen shot of my AI Editor. It shows a "stupid" personality tree that I can evaluate from left to right when needed. I can also pre-evaluate a node based on where the entity will be in X seconds.

Each node has a bit of smarts in it that are not represented in the editor. For instance, the "ChooseTarget" action has a bunch of smarts about which target should be chosen: Who has the highest threat, who has the lowest health, etc. I could represent all these decisions in the tree but I didn't see the need for that... yet.

Each one of these nodes are also executable independently (mostly). Only certain nodes depend on the nodes before them. And, more accurately, only a few nodes have the POSSIBILITY of depending on the node before them. For example, "UseAttackSkill on Target" depends on the node before it because it needs a target set in the AIState. If that was, say, "UseAttackSkill on Enemy Any", I could execute that node without regard for it's current location in the behavior tree.
> 1 votes

---
Tags: ai, rpg, turn-based
---


title: GLSL: Strange light reflections

text:
# Question
Title: GLSL: Strange light reflections
According to this tutorial I'm trying to make a normal mapping using GLSL, but something is wrong and I can't find the solution. The output render is in this image:

in this image is a plane with two triangles and each of it is different illuminated (that is bad). The plane has 6 vertices. In the upper left side of this plane are 2 identical vertices (same in the lower right). Here are some vectors same for each vertice:

```
normal vector    =  0, 1, 0 (red lines on image)
tangent vector   =  0, 0,-1 (green lines on image)
bitangent vector = -1, 0, 0 (blue lines on image)

```

here I have one question: The two identical vertices does need to have the same tangent and bitangent? I have tried to make other values to the tangents but the effect was still similar.

Here are my shaders

**Vertex shader:**

```
#version 130

// Input vertex data, different for all executions of this shader.
in vec3 vertexPosition_modelspace;
in vec2 vertexUV;
in vec3 vertexNormal_modelspace;
in vec3 vertexTangent_modelspace;
in vec3 vertexBitangent_modelspace;

// Output data ; will be interpolated for each fragment.
out vec2 UV;
out vec3 Position_worldspace;
out vec3 EyeDirection_cameraspace;
out vec3 LightDirection_cameraspace;

out vec3 LightDirection_tangentspace;
out vec3 EyeDirection_tangentspace;

// Values that stay constant for the whole mesh.
uniform mat4 MVP;
uniform mat4 V;
uniform mat4 M;
uniform mat3 MV3x3;
uniform vec3 LightPosition_worldspace;

void main(){

    // Output position of the vertex, in clip space : MVP * position
    gl_Position =  MVP * vec4(vertexPosition_modelspace,1);

    // Position of the vertex, in worldspace : M * position
    Position_worldspace = (M * vec4(vertexPosition_modelspace,1)).xyz;

    // Vector that goes from the vertex to the camera, in camera space.
    // In camera space, the camera is at the origin (0,0,0).
    vec3 vertexPosition_cameraspace = ( V * M * vec4(vertexPosition_modelspace,1)).xyz;
    EyeDirection_cameraspace = vec3(0,0,0) - vertexPosition_cameraspace;

    // Vector that goes from the vertex to the light, in camera space. M is ommited because it's identity.
    vec3 LightPosition_cameraspace = ( V * vec4(LightPosition_worldspace,1)).xyz;
    LightDirection_cameraspace = LightPosition_cameraspace + EyeDirection_cameraspace;

    // UV of the vertex. No special space for this one.
    UV = vertexUV;

    // model to camera = ModelView
    vec3 vertexTangent_cameraspace = MV3x3 * vertexTangent_modelspace;
    vec3 vertexBitangent_cameraspace = MV3x3 * vertexBitangent_modelspace;
    vec3 vertexNormal_cameraspace = MV3x3 * vertexNormal_modelspace;

    mat3 TBN = transpose(mat3(
        vertexTangent_cameraspace,
        vertexBitangent_cameraspace,
        vertexNormal_cameraspace
    )); // You can use dot products instead of building this matrix and transposing it. See References for details.

    LightDirection_tangentspace = TBN * LightDirection_cameraspace;
    EyeDirection_tangentspace =  TBN * EyeDirection_cameraspace;
}

```

**Fragment shader:**

```
#version 130

// Interpolated values from the vertex shaders
in vec2 UV;
in vec3 Position_worldspace;
in vec3 EyeDirection_cameraspace;
in vec3 LightDirection_cameraspace;

in vec3 LightDirection_tangentspace;
in vec3 EyeDirection_tangentspace;

// Ouput data
out vec3 color;

// Values that stay constant for the whole mesh.
uniform sampler2D DiffuseTextureSampler;
uniform sampler2D NormalTextureSampler;
uniform sampler2D SpecularTextureSampler;
uniform mat4 V;
uniform mat4 M;
uniform mat3 MV3x3;
uniform vec3 LightPosition_worldspace;

void main(){

    // Light emission properties
    // You probably want to put them as uniforms
    vec3 LightColor = vec3(1,1,1);
    float LightPower = 40.0;

    // Material properties
    vec3 MaterialDiffuseColor = texture2D( DiffuseTextureSampler, vec2(UV.x,-UV.y) ).rgb;
    vec3 MaterialAmbientColor = vec3(0.1,0.1,0.1) * MaterialDiffuseColor;
    //vec3 MaterialSpecularColor = texture2D( SpecularTextureSampler, UV ).rgb * 0.3;
    vec3 MaterialSpecularColor = vec3(0.5,0.5,0.5);

    // Local normal, in tangent space. V tex coordinate is inverted because normal map is in TGA (not in DDS) for better quality
    vec3 TextureNormal_tangentspace = normalize(texture2D( NormalTextureSampler, vec2(UV.x,-UV.y) ).rgb*2.0 - 1.0);

    // Distance to the light
    float distance = length( LightPosition_worldspace - Position_worldspace );

    // Normal of the computed fragment, in camera space
    vec3 n = TextureNormal_tangentspace;
    // Direction of the light (from the fragment to the light)
    vec3 l = normalize(LightDirection_tangentspace);
    // Cosine of the angle between the normal and the light direction,
    // clamped above 0
    //  - light is at the vertical of the triangle -> 1
    //  - light is perpendicular to the triangle -> 0
    //  - light is behind the triangle -> 0
    float cosTheta = clamp( dot( n,l ), 0,1 );

    // Eye vector (towards the camera)
    vec3 E = normalize(EyeDirection_tangentspace);
    // Direction in which the triangle reflects the light
    vec3 R = reflect(-l,n);
    // Cosine of the angle between the Eye vector and the Reflect vector,
    // clamped to 0
    //  - Looking into the reflection -> 1
    //  - Looking elsewhere -> < 1
    float cosAlpha = clamp( dot( E,R ), 0,1 );

    color =
        // Ambient : simulates indirect lighting
        MaterialAmbientColor +
        // Diffuse : "color" of the object
        MaterialDiffuseColor * LightColor * LightPower * cosTheta / (distance*distance) +
        // Specular : reflective highlight, like a mirror
        MaterialSpecularColor * LightColor * LightPower * pow(cosAlpha,5) / (distance*distance);

    //color.xyz = E;
    //color.xyz = LightDirection_tangentspace;
    //color.xyz = EyeDirection_tangentspace;
}

```

I have replaced the original `color` value by `EyeDirection_tangentspace` vector and then I got other strange effect but I can not link the image (not eunogh reputation)

Is it possible that with this shaders is something wrong, or maybe in other place in my code e.g with my matrices?

# Answer
> 2 votes
Solved... 3 days needed for changing one letter

from this:

```
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glVertexAttribPointer
(
    4,                  // attribute. No particular reason for 0, but must match the layout in the shader.
    3,                  // size
    GL_FLOAT,           // type
    GL_FALSE,           // normalized?
    sizeof(VboVertex),                  // stride
    (void*)(12*sizeof(float))            // array buffer offset
);

```

to this:

```
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glVertexAttribPointer
(
    4,                  // attribute. No particular reason for 0, but must match the layout in the shader.
    3,                  // size
    GL_FLOAT,           // type
    GL_FALSE,           // normalized?
    sizeof(VboVertex),                  // stride
    (void*)(11*sizeof(float))            // array buffer offset
);

```

see difference? :)

---
Tags: opengl, glsl
---


title: XNA matrix order problem

text:
# Question
Title: XNA matrix order problem
I want a matrix that scales first and then rotates. I tried the code below, but it didn't work. `zRotation`, `yRotation` and `xRotation` are rotations that shouldn't be affected by the origin. `allrot` should be affected. `xScale`, `yScale` and `zScale` are the scaling variables. The code below works except that it rotates and then scales.

```
Matrix worldMatrix = (
    Matrix.CreateRotationZ(MathHelper.ToRadians(zRotation)) *
    Matrix.CreateRotationX(MathHelper.ToRadians(xRotation)) *
    Matrix.CreateRotationY(MathHelper.ToRadians(yRotation))
) * (
    Matrix.CreateTranslation(origin) *
    Matrix.CreateRotationY(MathHelper.ToRadians(allrot)) *
    Matrix.CreateScale(xScale, yScale, zScale)
);

```

# Answer
> 2 votes
Your code is showing rotation first, translation second, another rotation third and scale last. That's almost the opposite of what you know it needs to be based on what you indicated in your question. Have you tried it with scale first?

If you are coming from an OpenGL background where the order to combine matrices is from right to left, XNA applies them opposite: left to right.

---
Tags: xna-4.0, matrix
---


# Question
Title: How to correctly Dispose a SourceVoice once its finished
i am starting to play a sound with XAudio2 and SourceVoice and once its finished, it should be correctly disposed to not have any leaks.

i was expecting it to be something like this:

```
        sourceVoice.Start();
        sourceVoice.StreamEnd += delegate
            {
                if (!sourceVoice.IsDisposed)
                {
                    sourceVoice.DestroyVoice();
                    sourceVoice.Dispose();
                }
            };

```

but that crashes with a read access violation in native code deep in XAudio2.dll which i cant debug.

# Answer
> 6 votes
I'm not familiar with SharpDX but I know a bit about the native xaudio C++ API.

You can't call DestroyVoice() in a callback at least in the native API which I assume StreamEnd delegate is a just a thin wrapper for OnStreamEnd() callback in the native API. A workaround may be queuing the sourceVoice to a "deleteList" in the OnStreamEnd callback and deleting everything in that list later somewhere in your game loop. Also, keep in mind that you probably don't want to create a source voice each time you play the same sound as it can be reused and deleted only after when you never need that sound ever again.

# Answer
> 2 votes
I think I might have the answer. According to this MSDN article:

> DestroyVoice waits for the audio processing thread to be idle, so it can take a little while (typically no more than a couple of milliseconds). This is necessary to guarantee that the voice will no longer make any callbacks or read any audio data, so the application can safely free up these resources as soon as the call returns.

My suspicions were that the reason there was a separate DestroyVoice method in the first place was that there was some lazy destruction going on, which is fairly common in real-time audio APIs because of the asynchronous real-time nature of audio playback.

So, by calling `Dispose` so quickly after `DestroyVoice`, you might be causing the deferred destruction of the voice to fail, since it is being released from managed memory by `Dispose` before whatever deferment mechanism has a chance to attempt to destroy the voice in `DestroyVoice`. This would also explain why you're not getting a stack trace; if it is being destroyed from a separate thread or on a delegate callback, you'd see the stack trace from that instead of from the `DestroyVoice` call.

While I'm no expert on this, this seems to be a problem big enough to merit a mention on MSDN, but the problem is that it only mentions this in the documentation for an underlying interface, `IXAudio2Voice`, making it a bit more difficult to find. I'm also not answering this from experience, so reader beware; this might not be the correct answer.

As a side note, the article also mentions this little gem:

> If any other voice is currently sending audio to this voice, the method fails.

Which mentions nothing about *how* it will fail... I'd advise you check up on this as well. Good luck!

**EDIT:** The article also mentions this:

> It is invalid to call DestroyVoice from within a callback (that is, IXAudio2EngineCallback or IXAudio2VoiceCallback).

As @XiaoChuan-Yu mentions in his answer, `StreamEnd` is a thin wrapper to the `OnStreamEnd` callback, and it would appear this might be causing your issue.

---
Tags: directx, sound, audio, sharpdx, xaudio2
---


# Question
Title: How should chat be transmitted and stored in an MMO?
Players in MMO games can usually send messages over different channels (private, public, guilds, et cetera).

How would I transmit and store this data so as to prevent outside users from being able to access somebody's private chat messages? Should I store the data in a temporary game log, or a database?

# Answer
> 13 votes
You're never going to really remove the ability for an outside party to intercept chat packets from clients, and you shouldn't worry too much, because when you're building an MMO you're building a game, not a industrial-strength crypographically secure chat platform.

You should implement chat messages as follows:

* The client transmits the chat data, which at a minimum includes the chat message but probably also includes channel or group information (such as public chat, guild chat, player-to-player whisper, et cetera).
* The server gets the chat data. First it logs it, probably somewhere offline because there's no need to keep it resident in memory for longer than necessary. Logging is important and often overlooked, but it's incredibly useful for GM arbitration and forensic diagnostics. When you run an MMO, you want to *log everything*.
* Once the data's been logged, the server determines who should get the chat message and broadcasts it appropriately. The server can then drop the remaining data on the floor; it doesn't need it any longer.

The most-vulnerable point here is the initial client-to-server transmission. If somebody snooped those packets, they could see messages not technically intended for them. You could encrypt the data, but that's a lot of effort for only minimal gain. The client must be able to decrypt chat packets eventually, and intercepting the packets as they leave the client would be the best place to do the aforementioned snooping, so the key is already available to the snooper, just a little harder to find.

It's very important that you pass your chat through a server that you are in control of, though. It need not be the game server, it can be a dedicated server for funneling chat, but you want to control the routing. It lets you have oversight for GM disputes, it lets you enforce user requests to block or mute other users, it solves the issues you might have with NAT punching or other networking shenanigans you can have trying to do peer-to-peer chat, and it provides enough of a barrier to casual hacking (which peer-to-peer chat is prone to) to solve 90% of the security concerns. Which is about as good as you'll get.

# Answer
> 2 votes
I am honestly not 100% sure what you are asking. But hopefully the following is helpful.

If you look into planeshift, an open-source MMO, you can look at their code and see how they decided to architect their system. This will not give you exact insight into all MMO's but most likely implementations are similar across different games.

Here are some directions for downloading their source. You will need to check it out via SVN

I have taken a look and if you go into `src/client/gui/` you will see a ChatWindow class. It takes care of sending messages back and fourth to the server for chatting and it also takes care of input history. It looks like they package up information and send it off to the server for it to deliver. So I imagine this chat information is stored on their server and thus not reachable by just anyone. That is unless you are able to get into the servers database to access chat records. I cant imagine them being able to keep everything either. If they do keep chat logs its probably only for a certain amount of time (A few days perhaps?)

Anyways, a broad answer for a broad question. I cannot really do much better than that without a more focused question. Feel free to comment if you have more narrow questions and I can try answering them.

Edit1: Also note that in the client folder, you can find and authentclient class. This handles client authentication, etc. I imagine it will also handle chat-related security in terms of authenticating itself into a chat server. They may not have dedicated servers for chat. So it could just be the game server that is also running chat services for all its clients. This is something you could figure out by really studying the code.

For bigger MMO's I would put money on them having dedicated chat servers just for taking care of chatting between players. (Just like they do for instances).

# Answer
> 1 votes
Most MMO's I played do not store messages for a longer period of time. Because that would most likely turn them into a GameCompany with a negative badge like the NSA. Unless, the players had direct access to their database.

Runescape has the messages stored in cache, and it only is avaiable for a small ammount of time. I have never heard of anybody getting banned due to the fact that such data has been stored. If one should ever report another play for what he said. He has to be quick, until his 500~ line chat limit gets used up. After that time all his messages will be deleted. In the most crowdy place, where players shout out each other it is up to 10 seconds.

The messages are always sent via server, and storing takes place at server not client. Otherwise, Player A who hacked into the client, would be able to manipulate the array responsible for chat and literally write that PLAYER B wrote something else. After a short while he could report that player for writing something and the other players cache might no longer hold such info.

If you store the messages on the CLIENT, which has done by a chat portal GaduGadu.pl the users will lose the ability to check their chats on different PC's. The data generated by the user would be vulnerable to third persons. Mostly in public internet Cafes. Or at friends house who might seek vengeance on his former friend.

If you store it on your server, it is impossible for Player B to access data of Player A and vice versa. Keep in mind that saying "can player B access that data" is a broad question. **You can never tell if the data is safe, unless your server is offline!** Here is an example.

# Answer
> 0 votes
Storing messages is only needed for delivery when you want to deliver them at a later time. For example when you want to allow people to send messages to players which are offline which are delivered the next time they log in or when you want to allow an admin to read chat at a later time.

When you don't need this, chat handling can and should be done completely in-memory.

Each chat message a client sends has to include some information about the recipient (public, guild, private message to player X). The server should then determine the characters which are allowed to read the message:

* For public messages, these are the characters in a specific radius around the sending character
* For guild messages, these are the characters who have the same guild as the sender who are currently online
* For private messages, it's the character of the same name, when it is online

The message should then be sent to the clients which control these characters.

Sending a message to a client which is not supposed to show it to the user is a waste of traffic and a violation of the "never trust the client" principle.

---
Tags: mmo
---