# Question
Title: Techniques for reducing terrain shader complexity
My terrain shader does quite a bit, but I don't know how to break it up in any way that will reduce my instruction count without removing key features of the terrain. It does the following:

* Multi-texture splatting (allows for 3 textures to be painted onto the terrain).
* Each texture from splatting also has a normal map.
* Directional lighting
* Allows shadows to cast onto it
* Calculates if a pixel of terrain is underwater, and colors the terrain differently based on how deep underwater it is.
* Calculates is the camera is underwater, and applies a "water fog" in that case.
* Specularity

The most expensive part of the terrain is the part it has to do if it's underwater, but I don't know of any way to break that up into a separate shader technique, unless I rendered all of the terrain twice and used a clipping plane at the water elevation. I'm currently down to 69 instructions, but need to get down to 64 instructions to run on SM 2.0. You can critique the shader itself if that will get me down to 64 instructions, but really I'm wondering about how other engines would manage to get these features into an SM 2.0 shader.

Here's the shader if it helps (yea, I know it's a bit ugly, I'm not a graphics programmer usually):

```
//------- Constants --------
float4x4 View               : VIEW;
float4x4 Projection         : PROJECTION;
float4x4 World              : WORLD;
float4x4 WorldViewProjection: WORLDVIEWPROJECTION;
float4x4 LightViewProjection: LIGHTVIEWPROJECTION;
float4 LightDir             : LIGHT_DIRECTION;
float4 AmbientColor         : AMBIENT_COLOR;
float AmbientPower          : AMBIENT_POWER;
float4 SpecularColor        : SPECULAR_COLOR;
float SpecularPower         : SPECULAR_POWER;
float4 DiffuseColor         : DIFFUSE_COLOR;
float4 CameraForward        : VIEW_FORWARD;
float4 CameraPos            : VIEW_POS;
float FogNear               : FOG_NEAR;
float FogFar                : FOG_FAR;
float4 FogColor             : FOG_COLOR;
float FogAltitude           : FOG_ALTITUDE;
float FogThinning           : FOG_THINNING;

float TerrainScale          : SCALE_FACTOR;
float TerrainWidth          : TERRAIN_WIDTH;

float WaterElevation        : WATER_ELEVATION;
float4 WaterColor           : WATER_COLOR;

bool UsingClippingPlane     : USING_CLIPPING_PLANE;
float4 ClippingPlane        : CLIPPING_PLANE;

float DepthBias = 0.0001f;

float4 darkWater = float4(0.0f, 0.156f, 0.467f, 1.0f);
float4 lightWater = float4(0.0f, 0.345f, 0.6f, 1.0f);

//------- Texture Samplers --------
Texture TextureMap          : TEXTURE_MAP;
sampler TextureMapSampler = sampler_state { texture = <TextureMap> ; magfilter = LINEAR; minfilter = LINEAR;
                                                                         mipfilter = LINEAR; AddressU  = Wrap;
                                                                         AddressV  = Wrap; AddressW  = Wrap;};

Texture GrassTexture        : GRASS_TEXTURE;
sampler GrassTextureSampler = sampler_state { texture = <GrassTexture> ; magfilter = LINEAR; minfilter = LINEAR;
                                                                         mipfilter=LINEAR; AddressU  = Wrap;
                                                                         AddressV  = Wrap; AddressW  = Wrap;};

Texture SandTexture         : SAND_TEXTURE;
sampler SandTextureSampler = sampler_state { texture = <SandTexture> ; magfilter = LINEAR; minfilter = LINEAR;
                                                                       mipfilter =LINEAR; AddressU  = Wrap;
                                                                       AddressV  = Wrap; AddressW  = Wrap;};

Texture RockTexture         : ROCK_TEXTURE;
sampler RockTextureSampler = sampler_state { texture = <RockTexture> ; magfilter = LINEAR; minfilter = LINEAR;
                                                                       mipfilter = LINEAR; AddressU  = Wrap;
                                                                       AddressV  = Wrap; AddressW  = Wrap;};

Texture GrassNormal         :GRASS_NORMAL;
sampler2D GrassNormalSampler : TEXUNIT1 = sampler_state
{ Texture   = (GrassNormal); magfilter = LINEAR; minfilter = LINEAR;
                             mipfilter = LINEAR; AddressU  = Wrap;
                             AddressV  = Wrap; AddressW  = Wrap;};

Texture SandNormal          : SAND_NORMAL;
sampler2D SandNormalSampler : TEXUNIT1 = sampler_state
{ Texture   = (SandNormal); magfilter  = LINEAR; minfilter = LINEAR;
                             mipfilter = LINEAR; AddressU  = Wrap;
                             AddressV  = Wrap; AddressW  = Wrap;};

Texture RockNormal          : ROCK_NORMAL;
sampler2D RockNormalSampler : TEXUNIT1 = sampler_state
{ Texture   = (RockNormal); magfilter = LINEAR; minfilter = LINEAR;
                             mipfilter=LINEAR; AddressU  = Wrap;
                             AddressV  = Wrap; AddressW  = Wrap;};

Texture ShadowMap               : SHADOW_MAP;
sampler ShadowMapSampler = sampler_state { texture = <ShadowMap>; MinFilter = POINT; MagFilter = POINT;
                                                                  MipFilter = NONE;  AddressU = Clamp;
                                                                  AddressV = Clamp;  AddressW  = Wrap; };

// For any shader that can support shadow mapping, simply add
// this function and call it from your pixel shader. Of course,
// you'll need to make sure this shader and material are setup to
// receive the ShadowMap sampler, and any needed parameters (e.g. LightViewProjection)
float4 ComputeShadowColor(float4 worldPos, float4 Color)
{
     // Find the position of this pixel in light space
    float4 lightingPosition = mul(worldPos, LightViewProjection);

    // Find the position in the shadow map for this pixel
    float2 ShadowTexCoord = 0.5 * lightingPosition.xy /
                            lightingPosition.w + float2( 0.5, 0.5 );
    ShadowTexCoord.y = 1.0f - ShadowTexCoord.y;

    // Get the current depth stored in the shadow map
    float4 shadowInfo = tex2D(ShadowMapSampler, ShadowTexCoord);
    float shadowdepth = shadowInfo.r;
    float shadowOpacity = 0.5f + 0.5f * (1 - shadowInfo.g);

    // Calculate the current pixel depth
    // The bias is used to prevent folating point errors that occur when
    // the pixel of the occluder is being drawn
    float ourdepth = (lightingPosition.z / lightingPosition.w) - DepthBias;

    // Check to see if this pixel is in front or behind the value in the shadow map
    if ( shadowdepth < ourdepth)
    {
        // Shadow the pixel by lowering the intensity
        Color *= float4(shadowOpacity, shadowOpacity, shadowOpacity, 1);
    };

    return Color;
}

struct VS_INPUT
{
    float4 Position : POSITION0;
    float3 Normal       : NORMAL0;
};

struct VS_OUTPUT
{
    float4 Position     : POSITION;
    float4 TexCoord     : TEXCOORD0;
    float3 Normal       : TEXCOORD1;
    float4 WorldPos     : TEXCOORD2;
    float4 ClipDistances    : TEXCOORD3;
};

VS_OUTPUT MultiTexturedNormaledVS( VS_INPUT input)
{
     VS_OUTPUT Output;

     Output.Position = mul(input.Position, WorldViewProjection);
     Output.WorldPos = mul(input.Position, World);
     Output.Normal = normalize(mul(input.Normal, World));

     Output.TexCoord.x = input.Position.x * 0.03f / TerrainScale;
     Output.TexCoord.y = input.Position.z * 0.03f / TerrainScale;

     Output.TexCoord.z = input.Position.x / (TerrainWidth * TerrainScale);
     Output.TexCoord.w = input.Position.z / (TerrainWidth * TerrainScale);

     Output.ClipDistances = dot(Output.WorldPos, ClippingPlane);

     return Output;
}

float4 MultiTexturedNormaledPS(VS_OUTPUT input) : COLOR0
{
     if ( UsingClippingPlane )
     {
         clip(input.ClipDistances);
     }

     float3 TerrainColorWeight = tex2D(TextureMapSampler, input.TexCoord.zw);

     // @TODO: Determine if this quad-tree node has all three textures on it, so we don't have to multiply by
     //        unneeded values.
     float4 normalFromMap = (2.0f * tex2D(RockNormalSampler, input.TexCoord) - 1.0f)    * TerrainColorWeight.r;
     normalFromMap += (2.0f * tex2D(GrassNormalSampler, input.TexCoord) - 1.0f)         * TerrainColorWeight.g;
     normalFromMap += (2.0f * tex2D(SandNormalSampler, input.TexCoord) - 1.0f)          * TerrainColorWeight.b;

     float4 Color = tex2D(RockTextureSampler, input.TexCoord)   * TerrainColorWeight.r;
     Color += tex2D(GrassTextureSampler, input.TexCoord)        * TerrainColorWeight.g;
     Color += tex2D(SandTextureSampler, input.TexCoord)         * TerrainColorWeight.b;

     // Factor in normal mapping and terrain vertex normals as well in lighting of the pixel
     float lightingFactor = saturate(dot(normalFromMap + input.Normal, -LightDir));

     float4 WorldPosToCam = float4(input.WorldPos - CameraPos);
     float d = length(WorldPosToCam);

     Color = ComputeShadowColor(input.WorldPos, Color);

     // Handle fog differently if there is water, and also handle if the camera is underwater
     float waterTerrainDiff = WaterElevation - input.WorldPos.y;

     float fogValue = FogThinning;
     float fogAlt = FogAltitude;
     float fogNearDist = FogNear;
     float fogFarDist = FogFar;
     float4 fogColor = FogColor;

     // If this pixel on the terrain is underwater, and the water elevation is not the default value
     if ( waterTerrainDiff > 0 )
     {
         if ( CameraPos.y < WaterElevation )
         {
            fogValue = 1;   // Setting FogThinning to 1 makes elevation-based fog become distance-based
            fogAlt = WaterElevation;
            fogNearDist = -200;
            fogFarDist = 250;
            fogColor = WaterColor;
         }
         else
         {
            fogValue = 1;   // Setting FogThinning to 1 makes elevation-based fog become distance-based
            fogAlt = WaterElevation;
            fogNearDist = 0;
            fogFarDist = 10;
            d = waterTerrainDiff;

            waterTerrainDiff = clamp(waterTerrainDiff, 0, 100);
            fogColor = lerp(lightWater, darkWater, waterTerrainDiff / 100.f);
         }
     }

     float l = saturate((d - fogNearDist) / (fogFarDist - fogNearDist) / clamp(input.WorldPos.y / fogAlt + 1, 1, fogValue));

     Color.rgb *= (AmbientColor + (DiffuseColor * lightingFactor) + (SpecularColor * lightingFactor));
     Color.a = 1.0f;

     return lerp(Color, fogColor, l);
}

technique MultiTexturedNormaled
{
     pass Pass0
     {
         VertexShader = compile vs_1_1 MultiTexturedNormaledVS();
         PixelShader = compile ps_2_0 MultiTexturedNormaledPS();
     }
}

```

