title: GPGPU Programming using HLSL and XNA

text:
# Question
Title: GPGPU Programming using HLSL and XNA
XNA Newbie question:

I'm trying to get the GPU to perform some calculations for me. I'm trying to figure out how to send some data to the GPU, get the GPU to process it, then get the result back. I've modified some code as below:

**HLSL:**

```
texture2D Input0;
sampler2D Input0Sampler = sampler_state
{
    Texture = <Input0>;
    MinFilter = Point;
    MagFilter = Point;
    MipFilter = Point;
    AddressU = Clamp;
    AddressV = Clamp;
};

texture2D Input1;
sampler2D Input1Sampler = sampler_state
{
    Texture = <Input1>;
    MinFilter = Point;
    MagFilter = Point;
    MipFilter = Point;
    AddressU = Clamp;
    AddressV = Clamp;
};

texture2D Input2;
sampler2D Input2Sampler = sampler_state
{
    Texture = <Input2>;
    MinFilter = Point;
    MagFilter = Point;
    MipFilter = Point;
    AddressU = Clamp;
    AddressV = Clamp;
};

texture2D Input3;
sampler2D Input3Sampler = sampler_state
{
    Texture = <Input3>;
    MinFilter = Point;
    MagFilter = Point;
    MipFilter = Point;
    AddressU = Clamp;
    AddressV = Clamp;
};

struct VertexShaderInput
{
    float4 Position : POSITION0;
    float2 TextureCoordinate : TEXCOORD0;
};

struct VertexShaderOutput
{
    float4 Position : POSITION0;
    float2 TextureCoordinate : TEXCOORD0;
};

struct PixelShaderOutput
{
    // TODO: Optionally add/remove output indices to match GPUProcessor.numOutputs
    float4 Index0 : COLOR0;
};

VertexShaderOutput VertexShaderFunction(VertexShaderInput vsInput)
{
    VertexShaderOutput output;

    output.Position = vsInput.Position;
    output.TextureCoordinate = vsInput.TextureCoordinate;

    return output;
}

PixelShaderOutput PixelShaderFunction(VertexShaderOutput psInput)
{
    PixelShaderOutput output;

    // TODO: Optionally add/remove samples to match GPUProcessor.numInputs
    //float4 input0 = tex2D(Input0Sampler, psInput.TextureCoordinate);
    //float4 input1 = tex2D(Input0Sampler, psInput.TextureCoordinate);
    //float4 input2 = tex2D(Input0Sampler, psInput.TextureCoordinate);
    //float4 input3 = tex2D(Input0Sampler, psInput.TextureCoordinate);

    // your calculations go here

    // TODO: Optionally add/remove outputs to match GPUProcessor.numOutputs
    output.Index0 = float4(100,200,13,24);//input0;

    return output;
}

technique Verlet
{
    pass Go
    {
        VertexShader = compile vs_1_1 VertexShaderFunction();
        PixelShader = compile ps_2_0 PixelShaderFunction();
    }
}

```

**C#**

```
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace HLSLTest
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;

        Texture2D tex;
        RenderTarget2D renOutput;

        Vector4[] cpuStore = new Vector4[1920 * 1080];
        Vector4[] gpuStore = new Vector4[1920 * 1080];

        Effect effect;

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here

            cpuStore = new Vector4[1920 * 1080];
            for (int i = 0; i < cpuStore.Length; i++)
            {
                cpuStore[i] = new Vector4(i);
                //gpuStore[i] = new Vector4(i);
            }

            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            tex = new Texture2D(GraphicsDevice, 1920, 1080, false, SurfaceFormat.Vector4);
            renOutput = new RenderTarget2D(GraphicsDevice, 1920, 1080, false, SurfaceFormat.Vector4, DepthFormat.Depth24Stencil8);

            tex.SetData<Vector4>(cpuStore);

            effect = Content.Load<Effect>("Shader");

            base.LoadContent();

            // TODO: use this.Content to load your game content here
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();

            // TODO: Add your update logic here

            base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            //GraphicsDevice.Clear(Color.CornflowerBlue);

            GraphicsDevice.SetRenderTarget(renOutput);
            //GraphicsDevice.Clear(Color.Black);
            effect.Techniques[0].Passes[0].Apply();
            //effect.Parameters["oldPositionTexture"].SetValue(Output);
            effect.CurrentTechnique.Passes[0].Apply();

            GraphicsDevice.SetRenderTarget(null);
            renOutput.GetData<Vector4>(gpuStore);
            //tex.GetData<Vector4>(gpuStore);

            base.Draw(gameTime);
        }
    }
}

```

The trouble is, when I put a breakpoint in the program and check the results stored in gpuStore, it contains a big list of vectors all the same value {X:0.2666667 Y:0.1333333 Z:0.5333334 W:1}. I was expecting it to return the value specified in my shader "float4(100,200,13,24)"

**EDIT:**

I've made some modifications thanks to Nathan's Advice. Here's what I have now:

**HLSL**

```
texture2D Input0;
sampler2D Input0Sampler = sampler_state
{
    Texture = <Input0>;
    MinFilter = Point;
    MagFilter = Point;
    MipFilter = Point;
    AddressU = Clamp;
    AddressV = Clamp;
};

texture2D Input1;
sampler2D Input1Sampler = sampler_state
{
    Texture = <Input1>;
    MinFilter = Point;
    MagFilter = Point;
    MipFilter = Point;
    AddressU = Clamp;
    AddressV = Clamp;
};

texture2D Input2;
sampler2D Input2Sampler = sampler_state
{
    Texture = <Input2>;
    MinFilter = Point;
    MagFilter = Point;
    MipFilter = Point;
    AddressU = Clamp;
    AddressV = Clamp;
};

texture2D Input3;
sampler2D Input3Sampler = sampler_state
{
    Texture = <Input3>;
    MinFilter = Point;
    MagFilter = Point;
    MipFilter = Point;
    AddressU = Clamp;
    AddressV = Clamp;
};

struct VertexShaderInput
{
    float4 Position : POSITION0;
    float2 TextureCoordinate : TEXCOORD0;
};

struct VertexShaderOutput
{
    float4 Position : POSITION0;
    float2 TextureCoordinate : TEXCOORD0;
};

struct PixelShaderOutput
{
    // TODO: Optionally add/remove output indices to match GPUProcessor.numOutputs
    float4 Index0 : COLOR0;
};

// input texture dimensions
static const float w = 1920;
static const float h = 1080;

static const float2 pixel = float2(1.0 / w, 1.0 / h);
static const float2 halfPixel = float2(pixel.x / 2, pixel.y / 2);

VertexShaderOutput VertexShaderFunction(VertexShaderInput vsInput)
{
    //VertexShaderOutput output;

    //output.Position = vsInput.Position;
    //output.TextureCoordinate = vsInput.TextureCoordinate;

    VertexShaderOutput output;
    vsInput.Position.x =  vsInput.Position.x - 2*halfPixel.x;
    vsInput.Position.y =  vsInput.Position.y + 2*halfPixel.y;
    output.Position = vsInput.Position;
    output.TextureCoordinate = vsInput.TextureCoordinate ;
    return output;

    //return output;
}

PixelShaderOutput PixelShaderFunction(VertexShaderOutput psInput)
{
    PixelShaderOutput output;
    // TODO: Optionally add/remove samples to match GPUProcessor.numInputs
    //float4 input0 = tex2D(Input0Sampler, psInput.TextureCoordinate);
    //float4 input1 = tex2D(Input0Sampler, psInput.TextureCoordinate);
    //float4 input2 = tex2D(Input0Sampler, psInput.TextureCoordinate);
    //float4 input3 = tex2D(Input0Sampler, psInput.TextureCoordinate);

    // your calculations go here

    // TODO: Optionally add/remove outputs to match GPUProcessor.numOutputs
    output.Index0 = float4(100,200,13,24);//input0;

    return output;
}

technique Verlet
{
    pass Go
    {
        VertexShader = compile vs_2_0 VertexShaderFunction();
        PixelShader = compile ps_2_0 PixelShaderFunction();
    }
}

```

**C#**

```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace HLSLTest
{
    internal sealed class QuadRender
    {
        private VertexPositionTexture[] verts;
        private GraphicsDevice myDevice;
        private short[] ib = null;

        ///
        /// Loads the quad.
        ///
        ///
        public QuadRender(GraphicsDevice device)
        {
            myDevice = device;
            verts = new VertexPositionTexture[]
            {
                new VertexPositionTexture
                (
                    new Vector3(0,0,0),
                    new Vector2(1,1)
                ),
                new VertexPositionTexture
                (
                    new Vector3(0,0,0),
                    new Vector2(0,1)
                ),
                new VertexPositionTexture
                (
                    new Vector3(0,0,0),
                    new Vector2(0,0)
                ),
                new VertexPositionTexture
                (
                    new Vector3(0,0,0),
                    new Vector2(1,0)
                )
            };

            ib = new short[] { 0, 1, 2, 2, 3, 0 };
        }

        ///
        /// Draws the fullscreen quad.
        ///
        ///
        public void RenderFullScreenQuad(Effect effect)
        {
            effect.CurrentTechnique.Passes[0].Apply();
            RenderQuad(Vector2.One * -1, Vector2.One);
        }

        public void RenderQuad(Vector2 v1, Vector2 v2)
        {

            verts[0].Position.X = v2.X;
            verts[0].Position.Y = v1.Y;

            verts[1].Position.X = v1.X;
            verts[1].Position.Y = v1.Y;

            verts[2].Position.X = v1.X;
            verts[2].Position.Y = v2.Y;

            verts[3].Position.X = v2.X;
            verts[3].Position.Y = v2.Y;

            myDevice.DrawUserIndexedPrimitives(PrimitiveType.TriangleList, verts, 0, 4, ib, 0, 2);
        }
    }
}

```

