# Question
Title: How do I perform an xBR or hqx filter in XNA?
I'd like to render my game scaled up with one of the hqx filters (hq2x, hq3x or hq4x) or an xBR filter in a shader.

How can I do this in XNA 4.0 and SM3?

*Side note: this question has been heavily edited to become what it is now.*

# Answer
I got this working. It does not use the hqx filter, it uses the xBR filter (which I prefer). For me, this is not a problem. If you require the hqx filter then you'll want to convert the .cg files into their appropriate XNA equivalent.

For completeness and searching reasons, I will be editing the question to be more concise and then posting all the relevant information to answer the question here.

---

## Step 1 : Game Code Setup

First off you'll most likely want to setup a render target where you draw your game at a 1:1 scale and then render the filter.

```
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace xbr
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {

        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        RenderTarget2D renderTarget;
        Effect xbrEffect;
        Matrix projection;
        Matrix halfPixelOffset = Matrix.CreateTranslation(-0.5f, -0.5f, 0);
        Texture2D pretend240x160Scene;

        // the bounds of your 1:1 scene
        Rectangle renderBounds = new Rectangle(0, 0, 240, 160);

        // the bounds of your output scene (same w:h ratio)
        Rectangle outputBounds = new Rectangle(0, 0, 720, 480);

        public Game1()
        {
           base.Content.RootDirectory = "Content";

           this.graphics = new GraphicsDeviceManager(this);
           this.graphics.PreferredBackBufferWidth = outputBounds.Width;
           this.graphics.PreferredBackBufferHeight = outputBounds.Height;
        }

        /// <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.
            this.spriteBatch = new SpriteBatch(base.GraphicsDevice);
            this.xbrEffect = Content.Load<Effect>("xbr");

            // a fake scene that is a 240x160 image
            this.pretend240x160Scene = base.Content.Load<Texture2D>("240x160Scene");
            this.renderTarget = new RenderTarget2D(base.GraphicsDevice, this.renderBounds.Width, this.renderBounds.Height);

            // default vertex matrix for the vertex method
            this.projection = Matrix.CreateOrthographicOffCenter(0, this.outputBounds.Width, this.outputBounds.Height, 0, 0, 1);

            // set the values of this effect, should only have to do this once
            this.xbrEffect.Parameters["matrixTransform"].SetValue(halfPixelOffset * projection);
            this.xbrEffect.Parameters["textureSize"].SetValue(new float[] { renderBounds.Width, renderBounds.Height });
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
        }

        /// <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)
        {
            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)
        {
            base.GraphicsDevice.Clear(Color.CornflowerBlue);
            base.GraphicsDevice.SetRenderTarget(this.renderTarget);

            // draw your scene here scaled 1:1. for now I'll just draw
            // my fake 240x160 texture
            spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.NonPremultiplied,
                              SamplerState.PointClamp, null, null);

            spriteBatch.Draw(this.pretend240x160Scene, this.renderBounds, this.renderBounds, Color.White);

            spriteBatch.End();

            // now we'll draw to the back buffer
            base.GraphicsDevice.SetRenderTarget(null);

            // this renders the effect
            spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.NonPremultiplied,
                              SamplerState.PointClamp, null, null, this.xbrEffect);

            spriteBatch.Draw(this.renderTarget, this.outputBounds, this.renderBounds, Color.White);
            spriteBatch.End();

            base.Draw(gameTime);
        }
    }
}

```

## Step 2 : Effect File

The following is the XNA compatible effect file to perform the xBR filter.

```
// all identified optimizations have been amalgamated into this file
float2 textureSize;
float4x4 matrixTransform;

const static float coef = 2.0;
const static float3 yuv_weighted = float3(14.352, 28.176, 5.472);

sampler decal : register(s0);

float4 df(float4 A, float4 B)
{
    return abs(A - B);
}

float4 weighted_distance(float4 a, float4 b, float4 c, float4 d,
                         float4 e, float4 f, float4 g, float4 h)
{
    return (df(a, b) + df(a, c) + df(d, e) + df(d, f) + 4.0 * df(g, h));
}

float4 main_vertex(inout float4 col0 : COLOR0, inout float2 tex0 : TEXCOORD0,
                   inout float4 pos0 : POSITION0) : TEXCOORD1
{
    float2 ps = 1.0 / textureSize;

    pos0 = mul(pos0, matrixTransform);

    return float4(ps.x, 0, 0, ps.y);
}

float4 main_fragment(float4 pos0 : POSITION0, float2 tex0 : TEXCOORD0,
                     float4 tex1 : TEXCOORD1) : COLOR0
{
    bool4 edr, edr_left, edr_up, px; // px = pixel, edr = edge detection rule
    bool4 ir_lv1, ir_lv2_left, ir_lv2_up;
    bool4 nc; // new_color
    bool4 fx, fx_left, fx_up; // inequations of straight lines.

    float2 fp = frac(tex0 * textureSize);
    float2 dx = tex1.xy;
    float2 dy = tex1.zw;

    float3 A  = tex2D(decal, tex0 - dx - dy).xyz;
    float3 B  = tex2D(decal, tex0 - dy).xyz;
    float3 C  = tex2D(decal, tex0 + dx - dy).xyz;
    float3 D  = tex2D(decal, tex0 - dx).xyz;
    float3 E  = tex2D(decal, tex0).xyz;
    float3 F  = tex2D(decal, tex0 + dx).xyz;
    float3 G  = tex2D(decal, tex0 - dx + dy).xyz;
    float3 H  = tex2D(decal, tex0 + dy).xyz;
    float3 I  = tex2D(decal, tex0 + dx + dy).xyz;
    float3 A1 = tex2D(decal, tex0 - dx - 2.0 * dy).xyz;
    float3 C1 = tex2D(decal, tex0 + dx - 2.0 * dy).xyz;
    float3 A0 = tex2D(decal, tex0 - 2.0 * dx - dy).xyz;
    float3 G0 = tex2D(decal, tex0 - 2.0 * dx + dy).xyz;
    float3 C4 = tex2D(decal, tex0 + 2.0 * dx - dy).xyz;
    float3 I4 = tex2D(decal, tex0 + 2.0 * dx + dy).xyz;
    float3 G5 = tex2D(decal, tex0 - dx + 2.0 * dy).xyz;
    float3 I5 = tex2D(decal, tex0 + dx + 2.0 * dy).xyz;
    float3 B1 = tex2D(decal, tex0 - 2.0 * dy).xyz;
    float3 D0 = tex2D(decal, tex0 - 2.0 * dx).xyz;
    float3 H5 = tex2D(decal, tex0 + 2.0 * dy).xyz;
    float3 F4 = tex2D(decal, tex0 + 2.0 * dx).xyz;

    float4 b = mul(float4x3(B, D, H, F), yuv_weighted);
    float4 c = mul(float4x3(C, A, G, I), yuv_weighted);
    float4 e = mul(float4x3(E, E, E, E), yuv_weighted);
    float4 d = b.yzwx;
    float4 f = b.wxyz;
    float4 g = c.zwxy;
    float4 h = b.zwxy;
    float4 i = c.wxyz;

    float4 i4 = mul(float4x3(I4, C1, A0, G5), yuv_weighted);
    float4 i5 = mul(float4x3(I5, C4, A1, G0), yuv_weighted);
    float4 h5 = mul(float4x3(H5, F4, B1, D0), yuv_weighted);
    float4 f4 = h5.yzwx;

    float4 Ao = float4(1.0, -1.0, -1.0, 1.0);
    float4 Bo = float4(1.0, 1.0, -1.0, -1.0);
    float4 Co = float4(1.5, 0.5, -0.5, 0.5);
    float4 Ax = float4(1.0, -1.0, -1.0, 1.0);
    float4 Bx = float4(0.5, 2.0, -0.5, -2.0);
    float4 Cx = float4(1.0, 1.0, -0.5, 0.0);
    float4 Ay = float4(1.0, -1.0, -1.0, 1.0);
    float4 By = float4(2.0, 0.5, -2.0, -0.5);
    float4 Cy = float4(2.0, 0.0, -1.0, 0.5);

    // These inequations define the line below which interpolation occurs.
    fx.x = (Ao.x * fp.y + Bo.x * fp.x > Co.x);
    fx.y = (Ao.y * fp.y + Bo.y * fp.x > Co.y);
    fx.z = (Ao.z * fp.y + Bo.z * fp.x > Co.z);
    fx.w = (Ao.w * fp.y + Bo.w * fp.x > Co.w);

    fx_left.x = (Ax.x * fp.y + Bx.x * fp.x > Cx.x);
    fx_left.y = (Ax.y * fp.y + Bx.y * fp.x > Cx.y);
    fx_left.z = (Ax.z * fp.y + Bx.z * fp.x > Cx.z);
    fx_left.w = (Ax.w * fp.y + Bx.w * fp.x > Cx.w);

    fx_up.x = (Ay.x * fp.y + By.x * fp.x > Cy.x);
    fx_up.y = (Ay.y * fp.y + By.y * fp.x > Cy.y);
    fx_up.z = (Ay.z * fp.y + By.z * fp.x > Cy.z);
    fx_up.w = (Ay.w * fp.y + By.w * fp.x > Cy.w);

    ir_lv1      = ((e != f) && (e != h));
    ir_lv2_left = ((e != g) && (d != g));
    ir_lv2_up   = ((e != c) && (b != c));

    float4 w1 = weighted_distance(e, c, g, i, h5, f4, h, f);
    float4 w2 = weighted_distance(h, d, i5, f, i4, b, e, i);
    float4 df_fg = df(f, g);
    float4 df_hc = df(h, c);
    float4 t1 = (coef * df_fg);
    float4 t2 = df_hc;
    float4 t3 = df_fg;
    float4 t4 = (coef * df_hc);

    edr      = (w1 < w2)  && ir_lv1;
    edr_left = (t1 <= t2) && ir_lv2_left;
    edr_up   = (t4 <= t3) && ir_lv2_up;

    nc = (edr && (fx || edr_left && fx_left || edr_up && fx_up));

    t1 = df(e, f);
    t2 = df(e, h);
    px = t1 <= t2;

    float3 res = nc.x ? px.x ? F : H :
                 nc.y ? px.y ? B : F :
                 nc.z ? px.z ? D : B :
                 nc.w ? px.w ? H : D : E;

    return float4(res.xyz, 1.0);
}

technique T0
{
    pass P0
    {
        VertexShader = compile vs_3_0 main_vertex();
        PixelShader = compile ps_3_0 main_fragment();
    }
}

```

## Results

The texture that I used for the 240x160 render:

The output from running the game:

## Sources

The .cg file that I converted into XNA compatible came from here. So credits go to them for writing it.
> 6 votes

# Answer
You can reduce the instruction count by using vector operations: e.g. instead of

```
edr = bool4((w1.x < w2.x) && ir_lv1.x,
            (w1.y < w2.y) && ir_lv1.y,
            (w1.z < w2.z) && ir_lv1.z,
            (w1.w < w2.w) && ir_lv1.w);

```

you can write

```
edr = (w1 < w2) && ir_lv1;

```

Operators in HLSL can be applied to vectors, even logical ones like `&&` to two `bool3` values. These operators will perform the operation componentwise.

# Shader code