# Answer
I was able to solve this problem by optimizing the shader.

This first change will get us down from 68 instructions to 67. We have logic in the shader that only occurs for pixels of terrain that are below the water level, you can see this logic separated by this code:

```
if ( waterTerrainDiff > 0 )
{
}

```

Within that was this:

```
waterTerrainDiff = clamp(waterTerrainDiff, 0, 100);

```

The clamp is to keep the value between 0 and 100, but we already know it must be greater than zero because of the condition that `(waterTerrainDiff > 0)`, so instead of clamp we can use min:

```
waterTerrainDiff = min(waterTerrainDiff, 100);

```

This brings us down to 68 instruction slots. Now, on the next line of the shader was this:

```
fogColor = lerp(lightWater, darkWater, waterTerrainDiff / 100.f);

```

We were clamping the value of `waterTerrainDiff` between 0 and 100, but then just dividing the value by 100.f, so if we include the division in the `min` call, then we save another instruction, which brings us down to 67.

```
waterTerrainDiff = min(waterTerrainDiff / 100.f, 1.f);
fogColor = lerp(lightWater, darkWater, waterTerrainDiff);

```

And the second important change, will bring us from 67 instructions down to 64, which is the exact number we need. We had a way to split up the parts of the shader that occurred when the camera was underwater, with the part when the camera that was above the water. So this code below, will get split into two seperate shader techniques:

```
if ( waterTerrainDiff > 0 )
{
    if ( CameraPos.y < WaterElevation )
    {
        fogValue = 1;   // Setting FogThinning to 1 makes elevation-based fog become distance-based
        fogAlt = WaterElevation;
        fogNearDist = -200;
        fogFarDist = 250;
        fogColor = WaterColor;
    }
    else
    {
        fogValue = 1;   // Setting FogThinning to 1 makes elevation-based fog become distance-based
        fogAlt = WaterElevation;
        fogNearDist = 0;
        fogFarDist = 10;
        d = waterTerrainDiff;

        waterTerrainDiff = min(waterTerrainDiff / 100.f, 1.f);
        fogColor = lerp(lightWater, darkWater, waterTerrainDiff);
    }
}

```

This goes in the shader technique that is called when the camera is underwater:

```
if ( waterTerrainDiff > 0 )
{
    fogValue = 1;
    fogAlt = WaterElevation;
    fogNearDist = -200;
    fogFarDist = 250;
    fogColor = WaterColor;
}

```

And here's the part in the shader technique that is called when the camera is above the water:

```
if ( waterTerrainDiff > 0 )
{
    fogValue = 1;
    fogAlt = WaterElevation;
    fogNearDist = 0;
    fogFarDist = 10;
    d = waterTerrainDiff;

    waterTerrainDiff = min(waterTerrainDiff / 100.f, 1.f);
    fogColor = lerp(lightWater, darkWater, waterTerrainDiff);
}

```

Here's a screenshot of the shader in action.

Below is the full resulting shader after the changes. It's quite a bit larger, but it meets the necessary criteria.

```
    //------- Constants --------
float4x4 View               : VIEW;
float4x4 Projection         : PROJECTION;
float4x4 World              : WORLD;
float4x4 WorldViewProjection: WORLDVIEWPROJECTION;
float4x4 LightViewProjection: LIGHTVIEWPROJECTION;
float4 LightDir             : LIGHT_DIRECTION;
float4 AmbientColor         : AMBIENT_COLOR;
float AmbientPower          : AMBIENT_POWER;
float4 SpecularColor        : SPECULAR_COLOR;
float SpecularPower         : SPECULAR_POWER;
float4 DiffuseColor         : DIFFUSE_COLOR;
float4 CameraForward        : VIEW_FORWARD;
float4 CameraPos            : VIEW_POS;
float FogNear               : FOG_NEAR;
float FogFar                : FOG_FAR;
float4 FogColor             : FOG_COLOR;
float FogAltitude           : FOG_ALTITUDE;
float FogThinning           : FOG_THINNING;

float TerrainScale          : SCALE_FACTOR;
float TerrainWidth          : TERRAIN_WIDTH;

float WaterElevation        : WATER_ELEVATION;
float4 WaterColor           : WATER_COLOR;

bool UsingClippingPlane     : USING_CLIPPING_PLANE;
float4 ClippingPlane        : CLIPPING_PLANE;

bool CameraUnderwater       : CAMERA_UNDERWATER;

float DepthBias = 0.0001f;

float4 darkWater = float4(0.0f, 0.126f, 0.367f, 1.0f);
float4 lightWater = float4(0.0f, 0.235f, 0.44f, 1.0f);

//------- Texture Samplers --------
Texture TextureMap          : TEXTURE_MAP;
sampler TextureMapSampler = sampler_state { texture = <TextureMap> ; magfilter = LINEAR; minfilter = LINEAR;
                                                                         mipfilter = LINEAR; AddressU  = Wrap;
                                                                         AddressV  = Wrap; AddressW  = Wrap;};

Texture GrassTexture        : GRASS_TEXTURE;
sampler GrassTextureSampler = sampler_state { texture = <GrassTexture> ; magfilter = LINEAR; minfilter = LINEAR;
                                                                         mipfilter=LINEAR; AddressU  = Wrap;
                                                                         AddressV  = Wrap; AddressW  = Wrap;};

Texture SandTexture         : SAND_TEXTURE;
sampler SandTextureSampler = sampler_state { texture = <SandTexture> ; magfilter = LINEAR; minfilter = LINEAR;
                                                                       mipfilter =LINEAR; AddressU  = Wrap;
                                                                       AddressV  = Wrap; AddressW  = Wrap;};

Texture RockTexture         : ROCK_TEXTURE;
sampler RockTextureSampler = sampler_state { texture = <RockTexture> ; magfilter = LINEAR; minfilter = LINEAR;
                                                                       mipfilter = LINEAR; AddressU  = Wrap;
                                                                       AddressV  = Wrap; AddressW  = Wrap;};

Texture GrassNormal         :GRASS_NORMAL;
sampler2D GrassNormalSampler : TEXUNIT1 = sampler_state
{ Texture   = (GrassNormal); magfilter = LINEAR; minfilter = LINEAR;
                             mipfilter = LINEAR; AddressU  = Wrap;
                             AddressV  = Wrap; AddressW  = Wrap;};

Texture SandNormal          : SAND_NORMAL;
sampler2D SandNormalSampler : TEXUNIT1 = sampler_state
{ Texture   = (SandNormal); magfilter  = LINEAR; minfilter = LINEAR;
                             mipfilter = LINEAR; AddressU  = Wrap;
                             AddressV  = Wrap; AddressW  = Wrap;};

Texture RockNormal          : ROCK_NORMAL;
sampler2D RockNormalSampler : TEXUNIT1 = sampler_state
{ Texture   = (RockNormal); magfilter = LINEAR; minfilter = LINEAR;
                             mipfilter=LINEAR; AddressU  = Wrap;
                             AddressV  = Wrap; AddressW  = Wrap;};

Texture ShadowMap               : SHADOW_MAP;
sampler ShadowMapSampler = sampler_state { texture = <ShadowMap>; MinFilter = POINT; MagFilter = POINT;
                                                                  MipFilter = NONE;  AddressU = Clamp;
                                                                  AddressV = Clamp;  AddressW  = Wrap; };

// For any shader that can support shadow mapping, simply add
// this function and call it from your pixel shader. Of course,
// you'll need to make sure this shader and material are setup to
// receive the ShadowMap sampler, and any needed parameters (e.g. LightViewProjection)
float4 ComputeShadowColor(float4 worldPos, float4 Color)
{
     // Find the position of this pixel in light space
    float4 lightingPosition = mul(worldPos, LightViewProjection);

    // Find the position in the shadow map for this pixel
    float2 ShadowTexCoord = 0.5 * lightingPosition.xy /
                            lightingPosition.w + float2( 0.5, 0.5 );
    ShadowTexCoord.y = 1.0f - ShadowTexCoord.y;

    // Get the current depth stored in the shadow map
    float4 shadowInfo = tex2D(ShadowMapSampler, ShadowTexCoord);
    float shadowdepth = shadowInfo.r;
    float shadowOpacity = 0.5f + 0.5f * (1 - shadowInfo.g);

    // Calculate the current pixel depth
    // The bias is used to prevent folating point errors that occur when
    // the pixel of the occluder is being drawn
    float ourdepth = (lightingPosition.z / lightingPosition.w) - DepthBias;

    // Check to see if this pixel is in front or behind the value in the shadow map
    if ( shadowdepth < ourdepth)
    {
        // Shadow the pixel by lowering the intensity
        Color *= float4(shadowOpacity, shadowOpacity, shadowOpacity, 1);
    };

    return Color;
}

//------- Technique: MultiTexturedNormaled --------

 struct VS_INPUT
 {
     float4 Position    : POSITION0;
     float3 Normal      : NORMAL0;
 };

struct VS_OUTPUT
{
    float4 Position     : POSITION;
    float4 TexCoord     : TEXCOORD0;
    float3 Normal       : TEXCOORD1;
    float4 WorldPos     : TEXCOORD2;
    float4 ClipDistances    : TEXCOORD3;
};

 VS_OUTPUT MultiTexturedNormaledVS( VS_INPUT input)
 {
     VS_OUTPUT Output;

     Output.Position = mul(input.Position, WorldViewProjection);
     Output.WorldPos = mul(input.Position, World);
     Output.Normal = normalize(mul(input.Normal, World));

     Output.TexCoord.x = input.Position.x * 0.03f / TerrainScale;
     Output.TexCoord.y = input.Position.z * 0.03f / TerrainScale;

     Output.TexCoord.z = input.Position.x / (TerrainWidth * TerrainScale);
     Output.TexCoord.w = input.Position.z / (TerrainWidth * TerrainScale);

     Output.ClipDistances = dot(Output.WorldPos, ClippingPlane);

     return Output;
 }

 float4 MultiTexturedNormaledPS(VS_OUTPUT input) : COLOR0
 {
     if ( UsingClippingPlane )
     {
         clip(input.ClipDistances);
     }

     float3 TerrainColorWeight = tex2D(TextureMapSampler, input.TexCoord.zw);

     // @TODO: Determine if this quad-tree node has all three textures on it, so we don't have to multiply by
     //        unneeded values.
     float4 normalFromMap = (2.0f * tex2D(RockNormalSampler, input.TexCoord) - 1.0f)    * TerrainColorWeight.r;
     normalFromMap += (2.0f * tex2D(GrassNormalSampler, input.TexCoord) - 1.0f)         * TerrainColorWeight.g;
     normalFromMap += (2.0f * tex2D(SandNormalSampler, input.TexCoord) - 1.0f)          * TerrainColorWeight.b;

     float4 Color = tex2D(RockTextureSampler, input.TexCoord)   * TerrainColorWeight.r;
     Color += tex2D(GrassTextureSampler, input.TexCoord)        * TerrainColorWeight.g;
     Color += tex2D(SandTextureSampler, input.TexCoord)         * TerrainColorWeight.b;

     // Factor in normal mapping and terrain vertex normals as well in lighting of the pixel
     float lightingFactor = saturate(dot(normalFromMap + input.Normal, -LightDir));

     float4 WorldPosToCam = float4(input.WorldPos - CameraPos);
     float d = length(WorldPosToCam);

     Color = ComputeShadowColor(input.WorldPos, Color);

     // Handle fog differently if there is water, and also handle if the camera is underwater
     float waterTerrainDiff = WaterElevation - input.WorldPos.y;

     float fogValue = FogThinning;
     float fogAlt = FogAltitude;
     float fogNearDist = FogNear;
     float fogFarDist = FogFar;
     float4 fogColor = FogColor;

     // If this pixel on the terrain is underwater, and the water elevation is not the default value
     if ( waterTerrainDiff > 0 )
     {
        fogValue = 1;   // Setting FogThinning to 1 makes elevation-based fog become distance-based
        fogAlt = WaterElevation;
        fogNearDist = 0;
        fogFarDist = 30;
        d = waterTerrainDiff;

        waterTerrainDiff = min(waterTerrainDiff / 100.f, 1.f);
        fogColor = lerp(lightWater, darkWater, waterTerrainDiff);
     }

     float l = saturate((d - fogNearDist) / (fogFarDist - fogNearDist) / clamp(input.WorldPos.y / fogAlt + 1, 1, fogValue));

     Color.rgb *= (AmbientColor + (DiffuseColor * lightingFactor) + (SpecularColor * lightingFactor));
     Color.a = 1.0f;

     return lerp(Color, fogColor, l);
 }

 technique MultiTexturedNormaled
 {
     pass Pass0
     {
         VertexShader = compile vs_2_0 MultiTexturedNormaledVS();
         PixelShader = compile ps_2_0 MultiTexturedNormaledPS();
     }
 }

 float4 MultiTexturedNormaledCameraUnderwaterPS(VS_OUTPUT input) : COLOR0
 {
     if ( UsingClippingPlane )
     {
         clip(input.ClipDistances);
     }

     float3 TerrainColorWeight = tex2D(TextureMapSampler, input.TexCoord.zw);

     // @TODO: Determine if this quad-tree node has all three textures on it, so we don't have to multiply by
     //        unneeded values.
     float4 normalFromMap = (2.0f * tex2D(RockNormalSampler, input.TexCoord) - 1.0f)    * TerrainColorWeight.r;
     normalFromMap += (2.0f * tex2D(GrassNormalSampler, input.TexCoord) - 1.0f)         * TerrainColorWeight.g;
     normalFromMap += (2.0f * tex2D(SandNormalSampler, input.TexCoord) - 1.0f)          * TerrainColorWeight.b;

     float4 Color = tex2D(RockTextureSampler, input.TexCoord)   * TerrainColorWeight.r;
     Color += tex2D(GrassTextureSampler, input.TexCoord)        * TerrainColorWeight.g;
     Color += tex2D(SandTextureSampler, input.TexCoord)         * TerrainColorWeight.b;

     // Factor in normal mapping and terrain vertex normals as well in lighting of the pixel
     float lightingFactor = saturate(dot(normalFromMap + input.Normal, -LightDir));

     float4 WorldPosToCam = float4(input.WorldPos - CameraPos);
     float d = length(WorldPosToCam);

     Color = ComputeShadowColor(input.WorldPos, Color);

     // Handle fog differently if there is water, and also handle if the camera is underwater
     float waterTerrainDiff = WaterElevation - input.WorldPos.y;

     float fogValue = FogThinning;
     float fogAlt = FogAltitude;
     float fogNearDist = FogNear;
     float fogFarDist = FogFar;
     float4 fogColor = FogColor;

     // If this pixel on the terrain is underwater, and the water elevation is not the default value
     if ( waterTerrainDiff > 0 )
     {
        fogValue = 1;   // Setting FogThinning to 1 makes elevation-based fog become distance-based
        fogAlt = WaterElevation;
        fogNearDist = -200;
        fogFarDist = 250;
        fogColor = WaterColor;
     }

     float l = saturate((d - fogNearDist) / (fogFarDist - fogNearDist) / clamp(input.WorldPos.y / fogAlt + 1, 1, fogValue));

     Color.rgb *= (AmbientColor + (DiffuseColor * lightingFactor) + (SpecularColor * lightingFactor));
     Color.a = 1.0f;

     return lerp(Color, fogColor, l);
 }

 technique MultiTexturedNormaledCameraUnderwater
 {
     pass Pass0
     {
         VertexShader = compile vs_2_0 MultiTexturedNormaledVS();
         PixelShader = compile ps_2_0 MultiTexturedNormaledCameraUnderwaterPS();
     }
 }

```
> 3 votes

