# Question
Title: Spritebatch Vertex shader world matrix change after each draw
I have a spritebatch where I draw some textures transformed in 3d space.

The easy way was just Begin with the transformation matrix, draw, and end it right after.

But that is silly, so I'm trying with a vertex shader.

My results however aren't the desired ones. After the first draw&transformation, the rest of the textures stop apprearing, that hints me that I cant change the world matrix between draws.

How should I approach this?

I set the projection matrix like this, before the sp.Begin:

```
shader.Parameters["Projection"].SetValue(Matrix.CreateOrthographicOffCenter(
                                         0, sp.GraphicsDevice.Viewport.Width,
                                         sp.GraphicsDevice.Viewport.Height, 0, 0, 1)
                                         );
sp.Begin(SpriteSortMode.Deferred, null, null, null, null, shader);

```

afterwards:

```
    rotM = Matrix.CreateFromYawPitchRoll(MathHelper.ToRadians(startRotations.Y), MathHelper.ToRadians(startRotations.X), MathHelper.ToRadians(startRotations.Z))
               //scale after rotation so I can destroy the z value after rotation
                * Matrix.CreateScale(endScale.X, endScale.Y, 0)
                * Matrix.CreateTranslation((Origin.X + PositionRec.X + Offset.X) * endScale.X, (Origin.Y + PositionRec.Y + Offset.Y) * endScale.Y, 0);

        shader.Parameters["World"].SetValue(rotM);
        shader.CurrentTechnique.Passes[0].Apply();
        sp.Draw(BackgroundTexture, Vector2.Zero, PositionRec, BackgroundColor * alpha);
        rotM = Matrix.Identity;

```

Vertex shader:

```
float4x4 World;
float4x4 Projection;

struct VertexShaderInput
{
    float4 Position : POSITION0;
    float2 TexCoord : TEXCOORD0;

};

struct VertexShaderOutput
{
    float4 Position : POSITION0;
    float2 TexCoord : TEXCOORD0;

};

VertexShaderOutput VertexShaderFunction(VertexShaderInput input)
{
    VertexShaderOutput output;

    float4 worldPosition = mul(input.Position, World);

    output.Position = mul(worldPosition, Projection);

    output.TexCoord= input.TexCoord;

    return output;
}

```

pixel shader:

```
float4 PixelShaderFunction(VertexShaderOutput input, bool front:  VFACE) : COLOR0
{
    float4 Color = tex2D(ColorMapSampler, input.TexCoord);
    return Color;

}

```

Why is this happening? It really looks like that the world matrix that I use is only changed the first time, why?

Thanks in advance, Roger

EDIT:

Ok since I wanted to reuse spritebatch to render quads in 3d, I had to addapt 2 classes in monogame to get this to work.

in spritebatch.cs i had to include some new methods:

```
     public void Draw(Texture2D texture, Vector2 position, Rectangle? sourceRectangle, Color color, Matrix transform)
            {

                Draw(texture, position, sourceRectangle, color, 0f, Vector2.Zero, 1f, SpriteEffects.None, 0f, transform);
            }

public void Draw(Texture2D texture,
        Vector2 position,
        Rectangle? sourceRectangle,
        Color color,
        float rotation,
        Vector2 origin,
        float scale,
        SpriteEffects effect,
        float depth,
        Matrix transform)
        {
            CheckValid(texture);

            var w = texture.Width * scale;
            var h = texture.Height * scale;
            if (sourceRectangle.HasValue)
            {
                w = sourceRectangle.Value.Width * scale;
                h = sourceRectangle.Value.Height * scale;
            }

            DrawInternal(texture,
                new Vector4(position.X, position.Y, w, h),
                sourceRectangle,
                color,
                rotation,
                origin * scale,
                effect,
                depth,
                transform);
        }

    internal void DrawInternal(Texture2D texture,
             Vector4 destinationRectangle,
            Rectangle? sourceRectangle,
             Color color,
             float rotation,
             Vector2 origin,
              SpriteEffects effect,
              float depth,
                Matrix transform)
            {
                var item = _batcher.CreateBatchItem();

                item.Depth = depth;
                item.Texture = texture;

                if (sourceRectangle.HasValue)
                {
                    _tempRect = sourceRectangle.Value;
                }
                else
                {
                    _tempRect.X = 0;
                    _tempRect.Y = 0;
                    _tempRect.Width = texture.Width;
                    _tempRect.Height = texture.Height;
                }

                _texCoordTL.X = _tempRect.X / (float)texture.Width;
                _texCoordTL.Y = _tempRect.Y / (float)texture.Height;
                _texCoordBR.X = (_tempRect.X + _tempRect.Width) / (float)texture.Width;
                _texCoordBR.Y = (_tempRect.Y + _tempRect.Height) / (float)texture.Height;

                if ((effect & SpriteEffects.FlipVertically) != 0)
                {
                    var temp = _texCoordBR.Y;
                    _texCoordBR.Y = _texCoordTL.Y;
                    _texCoordTL.Y = temp;
                }
                if ((effect & SpriteEffects.FlipHorizontally) != 0)
                {
                    var temp = _texCoordBR.X;
                    _texCoordBR.X = _texCoordTL.X;
                    _texCoordTL.X = temp;
                }

                item.Set(destinationRectangle.X,
                        destinationRectangle.Y,
                        -origin.X,
                        -origin.Y,
                        destinationRectangle.Z,
                        destinationRectangle.W,
                        (float)Math.Sin(rotation),
                        (float)Math.Cos(rotation),
                        color,
                        _texCoordTL,
                        _texCoordBR, transform);

                if (_sortMode == SpriteSortMode.Immediate)
                    _batcher.DrawBatch(_sortMode);
            }

```

in SpritebatchItem.cs

```
        public void Set(float x, float y, float dx, float dy, float w, float h, float sin, float cos, Color color, Vector2 texCoordTL, Vector2 texCoordBR, Matrix transform)
        {
            // TODO, Should we be just assigning the Depth Value to Z?
            // According to http://blogs.msdn.com/b/shawnhar/archive/2011/01/12/spritebatch-billboards-in-a-3d-world.aspx
            // We do.
            vertexTL.Position.X = x + dx * cos - dy * sin;
            vertexTL.Position.Y = y + dx * sin + dy * cos;
            vertexTL.Position.Z = Depth;
            vertexTL.Position = Vector3.Transform(vertexTL.Position, transform);
            vertexTL.Color = color;
            vertexTL.TextureCoordinate.X = texCoordTL.X;
            vertexTL.TextureCoordinate.Y = texCoordTL.Y;

            vertexTR.Position.X = x + (dx + w) * cos - dy * sin;
            vertexTR.Position.Y = y + (dx + w) * sin + dy * cos;
            vertexTR.Position.Z = Depth;
            vertexTR.Position = Vector3.Transform(vertexTR.Position, transform);
            vertexTR.Color = color;
            vertexTR.TextureCoordinate.X = texCoordBR.X;
            vertexTR.TextureCoordinate.Y = texCoordTL.Y;

            vertexBL.Position.X = x + dx * cos - (dy + h) * sin;
            vertexBL.Position.Y = y + dx * sin + (dy + h) * cos;
            vertexBL.Position.Z = Depth;
            vertexBL.Position = Vector3.Transform(vertexBL.Position, transform);
            vertexBL.Color = color;
            vertexBL.TextureCoordinate.X = texCoordTL.X;
            vertexBL.TextureCoordinate.Y = texCoordBR.Y;

            vertexBR.Position.X = x + (dx + w) * cos - (dy + h) * sin;
            vertexBR.Position.Y = y + (dx + w) * sin + (dy + h) * cos;
            vertexBR.Position.Z = Depth;
            vertexBR.Position = Vector3.Transform(vertexBR.Position, transform);
            vertexBR.Color = color;
            vertexBR.TextureCoordinate.X = texCoordBR.X;
            vertexBR.TextureCoordinate.Y = texCoordBR.Y;
        }

```

I don't know about the performance, are these calculations costly?

What do you guys think?

I think the rotation isn't working properly, going to investigate further

# Answer
> 2 votes
SpriteBatch.draw(...) probably isn't doing what you think it is. It doesn't immediately draw. This is supposed to be the case - especially since you are using deferred mode.

Making draw calls can be expensive so you want to do as few of them as possible. So for sprites, which are 4 vertices, you want to "batch" them. The XNA solution is the "SpriteBatch".

SpriteBatch.draw(...) actually just builds an internal buffer of sprites to draw later, with texture information and transformed vertices, and then, at an appropriate time, it draws them. This appropriate time is determined by the modes set in spriteBatch.begin().

Deferred mode basically tells sprite batch not to draw anything until the very end so the order can be sorted for all sprites. So I believe it won't actually make any real draw calls until SpriteBatch.end().

This means that your world matrix is actually only set before the last SpriteBatch.draw() call and thus is always the matrix you construct for the last sprite.

Regardless, the sprite batch will use the position information supplied in the SpriteBatch.draw() call to create a rectangle in the buffer which is already transformed correctly into world coordinates. This means the vertex is already in world coordinates when it reaches the vertex shader and shouldn't be transformed again with the world matrix. You actually just want to apply your view\*projection matrix transformation in the vertex shader (and view is probably Matrix.Identity so can be ignored).

Please try;

```
shader.Parameters["World"].SetValue(Matrix.Identity);

```

By the sounds of things, your original method was working without the shader, so you should maybe just return to that, unless you actually need a pixel shader for some reason.

---
Tags: xna, shaders, monogame, spritebatch, vertex
---


title: LibGDX strange camera behaviour

text:
# Question
Title: LibGDX strange camera behaviour
I'm currently doing my final assessment for my study Game Development. I'm currently facing a real weird (maybe explainable) result from my camera.

I just set up my scene with alot of tiles and a character. When I set up the camera's position and direction, I experience something strange. The camera is tilted somewhat, and I can't explain why that is happening.

This is looking pretty good. Except for when I move the camera, the tilting is becoming worse.

* Is this behaviour I should expect from the camera?
* I made sure the camera is never rotated, is there any possibility the models are slightly rotated?
* I use LibGDX with exported FBX files from 3Ds Max, converted to LibGDX's format "G3DB", are there any known issues with that?

# Answer
**Camera**

The problem might be the up vector of the Camera. This up vector is what determines the roll of the camera. As the camera rolls then what it considers up will change with it.

You can set it directly to (0,1,0) using "mCamera.up.set(Vector3.Y)". This should fix the tilt.

You are setting the camera lookAt using "mCamera.lookAt(...)" which may be changing the up vector. You might want to try mCamera.normalizeUp() right after to see if that sorts anything.

**Model**

Double check the way you create the world matrix for the model and make sure you are not applying any rotations. If you are remove them. If it looks right with all of them removed then you know the problem is there.
> 5 votes

---
Tags: opengl, java, libgdx, camera
---