the main program

```
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace HLSLTest
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;

        Texture2D tex;
        RenderTarget2D renOutput;

        Vector4[] cpuStore = new Vector4[1920 * 1080];
        Vector4[] gpuStore = new Vector4[1920 * 1080];

        Effect effect;
        QuadRender quad;
        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here

            cpuStore = new Vector4[1920 * 1080];
            for (int i = 0; i < cpuStore.Length; i++)
            {
                cpuStore[i] = new Vector4(100*i);
                //gpuStore[i] = new Vector4(i);
            }

            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);
            quad = new QuadRender(GraphicsDevice);

            tex = new Texture2D(GraphicsDevice, 1920, 1080, false, SurfaceFormat.Vector4);
            renOutput = new RenderTarget2D(GraphicsDevice, 1920, 1080, false, SurfaceFormat.Vector4, DepthFormat.Depth24);

            tex.SetData<Vector4>(cpuStore);

            effect = Content.Load<Effect>("Shader");

            base.LoadContent();

            // TODO: use this.Content to load your game content here
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();

            // TODO: Add your update logic here

            base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            //GraphicsDevice.Clear(Color.CornflowerBlue);

            GraphicsDevice.SetRenderTarget(renOutput);
            //GraphicsDevice.Clear(Color.Black);
            effect.Parameters["Input0"].SetValue(cpuStore);
            quad.RenderFullScreenQuad(effect);
            for (int i = 0; i < effect.Techniques.Count; i++)
            {
                for (int j = 0; j < effect.Techniques[i].Passes.Count; j++)
                {
                    effect.Techniques[i].Passes[j].Apply();
                }
            }
            //effect.Techniques[0].Passes[0].Apply();
            //effect.Parameters["oldPositionTexture"].SetValue(Output);
            //effect.CurrentTechnique.Passes[0].Apply();

            GraphicsDevice.SetRenderTarget(null);
            renOutput.GetData<Vector4>(gpuStore);
            //tex.GetData<Vector4>(gpuStore);

            base.Draw(gameTime);
        }
    }
}

```

Now I'm getting a runtime error

> InvalidCastException was unhandled
>
> Specified cast is not valid.

This is due to the line effect.Parameters\["Input0"\].SetValue(cpuStore);

**EDIT**

I can fix this if I can create my own Texture2D from a byte array.

For example if I use Emgu to load an image:

```
Image<Bgr, Byte> video = cap.QueryFrame();
Texture2D t = new Texture2D(GraphicsDevice, video.Width, video.Height, false, SurfaceFormat.Color);
t.SetData<byte>(video.Bytes);

```

But I get

> ArgumentException was unhandled
>
> The size of the data passed in is too large or too small for this resource.

# Answer
OK

The final version

**C#**

```
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Emgu.Util;
using Emgu.CV;
using Emgu.CV.Structure;

namespace HLSLTest
{
    public delegate void Disp();

    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        Capture cap = new Capture("output.avi");
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;

        RenderTarget2D renOutput;

        Vector4[] gpuStore = new Vector4[1920 * 1080];

        Effect effect;
        QuadRender quad;
        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here

            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);
            quad = new QuadRender(GraphicsDevice);

            renOutput = new RenderTarget2D(GraphicsDevice, 1920, 1080, false, SurfaceFormat.Vector4, DepthFormat.Depth24);

            effect = Content.Load<Effect>("Shader");

            base.LoadContent();

            // TODO: use this.Content to load your game content here
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();

            // TODO: Add your update logic here

            base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            Image<Bgr, Byte> video = cap.QueryFrame();
            using (Image<Bgra, float> vid2 = video.Convert<Bgra, float>())
            {

                Texture2D t = new Texture2D(GraphicsDevice, video.Width, video.Height, false, SurfaceFormat.Vector4);
                t.SetData<byte>(vid2.Bytes);

                GraphicsDevice.SetRenderTarget(renOutput);
                effect.Parameters["Input0"].SetValue(t);
                quad.RenderFullScreenQuad(effect);
                for (int i = 0; i < effect.Techniques.Count; i++)
                {
                    for (int j = 0; j < effect.Techniques[i].Passes.Count; j++)
                    {
                        effect.Techniques[i].Passes[j].Apply();
                    }
                }

                GraphicsDevice.SetRenderTarget(null);
                renOutput.GetData<Vector4>(gpuStore);
            }

            base.Draw(gameTime);
        }
    }
}

```

---

```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace HLSLTest
{
    internal sealed class QuadRender
    {
        private VertexPositionTexture[] verts;
        private GraphicsDevice myDevice;
        private short[] ib = null;

        ///
        /// Loads the quad.
        ///
        ///
        public QuadRender(GraphicsDevice device)
        {
            myDevice = device;
            verts = new VertexPositionTexture[]
            {
                new VertexPositionTexture
                (
                    new Vector3(0,0,0),
                    new Vector2(1,1)
                ),
                new VertexPositionTexture
                (
                    new Vector3(0,0,0),
                    new Vector2(0,1)
                ),
                new VertexPositionTexture
                (
                    new Vector3(0,0,0),
                    new Vector2(0,0)
                ),
                new VertexPositionTexture
                (
                    new Vector3(0,0,0),
                    new Vector2(1,0)
                )
            };

            ib = new short[] { 0, 1, 2, 2, 3, 0 };
        }

        ///
        /// Draws the fullscreen quad.
        ///
        ///
        public void RenderFullScreenQuad(Effect effect)
        {
            effect.CurrentTechnique.Passes[0].Apply();
            RenderQuad(Vector2.One * -1, Vector2.One);
        }

        public void RenderQuad(Vector2 v1, Vector2 v2)
        {

            verts[0].Position.X = v2.X;
            verts[0].Position.Y = v1.Y;

            verts[1].Position.X = v1.X;
            verts[1].Position.Y = v1.Y;

            verts[2].Position.X = v1.X;
            verts[2].Position.Y = v2.Y;

            verts[3].Position.X = v2.X;
            verts[3].Position.Y = v2.Y;

            myDevice.DrawUserIndexedPrimitives(PrimitiveType.TriangleList, verts, 0, 4, ib, 0, 2);
        }
    }
}

```

**HLSL**

```
texture2D Input0;
sampler2D Input0Sampler = sampler_state
{
    Texture = <Input0>;
    MinFilter = Point;
    MagFilter = Point;
    MipFilter = Point;
    AddressU = Clamp;
    AddressV = Clamp;
};

texture2D Input1;
sampler2D Input1Sampler = sampler_state
{
    Texture = <Input1>;
    MinFilter = Point;
    MagFilter = Point;
    MipFilter = Point;
    AddressU = Clamp;
    AddressV = Clamp;
};

texture2D Input2;
sampler2D Input2Sampler = sampler_state
{
    Texture = <Input2>;
    MinFilter = Point;
    MagFilter = Point;
    MipFilter = Point;
    AddressU = Clamp;
    AddressV = Clamp;
};

texture2D Input3;
sampler2D Input3Sampler = sampler_state
{
    Texture = <Input3>;
    MinFilter = Point;
    MagFilter = Point;
    MipFilter = Point;
    AddressU = Clamp;
    AddressV = Clamp;
};

struct VertexShaderInput
{
    float4 Position : POSITION0;
    float2 TextureCoordinate : TEXCOORD0;
};

struct VertexShaderOutput
{
    float4 Position : POSITION0;
    float2 TextureCoordinate : TEXCOORD0;
};

struct PixelShaderOutput
{
    // TODO: Optionally add/remove output indices to match GPUProcessor.numOutputs
    float4 Index0 : COLOR0;
};

// input texture dimensions
static const float w = 1920;
static const float h = 1080;

static const float2 pixel = float2(1.0 / w, 1.0 / h);
static const float2 halfPixel = float2(pixel.x / 2, pixel.y / 2);

VertexShaderOutput VertexShaderFunction(VertexShaderInput vsInput)
{
    //VertexShaderOutput output;

    //output.Position = vsInput.Position;
    //output.TextureCoordinate = vsInput.TextureCoordinate;

    VertexShaderOutput output;
    vsInput.Position.x =  vsInput.Position.x - 2*halfPixel.x;
    vsInput.Position.y =  vsInput.Position.y + 2*halfPixel.y;
    output.Position = vsInput.Position;
    output.TextureCoordinate = vsInput.TextureCoordinate ;
    return output;

    //return output;
}

PixelShaderOutput PixelShaderFunction(VertexShaderOutput psInput)
{
    PixelShaderOutput output;
    // TODO: Optionally add/remove samples to match GPUProcessor.numInputs
    float4 input0 = tex2D(Input0Sampler, psInput.TextureCoordinate);
    //float4 input1 = tex2D(Input0Sampler, psInput.TextureCoordinate);
    //float4 input2 = tex2D(Input0Sampler, psInput.TextureCoordinate);
    //float4 input3 = tex2D(Input0Sampler, psInput.TextureCoordinate);

    // your calculations go here

    // TODO: Optionally add/remove outputs to match GPUProcessor.numOutputs
    output.Index0 = input0;//float4(100,200,13,24);//input0;

    return output;
}

technique Verlet
{
    pass Go
    {
        VertexShader = compile vs_2_0 VertexShaderFunction();
        PixelShader = compile ps_2_0 PixelShaderFunction();
    }
}

```
> 1 votes

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


# Question
Title: How can I move an enemy towards a player in AndEngine?
I want to move all enemy towards player but i can't do this.Is there any way by which i c an perform this task?

# Answer
I provide you information about how to code this thing. For example we have to create two classes player and enemy.

**Player** class contains code about player movement and firing of player towards enemy.

**Enemy** class contains code about enemy movement towards player and firing of enemy. For enemy movements towards player you have to use **MoveModifier** and provide data about player in this modifier.