# Answer
> Calculates is the camera is underwater, and applies a "water fog" in that case.

The calculation could be done by you on the CPU and passed in instead?

> but really I'm wondering about how other engines would manage to get these features into an SM 2.0 shader

Sorry I went the shader critique route :/

In my terrain rendering I often bake colours in textures and the tainting for depth underwater (or whitening for high peaks) could be precomputed in this way.
> 0 votes

---
Tags: shaders, hlsl, terrain-rendering
---


# Question
Title: Making a 2D game with responsive resolution
I am making a 2D game, however I wish for it to be resolution agnostic.

My target resolution i.e. where things look as intended is 1600 x 900.

My ideas are:

Make the HUD stay fixed to the sides no matter what resolution, use different size for HUD graphics under a certain resolution and another under a certain large one.

Use large HD PNG sprites/backgrounds which are a power of 2, so they scale nicely. No vectors.

Use the player's native resolution. Scale the game area (not the HUD) to fit (resulting zooming in some and cropping the game area sides if necessary for widescreen, no stretch), but always fill the screen.

Have a min and max resolution limit for small and very large displays where you will just change the resolution(?) or scale up/down to fit.

What I am a bit confused though is what math formula I would use to scale the game area correctly based on the resolution no matter the aspect ratio, fully fit in a square screen and with some clip to the sides for widescreen.

Pseudocode would help as well. :)

# Answer
> 1 votes
You can scale the game image like follows.

```
width_scale = screen_width / game_width
height_scale = screen_height / game_height

scale = minimum(width_scale, height_scale)

game_on_screen = scale * game

```

The following image depicts the scaling effect of the game (left), in a portrait (center) and landscape (right) screen respectively

# Answer
> 0 votes
What I'm doing, as I target various mobile device sizes, is to find a common area (proportion-wise, not pixel-wise) for all of them and include crucial things only inside this minimum area. I then draw all things in the biggest size of all (so that e.g. a more unimportant cave wall may be visible on the iPhone 5, but only a little bit of it on the iPhone 4 or iPad). I then provide 2 sizes of graphics if needed and tell my platform, Corona, to zoom in and crop edges for every device, thus I have never black letterbox borders.

For mobile, my preferred work resolution is thus 2424 x 1536. I then resize most things to 50% for exporting. (iPad Retina would require 100%, which can be saved as eg. @2x, but you may decide not to add too many huge graphics.) Full-size PNG attached below. Imagine e.g. an iPhone 5 would cover the full width but would have it's upper and bottm parts cut off, but would be "safe" inside the white rectangle.

---
Tags: 2d, graphics, textures, screen, resolution
---


title: Throw object towards predefined place?

text:
# Question
Title: Throw object towards predefined place?
I have a 2D side-view game with object attributes such as x, y, speedX, etc. Now I want to throw a given object from any place on the screen onto a defined goal place, in such a way that its trajectory looks somewhat normal (with gravity, it making a curve and such). Imagine an enemy is destroyed and what he stole flies from him back towards the stolen object's origin. (I do have physics via Box2D in this game, but for this particular need, it seems I require a manual approach; for one thing, the object is allowed to pass other bridges and such for the time it flies back to its main bridge.)

How would I go about this? I've tried moving manually by adjusting towards a target speed and such, but the trajectory and timing looks very unnatural. Thanks!

# Answer
> 2 votes
Wiki has article about projectile trajectory here.

Maybe also this will help you (it helped me). It's brief explanation of two approaches to your problem - variable strength and angle of projectile being shoot. At the end of this post, there's short "Try it yourself!" section, where small JavaScript implementation exists (which may, again, help you).

Good luck!

# Answer
> 4 votes
One approach would be to use a parabolic trajectory, which is the shape that normal projectiles take.

We can use three points to define the parabola:

* Initial object position
* Final object position
* Turning point

The turning point can be a constant horizontal and vertical distance away from the target, it just needs to flip slides to suit the initial position.

The parabola equation we are using is

Solve the following simultaneous equations to find a and b.

Now we might be interested in finding the launch angle and a velocity. First we manipulate the projectile motion equations to obtain the following

The above equation takes the parabolic form we outlined above. To find the launch angle theta we can simply use

If we know the animation time t we can find the launch velocity v\_0 with

---
Tags: physics
---


# Question
Title: GLSL: Why can only some of the matrices be found?
I've been learning GLSL and to start I've been trying to replicate the fixed-function pipeline functionality with it, for 2D graphics. I've done it successfully in most things, so far, but I came into a weird problem. First of all, here are my shaders:

```
static const char gVertexSource[] =
    "#version 120\n"
    "in vec4 vertex;\n"
    "in vec4 color;\n"
    "in vec2 texCoord;\n"
    "uniform mat4 projection = mat4(1);\n"
    "uniform mat4 model = mat4(1);\n"
    "uniform mat4 view = mat4(1);\n"
    "varying vec4 outColor;\n"
    "varying vec2 texUV;\n"
    "void main() {\n"
    "  gl_Position = projection * view * model * vertex;\n"
    "  outColor = color;\n"
    "  texUV = texCoord;\n"
    "}\n";

static const char gFragmentSource[] =
    "#version 120\n"
    "uniform int textured = 1;\n"
    "uniform sampler2D texture;\n"
    "varying vec4 outColor;\n"
    "varying vec2 texUV;\n"
    "void main() {\n"
    "   float ftextured = textured;\n"
    "   gl_FragColor = (texture2D(texture, texUV) + vec4(abs(1 - ftextured)) ) * outColor;\n"
    "}\n";

```

It compiles fine and works fine, but something is wrong. This shader allows me to pass geometry with texcoords and colors and texture the final fragment while combining it with the color. In the projection matrix I set an orthographic camera which works perfectly. As you can see they are all default initialized to the identity, so even if i dont set the other matrices nothing happens.