# Question
Title: How can I measure the velocity of a Farseer body?
I want to know how fast my body(a circle) is moving. How can I do that? How can I measure the velocity of a body?

In addition, I want to limit the velocity of a body. For example, I want that a body couldn't move with more than 50 km/h. How can I do that?

# Answer
> 2 votes
The speed of a body should be available via the LinearVelocity property.

A simple version of the answer is this:

```
var km = 1000f;
var hour = 3600f;
if(myBody.LinearVelocity.Length() > (50*km/hour))
{
    var direction = Vector2.Normalize(myBody.LinearVelocity);
    myBody.LinearVelocity = direction*(50*km/hour);
}

```

A more advanced but efficient way of doing it is this:

```
float maxSpeed = 50 / 3.6f; //50km/h -> m/s
float maxSpeedSquared = maxSpeed * maxSpeed;
float len2 = myBody.LinearVelocity.LengthSquared();
if(len2 > maxSpeedSquared)
{
    float len = (float)Math.Sqrt(len2);
    myBody.LinearVelocity = myBody.LinearVelocity * (1f/len) * maxSpeed;
}

```

It is more efficient because it do less multiplications and do only one Sqrt, and only when necessary. Usually you shouldn't bother about this, but this second way was added in case someone that stumbles into the question need to apply this to a more critical section.

---
Tags: xna, c#, farseer-physics-engine
---


title: How do I find a point on a line?

text:
# Question
Title: How do I find a point on a line?
I have two points (A, B) and the length of d. How can I find point C?

# Answer
Compute a vector `V` from `A` to `B`, and normalize it.

```
V = (B - A) / |B - A|

```

Since the vector is normalized, it will have a length of one, and it will indicate the direction of `B` relative to `A`. If you then scale the vector by `d` you will have the displacement from `A` to `C`

```
V' = d * V

```

which you can simply add to `A` to yield `C`:

```
C = V' + A

```
> 26 votes

# Answer
In case your d is a ratio instead of a length, e.g 0.5 puts it on equal distance from A and B, you can do the following and avoid a normalization:

```
C = A * (1 - ratio) + B * ratio

```
> 1 votes

---
Tags: mathematics, vector
---


title: Shape collision checking

text:
# Question
Title: Shape collision checking
I want to check in an shape, wether an point is in it or not. The shape is descriped with one Array of float vectors. The vectors are added in clock direction. The first I can check very easy, the second too, but the third is more difficult. How I can calculate this ? How this category is in math named, so that I can google ?

# Answer
This is called point in polygon. You can find different kinds of algorithms depending on whether your polygons are convex or concave.
> 1 votes

---
Tags: collision-detection
---


# Question
Title: Collision Scenario, Detection and Response
I have `AABB`, `BSphere`, a `Polygon Soup`, a `Triangle`, a `Plane`, a `Point` and a `Ray` objects with a collision test that returns '**bool**' if two objects collide or not.

How can I use the above objects to implement an appropriate collision detection for my game?

It's a simple game where a player walks inside a rooms, and does the 'escape the room' scenario.

My levels is much like old Resident Evil with those 'static' cameras inside the rooms, some items inside containers, a monster and few items laying around so you can pick them up if you want.

* A room is just a 'Sector' - it would be a 'Polygon Soup'
* A player and all Entities are AABB

My question is:

1. Is my collision tests that returns (true/false) is enough for appropriate collision detection or do I need extra info like the normal vectors?
2. Should I go writing this myself or stop playing around and use some open/free physics engine for a simple game like this?

# Answer
What you have accomplished is collision detection. You will need more information to resolve this collision. Usually you need:

* Penetration depth
* Collision normal
* Point(s) of collision

There are many resolution schemes, some simple and some very difficult. I usually recommend people trying out "impulse resolution" first. I wrote some articles on this topic.

The equation used to create an appropriate impulse is:

`j` is the scale of the impulse vector used to press two rigid bodies apart. `e` is the coefficient of restitution, a value from 0 to 1 representing bounciness. `V^A` and `V^B` are the velocities of rigid bodies A and B involved in the collision. `n` is the collision normal retrieved by the collision detection routine.

Please see the article I linked for many more implementation details I've left out here for brevity's sake.

You should stop and use a pre-made engine if you don't want to spend a lot of time making your own. If you like to learn and have the time, then you should learn to do this on your own.
> 2 votes

# Answer
> What else do i need to have in my collision Classes to perform collision response between all collision geometries? Do I need more info other than \>return if two objects collide (true/false) ?

A collision test that only returns true/false is usually called an overlap test. This is due to the fact that this is the only info that it returns.

For more appropriate collision response you might also need:

* The intersection point between the two objects.
* and also the penetration depth.
* you might need the normal vector of the surface.
* And sometimes the time (t) of the collision especially when you are implementing dynamic collision detection, but I doubt that you need it for your simple game.

But determining what info you need depends on how you are going to implement your collision response and what info you need. For example if your collision response calculates the torque then you should calculate the intersection point to be able to determine where the force is going to be applied.

* τ is the torque vector and τ is the magnitude of the torque.
* r is the displacement vector (a vector from the point from which !\[torque is measured to the point where force is applied).
* F is the force vector.

The reason I am showing the torque equation is that you need the collision point in order to calculate it (calculate r). You usually need the normal vector, which can looked up once you the know face that collided, so you can implement any kind of reflection or knocking back. But this is also not strictly needed since you can get a way with a simpler approximation.

> Should I go writing this myself or stop playing around and use some open/free physics engine for a simple game like this?

You can do it either way, but in the end it's a personal preference especially if you are learning and not delivering a commercial product.

A physics engine will give you more options for your collision response. But it doesn't mean that it will be "better". A collision response might be as simple as knocking back an object.

Integrating a physics engine also means more work than what you might need. So you are the only one that can determine what is needed, and it's especially hard for us to judge without an appropriate context.
> 2 votes

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


# Question
Title: Why divide by w makes the pixel shader look better?
I'm writing a shader in HLSL (Direct3D11 with SharpDX) and after some computations I was trying to make a test and print the depth z of a specific point in my pixel shader, like this:

```
myZ = input.p.z;
color = float4(myZ, myZ, myZ, 1.0f);
return color;

```

The result of this is the one I expect, but though I see what I expect (pixels darker as I get closer and lighter when they are far away), I have to move the camera quite close to the model to start seeing some darker pixels. If not, everything is white.

The thing is, if I do this instead, as I read in some forum:

```
myZ = input.p.z/input.p.w;
color = float4(myZ, myZ, myZ, 1.0f);
return color;

```

then I can see everything from the beginning much finer. The problem is I don't understand the logic behind this. Why would this help and why would it make sense.

Any help appreciated, thanks!

# Answer
The depth buffer is not linear. More bits of precision are available closer to the camera and so changes in depth close up end up being very tiny changes that don't convert to color differences you could actually see. Dividing by `w` linearizes the depth buffer such that small changes in depth result in visible changes in color.

http://www.gamedev.net/topic/539378-why-non-linear-depth-buffer/ http://mynameismjp.wordpress.com/2010/03/22/attack-of-the-depth-buffer/ http://www.mvps.org/directx/articles/linear\_z/linearz.htm
> 5 votes

---
Tags: shaders, directx11, sharpdx
---


# Question
Title: How do I create a color picker with variable hue and saturation?
I am trying to create a Color Picker similar to that of MS Paint.

Unfortunately, I can't figure out the algorithm for saturation.

This is what my current algorithm creates. Anytime I try to perform a saturated effect going down on the Y axis, it just makes everything after the first line completely red or black.

```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SFML;
using SFML.Graphics;
using SFML.Window;

namespace Source
{
class ColorWheel : IGameObject
{
    Image image = new Image(255*6,355);
    Color color = new Color(255,0,0);
    int brightness = 255;
    public Sprite sprite = new Sprite();

    public ColorWheel()
    {
        for (int y = 0; y < 255; y++)
        {
            for (int x = 0; x < 255 * 6; x++)
            {
                //Red 255 - Green 0-254
                if (color.R == brightness && color.G < brightness && color.B == 0)
                {
                    color.G += 1;

                    //color.R -= (byte)y;
                    //color.G += (byte)y;
                    //color.B += (byte)y;
                }
                //Green 255 - Red 255-0
                else if (color.R > 0 && color.G == brightness && color.B == 0)
                {
                    color.R -= 1;

                    //color.R -= (byte)y;
                    //color.G -= (byte)y;
                    //color.B += (byte)y;
                }
                //Green 255 - Blue 0-255
                else if (color.R == 0 && color.G == brightness && color.B < brightness)
                {
                    color.B += 1;

                    //color.R += (byte)y;
                    //color.G -= (byte)y;
                    //color.B += (byte)y;
                }
                //Blue 255 - Green 255-0
                else if (color.R == 0 && color.G > 0 && color.B == brightness)
                {
                    color.G -= 1;

                    //color.R += (byte)y;
                    //color.G -= (byte)y;
                    //color.B -= (byte)y;
                }
                //Blue 255 - Red 0-255
                else if (color.R < brightness && color.G == 0 && color.B == brightness)
                {
                    color.R += 1;

                    //color.R += (byte)y;
                    //color.G += (byte)y;
                    //color.B -= (byte)y;
                }
                //Red 255 - Blue 255-0
                else if (color.R == brightness && color.G == 0 && color.B > 0)
                {
                    color.B -= 1;

                    //color.R -= (byte)y;
                    //color.G += (byte)y;
                    //color.B -= (byte)y;
                }

                image.SetPixel((uint)x, (uint)y, color);
            }

                //brightness--;
        }

        Texture texture = new Texture(image);
        sprite.Texture = texture;
    }

    public void Update(double dt)
    {
    }

    public void Render(RenderWindow rWindow)
    {
        rWindow.Draw(sprite);
    }

}

```

}

# Answer
> 3 votes
If not going with HSL or a similar method, and staying with RGB, it helps to understand the relationship.

As white is \[255, 255, 255\], lowering the G and B values similarly will result in a very light red color (shades of pink). When the color becomes \[255, 0, 0\], the color is a stark, bright, primary red. As that red value is lowered, the red becomes darker until black at 0, 0, 0. Lowering the red before the G and B values reach 0 (i.e. r \> g == b) creates a desaturated "greyish" red.

This same process is true for any hue. Green is simply the G value being higher than the R and B values, yellow is the combination of R and G values overwhelming the B.

\[255, 255, x\] where x is 0 to 255 is a bright to light yellow. \[x, x, 0\] where x is 0 to 255 is a dark to bright yellow. \[x, x, z\], where x is variable and z is less than x results in varying brightness of a desaturated yellow.

Thus, hue is essentially the proportion of the two highest of the three RGB values. Saturation is essentially the proportion of that hue to the third value. If the hue is high, the color is bright. If the third color is also high, the color is light. If the hue is low, the color is darker. If the third color is high and the hue is low, the color is a murkier or greyer color.

