# Question
Title: Implementing Geometry Instancing in DirectX
I have a project that I'm doing in Managed DirectX (DX9) where I want to render lots of grass. My current method (many draw calls) is slow, but I've heard Geometry Instancing can fix that.

I know that I have to have one vertex buffer to store the vertices that will drawn multiple times. I know that I need another vertex buffer to store the transformations (from what I've seen you can only have *one* additional vertex buffer). So should the second vertex buffer store transformation matrices? I tried coding this, but when I want to create a new vertex buffer one of the required parameters is `vertexFormat`, but I can't supply a vertex format since this is a matrix.

I also wanted to try to have the second vertex buffer store the translation values as `Vector3`, but how do I tell DirectX that the values in the second vertex buffer are to be used as translation values? Secondly, I also need rotation values. Do I store these in a *third* vertex buffer?

Basically, I want to use geometry instancing to draw multiple instances of a quad that are rotated and translated.

# Answer
> 2 votes
What you'll wind up doing David is creating a vertex buffer to hold the different transformation matrices for each instance of grass. You will need a vertex declaration that has your standard 'grass' vertex components( pos, norm, uv...etc ), and in that same declaration 4 additional 4-component floats to hold the 4x4 transformation matrix...the declaration will look like this:

```
IDirect3DVertexDeclaration9 *pVDInstances = NULL;

// create instance vertex declaration
    D3DVERTEXELEMENT9 pElements[] = {
        { 0, 0, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 }, // position
        { 0, 12, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_NORMAL, 0 }, // normal
        { 0, 24, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0 }, // uv
        { 1, 0, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 1 }, // 1st row transformation matrix
        { 1, 16, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 2 }, // 2nd row transformation matrix
        { 1, 32, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 3 }, // 3rd row transformation matrix
        { 1, 48, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 4 }, // 4th row transformation matrix
        D3DDECL_END()// add additional data declarations before this line if you require( be sure to change the 'stride' when setting the 2nd stream source below... )
    };

    hr = pd3dDevice->CreateVertexDeclaration( ( D3DVERTEXELEMENT9* )&pElements, &pVDInstances );
    if( FAILED( hr ) )
    {
        // handle failure
    }

```

Take note of the first parameter of the D3DVERTEXELEMENT9 constructor...it is '0' for the mesh object and '1' for the transformation matrix. This is because you are going to instruct the graphics device to use 2 different vertex buffers. Also take note of the 'offset' parameters...they begin again at 0 for the 2nd vertex buffer.

Before you can render though, you must also set the frequency of transformation matrices per instance...such that for every instance of grass the graphics device will use 1 transformation matrix.

Before the draw call you will instruct the graphics device like this:

```
if( FAILED( hr = pd3dDevice->SetStreamSourceFreq( 1, ( D3DSTREAMSOURCE_INSTANCEDATA | 1ul ) ) ) )
{
    // handle error
}

// the instance buffer holds the transformation matrices for each instance of grass
IDirect3DVertexBuffer9 *pVBInstances = pXGrassModel->GetInstanceBuffer();

// Set up the instance data stream
if( FAILED( hr = pd3dDevice->SetStreamSource( 1, pVBInstances, 0, sizeof( D3DXMATRIX ) ) ) ) // you can change this if your instance buffer holds more than a single transformation matrix
{
    // handle error
}
if( FAILED( hr = pd3dDevice->SetVertexDeclaration( pVDInstances ) ) )
{
    // handle error
}

```

// then set materials and textures as usual and draw

Here is a vertex shader for instances:

```
struct VS_OUTPUT_Inst
{
   float4 Position : POSITION0;
   float3 Normal : TEXCOORD0;
   float2 UV : TEXCOORD1;
};

VS_OUTPUT_Inst InstancesPass_Vertex_Shader( float4 vPos : POSITION,
                    float3 vNormal : NORMAL,
                    float2 vUV : TEXCOORD0,
                    float4 vRowX : TEXCOORD1,
                    float4 vRowY : TEXCOORD2,
                    float4 vRowZ : TEXCOORD3,
                    float4 vRowW : TEXCOORD4 )
{
    VS_OUTPUT_Inst Output = ( VS_OUTPUT_Inst )0;

    float4x4 mWorld;
    mWorld._m00_m01_m02_m03 = vRowX.xyzw;
    mWorld._m10_m11_m12_m13 = vRowY.xyzw;
    mWorld._m20_m21_m22_m23 = vRowZ.xyzw;
    mWorld._m30_m31_m32_m33 = vRowW.xyzw;

    float4x4 mWorldView = mul( mView, mWorld );

    float4 Pos = mul( vPos, mWorld );
    Pos = mul( Pos, mView );
    Pos = mul( Pos, mProjection );

    Output.Position = Pos;

    Output.Normal = normalize( mul( vNormal, ( float3x3 )mWorldView ) );

    Output.UV = vUV;

    return( Output );
}

```

Note the Semantics used here can be traced to the semantics used in the vertex declaration above...

# Answer
> 2 votes
The DirectX SDK has samples on how to do this, and there are resources online you can find on how to do this. Look in `C:\Program Files (x86)\Microsoft DirectX SDK (June 2010)\Samples\C++\Direct3D\Instancing\Instancing.cpp`.

Here's a Nvidia GPU Gem article on Geometry Instancing.

And here's an article on MSDN. This article shows you the two vertex buffers in a diagram, shows you the format they use, then immediately show you how to setup the stream source using the D3D device. Setting up instance data requires using the D3DSTREAMSOURCE\_INSTANCEDATA flag.

---
Tags: 3d, directx, directx9, instancing
---


# Question
Title: Calculating the point(s) at which two moving objects are a certain distance from each other
# Problem

This is similar to a Closest Point of Approach calculation, but instead of the closest point(s), I want the points at which the objects are a given distance away from each other. (Imagine two spaceships moving on a collision course towards each other; I want to know at what point Ship B is within Ship A's weapons range.)

# Attempted solution

I started by using this page which details a method of calculating the CPA. This seemed a promising start:

> d(t) = |P(t) – Q(t)| = |w(t)| where w(t)=w0+t(u-v) with w0=P0-Q0

Rationale: for a desired distance of 5 units, I want to do:

> 5 = |w(t)|

Square, substitute variables, and expand. I'm working in 2D, so this isn't too bad. Variable substitution as follows:

```
w.x = a
w.y = b
t = x   //(Wolfram won't solve for other variables?!)
u.x = p
u.y = q
v.x = r
v.y = s

```

> (a +x(p-r))^2 + (b + x(q-s))^2 = 25

Throw this into Wolfram Alpha and it gives the enormous formulas to solve for x.

And turn it into Python code:

```
def CPA_distance(e1, e2, dist):
    """Calculates the (two) times when e1 and e2 are exactly dist apart from each other."""
    posd = e1.pos - e2.pos
    dist2 = dist*dist

    a = posd.x
    b = posd.y
    p = e1.vel.x
    q = e1.vel.y
    r = e2.vel.x
    s = e2.vel.y

    #TODO: account for the case where (p**2 - 2*p*r + q**2 - 2*q*s + r**2 + s**2) == 0 -> they'll never intersect

    #NOTE: This function will return incorrect results if the velocities for the two entities are the same. In this case, simply check the distance between them.

    denominator = (p**2 - 2*p*r + q**2 - 2*q*s + r**2 + s**2)
    sqrt_part = sqrt(   (2*a*p - 2*a*r + 2*b*q - 2*b*s)**2
                    - 4*(a**2 + b**2 - dist2)*(p**2 - 2*p*r + q**2 - 2*q*s + r**2 + s**2))
    sub = -a*p + a*r - b*q + b*s
    t1 = ( -0.5 * sqrt_part + sub ) / denominator
    t2 = (  0.5 * sqrt_part + sub ) / denominator

    return (t1, t2)

```

This works in the majority of cases, but not all of them. It's possible for the calculation of `sqrt_part` to fail attempting to take the square root of a negative number, for instance with the following parameters (pseudocode):

```
e1 = ( pos = (5,5), vel = (0.5, 0.5) )
e2 = ( pos = (0,0), vel = (-0.5, 0.5) )
dist = 5

```

# Question

What's going on that causes me to have a negative value inside the square root? Just drawing out the initial locations of e1 and e2 shows me that they'll never come within the required distance of each other but I'd have thought that I'd either get a negative time or get a divide by zero somewhere.

Is this a "valid" outcome which I can take to mean "will never get within distance, even in the past" or are my formulas all wrong?

# Answer
A negative solution means that the time at which that separation distance occurred is in the past.

An imaginary (or complex!) solution means that the time at which that separation distance occurred neither has, nor ever will, occur. This is the meaning of the square-root term being negative.
> 1 votes

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


# Question
Title: How do I follow this glsl1.2 + lights + shadows tutorial?
I am following this great tutorial but I have many questions.

Let's see if I understand the basic idea.

```
1. I must create the same number of FBOs that lights (maximum 8).
2. I must create the same number of depth textures (shadow maps) that FBOs.
3. For every FBO I must perform offscreen render (render to texture, drawing the scene from the point of view of each of the lights, maximum 8 times).

```

Is this correct or can I use just a texture with multiple FBOs, or fbo with various textures or how?

Assuming you use the idea above, how should the final render of the scene?

```
glUseProgram(programa);
  glUniformli(shadowM0,4);
  glActivateTexture(GL_TEXTURE4);
  glBindTexture(GL_TEXTURE_2D,depthT0);
  //Draw Escene?

  glUniformli(shadowM1,5);
  glActivateTexture(GL_TEXTURE5);
  glBindTexture(GL_TEXTURE_2D,depthT1);
  //Draw Escene?

  glUniformli(shadowM2,6);
  glActivateTexture(GL_TEXTURE6);
  glBindTexture(GL_TEXTURE_2D,depthT2);
  //Draw Escene?

  ...
glUseProgram(0);

```

Is this okay? I think not, because it uses a lot of resources and the scene would have to be drawn up to 7 times. (One per light source and shadow mapping).

Well but then how should the render scene with multiple light sources and shadows?

# Answer
In a forward a rendering approach (aka the built-in simple methods like you describe), it is correct to say that the scene must be rendered once per light.

To achieve better performance with multiple lights, you need to use specialized rendering approaches via shaders that can accumulate multiple lights in one pass. The most popular of these techniques is Deferred Rendering, but there are some other less popular approaches as well.
> 0 votes

---
Tags: opengl, glsl
---


# Question
Title: How do I make my SFML mouse position capture fast enough?
I'm new to game development and making a Pong clone in SFML. I am trying to set the screen's top and bottom as bounds for the paddle.

Here is my attempt:

```
#include "main.h"
#include "objects.h"

int main()
{
sf::RenderWindow window(sf::VideoMode(900, 600), "Pong");
window.setVerticalSyncEnabled(true);
initData();
while (window.isOpen())
{
#pragma region Event Handling
    sf::Event event;
    while (window.pollEvent(event))
    {
        switch (event.type)
        {
        case sf::Event::Closed:
            window.close();
            break;
        default:
            break;
        }
    if (sf::Mouse::getPosition(window).y <= 500 &&  sf::Mouse::getPosition(window).y >= 0)
    {
        player1paddle.setPosition(100, sf::Mouse::getPosition(window).y);
    }
    }
 #pragma endregion
 #pragma region Rendering
    window.clear(sf::Color::Black);
    window.draw(net);
    window.draw(player1paddle);
    window.draw(aipaddle);
    window.display();
 #pragma endregion
}

    return 0;
}

```

The problem: When I move the mouse fast, the sprite stops moving before it hits the bottom. I'm assuming this is caused by the mouse moving faster than the loop is running. Is there a faster/more efficient way to do this?

# Answer
Your problem is that mouse move events are discrete.

For example, slowly moving the cursor over 50 pixels, might get you 5, 10, 15 or more mouse move events. However, if you move your cursor fast, it's possible to get only one mouse move event for the entire distance or possibly none at all (if the target point is outside your window).

This is something you can't really change, unless by trapping the cursor inside your window (also known as clipping or wrapping the cursor). Unfortunately, this functionality isn't exposed by SFML so far, though there is an open issue regarding it.

What you can do as a work-around:

* Whenever there is a mouse move event, move the cursor back to the center of the window.
* The distance travelled can be used to determine the paddle movement.
* Just keep in mind to not do this if your window isn't the active forgeground window (this can be tricky; there's going to be some new API method in SFML 2.2 to make this easier).
> 2 votes

---
Tags: input, sfml
---


title: Java JscrollPane

text:
# Question
Title: Java JscrollPane
Hello I have a game where you can have a shop and buy stuff. when you press enter the shop stock menu opens. I want to be able to show all of the items available and I want to be able to scroll threw them all with a jscrollpane or jscrollbar. I don't know how I would approach this please help me and please don't take this question down mods and admins because tis will be very helpful for me. here is my code if you need to see it:

```
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.util.ArrayList;

import javax.swing.ImageIcon;
import javax.swing.JScrollPane;

public class stock {
    static Image img;
    public static int money = 1000;

    public static ArrayList<item> item = new ArrayList<item>();
    public static JScrollPane j = new JScrollPane();
    public static void tick(){
        if(Keys.isPressed(Keys.ESCAPE)){
            options.stockopen = false;
        }

        for (int i = 0; i < item.toArray().length; i++) {
            item.get(i).tick();
        }

        item.add(new item(200,100,8,"Melon"));
        item.add(new item(200,150,2,"Bread"));
        item.add(new item(200,200,1,"Milk"));

    }

    public static void render(Graphics g){
        ImageIcon i2 = new ImageIcon("res/stockscreen.png");
        img = i2.getImage();
        g.drawImage(img,0,0, null);

        g.setColor(Color.yellow);
        g.setFont(new Font("italic", Font.BOLD, 20));
        g.drawString("€ "+money, 13, 30);

        for (int i = 0; i < item.toArray().length; i++) {
            item.get(i).render(g);
            //if (item.get(i).isrem) {

            //}
        }

    }

}

```

# Answer
You can pass the menu container into the `JscrollPane` when `new JscrollPane(menuContainer)` and add the `JscrollPane` object you create where you are adding your menu-container.

**example**
If you want a `JPanel` to be in a `JFrame` and have `JScrollPane` to scroll through, you can do so by.....

```
JFrame jf = new JFrame();
// some statements
JPanel jp = new JPanel();
// some statements
JScrollPane js = new JScrollPane(jp);
jf.add(jp);

```

something like this.. here jp will be like the menu-container.
> 2 votes

---
Tags: java
---


# Question
Title: Box2D: Adjusting character position for side-scrolling
In my side-scroller I would like to give the illusion of the character walking forward while his sprite is actually being held in place. If he walks near the edge of the screen, I would like to adjust his position at each step so that he is remaining still while the background moves backwards at the same rate he would have been moving. I think you get what I mean.

I figured that a simple case of "position = position - velocity" would do the trick, but then I realized it is not quite that easy with box2d. Velocity is expressed not at distance per frame, but distance per second. So instead I am essentially using position = position - velocity/60 since my game refreshes (or attempts to refresh at) 60 frames per second. But I can still see some lilting in the character's movement, and if I monitor his position, it shows that it indeed changes, most likely due to variations in frame rate.

Is velocity/60 the best I can hope for, save for hard coding the stop positions?

I am using the newest release of Box2Dweb. Yes, the javascript one. Here's a sample of the code:

```
var posX = this.body.GetPosition().x;
var posY = this.body.GetPosition().y;
var velX = this.body.GetLinearVelocity().x;

if(posX > 21 || posX < 12){
    screen.pos -= velX;
    this.body.SetPosition(new b2Vec2(posX - (velX/60),posY));
    }

```

I realize I can hardcode the positions like this:

```
    if(posX > 21) {
        screen.pos -= velX;
        this.body.SetPosition(new b2Vec2(21,posY));
    } else if(pos < 12){
        screen.pos -= velX;
        this.body.SetPosition(new b2Vec2(12,posY));
    }

```

But I'm not super excited about how decidedly undynamic that option is.

# Answer
> 1 votes
It is often advised to handle movements independent of the frame rate (since it will always vary at least a bit), as it will result in smoother transitions. So instead of hard-coding your desired value of "60", you could do the following instead:

1. Calculate the movement you want to apply, e.g. per second.
2. Divide that movement by the "time since the last frame" (e.g. in seconds).
3. In the current frame, update the player's position by the result of step #2. This ensure that over one second, regardless of the frame-rate, the desired movements gets applied.

There are however valid arguments to e.g. let the physics engines run on fixed time steps (as oppose to variable time set as shown above). For more details, see this GameDev.SE thread.

---
Tags: javascript, box2d
---


# Question
Title: How do I morph between meshes that have different vertex counts?
I am using `MeshMorpher` from the Unify wiki in my Unity project, and I want to be able to transform between arbitrary meshes.

This script only works when there are an equal number of vertices between the two meshes. Is there some way to equalize the vertex count between a set of meshes? I don't mean that this would reduce the vertex count of a mesh, but would rather add redundant vertices to any meshes with smaller counts.

However, if there is an alternate method of handling this (other than increasing vertices), I would like to know.

# Answer
> 1 votes
Just a supposition here but a way to go without artifacts could be mesh conforming :

in short casting your mesh B onto your mesh A, easy to implement with morphed planes but could be a whole other issue with closed meshes.

What you need to do is create a function which will approximate the new point coordinates based on a set of points (as you have greater count with mesh A) and remap the point, kill the triangles, recreate the triangles the normals and then interpolate...

Mesh conforming demo

EDIT : one of the simple way to do that would be to approximate new base position based on the same vertex index than the one of mesh A ex:

Mesh A 20 Vertices Mesh B 10 Vertices

Kill Mesh B triangles Set Mesh B Vertices in index Order using for ex :

```
VertexPosMeshB[1] = (VertexPosMeshA[1] + VertexPosMeshA[2])/2; //scaling down to the actual size of Mesh B and approximating to fit previous pos

```

Re create Triangles in Index order or with a home made algo fitting the mesh shape. then Interpolate mesh B vertices over time until it fits the state you want

WARNING : If you mesh counts are too far apart of course you will have some weird results, try looking for Tesselation then to make your mesh with less poly conform to the one with more poly without "actually" being forced to keep the exact same number of vertices when you create your meshes.

A mix of tesselation and approximation algorithm could do the trick i believe

# Answer
> 0 votes
This tool is **not** useful for transforming between arbitrary meshes and it says that in the link you provided.

All this tool does is take `N` vertices with positions `X0i, Y0i, Z0i` and slowly transitions them to position `X1i, Y1i, Z1i`. It just takes a lot of numbers and does a time weighted average between them and a lot of other numbers each frame. Sort of like:

```
1 ... 1.1 ... 1.2 ... 1.3 ... ... 2

```

This process is also called **interpolation**.

There is no magic happening

From your link:

> /// However the mesh morpher requires that you use the same amount of vertices for each mesh and that those vertices are laid out in the exact same way...

There are other ways to accomplish what you describe but they require very advance techniques and a very large amount of computation power.

For instance, you could:

1. Convert the meshes to voxels.
2. Do a boolean operation on two resulting models to get the differences.
3. Use some transformation to gradually dissolve the pieces that exist on the original source mesh and do not exist in the target destination mesh.
4. Use another transformation to grow the pieces that exist in the target but not in the source.
5. Replace the voxel model with the target model.

If you want to spend even more computing power, you could use something like dual marching cubes to convert the in-between frames into smooth meshes...

Generally the morphing algorithm you linked to is an interpolation tool used to smoothly transition one mesh from pose A to pose B of the same mesh after some changes were applied to the positions of it's vertices.

---
Tags: unity, animation, vertex, mesh
---


title: Radiosity: Integrating Hemicubes

text:
# Question
Title: Radiosity: Integrating Hemicubes
I'm working on a radiosity processor in DirectX 9. I have efficiently rendered hemicubes from the perspective of texels within a lightmap. Now, as I try to integrate the hemicubes (to sum the incident light that can be seen from the POV of a single texel within the lightmap) I run into a problem.

This tutorial says a hemicube is integrated by adding the colors from each pixel of the hemicube (after they have been scaled by the multiplier map) and then dividing the sum of colors by the total pixel count of the hemicube. The author says the sum of all pixels in the multiplier map should add up to 1... If this is true, why divide the sum of incident light by the number of pixels in the map?

How is a multiplier map created?

How should I handle the integration of hemicubes?

**Edited to update changes - now normalizes multiplier map**

Here is pseudocode for integration of a single hemicube surface:

```
// set the max hemicube value using pre-calculated values
   FLOAT fHemicubeMaxValue;
   switch( uHemicubeSize )
   {
      case 32: fHemicubeMaxValue = 1.23e-3f; break;
      case 64: fHemicubeMaxValue = 3.11e-4f; break;
      case 128: fHemicubeMaxValue = 7.77e-5f; break;
   }

   // lock the hemicube render target
   BYTE *HemicubePixels = Lock( HemicubeSurface );

   // temp color
   D3DXVECTOR4 vColor( 0, 0, 0, 0 );

   // sum colors
   for( int y = 0; y < hemicubeHeight; ++y )
       for( int x = 0; x < hemicubeWidth; ++x )
           vColor += ToColor( HemicubePixels[ y * hemicubeWidth + x ] * ToColor( MultiplierMap[ y * hemicubeWidth + x ] * fHemicubeMaxValue );

```

During integration the hemicube pixels are scaled by the normalized multiplier map so that the incident color components will add up to a value between 0 and 1.

The implementation of radiosity renders hemicubes to a 'master' surface that holds many hemicubes. When the master hemicube surface has reached capacity then incident light is calculated by integrating the hemicubes within the master surface, thus reducing calls to IDirect3DDevice9::GetRenderTargetData() and IDirect3DTexture9::LockRect(). A 'current hemicube' index is maintained and this index is stored within each LumelData struct for lookup during the call to CalcIncidentLight().

Here is pseudocode of entire radiosity implementation:

```
// pass counters
UINT uiPass = -1; ucReflectivePasses = ...;

// iterate passes
while( ++uiPass < ucReflectivePasses )
{
   // iterate scene mesh objects
   for each mesh in meshCollection:
   {
      // current surface
      UINT uiSurface = -1;

      // declare current hemicube index
      UINT uiCurHemicube = 0;

      // point to mesh radiative surface( render target )
      meshRadiativeSurface = mesh.GetRadiativeSurface();

      // point to mesh residual surface( render target )
      meshResidualSurface = mesh.GetResidualSurface();

      // storage vector to hold LumelData pointers for lumels whose hemicubes have been rendered to the master hemicube surface.
      // A LumelData struct contains the world space pos, world space normal, uv coord, and index of the lumel's hemicube partition within the master hemicube surface
      std::vector< LumelData* > stgLumelData;

      for each surface in mesh:
      {
         // inc surface counter
         ++uiSurface;

         // get surface world space positions( used to calc a lumel's w.s. pos )
         D3DXVECTOR3 pvSurfacePos[ 3 ];
         memcpy( &pvSurfacePos, mesh.vertex_data[ uiSurface ].pos, 3 * sizeof( D3DXVECTOR3 ) );

         // get surface normal
         D3DXVECTOR3 vSurfaceNormal = mesh.vertex_data[ uiSurface ].normal;

         // get surface light map uv coords
         D3DXVECTOR2 pvSurfaceUV[ 3 ];
         memcpy( &pvSurfaceUV, mesh.vertex_data[ uiSurface ].uv, 3 * sizeof( D3DXVECTOR2 ) );

         // get surface material
         Material matSurface = mesh.materials[ mesh.attribute_data[ uiSurface ] ];

         // half pixel
         D3DXVECTOR2 vHalfPixel( 0.5f / uLightMapWidth, 0.5f / uLightMapHeight );

         // determine lumel coverage using the surface's light map uv coordinates
         RasterizeTri( uLightMapWidth, uLightMapHeight, pvSurfaceUV )
         {
            // calculate edge planes( perpendicular to edge vector )
            // allocate and fill an array of three EdgeData structs
            // determine bounds( min x, max x, min y, max y )
            EdgeData *pEdgeData = NULL;
            D3DXVECTOR4 vSurfaceBounds;
            BuildEdgeData( vHalfPixel, pvSurfaceUV, &vSurfaceBounds, &pEdgeData );

            // set cur scanline position to the first
            int nCurYPos = vSurfaceBounds.z;

            // iterate scanlines
            while( nCurYPos <= vSurfaceBounds.w )
            {
               // iterate scanline pixels
               int nCurXPos = vSurfaceBounds.x;
               while( nCurXPos <= vSurfaceBounds.y )
               {
                  // determine uv coord of the current lumel
                  D3DXVECTOR2 vLumelUV( nCurXPos / uLightMapWidth + vHalfPixel.x, nCurXPos / uLightMapHeight + vHalfPixel.y );

                  // validate the lumel's position inside the surface using the 'point-behind-plane' test
                  bool bValidLumel = true;
                  UINT ui = -1;
                  while( ++ui < 3 )
                  {
                      if( !IsPointBehindPlane( &vLumelUV, &pEdgeData[ ui ]->pEdgePlane ) )
                      { bValidLumel = false; break; }
                  }

                  if lumel lies behind all three edges( bValidLumel == true ):
                  {
                     // fill a LumelData struct with the lumel's:
                     //   world space pos( calculated using the surface positions, surface uvs, and lumel uv )
                     //   world space normal
                     //   lightmap uv coord
                     //   index within the master hemicube surface
                     LumelData *pLumelData = NULL;
                     BuildLumelData( pvSurfacePos, vSurfaceNormal, pvSurfaceUV, &vLumelUV, &pLumelData, uiCurHemicube++ );

                     // store the LumelData pointer to vector
                     stgLumelData.push_back( pLumelData );

                     // render hemicube
                     // draw the residual energy of scene objects( including the skybox ) to the master hemicube surface
                     SceneVisibility( &pLumelData )
                     {
                        // draw the scene
                        DrawScene();

                        // draw the skybox on the first pass only
                        if( !uiPass )DrawSkybox();

                        if the master hemicube surface has reached capacity( pLumelData->uiHemicube >= ucMaxHemicubePartitions ):
                           // calc incident light for each lumel in the storage vector by integrating the corresponding hemicube
                           // write the incident light directly to the radiative surface( alpha blending is used to add the incident light to any existing radiative energy for that lumel )
                           // write the residual energy as calculated using this formula: residual energy = incident light * surface reflectivity + surface emission
                           CalcIncidentLight( hemicubeMasterSurface, meshRadiativeSurface, meshResidualSurface, &matSurface, &stgLumelData );
                           ui = 0;
                           while( ui++ < stgLumelData.size() )
                              delete stgLumelData[ ui ];
                           stgLumelData.clear();
                           uiCurHemicube = 0;
                      }
                  }
                  nCurXPos++;
               }
               nCurYPos++;
            }
         }
      }
      // calc incident light for any remaining lumels within the storage vector
      CalcIncidentLight( hemicubeMasterSurface, meshRadiativeSurface, meshResidualSurface, &surface.material, &stgLumelData );
      ui = 0;
      while( ui++ < stgLumelData.size() )
         delete stgLumelData[ ui ];
      stgLumelData.clear();
      uiCurHemicube = 0;
   }
}

```

This is a screenshot taken from the outside of a structure with 2 windows...At the moment the structure is shaded with the lightmap only! The skybox (all white textures for debug) surrounds the structure and is used as the only source of light in the scene.

This is a screenshot from the inside of the structure. You can see very little light covers the geometry.

The structure's outside is entirely white, indicating the form factor calculations are correct. The hemicubes used on the outside of the structure were covered in white color from the skybox, then modulated with the multiplier map and scaled by the maximum form factor value 0.0013 for a 96x32 hemicube, the integration of which adds up to approximately 1...

If the walls inside the structure see very bright light (although in limited quantities), should I expect to see such miniscule amounts of light inside the structure?

# Answer
> 1 votes
You need to weight the samples by the cosine of the sample and the forward direction of the hemicube. This is because the amount the texel contributes is related to what its incident angle is from the normal. You can precompute these cosine values offline for each pixel since they are the same for every hemicube, assuming all your hemicubes are oriented the same relative to the surface normal. That's what the "multiplier map" contains. However this only is accurate for a polar projection

In the code you linked they also add another term which accounts for the perspective distortion of storing the texels in a cube which is rendered with 90 degree FOVs. This means that the samples near the seams are less direct facing. This makes sense if you think of the distance to a plane perpendicular to your viewing direction. It's closest in the center. So they combine these two terms together into multiplayer map.

Finally, they normalize the map. Since each hemicube is the same resolution you can bake in the constant 1.0 / ( hemicubeWidth * hemicubeHeight ) term.

This makes the integration code very simple:

```
// lock the hemicube render target
BYTE *HemicubePixels = Lock( HemicubeSurface );
FLOAT *MultiplierMap = {...};
// temp color
D3DXVECTOR4 vColor( 0, 0, 0, 0 );

// sum colors
for( int y = 0; y < hemicubeHeight; ++y )
    for( int x = 0; x < hemicubeWidth; ++x )
        vColor += ToColor( HemicubePixels[ y * hemicubeWidth + x ]) * MultiplierMap[ y * hemicubeWidth + x];

// vColor is the result

```

---
Tags: c++, directx9, radiosity
---


# Question
Title: How can I introduce time pressure on the player's decisions?
I am designing a hacking game, in which the player usually can take his time thinking about how to overcome the obstacles that he/she currently faces. However, I decided that besides coming up with clever solutions, hacking should also feel intense, and that the game needs some ways to put a time pressure on the player's decisions.

First such mechanic that I added reassured me that I am going in the right direction: Sometimes the player can trigger a network trace, which lasts X seconds and can potentially kick the player out of the network unless he/she reacts quickly enough and succeeds in evading the trace. I would like to add perhaps one or two more mechanics that would put the player under a time pressure, but I am a little stuck and always seem to come up with a variations on 'Countdown', i.e. 'There will be (a punishment) in (X) seconds, unless (some action is taken)', but obviously all those mechanics end up too similar.

In abstract terms — that is, without knowing the particular mechanics in my ruleset — how can I introduce a time-pressure on the player's decisions?

# Answer
> 24 votes
When I read your question I immediately had to think of the GameBoy game **Mario's Picross**.

It's essentially a Nonogram game: You're supposed to find the right tiles in a grid identified by numbers (similar to how **Minesweeper** works, but with different mechanics).

By default, you've got 15 minutes to solve a puzzle, which is plenty of time. However, whenever you make mistakes, your time remaining is reduced (the more time you have left, the more you're losing).

