# Question
Title: How can I track down outstanding references to a D3D swap chain?
On direct3d\_11.1 initialisation the swapchain is resized to the desired proportions but after the getting the backbuffer it isn't released. I check the return value and check its address which doesn't get nullified. It can't for the life of me see why/what is holding itself live. Do you know of any clever ways of determining this? I have done a solution-search for all places I use the swapchain. Which was Direct2d class - but I don't instantiate it anymore.

Here is a snippet of the onresize function which is called once at the end of the initialisation and once during WM\_SIZE. Yes I know I need to release all outstanding references but the backbuffer won't release. Neither, for that matter, will a few depthstencilstates. Where should I look? How do I find it? Is there something that tells you what the references are?

VS Output says swapchain cannot resize due to outstanding references. The number of references is 2 after getting the backbuffer and continues to be so even after the pBackbuffer-\>release request.

```
    try
{
    assert(m_spD3DImmediateContext);
    assert(m_spD3DDevice);
    assert(m_spSwapChain);

    //ReleaseCOM(m_pRenderTargetView);
    //ReleaseCOM(m_pDepthStencilView);
    //ReleaseCOM(m_spDepthStencilBuffer);
    //m_spRenderTargetView.Reset();
    //m_spDepthStencilView.Reset();
    //m_spDepthStencilBuffer.Reset();
    //m_spDepthDisabledStencilState.Reset();

    // This is used to monitor the reference count
    auto Myref = m_spSwapChain->AddRef();
    Myref = m_spSwapChain->Release();

    ULONG RefCount = 0;

    //CRenderStates::ResetAll();

    //if (m_spDepthEnabledStencilState)
    //  RefCount = m_spDepthEnabledStencilState->Release();
    ////assert(RefCount == 0); // FAIL
    //if (m_spDepthDisabledStencilState)
    //  RefCount = m_spDepthDisabledStencilState->Release();
    //assert(RefCount == 0);   // FAIL

    m_spD3DImmediateContext->OMSetRenderTargets(0, 0, 0);

    if (m_spDepthStencilView)
        RefCount = m_spDepthStencilView->Release();
    assert(RefCount == 0); // OK
    if (m_spDepthStencilBuffer)
        RefCount = m_spDepthStencilBuffer->Release();
    assert(RefCount == 0); // OK
    if (m_spRenderTargetView)
        RefCount = m_spRenderTargetView->Release();
    assert(RefCount == 0); // OK

    //m_spRenderTargetView.Reset();
    //m_spDepthStencilView.Reset();
    //m_spDepthStencilBuffer.Reset();
    //m_spDepthDisabledStencilState.Reset();

    //assert(m_spRenderTargetView == nullptr);
    //assert(m_spDepthStencilView == nullptr);
    //assert(m_spDepthStencilBuffer == nullptr);
    //assert(m_spDepthDisabledStencilState == nullptr);

    Myref = m_spSwapChain->AddRef();
    Myref = m_spSwapChain->Release();

    // **** Fails Here after WM_SIZE ****
    // Resize the swap chain and recreate the render target view.
    COMERR(m_spSwapChain->ResizeBuffers(1, m_iClientWidth, m_iClientHeight, DXGI_FORMAT_R8G8B8A8_UNORM, 0),
        "CD3DObject::OnResize() SwapChain Could not resize.");
    ID3D11Texture2D* pBackBuffer;
    COMERR(m_spSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), reinterpret_cast<void**>(&pBackBuffer)),
        "CD3DObject::OnResize() SwapChain could not get backbuffer 0.");
    COMERR(m_spD3DDevice->CreateRenderTargetView(pBackBuffer, 0, m_spRenderTargetView.GetAddressOf()),
        "CD3DObject::OnResize() Could not re-create render target view.");

    Myref = m_spSwapChain->AddRef();
    Myref = m_spSwapChain->Release();

    //ReleaseCOM(pBackBuffer);
    RefCount = pBackBuffer->Release();

    Myref = m_spSwapChain->AddRef();
    Myref = m_spSwapChain->Release();

    // **SNIP**

```

Note: The COMERR macros are for exception handling the return values.enter code here. Thank you for any help or wisdom on this.

***EDIT***

This is the InitDirect3D function:

```
//CALLSTACK_PUT("CD3DObject::InitDirect3D")

//UINT uiCreateDeviceFlags = 0;
// This flag adds support for surfaces with a different color channel ordering
// than the API default. It is required for compatibility with Direct2D.
UINT uiCreateDeviceFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT; // Interop
#if defined(DEBUG) || defined(_DEBUG)
uiCreateDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG;
#endif

// Set feature levels supported by our application
D3D_FEATURE_LEVEL eFeatureLevel1[] =
{
    D3D_FEATURE_LEVEL_11_1,
    D3D_FEATURE_LEVEL_11_0,
    D3D_FEATURE_LEVEL_10_1,
    D3D_FEATURE_LEVEL_10_0,
    D3D_FEATURE_LEVEL_9_3,
    D3D_FEATURE_LEVEL_9_2,
    D3D_FEATURE_LEVEL_9_1
};

// Create Direct3D device and context
ComPtr<ID3D11Device>        spDevice;
ComPtr<ID3D11DeviceContext> spContext;
D3D_FEATURE_LEVEL           stReturnedFeatureLevel;
LOGADDRESS_SP(spDevice.GetAddressOf());
LOGADDRESS_SP(spContext.GetAddressOf());

COMERR(D3D11CreateDevice(nullptr,                   // default adapter
                         D3D_DRIVER_TYPE_HARDWARE,
                         0,                         // no software device
                         uiCreateDeviceFlags,
                         eFeatureLevel1,
                         ARRAYSIZE(eFeatureLevel1),
                         D3D11_SDK_VERSION,
                         &spDevice,
                         &stReturnedFeatureLevel,
                         &spContext),
    "CD3DObject::InitDirect3D()\nD3D11.1 Could not create device.");

if(stReturnedFeatureLevel < D3D_FEATURE_LEVEL_11_0)
{
    MessageBox(m_hMainWnd, "CD3DObject::InitDirect3D()\nThis software needs DirectX 11.1 and is unsupported by your computer.", "Error", MB_OK);
    return false;
}

// Fetch the underlying interfaces and store them:
COMERR(spDevice.As(&m_spD3DDevice), "CD3DObject::InitDirect3D()\nCould not get device as DirectX 11.1.");
COMERR(spContext.As(&m_spD3DImmediateContext), "CD3DObject::InitDirect3D()\nCould not get Context as DirectX 11.1.");

spDevice->Release();
spContext->Release();

LOGADDRESS_SP(m_spD3DDevice.GetAddressOf());
LOGADDRESS_SP(m_spD3DImmediateContext.GetAddressOf());

// This is the earliest the Debug Layer can be created
g_pEngine->CreateDebugLayer();
g_pEngine->GetDebug()->ReportLiveDeviceObjects(D3D11_RLDO_SUMMARY | D3D11_RLDO_DETAIL);

// Set private data
SETPRIVATEDATA(spDevice, "spDevice");
SETPRIVATEDATA(m_spD3DDevice, "CD3DObject::m_spD3DDevice");

HR(m_spD3DDevice->CheckMultisampleQualityLevels(DXGI_FORMAT_R8G8B8A8_UNORM,
                                              4,
                                              &m_ui4xMsaaQuality));
assert(m_ui4xMsaaQuality > 0);

DXGI_SWAP_CHAIN_DESC1 stSwpChainDesc = { 0 };
stSwpChainDesc.Width = 0;
stSwpChainDesc.Height             = 0;
stSwpChainDesc.Format             = DXGI_FORMAT_B8G8R8A8_UNORM;
stSwpChainDesc.Stereo             = false;
stSwpChainDesc.SampleDesc.Count   = 1;
stSwpChainDesc.SampleDesc.Quality = 0;
stSwpChainDesc.BufferUsage        = DXGI_USAGE_RENDER_TARGET_OUTPUT;
stSwpChainDesc.BufferCount        = 1;                                  // Used to be 1
stSwpChainDesc.Scaling            = DXGI_SCALING_STRETCH;
stSwpChainDesc.SwapEffect         = DXGI_SWAP_EFFECT_DISCARD;
stSwpChainDesc.Flags              = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;
LOGADDRESS(stSwpChainDesc);

// Use 4X MSAA?
if(m_bEnable4xMsaa)
{
    stSwpChainDesc.SampleDesc.Count   = 4;
    stSwpChainDesc.SampleDesc.Quality = m_ui4xMsaaQuality-1;
}
// No MSAA
else
{
    stSwpChainDesc.SampleDesc.Count   = 1;
    stSwpChainDesc.SampleDesc.Quality = 0;
}

Microsoft::WRL::ComPtr<IDXGIDevice> spDXGIDevice;
m_spD3DDevice.As(&spDXGIDevice);

IDXGIAdapter* pDxgiAdapter = 0;
HR(spDXGIDevice->GetParent(__uuidof(IDXGIAdapter), (void**)&pDxgiAdapter));

IDXGIFactory2* pDxgiFactory = 0;
HR(pDxgiAdapter->GetParent(__uuidof(IDXGIFactory), (void**)&pDxgiFactory));
pDxgiFactory->CreateSwapChainForHwnd(m_spD3DDevice.Get(), m_hMainWnd, &stSwpChainDesc, nullptr, nullptr, &m_spSwapChain);

g_pEngine->GetDebug()->ReportLiveDeviceObjects(D3D11_RLDO_SUMMARY | D3D11_RLDO_DETAIL);

ReleaseCOM(pDxgiAdapter);
ReleaseCOM(pDxgiFactory);

spDXGIDevice->Release();

LOGADDRESS_SP(spDXGIDevice.GetAddressOf());
LOGADDRESS_SP(pDxgiAdapter);
LOGADDRESS_SP(pDxgiFactory);

g_pEngine->GetDebug()->ReportLiveDeviceObjects(D3D11_RLDO_SUMMARY | D3D11_RLDO_DETAIL);

OnResize();

SETPRIVATEDATA(m_spD3DImmediateContext, "CD3DObject::m_spD3DImmediateContext");
SETPRIVATEDATA(m_spSwapChain,           "CD3DObject::m_spSwapChain");
SETPRIVATEDATA(m_spDepthStencilBuffer,  "CD3DObject::m_spDepthStencilBuffer");
SETPRIVATEDATA(m_spRenderTargetView,    "CD3DObject::m_spRenderTargetView");
SETPRIVATEDATA(m_spDepthStencilView,    "CD3DObject::m_spDepthStencilView");
SETPRIVATEDATA(m_spDepthEnabledStencilState,  "CD3DObject::m_spDepthEnabledStencilState");
SETPRIVATEDATA(m_spDepthDisabledStencilState, "CD3DObject::m_spDepthDisabledStencilState");
//CALLSTACK_REMOVE

```

This is the ONResize function: Note that the reason I do so many Debug reports is to compare them before and after -\>release-ing (etc).