```
float2 texture_size;
float4x4 matrixTransform;

const static float coef = 2.0;
const static float3 yuv_weighted = float3(14.352, 28.176, 5.472);

sampler decal : register(s0);

float4 df(float4 A, float4 B)
{

    // begin optimization: reduction of 42 instruction slots
    float4 result = float4(A.x - B.x, A.y - B.y, A.z - B.z, A.w - B.w);

    return abs(result);
    // end optimization

    /* old code

    //return float4(abs(A.x - B.x), abs(A.y - B.y), abs(A.z - B.z), abs(A.w - B.w));
    */
}

float4 weighted_distance(float4 a, float4 b, float4 c, float4 d, float4 e, float4 f, float4 g, float4 h)
{
    return (df(a, b) + df(a, c) + df(d, e) + df(d, f) + 4.0 * df(g, h));
}

float4 main_vertex(inout float2 texCoord : TEXCOORD0, inout float4 position : SV_Position) : TEXCOORD1
{
    float2 ps = float2(1.0 / texture_size.x, 1.0 / texture_size.y);
    float4 t1;

    t1.xy = float2(ps.x, 0); // F
    t1.zw = float2(0, ps.y); // H

    position = mul(position, matrixTransform);

    return t1;
}

/*    FRAGMENT SHADER    */
float4 main_fragment(float4 p : POSITION0, float2 tex0 : TEXCOORD0, float4 tex1 : TEXCOORD1) : COLOR0
{
    bool4 edr, edr_left, edr_up, px; // px = pixel, edr = edge detection rule
    bool4 ir_lv1, ir_lv2_left, ir_lv2_up;
    bool4 nc; // new_color
    bool4 fx, fx_left, fx_up; // inequations of straight lines.

    float2 fp = frac(tex0 * texture_size);
    float2 dx = tex1.xy;
    float2 dy = tex1.zw;

    float3 A = tex2D(decal, tex0 - dx - dy).xyz;
    float3 B = tex2D(decal, tex0 - dy).xyz;
    float3 C = tex2D(decal, tex0 + dx - dy).xyz;
    float3 D = tex2D(decal, tex0 - dx).xyz;
    float3 E = tex2D(decal, tex0).xyz;
    float3 F = tex2D(decal, tex0 + dx).xyz;
    float3 G = tex2D(decal, tex0 - dx + dy).xyz;
    float3 H = tex2D(decal, tex0 + dy).xyz;
    float3 I = tex2D(decal, tex0 + dx + dy).xyz;
    float3 A1 = tex2D(decal, tex0 - dx - 2.0*dy).xyz;
    float3 C1 = tex2D(decal, tex0 + dx - 2.0*dy).xyz;
    float3 A0 = tex2D(decal, tex0 - 2.0*dx - dy).xyz;
    float3 G0 = tex2D(decal, tex0 - 2.0*dx + dy).xyz;
    float3 C4 = tex2D(decal, tex0 + 2.0*dx - dy).xyz;
    float3 I4 = tex2D(decal, tex0 + 2.0*dx + dy).xyz;
    float3 G5 = tex2D(decal, tex0 - dx + 2.0*dy).xyz;
    float3 I5 = tex2D(decal, tex0 + dx + 2.0*dy).xyz;
    float3 B1 = tex2D(decal, tex0 - 2.0*dy).xyz;
    float3 D0 = tex2D(decal, tex0 - 2.0*dx).xyz;
    float3 H5 = tex2D(decal, tex0 + 2.0*dy).xyz;
    float3 F4 = tex2D(decal, tex0 + 2.0*dx).xyz;

    float4 b = mul(float4x3(B, D, H, F), yuv_weighted);
    float4 c = mul(float4x3(C, A, G, I), yuv_weighted);
    float4 e = mul(float4x3(E, E, E, E), yuv_weighted);
    float4 d = b.yzwx;
    float4 f = b.wxyz;
    float4 g = c.zwxy;
    float4 h = b.zwxy;
    float4 i = c.wxyz;

    float4 i4 = mul(float4x3(I4, C1, A0, G5), yuv_weighted);
    float4 i5 = mul(float4x3(I5, C4, A1, G0), yuv_weighted);
    float4 h5 = mul(float4x3(H5, F4, B1, D0), yuv_weighted);
    float4 f4 = h5.yzwx;

    float4 Ao = float4(1.0, -1.0, -1.0, 1.0);
    float4 Bo = float4(1.0, 1.0, -1.0, -1.0);
    float4 Co = float4(1.5, 0.5, -0.5, 0.5);
    float4 Ax = float4(1.0, -1.0, -1.0, 1.0);
    float4 Bx = float4(0.5, 2.0, -0.5, -2.0);
    float4 Cx = float4(1.0, 1.0, -0.5, 0.0);
    float4 Ay = float4(1.0, -1.0, -1.0, 1.0);
    float4 By = float4(2.0, 0.5, -2.0, -0.5);
    float4 Cy = float4(2.0, 0.0, -1.0, 0.5);

    // These inequations define the line below which interpolation occurs.
    fx.x = (Ao.x*fp.y + Bo.x*fp.x > Co.x);
    fx_left.x = (Ax.x*fp.y + Bx.x*fp.x > Cx.x);
    fx_up.x = (Ay.x*fp.y + By.x*fp.x > Cy.x);

    fx.y = (Ao.y*fp.y + Bo.y*fp.x > Co.y);
    fx_left.y = (Ax.y*fp.y + Bx.y*fp.x > Cx.y);
    fx_up.y = (Ay.y*fp.y + By.y*fp.x > Cy.y);

    fx.z = (Ao.z*fp.y + Bo.z*fp.x > Co.z);
    fx_left.z = (Ax.z*fp.y + Bx.z*fp.x > Cx.z);
    fx_up.z = (Ay.z*fp.y + By.z*fp.x > Cy.z);

    fx.w = (Ao.w*fp.y + Bo.w*fp.x > Co.w);
    fx_left.w = (Ax.w*fp.y + Bx.w*fp.x > Cx.w);
    fx_up.w = (Ay.w*fp.y + By.w*fp.x > Cy.w);

    //ir_lv1.x = ((e.x != f.x) && (e.x != h.x));
    //ir_lv1.y = ((e.y != f.y) && (e.y != h.y));
    //ir_lv1.z = ((e.z != f.z) && (e.z != h.z));
    //ir_lv1.w = ((e.w != f.w) && (e.w != h.w));
    ir_lv1 = ((e != f) && (e != h));

    //ir_lv2_left.x = ((e.x != g.x) && (d.x != g.x));
    //ir_lv2_left.y = ((e.y != g.y) && (d.y != g.y));
    //ir_lv2_left.z = ((e.z != g.z) && (d.z != g.z));
    //ir_lv2_left.w = ((e.w != g.w) && (d.w != g.w));
    ir_lv2_left = ((e != g) && (d != g));

    //ir_lv2_up.x = ((e.x != c.x) && (b.x != c.x));
    //ir_lv2_up.y = ((e.y != c.y) && (b.y != c.y));
    //ir_lv2_up.z = ((e.z != c.z) && (b.z != c.z));
    //ir_lv2_up.w = ((e.w != c.w) && (b.w != c.w));
    ir_lv2_up = ((e != c) && (b != c));

    float4 w1 = weighted_distance(e, c, g, i, h5, f4, h, f);
    float4 w2 = weighted_distance(h, d, i5, f, i4, b, e, i);

    // begin optimization: reduction of 6 instruction slots
    float4 df_fg = df(f, g);
    float4 df_hc = df(h, c);
    // end optimization

    float4 t1 = (coef * df_fg);
    float4 t2 = df_hc;
    float4 t3 = df_fg;
    float4 t4 = (coef * df_hc);

    //edr = bool4((w1.x < w2.x) && ir_lv1.x,
    //            (w1.y < w2.y) && ir_lv1.y,
    //            (w1.z < w2.z) && ir_lv1.z,
    //            (w1.w < w2.w) && ir_lv1.w);
    edr = (w1 < w2) && ir_lv1;

    //edr_left = bool4((t1.x <= t2.x) && ir_lv2_left.x,
    //                 (t1.y <= t2.y) && ir_lv2_left.y,
    //                 (t1.z <= t2.z) && ir_lv2_left.z,
    //                 (t1.w <= t2.w) && ir_lv2_left.w);
    edr_left = (t1 <= t2) && ir_lv2_left;

    //edr_up = bool4((t4.x <= t3.x) && ir_lv2_up.x,
    //               (t4.y <= t3.y) && ir_lv2_up.y,
    //               (t4.z <= t3.z) && ir_lv2_up.z,
    //               (t4.w <= t3.w) && ir_lv2_up.w);
    edr_up = (t4 <= t3) && ir_lv2_up;

    //nc.x = (edr.x && (fx.x || edr_left.x && fx_left.x || edr_up.x && fx_up.x));
    //nc.y = (edr.y && (fx.y || edr_left.y && fx_left.y || edr_up.y && fx_up.y));
    //nc.z = (edr.z && (fx.z || edr_left.z && fx_left.z || edr_up.z && fx_up.z));
    //nc.w = (edr.w && (fx.w || edr_left.w && fx_left.w || edr_up.w && fx_up.w));
    nc = (edr && (fx || edr_left && fx_left || edr_up && fx_up));

    // to actually compile this shader, uncomment the following line
    // which reduces the instruction count to under 512
    //nc.zw = (float2)0;

    t1 = df(e, f);
    t2 = df(e, h);

    //px = bool4(t1.x <= t2.x,
    //           t1.y <= t2.y,
    //           t1.z <= t2.z,
    //           t1.w <= t2.w);
    px = t1 <= t2;

    float3 res = nc.x ? px.x ? F : H : nc.y ? px.y ? B : F : nc.z ? px.z ? D : B : nc.w ? px.w ? H : D : E;

    return float4(res.x, res.y, res.z, 1.0);
}

technique mainTech
{
    pass mainPass
    {
        VertexShader = compile vs_3_0 main_vertex();
        PixelShader = compile ps_3_0 main_fragment();
    }
}

```

# Pictures

The original image by Redshrike has been scaled up by a factor of 4.

* Point sampling

* xBR
> 6 votes

---
Tags: xna, 2d, shaders, pixel, scale
---


# Question
Title: How do I sample a Depth/Stencil Texture in HLSL?
I am shadow mapping in Direct3D 9. I'm trying to avoid rendering depth to a 32-bit render target. So, I've created a depth/stencil texture( a texture w/usage Depth/Stencil ). When I render I do this:

```
//device
IDirect3DDevice9 *pd3dDevice = GetDevice();

// set an rt the same size as the depth/stencil texture(needs attention...this render target will not be rendered to)
pd3dDevice->SetRenderTarget(0, GetShadowMapRT());

// set the shadow map depth/stencil texture surface
pd3dDevice->SetDepthStencilSurface(GetShadowMapDSSurface());

pd3dDevice.SetStreamSource(0, GDEOctree.Geometry,
                Constants.OctreeVertexSize * GDEOctree.StaticGeometryVertexCount, 12);

// set vertex format
pd3dDevice.VertexFormat = SlimDX.Direct3D9.VertexFormat.Position;

// set indices
pd3dDevice.Indices = GDEOctree.ShadowCasterIndices;

// set render states
DeviceManager.SetRenderState(RenderState.ZEnable, 1);
DeviceManager.SetRenderState(RenderState.ZWriteEnable, 1);
DeviceManager.SetRenderState(RenderState.ZFunc, (int)Compare.LessEqual);
DeviceManager.SetRenderState(RenderState.CullMode, (int)Cull.Counterclockwise);
DeviceManager.SetRenderState(RenderState.StencilEnable, 0);
DeviceManager.SetRenderState(RenderState.AlphaBlendEnable, 0);
DeviceManager.SetRenderState(RenderState.ColorWriteEnable, 0);

// draw shadow casting geometry
...

// get the effect
ID3DXEffect *pFX = GetFX();

// set the shadow map depth/stencil texture
pFX->SetTexture(GetShadowMapDSTexture());

// in pixel shader sample shadow map...
?

```