This adds an interesting tension to the game: You'll want to solve it fast. You can take your time, think 5 minutes about the problem, and then start solving it. Or you can risk it and start straight away. If you make a mistake, you won't be faster or better compared to the slower approach, but you've still got the option to do so.

Depending on your game, I could imagine that some similar mechanic would fit rather well into it. It should fit the whole timed approach and the actual theme as well, without having to explain anything special: If there's some intruder, if he's doin mistakes, he might be a lot easier to spot.

# Answer
> 7 votes
Depending on the scenario / setting of your game, the following things could work:

*Note:* Those are just some quick ideas and not completely thought through!

1. Perhaps you can weave in something like the following into the narrative: "Your hacker computer is having hardware issues since a few hours ago. It will only keep running for a certain time, before overheating. So be fast and stay away from brute force methods that stress your machine and so shorten the time before it overheats".
2. If that hacking bit (at least in one of the missions) is a piece of work that lasts several days in game time (not in one session of course), there might be the risk that authorities silently recognized the attack (triggered by a high risk, high reward decision of the player) and started investigations. As a result they might be out to get you. So to put some stress on the player, you could work with sound, e.g. police sirens and which puts extra stress on the hacker, since he/she doesn't know if they are coming for him/her or just passing down the street. Some additional game element, such as hiding your hacking involvement might be implemented, so that the player (if he/she thinks he/she is about to be made by the police) can hide their involvement e.g. by deleting parts of their previous results. The in-game results could be time loss, but at the same time averting the game-over state.
3. A similar idea: If you are always hacking away from home, that won't play any role. But if for special missions you are at a special location (had to break into some backbone data center or perhaps something a bit more likely), there might be security personnel wandering about. And if you hear them or see their flashlight cones wandering around, you have to stop typing in order to not be made, which in return costs you valuable time = enhanced stress level.
4. In addition to my idea #2: If you hack an institution, the police would arrive physically at your location. If however, you hack another individual, more specifically another hacker, he/she might try to attack you in return, so you would have to fend of their attacks while still still keeping your own ones going as well.