So far so good. After this, i wanted to set the model mat4 with the actual transform of an object so it scales and re-positions within the screen. For my surprise, `glGetUniformLocation()` always returns -1 for the model uniform, even though it works fine for projection. So I tried to set the view matrix instead of the model matrix, which would end up in the same final result, and again, for my surprise, it worked.

I figured it could be something related to the order of declaration / order of multiplication or even the name of the uniform, so i tried many combinations always with the same result. Also tought I could be running out of uniform space (unlikely with only the basic matrices and my high end system), so I tried adding another mat4 uniform and that one could also be found correctly..

I really dont get what I could be doing wrong and I tried most things to debug this problem.. Any ideas on what is wrong with this shader?

# Answer
Uniform variables that do not contribute to the final result in the shader are optimized away by the compiler. So when you declare uniform mat4 and it does not contribute to the final result of the program like `gl_FragColor` (even if its used in the calculations ), the shader compiler will remove it from the program and always return -1 when you query its location.

The other reasons could be

* you are not binding the correct shader program (using `glUseProgram` before using `glGetUniformLocation`).
* if you misspell the variable name to `glGetUniformLocation`.

You can also debug it:

* Query all your uniform variable names using `glGetActiveUniform`.
* check if openGL generate any errors, I recommend gDebugger.
> 3 votes

# Answer
I found the problem, it was a very silly thing as expected, sorry to waste your time.

Turns out the model uniform was at location 0, and i was checking the location's validity with (location \> 0) instead of (location != -1).

Thanks everyone.
> 1 votes

---
Tags: opengl, glsl
---


# Question
Title: Is it possible to make isometric game of 200 * 200 tiles per map in Unity?
We made an isometric game in AndEngine. Now we want to convert this game into Unity. I am searching for tiles map support/plugin in Unity. I come across a plugin called Map and nav http://forum.unity3d.com/threads/138355-Tile-Based-Map-amp-Nav . but the problem is it only support 50\*50 tiles per map. My map is 200 * 200 tiles. I want to know is there any plugin or way to acheive 200 * 200 tiles per map in Unity ?

Thanks

# Answer
> 2 votes
I assume you're talking about mobile, and a 3D game. If either of these is untrue, you should be perfectly fine in any situation.

I'm currently working on a 3D tile-based mobile game. I've written my own tile engine for Unity (note: I didn't write my own renderer, I honestly don't see the point). In the game the camera rotation is fixed and it's ortographic, which allows some optimizations.

While having a 200x200 map is easily possible (and has been done) with my system, older phones like my Samsung Galaxy S are simply too slow to use it, even after optimizations. Fps can be between 5 and 20 which means it's not enjoyable.

One important thing I noticed is that after optimizing graphics a lot (custom static batching, throwing away invisible sides, generating a custom terrain mesh, etc.) the choke point wasn't really graphics. Since with isometric games you have a pretty good idea of what the player sees at each point, it's very easy to minimize the amount of data that needs to be loaded.

So right now the weakest link is the amount of units and non-static stuff on the map. Pathfinding is acceptable with a pre-calculated graph (using A\* from Aaron Granberg). For collisions I use an optimized model with boxes spanning multiple tiles (pre-calculated) and unity's physics engine, but I don't do any dynamic body stuff, only checking for collisions in certain situations (player movement mostly).

So the final answer is: yes. You may have to cut back on the features, but it is definitely possible.

# Answer
> 3 votes
It is possible to make an isometric game with 200 * 200 tiles per map in Unity3D, but you will have to make your own renderer and make several optimizations to your code, probably more than you would have anticipated.

As for your renderer, you will want to have complete control over your mesh data so you can do things like hide faces that are not visible to the camera, removing vertices that are to far away, combine meshes, and more.

For code optimizations, the way you index your tiles could arguably be the most important factor, as that is 200 * 200 potential objects. You should build a queue for loading the tile objects or their data.

---
Tags: unity, isometric
---


title: Java Slick2d collision feedback

text:
# Question
Title: Java Slick2d collision feedback
I'm trying to build a collision response ( it uses vectors2f from slick2d ) so that enemies don't overlap on each other so basicly what I'm doing right now is, I loop trough all enemies in array trough the same array of enemies to check if they collide or not , if they collide I swap their velocity.

The code partialy works for some enemies and doesn't for others. If anyone can give me some links how to code this or advise me how to do it , that would be nice. I already google'd to see if I could find something like this but I couldn't find anything.

**Here is the code for the current code i got:** http://pastebin.com/AbCvTtV0

**Slick 2d documentation** : http://www.slick2d.org/javadoc/

# Answer
I'm going to expand on Dirk's answer a little bit.

> You might get 2 collisions (for example once for colliding enemy 2 with enemy 5 and once for colliding enemy 5 with enemy 2) and thus reverting the swapping of velocities. You could resolve this by starting your second loop not with k = 0 but with k = i+1.

This will allow you to get rid of the IF block starting on line 7: `if(enemies.get(i) != enemies.get(k))`

> (Furthermore, you should make sure the collision boxes are not overlapping after you swapped the velocities.)

To do this you should add some code to your IF block starting on line 12. Just make sure that enemies.get(i) and enemies.get(k) are not overlapping anymore by either moving one or both of them. If you need further help consider posting your Enemy class so we can take a look at what methods you have available.
> 1 votes

# Answer
You might get 2 collisions (for example once for colliding enemy 2 with enemy 5 and once for colliding enemy 5 with enemy 2) and thus reverting the swapping of velocities. You could resolve this by starting your second loop not with k = 0 but with k = i+1.

(Furthermore, you should make sure the collision boxes are not overlapping after you swapped the velocities.)
> 1 votes

# Answer
This question is probably irrelevant now, but for future reference, as well with anyone coming here with the same problem:

I would use the "java.awt.rectangle", and store the X, Y, and width and height values there. It includes one of my favorite methods: **public boolean intersects(Rectangle other)**. I'm assuming there is a class called "Entity", but if the name for your enemy class is different, just use that. I'm also assuming that you have an arraylist of entities somewhere. Again, if it is a hashmap or just regular array, or has a different name, replace the "Entity e: entities" with the proper name and method to access your data.

Stick this in the entity class (no need to modify it):

```
private java.awt.Rectangle bounds;

public Entity(/*your other paramaters here*/, java.awt.Rectangle bounds){
    this.bounds = bounds;
}

/* Other methods go here */

public void setBounds(java.awt.Rectangle bounds){
    this.bounds = bounds;
}

public java.awt.Rectangle getBounds(){
    return bounds;
}

public boolean colliding(Entity possibleCollider){
    return bounds.intersects(possibleCollider.getBounds());
}

```

Then, all you have to do is test for collisions in your main loop (or updating thread; doesn't matter where it goes, as long as it's being checked regularly). You may need to modify it if you do not have an arraylist as your entity storage mechanism:

```
for (Entity e1: entities){ // Compare 1 entity
    for (Entity e2: entities){ //to all the others
        if (e1 != e2){
            //This is indeed another entity, not the same one.

            e1.velocity.x = -e1.velocity.x
            /* You can reverse just the x
             * if you want; otherwise do the same
             * thing with e2. Also, if you want the Y
             * direction reversed as well, simply copy and replace X with Y.
             */

            /* Entity is colliding with another,
             * Do whatever else you need to here (such as applying damage)
             */
        }
    }
}

```
> 1 votes