The problem is that the depth/stencil texture is a D24SX format...How do I sample from a texture of this format?

My original attempt which of course will not work:

```
tex2D(g_SamplerShadowMap, vShadowMapUV);

```

I read a post here that says:

> When reading from the texture, one extra component in texture coordinates will be the depth to compare with.

Or, how do I convert the color returned from the sampler code above to a single floating point value? The above code will return a 4-component vector but depth should be one value for comparison.

EDIT:

Below is the vertex shader for the shadow map pass...I do not compile a pixel shader for the shadow map pass because color is not written...only depth.

```
//--------------------------------------------------------------//
// ShadowMap Pass
//--------------------------------------------------------------//
void VS_ShadowMap( in float4 Position : POSITION0,
                    out float4 oPos : POSITION0 )
{
    // position of geometry in the shadow emitting light's clip space
    oPos = mul(mul(Position, mW), g_mShadowViewProjection);
}

technique DeferredShading
{
    pass ShadowMap
    {
        VertexShader = compile vs_3_0 VS_ShadowMap();
        PixelShader = NULL;
    }
}

```

# Answer
> 2 votes
There are two main ways to do this.

First way is to do exactly what you're trying to avoid doing, and use a render target. This is the way used by the Shadow Mapping sample for D3D9 in the old DirectX SDK, although it needn't be 32-bit (D3DFMT\_R16F may well be sufficient). As a possible optimization you could use a NULL depth/stencil target, enable blending, and use either D3DBLENDOP\_MIN or D3DBLENDOP\_MAX (your mileage may vary).

The second way is to use a Depth Buffer as Texture GPU Hack although be aware that hardware support may be patchy depending on what degree of older hardware you want to support - INTZ looks to be the only format supported across all 3 vendors:

> INTZ is for recent (DX10+) hardware. With recent drivers, all three major IHVs expose this. According to ATI, it also allows using stencil buffer while rendering. Also allows reading from depth texture while it’s still being used for depth testing (but not depth writing). Looks like this applies to NV & Intel parts as well.

# Answer
> 1 votes
`tex2D(g_SamplerShadowMap, vShadowMapUV).r` should get you the depth value, in case your sampler, and texture are set up and bound correctly.

---
Tags: hlsl, directx9, depth-buffer, sampler-state
---


title: Ray casting problem using JOGL

text:
# Question
Title: Ray casting problem using JOGL
I'm trying to port an old perfectly functioning ray casting implementation from my lwjgl project (FF pipeline) to a new project using JOGL and shaders. My problem is that my ray no longer intersects the model at the mouse location although the ray always passes through the mouse location (see image). Further to this, as soon as I apply any transformation to the model - rotation, movement along x,y or z - the ray is completely off and doesn't pass through the mouse location in any case. Would anyone know why this would be happening? As far as I can tell the code is doing exactly what the old project did. I am currently using FloatUtil.mapWinToRay() although I have also tried FloatUtil.mapWinToObjCoords() with the same results.

**Function that creates the testing ray:** I use nearVector and farVector to draw the ray.

```
public Ray getPickingRay(float[] modelMatrix,
                                float[] projMatrix,
                                int[] viewport,
                                float winx,
                                float winy
                            ) {

    // first the near vector
    float[] mat4Tmp1 = new float[16];
    float[] mat4Tmp2 = new float[16];
    float[] vec4Tmp2 = new float[4];
    Ray ray = new Ray();
    FloatUtil.mapWinToRay(winx, winy, 0, 1,
            modelMatrix, 0,
            projMatrix, 0,
            viewport, 0,
            ray,
            mat4Tmp1, mat4Tmp2, vec4Tmp2);

    nearVector[0] = ray.orig[0];
    nearVector[1] = ray.orig[1];
    nearVector[2] = ray.orig[2];
    farVector[0] = ray.dir[0] * 100;
    farVector[1] = ray.dir[1] * 100;
    farVector[2] = ray.dir[2] * 100;

    return ray;
}

```

**Function that updates the ray position:**

```
private void updateLineData(GL4 gl) throws Exception{

   //container for two ray vertices
   float[] all = {0,0,0,0,0,0};

  //apply same translation to ray as is applied to entire model.
  view3 = translate(view2, transX, transY, transZ);
  //pass the matrix to the line shader
  shaderLine.setUniform(iMVPLine, multiply(projection,  view3),
         Shade.MatDataType.MAT4);

  if (updatePos == true){
    updatePos = false;

    int[] viewport = {0,0,screenWidth,screenHeight};
    float[] dest = new float[3];

     Ray ray = pick.getPickingRay(view3,
            projection,
             viewport,
            mx, my);

    float[] front = pick.nearVector;
    float[] back = pick.farVector;

    all[0] = front[0];
    all[1] = -front[1];
    all[2] = -front[2];
    all[3] = back[0];
    all[4] = -back[1];
    all[5] = -back[2];
    whole.updateLine(gl, all);
  }

}

```

**Update the line data buffer:**

```
  public void updateLine(GL4 gl, float[] pos)
  {

      for (int i=0;i<pos.length; i++){
          vertLineBuffer[i] = pos[i];
      }
      //populate the color buffer
      FloatBuffer fbData = Buffers.newDirectFloatBuffer(vertLineBuffer);

      gl.glBindBuffer(GL4.GL_ARRAY_BUFFER, vboLineHandles[VERTICES_LINE_IDX]);
      gl.glBufferSubData(GL4.GL_ARRAY_BUFFER, 0, fbData.capacity() * 4, fbData);
      fbData.clear(); //don't need this anymore

  }

```

A final note/clue is that as I click closer to the centre of the screen the intersection point between the ray and the model gets closer to the mousepointer. It is almost as if the ray always wants to point to 0,0,0. My expectation would be that I wouldn't be able to see the ray when it is drawn as it would be following my line of sight thru the model. Then when I translate the view I would be able to see it as I would be looking at a slight angle to the new ray. Currently when the ray draws I can see it right away as it draws between near the centre of the screen and out in the direction of the mousepointer. Any help/hints or tips would be greatly appreciated.

# Answer
> 1 votes
The basic cause of the problem was that my value for screenY (2D location of mouseclick on Y-axis) was incorrect and so passing it to any valid picking ray function returned invalid results. My old working project got the mouse position values from the org.lwjgl.input.Mouse class whereas the new project is using java.awt.event.MouseListener. The lwjgl implementation of the click event resolved the Y position to the correct value (0,0 at bottom left corner). java.awt.event.MouseListener returns (0, screenHeight) at bottom left. You have to modify the Y simply by passing (screenHeight - mouseY) instead of just mouseY.
The following routine will get the near and far vertices for a picking ray using JOGL:

```
public float[] getPickingVector(float[] camera,
                                float[] projection,
                                int[] viewport,
                                float winX,
                                float winY) throws Exception {

    float[] mat4Tmp1 = new float[16];
    float[] mat4Tmp2 = new float[16];

    FloatUtil.mapWinToObjCoords(winX, winY, 0, camera, 0,
            projection, 0,
            viewport, 0,
            nearVector, 0,
            mat4Tmp1, mat4Tmp2);

    FloatUtil.mapWinToObjCoords(winX, winY, 1, modelview, 0,
            projection, 0,
            viewport, 0,
            farVector, 0,
            mat4Tmp1, mat4Tmp2);

}

```

---
Tags: java, glsl, raycasting, jogl
---


title: OpenGL Depth Test Errors

text:
# Question
Title: OpenGL Depth Test Errors
I've been working on this problem for a while now. My problem is that the sphere in the top image, is under-lapping the plane which should have a lower Z value. Although, when depth testing is disabled, it is resolved. But it favors draw order over actual fragment depth value. I was changing the depth mask out of desperation. ;)

```
GL11.glDisable(GL11.GL_DEPTH_TEST);
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
rootObject.render(ambient);

GL11.glBlendFunc(GL11.GL_ONE, GL11.GL_ONE);
GL11.glDepthMask(false);
GL11.glDepthFunc(GL11.GL_EQUAL);

for(int i = 0; i < lights.size(); i++){
    lights.get(i).use();
    rootObject.render(lights.get(i).getProgram());
}

GL11.glDepthFunc(GL11.GL_LESS);
GL11.glDepthMask(true);

```

-- Screenies:

```
GL11.glEnable(GL11.GL_DEPTH_TEST);

```

```
GL11.glDisable(GL11.GL_DEPTH_TEST);

```

# Answer
Turns out, the problem was my projection matrix. I found this error when I was switching vector math libraries. And I forgot transformations in javax's vecmath are row-major order. So I switched the near and far planes, and it worked perfectly.

```
(0.1f, 1000f) to (1000f, 0.1f)

```
> 0 votes

# Answer
From the looks of it, you need to throw `glDepthMask` out.

```
GL11.glEnable(GL11.GL_DEPTH_TEST); // Enable depth testing
GL11.glEnable(GL11.GL_BLEND); // Enable blending
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); // Common blending formula for transparency
rootObject.render(ambient); // Background

GL11.glBlendFunc(GL11.GL_ONE, GL11.GL_ONE); // This is uncommon blending formula ..
GL11.glDepthFunc(GL11.GL_LEQUAL); //<-- Less or Equal = LEqual

for(int i = 0; i < lights.size(); i++){
    lights.get(i).use();
    rootObject.render(lights.get(i).getProgram()); // spheres?
}

```
> 0 votes

---
Tags: opengl, depth
---


title: Where do I store project data in Unity?

text:
# Question
Title: Where do I store project data in Unity?
In Unity the PhysicsManager has project data. It exists across scenes but its data is unique to each project. If it make my own CustomManager, where/how to I store its data so that it's associated with the project, not a particular scene.

Most of the examples show storing data in properties in components on GameObjects but the PhysicsManager is not a component of a GameObject as far as I can tell. I want my custom manager to do whatever PhysicsManager is doing to store its data.

Any examples, pointers, links to articles?

# Answer
> 1 votes
Depending on the amount of data you have to store PlayerPrefs should be perfect for that. If player prefs is not enough or does not suits your needs you can store project custom data in a text file (personally i place it in resources but it could be anywhere) and read it when needed

for ex : i made a plugin for unity to define different sizes atlases path, and everything is stored in a textfile where i have some JSON arrays, and when i load my scene i read my file and forget about it

---
Tags: unity
---


title: Triangular Mesh Collision/ Resolution

text:
# Question
Title: Triangular Mesh Collision/ Resolution
I've been trying some different approaches for collision detection and now I want to try to implement simple Mesh-Mesh collision detection for triangular meshes. I'm wondering if I'm on the right track, or if I'm missing something critical.

My general idea for collision detection involves a moving object with no rotation, against stationary objects. I also want the moving objects to slide across the surface/ edge of stationary objects in which they collide. The algorithm is:

> * Make a list of all the stationary objects which are in range of the moving object origin.
> * Add to the list of all the stationary objects which are in range of the displaced moving object
> * Sort the list by shortest distance to the moving object origin.
> * Iterate through the list and detect collisions between the displaced moving object and stationary object
>     + find the shortest distance in which a vertex of the moving object passes through a triangle of the stationary object (or vice versa).
>     + find the shortest distance in which an edge of the moving object passes through an edge of the stationary object.
>     + If shortest distance was vertex
>         - Project the displacement across the broken triangle plane and locate the end point.
>         - Recalculate the displacement using this end point and the origin
>         - Restart iterations
>     + If shortest distance was vertex
>         - Project the displacement across the plane created by these two edges at the point of contact. Find the end point of this projection
>         - Recalculate the displacement using this end point and the origin
>         - Restart iterations
>     + If no collisions found then continue iterating
> * Apply final displacement to position of the moving object