# Answer
> 4 votes
I think that most of the ideas here are a great inspiration, I think it would help you more to try and pull yourself out of the game and stop thinking of it as "a mechanic to a game". Think of what pressures would occur in real world situation.

You end up with a number of solutions from this, some could be as simple as allowing the player to purchase new scripts that detects another user has logged onto the same machine, starting to view logs etc (started to investigate).

I would personally make the game react more to possible real life events. Say if a player takes on a simple hacking mission at the start, does it and moves on but forgets to remove the logs. You could later alert the player that there's news on TV of a breach and police are investigating. Meaning the player would need to start going back and covering their steps.

This makes the game non linear and more life like in my opinion and makes the player feel more freedom rather than following a defined course.

Just my thoughts, good luck with the game

# Answer
> 2 votes
As I recall (haven't played it in a long time) the old school Shadowrun game on Genesis had a twist on your network trace mechanic for more dangerous targets. Less risky hacking targets would simply kick you out of the network, but more dangerous targets could actually trace your physical location and then send goons after you. That would certainly ratchet up the pressure to be fast!

# Answer
> 1 votes
One of the old-school techniques from the world of writing is overlapping "fuses". You're sort of on the right track with the trace, but it lacks punch as it's the only 'clock' running.

Say, for example, there's a time limit to the overall segment - the player has 30 minutes to infiltrate a secured compound, hack into one of the systems, then find the commands to shut down the protocols blocking them from their primary objective.

Add a few patrolling guards to introduce yet another time crunch, as well as a physical threat, and trying to concentrate on the task at hand becomes much more difficult.

Or, possibly, triggering the automated security sets off a Halon dispersal system. There are respiration systems nearby, but they're intended for escape - only lasting a few minutes each. The Halon shuts off after 10-15 minutes (player doesn't know when), after which time security will storm the room.