# Answer
public void updateEnemy(ArrayList enemies, int delta, Player player){

```
    for (int i = 0; i < enemies.size(); ++i)
        enemies.get(i).update(delta);

// Then run the collision code
for (int i = 0; i < enemies.size(); ++i)
{

    enemies.get(i).update(delta);

    enemies.get(i).velocity = new Vector2f(player.getX() - enemies.get(i).getX(), player.getY() - enemies.get(i).getY());
    enemies.get(i).position.add(enemies.get(i).velocity.scale(enemies.get(i).speed));

        for (int j = 0; j < enemies.size(); ++j)
        {
                if (j == i) continue; // so it doesn't check itself

                // Calculate the euclidian distance between a and b
                float distanceX = enemies.get(i).getX() - enemies.get(j).getX();
                float distanceY = enemies.get(i).getY() - enemies.get(j).getY();

                float distance = (float) Math.sqrt(distanceX * distanceX + distanceY * distanceY);
                float overlap,directionX,directionY;
                if (distance < 30)
                {
                        overlap = 30 - distance;

                        // Normalize and set to half the overlap
                        directionX = (distanceX / distance) * (overlap / 2);
                        directionY = (distanceY / distance) * (overlap / 2);

                        // Update a and b's positions
                        enemies.get(i).position.x =(enemies.get(i).position.x + directionX);
                        enemies.get(i).position.y =(enemies.get(i).position.y + directionY);

                        enemies.get(j).position.x =(enemies.get(j).position.x - directionX);
                        enemies.get(j).position.y =(enemies.get(j).position.y - directionY);
                }
        }
}
}

```
> 0 votes

---
Tags: java, slick, collision-avoidance
---


title: Design to handle logic within a state

text:
# Question
Title: Design to handle logic within a state
I am designing a new game and I am trying out the entity-component design where entities are comprised of groups of components holding a bunch of attributes. I also have a stack of 'game states' and 'game systems'. On creation, a new state grabs a bunch of (singleton) system s from a provider of systems. The systems are created at the beginning and maintain a list of entities that are relevant to it by inspecting what components are on the entity. At the moment I have the game logic within a bunch of 'systems', the state simply maintains a list of systems to update/draw.

I realize that the state should really be holding all information relevant to the state. For instance the state should be holding the information on who's turn it is e.t.c. I have it so the system stores all information on the state at the moment and accesses it via the observer pattern. This is turn leads to all sorts of problems as it pretty much couples the system s to the state + it makes the code pretty messy and inefficient.

For instance I have a movement system that is interested in entites with the 'movable' component. The system needs to read from the state who can move at this point. How far they are allowed to move and also controller input to actually do the move. For each of these things I must access the observer methods to modify the state from the system.

The game is turn based at the moment and one of the states is a movement state, it has two systems registered to it, a movement system and a camera system which it updates in turn.

At the moment the movement system gets from the state an entityId representing the 'selected' entity and checks input to see if the player is moving it. If moved the 'location' component is updated on the entity and the system stores the location onto the state via the observer. The camera system then looks up this location on the state and updates the entity with the 'camera' component with this location.

The solution I have at the moment does not seem elegant at all and it is extremely long winded to implement even simple functionality. I am thinking I am doing something fundamentally wrong with the design. I have a few questions that come to mind:

1. Should the state hold the list of entities and do the logic?
    * The systems should maybe only be pure logic calls at this point that hold no variables.
    * How would I handle entities in this situation? I can envisage a state holding loads of entities only to be used for specific segments of the logic.
2. Should the components hold the logic?
3. Should I just make the systems into 'micro-states'? Which is to make them separate instances and have them hold local variables needed for the state.

# Answer
> 3 votes
There are currently no established best practices in component entity system engines design (unlike MVC for example).

My personal biased preferred way is to:

1. Treat entities as nothing more then an IDs that "group" components together.
2. Put data/state into components.
3. Put logic into some components - if they react to messages.
4. Put logic into systems - if something needs to be updated every cycle of the game loop.
5. Make components communicate with each other via messaging.
6. Make systems iterate over all components of a specific type.

---
Tags: component-based, entity-system, state, fsm
---


title: Blender Texture Seam

text:
# Question
Title: Blender Texture Seam
I am trying to follow this tutorial to create a brushed metal "start" button. (I am very new to all of this) I want the button to look nice when rendered in a game engine.

For some reason I can not figure out how to get the texture to wrap cleanly without seams. I modeled the "pill" part of the button using mirror and subsurf modifiers. The texture is a free version from cgtextures that is supposedly ready to be tiled. I created the various textures (normal/specular/etc) using CrazyBump as mentioned in the tutorial.

But now I'm stuck! The seems are driving me insane

# Answer
> 3 votes
You need to look up how to unwrap and layout your UVs.

Here is a link to get you started:

http://3d.about.com/od/3d-101-The-Basics/a/Surfacing-101-Creating-A-UV-Layout.htm

The tutorial you are following is laying out a texture on a plane, and so his texture is not wrapping around a 3D object. When apply 2D texture to a 3D object the UVs need to be laid out correctly so that it hides the seam or is unnoticeable.

I haven't done 3D work in a while, but I hope this helps.

---
Tags: textures, models, blender
---


# Question
Title: Bodies do not stay sticked together by joint in retina display
I'm rehearsing on Box2D revolute joints. Everything's going pretty well except for one thing. For some reason bodies joined together with revolute joints do not stay sticked, they start getting apart from each other from the app start when I run it on retina device or simulator. On non retina device it works just fine, as expected. Here's the screenshot of the non-retina version:

And here's the behavior when I run the same app on retina device/simulator:

I'm taking content scale factor into account.

# Answer
Ok, I've finally found the reason for the wrong behavior on retina display. The problem arose from the fact that although I was taking care of the content scale factor in the other parts of the program, I was not taking it into account when initializing joint definitions. It used to be like this:

```
myRevoluteJointDef.Initialize(body1,body2,b2vec2(10.0,5.0));

```

This way the joints did not work properly and bodies were "seesawing" around some other point. After I changed the code to this:

```
myRevoluteJointDef.Initialize(body1,body2,b2vec2(10.0/SCALE_FACTOR,5.0/SCALE_FACTOR));

```

everything worked as it should. Note that the SCALE\_FACTOR is a macro I've defined in a header file that simply takes the current device's content scale factor, which is 2 in retina display and 1 in non-retina one.
> 1 votes

---
Tags: ios, box2d
---


# Question
Title: Best way to network the movement of 2D tanks?
I'm working on a multiplayer Flash game with a Python server and I have a quick question regarding how I should send positional updates for tanks for other players.

Should I choose

**Option A**:

When the player presses the move key, send the new velocity to the server and let the server calculate the new position per tick?

or

**Option B**:

When the player presses the move key, send the new position to the server and calculate the velocity clientside?

Which is the best option, in your opinion? What is most common? What will have less issues?

Other suggestions are welcome, I don't really know what I'm doing here. ;)

# Answer
My understanding is that you **should never trust the client** in a multiplayer game and therefore aim to do any gameplay critical processing server-side. The disadvantage of pure client-side logic is that there is no verification

In other words you should probably go with a third option; send an abstract representation of what the player wants to do to the server. For example you would send a 'move key' event to the server, which would then calculate the velocity/position of the player and then update the view on the client.

However, you don't want your clients to be waiting on the server before updating the game state as this could cause lagging issues. A better solution may be to update the game state on the client as well, whilst treating the server state as authoritative and overriding the client if necessary.
> 6 votes

# Answer
What you are looking for is 'Client-Side Prediction'.

Basically each client predicts where everything is going to be until it receives an update from the server telling it where everything actually is. This way the host is the authority on all movement, but the client doesn't have to wait for a server response before updating the positions of objects.

You will want to combine this with some smoothing so that objects don't appear to teleport every time they receive an update from the server as well.

One thing you may want to do is have the clients be authoritative of their own positions - in other words the clients tell the host where they are, then the host distributes these positions to everyone else. You will have to add checks on the host to ensure no-one is cheating (moving too fast, teleporting and so forth). This will lead to a more responsive game, but can be trickier to implement and fine tune.

It's a bit too long to go into all the details here, but at least I hope I've given you a place to start from.
> 2 votes

# Answer
I would send the key they pressed and have the server determine what action this relates to and take the appropriate actions.

For example, the player pushed the 'w' key. The server gets sent "Hey, this guy pushed the w key". The server would look and see what the W key should do for the player. It finds that this means the player should move forward. The server then moves the player forward in the world.

At the same time, the client is predicting what is going to happen based on the assumption that what it is being told to do is valid. Then, every so often, the client receives data from the server and everything is set to what the server says.

This is actually what causes the rubber band effect you can see sometimes in network games. The client is predicting where things will be at but gets it wrong. Then when it receives new data from the server, it snaps everything to where it should be (IE what the server says).

You should, ideally, never send any significant data from the client to the server because of cheating.

For example, if you sent velocity the player could be altering the data to be something it shouldn't. Even worse would be sending the position to the server. Even if you send just a bool value saying, hey I want to move this way, this could be done automatically by a hack of some sort. Even sending what keys were pressed is still vulnerable, but you can't get anymore unrelated from data than that.
> 0 votes

---
Tags: flash, networking, python, server
---


# Question
Title: How can I make a sprite-sheet-based animation system?
I want to make animations based on a sprite sheet, but I'm stuck implementing it.

The key things I need my code to do are:

* Play through a set of images once (e.g. a jump animation)
* Loop through a set of images continuously (e.g. a walking animation)
* Change an animation's speed

How can I implement such a system?

# Answer
The way I do 2D animations is as follows:

# Sprite Retrieval Class

This class can either load an image file or it can load a sprite from a sprite sheet. It's very self explanatory.

```
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class Sprite {

    private static BufferedImage spriteSheet;
    private static final int TILE_SIZE = 32;

    public static BufferedImage loadSprite(String file) {

        BufferedImage sprite = null;

        try {
            sprite = ImageIO.read(new File("res/" + file + ".png"));
        } catch (IOException e) {
            e.printStackTrace();
        }

        return sprite;
    }

    public static BufferedImage getSprite(int xGrid, int yGrid) {

        if (spriteSheet == null) {
            spriteSheet = loadSprite("AnimationSpriteSheet");
        }

        return spriteSheet.getSubimage(xGrid * TILE_SIZE, yGrid * TILE_SIZE, TILE_SIZE, TILE_SIZE);
    }

}

```

# Animation Class

```
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;

public class Animation {

    private int frameCount;                 // Counts ticks for change
    private int frameDelay;                 // frame delay 1-12 (You will have to play around with this)
    private int currentFrame;               // animations current frame
    private int animationDirection;         // animation direction (i.e counting forward or backward)
    private int totalFrames;                // total amount of frames for your animation

    private boolean stopped;                // has animations stopped

    private List<Frame> frames = new ArrayList<Frame>();    // Arraylist of frames

    public Animation(BufferedImage[] frames, int frameDelay) {
        this.frameDelay = frameDelay;
        this.stopped = true;

        for (int i = 0; i < frames.length; i++) {
            addFrame(frames[i], frameDelay);
        }

        this.frameCount = 0;
        this.frameDelay = frameDelay;
        this.currentFrame = 0;
        this.animationDirection = 1;
        this.totalFrames = this.frames.size();

    }

    public void start() {
        if (!stopped) {
            return;
        }

        if (frames.size() == 0) {
            return;
        }

        stopped = false;
    }

    public void stop() {
        if (frames.size() == 0) {
            return;
        }

        stopped = true;
    }

    public void restart() {
        if (frames.size() == 0) {
            return;
        }

        stopped = false;
        currentFrame = 0;
    }

    public void reset() {
        this.stopped = true;
        this.frameCount = 0;
        this.currentFrame = 0;
    }

    private void addFrame(BufferedImage frame, int duration) {
        if (duration <= 0) {
            System.err.println("Invalid duration: " + duration);
            throw new RuntimeException("Invalid duration: " + duration);
        }

        frames.add(new Frame(frame, duration));
        currentFrame = 0;
    }

    public BufferedImage getSprite() {
        return frames.get(currentFrame).getFrame();
    }

    public void update() {
        if (!stopped) {
            frameCount++;

            if (frameCount > frameDelay) {
                frameCount = 0;
                currentFrame += animationDirection;

                if (currentFrame > totalFrames - 1) {
                    currentFrame = 0;
                }
                else if (currentFrame < 0) {
                    currentFrame = totalFrames - 1;
                }
            }
        }

    }

}

```

The animation class has start, stop, restart and reset to control the animation. You could easily add a boolean to test whether it should loop or not. I will not add this for you.

# Frame Class

```
import java.awt.image.BufferedImage;

public class Frame {

    private BufferedImage frame;
    private int duration;

    public Frame(BufferedImage frame, int duration) {
        this.frame = frame;
        this.duration = duration;
    }

    public BufferedImage getFrame() {
        return frame;
    }

    public void setFrame(BufferedImage frame) {
        this.frame = frame;
    }

    public int getDuration() {
        return duration;
    }

    public void setDuration(int duration) {
        this.duration = duration;
    }

}

```

The Frame class holds an image and a duration associated with that image.

# Implementation

The way I implement the animation is as follows:

**Player.java**

```
// Images for each animation
private BufferedImage[] walkingLeft = {Sprite.getSprite(0, 1), Sprite.getSprite(2, 1}; // Gets the upper left images of my sprite sheet
private BufferedImage[] walkingRight = {Sprite.getSprite(0, 2), Sprite.getSprite(2, 2};
private BufferedImage[] standing = {Sprite.getSprite(1, 0)};

// These are animation states
private Animation walkLeft = new Animation(walkingLeft, 10);
private Animation walkRight = new Animation(walkingRight, 10);
private Animation standing = new Animation(standing, 10);

// This is the actual animation
private Animation animation = standing;

```

In your update or tick method you will have:

```
animation.update();

```

In your render or draw method you will have:

```
g.drawImage(animation.getSprite(), x, y, null);

```

Lets say you have implemented MouseListener

```
public void mousePressed(MouseEvent e) {
    animation = walkLeft;
    animation.start();
}

public void mouseReleased(MouseEvent e) {
    animation.stop();
    animation.reset();
    animation = standing;
}

```

