# Question
Title: How can I convert a model's rigging from standard bones to a biped in 3DS Max?
I've purchased a rigged 3D model from Turbosquid. Unfortunately the model has been rigged using standard bones instead of a biped.

Is the a way I can automatically converting the skinning from bones to biped?

# Answer
> 2 votes
Apparently there's a company called Mixamo that sells and constructs anthropomorphic models as a service. And their web interface handles rigging. And it's fairly expensive, with a very brief free trial.

But assuming you get it right on one of those first two tries, you should be able to import one of their "auto-rigged" models back into 3dsmax, and run a free max script that will convert it to biped rigging.

I assume this script relies on their automatic rigging conventions in order to function, but it starts with a list of bodypart ids as constants. So perhaps you could tweak those values, or otherwise prep your own model, and run the script in isolation. In any case, perhaps it would give you some insight in how to go about converting the model manually. Good luck.

---
Tags: 3dsmax
---


# Question
Title: How can I measure the velocity of a drag gesture?
I want to measure the velocity of a drag(FreeDrag, VerticalDrag, HorizontalDrag) gesture on my Windows Phone. For example, if the measured velocity of a drag is 40 km/h, the player will shoot a bullet in the dragging direction that flies with 40 km/h.

How can I measure the velocity of a drag gesture on my Windows Phone?

**Update:** I don't know how to measure the time. Is it possible to do it without touchCollection or should I use touchCollection to determine the StartTime and the EndTime?

I'm not sure if I need the touchCollection block. In addition, I'm not sure if I can use two different types, TimeSpan for StartTime and DateTime for EndTime.

What is the best way to measure the time?

```
TimeSpan StartTime;
DateTime EndTime;
TouchPanel.EnabledGestures = GestureType.FreeDrag;
protected override void Update(GameTime gameTime)
{
 TouchCollection touchCollection = TouchPanel.GetState();
 foreach (TouchLocation tl in touchCollection)
 {
   GestureSample gs = TouchPanel.ReadGesture();
    if ((tl.State == TouchLocationState.Pressed))
    {
     StartTime = gs.Timestamp;
     }
    if ((tl.State == TouchLocationState.Released))
    {
     EndTime = DateTime.Now;
     }
  }

    while (TouchPanel.IsGestureAvailable)
    {
    GestureSample gs = TouchPanel.ReadGesture();
       switch (gs.GestureType)
        {
          case GestureType.FreeDrag:
               StartTime = gs.Timestamp;
           break;
         }
     }
        base.Update(gameTime);
 }

```

# Answer
> 3 votes
Using the information from your previous question, you know what the delta of the drag was. This gives you distance. The only other thing you need to get velocity is a time. So, record the time when the touch even started, and when it finished. The difference in those times is the time it took for the gesture to complete.

Now you have distance and time. So the velocity is equal to `distance/time`.

Even though this will work in theory, I think you'll need to test for how well it works in practice. I think you'll find that a 1:1 ratio for swipe speed to bullet speed will be a little hard to control, especially if the user also needs to define a direction to shoot.

# Answer
> 2 votes
The quickest/simplest approach is to get the position and time of the touch and then get the position and time of the release. Then dividing the position difference (which is a vector) by the time difference you have an approximation to the velocity.

However, there are more complicated ways to do this which can be desirable in some cases. For example, if you want to make your velocity measurement resistant to jittering/variations in the final position of the pointer, then you can sample the positions of the pointer between the touch and release at regular intervals and then do a linear fit to the pointer position (each component) vs. time. This helps correct for the natural tendency for the hand to create an arch when moving the pointer as well as jittering.

---
Tags: xna, c#, windows-phone-7, windows-phone-8
---


# Question
Title: How to fill/initialize D3D11_SAMPLER_DESC properly?
If I want to set explicitly every parameter of the structure I just do so and that's it. But what if I want to set only some of them and leave the rest with default values? I've seen in some tutorial zeroing the structure:

```
ZeroMemory(&samplerDesc, sizeof(D3D11_SAMPLER_DESC));

```