The real 'meat and potatoes' in such games comes from trying to juggle multiple lesser challenges simultaneously, rather than dealing with a single monolithic one.

# Answer
> 1 votes
I think you are heading in the right direction as well. If you want time pressure, you need to add an aspect of a countdown or time limit. Deus Ex: Human Revolution has a similar concept to your ideas about a network trace. The hacking was a mini-game that you could undertake to open doors, safes etc. without having to search for the key or wait for the story to advance to the point of making the key available.

A hacking attempt starts out with the system unaware of your presence. You are 'jacked into' the terminal node of a network diagram. The goal is to subvert nodes along the graph to reach all of the server nodes on the graph. Each action you take has a time to complete and a risk of alerting the system. When you trip an alert, a network trace starts from server nodes and if it reaches your terminal before you complete the graph or voluntarily disconnect, then you fail and face the consequences. The trace was essentially a countdown timer, which made each hacking node suspenseful on its own and made the entire thing a race against the clock once started. Consequences were usually just having to wait for the system to reset, but occasionally an alarm would sound and guards with guns would come try to kill you.

You can watch the in-game tutorial for the hacking system. There were various upgrades you could buy with your hard-earned experience points to improve your hacking abilities, as well as some single-use items you could find that would help with difficult hacks.

The mini-game was fairly interesting to learn and a vast improvement over 'hacking' in the first two games of the series, but it became tedious by the end of the story line. If you spent enough points on upgrades, most systems became trivially easy to hack, while the hard ones remained very difficult to complete fully. If you didn't spend your points on hacking upgrades, hard systems remained nigh impossible to take down without blowing through stacks of the worm software items.

Also, as there were only a handful of node-types to overcome and only 4 specific actions you could take at any given time. Every hacking attempt would devolve into either throwing all your items at it or just attacking every node as quickly as possible to get to the end.

In particular, if you added more ways to prepare for and react to the network trace, you could make your game much more enjoyable than Deus Ex's version.

Adding more mechanics of time pressure could end up being too similar. One idea that springs to mind is that the player must maintain the integrity of their connection to the system. Taking some actions decreases this integrity, taking other actions might hold it steady or even bolster it. If the integrity reaches zero, the signal is lost and your hacking attempt ends.

From a broader perspective, you can look at time as a resource the player must manage. Adding other resource pressures can increase the intensity of the time resource. You could try limiting the number of actions the player can take (the actions themselves become a resource) or the rate at which they can be taken (having to wait for some focus or brainpower resource to recharge between actions).

Riffing on Phillip's ideas, you could simulate the resources of the attacker's machine. Launching one kind of hack takes up x% CPU and yMB RAM for z seconds, or running a trace evasion program takes up a chunk of resources continuously. You can only take additional actions when your machine has the CPU and memory available for it.

You could also add an aspect of *timing* to the user's actions. Make it so certain actions can only be taken or completed at certain times. Or make it so you have to click, hold and release buttons at specific intervals to finesse your actions. (Like sports games frequently do: click & hold for a power level and click at the right moment for timing. Here's is a field-goal kicking game that implements this mechanic.) The better the players timing, the more likely their action is to succeed, or the better the outcome of the action.

Finally, if you want to reduce the starkness of the network trace - where either you're getting counted down or not - you could implement a heat or suspicion activity. Think of Grand Theft Auto or Thief or Assassin's Creed, where doing suspicious or illegal things raises the attention of the guards. If you keep being bad, the guard will attack or pursue you. But if you actively do something to deflect their attention (hide in a shadow, duck down an alley way, blend into a crowd, etc.), they leave you alone. You could adapt this mechanic for an anti-intrusion system without much of a stretch.

Good luck and it sounds like you're onto a fun game!

---
Tags: game-design, game-mechanics
---


# Question
Title: How to draw multiple shapes in one draw call?
I have a misunderstanding about vertex buffers in DirectX. I'm trying to draw infinite vertices that they may represent a line or a circle or a rectangle in a single draw call. I can bind them all together and set a flag for each vertex to determine which shape I have to draw now with `DrawPrimitive()`, but the questions are:

1. When I first create the vertex buffer, I set a constant length of 1000 for it because I don't know how many vertices I'm going to draw. How can I avoid this?
2. I don't know the proper way of drawing these vertices at all. I mean I can draw them right now with a dynamic VB, but I have no idea on performance and etc.

BTW, I've read this article which is pretty good, but it doesn't apply to my issue.

**Edit**

For example, I have 6 vertices which 2 of them are shaping a line and the other 4 are shaping a rectangle. I can bind them all together and copy them into the vertex buffer and then draw. Now, what if next time I wanted to draw a line and two rectangles? In this case I have to add 4 other vertices to my current list and we suppose my VB is not big enough to do that. This is my misunderstanding that I don't know if I should reserve enough space at first place for my VB or there is an alternative to pitch the length during runtime.

I'm trying to draw basic 2d shapes here nothing 3d:

```
// A class member
std::vector<Vertex2D> mVertices;

// Draw method
{
void* buffer = new char[this->mVertices.size() * sizeof(Vertex2D)];

Device()->VertexBuffer()->Lock(0, sizeof(buffer), &buffer, D3DLOCK_DISCARD);
memcpy(buffer, this->mVertices.data(), sizeof(buffer));
Device()->VertexBuffer()->Unlock();

Device()->SetStreamSource(0, Device()->VertexBuffer(), sizeof(Vertex2D), sizeof(Vertex2D));
Device()->SetFVF(D3DFVF_VERTEX2D);
Device()->DrawPrimitive(D3DPT_LINELIST, 0, this->mVertices.size());

delete[] buffer;
}

```

It's a simple draw call in a bigger loop. `mVertices` is a collection of different vertices for different shapes. My second question was, how to draw different shapes from one vertex buffer in a single draw call. My first question was, how can I adjust vertex buffer's length with a relevant length to my vertices and not a default value at compile time.

# Answer
> 1 votes
The standard way of rendering multiple shapes is to have a vertex buffer for each shape. When you want to draw lots of quads you can set your vertex buffer once and modify the world matrix for each quad you want to draw, i.e. scale, rotation, translation. It's easier to encapsulate this into a class.

I understand that you wish to use one draw call to be efficient but I would hazard a guess that mapping the vertex buffer to main memory every time you wish to change the geometry would be much more time consuming (assuming you do it often).

Direct3D does not provide a way to change the length of a vertex buffer after creation, so if you were to go down this route you would have to create extra buffers when you ran of out space.

Also I'm not sure how efficient this system would be when adding functionality to not render shapes (visibility flag), etc.

Just wanted to add a point on instancing.

You can use hardware instancing as P. Avery mentions. This would allow you to use one draw call per shape. So for instance you have a vertex buffer for a unit quad and then just use an array of matrices to transform the quad into the correct scale, rotation and position. More info can be found here on MSDN.

# Answer
> 0 votes
maybe instancing is what you want...you can instance a collection of vertices( a single vertex or many vertices, a mesh for example ) many times. This is done in software before the draw call...see this for an example of instancing...

---
Tags: directx9
---


title: (unity) move the world or the character

text:
# Question
Title: (unity) move the world or the character
I'm making a game like this: https://www.youtube.com/watch?v=hO7573lphqI

wherein a 3D ship is flying around on a 2D plane. From the player's perspective, the ship will stay stationary in the center of the screen.

The question I have is whether it's better to have to ship stay stationary and the world move around the ship? Or should I have the camera follow the ship as it moves around?

Notes:

* assume the ship can go infinitely in any direction
* this is in Unity, though I'm curious if that differs from other tools like Unreal
* I will be culling items that are offscreen either way

Obviously, having the camera follow the ship is easier from the programming side of things, but I'm wondering if there's a good reason not to do that (if the player moves far enough in one direction does it hit an internal limit that would break the game)?

Thanks!