# Closing Notes

Here is a screen shot of the layout of a sprite sheet.

Each tile is 32 x 32 pixels.

Normally I wouldn't write this much code. However, I remember when I was struggling to figure this out and it annoyed the shit out of me... So here you go!

Good luck and I hope you can refactor it to suit your needs :)
> 19 votes

---
Tags: java, animation, spritesheet
---


# Question
Title: XNA - Accessing primary View, Project, World matrices from a game component
In XNA4, I have an EnemyManager class that takes care of all of the enemies. When it comes time to draw, however, it needs access to the game's main View, Projection, and World matrices.

I could just pass a reference to my DavesGame object down in there, but that seems like bad design. I could put them in an interface and expose them as a game service.

I'm leaning towards the latter, but I'm wondering what the correct & elegant way to do it is.

Thanks! Dave

# Answer
First let's assume how the matrices are "bundled" doesn't matter. I'd suggest a `Camera` class of some kind, but it doesn't matter - it could be a struct or as loose `Matrix` objects.

**Let's look at how you might pass that `Camera` around:**

Passing it around as a service isn't great. It's a lot of extra work and indirection, to fulfil a need that you probably don't have. Services are mostly for people making APIs that will be consumed by third-parties - and I assume you're not doing that. See this answer for a full description.

Grabbing it through `Game` is essentially no different to grabbing it through `Services`, but you lose all of the advantages (although you didn't need them anyway, and this saves you making a class).

You could be quick-and-dirty and make it "global" (in C# this would probably be a `public static` on your game class). This is ok when you want to do something quickly. And in C# it's relatively painless to undo, once you need a "real" architecture.

Passing it into the constructor of your component isn't a great idea. Consider the very possible scenario where you'd like to draw your component twice. Perhaps for split-screen, perhaps for a level-editor. Then you very messily have to modify persistent state before each draw. If you can ignore this downside, it is a reasonable architecture.

But there's one more blindingly obvious option: **Why not just pass it in as a parameter to your `Draw` method?**

Oh, you can't because you're using `DrawableGameComponent`? The solution to that is simple: Stop using `DrawableGameComponent`! Seriously. It doesn't actually *add* anything to your architecture unless you're creating drag-and-drop-style components for third-party consumption (which, again, I am assuming you are not doing).

Its limitations are not worth the extra hoops you have to jump through, if you're not actually using it for its intended purpose.

I suggest you replace it with your own base class, where you can modify the method signatures on to your heart's content. The remaining infrastructure you get with `DGC` amounts to a list and a pair of loops, maybe 5 lines of trivial code.

I've written about why `DGC` is a terrible basis for an architecture (because it leaves you in these horrible tight spots) here and here and here and here.
> 2 votes

---
Tags: xna
---


# Question
Title: Where can I find the full game list of Game Design Challenge on GDC?
The GDC Game Design Challenge is very interesting, the event gives designers the opportunity to display their amazing creativity.

When I searched for the old events I could only find articles which featured one or two games, never the whole list. Is there a record of all the games that have been designed for this event throughout the last ten years?

# Answer
I've compiled the following list of all the Game Design Challenges (and there will be no more as 2013 was the last) along with their subtitle (I've had to guess a few). They all have links to articles or videos that contain info about all the entries and say which one won.

I haven't read through all of these (and I didn't watch the conference video) but all the information about the entries should be there, otherwise googling the subtitle of an event may divulge more details. I've listed the actual entries for each year and emboldened the winner, I managed to find titles for most of the entries but a few were not mentioned.
> 8 votes

---
Tags: game-design, competition
---


# Question
Title: How can set vibration option with my game in android?
I am using AndEngine to develop an Android game and I want vibration to be triggered when an enemy hits a player.

How can I implement this into my game?

# Answer
Add this permission to your Manifest.xml file

```
<uses-permission android:name="android.permission.VIBRATE" />

```

