# Question
Title: UV texture mapping with perspective correct interpolation
I am working on a software rasterizer for educational purposes and I am having issues with the texturing.

The problem is, only one face of the cube gets correctly textured. The rest are stretched edges:

You can see the running program online here.

I have used cartesian coordinates, and all I do is interpolate the uv values along the scanlines. The general formula I use for interpolating the uv coordinates is pretty much the one I use for the z-buffering interpolation and looks like this (in this case for horizontal scanlines):

```
    u_Slope = (right.u - left.u) / (triangleRight_x - triangleLeft_x);
    v_Slope = (right.v - left.v) / (triangleRight_x - triangleLeft_x);
    //[...]
    new_u = left.u + ((currentX_onScanLine - triangleLeft_x) * u_Slope);
    new_v = left.v + ((currentX_onScanLine - triangleLeft_x) * v_Slope);

```

Then, when I add each point to the pixel buffer, I restore z and uv:

```
                z =  (1/z);
                uv.u = Math.round(uv.u * z *100);//*100 because my texture is 100x100px
                uv.v = Math.round(uv.v * z *100);

```

Then I turn the u v indexes into one index in order to fetch the correct pixel from the image data (which is a 1 dimensional px array):

```
        var index = texture.width * uv.u + uv.v;
        //and the rest is unimportant imagedata[index].RGBA bla bla

```

The interpolation formula is correct considering the consistency of the texture (including the straight stripes).

I must get some sleep now, but before I get into further dissecting of every single value to see what goes wrong, Can someone more experienced guess why might this be happening, just by looking at the cube?

"I have no idea what I'm doing" (it's my first time implementing a rasterizer). Did I miss an important stage?

Thanks for any insight.

---

PS: My UV values are as follows:

```
    { u:0,   v:0 },
    { u:0,   v:0.5 },
    { u:0.5, v:0.5 },
    { u:0.5, v:0 },
    { u:0,   v:0 },
    { u:0,   v:0.5 },
    { u:0.5, v:0.5 },
    { u:0.5, v:0 }

```

## \[EDIT\]

The uv values were to blame, and pixel 50 being in the second zone, as Victor pointed out.

My new uv values:

```
                    {u:0, v:0},
                    {u:0, v:1},
                    {u:1, v:1},
                    {u:1, v:0},
                    {u:1, v:0},
                    {u:1, v:1},
                    {u:0, v:1},
                    {u:0, v:0}

```

To some extent this was "a bug in my code", but also I had overlooked an important part of the process: the uv values should not just be assigned to the 8 corners of the cube.

# Answer
> 4 votes
I took a quick look at your example and your code. You're extremely close to solving this, so I don't mind helping with a question that looks suspiciously like homework ;).

In data.js, you are assigning the same UV coordinates to the front and rear faces of the cube. The coordinates seem to be (\[0,0\], \[0,0.5\], \[0.5,0.5\], \[0.5,0\]). This means that you can only get texels from inside that part of your texture, regardless of which side of the cube you draw.

Because the UV coordinates go all the way up to 0.5, you include a single-pixel edge of the "2" and "3" areas when you draw the "1" face of the cube. For instance, when the u coordinate is 0.5, you will multiply that by 100 and get 50, which is the first pixel of the "2" area.

Finally, this bit of code, from your post, looks slightly wrong:

```
var index = texture.width * uv.u + uv.v;

```

The 'u' coordinate is like the 'x' coordinate in your texture, so you don't want to jump by `texture.width` when you add 1 to u. If the texture image is stored in the normal way (with each row of the texture appearing in order), you want to change this math to

```
var index = uv.u + texture.width * uv.v;

```

# Answer
> 2 votes
Golden rule when you are using floating point: count on every calculation to have an error in the result.

It looks like your texture mapping is mapping a bit of memory past the edge of the textures. This may be because of floating point error.

This part catches my attention:

```
z =  (1/z);
uv.u = Math.round(uv.u * z *100);//*100 because my texture is 100x100px
uv.v = Math.round(uv.v * z *100);

```

Each time this code runs, the variables will deviate from their original values. You should store and restore the original values of these variables, rather than recalculate them. Or create separate variables for the "temporary" values.

It's hard to tell from what you have cut'n'pasted but I suspect you are also "stacking" calculations `new_u` and `new_v` in a similar manner. Rewriting your formulae to not do this could help.

That link I gave? Don't read it, it's far too long :)

---
Tags: javascript, textures, interpolation, software-rendering, uv-mapping
---


# Question
Title: Camera lookAt target changes when rotating parent node
have the following issue.I have a camera with lookAt method which works fine.I have a parent node to which I parent the camera.If I rotate the parent node while keeping the camera lookAt the target , the camera lookAt changes too.That is nor what I want to achieve.I need it to work like in Adobe AE when you parent camera to a null object:when null object is rotated the camera starts orbiting around the target while still looking at the target.What I do currently is multiplying parent's model matrix with camera model matrix which is calculated from lookAt() method.I am sure I need to decompose (or recompose ) one of the matrices before multiplying them .Parent model or camera model ? Anyone here can show the right way doing it ?

UPDATE: The parent is just a node .The child is the camera.The parented camera in AfterEffects works like this: If you rotate the parent node while camera looks at the target , the camera actually starts orbiting around the target based on the parent rotation.In my case the parent rotation changes also Camera's lookAt direction which IS NOT what I want.Hope now it is clear .

# Answer
If you want the orbiting effect, it should be quite simple. Put the parent object at the same location as the target. Attach the camera to the parent and translate it to the desired distance from the target/parent. Set the camera's target to the object and then rotate the parent.

Just make sure the object is not in the same hierarchy as the target and it will remain motionless. Also, you might want to let us know what systems/code you're working with.
> 1 votes

---
Tags: mathematics, camera, matrix, rotation
---


title: App Store free promotion

text:
# Question
Title: App Store free promotion
How can I make my app to be free for certain period of time? Is it ok to switch it to free and then after a day or two switch back to my original price, is it possible and where can I do it?

# Answer
Yes you can change from free to paid and vice versa. More conveniently you can schedule prices changes.

http://developer.apple.com/library/mac/#documentation/LanguagesUtilities/Conceptual/iTunesConnect\_Guide/11\_EditingandUpdatingAppInformation/EditingandUpdatingAppInformation.html

> Scheduling Price Tier Changes
>
> If you have a Paid Applications contract in effect, iTunes Connect allows you to schedule price tier changes for your apps over time. Scheduling is useful for sales and other temporary pricing changes that have a definite beginning and end date, as well as permanent pricing changes that have no end. For example, you might offer a promotional price for a month and then return to the regular price.
>
> To schedule price tier changes, you must have already submitted the app; the options for price scheduling appear only when you are editing an already submitted app. For each price tier, you can set an effective date (the date when the new tier will take effect on the App Store), and an end date (the date when the tier will no longer be in effect and will return to the previously set price tier).
>
> You can set up as many price tier changes as you want in advance and your app will change prices on your effective dates, but no interval can begin more than a year in the future. Your price tier schedule will show at all times on the “Rights and Pricing” page for your app. There you can track when your price changes will occur.
> 4 votes

# Answer
An app can be paid then switched to free but an app can never be switched from free to paid. You would need to release a new app if you want your free app to be paid. The app would then be subject to apple's review process again.

> TL;DR:
>
> Paid -\> Free = Okay
> Free -\> Paid = Not Possible
> 1 votes

---
Tags: ios, marketing, appstore
---


# Question
Title: XNA 4.0 - container with content, that can slide (C#)
I got an idea, but I got no idea on how to make it.
Okay, so here is the deal.

I want a container which can contain certain objects (These objects will draw the sprites/graphics).
But because of different screen sizes, I want to be able to scale the containers width and height. But I do not want the objects in the container, that go outside of the container, because of the scaling to be visible.

Because I want the objects all to be positioned horizontaly to eachother and I want a horizontal sliderbar, so I can slide from left to right within the container.

I wonder if anyone could point me in the right direction.

Thanks in Advance,
Mark

# Answer
> 0 votes
What you are asking for sounds like "basic" window / UI functionality to me. Now I wrapped the word basic in quotes because while its a standard feature of many UI libraries and development platforms, I have never had to develop this myself and I personally wouldn't know where to begin without looking at some reference code. Also, many people will tell you to avoid writing GUI libraries of your own at all costs to avoid headaches and to save yourself lots of time.

That being said, there are XNA UI libraries out there that you should be able to utilize or, at the very least, be able to look at some source code from so that you can get some ideas as far as how to roll your own UI control that you are describing in your question.

I did a quick search on XNA UI libraries and I think the following two could be of use to you:

NeoforceControls \- Looks like a very complete framework but could be hard to dig through if you are looking to use it as just a code reference especially considering reviewers claims of a lack of documentation. This could be good to use as a complete UI framework for your game or as a learning tool for more advanced UI features.

Ruminate MonoGame GUI (formerly XNAGui)- Looks like its much simpler than the one above so you may not be able to use it in its entirety for your game but it looks like it has some scrolling windows / containers that you could look at some code as a reference. I imagine this code is going to be much more straightforward than neoforce if you plan on creating your own control.

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


# Question
Title: How to implement friction in a physics engine based on "Advanced Character Physics"
I have implemented a physics engine based on the concepts in the classic text Advanced Character Physics by Thomas Jakobsen. Friction is only discussed very briefly in the article and Jakobsen himself notes how "other and better friction models than this could and should be implemented."

Generally how could one implement a believable friction model on top of the concepts from the mentioned article? And how could the found friction be translated into rotation on a circle?

---

I do not want this question to be about my specific implementation but about how to combine Jakobsens ideas with a great friction system more generally. But here is a live demo showing the current state of my engine which does not handle friction in any way: http://jsfiddle.net/Z7ECB/embedded/result/

---

Below is a picture showing and example on how collision detection could work in an engine based in the paper. In the Verlet integration the current and previous position is always stored. Based on these a new position is calculated. In every frame I calculate the distance between the circles and the lines. If this distance is less than a circles radius a collision has occurred and the circle is projected perpendicular out of the offending line according to the size of the overlap (offset on the picture).

Velocity is implicit due to Verlet integration so changing position also changes the velocity. What I need to do know is to somehow determine the amount of friction on the circle and move it backwards parallel to the line in order to reduce its speed.

# Answer
> 4 votes
You should take a look at Mathias Mueller et all's "position based dynamics" paper. It's basically the same as Jacobsons' paper and he might give you more info about friction.

http://www.matthiasmueller.info/publications/posBasedDyn.pdf

They state that friction is basically damping the particle's velocity in the plane of the collision by some scalar value.

Note that this doesn't give you any coulomb friction effects (the amount of momentum into the collision doesn't affect the magnitude of the friction force) but you might be able to get that by considering the particle's velocity into the collision plane.