# Answer
Both the points brought up by projectskillz and by twyla are important considerations. However they push in opposite directions (floating point precision means you don't want to move the player too far from the origin, but NPC ships will be extremely hard to handle if the world is moving) so you'll need to find a third-way compromise. For an infinite universe I would try a zones approach, where the world stays still within a zone, but when the player reaches the edges of the zone the world snaps over by the width of the zone, thus always keeping the player near the origin.
> 2 votes

# Answer
There aren't any technical drawbacks in both implementations.

That said, simplicity is very important when designing software. For many reasons. A game - most of the time -, simulates a subset of the reality. So trying to achieve a simulation that is more natural, that works like it would work in real life, is a noble objective to pursue. Even when there are some technical disadvantages.

But in your case, attaching the camera to the ship in the Hierarchy and moving the ship is the most natural way of doing. The other way doesn't have advantages and has the disadvantage that is just... weird.

You will have the challenge of making it be able to "go infinitely" to any direction, but this is a problem you'd have on both implementations.
> 2 votes

# Answer
Asking yourself one question should make the answer glaringly apparent:

"***How many game objects need to move for either implementation?***"

Under most circumstances, the ship moving through the game world requires only the player's ship itself to move. All other objects in the game remain relatively stationary in game-world-space.

If the ship is stationary and the game world moves, now you're introducing a whole world of mathematical nightmares in trying to calculate the movements of anything else which moves within game-world-space. NPC ships (and other PC ships, if ever making a multiplayer game), planets, space stations, etc.

Think back to the days when people thought the Earth was the center of the universe and all the wonky, lopsided mathematical formulas they had to work out to explain how other known planets varied their orbit speed throughout the year (sometimes appearing to reverse directions). Even though you've touched on this, you don't seem to quite realize just how deep this rabbit hole can go!

As others have pointed out, there are some issues concerning floating-point precision if you make your levels excessively large. Just be smart with your level designs and you'll save yourself a world of headaches.
> 2 votes

# Answer
In unity you can move as far as you want off the origin point.
There is no internal limit. However you will encounter a different type of limit. The floating point precision limit.

In short **floating point types** have a **precision limit** of around **7 digits** no matter the placement of the dot.

So for example you moved a character past say 1000 unity units.

You wanted to move an object from 1000.0000 to 1000.0001 you may or may not see jittering and your Gameobject may or may not be exactly in the place you expect it to.

So in general you would want to keep your gameplay as close to the origin as possible.

So if you wanted to be able to infinitely move in one direction you would absolutely need to implement a system that moves the world and loads it dynamically as you move.

This is not really just a limit of unity but of just how floating point numbers work. You could get double the precision if you were to use the double type however, Unity represents everything internally as a floating point number as they are just faster and have a lower memory footprint on almost every modern system today.

For a detailed explanation of this check here. http://www.davenewson.com/dev/unity-notes-on-rendering-the-big-and-the-small
> 1 votes

---
Tags: unity, transformation
---


title: AndEngine Foreground Sprite

text:
# Question
Title: AndEngine Foreground Sprite
I'm developing an Android game and have some troubles: I want to add some foreground sprites, that must obstruct my player.

Se the following example: Its a screenshot from "Shinobi 3". We can see the player, the enemy, the background and two foreground trees, that hide the player's arm and part of the enemy.

I'm using AndEngine GLES2 Anchor Center and I am trying to add a new layer to my scene.

```
Sprite Forest = new Sprite(getWidth() * 0.5f, textureHeightForest * 0.5f + 100, ResourcesManager.getInstance().foreground_forest_region, vbom);
Entity foregroundLayer = new Entity();
foregroundLayer.attachChild(hillFurthest);
attachChild(foregroundLayer);

```

But it still shows behind my player sprite. I am trying to find something in HUD-class (it's always shown in the foreground), but got no results. Can anyone help please?

# Answer
> 1 votes
You can add the sprites directly to the scene and set their z-index to higher value than the player. Then simply call `scene.sortChildren()` and the trees will be in front. Also if you add the trees last, they will obstruct your player.

More sophisticated version of this is to use a custom parallax layer that will be added with higher z-index and that would even create the 3D effect.

---
Tags: andengine
---


# Question
Title: CCUserDefault, iOS/Android and game updates
My game uses cocos2d-x and will be published on iOS platform first, later on Android. I save a lot of things with CCUserDefault (scores, which level was completed, number of coins taken, etc...). But now I have a big doubt.

What will happen when the game will receive its first update?

CCUserDefault uses an XML file stored somewhere in the app storage space. This file is created and retained until one uninstalls the app. I am wondering what happens when the app is updated. Will the old XML file be maintained?

Because if not, how should I handle app updates (updates in the sense that 2, 3 or more new level packages will be added, but the informations about the old ones, like scores, which level was finished and which not, number of coins, etc., need absolutely not to be lost)?

# Answer
Ok, i found the answer. CCUserDefault stores the xml file under:

```
application_home/library/caches

```

The iOS App Programming Guide states that all the data under

```
application_home/document

application_home/library

```

will be preserved. That is, after the update, your userdefault.xml file will be still there
> 1 votes

# Answer
Here's a similar question on stackoverflow regarding NSUserDefaults which I would assume CCUserDefault emulates or inherites

https://stackoverflow.com/questions/1638766/do-nsuserdefaults-persist-through-an-update-to-an-app-in-the-appstore
> 0 votes

# Answer
Your `.xml` file will be there after updating.

The exact path in iOS is

```
/Users/yourusername/Library/Application Support/iPhone Simulator/(select your
version)7.0.3/Applications/(something like this)9C9FF1EB-0674-4FA9-A113
D9E3DAD7B2CB/Library/Preferences/com.yourcompany.projectname.plist

```

Open this plist and you can see the key and associated stored value.

Make sure to keep your library folder unhidden by running this in the terminal:

```
chflags nohidden ~/Library

```

I don't know about Android.
> 0 votes

---
Tags: ios, cocos2d-x, savegame
---


# Question
Title: First person camera world matrix issue (in THREE.js and webGL)
I'm trying to create a Portal-like effect in webGL using THREE.js.

I have two scenes connected by a pair of portals. The view of the 2nd scene in rendered inside the 1st portal using stencils and some matrix math

This is the code I use to determine the view in the portal:

```
function getPortalViewMatrix(cam, src, dst)
{
 var inverseCamToSrc = new THREE.Matrix4().getInverse(cam.matrixWorld).multiply(src.matrix);
 var rot = new THREE.Matrix4().makeRotationY(Math.PI);
 var portalViewMatrix = dst.matrix.clone().multiply(inverseCamToSrc).multiply(rot);

 return portalViewMatrix;
}

```

This setup worked as intended until I added first person camera controls, taken from this example.

Now, the view of the second scene is wrong whenever I rotate the camera (but remains correct if you only walk around), as you can see in here (only works in Chrome). The full source is also available there.

The PointerLockControls class I use places the Camera in a 'rig' to avoid gimbal lock:

yawObject -\> pitchObject -\> camera

The yawObject is rotated on the y axis. The pitchObject is rotated on the x axis. The camera itself remains fixed as a child of the pitchObject.

The PointerLockControls work very well, but because of this setup the matrixWorld property of the camera does not seem to represent the same values as with a free floating camera. And my understanding of matrix math is lacking to fix this problem.

I've tried different things like inverting the various matrices involved, using quaternions (decomposing camera.matrixWorld) but that has just been an exercise in random trial and error on my part.

Can anyone help me to understand this problem, and perhaps offer a solution?

Any help would be greatly appreciated.

# Answer
> 1 votes
Assuming your jsfiddle code is what needs fixing, try:

```
function getPortalViewMatrix(cam, src, dst)
{
 return dst.matrix.clone().multiply(cam.matrixWorld);
}

```

That syncs the two worlds.

---
Tags: camera, matrix, webgl, three.js
---


title: Sound composition/compilation softwares

text:
# Question
Title: Sound composition/compilation softwares
I'm a one man developer company. I'm working on a game for which I need some variety of sounds. I searched online stock music and it does not give me what I'm exactly looking for.

As a desperate and unsatisfied enthusiast and low-budget game maker, I would like to give a try to compose sound myself.

Is there any sound composing software for games available(with some instruments) ? I believe I have some good music taste. but, it needs some time to achieve what I need. I'm willing to put this much for my super game.

# Answer
> 1 votes
There is Linux Multimedia Studio (which, despite its name, also runs on Windows), which is a free open-source music composing software heavily inspired by the commercial FL Studio. It comes with a library of instrument samples and a couple of synthesizer plugins. It also supports the VSTi plugin standard, which means that a lot of synthesizer plugins for other composing softwares can be used.

But it doesn't get near the commercial alternatives in regards to feature-set, stability and polish.

By the way: Just having a good taste in music often doesn't mean that you are also able to reproduce your favorite style of music. To really understand how and why certain kinds of music work the way they do, you will have to invest a lot of time into learning music theory. Composing is a skill with a learning curve just as brutal as that of programming or art. When you want to learn how to be a composer, you might want to sign up on Music Stackexchange.

# Answer
> 2 votes
Not for free. Composing takes some money. There are programs like Cubase, Ableton, and Reason for sequencing music. You will want some extra sound libraries though, if you want it to sound any good. This costs quite a bit. I bought an LA Strings library, some native Instruments libraries, and Stormdrum for drum sounds, and then various other things. I've spent over 2500 dollars on this stuff. Then you'll probably want a midi keyboard and some decent headphones.

---
Tags: sound
---


title: Best mobile games resolution ratio

text:
# Question
Title: Best mobile games resolution ratio
What is the best landscape and portrait resolution ratios that will fit the most of the devices out there and the black bars size will be minimum?

# Answer
For minimizing the amount of black bars you should aim around the median ratio of target devices, that would probably be 8:5 or 5:3.

But if you really need your game to be a fixed ratio, consider using some filler art instead of black bars, you might simply have a playing field background with some out of bounds area that is cropped away depending on screen aspect ratio.
> 1 votes

---
Tags: java, libgdx
---


# Question
Title: Compute cone angle (cos) given side and hypotenuse vectors at time 0 and world matrix at time 1
I need a formula for the cosine of a cone, given normalized side vector, normalized hypotenuse vector at time 0 and world matrix at time 1. This is needed to implement custom spotlights in a level editor which can be tweaked by user via standard translation/rotation/scale gizmo.

The cosine of the cone at time 0 (when world matrix is Identity) can be computed via this formula:

```
Vector3.Dot(side, hypotenuse);

```

I tried this formula for time 1:

```
Vector3.Dot(Vector3.Normalize(Vector3.Transform(side, matrix)), Vector3.Normalize(Vector3.Transform(hypotenuse, matrix)));

```

but it does not work.

# Answer
Despite its name, `Vector3.Transform()` does not transform a vector but a point. The unwanted side effect is that the translation part gets added to your vector. If you want to actually transform a vector, you need to use `Vector3.TransformNormal()`, which will omit the translation part:

```
Vector3.Dot(Vector3.Normalize(Vector3.TransformNormal(side, matrix)),
            Vector3.Normalize(Vector3.TransformNormal(hypotenuse, matrix)));

```
> 1 votes

# Answer
Sorry, the formula was correct. I built my side and hypotenuse vectors at time 0 incorrectly. My mistake was that I used normalized vectors at time 0 in the transformation, while you need to use the original ones. You can indeed find the cosine at time 1 with this formula:

```
Vector3.Dot(Vector3.Normalize(Vector3.Transform(side, matrix)), Vector3.Normalize(Vector3.Transform(hypotenuse, matrix)));

```
> 0 votes

---
Tags: lighting, mathematics
---


title: Loading sound file into monogame

text:
# Question
Title: Loading sound file into monogame
I'm trying to load sound into my game. I downloaded an .mp3 sound (a second long) and tried to load it both as Song and as SoundEffect, but it didn't work, so I tried loading the same sound but as .wav and I was able to load it as a SoundEffect. The problem is that the sound that is coming out sounds like static noise. I looked a bit into this and found out I need to load sounds as .xnb files, so I downloaded 'XNAContentCompiler' project and tried to compile the sounds causing a 'PInvokeStackImbalance' error.

So I found this thread: http://xboxforums.create.msdn.com/forums/p/65519/65519.aspx

Saying I can ignore this and continue.

The xnb file fails to be created when I try to convert the .wav files, saying it is 24-bit audio and I may only use 8 to 16 bit. So I tried to compile the .mp3 file and it succeed, creating a 1k file that I still cannot load not as a Song and not as SoundEffect.

I'm now completely lost on this and can no longer understand what I need to try to load and what is a different problem completely, and I would love some explanations.

# Answer
> 1 votes
I was experimenting with monogame and noticed that ,the xna content pipeline creates .wma file and .xnb file in the output directory for each mp3 i compile. I can get the song to play on my windows 8 project only if i copy both the .wav and .xnb to the content directory.

---
Tags: c#, monogame
---


# Question
Title: Why is the light following my camera around?
I have implemented a simple Phong shader without specular highlights for now (just ambient + diffuse components)

The problem however, is that the calculations seem to be done in camera space; as I move the camera around, the light source seems to move along with it. This is evident by me not being able to see the dark side of the models

(Note: Image is a gif, if it is not animating, open in a new tab)

My light is a point light, that I would like to have fixed somewhere in the world. It has a defined position. To my shader, I also pass in the M, V, P matrices, as well as the normal matrix, which is the inverse transpose of the MV matrix

```
cameraPosition=glm::vec3(8,8,8);
cameraTarget=glm::vec3(0,0,0);
cameraUp=glm::vec3(0,0,1);
glm::vec3 cameraDirection=glm::normalize(cameraPosition-cameraTarget);
cameraRight=glm::cross(cameraDirection, cameraUp);
view=glm::lookAt(cameraPosition, cameraTarget, cameraUp);
glm::mat4 model_view = view * modelMatrix;
glm::mat4 normal_matrix = glm::transpose(glm::inverse(model_view));

```

The following is my shader code

```
attribute vec3 vertex_position;
attribute vec3 vertex_colour_in;
attribute vec3 vertex_normal;

uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;
uniform mat4 normal_matrix;
uniform vec3 ambient_light_colour_in;
uniform vec3 light_position_in;

varying vec4 fragment_colour;

void main(void){
  //position
  gl_Position = projection * view * model * vec4(vertex_position, 1.0);

  //ambient colour
  vec3 ambient_colour = ambient_light_colour_in * vertex_colour_in;

  //diffuse colour
  vec3 normal = normalize(vec3(normal_matrix * vec4(vertex_normal, 0.0)));
  vec4 pos4 = view * model * vec4(vertex_position, 1.0);
  vec4 lightPos4 = vec4(light_position_in, 1.0);
  vec3 lightDirection = normalize((lightPos4 - pos4).xyz);
  vec3 diffuse_colour = vertex_colour_in * max(0.0, dot(normal, lightDirection));

  fragment_colour.rgb = ambient_colour + diffuse_colour;
}

```

As far as I understand, the problem is that these lighting calculations are done in Camera space, and hence change when the camera changes position. So, my question is **How would I change that to get the light to be at a fixed position, ie: do the light calculations in World space**

# Answer
You're multiplying your vertex position and normal by the view matrix, change it to only use the model matrix.

`vec4 pos4 = model * vec4(vertex_position, 1.0);`

Change the normal\_matrix to just be the inverse transpose of the model matrix only.

```
glm::mat4 normal_matrix = glm::transpose(glm::inverse(modelMatrix));

```
> 2 votes

---
Tags: opengl, glsl, lighting, graphics-programming
---


# Question
Title: What is wrong with my smooth shading code?
I am having trouble getting smooth lighting to work in Java Monkey Engine.

My terrain is voxel-based, with an iso-surface generated via Marching Cubes over the data field.

Up until now, I have been simply calculating the triangle-face normals, and using only those when creating the mesh for each chunk. This produces the faceted look typical of this approach.

Now, I am iterating over each triangle in the chunk, and adding the triangle-face-normal to each vertex normal in the triangle. Vertices are shared between triangles. As I understand it, this should smooth out the lighting, and reduce the faceted look. I am not seeing these results.

Here is a snippet which illustrates the vertex normal processing:

```
        for( UUID blockId : chunk.blockIds )
        {
            Block block = BlockStore.getInstance().getBlock( blockId );

            FastTable<Triangle> blockTris = block.getTris();
            if( blockTris == null )
                continue;

            for( Triangle tri : blockTris )
            {
                javax.vecmath.Vector3f triFaceNormal = (javax.vecmath.Vector3f)( tri.norm.clone() );

                tri.getVert0().norm.add( triFaceNormal );
                tri.getVert1().norm.add( triFaceNormal );
                tri.getVert2().norm.add( triFaceNormal );
            }

            for( Triangle tri : blockTris )
            {
                tri.getVert0().norm.normalize();
                tri.getVert1().norm.normalize();
                tri.getVert2().norm.normalize();
            }
        }

```

Then the blocks/triangles for this chunk are iterated over again, and the component values of all the vertex normals are added sequentially to the "normal buffer", which is fed into the mesh creation.

Here is what the mesh data looks like, using the JME ShowNormals material, which color-codes things according to normal direction. You can clearly see the facets:

And here is the code which builds the chunk mesh, after the buffers have been populated:

```
        chunkMesh.setBuffer( VertexBuffer.Type.Index, 1, BufferUtils.createIntBuffer( uberIntBuf ) );
        chunkMesh.setBuffer( VertexBuffer.Type.Position, 3, BufferUtils.createFloatBuffer( uberVertBuf ) );
        chunkMesh.setBuffer( VertexBuffer.Type.TexCoord, 2, BufferUtils.createFloatBuffer( texBuffer ) );
        chunkMesh.setBuffer( VertexBuffer.Type.Normal, 3, BufferUtils.createFloatBuffer( uberVertNormBuf ) );

        TangentBinormalGenerator.generate( chunkMesh );

        chunkMesh.updateBound();

```

You can see in this screenshot, that the individual triangles do have some blending, indicating that the summation of a vertex's surrounding triangle-face normals, into the vertex normal, is having *some* effect.

I'm not sure what I am doing wrong.

# Answer
> 3 votes
I have solved the problem. As it turns out, in my Marching Cubes polygonizer, I was inadvertently making copies of the vertex data, (objects), which were then being propagated through the rest of the processing pipeline.

Something I learned: If you know smooth shading is enabled, and you see sharp edges on anything but very acute angles, then your vertex data is not properly shared.

---
Tags: java, 3d, jmonkeyengine
---


# Question
Title: How AAA games use this texture in the tone-mapping shader?
I found that Battlefield 3 as well as Saint's Row the Third use this texture in their final tone-mapping stage. Can anyone share a link to an article about how this texture is used?

**UPDATE:** As there are hardly any examples of Color Grading implementation on the net, I will post my quick and dirty sample for XNA 4.0. This does nothing but builds the default 2d colormap from scratch on GPU, copies it's contents into a 3d texture on CPU and performs the actual color-correction with the shader code from the article provided in the answer.

XNA 4.0 Color Correction Sample

If you want to know what you can do with this, look here:

http://the-witness.net/news/2012/08/fun-with-in-engine-color-grading/

In short the author explains there, how you can basically make a screenshot of your normal in-game image with the default color grading palette on top, perform screenshot color correction in photoshop, cut and copy the deformed color correction palette into the engine and have that color correction applied for every in-game scene automatically.

# Answer
This looks like the bottom layer of a volume texture that many games these days use to perform color correction. The idea is that the final RGB screen color, after rendering and tonemapping, is used as a texture coordinate to index into this texture, and the color found in the texture replaces the original color.

This allows artists to arbitrarily modify the colors of the scene, by loading a volume texture that represents the desired modifications. The "identity" texture - which results in no modification of the color at all - consists of a texture which has a red gradient along the X axis, a green gradient along the Y axis, and a blue gradient along the Z axis (i.e. the volume texture depth axis). The first layer (Z = 0) would therefore look like the texture you posted.

GPU Gems 2 describes the technique in more detail.
> 50 votes

---
Tags: textures, hlsl
---


title: Hearthstone suggest a card algorithm

text:
# Question
Title: Hearthstone suggest a card algorithm
Does anyone have an insight of the suggest a card algorithm in hearthstone deckbuilding? I would like to try to see it that same suggestion can be applied in MtG, having for example to choose your total mana and get suggestions for color, colorless and enchantments/artifacts/sorceries/instants.

# Answer
Since Hearthstone is written in Unity it is trivial to decompile the scripts (because .NET), and this does in fact allow us to see the algorithm for deck building.

The algorithm (found in `RandomDeckMaker.GetChoices`) is actually very simple. It basically tries to pick random cards to bring the deck to the following distribution:

* 12 class-specific cards
* 4/4/3/2/2/1/1 cards with cost 0-1/2/3/4/5/6/7+
* 8 spell cards
* 15 minions

The function takes an argument to specify the number of cards to pick, and it will attempt to randomly pick that many cards matching the first unmatched criteria in the list above; if it cannot pick enough cards from matching that criteria, it moves to the next one and continues until it has enough cards. If all criteria have been processed, it just picks random, valid cards regardless of the type or mana cost. When asking for recommendations, it picks 3 cards; if you ask it to finish the deck for you, it repeatedly picks one card until the deck is full.

This only applies to personal deck building; cards for Arena decks are picked by the server (see class `DraftManager`), and might therefore follow a different algorithm.
> 5 votes

---
Tags: algorithm, logic
---


# Question
Title: Applying a noise texture to distort edges
I asked this question over on StackOverflow but then found this site, and it's probably better suited to here.

I'm trying to implement Sketchy Drawings. I'm at the part of the process which calls for the use of the noise texture to derive uncertainty values that will provide an offset into the edge map.

Here is a picture of my edge map for a torus:

And here is the noise texture I've gotten using the Perlin function as suggested:

I have these saved as textures in `edgeTexture` and `noiseTexture` respectively.

Now I'm stuck on the section where you have to offset the texture coordinates of the edge map by uncertainty values derived from the noise texture. This image is from the book:

```
offs = turbulence(s, t);
offt = turbulence(1 - s, 1 - t);

```

I'm ignoring the 2x2 matrix for the time being. Here is my current fragment shader attempt and the result it produces:

```
#version 330

out vec4 vFragColor;

uniform sampler2D edgeTexture;
uniform sampler2D noiseTexture;

smooth in vec2 vTexCoords;

float turbulence(float s, float t)
{
    float sum = 0;
    float scale = 1;
    float s1 = 1;
    vec2 coords = vec2(s,t);

    for (int i=0; i < 10; i++)
    {
        vec4 noise = texture(noiseTexture, 0.25 * s1 * coords);
        sum += scale * noise.x;
        scale = scale / 2;
        s1 = s1 * 2;
    }

    return sum;
}

void main( void )
{
    float off_s = turbulence(vTexCoords.s, vTexCoords.t);
    float off_t = turbulence(1 - vTexCoords.s, 1 - vTexCoords.t);

    vFragColor = texture(edgeTexture, vTexCoords + vec2(off_s, off_t));
}

```

Clearly my addition to the `vTexCoords` is way off, but I can't see why. I have tried several other turbulence function definitions but none were close to the desired output so I'm thinking my overall approach is flawed somewhere. Any help here is greatly appreciated, and please comment if I haven't been clear. The desired output for a torus would just look like a roughly drawn circle I would imagine.

# Answer
It looks like you're applying way too much noise. You want to multiply the noise value by a small factor so it has a very small amplitude, corresponding to just a few pixels of distortion. Right now you're distorting it so much that every pixel is being sent to a completely different location in the texture, just making a hash of the whole thing.

Also, I've only skimmed that article, but I'm pretty sure you're not supposed to render the Perlin noise on the surface of the torus the way you show in your second shot. Much more likely, you're supposed to apply the Perlin noise in screen space, using it as the noise texture directly.

You also likely don't need 10 octaves of noise as you're currently calculating in your turbulence function. In fact, just start with a single octave (a single Perlin noise sample) and add more octaves only if needed. You'll want a parameter to control the texture coordinate scale (frequency) used for the noise sample, as well.
> 3 votes

---
Tags: textures, glsl, perlin-noise
---


title: Clay Jam continuous path/tap

text:
# Question
Title: Clay Jam continuous path/tap
I saw this game Clay Jam, that the user can create a path in the sand. The path is a continuous one, and it can varies from a single point to curves.

How one can develop smooth and continuous paths?

# Answer
> 2 votes
It renders using bump- / specular maps. Refer to this video. The ground geometry is never modified.

Bumpmaps are just heightmaps used for realistic lighting. To clarify definitions,

1. bumpmapping is a rendering technique, typically written as a shader, which creates the illusion of surface detail on what is in fact a flat piece of geometry... in this case, the ground.
2. heightmap is a 2D grid / array of scalar values representing heights in different cells of the map. This would be the source of information for the bumpmapping process.

Modifying the heightmap to reflect the user's touch-drag would consist of getting the sequence of touch points (optionally adding some interpolation points to provide a smoother path), then connecting them, and calculating the 2D vector between each point-pair on the drag path.

You'd then carve a groove along each such vector. The carving in v-form would be done with a circular "brush" mini-texture that has high intensity toward the centre, and an intensity approaching zero toward the edge... in fact, there is a slight negative intensity toward the edge, as you can see that a lip is created around the furrow. Onto your clean, flat heightmap texture, the brush shape is painted onto/around every pixel/texel between the start and the end of the vector path. The *pixel* path is probably best calculated with something like Bresenham's Line Algorithm, or even better, Xiaolin Wu's Line Algorithm, which allows sub-pixel accuracy for a smoother path.

Lastly write your pixel / fragment shader to utilise the heightmap texture for lighting, based on light source direction. There are endless sources both on this site and elsewhere online on how to go about producing and rendering bump and specular maps.

---
Tags: game-design, software-engineering, game-mechanics, cocos2d
---


title: Unity3D Multiplayer Networking

text:
# Question
Title: Unity3D Multiplayer Networking
I am making a **multiplayer game using Unity3D**, similar to SecondLife (but focusing on a particular gameplay task). Users will be able to register/login directly in the game and their character will be spawned. So far, I have made the back-end Rest-ful API to manage users. I am able to use login and register from the unity itself ( Using REST Calls e.g. *www.myDomain.com/api/login* ) but how do I spawn the characters accordingly?

Also, currently I am making a token based authentication system for the API ( much like Facebook, Twitter) as the API itself is state-less. Should I be storing the tokens in **playerprefs**?

I have gone through this tutorial but it doesn't seem to solve my problem. Any kind of direction will help. Thank you.

# Answer
Ill just point you in the right direction.

Probably should use photon networking and if you want to know the basics of that this is the video series for you.

https://www.youtube.com/watch?v=AIgwZK151-A

Spawning players is pretty straightforward in unity.
> 1 votes

---
Tags: unity, networking, multiplayer
---


# Question
Title: Should I use one thread per game object?
I developing a simple real-time strategy game in a small team with no experience, and we're considering using one thread per game object (tank, soldier, etc). Is this a good idea or is it overkill?

The thread would call each object on each instant change (game timer, not graphic engine timer)

We're using Python with the Panda3D engine, meaning the GIL is probably going to reduce a lot the possible speed improvements.

# Answer
> 13 votes
Rule number one of multithreading: **Don't even think about it, unless you really need to use multiple CPU cores for performance reasons\***. Multithreading opens up a whole can of worms of obscure and impossible to reproduce bugs:

* **Race conditions!** Because you have no control over the thread scheduling of the OS, you have no control over the order in which things happen. You might *assume* that a certain task takes much longer to complete than another and build on that assumption. But in one of a million executions that assumption is wrong, and an obscure bug happens which is impossible to reproduce.
* **Synchronization issues!** When one thread modifies data while another thread is in the process of reading it, the thread reads a mixed state of old and new data. This can lead to really obscure bugs which are - again - almost impossible to reproduce.
* **Deadlocks!** The two problems above can be avoided by certain synchronization and locking techniques which are available in most programming languages. Unfortunately these features take a lot of knowledge and experience to use correctly. When you use them incorrectly, you will quickly run into deadlocks: Two threads both blocking their data structure and both waiting for the other thread to release theirs. This will lead to an infinite loop and cause both threads to freeze.

When you and your team are inexperienced, do it without multithreading. You will run into enough bugs and architecture problems without the additional complexity nightmares brought to you by unnecessary threading.

The great age of real-time strategy games were the late 90s in which there were practically no multi-core CPUs on the consumer market. Tons of great RTS games (Command&Conquer, Age of Empires, Total Annihilation, Starcraft...) did well without multiple cores on much worse hardware than you have today. So why shouldn't you be able to do the same?

<sub>\*) Exception from this rule: Waiting for I/O of files, network or user input. But in that case you shouldn't write your own multithreading code. Use the asynchronous APIs with callbacks provided by the standard library when you can. These use multithreading "under the hood", but hide the nasty details from you.</sub>

# Answer
> 4 votes
That sounds like a really bad idea. For multithreading to work well you need individual tasks that require significant computation, and can be easily segregated so that they don't work on the same dataset.

There is an overhead to each new thread you use, there is in some cases a big overhead for shipping data between threads, and once you have occupied each virtual core with a thread there is no performance to gain by starting more threads.

If you are to use multithreading you would want to do something like putting pathfinding in its own thread. But for now you are probably better off just making the game as simple as possible.

# Answer
> 4 votes
## Before you do anything read the first paragraph here

First and foremost, running hundreds of threads isn't going to boost performance. It is going to instantly **ruin** your game. Why ? Because afaik in Windows and Linux the schedulers wakes up every millisecond (possibly more like 3) to check if another process needs to run. So if you have 50 tanks and 100 soldiers that means that you can hope for 7 frames per second. Sounds great to you?

based on this link

Each tool has advantages and disadvantages. If you don't *need* the advantages, you still suffer from the disadvantages if you misuse it needlessly.

tl;dr Basically, threading is "Would you do *that* for me? But don't stop doing *this* while you do *that* other thing. It is also sometimes, "Would you do that *big task* faster if I break down into *smaller separable chunks*?"

Multithreading is advantageous for:

* Software performance optimization for multi-core systems hardware. I did not see a case where that was *needed* for indie gaming.
* Writing software that handles multiple, possibly unrelated processes at the same time, like a server handling an unknown number of clients. This use is not as popular nowadays but it's useful to understand as a design concept.
* Running another process asynchronously without halting the main program until it's completion. For instance, lets say you have a huge DB and you are loading some statistics. You wouldn't want the GUI to freeze until it's done? Another example that was mentioned here is running a long AI process and allowing the game to continue uninterrupted.

All the above works great especially when you don't need to share data between threads although if you do, there are special variations of the usual data-structures like lists and hashes for you to do so.

It is a subtle difference but the game is one process and the units are one part (entities) of that game that continuously need to communicate with the game. They don't need to be running on their own. They need to be **synchronized** with the game world.

If you want to mess around with "advanced techniques", you could try the Entity Component design pattern. I don't recommend it if you are new to this. Just use an array of soldiers and possibly pool and reuse dead soldiers. Then when you have a list or whatever container you choose, iterate over the soldiers each frame and go `unit.doYourThing();`

You may want all the units to inherit from a base unit so you could iterate over them all easily without having to treat each unit type differently in the main game loop.

# Answer
> 4 votes
I won't repeat why you should not use one thread per game entity, but if you truly want to use a simple-to-think-yet-efficient concurrent model, look for the **actor model**. In the actor model, you software is made of *actors*. Each actor is a parallel entity that you may think as a thread with state, even though it may be implemented differently. Each actor also has a *mailbox* which can receives *messages* from other actors. Thus, no state is shared between actors; every relevant information is communicated through actors by copying it into the messages. Thus in the actor model, you completely avoid inconsistent state and errors due to race conditions or bad handling of synchronization. You also avoid almost all deadlocks, which arises only by abusing the possibility for an actor to wait a reply of another actor and do nothing until then (which is bad if the actor could do something else while waiting for the reply).

In practice, actors are often written using a thread pool where a thread pool job terminates when the actor polls its mailbox for new messages. There are several frameworks in various programming languages for the actor models, even languages design around the concept (erlang). Just have a look on wikipedia : https://en.wikipedia.org/wiki/Actor\_model#Actor\_libraries\_and\_frameworks

---
Tags: multithreading, rts, strategy
---


title: Unity - 2D Wall Jumping

text:
# Question
Title: Unity - 2D Wall Jumping
I'm developping a 2D platformer and i'm facing a little trouble. I'm actually trying to develop a Wall detection and the possibility to Wall Jump and go in the opposite direction. I'm able to detect Walls and when i press the jump button my player goes nuts. I actually made a little video to show you what's going on + my code :

Speed x 15 (on the code i only multiply the force on X by 15) = http://youtu.be/zeK8RTVQdiU
Normal Speed = http://youtu.be/GvW\_x0hd7wk

Here is my code

```
#pragma strict
var moveSpeed : float = 600;
var jumpSpeed : float = 25;
var fallSpeed : float = 64;
var maxFallSpeed : float = 60;
var maxUpSpeed : float = 25;
var slopeLimit : float = 45;
var onGround : boolean;
var touchLeft : boolean;
var touchRight : boolean;
var justBounced : boolean;
var contactAgainst : boolean;

private var vm : float;
private var xScale : float;
private var h : float;
private var v : float;
private var jump : boolean;
private var boxCollider : BoxCollider2D; //If boxCollider2D is used replace w/ ...     private var boxColl : BoxCollider2D;
private var circleCollider : CircleCollider2D;
private var vectorRight : Vector2;
private var vectorLeft : Vector2;

function Start () {
    xScale = transform.localScale.x; //Get correct starting Orientation for player.
    boxCollider = GetComponent(BoxCollider2D); //if boxCollider2D is used replace w/... boxColl = GetComponent(BoxCollider2D);
   circleCollider = GetComponent(CircleCollider2D);
    var vectorLeft = Vector2(Vector3.left.x, Vector3.left.y);
    var vectorRight = Vector2(Vector3.right.x, Vector3.right.y);
}

function Update () {
    h = Input.GetAxisRaw("Horizontal"); //get horizontal input
    v = Input.GetAxisRaw("Vertical"); //get vertical input
    jump = Input.GetKey(KeyCode.Space); //get jump input
    if((touchLeft || touchRight) && contactAgainst) {
        var forceSaut : float;
        if(touchLeft && !touchRight && jump) {
            h = 1;
            forceSaut = h * moveSpeed * Time.deltaTime;
            Debug.Log(forceSaut);
            rigidbody2D.AddForce(Vector2.right * forceSaut); //Apply horizontal movement
            rigidbody2D.AddForce(Vector2.up * jumpSpeed); //Apply vertical movement
            justBounced = false;
        }
        else if(!touchLeft && touchRight && jump) {
            h = -1;
            forceSaut = h * moveSpeed * Time.deltaTime;
            Debug.Log(forceSaut);
            justBounced = true;
            rigidbody2D.AddForce(Vector2.right * forceSaut * 15); //Apply horizontal movement
            rigidbody2D.AddForce(Vector2.up * jumpSpeed * 3); //Apply vertical movement
        }
        else {
//              Debug.Log("collision et contre un mur !");
        }
    }
}

function FixedUpdate(){
    if(onGround && jump && !touchLeft && !touchRight){ //Are we grounded can we jump?
            vm = jumpSpeed;
    }
    if(justBounced)
        h = 0;
    var moveH : float = h * moveSpeed * Time.deltaTime; //Smooth horizontal movement
    //Flip character orientation
    if(h < 0){
            transform.localScale.x = -xScale;
    } else if(h > 0){
            transform.localScale.x = xScale;
    }

    rigidbody2D.AddForce(Vector2.right * moveH); //Apply horizontal movement
    rigidbody2D.AddForce(Vector2.up * vm); //Apply vertical movement

    vm -= fallSpeed * Time.deltaTime;

    vm = Mathf.Clamp(vm, -maxFallSpeed, maxUpSpeed); //Clamp vertical speeds
    rigidbody2D.velocity = Vector2.zero; //Stop movement if there is no input
    onGround = touchLeft = touchRight = false;
    checkPositionCollision();
}

function OnCollisionEnter2D(c : Collision2D){
CheckCollision(c);
}

function OnCollisionStay2D(c : Collision2D){
CheckCollision(c);
}

function OnCollisionExit2D(c : Collision2D) {
contactAgainst = false;
}

function CheckCollision(c : Collision2D){
for(var contact in c.contacts){
        if(vm <= 0 && contact.point.y <= transform.position.y - ((circleCollider.radius * transform.localScale.y + transform.localScale.y) / 2) && Vector2.Angle(Vector2.up, contact.normal) <= slopeLimit){
                onGround = true;
                justBounced = false;
                vm = Mathf.Max(0, vm);
                contactAgainst = true;
        }
//          if(vm <= 0 && contact.point.y <= transform.position.y - ((boxCollider.size.y * transform.localScale.y) / 2) && Vector2.Angle(Vector2.up, contact.normal) <= slopeLimit){
//                  onGround = true;
//                  vm = Mathf.Max(0, vm);
//          }
}
}

function checkPositionCollision() {
    var yCircle = transform.localPosition.y + (circleCollider.center.y * transform.localScale.y);
    var circlePosition = Vector3(transform.localPosition.x , yCircle, transform.localPosition.z);
    var hitRight = Physics2D.Raycast(circlePosition, transform.right, circleCollider.radius * transform.localScale.y + transform.localScale.y,  1 << LayerMask.NameToLayer("Walls"));
    var hitLeft = Physics2D.Raycast(circlePosition, -transform.right, circleCollider.radius * transform.localScale.y + transform.localScale.y,  1 << LayerMask.NameToLayer("Walls"));
    if(hitRight) {
        touchRight = true;
        justBounced = false;
    }
    if(hitLeft) {
        touchLeft = true;
        justBounced = false;
    }
}

```

Thanks for your help :)