and when there is a collision or something like that (I assume that you're handle the collision detection with AndEngine)

you can add this code :

```
// this is how you get an instance of Vibrator from current Context
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

// this is how you set the vibrate time (its in milliseconds, so if you want it
// to vibrate for 1 sec - write 1000
v.vibrate(300);

```
> 4 votes

# Answer
You can find the API documentation for the Vibrator here. To determine if the player is hit by an enemy you should lookup a decent tutorial on how collision is handled in AndEngine and add the vibrator code to the collision handler.
> 0 votes

---
Tags: android, andengine
---


# Question
Title: How do i create a Xna 4.0 Creating BoundyBox
I understand what other people have done and when creating it myself it just seems to go wrong or the version is different so doesn't work in first place. Any easy code for this?

# Answer
We need more details to be able to help you with your code. However, you can look at this tutorial and see if it helps.

Please edit your post with more details!

http://www.toymaker.info/Games/XNA/html/xna\_bounding\_box.html
> 1 votes

# Answer
I have tried that website ( http://www.toymaker.info/Games/XNA/html/xna\_bounding\_box.html ) and it the m\_transforms\[mesh.ParentBone.Index\] is giving me an error since m\_transforms isnt defined
> 0 votes

---
Tags: xna, c#, bounding-boxes
---


title: Game Editor plugin architecture

text:
# Question
Title: Game Editor plugin architecture
I'm creating 3D Game Editor for my own use. As rendering i took `Ogre3D` and `MFC` as UI.

I faced with architecture problem.

I am using Document/View architecture and for each Doc. i create `new SceneManager` and for each View i create own viewport, camera, my own local Input manager which send input data to local camera. Also it's sending input data and pointer to `SceneManager` to global `ToolManager` which contains some base tools like `Move`, `Select` etc. and the pointer to active tool, if it's NULL he is sending input to `SelectTool` by default.

I'm only at start but i'm thinking of the future. I think that this strategy of passing some data to the global manager is not so good how it looks now. Can you give me some design advices or articles and share with me your experience.

Thank you for your time.

Edit:

I think that plugin architecture would give a lot flexibility and it\`s like all editors do. But i never before faced with that. So i will try to tell u what i think about it. Host App contain

1. PLuginManager:
    * load/unload plugins
    * base interface to add frame/window and other UI
    * base interface to communicate with other plugins
2. EventListener
    * collect all events and EventListeners
    * send specific events to it listener

It's all what host app contains. But, how to implement it? I mean all communication. How to load and save files. Edit object with different plugins. I'm thinking to use QT, is it better than MFC or wxWigets.

Can you give me some advices please.

# Answer
> 2 votes
At the very basic level, you probably want your plugins to be able to provide new tools and new commands (alternative save methods, for example). You can implement this kind of extensibility, along with any other similar extensibility, in the same fashion.

You define for your system an interface that a plugin must conform to. This should at a minimum include hooks that the editor will call to load and unload the plugin. Pass, to the load function, references to all the extensibility interfaces you have supplied (or an interface that allows you to locate those interfaces).

For each extensibility interface, you want to have a related interface that corresponds to the new thing your plugin may be adding. For example, you might have an `ITool` interface that defines the properties of a tool the user can select from a palette and use to manipulate the scene. Or, you might have an `ICommand` interface that's used to populate your menu bar with options. The details of those interfaces are up to your particular needs and implementation.

The extensibility interface provides methods that allow the plugin to install new instances of `ITool`, `ICommand` or what have you. For example, you might pass your plugins an instance of the `Toolbox` class:

```
struct Toolbox {
    void AddTool (ITool * tool);
    void RemoveTool (ITool * tool);
    // ...
}

```

Because this type allows for tools to be added and removed from the available set, a plugin can define an entirely new tool that conforms to the `ITool` interfaces, such as a `MeshSplitTool` for example, and install that tool in the toolbox during the plugin's loading callback.

Similarly, you will want to remove the tool (and probably release its memory) in the plugin's unload callback.

This approach can be applied to any number of different things you'd want to extend. At the heart of it you:

* Define in the main editor the interface that new things must conform to.
* Allow plugins to install and remove instances of those new things so long as they fit the defined interface.
* Have the rest of the editor work in terms of that defined interface, so it doesn't care whether or not the particular objects it is working with came internally or from a plugin in some DLL.

# Answer
> 1 votes
My first question would be why have a `ToolManager` with methods like `Move` and `Select`. Different tools are going to provide different mechanics depending on the choice you've picked and trying to put all this logic into some manager class seems wrong and the typical approach to code bloat or god-like object class.

Instead, consider having your `SelectTool` register itself for input commands when the user selects it. Then as input occurs, this object determines what it does. When you select a different tool, perhaps the terrain splat tool, the `SelectTool` unregisters itself for input and the `SplatTool` registers itself instead.

Of course, there may be overlap between these two tools, which makes sense to be factored into a base class, perhaps called `Tool` for simplicity that all your specialized tools subclass from. In this case, perhaps the point of a `ToolManager` class could then be useful for registering different tools as plugins?

I think this fits with some of your edit comments.

As for which UI platform to consider, it really should boil down to what you're most comfortable using. All proposed UI solutions simply abstract the Win32 API from you and provide some feature rich classes that make UI programming easier and faster. In the end, they accomplish the same. The biggest difference here is that MFC is pure Microsoft. You can use MFC on \*nix systems but of course the use of emulators such as Wine/CrossOver is necessary. Otherwise, using UI toolkits such as wxWidgets/QT offer more cross platform options.

---
Tags: architecture, design-patterns, plugin
---


# Question
Title: Tools for generating texture atlases/sprites from source images?
Is there an industry standard file format for texture atlases?

What are the apps that take a directory of images and turns it into a texture atlas png and a text file describing what's on it?

This is primarily for use in OpenGL iPhone/Objective-C, but it seems like there ought to be a standard across many platforms. I can create these by hand or by writing a script to simply tile them, but it seems like there would be some tools already made for this.

# Answer
I would recommend Zwoptex. I think it would do exactly what you want for your iPhone game. And if you have not tried cocos2d yet, Zwoptex is supported by it.
> 2 votes

# Answer
SpriteSheetPacker is an extendible tile sheet packer. It can export sheet look up tables in a text format and in XML by default, but you can write plug ins in C# to add new export formats.
> 3 votes

# Answer
I've been using Texture Packer to create sprites for my iPhone game. It's similar to Zwoptex but is multi-platform and has a free version.
> 3 votes

# Answer
I use ImageMagick myself it is a commandline tool, but quite good, because it can do craploads of things (even converting between file formats, doing minor edits, some optmizations...) and because it is commandline you can make scripts to use it in the most awesomenest way possible...

I made a script geared for my pipeline, that consisted of calling it from a folder full of animations, and the sprite sheet would "pop" out already optmized and in .png, does not matter what was the input frames :)
> 1 votes

# Answer
I recommend Shoebox, perfect tool and it's free!

http://www.renderhjs.net/shoebox/ Works for most platforms too!
> 1 votes

---
Tags: iphone, textures, objective-c, sprites
---


title: How to open .lmesh and .lanim files?

text:
# Question
Title: How to open .lmesh and .lanim files?
I try to open league of legends models using Blender, but I don't know how to handle .lmesh and .lanim files. These files are located in here: http://static.lolking.net/shared/mv/

# Answer
The LMesh used by lolKing is not the actual format used by League of legends; if you look in the RAF archive in your league of legends installation, the files are using .SKN extension. The SKN format is well-documented by various open-source viewers such as LolBlender. I don't think the existing tools are fully updated for the latest version though, so you might have to do some legwork yourself modifying the import/export scripts. The Maya importer seems to be the only one that is actively updated.

I took a look at the LMESH file to compare it with the corresponding SKN, and there are differences in encoding. For example, strings are lenghth-prefixed instead of fixed-size. I'm not sure you'll find a whole lot of documentation but it seems fairly straightforward enough to reverse-engineer by comparing to the original.
> 3 votes

---
Tags: 3d, blender
---


title: Stitching meshes together

text:
# Question
Title: Stitching meshes together
I have a voxel engine that generates a mesh per chunk and now I want my meshes to be 1 mesh, but if I create them as a single mesh I kind of lose the benefit of chunking the data in the first place.

=Here's what i'm currently getting

I need to remove the gaps, any ideas?

# Answer
> 4 votes
You can still generate meshes per chunk, but to ensure the edges line up, you need to access voxels outside the current chunk. So, your chunks need to know about each other. When accessing a voxel in a chunk, have it access the 'world' level to retrieve the voxel. The 'world' level shouldn't care about which chunk a voxel is in. So inside your chunk it would be something like:

```
//inside chunk class
getVoxelAt(x, y, z)
    this.parentWorld.getVoxelAt(x,y,z)

```

And the function inside parent world

```
// inside world class
getVoxelAt(x,y,z)
    chunk = getChunkThatContains(x,y,z)
    chunk.getChunkLocalVoxel(x - chunk.base.x, y - chunk.base.y, z - chunk.base.z)

```

Where `getChunkLocalVoxel` takes the local coordinates of the voxel. So it would access whatever data structure you're using to hold chunk data, like an array:

```
 //inside chunk class
 getChunkLocalVoxel(x,y,z)
    return voxels[x][y][z];

```

You're likely getting gaps now because when you come to the edge of a chunk, you assume there's nothing beyond the edge when generating your mesh. So the mesh has gaps.

---
Tags: c#, unity, 3d-meshes, dynamic-mesh
---


title: lz4 archive with encryption

text:
# Question
Title: lz4 archive with encryption
I want to make a game data archive that contains all the game assets, now I could use zlib or lz4 to just make a simple zip archive type thing, but I need a bit more security, does anyone have any recommendations on adding AES encryption to the whole thing? I was also thinking maybe I need like a MPQ archive type system where I can mount the thing in the game engine and it acts as an interface to accessing the individual files inside, allowing streaming?

Any ideas appreciated, thanks.

# Answer
> 1 votes
A better approach than straight up encrypting the data would be to pack the data in a compressed format that still allows efficient loading, and then use a check sum to verify the integrity of the data at load time. Any form of message digest (even rolling your own) should be significant enough.

Also, be aware of what encryption seeks to accomplish, and who it keeps out. If your objective is to keep 100% of people from accessing your data, then you may want to reconsider not shipping that data with the game. The objective of this is to keep out the majority of people, but the people that really want access to this data will take the time to break your compression/encryption efforts, or simply access the data in memory when the program is handling it.

# Answer
> 0 votes
This is utterly pointless. You need to protect your game assets so bad that you want to hit load times with it? Just use "security by obscurity" and pack the data into a single binary (.wad or .mpq style)

---
Tags: compression, encryption
---


# Question
Title: How to get more than one window in Java LWJGL
I'm trying to write a game in Java LWJGL. And I need more than one (multiple) display window. By default I've got one display window where I can draw everything. But I'd like to split some data to other window. Any one know a way or tutorial to achieve this?

Regards.

# Answer
A possibility is that you could create multiple AWT windows, each with its own rendering thread and with different `GLContexts`. This would allow each window to have an entirely separate OpenGL context, somewhat like having multiple `Displays`, but requiring some extra "glue" code to get it working.

**EDIT:** Another interpretation of your question might be about having multiple windows inside the main game display. In that case, a better way of doing things might be to render to a framebuffer object so that you can create fake windows on-screen.
> 4 votes

# Answer
As far as I can read LWJGL code, Display is a static entity, so you'd either have to hack your way through LWJGL code or try a multi-process (not multi-threaded) approach. Multiple threads would share the state of the Display; multiple processes (separate JVMs) would not, and they could have separate windows, but transferring data and events between would be troublesome.
> 1 votes

# Answer
Did a quick check. Creating more than one Display in the same program results in an error, even if they are created in seperate Threads. One thing you can do, is to create seperate java programs for the two (or more) displays that you need, and have them communicate using sockets and/or streams.
> 1 votes

# Answer
This is just a shot in the dark, but could you create the display in a different thread? Since I know that LWJGL doesn't multithread with display/keyboard/etc., this is my best guess.
> 0 votes

# Answer
In LWJGL Display works for the thread it is called in but no where else outside of the thread. you **do not** need a separate process to create multiple windows.

this is what I have read in the LWJGL Wiki but please correct me if I am wrong.
> 0 votes

---
Tags: java, windows, lwjgl
---


# Question
Title: Fast method of detecting whether point is inside mesh
I'm trying to construct a 3d object from a large number of particles. I think this is called BVH (Bounding volume hierarchy). I figured the best way is to draw the particles inside the mesh, then let them drop down. Repeat as often as produces suitable results.

For this, I need to check for each point whether they lie inside the 3d model. I might be using something in the order of 1 million particles, so the point-in-mesh code needs to be fast. I have some clues about creating a 2d stencil projection first, and checking against that. But I'm not really sure what's the smart way to go about this.

# Answer
> 2 votes
As the link suggests, a BVH is a data structure that is used to quickly compute collision queries for a set of polygons. It doesn't usually provide information about the underlying geometry itself other than possibly maintaining references to triangles in the leaves of the tree.

In terms of your problem of finding out whether or not a point is within a set of geometry, a BVH is a good way to go. How to construct a BVH from a set of particles is a bit more tricky. In general, your BVH won't be a tight fit, and might result in some false positives for points that are extremely close to your point set.

In order to reconstruct a 3D surface from your points you will likely need to use some implicit representation to generate triangles. This work was done back in 2001 with a very famous model:

http://vgc.poly.edu/~csilva/papers/vis2001c.pdf

Once you get the idea for how to think about these kinds of problems, solutions are available via the Computational Geometry Algorithms Library. More specifically, they have a solution to the problem of generating surfaces from 3D point sets:

http://www.cgal.org/Manual/latest/doc\_html/cgal\_manual/Surface\_reconstruction\_points\_3/Chapter\_main.html

# Answer
> 2 votes
If you want to spawn particles on the surface of a mesh, it's relatively easy: pick a random triangle, then pick a random point on it. The choice of triangle should be weighted by area so that the particles don't clump into the denser areas of the mesh (unless that is a desirable effect).

To spawn particles within the volume enclosed by a mesh is harder. Rejection sampling - generating random points in the bounding box of the model, then checking if they're inside and throwing away the ones that aren't - will work, but I suspect it isn't very efficient, as you'll generate many points you won't use. Still might be worth a try. To test whether a point is inside the mesh, see this StackOverflow question, which points out that you only need a 2D acceleration structure, not full 3D, to make this work. But you're still going to be doing a bunch of ray-triangle tests to determine whether a point is inside or outside the volume.

If you did build a full 3D acceleration structure, such as a BSP or BVH, there's probably a way to use it to focus the generation of points. For instance, you could pre-calculate the volume of each BSP leaf node, then generate a point by picking a random leaf node weighted by volume and generating a random point within it. That sounds difficult, though - both calculating the volume of a BSP node and picking a random point within it sound nontrivial.

# Answer
> 0 votes
I think the easiest method is to pre-build a skeleton. If your moving the object, then the skeleton can be composed of grid point means. The skeleton needs just enough articulation that the skeleton never leaves the grid. Each "bone" will have numerical ranges of gridpoints that are close to it.

To check a particle find the closest bone. Then find 2 grid points near the particle, then check if a solution exists where particle is in the plane point1 point2, arbitrary point on bone. The grid points must be chosen with care, to be left and right of the bone, and close enough that they don't leave an arc where the particle could hide.

---
Tags: collision-detection, mathematics, particles, intersection
---


# Question
Title: Support for different resolutions in a tabletop environment
Right now I am experimenting with XAML and C# to write a small Windows Store App which supports displaying a playmat with cards. However not everyone uses the same resolution and with a somehow fixed layout I run really fast into some issues. Having a really high resolution yields

where all the zones are huge (and ugly stretched) and the icons as well as the fonts are really small. Changing to a low resolution yields

which is okayish so far, yet I would need to find out how to scale assets like the displayed card such that it fits the zones.

**Are there any best practices, creating such fixed layouts and optimizing them for different resolutions? How should I correctly compute the sizes for a card on the table? And is there anything to keep in mind when creating fullscreen content for different resolutions?**

# Answer
> 2 votes
You can base everything's size on a percentage of the screen space it should take up; for example, a card may take up 5% of the screen's width and 7.5% of its height (these are just examples).

Before you do that, you will want to go with a resolution such as 800x600 that simplifies the math to find the percentage values. Then as long as you use the relative percentages everywhere instead of absolute pixel values, it should work. Note: this is a lot easier to do in 2D, but should carry over for 3D ***theoretically***.

--You may also want to find the aspect ratio being used as well. Going from 800x600 to 1920x1080 would cause your cards to get fat horizontally.

---
Tags: c#, graphics, resolution, windows-8
---


title: Distortion Effect

text:
# Question
Title: Distortion Effect
I'm trying to make a distortion effect for a space game. The idea is that the effect has a central point, and all nearby objects appear to swirl into that point. I've made a preliminary version and it looks like this:

I'm pretty much satisfied with this effect, but the problem is that it takes far too long -- about 150 ms -- and I need to render it every second or third frame, at least. How can I achieve a similar effect efficiently in Java2D? (If you're interested, my source code is here: http://pastebin.com/1W9RrA44)

# Answer
Kevin gave you a good list of what you really need to do first to improve the performance of the code. However I would just throw out the code and implement the effect on higher level so that Java can utilize native code and GPU.

# Radial blur

Based on the screenshot it looks like the effect you are looking for is radial blur with rotation. These can be implemented by first rendering the scene to an offscreen image instead of directly to the screen and then repeatedly rendering the image to the screen with scaling and rotation. These are operations that Java can accelerate on the GPU automatically and you might get even better performance by creating the offscreen image as VolatileImage. Make sure you are using bilinear filtering for better quality: `g.setRenderingHints(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);`

In pseudo-code the algorithm would look something like:

```
render scene to offscreen_image
for i in 1 to N
    scale = any function that returns 1 for the first image and approaches zero when i grows.
    rotation = i * constant
    render offscreen_image to screen with scale and rotation
endfor

```

When rendering the offscreen\_image to the screen, you also probably want to fade it to background color a little. In Java you can do this with AlphaComposite. This should be enough to make your effect fast enough. However there is still room for improvement.

# Feedback loop

The rendering time of the implementation above is proportional to N. In some cases, mainly if your frame rate is constant, you can further accelerate the rendering by keeping the previous rendering result in the offscreen image and rendering only one copy of the offscreen image. This makes the effect very fast, but the dependency of previous rendering results might be undesirable. This also limits the shape of the scaling and rotation functions. The pseudo-code for that would be:

```
render scene on top of offscreen_image_1 without clearing
scale = constant_1
rotation = constant_2
render offscreen_image_1 to offscreen_image_2 with scale and rotation
render offscreen_image_2 to screen
swap offscreen_image_1 and offscreen_image_2

```

Scale and rotation constants can still vary based on time / framecounter in this version.

You might have seen this effect in action in some music player visualization (Winamp, Media Player etc.). Here is an example video: https://www.youtube.com/watch?v=jasdVfbAFVw#t=237s.
> 4 votes

# Answer
Per-pixel image processing on the CPU is something where microöptimization is worth thinking about from the start. You're doing memory allocation and object initialization on a per-pixel basis; this is probably most of your problem.

The first thing you should do is figure out how to use *only* arrays of primitives (`byte[]` etc.) to perform your computation.

* Do not use `ArrayList`, but only arrays.
* Do not use `Integer`, but only `int`, `byte`, etc.
* Do not use arrays of arrays, but use a flat array and compute coordinates like `arr[x + width * y]`.
* Do not allocate any arrays (`new byte[]`) inside a loop.

Once you have this taken care of (and it'll probably help a lot), the next step is to get rid of your single-pixel image access operations (`getRGB` and `setRGB`). Instead, get an entire array of pixels from the image and write back the same way; I'm sure `BufferedImage` has operations to retrieve and store the image data as arrays, but I'm not familiar enough with it to recommend specific methods.
> 5 votes

---
Tags: java, 2d, effect
---


# Question
Title: Drawing more that one quad with only one glDrawArray call....?
**Edit**

After initially thinking that my sprite batch test was faster than calling each sprite individually, it appears that is not the case!! :-(

With a single set of GL calls for a each sprite, I can get about 90 quads to move with no performance degradation.

With my batching test I can get about 12 (all in one call).

The problem is that I can't find any examples (code) anywhere for how this can be achieved using Android (Java) and OpenGL ES 2.0.

My method involved passing in an array of coordinate sets instead of a single set of coordinates, and then the method would build an array to store these coordinates in and then render the relevant amount of vertices. Like I say, it works but the performance is awful!! Is this the right approach?

Could anyone help? Thanks!

I'm using Android with openGLES 2.0 and I can't work out how to draw 2 (or more, but for the sake of simplicity, lets say 2 for the time being) textured quads using only 1 call to glDrawArrays.

My shaders are fairly standard and take into account sprite opacity as follows:

```
//vertex shader
    String strVShader =
              "uniform mat4 uMVPMatrix;" +
              "attribute vec4 a_position;\n"+
              "attribute vec2 a_texCoords;" +
              "varying vec2 v_texCoords;" +
              "void main()\n" +
              "{\n" +
              "gl_Position = uMVPMatrix * a_position;\n"+
              "v_texCoords = a_texCoords;" +
              "}";

//Fragment shader

    String strFShader =
        "precision mediump float;" +
        "uniform float opValue;"+
        "varying vec2 v_texCoords;" +
        "uniform sampler2D u_baseMap;" +
        "void main()" +
        "{" +
        "gl_FragColor = texture2D(u_baseMap, v_texCoords);" +
        "gl_FragColor *= opValue;"+
        "}";

```

Then my rendering method takes in vertices that set the position and size of the quad, set the texture, apply rotation (if any) etc...

And then draws with the following line:

```
GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4);

```

I've been looking for a couple of days now for examples of how this can be achieved, but nothing seems to explain how it is actually done.

Can anyone give me any clues?

Note: To keep the question short, I have omitted my actual draw method. If this is required to give a fuller answer, please just ask and I will post.

Also please note that I need to do this as I'm trying to work out how to **batch** my sprites to increase performance.

# Answer
glDrawArrays claims that the passed in values for glDrawArrays specify a primitive type, a start index, and an index count. Assuming each index represents a vertex, you would need to specify more than 4 indices for it to draw more than one quad.

http://www.opengl.org/sdk/docs/man/xhtml/glDrawArrays.xml
> 3 votes

---
Tags: android, sprites, performance, opengl-es2, spritebatch
---


title: Automated testing of games

text:
# Question
Title: Automated testing of games
Are there methods of automated testing of games?

Specific experiences are appreciated, with relevant information about the project such as platform and type of game if that helps with clarification.

# Answer
One-person independent game. It was a multiplayer tank game with destructible terrain, and the destructible terrain and collision code proved somewhat flaky.

I ended up rigging up some basic dumb AIs (by "dumb", I mean "absolutely idiotic" - they would randomly choose "drive towards an enemy tank", "drive away from an enemy tank", and "drive in a random direction", while randomly firing the main weapon) and playing the game at maximum framerate while recording keypresses. I got about 10-15x realtime. The code was heavily asserted, so if anything went wrong, it would dump the entire keypress log to disk along with an error report and the initial random seed. I could then go and replay the keypress log to duplicate the state exactly, or just debug from the error report.

I left it running constantly for literally months. At the beginning it would rarely get an hour without crashing - I had to sit there and babysit it for a week, killing several obscure bugs per day. Eventually it got to the point where it was running for a week between failures, which translates to about 1500 player hours per crash.

It was invaluable and I heartily recommend it.
> 74 votes

# Answer
For an MMO I worked on (100ish developers, PC focused), we tried to add a huge variety of automated testing with varying success. Here's what worked:

* Basic tests during our automated build process were a huge win. This included tasks such as creating a character, transferring maps, running some scriptable UI tests and looking for expected behavior. This caught a huge number of bugs before they actually got to the rest of the company.
* On the server infrastructure end, we developed a bunch of different automated tests that simulated typical MMO server transactions. We could then play these back under a variety of circumstances to compare performance or ensure safety. Over time these tests became more and more accurate until it turned into a playback of live recorded data
* We wrote a "fake player" that would randomly roam around the world, jump, kill things, and say random things in chat. This found a huge number of physics and infrastructure issues.

What didn't work:

* We tried to add some very specific combat-oriented automated tests to the automated builder, but this basically never worked. It would work for about 3 days after being implemented, until a designer or artist changed something and the test would fail, throwing off the build failed alarms. 90% of the time it wasn't a real problem. These tests were too fragile, and actually testing specific gameplay on a specific map with specific powers can be unmaintainable
* We tried implementing an automated performance test that would compare client performance (average FPS, etc) against recorded performance from a week ago. This was also fairly fragile as the demos we used for this tended to rot fairly often, and it was difficult to ascertain if a slowdown was caused by an actual loss in performance or some side effect of the test process.
> 33 votes

# Answer
Working on a 4x strategy game with 3d combat (think Homeworld meets Masters Of Orion) that unfortunately never saw the light of day as the company ran out of funding..

I always ensured that you could play the game without human players so we could leave the game running overnight.

We could turn off the 3d combat (simplified to a random result) and we left the AI strategy engine playing itself. This found numerous bugs and issues. Not only show stopper bugs but strategy bugs where the (eg) AI strategies would get deadlocked and spend 1000s of turns not doing "the right thing". These sort of bugs were difficult to spot just "playing the game".
> 18 votes

# Answer
On a first person shooter I worked on (Descent 3 -- linux/mac/windows, ~30 people on the team in 1999), the demo recording/playback capability turned out to be extremely useful. I made an option where you could playback the demo as fast as the game could render frames, and that became a great way to verify performance after a bunch of things changed.

It also exercised a lot of the code beyond the rendering system, so it was a nice sanity check. After making a bunch of changes I could just run the demo playback of 10 minutes of gameplay. Many times it would catch a bug in an area I wouldn't have thought to check myself.
> 13 votes

# Answer
We had a openworld shooter (x360,PS3,PC) that used a quick smoketest on the build server - it loaded the game, stepped through the front end, ran \[the avatar\] forwards, dumped a screenshot, and exited. If cctray detected the clean exit the build was a success.

We ran it for about the last year of the project, and with a team size of ~100 devs.

It was effective at catching showstopping bugs but it was easy to create a build that passed the smoketest but failed most "real" levels, or didn't work in multiplayer, or nobbled the AI, so it wasn't perfect. It was definitely worth doing.

I've heard since I left they've started running a larger range of smoketests, farmed out to multiple PCs. Apparently maintaining the smoketests is an issue, and there's a small team dedicated to just keeping the build servers and software maintained, so I can't say if that's been a success or not.
> 8 votes

# Answer
My experience with Automated Testing during the development of Crysis 2 is available here: http://yetanothergameprogrammingblog.blogspot.com/2010/06/aaa-automated-testing.html

Summary:

* Automated testing improved deliverables stability, increasing productivity for both content creators' and engineers
* Automated testing is an effective tool to improve code quality and reduce the chances of having to work overtime
* The Game Industry as a whole is very reactionary in general, automated testing meets several irrational arguments against
* Don't call it testing, call it something else, almost anything else (Look at Behavior-Driven-Development)
* Be flexible, writing good tests is hard and require skills that are not widely available in the Game Industry
> 6 votes

# Answer
Game development is actually one of those cases where unit testing seems to make some sense to me, because the interactions between discrete systems are so common. Design-by-contract is of course a part of this, and should be planned on from day one of development, but I don't see why it couldn't be implemented later assuming the wherewithal to do so exists.

The hard part is, of course, integration testing. Lots of a game can be tested just by demo-looping it or something, but that stuff is conceptually fairly easy to debug--where I'd be more interested in spending my time is exposing bugs that will happen when a *player* does something, with the mindset that a bug the player never sees is obviously less important than a bug the player does.

Which is pretty difficult, obviously. Tactics that work on other applications (fuzzing, expected-pass/expected-fail, etc.) don't work so well here. In scriptable systems it seems like building a test set of scripts to simulate a player are the way to go (see JZig's answer). But testing specifically for stuff a player may encounter directly strikes me as the best place to focus your time for both human and automated testing purposes.
> 2 votes

---
Tags: testing, automated-testing
---