# Answer
> 0 votes
In a "normal" rigid body engine you would model friction as impulses perpendicular to the normal. I would guess that in this context that would mean instead of impulses set the position of the affected particle appropriately. With the constraints in place this should, if I understand the article correctly, then iteratively reach a state where friction has also affected rotation. I am guessing that by "better model" the author means better way of determining the amount of friction than a linear projection of interpenetration. This is however a guess on my side as I have never implemented physics by this approach myself.

EDIT:

To calculate the size of friction forces you have the offset-value in your image. As you're using verlet with fixed timestep we know that this offset is actually the velocity that the contact had in the direction of the contact normal (well not exactly, and I think this is what the author means by making a better approximation of friction). Knowing the velocity along the contact normal is essential as we can use it to determine the impulse. The best way is to apply friction in the form of impulses in each frame where there is a contact. The size of the friction in the axes parallell to the plane of contact is determined by the friction coefficient (determined by the materials, for example 0.7 for rather high friction). The maximum friction you could have is the friction coefficient multiplied by the offset. Do note that this value could be bigger than the actual velocity along one of the axes. In that case you have static friction and the particle should not move at all in that axis. If the value is less than that the particle will move a little bit but be slowed down, ie dynamic friction.

---
Tags: physics, rotation, collision-resolution
---


title: Javascript keyDown - no event approach

text:
# Question
Title: Javascript keyDown - no event approach
I'm making game in JavaScript. I have canvas for drawings and game loop. I'd like to make method readKeyboard, in game loop, to check if there is any pressed key. I don't want to attach event to canvas, because it doesn't fit game loop design. Maybe I should attach this event? What is the best solution?

# Answer
You could use a library like KeyboardJS, which will listen the keyboard events and fill an array with the active keys.

In your gameloop:

```
var activeKeys = KeyboardJS.activeKeys();
if (activeKeys.indexOf(84) > -1) {
  // key pressed
}

```

I also made my own library, which is lighter but clearly less complete than KeyboardJS.
> 5 votes

---
Tags: javascript, keyboard
---


# Question
Title: Deformation of Sphere using Transformations
I have a graphic related question. I need to have a transformation matrix that I have no idea about what it is. The problem is to create right image from the right sphere. I created those images in Maya, but I need some matrices for the graphics course. Here is the image: Our professor told us to use some sine and cosine in our transformations, but I have no idea what he meant. I thought of intersecting a plane from the grid(that is xz plane) and sphere, and then scaling down the resulting circle. Would that work?

I also checked this paper, however it looks like a bit advanced for me. Another thing is I guess that paper is not about the same type of information I was looking for.

It would be great if you could help me.