# Answer
> 0 votes
Well, i answered the question by myself, recreating completly the class, here is my code :

using UnityEngine; using System.Collections;

public class PlayerController : MonoBehaviour {

```
public bool onGround = false;
public bool jump = false;
public float maxSpeedX = 3f;
public float maxSpeedY = 3f;
public LayerMask whatIsGround;
public Transform groundChecker;

private float groundRadius = 0.1f;
private bool facingRight = true;
public bool touchLeft = false;
public bool touchRight = false;
private CircleCollider2D circleCollider;

public float velocityX;
public float velocityY;

void Start () {
    circleCollider = GetComponent<CircleCollider2D>();
}

void FixedUpdate () {
    float forceX = 0;
    float forceY = 0;
    velocityX = rigidbody2D.velocity.x;
    velocityY = rigidbody2D.velocity.y;
    //Je test si mon personnage est collé à un mur
    checkWallPosition();

    onGround = Physics2D.OverlapCircle (groundChecker.position, groundRadius, whatIsGround);
    float moveH = Input.GetAxisRaw ("Horizontal");
    jump = Input.GetButtonDown("Jump");

    //Si je touche le sol
    if (onGround) {
        if(moveH != 0) {
            forceX = maxSpeedX * moveH;
        }
        if(jump && !touchLeft && !touchRight) {
            forceY = maxSpeedY;
        }
        else if(jump && (touchLeft || touchRight)) {
            if(touchLeft) {
                forceX = maxSpeedX;
            }
            else {
                forceX = -maxSpeedX;
            }
            forceY = maxSpeedY;
            Flip ();
        }
        else {
            forceY = rigidbody2D.velocity.y;
        }
    }

    //Si je ne touche pas le sol
    else {
        if(!jump && !touchLeft && !touchRight) {
            forceY = rigidbody2D.velocity.y;
            forceX = rigidbody2D.velocity.x;
        }
        else if(jump && (touchLeft || touchRight)) {
            if(touchLeft) {
                forceX = maxSpeedX;
                if(!facingRight)
                    Flip ();
            }
            else {
                forceX = -maxSpeedX;
                if(facingRight)
                    Flip ();
            }
            forceY = maxSpeedY;
        }
        else if(touchLeft || touchRight) {
            if(moveH == 0) {
                forceX = 0;
                forceY = rigidbody2D.velocity.y;
            }
            else {
                if((touchLeft && moveH == -1) || (touchRight && moveH == 1)) {
                    if(moveH == -1 && facingRight) {
                        Flip ();
                    }
                    if(moveH == 1 && !facingRight) {
                        Flip ();
                    }
                    forceY = rigidbody2D.velocity.y / 3;
                }
            }
        }
    }

    //Ici les forces sont appliquées
    rigidbody2D.velocity = new Vector2 (forceX, forceY);

    //Ici le personnage est retourné en fonction de sa position
    if (onGround) {
        if (moveH > 0 && !facingRight) {
            Flip ();
        }
        else if (moveH < 0 && facingRight) {
            Flip ();
        }
    }

}

private void Flip(){
    facingRight = !facingRight;
    Vector3 theScale = transform.localScale;
    theScale.x *= -1;
    transform.localScale = theScale;
}

private void checkWallPosition() {
    touchLeft = touchRight = false;
    float yCircle = transform.localPosition.y + (circleCollider.center.y * transform.localScale.y);
    Vector3 circlePosition = new Vector3(transform.localPosition.x , yCircle, transform.localPosition.z);
    bool hitRight = Physics2D.Raycast(circlePosition, transform.right, circleCollider.radius * transform.localScale.y + transform.localScale.y,  1 << LayerMask.NameToLayer("Walls"));
    bool hitLeft = Physics2D.Raycast(circlePosition, -transform.right, circleCollider.radius * transform.localScale.y + transform.localScale.y,  1 << LayerMask.NameToLayer("Walls"));
    if(hitRight) {
        touchRight = true;
    }
    if(hitLeft) {
        touchLeft = true;
    }
}
}

```

# Answer
> 1 votes
So this is just a guess but I think your problem stems from **applying Force in your update method**.

Try if you can, to move any code that adds force in the **fixed update** method.

Also you might want to try to calculate just one vector to apply force too rather than mixing two addforce together unity may not be mixing them like you would expect them to be.

---
Tags: unity
---


# Question
Title: how to make different sprite when moving and aiming
I want to create top down game where you are Russian soldier in libGDX. The player controls the soldier with `W/A/S/D` and aims with the mouse. That way the soldier can run sideways and shoot towards enemy.

What is best way to make his legs walk into the right direction but aim the weapon towards the mouse pointer?

My idea is to make two sprites, for both torso/weapon and legs and let them lay over each other but I don't know if that is best way to do it.

# Answer
Your solution is probably the easiest way to do it and I see no reason of why it wouldn't be valid. If you use only one sprite for a character this will mean that you will have to do a sprite per walking-direction/firing-direction combination pair.

In the case of a character viewed from the side you can use deformation to deform the sprite in the correct pose (They do this in Rayman origin), but this is very difficult to look right for little visual gain, and little time gain over painting each half-sprite in your case.
> 1 votes

---
Tags: libgdx
---