The reason the iteration is repeated after a collision is found is to avoid the case where the resolution causes a new collision in previously checked objects.

---

To get the vertex and edge intersections I have made two equations, both of which have `M` as the displacement I wish to apply to the moving object.

All capital variables are `Vec3`'s, Two capitals next to eachother are deltas `AB == B - A`. lowercase variables are scalars. `Mat3`'s take `Vec3`'s as columns

This is my equation for testing a moving vertex against a stationary triangle:

```
//Ray:
P = M*t + Q
//Trianlge:
P = A + AB*u + AC*v
//Ray-Triangle Intersect:
M*t + Q = P = A + AB*u + AC*v
AQ = -M*t + AB*u + AC*v
AQ = Mat3(-M, AB, AC*v) * Vec3(t, u, v)

Vec3(t, u, v) = Mat3(-M, AB, AC*v)^-1 * AQ

```

`t, u, v` must all be `[0,1]`, and `u + v <= 1` for a collision to occur

This is my equation for testing a moving edge against a stationary edge:

```
//Moving Ray:
P = AB*u + M*t + A
//Stationary Ray
P = CD*v + C
//Moving Ray - Ray Intersect
AB*u + M*t + A = CD*v + C
AC = M*t + AB*u - CD*v
AC = Mat3(M, AB, -CD) * Vec3(t, u, v)

Vec3(t, u, v) = Mat3(M, AB, DC)^-1 * AC

```

`t, u, v` must all be `[0,1]` for a collision to occur

---

So how does this look?

# Answer
> 1 votes
Are you on track, yes no maybe.

Figuring collision sets (moving vs. stationary) is helpful, but will not bring you far. If you implement a general NxM solution **that is efficient** you may actually get more bang for your buck.

For starters you should separate your collision detection from your collision response. This makes sense since you may want to collide different shapes, but the actual response is the same.

For the collision repose you implement a spring system (rigid body physics?). If the moving body overlaps with a static object (any body overlaps with any other body), you apply a force along surface normal to separate the two again.

The collision detection on the other hand is quite involved. Before we look at the nitty gritty details, we need to talk about early discarding collision detection. Here you want bounding boxes or bounding spheres. Spheres are really sexy, since they are dirt cheep to test collision on (`length(o1 - o1) < r1 + r2`). If the bounding volumes do not intersect, no need to test collision on the meshes.

If you want to handle a really large amount of objects it may be advisable to additionally use a special organisation structure, such as an octtree. The even prevents testing the bounding volumes of objects that are not even in the same general area.

Now that we have determined that the bounding volumes intersect, we can start to test meshes. In the naive approach you basically test each triangle with each other. This can be optimized further, such as storing spatially organized lists, but that may be overkill.

The actual triangle / triangle intersection is quite well understood. For example this algorithm is quite efficient. The basic approach is to intersect the two planes the triangles are in and then looking if the points where the triangles "start" and "end" on the line overlap.

I have not extensively checked your math but it looks sane at first glance.

Then again, why are you not using a physics library for this, like ODE or Bullet? If you absolutely do not want to use the ridgid body physics implemented there you can only use collision subsystem.

---
Tags: collision-detection, algorithm, collision-resolution
---


# Question
Title: How can I cycle through sprites when the player touches some UI element?
```
    if(Input.GetKey("y")){
        gameObject.GetComponent<SpriteRenderer>().sprite = Characters[0];

    }
    if(Input.GetKey("u")){
        gameObject.GetComponent<SpriteRenderer>().sprite = Characters[1];
    }
    if(Input.GetKey("i")){
        gameObject.GetComponent<SpriteRenderer>().sprite = Characters[2];
    }

```

This is my current script, which changes character at keypress Y, U, and I. However as I am developing for touch, I want them to change when a box at the screen is pressed (Left one):

How can I proceed with this? Can I set the sprites to numbers, and let's say at button press, it adds +1, and that changes the sprite? And if so, how does the last one work to get it back at 0? Appriciate all answers. :)

# Answer
> 1 votes
Something like this:

```
selected_character++;
if (selected_character >= num_characters)
{
    selected_character = 0;
}

```

and you can select the sprite by

```
gameObject.GetComponent<SpriteRenderer>().sprite = Characters[selected_character];

```

You also have to declare a new class member to make the code above work:

```
int selected_character = 0;

```

---
Tags: unity, sprites, touch
---


title: Irregular gravity bouncing

text:
# Question
Title: Irregular gravity bouncing
I am working in a simple bouncing ball game. The ball moves right to left at a constant speed and back when it collides with the border of the display. But it jumps every time the the user clicks and then it falls. I apply no friction or something of that kind so when the ball bounces it has to have the exact opposite speed it had when it collided, but due to acceleration, when the frame rate is low it accelerates more than it should and bounces at a greater speed (and higher position), and when the frame rate is too high it bounces at a lower speed (and lower position). This obviously doesn't affect horizontal movement because there is no acceleration in there.

```
double current_time = SDL_GetTicks();
//for my convenience this is global variable
deltaTime = current_time - *previous_time;
*previous_time = current_time;

//Apply motion in x and y
ball.x += ball.x_speed * deltaTime / 1000;
ball.y += ball.y_speed * deltaTime / 1000;

//Accelerate
//Not quite sure where this should go for physical correctness
ball.y_speed += 1.5 * deltaTime;

ball.rect.x = (int) ball.x;
ball.rect.y = (int) ball.y;

```

So I now want to know how to make the speed be constant even if the frame rate isn't when I collide with the ground (obviously without getting rid of gravity acceleration).

**Update**

I didn't find any other relevant code to show you but I will provide a broader look at how I process and display the objects in the game.

I am using SDL to create this game. So I create this struct as a game object:

```
typedef struct PHYS_Object
{
    SDL_Rect collider;
    int x_speed, y_speed;
    //These two are the exact position of the object
    double x, y;
    int usesGravity;
    SDL_Texture* sprite;
}PHYS_Object;

```

Then in the main function before entering the main loop I create the objects and provide all the needed information like the image it's gonna use, the position etc... and store the objects that move in an array and objects that collide in other array (some of them are in both).

then in the main loop it goes like this:

```
//Abbreviated code
while(!quit)
{
    if(is_clicked(&button_1))
    {
        react_to_click();
    }else if(is_clicked(&button_2))
    {
        react_to_click();
    }else if(is_clicked(&play_button))
    {
        ball.y_speed = -250;
    }

    //Now move all the objects in the array
    //according to their speeds and position
    //See the code above
    PHYS_ApplyMotion(moving_objects_array);

    //Now detect and react appropriately to the
    //collisions produced after motion occurred
    PHYS_DetectCollisions(colliding_objects_array);

    SDL_RenderClear(renderer);
    SDL_RenderCopy(everything);
    SDL_RenderPresent(renderer);
}

```

# Answer
I believe the problem is that you're assuming that the ball is at a constant speed throughout the time step. The relevent parts of your code are:

```
ball.y += ball.y_speed * deltaTime / 1000;
ball.y_speed += 1.5 * deltaTime;

```

Unfortunately, this method only gives an approximation of the position, and this is why you are seeing errors. You are not taking into account the smooth speed variation between the last time step and this time step.

Fortunately, it's actually pretty easy to take this variation into account. The equation for distance travelled moving under a constant acceleration is:

**s** = **u**t + 0.5**a**t2

Where **s** is the displacement, **u** the speed at the start of the time step, **a** the acceleration of the body and t the time step. In your case:

```
u = ball.y_speed;
t = deltaTime / 1000;
a = 15000;

```

So, to correct your problem you can use the following code:

```
ball.y += (ball.y_speed * deltaTime / 1000) + (0.5 * 15000 * ((deltaTime / 1000) * (deltaTime / 1000));
ball.y_speed += 15000 * deltaTime / 1000;

```

This should fix your issue.
> 1 votes

# Answer
Try basing your calculations on system time if you want it to be non frame-rate dependent. The only thing I can say is that basing the movement calculations on frame-rate should mean that if the frame rate drops then then the ball should slow down with the frames. I have done something similar to this before and what I did is each gamestep or MainUpdate would update a tickRate variable and then if the application hung then anything that was dependent on the tickRate would run at the speed of the applications MainUpdate. This allows the graphics to drop frames or run at a variable framerate with no negative effects on performance. Though I'm sure deltaTime is based off of the main game loop which would mean variance in graphics frames shouldn't effect it.
> 0 votes

---
Tags: physics
---


# Question
Title: How to diagnose the problem when the input assembler and the vertex shader look correrct, but the Output Merger is wrong?
I'm porting some OpenGL code to Direct X 11. I ended up with nothing being drawn on the screen. I reverted to a simple program, which I am writing about here.

I'm now trying to use the Graphics Tools in Visual Studio to diagnose a very simple "Hello Triangle" program. In my program, I am drawing simple geometry and using a basic shader. The shader just outputs a constant color.

```
float4 ps_main(VS_OUTPUT Input) : SV_TARGET
{
    return float4(0.2f, 0.2f, 0.2f, 1.0f);
}

```

However, the Output Merger shows nothing.

**(LOOK CLOSELY)**

When I click on the output merger, I see a green alpha checkerboard.

What I would like to know ultimately, is what I'm doing wrong. (Why is the output merger basically blank?) Additionally, I'd like to learn some skill in reading outputs like this:

This is the contents of `basic.hlsl`

```
cbuffer cbTransform : register( b0 )
{
    matrix matWorldViewProj;
};

struct VS_INPUT
{
    float3 Position     : POSITION0;
    float2 TexCoord     : TEXCOORD0;
    float3 Normal       : NORMAL;
    float4 Color        : TEXCOORD1;
};

struct VS_OUTPUT
{
    float4 Position     : SV_POSITION;
    float2 TexCoord     : TEXCOORD0;
    float3 Normal       : NORMAL;
    float4 Color        : COLOR0;
};

VS_OUTPUT vs_main( VS_INPUT Input )
{
    VS_OUTPUT Output;
    Output.Position = mul(float4(Input.Position,1), matWorldViewProj);
    Output.TexCoord = Input.TexCoord;
    Output.Normal = mul(Input.Normal, (float3x3)matWorldViewProj);
    Output.Color = Input.Color;
    return( Output );
}

float4 ps_main(VS_OUTPUT Input) : SV_TARGET
{
    return float4(0.2f, 0.2f, 0.2f, 1.0f);
}

```

Here's what matWorldViewProj looks like:

# Answer
Fix your matWorldViewProj. w values are NaN, so the transformation will fail miserably. The w column should be (0,0,0,1).

Also, you should be getting complaints at the following line:

```
Output.Position = mul(Input.Position, matWorldViewProj);

```

as you multiply a 4x4 matrix with a float3. Change it to:

```
Output.Position = mul(float4(Input.Position,1), matWorldViewProj);

```

and **fix** the w values in C++ code.
> 0 votes

---
Tags: directx, directx11, hlsl, debugging
---


title: Parallax effect for layers in Unity2D

text:
# Question
Title: Parallax effect for layers in Unity2D
I have a simple game scene where i have put a number of images. I combined these images into layers (SortinLayer, to be specific). So now I have 3 layers. I have read a few tutorials, but in them was described how to make parallax effect for the certain bitmap, not for a group of images that were grouped under one layer. But I need to make a parallax effect for the whole layer. Is it possible to do this in Unity2D?

# Answer
In unity, SortingLayers (or camera layers for that matter) are not groups of object you should see them as tags :