# Answer
> 3 votes
This type of transformation cannot be done with a (single) matrix; those can only handle *linear* transformations, and the image you posted plainly shows a non-linear transformation. (A linear transformation could deform the sphere into an ellipsoid, but it couldn't produce a waist in the middle like that.)

I'm going to assume that what your professor meant here was to apply a different matrix to each vertex of the sphere, where the matrix depends on the vertex's position. So to apply it, you'd iterate over the vertices, calculate the matrix for each vertex according to some formula that you can make up, and then transform that vertex by the resulting matrix.

For example, to suck in the middle of the sphere like that shown, you might want to use a scaling in the xz plane, where the amount of scaling depends on the vertex's y-coordinate. You'd make up a function that would give you a scale factor less than 1.0 when y = 0, but increases toward 1.0 as y goes up to +1 or down to -1. You could make such a function by taking a sin or cos function and scaling/translating it appropriately. Actually, just a quadratic function like (y^2 + 1) / 2 would do as well.

---
Tags: graphics, matrix, transformation
---


# Question
Title: How to shift a vector based on the rotation of another vector?
I’m learning 2D programming, so excuse my approximations, and please, don’t hesitate to correct me. I am just trying to fire a bullet from a player. I’m using HTML canvas (top left origin).

Here is a representation of my problem:

* The black vector represent the position of the player (the grey square).
* The green vector represent its direction.
* The red disc represents the target.
* The red vector represents the direction of a bullet, which will move in the direction of the target (red and dotted line).
* The blue cross represents the point from where I really want to fire the bullet (and the blue and dotted line represents its movement).

This is how I draw the player (`this` is the player object. Position, direction and dimensions are 2D vectors):

```
ctx.save();
ctx.translate(this.position.x, this.position.y);
ctx.rotate(this.direction.getAngle());
ctx.drawImage(this.image, Math.round(-this.dimensions.x/2), Math.round(-this.dimensions.y/2), this.dimensions.x, this.dimensions.y);
ctx.restore();

```

This is how I instanciate a new bullet:

```
var bulletPosition = playerPosition.clone(); // Copy of the player position
var bulletDirection = Vector2D.substract(targetPosition, playerPosition).normalize(); // Difference between the player and the target, normalized
new Bullet(bulletPosition, bulletDirection);

```

This is how I move the bullet (`this` is the bullet object):

```
var speed = 5;
this.position.add(Vector2D.multiply(this.direction, speed));

```

And this is how I draw the bullet (`this` is the bullet object):

```
ctx.save();
ctx.translate(this.position.x, this.position.y);
ctx.rotate(this.direction.getAngle());
ctx.fillRect(0, 0, 3, 3);
ctx.restore();

```

How can I change the direction and position vectors of the bullet to ensure it is on the blue dotted line?

I think I should represent the shift with a vector, but I can’t see how to use it.

# Answer
> 1 votes
Just offset the shot when you instance a new bullet.

I assume your always working in world space given how you instance a new bullet so like this.

```
Vector2D offset = player.velocity.perpendicular().normalize().scaleBy(playerWidth * 0.5);

// Some vector.perpendicular() functions will be left handed some will be right.
// so you might have to negate this offset value to get it on the proper side of the player.

var bulletPosition = playerPosition.clone().add(offset); // Copy of the player position

// now you should have no problems calculating your angle etc since you have a valid starting point for your bullet.

```

Edit: I just noticed that your also calculating the direction of travel for the bullet from the player's position and not the bullets position when you first instantiate a new bullet.

```
var bulletDirection = Vector2D.substract(targetPosition, bulletPosition).normalize(); // Difference between the bullet and the target, normalized
new Bullet(bulletPosition, bulletDirection);

```

Edit: Your right I screwed up. You need to use the players facing as your offset.

```
// If the player's velocity is independent to the player rotation
// (ie. a space game or drifting etc) use the rotation as the vector your facing.
Vector2D offset = player.velocity.perpendicular().normalize().scaleBy(playerWidth * 0.5);
bulletPosition = player.position.add(offset);

```

you should now be able to calculate the direction of travel of the new bullet like I did above.

---
Tags: vector, html-canvas
---


title: XNA Shader Texture Memory

text:
# Question
Title: XNA Shader Texture Memory
I was wondering about texture optimization in XNA 4.0.

Will the the contentmanager send the texturedata to the GPU directly when the texture gets loaded or do I send the texture data to the GPU when I declare a texture in my shader.

If that's the case, what happens if I have 5 shaders all using the same texture, does that mean that I send 5 instances of that texture data to the gpu or am I simply telling the GPU what preloaded texture to use?

Or does XNA do the heavy lifting in the background?

# Answer
> 2 votes
Pretty much everything in XNA that you can call `SetData` on stores its data in GPU memory. That is: `VertexBuffer`, `IndexBuffer`, **`Texture2D`**, etc. Shaders themselves are also stored on the GPU.

They start existing on the GPU as soon as you create them (or `ContentManager` creates them for you.)

The GPU has "texture samplers". Conceptually these are *pointers* (references) to a texture in GPU memory. When you set `GraphicsDevice.Textures[0] = myTexture` (or something sets it for you, like `SpriteBatch` or `BasicEffect`), XNA sets sampler 0 on the GPU to *point* at the memory for "myTexture" (which is already on the GPU). This is so cheap that it's practically a free operation.

So, when you write this in your shader:

```
sampler myTextureSampler : register(s0);
...
tex2D(myTextureSampler, uv);

```

You are saying you want to load pixel data from whatever texture is pointed to by sampler 0.

---
Tags: xna, c#, shaders, hlsl
---


# Question
Title: How can I generate a navigation mesh for a tile grid?
I haven't actually started programming for this one yet, but I wanted to see how I would go about doing this anyway.

Say I have a grid of tiles, all of the same size, some traversable and some not. How would I go about creating a navigation mesh of polygons from this grid?

My idea was to take the non-traversable tiles out and extend lines from there edges to make polygons... that's all I have got so far. Any advice?

# Answer
Here's one of the methods I came up with when doing navmesh for an RTS game. Note that it is homebrew, no third-party tools were used, it took me about 3 weeks to implement and bugfix:

1. **Use Marching Squares algorithm to convert obstacle tiles into outlines**. Note that map edges is an outline too and need to be included as well.
2. **Reduce number of points in outlines using Douglas-Peucker algorithm** (purple lines on the bottom picture)
3. **Feed all points into Delaunay triangulation** (to get most uniform triangles)
4. **Add additional points in empty areas and along the map edges** (to get more even navmesh)
5. **Check along obstacle outlines and flip polygons produced by Delaunay to match outlines.** \- Often Delaunay could place triangles (grey) mismatching your outlines (red), then you need to detect and flip them. Adjoining them back into a polygon, split it along outline(s) and triangulate it manually
6. **Clip obstacles innards** \- remove polygons that are within obstacles (pink on the picture above)
7. **Fill in connectivity data between remaining triangles and vertices as you need** \- that's your navmesh.

Result:
> 31 votes

# Answer
Meshes are typically implemented as graphs. If you wish to implement path-finding in a map based on a grid do the following:

Create a graph where each traversable square is represented as a vertex. Each pair of adjacent traversable squares represented as vertices, will have an edge between them. And you're done.
> 1 votes

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


title: Stencil mask with AlphaTestEffect

text:
# Question
Title: Stencil mask with AlphaTestEffect
I am trying to pull off the following effect in XNA 4.0:

The purple area has 50% opacity. I have gotten pretty close with the following code:

```
public static DepthStencilState AlwaysStencilState = new DepthStencilState()
        {

            StencilEnable = true,
            StencilFunction = CompareFunction.Always,
            StencilPass = StencilOperation.Replace,
            ReferenceStencil = 1,
            DepthBufferEnable = false,
        };

public static DepthStencilState EqualStencilState = new DepthStencilState()
        {
            StencilEnable = true,
            StencilFunction = CompareFunction.Equal,
            StencilPass = StencilOperation.Keep,
            ReferenceStencil = 1,
            DepthBufferEnable = false,
        };

...

if (_alphaEffect == null)
{
       _alphaEffect = new AlphaTestEffect(_spriteBatch.GraphicsDevice);
       _alphaEffect.AlphaFunction = CompareFunction.LessEqual;
       _alphaEffect.ReferenceAlpha = 129;
       Matrix projection = Matrix.CreateOrthographicOffCenter(0, _spriteBatch.GraphicsDevice.PresentationParameters.BackBufferWidth, _spriteBatch.GraphicsDevice.PresentationParameters.BackBufferHeight, 0, 0, 1);
       _alphaEffect.Projection = world.SystemManager.GetSystem<RenderSystem>().Camera.View * projection;
}

_mask = new RenderTarget2D(_spriteBatch.GraphicsDevice, _spriteBatch.GraphicsDevice.PresentationParameters.BackBufferWidth, _spriteBatch.GraphicsDevice.PresentationParameters.BackBufferHeight, false, SurfaceFormat.Color, DepthFormat.Depth24Stencil8);
_spriteBatch.GraphicsDevice.SetRenderTarget(_mask);
_spriteBatch.GraphicsDevice.Clear(ClearOptions.Target | ClearOptions.Stencil, Color.Transparent, 0, 0);

_spriteBatch.Begin(SpriteSortMode.Immediate, null, null, AlwaysStencilState, null, _alphaEffect);
_spriteBatch.Draw(sprite.Texture, position, sprite.SourceRectangle,Color.White, 0f, sprite.Origin, 1f, SpriteEffects.None, 0);
_spriteBatch.End();

_spriteBatch.Begin(SpriteSortMode.Immediate, null, null, EqualStencilState, null, null);
_spriteBatch.Draw(_maskTex, new Vector2(x * _maskTex.Width, y * _maskTex.Height), null, Color.White, 0f, Vector2.Zero, 1f, SpriteEffects.None, 0);
_spriteBatch.End();

_spriteBatch.GraphicsDevice.SetRenderTarget(null);
_spriteBatch.GraphicsDevice.Clear(Color.Black);

_spriteBatch.Begin();
_spriteBatch.Draw((Texture2D)_mask, Vector2.Zero, null, Color.White, 0f, Vector2.Zero, 1f, SpriteEffects.None, layer/max_layer);
_spriteBatch.End();

```

My problem is, I can't get the AlphaTestEffect to behave. I can either mask over the semi-transparent purple junk and fill it in with the green design, or I can draw over the completely opaque grassy texture. How can I specify the exact opacity that needs to be replace with the green design?

# Answer
I'm not sure if you can do this with the AlphaTestEffect(in fact I does not know how ATE works). I recently want to draw some kind of menu, that fills the the the stencil buffer correctly and is a kind of mask.

My PixelShader looks like this:

```
float4 PSFunc (VertexShaderOutput input) : COLOR0
{
    float4 texel = tex2D(TextureSampler, input.TexCoord);
    clip(texel.w - AlphaClipValue);
    return texel;
}

```

AlphaClipValue defines what pixel are visible in texture. e.g. 0.8f defines that alle Alpha values in the texture that are above 204 gets drawn. Other pixel get cliped.

```
protected readonly DepthStencilState DrawMaskDepthStencilState =
    new DepthStencilState(){
        StencilEnable = true,
        StencilFunction = CompareFunction.Always,
        StencilPass = StencilOperation.Invert,
        ReferenceStencil = 0,
        DepthBufferEnable = true,
    };
protected readonly DepthStencilState DrawSceneDepthStencilState =
    new DepthStencilState(){
    StencilEnable = true,
        StencilFunction = CompareFunction.Equal,
        StencilPass = StencilOperation.Keep,
        ReferenceStencil = 0,
        DepthBufferEnable = true,
    };

```

Now the Draw()

```
public override void Draw(GameTime gameTime){
    //set state that is able to draw
    GraphicsDevice.DepthStencilState = DrawMaskDepthStencilState;

    //set texture and AlphaClipValue (1 means only pixel with Alpha==255 gets drawn)
    DrawMenuEffect.Texture = _maskTexture;
    DrawMenuEffect.AlphaClipValue = 1f;
    DrawMenuEffect.CurrentTechnique.Passes[0].Apply();
    GraphicsDevice.DrawUserPrimitives(PrimitiveType.TriangleStrip,    FullScreenQuadStripVertices,0,2);

    GraphicsDevice.DepthStencilState = DrawSceneDepthStencilState;

    // Now draw rest of the scene
}

```

I using my own projected quads to draw the texture, because I do not like the SpriteBatch(it resets some state that is does not reset). But I think it should work with SpriteBatch, too. Otherwise you can look here to see how to create them.
> 1 votes

---
Tags: xna-4.0, stencil
---


# Question
Title: Boat passing under a bridge in a 2D tile based RTS
I'm writing a 2D tile based RTS. And I want to add a 'pseudo 3D' feature to it - bridges over the rivers.

I havent't start any coding yet, just trying to think how it fits the collision detection model. A boat passing under the bridge and a unit moving over the bridge will eventually occupy the same cell on the map. How to prement them from colliding?

Is there a common approach to solve such a problem? Or I need to implement a 3D world to do this?

# Answer
You'll basically have to create a third dimension, though in the simplest case it can consist of just two values: "on ground/on bridge" and "on water/below bridge".

An inspiration can be found in the way Advanced Strategic Command does it: Units occupy a specific height level, can only move around on height levels fitting to their type unless there are specific features allowing them to do otherwise (for example runways for aircraft) and changing them *usually* costs movement points, with penalties on some height levels or others. A tile can be occupied by any number of units as long as each is on a different height level.

In case of ASC, the levels are:

* space
* high altitude (bombing)
* medium altitude (interceptors)
* ground attack altitude
* ground (most ground units and hovercraft, even over water)
* water
* partially submerged (submarines)
* submerged ("hidden" submarines)
> 7 votes

# Answer
You can add a simple attribute to each tile that specifies its level.

So for example:

```
tileA.layer = 0 // Will be at the bottom
tileB.layer = 1 // Will be above level 0, on top of it.

// Add tiles to layered list
List<List<Tile>> tiles = new List<List<Tile>>();
tiles[0].add(tileA);
tiles[1].add(tileB);

// Draw 'em in the right order!
void Draw(List<List<Tile>> tiles) {
    foreach( var listOfTiles in tiles ) {
        foreach( var tile in listOfTiles ) {
            tile.draw();
        }
}

```

Now you can sort your tiles depending on their layer values and draw them bottom -\> top! This will make it look like you have a certain depth in your game. Most tile engines support this. Another cool thing you can add is transparency to your textures so you can see through to the bottom layer.

This can be done with water for example - imagine the water at lvl 1 and then the ocean floor at lvl 0. If the water texture is somewhat transparent, you will be able to see the ocean floor from above.
> 9 votes

---
Tags: 2d, 3d, collision-detection, rts
---


# Question
Title: Writing a Master's Thesis on evaluating visual scripting systems
I am thinking to write my Master's thesis around theorizing, and then implementing a PlayMaker or Kismet-like (building game logic by visually arranging FSMs) tool in Unity. The only thing I am still concerned about is the actual research question that I should pose.

I was kinda hoping that the more experienced game designers out there might know.

**Update**: What about reducing the use of visual programming to graphically designing FSM-Action-Transition flows, which can then be attached to game entities (very much like http://playmaker.com does it)?

**Update 2:** Regarding the evaluation of the approach: I was thinking that it would not be so practical to try to quantitatively prove that my tool is better than the competition. This is in fact not the essence of the thesis. The problem that I see myself trying to solve is more of the type of "how do we prove that the approach is easy to pickup and learn from people without specific programming knowledge" I could build a "test sandbox" - an unfinished puzzle level that each of the test subjects is supposed to complete by following a number of certain tasks. The taks will vary from simply adding a missing transition between two states, through correcting intentional mistakes in the logic, to designing entire state machines on one'e own. The evaluation will then be done based on the completion of the tasks.

# Answer
> 4 votes
From the references of an austrian master thesis about visual programming

may this links could help you to get an start

Visual Programming 1999

Visual Programming, Knowledge Engineering, and Software Engineering, 1996.

There seems to be an book from Addison-Wesley with the german title "Visuelle Programmierung. Grundlagen und Einsatzmöglichkeiten". I am sure there is the english counterpart too somewhere. Amazon could show it if you enter the german title.

# Answer
> 2 votes
One of the major problem of visual programming was stated as the Deutsch limit, stating that

> The problem with visual programming is that you can't have more than 50 visual primitives on the screen at the same time.

Now one could argue that the same applies to lines of code (you can't have more than 50 lines on screen at the same time).

The main problem, IMHO, is that many attempts to create a Visual editor makes things messy : lines of codes have a natural order. You read them left to right (or right to left in some languages) and each line below the previous one.

With visual blocks, you will end up with spaghetti code, literally, as lines will fill the space between blocks, and from that, getting a good idea of what the code does is hard.

Another problem is that most attempts aren't as user friendly as people think. I've been a Virtools teacher during 4 years (Virtools was a french 3D engine in early 2000, using visual scripting). Most of the time, students would put two blocks together, and forget links, thinking that the software would understand what it was to do. Something like writing

```
int i = 42;
print(); // they'd assume that because we compute i just before, print will have to print the value of i

```

---
Tags: game-design, education
---


# Question
Title: What is going on in this SAT/vector projection code?
I'm looking at the example XNA SAT collision code presented here:

http://www.xnadevelopment.com/tutorials/rotatedrectanglecollisions/rotatedrectanglecollisions.shtml

See the following code:

```
private int GenerateScalar(Vector2 theRectangleCorner, Vector2 theAxis)
{
    //Using the formula for Vector projection. Take the corner being passed in
    //and project it onto the given Axis
    float aNumerator = (theRectangleCorner.X * theAxis.X) + (theRectangleCorner.Y * theAxis.Y);
    float aDenominator = (theAxis.X * theAxis.X) + (theAxis.Y * theAxis.Y);
    float aDivisionResult = aNumerator / aDenominator;
    Vector2 aCornerProjected = new Vector2(aDivisionResult * theAxis.X, aDivisionResult * theAxis.Y);

    //Now that we have our projected Vector, calculate a scalar of that projection
    //that can be used to more easily do comparisons
    float aScalar = (theAxis.X * aCornerProjected.X) + (theAxis.Y * aCornerProjected.Y);
    return (int)aScalar;
}

```

I think the problems I'm having with this come mostly from translating physics concepts into data structures. For example, earlier in the code there is a calculation of the axes to be used, and these are stored as `Vector2`, and they are found by subtracting one point from another, however these points are also stored as `Vector2`s. So **are the axes being stored as *slopes* in a single `Vector2`?**

Next, **what exactly does the `Vector2` produced by the vector projection code represent?** That is, I know it represents the projected vector, but as it pertains to a `Vector2`, what does this represent? A point on a line?

Finally, **what does the scalar at the end actually represent?** It's fine to tell me that you're getting a scalar value of the projected vector, but none of the information I can find online seems to tell me about a scalar of a vector as it's used in this context. I don't see angles or magnitudes with these vectors so I'm a little disoriented when it comes to thinking in terms of physics. **If this final scalar calculation is just a dot product, how is that directly applicable to SAT from here on?** Is this what I use to calculate maximum/minimum values for overlap? I guess I'm just having trouble figuring out exactly what the dot product is representing in this particular context.

Clearly I'm not quite up to date on my elementary physics, but any explanations would be greatly appreciated.

# Answer
the return value works out the same as `aNumerator`. I don't know why all the extra code is needed. And very definitely should not be returned as an `int`, should be returned as a float.

I'll re-write the above in pseudo-code;

```
//C is theRectangleCorner
//A is theAxis
aN = C DOT A;  //dot product
aD = lengthOfA^2; //lengthsquared
aDR = (C dot A) / lengthOfA^2;
aCP = ((C dot A) / lengthOfA^2 )*Ax, ((C dot A) / lengthOfA^2)*AY);

//Now that we have our projected Vector, calculate a scalar of that projection
//that can be used to more easily do comparisons

float aScalar = ((C dot A) / lengthOfA^2 )*Ax *Ax + ((C dot A) / lengthOfA^2)*AY*AY);
   =((C dot A) / lengthOfA^2 )(Ax^2+Ay^2)
   =((C dot A) / lengthOfA^2 )(lengthOfA^2 ) // 2 length^2 cancel out
   = C dot A

```

Not sure if that made things clearer but it hopefully shows how `aScalar==aNumerator`. This might be a good candidate for The Daily WTF. Bizarre.

The scalar at the end is the dot product of the corner vertex and the axis, which represents the projection of the vertex ONTO the axis. If you think of the axis as a number-line (like you used in 1st grade/class). The dot-product tells us how far along that number-line the projection lies.

For example, if the 4 corners of box-a is projected onto an axis and you get values of {4.0,5.1,4.5, & 6.1}. Imagine the 3 corners of triangle-b are projected on to the same axis an we get {6.5,7,6.4} as our 3 values. We can see that there is no overlap as the largest value of box-a(6.1) is less than the smallest value of tri-b(6.4).

BTW we get the values above as follows;

```
4.0= box-A.corner1 DOT axis
5.1= box-A.corner2 DOT axis
4.5= box-A.corner3 DOT axis
6.1= box-A.corner4 DOT axis

```

Notice that the dot product generally results in a non-integer result, which is the SECOND bizarre thing about the code in question (it returns an int).

To answer your first question, an axis IS a vector, or at least can be considered a vector for the purposes of SAT.
> 1 votes

---
Tags: xna, c#, physics, separating-axis-theorem
---


# Question
Title: Who should respond to collision: Unit or projectile?
In an RTS if a projectile hits a unit. Who should handle the collision?

If projectile handles the collision, it must be aware of all possible types of units, to know what damage to inflict. For example a bullet will likely kill a human, but it will do nothing to a tank.

The same goes if unit handles a collision. So either way one of them should be aware of all possible types of the other.

Of course the 'true' way would be to do full physics simulation, but that's not an option for an RTS with 1000s of units and projectiles...

So what are the common practicies in this regards?

# Answer
This is a question that is highly specific to the game and implementation. So let's discuss yours:

But broadly, you don't have to worry about who should handle the collision if both parts of the collision can collaborate on the processing.

For instance, instead of considering all possible damage sources vs. all possible types of units, consider storing only 2 values in the projectile: "Damage Type" and "Raw Damage". Then, when a unit collides with the bullet, have the bullet pass the "Damage Type" and "Raw Damage" parameters.

The Unit then would have some method to calculate how much damage it should take given those two inputs. You'd need to use Delegates, Callbacks, or something similar to communicate between the two objects (you did not list a language, so I can't provide more specifics)

This way, units only have to consider possibilities that are relevant to them, and the bullet doesn't care what it hits.

In this example, Damage Type might be "Projectile", "Explosion", or even something more specific, like "LightMachineGunBullet". Units would then modify the raw damage based on the damage type, for instance, a tank that takes only 10% damage from Projectiles, but 100% from explosions.
> 3 votes

---
Tags: collision-detection, physics, rts
---


# Question
Title: Low complexity shader to indicate the sides of a polyline
I have a bunch of polylines that I draw using GL\_LINES. They can have thousands of points. They actually represent the separation of land and water on a map. I don't have complete polygons, just the ordered set of points.

I'm looking for a neat but efficient way to visually convey Side A and Side B as being different. For example I could offset the polyline in one direction a few times and fade it out (but every offset is doubling the number of points), or offset it once to make a "ribbon" and give one side a 'glow' like effect to mimic the outer glow or shadow of a polygon).

This is for a mobile application and I'm using OpenGL ES 2. I'd like to keep the effect as simple as possible from a complexity stand point. I'm looking for some additional ideas; maybe there's a clever shader technique out there or a visual effect I haven't considered.

# Answer
> 0 votes
Given the lack of geometry shaders, you'll have to do something with your input data.

A simple approach would be to create a quad for each line segment, extending N pixels in the X axis. In old style GL immediate mode pseudo-code:

```
glBegin(GL_QUADS)
for each line {
    glColor(0, 0, 0, 1)
    glVertex(line.x0 - N, line.y0)
    glColor(1, 0, 0, 1)
    glVertex(line.x0, line.y0)
    glColor(1, 0, 0, 1)
    glVertex(line.x1, line.y1)
    glColor(0, 0, 0, 1)
    glVertex(line.x1 - N, line.y1)
}

```

If you want even prettier results: offset along a vector perpendicular to the line (instead of just in the X-axis) to get an even thickness, and fill in the gaps in the line joins. Look at 2d line art stroking algorithms (like in postscript) for inspiration.

# Answer
> 0 votes
This is probably not better than offsetting the coordinates to produce a texturable triangle strip, and I haven't tested it, but since you're looking for ideas:

Use a thick line width, and a fragment shader which draws a glow on one side by comparing the interpolated projected vertex coordinate (passed from the vertex shader) to `gl_FragCoord` and deriving a gradient from the difference. I don't know exactly how varyings are interpolated on thick lines, so I don't know how well this will actually work.

Note that wide lines may be inefficient or even not supported by your hardware.

---
Tags: glsl, opengl-es2
---


# Question
Title: How do I get the axes for SAT collision detection
In SAT collision detection how do I calculate the axes for projection?

# Answer
> 4 votes
We'll initially stick to 2D collisions detection for simplicity. (I'll discuss 3D at the end).

The axes used in SAT are the normal vectors of all of the edges of the two objects being considered.

Consider the box in this diagram;

The box has 4 edges: AB,BC,CD & DA (if using the clockwise convention). Each of these edges can be written as a vector;

1. edge AB is the vector B-A. (That is vectorB minus vectorA)
2. A & B are points, the expression (B-A) is the vector which encapsulates the distance and direction from point A to point B.
3. We need the normal to this edge, A normal is vector at right angles to the edge. We can calculate this by swapping x and y of the edge and multiplying the y value by -1.

I'll do a numerical example;

```
A=(100,100)
B=(150,175)

edgeAB B-A=(150-100,175-100)=(50, 75)

normalAB=(-75, 50)

```

For SAT we need also to find normalBC, normalCD and normal DA. We also need to find the normals to all the edges of the other object in the collision detection.

All these normals are the set of **axes** which we will project both objects' vertices onto.

In some tutorials you will be advised to normalise the axes. this is not necessary, although I find it does make visualising the process easier.

Note, in the diagram, normalAB is parallel with normalCD in this case the result of projection on these axes will be the same (overlap or non-overlap) will be the same so there is no need to project on to both of them. You can eliminate normal CD. Similarly normal BC and normal DA are parallel, so you can eliminate one of these.

### 3D normals

For 3D you will need to find the normals for all the faces, you will also need to get the cross product of all the edges of one object with all the edges of the other.

---
Tags: collision-detection, vector, separating-axis-theorem
---


title: Influence Maps for Pathfinding?

text:
# Question
Title: Influence Maps for Pathfinding?
I'm taking the plunge and am getting into game dev, it's been going well but I've got stuck on a problem.

I have a maze that is 100x100 with 0,1 to indicate if its a path or a wall.

Within the maze I have 300 or so enemies and a player.

The outcome I'm looking for is all the enemies work their way towards the player position.

Originally I did this using an A\* path finding algorithm but with 300 enemies it was taking forever to path find each one individually.

After some research I found that an influence map / collaborative diffusion would be the best way to go.

But I'm having a real hard time working out how this is actually done.

Firstly.. How do you create a influence map?

From what I understand each of my walls with have a scent of 0 so that makes them impassable.. then basically a radial effect from my player position to each other cell (So my player starts at 100 and then going outwards from that each other cell will be reduced value)

Is that correct? If so,.. How would you do that (Math magic?)

My next problem is if that is correct how would my "enemies" stop from getting stuck if they have gone down the wrong way? As say if my player was standing on the otherside of a wall if the enemy is just looking for larger numbers wont it keep getting stuck?

I'm doing this in JavaScript so performance is key.

Thanks for any help!

EDIT:

Or if anyones got a better solution? I've been reading about navmeshs, steering pathing, pre calculating all paths on load etc etc

# Answer
> 7 votes
> The outcome I'm looking for is all the enemies work their way towards the player position.
>
> Originally I did this using an A\* path finding algorithm but with 300 enemies it was taking forever to path find each one individually.

Rather than searching from each enemy to the player, search outwards from the player to every enemy at once. This way, rather than doing 300 searches, you only need to do one.

More specifically, just do a breadth-first search *(or djikstra's, if your graph is weighted)* from the player outwards, until every enemy has been reached.

You could alter this strategy to work with A\* by changing your heuristic `EstimatedDistanceToEnd` *(aka `h(x)`)* to be the minimum estimate to any enemy, but with a lot of enemies this may end up being slower than the simpler option. The heuristic must be consistent for this to work.

---

Also remember that **you don't need to run your pathfinder every single frame** for most games - often you can get away with only once or twice a second, or even less, depending on the game.

If that is *still* too slow, you could look into using D\* lite to reuse information between subsequent searches. But, I would bet money that running a single breadth-first search a few times a frame will be more than fast enough.

# Answer
> 0 votes
Rq1 : if one enemy'path encounters the path of another allready computed enemy's path, it just has to follow it to reach the player, which quite breaks down the cumulated length of path to compute.
Rq2 : If we take that into account, you might :
\- compute the right path for near enemy only (?distance \<10 ?), using rq1.
\- And then just compute a few (8 ?? more ??) path from various location on the map,
\- Then each monster's task is to reach the nearest path (...still using rq1). (This would lead to possibly non-optimal path for the far away enemies, but all the best for the poor player who will have to face the 300 monsters :-) )

---
Tags: path-finding
---


# Question
Title: Algorithm for procedural city generation?
I am planning on making a (simple) procedural city generator using Java. I need ideas on whan algorithm to use for the layout, and the actual buildings. The city will mostly have skyscrapers, not really much complex stuff.

For the layout I already have a simple algorithm implemented:

1. Create a Map with java.awt.Point keys and Integer values. Fill it with all the points in the city's bounds with the value as -1 (unnassigned)
2. Shuffle the map, and assign the 1st 10 of the keys IDs (from 1-10)
3. Loop until all points have IDs:
4. Loop though all points:
5. Assign points next to an assigned point IDs of the point next to them, if 2 or more points border the point, then randomly choose which ID the point will get.
6. Stop looping #3-5 when all points have ids
7. You will end up with 10 random regions. Make roads bordering these regions.
8. Fill the inside of each region with a randomly spaced and randomly rotated grid

**PROBLEM:** This is not the *fastest* way to do it.

What algorithm should I use for the layout. And what should I use to make each building's design? I don't even know how I'm going to do that yet (fractals maybe). I just need some ideas, not actual code.

# Answer
The procedure you've described seems to be about generating a number of regions on your map. For this problem, I'd suggest using a voronoi diagram instead. A nice tutorial for generating one can be found here. I think this would be faster than your algorithm.

Looking further ahead to road and building generation, there are a lot of different algorithms because of the different requirements. Is this a modern American city with sky-scrapers and suburbs or a historic Roman city with temples and 1-story buildings? This type of difference will affect what you want from your city generator.

If you're interested in reading some academic stuff, I'd recommend a couple of papers on Pascal Müller's site.
> 5 votes

---
Tags: java, procedural
---


# Question
Title: Does concurrency inherently introduce "randomness" into a game?
When a game is implemented with concurrency (as most games are), does this necessarily, by its very nature, introduce an element of randomness into the game that is outside of the players' control?

Note that when I use the word "random", I'm not meaning to launch into a philosophical debate about the deterministic nature of the system. I understand that concurrency is deterministic in the sense that the operating system decides which processes to allow time on the CPU and in what order (or the JVM controls which Thread's turn it is to execute, etc). But my understanding of this is that there is no way to control or predict whether one thread's next command will execute before or after another.

The reason I'm asking is because this seems like a fundamental difficulty for game development where a game is supposedly designed around a player's skill. Consider a game like *League of Legends*. Assume that two players are battling it out. It's a very close contest between the two and it's coming down to the wire -- so much so that whoever gets their last attack off will be the one to kill the other and win the game for their team.

If the players are implemented using concurrency and the situation really was like this, is it essentially out of the players' hands at this point? Is the outcome of this match all up to whatever system is arbitrarily deciding which player's thread/process will execute next? If not, what am I misunderstanding about concurrency? If so, is there any way around this problem so that a game of skill can always be a game of skill, especially in those most crucial moments?

# Answer
No, it does not.

> But my understanding of this is that there is no way to control or predict whether one thread's next command will execute before or after another.

If this were true, it would be next to impossible to create game software that functioned reliably. As it is, there are ways to ensure that key operations perform in a reliable order.

> whoever gets their last attack off will be the one to kill the other and win the game for their team. If the players are implemented using concurrency and the situation really was like this, is it essentially out of the players' hands at this point?

If there is a single authoritative host, one of the commands will reach the host system before the other and will be processed first. One player may win purely due to better network latency, just as in real sports the player with the fastest reflexes may win. But it won't be affected by the concurrency on the host computer.

In a peer to peer game, the results will be processed side by side on each machine and will all take effect. So the results should be the same everywhere, regardless of how each computer processes them. Again, if one side happened to submit a command more quickly than the other, than that may convey an advantage.

> If not, what am I misunderstanding about concurrency?

All that you're misunderstanding, is that concurrency - when handled properly and safely - only applies to independent events, and that these events usually have a prescribed order before they even reach the game software (dictated by the network traffic, for instance). At the point where the events interact, such as both operating on a single game state, they must stop being concurrent and start being serialised. It is certainly possible that a badly programmed game could introduce some sort of error or bias when it comes to combining these events, but it's much more likely that any advantage would be introduced between the player and the game by network latency or other physical factors.
> 6 votes

---
Tags: game-design, multithreading
---


# Question
Title: How does the SAT collision detection algorithm work
There are a lot of tutorials and sample code available showing how to implement the SAT collision detection algorithm.

But can someone explain, without math or code, what are the general principls behind this technique.

# Answer
> 20 votes
The basic idea behind the **Separating Axis Theorem** (SAT) is that if we can find a gap or *separation* between two objects then they must not be touching.

The corollary is that if we cannot find a gap between them, the objects *are* touching.

But how can we be sure that there is no gap, how can we be sure we've looked sufficiently hard for a gap? Let's think about what happens in the real world, when two objects are very close to each other and we want to check if they are touching or not;

We look along the edges of the objects!

Imagine the scene in the image above. You have to help your friend in the red car to parallel park into a tight spot. 'Bump parking' is considered rude where I come from, so you want to position yourself where you can see clearly if is getting too close to the white car.

You are probably going to position yourself close to 'A' and look along the yellow line. If you look that way and see daylight between the two cars, you know they are not touching. If the cars get VERY close, then looking along the yellow line is the only way to spot the very moment of collision.

What we are doing here is looking along the rear edge of the white car.

How did we know to look along that particular edge? In the real world we use our intuition. We know that looking along the purple line \[long edge of the red car\] or the green line \[long edge of the white car\] will not help in this situation.

But a computer doesn't have intuition, so we will ask it to "look" along **all** edges of both objects. If it finds a gap along **even one** of those edges then there's no collision. If it finds no gap on any of those edges, then that means the objects have collided.

How do we get the computer to 'look along an edge'? We use projections. We find a line (any line) at right angles to the edge we are considering and project both objects onto that edge. This line is called an 'axis' (not necessarily a coordinate axis, like x-axis or y-axis,)

A projection is a one dimensional version of the object (much like a shadow is a two dimensional version of a 3D object).

So we project all the points (usually just the corners) of the objects on to the axis. The projection converts the 2D points into distances along the axis. Now we can check if there is a gap between the projections. There is a gap if the smallest projection of one is greater than the largest projection of the other.

We repeat this process for all the edges, if a gap(separation) is found, that proves that the objects are not colliding. If we check all the edges of both objects and can't find a gap, them we can conclude the objects are touching.

For the underlying math, and examples of how to decide which lines you should be projecting on to, read How do I get the axes for SAT collision detection

---
Tags: collision-detection, separating-axis-theorem
---


# Question
Title: C++ OpenGL wireframe cube rendering blank
I'm just trying to draw a bunch of lines that make up a "cube". I can't for the life of me figure out why this is producing a black screen. The debugger does not break at any point.

I'm sure it's a problem with my pointers, as I'm only decent at them in regular c++ and in OpenGL it gets even worse.

```
const char* vertexSource =
    "#version 150\n"
    "in vec3 position;"
    "void main() {"
    "   gl_Position = vec4(position, 1.0);"
    "}";

const char* fragmentSource =
    "#version 150\n"
    "out vec4 outColor;"
    "void main() {"
    "   outColor = vec4(1.0, 1.0, 1.0, 1.0);"
    "}";

int main() {

    initializeGLFW();

    // Initialize GLEW
    glewExperimental = GL_TRUE;
    glewInit();

    // Create Vertex Array Object
    GLuint vao;
    glGenVertexArrays(1, &vao);
    glBindVertexArray(vao);

    // Create a Vertex Buffer Object and copy the vertex data to it
    GLuint vbo;
    glGenBuffers( 1, &vbo );

    float vertices[] = {
         1.0f,  1.0f,  1.0f, // Vertex 0 (X, Y, Z)
        -1.0f,  1.0f,  1.0f, // Vertex 1 (X, Y, Z)
        -1.0f, -1.0f,  1.0f, // Vertex 2 (X, Y, Z)
         1.0f, -1.0f,  1.0f, // Vertex 3 (X, Y, Z)
         1.0f,  1.0f, -1.0f, // Vertex 4 (X, Y, Z)
        -1.0f,  1.0f, -1.0f, // Vertex 5 (X, Y, Z)
        -1.0f, -1.0f, -1.0f, // Vertex 6 (X, Y, Z)
         1.0f, -1.0f, -1.0f  // Vertex 7 (X, Y, Z)
    };

    GLuint indices[] = {
        0, 1,
        1, 2,
        2, 3,
        3, 0,
        4, 5,
        5, 6,
        6, 7,
        7, 4,
        0, 4,
        1, 5,
        2, 6,
        3, 7
    };

    glBindBuffer( GL_ARRAY_BUFFER, vbo );
    glBufferData( GL_ARRAY_BUFFER, sizeof( vertices ), vertices, GL_STATIC_DRAW );
    //glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, vbo);
    //glBufferData( GL_ELEMENT_ARRAY_BUFFER, sizeof( indices ), indices, GL_STATIC_DRAW );

    // Create and compile the vertex shader
    GLuint vertexShader = glCreateShader( GL_VERTEX_SHADER );
    glShaderSource( vertexShader, 1, &vertexSource, NULL );
    glCompileShader( vertexShader );

    // Create and compile the fragment shader
    GLuint fragmentShader = glCreateShader( GL_FRAGMENT_SHADER );
    glShaderSource( fragmentShader, 1, &fragmentSource, NULL );
    glCompileShader( fragmentShader );

    // Link the vertex and fragment shader into a shader program
    GLuint shaderProgram = glCreateProgram();
    glAttachShader( shaderProgram, vertexShader );
    glAttachShader( shaderProgram, fragmentShader );
    glBindFragDataLocation( shaderProgram, 0, "outColor" );
    glLinkProgram (shaderProgram);
    glUseProgram( shaderProgram);

    // Specify the layout of the vertex data
    GLint posAttrib = glGetAttribLocation( shaderProgram, "position" );
    glEnableVertexAttribArray( posAttrib );
    glVertexAttribPointer( posAttrib, 3, GL_FLOAT, GL_FALSE, 0, 0 );

    // Main loop
    while(glfwGetWindowParam(GLFW_OPENED)) {

        // Clear the screen to black
        glClearColor( 0.0f, 0.0f, 0.0f, 1.0f );
        glClear( GL_COLOR_BUFFER_BIT );

        // Draw lines from 2 vertices
        glDrawElements(GL_LINES, sizeof(indices), GL_UNSIGNED_INT, indices );

        // Swap buffers
        glfwSwapBuffers();
    }

    // Clean up
    glDeleteProgram( shaderProgram );
    glDeleteShader( fragmentShader );
    glDeleteShader( vertexShader );

    //glDeleteBuffers( 1, &ebo );
    glDeleteBuffers( 1, &vbo );

    glDeleteVertexArrays( 1, &vao );

    glfwTerminate();
    exit( EXIT_SUCCESS );
}

```

# Answer
> 1 votes
You have no view or projection matrix, so your view volume is a cube 2 units wide and 2 units high and centred on the origin.

Coincidentally, you are drawing a cube that is 2 units wide and 2 units high and centred on the origin. So your cube is getting draw just on the outside edge the view volume.

Draw a smaller cube (use +/-0.5f for vertex coords) and you should see something.

That's assuming that the rest of the code is fine...

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


# Question
Title: How to apply effects that occur (or change) over time to characters in a game?
So assume that I have a system that applies Effects to Characters like so:

```
public class Character {
    private Collection<Effect> _effects;

    public void AddEffect (Effect e) {
        e.ApplyTo(this);
        _effects.Add(e);
    }
    public void RemoveEffect (Effect e) {
        e.RemoveFrom(this);
        _effects.Remove(e);
    }
}

public interface Effect {
    public void ApplyTo (Character character);
    public void RemoveFrom (Character character);
}

```

**Example Effect: Armor Buff for 5 seconds.**

```
void someFunction() {
    // Do Stuff ...
    Timer armorTimer = new Timer(5 seconds);
    ArmorBuff armorbuff = new ArmorBuff();
    character.AddEffect(armorBuff);
    armorTimer.Start();
    // Do more stuff ...
}

// Some where else in code
public void ArmorTimer_Complete() {
    character.RemoveEffect(armorBuff);
}

public class ArmorBuff implements Effect {
    public void applyTo(Character character) { character.changeArmor(20); }
    public void removeFrom(Character character) { character.changeArmor(-20); }
}

```

Ok, so this example would buff the Characters armor for 5 seconds. Easy to get working. But what about effects that change over the duration of the effect being applied. Two examples come to mind:

**Damage Over Time: 200 damage every second for 3 seconds.** I could mimic this by applying an *Effect* that lasts for 1 second and has a counter set to 3, then when it is removed it could deal 200 damage, clone itself, decrement the counter of the clone, and apply the clone to the character. If it repeats this until the counter is 0, then you got a damage over time ability.

I'm not a huge fan of this approach, but it does describe the behavior exactly.

**Degenerating Speed Boost: Gain a speed boost that degrades over 3 seconds until you return to your normal speed.** This is a bit harder. I can basically do the same thing as above except having timers set to some portion of a second, such that they occur fast enough to give the appearance of degenerating smoothly over time (even though they are really just stepping down incrementally).

I feel like you could get away with only 12 steps over a second (maybe less, I would have to test it and see), but this doesn't seem very elegant to me. The only other way to implement this effect would be to change the system so that the *Character* checks the \_effects collection for effects that alter any of the properties any time that they are being used. I could handle this in functions like *getCurrentSpeed()* and *getCurrentArmor()*, but you can imagine how much of a hassle it would be to have that kind of overhead every time you want to do a calculation with movement speed (which would be every time you move your character).

Is there a better way to deal with these kinds of effects or events?

# Answer
> 0 votes
I have something similar to your first option. However, it's a bit more self contained in a timed effect. Timed effects have some settings:

* **Tick delay**: The time before counting starts.
* **Tick count**: The number of times the effect ticks. Each tick is an event where some effect is calculated and applied.
* **Tick time**: The time between each tick.
* **Effect**: This is the effect to apply *per tick*. This is an object that contains info about what to change, by how much, a maximum/minimum total amount and so on.

I use this for one off effects too. Just set the tick count to `1` and the tick time to `0`. The effect is applied immediately.

Since each tick is an event, I can calculate the potency of the effect based on the time elapsed since the effect was applied, the amount of *whatever* has been applied already and various other attributes.

---
Tags: events, character, timer, effects
---


# Question
Title: Google Cloud Messaging (GCM) for turn-based mobile multiplayer server?
I'm designing a multiplayer turn-based game for Android (over 3g). I'm thinking the clients will send data to a central server over a socket or http, and receive data via GCM push messaging. I'd like to know if anyone has practical experience with GCM for pushing 'real-time' turn data to game clients. What kind of performance and limitations does it have?

I'm also considering using a RESTful approach with GAE or Amazon EC2. Any advice about these approaches is appreciated.

# Answer
> I'm thinking the clients will send data to a central server over a socket or http, and receive data via GCM push messaging.

GCM push messaging strategy isn't appropriate for sending large amounts of data, for a few reasons:

* Rate limits are in place to prevent malicious or poorly coded apps from spamming an individual device with messages.
* Messages aren't guaranteed to arrive in-order.
* Messages aren't guaranteed to arrive as fast as you send them out. Even if the device receives one GCM message a second, at a max of 1K, that's 8kbps, or about the speed of home dial-up internet in the early 1990's. Your app rating on Google Play will reflect having done that to your users.

> I'm also considering using a RESTful approach with GAE or Amazon EC2.

Yes, it is good approach to use Cloud for turn-based mobile multiplayer server.

**There are couple of ways to do multiplayer game:**

* Multiplayer on the same device: Make multiplayer logic for your game and allow multi touch controller for both players on the same screen. It can be turn based or simultaneous. For this game you do not have any dependency but the players should be near each other.
* Bluetooth game: This the next stage of multiplayer games. A little bit trickier but can be done. The controller need to get and synchronize the game between two devices that are near each other. A short review of the Bluetooth android API and you are good to go.
* Score comparison: This is not a real multiplayer but you can upload scores of the users and compare with other users. You can do it yourself with server side that will store all the scores for each user or use existing services that allow score comparison like Skiller SDK or scorelop SDK.
* Real multiplayer games: This is the best one from my opinion. Everybody can play with everybody else in real time (as far as latency allows :D). This one is pretty difficult, if you want to do all by yourself. Here you will need a strong server side and a lot of server logic. But again you can use existing services that handle the server side for you. I went with the Skiller multiplayer SDK. Good support and monetization features.

**If you want to create turn-based mobile multiplayer server, the follwoing resources may help you**
> 3 votes

---
Tags: android, multiplayer, turn-based, google-app-engine, socket
---


# Question
Title: Tilting towards turn direction (for a motorbike)
I have a motorbike which moves along based on a direction vector, I set its forward direction to the direction it's moving.

What I'd like to also do with it is have the motorcycle tilt in the direction it's turning, I haven't had much luck figuring this out though, any ideas?

# Answer
Take the cross product of those two vectors (turning direction and current forward direction). Assuming your bike is riding on the XZ plane, if the vector points upward (y is positive) then the bike should tilt left, if it points downward (y is negative) then it should tilt right. The magnitude of the vector probably represents how "big" the tilt should be, but I haven't tried it.

For example, if the bike is currently facing down the negative z axis, the forward direction will be:

```
{0,0,-1}

```

If you want to turn 90 degrees *right*, the turning direction vector will be:

```
{1,0,0}

```

If you want to turn 90 degrees *left*, the turning direction vector will be:

```
{-1,0,0}

```

If you calculate the cross products for both left and right turns, they look like this:

```
Right turn: {0,0,-1} x {1,0,0} = {0,-1,0}
Left turn: {0,0,-1} x {-1,0,0} = {0,1,0}

```
> 1 votes

---
Tags: mathematics, rotation, vector
---


# Question
Title: In what kind of variable type is the player position stored on a MMORPG such as WoW?
I even heard J. Carmack quickly talk about it...

How a software can track a player's position so accurately, being on a such huge world, without loading between zones, and on a multiplayer scale ? How is the data formatted when it passes through the netcode ?

I can understand how vertices are stored into the graphic card's memory, but when it comes to synchronize the multiplayer, I can't imagine what is best.

# Answer
Scott Bilas worked on Dungeon Siege and wrote a paper, "The Continuous World of Dungeon Siege". While Dungeon Siege is not a MMO, it does have a world, and he talks about player positioning in his paper. I found it to be a great read. Here is the relevant section:

> The Precision Issue
>
> From the beginning, the engineering team knew that the continuous world was going to significantly affect the engine and content design, and the core issue was numerical stability. Imagine two characters walking in formation two meters apart heading east away from the origin. At some point, the distance from each other is overwhelmed by the distance from the origin, and the characters will appear to be “at the same location”.
>
> With floating point, the further you get from the origin, the more precision you lose, which can cause all manner of nasty problems. Things don’t sort right, cracks appear between adjacent meshes, space starts to quantize, and cats and dogs start living together. Dungeon Siege uses the FPU in single precision mode for the obvious performance benefits, and to match the native precision of the video hardware. However, even if we increased the precision, it ultimately could never solve the problem because the world was planned to be, and ended up, incredibly large.
>
> The precision problem meant it would not be possible to have a unified world coordinate space like most other games. Instead, the solution was to segment the continuous world into a set of independent coordinate spaces, and switch among them periodically to reset the precision. A variety of ideas were tried out within these constraints, and we eventually settled on a variation of a standard portal system.
>
> Our solution consists of a relational node-based coordinate system, in which each chunk of geometry (Siege Node) has its own coordinate space, and is linked spatially to neighboring geometry via the doors it shares in common with those neighbors. The arrangement of nodes connected by doors forms a continuous graph that represents the entire world map. This node system evolved over time from its original goal of maintaining FPU precision to become the primary method of efficiently subdividing space, and the root of countless optimizations.
>
> In order to encapsulate the concept of a 3D position relative to a specific node, the traditional (x,y,z) vector had to be augmented with a node ID (x,y,z,node) and represent an offset from the origin of a specific node instead. This 4-tuple is encapsulated as a Siege Node Position, or SiegePos. Later on, we added a SiegeRot (quaternion,node) in order to handle comparisons between orientations across nodes.
>
> The phrase “there is no world space” became a mantra to the team, although it literally took years for everyone to fully grok what it meant.

You can see more of his papers on Dungeon Siege here.
> 26 votes

# Answer
For a huge zoneless world I would either go for a double precision vertex, or floating point with smaller chunks dividing the land.

Each chunk would have it's own coordinate system. When you cross the border to each of these chunks you would transform everything to that coordinate system. That's how they do it in flight sims anyway.

If you have small zones, I guess float will be enough.
> 3 votes

# Answer
I'd say a for actual location it's a vector of 3 floats. But there would also be a zone index associated with the player as well. (But not part of the location because everything handled by that zone server is in the same zone and hence doesn't need to be in the same data structure.)

Remember there are at least 4 zones. The 4 major continents. I don't think any one of those is more than about 10km on a side. For example, this blog pre the latest expansion calculates the entire travel-able area as 41 square miles. All of the battlegrounds, all of the instances, are each with-in their own zone and coordinate space as well.

Using the LUA API you can get the position of the player GetPlayerMapPosition() returns two floats each from 0 to 1 as a proportion along the entire world map.
> 2 votes

# Answer
For WoW, I expect that they use a simple float x/y/z - but relative to a specific 'zone'

This would help to handle 'moving zones', for example, boats and zeppelins
> 1 votes

# Answer
Usually online games such as Wow, Tibia etc. Store the player pos. using three variables X + Y + Z in the SQl player meta table. Runescape does it without the Z - that way the player is always rendered on the top the top of the ground mesh.
> 1 votes

# Answer
A float? Well, an array of 3 floats for a 3D game. At least for us we use feet as units so all you need is 3-4 decimal places to be at the point that float noise isn't a problem. If a big zone is only a mile or two on a side, its not all that big a deal. As for transparent zoning in MMOs, thats a different question altogether. In the grand scheme of difficult problems in an MMO, storing position is pretty low on the list.
> -2 votes

---
Tags: multiplayer
---


# Question
Title: Determining if something is on the right or left side of an object?
I have a character in a 3D world which is facing an arbitrary direction on a flat plane, the player can click on the left or right side of the character and based on which side is clicked on a different action happens.

How can I determine which side the click occured on? Obviously for straight on ahead (0,0,1) I can simply use the x coordinate of the click point to determine if it's the left or right hand side, but what about other cases?

# Answer
> 4 votes
You first have to figure out which direction is 'to the right' of your character. For thsi you will need to know which way the character is facing (uusally 'direction') and which way is up typically (0,1,0) or it could be the normal of the plane the character moves around on.

```
right = Vector3.Cross(direction, up);

```

Next, we need a vector representing the relative position of the mouse click and the character.

```
mouseDir= mousePos-charPos;

```

finally, we need to check if the angle between the right vector and the mouseDir vector is greater than or less than 90 degrees. If the angle is less than 90deg the the mouse click is on the right, other wise it is on the left.

The dot product will return a positive value if the angle is less than 90, a negative value if the angle is greater than 90.

```
if(Vector3.Dot(right, mouseDir) <0){
   //do left hand stuff
}else{
   //do right hand stuff
}

```

# Answer
> 2 votes
You can use vector cross product for that. Create a vector from character to the clicked position and take a cross product of that and the character facing direction. The sign of the cross product "up" component determines which side was clicked. For ground plane this is the y-component of the cross product. For arbitrary plane, use dot product of the cross product and the plane normal to get the sign.

```
vec3 delta = clickPosition - characterPosition;
vec3 cross = crossProduct(delta, characterDirection);
float dot = dotProduct(cross, planeNormal);
if (dot < 0) {
    // Do something
}
else {
    // Do something else
}

```

---
Tags: mathematics, vector, direction
---


title: Understanding normal maps on terrain

text:
# Question
Title: Understanding normal maps on terrain
I'm having trouble understanding some of the math behind *normal map textures* even though I've got it to work using borrowed code, I want to understand it.

I have a terrain based on a heightmap. I'm generating a mesh of triangles at load time and rendering that mesh.

Now for each vertex I need to calculate a **normal**, a **tangent**, and a **bitangent**. My understanding is as follows, have I got this right?

**normal** is a unit vector facing outwards from the surface of the triangle. For a vertex I take the average of the normals of the triangles using that vertex.

**tangent** is a unit vector in the direction of the 'u' coordinates of the texture map.

As my texture u,v coordinates follow the x and y coordinates of the terrain, then my understanding is that this vector is simply the vector along the surface in the x direction. So should be able to calculate this as simply the difference between vertices in the x direction to get a vector, (and normalize it).

**bitangent** is a unit vector in the direction of the 'v' coordinates of the texture map.

As my texture u,v coordinates follow the x and y coordinates of the terrain, then my understanding is that this vector is simply the vector along the surface in the y direction. So should be able to calculate this as simply the difference between vertices in the y direction to get a vector, (and normalize it).

However the code I have borrowed seems much more complicated than this and takes into account the actual values of u, and v at each vertex which I don't understand the need for as they increase in exactly the same direction as x, and y.

I implemented what I thought from above, and it simply doesn't work, the normals are clearly not working for lighting.

Have I misunderstood something? Or can someone explain to me the physical meaning of the tangent and bitangent vectors when applied to a mesh generated from a hightmap like this, when u and v texture coordinates map along the x and y directions.

Thanks for any help understanding this.

# Answer
> 5 votes
There are quite some tutorials, I'm sure, on the issue of normal mapping, but since you're here, I assume you're not satisfied with what you found.

In your case, the terrain is ussualy a Monge Patch, which is not a complicated 2D manifold to perform geometric measurments using normal differential geometry.

First, **why a normal map technique**?

Because the normal computed from the geometry, by averaging the face normals at a common vertex, like you described, and then computing another interpolated, per pixel normal won't allow for micro-relief lighting. The normal computed this way is "accurate" only if there's no "skin" on your geometric surface.

There are some algorithms that compute the normal map texture (the mostly blue/fuchsia RGB texture you know by now). They could rely on image processing (for example, a convolution kernel to compute the image gradients in the x and y direction and then take their cross product to come up with the 3d vector for a normal - which is quite natural for these Monge patches). You are not interested in those, since you already come with a texture.

Then **how to map** the normal texture correctly?

Its *(uv)* coordinates should coincide with your diffuse/ambient texture that you want to enhance with lighting computations. Like you said, the *u* could be in the *x* direction, the *v* in the *y* direction of a 2D rectangle that is viewed from above. For this rectangle, there is an extrinsic normal that, in the "undeformed/unmapped" state, points out of the screen (like in the above figure). This is also a Monge patch, where the normal is piercing the screen towards your eyes, the tangent is down (assume you're not batman :) ) and the bitangent is towards the right. EXAMINE the little red dot in in both figures! This is the same dot on the texture, but when mapped, localy, in a neighbourhood around it, the texture will get stretched! It is this stretching that calls for differential geoemtry stuff: you want to see HOW the tangent and bitangent are pointing when this point lies on a Monge patch, instead of your rectangular, flat screen surface.

**What does the normal map have to do with frames?** Well, if for each pixel you assume the normal map is telling you that the NEW normal is not pointing in the perpendicular direction from the rectangle (the right figure!). You then store this corrected normal as a 3D vectors. For that you need 3 coordinates and.. a *coordinate frame*. Here's the magic! This frame is the initial (T,B,N) frame, the tangent-normal frame of that rectangle. When you map a pixel onto a Monge patch, you *rotate* this frame. This new frame comes as *vertex attribute* through the vertex shader input (i.e. your original per-vertex normal and a tangent vector). This tangent vector is also computed from the geometry, for example by using finite differencing: using the same concept you described, by approximating a directional derivative in the direction of *u*. Since you have these two *geometry* related vectors, you can compute the binormal ass their cross product.. and you have the whole frame.

**Why do we need to transform that normal anyway?**

As said before, this normal is not in object frame coordinates! It's in tangent space coordinates! You usually perform lighting computations in object space, so you need to get your normal in object coordinates by multiplying the vector you get using the *tex2D* sampling function from that normal texture BY the (T,B,N) matrix. Now you have the corrected normal and the lighting equation computations must work accordingly.

**Another hidden aspect!:** the computations of the tangent *rely* on the (uv) mapping AND on the geometry. For a vertex *V* having *(uv)* as its texture coordinate pair, you need to know what *V'* vertex of the surface is nearest to *V* and has a mapping of *(u+epsilon, v)*. Since you're talking heightmaps, this vertex is easy to find in a natural way. The tangent can be approximated as `(V' - V)/epsilon` and then normalize, but please observe that the texture coordinates and the geometry are *both* used in the computation of the tangent field. If you do not correlate them correctly, your normals will be rubbish in the end.

---
Tags: mathematics, graphics-programming, normal-mapping
---


title: Making an interactive 2D map

text:
# Question
Title: Making an interactive 2D map
So recently I have been working on a Legend of Zelda: A Link to the Past clone, and I am wondering how I could handle certain map interactions (like cutting grass, lifting rocks, etc).

The way I am currently doing the tilemap is with 2 PNGs. The first is the "tilemap" where each pixel represents a 16x16 tile and the (red, green) values are the (x, y) coords for the tile in the second PNG (the "tileset"). I am then using the blue channel to store collision data.

Each tile is split into 4 8x8 tiles and represented by a 2 bit value (0 = empty, 1 = Jumpdown point, 2 = unused right now, 3 = blocking). 4 of these 2 bit values make up the full blue channel (1 byte). So collisions work great, and I am moving on to putting interactive units on the level; but I am not sure what a good way is to do it.

I have experimented with spawning an entity for each grass and rock, but there are just WAY to many; FPS just dies even if I confine it to the current "zone" the user is in (for those who remember LTTP it had zones you moved between). It does make a difference that this is a browser-based JavaScript game.

**tl;dr:** What is a good way to have an interactive map without using full blown entities for each interactive item?

# Answer
> 2 votes
You could use just red to store the type of the tile.
And you have a function/ a table that gives you x,y in the tileset for the type.
So now green is free and you can use it to store a state ( for grass : 0:normal, 1:cut, 2 : burnt, ... ). Then when you draw you use both type and state to find the right tile.
In fact you need also to provide a few functions for each type to react.

expl : hitBySword(tileType, state) returns -1 if no state change, and the new state if change.

hitBySword(water,0) == -1 ; hitBySword(grass, 0) == 1; hitBySword(grass, 1) == -1;

Edit : 1) my suggestion is to use TYPE in the red, something like :

```
tileTypeEnum = {
roof : 0,
grass : 1,
water : 2,
rock  : 3
}

```

and 256 types might be enough.

and then you have a lookup table :

```
typeToTileIndex=[];
typeToTileIndex[roof]=0;  typeToTileIndex[grass]=5;

```

and finally you might setup your png and/or your tile array such as :

```
finalIndex = typeToTileIndex[red]+blue;

```

if you use animated tiles, the above could become :

```
 typeToTileIndex[grass]={ i:0, anLength : 3, anTime:0.3};

```

((if you use several tyles for one type (example to do grass/water transition North/South/...) store it in the blue, and the state would be in the transparency.))

or you can have full flexibility other animations with :

```
  typeToTileIndex[grass]=[];
  typeToTileIndex[grass][normal] = { i:0, anLength : 3, anTime:0.3};
  typeToTileIndex[grass][cut]    = { i:4, anLength : 1, anTime:0.0}; // no anim if cut
  typeToTileIndex[grass][burnt]  = { i:5, anLength : 6, anTime:0.1};

```

3 others remarks :
1) you might use transparency to store other data .
2) since your map is not used as bitmap but rather as a proprietary format you can go for your own format, using JSON to stringify for instance and using XMLHTTPRequests to load it. Advantage is that you could store the type / state -\> tile anim lookup table here, and other info maybe. But you'll have to code an editor, maybe in html+javascript.
3) Even if you stick to a png, you could still move the map data, once loaded, in another data structure that would be more easy to handle or contain more data. So drawing all tiles would become, for instance :