This thing work perfect when player set at constant position but create problem when you move player object. To make this correct you have to unregister **MoveModifier** that was previously created and attach new **MoveModifier** with enemy.

Same thing goes repeated with all the enemies. Only once you have to prepare enemy class and your task is complete. I don't provide any code because of no need if you have further problem then add as comment.
> 1 votes

# Answer
Get the difference in positions on the x and y axis and use Pythagorean theorem to calculate the length

```
double dx = player.x - enemy.x;
double dy = player.y - enemy.y;
double length = Math.sqrt(dx * dx + dy * dy);

```

Normalize the differences in positions

```
double accelerationX = dx / length;
double accelerationY = dy / length;

```

Add the acceleration multiplied by a speed determined by you to move the enemy.

```
enemyPosition.x += (accelerationX * speed);
enemyPosition.y += (accelerationY * speed);

```

This is the linear algebra way. There is also a trigonometry way, however, this works fine.

Note: I am on my phone so this is all un tested and you will need to modify it to work with your code.

P.s - this code should be placed in an update method that gets called a certain amount of times per second
> 1 votes

# Answer
If you are using vectors:

```
Vector2 direction = player.position - enemy.position;
direction.normalize();
enemy.position += direction * enemy.speed;

```
> 1 votes

---
Tags: android, andengine
---


title: How can I morph between 2D sprites?

text:
# Question
Title: How can I morph between 2D sprites?
A friend and I are writing a topdown RPG called NecroMonster. In the game when you defeat an enemy you can take its shape (basically morph into it) and we don't know how to make this look right.

How can I create a morph animation between several 2D sprite sets that are relatively simple and will look the part?

# Answer
If its a 2D RPG then you are surprisingly more flexible than its 3D counterpart. If you are working with just simple sprites then you are only limited by your desire and skill to animate it.

There won't be any right answer here as this is more a graphical design choice than a technical question or limitation - due to that I would recommend making this a wiki entry for "ideas for morphing" or similar.

My idea would be to play on your games title and theme: **Necro**-Monster.

Seeing as "necro" signifies the dead and corpses you could have the character sink into the floor or crouch into a black, death like mass (giving you a set starting point for all charater transformations to keep things simple). After a short pause they "uncrouch" into the monster *shape*. The monster form would then shake off the black-death mass material or it would simply fade or slide off depending on your desired graphical complexity.
> 5 votes

---
Tags: animation
---


title: Incorrect GPU skinning

text:
# Question
Title: Incorrect GPU skinning
I'm having some problems with implementing skinning and skeletal animation. It seems that the skeleton and the mesh are loaded correctly, but the mesh gets funky when the bone transformations are applied. What could be the problem?

---

**Images depicting the scenario**

Here's my original model made in Blender:

And here's the bone structure:

This is what the skeleton looks like in the bind pose when I load it, each joint is depicted as a red sphere. I seems to be correct:

And this is with the mesh, without transforming the vertices. Again, seems normal (note that the camera is rotated -30 degrees around the X axis, so the mesh is lying on the ground and the skeleton is standing up):

And finally, here's the vertex transformation in action. This is where it gets ugly:

---

As you can see from the images, everything goes nicely until the bones are actually transforming the vertices. Here's some relevant code, I hope the variable names are self-explanatory, and as I try to rubber-duck everything, I try to include the comments about what I think I'm doing.

**Vertex struct**

```
// Vertex struct
struct Vertex
{
    public Vector3 position; // Position
    public Vector3 normal;   // Normal
    public Vector2 uv;       // UV coordinate
    public Vector3 tangent;  // Tangent
    public Vector3 bitangent; // Bitangent
    public int bone0, bone1, bone2, bone3; // Bone indices
    public Vector4 boneWeights; // Bone weights

    // Retrieves the size of the struct in bytes
    public int Size()
    {
        return 4 * Vector3.SizeInBytes + Vector2.SizeInBytes + Vector4.SizeInBytes + 4 * sizeof(int);
    }
}

```

---

**Mesh creation**

```
// ** Create the mesh **
// Vertices
id_vb = GL.GenBuffer();
GLStates.UseVertexBuffer(id_vb); // equivalent to glBindBuffer
GL.VertexAttribPointer(6, 4, VertexAttribPointerType.Float, true, Vertex.Size(), Vector3.SizeInBytes * 4 + Vector2.SizeInBytes + sizeof(int) * 4);
GL.VertexAttribPointer(5, 4, VertexAttribPointerType.Int, true, Vertex.Size(), Vector3.SizeInBytes * 4 + Vector2.SizeInBytes);
GL.VertexAttribPointer(4, 3, VertexAttribPointerType.Float, true, Vertex.Size(), Vector3.SizeInBytes * 3 + Vector2.SizeInBytes);
GL.VertexAttribPointer(3, 3, VertexAttribPointerType.Float, true, Vertex.Size(), Vector3.SizeInBytes * 2 + Vector2.SizeInBytes);
GL.TexCoordPointer(2, TexCoordPointerType.Float, Vertex.Size(), Vector3.SizeInBytes * 2);
GL.NormalPointer(NormalPointerType.Float, Vertex.Size(), Vector3.SizeInBytes);
GL.VertexPointer(3, VertexPointerType.Float, Vertex.Size(), 0);

// Indices
id_ib = GL.GenBuffer();
GLStates.UseElementBuffer(id_ib);
GL.BufferData(BufferTarget.ElementArrayBuffer, (IntPtr)(sizeof(uint) * indices.Count), indices.ToArray(), BufferUsageHint.StaticDraw);

```

---

**Uploading bone transformations to the vertex shader**

```
// Upload bone transformations
for (int i = 0; i < e.Skeleton.bones.Count && i < 16; ++i)
{
    // InverseLink is the inverse bind pose
    Matrix4 boneTransform = e.Skeleton.bones[i].InverseLink * e.Skeleton.bones[i].Entity.worldTransform.Matrix;

    // Upload the bone transform matrix
    GL.UniformMatrix4(Shader.currentShader.GetUniformLocation("boneTransforms[" + i + "]"), false, ref boneTransform);
}

```

---

**Render the mesh**

```
GLStates.UseVertexBuffer(id_vb);
GLStates.UseElementBuffer(id_ib);

// Re-upload the vertex data
GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(Vertex.Size() * vertices.Count), vertices.ToArray(), BufferUsageHint.StreamDraw);

// Enable vertex arrays
GL.EnableVertexAttribArray(6);
GL.EnableVertexAttribArray(5);
GL.EnableVertexAttribArray(4);
GL.EnableVertexAttribArray(3);
GL.EnableVertexAttribArray(2);
GL.EnableVertexAttribArray(1);
GL.EnableVertexAttribArray(0);

GL.VertexAttribPointer(6, 4, VertexAttribPointerType.Float, true, Vertex.Size(), Vector3.SizeInBytes * 4 + Vector2.SizeInBytes + sizeof(int) * 4);
GL.VertexAttribPointer(5, 4, VertexAttribPointerType.Int, true, Vertex.Size(), Vector3.SizeInBytes * 4 + Vector2.SizeInBytes);
GL.VertexAttribPointer(4, 3, VertexAttribPointerType.Float, true, Vertex.Size(), Vector3.SizeInBytes * 3 + Vector2.SizeInBytes);
GL.VertexAttribPointer(3, 3, VertexAttribPointerType.Float, true, Vertex.Size(), Vector3.SizeInBytes * 2 + Vector2.SizeInBytes);
GL.VertexAttribPointer(2, 2, VertexAttribPointerType.Float, true, Vertex.Size(), Vector3.SizeInBytes * 2);
GL.VertexAttribPointer(1, 3, VertexAttribPointerType.Float, true, Vertex.Size(), Vector3.SizeInBytes);
GL.VertexAttribPointer(0, 3, VertexAttribPointerType.Float, true, Vertex.Size(), 0);

// And finally, draw the mesh
GL.DrawElements(BeginMode.Triangles, indices.Count, DrawElementsType.UnsignedInt, 0);

```

---

**Vertex shader**

```
#version 330

uniform mat4 projection;
uniform mat4 view;
uniform mat4 world;

uniform vec3 diffuseColor;

uniform mat4 boneTransforms[16];

layout(location = 0) in vec3 in_position;
layout(location = 1) in vec3 in_normal;
layout(location = 2) in vec2 in_texcoord;
layout(location = 3) in vec3 in_tangent;
layout(location = 4) in vec3 in_binormal;
layout(location = 5) in vec4 in_boneIndex;
layout(location = 6) in vec4 in_boneWeight;

out mat3 tangentToWorld;
out vec2 texcoord;
out vec3 color;

void main(void)
{
    // Use this if you do NOT want to use bones
    // gl_Position = projection * view * world * vec4(in_position, 1.0);

    // Get the vertex position
    vec4 vPos = vec4(in_position, 1.0);

    // Declare the bone vectors
    vec4 b0 = vec4(0);
    vec4 b1 = vec4(0);
    vec4 b2 = vec4(0);
    vec4 b3 = vec4(0);

    // If bone 0 is to be used
    if(in_boneIndex.x != -1)
    {
        // Transform by bone 0 matrix, weight by bone 0 weight
        b0 = (boneTransforms[int(in_boneIndex.x)] * vPos) * in_boneWeight.x;
    }
    // If bone 1 is... and so on
    if(in_boneIndex.y != -1)
    {
        b1 = (boneTransforms[int(in_boneIndex.y)] * vPos) * in_boneWeight.y;
    }
    if(in_boneIndex.z != -1)
    {
        b2 = (boneTransforms[int(in_boneIndex.z)] * vPos) * in_boneWeight.z;
    }
    if(in_boneIndex.w != -1)
    {
        b3 = (boneTransforms[int(in_boneIndex.w)] * vPos) * in_boneWeight.w;
    }

    // Finally, apply the WVP transform to the newly-acquired vertex position
    gl_Position = projection * view * world * vec4(((b0 + b1 + b2 + b3).xyz), 1.0);

    // Pass the color
    color = diffuseColor;

    // Transform NBT to world
    tangentToWorld[0] = (world * vec4(in_tangent, 0.0)).xyz;
    tangentToWorld[1] = (world * vec4(in_binormal, 0.0)).xyz;
    tangentToWorld[2] = (world * vec4(in_normal, 0.0)).xyz;
}

```