specifically for the sprites, sorting layers are used to define the order of render of the objects. you can go through all the sprite-renderers and check their layers and apply something to their transforms but that will consume "a lot"\* of resources.

better solution is to really group your objects by parenting them to the same transform, and then you move that transform.

For ex : 30 objects and you want to make three "layers" (but once again it is parallax layers not sorting layers (they can be related (you want stuff to be drawn in order) but are not the same thing))

what you would do in that case if create three empty game objects and drag 10 object onto each of them, then you'd move those 3 game objects according to the camera to achieve the parallax effect

* "a lot" does not mean gigantic amounts (while that depends on the number of sprites you go through...) but it means that this is not the best approach
> 2 votes

---
Tags: unity, 2d, parallax-scrolling
---


# Question
Title: How to profile CPU and GPU performance if I have a monster PC?
I'm going to upgrade my PC soon. I'm worried that I will no longer spot performance losses in my game because of the better specs.

I can check memory usage easily, but how do I check and debug CPU and GPU usage? I used to rely on the framerate, but I guess that it is not accurate.

# Answer
They're called profilers. Visual Studio has both CPU and GPU profilers built in to recent versions. A profiler will give you an idea of how much time your app is taking and where that time is being spent. This won't entirely avert the problems of over-specced hardware, though; the app might peg a lesser CPU but only use 60% of your developer machine. They can help you track trends, e.g. noticing that what used to take 0.5ms now takes 2ms, which is indicative of changes that broke performance.

Frame rate has never been useful for performance measuring. You need to time things. You can build an in-game instrumented profiler, which can be a huge help (and companies like RAD sell some off-the-shelf instrumented profilers geared for games) or you can use a separate sampling profiler which collects stats from a running program without needing to modify it.

Tools like Very Sleep are free profilers that you can run if you're not in Visual Studio or don't want to pay for more competent developer tools (which are often a far better investments than new hardware, I might note). There are similar tools available for OSX, Linux, consoles, and the mobile platforms. Intel's VTune is the most capable sampling profiler I know of, but it is expensive and only works on Intel CPUs naturally (though it does support non-Windows OSes).

For GPU, you can use stand-alone tools like NVIDIA's NSight or AMD's PerfStudio or Intel's GPA. Again, there are some tools for other platforms besides Windows; the ones for consoles tend to be top-notch while the ones for Linux are currently all junk and I'm not personally familiar with the offerings on other platforms.

Ultimately, though, you need to test on target hardware. Figure out what your target low-end hardware is and then buy one of those (or find a tester that has one). Test on that. There's absolutely no other good way to ensure that your game will run well on that hardware other than to just test it with that specific hardware. This is true for PCs, mobile devices, etc. (and this is one of the reasons many developers prefer targetting consoles or closed ecosystems like Apple's products; it vastly reduces the number of hardware configurations that need to be tested)

Game development studios will often have whole labs of varying configurations (different levels of performance, hardware from different manufacturers, different versions of the target OS, etc.) to do their testing. Smaller indie devs might have a couple machines to test on, like a primary desktop, a backup desktop, and a laptop (and then have to rely far more on volunteer testing).
> 13 votes

---
Tags: software-engineering, performance, gpu, debugging
---


# Question
Title: How can I make location-based spells which create soil patches on the ground?
I'm making a spell that'll place a soil patch on the ground in skyrim, and I cannot get it to work. I would like some help. When I tested the spell in game, no soil patch appeared on the ground. I tried doing it on different terrains and different levels of hills, mountains, etc. with no luck. I'm not sure what I am missing. I'm using the soil patches that are functional in the HearthFire DLC.

Here is what I've done thus far:

I made an activator "marker" with a script attached to it that is supposed to summon a soil patch at its location. This is the current script for it:

> ```
> ScriptName maSpawnSoilPatchActivatorScript Extends ObjectReference
>
> ObjectReference refMarkerPosition
>
> Event OnInit()
>
>    refMarkerPosition = Self.PlaceAtMe(Game.GetForm(0x02008240))
>
> EndEvent
>
> ```

After, I made a "dummy" explosion that is supposed to place the activator at the location where the spell hits, so that it can spawn the soil patch in that location.

I then added the dummy explosion to a new magic effect, and then attached the magic effect to the conjuration spell I created.

# Answer
Try using `PlaceAtMe` to place your soil patch in the *magic effect*, rather than in the activator.

I have teleport spell to teleport me to my created world which works fine if the script is placed in the magic effect section rather than the activator. Try that.
> 2 votes

---
Tags: skyrim-modding
---


title: How to create laser redirection?

text:
# Question
Title: How to create laser redirection?
Think portal 2, where a laser can go through a cube, and depending on the rotation of that cube, it will redirect it. Examples:

Here is my barely functioning code. It works for one cube, I'm able to get the original (source) laser to hit any 'redirect' cube, then I'm able to cast a line renderer and change the rotation.

Problem comes when I try to use the redirect laser to hit another redirect cube, I can't figure out how to make this code work for multiple cubes hitting off each other.

```
using UnityEngine;
using System.Collections;

public class outLaser : MonoBehaviour
{
    public sourceLaser1 reference; //referring to another class that has the original (source) laser

    LineRenderer redirectLaser;
    RaycastHit redirectHit;

    void Awake()
    {
        redirectLaser = GetComponent<LineRenderer>();

    }

    void Update()
    {
        if(reference.sourceHit.collider.gameObject == transform.parent.gameObject)
        {
            if(Physics.Raycast(transform.position, -transform.forward, out redirectHit, Mathf.Infinity))
            {
                redirectLaser.enabled = true;
                redirectLaser.SetPosition(0, transform.position);
                redirectLaser.SetPosition(1, redirectHit.point);
            }
        }
        else
        {
            redirectLaser.enabled = false;
        }
    }
}

```

Tried many different solutions, all with no avail.

Here's what it looks like:

EDIT: I've gotten this far

```
    if(reference.sourceHit.collider.gameObject == transform.parent.gameObject)
    {
        if(Physics.Raycast(transform.position, -transform.forward, out redirectHit, Mathf.Infinity))
        {
            redirectLaser.enabled = true;
            redirectLaser.SetPosition(0, transform.position);
            redirectLaser.SetPosition(1, redirectHit.point);

            //Logic that allows redirect cube to accept redirect raycasts
            cubeThatsHit = redirectHit.collider.gameObject;

            if(cubeThatsHit.gameObject.tag == "Redirect")       //if the cube that is hit is a redirect cube, do this
            {
                   //This is where I need the logic
            }
        }
    }
    else
    {
        redirectLaser.enabled = false;
    }

```

# Answer
> 3 votes
You should just have one component for your laser. The source object would just have the laser component. The "redirect" object will have an additional component called `redirect`. The laser component casts a ray, if that ray hits an object containing a `redirect` component, the "redirect" object powers up its own laser.

Think of the laser more as a trigger to power up the cubes. When the cubes are powered up, they emit their own laser in the direction defined by their rotation. This allows you to redirect the laser as many times as needed.

---
Tags: c#, unity, lines
---


title: Threading in Sound

text:
# Question
Title: Threading in Sound
I am developing a game and a question that constantly comes to mind is how my sound system is going to work. I am currently working on the graphics and terrain generation portion of my game and sound is a ways away but I still would like to be prepared. As it currently stands I have a seperate thread on the CPU for audio but it occurs to me that if I want to play multiple sound files at once it would have to wait for one to stop for the other to start, for example, a duck quacking while a stick snapped. If the two happen symultaniously it stands to reason that you would hear them at the same time. I thought of making a seperate CPU thread for each sound file but I am sure that would be messy. I then had the idea of having a seperate GPU thread for each sound since GPU's have many cores but that would be silly to use the graphics card to play audio.

In conclusion:

* Is using the GPU for playing multiple sound files symultaniously benefitial?

# Answer
> 2 votes
In the end, your sounds must be streamlined as one flux of bytes to the DSP device. Check how it works in linux, you get `/dev/dsp` which is a link to `/dev/dsp0` (but its a detail) and it accepts only ONE process to open one descriptor on it, and you stream your flux to it and it gets played on the speakers provided your driver is working.

The driver will copy chunks of the buffered data in the `dsp` file into the sound card device onboard memory which is itself playd-back by the actual dsp processor, and output to the cards `DAC` (digital to analog converter), then to operational amplifiers, then to jack output.

The way for multiple process to play sounds together, is to go throug a `mixer`. The mixer is a virtual device which works in software, and accepts multiple streams, these streams are additionned and result in one unique stream, that is then output to `dsp` device.

Windows and Mac have mixers set by default as well.

When a game is outputting multiple sounds, it better do its own mixing, which libraries will provice. like SDL\_mixer. Or fmod, or OpenAL. You are not obligated to use those but I strongly recommended it !

Then it is quite easy, the library will take sound files as input, give them to decompress to the appropriate sub-library (libvorbis, libffmpeg...) and buffer or streams the sound according to heuristics based on the file size. Then the library will use threads internally to make sure the mixer buffer is always filled by the currently played sound samples.

A typicall buffer is 2048 of size, which at 44kHz stereo sampling will give you 23 mili-seconds, this is just enough to get re-scheduled by the OS in time.

Every serious OS on this planet will have a "multimedia scheduler", which is a heuristical weight atribution for threads that have a connection opened with the DSP device. This helps getting rescheduled faster, which in turns helps into preventing the mixer buffer to become empty. This would results in cracks in the sound, which is ugly and scary.

If you do not want to use a library for sound playing, then you need to make the sample mixer yourself and this is no play in the park. You need to keep pointers to the last sampled played in each of your currently playing sounds, you need to keep a state machine for each sample, that will remember its configuration. Like infinite loop, or "just 2 loops please", this is set by the client of your sound library. You need to make it thread safe, and also care about memory usage if all your sounds need to be in memory. If its impossible you need to do a cache prefetcher system that streams on demand. Also reading esoteric formats like mp3 will be tough unless you use a library.

Final point with the GPU. this would be a bad idea, because GPU uses loose floating point operation precisions and you will get losses in your sound. Also you need to move samples into texture memory and particuarly bad : do a lot of read-backs from the render targets to get the result of your mixing. This would be done easily using microsoft `AMP` or nvidia `thrust`, or `vexCL` or `boost compute`. Because the operation is a simple `add`.

However, be please mind the latency, in general you want your sounds to react very fast, 20ms is a long delay for profesionals. (look up `ASIO` drivers) using the GPU you are contemplating at 3 frame delays usually, so 48ms... keep in on CPU. srsly.

---
Tags: audio, gpu
---


# Question
Title: Should I draw directly on a CCLayer or a CCSprite?
Now I am a little confused in my cocos2d-x cpp project. I want to draw lines with user's finger touch. Following the screenshot of a CCScene:

In the screen, there are two squares. I want show an animation in the first square and let the second one draw lines with user touch.

Now these two squares are `CCSprite`. And I can draw dots in the second one on the `CCLayer`. But I am little confused that I should draw lines on the `Sprite` or on the `Layer`.

Or are there other ways to organize the code?

# Answer
> 1 votes
well, ask yourself, do the lines only pertain to the squares? If so, why not add the lines as a child of the square and then setting the position to where you want it. Since the lines are children of square positioning starts relative to the squares position.

# Answer
> 0 votes
> I want to draw lines with user's finger touch. Following the screenshot of a CCScene

I had a same project in cocos2dx. for drawing something like this you can use `CCRenderTexture`. RenderTexture work like a paiting canvas. you put a sprite ( imagine it as a painting brush) on somewhere on RenderTexture and call `sprite->visit()`. If you this `visit()` on `CCTouchMoved()` you can draw on Render Texture as player finger move.