```
for (xt=cameraX; xt<cameraX + cameraWidth ; xt++)
       for (yt=cameraY; yt<cameraY + cameraHeight ;yt++)
             map[xt][yt].draw();

```

two level editors :

http://dambots.com/dame-editor
http://www.ogmoeditor.com/

# Answer
> 0 votes
Since the number of entities directly affects your FPS overall i have to ask, do you draw everything on every frame? In browsers this is often the bottleneck, remember back in the time of ALTTP we used blitting engines, only drawing dirty-marked rectangles, aswell as caching images.

For example:

1 entity + 1 layer of grass + 1 layer of ground get rendered into one image and you only draw that combined image. This allready saves performance if the combination has to be drawn 3 times.

EDIT: if you implement a scenegraph, you can query that graph for boundry boxes of your dirty space, then only draw that dirty space onto the canvas.

i allready made a huge post once about a scene graph in js: https://stackoverflow.com/questions/13099845/collision-detection-in-html5-canvas-optimization-too/13100287#13100287

---
Tags: 2d, game-design, graphics, javascript, game-mechanics
---


# Question
Title: How do you clean up textures that are too photo-realistic to match the rest of your game assets?
I was browsing for textures online and notice most of it are too photo-realistic and many of them is just photo of real thing.
I'm sure there some "cleanup" process for this type of texture using Photoshop filter or via other tool etc. Let say I want texture to match Left for Dead 2 look.
Does anyone have any links\resources on this?