---

I guess there's all the relevant code. I'm more than happy to supply you with more code and information in case I missed something.

# Answer
> 1 votes
From a quick once-over it looks like all your stuff is correct conceptually. However, your vertex shader looks a bit suspect though. It seems like you are applying the world transform twice since it is already contained in the bone transforms. Or at least it seems that way in your code. This would be valid though if you bone transforms were relative to your overall object transform.

Also, I was initially confused by the fact that you were transforming by each bone influence and then adding the positions versus building a combined matrix first. I'm too lazy to work it out, but I *think* they are identical mathematically so this could just be a personal style thing.

The way I would usually do it is this:

```
// Declare the bone vectors
mat4 worldSkinned = mat4(0);

// If bone 0 is to be used
if(in_boneIndex.x != -1)
{
    worldSkinned += boneTransforms[int(in_boneIndex.x)] * in_boneWeight.x;
}
if(in_boneIndex.y != -1)
{
    worldSkinned += boneTransforms[int(in_boneIndex.y)] * in_boneWeight.y;
}
if(in_boneIndex.z != -1)
{
    worldSkinned += boneTransforms[int(in_boneIndex.z)] * in_boneWeight.z;
}
if(in_boneIndex.w != -1)
{
    worldSkinned += boneTransforms[int(in_boneIndex.w)] * in_boneWeight.w;
}

gl_Position = projection * view * worldSkinned * vPos;

```

However, I prefer this way because you also need to transform the TBN basis and this way you can reuse the same matrix if you don't care about non-uniform scales

```
// Transform NBT to world
tangentToWorld[0] = (worldSkinned * vec4(in_tangent, 0.0)).xyz;
tangentToWorld[1] = (worldSkinned * vec4(in_binormal, 0.0)).xyz;
tangentToWorld[2] = (worldSkinned * vec4(in_normal, 0.0)).xyz;

```

If you do need to care about non-uniform scales then you need to

```
mat3 worldSkinnedNormal = transpose(inverse(mat3(worldSkinned)));
tangentToWorld[0] = (worldSkinnedNormal * in_tangent).xyz;
tangentToWorld[1] = (worldSkinnedNormal * in_binorma).xyz;
tangentToWorld[2] = (worldSkinnedNormal * in_normal).xyz;

```

Or just pass a second boneTransformsInverseTranspose\[\] to the shader, which could be faster depending on whether you are bottlenecked on uniforms or shader math.

EDIT: Also, another thing I noticed is that your index attribute seems weird. You have a float shader input but you are using glVertexAttribPointer with type GL\_INT but with normalization turned on. So you are actually getting float(idx)/float(INT\_MAX) in your shader. You should try passing false for the fourth argument or alternatively using an ivec4 in your shader and glVertexAttribIPointer directly.

---
Tags: c#, opengl, glsl, skeletal-animation, skinning
---


# Question
Title: Why does calling GL.Color4 result in a blank screen?
I am learning OpenGL using OpenTK and VB.NET. I made a square with a texture:

```
    GL.Begin(BeginMode.Quads)
    GL.TexCoord2(0.0, 0.0)
    GL.Vertex3(-1.0, 1.0, 0.0)
    GL.TexCoord2(1.0, 0.0)
    GL.Vertex3(1.0, 1.0, 0.0)
    GL.TexCoord2(1.0, 1.0)
    GL.Vertex3(1.0, -1.0, 0.0)
    GL.TexCoord2(0.0, 1.0)
    GL.Vertex3(-1.0, -1.0, 0.0)
    GL.End()

```

This works fine and produces this image:

When I add `GL.Color4`, the whole screen is completely blank. This is what my code looks like:

```
    GL.Color4(100, 100, 100, 255)
    GL.Begin(BeginMode.Quads)
    GL.TexCoord2(0.0, 0.0)
    GL.Vertex3(-1.0, 1.0, 0.0)
    GL.TexCoord2(1.0, 0.0)
    GL.Vertex3(1.0, 1.0, 0.0)
    GL.TexCoord2(1.0, 1.0)
    GL.Vertex3(1.0, -1.0, 0.0)
    GL.TexCoord2(0.0, 1.0)
    GL.Vertex3(-1.0, -1.0, 0.0)
    GL.End()

```

Here is an additional piece of code:

```
    GL.ShadeModel(ShadingModel.Smooth)
    GL.ClearColor(Color.Black)
    GL.ClearDepth(1.0)

    GL.Enable(EnableCap.Texture2D)
    GL.BlendFunc(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.One)
    GL.Enable(EnableCap.Blend)

    GL.Hint(HintTarget.PerspectiveCorrectionHint, HintMode.Nicest)

```

# Answer
> 3 votes
The `GL.Color*` functions can only be used between `GL.Begin` and `GL.End.` Your code sample has the lone `GL.Color4` call *before* `GL.Begin`. If you move it inside the begin/end block, you should see things again.

The most-likely reason this has led to a blank screen is that you're actually putting OpenGL into an error state and you're not retrieving any errors from OpenGL. If you had error handling code in place, you'd likely be seeing a message to the effect of "`glColor` must be called between `glBegin` and `glEnd`."

---
Tags: opengl, textures
---


# Question
Title: What is a GUI element with a filling-up rectangle shape called?
After every game of StarCraft 1, the statistics screen shows up. The part I like on this screen is the points counter. It starts from zero and then it counts up to the points you have achieved, with a filling-up rectangle shape based on the number it represents.

What is this type of counter called?

For example, the *Units* bar for *Alpha Squadron* counts from 0 to 4975.

# Answer
The item you're talking about would be referred to as a progress bar:

In this case, the progress bar is animated to fill up over a small amount of time. When completely full, the progress bar matches the highest score for that category.

So, where `4975` is equal to 100% of the bar being full, `2000` is `2000/4975 = .40` or 40% full, as you can see in your example image:

You can animate these in the standard fashion of adding to their value by a small amount each frame until they are set to their desired value.

```
Update() {
    if(currentValue < targetValue)
        currentValue += increment;
}

```

Or in a more controlled manner with a time step included in the calculation.
> 8 votes

---
Tags: gui, terminology, ui-design
---


# Question
Title: How should I implement parallax scrolling with pan and zoom in HTML5?
I'm writing a planetary motion simulator with the HTML5 canvas element and I want to put one or more layers of stars in the background. The user can click and drag the screen to navigate around the map as well as zoom in and out. The map is infinite; they could scroll forever in any direction. I'd like to have the background layer move more slowly than the foreground so as to give the illusion of depth.

How should I go about implementing this? Can I load an image file and tile it? Should I create an SVG image? Should I just use the CanvasRenderingContext2D.fill() to create the background? I'm trying to keep the game running as close to 60fps as possible.

# Answer
You need to test it on your target platforms. Canvas implementations vary hugely in their performance, and a technique which is an optimisation on one may be a pessimisation on another.

If the layers are going to be "sparse" with few objects, I'd recommend just drawing those objects (in order, using painter's algorithm).

However, if there are lots of layers using blending, you may reach an implementation's limit of pixel-pushing. Blending is much more expensive than not blending (as it needs reading as well as writing, even if it's done by the GPU).

I can't really see a problem drawing 100 stars per layer, with 2-3 layers, if the stars are small compared to the total area.
> 1 votes

# Answer
Canvases are, as far as my knowledge/experience goes, not suited to animate large areas of the screen. For these purposes you should fall back to CSS and JavaScript.

One idea would be to set up a few divs behind the canvas. With CSS you define a repeating background for each one of these divs. With JavaScript you trigger then from your code, or even with default browser events, a drag event (i.e. mousedown, mouseup, mousemove/mouseover and mouseout).