If you are more interseted in more detail you can check this example:

```
void ccTouchesBegan(CCSet* touches, CCEvent* event)
{
    RenderTexure->begin();
    brush->setVisible(true); // brush is a simple sprite
}
void PaintingScene::ccTouchesMoved(CCSet* touches, CCEvent* event)
{
    CCPoint currentTouch = touch->getLocation();
    brush->setPosition(currentTouch);
    brush->visit();
}
void ccTouchesEnded(CCSet* touches, CCEvent* event)
{
    brush->setVisible(false);
    RenderTexure->end();
}

```

---
Tags: c++, cocos2d-x, ccsprite
---


# Question
Title: Why does Unity save textures in bitmap format for APKs and IPAs?
Why does Unity save graphic resources in Android apks and iOS ipas in a bitmap format(width\*height\*bpp)?

I want to save my resources in a small apk, but instead of 1mb for an image Unity stores 11mb for a single image.

# Answer
Your source texture is stored and converted regarding the individual platform settings. These settings include resolution, compress and the like. On Android for example you can choose between RGBA16 or ETC1 textures. Those are part of the build settings.
> 1 votes

---
Tags: unity, assets, memory
---


title: Give alpha to an object OpenGL ES

text:
# Question
Title: Give alpha to an object OpenGL ES
I am new on OpenGl and what I want to achieve is to give a texture the alpha from 1.0 to 0.0

I have been searching and only found "how to load alpha in images" but I cant find how to apply alpha to an object

I has been tried with:

```
    gl.glEnable(GL10.GL_ALPHA_TEST);
    alpha += 0.002f;
    if(alpha > 1) alpha = 1f;
    gl.glAlphaFunc(GL10.GL_EQUAL, alpha);

```

But it doesn't work.

How I can give alpha value (to make the effect of fade) to an object/texture?

# Answer
> 0 votes
I made it!

That is the code

```
gl.glEnable(GL10.GL_BLEND);
gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
gl.glColor4f(1f, 1f, 1f,alpha);
alpha -= 0.002f;
if(alpha < 0) alpha = 0f;

```

---
Tags: opengl-es, alpha
---


# Question
Title: How do I render my 3D game in ASCII art?
I'm trying to create an Easter egg for a 3D game in Unity3D. I want to render my game momentarily in ASCII art.

My first idea is to create a shader to do that, but I'm not sure if it's the right way.

# Answer
I don't know of any plug and play solutions for it, but here is an algorithm that works in the pixel shader with just a texture as extra assets.

The asset required is a small texture with a single row of some number of tiles, where the left most is the darkest and the right most the lightest.

What happens then is (per frame):

* Take the buffer you want to make an ASCII version of and downscale it by the tile size (so if you have 8x8 tiles the image will be scaled down by 8 in both dimensions).
* Create a new render target of the original full sized buffer.
* Use a pixel shader with the following:
* + A sampler input for the buffer (with sampling set to nearest neighbor), and a sampler input for the tiles.
* + Uniforms for the tile size, amount of tiles and final output resolution
* The pixel shader should then:
* + Get the gray scale value from the downscaled buffer ( `(col.r+col.g+col.b) / 3.0` is probably sufficient, even though that isn't quite how eyes work)
* + Use this information to get which tile you want to render from (`floor(grayscale * TILE_COUNT)`)
* + Calculate the pixel X/Y coordinates of the output and take those module the tile size (tileX/tileY).
* + Return as color the value sampled from the tile buffer at `vec2( whichTile * TILE_WIDTH + tileX, tileY ) / vec2( TILE_WIDTH * TILE_COUNT, TILE_HEIGHT )`

The linked page has several images of examples, one thing I'd consider adding would be a slight bit of noise to the calculated grayscale value so it's not one big block of `MMMMMMMMMMMMMMMM`s

Updated: @Lokkij in the gamedev chatroom posted a more complete tutorial for Unity: http://pentahelix.github.io/ASCII-Tutorial-Revisited/
> 19 votes

---
Tags: unity, shaders
---


# Question
Title: libgdx, how to check collision of randomly generated actors?
I have two groups of randomly generated actors, one is bullets second is enemies. And as of now I have no idea how to check collision of randomly genrated actors and remove the overlaped actors. I'm newby.

At least provide some pseudocode! Thanx in advance!!!

# Answer
> 6 votes
First ensure that your Actors are able to report their bounds:

```
public class Enemy extends Actor {

    Rectangle bounds;
    public Enemy() {
        bounds=new Rectangle((int)getX(), (int)getY(), (int)getWidth(), (int)getHeight());
    }

    public Rectangle getBounds() {
        return bounds;
    }

    private void setXY(float pX,float pY) {
        setPosition(pX, pY);
        bounds.setX((int)pX);
        bounds.setY((int)pY);
    }
}

```

Then collect any Actors into ArrayLists:

```
//init lists
List<Enemy> enemies = new ArrayList<Enemy>();
List<Bullet> bullets = new ArrayList<Bullet>();

//add actors to lists
enemies.Add(new Enemy());
bullets.Add(new Bullet());

```

Now you can itterate though the lists and check for collisions:

```
for (int i = enemies.size() - 1; i >= 0; i--) {
    Enemy enemy = enemies.get(i);
    for (int j = bullets.size() - 1; j >= 0; j--) {
        Bullet bullet = bullets.get(j);
        if(enemy.getBounds().overlaps(bullet.getBounds())) {
            //handle collision
        }
    }
}

```

---
Tags: java, android, libgdx
---


# Question
Title: How crucial is 3D terrain in a classic RTS game?
My love of RTS games is from the days of Warcraft II, C&C, etc, when top-down/isometric views were king and terrain was generally tiled and flat. More modern games - as CPU/GPU power increased - moved to fully 3D terrain but I wondered is this considered a necessity in a modern game or would a more old-school design still have mileage? 3D terrain adds tactical elements but are those essential, or typically not that important to the gameplay, or even gimmicky?

# Answer
3d terrain always comes with a cost: Objects get obscured behind cliffs, so the player needs to rotate the camera to maintain situational awareness. This takes time and disorients the player. They end up fighting the camera more than they fight the enemy.

So before you add height levels just for the heck of it, consider how much it adds to your game in regards to gameplay. When units on higher terrain have an advantage over those on lower terrain, it can add another interesting aspect. But it's an effect which you need to balance. You have to consider for yourself if this fits into your overall game mechanics and if it improves them enough to justify the usability problems it causes.

Also keep in mind that height levels and a 3d engine aren't dependent on each other.

There were lots of games during the RTS boom in the late 90s / early 2000s which used 2d engines and still used height levels with all the gameplay ramifications.

And there are RTS games which use 3d engines but make almost no use of height levels. Warcraft 3, for example, has a distinctive "fisheye" look to show off the shiny new 3d engine which sets it apart from its predecessor, but makes very sparingly use of height levels. Most of the gameplay feels 2d. I am not even sure if height even *has* a gameplay effect in WC3. When I remember correctly, it was a purely cosmetic thing.
> 4 votes

---
Tags: 3d, game-design, rts
---


# Question
Title: How to do an infinite torus topology battlefield for over-the-shoulder perspective
I'm currently prototyping a simple two-player adversarial game, where the players are able to move around and shoot at each other with cannons. I would like the playing area to feel essentially unbounded, but I don't want one of the players to be able to stall the game by just rushing away from his opponent.

The standard solution to this dilemma in the 2D days was to introduce a torus topology: if a player leaves the screen from the top, they enter at the bottom. If they leave from the right, they enter from the left. I am looking for a workable analogon to this system for games played from a third-person perspective.

Technically you can implement this just fine. However, since they lack complete battlefield overview, it will confuse the heck out of the players if their opponent pops out of/into existence.

Currently I'm thinking of combining the following techniques:

* A map that shows top-down overview. This provides the context you used ot have in the 2D game.
* Rendering the closest periodic image of the enemy as solid. This is not necessarily the one in the same "screen".
* Rendering the others as "ghosts".

Will this be enough to make this design work? Can it be made to work better with some tweaks? Is torus topology and third person perspective just a really bad idea?

# Answer
The actual topology doesn't matter as much as your viewpoint on it. You could pull exactly that old 2-D trick by making any 'view' on the world never be able to display an area larger than the world itself - so there's only ever one opponent (though you may be able to reach him by running in either of two directions) and no ghosts. Mark the edges of vision (very far away) with a haze of grey if you must.

Or maybe I just don't understand the problem correctly.
> 3 votes

# Answer
How about playing the game on the top of some closed, finite 3d surface, such as a sphere or cube (or a noise function perturbed version of one of these to make it a more interesting generalized polyhedron). This will give you the effect of wrapping around, which will make the inifnite chase scenario somewhat trickier for the players. Having a 2D overview map would still have the popping off the one side and popping up on the other side issue, so perhaps a 3D map may be better: i.e., a simplified zoomed out overview of the 3D polyhedron model rendered with transparency.
> 6 votes

# Answer
You need to think with Portals :-)

Make the playing field large enough that a player can't see from one end to the other (e.g. using fog). That way, a player can never see two instances of the same opponent. Of course weapon ranges need to be limited appropriately as well.

Then, when a player nears the edge of the playing field, just draw a second copy of the map beyond that edge. That way, it will look like an infinite (though sort of repeating) playing field. When a player walks past the edge of the playing field, wrap them around. Same applies to any shots fired or attachs made at the edge of the playing field.

So, effectively, like with classic room-and-portal-based engines, you can have rooms loop over themselves. An even easier way might be to split up the whole playing field into tiles. Each tile knows its adjacent tiles in all four directions. Then hook up the tiles at the edge of the playing field to their opposite number. Pick the tile your player is on, and draw a limited number of tiles in all directions relative to that. This way, you do not need to wrap.

Well, I'm lying, actually, you'll need to wrap at *each* tile boundary.

If you think making the playing field large enough that you can not see to the end is too much (you'll need a little more, so that a player can't just walk backward a few steps and hit you from the other side), you could make the mechanic more explicit, either by having an actual teleporter fence (or a thick wall of fog)) at the edge, and having a player frozen for a second while teleporting (maybe even with directional stereo sound, so the opponent is warned of the teleport, and the teleport makes a player weaker as it gives an advantage). Alternately, you could model your world so it seems like a small moon or so, with the ground obviously curved. But then you would probably have an area for the opponent to hide again.
> 1 votes

# Answer
As with the "topology doesn't matter" answer, you can do the torus solution pretty easily. It's possibly easiest if you've got a tiled world. E.g. instead of one giant terrain mesh you have a map made up of M x N tiles. When you're in tile m,n you can see that tile and +/- 1 in each direction; just wrap the result of the additions and subtractions and you're done. I.e. tile 0,0 can "see" and is attached to as appropriate tiles 0,1, 1,1, 1,0 plus M-1,1, M-1,0, M-1,N-1, 0,N-1, and 1,N-1
> 0 votes

---
Tags: graphics, game-design, level-design
---


# Question
Title: What causes sprite tearing / corruption in unity PC stand alone running on Windows XP?
The image below is representative of my client's experience running the released version of an app I created for him on his Windows XP Machine.

I built it using Unity 4.5. The messed up buttons are the product of a png import to a sprite render all done using the Unity editor. I created the sprites at a resolution of 1024X96 and scaled them down using the editor. I have the applications default resolution set up for 800X600 windowed and the user can resize the game window.

I cannot seem to recreate the problem using the editor or a release on my local machine. He said it worked fine on his Windows 7 Machine, though he said the text looked blurry. Any thoughts?