# Answer
Yes, there are filters you can apply. Though it will depend on the style you're looking for. For example using GIMP I produced this:

From photo realistic to gritty semi-realistic cartoon. The filters I applied:

1. Apply RGB noise
2. Apply Blur
3. Apply Cartoon

Very quick to do. But you may have to tweak it more depending on the style you're after.

Original image source.
> 5 votes

# Answer
You can always cut the number of pixels to 90% "make the picture thiner"

If you get rid of 1,9 mb from a 2mb picture you will get your pic as sharp as the Pokemons :) I Hope that that is what you meant.
> 2 votes

---
Tags: textures, assets
---


# Question
Title: Is it possible exchange points between players using Game Center?
I want to create a turn based two player game. In my game in a certain stage if player 1 loses he must give few points that he have to the opposite player. The game is implemented with game center. Is there any possibility that I can do this point exchange via game center. I am also thinking about creating a local DB can some one help me with the best possible way.

# Answer
I dont know the version of the sdk you are using, but in the latest version Game Center now support multiplayer games, witch means now Game Center can handle **all** data exchange.

Take a look at this tutorial: How To Make A Simple Multiplayer Game with Game Center Tutorial: Part 1/2
> 2 votes

# Answer
The ammount of "points" stored in the GS is always an integer number. 1500 points (I noticed that some funny boys hacked the game highscores for the IOS game "Temple Run" putting the maximum possible integer 237~.

Anyway a simple script would handle that example:

If player A wants to give $x= '1000' points Then

Check if Player A point count =\< $x

If False end

If true add value -$x points to Player A point count

and Add value $x to player B point count END
> 0 votes

---
Tags: cocos2d-iphone, game-center, xcode
---


# Question
Title: GLSL per pixel lighting with custom light type
Ok, I am having a big problem here. I just got into GLSL yesterday, so the code will be terrible, I'm sure.

Basically, I am attempting to make a light that can be passed into the fragment shader (for learning purposes). I have four input values: one for the position of the light, one for the color, one for the distance it can travel, and one for the intensity. I want to find the distance between the light and the fragment, then calculate the color from there. The code I have gives me a simply gorgeous ring of light that get's twisted and widened as the matrix is modified. I love the results, but it is not even close to what I am after.

I want the light to be moved with all of the vertices, so it is always in the same place in relation to the objects. I can easily take it from there, but getting that to work seems to be impossible with my current structure. Can somebody give me a few pointers (pun not intended)?

Vertex shader:

```
attribute vec4 position;
attribute vec4 color;
attribute vec2 textureCoordinates;

varying vec4 colorVarying;
varying vec2 texturePosition;
varying vec4 fposition;
varying vec4 lightPosition;
varying float lightDistance;
varying float lightIntensity;
varying vec4 lightColor;

void main() {
    vec4 ECposition = gl_ModelViewMatrix * gl_Vertex;
    vec3 tnorm = normalize(vec3 (gl_NormalMatrix * gl_Normal));
    fposition = ftransform();

    gl_Position = fposition;
    gl_TexCoord[0] = gl_MultiTexCoord0;
    fposition = ECposition;

    lightPosition = vec4(0.0, 0.0, 5.0, 0.0) * gl_ModelViewMatrix * gl_Vertex;
    lightDistance = 5.0;
    lightIntensity = 1.0;
    lightColor = vec4(0.2, 0.2, 0.2, 1.0);
}

```

Fragment shader:

```
varying vec4 colorVarying;
varying vec2 texturePosition;
varying vec4 fposition;
varying vec4 lightPosition;
varying float lightDistance;
varying float lightIntensity;
varying vec4 lightColor;

uniform sampler2D texture;

void main() {
    float l_distance = sqrt((gl_FragCoord.x * lightPosition.x) + (gl_FragCoord.y * lightPosition.y) + (gl_FragCoord.z * lightPosition.z));
    float l_value = lightIntensity / (l_distance / lightDistance);
    vec4 l_color = vec4(l_value * lightColor.r, l_value * lightColor.g, l_value * lightColor.b, l_value * lightColor.a);

    vec4 color;
    color = texture2D(texture, gl_TexCoord[0].st);
    gl_FragColor = l_color * color;
    //gl_FragColor = fposition;
}

```

Result produced by this code:

http://i1177.photobucket.com/albums/x349/Jpdiffy/ScreenShot2012-11-16at93614PM.png

With Ken's edit:

http://i1177.photobucket.com/albums/x349/Jpdiffy/ScreenShot2012-11-17at32733PM.png

# Answer
If you want the light to have maintain a relative position to all the objects you are rendering, then this line;

```
lightPosition = vec4(0.0, 0.0, 5.0, 0.0) * gl_ModelViewMatrix * gl_Vertex;

```

should be \[after edit\];

```
lightPosition = gl_ModelViewMatrix*vec4(0.0, 0.0, 5.0, 0.0)  ;

```

Also, is the `l_distance` meant to be the distance from the light to the fragment? Your code for l-disatnce doesn't make any gsense (to me at least). If its meant to be distance;

```
vec4 l_vector=gl_FragCoord-lightPosition;

float l_distance = sqrt((l_vector.x*l_vector.x) + (l_vector.y *l_vector.y) + (l_vector.z * l_vector.z));

```
> 2 votes

---
Tags: opengl, glsl, lighting
---


title: How to use NGUI with Unity

text:
# Question
Title: How to use NGUI with Unity
I feel like Im missing something really simple, but Ive read about all the events NGUI can generate from an object and just dont get where to recive (or handle) the event. Do I just attach it to a script on the object?

# Answer
Yup.

You can also look into add-on frameworks like NData, which is a MVVM data manager which can simplify a lot of UI code (and complicate other UI code; use the right tool for the job and all that jazz).
> 0 votes

# Answer
The easiest way to handle UI Events in NGUI is to use the UIEventListener class. All you have to do is call it like this:

```
UIEventListener.Get(buttonObj).onClick += YourClickCallback;

```
> 2 votes

# Answer
Some of the NGUI widget scripts have delegates to handle events, I just modified the rest to let me supply event handlers - ie. added a buttonClickDelegate and buttonHoldDelegate to UIButton
> 0 votes

---
Tags: unity
---


title: OpenGL fovx question

text:
# Question
Title: OpenGL fovx question
To boil my question down to the simplest form, I fear I am oversimplifying how mat4 perspective works. I am using

```
mat4.perspective(45, 2, 0.1, 1000.0)

```

(the binding is WebGL fwiw). With a fovy of 45, and an aspect ratio of 2, I expect to have a fovx of 90. Thus, if I position my camera at (0, 0, 50), looking towards the origin, I expect to see a cube positioned at (50, 0, 0) (45 degrees) right at the very periphery of my screen, half on, half off,. Instead, a cube at (50, 0, 0) is totally off screen, and my actually periphery occurs at about (41.1, 0, 0).

What am I missing here?

Thanks, nick

# Answer
You can't multiply the angle by the aspect ratio directly; the aspect ratio is the ratio of pixels horizontally vs. vertically, not the ratio of the angles.

To demonstrate the problem: Assume we have a window that's 100 pixels tall, and 1000 pixels wide. That's a 10:1 aspect ratio. If we have a 90 degree vertical field of view, then naively multiplying the vertical angle by the field of view would imply that we had a 900 degree horizontal field of view. Which is clearly nonsense.

To get the horizontal field of view, you need to convert the angle into pixels, multiply the pixels by the aspect ratio, and then convert back into an angle. It'd look something like this:

```
float halfVerticalFOV = verticalFOV * 0.5f;
float verticalPixels = tan( halfVerticalFOV );
float horizontalPixels = aspectRatio * verticalPixels;
float halfHorizontalFOV = atan( horizontalPixels );
float horizontalFOV = halfHorizontalFOV * 2.0f;

```

(Note that trigonometry functions like tan() and atan() will expect your angles to be expressed in radians, not in degrees)

(Also note that I haven't bothered to calculate actual numbers of pixels; just converted our numbers into pixel-relative units so we can legally multiply them by the aspect ratio, before converting back into angles)

Running your example through this code shows that with a vertical FOV angle of 45 degrees and an aspect ratio of 2:1, your horizontal FOV angle will be approximately 79.278 degrees.

Comparing that back to your hand-placed cube, if we calculate `atan2(41.1,50.f)` (the offset from your camera to the cube you placed manually at the edge of the screen), that returns an angle of 39.42 degrees from forward. The 79.278 FOV value we calculated earlier gives us 39.639 degrees to either side of the camera. So your eyeballing gave an approximate 39.42 degrees from center to edge, and our calculation gives us 39.64 degrees. So your eyeballing was pretty close.

In fact, you'd actually want to place your cube at `tanf( halfHorizontalFOV ) * 50.f == 41.4213` in order to place its center point precisely on the edge of the screen, with the camera placed 50 units back from the object, as in your situation.
> 7 votes

---
Tags: opengl, perspective
---