In this event you can then determine the moved distance and direction as a pixel-vector by comparing it to the last determined mouse position (see http://www.quirksmode.org/js/events\_properties.html \- Mouse position). This vector can then be used to change the background's offset (background-position) at each single div. By applying only a percentage of this movement-vector to the background's position you get a nice parallax-effect. For instance:

1. layer 33%
2. layer 66%
3. layer 99%
> 0 votes

# Answer
If you've not gone too far on the rendering side yet, one simple solution would be to use an actual 3D renderer. This way you don't have to reinvent the wheel and implement the parallax yourself, you can simply throw a classic perspective projection, a camera, and you're good to go.

The last time I checked, three.js seemed to be a quite compelling option but I'm sure there are plenty of other libs that might suit your needs. Going this way will also probably require a WebGL-enabled browser for proper performance, which might or might not be an option depending on what your final goal is (do you want the largest audience possible or are you just experimenting?).
> 0 votes

---
Tags: javascript, html5, parallax-scrolling
---


# Question
Title: P2P card game: Shuffling without knowing the final order?
So, I am conceptualizing a P2P trading card game. The issue is the network: knowing the identity of a card is giving a major advantage, so both clients need enough information about a card that they know it exists, but not so much that the "value" or "specialties" of a card can be determinated.

The basic approach to that is simple: each client has a public and a private key for each card, and to decrypt the card you need all private keys associated to that card.
Whenever a card is played the appropriate key is send over, whenever a card is drawn the other players send the needed keys over.

However there is a issue: the start state is known and from it you could determine which card is which, what makes the whole thing a bit pointless.
How do I shuffle cards over the network so that the client doesn't know the actual end state (without knowing the keys)?

# Answer
You can do this by **making the secret starting state verifiable** and **guesses difficult**:

* Have all players generate a new private/public key pair, send the public keys
* Let them shuffle their own decks
* Choose and/or exchange salts (see below)
* Generate signatures for the information you want to check:

+ Either a player's full deck if that can become known after the game or
    + the individual cards if you want to check after each card is revealed and not make the deck known if not all cards are played

and send them over
* Have players choose a seed each to **shuffle the opposing decks only**. This ensures shuffling takes place with no knowledge (because the key pair was newly created and the cards have not been revealed, but have been "locked in place" by the signature(s))

After this you can use the same methods as a normal card game would use, for example addressing cards by their starting position in the deck or their current position. You need to keep track of the starting position in the hidden (signed) deck for each card, at least until it's revealed.

Depending on what you sign, verification takes place at different times:

* If you signed the deck, transmit the full deck after the game is over. A cheater will be revealed because of mismatched cards **or** the signature.
* If you signed the cards, check whenever one is revealed. The signature won't match if a player tries to cheat.

**The strength of this algorithm depends on two assumptions:**

1. Players can't choose a card that matches the transmitted signature.

This should be inherent in correctly used modern cryptographic algorithms unless the key is chosen maliciously, with known collisions. You can protect against it by letting the opposing player(s) choose salts, which should prevent using known collisions.
2. Players can't verify the signatures without knowing the cards.

This part is trickier, as the amount of plain texts is very limited if you sign individual cards only.

Possible solutions:

* Add a secret salt for each signature:

    This should not allow players to choose cards unless there is a collision weakness in the signing algorithm. Adding a salt to each card also prevents revealing cards that are the same.

    The salt is stored and revealed when the signature has to be checked.
    * Make guesses more expensive:

    (Checking the signature should already be somewhat expensive, this adds even more computations.)

    This can be done by using a (possibly known) salt and hashing the plain-text multiple times, but is possibly not as secure as the first option when used alone and is not as efficient. It can greatly increase the security together with a secret salt though, as the difficulty is multiplied.

    A side-effect is that it makes finding collisions much more difficult.

If you want to future-proof the game while making it as fast as possible let the players choose minimums for the secret salt length and hash repetitions that are enforced for all players. You need to cap these when running a verification/leaderboard server though, to avoid a potential DoS.

You can run verifications in the background to avoid delays, as a failure should terminate the game independently of its current state. (Make sure the transmissions can't be faulty though!)
> 5 votes

---
Tags: networking, security, card-game, peer-to-peer
---


# Question
Title: Field of view settings for first person shooter
Are there any industry standards for setting the field of view (FOV) for FPS games or is it solely based on trial and error? Are there any guidelines for choosing the correct value?

# Answer
> 3 votes
There's no generic solution, as it essentially depends on how far away from the screen you are as well as the dimensions of your screen.

Imagine the screen being a transparent window: Depending on how far away you're sitting (and the screen size of course), you'd be able to see a different amount of the world behind you, with anything outside a specific angle being covered by the window (screen) borders and the wall (or outside world).

If you'd like to measure this for you personally, take your head's position and imagine two lines (or planes) from your head to each of the screen's borders. Measure the angle between those and you've got your own personal preference for a good FOV.

This is especially important for FPS games. It's less about immersion, but more about being able to play the game without getting motion sickness. Not everyone is similarly affected and some might have no problems with game x, while having issues with game y.

In general, just play safe and don't force any fixed angle. Instead, allow the user to choose an FOV. To avoid cheating, you should still limit the angle, but I'd suggest you do so leaving much room for configuring the game to the user's likings.

Personally, I'd suggest allowing any value between 60° and 120°, which should be perfect for pretty much anyone. This can be a challenge for level designers as well as artists, but overall it should greatly improve user experience as well as review scores and the like (I always love TotalBiscuit going to options first, hunting for a FOV setting, and then starting to rage if it's missing (which I consider a completely legit and understandable reaction)).

# Answer
> 1 votes
60 to 90 degrees is probably the standard range. As others have mentioned, it's important to make this adjustable so players can specialize it to their own setups.

It's important to consider that players have monitors of different aspect ratios. You'll need to think about how you want the FOV setting to be applied: as the vertical FOV, or as the horizontal FOV. Diagonal FOV is also a possibility. In any case, the exact vertical and horizontal FOVs will vary with the monitor aspect ratio as well as with the overall FOV setting.

Another thing to think about is multi-monitor support. Both NVIDIA and AMD's multi-monitor gaming systems work by causing a group of monitors to appear as a single giant screen to the game, in which case the game needs to render with a super-wide FOV. Ideally, the game would detect this and automatically make the necessary adjustments. This affects HUDs, menus, etc. as well - you probably want them to still appear on the primary monitor when using a multi-monitor setup.

---
Tags: camera
---


# Question
Title: Google play game services and Facebook integration in one game
We are creating a cross platform game for iOS and Android. We have thought about how and with which services we should integrate achievements and scoreboards with.

For the iOS part, we are pretty sure that this how we want to do, in order from when the user opens the app for the first time:

* Connect with Game Center (Should be automatic, the user shouldn't even notice?) We will also get the players nickname for public scoreboards here.
* Ask if the user wants to connect with Facebook so that we can compare the players highscores with their friends.

We could add Google play game services there as well, but I don't feel like that adds anything to the experience for the end user.

Now comes the tricky part: Android

We thought that we could do just like for iOS, except that we replace Game Center with Google Play Game Services. However, unlike Game Center, Game Services will ask the user to log in to their Google+ account and allow us to access their account. So now, what we have is a double login, first with Google+ and then with Facebook. What will users think about that? Should we scrap Play Services entirely and just ask the user for a nickname within our app and user Facebook for achievements?

# Answer
There is a common design error that comes up for multi-mobile platform projects, and it's not limited to games. People who prefer iOS think that everyone, Android users included, will balk at anything except the iOS experience. So when designing the android half of a mobile app, the design includes iOS-style inputs and layouts. Likewise, Android designers think that they need to apply custom style to everything iOS so that it doesn't look 'iphoney'.

Both these ideas are wrong. People who don't own iPhones don't secretly pine for the day when they will finally get an iPhone and its glossy, rounded-corner buttons. And iPhone users have no interest in seeing anything different from the common iOS app layout. The two platforms are different, but their respective users prefer that difference.

Android users who are willing to use Google Play services are used to having to sign in. People who use Game Center are (ostensibly) aware that they're always logged in and can log out at any time. Don't assume that Android is less agreeable, simply because it gets permissions on an app-by-app basis. Afterall, that's how Facebook works, and users still agree to its permission requests.

As for your question, would it be off-putting to users to have to sign in to two services? That is entirely up to your execution of the sign-ins. You're right, it would be annoying to put the two sign-ins back to back before the user even gets to try your gameplay. So don't do that. Be more subtle; let the player enjoy the game a little before prompting them to post their highscores.

You could go the way of CCS and constantly harass users to Facebook beg, or you could go the cheap tower defense method, and just show a reminder every few rounds. I think the trick is to be respectful of the player, and not let the social "features" get in the way of enjoying the game.
> 3 votes

---
Tags: android, facebook
---


# Question
Title: Which camera angle is used for these sprites?
I am trying to replicate these sprites:

But I am not managing to make sense of how it is done. The character is facing forward ( \<--- ), but you can see the front of its body instead of just the side. Why? Is the camera positioned diagonally? Or is the body bent, as in a fighter stance?

Or a combination of both?

Which exactly is the positioning/perspective/view I should use to replicate it correctly?

# Answer
To my untrained eye, the "camera" is looking at the characters in question mainly from the side. You're seeing what would be the front of the bodies (the chest) because they are standing in a combat-ready pose (as you posited) that is akin to a fencer's pose (to help minimize the surface area presented to the foe).

Not all of the characters have as much tilt to their body, which accounts for some of the variation.

I don't think the actual "camera" is viewing the characters on a diagonal, like in your last sketch, because if you were to draw a horizontal line at the level of each sprite's heels you'd see the heel of both feet is generally on or quite near that line (unlike in your last sketch). Though the bottom pixel of the "back" feet is often lower than that of the front, that's due to perspective and the fact that the character's feet are at approximate right angles to eachother.
> 3 votes

---
Tags: graphics, animation, sprites, spritesheet
---


# Question
Title: App: My game is ugly. Advice on making it less ugly
Following is the main screen you see when you start the app.

After touch, you get directed to the two options. You can either start from the last puzzle you solved or select from the list

This is the screen you will see if you select the second option

This is the game screenshots

Option open

GameExplanation : you move the Tetris shaped blocks to make certain pattern. I tried to make it nice and clean but instead I get an impression that this looks just plain lack of anything at all. I sincerely fear that this blunt look will destroy the first impression.

Ty everyone I am taking everyone's advice and editing a bit by a bit. when app starts, letters and the tetris blocks are all not organized. As the blur effect runs down, correct image shows up.

* trying to not use one-channeled-simple-color; mix more than one color.
* use pastel tones.
* re-scale images for higher quality.

# Answer
First of all: I'm no designer either, my games usually consist of "programmer art". ;)

Probably the quickest escape, congusbongus already noted in the comments:

* Get a designer. However, this most likely will cost you some money unless you know someone or got someone really interested in the game, etc.

But apart from that, there are some simple things you can try out on your own without having you to be some huge or awesome designer:

* Even if you want a "clean" look, avoid using pure colors, essentially any color consisting only of one component (like red but no blue or green) at full (or nearly full) intensity.

If you're using any of the classic 16-color-display colors (like bright red or green), you'll automatically get some look that is often considered cheap or "too retro" (I'd say Windows 3.x shareware style). This also applies to using default greys: Don't do it. You'll get some rather boring and stale look rather fast.

Just have a look at Windows 8's new UI: Many don't like it, I agree partially, but they got one thing right: colors!

Here's a quick mockup where I simply changed some colors and I think it looks a lot better already:
* Don't do clean shapes. This really depends on your actual design and what you've got in mind, but you don't always have to use unicolored shapes to get a clean look. You could just add a slight texture, some highlights, and/or drop shadows to get something look more complex or not just that simple without overcomplicating things. For example, I picked the T shape, added some texture and a slight bevel and drop shadow:

On a second thought, I'd agree it might look a bit too dark/dirty, but that would be just nother setting with the color slider.
* Use antialiasing. Looking clean is one thing, looking pixelized "I only got two colors" is something different.
* Avoid pixelization, unless it's your specific art style. This is similar to my previous point about antialiasing, however you should keep it minimal. Especially your fonts look blurry and pixelated, not clean or properly antialiased. This is most likely some upscaling issue with the font drawing.
* Add fluff: How about making the shapes a bit "gooey", e.g. let their outlines flow a bit when touched. Or how about black outlines that look like they're drawn with crayons or pencils? This will create a different, not so 100% clean look, but it might get you something more unique than "just another Win8 style app". Just make sure it's something you can notice in a screenshot as well! I agree with Boreal Games on adding "juice". But make sure it's more than just some touch feedback or (sound) effect you can't really show off in screenshots (I really hate screenshots on app stores with added in fingers or hands as they always feel photoshopped, even if they only added that hand).
> 4 votes

# Answer
A simple piece to make your Tetris puzzle look better is to go with the original design scheme tetris used:

Seperate the 7 colours that you will use (these don't need to stay close to the originals at all but may help with attracting those that recognize it's classic colour scheme.) Giving yourself a colour pallette before you have even made your set of shapes can really help and if you are going for the tetris shapes then you only need 7 colours for them.

You can use the fact that the tetrominos are actually 4 squares adjacent to each other instead of one solid shape *if you prefer*. This will make your design look more diverse but it can lend itself to many different design choices. You can make each segment into a square with bezel, rounding, inset or a border:

You can still apply these effects and styles to a solid tetromino shape and get different effects from it. I know from chat that you use Paint.NET so here are some useful plugins to get you started:

You could also play with segment shapes so instead of a square, do a circle or octagon and that way your background can play a larger part (giving gaps between the shapes will reveal what background you use.)

Ultimately, play around with your design and use some clean up techniques like the others mentioned: my personal favourite being the anti-aliasing. One of the best resources I found you can find here in this Stack Overflow question and here in this blog post that gives you many options. This will quickly ensure a lot of your display looks crisp and un-pixelated which I think is the main source of your issue.

## To ensure you keep your apps "ugliness" scale to an all time low do 3 core things:

* **Decide on a colour pallete:** whatever colours you choose, pastel, solid, bevelled or otherwise - stick with it
* **Use anti-aliasing:** also called multisampling to make sure jagged edges from transparent or high contrast pixels are smoothed
* **Create high resolution images:** scaling an image up from a low resolution to higher almost always produces a lower quality. It doesn't matter how simple you make the design, however, use the highest resolution you can whilst being mindful of your resources budget. No need for your tetronimo to be 1920 x 1080 and 1.3Meg, but no harm in making it bigger than 10 x 10.

As an example of what you can acheive with a few minutes in Paint.NET or Photoshop, here is my example:

Where you go from there is completely up to you!
> 5 votes

# Answer
A minimal color scheme can look great, and your color choices themselves are perfectly fine. However, you should make the graphics look sharper and cleaner. They're upscaled, which looks pretty bad. Create your graphics at a higher resolution than you need and then shrink them based on the device resolution.

In terms of making a UI more interesting, you should try and juice it up. Juice is anything that you add to a game to make it look or sound more fun while never changing the core gameplay. To explain better, watch a quick presentation on juice. Some easy ways of doing this are adding sound effects, screen shaking, and particles when you tap something. You'll make a user feel like they are a god in your little world by turning their finger into a ten ton pillar.
> 2 votes

# Answer
advice I had as a UI designer/developer a very long time ago is to design/develop in black and white, add colour only for emphasis. I've seen so many bits of software over the years that were destroyed by a theme, skin or graphics that the developer probably thought was a good idea at the time, but that looked pretty awful to anyone with a small amount of aesthetic judgement.

The other tip I would give is to make sure all of your bitmap assets are scaled correctly, with filtering and/or use anti-aliasing. The final rule is to design "sets", so that all of your assets have a similar aesthetic.

If you apply those 3 it's hard to go wrong :).

(Another quick tip: If you're going to use gradient fills, make them as subtle as possible).
> 2 votes

---
Tags: android, graphics-design, ui-design
---


# Question
Title: How to hide all console output in Panda3d?
Whenever I start my Panda3d application, i.e. initialise the `ShowBase` class, I get the following console output:

```
Known pipe types:
  wglGraphicsPipe
(all display modules loaded.)

```

The application works fine, so I would like to suppress these lines.
How can I disable/hide this output?

Also, what does this mean exactly?

# Answer
> 1 votes
Panda loads the display modules that have been specified in the Config.prc file (through load-display and aux-display lines) and lists which ones are available for rendering. Examples are the "pandagl" module, which makes the "wglGraphicsPipe" rendering pipeline available on Windows (the OpenGL renderer), and the "pandadx8" and "pandadx9" modules (with the respective DirectX renderers).

If you really wish to hide this information, you can start Panda with "window-type none" to prevent it from creating the window, creating the pipe and opening the window explicitly, telling Panda not to output the pipe types when opening the pipe:

```
base.makeDefaultPipe(printPipeTypes=False)
base.openDefaultWindow()

```

However, there is no real reason to suppress it, as it won't appear in a deployed game (only in the log file). You can also redirect this output to a log file yourself if you wish, by setting the "notify-out" configuration variable to a filename in your Config.prc file.

---
Tags: panda3d
---


# Question
Title: projected textures not appear on the "back" of the mesh as well?
I want to create blood wounds on my character's bodies by using projected textures. I've watched some commentaries on games like Left 4 Dead and they say they use projected textures for the blood. But the way projected textures work is that if you project a texture on a rigged character, say his chest, it will also appear on his back. So what's the trick? How to get projected textures appear only on one "side" of the mesh?

I use the Panda3D game engine, if that will help.

# Answer
It sounds like you are using ancient projected textures in a fixed-function pipeline. If that is true, you will not be able to solve your problem without a custom shader that checks the dot product of the blood-inducing vector to the vertex normal. However, if you can use programmable pipeline, you can abandon 90s and venture forth into 21 century with decals. Decals are being used for tasks such as blood marks, explosion craters, wall posters, etc. since forever.

Chances are, L4D devs meant that they used decals which were projected geometrically onto objects. Nice article about these decals can be found here.

If you're stuck with fixed pipeline, I guess the best approach is texture blending. For example, prepare bloody texture of some limb, and then blend it with the limb texture when said limb gets hit.

> But in L4D the texture is projected on animated models. Will this work on animated models?

It is, of course, also possible to do skinned decals. The only difference I can see is that for an animated models you have to adjust the decal frustrum, so decal position will be adjusted back to the bind pose.

For example, here is one way of doing it. Represent the decal as a sphere and find the biggest colliding bone in current animation. Let's call it `decalBone`. Also let's say it stores the per-bone transformations in `decalBone.Offset`, and it's possible to get world transformations via `decalBone.WorldTransform`. Then your adjusted transformation will be something like `targetDecalTransform = Matrix.Inverse(decalBone.WorldTransform * decalBone.Offset)`. Use it to adjust the raw decal frustrum centered on the world position.

With this frustrum you can now do the same thing you've already done with static model decals: get affected mesh faces, clip them against frustum, triangulate the resulting faces into decal vertices, calculate UVs and transform vertices to the mesh local space.
> 2 votes

# Answer
Alternatively, you can combine your approach with shadow mapping in order to make it work dynamically and get correct occlusion. If you create a camera that renders its depth information into a texture set to the Texture.FT\_shadow filter type, and then use a combination of texture modes (or a shader) to only apply your projected texture where the shadow map compare succeeds, that should do the trick.
> 0 votes

---
Tags: textures, projection, character, panda3d
---


# Question
Title: Box2D body jitters when colliding with static body
I am developing a game where a body is moved within the scene using touch. The scene has a boundary wall made up of static rectangular bodies. When I move the object along the boundaries, on collision, it jitters.

This is because the boundary wall pushes the body outwards while the touch pushes it against the wall. I am using linear velocity to move the body using touch. I tried to avoid this by setting the linear velocity of the body to 0 on collision with the boundary wall but it didn't work. I am trying to have a smooth movement along the boundary walls with no jitters. How can I solve this?

Following snippet moves the body on touch. Linear velocity vector has direction towards the touch point. The movement is smooth within the play area but not at the boundaries.

```
 case TouchEvent.ACTION_MOVE:

                strikerBody.setLinearVelocity((pSceneTouchEvent.getX()-body.getPosition().x * PIXEL_TO_METER_RATIO_DEFAULT),(pSceneTouchEvent.getY()-body.getPosition().y * PIXEL_TO_METER_RATIO_DEFAULT));

```

These are the bounadry walls:

```
final Rectangle groundLeft = new Rectangle(camera.getWidth() / 2 - camera.getWidth() / 4, 1, camera.getWidth()/2, 20, this.resourcesManager.vbom);
        final Rectangle groundRight = new Rectangle(camera.getWidth() / 2 + camera.getWidth() / 4, 1, camera.getWidth()/2, 20, this.resourcesManager.vbom);

    final Rectangle roofLeft = new Rectangle(camera.getWidth() / 2 - camera.getWidth() / 4, camera.getHeight() - 1, camera.getWidth()/2, 20, this.resourcesManager.vbom);
    final Rectangle roofRight = new Rectangle(camera.getWidth() / 2 + camera.getWidth() / 4, camera.getHeight() - 1, camera.getWidth()/2, 20, this.resourcesManager.vbom);

    final Rectangle leftTop = new Rectangle(1, camera.getHeight() / 2  + camera.getHeight() / 4 + camera.getHeight() / 12 + camera.getHeight() / 16 , 20, camera.getHeight()/2 - camera.getHeight()/12, this.resourcesManager.vbom);
    final Rectangle leftBottom = new Rectangle(1, camera.getHeight() / 2  - camera.getHeight() / 4 - camera.getHeight() / 12 - camera.getHeight() / 16, 20, camera.getHeight()/2 - camera.getHeight()/12, this.resourcesManager.vbom);

    final Rectangle rightTop = new Rectangle(camera.getWidth() - 1, camera.getHeight() / 2  + camera.getHeight() / 4 + camera.getHeight() / 12 + camera.getHeight() / 16, 20, camera.getHeight()/2 - camera.getHeight()/12, this.resourcesManager.vbom);
    final Rectangle rightBottom = new Rectangle(camera.getWidth() - 1, camera.getHeight() / 2  - camera.getHeight() / 4 - camera.getHeight() / 12 - camera.getHeight() / 16, 20, camera.getHeight()/2 - camera.getHeight()/12, this.resourcesManager.vbom);final FixtureDef wallFixtureDef = PhysicsFactory.createFixtureDef(0, 0.5f, 0.5f);
    PhysicsFactory.createBoxBody(this.mPhysicsWorld, groundLeft, BodyType.StaticBody, wallFixtureDef).setUserData("wall");
    PhysicsFactory.createBoxBody(this.mPhysicsWorld, groundRight, BodyType.StaticBody, wallFixtureDef).setUserData("wall");

    PhysicsFactory.createBoxBody(this.mPhysicsWorld, roofLeft, BodyType.StaticBody, wallFixtureDef).setUserData("wall");
    PhysicsFactory.createBoxBody(this.mPhysicsWorld, roofRight, BodyType.StaticBody, wallFixtureDef).setUserData("wall");

    PhysicsFactory.createBoxBody(this.mPhysicsWorld, leftTop, BodyType.StaticBody, wallFixtureDef).setUserData("wall");
    PhysicsFactory.createBoxBody(this.mPhysicsWorld, leftBottom, BodyType.StaticBody, wallFixtureDef).setUserData("wall");

    PhysicsFactory.createBoxBody(this.mPhysicsWorld, rightTop, BodyType.StaticBody, wallFixtureDef).setUserData("wall");
    PhysicsFactory.createBoxBody(this.mPhysicsWorld, rightBottom, BodyType.StaticBody, wallFixtureDef).setUserData("wall");

    this.attachChild(groundLeft);
    this.attachChild(groundRight);
    this.attachChild(roofLeft);
    this.attachChild(roofRight);
    this.attachChild(leftTop);
    this.attachChild(leftBottom);
    this.attachChild(rightTop);
    this.attachChild(rightBottom);

```

# Answer
So were going to get a little tricky here.

Create a second object that is an exact clone of your first one and attach them with a weld joint. These objects should not collide with each other and the one of them should collide with everything but the wall and one should collide with only the wall.

Duplicate your walls too, if its static don’t worry about the weld joint. If you need them to stay in the same location use the weld joint. This should only collide with the new object being touched.

The two new objects should only collide with each other. Next set both their restitution and friction to 0. This should result in no bounce or rotational forces causing the object to simply slide along the wall instead of constantly bouncing off.
> 1 votes

# Answer
Depending of the way you have implemented your physics and graphics, it may be either your dynamic body being too small (or too large) or if your physics and graphics are not synced right. I suspect the former, as many physics libraries (Box2D does it too, if I remember correctly) have a penetration tolerance which allows the bodies to intersect just a little bit. If the penetration tolerance is a notable percent of your body size, it becomes visible as jittery motion when hugging static bodies.
> 0 votes

# Answer
I believe, that setting linear velocity to move body is not great idea. The result of each step calculations is positions and velocities of the bodies. So, when your body collides with a wall, box2d calculates contact impulses, that makes body velocity according to situation. But then, you settting this velocity by hand, and all box2d calculations are breaking down.

I suggest to use impulses or forces to controll a movement. Sure, impulses more preferable, because they allow to achieve better interactivity. To make movement more smooth, you can try linear damping. Also, some manual correction of impulse value can help. For example, make in view current velocity of the body, distance to the touch (farther- stronger), count of touches and etc. Using forces also can make movement more gently. Another good way to move body is use b2MouseJoint or b2MotorJoint.
> 0 votes

---
Tags: box2d, physics, andengine
---


title: How to keep a GameObject from dropping?

text:
# Question
Title: How to keep a GameObject from dropping?
I am applying the following script to first person object:

```
function Update () {
   var mountain : GameObject;

   mountain = GameObject.Find("QuantumCold_B");
   transform.RotateAround(mountain.transform.position, Vector3.up,20 * Time.deltaTime);
}

```

When I run this it looks like the mountain is turning and the first person object is falling. I applied this script to the first person object thinking it would rotate around the mountain. Perhaps I need to apply lookAt in some way? How do I keep the first person object form falling?

I did set the gravity=0 for motor section of Character Motor Script.

# Answer
You keep a game object from dropping by removing or disabling any scripts that might be altering its position.
> 1 votes

---
Tags: unity, unityscript
---


# Question
Title: How to avoid character to move when selected
I've got a player Class which can walk to a certain point on the screen when left mouse is pressed:

```
if (mState.LeftButton == ButtonState.Released && oldMouseState.LeftButton == ButtonState.Pressed)
            {

                    if (mState.X > CurrentPosition.X)
                    {
                        CurrentDirection = Direction.Right;
                    }
                    else if (mState.X < CurrentPosition.X)
                    {
                        CurrentDirection = Direction.Left;
                    }

                    CurrentDestination = new Vector2(mState.X, mState.Y);
                    CurrentState = PlayerState.Moving;
                    reachedDestination = false;
            }

```

Now I have several Characters on screen. If I want to select one of them I also do a left click, which sets the character to selected.

```
    if (mState.LeftButton == ButtonState.Released && oldMSstate.LeftButton == ButtonState.Pressed)
            {
                if (player1.BoundingBox.Contains(new Point(mState.X, mState.Y)))
                {
                    if (!player1.Selected)
                    {
                        player1.Selected = true;
                        player2.Selected = false;
                    }
                }
if (player2.BoundingBox.Contains(new Point(mState.X, mState.Y)))
                {
                    if (!player2.Selected)
                    {
                        player2.Selected = true;
                        player1.Selected = false;
                    }
                }
}

```

The problem is that as soon as one of the characters is selected it also performs the moving animation. This is beacuse for the trigger is the same for both moving to destination and selecting.

Do you know any way to avoid this behaviour and still keep using the left click for both?

Thanks in advance!

# Answer
On touch devices, developers are freely given two seperate events in the form of "touch and hold" and "tap". You could try to implement this manually. Since you seem to want to use the same button for both actions, I think the best solution would be implementing some sort of miniscule delay between clicking a point, and them moving to it (say, 200ms). If the click is released before the 200ms, then count it as a "click", and check if a character's bounding box is in the click. I should note that this delay will be a heavy hit on gameplay if your action is fast-paced, and you may have to increase that 200 number if some of your players have a tendency to make longer presses. (I know plenty of amature computer users who always "firmly" click on files/links for a full second)

The alternative is: If you have some sort of class to handle the controls (ie, handles rebinding of controls, or other forms of input like touch/controller) then add a feature to let a particular event be "cancelled" once one class has handled it. Javascript has something like that. Ensure that your unit-selection runs first, and cancel the click event since it's already been processed. The downside to this approach is that if someone misclicks a character, they'll walk towards them.

Having played some top-down games of the kind, I can't tell you how annoying it is to have the controls for "Throw a grenade at a razor-faced demon" and "Run closer to the razor-faced demon with your grenade" to be a few pixels apart.
> 1 votes

# Answer
Clicking should be handled in a separate layer. In the past, I've called this layer the HUD (heads up display), and it handles unit selection, giving commands to the selected units, moving the view port, and other user activities that are not part of "the game". So instead of having each unit check where the user has clicked, have your HUD handle each click and pass commands down to the units. That way, you can check to see if you've selected a unit, and if not, then move the selected unit.

In very rough pseudocode:

```
class HUD
{
    Unit selectedUnit;
    ...
    void HandleClick(e)
    {
        bool unitWasSelected = false;
        foreach(unit in world)
        {
            if(unit was clicked)
            {
                unitWasSelected = true;
                selectedUnit= unit;
            }
        }
        if(!unitWasSelected)
        {
            selectedUnit.Move();   // Send a command down
        }
    }
    ...
}

```

My HUD manages which units are selected, and even draws the selection circles around the selected units. I've gone so far that my selected units have no idea that they are selected, any why should they? A real separation of responsibilities is nice.
> 1 votes

---
Tags: xna, c#, movement, selection
---


# Question
Title: Using Shader causes triangle to disappear
The following is my rendering code.

```
Private Sub GameRender()
    GL.Clear(ClearBufferMask.ColorBufferBit + ClearBufferMask.DepthBufferBit)
    GL.ClearColor(Color.SkyBlue)

    GL.UseProgram(theProgram)

    GL.EnableClientState(ArrayCap.VertexArray)
    GL.EnableClientState(ArrayCap.ColorArray)

    GL.BindBuffer(BufferTarget.ArrayBuffer, vertexPositionID)
    GL.DrawArrays(BeginMode.Triangles, 0, 3)

    GL.DisableClientState(ArrayCap.ColorArray)
    GL.DisableClientState(ArrayCap.VertexArray)

    GlControl1.SwapBuffers()
End Sub

```

This is screenshot without `GL.UseProgram(theProgram)`

This is screenshot with `GL.UseProgram(theProgram)`

Here are my shader code that I picked from online tutorial.

Vertex Shader

```
#version 330
layout(location = 0) in vec4 position;
void main()
{
    gl_Position = position;
}

```

Fragment Shader

```
#version 330
out vec4 outputColor;
void main()
{
   outputColor = vec4(1.0f, 1.0f, 1.0f, 1.0f);
}

```

These are my shader creation code.

```
    '' Initialize Shader
    Dim shaderList(1) As Integer
    shaderList(0) = CreateShader(ShaderType.VertexShader, strVertexShader)
    shaderList(1) = CreateShader(ShaderType.FragmentShader, strFragShader)

    theProgram = CreateProgram(shaderList)

    GL.DeleteShader(shaderList(0))
    GL.DeleteShader(shaderList(1))

```

Here are my helper functions

```
Private Function CreateShader(ByVal shaderType As ShaderType, ByVal code As String)
    Dim shader As Integer = GL.CreateShader(shaderType)
    GL.ShaderSource(shader, code)
    GL.CompileShader(shader)

    Dim status As Integer
    GL.GetShader(shader, ShaderParameter.CompileStatus, status)
    If status = False Then
        MsgBox(GL.GetShaderInfoLog(shader))
    End If

    Return shader
End Function

Private Function CreateProgram(ByVal shaderList() As Integer) As Integer
    Dim program As Integer = GL.CreateProgram()
    For i As Integer = 0 To shaderList.Length - 1
        GL.AttachShader(program, shaderList(i))
    Next
    GL.LinkProgram(program)

    Dim status As Integer
    GL.GetProgram(program, ProgramParameter.LinkStatus, status)
    If status = False Then
        MsgBox(GL.GetProgramInfoLog(program))
    End If

    For i As Integer = 0 To shaderList.Length - 1
        GL.DetachShader(program, shaderList(i))
    Next

    Return program
End Function

```

# Answer
After

```
#version 330
layout(location = 0) in vec4 position;

```

you want to use OpenGL \> 2.0, this means that you need to store all your vertices in Vertex Buffer Objects (VBO) which are bound to Vertex Array Objects (VAO).

For testing you should first comment the `gl_ModelViewProjectionMatrix *` part and put your rectangle into the view volume (i think it was from x = -1 to x = 1 and the same for y)
> 0 votes

---
Tags: opengl, shaders, opentk
---


# Question
Title: Should I use an abstract class or function pointer to implement component notifications?
I want to create a component-based game engine with subsystems which do the work, entities which are simply a list of components (plus position and rotation, because every object will have that), and data.

In addition I want the subsystem to create the components for the entity (the entity has a list of component types and the subsystem creates them). The subsystem has to be notified if an entity is added to the world. I think the best way is the observer pattern: my scene manager notify every subsystem.

This is where I got stuck. When the scene manager notifies, should this be a function pointer or a abstract system class with handle message? In the first case, how can I get this work with a variable count of parameters?

This approach with an abstract class is not my favorite, I think function pointers may be better. Consider this case: my position component will be edited from the position system, so my system or my component have to notify the render system.

Given my above requirements, what should I do to deal with these notifications?

# Answer
> 1 votes
Move your initialization logic. The "subsystem" can *create* a component or *register* a component, but leaves it uninitialized. Then the code that requested the creation can initialize the component, using the per-component-type initialization methods that understand all the different types. If the subsystem needs an initialized version of the component, have a separate "activate" message you can send after activating the component (or even better, let game objects be active/inactive, and activate all components as necessary after activating the game object - this lets you remove/deactivate an entire object without destroying or deinitializing it, which does come in handy here and there).

So, create the component, register it, initialize it, active, and profit, in that order.

Another approach would be to do one of your suggestions and have messages with "rich" data. A super easy way to accomplish this is to just use Lua tables or the like for your messaging (embedding Lua is C++ is super easy). Another similar way is to pack all your message data into a string of some kind (using XML, JSON, or a custom format) that can then be parsed/unpacked by the subsystem when it creates the component. I'd highly recommend the first approach, though.

---
Tags: c++, component-based
---


# Question
Title: Which coordinate space is the canonical default for each shader pipeline stage?
I'm working with Direct3D 11 and HLSL. I use four different shaders (vertex, hull, domain and pixel).

I always have troubles using the right coordinate space in my shaders. Could somebody identify the appropriate space for the vertex, hull, domain and pixel shader stages?

# Answer
* The vertex shader takes input data from vertex buffers (which are typically in model space), transforms that input, and produces output data in clip space. After the vertex shader stage, the perspective divide (by the output `w` coordinate) occurs.
* The pixel shader deals with fragments, not vertices, but when you do make use of coordinates (via `SV_Position` for example), those coordinates are in screen space (offset by 0.5). This means they range from zero to one.
* The hull and domain shaders operate on input data and produce output data within the same space. Because the input data is generally in model space, the output data is also in model space.

That said, these are just canonical defaults. Since you are controlling the input data and the interpretation of that input data, you can place that data in any coordinate frame that is useful to you. For example, when faking 2D graphics in a 3D API it can be useful to simply place pixel coordinate input data into vertex buffers and have a very simple, almost no-op vertex shader.

There are some aspects of the pipeline outside your programmable control though. For example, `SV_Position` will always be offset screen space. The biggest thing to worry about it actually the output of the vertex shader stage. The rest of the pipeline will assume that output is in clip space, perform clipping, and perform the perspective division by `w`. Consequently you may need to set `w` accordingly (often to `1.0`) if you want to "avoid" this division.
> 7 votes

---
Tags: shaders, hlsl, directx11
---


# Question
Title: Understanding the z-axis vector from OpenGL modelview matrix
I would like to shoot spheres in the current view direction in a simple scene. I use an FPS camera, so no z-rotation. The vector pointing in the correct direction should be `(m[8], m[9], m[10])` where `m` is the modelview matrix as returned by `glGetDoublev(...)`.

In my understanding that vector is normalized, so when I scale it by some scalar its length will equal that scalar. If I draw an object every frame and translate it by the scaled z-axis vector (plus camera position), the object should be directly in front of me, all the time, right?

However, when I run my program, the object is not in front of me all the time. It is in front of me, as long as no rotation around the y-axis is done. Here is the relevant (I think) source code:

```
/* camera */
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glRotatef(g_cam.rx, 1, 0, 0);
glRotatef(g_cam.ry, 0, 1, 0);
glTranslatef(-g_cam.tx, -g_cam.ty, -g_cam.tz);

/* get z-axis vector */
double mm[16];
glGetDoublev(GL_MODELVIEW_MATRIX, mm);

/* should be in front of me, all the time */
glPushMatrix();
glTranslatef(g_cam.tx + 10 * mm[8], g_cam.ty + 10 * mm[9], g_cam.tz - 10 * mm[10]);
glColor3f(0, 0, 1);
glCullFace(GL_FRONT);
glutSolidTeapot(2);
glCullFace(GL_BACK);
glPopMatrix();

```

Note that this is not about how to place an object in front of me all the time, but rather what is wrong with my understanding, that using the z-axis vector does not work here.

I know that this is a frequent question, because I found lots of material on the internet. However, I seem to be missing something yet. It would be great if you could help me with it :)

If the problem is not as obvious as I think it is, I can prepare a small example demonstrating the issue.

# Answer
> 2 votes
You would need to use the *inverse* view matrix for this. The view matrix transforms from world space to camera space, so the third column (elements 8, 9, 10) of this matrix is the *world* Z-axis expressed in *camera* coordinates. You want to invert it so you get the matrix that goes from camera space to world space; then its third column will be the *camera* Z-axis expressed in *world* coordinates, which is what you want.

Since the upper 3x3 part of the view matrix is rotation only, its inverse is its transpose. So you can extract the vector you want by using components 2, 6, 10 instead of 8, 9, 10.

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


title: Scrolling Box2D DebugDraw

text:
# Question
Title: Scrolling Box2D DebugDraw
I'm developing a game using Box2D (javascript implementation - Box2DWeb), and I would like to know how I can pan the debug draw. I know the usual answer is - don't use debug draw, it's just for debugging. I'm not, however not all my objects are on the same screen, and i'd like to see where they are in the physics representation.

**How can I pan the debug drawing?**

As you can see the debug draw stuff, is show on the top left, but it only shows a small part of the world.

Here is an example of what I mean:
http://onedayitwillmake.com/ChuClone/

The game is open source, If you'd like to poke through and note something that perhaps i'm doing something that is obviously wrong:
https://github.com/onedayitwillmake/ChuClone

Here's my **hacky way** that I'm using now to scroll the b2DebugDraw view, in which I added a property offsetX and offsetY into b2DebugDraw

# Answer
> 1 votes
I've asked this question myself, and the answer is quite simple, just translate the debug draw context.

```
        debugDraw.SetDrawScale( camera.scaleWorldToScreen ); //My camera is doing the worldToScreen/screenToWorld conversion, so it has the scales.

        debugCtx.save();
        debugCtx.clearRect( 0, 0, debugCanvas.width, debugCanvas.height );
        debugCtx.translate( camera.position[0], camera.position[1] ); //translate it to the camera position
        debugCtx.scale( 1, -1 ); //invert the y coord.
        world.DrawDebugData();
        debugCtx.restore();

```

# Answer
> 1 votes
I'm not sure if this applies to your case or not, but c++ implementation of box2d ask for some class to do rending jobs. so you have to provide box2d with some class telling him how to draw objects. you can manually pad all the given box2d data in your debugdraw class.

---
Tags: javascript, box2d, debugging
---