# Answer
> 6 votes
If you want to have a colour-picker with *Hue* on one axis and *Saturation* on the other, it might be good to think of your colours in terms of the *Hue-Saturation-Value* (HSV) or Hue-Saturation-Lightness (HSL) colourspaces instead of Red-Green-Blue (RGB).

There's no magic going on here -- HSL and HSV are just another another way of thinking about colour.

---

**Example:**

In HSV, `(0, 0.5, 0.5)` is `0` along the Hue axis (which is pure red), `0.5` along the Saturation (which is a somewhat greyish colour) and `0.5` along the Value (which gives a medium shade). The result is quite an unsaturated red.

Here's what that looks like in GIMP's colour picker:

The values for H, S and V on the right there are a little confusing because GIMP treats Hue as between 0 and 360 and Saturation and Value between 0 and 100, but the principle is the same.

You can also see on the right what RGB values that would translate to. Apparently, such a red is `(128, 64, 64)` in RGB.

A different Hue might look like this:

Note how the S and V sliders are in the same place. I've only changed the Hue value. You could very easily write some code that steps through the different Hues, as well as through different Saturations to create a 2-dimensional grid of HSL values that represent the colour picker you want.

Note that the RGB sliders have changed a lot! GIMP automatically calculates what the RGB equivalent of an HSV colour is.

---

**Conversion**

You'll probably want to convert your HSV colours to RGB equivalents so your renderer can handle them.

This conversion is not too complicated. In fact, there are some really good answers on StackOverflow, along with code you can easily adapt to your language.

However, if you're curious, the general idea behind the conversion (and perhaps a nice analogy to make the idea of a "colourspace" clearer) is this: The same way you can think of RGB as a cube with R, G and B each along one axis of it...

Thanks, Wikipedia!

... you can think of the HSV colourspace as a cylinder:

Wikipedia again.

The conversion essentially stretches and bends that cylinder to match with the cube.

# Answer
> 2 votes
Here is the answer. Please use this as you see fit, freely, as I am glad to post a working class that will create a Color Picker for anyone using C# and SFML.net- but also providing the logic for anyone who wishes to create a Color Picker for C# only.

The solution is simple: http://richnewman.wordpress.com/about/code-listings-and-diagrams/hslcolor-class/

1) Add the HSLColor class from the above link.

```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using SFML;
using SFML.Graphics;
using SFML.Window;

namespace Source
{
class ColorWheel : IGameObject
{
    Image image = new Image(240, 220);
    HSLColor hslColor = new HSLColor();
    System.Drawing.Color systemColor = new System.Drawing.Color();
    Color pixelcolor = new Color();
    public Sprite sprite = new Sprite();

    public ColorWheel()
    {
        pixelcolor = Color.Red;
        hslColor.SetRGB(pixelcolor.R, pixelcolor.G, pixelcolor.B);

        for (int y = 0; y < 220; y++)
        {
            //pixelcolor = Color.Red;
            //hslColor.SetRGB(pixelcolor.R, pixelcolor.G, pixelcolor.B);
            hslColor.Hue = 0;
                for (int x = 0; x < 240; x++)
                {
                    systemColor = hslColor;
                    pixelcolor.R = systemColor.R;
                    pixelcolor.G = systemColor.G;
                    pixelcolor.B = systemColor.B;
                    image.SetPixel((uint)x, (uint)y, pixelcolor);
                    hslColor.Hue += 1;
                }
                hslColor.Saturation -= (y * 0.01);

        }

        Texture texture = new Texture(image);
        sprite.Texture = texture;
    }

    public void Update(double dt)
    {
    }

    public void Render(RenderWindow rWindow)
    {
        rWindow.Draw(sprite);
    }

}
}

```

And here is the resulting image, which you are freely allowed to use for anything you want. You do not even need to use the ColorWheel class, but simply use this image and get the pixel at the mouse position to dye your gameobjects as you see fit.

To change the brightness (which would be on the slider) use hslColor.Luminosity in the equation, and it would probably be best to use the ColorWheel class instead of the image, unless you feel confident adjusting the image brightness based on a double integer attached to the slider. A good Color Picker GUI which includes both the image, mouse cursor, and slider with just a few lines of code would be TGUI. Obviously you would want to replace the default image with the ColorWheel class if you were using it, or the ColorWheel image I just provided.

All free to be used by anyone as they see fit.

---
Tags: c#, sfml, color
---


# Question
Title: How do I generate paylines and pay dots for a slot game?
I'm working on a HTML5 slot game and am completely stuck on the pay lines and the dots that produce the lines from 1 end to the other.

What's the logic behind generating a random number of dots (9-30) and then paylines properly? Paylines shouldn't overlap each other. Similarly paydots shouldn't overlap and position themselves properly. On a small mobile screen 30 dots should just fit fine.

Then, how can I go about matching combinations from reels against the paylines?

# Answer
> 2 votes
For game shops dedicated to making slot machines, the manner in which a game pays out is determined by a staff of mathematicians dedicated to statistics. In my experience (a single shop of about 25 people) the mathematicians were roughly equal in number to the programmers and artists.

Of course, this is true for a company making games headed to real casinos, where payouts need to be known with extreme accuracy. They need that information both for selling their games to gambling businesses and for complying with local law. *Your game* probably does not need such meticulous work.

---
Tags: architecture, game-mechanics, html5, browser-based-games
---


# Question
Title: How can I increase the tileset limit in RPG Maker VX?
In RPG Maker VX, the default setup allows you to have five tilesets for the map layout. Is there a way I can increase this limit?

I know it's possible to make "fake" tiles by using events overlaid on the real tiles to show different images. However, this is a huge hassle to setup, and isn't a very clean way of creating the game; I'm hoping there is another way.

# Answer
> 2 votes
It looks like RPG Maker VX is overly restrictive with this when compared to other versions, and there is no out-of-the-box way to do it. However, there are at least community-made scripts, such as SwapXT (download), that allow you to work around the limitation.

---
Tags: rpg, rpg-maker-vx, tilesets
---


# Question
Title: Help with "Cannot find ContentTypeReader BB.HeightMapInfoReader, BB, Version=1.0.0.0, Culture=neutral." needed
I have this irritating problem in XNA that I have spent my Saturday with:

> Cannot find ContentTypeReader BB.HeightMapInfoReader, BB, Version=1.0.0.0, Culture=neutral.