```
    //CALLSTACK_PUT("CD3DObject::OnResize")
try
{
    assert(m_spD3DImmediateContext);
    assert(m_spD3DDevice);
    assert(m_spSwapChain);

    //ReleaseCOM(m_pRenderTargetView);
    //ReleaseCOM(m_pDepthStencilView);
    //ReleaseCOM(m_spDepthStencilBuffer);
    //m_spRenderTargetView.Reset();
    //m_spDepthStencilView.Reset();
    //m_spDepthStencilBuffer.Reset();
    //m_spDepthDisabledStencilState.Reset();

    // This is used to monitor the reference count
    auto Myref = m_spSwapChain->AddRef();
    Myref = m_spSwapChain->Release();

    ULONG RefCount = 0;
    m_spD3DImmediateContext->ClearState();

    CRenderStates::ResetAll();

    if (m_spDepthEnabledStencilState)
        RefCount = m_spDepthEnabledStencilState->Release();
    assert(RefCount == 0); // FAILS == 1
    if (m_spDepthDisabledStencilState)
        RefCount = m_spDepthDisabledStencilState->Release();
    assert(RefCount == 0); // FAILS == 1
    if (m_spDepthEnabledStencilState)
        RefCount = m_spDepthEnabledStencilState->Release();
    assert(RefCount == 0); // OK == 0
    if (m_spDepthDisabledStencilState)
        RefCount = m_spDepthDisabledStencilState->Release();
    assert(RefCount == 0); // OK == 0

    m_spD3DImmediateContext->OMSetRenderTargets(0, 0, 0);

    if (m_spDepthStencilView)
        RefCount = m_spDepthStencilView->Release();
    assert(RefCount == 0);
    if (m_spDepthStencilBuffer)
        RefCount = m_spDepthStencilBuffer->Release();
    assert(RefCount == 0);
    if (m_spRenderTargetView)
        RefCount = m_spRenderTargetView->Release();
    assert(RefCount == 0);

    //m_spRenderTargetView.Reset();
    //m_spDepthStencilView.Reset();
    //m_spDepthStencilBuffer.Reset();
    //m_spDepthDisabledStencilState.Reset();

    //assert(m_spRenderTargetView == nullptr);
    //assert(m_spDepthStencilView == nullptr);
    //assert(m_spDepthStencilBuffer == nullptr);
    //assert(m_spDepthDisabledStencilState == nullptr);

    //LOGADDRESS_SP(m_spD3DImmediateContext.GetAddressOf());
    //LOGADDRESS_SP(m_spSwapChain.GetAddressOf());
    //LOGADDRESS_SP(m_spDepthStencilBuffer.GetAddressOf());
    //LOGADDRESS_SP(m_spRenderTargetView.GetAddressOf());
    //LOGADDRESS_SP(m_spDepthStencilView.GetAddressOf());
    //LOGADDRESS_SP(m_spDepthEnabledStencilState.GetAddressOf());
    //LOGADDRESS_SP(m_spDepthDisabledStencilState.GetAddressOf());
    //LOGADDRESS_SP(m_spSwapChain.GetAddressOf());
    LOGADDRESS_SP(m_spD3DDevice.Get());
    LOGADDRESS_SP(m_spD3DImmediateContext.Get());
    LOGADDRESS_SP(m_spSwapChain.Get());
    LOGADDRESS_SP(m_spDepthStencilBuffer.Get());
    LOGADDRESS_SP(m_spRenderTargetView.Get());
    LOGADDRESS_SP(m_spDepthStencilView.Get());
    LOGADDRESS_SP(m_spDepthEnabledStencilState.Get());
    LOGADDRESS_SP(m_spDepthDisabledStencilState.Get());
    LOGADDRESS_SP(m_spSwapChain.Get());

    Myref = m_spSwapChain->AddRef();
    Myref = m_spSwapChain->Release();

    g_pEngine->GetDebug()->ReportLiveDeviceObjects(D3D11_RLDO_SUMMARY | D3D11_RLDO_DETAIL);

    // Resize the swap chain and recreate the render target view.
    COMERR(m_spSwapChain->ResizeBuffers(1, m_iClientWidth, m_iClientHeight, DXGI_FORMAT_R8G8B8A8_UNORM, 0),
        "CD3DObject::OnResize() SwapChain Could not resize.");
    ID3D11Texture2D* pBackBuffer;
    COMERR(m_spSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), reinterpret_cast<void**>(&pBackBuffer)),
        "CD3DObject::OnResize() SwapChain could not get backbuffer 0.");
    COMERR(m_spD3DDevice->CreateRenderTargetView(pBackBuffer, 0, m_spRenderTargetView.GetAddressOf()),
        "CD3DObject::OnResize() Could not re-create render target view.");

    g_pEngine->GetDebug()->ReportLiveDeviceObjects(D3D11_RLDO_SUMMARY | D3D11_RLDO_DETAIL);

    Myref = m_spSwapChain->AddRef();
    Myref = m_spSwapChain->Release();

    //ReleaseCOM(pBackBuffer);
    LOGADDRESS_SP(pBackBuffer);
    RefCount = pBackBuffer->Release();
    RefCount = pBackBuffer->Release();
    LOGADDRESS_SP(pBackBuffer);
    //assert(RefCount == 0);

    g_pEngine->GetDebug()->ReportLiveDeviceObjects(D3D11_RLDO_SUMMARY | D3D11_RLDO_DETAIL);

    Myref = m_spSwapChain->AddRef();
    Myref = m_spSwapChain->Release();

    // Create the depth/stencil buffer and view.
    D3D11_TEXTURE2D_DESC stDepthStencilDesc;

    stDepthStencilDesc.Width = m_iClientWidth;                // Width of texture in texels
    stDepthStencilDesc.Height = m_iClientHeight;                  // Hieght of texture in texels
    stDepthStencilDesc.MipLevels = 1;                             // Mipmap levels
    stDepthStencilDesc.ArraySize = 1;                             // Number of textures in a texture array
    stDepthStencilDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; // 24bits depth [0,1] 8 bits stencil [0,255]

    // Use 4X MSAA? --must match swap chain MSAA values.
    // AD This is set to false in this constructor.
    if (m_bEnable4xMsaa)
    {
        stDepthStencilDesc.SampleDesc.Count = 4;
        stDepthStencilDesc.SampleDesc.Quality = m_ui4xMsaaQuality - 1;
    }
    // No MSAA
    else
    {
        stDepthStencilDesc.SampleDesc.Count = 1;
        stDepthStencilDesc.SampleDesc.Quality = 0;
    }

    stDepthStencilDesc.Usage = D3D11_USAGE_DEFAULT;   // Texture is: GPU only Read/Write
    stDepthStencilDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL; // How the texture is bound to the pipeline
    stDepthStencilDesc.CPUAccessFlags = 0;                        // How CPU will access the texture
    stDepthStencilDesc.MiscFlags = 0;                         // Optional - N/A to depth/stencil buffer

    //ID3D11Texture2D* pDSB = m_spDepthStencilBuffer.GetInterfacePtr();
    COMERR(m_spD3DDevice->CreateTexture2D(&stDepthStencilDesc,       // Description of texture to create
        0,                         // Pointer to initial data to fill texture with
        //m_spDepthStencilBuffer.ReleaseAndGetAddressOf())); // Return pointer to depth/stencil buffer
        m_spDepthStencilBuffer.GetAddressOf()), // Return pointer to depth/stencil buffer
        //&pDSB));                   // Return pointer to depth/stencil buffer
        "CD3DObject::OnResize() Could not create 2D Texture.");

    assert(m_spDepthStencilBuffer);

    //ID3D11DepthStencilView* pDSV = m_spDepthStencilView.GetInterfacePtr();
    COMERR(m_spD3DDevice->CreateDepthStencilView(m_spDepthStencilBuffer.Get(),  // Resource we want to create as view to
        0,                       // Null if we already specified the data type of this d/s buffer
        m_spDepthStencilView.GetAddressOf()), // Return depth/stencil view
        //&pDSV));                 // Return depth/stencil view
        "CD3DObject::OnResize() Could not create depth stencil view.");

    assert(m_spDepthStencilView);

    //ID3D11RenderTargetView* pRTV = m_spRenderTargetView.GetInterfacePtr();
    // Bind to the 'Output Merger' Stage
    // Bind the render target view and depth/stencil view to the pipeline.
    m_spD3DImmediateContext->OMSetRenderTargets(1,                     // Number of render targets we are binding
        m_spRenderTargetView.GetAddressOf(), // First of array of render target views
        //&pRTV,                 // First of array of render target views
        m_spDepthStencilView.Get()); // Pointer to the d/s view to bind

    //assert(m_spRenderTargetView);
    //assert(pRTV);
    //assert(m_spDepthStencilView);

    // Set the viewport transform.
    m_ScreenViewport.TopLeftX = 0;
    m_ScreenViewport.TopLeftY = 0;
    m_ScreenViewport.Width = static_cast<float>(m_iClientWidth);
    m_ScreenViewport.Height = static_cast<float>(m_iClientHeight);
    m_ScreenViewport.MinDepth = 0.0f;
    m_ScreenViewport.MaxDepth = 1.0f;

    m_spD3DImmediateContext->RSSetViewports(1, &m_ScreenViewport);

    /**** ****** ****** ******* ******* ***** **/
    //      (Re) create the DepthEnabledStencilState &
    //      DepthDisabledStencilState
    /**** ****** ****** ******* ******* ***** **/

    D3D11_DEPTH_STENCIL_DESC stDepthEnabledStencilDesc;

    // Initialize the description of the stencil state.
    ZeroMemory(&stDepthEnabledStencilDesc, sizeof(stDepthEnabledStencilDesc));

    // Set up the description of the stencil state.
    stDepthEnabledStencilDesc.DepthEnable = true;
    stDepthEnabledStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
    stDepthEnabledStencilDesc.DepthFunc = D3D11_COMPARISON_LESS;

    stDepthEnabledStencilDesc.StencilEnable = true;
    stDepthEnabledStencilDesc.StencilReadMask = 0xFF;
    stDepthEnabledStencilDesc.StencilWriteMask = 0xFF;

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

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

    // Create the depth stencil state.
    COMERR(m_spD3DDevice.Get()->CreateDepthStencilState(&stDepthEnabledStencilDesc,
        m_spDepthEnabledStencilState.GetAddressOf()),
        "CD3DObject::OnResize() Could not create depth 'enabled' stencil state.");

    // Set the depth stencil state.
    m_spD3DImmediateContext.Get()->OMSetDepthStencilState(m_spDepthEnabledStencilState.Get(), 1);

    /* ***  **  *** ** *** ** *** ** *** ** *** **
    Initialise the Disabled depth stencil state
    */ // ***  **  *** ** *** ** *** ** *** ** ***

    D3D11_DEPTH_STENCIL_DESC stDepthDisabledStencilDesc;

    /*
    Here we setup the description of the depth stencil.
    Notice the only difference between this new depth stencil
    and the old one is the DepthEnable is set to false here
    for 2D drawing.
    */

    // Clear the second depth stencil state before setting the parameters.
    ZeroMemory(&stDepthDisabledStencilDesc, sizeof(stDepthDisabledStencilDesc));

    // Now create a second depth stencil state which turns off the Z buffer for 2D rendering.  The only difference is
    // that DepthEnable is set to false, all other parameters are the same as the other depth stencil state.
    stDepthDisabledStencilDesc.DepthEnable = false;
    stDepthDisabledStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
    stDepthDisabledStencilDesc.DepthFunc = D3D11_COMPARISON_LESS;
    stDepthDisabledStencilDesc.StencilEnable = true;
    stDepthDisabledStencilDesc.StencilReadMask = 0xFF;
    stDepthDisabledStencilDesc.StencilWriteMask = 0xFF;
    stDepthDisabledStencilDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
    stDepthDisabledStencilDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR;
    stDepthDisabledStencilDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
    stDepthDisabledStencilDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
    stDepthDisabledStencilDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
    stDepthDisabledStencilDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR;
    stDepthDisabledStencilDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
    stDepthDisabledStencilDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS;

    // Create the state using the device.
    COMERR(m_spD3DDevice.Get()->CreateDepthStencilState(&stDepthDisabledStencilDesc,
        m_spDepthDisabledStencilState.GetAddressOf()),
        "CD3DObject::OnResize() Could not create depth disabled stencil state.");

}
catch (CException e)
{
    e.ExceptionMsgBox();
    exit(E_FAIL);
}
catch (std::exception e)
{
    CException x(e.what(), __FILE__, S__LINE__, (HRESULT)0);
    x.ExceptionMsgBox();
    exit(E_FAIL);
}
//CALLSTACK_REMOVE

```