but the default values (http://msdn.microsoft.com/en-us/library/windows/desktop/ff476207%28v=vs.85%29.aspx) aren't always 0. Is this incorrect? Should I always specify all values explicitly (especially LOD values seem tricky)?

I'm asking about `D3D11_SAMPLER_DESC` but maybe the same rules apply to other DX structures?

# Answer
> 3 votes
> but the default values aren't always 0. Is this incorrect?

If it was just the default values being different from 0, then zeroing the desc struct wouldn't necessarily be incorrect, it just wouldn't give you a default sampler state.

However for some of the members (such as `D3D11_TEXTURE_ADDRESS_MODE AddressU, AddressV, AddressW`) `0` is not even a valid value and creating the sampler state will fail, so yes it's incorrect here.

To avoid having to specify the defaults every time, you could write a wrapper, an init or "factory" function, or store a const instance with the default values set somewhere.
D3D already comes with some Helper Structures which wrap many of the DESC structs and can intialize them with the proper default values for you (as long as you don't define `D3D11_NO_HELPERS`).

# Answer
> 1 votes
Zeroing the structure is incorrect. Some of the enum types do not have zero as a valid value, but that's likely to be fairly harmless as the D3D runtime will probably just substitute default values for zeroes (possibly with a warning emitted to the debug layer; I haven't checked). However, where zeroing will really foul you up is with the `MaxLOD` member, where setting it to zero effectively disables mipmaps on that texture. That's definitely something you'd need to watch out for.

Personally, I would just always explicitly initialize all members of the sampler struct.

---
Tags: directx, initialization, sampler-state, struct
---


# Question
Title: Directx 11: emulating palette swapping with shader 5.0 and c++
i'm trying to swapping the colors using a texture as index and a second one as palette.

Here is the full listing of the code:

```
#include <windows.h>
#include <windowsx.h>
#include <vector>
#include <dxgi.h>
#include <d3dcommon.h>
#include <d3d11.h>
#include <d3dx11.h>
#include <d3dcompiler.h>
#include <xnamath.h>

#pragma comment(lib, "dxgi.lib")
#pragma comment(lib, "d3d11.lib")
#pragma comment(lib, "d3dx11.lib")
#pragma comment(lib, "d3dx10.lib")
#pragma comment(lib, "D3dcompiler.lib")

// define the screen resolution
#define     SCREEN_WIDTH    300
#define     SCREEN_HEIGHT   180
const float SCREEN_DEPTH    = 1000.0f;
const float SCREEN_NEAR     = 0.1f;

struct SIMPLEVERTEX
{
    XMFLOAT3 Pos;
    XMFLOAT2 Tex;
    XMFLOAT4 Color;
};

struct CONSTANTBUFFER
{
    XMMATRIX Scaling;
    XMMATRIX World;
    XMMATRIX View;
    XMMATRIX Projection;
};

// the WindowProc function prototype
LRESULT CALLBACK    WindowProc( HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam );
// Gestione delle DirectX 11
bool                InitializeDirectX11( HWND p_Hwnd );
void                CleanupDirectX11();
void                BeginScene(float red, float green, float blue, float alpha);
void                EndScene();
void                Render();

// the entry point for any Windows program
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow )
{
    WNDCLASSEX          wc = {};

    wc.cbSize           = sizeof( WNDCLASSEX );
    wc.style            = CS_HREDRAW | CS_VREDRAW;
    wc.lpfnWndProc      = WindowProc;
    wc.hInstance        = hInstance;
    wc.hCursor          = LoadCursor( NULL, IDC_ARROW );
    //wc.hbrBackground  = (HBRUSH)( COLOR_WINDOW + 1 );
    wc.lpszClassName    = L"WindowClass";

    RegisterClassEx( &wc );

    unsigned int        width, height;

    width               = GetSystemMetrics(SM_CXSCREEN);
    height              = GetSystemMetrics(SM_CYSCREEN);

    RECT                rect;

    rect.left           = 0;
    rect.top            = 0;
    rect.right          = SCREEN_WIDTH;
    rect.bottom         = SCREEN_HEIGHT;
    AdjustWindowRect( &rect, WS_OVERLAPPEDWINDOW, FALSE );
    rect.right          -= rect.left;
    rect.bottom         -= rect.top;
    rect.left           = (width - rect.right) / 2;
    rect.top            = (height - rect.bottom) / 2;

    // Creazione della window.
    HWND    hWnd;

    hWnd                = CreateWindowEx( NULL, L"WindowClass", L"Palette swapping", WS_OVERLAPPEDWINDOW, rect.left, rect.top, rect.right, rect.bottom, NULL, NULL, hInstance, NULL );

    // Inizializza DirectX 11.
    InitializeDirectX11(hWnd);

    ShowWindow( hWnd, nCmdShow );

    // enter the main loop:

    MSG     msg;

    while( TRUE )
    {
        while( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) )
        {
            TranslateMessage( &msg );
            DispatchMessage( &msg );
        }

        if( msg.message == WM_QUIT )
            break;
        else
        {
            // Render
            Render();
        }
    }

    CleanupDirectX11();

    return msg.wParam;
}

// this is the main message handler for the program
LRESULT CALLBACK WindowProc( HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam )
{
    switch( message )
    {
    case WM_KEYUP:
        {
            if( wParam == VK_ESCAPE )
            {
                DestroyWindow( hWnd );
                return 0;
            }
        }
        break;

    case WM_DESTROY:
        {
            PostQuitMessage( 0 );
            return 0;
        }
        break;

    case WM_PAINT:
        {
            PAINTSTRUCT     ps;
            BeginPaint( hWnd, &ps );
            EndPaint( hWnd, &ps );
        }
        return 0;
    }

    return DefWindowProc ( hWnd, message, wParam, lParam );
}

IDXGIFactory                * g_Factory             = NULL;
IDXGIAdapter                * g_Adapter             = NULL;
ID3D11Device                * g_Device              = NULL;
ID3D11DeviceContext         * g_Context             = NULL;
IDXGISwapChain              * g_Swapchain           = NULL;
ID3D11RenderTargetView      * g_Targetview          = NULL;
ID3D11VertexShader          * g_VertexShader        = NULL;
ID3D11InputLayout           * g_VertexLayout        = NULL;
ID3D11PixelShader           * g_PixelShader         = NULL;
ID3D11ShaderResourceView    * g_TextureRV           = NULL;
ID3D11ShaderResourceView    * g_PaletteRV           = NULL;
ID3D11SamplerState          * g_Sampler             = NULL;
ID3D11BlendState            * g_BlendState          = NULL;
ID3D11Buffer                * g_VertexBuffer        = NULL;
ID3D11Buffer                * g_ConstantBuffer      = NULL;
XMMATRIX                    g_World;
XMMATRIX                    g_View;
XMMATRIX                    g_Projection;
XMMATRIX                    g_Scaling;
XMMATRIX                    g_2nd;

ID3D11Texture2D             * g_pDepthStencil       = NULL;
ID3D11DepthStencilView      * g_pDepthStencilView   = NULL;

bool InitializeDirectX11( HWND p_Hwnd )
{

    // Create DXGI factory.
    if( FAILED( CreateDXGIFactory( __uuidof( IDXGIFactory ), (void**)&g_Factory ) ) )
        return false;

    // Main adapter.
    g_Factory->EnumAdapters( 0, &g_Adapter );

    D3D_FEATURE_LEVEL       Featurerequested        = D3D_FEATURE_LEVEL_11_0;
    UINT                    Featurelevel            = 1;
    D3D_FEATURE_LEVEL       Featuresupported;

    // Watch out, you must pass D3D_DRIVER_TYPE_UNKNOWN to avoid E_INVALIDARG result.
    if( FAILED( D3D11CreateDevice( g_Adapter, D3D_DRIVER_TYPE_UNKNOWN, NULL, D3D11_CREATE_DEVICE_DEBUG, &Featurerequested, Featurelevel, D3D11_SDK_VERSION, &g_Device, &Featuresupported, &g_Context ) ) )
        return false;

    DXGI_SWAP_CHAIN_DESC    Chaindesc;

    Chaindesc.BufferCount                           = 1;
    Chaindesc.BufferDesc.Width                      = SCREEN_WIDTH;
    Chaindesc.BufferDesc.Height                     = SCREEN_HEIGHT;
    Chaindesc.BufferDesc.Format                     = DXGI_FORMAT_R8G8B8A8_UNORM;
    Chaindesc.BufferDesc.RefreshRate.Numerator      = 0;
    Chaindesc.BufferDesc.RefreshRate.Denominator    = 1;
    Chaindesc.BufferDesc.Scaling                    = DXGI_MODE_SCALING_UNSPECIFIED;
    Chaindesc.BufferDesc.ScanlineOrdering           = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
    Chaindesc.BufferUsage                           = DXGI_USAGE_RENDER_TARGET_OUTPUT;
    Chaindesc.OutputWindow                          = p_Hwnd;
    Chaindesc.SampleDesc.Count                      = 1;
    Chaindesc.SampleDesc.Quality                    = 0;
    Chaindesc.Windowed                              = true;
    Chaindesc.SwapEffect                            = DXGI_SWAP_EFFECT_DISCARD;
    Chaindesc.Flags                                 = 0;

    if( FAILED( g_Factory->CreateSwapChain( g_Device, &Chaindesc, &g_Swapchain ) ) )
        return false;

    // Get the pointer to the back buffer.
    ID3D11Texture2D *       Backbuffer;

    if( FAILED( g_Swapchain->GetBuffer( 0, __uuidof(ID3D11Texture2D), (LPVOID*)&Backbuffer ) ) )
        return false;

    // Create the render target view with the back buffer pointer.
    if( FAILED( g_Device->CreateRenderTargetView( Backbuffer, NULL, &g_Targetview ) ) )
        return false;

    // Release pointer to the back buffer as we no longer need it.
    Backbuffer->Release();

    // Create depth stencil texture
    D3D11_TEXTURE2D_DESC descDepth;
    ZeroMemory( &descDepth, sizeof(descDepth) );
    descDepth.Width                         = SCREEN_WIDTH;
    descDepth.Height                        = SCREEN_HEIGHT;
    descDepth.MipLevels                     = 1;
    descDepth.ArraySize                     = 1;
    descDepth.Format                        = DXGI_FORMAT_D24_UNORM_S8_UINT;
    descDepth.SampleDesc.Count              = 1;
    descDepth.SampleDesc.Quality            = 0;
    descDepth.Usage                         = D3D11_USAGE_DEFAULT;
    descDepth.BindFlags                     = D3D11_BIND_DEPTH_STENCIL;
    descDepth.CPUAccessFlags                = 0;
    descDepth.MiscFlags                     = 0;
    HRESULT hr = g_Device->CreateTexture2D( &descDepth, NULL, &g_pDepthStencil );
    if( FAILED( hr ) )
        return false;

    D3D11_DEPTH_STENCIL_DESC dsDesc;

    // Depth test parameters
    dsDesc.DepthEnable                      = true;
    dsDesc.DepthWriteMask                   = D3D11_DEPTH_WRITE_MASK_ALL;
    dsDesc.DepthFunc                        = D3D11_COMPARISON_LESS_EQUAL;

    // Stencil test parameters
    dsDesc.StencilEnable                    = true;
    dsDesc.StencilReadMask                  = 0xFF;
    dsDesc.StencilWriteMask                 = 0xFF;

    // Stencil operations if pixel is front-facing
    dsDesc.FrontFace.StencilFailOp          = D3D11_STENCIL_OP_KEEP;
    dsDesc.FrontFace.StencilDepthFailOp     = D3D11_STENCIL_OP_INCR;
    dsDesc.FrontFace.StencilPassOp          = D3D11_STENCIL_OP_KEEP;
    dsDesc.FrontFace.StencilFunc            = D3D11_COMPARISON_ALWAYS;

    // Stencil operations if pixel is back-facing
    dsDesc.BackFace.StencilFailOp           = D3D11_STENCIL_OP_KEEP;
    dsDesc.BackFace.StencilDepthFailOp      = D3D11_STENCIL_OP_DECR;
    dsDesc.BackFace.StencilPassOp           = D3D11_STENCIL_OP_KEEP;
    dsDesc.BackFace.StencilFunc             = D3D11_COMPARISON_ALWAYS;

    // Create depth stencil state
    ID3D11DepthStencilState * pDSState;
    g_Device->CreateDepthStencilState(&dsDesc, &pDSState);

    // Bind depth stencil state
    g_Context->OMSetDepthStencilState(pDSState, 1);

    // Create the depth stencil view
    D3D11_DEPTH_STENCIL_VIEW_DESC descDSV;
    ZeroMemory( &descDSV, sizeof(descDSV) );
    descDSV.Format                          = descDepth.Format;
    descDSV.ViewDimension                   = D3D11_DSV_DIMENSION_TEXTURE2D;
    descDSV.Texture2D.MipSlice              = 0;
    hr = g_Device->CreateDepthStencilView( g_pDepthStencil, &descDSV, &g_pDepthStencilView );
    if( FAILED( hr ) )
        return false;

    g_Context->OMSetRenderTargets( 1, &g_Targetview, g_pDepthStencilView );

    // Setup the Viewport for rendering.
    D3D11_VIEWPORT      Viewport;

    Viewport.Width      = (float)SCREEN_WIDTH;
    Viewport.Height     = (float)SCREEN_HEIGHT;
    Viewport.MinDepth   = 0.0f;
    Viewport.MaxDepth   = 1.0f;
    Viewport.TopLeftX   = 0.0f;
    Viewport.TopLeftY   = 0.0f;

    // Create the Viewport.
    g_Context->RSSetViewports( 1, &Viewport );

    // Compile the vertex shader
    ID3DBlob            * Errorblob = NULL;
    ID3DBlob            * VSBlob = NULL;
    if( FAILED( D3DX11CompileFromFile( L"Palette.fx", NULL, NULL, "VS", "vs_5_0", D3DCOMPILE_ENABLE_STRICTNESS, 0, NULL, &VSBlob, &Errorblob, NULL ) ) )
        return false;

    // Create the vertex shader
    if( FAILED( g_Device->CreateVertexShader( VSBlob->GetBufferPointer(), VSBlob->GetBufferSize(), NULL, &g_VertexShader ) ) )
    {
        VSBlob->Release();
        return false;
    }

    // Define the input Layout
    D3D11_INPUT_ELEMENT_DESC Layout[] =
    {
        { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
        { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 },
        { "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }
    };

    UINT                Elements = ARRAYSIZE( Layout );

    // Create the input Layout
    g_Device->CreateInputLayout( Layout, Elements, VSBlob->GetBufferPointer(), VSBlob->GetBufferSize(), &g_VertexLayout );
    VSBlob->Release();
    if( !g_VertexLayout )
        return false;

    // Set the input layout
    g_Context->IASetInputLayout( g_VertexLayout );

    // Compile the pixel shader
    ID3DBlob            * PSBlob = NULL;
    if( FAILED( D3DX11CompileFromFile( L"Palette.fx", NULL, NULL, "PS", "ps_5_0", D3DCOMPILE_ENABLE_STRICTNESS, 0, NULL, &PSBlob, &Errorblob, NULL ) ) )
    {
        LPSTR text = (char *)Errorblob->GetBufferPointer();
        return false;
    }

    // Create the pixel shader
    g_Device->CreatePixelShader( PSBlob->GetBufferPointer(), PSBlob->GetBufferSize(), NULL, &g_PixelShader );
    PSBlob->Release();
    if( !g_PixelShader )
        return false;

    // Create vertex buffer
    SIMPLEVERTEX Vertices[] =
    {
        { XMFLOAT3( -0.5f, -0.5f, 0.0f ), XMFLOAT2( 0.0f, 1.0f ), XMFLOAT4( 1.0f, 1.0f, 1.0f, 1.0f ) },
        { XMFLOAT3( -0.5f, 0.5f, 0.0f ), XMFLOAT2( 0.0f, 0.0f ), XMFLOAT4( 1.0f, 1.0f, 1.0f, 1.0f ) },
        { XMFLOAT3( 0.5f, -0.5f, 0.0f ), XMFLOAT2( 1.0f, 1.0f ), XMFLOAT4( 1.0f, 1.0f, 1.0f, 1.0f ) },
        { XMFLOAT3( 0.5f, 0.5f, 0.0f ), XMFLOAT2( 1.0f, 0.0f ), XMFLOAT4( 1.0f, 1.0f, 1.0f, 1.0f ) }
    };

    D3D11_BUFFER_DESC           Buffer = {};

    Buffer.Usage                = D3D11_USAGE_DEFAULT;
    Buffer.ByteWidth            = sizeof( SIMPLEVERTEX ) * ARRAYSIZE( Vertices );
    Buffer.BindFlags            = D3D11_BIND_VERTEX_BUFFER;
    Buffer.CPUAccessFlags       = 0;

    D3D11_SUBRESOURCE_DATA      Initdata = {};

    Initdata.pSysMem            = Vertices;
    if( FAILED( g_Device->CreateBuffer( &Buffer, &Initdata, &g_VertexBuffer ) ) )
        return false;

    // Set vertex buffer
    UINT                        Stride = sizeof( SIMPLEVERTEX );
    UINT                        Offset = 0;
    g_Context->IASetVertexBuffers( 0, 1, &g_VertexBuffer, &Stride, &Offset );

    // Set primitive topology
    g_Context->IASetPrimitiveTopology( D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP);

    // Create the constant buffer
    Buffer.Usage                = D3D11_USAGE_DEFAULT;
    Buffer.ByteWidth            = sizeof(CONSTANTBUFFER);
    Buffer.BindFlags            = D3D11_BIND_CONSTANT_BUFFER;
    Buffer.CPUAccessFlags       = 0;
    if( FAILED( g_Device->CreateBuffer( &Buffer, NULL, &g_ConstantBuffer ) ) )
        return false;

    // Create index texture.
    if( FAILED( D3DX11CreateShaderResourceViewFromFile( g_Device, L"Vortex.png", NULL, NULL, &g_TextureRV, NULL ) ) )
        return false;

    // Create palette texture.
    if( FAILED( D3DX11CreateShaderResourceViewFromFile( g_Device, L"Palette8x1.png", NULL, NULL, &g_PaletteRV, NULL ) ) )
        return false;

    // Create the sample state
    D3D11_SAMPLER_DESC          Sampler;

    ZeroMemory( &Sampler, sizeof(Sampler) );
    Sampler.Filter              = D3D11_FILTER_MIN_MAG_MIP_POINT;
    Sampler.AddressU            = D3D11_TEXTURE_ADDRESS_BORDER;
    Sampler.AddressV            = D3D11_TEXTURE_ADDRESS_BORDER;
    Sampler.AddressW            = D3D11_TEXTURE_ADDRESS_BORDER;
    Sampler.ComparisonFunc      = D3D11_COMPARISON_ALWAYS;
    Sampler.MinLOD              = 0;
    Sampler.MaxLOD              = D3D11_FLOAT32_MAX;

    if( FAILED( g_Device->CreateSamplerState( &Sampler, &g_Sampler ) ) )
        return false;

    // Create the blend state
    D3D11_BLEND_DESC            BlendState;

    ZeroMemory( &BlendState, sizeof(D3D11_BLEND_DESC) );
    BlendState.RenderTarget[0].BlendEnable              = true;
    BlendState.RenderTarget[0].SrcBlend                 = D3D11_BLEND_SRC_ALPHA;
    BlendState.RenderTarget[0].DestBlend                = D3D11_BLEND_INV_SRC_ALPHA;
    BlendState.RenderTarget[0].BlendOp                  = D3D11_BLEND_OP_ADD;
    BlendState.RenderTarget[0].SrcBlendAlpha            = D3D11_BLEND_SRC_ALPHA;
    BlendState.RenderTarget[0].DestBlendAlpha           = D3D11_BLEND_INV_SRC_ALPHA;
    BlendState.RenderTarget[0].BlendOpAlpha             = D3D11_BLEND_OP_ADD;
    BlendState.RenderTarget[0].RenderTargetWriteMask    = 0x0f;

    g_Device->CreateBlendState( &BlendState, &g_BlendState );

    float blendFactor[4]        = { 0.0f, 0.0f, 0.0f, 0.0f };
    UINT sampleMask             = 0xffffffff;

    g_Context->OMSetBlendState( g_BlendState, blendFactor, sampleMask );

    // Initialize the world matrix
    g_World                     = XMMatrixIdentity();
    g_World                     = XMMatrixTranslation( 0, 0, 22 );
    g_2nd                       = XMMatrixIdentity();
    g_2nd                       = XMMatrixTranslation( 42, -36, 20 );

    // Initialize the view matrix
    XMVECTOR        Eye         = XMVectorSet( 0.0f, 1.0f, -1.0f, 0.0f );
    XMVECTOR        At          = XMVectorSet( 0.0f, 1.0f, 0.0f, 0.0f );
    XMVECTOR        Up          = XMVectorSet( 0.0f, 1.0f, 0.0f, 0.0f );
    g_View                      = XMMatrixLookAtLH( Eye, At, Up );

    // Initialize the projection matrix
    g_Projection                = XMMatrixOrthographicLH((FLOAT) SCREEN_WIDTH, (FLOAT) SCREEN_HEIGHT, 0.0f, 10000.0f);

    // Scaling.
    g_Scaling                   = XMMatrixIdentity();
    g_Scaling._11 = 64.0;
    g_Scaling._22 = 64.0;

    return true;
}

void CleanupDirectX11()
{
    // Rilascio.
    if( g_ConstantBuffer ) g_ConstantBuffer->Release();

    if( g_VertexBuffer ) g_VertexBuffer->Release();

    if( g_PixelShader ) g_PixelShader->Release();

    if( g_VertexLayout ) g_VertexLayout->Release();

    if( g_VertexShader ) g_VertexShader->Release();

    if( g_Targetview ) g_Targetview->Release();

    if( g_Swapchain ) g_Swapchain->Release();

    if( g_Device) g_Device->Release();

    if( g_Adapter) g_Adapter->Release();

    if( g_Factory ) g_Factory->Release();
}

void BeginScene(float red, float green, float blue, float alpha)
{
    float color[4];

    // Setup the color to clear the buffer to.
    color[0] = red;
    color[1] = green;
    color[2] = blue;
    color[3] = alpha;

    // Clear the back buffer.
    g_Context->ClearRenderTargetView( g_Targetview, color );

    return;
}

void EndScene()
{
    g_Swapchain->Present( 0, 0 );

    return;
}

void Render()
{

    // Clear the back buffer
    float Clearcolor[4] = { 0.0f, 0.5f, 1.0f, 1.0f }; // red,green,blue,alpha
    g_Context->ClearRenderTargetView( g_Targetview, Clearcolor );

    // Clear the depth buffer to 1.0 (max depth)
    g_Context->ClearDepthStencilView( g_pDepthStencilView, D3D11_CLEAR_DEPTH, 1.0f, 0 );

    // Update variables
    CONSTANTBUFFER                  Buffer;

    Buffer.World                    = XMMatrixTranspose( g_World );
    Buffer.View                     = XMMatrixTranspose( g_View );
    Buffer.Projection               = XMMatrixTranspose( g_Projection );
    Buffer.Scaling                  = XMMatrixTranspose( g_Scaling );
    g_Context->UpdateSubresource( g_ConstantBuffer, 0, NULL, &Buffer, 0, 0 );

    // Render
    g_Context->VSSetShader( g_VertexShader, NULL, 0 );
    g_Context->VSSetConstantBuffers( 0, 1, &g_ConstantBuffer );
    g_Context->PSSetShaderResources( 0, 1, &g_TextureRV );
    g_Context->PSSetShaderResources( 1, 1, &g_PaletteRV);
    g_Context->PSSetSamplers( 0, 1, &g_Sampler );
    g_Context->PSSetShader( g_PixelShader, NULL, 0 );
    g_Context->Draw( 4, 0 );

    // Present our back buffer to our front buffer
    g_Swapchain->Present( 0, 0 );
}

```

and the shaders:

```
//--------------------------------------------------------------------------------------
// File: Tutorial04.fx
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//--------------------------------------------------------------------------------------

Texture2D txTexture : register( t0 );
Texture2D txPalette : register( t1 );
SamplerState sampling : register( s0 );

//--------------------------------------------------------------------------------------
// Constant Buffer Variables
//--------------------------------------------------------------------------------------
cbuffer ConstantBuffer : register( b0 )
{
    matrix Scaling;
    matrix World;
    matrix View;
    matrix Projection;
}

//--------------------------------------------------------------------------------------
struct VS_INPUT
{
    float4 Pos : POSITION;
    float2 Tex : TEXCOORD0;
    float4 Color : COLOR0;
};

struct PS_INPUT
{
    float4 Pos : SV_POSITION;
    float2 Tex : TEXCOORD0;
    float4 Color : COLOR0;
};

//--------------------------------------------------------------------------------------
// Vertex Shader
//--------------------------------------------------------------------------------------
PS_INPUT VS( VS_INPUT input )
{
    PS_INPUT output = (PS_INPUT)0;
    output.Pos = mul( input.Pos, Scaling);
    output.Pos = mul( output.Pos, World );
    output.Pos = mul( output.Pos, View );
    output.Pos = mul( output.Pos, Projection );
    output.Tex = input.Tex;
    output.Color = input.Color;

    return output;
}

//--------------------------------------------------------------------------------------
// Pixel Shader
//--------------------------------------------------------------------------------------
float4 PS( PS_INPUT input ) : SV_Target
{
    float4 Index = txTexture.Sample( sampling, input.Tex );
    float w, h;
    txPalette.GetDimensions( w, h );
    return txPalette.Sample( sampling, float2( ( Index.r * 255.0 ) / w, 0 ) );
}

```

The final rendering has some garbage on the texture, but i don't know WHAT cause it. Sampling, blending? What i'm missing?

The correct one is on the right.

The first texture use the red channel as index for the right texel on the second texture.

@Andon Coleman

This image show the texture ( the rightmost one) with +0.5 added to get the center of the texel.

# Answer
> 1 votes
Ok, i have modified the shader with the Load instruction suggested by @melak47, and now is working.

```
Texture2D<float4> txPalette : register( t1 );

//--------------------------------------------------------------------------------------
// Pixel Shader
//--------------------------------------------------------------------------------------
float4 PS( PS_INPUT input ) : SV_Target
{
    float4 Index = txTexture.Sample( sampling, input.Tex );
    return txPalette.Load( int3( Index.r * 255.0 + 0.5, 0, 0 ) );
}

```

To get the correct color, i had to add the 0.5 offset. Thank you for the help.

---
Tags: c++, shaders, directx11, palette
---


title: Controls: Rolling on a ceiling

text:
# Question
Title: Controls: Rolling on a ceiling
Currently I'm writing an iOS game where the basic movement is rolling. Technically you make the player turn clockwise or counterclockwise. When you tilt the device to the right, you will rotate clockwise. This makes sense, because you are standing on a floor, so this will make you roll right. Same idea goes for left, of course.

But sometimes, the player can roll in some sort of looping. The problem with that is, is that the player is in contact with something above (in other words, with a ceiling). This makes the logic turn: tilting the device to the right, makes your rotate clockwise, which will cause you rolling to the left instead.

Physically this is okay for me. But I've seen lots of people trying my game getting confused about it. As they go into the loop, they turn the device the other was as well, in order to follow the direction of the loop. But that makes them roll the other way and slow down, and eventually drop.

I don't want to do a stupid check like: if touching at the top side, then reverse the control, because to me that feels not natural. So, I guess there are lots of other people with the same feeling to this as I'm experiencing.

So, my question is: Are there any good techniques of handeling this issue? Make it feel natural most of the time for everyone?

# Answer
Your players can be categorised in one of two mental models.

Some of your players are like you -- they've associated tilting right/left with the ball spinning clockwise/anticlockwise.

Others have a different mental model: They associate tilting right/left with the ball moving right/left on the screen. It's these players who, when their ball is tracking the ceiling, expect that tilting left will send the ball toward the left on the screen.

As long as the ball is only following the ground, this mistaken mental model is okay -- the two mental models both produce the same, predictable results for any particular set of control inputs. But as soon as you throw a new context into the mix -- the ball following the ceiling -- half the players will become confused, as the game's behaviour suddenly doesn't match their mental model of what the game should be doing any more.

There are a couple things you can do to handle this situation.

The first thing to try when you find yourself in this sort of situation (half your users are confused because they have an incorrect mental model of how the game works) is always **teaching**. You want to have a tutorial very early in the game where you explain to the user that tilting left/right causes the ball to spin in that direction, and let them practice with it in a hazard-free scenario until they feel comfortable with it.

The second thing to try is to see if you can't make both mental models work, by **avoiding the situation** which causes them to come into conflict. In this case, *don't* have the ball be able to follow the ceiling, or perhaps spin the view around so that whatever surface the ball is following is at the bottom of the screen, so that tilting left *does* always move the ball to the left on the screen, even if that's technically the 'ceiling'. This has the benefit of not needing a 'tutorial' scenario; it just allows people's assumed controls to work for them in every situation, no matter which mental model they've picked, because we're presenting scenarios in such a way that both mental models produce the same expected behaviour for the same set of control inputs.

If you can't solve this sort of conflict in either of the two previous ways, then in some cases, you can offer a **game configuration setting** to swap control styles between the two mental models, so that each player can make the game controls work according to their own intuition of how the controls ought to work.

But you probably can't do that last option in this case -- the problematic "tilt left to go left" mental model doesn't work at all if the ball is traveling along a wall (which I assume is possible in your game, since you've mentioned floors and ceilings and loops). In your case, you're probably going to need to do one of the first two options; either teach people the correct mental model, or change your presentation style so that the incongruity between the two possible mental models doesn't present itself.
> 2 votes

# Answer
In addition to the solutions provided by Trevor, there is also the possibility to automatically reverse the controls on-the-fly. This is what *Super Mario Galaxy* does. When the player moves around small "planets", the gravity in screen space changes if the camera is fixed to show the whole planet. Effectively Mario will be upside down, but he keeps walking to the same direction he is facing while the buttons are pressed down. If the button is released and pressed again, the movement direction is recalculated. See the picture below for illustration.

When pressing and holding down *right*, character starts to move right and keeps moving around the planet until button is released. If the character is "below" the planet and *right* button is pressed, he starts to move right in screen space, which is the opposite direction compared to his previous movement.

The same mechanism is applied not just for spherical planets, but also in cases where there is only vertical gravity, but the direction suddenly changes between downwards and upwards. In this case when the gravity suddenly flips, the movement direction is readjusted on the fly even while the button is held down.

This approach works reasonably well for this game. Both new and experienced players can quite easily move the player around intuitively most of the time. However sometimes the player must readjust the direction when the character starts moving to unexpected direction.
> 1 votes

---
Tags: physics, mobile, control, user-experience
---


title: Dynamic Terrain Triangulation

text:
# Question
Title: Dynamic Terrain Triangulation
Is there someone who know/have an algorithm which can perform terrain triangulation like on the example image right under (there is a secondary image as well).

The reason I say "Dynamic" is because I want it to support Dynamic changes to the terrain, like if one was to dig into the ground or into the side of a mountain, then it should be capable of triangulating the new changes without destroying the old terrain which doesn't need changes.

*Ignore the things like the trees, etc. This is only about the style of the terrain itself.*

I've tried using the Marching Cubes Algorithm, though it didn't give me that triangle'ish feeling, like in the image(s) above (While ignoring the normal rendering in my example).

## Bottom Line

Does anybody know/have an algorithm, or any idea of how to...

* Triangulate terrain so it have that style like in the above example image(s).
* Support dynamic changes like Marching Cubes does, but with this triangle'ish style.

Note: All the "points" would be in an unsorted list, where the "points" of course is all the vertices, which should be used to generate all the triangles from.

---

> Disclaimer: I usually answer and sometimes ask question on Stack Overflow, so if anything is wrong with my question here I apologize, though comment and I will fix whatever is wrong.

# Answer
One (expensive) approach I've been playing with is Constructive Solid Geometry (CSG). csg.js, for example, is a nice clean short piece of code (if inefficient BSP approach) that can subtract and union meshes together. It'd be straightforward to port the approach literally to any other language. And there are more efficient CSG algorithms that can be googled once you know the terminology.

Using BSP splitting (as csg.js demonstrates) really fragments your meshes. You can tidy them up again using Hertel-Mehlhorn algorithm or you can tag the polygons before you BSP them so you can cheaply find all the split parts after and reassemble concave polygons in a tidy-up pass.

I've been playing with it to shoot holes in meshes for today's Ludum Dare competition: http://williamedwardscoder.tumblr.com/post/69968194211/last-week-i-discovered-csg-js-constructive-solid

And a fun video I just made: http://www.youtube.com/watch?v=7zjz-hpm8No
> 4 votes

# Answer
This is a super hard question, and you probably wont find your answer you want just like that. Most likely you will have to do some own research on how to achieve this.

there is also so many different ways doing this, and depending on your requirements you have to choose one that suits you.

The way i would do it would be that you take the direction that the player is digging in and with that you project that direction (or in any means find the triangels affected directly in a visinity ( basicly the size of the hole i guess. ) and from there then modify the vertexes so that you create an specialized gap towards that direction. this would also of course require to modify the amount of vertexs all the time so that you have to tessellate the digging.

You could also of course use voxelbased information and from there create vertexes that you could build your terrain with.
> 0 votes

# Answer
Take a look at the dual contouring algorithm. It can be used as a basis for the terrain stuff.

A useful idea is to combine it with polygon reduction methods, maybe even parameterized (so that steep hills have sharp corners but hills don't).
> 0 votes

# Answer
I didn't try anything, because it would take to long to set up a testing environment, but I would try to get rid of vertices that are too close to each other, combined with some randomness. Reconnect edges to adjacent vertices that were not removed. I really don't know what this is going to look like, but I think it can't be that bad.

When I see your attempt demo image, it looks like you are using some perlin noise. Great, but I think you should use some extra octaves to make the landscape a bit more nice.
> 0 votes

---
Tags: opengl, 3d, procedural-generation, terrain, triangulation
---


# Question
Title: Is the GraphicsDevice.Clear call in XNA necessary in 3D?
It's a touch embarrassing to ask I think, but I've just never paid it any attention before and used it as I've seen in tutorials or the like in the past I believe.

Is there a need to use GraphicsDevice.Clear? If you don't use a skybox or similar, how do you change the "void" color from purple to something else?

I'm not seeing a way to change the backcolor or w/e you'd call it in 3D. I also can comment out the GraphicsDevice.Clear call I've always seemed to use and nothing seems to change.

Thanks!

Edit: With the code below, I still get a purple background:

```
    //Part of Game1.cs
    protected override void Draw(GameTime gameTime) {
        frameRate++;
        Map.ResortChunkPriority(Player);
        //GraphicsDevice.Clear(ClearOptions.DepthBuffer | ClearOptions.Target, Color.White, 1f, 0);
        Map.Render(GraphicsDevice, clsResources.eTerrain, Player);
        base.Draw(gameTime);
    }

    //Map.Render call
    public void Render(GraphicsDevice device, Effect effect, clsEntity Player) {
        effect.CurrentTechnique = effect.Techniques["MainTech"];
        effect.Parameters["VP"].SetValue(clsCamera.viewMatrix * clsResources.projectionMatrix);

        device.Indices = clsResources.indexBuffer;

        for (int i = 0; i < RenderQueue.Count; i++) {
            //if (RenderQueue[i].fDist > 10) continue;
            RenderQueue[i].Render(device, effect, Player.ChunkPosition);
        }
    }

    //RenderQueue's Render call
    public void Render(GraphicsDevice device, Effect effect, strVector2 CurrentChunk) {
        if (iGenState != 4) return;
        effect.Parameters["xOffset"].SetValue(CubeOffset.X);// + ChunkPos.X);
        effect.Parameters["zOffset"].SetValue(CubeOffset.Z);// + ChunkPos.Z);

        for (int i = 0; i < effect.CurrentTechnique.Passes.Count; i++) {
            effect.CurrentTechnique.Passes[i].Apply();
            FaceStrips[0].Render(device, effect); FaceStrips[1].Render(device, effect);
            if (CurrentChunk.Z >= ChunkPos.Z) FaceStrips[2].Render(device, effect);
            if (CurrentChunk.Z <= ChunkPos.Z) FaceStrips[3].Render(device, effect);
            if (CurrentChunk.X <= ChunkPos.X) FaceStrips[4].Render(device, effect);
            if (CurrentChunk.X >= ChunkPos.X) FaceStrips[5].Render(device, effect);
        }
    }

    //FaceStrip's Render call
    public void Render(GraphicsDevice device, Effect effect) {
        if (iVertCounter == 0) return;

        for (int j = 0; j < geometryBuffer.Length; j++) {
            device.SetVertexBuffer(geometryBuffer[j]);
            device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, geometryBuffer[j].VertexCount, 0, geometryBuffer[j].VertexCount / 2);
        }
    }

```

# Answer
`GraphicsDevice.Clear(Color.White);` would give you a white background color as an example.

This function clears the backbuffer, z buffer, and stencil buffer. It is recommended that you call this before doing any rendering in a given frame. You'll likely run into some weird rendering issues by not clearing the buffer, but you might not see any direct changes depending on your rendering setup.

tl;dr just keep it.
> 3 votes

# Answer
If you do not call GraphicsDevice.Clear, whatever you drew last frame will draw again next frame and so on and so on. the screen will just be overdrawn with new stuff without the previous drawn stuff removed.
> 0 votes

---
Tags: xna, c#
---


# Question
Title: Make Gameobject Stand On Surface Facing Certain Direction
I want to make a biped character stand on any surface I click on.

Surfaces have up vectors of any of positive or negative X,Y,Z. So imagine a cube with each face being a gameobject whose up vector pointing directly away from the cube.

If my character is facing "forward" and I click on a surface which is to the left or right of me ( left or right walls), I want my character to now be standing on that surface but still be facing in the direction he initially was. If I click on a wall which is in the forward path of my character i want him to now be standing on that surface and his forward to now be what was once "up" relative to my character. Here is the code I am working with now.

```
void Update()
{
    if (Input.GetMouseButtonUp (0)) {
        RaycastHit hit;
        var ray = Camera.main.ScreenPointToRay(Input.mousePosition);

        if (Physics.Raycast(ray, out hit)) {
            Vector3 upVectBefore = transform.up;
            Vector3 forwardVectBefore = transform.forward;
            Quaternion rotationVectBefore = transform.rotation;

            Vector3 hitPosition = hit.transform.position;
            transform.position = hitPosition;
            float lookDifference = Vector3.Distance(hit.transform.up, forwardVectBefore);

            if(Vector3.Distance(hit.transform.up, upVectBefore) < .23) //Same normal
            {
                transform.rotation = rotationVectBefore;
            }
            else if(lookDifference > 1.412 && lookDifference <= 1.70607) //side wall
            {
                transform.up = hit.transform.up;
                transform.forward = forwardVectBefore;
            }
            else //head on wall
            {
                transform.up = hit.transform.up;
                transform.forward = upVectBefore;
            }
        }
    }
}

```

The first case "Same normal" works fine, however the other two do not work as I would like them to. Sometimes my character is laying down on the surface or on the wrong side of the surface. Does anyone know nice way of solving this problem?

# Answer
Without being too assertive here, it seems you are using a lot of "Magic Numbers"

I think a nice solution here could be to use the feature :

```
RaycastHit.normal

```

Which will give you the exact direction for the upvector of your object. And use the nice built-in :

```
Transform.LookAt(target, RaycastHit.normal);

```

it could give something like that :

```
void Update()
{
if (Input.GetMouseButtonUp (0)) {
    RaycastHit hit;
    var ray = Camera.main.ScreenPointToRay(Input.mousePosition);

    if (Physics.Raycast(ray, out hit)) {

        transform.position = hit.point;
        transform.LookAt(target, hit.normal);

    }
}
}

```

Knowing that target is the point your transform you want to spawn is looking at.
> 1 votes

---
Tags: c#, unity, vector, normals, unityscript
---


# Question
Title: Really weird peaks when profiling a simple scene with Unity3D
I need some help optimizing my game. I have spent last 3 days digging around with no luck. I have noticed really odd results in the unity profiler so, I have created a simple scene with just a cube and a camera, and again, really odd results. Could anybody have a look at this screenshots?:

You will see some significant peaks that make the frame time too high (30fps sometime or less). Scene hasn't any script, no coliders, no rigid bodies (notice the Physics simulate % in one of the shots).

Could anybody explain what is happening?

PD. Target platform is Android. This are taken from a Nexus 4 device. PD2. Somebody can argue that this is not a real scenario, but I have had this problems in a real game myself and wanted to show a simple example to expose the problem.

Thanks in advance.

# Answer
For What i can see :

* You have some shader taking a lot of resources, do you have a custom shader?
* you have a peak related to WaitForTargetFrameRate this looks a lot like a VSynch issue i had before, try disabling VSynch and you should get some relief already

Vsync can be disabled in Quality Settings
> 1 votes

---
Tags: android, unity, optimization
---


# Question
Title: How to obtain a camera stream from Unity without rendering it to the player's screen?
I'd like to stream the output of two cameras to a separate process. Right now, it looks like the best way to do that is to grab the rendered camera views from the screen via platform specific screen capture hooks then compress them real time with h.264. Is there a way to grab the input of the cameras within unity and avoid rendering them to the screen?

One solution I'm considering involves using Unity's multiplayer capability to run the game on a separate machine and grab it from that screen buffer, unbeknownst to the player.

# Answer
If you want to allow the players to get some kind of flyCam CounterStrike-like you should have it calculated and redered in client machine because it's cheaper for your bandwith.

But actually what you are trying to perform could be done through RenderTexture and Camera.targetTexture despite the fact that you will not be able to avoid rendering process from the host machine you will still be able to not show the result on screen and actually send it to other players through network.

EDIT : To be more clear other players could also control the cam or any cam you want but the issue would still be the bandwith and processing power of the host machine for each cam you should count that you render and send the package to other player client... If other players have their own version of the game in local then you dont have to render it on the host you can render it on the client which will be much more responsive for everybody. I hope this answered your question
> 3 votes

---
Tags: unity
---


title: Why nearby triangles tend to disappear?

text:
# Question
Title: Why nearby triangles tend to disappear?
~~I've just enabled back face culling and~~ I'm noticing a weird behavior: when all vertices of my triangle is outside the view and 2 of them is behind me (I think) the triangle disappears.

So to see it, here is a GIF.

I suspect the projection matrix reverses the order of the two vertices when they fall behind me, and changes the winding of my triangle.

But it's unclear why does the triangles disappear only if all vertices out of view...

How can I work around this problem, if possible?

I develop on Linux if that matters.

UPDATE:

It's pointed out it might not be due to the back face culling. I disabled it and I can indeed reproduce it. The cubes are 20×20 and the vertical field view is 90°. Its vertical apparent size roughly fills the window.

UPDATE 2:

Ok I'll post the relevant part of the code, projection and view matrixes are set up using my own functions:

```
void createViewMatrix(
    GLfloat matrix[16],
    const Vector3 *forward,
    const Vector3 *up,
    const Vector3 *pos
)
{
    /* Setting up perpendicular axes */
    Vector3 rright;
    Vector3 rup = *up;
    Vector3 rforward = *forward;

    vbonorm(&rright, &rup, &rforward); /* Orthonormalization (right is computed from scratch) */

    /* Filling the matrix */
    matrix[0] = rright.x;
    matrix[1] = rup.x;
    matrix[2] = -rforward.x;
    matrix[3] = 0;

    matrix[4] = rright.y;
    matrix[5] = rup.y;
    matrix[6] = -rforward.y;
    matrix[7] = 0;

    matrix[8] = rright.z;
    matrix[9] = rup.z;
    matrix[10] = -rforward.z;
    matrix[11] = 0;

    matrix[12] = -vdp(pos, &rright);
    matrix[13] = -vdp(pos, &rup);
    matrix[14] = vdp(pos, &rforward);
    matrix[15] = 1;
}

void createProjectionMatrix(
    GLfloat matrix[16],
    GLfloat vfov,
    GLfloat aspect,
    GLfloat near,
    GLfloat far
)
{
    GLfloat vfovtan = 1 / tan(RAD(vfov * 0.5));

    memset(matrix, 0, sizeof(*matrix) * 16);
    matrix[0] = vfovtan / aspect;
    matrix[5] = vfovtan;
    matrix[10] = (near+far)/(near-far);
    matrix[11] = -1;
    matrix[14] = (2*near*far)/(near-far);
}

```

Projection matrix set up with this call:

```
createProjectionMatrix(projMatrix, VERTICAL_FOV, ASPECT_RATIO, Z_NEAR, 10000);

```

(VERTICAL\_FOV = 90, ASPECT\_RATIO = 4.0/3, Z\_NEAR = 1)

Level drawing is simply:

```
void drawStuff()
{
    GLfloat projectView[16];

    glClearColor(0, 0, 0, 1);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    createViewMatrix(viewMatrix, &camera.forward, &camera.up, &camera.pos);

    multiplyMatrix(projectView, viewMatrix, projMatrix); /*< Row mayor multiplication. */

    glUniformMatrix4fv(renderingMatrixId, 1, GL_FALSE, projectView);
    bailOnGlError(__FILE__, __LINE__);

    renderLevel(&testLevel);
}

```

Cubes are rendered wall by wall (optimizing this will be another story):

```
    for (j = 0; j < 6; j++)
    {
        glBindTexture(GL_TEXTURE_2D, cube->wallTextureIds[j]);
        bailOnGlError(__FILE__, __LINE__);

        glDrawElements(GL_TRIANGLE_FAN, 4, GL_UNSIGNED_INT, (void*)(sizeof(GLuint) * 4 * j));
        bailOnGlError(__FILE__, __LINE__);
        glUniform4f(extraColorId, 1, 1, 1, 1);
        bailOnGlError(__FILE__, __LINE__);
    }

```

Vertex shader:

```
#version 110

attribute vec3 position;
attribute vec3 color;
attribute vec2 texCoord;

varying vec4 f_color;
varying vec2 f_texCoord;

uniform mat4 renderingMatrix;

void main()
{
    gl_Position =  renderingMatrix * vec4(position, 1);
    f_color = vec4(color, 1);
    f_texCoord = texCoord;
}

```

Fragment shader:

```
#version 110

varying vec4 f_color;
varying vec2 f_texCoord;

uniform sampler2D tex;

uniform vec4 extraColor;

void main()
{
    gl_FragColor = texture2D(tex, f_texCoord) * vec4(f_color) * extraColor;
}

```

The depth buffer simply set up by enabling it.

# Answer
So far it seems it is an OpenGL driver issue. I don't have other computer to test this on to confirm.

If I force software rendering by

```
$ export LIBGL_ALWAYS_SOFTWARE=1

```

The problem goes away. Probably I need to look around bugs with Mesa.
> 5 votes

# Answer
Though similar issues are often caused by clipping, the near plane is not the issue here. If it would be, the disappearance would be per pixel and not per triangle.

In your animation the triangles exactly disappear at the moment all of its three vertices get outside of the screen. Your algorithm may be based on the false assumption that triangles are hidden when all their vertices are hidden.

Here is an article talking about a good frustum culling implementation.
> 6 votes

# Answer
The triangles are disappearing because of the camera frustrum's near plane. Everything that is closer to the camera than the near plane is automatically clipped. You just need to put your near plane even more close of the the camera location. How you can configure the near plane depends on your graphical library or engine. In OpenGL, for example you should set the zNear parameter of gluPerspective:

```
void gluPerspective(GLdouble fovy, GLdouble aspect, GLdouble zNear, GLdouble zFar);

```
> -1 votes

# Answer
its purely related to the near clipping plane for camera and has nothing related to backface culling. U need to reduce the near clipping plane and the clipping will go off.
> -1 votes

---
Tags: opengl, 3d, linux
---


# Question
Title: How do I lock drawn lines to be orthogonal to an existing one?
I'm making a 2D game in Corona for Android/iPhone that is similar to Volfied. In my game, the user has to touch the screen to draw a line for the character to move along. How can I force the lines to be orthogonal, as opposed to being free-drawn?

I can detect the swipe's direction with `atan2` and the difference of X and Y, but I am having trouble determining the pivot points of the line. How can I determine when the line should make a turn?

You can see what I am trying to accomplish in this video of Volfied gameplay.

# Answer
Here's a sample that shows how to obtain the beginning and end coordinates: http://developer.coronalabs.com/code/mark

Essentially to lock it to orthogonal, you need to find which orthogonal direction is the smallest angle from the given angle, and set your beginX and beginY appropriately.

For example, knowing that you're swiping from left to right I might do the following:

```
local swipeDifferenceX = beginX - endX
local swipeDifferenceY = beginY - endY

// If the user moved further in the X direction
if(swipeDifferenceX >= swipeDifferenceY)
    endY = beginY
else
    endX = beginX

```

This will likely require some playing around with and I probably messed up some logic since I only have a few minutes to respond, but I trust you can figure out the rest.
> 1 votes

---
Tags: vector, lua, trigonometry
---


# Question
Title: Pixel perfect clickable picture in OpenGL/C++
So I have a picture(for easier understanding of problem like this: http://www.lib.utexas.edu/maps/europe/europe\_95.jpg).

My goal is to click on any of the countries and get what country I clicked. The picture is full of colors, not just simple lets say Germany is purple. Also if I hover above a country I could also do things, like highlight it, write some text in a bar, etc.

What solutions popped in my mind:

* Draw every slice into a mesh, and ray trace the click. (making lots of meshes is a lot of time)
* Draw a single quad with texture, make a pixelmap, and get the coordinates clicked, then look up in the table.(I have to make a map for every resolution)

Is there any better way of doing this? Or are there any algorithms for it?

# Answer
If you take a look, there are rivers and names etc. This will make it rather hard to use the second approach. I would definitely go with the approach were you create a polygon shape for every country, and use simple maths to determine wether a given point lies in the polygon or not. I know this will require you to make a shape for every country. But I think that using the color of the pixel is going to bring you a lot of headache.

This approach will preform pretty good I guess, since you can filter first on AABB, and possibly filter further using a quadtree.
> 1 votes

# Answer
How about using a transparent layer with a different value for each country? Then, you could just query the alpha value for the pixel and use a lookup table.

The only challenge is getting the alpha data there in the first place, but I'm sure you can come up with a creative answer to do that. Maybe just write a very simple editor which flood fills based on each mouse click and then prompts you for a name. It could write both the alpha layer and the look up table for you.
> 1 votes

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


# Question
Title: Scaling background without scaling foreground in platformer?
I'm currently developing a platform game and I've run into a problem with scaling resolutions.

I want a different resolution of the game to still display the foreground unscaled (characters, tiles, etc) but I want the background to be scaled to fit into the window.

To explain this better, my viewport has 4 variables: (x, y, width, height) where x and y are the top left corner and width and height are the dimensions. These can be either 800x600, 1024x768 or 1280x960. When I design my levels, I design everything for the highest resolution (1280x960) and expect the game engine to scale it down if a user is running in a lower resolution.

I have tried the following to make it work but nothing I've come up with solves it so far:

```
scale = view->width/1280;
drawX = x * scale;
drawY = y * scale;

```

(this makes the translation too small for low resolution)

and

```
scale = view->width/1280;
bgWidth = background->width*scale;
bgHeight = background->height*scale;
drawX = x + background->width/2 - bgWidth/2;
drawY = y + background->height/2 - bgHeight/2;

```

(this makes the translation completely wrong at the edges of the map)

The thing is, no matter what resolution the game is run at, the map remains the same size, and the foreground is unscaled. (With a lower resolution you just see less of the foreground in the viewport)

I was wondering if anyone had any idea how to solve this problem?

Thank you in advance!

# Answer
Really depends on how you're going about drawing.

Let's suppose you're using an image for your back ground

Sounds like you're using an image for your background and laying sprites and tiles over?

In that case, do the resizing yourself instead of relying on Java or whatever library you're using.

Pretty simple to do, really: have a drawBackground() method, which checks the size of the frame you're drawing in, and if necessary, resizes the image. You don't want to do that every paint cycle (unless it's a continuously changing image) so hang on to the resized image.

Once you've got the background drawn, then you can tile the foreground objects without any need to rescale them. write it in a seperate method to keep your head straight.

pseudocode goes something like this: (been a while since I did this in Java, my syntax is probably atrocious)

Image i, backgroundImage; drawBackground(i); drawForeground(i);

drawBackGround(Image i); { if !(backGroundImageIsCorrectSize(backgroundImage.getDimensions())) { resizeBackgroundImage(backGroundImage); } i = backgroundImage.copy(); }

drawForeground(Image i) { foreach(tile in tileList)
tile.draw(i) }

Then, just hand off the completed image to be drawn. If you're savvy, you can even do all this in a second thread, though for simple graphics, that may not be necessary.

It's hard to be more specific without more details.

If you really wanna get a handle on java graphics, I recommend a book called "Filthy Rich Clients." It's not aimed at games per se, but it gives a really great overview of the java 2D library in plain English and it's full of good, inspiring ideas. here's the link
> 1 votes

---
Tags: 2d, graphics, platformer, resolution, scale
---


# Question
Title: Load all bitmaps at once or only when needed?
I am starting to get a pretty hefty amount of bitmaps in my 2d game for android. I load them all in 3 colors to save some memory but the thing is, I load all of them when "Start game" is pressed, even the ones that wont be used for another 5-6 levels. And There is no switching activities between levels, its all controlled using states to make the game smoother. I lack knowledge in memory-management so any kind of advice or preferred methods would be greatly appriciated. For example, if the bitmaps from level 1 never needs to be used again, do I need to delete them from memory manually or does the GC do that for me?

Also, does anyone know a good method for re-using bullets? I imagine just creating new ones will take a toll on memory? Cus Right now Im at 16mb heap when running my game, which makes no sense at all, even when I disable 80% of my game heap-size stays high, so Im obviously missing something.

# Answer
Best design is to load and unload resources yourself and don't let the engine or library do this for you. This way you have all control.

Be sure to unload ALL resources you don't need in the current scene.

as for re-using bullets... I would instance a small bitmap for every bullet and unload it once it reached a certain distance or has, for example, left the screen (so it isn't visible)

Hope this helps.
> 1 votes

---
Tags: java, 2d, android, sprites, memory-efficiency
---


# Question
Title: How can I repeat a portion of a texture on a quad?
I want to repeat a selected part of the texture into a quad.

I was looking at this thread, however the solution involved changing my HLSL.

Is there any way to do it without changing my shader settings?

```
SamplerState SampleType
{
    Filter = MIN_MAG_MIP_LINEAR;
    AddressU = Wrap;
    AddressV = Wrap;
};

float4 TexturePixelShader(PixelInputType input) : SV_Target
{
    float4 textureColor;

    // Sample the pixel color from the texture using the sampler at this texture coordinate location.
    textureColor = shaderTexture.Sample(SampleType, input.tex);

    return textureColor;
}

```

And here's my current texture calculations:

```
// Get desired texture coordinates.
tLeft = (float)relTextureX / aTextureWidth ;
tRight = (float)(relTextureX + relTextureWidth) / aTextureWidth;
tTop = (float)relTextureY / aTextureHeight;
tBottom = (float)(relTextureY + relTextureHeight) / aTextureHeight;

// Create the vertex array.
vertices = new VertexType[m_vertexCount];
if (!vertices)
{
    return false;
}

// Load the vertex array with data.
vertices[0].position = D3DXVECTOR3(left, top, 0.0f);  // Top left.
vertices[0].texture = D3DXVECTOR2(tLeft, tTop);

vertices[1].position = D3DXVECTOR3(right, bottom, 0.0f);  // Bottom right.
vertices[1].texture = D3DXVECTOR2(tRight, tBottom);

vertices[2].position = D3DXVECTOR3(left, bottom, 0.0f);  // Bottom left.
vertices[2].texture = D3DXVECTOR2(tLeft, tBottom);

// Second triangle.
vertices[3].position = D3DXVECTOR3(left, top, 0.0f);  // Top left.
vertices[3].texture = D3DXVECTOR2(tLeft, tTop);

vertices[4].position = D3DXVECTOR3(right, top, 0.0f);  // Top right.
vertices[4].texture = D3DXVECTOR2(tRight, tTop);

vertices[5].position = D3DXVECTOR3(right, bottom, 0.0f);  // Bottom right.
vertices[5].texture = D3DXVECTOR2(tRight, tBottom);

```

# Answer
You will have to put your **texture wrap mode to repeat** and use UV texture coordinates larger than the usual 0.0 - 1.0 range. Like for example 0.0 - 2.0 on the x axis will repeat your texture twice on the x axis!
> 1 votes

# Answer
in the shader file I believe in the vertex shader file you can do something like this:

```
output.texcoord = input.texcoord * 2.0f;

```

What this will do is move the texture UV coord's over 2 units over. What you will do is achieve texture repeating. If you don't you can just either have it times by 1.0f .

So, the output would be for the pixelshader or fragment shader (openGL) and the input would be for the vertex input inside the shader.

It must be done in the vertex shader because the pixel shader only focuses on the pixels inside the mesh.
> 0 votes

---
Tags: c++, textures, directx, directx10
---


title: Rotate GameObject on click

text:
# Question
Title: Rotate GameObject on click
I'm trying to get a card to flip when clicked but the flipping only works the first flip. While debugging, I can see that OnMouse is called every time I click.

```
public class CardController : MonoBehaviour
{
   bool isShowingFront = true;
   bool isFlipping = false;
   float speed = 0.005F;
   Quaternion flipRotation = new Quaternion (0, 0, 0, 0);
   // Use this for initialization
   void Start ()
   {

   }

   // Update is called once per frame
   void Update ()
   {

      if (transform.rotation.y != flipRotation.y) {
             transform.rotation = Quaternion.Lerp (transform.rotation, flipRotation, Time.deltaTime * speed);
             isFlipping = true;
      } else {
             isFlipping = false;
      }

   }

   void OnMouseUp ()
   {
      if (isShowingFront) {

             flipRotation.y = 180;

      } else {
             flipRotation.y = 0;
      }

      isShowingFront = !isShowingFront;
      Debug.Log ("I was clicked");
   }
}

```

# Answer
> 1 votes
The third parameter of the Lerp() method is the interpolation factor between *from* and *to* and should be between 0 and 1. Every time you flip a card you want to make this factor go from 0 to 1 over a period of time. You can do this as follows:

1. Add a float member variable *t*.
2. When the card is clicked set *t* to 0.
3. In your update function add `t += Time.deltaTime * speed; if(t > 1.0f) t = 1.0f;`
4. Pass *t* as the third parameter to the Lerp() method.

Note: if you can flip cards while they're still rotating, the rotation speed will not be constant this way. E.g. if flipping a card takes 1 second, flipping it again half way through will take 1 second as well instead of 0.5 second. You can make the speed constant by not setting *t* to 0 on click, but interpolating the value based on the current rotation.

# Answer
> 0 votes
try working with the transform.Rotate(...) function. I think it's easier to use and it doesn't require quaternions.

As for your game logic I'd make a boolean which states if the card is flipped or not and according to that use the right transform.Rotate(...) function.

---
Tags: unity, quaternion
---


# Question
Title: How does server code modify game state on the server while still accepting additional server game calls
Question first, then explanation second.

**How can a webservice backend to a game modify and alter the server game state while the game simultaneously accepts webservice calls from other users of the game?**

These are my assumptions of how browser-based games work. They may be full of misconceptions, and **please** correct me if I am wrong!

1. Turn-based games are intuitively games that would best be represented by a single instance of a game.
2. Turn-based browser games with a server backend would typically call a sort-of "webservice" on the server.
3. A webservice has to complete its entire operation and then return.

I'm getting confused during the conversion between the "entire operation" part of the webservice and the *non-static* "single instance" of the game backend itself. How can a webservice, with their static nature, modify and alter a game while the game simultaneously accepts webservice calls from other users of the game? The only way I can see this occurring with static method calls is that the webservice saves and loads the game for each call, which seems horrifically wasteful on resources.

For example, consider a 3-player connect-four board, where only one player can play at once but users can change their color at will. The user should be able to change their color while waiting for the other players to play.

The question I have here is both conceptual and implementation-oriented, although it's mainly the conceptual that I'm curious about.

# Answer
> 2 votes
Every "message" that is sent to the server should have an ID. Your server constantly accepts those messages from every connected client.

Let's take your example with the 3 players. They are all connected to the server and are registered there as player 1, 2 and 3. Now, at this moment it might be player 2's turn but he's still thinking about his move and player 1 wants to change his color. This can be done very simply.

The server, as mentioned before, constantly accepts messages and loops over all available ID's that those messages might have. Player 1 who wants to change his color will send a packet with ID CHANGE\_COLOR for example which holds a struct with the name of the player (player 1) and the color he wants to be. The server will receive this message and check the ID it has. It will then run through the code associated with this ID.

This does not interrupt the fact that player 2 is now doing his move (which might be the following packet the server receives). This packet could have the ID PLAYER\_MOVE. This packet could hold a struct with, again, the name of the player and his movement. The server will check if the player that sent this packet is able to make this move (check if it's his turn) and then run through the code associated with this ID. If player 1 would try this the server could simply reject his move and reset it to the previous state.

I hope this is what you wanted to know. If you want code, take a look at the basic tutorial for RakNet. This library uses the system I explained.

# Answer
> 1 votes
When players start a game a new instance is spun up on the server and given an ID.

when players make a change, their command is created with their game ID and sent to the web service.

The web service there merely acts as a router that uses the game ID to send the command onward to the proper instance, which holds it in a message queue until it can retrieve them.

In this way one client can play multiple, simultaneous games because each they start has its own ID. Similarly, each web service is handling multiple, simultaneous instances. Also, multiple players can interact independently in one game because messages are queued up at the game's instance and not at the web service interface.

Given all of this, **no commands really happen simultaneously**, the instance receiving the command from the web service simply retrieves them one at a time from its incoming queue.

# Answer
> 0 votes
I disagree with the direction a few of the other answers went in. They all seem under the assumption that your game server must be its own distinct process with its own protocol. This is mostly true for real-time games, but a truly turn-based game can quite easily be a Web service built the usual way you'd build any other large, scalable Web application.

> Turn-based games are intuitively games that would best be represented by a single instance of a game.

As above, not necessarily. Depends on what you mean by "instance of a game," but if you mean individual process, then definitely no.

> Turn-based browser games with a server backend would typically call a sort-of "webservice" on the server.

The should, without the quotes. Some turn-based games have particular needs that *do* require their own game server processes and protocols; certainly not your example game, though.

> A webservice has to complete its entire operation and then return.

Yes, but that operation could well be "enqueue an action that is executed shortly by another server." The trick is that you in some fashion need to tell the players when things happen and when their turn starts. This could be done with Websockets, server-side events, or the traditional polling (long polls or frequent short ones; long polls are better for bandwidth).

This answers your direct questions, but I feel you would be better served if you posted a new question with more specific details about your game.

---
Tags: client-server, browser-based-games
---


# Question
Title: How should I determine the bounding rectangles for frames within a sprite sheet?
I have a spritesheet for a character. The spritesheet has several rows, and each row represents an animation. The elements within a row might vary in width.

How can I load the different sections of the spritesheet and set animations for each game element?

My first approach to this problem was to manually calculate the rectangle for each frame and hardcoding them into the respective object classes. The `Hero` class, for example, would have several arrays of rectangles with the hardcoded bounds of every frame of animation. This method is really primitive, however, so I am looking for a solution that takes this to the next level.

-

I am at the moment using an interesting approach which although in the end is very easy to use, it sounds a little complex, but i would like an opinion about it.

I have an Animation class which has a function setFrames(Rectangle.Float\[\] frames); Every game element has an animation, even if it only has a sigle sprite its whole lifetime. This class takes care of which frame is time to show at a certain time of the game. The way to use it is simply set the frames everytime a new animation is supposed to play, and receive the rectangle in the draw (and update is, ofc)

Example: While Idle, I press right button, this makes me walk right setFrames method is called with the "walking" rectangle array passed in its argument, thus changing which frames are looping.

Now, the way i abstracted from the rectangles was I started packing my sprites with a program called TexturePacker which places the sprites in a spritesheet by itself and creates an XML file with each sheet element's name and position, as simple as this:

```
<?xml version="1.0" encoding="UTF-8"?>
<!-- Created with TexturePacker http://www.codeandweb.com/texturepacker-->
<!-- $TexturePacker:SmartUpdate:d4e1eb1edb1e925f5e2b7fea77dae064:e103ddd8b5f54e4f084f4075e778872a:e8412e2a02129a8b5ad20319afc153de$ -->
<!--Format:
n  => name of the sprite
x  => sprite x pos in texture
y  => sprite y pos in texture
w  => sprite width (may be trimmed)
h  => sprite height (may be trimmed)
oX => sprite's x-corner offset (only available if trimmed)
oY => sprite's y-corner offset (only available if trimmed)
oW => sprite's original width (only available if trimmed)
oH => sprite's original height (only available if trimmed)
r => 'y' only set if sprite is rotated
-->
<TextureAtlas imagePath="blabla.png" width="128" height="128">
    <sprite n="four" x="2" y="2" w="100" h="32"/>
    <sprite n="one" x="2" y="36" w="32" h="32"/>
    <sprite n="three" x="36" y="36" w="53" h="32"/>
    <sprite n="two" x="91" y="36" w="12" h="32"/>
</TextureAtlas>

```

Then, I created a SheetLoader class, which is essentialy a parser of the XML file and receives the XML path in its argument and fills this:

```
private HashMap<String, Rectangle.Float> textures;

```

with the elements names as keys and the elements rectangles. This class also has a method called getSprite(String); which returns a rectangle of a sprite based on its name (its a simple call from the hashmap)

I then created this weird Enum class:

```
package render;

import java.awt.Rectangle;

public enum Anims {

    HEROIDLE("Resources/SpriteSheets/blabla.xml", "one", "two", "three", "four", "three");

    Rectangle.Float[] frames;

    Anims(String path, String... animation)
    {
        frames = new Rectangle.Float[animation.length];
        SheetLoader sL = new SheetLoader(path);

        for(int i=0; i<animation.length; i++)
        {
            frames[i] = sL.getSprite(animation[i]);
        }
    }

    public Rectangle.Float[] getFrames() {return frames;}
}

```

So basically the way to use this is, to create a new animation I add a new enum with the info from the XML path (where i get the rectangles from), and the sequence of the sprites that form the animation, and if this info exists, the enum is successfuly created. Using this is very easy later, for example if i wanna change the hero animation to idle id just do:

```
animation.setFrames(Anims.HEROIDLE.getFrames());

```

The thing i like about this method is, i can forget about worrying about the rectangles. I just make the spritesheet, I send the XML file to the game and i just use the sprite names directly in the enum declaration.

Still this way might not be the best in therms of simplicity or optimization, so if that is the case id like to know different solutions or how it is usually done.

# Answer
I don't see much wrong with your approach. A good sprite graphics pipeline doesn't require any manual definitions for the sprites. How all of this happens is just an implementation detail, but the graphics artist should not need to care about it. Usually they are the most comfortable using Photoshop, so the more you can push to Photoshop of the pipeline, the better. The other tools of the pipeline can be executed by the artists, programmers or automatically, it's up to you.

One problem I see in your approach is this line:

> HEROIDLE("Resources/SpriteSheets/blabla.xml", "one", "two", "three", "four", "three");

Here you seem to be specifying the frames in the code. It would be nice if the artists could do this themself. How this would happen depends on the rest of your toolchain and there might not be both easy and userfriendly solution.

Another thing you could improve on is to use code generation for creating the constants in your Anims class. This code generation would be run when the sprite data has changed. The benefit would be removing one more manual step, as manual steps are always more or less error prone. On the other hand depending on the size of the game/engine this might not be worth the effort.
> 1 votes

---
Tags: java, game-design, animation, sprites, spritesheet
---


# Question
Title: What is the value of gameTime.ElapsedGameTime.TotalSeconds?
I was wondering what is exactly the value of `gameTime.ElapsedGameTime.TotalSeconds` in a second? Please explain it to me completely and as great as you can.

# Answer
> 3 votes
From the documentation `ElapsedGameTime` is:

> Property Value
>
> Elapsed game time since the last update.

This means it's the amount of time since the last time the update function was called. It's a `TimeSpan`. Getting `TotalSeconds` from a `TimeSpan` will give you the time in seconds. This is likely to be a pretty small value, since updates happen very fast.

---
Tags: xna, monogame
---


# Question
Title: AI to move custom-shaped spaceships (shape affecting movement behaviour)
I'm designing a networked turn based 3D-6DOF space fleet combat strategy game which relies heavily on ship customization. Let me explain the game a bit, since you need to know a bit about it to set the question.

What I aim for is the ability to **create your own** fleet of ships with **custom** shapes and attached modules (propellers, tractor beams...) which would give advantages and disadvantages to each ship, so you have lots of different fleet distributions. E.g., long ship with two propellers at the side would let the ship spin around that plane easily, bigger ships would move slowly unless you place lots of propellers at the back (therefore spending more "construction" points and energy when moving, and it will only move fast towards that direction.) I plan to balance all the game around this feature.

The game would revolve around two phases: orders and combat phase. During the orders phase, you command the different ships. When all players finish the order phase, the combat phase begins and the ship orders get resolved in real-time for some time, then the action pauses and there's a new orders phase.

The problem comes when I think about player input. To move a ship, you need to turn on or off different propellers if you want to steer, travel forward, brake, rotate in place... These propellers don't have to work at their whole power, so you can achieve more movement combinations with less propellers.

I think this approach is a bit boring. The player doesn't want to fiddle with motors or anything, you just want to MOVE and KILL. The way I intend the player to give orders to these ships is by a **destination** and a **rotation**, and then the AI would calculate the correct propeller power to achive that movement and rotation. Propulsion doesn't have to be the same throught the entire turn calculation (after the orders have been given) so it would be cool if the ships reacted as they move, adjusting the power of the propellers for their needs dynamically, but it may be too hard to implement and it's not really needed for the game to work.

In both cases, **how would that AI decide which propellers to activate for the best (or at least not worst) trajectory to be achieved?**

I though about some approaches:

* **Learning AI:** The ship types would learn about their movement by trial and error, adjusting their behaviour with more uses, and finally becoming "smart". I don't want to get involved THAT far in AI coding, and I think it can be frustrating for the player (even if you can let it learn without playing.)
* **Pre-calculated timestep movement:** Upon ship creation, ALL possible movements are calculated for each propeller configuration and power for a given delta-time. Memory intensive, ugly, bad.
* **Pre-calculated trajectories:** The same as above but not for each delta-time but the whole trajectory, which would then be fitted as much as possible. Requires a fixed propeller configuration for the whole combat phase and is still memory intensive, ugly and bad.
* **Continuous brute forcing:** The AI continously checks ALL possible propeller configurations throughout the entire combat phase, precalculates a few time steps and decides which is the best one based on that. Con: what's good now might not be that good later, and it's too CPU intensive, ugly, and bad too.
* **Single brute forcing:** Same as above, but only brute forcing at the beginning of the simulation, so it needs constant propeller configuration throughout the entire combat phase.
* **Coninuous angle check:** This is not a full movement method, but maybe a way to discard "stupid" propeller configurations. Given the current propeller's normal vector and the final one, you can approximate the power needed for the propeller based on the angle. You must do this continuously throughout the whole combat phase. I figured this one out recently so I didn't put in too much thought. A priori, it has the "what's good now might not be that good later" drawback too, and it doesn't care about the other propellers which may act together to make a better propelling configuration.

I'm really stuck here. Any ideas?

# Answer
Sorry haven't got a tried-and-tested solution, but can this not be solved mathmatically?

Given any propeller and its offset from the center of mass, you can compute what plane you can rotate in.

For any movement, you can use 1 or more propellers. Each propeller can be queried to see whether its plane can contribute to the target orientation, how much effort it would take from the propeller to contribute (propellers far from the CoM can use less energy to generate more turn), and how close that would get you to the target oritentation. Then you A\* across that search space until you come up with a solution with low cost, which could be least total energy used or fastest movement.

Keep reevaluating that as you complete the turn and moderate power as you approach the target, maybe with a PID controller.

For forward movement, a simple solution would drive you always forwards, dropping your target speed as you approach the target. As you've got 3D space to play in you can avoid complicated 3-point turn routines. You'd need to factor the output from the propellers chosen for straight-line speed into your turning calculations, as some kind of initial state.

This is very back-of-the-envelope but I don't see any major flaws. Just lots of hard work and number tweaking. :)
> 4 votes

# Answer
Since you want to give up a bit of player control for playability using an AI, you might want to consider also simplifying the effect of tacking on propellers and altering ship dimensions into less, more easily manageable parameters for a computer algorithm. The player is still allowed to add propellers on any given part of the ship, but once completed this is 'compressed' into parameters.

Each propeller affects the turn rate of the ship, or, combined with a parallel placed propeller, affects the travel rate in a specific dimension. Combine these parameters for each propeller, and you get the maximum turn rate and speed for a ship. Combine these two parameters for each propeller and propeller set into the maximum turn and speed rate for the ship as a whole, for all available dimensions (up, down, left, right, forward, backward).

Using the turn rate and velocity for each dimension, you have enough information to actually allow the ship to move to a destination. The player will see the effect of his propeller configuration, but under the hood his input is vastly simplified. You could come up with more than one fly strategy based on the distance the ship has to travel, to make the flight look more natural and increase the player's sense he or she has exerted control over the ship movement. But in the end, like you said, it will not matter how the ship gets to the destination and whether its route is optimal, it just needs to be there and its arrival time is influenced by the propeller configuration.

For the ship dimensions, you could factor them in once you have the compressed velocity values for a rough effect, or use them while calculating for a more precise effect. You would probably want to test if the precise method is worth the effort, because the difference might not impact the player's sense of control.
> 7 votes

# Answer
In space, shape does not affect movement. No air to drag on.

It's the ship plus add-ons total mass that matters. It's a simpler mass thrust gravity problem. So you can do these calculation or since it's a turn base game, develop a movement system like RPGs like Traveller have.
> 0 votes

---
Tags: algorithm, ai, movement, turn-based-strategy
---


# Question
Title: Algorithm for game difficulty/pacing curve generation in single player RPG
I'm looking at this article about pacing in entertainment and games. It suggests that all good entertainment roughly follows a pacing/engagement curve like Star Wars(below).

I'm interested in **how I can procedurally generate random-looking curve that would conform to the Star Wars engagement intensity pattern** (linear increase and oscillating peaks-valleys). The simplest implementation I can think of is a rectified sine wave and a sloped line, but that would be very predictable. I have an algorithm for perlin noise already in the game and am interested **if I can leverage perlin noise algorithm to procedurally generate a varying sequence of peaks and valleys on an increasing slope.**

Here's my attempt so far:

Once I have an algorithm, I can reference it to get engagement difficulty in relation to game turn or progress through some level.

---

I will add my thoughts to this question in hopes that **someone can correct or point out flaws in my approach below:**

* I get the basic XP system in place (previous level \*1000 to advance to next level)
* Decide on the level cap (lets say 20 levels)
* Plot available equipment tiers vs 20 levels (regular at lvl 1, magical at lvl 10, epic at lvl 20)
* Using the peak-valley graph decide how many fights are in each peak-valley cycle (5 to reach lvl 2, 12 to reach lvl 20).
* estimate number of turns per fight, let's say 5 turns per fight
* calculate xp needed and turns needed to reach to each new level
* Plot turn number and hypothetical xp the party has at each level.

Now for each peak I have a number of turns and the amount of XP that the curve should have between two valleys.

Using whatever formula the curve follows at that peak (let's assume a bell curve), I can get the xp value of monsters I have to spawn during that turn. These monsters have their equipment adjusted according to the equipment vs tier/turn number that was calculated above.

Now I need to adjust monster XP and test it at different levels. A simple sanity check: a party of 6 players must kill:

* 750 xp of monsters in first fight in 5 turns, that is 30 actions.
* 1500 in second fight
* 1800 in third fight
* 1350 in fourth
* 555 in fifth

# Answer
> 2 votes
Yes, you can leverage the noise algorithm. Use your attempt so far as a baseline. Then, using a single dimension perlin noise function, use the x axis as an input to add noise to your baseline function. You can either do this at every point along the axis, or you can do it just for the peaks and valleys and interpolate the values between.

This will be pretty unrelated to your terrain height algorithm. The only similarities being that you're using perlin noise for both.

Another algorithm available to you is midpoint displacement:

You will have to modify the algorithm a bit, since it doesn't usually expect baseline values other than zeros. Once modified, use your sloped sine wave as an input.

# Answer
> 1 votes
This is sounding a bit like Valve's "Game Director" in the Left For Dead series.

The idea is that there's an AI "watching" the player to make sure they're having fun. When things are tough it generates fewer and weaker enemies. When you seem to be picking the zombies apart effortlessly, it creates more and harder zombies.

Not only that, it also tries to create suspense by leaving periods of dead time where there are no enemies, then unleashing zombie hell on the player.

Personally, I found it pretty effective. I liked the pacing in those games.

I'm wondering what sort of RPG you're coding. Is this the retro style RPG where monsters attack you randomly as you wander the map/ (like the old final fantasy games?) Or is it more action / adventure like Diablo?

I think either way, you could probably create the same effect. Instead of a continuous stream of enemies, which is psychologically taxing, create some dead time in between your battles so that the player has time to adjust inventory, heal, etc.

Rather than planning all this out in advance, why not just do it on the fly? come up with some algorithm that tells your "game director" how much trouble the player is having at any set time in the game, (You can look at things like player level, hitpoints, recent potions used, etc.) then use that information to adjust the difficulty of the enemies.

Leave some room in the director for a few pushover battles, and some fairly epic fights, regardless of how hard the player's doing, but set it up to where the player should have a reasonable expectation of winning, at least most of the time. (But not all the time... See Dwarf Fortress's motto: Losing is fun)

# Answer
> 1 votes
Another possibility is that instead of adding Perlin noise to the y axis of your graph, you could use it to scale the x axis. This would mean that you have a fixed difficulty curve, but it takes a different amount of time to get through different bits of it. For example the Perlin noise could be in the range 0.5 to 2.0, and that could be how quickly time passes on that curve.

---
Tags: algorithm, procedural-generation, rpg, difficulty, dynamic-difficulty
---


# Question
Title: Encode two integers into colour values and compare them in a HLSL shader
I am writing a 2D point and click adventure game in Monogame, and I'd like to be able to create an image mask for every room which defines which parts of the background a character can walk behind, and at which Y value a character needs to be at for the background to be drawn above the character.

I haven't done any shader work before but after doing some reading I thought the following solution should work:

* Create a mask for the room with different walk behind areas painted in a colour that defines the baseline Y value (Walk Behind Mask)
* Render all objects to a RenderTarget2D (Base Texture)
* Render all objects to a different RenderTarget2D, but changing every pixel of each object to a colour that defines its Y value (Position Mask)
* Pass these two textures plus the image mask into the shader, and for each pixel compare the colour of the image mask to the colour of the Position Mask to the Walk Behind Mask - if the Position Mask pixel is larger (thus lower on the screen and closer to the camera) than the Walk Behind Mask, draw the pixel from the Base Texture, otherwise draw a transparent pixel (allowing the background to show through).

I've got it mostly working, but I'm having trouble packing and unpacking the Y values into colours and retrieving them correctly in the shader. Here are some code examples of how I'm doing it so far:

(When drawing to the Position Mask RenderTarget2D)

`Color posColor = new Color(((int)Position.Y >> 16) & 255, ((int)Position.Y >> 8) & 255, (int)Position.Y & 255);`

So as far as I can tell, this should be taking the first 3 bytes of the position integer and encoding them into a 4 byte colour (ignoring the alpha as the 4th byte). This seems to work fine, as when my character is at Y = 600, the resulting Color from this is: {\[Color: R=0, G=2, B=88, A=255, PackedValue=4283957760\]}.

I then have an area in my Walk Behind Mask that I only want the character to be displayed behind if his Y value is lower than 655, so I've painted it with R=0, G=2, B=143, A=255.

Now, I think I have the shader OK as well, here's what I have:

```
sampler BaseTexture : register(s0);
sampler MaskTexture : register(s1);
sampler PositionTexture : register(s2);

float4 mask( float2 coords : TEXCOORD0 ) : COLOR0
{
    float4 color = tex2D(BaseTexture, coords);
    float4 maskColor = tex2D(MaskTexture, coords);
    float4 positionColor = tex2D(PositionTexture, coords);
    float maskCompare = (maskColor.r * pow(2,24)) + (maskColor.g * pow(2,16)) + (maskColor.b * pow(2,8));
    float positionCompare = (positionColor.r * pow(2,24)) + (positionColor.g * pow(2,16)) + (positionColor.b * pow(2,8));
    return positionCompare < maskCompare ? float4(0,0,0,0) : color;
}

technique Technique1
{
    pass NoEffect
    {
        PixelShader = compile ps_3_0 mask();
    }

}

```

This isn't working, however - currently all characters are displayed behind the walk behind area, regardless of their Y value.

I tried printing out some debug info by grabbing the pixel from both the Position Mask and the Walk Under Mask under the current mouse position, and it seems like maybe the colours aren't being rendered to the Position Mask correctly? When calculating the colour in that code above I'm getting R=0, G=2, B=88, A=255, but when I mouseover my character I get R=0, G=0, B=30, A=255.

Any ideas what I'm doing wrong? It seems like maybe I'm losing some information when rendering to the RenderTarget2D, but I'm now knowledgeable enough to figure out what's happening.

Also, I should probably ask, is this an efficient way to do this? Will there be a performance impact?

Edit: Whoops, turns out there was a bug that I'd introduced myself, I was drawing out the Position Mask with the position Color, left over from some early testing I was doing. So this solution is working perfectly, though I'm still interested in whether this is an efficient solution performance wise.

# Answer
> 1 votes
I'd have rendered 2 different images; first the full background and then the characters and then the foreground image which I would have pre-rendered, à la painters algorithm

when panning the camera you can offset the further images less for a parallax effect to create some perspective

# Answer
> 0 votes
if you are not stuck with a single image, I would render the 2d objects (this even works for dynamic objects) with different z values (this way you can also create proper transparent windows).

# Answer
> 0 votes
There is one possible problem which your method: it computes two floating point numbers requiring 24 bits of precision, and that’s exactly the limit of a traditional 32-bit float (23 bits of mantissa plus an implicit one). I wouldn’t rely on computations being accurate to the last bit.

Your function can be tweaked so that it only requires 8 bits of precision:

```
{
    float4 color = tex2D(BaseTexture, coords);
    float4 maskColor = tex2D(MaskTexture, coords);
    float4 positionColor = tex2D(PositionTexture, coords);
    float difference = dot(positionColor - maskColor,
                           float4(65536.0, 256.0, 1.0, 0.0);
    return difference < 0 ? float4(0,0,0,0) : color;
}

```

I also used a dot product and expanded the `pow` calls in case the compiler isn’t smart enough.

---
Tags: xna, opengl, hlsl, monogame
---


# Question
Title: Art asset creation workflow question: are there any neat ways to save your work and automatically export it to desired format?
To be specific: I have used GraphicsGale for pixel art sprites. The program saves its files in its own format (.gal, I believe), but the images in my game have to be .png. Saving it to .png loses information for GraphicsGale, like the palette. Manually keeping to seperate files impairs the workflow. Ideal would be that after every save, the original file is saved in one folder, and a .png export in another, awaiting runtime and packing. Any suggestion/thoughts?

# Answer
> 3 votes
Automation is a common solution here. Create a build script that checks the date/time of source assets and automatically exports fresh game assets for the files that are out of date.

The details of the script will vary depending on the content creation tools, and the type of assets. Some of them can be easily automated with command line calls to their executables along with some input parameters (i.e. . With others you might have to get more creative and use GUI automation tools like Autoit.

Many IDEs will allow for custom scripts to be run before or after their own build process. Check your own IDE to see if such a thing is allowed, if not, you might check to see if you can include the building of your project in the automation (might want to do that anyway, just to have a complete solution).

This automation process should be made to be fairly flexible. For example, you don't want to have to explicitly include each source asset file you create. Make the script recognize file extensions to decide how to handle the file. Also, organizing your source asset directory the same way your game asset directory is organized will help the script automatically place generated files where they're supposed to go.

---
Tags: graphics, export, asset-workflow
---