It throws me that when I do (within the game assembly's Renderer.cs class):

```
this.terrain = this.game.Content.Load<Model>("heightmap");

```

There is a heightmap.bmp and I don't think there's anything wrong with it, because I used it in a previous version which I switched to this new better system.

So, I have a `GeneratedGeometryPipeline` assembly that has these classes: `HeightMapInfoContent`, `HeightMapInfoWriter`, `TerrainProcessor`. The `GeneratedGeometryPipeline` assembly does not reference any other assemblies under the solution.

Then I have the game assembly that neither references any other solution assemblies and has these classes: `HeightMapInfo`, `HeightMapInfoReader`.

All game assembly classes are under namespace `BB` and the `GeneratedGeometryPipeline` classes are under the namespace `GeneratedGeometryPipeline`.

I do not understand why it does not find it. Here's some code from the `GeneratedGeometryPipeline.HeightMapInfoWriter`:

```
 /// <summary>
    /// A TypeWriter for HeightMapInfo, which tells the content pipeline how to save the
    /// data in HeightMapInfo. This class should match HeightMapInfoReader: whatever the
    /// writer writes, the reader should read.
    /// </summary>
    [ContentTypeWriter]
    public class HeightMapInfoWriter : ContentTypeWriter<HeightMapInfoContent>
    {
        protected override void Write(ContentWriter output, HeightMapInfoContent value)
        {
            output.Write(value.TerrainScale);

            output.Write(value.Height.GetLength(0));
            output.Write(value.Height.GetLength(1));
            foreach (float height in value.Height)
            {
                output.Write(height);
            }
            foreach (Vector3 normal in value.Normals)
            {
                output.Write(normal);
            }
        }

        /// <summary>
        /// Tells the content pipeline what CLR type the
        /// data will be loaded into at runtime.
        /// </summary>
        public override string GetRuntimeType(TargetPlatform targetPlatform)
        {
            return "BB.HeightMapInfo, BB, Version=1.0.0.0, Culture=neutral";
        }

        /// <summary>
        /// Tells the content pipeline what worker type
        /// will be used to load the data.
        /// </summary>
        public override string GetRuntimeReader(TargetPlatform targetPlatform)
        {
            return "BB.HeightMapInfoReader, BB, Version=1.0.0.0, Culture=neutral";
        }
    }

```

Can someone help me out?

# Answer
> 1 votes
The problem was that the assembly name contained a space.

# Answer
> 0 votes
Another technique is to have a 'data' project which defines the reader and type which is returned by that reader, and a 'pipeline' project which defines the writer and the content version of that type.

Then you can do the following:

```
    public override string GetRuntimeType(TargetPlatform targetPlatform)
    {
        return typeof(HeightMapInfo).AssemblyQualifiedName;
    }

    public override string GetRuntimeReader(TargetPlatform targetPlatform)
    {
        return typeof(HeightMapInfoReader).AssemblyQualifiedName;
    }

```

... since the writer (defined in the pipeline assembly) can reference the data project which defines the runtime type and reader type.

---
Tags: xna, c#, terrain-rendering, pipeline
---


# Question
Title: Movieclip to spawn in in a set perimeter
I like to make a movieclip randomly spawn in a set area. But theres a little more to it, usually you'd have something like the X pos set to something like 250 (say the centre) and the Y pos set to be `math.random` but it won't work for how I'd like it.

I'm making a First Person Shooter and want the `Enemy movieclip` to spawn off stage but from the Top, Bottom, Left and Right of the stage as shown in the quick annotated image below.

Is this possible to be done? If so how could I achive this?

Thanks for your help.

# Answer
> 1 votes
You can still trivially use `math.random`. You just need to perform a little algebra.

If you have a 20 unit area on either side of some arbitrarily-sized area, you have 40 units in total split into two parts. You can take a random number number and scale it to those 40 units and then place it appropriately whether that number is `<20` or `>=20`.

For instance:

```
spawnRandom():
 // get X in the 40 units of space legal to spawn in
 X = math.random() * 40

 // offset X to account for the middle area it can't be in
 if X < 20:
  X = -stage.width/2 - X
 else
  X = stage.width/2 + (X - 20)

 // same for Y

 return position(X, Y)

```

You now have a position that is linearly distributed across the legal areas while ignoring the center rectangle.

---
Tags: 2d, actionscript-3, random, spawning
---


# Question
Title: How to make child transforms honor parent origin
I'm working on a 2D transform system that has the following requirements:

* Transforms can have children
* Transforms have anchor points/origins that offset them
* Children should honor the parent's origin for translation
* Rotations occur relative to the local origin (i.e. objects rotate around their origin rather than the parent's)

As an example of what I'm looking for: \- You add red square in the middle of the screen and center its origin \- You add a white square, center its origin, scale it down slightly and make it a child of the red square \- Every frame you rotate both squares by a fixed amount

What you should see is a red square rotating around its center in the middle of the screen and a white square rotating inside the red square.

The way that I'm doing it now is something like this:

```
c = child;
p = child.parent;
c.local_transform.translate(c.translation);
c.local_transform.rotate(c.rotation);
c.local_transform.scale(c.scale);
c.local_transform.translate(c.origin.inverse());
c.local_transform.translate(p.origin);

c.world_transform = c.local_transform * p.world_transform;

```

This doesn't fully work however. The red square appears in the center and rotates around its origin but the white square seems to rotate both around its origin AND the world origin (i.e. the top left corner of the window).

What am I missing?

# Answer
Typically, you make a combined transformation matrix (CTM), which is the product of all parent transformations and the current node's transformation. This applies parent transformations to the children. Each node typically has a single transformation matrix, but your code appears to have two per node (`local_transform` and `world_transform`), so I'm not sure what language/framework you're using.

The pseudocode code looks something like this:

```
void Node::render(Matrix ctm) {
    ctm = ctm * this.transform; //apply this node's transform to the CTM
    foreach(Node child in this.children){
        child.render(ctm);
    }
}

```

Each node multiplies it's own transformation matrix into the CTM, and passes the CTM to it's children.
> 1 votes

---
Tags: matrix, transformation, scene-graph
---


# Question
Title: How do I create a web player for a game engine written in C++?
This web player is for the Unreal Development Kit, and works very well without a browser plugin. I'm wondering how it is built.

How do I create a web player for a game engine written in C++?

# Answer
Emscripten can be used to port C++ applications to javascript. It was able to succesfully make the Unreal 3 engine run in a web browser.

It works best in browsers which support asm.js, an optimization-friendly subset of the Javascript language which can reach performance comparable to native code.
> 5 votes

# Answer
pepper.js allows you to write C++ code and then deploy directly as:

* Machine code via PNaCl for higher performance, currently only supported by Chrome.
* Javascript via Emscripten for maximum reach.

From the project page:

> pepper.js is a JavaScript library that enables the compilation of native Pepper applications into JavaScript using Emscripten. This allows the simultaneous deployment of native code on the web both as a Portable Native Client (PNaCl) executable and as JavaScript. Native Pepper applications can now be run in Chrome, Firefox, Internet Explorer, Safari, and more.

*Disclosure: I work on the Chrome team.*
> 4 votes

---
Tags: c++, browser-based-games, web
---


# Question
Title: How can I efficiently render a very large model?
I have a *huge* model I want to draw in my XNA application; due to its size I am experiencing a tremendous loss of performance.

The model has about 50,000,000 edges and has a size on disk of 205 MB in the `.x` format. Yes, the model has to be this big.

Is there a way to transfer the model directly to my GPU in order to let the GPU do the drawing like when transferring a `VertexBuffer`? When I try to fill a vertex buffer with the object I am getting an `OutOfMemoryException`.

# Answer
The out-of-memory exception likely occurs because the vertex buffer must be backed by system memory in order to handle device loss in the underlying D3D9 implementation of XNA (it's probably in the `D3DPOOL_MANAGED` pool).

Transferring the data to the GPU and filling a vertex buffer with the data are the same thing (a vertex buffer is the only place in XNA's API you can store this data).

You're going to have to chunk the model file up into multiple vertex buffers when you load the data off the disk. The best way to do this is probably *not* to the naive thing and chunk it up sequentially, but rather to partition the model using some kind of spatial partitioning scheme (octree, bsp, what have you) so that you can completely avoid issuing draw calls for chunks of the model that are outside the view frustum.

This approach will:

* Alleviate (but not solve) your system memory issues by requiring smaller allocations to hold the system-backed resources (even though the total memory usage will be the same or larger).
* Improve your rendering performance by allowing you to make only the needed draw calls for only the needed parts of the model, based on frustum culling techniques. If you aren't clear on what frustum culling is, that might be a good topic to research or ask a new question about.
> 1 votes

---
Tags: xna, directx, models, xna3.1
---


# Question
Title: What does "GL_CLAMP_TO_EDGE should be used in NPOT textures" mean?
I have two sRGB PNG images I am using for textures. One is 64x64, and works fine. The other is 64x47, and when I attempt to use it I get an error:

```
reason: 'GL_CLAMP_TO_EDGE should be used in NPOT textures'

```

What does this mean, and how do I address it?

# Answer
> 2 votes
It means that where you call `glTexParameteri` with `GL_TEXTURE_WRAP_S` or `GL_TEXTURE_WRAP_T`, you are specifying a value *other than* `GL_CLAMP_TO_EDGE` (such as `GL_REPEAT`), which is not supported for textures with dimensions that are not powers of two (64 is a power of two, but 47 is not, thus your second texture is a "NPOT" or "non-power-of-two" texture).

To fix this, either pass `GL_CLAMP_TO_EDGE` for that texture or alter the source texture's dimensions to be powers of two. This is usually done most easily by simply expanding the offending dimension up to the next available power of two.

---
Tags: opengl
---


# Question
Title: How can I improve the performance of texture switching without resorting to atlasing?
I'd like to use texture images that are not a sprite sheet or other form of texture atlas, mainly because I'll be consistently adding and swapping textures while I figure out the direction my game takes.

In Java, I'm using slick2d's `TextureLoader` to load a texture, and then I bind it with an unique id. However, when not using a spritesheet I have many more images to bind, which causes a potential performance problem. I've noticed that calling `glBindTexture` for every block I'm drawing is bad, it drops my FPS to 1.

I'm already rendering blocks with `glCallList` so I've found a middle-ground. I bind a single block texture and then render all blocks of that type in the chunk, and repeat for each unique block type. However, that's still less than preferable.

Is there a better way to efficiently use multiple textures without an atlas or sprite sheet?

# Answer
> 1 votes
It seems very odd that you see the performance of your game fall to 1 FPS. It's likely there is more to that than just the texture binding, but that is not really relevant to the issue, because it is still true that binding a new texture for every draw call is expensive and will have *some* negative impact on performance, which you are looking to alleviate.

Unfortunately, the technique of using texture atlases is designed to help combat *exactly* the problem you are seeing (a sprite sheet is just a specialized texture atlas where every sub-image is stored in a cell in a regular grid).

State changes on the GPU are slow and should be down as infrequently as possible. This includes changes of texture and shader state. In your case, you're changing the texture every time you render a new object, which is just about the worst-case scenario you can have without being intentional about degrading performance.

Minimizing state changes improves performance, and your middle ground solution (to draw everything using the same texture at once) does eliminate a lot of state changes. It's a valid approach, and one that is commonly used.

Sprite sheets or texture atlases allow you to *further* minimize your texture state changes, and are consequently superior if you can use them.

So unfortunately, the answer to your question is you *can't* improve this scenario(\*) beyond what you have described as your middle ground solution or using the sprite sheets you explicitly don't want to use.

(\*) I am speaking only of the texture-state-change-related performance, obviously. I still suspect that something *else* is wrong in your code, but that's neither here nor there.

---
Tags: opengl, sprites, slick
---


title: How can I create a mirror with Unity?

text:
# Question
Title: How can I create a mirror with Unity?
Can anyone explain how I can create a mirror effect like the one in this YouTube video using Unity Pro?

I know that I need to use render textures to do it, but I am not sure how.

# Answer
> 2 votes
Those are done with Render textures . Simply create a new `Render Texture` to your project and a camera to your scene. Then assign that camera's `Target Texture` to the `Render Texture` you created.

---
Tags: unity, graphics
---


# Question
Title: How can I render a single object that uses multiple textures?
I'm looking for a technique to render an object with multiple texture sources. One texture is static, the other is generated dynamically (it's a render target). For example, say I was rendering a TV. The frame of the TV is a static texture and the image comes from a render-to-texture pass.

It doesn't sound difficult but I've been unable to find a decent approach. Some of my ideas are:

1. Instead of rendering to a unique texture I render to a part of the other texture (so the part with the TV screen is overwritten, the frame remains). This doesn't work if I want to combine multiple textures (two TVs with different frames, same show playing)
2. Create a two-part object: render the TV frame as one-object then render the image as another. This would require leaving a hole in the one model, or putting the other model slightly on top. Is there a drawback to this approach?

Is there another approach that works well?

# Answer
> 3 votes
There are three ways to do this that I know of.

The first is to use three source textures. One is the standard diffuse texture, one is the video texture, and the third is a mask texture. You sample all three but then use the mask to decide which of the first two textures you actually use to generate your output color. You generally need two sets of texture coordinates.

The second is to do the same as the above but to use a vertex attribute as your mask. This lets you mark which vertices are part of the TV display and which aren't.

The third is to use two models like your second suggestion. This requires less model data (you don't need two sets of texture coordinates, don't need a mask, and need less duplicated vertices). However, while the data is smaller, it requires one extra draw call.

Which is faster is going to depend on a lot of details we can't predict, but in general I'd go with the third option. Especially since in the case of a TV you likely want a lot more differences between the screen and the TV itself given that TV screen give off light and that you might want some extra shader effects on the TV screen.

---
Tags: opengl, webgl
---


# Question
Title: How do you change a Body's origin in Farseer?
In Farseer 3.3.1 for XNA, how do I change the origin of a Body? For example, when I create a Circle Body, instead of it rotating around its center, I want it to rotate around another specified point.

# Answer
> 4 votes
I guess the revoulte joint is what you want. You can use it to pin the circle at a given position and the circle will rotate around that position.

# Answer
> 0 votes
The centroid is necessary for physics calculations. In other words that is not the origin you are trying to move but the center of mass. Unless I'm mistaken you're going to have to do a bit of trig or get fancy with matrices.

# Answer
> 0 votes
Just to give a late answer to the question, answering what the question literally asks (for anyone who comes across it by searching):

You don't so much change the origin of a `Body` as you **place your `Fixture`s relative to the body's origin** (ie: in "Local" body space).

For example, assuming:

```
float radius = 1f;
float density = 1f;

```

A centred circle would be this:

```
Body body = BodyFactory.CreateCircle(world, radius, density);

```

But a circle offset from the body origin by its radius would be:

```
Body b = BodyFactory.CreateBody(world);
FixtureFactory.AttachCircle(radius, density, body, new Vector2(0, radius));

```

(Other shapes have similar offset parameters available. Raw polygons vertices are specified relative to the body's origin.)

---

Now, even if you do this, the centre of mass will still be at centre of the circle. **If you want to move the centre of mass**, you can do this:

```
body.LocalCenter = new Vector2(0, 0);

```

That is in the case where you've moved the circle centre away from the body's origin (as above), but you want to keep the centre of mass at the origin.

If you don't move the circle fixture, and just want to move the centre of mass, then do something like this:

```
body.LocalCenter = new Vector2(0, radius);

```

It is important to note, however, that Farseer normally recalculates the centre of mass! It does so if any of these things happen:

* You attach or remove a fixture from the `Body`
* You set `BodyType`
* You set `IsStatic`
* You set `FixedRotation`
* You call `ResetMassData()`

So if you do any of those things, you must set `LocalCenter` *afterwards*.

---
Tags: xna, farseer-physics-engine
---


title: Duration in ScaleModifier andengine

text:
# Question
Title: Duration in ScaleModifier andengine
I want to scale an image before screen resume in AndEngine so I have applied the following code to my sprite:

```
ScaleModifier scaleDrag1 = new ScaleModifier(1, 1, 0.7f);

drag1.registerEntityModifier(scaleDrag1);

```

But my issue is that the scaled image is shown when the screen resumes because of the 1 duration. It makes my sprite scale after the screen resume so the scaling is visible to the user, I tried setting the duration to 0 but then that sprite is not shown.

Can anyone tell me what should I do to scale image before resume in AndEngine.

# Answer
> 0 votes
Casting is required in that case , i resolved with code below :

```
ScaleModifier scaleDrag1 = new ScaleModifier((float) 0.01, 1, 0.7f);

```

# Answer
> -1 votes
You can scale the sprite by using drag1.setScale(0.7f).

---
Tags: andengine
---


# Question
Title: Linking error at tessellation shaders in GLSL
I'm testing the triangle tessellation from the link http://prideout.net/blog/?p=48#shaders . All the shader are compiled correctly, but when I try to link the program using the command:

```
glLinkProgram(programID);

```

I got the following error:

```
Tessellation control info
(0): error C6029: No input primitive type
----------------------------------------
Tessellation evaluation info
(0): error c7005: No tessellation primitive mode specified
-----------------------------------------------------------
Geometry info
(0): error C6022: No input primitive type
(0): error C6029: No ouput primitive type
----------------------------------------
Not valid

```

It's so strange I declare output for TC Shader using command:

```
layout(vertices = 3) out;

```

And input layout for TE shader using command:

```
layout(triangles, equal_spacing, cw) in;

```

Why I still got this error? I hope to see you answer about it.

I put my shaders in below:

Vertex shader:

```
#version 410 core

in vec4 Position;
out vec3 vPosition;

void main()
{
    vPosition = Position.xyz;
}

```

TC shader:

```
#version 410 core

layout(vertices = 3) out;
in vec3 vPosition[];
out vec3 tcPosition[];

#define ID gl_InvocationID

void main()
{
    float TessLevelInner = 3;
    float TessLevelOuter = 2;
    tcPosition[ID] = vPosition[ID];
    if (ID == 0) {
        gl_TessLevelInner[0] = TessLevelInner;
        gl_TessLevelOuter[0] = TessLevelOuter;
        gl_TessLevelOuter[1] = TessLevelOuter;
        gl_TessLevelOuter[2] = TessLevelOuter;
    }
}

```

TE Shader:

```
#version 410 core
//TessEval

layout(triangles, equal_spacing, cw) in;
in vec3 tcPosition[];
out vec3 tePosition;
out vec3 tePatchDistance;
uniform mat4 Projection;
uniform mat4 Modelview;

void main()
{
    vec3 p0 = gl_TessCoord.x * tcPosition[0];
    vec3 p1 = gl_TessCoord.y * tcPosition[1];
    vec3 p2 = gl_TessCoord.z * tcPosition[2];
    tePatchDistance = gl_TessCoord;
    tePosition = normalize(p0 + p1 + p2);
    gl_Position = Projection * Modelview * vec4(tePosition, 1);
}

```

Geometry shader:

```
#version 410 core
//geometry shader
layout(triangles) in;
layout(triangle_strip, max_vertices = 3) out;
in vec3 tePosition[3];
in vec3 tePatchDistance[3];
out vec3 gFacetNormal;
out vec3 gPatchDistance;
out vec3 gTriDistance;
uniform mat4 Modelview;
uniform mat3 NormalMatrix;

void main()
{
    vec3 A = tePosition[2] - tePosition[0];
    vec3 B = tePosition[1] - tePosition[0];
    gFacetNormal = NormalMatrix * normalize(cross(A, B));

    gPatchDistance = tePatchDistance[0];
    gTriDistance = vec3(1, 0, 0);
    gl_Position = gl_in[0].gl_Position; EmitVertex();

    gPatchDistance = tePatchDistance[1];
    gTriDistance = vec3(0, 1, 0);
    gl_Position = gl_in[1].gl_Position; EmitVertex();

    gPatchDistance = tePatchDistance[2];
    gTriDistance = vec3(0, 0, 1);
    gl_Position = gl_in[2].gl_Position; EmitVertex();

    EndPrimitive();
}

```

Fragment Shader:

```
#version 410 core
//fragment shader
out vec4 FragColor;
in vec3 gFacetNormal;
in vec3 gTriDistance;
in vec3 gPatchDistance;
in float gPrimitive;
uniform vec3 LightPosition;

float amplify(float d, float scale, float offset)
{
    d = scale * d + offset;
    d = clamp(d, 0, 1);
    d = 1 - exp2(-2*d*d);
    return d;
}

void main()
{
    vec3 AmbientMaterial = vec3(0.04f, 0.04f, 0.04f);
    vec3 DiffuseMaterial = vec3(0, 0.75, 0.75);
vec3 LightPosition = vec3(0.25, 0.25, 1);
    vec3 N = normalize(gFacetNormal);
    vec3 L = LightPosition;
    float df = abs(dot(N, L));
    vec3 color = AmbientMaterial + df * DiffuseMaterial;

    float d1 = min(min(gTriDistance.x, gTriDistance.y), gTriDistance.z);
    float d2 = min(min(gPatchDistance.x, gPatchDistance.y), gPatchDistance.z);
    color = amplify(d1, 40, -0.5) * amplify(d2, 60, -0.5) * color;

    FragColor = vec4(color, 1.0);
}

```

# Answer
> 0 votes
I solved the problem. The error is in the code of loading shader.

```
glShaderSource(pShader[st], 1, (const GLchar**)sProgram, NULL);

```

I changed 1 to size of the char\* array sProgram

---
Tags: opengl, glsl, c, tessellation
---


# Question
Title: Anisotropic filtering on gbuffer textures for shading pass?
I have a OpenGL 3.3 deferred shader. For my geometry pass I have diffuse textures and/or normal map textures from my models and here I use max anisotropic filtering. But in my shading pass, where the three input textures are position, normal and diffuse textures (the output from geometry pass) - does it even make sense to use anisotropic filtering on these for the shading stage? It wouldn't look any better no?

# Answer
Anisotropic filtering is used to diminish aliasing and blur effects of textures that are rendered in planes with angles not oblique (multiple of 90 degrees) in relation with the camera. In the shading pass you will be rendering the light volumes only, which don't have any texture attached to their geometry. Indeed, the only textures you will use are the full-screen position, normal and diffuse textures, which will be oblique in relation with the camera by definition. Thus, anisotropic filtering will not be necessary for this pass.
> 4 votes

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


# Question
Title: How to implement special weapon and armor effects (ex: vampiric, holy, damage shield, thorns)?
I'm working on the inventory system for my game, and am interested in **how do I implement additional weapon and armor properties that are not just damage or armor?**

If all I have is damage and armor, the equation is simple: damage = weapon damage - armor;

But I'm looking for a more interesting user experience - namely items that have 2-3 properties that modify various game mechanics.

For example, I can use a bunch of flags and write a **big if/else statement** in my attack method and check for all these at appropriate points:

if (weapon is vampiric) { heal attacker for x }

if(weapon is holy) { check defender type, add extra damage }

if(armor absorbs first x damage) { reduce damage to defender by x }

Another way that I thought might be better is the **decorator design pattern** \- progressively wrapping the output of one weapon creation into another :

```
public class Main {

    public static final void main(String[] args) {
    Weapon w = new MeleeWeapon();

        w = new Holy(w);
        w = new Vampiric;
        w = new Enchanted(w,1);

        Damage damage = w.damage();

    }

}

```

It seems to me that decorator would allow me to write more flexible code and add more types later, but I'm not sure if it will just move the if/else statements into the weapons special property method.

# Answer
> 7 votes
The words themselves helps you : a weapon is just a carrier for effects. Some are instantaneous (damage), other are longer (poison).

The scope of the effects is also quite large : some effects affect the weapon owner, some others the opponent. And most of the time, you need to take all of them into account (nevertheless, you can easily fasten the search to know which ones are applicable).

```
def Attack( attacker, receiver) :
    status = receiver.status() # original LP, MP, etc
    impacts = [] # the list of impacts (poison, speed, etc) to be applied
                 # impact need to be sortable by category, so we can
                 # enhance them or cancel them
    for effect in attacker.effects:
        # accumulation the instantaneous impacts
         if effect.instantaneous:
             impacts.append( effects.apply(status, impacts) )
        # some effects last a while, an active instance will be carried by the receiver
        # those instance have a tick method and will stop after a moment and be removed
         elif effect.lasting:
             receiver.effects.append( effect.get_copy() )
         else:
             continue
    # we need to apply receiver effects as some may cancel some impacts of the attacker
    for effect in receiver.effects:
         if effect.on_impacts: # effects that can modify impacts
             impacts.append( effects.apply(status, impacts) )
         elif effect.on_effects: # effects than can modify lasting effects
             receiver.effects = effect.filter(receiver.effects, status )
         else:
             continue

    # lastly, we apply all the impacts.
    status.change( impacts )
    receiver.status = status

```

For example, the computation of a warrior carrying a sword with poison protection stung by a giant scorpion would something like :

```
Warrior.effects = [ PoisonProtection(.30), #effect.on_impact,
                    CannotBeStun(), #effect.on_effects,
                    FireDamage(+15%), #effect.instantaneous
                    SensibleToIce(+15%), #effect.instantaneous ]

Scorpion.effects = [ SimpleDamage(min=10, max=30),
                     PoisonDamage( 30),
                     LastingPoisonDamage( dmg_per_sec=3, length=15) ]

```

This needs to be extented to manage area effects but you get the general idea.

# Answer
> 2 votes
`new`ing repeatedly and the jumps this will incur between memory locations where the original object and its various wrappers are located, will be more costly than the extensive conditionals you mention or the approach offered below. Also, I would hesitate at using the Decorator Pattern in this instance because there is no clear order in which decorators would apply, thus making code potentially confusing to debug; preferable to have all options listed linearly, but encapsulated individually.

What I would suggest would be function pointers, functors or the Strategy Pattern for languages that do not support first-class functions or where there is otherwise a strong desire to work to fixed interfaces.

In your weapon class, hold a series of references to your possible function pointers, functors or strategies representing the various possible effects, and call each (non-null) one at the time when you need to do weapon processing. You can hold these references either as members, or as entries in an array or dictionary (more dynamic and workable with a scripting engine, but also a little slower). Try to maintain an update phase where you are resolving *all* weapon effects, *not only damage*.

**P.S.** This is quite closely related to how we often build OO-based entity-component systems, though the distinction ought to be made here that we are not considering each of these to be a component of an entity, but rather to be a component of a weapon which is usually referenced by the weapon or hand component of an entity. That said, a weapon may itself be a type of entity.

**P.P.S.** Be careful applying traditional (read: business) software development design patterns when writing (real-time) games. Not all of them are nearly as applicable here as in the wider world, as game architecture necessitates a very different set of concerns.

---
Tags: architecture, game-mechanics, procedural-generation, inventory
---


# Question
Title: Why does XNA's ContentManager follow generic type parameters for serialization purposes?
I've finally gotten to the bottom of a problem and am wondering what my best recourse is. In short, the problem is that XNA's `ReflectiveReader` reflects into generic type parameters, even if no instance of that generic type is stored in the object being serialized.

An example best demonstrates this. Consider the following model classes:

```
namespace Model
{
    using System.Collections.Generic;
    using Microsoft.Xna.Framework.Graphics;

    public abstract class Entity
    {
    }

    public sealed class TestEntity : Entity
    {
        public Texture2D Texture
        {
            get;
            set;
        }
    }

    public abstract class EntityData
    {
    }

    public abstract class EntityData<TData, TEntity> : EntityData
        where TData : EntityData
        where TEntity : Entity
    {
    }

    public sealed class TestEntityData : EntityData<TestEntityData, TestEntity>
    {
    }

    public sealed class LevelData
    {
        public List<EntityData> Entities
        {
            get;
            set;
        }
    }
}

```

Now suppose I want to define an instance of LevelData inside an XML file to be later loaded with the `ContentManager` (*Test.xml*):

```
<?xml version="1.0" encoding="utf-8"?>
<XnaContent xmlns:Model="Model">
  <Asset Type="Model:LevelData">
    <Entities>
      <Item Type="Model:TestEntityData">
      </Item>
    </Entities>
  </Asset>
</XnaContent>

```

Now consider this simple load logic:

```
Content.Load<LevelData>("Test");
Content.Load<Texture2D>("Texture");

```

The first line succeeds, but the second throws an exception:

```
Microsoft.Xna.Framework.Content.ContentLoadException was unhandled
  Message=Error loading "Texture". ContentTypeReader Microsoft.Xna.Framework.Content.Texture2DReader, Microsoft.Xna.Framework.Graphics, Version=4.0.0.0, Culture=neutral, PublicKeyToken=842cf8be1de50553 conflicts with existing handler Microsoft.Xna.Framework.Content.ReflectiveReader`1[[Microsoft.Xna.Framework.Graphics.Texture2D, Microsoft.Xna.Framework.Graphics, Version=4.0.0.0, Culture=neutral, PublicKeyToken=842cf8be1de50553]], Microsoft.Xna.Framework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=842cf8be1de50553 for type Microsoft.Xna.Framework.Graphics.Texture2D.
  Source=Microsoft.Xna.Framework
  StackTrace:
       at Microsoft.Xna.Framework.Content.ContentTypeReaderManager.AddTypeReader(String readerTypeName, ContentReader contentReader, ContentTypeReader reader)
       at Microsoft.Xna.Framework.Content.ContentTypeReaderManager.GetTypeReader(String readerTypeName, ContentReader contentReader, List`1& newTypeReaders)
       at Microsoft.Xna.Framework.Content.ContentTypeReaderManager.ReadTypeManifest(Int32 typeCount, ContentReader contentReader)
       at Microsoft.Xna.Framework.Content.ContentReader.ReadHeader()
       at Microsoft.Xna.Framework.Content.ContentReader.ReadAsset[T]()
       at Microsoft.Xna.Framework.Content.ContentManager.ReadAsset[T](String assetName, Action`1 recordDisposableObject)
       at Microsoft.Xna.Framework.Content.ContentManager.Load[T](String assetName)
       at XnaContentManagerRepro.Game1.LoadContent() in D:\Temp\XnaContentManagerRepro\XnaContentManagerRepro\XnaContentManagerRepro\Game1.cs:line 53
       at Microsoft.Xna.Framework.Game.Initialize()
       at XnaContentManagerRepro.Game1.Initialize() in D:\Temp\XnaContentManagerRepro\XnaContentManagerRepro\XnaContentManagerRepro\Game1.cs:line 39
       at Microsoft.Xna.Framework.Game.RunGame(Boolean useBlockingRun)
       at Microsoft.Xna.Framework.Game.Run()
       at XnaContentManagerRepro.Program.Main(String[] args) in D:\Temp\XnaContentManagerRepro\XnaContentManagerRepro\XnaContentManagerRepro\Program.cs:line 15
  InnerException:

```

If I set a breakpoint on the line that loads the texture and then examine the `ContentTypeReaderManager.nameToReader` member, I see this:

As you can see, a `ReflectiveReader` is indeed being mapped for the `Texture2D` type. This stems from my `TestEntity` class (see the the entries above the one highlighted in the image above). But if you examine my model classes, nothing hanging off `LevelData` has an instance of `TestEntity` or even `Entity` in it!

If I change the `TestEntityData` class to this:

```
public sealed class TestEntityData : EntityData<TestEntityData, Entity>
{
}

```

The exception no longer occurs. That's because `TestEntity` is never considered, so neither is `Texture2D`. Thus, the `ReflectiveReader` is looking at - and following - the generic type parameters in my model classes! I can only assume this is a bug - it makes no sense at all to me why this would be necessary.

My model classes have these generic type parameters for a good reason - they make my model code much simpler. Am I stuck here? Is my only option to refactor my models to never have a generic type parameter of my entity types? I considered using `ContentSerializerIgnoreAttribute`, but that only works against properties and fields, which makes sense considering they're the only things that should influence serialization.

Anyone have any advice?

# Answer
While it's true that *in general*, serialization doesn't necessarily have to concern itself with the types of the objects in question and only record representations of their state... not all serialization implementations do that. Most of the built-in .NET serialization methods *do* record information about types participating in serialization. There are advantages to that choice (allowing for more robust validation) as well as disadvantages (larger serialized object size), but it's not *wrong* per se and you just have to live with it.

XNA's content pipeline, for your types, traverses the serializable property (and field) graph and creates readers for them. You can see this behavior if you examine the initialization for `ReflectiveReader<T>` (the `Initialize` method, not the constructor). It does this via reflection, *not* based on the actual data in the XML (again, this is verifiable by looking at the reflected code). So it doesn't matter if there is a reference to the texture in your data or not, if there's a `Texture2D` property in the type's property graph, it will try to create a reader for it as part of the initialization of the content pipeline.

You are not supposed to use direct references to `Texture2D` objects in your custom content. You may find this thread (or this one, to a lesser degree). The alleged solution to the issue is to use external references to `Texture2DContent` instead.
> 4 votes

---
Tags: xna, xna-content-pipeline, xml, serialization
---


# Question
Title: Does a 2D Vector or 2x2 Matrix play any role in 2D Transformations?
I'm having trouble trying to figure out if a vec2 or mat2 class are used at all in transformations for 2D rendering. Vec2, apart from representing UVs, AFAIK, is relatively pointless in regards to homogeneity.

What about 2x2 Matrix? I guess if we're hanging on to temp variables for shear, scale, and/or rotation it could make sense, but I'm feeling like I'll never use it.

It isn't much effort to implement, but I'd like to know if I'm missing something, or if Vec2 and Mat2 are largely useful for representing objects in 2D space.

I do know that a 3x2 or 2x3 matrix is a more data efficient\* way to store the data for affine transformations-- does vec2 have any utility in these sort of cases?

* Or is this even true? Do alignment optimizations negate this advantage? Or is it only true for the data that we transfer into OpenGL?

# Answer
> 4 votes
Of course they're useful.

A `vec2` is handy because you have absolutely no need to store the third component most of time. It's only needed when actually doing affine transformations. You can even have different `mul_point` and `mul_vector` operations with your `mat3x3` to avoid the need to even construct a `vec3` in a great many cases. In 3D, we typically use `vec3` everywhere on then occasionally use it to construct an appropriate `vec4` where necessary, which is fairly rare.

For matrices, the same applies. You have to deal with non-affine transformations all the time. There's no good reason to use a `mat3x3` where a `mat2x2` will work. Again, same in 3D, where there are plenty of places that don't bother with a full `mat4x4`. It's a bit more useful in 3D since rotations are considerably more complex and you end up wanting to work with matrices for them more often than you might in 2D, but you still end up using them. It's not always convenient or efficient to use a scalar rotation value in 2D given that it requires `sin`/`cos`/`tan` calls in places that a matrix would not. You'll likely find that you often take your scalar rotation and convert it to a 2x2 matrix for computation of rotations where there simply is no need for translation.

---
Tags: 2d, matrix, vector
---


# Question
Title: Flixel text causing memmory leak (FlxText) - AS3
I am calling kill() and destroy() on flxText when i dont need it anymore, how come its still using the memmory it let the game run for a while it went up to 1,5 gig of ram, then i commented it out the code where flxText is made and got this http://shrani.najdi.si/?3u/x6/1MkFPi08/fac.png (using only 170m-190m), so its obviously flixel text not cleaning up propperly , wat do ?

# Answer
So what i did to fix this is, i made 10 variabiles in advance and made the code check if there are any dead ones first, and then just revive the dead one. Recycling 10 objects forever fixed the leak
> 1 votes

# Answer
Hi Matthew and thank you for your question.

Since ActionsScript uses garbage collection there are only 2 reasons.

First you have references to these objects in your own objects or from a manager in fixel. In this case be aware to null your references. Maybe the tool mentioned here could be useful.

Second your garbage collection did not trigger automatically. In this case force it to clean up. Sometimes garbage collection can not or need many attempts to free all memory. This is caused by circular references. I.e. A references B and B references A and you null the reference to A.

So what to do. Check if you really null your references and that no reference is left from your side of code. If the problem continuous check if flixel tracks some references internally and lookup how to remove them. If the problem is not solved check for objects that reference each other. Normally this should not cause this problem because garbage collection checks for circular references.

I hope I could help you. Have further questions?, please tell us. Michael
> 2 votes

# Answer
I've found it helps to set all references for objects to `null` on `destroy`.
> 1 votes

---
Tags: actionscript-3, flixel
---


# Question
Title: How to change the start position of my 2D game
I am trying to create a game where you have to move a ball on a platform. At the start of the game, the ball is dropped on the platform and then you can move it around. This is al working, no problems here.

To keep the overview, the ball is centered in the middle of a div. When you move the ball you actually move the platform (giving the illusion the ball moves). This function should stay as it is. The platform is build in javascript as follows:

```
var levels = [
    [
        [1,1,1,1,1],
        [1,1,1,1,1],
        [1,2,1,1,1]
    ]
];

```

Where 1 = green tile, 0 = no tile and 2 is a yellow tile.

When loading the level it will generate the first tile (in this case the first 1) in the center of the div, then the next one and the next, etc. Al good so far, but if I change the first 1 tile to a 0 tile (= no tile), it will generate the platform, but since the platform is created in the middle of the div and since 0 is no tile, no tile will be generated and the ball will fall endlessly.

This is no good, I want to have different platforms and not always start with a 1 tile at this position. So I figured to make a "start tile". This is the yellow 2 tile. The idea is that this tile is the tile that always should be shown in the middle of the div at the start of a game, so that the ball always drops on the yellow tile. Therefore the whole platform should be moved at game start/load in order to center the yellow tile.

And this is my problem. How to do this?

I hope my problem is clear. I've also made a fiddle (click the 1 to start the game), so you can try things out

Many thanks

ps so in short:

* Ball always drops in middle (must stay this way)
* Yellow "start tile" should be moved/centered in the div, so the ball drops on it at game start

pps: The yellow tile can have a different position, it depends on the platform design

# Answer
> 3 votes
In `loadLevel`, when you're doing `new tile` (and passing in `x` and `y`) to create a tile at a particular position, you could *offset that position* by the negative of the yellow tile's position.

The yellow tile's position then becomes `(0,0)`, which is where the ball starts. All other tiles are moved over by the same amount.

If you only ever have only one yellow tile in a level, it might make sense to store its position explicitly in the level data structure:

```
var levels = [
    {
        yellowTilePosition : [1, 2],
        tiles : [ [1,1,1,1,1],
                  [1,1,1,1,1],
                  [1,1,1,1,1] ]
    }
];

```

Alternatively, you could iterate through your level data to figure out which tile is yellow.

---

If you're up for something more drastic, I'd really recommend Processing.js or Pixi.js over jQuery for writing web-based games. They have ways of controlling rendering (with `scale`, `translate` and the like) with which you can properly implement a camera, independently of where the player is positioned.

---
Tags: javascript, jquery
---


title: Python Performance vs Game Maker

text:
# Question
Title: Python Performance vs Game Maker
I was originally thinking of creating a game with Python and SFML. I understand Python is slow compared to C++, but how is it compared to Game Maker?

The main reason I ask is I recently played a Game Maker game (The Iconoclasts) which ran at a fairly bad frame-rate on my computer (GMA 950). I'm worried I would have similar performance issues with Python/SFML.

# Answer
**To say "Python is slow compared to C++" is a generalization that ignores a lot of real-world practicalities** and is usually a poor kind of judgement to rely on. What you really want to do is look at what a particular language or technology can bring to the table in terms of your needs and, similarly, evaluate any potential downfalls of that technology against your needs.

**If you are having to ask this kind of a question, there is a very good chance that the limiting factor in terms of performance of any game you make will be *you*** and not the technology choices themselves. Consequently the optimal choice is the one that empowers you the most, in other words, the technology or language you already know best.

As for the poor performance of the Game Maker game you played, that could be attributable to a number of factors, some of which are specific to that game, such as specific poor code that may have been written via Game Maker's tools or scripting languages. It isn't necessarily a fault of Game Maker itself.
> 50 votes

# Answer
If I had to guess the biggest reason that the game you played runs so slow is not that it's a game maker game, but that game maker markets itself specifically to non-programmers. Because you have non programmers making games it's highly likely that the game in question uses some very inefficient algorithms that cause it to run slow.

As in most cases, the speed of the language will only lightly affect the overall performance of the program. When people say "omg this language is 50% slower than this other language" and the speed is still stupid fast in both cases then you'll find little to no discernible difference to the end user.
> 4 votes

# Answer
Game Maker is a good beginner's tool. But I recommend moving upward to bigger and better programs if you have any previous programming experience. I used GameMaker for a college 2D game development course, it has a nice, easy to use drag and drop system. The problem, however, is that the program's drag and drop doesn't use the most efficient (or logical) commands. Plus the drag and drop doesn't support a lot of the advanced commands that the program is capable of executing, so the programmer has to get creative with it, or learn to code. If you learn to use GameMaker code, however, then you would be able to get around that with relative ease.

But, it can be hard to learn a code for one single program with the busy schedules we all have, which is most likely why you experienced the slow performance.

But as Kort Pleco previously stated, most language speeds are not noticably different.. It all depends on how the code is written and executed. A lot of redundancies can make it considerably slower, which is normally due to a lack of experience in coding.
> 3 votes

# Answer
For the game I am working on, I use a diamond-square algorithm to randomly create terrain upon starting a new game. To decide between using python with pygame for the project or GameMaker, I implemented the terrain generator in both. Pygame performed slightly faster, but the difference was negligible. Ultimately I chose GameMaker as I can work much faster in it.
> 2 votes

# Answer
The accepted answer is dead on but I just wanted to add my 2 cents as a GM user for nearly 8 years.

GM did have many issues with optimizations so there is some legitimate concern. There are a group of deprecated methods \*_variable\_exists? that used to exist in Gamemaker pre-studio. Because of this convenience method it was leveraged in almost every imaginable library and extension that was written for GM. Turns out these methods were horribly expensive and were causing major issue when running large scale games.

So there are many cases where GM can be really bad but with proper knowledge and careful use it is no less legitimate than any other method (unity2d,pygame,etc.). Just make games and have fun.
> 1 votes

---
Tags: performance, python, game-maker, sfml
---


# Question
Title: How can I set the world matrix from an array of floats in D3D9?
I have objects that hold their own transform matrix (calculated every frame by the physics system) held in a linear array of floats as follows:

```
[m0, m1,  m2,  m3]
[m4, m5,  m6,  m7]
[m8, m9, m10, m11]

```

How can I assign this matrix to D3D's world matrix for use in rendering the objects?

# Answer
> 1 votes
If you are using the effect interface, you'll need to obtain a `D3DXHANDLE` to your world matrix variable (for example, by calling `GetParameterBySemantic` on the effect.

You can then either convert your matrix to a `D3DXMATRIX` and use the matrix-setting call or leave the value in its raw form and call the raw value setter. Note that to do the latter you'll need to extend your array anyway, to include the missing elements, otherwise they may be unspecified values.

If you're not using the effect framework, convert your matrix to a `D3DMATRIX` use the `SetTransform` method on your device using `D3DTS_WORLD` as the matrix type.

---
Tags: c++, directx, directx9
---


# Question
Title: How do I dispose of OpenGL resources cleanly on Android?
I am creating a framework for OpenGL ES 2.0 for Android. How can I cleanly dispose of my OpenGL resources when my Android app is done?

I check for `isFinished()` in the `onPause()` event and then dispose of the resources but it calls the OpenGL functions from the main UI thread so it gives me an error (`0x501`).

When I try to call `isFinished()` inside my `onDraw()` in my `GLSurfaceView.Renderer` class, it is never called when I quit my app.

Anyone got any ideas?

# Answer
> 5 votes
As has been noted, if you are using `GLSurfaceView`, you don't *need* to handle the cleanup as the resources will be released when the context is lost.

---
Tags: android, opengl-es2
---


# Question
Title: Where is the Shader Designer in Visual Studio?
I have Visual Studio 2012 Ultimate and I've been trying to access the Shader Designer. I searched through MSDN's text and Channel9's videos, but they keep failing to mention how to access it.

Can someone let me know where it is?

# Answer
> 1 votes
Much like any of the other designers in Visual Studio, you actually have to have a file of the appropriate type in your solution, and then the designer will launch every time you double-click on the file (or until you change the designer association for that file type).

For the shader designer, the file type is `.dgsl`. Simply add an existing `.dgsl` file or add a new one (the template should be under the "Graphics" sidebar heading in the Add New Item dialog), and open it and the designer will fill the main view.

More information can be found on MSDN here.

---
Tags: c++, 3d, directx, shaders
---


# Question
Title: How do you display non-cutout transparent 2D textures with a depth buffer? (OpenGL)
I've been able to get my 2D renderer to display transparent cutout textures by testing the alpha of a fragment and discarding if it is less than 1 (or any fraction really). The problem is I want to support using translucent textures.

The current way I sort my sprites is by what texture they use, so that I can minimize texture changes. The only way I can think of getting this to work properly is by scrapping that and only sorting by z-order. But I don't want to throw away the optimization I already did. Is there any way to do both?

Does only rendering in 2D simplify the problem at all?

I was hoping to support translucent sprites, but my font renderer makes translucent font textures, so I can't just only use cutouts.

EDIT: After doing some research, it seems there really is no easy way to do this. (depth peeling for a 2D renderer seems a little overkill) I'm going to compromise by having my renderer hold 2 different sets of sprites, cutouts and translucent. I can draw the cutouts first in whatever order I want, making full use of texture atlases. The translucent textures, however, will need to be in z-order, ignoring atlases.

If anyone can tell me a better way, I'm all ears.

# Answer
A solution to this problem is presented in 3D Graphics with XNA Game Studio 4.0 (The XNA and directX-ness of the book is not relevant to the solution.) Although the method is technically imperfect and presented as a solution for billboarding, it works when disabling the depth buffer and z-sorting is a not viable method.

The problem is described as requiring the depth buffer in order to avoid textures overlapping wrongly, but not wanting obscured polygons to be covered up by transparency:

The solution is to draw all these sprites twice, using distinct shaders settings for each pass.

1. With depth buffer, draw only the *opaque* portions of the texture. Opaque can be defined by some arbitrary cutoff alpha, such as 0.5; Other pixels are not drawn.
2. Disable the depth buffer, and draw only the pixels below the cutoff.

In the first pass, the "solid" pixels will be drawn only when they are not obscured by another texture of higher depth. In the second, the translucent pixels will be drawn everywhere and blend together.

The imperfect part of this solution is that it is possible for mid-high alpha pixels to incorrectly obscure mid-low alpha pixels. This effect only happens when the sprites are drawn out of z-order, and only for pixels that are already alpha-blending. So the effect is minimal, and it should be possible to mitigate it by tweaking the alpha cutoff value.
> 1 votes

---
Tags: opengl, 2d, depth-buffer, transparency
---


# Question
Title: Why not use vectors to represent orientation?
From what I've read, people mostly use either quaternions or 3x3 matrices to represent 3D orientations, while plain vectors are used for angular velocity/momentum. Since we can use vectors to represent angular velocities, why can't we also use vectors to represent orientations? Are there any specific reasons or is it simply less convenient?

EDIT: Just to clarify, I mean using a 3D vector to represent a rotation around an arbitrary axis, with the magnitude being the rotation.

# Answer
> 9 votes
You are correct that a combined axis-angle representation like the one you describe has a stronger expressive power than many other systems because it can more conveniently store a *rotation speed*.

However, in practice, people actually use quaternions and 3×3 matrices to **manipulate** rotations a lot more than just **represent** them.

One typical operation is the combination of two rotations:

* with quaternions, this is usually 16 multiplications.
* with 3×3 matrices, this is usually 27 multiplications.
* with an axis-angle representation, you don’t have much choice but to convert the transformation to something else, often a quaternion, requiring at least 16 multiplications *plus* a square root and three divisions (for normalisation) and at least two sine and two cosine operations.

Another operation is the transformation of a vector by a rotation:

* with quaternions, this is usually 15 multiplications
* with 3×3 matrices, this is usually 9 multiplications
* with an axis-angle representation, this is at least 20 multiplications, a square root, three divisions, and two sine/cosine operations.

As you can see, the storage efficiency of an axis/angle representation is usually not worth it when you actually need to do things with the rotation. This article on Wikipedia has some more details.

# Answer
> 3 votes
> EDIT: Just to clarify, I mean using a 3D vector to represent a rotation around an arbitrary axis, with the magnitude being the rotation.

That is nearly what is saved in a quaternion only in a representation more useful to do calculations with it.

So basically, using a vector/angle pair directly:

* is not very convenient for the machine and the programmer to maintain. Eg concatenating one vector/angle with another is very expensive and is probably done by converting both into matrix form, multiplying and converting it back. Quaternions are pretty good for calculations and allow easy slerps when interpolating between two angles.
* is not very convenient when trying to figure out what a rotation looks like or when trying to enter one manually. Euler angles are the best for that.

Also storing the angle as magnitude is a bad idea because calculating the magnitude of a vector is VERY expensive. You should pay that extra float.

# Answer
> 2 votes
The reason is because you cannot use a vector on its own to apply a rotation to anything. With a quaternion or matrix you can use mathematically defined operations to rotate something else. This is useful for transforming frames of reference, and is what the entire 3D pipeline is built upon.

However if only a direction is required, then yes a vector can be used. Vectors only represent a direction and scale (scale of the direction).

# Answer
> -3 votes
Everybody is quite used to use vectors to represent orientations. notably this is classically the case in OpenGL light (directionals and spots) definitions, and camera directions. In DirectX also and in shaders also. we normally make sure the vector is normalized if the module is umimportant.

Many raytracers have a ray structure using `v p; v u;` which means a position and a unit vector representing the direction.

An alternative representation of direction is trhough the use of 2 angles, I use that systematically for first person shooter camera system. the mouse rotate lateraly and then vertically : 2 angles. This is enough and works very well.

---
Tags: 3d, matrix, vector, quaternion
---


title: .rrr subscript for float type

text:
# Question
Title: .rrr subscript for float type
I'm a little confused with this construction:

```
float sdcolor = MyColor.r; // MyColor has float4 type
float rcolor = sdcolor.rrr; // .ggg or .bbb isn't working

return float4(rcolor , rcolor , rcolor , 1);

```

Hence the question: how it's possible to subscript **anything** from a float type? What is the meaning of the `.rrr` subscript?

# Answer
> 2 votes
In HLSL, scalar values behave like 1-dimensional vectors. They have a `.x` component, or equivalently a `.r` component. Writing `.xxx` or `.rrr` is just a way of converting a scalar into a vector, in this case a `float3`, by duplicating that component.

```
float3 rgb;
float gray = dot(rgb, 0.333.xxx);         // You can do it on literal constants
rgb = lerp(rgb, gray.xxx, desaturation);  // And on scalars

```

It's usually not necessary to do this, as HLSL is pretty good about automatically converting scalars to vectors where needed. It's more of a stylistic choice; some shader authors do this to make the conversion explicit, even if it's not required by the language.

---
Tags: shaders, hlsl
---


title: Filling in gaps in a grid

text:
# Question
Title: Filling in gaps in a grid
I have a set of terrain sprites available to represent terrain:

* Flat
* North-South Straight Cliff (x 2 allowing for slope direction either way)
* West-East Straight Cliff (x 2 allowing for slope direction either way)
* Convex North West Cliff
* Convex North East Cliff
* Convex South East Cliff
* Convex South West Cliff
* Concave North West Cliff
* Concave North East Cliff
* Concave South East Cliff
* Concave South West Cliff

There source for my terrain is a height map that I am looking to represent with contours made up from above sprites. The cliff tiles would be placed on the below-threshold tiles that border the above-threshold ones. However when I split the height map by threshold I get terrain features that are impossible to represent with the tile set, for example:

```
    .....
... 1 1 1 ...
... 0 0 0 ...
... 1 1 1 ...
    .....

```

Where 1's represent tiles that are above the threshold and 0-tiles are below. My sprite set lacks the tile to represent either immediate neighbors (in this case North and South neighbors) being above threshold.

I am looking for a good approach to get rid of these cases. I have already tried just looping through all columns/rows looking for `1 0 1` combinations and changing the height map value to be above the threshold. In the end, I don't really mind the way the "gaps" are filled in, as long as the end result can be represented with my tile set.

Remember cases with diagonal gaps must be considered. For example:

```
    .....
... 0 0 1 ...
... 0 0 0 ...
... 1 0 0 ...
    .....

```

Also cannot be represented with my tiles set.

Finally, I'm also looking for a scalable solution to this problem. If I require to use and even more restrictive tile set that requires `1 (0 x n) 1` gaps to be filled in, as in the two above-threshold tiles can be `n` below-threshold tiles away from each other.

P.S. Apologies for my previous poorly worded question.

# Answer
> 2 votes
One solution is to start the terrain with one type only (e.g. all 0s or all 1s), and "paint" the other type on progressively, noting the ones that you need to change into "cliffs" or "transitions". If you ever need to make an impossible cliff, resolve it by either "promoting" the cliff or discarding the thing you're trying to paint and move on.

For example, you can start with 0s:

```
0 0 0
0 0 0
0 0 0

```

Start painting the 1s, noting the cliffs you have to make

```
(1)c 0      1(1)c      1 1(1)
 c c 0  ->  c c 0  ->  c c c  -> ...
 0 0 0      0 0 0      0 0 0

```

Then when you find that you need to make an impossible cliff (e.g. both north and south facing):

```
 1 1 1
 ? c c
(1)c 0

```

You can either promote the impossible cliff to a 1 (noting that this could set off a recursive process due to the promoted 1 creating new impossible cliffs):

```
 1 1 1
(1)c c
 1 c 0

```

or you can cancel placing that 1 and move on:

```
 1 1 1
 c c c
(0)0 0

```

# Answer
> 0 votes
In the case you are still looking for a postprocess you could do it like this : What is different here is that it looks for \[0\] values instead of \[1\]

```
//Enclose this in a for loop of all your values(or just use an index of the [0] at
//creation
if(yourValueAtIndex == 0) {
    int[] sourroundingsOneValues = selectSurroundingOnes(); // only the [1]
    int counter = 0;
    for(int i = 0; i < sourroundingsOneValues.length; i++) {
        //for each [1] value
        if (AllneigboursVal != 1) //direct neighbours is only 2 values in a conf of 8
            counter++

        if (counter >2) { // if i have at least 2 ones alone around my 0
            yourValueAtIndex = 1; // then i set my zero to 1 to connect them
            break;
        }
    }
}

```

This is a stripped down version of what you could implement

---
Tags: algorithm, grid
---


# Question
Title: How do I efficiently use 16 bit texture coordinates?
While loading a model I get a big array of 32 bit floating point texture coordinates. I just upload that to a single vertex buffer (along with other data, such as vertices, normals, etc.) and use it while rendering via

```
glVertexAttribPointer(texcoordindex,2,GL_FLOAT,GL_FALSE,texcoordstride,texcoordoffset);

```

I use this format for all types of meshes.

However, 16 bit and the ~65000 possible values are more than enough to represent textures that are mostly smaller than 4096 in size per dimension.

Now I'm wondering how to most effectively switch to some 16 bit based texture coordinate format, with respect to maximizing performance, i.e. minimizing the bandwidth and storage used, as well as minimizing ALU operations. Mainly I'm wondering:

* Should I use half floats or short integers?
* How do I convert the 32 bit floats I get when loading the model safely to the respective 16 bit format and upload it to the vertex buffer? In C++ or other languages, by rolling some custom type conversion via bit twiddling, or use standard procedures provided by the language or libraries such as GLM?
* How do I have to change the glVertexAttribPointer call to use that format, and does the input in the vertex shader stay a "vec2"?
* Is there maybe another option to save space here? For example, most textures are in the range of 256x256 to 1024x1024 range. 16 bits are way too much for that, but 8 bit are not enough for most textures. Are there some other strategies to save space here?

# Answer
GLSL does not give support to operate on 16 bit types, unless for compatibility with OpenGL ES, which does not change type functionality. However, you could use `uint packHalf2x16(vec2 v)` to encode two 16 bit as an uint. Done that you could use `vec2 unpackHalf2x16 (uint v)` to convert the values back from the encoded representation. You should use this function in the beginning of your shader to acquire the coordinates.
> 2 votes

# Answer
the easy option to integrate is to store 2 texture coordinates into one float using the int part and the decimal part:

```
//c++ code:
float       packCoord(const vec2 & tc)
{
    return floorf(tc.x * 1000.0f)+tc.y * 0.1;
}
//shader code
mediump vec2    UnpackCoord(highp float f)
{
    highp float fr = fract(f);
    return vec2( (f-fr)/1000.0, fr * 10.0);
}

```

This method stores the first value in the integer part (by multiplying by 1000) of the float, and the second value in the fractional part. Using the magic number `1000` allows you reliably to store values from `0` up to `9.999` and for texture coordinates this is more than enough. For a 2028 texture there is almost no precision loss using this method compared to the classic approach.

The computing cost if the unpacking is unnoticeable.
> 2 votes

# Answer
The most effective solution ended up being just handing half floats on the C++ side (by using the GLM "half" data type, which is a 16 bit sized float) and just changing the one parameter in glVertexAttribPointer to GL\_HALF\_FLOAT instead of GL\_FLOAT.

It's probably even more efficient to hand over normalized shorts or something like that, since they have "even spacing" in terms of precision, which is exactly what's perfect for texture coordinates, but I do not have time right now to try that out since the current solution is working perfectly, and I'm not even sure if half floats have holes big enough in their precision to miss a couple of texture coordinates in a (for example) 4096x4096 texture.

On another note, I did this for all data types where 16 bit floats are probably good enough (colors, normals, etc.) and it promptly upped the FPS I get on low end hardware by about 66% (in scenes that were heavy on vertices, and not so heavy on fragment operations), so it was definitely worth it.
> 0 votes

---
Tags: opengl, graphics, memory-efficiency
---