Here is the DebugReport - right when OnResize is called - not the first time but during a WM\_SIZE - once the user has resized the window. Report right before the swapchain resize:

> D3D11 WARNING: Live ID3D11Device at 0x000000000031D8C0, Name: CD3DObject::m\_spD3DDevice, Refcount: 8 \[ STATE\_CREATION WARNING #441: LIVE\_DEVICE\] D3D11 WARNING: Live ID3D11Context at 0x0000000000323A00, Name: CD3DObject::m\_spD3DImmediateContext, Refcount: 0, IntRef: 1 \[ STATE\_CREATION WARNING #2097226: LIVE\_CONTEXT\] D3D11 WARNING: Live ID3DDeviceContextState at 0x000000000033B7A0, Refcount: 0, IntRef: 1 \[ STATE\_CREATION WARNING #3145742: LIVE\_DEVICECONTEXTSTATE\] D3D11 WARNING: Live ID3D11BlendState at 0x0000000000346B00, Refcount: 0, IntRef: 1 \[ STATE\_CREATION WARNING #435: LIVE\_BLENDSTATE\] D3D11 WARNING: Live ID3D11DepthStencilState at 0x00000000003470C0, Refcount: 0, IntRef: 1 \[ STATE\_CREATION WARNING #436: LIVE\_DEPTHSTENCILSTATE\] D3D11 WARNING: Live ID3D11RasterizerState at 0x00000000003472E0, Refcount: 0, IntRef: 1 \[ STATE\_CREATION WARNING #437: LIVE\_RASTERIZERSTATE\] D3D11 WARNING: Live ID3D11Sampler at 0x0000000000347600, Refcount: 0, IntRef: 1 \[ STATE\_CREATION WARNING #434: LIVE\_SAMPLER\] D3D11 WARNING: Live ID3D11Query at 0x0000000000347880, Refcount: 0, IntRef: 1 \[ STATE\_CREATION WARNING #438: LIVE\_QUERY\] D3D11 WARNING: Live IDXGISwapChain at 0x0000000000347A60, Name: CD3DObject::m\_spSwapChain, Refcount: 1 \[ STATE\_CREATION WARNING #442: LIVE\_SWAPCHAIN\] D3D11 WARNING: Live ID3D11Texture2D at 0x00000000003481C0, Refcount: 0, IntRef: 2 \[ STATE\_CREATION WARNING #425: LIVE\_TEXTURE2D\] D3D11 WARNING: Live ID3D11RenderTargetView at 0x00000000003487D0, Refcount: 1, IntRef: 0 \[ STATE\_CREATION WARNING #428: LIVE\_RENDERTARGETVIEW\] D3D11 WARNING: Live ID3D11RenderTargetView at 0x0000000000348BD0, Name: CD3DObject::m\_spRenderTargetView, Refcount: 0, IntRef: 0 \[ STATE\_CREATION WARNING #428: LIVE\_RENDERTARGETVIEW\] D3D11 WARNING: Live ID3D11Texture2D at 0x0000000000348DF0, Refcount: 1, IntRef: 0 \[ STATE\_CREATION WARNING #425: LIVE\_TEXTURE2D\] D3D11 WARNING: Live ID3D11Texture2D at 0x0000000000349170, Name: CD3DObject::m\_spDepthStencilBuffer, Refcount: 0, IntRef: 2 \[ STATE\_CREATION WARNING #425: LIVE\_TEXTURE2D\] D3D11 WARNING: Live ID3D11DepthStencilView at 0x00000000003494F0, Refcount: 1, IntRef: 0 \[ STATE\_CREATION WARNING #429: LIVE\_DEPTHSTENCILVIEW\] D3D11 WARNING: Live ID3D11DepthStencilView at 0x0000000000349720, Name: CD3DObject::m\_spDepthStencilView, Refcount: 0, IntRef: 0 \[ STATE\_CREATION WARNING #429: LIVE\_DEPTHSTENCILVIEW\] D3D11 WARNING: Live ID3D11DepthStencilState at 0x00000000003499A0, Name: CD3DObject::m\_spDepthEnabledStencilState, Refcount: 0, IntRef: 0 \[ STATE\_CREATION WARNING #436: LIVE\_DEPTHSTENCILSTATE\] D3D11 WARNING: Live ID3D11Texture2D at 0x000000000034EAB0, Refcount: 0, IntRef: 1 \[ STATE\_CREATION WARNING #425: LIVE\_TEXTURE2D\] D3D11 WARNING: Live ID3D11Context : 1 \[ STATE\_CREATION WARNING #422: LIVE\_OBJECT\_SUMMARY\] D3D11 WARNING: Live ID3DDeviceContextState : 1 \[ STATE\_CREATION WARNING #422: LIVE\_OBJECT\_SUMMARY\] D3D11 WARNING: Live ID3D11BlendState : 1 \[ STATE\_CREATION WARNING #422: LIVE\_OBJECT\_SUMMARY\] D3D11 WARNING: Live ID3D11DepthStencilState : 2 \[ STATE\_CREATION WARNING #422: LIVE\_OBJECT\_SUMMARY\] D3D11 WARNING: Live ID3D11RasterizerState : 1 \[ STATE\_CREATION WARNING #422: LIVE\_OBJECT\_SUMMARY\] D3D11 WARNING: Live ID3D11Sampler : 1 \[ STATE\_CREATION WARNING #422: LIVE\_OBJECT\_SUMMARY\] D3D11 WARNING: Live ID3D11Query : 1 \[ STATE\_CREATION WARNING #422: LIVE\_OBJECT\_SUMMARY\] D3D11 WARNING: Live IDXGISwapChain : 1 \[ STATE\_CREATION WARNING #422: LIVE\_OBJECT\_SUMMARY\] D3D11 WARNING: Live ID3D11Texture2D : 4 \[ STATE\_CREATION WARNING #422: LIVE\_OBJECT\_SUMMARY\] D3D11 WARNING: Live ID3D11RenderTargetView : 2 \[ STATE\_CREATION WARNING #422: LIVE\_OBJECT\_SUMMARY\] D3D11 WARNING: Live ID3D11DepthStencilView : 2 \[ STATE\_CREATION WARNING #422: LIVE\_OBJECT\_SUMMARY\]

# Answer
The actual answer I found it to be was based on a cumulation of both Josh Petrie's and Chuck Walbourn's answer/comments. Using LiveReporting both before and after each call in the resize function I was able to determine the area of the problem - Which was the extra Texture2D being created. It turns out that (I think) the ComPtr somehow instatiates one just by creating the pointer. Most likely statically.

```
ComPtr<ID3D11Texture2D> spBackBuffer;

```

Then I call ReleaseAndGetAddressOf() not only on the spBackBuffer but also on the RenderTargetView (Partial Qudos to the great and powerful Chuck Walbourn). For some reason the DepthBuffer and DepthView do not need it. They are released in the first instance before the resize anyway.

```
    g_pEngine->GetDebug()->ReportLiveDeviceObjects(D3D11_RLDO_SUMMARY | D3D11_RLDO_DETAIL);
    // Resize the swap chain and recreate the render target view.
    COMERR(m_spSwapChain->ResizeBuffers(1, m_iClientWidth, m_iClientHeight, DXGI_FORMAT_R8G8B8A8_UNORM, 0),
        "CD3DObject::OnResize() SwapChain Could not resize.");
    g_pEngine->GetDebug()->ReportLiveDeviceObjects(D3D11_RLDO_SUMMARY | D3D11_RLDO_DETAIL);
    //ID3D11Texture2D* pBackBuffer;
    ComPtr<ID3D11Texture2D> spBackBuffer;
    //COMERR(m_spSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), reinterpret_cast<void**>(&pBackBuffer)),
    COMERR(m_spSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), reinterpret_cast<void**>(spBackBuffer.ReleaseAndGetAddressOf())),
        "CD3DObject::OnResize() SwapChain could not get backbuffer 0.");
    g_pEngine->GetDebug()->ReportLiveDeviceObjects(D3D11_RLDO_SUMMARY | D3D11_RLDO_DETAIL);
    //COMERR(m_spD3DDevice->CreateRenderTargetView(pBackBuffer, 0, m_spRenderTargetView.ReleaseAndGetAddressOf()),
    COMERR(m_spD3DDevice->CreateRenderTargetView(spBackBuffer.Get(), 0, m_spRenderTargetView.ReleaseAndGetAddressOf()),
        "CD3DObject::OnResize() Could not re-create render target view.");
    g_pEngine->GetDebug()->ReportLiveDeviceObjects(D3D11_RLDO_SUMMARY | D3D11_RLDO_DETAIL);

```

After the WM\_SIZE and resize is called, the LiveReport (detail not summary) shows what outstanding objects need to be released. Internal refs are ok its the external ones I needed to worry about. Ideally all the DepthStates/DepthView/DepthBuffer/RenderTarget and hey presto resizing worked.

Thank you all that helped - I really learned a lot be going over this.
> 0 votes

# Answer
The `ID3D11Debug` interface allows you to `ReportLiveObjects`, which is a useful way to acquire a breakdown of the live D3D objects at any given point in time. This report will show you the total reference count to an interface, broken down into the external (your) and internal (D3D's) numbers. This will let you confirm that

* you have actually released all your references to an object at a given point in time and,
* if D3D is still holding a reference to an object internally

The latter may mean that you are holding a reference to an interface which itself, internally, holds a reference to the swap chain.

To get an `ID3D11Debug` interface, use `QueryInterface` on your device object using the `IID_ID3D11Debug` ID. Then call `ReportLiveObjects` on the resulting interface using the `D3D11_RLDO_DETAIL` flag. Note that you must also have enabled the debug layer when creating the device itself.

The output will consist of a lot of lines like:

```
D3D11 WARNING:  Live <type> at <address>, Refcount: X, IntRef: Y [STATE_CREATION WARNING #nnn: LIVE_<type>]

```

This shows you the object type, it's address, external and internal reference count.

You should always get at least some output from this function when you call it, because the debug interface itself (and thus the device) will be alive and thus reported. Unfortunately there is no way to get a report on the specific interfaces holding a given interface alive, you simply have to work backwards manually through the report.
> 4 votes

# Answer
I think the problem is your use of `m_spD3DImmediateContext->OMSetRenderTargets(0, 0, 0);` which doesn't do anything at all to the render target view binding--it just clears the depth/stencil view. To clear the render target settings, you should use the following assuming you aren't using Multiple Render Targets (MRTs):

```
ID3D11RenderTargetView* nullViews [] = { nullptr };
m_spD3DImmediateContext->OMSetRenderTargets(1, nullViews, nullptr);

```

If you are using MRTs, you may need as many `nullViews` entries as you have maximum MRTs with a worst case of:

```
ID3D11RenderTargetView* nullViews [D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT] = { 0 };
m_spD3DImmediateContext->OMSetRenderTargets(D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT, nullViews, nullptr);

```

However, it is probably sufficient to do the first form assuming you never bind the swapchain backbuffer RTV anywhere but the 0th slot.

Also, be sure to use the following just before you start doing the swap chain resize:

```
m_spD3DImmediateContext->Flush();

```

This is actually noted on MSDN as a critical step for resizing because of deferred destruction of objects.

If you look at the code for handling resize in the Direct3D Win32 Game Visual Studio template, you'll see that I do the following sequence before the use of DXGI's `ResizeBuffers` for resizing the swap chain:

```
// Clear the previous window size specific context.
ID3D11RenderTargetView* nullViews [] = { nullptr };
m_d3dContext->OMSetRenderTargets(ARRAYSIZE(nullViews), nullViews, nullptr);
m_renderTargetView.Reset();
m_depthStencilView.Reset();
m_d3dContext->Flush();

```
> 0 votes

---
Tags: directx11
---


# Question
Title: Extract smaller frustum from camera frustum?
**Background:**

I was thinking of implementing multiselection by performing a frustum culling on a sub-part of the screen.

**Problem:**

Given total screensize, a rectangle on the screen (pos, size), and the original camera frustum (projection, pos, rot), how can I construct a sub frustum corresponding to the given rectangle?

**UPDATE:**

To be implementation specific, I am using DirectX and in DirecXMath there is a BoundingSphere vs BoundingFrustum intersection currently used in my ordinary frustum culling. http://msdn.microsoft.com/en-us/library/windows/desktop/hh855914(v=vs.85).aspx

So presumably given a new projection matrix and a new rotation I would be able to construct a new BoundingFrustum to use in my ordinary frustum culling.

# Answer
> 1 votes
In my first attempt, I created a new projection matrix for the smaller window, and then tried to rotate the frustum using LookAt, this almost worked but had some distortion when tilting up or down.

However, using a different approach it turns out the problem was quite easy to solve in DirectX. The BoundingFrustum class that I used (while It can be constructed from a projection matrix) actually consists of a nearplane, farplane, and 4 different sloops. By multiplying the 4 sloops with the ratio between the sub window and parent window, I get a working subfrustum.

**Solution**

Here is a code sample in DirectX with some functionality hidden, but it should not be to hard to follow.

```
BoundingFrustum getSubFrustum( FloatRectangle& window, FloatRectangle& sub_window )
{
    // Construct bounding frustum from camera projection
    BoundingFrustum f(m_mat_projection);
    f.Origin = m_position;
    f.Orientation = m_rotation;

    // Translates the rectangle from "0 .. 2x", to "-x .. x"
    // making center 0,0 in the new coordinate system
    Float2 center = window.center();
    window.translate(-center);
    sub_window.translate(-center);

    // Adjust bounding slopes to match sub window
    float left = sub_window.position.x/window.position.x;
    float right = (sub_window.position.x + sub_window.size.x)/(window.position.x + window.size.x);
    float bottom =  sub_window.position.y/window.position.y;
    float top =  (sub_window.position.y + sub_window.size.y)/(window.position.y + window.size.y);
    f.LeftSlope *= left;
    f.RightSlope *= right;
    f.TopSlope *= top;
    f.BottomSlope *= bottom;

    return f;
}

```
* It works! However, It feels like I have not understood the problem. I would still love to hear a solution using the projection matrix only, so it would be possible to use the projection while actually drawing.

# Answer
> 2 votes
I'm not familiar with DirectX, but the BoundingFrustum docs you link to say that it can be constructed from a projection matrix.

All you need to do, then, is multiply your *actual* projection matrix by a matrix which (if you used it to draw with) would scale/translate the graphics so that the rectangle you want fills the viewport, then use that matrix product to construct a BoundingFrustum.

The matrix should just be an appropriate scale and translation in X and Y coordinates.

You can test it out by actually drawing using the modified projection matrix.

# Answer
> 0 votes
Construct a new projection matrix, with smaller FOV and near/far planes shifted towards the middle. Then build your shrinked Frustum out of it - simple as that.

---
Tags: opengl, 3d, directx, camera, frustum
---


# Question
Title: How can i calculate that normal lays in same part of plane with point?
I.e. n0 for A and n1 for B. Plane divided by plane CD.

# Answer
> 1 votes
First, find the center:

```
p0 = (C + D) * 0.5

```

Now, take the relative vector from the center to the point in question:

```
p1 = (X - p0)

```

Finally, take the dot product with the normals you might want:

```
d0 = n0.dot(p1)
d1 = n1.dot(p1)
...
etc.

```

Then, check to see if its greater than zero

```
abovePlane0 = d0 > 0
abovePlane1 = d1 > 0

```

... etc.

---
Tags: 2d, geometry, trigonometry
---


# Question
Title: HLSL Pixel Shader - Color depending on condition
I am new to shaders and HLSL so bare with me on this one.

I have a 2D tile map in my game and want to create a mini-map, at first I was just copying all the data from one sprite batch to another and rendering it in a smaller camera. This obviously has a performance issue.

So I want to make a mini-map that is composed of coloured pixels depending on what is in that particular cell.

I have a basic shader going at the moment that converts tex coordinates to pixel position but now I need a way to determine what color to set it. My instant decision was to simply pass in a 2d array of colors and grab the color using the x and y coordinate of the pixel, this crashed lol.

Here is what I have so far for the shader:

```
sampler s0;

// The width and height of the texture being sampled
int width, height;

float4 PixelShaderFunction(float2 coords : TEXCOORD0) : COLOR0
{
    float4 color = tex2D(s0, coords);
    // Covert the tex coordinates to pixel coordinates
    int2 tc = int2(width * coords.x, height * coords.y);

    // Here I need to do some sort of check or something?

    return color;
}

technique Technique1
{
    pass Pass1
    {
        PixelShader = compile ps_2_0 PixelShaderFunction();
    }
}

```

How can I pass the color data to the pixel shader so it knows what color to set each pixel? *I already know how to pass data but not sure how I can represent that data to pass it*.

My map is every changing and units are moving around constantly, so the data will be passed in almost every frame.

# Answer
> 1 votes
I think it's bad idea pass tile map to shader. Match better will be just create bitmap and initialize colors pixel-by-pixel. Create bitmap with same size as your tilemap has and then draw part of them.

Create minimap bitmap:

```
 Bitmap miniMapBitmap = new Bitmap(worldWidth, worldHeight);
    for (int x = 0; x < worldWidth; x++)
    {
        for (int y = 0; y < worldHeight; y++)
        {
            miniMapBitmap.SetPixel(x, y, GetMiniMapColor(x, y)); // place for conditions :D
        }
    }

```

Create Texture2D from bitmap:

```
Texture2D miniMapTexture = null;
using (MemoryStream stream = new MemoryStream() )
{
    bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
    stream.Seek(0, SeekOrigin.Begin);
    miniMapTexture = Texture2D.FromFile(GraphicsDevice, stream);
}

```

Draw part of minimap texture corresponding to visible tiles (for example):

```
spritebatch.Draw(
    miniMapTexture,
    miniMapPosition,
    new Rectangle(cameraOffsetX, cameraOffsetY, screenWidth, screenHeight),
    Color.White);

```

# Answer
> 0 votes
In my game, I do this by setting UVS in vertex data and drawing a mesh for the map using texture coords from the vertex data. Basically:

* Create a tile map that is the same aspect ratio as the sprite sheet you are using to draw your current tile map; where each pixel represents a tile.
* Pass this to the shader.
* Create a vertex buffer that is just a mesh representing your tile map. You can do this either by creating a mesh grid filled with triangles, or by drawing the map as a point set.
* Each vertex's UV coordinates are defined by its tile type.
* The fragment shader looks up into the tile map color sheet to determine what color to draw.
* Render the entire thing to a render target with an orthographic camera. The contents of the render target are now your mini-map.

Technically, you only need to render this once each time the map changes, but I render it every frame in my game so I can do things like have a 3D effect, or have animated bits of the mini-map.

---
Tags: xna, shaders, tilemap
---


# Question
Title: Problem with 2D matrix transform og shapes
I have set myself onto the task of creating a class BaseObject, which represents a graphics object with an associated shape as the member variable shape, which is a pointer an object Polygon. I'll provide their declarations here, together with the relevant implementations of the functions I am certain is causing my problem. My problem? As simple as 2D matrix transformations are, they seem to distort my shapes in ways I do not like. I am using the SDL2 graphics library for this problem. Here is the declaration for the BaseObject class.

```
class BaseObject : public Entity
{
protected:
  Polygon shape; // Pointer to a shape
  static uint baseObjectCount; // Useless variable?
  Vector2 posVec; //Position vector
public:
// Positioning and geometry
  Vector2 positionRelativeTo(const BaseObject &other) const;
  double distanceTo(const BaseObject &other) const;

// Get, set, ready!!!!
  Vector2 getPos() const;
  void setPos(Vector2 newPosVector);
  void relPos(Vector2 relPosVector);

// Geometric transforms. Simple and temporary interface with the
// Polygon class.
  void rotate(double theta);
  void scale(double ratio);

// Return a pointer to the shape.
  Polygon* getShape();

// Rendering and game state interface
  virtual void setShape(Polygon &targetShape);
  virtual void render();
  virtual void update();

//Constructors and destructors
  BaseObject();
  BaseObject(Vector2 initPos);
  BaseObject(const BaseObject& other);
  ~BaseObject();
};

```

The declaration of the Polygon class.

```
class Polygon
{
protected:
    SDL_Renderer* renderer;
    Vector2 *vertices = NULL;
    Vector2 *posVec; //Relative position.
    uint numVertices;

public:
    void createCircle(double radius, uint numVertices);

    SDL_Point* makeSDL_PointArray();
    void setPosVec(Vector2 &argPosVec);
    void setRenderer(SDL_Renderer*);
    void setVertices(Vector2* vertices, uint numVertices);
    void translate(Vector2 translationVector);
    void rotate(double theta);
    void scale(double ratio);
    void draw();

    Polygon();
    Polygon(Vector2* vertices, uint numVertices);
    Polygon(const Polygon &other);
};

```

The Polygon class uses an array of Vector2 objects, which is my own implementation of 2D vectors. The classes in themselves work fine, so I won't create a wall of definitions of functions. Rather, I'd like to present you my code for the transformation.

```
void Vector2::transform(double a, double b, double c, double d)
{
    x = a*x + b*y;
    y = c*x + d*y;
}

```

The function alters the x and y coordinates of the Vector2 instance. Each Vector2 associated with the Polygon class is relative to the origin, and on paper this transformation works fine. The transform assumes the following structure of the transformation matrix, and each argument a, b, c and d corresponds to the values a, b, c and d in this matrix.

```
[ a, b ]   [ x ]
[      ] * [   ]
[ c, d ]   [ y ]

```

The function used to rotate a class Polygon is the following:

```
void Polygon::rotate(double theta)
{
    for (uint i = 0; i < numVertices; i++)
    {
        vertices[i].transform(cos(theta), sin(-theta), sin(theta), cos(theta));
    }
}

```

Here, the transform function of the Vector2 class is used as a base for implementing the rotation matrix. By looping through every vertex / Vector2 representing the polygon, this transformation should do the job of rotating the "polygon" around the origins. However, when using this function, the circle drawn gets distortes as if being skewed. I did think this might have to do with the Y-axis being inverted in computer graphics, but testing the transformation matrix on paper produces the desired result on vectors no matter the orientation of the y-axis. My assumption is that the distortion is caused by errors in the trigonometric function in the , but a double precision value should not make a 90 degree (2Pi/4 rad) rotation transform a circle into a squished ellipse. This leads me to again believe this is related to the inverted y-axis and errors in my linear algebra. Ideas? I do not think all of the code need sto be posted here, but I'd be willing to share more of it if my ideas are completely off the table.

# Answer
> 1 votes
The **transform** method of **Vector** class is wrong. If you want to perform a transformation of the vector that is equivalent to multiplying a vector by a transform matrix, you should modify your code as follows:

```
void Vector2::transform(double a, double b, double c, double d)
{
   double newX = a*x + b*y;
   y = c*x + d*y;
   x = newX;
}

```

---
Tags: c++, sdl, graphics-programming, linear-algebra, transformation
---


# Question
Title: How can I make a "random" generator that is biased by prior events?
I am looking to implement a chance based system which is biased by prior event.

Background: Some years back, I remember an update for World of Warcraft announcing that they implemented a new chance calculator that would counteract spiky chains of events. (e.g. making critical strikes or dodging several times in a row). The idea was that in the event that you would dodge a hit, the chance that you would dodge the next hit would be diminished, but it would work both ways. Not dodging a hit would equally increase the chance of dodging the next hit. The major trick here, was that over several trials the dodge chance would still correspond to the percentage given to the player in his or hers stat-sheet.

This kind of system very much intrigued me at the time, and now I am in the situation of needing such a solution.

Here are my troubles:

* I am guessing that I would be able to find online resources on implementing such a system, but I may just be lacking the relevant buzz words for finding it.
* Also I need this approach to fit a system that is not binomial (i.e. two outcomes), but instead contains 4 mutually exclusive events.

My current approach is similar to that of a raffle ticket system. When an event occurs I change the weights in favor of all other events. This could work if the four event were meant to be equally likely, but in my case, on needs to be much more prevalent. But as the prevalent event happens more often, it shifts the weights of the other a lot higher than intended and I cannot seem to find the numbers for the weight shifts that are needed to keep the average ticket count around the initial values that the event were given.

A few direction pointers or a clear cut example would be much appreciated.

# Answer
> 20 votes
Basically, what you're asking for is a "semi-random" event generator that generates events with the following properties:

1. The average rate at which each event occurs is specified in advance.
2. The same event is less likely to occur twice in a row than it would be at random.
3. The events are not fully predictable.

One way to do that is to first implement a *non-random* event generator that satisfies goals 1 and 2, and then add some randomness to satisfy goal 3.

---

For the non-random event generator, we can use a simple dithering algorithm. Specifically, let *p*1, *p*2, ..., *p**n* be the relative likelihoods of the events 1 to *n*, and let *s* = *p*1 \+ *p*2 \+ ... + *p**n* be the sum of the weights. We can then generate a non-random maximally equidistributed sequence of events using the following algorithm:

1. Initially, let *e*1 = *e*2 = ... = *e**n* = 0.
2. To generate an event, increment each *e**i* by *p**i*, and output the event *k* for which *e**k* is largest (breaking ties any way you want).
3. Decrement *e**k* by *s*, and repeat from step 2.

For example, given three events A, B and C, with *p*A = 5, *p*B = 4 and *p*C = 1, this algorithm generates something like the following sequence of outputs:

```
A B A B C A B A B A A B A B C A B A B A A B A B C A B A B A

```

Notice how this sequence of 30 events contains exactly 15 As, 12 Bs and 3 Cs. It's not *quite* optimally distributes — there are a few occurrences of two As in a row, which could've been avoided — but it gets close.

---

Now, to add randomness to this sequence, you have several (not necessarily mutually exclusive) options:

* You can follow Philipp's advice, and maintain a "deck" of *N* upcoming events, for some appropriately sized number *N*. Every time you need to generate an event, you pick a random event from the deck, and then replace it with the next event output by the dithering algorithm above.

Applying this to the example above, with *N* = 3, produces e.g.:

```
A B A B C A B B A B A B C A A A A B B A B A C A B A B A B A

```

whereas *N* = 10 yields the more random-looking:

```
A A B A C A A B B B A A A A A A C B A B A A B A C A C B B B

```

Note how the common events A and B end up with a lot more runs due to the shuffling, whereas the rare C events are still fairly well spaced out.
* You can inject some randomness directly into the dithering algorithm. For example, instead of incrementing *e**i* by *p**i* in step 2, you could increment it by *p**i* × random(0, 2), where random(*a*, *b*) is a uniformly distributed random number between *a* and *b*; this would yield output like the following:

```
A B B C A B A A B A A B A B A A B A A A B C A B A B A C A B

```

or you could increment *e**i* by *p**i* \+ random(−*c*, *c*), which would produce (for *c* = 0.1 × *s*):

```
B A A B C A B A B A B A B A C A B A B A B A A B C A B A B A

```

or, for *c* = 0.5 × *s*:

```
B A B A B A C A B A B A A C B C A A B C B A B B A B A B C A

```

Note how the additive scheme has a much stronger randomizing effect for the rare events C than for the common events A and B, as compared to the multiplicative one; this might or might not be desirable. Of course, you could also use some combination of these schemes, or any other adjustment to the increments, as long as it preserves the property that the *average* increment of *e**i* equals *p**i*.
* Alternatively, you could perturb the *output* of the dithering algorithm by sometimes replacing the chosen event *k* with a random one (chosen according to the raw weights *p**i*). As long as you also use the same *k* in step 3 as you output in step 2, the dithering process will still tend to even out random fluctuations.

For example, here's some example output, with a 10% chance of each event being chosen randomly:

```
B A C A B A B A C B A A B B A B A B A B C B A B A B C A B A

```

and here's an example with a 50% chance of each output being random:

```
C B A B A C A B B B A A B A A A A A B B A C C A B B A B B C

```

You could also consider feeding a mix of purely random and dithered events into a deck / mixing pool, as described above, or perhaps randomizing the dithering algorithm by choosing *k* randomly, as weighed by the *e**i*s (treating negative weights as zero).

Ps. Here are some completely random event sequences, with the same average rates, for comparison:

```
A C A A C A B B A A A A B B C B A B B A B A B A A A A A A A
B C B A B C B A A B C A B A B C B A B A A A A B B B B B B B
C A A B A A B B C B B B A B A B A A B A A B A B A C A A B A

```

---

**Tangent:** Since there has been some debate in the comments about whether it's necessary, for deck-based solutions, to allow the deck to empty before it's refilled, I decided to make a graphical comparison of several deck-filling strategies:

Plot of several strategies for generating semi-random coin flips (with 50:50 ratio of heads to tails on average). Horizontal axis is number of flips, vertical axis is cumulative distance from the expected ratio, measured as (heads − tails) / 2 = heads − flips / 2.

The red and green lines on the plot show two non-deck-based algorithms for comparison:

* Red line, **deterministic dithering**: even-numbered outcomes are always heads, odd-numbered outcomes are always tails.
* Green line, **independent random flips**: each outcome is chosen independently at random, with a 50% chance of heads and a 50% chance of tails.

The other three lines (blue, purple and cyan) show the results of three deck-based strategies, each implemented using a deck of 40 cards, which is initially filled with 20 "heads" cards and 20 "tails" cards:

* Blue line, **fill when empty**: Cards are drawn at random until the deck is empty, then the deck is refilled with 20 "heads" cards and 20 "tails" cards.
* Purple line, **fill when half empty**: Cards are drawn at random until the deck has 20 cards left; then the deck is topped up with 10 "heads" cards and 10 "tails" cards.
* Cyan line, **fill continuously**: Cards are drawn at random; even-numbered draws are immediately replaced with a "heads" card, and odd-numbered draws with a "tails" card.

Of course, the plot above is just a single realization of a random process, but it's reasonably representative. In particular, you can see that all the deck-based processes have limited bias, and stay fairly close to the red (deterministic) line, whereas the purely random green line eventually wanders off.

(In fact, the deviation of the blue, purple and cyan lines away from zero is strictly bounded by the deck size: the blue line can never drift more than 10 steps away from zero, the purple line can only get 15 steps away from zero, and the cyan line can drift at most 20 steps away from zero. Of course, in practice, any of the lines actually reaching its limit is extremely unlikely, since there's a strong tendency for them to return closer to zero if they wander too far off.)

At a glance, there's no obvious difference between the different deck-based strategies (although, on average, the blue line stays somewhat closer to the red line, and the cyan line stays somewhat further away), but a closer inspection of the blue line does reveal a distinct deterministic pattern: every 40 draws (marked by the dotted gray vertical lines), the blue line exactly meets the red line at zero. The purple and cyan lines are not so strictly constrained, and can stay away from zero at any point.

For all the deck-based strategies, the important feature that keeps their variation bounded is the fact that, while the cards are *drawn from* the deck randomly, the deck is *refilled* deterministically. If the cards used to refill the deck were themselves chosen randomly, all of the deck-based strategies would become indistinguishable from pure random choice (green line).

# Answer
> 52 votes
Don't roll dice, deal cards.

Take all possible results of your RNG, put them in a list, shuffle it randomly, and return the results in the randomized order. When you are at the end of the list, repeat.

The results will still be uniformly distributed, but individual results won't repeat unless the last of the list also happens to be the first of the next one.

When this is a bit too predictable for your taste, you could use a list which is `n` times the number of possible results and put each possible result into it `n` times before shuffling. Or you could reshuffle the list before it is iterated completely.

# Answer
> 17 votes
You could try a Markov Random Graph. Consider each event that can occur to be a node in a graph. From each event, make a link to each other event that could possibly come after it. Each of these links is weighted by something called the *transition probability*. Then, you perform a random walk of the graph according to the transition model.

For instance, you can have a graph that represents the outcome of an attack (critical hit, dodge, etc.). Initialize the starting node to one picked at random given the player's stats (just "roll the dice"). Then, on the next attack, decide what happens next given the transition model.

Care needs to be taken to decide how to weight the transitions. For one thing, all the transitions coming out of a node need to add up to a probability of 1. One simple thing you could do is make a transition from every node to every other node, with weights equivalent to the probability that those events happen *a priori*, given that the current event cannot occur again.

For instance, if you have three events:

```
  Critical, P = 0.1
  Hit,      P = 0.3
  Miss,     P = 0.6

```

You can set up the transition model such that a critical hit does not occur again simply by redistributing its probability mass to the other events uniformly:

```
  Critical -> Critical,   P = 0.0
  Critical -> Hit,        P = 0.35
  Critical -> Miss,       P = 0.65

```

EDIT: As the comments say below, this model is not complicated enough to get the desired behavior. Instead, you may have to add multiple additional states!

# Answer
> 3 votes
Here's an implementation I created in C# which will:

* Activate events based on probabilities
* Adjust those probabilities to decrease chances of recurring events
* Not stray too far from original probabilities

I've added a few comments so that you can see what I'm doing.

```
    int percentageEvent1 = 15; //These are the starter values. So given a scenario, the
    int percentageEvent2 = 40; //player would have around a 15 percent chance of event
    int percentageEvent3 = 10; //one occuring, a 40 percent chance of event two occuring
    int percentageEvent4 = 35; //10 percent for event three, and 35 percent for event four.

    private void ResetValues()
    {
        percentageEvent1 = 15;
        percentageEvent2 = 40;
        percentageEvent3 = 10;
        percentageEvent4 = 35;
    }

    int resetCount = 0; //Reset the probabilities every so often so that they don't stray too far.

    int variability = 1; //This influences how much the chance of an event will increase or decrease
                           //based off of past events.

    Random RandomNumberGenerator = new Random();

    private void Activate() //When this is called, an "Event" will be activated based off of current probability.
    {
        int[] percent = new int[100];
        for (int i = 0; i < 100; i++) //Generate an array of 100 items, and select a random event from it.
        {
            if (i < percentageEvent1)
            {
                percent[i] = 1; //Event 1
            }
            else if (i < percentageEvent1 + percentageEvent2)
            {
                percent[i] = 2; //Event 2
            }
            else if (i < percentageEvent1 + percentageEvent2 + percentageEvent3)
            {
                percent[i] = 3; //Event 3
            }
            else
            {
                percent[i] = 4; //Event 4
            }
        }
        int SelectEvent = percent[RandomNumberGenerator.Next(0, 100)]; //Select a random event based on current probability.

        if (SelectEvent == 1)
        {
            if (!(percentageEvent1 - (3 * variability) < 1)) //Make sure that no matter what, probability for a certain event
            {                                                //does not go below one percent.
                percentageEvent1 -= 3 * variability;
                percentageEvent2 += variability;
                percentageEvent3 += variability;
                percentageEvent4 += variability;
            }
        }
        else if (SelectEvent == 2)
        {
            if (!(percentageEvent2 - (3 * variability) < 1))
            {
                percentageEvent2 -= 3 * variability;
                percentageEvent1 += variability;
                percentageEvent3 += variability;
                percentageEvent4 += variability;
            }
        }
        else if (SelectEvent == 3)
        {
            if (!(percentageEvent3 - (3 * variability) < 1))
            {
                percentageEvent3 -= 3 * variability;
                percentageEvent1 += variability;
                percentageEvent2 += variability;
                percentageEvent4 += variability;
            }
        }
        else
        {
            if (!(percentageEvent4 - (3 * variability) < 1))
            {
                percentageEvent4 -= 3 * variability;
                percentageEvent1 += variability;
                percentageEvent2 += variability;
                percentageEvent3 += variability;
            }
        }

        resetCount++;
        if (resetCount == 10)
        {
            resetCount = 0;
            ResetValues();
        }

        RunEvent(SelectEvent); //Run the event that was selected.
    }

```

Hope this helps, please do suggest improvements to this code in the comments, thanks!

# Answer
> 3 votes
Let me generalize mklingen's answer a bit. Basically, you want to implement the Gambler's Fallacy, though I'll provide a more general method here:

Say there are `n` possible events with probabilities `p_1, p_2, ..., p_n`. When event `i` happened, its probability shall rescale with a factor `0≤a_i≤1/p_i` (the latter is important, otherwise you end up with a probability greater than one and the other events must have negative probabilities, which basically mean "anti"-events. Or something), though typically `a_i<1`. You could for example choose `a_i=p_i`, which means the probability of an event happening a second time is the original probability the event happening precisely two times in a row, e.g. a second coin toss would have a probability of 1/4 instead of 1/2. On the other hand, you can also have some `a_i>1`, which would mean triggering a "stroke of luck/misfortune".

All the other events shall remain equally probable relative to one another, i.e. they all have to be rescaled by the same factor `b_i` such that the sum of all probabilities equals one, i.e.

```
1 = a_i*p_i + b_i*(1-p_i)  # Σ_{j≠i) p_j  = 1 - p_i
⇒ b_i = (1 - a_i*p_i) / (1 - p_i).   (1)

```

---

So far, so simple. But now let's add another requirement: Considering all possible sequences of two events, the single-event probabilities extracted therefrom shall be the original probabilities.

Let

```
        / p_i * b_i * p_j  (j≠i)
p_ij = <
        \ a_i * (p_i)²     (j=i)

```

denote the probability of event `j` happening after event `i` and note that `p_ij≠p_ji` unless `b_i=b_j (2)` (which by `(1)` implies `a_j = 1 - a_i*p_i + (1-a_i)*p_i/p_j`). This is also what Bayes' theorem requires and this also implies

```
Σ_j p_ij = p_i * b_i * (1 - p_i) + a_i * (p_i)²
         = b_i * p_i + (a_i - b_i) * (p_i)²
         = p_i  # using (1)

```

just as desired. Just note how this means one `a_i` fixes all the other ones.

---

Now let's see what happens when we apply this procedure multiple times, i.e. for sequences of three and more events. There are basically two options for the choice of the third event's rigged probabilities:

a) Forget about the first event and rig as if only the second one occurred, i.e.

```
         / p_ij * a_j * p_j  (j=k)
p_ijk = <
         \ p_ij * b_j * p_l  (j≠k)

```

Note that this usually violates Bayes, since e.g. `p_jik≠p_ikj` in most cases.

b) Use use the probabilities `p_ij` (for fixed `i`) as new probabilities `pi_j` from which you obtain the new probabilities `pi_jk` for event `k` to happen next. Whether you modify the `ai_j` or not is up to you, but be aware that the new `bi_j` are definitely different due to the modified `pi_j`. Then again, the choice of `ai_j` is probably restricted by requiring all permutations of `ijk` occurring with the same probability. Let's see...

```
         / p_ij * bi_j * pi_k  (j≠k)
p_ijk = <
         \ (p_ij)² * ai_j      (j=k)

         / b_i * bi_j * p_i * p_j * pi_k  (i≠j≠k≠i)
         | b_i * ai_j * p_i * (p_j)²      (i≠j=k)
      = <  a_i * (p_i)² * bi_i * pi_k     (i=j≠k)
         | b_i * p_i * bi_j * p_k * pi_i  (i=k≠j)
         \ a_i * ai_i * (p_i)² * pi_i     (i=k=j)

```

and cyclic permutations thereof, which must be equal for the respective cases.

I'm afraid my continuation on this will have to wait a while...

# Answer
> 1 votes
I think the best option is to use random-weighted item selection. There's an implementation for C# here, but they can be easily found or made for other languages as well.

The idea would be to reduce an option's weight every time it's picked, and increase it every time it's not picked.

For example, if you decrease the weight of the picked-option by `NumOptions-1` and increase the weight of every other option by 1 *(being careful to remove items with weight \< 0 and readd them when they rise above 0)*, every option will be picked approximately the same number of times over a long period, but recently-picked options will be much less likely to be picked.

---

The problem with using a random ordering, as suggested by many other answers, is that after every option but one has been picked, you can predict with 100% certainty what option will be picked next. That's not very random.

# Answer
> 1 votes
## ***My answer is incorrect, my test was flawed.***

I'm leaving this answer here for the discussion and comments that point out the flaws in this design, but the actual test was incorrect.

> What you're looking for is a weighted weight: the weights for your four possible outcomes need to be further adjusted (weighted) by previous outcomes, while still remaining the proper weights overall.
>
> The easiest way to accomplish this is to **alter all of the weights for each roll by decreasing the weight for the specific value rolled and increasing the other weights**.
>
> As an example, lets say you have 4 weights: Fumble, Miss, Hit, and Crit. Lets also say your desired overall weights for them are Fumble = 10%, Miss = 50%, Hit = 30%, and Crit = 10%.
>
> If you use a random number generator (RNG) to produce values between 1 and 100, and then compare that value to where it falls within this range (1-10 Fumble, 11-60 miss, 61-90 hit, 91-100 crit), you're generating an individual roll.
>
> If, when you make that roll, you then immediately adjust those ranges based on the value rolled, you'll be weighting future rolls, but you also need to reduce the rolled weight by the same *total* amount that you increase the other weights by. So in our example above, you would reduce the rolled weight by 3 and increase the other weights by 1 each.
>
> If you do this for each roll, you will still have the chance of streaks, but they will be greatly reduced, because for each roll you are increasing the chance that future rolls will be anything other than what the current roll is. You can increase this effect, and thereby further reduce the chance of streaks, by increasing/decreasing the weights by a greater factor (e.g. reduce current by 6 and increase others by 2).
>
> I ran a quick app to validate this approach, and after 32000 iterations with those weights, it produces the following graphs. The upper graph shows the 4 weights immediate values at each roll, and the lower graph shows the sum count of each type of result rolled up to that point.
>
> As you can see, the weights fluctuate slightly around their desired values, but the overall weights stay within the desired ranges, and after the initial variety of the starting numbers settles out, the results fit our desired percentages almost perfectly.
>
> Note that this example was produced using the .NET System.Random class, which is not really one of the better RNGs out there, so you probably can get more accurate results by using a better RNG. Also note that 32000 was the maximum results I could graph with this tool, but my test tool was able to generate over 500 million results with the same overall patterns.

# Answer
> 0 votes
You could do what is essentially a filter. Keep track of the past n events. The probability is the some of some filter applied to those events. The 0th filter is the base probability, if 0 then you dodged, if 1 you failed. Let's say the base was 25%, and the filter decreases by half each iteration. Your filter would then be:

```
[.25 .125 .0625 .03125]

```

Feel free to continue if you wish. The overall probability of this scheme is slightly higher than the base probability of .25. In fact, the probability, given the same scheme, is (I'm calling x the real probability, p is the probability input):

```
x=p+(1-x)*(p/2+p/4+p/8)

```

Solving for x, one finds the answer is `p(1+1/2+1/4+1/8)/(1+p(1/2+1/4+1/8)`, or for our given case, `x=0.38461538461`. But what you really want is to find p, given x. That turns out to be a more difficult problem. If you assumed an infinite filter, the problem becomes `x+x*p=2*p`, or `p=x/(2-x)`. So increasing your filter, you could then solve for a number p which will on average give you the same results, but at a rate dependent on how much success has recently happened.

Basically, you use the previous values to determine what the acceptance threshold is this round, and take a random value. Then produce the next random value given the filter.

# Answer
> -1 votes
Just like you proposed yourself, one of the approaches to this is to implement a weighted random. The idea is to make a random number (or outcome) generator where weights and outcomes can be modified.

Here is an implementation of this in Java.

```
import java.util.Map;
import java.util.Random;

/**
 * A psuedorandom weighted outcome generator
 * @param <E> object type to return
 */
public class WeightedRandom<E> {

    private Random random;
    private Map<E, Double> weights;

    public WeightedRandom(Map<E, Double> weights) {
        this.random = new Random();
        this.weights = weights;
    }

    /**
     * Returns a random outcome based on the weight of the outcomes
     * @return
     */
    public E nextOutcome() {
        double totalweight = 0;

        // determine the total weigth
        for (double w : weights.values()) totalweight += w;

        // determine a value between 0.0 and the total weight
        double remaining = random.nextDouble() * totalweight;

        for (E entry : weights.keySet()) {
            // subtract the weight of this entry
            remaining -= weights.get(entry);

            // if the remaining is smaller than 0, return this entry
            if (remaining <= 0) return entry;
        }

        return null;
    }

    /**
     * Returns the weight of an outcome
     * @param outcome the outcome to query
     * @return the weight of the outcome, if it exists
     */
    public double getWeight(E outcome) {
        return weights.get(outcome);
    }

    /**
     * Sets the weight of an outcome
     * @param outcome the outcome to change
     * @param weight the new weigth
     */
    public void setWeight(E outcome, double weight) {
        weights.put(outcome, weight);
    }
}

```

**EDIT** In the case where you want to adjust the weights automatically, for example increase the chance of A when the result was B. You can either,

1. Change the behaviour of the `nextOutcome()` method, so it modifies the weight according to the result
2. Use `setWeight()` to modify the weight of according to the result.

---
Tags: random
---


# Question
Title: XNA Monogame - Move .dll and .xml root folder
I was just wondering if it's possible to move the dll and xml files into a subfolder, like in this picture:

Thanks !

# Answer
This isn't really so much of a MonoGame issue as much as it is a .NET issue.

The XML files are unimportant and can safely be deleted as they only contain the documentation for the matching DLL files. I'm not sure if there is any kind of legal requirement for you to keep them around but I seriously doubt it. I am not a lawyer.

Moving the DLL files though will prevent GameName1.exe from locating them at runtime. This could possibly be fixed though I'm not sure it's really worth the effort. The rules for locating DLLs in the .NET runtime can be found here: https://msdn.microsoft.com/en-us/library/yx7xezcf.aspx?f=255&MSPPError=-2147217396. I think you can tell .NET to look for assemblies in another folder through a configuration file.
> 1 votes

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


# Question
Title: how to 'Scale up' my procedurally generated island/continent without losing its uniqueness?
Currently I am trying to make a procedural terrain generator. When I first started creating my terrain generator I decided to use a radial mask to generate my islands/continents like so:

But as time went along, I decided that these islands were way too small and I needed the islands to be much larger almost like continents than islands. So what I did was simply make the radial mask bigger. Which did overall result in bigger islands but my islands were now very much 'centered-based' with each island generating roughly the same except for the very outer extremities:

Here is the code I used to generate the procedural island. I included a comment on what value I changed to make the island larger. I used Libnoise for the perlin noise.

```
 void createRadiIsland(int centerX, int centerY)
{
    Perlin perlin = new Perlin();
    perlin.OctaveCount = 8;
    perlin.Frequency = 0.1;
    int seed = 50;
    float BiasX = 7f;
    float BiasY = 7f;
    for (int x = 0; x < grid.columns; x++)
    {
        for (int y = 0; y < grid.rows; y++)
        {

            float distanceX = (centerX - x) * (centerX - x);
            float distanceY = (centerY - y) * (centerY - y);

            float distanceToCenter = Mathf.Sqrt(distanceX * BiasX + distanceY * BiasY);
            distanceToCenter = distanceToCenter / 500; //<-- larger the value the bigger the island
            grid.FindTile(x, y).elevation = Mathf.RoundToInt(((float)perlin.GetValue(x - 0.98 + seed, y - 0.98 + seed, .1) - distanceToCenter * 10));

        }

    }
}

```

How should I modify my code so that it generates islands/continents that have the general uniqueness of the first island but at a much greater scale? Would I even be able to use a mask anymore? Would I have to use a completely new approach to generating my terrain?

side note:

I thought about solving my problem by using multiple radial gradients instead of just one but I am afraid that it will end up making my islands too blobby looking and not very realistic. Is that true?

# Answer
1. create the low-resolution elevation map with the algorithm you used first
2. scale it up using linear interpolation
3. add another round of perlin noise to the upscaled elevation map, this time with the higher resolution but smaller height scale. This will add more detail to your landscape.
> 1 votes

# Answer
I do this in my game by generating a **distance field** to a set of line segments, and using that as an additional mask on top of the radial one. Here's how its done:

* Generate N pairs of random points and connect them together as line segments.
* For each pixel in the mask, determine the distance to every line segment. Take the min over all segments, called `d*`.
* Set the pixel to `MAX_DISTANCE - d*`
* The result is a mask with values between `0` and `MAX_DISTANCE`. Higher values correspond to pixels that are closer to line segments, while lower values are further away.
* Multiply the heightmap by this mask after applying the radial gradient.
* Scale the mask as desired.

The result is "mountain ranges" and "valleys" in straight lines. For a crazier effect, you can distort the distances in the mask using Perlin noise.
> 2 votes

---
Tags: c#, unity, procedural-generation, terrain
---


title: UDK ping check without joining a game?

text:
# Question
Title: UDK ping check without joining a game?
I have made great strides in creating a custom built server browser for UDK. It registers servers with a master, and the client can download the list and populate the server browser.

However I'd like to tell users the ping of a server in the server browser. I know PlayerReplicationInfo has a server check native function, but that only works when the player is actually connected to a server.

I want to ping check a server without joining it, and then collect the data to show to the player?

Is this easy to implement? Hard to implement? Maybe it's a waste of time because of the time required to ping all the possible servers? If it's easy to implement how can I do it? Do I need to make a custom TCPLink class that counts the time it takes for a message to go back and forth?

# Answer
I'm not used to UDK, by the way I'll try to answer your question at just a theoretical level. I'm trying to implement network games in a project of mine, and found out how to let client ping check servers without actually joining games. Also, this is an intuition from Halo:CE network code.

Let's suppose the central server browser has a list of servers, these info are ready to be sent to requesting clients. When a client wants to browse servers it actually only gets a list of IPs to check for: for every IP, the client sends a data packet to that IP (which is the address of a server currently running a game) with a data message to request server info, such as server name, game type, map name, no. of players. Also, client sends its timestamp attached to this packet.

When a server receives such packet, it sends back another packet with the requested info: server name, game type, map name, no. of players; then CLIENT's timestamp from previous client's packet is attached to the new packet.

When client receives server's response back, it can show in a browser window these info, plus round trip time (RTT) to that server, which is: RTT = current\_timestamp - old\_timestamp. You don't need to store old timestamp, because you're getting it back from the server itself.

All this can be done without having a client joining a game by using UDP connection protocol: you just have to set up a different port for "ping" information exchange, and set up some raw packet messages to be recognized both on server-side and client-side machines.

HCE works this way, I guess: client only asks central server for a list of IP, then every single IP is sent a packet to get information about current game running and ping value relative to the client. When refreshing servers list, clients ask server browser back for a new list of IPs to check for.

FYI servers can use two ports: a port client\_port (this is no code, just a generic variable name) is used to sync the current game with connected clients; then another port server\_port listens to incoming packets from clients which want to ask server "Who are you? What game are you running?" and answer these clients back.
> 1 votes

---
Tags: networking, multiplayer, udk
---


# Question
Title: Does PBR mean only one, right technique to view 3D scenes?
For example if I call Unity 5's render pipeline "PBR" (Physically-Based Rendering) and also call Unreal Engine 4's render pipeline "PBR," does it mean that the same model with the same PB textures will be viewed identically in very similar or equal scene setups on both engines?

I just wondering if someone says "PBR," does it mean only one, single, right way to do "PBR," or do implementations vary from one to the other?

# Answer
Physically-Based Rendering (PBR) is really a modern tag people use to refer to the trend of making the rendering system "correct" with regard to the real-world physics of light interacting with surfaces, rather than an exact definition of a full rendering system. In other words, I would say PBR is more a definition of the aspiration of the system than what it strictly does.

See here for a good summary of the topic.

Therefore no two systems are guaranteed to try to get to the goal in the same way.

Different systems may model light more or less accurately in the simulation for example - i.e. one might have better global illumination system or better shadow mapping etc. So while the system might model light-surface interaction more accurately, and thus be described as a PBR system, the incident lighting on the surface in the first place might be a bit different giving different results in each system.

So, if given a single flat surface in a scene with one light it's reasonable to expect two PBR systems to give basically the same results. But when it comes to rendering a whole scene with lots going on, there are many variables in play that will probably lead to more obvious variations in the resultant image.
> 4 votes

# Answer
The idea of physically based rendering is to reach a closer approximation of how light behaves in the real world and use this model to generate a 2D impression of a 3D scene. This is basically what we are doing since the invention of 3D graphics, just with more simplified models of optics. So yes, PBR is mostly a buzzword.

A perfect approximation of real-world physics of light would require to simulate every single photon accurately (and don't forget about the wave/particle duality of photons which is required to accurately simulate some optical phenomenons you encounter in real-life). That's the only way to create a *truly* photorealistic impression of *any* scene possible in real-life. But doing this in real-time would greatly exceed the abilities of todays computers by several orders of magnitude. That means you will always need to take some shortcuts and simplifications to get a reasonable compromise between image quality and rendering performance. How to make this compromise is up to each rendering pipeline.
> 2 votes

---
Tags: unity, rendering, unreal-4, pbr
---


title: Fb.Feed dialog closes before saving

text:
# Question
Title: Fb.Feed dialog closes before saving
I'm having trouble with the Facebook UnitySDK when I use the FB.Feed() method for posting on user's timeline. The share dialog closes before the post is completed, Right after i press the "Post" button. This only happens when I test the app on the iOS Device since on the Unity Editor it works fine and I can post on the user's wall. User Login and getting username and profile pic, for example, work fine. The problem is when I try to share the user's score on facebook. Here's my code for the method:

```
public void Share_Score(){
        FB.Feed (
            toId: "",
            link: "http://www.facebook.com/appname",
            linkName: "App Name",
            linkCaption: "I just scored " + " points",
            linkDescription: "Playing this game is awesome!",
            actionLink:"http://www.facebook.com/appname",
            actionName: "Appname Fan Page"
                );
    }

```

The only error that appears on XCode is the following: 2015-02-11 10:13:07.025 hotdogcontest\[749:224865\] FBSDKLog: FBLinkShareParams: only "http" or "https" schemes are supported for link thumbnails

# Answer
> 1 votes
replace the link to something like this

```
link: "http://apps.facebook.com/" + FB.AppId + "/?challenge_brag" + (FB.IsLoggedIn ? FB.UserId : "guest")

```

---
Tags: unity, ios, facebook
---


# Question
Title: Can I post to Facebook with my own text from Unity on behalf of the user?
I'm using Facebook SDK for Unity 6.0 with FB.Feed.

I'm trying to post a link to the user's feed, text and link on his behalf.

So far I've managed to publish only a link and its details, the part where the user can write the post is left empty for him to fill.

# Answer
```
if (FB.IsLoggedIn)
    {
            FB.Feed(
            linkCaption: "YourGame",
            picture: "http://YourImageLink.png",
            linkName: "YourGameMessage!",
            link: "http://apps.facebook.com/" + FB.AppId + "/?challenge_brag" + (FB.IsLoggedIn ? FB.UserId : "guest")
            );
    }

```
> 1 votes

---
Tags: unity, facebook
---


# Question
Title: Stop Unity UI Buttons from being clicked when a Facebook Window is overlayed
Having an odd issue. When I play with the Facebook SDK for Unity, and the Windows popup like the login window or the Friend Selector window, if I use the mouse to click in the window I end up clicking the Unity 4.6 UI buttons underneath it. Anyone know how to avoid this?

# Answer
> 1 votes
When you display/activate the Facebook SDK popup disable the Unity UI under it until the facebook popup completes.

You might need to reorganize the UI tree to easily deactivate everything but the FB UI by splitting it in two.

# Answer
> 0 votes
There is several different ways to accomplish this task, I found the best way for me was to use a bool and if statement like if(!PauseManager.paused) You could do something like if(!LoginPanelActive) or something then if it is paused or active the buttons just won't trigger and will not until you want them to again. This will also block drags across mobile amongst other bugs you may encounter going a different route.

---
Tags: unity, facebook, gui
---


# Question
Title: Too much animation work for 2d characters. Creating 2d character animations by prerendering an animated 3d model?
I've read a bit about creating assets for games and the consensus seems to be that 2D is cheaper than 3D in all aspects with the exception of character animation. That's caused by the need of redrawing every frame of an animation versus simply animating the skeleton of a model.

The cheapest solution seems to be making all the assets with lots of animations as 3d models and prerendering them to create sprite sheets, and leave the background and everything else that has few animations traditionally drawn.

**How do I do it**, what tools would be appropriate, whats the process and workflow? How does the pipeline for this work? **Where could I learn more about doing something like this?**

On the other hand, **I'm afraid that such an approach greatly limits the available customisation of my characters** \- wouldnt such a thing mean that each combination of gear needs to have its own spritesheet? Doesnt that pump up my game size and memory footprint and slow it down due to slow disk access?

How viable is putting a 3d model in a isometric view 2d environment? Would that be a solution to the "lots of sprites" problem, if it exists? How would I go about that in Unity? Where could I learn about that approach?

**I've looked at this question but it did'nt really help me**, the answers are just vaugue suggestions, I want solutions and resources to learn how to implement those solutions.

**EDIT:** I'll elaborate on why that question isnt the same as mine, because some of the commenters didnt get it. That post refers to a game called hero academy that has little to do with the isometric game I'm talking about - that one has a grid, does not use the 8 directions, does not adress the customisation of a character via gear etc. All in all it's totally another beast. As for my question, **think Diablo II**.

Out of the answers I found there it seemed like the answer referring to project zomboid might be on the right track for me, but I had doubts about the customisation and tons of sprites. So what am I asking here? Does the "project zomboid method" fit my needs (trying it out only to find out it doesnt work would be a waste of time) and if it does, how do I do that in Unity. Why didnt i phrase the question that way in the first place? To **avoid the XY problem**. Hope this clarifies well enough.

# Answer
You could have your characters represented as 3D models, then rendered to off-screen buffers as sprite sheets on demand and use them to render 2D images. Workflow is rather simple - you just render frames of your animation to render target, then use that produced image as spritesheet.

For combinations of gear you can just render/have each piece of gear available as separate sprite and then just combine/layer them as necessary. You can draw naked character first, then draw selection of armor on top, one selected weapon in hand, etc.
> 1 votes

# Answer
You could use something like Dragon Bones instead. That could really save you a lot of work.

http://dragonbones.github.io/

Making nice looking 3d animation is a serious highly paid profession. Making 3d models that will look nice in a 2d game is even more challenging in some sense. You have to remember 3d models in a 2d game may look out of place. Also if you go ahead and use 3d models, you may as well just stick the in the game as they are and render the in game.

Just because game-play is 2d, does not mean visuals need to be as well.
> 1 votes

# Answer
I think you should break this up into multiple questions and try again. Offhand, I see 3 questions that all warrant their own detailed answers, but there are probably more that you can ask to get the detailed answers you wish for:

# Using 3D to generate 2D Sprites

You can just use 3D as a way to render Sprites, i.e. by creating your animations, then rendering them out as individual frames and stitching those together into a sprite sheet.

# How do I attach customizations to 2D Sprites

The same way you would to 3D Sprites: You break them up into several objects, mark "attachment points" on the main sprite (different ones for each frame in some additional metadata file), and then whenever you draw an actor, you draw the attachments at the attachment points. You may also have to mark attachment points as "above" or "below" the actor, so e.g. you can draw a backpack obscured by the character while she's facing you, but still have a helmet obscure the character's head. And of course you'd need 2D sprites from every angle for the customizations as well.

If you also want to customize the actual graphics, you would also split up parts of the main character into different parts, and then you can apply scale factors to them (e.g. to get a narrower face, offer different noses etc.).

# How do I put 3D models in a 2D environment

In short, you can't. What you usually do is the reverse, use a 3D environment with a fixed camera, and then put up all the 2D content as if they were cardboard standups. Then you can leave room between them and use a projection matrix that does not make things in the distance get smaller (IIRC that's what Unity already does when you create a 2D game). Then you can just place the 3D models in between the cardboard standups.
> 1 votes

# Answer
If you want a 3D model in a TRUE 2D environment, it won't happen. If you want a faux 2D environment (so by locking your camera to certain axes), then you'll get what you want.

Or you can go your route of rendering sprite sheets, I.E Diablo 2 style.

There are many tutorials for isometric views in Unity, just check Youtube.

If you want a 3D iso view, all it is setting your camera to orthographic and locking the axes.
> 0 votes

# Answer
You could take a look at BrashMonkey Spriter. Which is a software for creating 2D animatinos that are *rotation based* instead of *frame based*. It is mainly made for XNA framework, but there are many community implementations for other software aswell, and you may implement your own code if you have good knowledge of C#. (It has implementations for example Unity)

The program uses techniques with bones like 3d animations and keyframed animation, and you can exchange the parts of the body with eas. However, it's not produced by a big professional company and all features are not fully implemented ( It has support for creating collision boxes frame controlled but you have to implement the code to use them yourself. For commercial purposes, the license is also *relatively cheap*. The file output is basicly a huge xml file (.scml) which is then read and processed by the game.
> 0 votes

---
Tags: 2d, 3d, unity, animation, skeletal-animation
---


# Question
Title: Good Configuration Manager System Design for medium-large sized projects?
I've create smaller games which simply needed a class which basically opens an INI file (with feather-ini-parser library) with config values for the whole game (rendering ops, music, bindings).

But I want to go to medium-larger projects and my current configuration managing system I used earlier will be getting more complicated when my engine grows. I need a new config manager system and I tried to research but found nothing. My current config manager for 'mid-large games' is this:

The ConfigManager class interface:

```
    class ConfigManager
    {
    protected:
        class INIFile
        {
        protected:
            std::string id;
            ini_t ini;
        public:
            INIFile(std::string &id, Poco::Path& filename);
            ~INIFile();

            void Destroy() { delete this; }
            std::string& getId() { return id; }
            ini_t& getINI() { return ini; }
        };

        typedef std::vector<INIFile*> INIFiles;
        INIFiles files;
    public:
        ConfigManager();

        bool openConfiguration (Poco::Path& filepath, std::string& id);
        void closeConfiguration(std::string& id);

        void flushConfigsToDisk();

        void getConfiguration(Ogre::String &id, ConfigModule& mod);
        void setConfiguration(Ogre::String &id, ConfigModule& mod);
    };

```

ini\_t is a typedef of an INI Reading/Writting library (feather-ini-parser) this class is instanced in the main Engine class (avoid Singleton use), id is the unique identifier to the file opened like "Input", "MyGameCfg", "Rendering", etc. the `ConfigModule` is a "section" from the INI file opened and it's structure is:

```
    class ConfigModule
    {
        friend class ConfigManager;

    protected:
        optValuesVector keyValues;
        Ogre::String section;
        bool is_empty;
        bool nominal;

    public:
        ConfigModule();
        ~ConfigModule();

        Ogre::String getOptionVal(Ogre::String& key);
        Ogre::String setOptionVal(Ogre::String& key, Ogre::String& val);

        bool is_empty() { return is_empty; }
        bool status() { return nominal; }

    };

```

ConfigModules are "wrapped C++ INI sections" and stored in specific game classes like Input, GameLogic, Rendering classes. Instead to invoking an instance of the ConfigManager every time to get an setting every time, the ConfigManager is ONLY invoked when some of the game classes needed to write configurations and re-parse the config file with the new values.

**My Question is:** Is this a good approach (at least I feel this system has it's flaws, probably change configuration formats from INI to Lua ) to handle multiple configurations in large games? or there is another better design I can follow?. Thanks.

# Answer
> 3 votes
Your system looks fine.

I am more used to having all of my configurations for a game in a single file but I also work on very large projects where I have folders of configurations. Your system as described above should be able to handle both of those situations just fine. I do not see any concerns you may be perceiving in the question nor do I foresee any that you may run into either.

As to your thoughts of changing it from an INI format to Lua, that is completely up to you and no general 'this is better than that' rule exists. Just make sure that it fits your needs. If you have Lua in your engine already for other purposes (Its how you script game play or UI components or AI logic checks, etc) then it may make sense to change the configuration files over to use it as well. Maintaining less technology can make things simpler in the long run.

Just to be clear, adding in Lua processing just for a configuration file parser is probably overkill, especially when you already have a parsing system in place.

Hope this helps.

# Answer
> 0 votes
In my opinion, it depends on what you need of course, but I personally really like the way this configuration parser was written.

https://github.com/LaurentGomila/SFML/wiki/Source:-Settings-Parser

It's under the SFML wiki, but rest assured it has no dependencies on the library. You only need standard C++.

It is template code so you can assuredly expand on it without too much effort, if you wish to use it as a base.

It also has write capabilities.

---
Tags: c++, architecture, configuration
---


# Question
Title: How to get Unity's 4.6 UI images to layer over each other perfectly?
I've been noticing that if I have two images, lets say squares. I have A as the parent of triangle B. Triangle A and B both have their offsets at their anchors, which are on the 4 corners of it's "box".

Triangle A should be behind triangle B, since it renders from top to bottom in the hierarchy (the last item being on top). However as I re-size my screen, sometimes triangle A will poke out from behind triangle B. Even if they both are using the same image, and have the exact same dimensions.

Whats causing this, and how do I fix it?

Additionally, I noticed that while the anchors and offsets can be finely adjusted, the image is not. You have to adjust by certain interval sizes and the image will just snap to that new size rather than adjusting finely as you change the offset or anchors.

# Answer
Turns out that I had pixel perfect enabled, without it enabled this solved the problem I was having.
> 0 votes

---
Tags: unity, gui
---


# Question
Title: Is there a significant amount of overhead when using STL containers instead of plain arrays?
I have read discouraging statements about using plain arrays in c++. Where videogame development is involved we are aiming, as far as I know, at max speed execution. STL containers (such as std::vector) bring some elements not present in plain old arrays (iterators, etc). Does such functionality add overhead? (e.g. pointer chasing, etc) If so, is it worth it in real life to lose some speed in exchange for type safety?

# Answer
> 3 votes
This depends on what operation you are performing on vectors. vectors are actually really fast. iteration is as fast as possible, since the vector does *not* store pointers but an array of objects in one straight block of memory, so iterating over a vertex is as fast as iterating over an array. And even the iterator-objects do not add a overhead, in production-mode (so if you don't compile in debug-mode), they do no runtime-checks but just trust you in what you're doing. Adding a new element is still really fast as long as it still fits in the allocated block of memory. If not, it either copies or moves the objects to a new block of memory, depending on if this class *has* a move-constructor and if it is noexcept. You can, of course, std::move your object in or even emplace\_back (construct it right in place) so you don't even need to copy or with emplace\_back not even to move. I'd never use plain arrays, they just need too much attention to not leak and not read from uninitialized memory, vectors will do all this for you. In debug-mode, vectors will perform boundary-checks when you access an element (i.e. with array-operator \[\]), in non-debug mode they won't to give you best performance. vectors are awesome, just use them!

---
Tags: c++, efficiency
---