# Answer
It seems that scaling the images for the buttons from 1024X96 to 798X75 while targeting a default resolution of 800X600 solved the graphics corruption. I wish I knew why this was the case, but I will take a win any day. Thanks to all who have contributed.
> 0 votes

---
Tags: unity, sprites
---


# Question
Title: Assigning multiple game objects to a single sprite (Unity)
I've been making a pokemon game clone on my own with Unity, as I'm a beginner and just trying to learn. Up until now I've been splicing the town pictures and manually putting them together, but this is extremely time consuming and takes several hours. Unity won't let me drag multiple sprites onto the scene, so I have to find another way. So currently my idea is to keep the image of the town as a single sprite, drag it onto the scene, and break it up into 16x16 pixel game objects, so I can add colliders and triggers and what not to each of the game objects. I found a way on the Internet to break up a single sprite into an array of sprites, but I don't know how to lay them out onto the scene. Can someone point me in the right direction and give some help? Thanks

# Answer
> 4 votes
It sound to me as though you already have an entire map of the town drawn up and you are trying to break it down into 16px X 16px tiles for the sole purpose of adding triggers and colliders etc. Why not just keep the map as its own object and put your collider and trigger objects over it where you need them to be?

Really, a tile based map might be better in this case for memory and performance optimization. There are many free tools to do this already available in Unity's Asset Store. Or, you could create your own map editor - in the language of your choice, and have it export to a text file so that your games then could import them.

Good luck!

Best Regards, Ben

---
Tags: unity, sprites, tiles, gameobject
---


# Question
Title: How to create a two-way teleport system?
I'm trying to create a two-way teleport system in which players can move into a teleport gameobject, and is then teleported to another linked teleport gameobject.

How I was planning to have it work was very simple. On the teleport gameobject's script, it would have a public property to the other teleport's transform in which to teleport the player to. In `OnTriggerEnter`, I simply set the entering's collider position to that of the linked teleport.

```
void OnTriggerEnter(Collider other) {
    other.transform.position = DestinationPoint.position;
}

```

However, when the player's position is changed, it triggers the `OnTriggerEnter` of the destination teleport, and thus the player gets stuck bouncing back and forth between the two points.

What's a good way to prevent this? Some less than ideal solutions I came up with is to offset the position that player teleports too slightly so that he doesn't cause `OnTriggerEnter` to be called at the destination portal, but I'd like to avoid that.

# Answer
How I ended up solving this is by delegating the act of teleporting to a `TeleportEntityCommand`. When an entity enters a teleporter in the scene, it fires an event to the command notifying it of a teleport request, sending it the gameobject that wishes to teleport.

`TeleportEntityCommand` maintains a `List<GameObject>` of objects being teleported. When a request comes in, the gameobject is added to the list, is teleported, and then after a short cool down time, is removed from the `List`. While a gameobject is in the `List`, any requests to teleport from any of the other teleporters for this gameobject will be ignored briefly.

The abbreviated solution is as follows.

```
public class TeleporterView : MonoBehaviour {
    // Assume this dispatches to TeleportEntityCommand.Execute()
    private Signal TeleportEntitySignal;

    public Transform Destination;

    void OnTriggerEnter(Collider other) {
        TeleportEntitySignal.Dispatch(other.gameObject, Destination.position);
    }
}

public class TeleportEntityCommand : Command {
    private List<GameObject> _gosToTeleport = new List<GameObject>();

    [Inject]
    public GameObject GameObject { get; set; }

    [Inject]
    public Vector3 Destination { get; set; }

    public override void Execute() {
        if (!_gosToTeleport.Contains(GameObject)) {
            _gosToTeleport.Add(GameObject);
            RoutineRunner.StartCoroutine(TeleportUpdate());
        }

        private IEnumerator TeleportUpdate() {
            // Teleport the object, but then wait n seconds
            // to block teleporting the object again when it
            // hits the destination portal's collider.
            GameObject.transform.position = Destination;
            yield return new WaitForSeconds(1f);
            _gosToTeleport.Remove(GameObject);
        }
    }
}

```
> 3 votes

# Answer
Personally i would leave this feature in as it would be to funny to let go :). On a serious note.

coudl you not use an objects state? such as a player object give it HasTeleported property as a boolean.

So simply say

```
If(!hasTeleported)
{
    //beam me up scotty
    hasteleported = true;
}

```

then after so many seconds or whatever set HasTeleported back to false, basically a "debuff"
> 0 votes

# Answer
The teleporters obviously need to have a reference to each other in order to send to each other. You could use that reference to temporarily deactivate the destination.
> 0 votes

---
Tags: unity
---


# Question
Title: Removing inline declarations makes code work. Why?
This does not work:

```
camera = new OrthographicCamera(100, 100 * (Gdx.graphics.getHeight() /Gdx.graphics.getWidth()));

```

This does:

```
float w = Gdx.graphics.getWidth();
float h = Gdx.graphics.getHeight();

camera = new OrthographicCamera(100, 100 * (h/w));

```

I do not get the difference. One displays fine on my screen, the other remains black.

Why is this? Is there any syntactical reason why this does not work, or is it a bug?

# Answer
> 5 votes
It's because you're doing integer math in the first case, but not in the second.

First, a quick look at the documentation

> **getWidth**
> `int getWidth()`
> **Returns:**
> the width in pixels of the display surface. \<
>
> ---
>
> **getHeight**
> `int getHeight()`
> **Returns:**
> the height in pixels of the display surface

So now we know that the two methods return integer values (understandable - it's a count of pixels). So when you execute this:

```
Gdx.graphics.getHeight() / Gdx.graphics.getWidth()

```

... it does the division, which for integers *truncates* the result ("rounds" towards 0). And since screen widths are usually larger than heights...

```
1. Gdx.graphics.getHeight() / Gdx.graphics.getWidth() =
2. 1080 / 1980 =
3. 0.545454545 =
4. 0

```

... so you're really ending up with:

```
camera = new OrthographicCamera(100, 0);

```

Fortunately, this fix is simple. You can either keep the assignment to local `float` variables, like you do in your latter example, or you could just cast one of the returns:

```
camera = new OrthographicCamera(100, 100 * ((float) Gdx.graphics.getHeight() / Gdx.graphics.getWidth()));

```

---
Tags: libgdx
---


title: Exporting spritesheet for Cocos2d

text:
# Question
Title: Exporting spritesheet for Cocos2d
I would like to know how people usually save the animations in order to load them easily in Cocos2d with as few hard-code as possible.

E.G. The solution I thought of is to have one plist file containing information about each frame, and the second plist to contain information about each of the animation(name of the animation, which frames to play, and the delay probably).

If this is the correct solution, how can I generate such plist files for spritesheet automatically?

# Answer
This is the most basic code of creating and playing an animation in cocos2d:

```
auto cacher = SpriteFrameCache::getInstance();
cacher->addSpriteFramesWithFile("emad-running.plist");
Sprite* someSprite = Sprite::create();

// load all the animation frames into an array
Vector<SpriteFrame*> frames;
for (int i = 0; i <= 10; i++)
{
    stringstream ss;
    ss << "run_" << i << ".png";
    frames.pushBack(cacher->getSpriteFrameByName(ss.str()));
}

// play the animation
Animation* anim = Animation::createWithSpriteFrames(frames, 0.05f);
someSprite->runAction(Animate::create(anim));
someSprite->setPosition(X, Y);

this->addChild(someSprite);

```

And for creating some file like "emad-running.plist", I suggest `Texture Packer`. This tool support cocos2d fully. you can import your separated image, and Texture Packer give you two file:

1. "emad-running.plist"
2. "emad-running.pvr" OR "emad-running.png" OR ...

This two file complete each other and in code you just need to refer`.plist` and you are done. :)

This is how you do in TexturePacker:

<sub>(source: raywenderlich.com)</sub>
> 1 votes

---
Tags: ios, cocos2d, spritesheet, export
---


title: LWJGL exception in JME3-JFX!

text:
# Question
Title: LWJGL exception in JME3-JFX!
Video playback in jMonkeyEngine 3.0 seemed to be in limbo for quite a while until I chanced upon this thread about playing videos by integrating JavaFX 2 into the JME3 framework. This coupled with the recent announcement of MP4 playback support in JavaFX made JME3 a real contender for a project I'm currently working on.

I followed the prescribed method as mentioned in the former thread, got the sources from the JME3-JFX project page and setup the project in eclipse. When I ran the example \[**TestMovie.java**\] with the given URL from Oracle, it ran smoothly with no issues. However when I attempted to play an MP4 file, it played for a brief period with messed up colours and then exited with a *java.lang.IllegalArgumentException* exception.

Here is the eclipse console output :

```
INFO: Audio effect extension version: 1.0
Nov 27, 2014 6:33:13 PM com.jme3.audio.lwjgl.LwjglAudioRenderer initInThread
INFO: Audio max auxilary sends: 4
Nov 27, 2014 6:33:34 PM com.jme3.app.Application handleError
SEVERE: Uncaught exception thrown in Thread[LWJGL Renderer Thread,5,main]
java.lang.IllegalArgumentException: Number of remaining buffer elements is 6627840, must    be at least 14745600. Because at most 14745600 elements can be returned, a buffer with at least 14745600 elements is required, regardless of actual returned element count
at org.lwjgl.BufferChecks.throwBufferSizeException(BufferChecks.java:162)
at org.lwjgl.BufferChecks.checkBufferSize(BufferChecks.java:189)
at org.lwjgl.BufferChecks.checkBuffer(BufferChecks.java:230)
at org.lwjgl.opengl.GL11.glTexImage2D(GL11.java:2845)
at com.jme3.renderer.lwjgl.TextureUtil.uploadTexture(TextureUtil.java:352)
at com.jme3.renderer.lwjgl.LwjglRenderer.updateTexImageData(LwjglRenderer.java:1913)
at com.jme3.renderer.lwjgl.LwjglRenderer.setTexture(LwjglRenderer.java:1936)
at com.jme3.material.MatParamTexture.apply(MatParamTexture.java:86)
at com.jme3.material.Material.render(Material.java:1088)
at com.jme3.renderer.RenderManager.renderGeometry(RenderManager.java:523)
at com.jme3.renderer.queue.RenderQueue.renderGeometryList(RenderQueue.java:322)
at com.jme3.renderer.queue.RenderQueue.renderQueue(RenderQueue.java:374)
at com.jme3.renderer.RenderManager.renderViewPortQueues(RenderManager.java:763)
at com.jme3.renderer.RenderManager.flushQueue(RenderManager.java:719)
at com.jme3.renderer.RenderManager.renderViewPort(RenderManager.java:983)
at com.jme3.renderer.RenderManager.render(RenderManager.java:1029)
at com.jme3.app.SimpleApplication.update(SimpleApplication.java:252)
at com.jme3.system.lwjgl.LwjglAbstractDisplay.runLoop(LwjglAbstractDisplay.java:151)
at com.jme3.system.lwjgl.LwjglDisplay.runLoop(LwjglDisplay.java:185)
at com.jme3.system.lwjgl.LwjglAbstractDisplay.run(LwjglAbstractDisplay.java:228)
at java.lang.Thread.run(Thread.java:745)

```

Now I'd like to clarify that the same MP4 file played flawlessly in a vanilla JavaFX project. Also, one of the developers has confirmed in the first mentioned thread on the jMonkeyEngine forums that he was able to play MP4 videos flawlessly and three of them simultaneously nonetheless. I'm testing these samples on Java 1.8 u25 on Windows 8.1 Pro \[x86-64\] running an Intel Core i5 \[Haswell\] with Intel HD 5000 graphics.

I'm a beginner to graphics development and am aware that the jMonkeyEngine forums are the best place to ask my question but their forum's Q/A section seems to be broken and I'm unable to post there. Any and all help will be appreciated.

# Answer
> 1 votes
This was bug. Reported it and it has hence been fixed.

---
Tags: jmonkeyengine, video
---


# Question
Title: Why is 2D light ray collision result getting inverted at specyfic angle
recently i've been working on 2D lighting for my game. I've created new little project, and I've encoutered a problem. The collision between light ray and the object is fine at angles 316-360 and 0-136 degrees. On the others, light gets inverted (it's gone form the source to the object, and it's present on the 'dark side'.
I know the code isn't efficient, it's just my concept project, I would like you just to help me understand what is going on in here.

Here's a function that checks for collision, for every single point in a light ray.

```
public Vector2 Intersects(Rectangle rectangle,SpriteBatch s)
{
    Point p0 = new Point((int)startPos.X, (int)startPos.Y);
    Point p1 = new Point((int)endPos.X, (int)endPos.Y);

    foreach (Point testPoint in BresenhamLine(p0, p1))
    {
        if (rectangle.Contains(testPoint))
        {
            s.Draw(this.texture, new Rectangle(testPoint.X, testPoint.Y, 3, 3), Color.Black);
            return new Vector2((float)testPoint.X, (float)testPoint.Y);
        }
        else
        {
            final = testPoint;
                s.Draw(this.texture, new Rectangle(testPoint.X, testPoint.Y, 3, 3), Color.Black);
        }
    }
    s.Draw(this.texture, new Rectangle(final.X, final.Y, 2, 2), Color.Black);
    return Vector2.Zero;
}

// Swap the values of A and B

private void Swap<T>(ref T a, ref T b)
{
    T c = a;
    a = b;
    b = c;
}

// Returns the list of points from p0 to p1

private List<Point> BresenhamLine(Point p0, Point p1)
{
    return BresenhamLine(p0.X, p0.Y, p1.X, p1.Y);
}

// Returns the list of points from (x0, y0) to (x1, y1)

private List<Point> BresenhamLine(int x0, int y0, int x1, int y1)
{

    List<Point> result = new List<Point>();

    bool steep = Math.Abs(y1 - y0) > Math.Abs(x1 - x0);
    if (steep)
    {
        Swap(ref x0, ref y0);
        Swap(ref x1, ref y1);
    }
    if (x0 > x1)
    {
        Swap(ref x0, ref x1);
        Swap(ref y0, ref y1);
    }

    int deltax = x1 - x0;
    int deltay = Math.Abs(y1 - y0);
    int error = 0;
    int ystep;
    int y = y0;
    if (y0 < y1) ystep = 1; else ystep = -1;
    for (int x = x0; x <= x1; x++)
    {
        if (steep) result.Add(new Point(y, x));
        else result.Add(new Point(x, y));
        error += deltay;
        if (2 * error >= deltax)
        {
            y += ystep;
            error -= deltax;
        }
    }

    return result;
}

```

# Answer
> 1 votes
I believe it's because you're using the Bresenham line drawing, which swaps the start/end points sometimes. See the calls to `Swap()`.

I'd suggest instead using linear interpolation for line drawing, which would look something like this (untested):

```
double lerp(double begin, double end, double t)
{
    return begin + (end-begin) * t;
}

private List<Point> DrawLine(int x0, int y0, int x1, int y1)
{
    List<Point> result = new List<Point>();
    int Nsteps = Math.max(Math.abs(x1 - x0), Math.abs(y1 - y0));
    for (int i = 0; i <= Nsteps; i++)
    {
        float t = 1.0 * i / Nsteps;
        result.Add(new Point(lerp(x0, x1, t), lerp(y0, y1, t)));
    }
    return result;
}

```

The code is much simpler too (and lerp is useful for all sorts of things other than line drawing).

---
Tags: xna, 2d, lighting
---


# Question
Title: Drawing in a static location when using a camara transform
I'm using a matrix transform to move a 2d camera in Monogame, and I was wondering: How, if I initiated my spritebatch with a matrix transform, can I draw something in a static (non-moving) position? For example, I want to put debugging variables in the corner of the window.

# Answer
Draw the images or text with static location in an other spritebatch.Begin, which doesn't have a matrix transform.
> 2 votes

---
Tags: xna, monogame
---


# Question
Title: Are completely dumb client multiplayer games feasible?
Is it possible to make a networked game, where each client displays a pixel array sent to it by the server, and sends inputs back to the server? This would be much simpler to implement than using client-side prediction, but I would imagine it would be too slow. Would it be possible?

# Answer
Yes it's feasible and no it's not cost effective or performant. Think about how Netflix works, it is able to service millions of customers with 1080p and even 4k streaming.

Why it will not be worthwhile to attempt what you suggest with current technology:

1. Latency, the client will need to send the user's input to the server and wait for the visual feedback from the server, this could take as much as half a second for clients abroad. Even if it only takes 0.1 seconds, it makes the game seem sluggish an less responsive.
2. Rendering costs: first, you would need a GPU per client(?) to render the graphics. What about game logic and physics, you will need pretty much a CPU and ~3Gig memory per user.
3. Compression: When Netflix sends video, it's a compressed format. Compressing the video just in time would be hard, which would contribute to latency and hardware costs.

You could probably get away with running all the logic on the server side; I would never recommend running the rendering on the server side. Also, you should leverage the power of the client to respond to input (even if you correct it afterwards) before response is coming back from the service to improve fluidity.
> 5 votes

# Answer
This is exactly what NVIDIA is doing with GRID. The idea is that the game runs completely on a server. The client sends their keyboard- and mouse input to the server and receives a video stream (compressed with a video codec, not uncompressed pixel arrays) from what the server is rendering.

How are they going to solve the latency problem? I don't know, but NVIDIA seems to be quite confident that they will manage to deploy a network infrastructure which will provide low enough latency to make games enjoyable. At least they seem to bet a lot of money on it.
> 6 votes

# Answer
It is working already. Many games were running through telnet connection. Even now you can play NetHack and many other ASCII compatible games with 80x25 console. It means for pretty fast gameplay you should pass 2000 characters with 2-5 rate per second. That would be 10 kilobytes per second which is fine.

If you will increase window which you are looking with, you will hit the wall very fast. It is not bandwidth wall, but latency wall. With increased package you send through net, your responce will be more reluctant. It looks like "bandwidth-latency window", while increasing bandwidth, your latency rises because of caching everywhere.

Modern games can not solve this problem, and even multiplayer once, even the best - like Counter-Strike or League of Legends, have limitations which decrease quality of play if you do not have computers connected directly via LAN. Good gamers which are playing on tournaments, are different from casual ones because they are constantly playing with latency \<1ms.

But network design of League of Legends have very good synchronization, so if you ask them they may point you where you can buy it or use.

Other alternative - "pass by elements", which means you are passing vector graphics via net. Many standarts is developed, but most known example is "xorg-server". I was thinking a little about writing some nice small vector graphics network sender-receiver, but in my expirience all those are suffering from "small bandwidth--latency windows". It means that best expirience can be achieved with connected directly computers.

If you want simply send image via net, there is h264 codecs with open source. FFmpeg project was working on different codecs. Many open packages exists, which are easily distinguishable by \*VNC. Usually this software is used to get remote administration.

For small refresh rate games, like "hidden objects" and so on, ideally would be just implement on-demand downloading with caching. Browsers allow this, but I do not know much about writing browser games.
> 6 votes

---
Tags: networking, multiplayer
---


# Question
Title: How to execute code every x seconds in unity?
So I have a flashlight battery script I created and I need to know how do you make the battery variable go down every few seconds(whatever time you set.) I tried `InvokeRepeating` but it was an absolute disaster (The battery variable just went down really fast and ignored my script). Anyways this is the code I have:

```
void Update ()
{
    if (light == false) {
        battery+=0;
    }
    if (light == true) {
        battery--;//This is what I want to have every few seconds
    }

    if (battery == 0) {
        myLight.enabled = false;
        light =false;
        battery++;
        InvokeRepeating("invoke", 1, 0.01F);
    }
}

void invoke(){
    light = false;
    myLight.enabled = false;
}

```

# Answer
You're on the right track with `InvokeRepeating`. However, three issues:

1. You're currently calling your `invoke` method every .01 seconds.
2. Your `invoke` method disables your `myLight` component, rather than decreasing `battery`.
3. Your `invoke` method is a very confusing name.

*I'm not sure you're calling `InvokeRepeating` in a good spot, but I'll let you test that :)*

I'd suggest changing your `invoke` method to something like this:

```
void DecreaseBattery(){
    battery--;
}

```

Then edit your `InvokeRepeating` call:

```
InvokeRepeating("DecreaseBattery", 30f, 30f);

```

This will invoke DecreaseBattery after 30 seconds, and then every 30 seconds thereafter.

If you ever need to cancel or restart the `InvokeRepeating` call, you may want to use `CancelInvoke();` somewhere to ensure multiple repeats don't overlap.
> 3 votes

---
Tags: unity
---


title: MD5Mesh Calculate Vertex Normals

text:
# Question
Title: MD5Mesh Calculate Vertex Normals
I am writing an MD5 3D model loader to display animated models. The vertices and texcoords load in correctly, but the lighting is supposed to be smooth. I calculate per-vertex normals by looping through all triangles, finding the triangle normal, and then adding that to each of the triangle's vertices' normal (follow?). Then, I normalize all the normals. This should work, but md5 declares each vertex with a texcoord, meaning that if I have a single vertex that has different texcoords for each of the faces it's attached to, it declares multiple vertices at the same position. Each of these will end up with its own normal, resulting in flat shading. Should I somehow merge duplicate vertices, or export the model differently, or do something fancy that I haven't thought of?

Thanks!

# Answer
If you want smooth normals everywhere you will need to deduplicate vertices for normal calculation purposes. So instead of *"for each vertex, for each index, if index value == this vertex, add normal"* you'll need to use *"for each vertex, for each index, if vertices\[index value\].pos == this vertex.pos, add normal"*.
> 1 votes

---
Tags: 3d-meshes, normals, shading
---


title: How to constrain axis-angle rotation?

text:
# Question
Title: How to constrain axis-angle rotation?
I have a problem where I'm performing an axis-angle rotation and am trying to constrain my rotations. Specifically I have a skeleton (model/mesh with rig, transforms are hierarchy parented to pelvis which move the triangles of the mesh) and I am constraining the motions to prevent bad joint rotations (e.g. knees bending sideways or backwards). The rotations in this case can pretty much be constrained by saying "do not rotate about X/Y/Z."

I'm using the Unity3D RotateAround function which rotates about a specified axis at a point by an arbitrary angle. Given control over this point, axis, and angle how can I constrain this rotation to prevent "bad" rotations?

# Answer
> 1 votes
I spent a while chasing ways to change my problem to use Euler angles, but the easy solution was actually to just 0 the components of the axis I didn't want, i.e. (in C# Unity script)

```
Vector3 axis = Vector3.Cross(RD, RE);
axis.x = CanPitch() ? axis.x : 0.0f;
axis.y = CanYaw() ? axis.y : 0.0f;
axis.z = CanRoll() ? axis.z : 0.0f;

```

where RD and RE are Vector3's and CanRoll(), CanPitch(), and CanYaw() are functions that return a boolean value indicating if roll, pitch, and yaw are allowed on this joint (rotations about z, x, or y axes respectively).

This seems like a very obvious answer, but I spent awhile trying to verify that this actually does what I want.

---
Tags: unity, rotation, transformation, skeletal-animation, axis
---